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

managedRelay.ts

923 lines33.0 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 return yield* SynchronizedRef.modifyEffect(cachedTokens, (tokens) =>
550 Effect.gen(function* () {
551 const activeTokens = tokens.filter((token) => token.expiresAtMillis > nowMillis + 5_000);
552 const cached = activeTokens.find((token) =>
553 tokenMatches(token, {
554 accountId: accountId.value,
555 clientId: options.clientId,
556 relayUrl,
557 thumbprint: input.thumbprint,
558 scopes: input.scopes,
559 nowMillis,
560 }),
561 );
562 if (cached) {
563 yield* Effect.annotateCurrentSpan({
564 "relay.token_cache.result": "hit",
565 });
566 return [cached, activeTokens] as const;
567 }
568 yield* Effect.annotateCurrentSpan({
569 "relay.token_cache.result": "miss",
570 });
571 const response = yield* exchangeAccessToken(input);
572 const next: ManagedRelayAccessTokenCacheEntry = {
573 accountId: accountId.value,
574 clientId: options.clientId,
575 relayUrl,
576 thumbprint: input.thumbprint,
577 scopes: input.scopes,
578 accessToken: response.access_token,
579 expiresAtMillis: nowMillis + response.expires_in * 1_000,
580 };
581 const nextTokens = [...activeTokens, next];
582 if (options.accessTokenStore) {
583 yield* options.accessTokenStore.save(nextTokens);
584 }
585 return [next, nextTokens] as const;
586 }),
587 ).pipe(Effect.withSpan("clientRuntime.managedRelay.tokenCacheCriticalSection"));
588 },
589 );
590​
591 const authorize = Effect.fn("clientRuntime.managedRelay.authorize")(function* (input: {
592 readonly clerkToken: string;
593 readonly scopes: ReadonlyArray<RelayDpopAccessTokenScope>;
594 readonly target: DpopProofTarget;
595 }) {
596 yield* Effect.annotateCurrentSpan({
597 "relay.client_id": options.clientId,
598 "relay.scopes": input.scopes.join(" "),
599 "http.request.method": input.target.method,
600 "url.full": input.target.url,
601 });
602 const thumbprint = yield* signer.thumbprint;
603 const token = yield* obtainAccessToken({
604 clerkToken: input.clerkToken,
605 scopes: input.scopes,
606 thumbprint,
607 });
608 const proof = yield* signer
609 .createProof({
610 ...input.target,
611 accessToken: token.accessToken,
612 })
613 .pipe(
614 Effect.mapError(
615 (error) => new ManagedRelayRequestProofCreationError(proofCreationErrorFields(error)),
616 ),
617 );
618 return { accessToken: token.accessToken, proof, thumbprint };
619 });
620​
621 const invalidateAccessToken = Effect.fn("clientRuntime.managedRelay.invalidateAccessToken")(
622 function* (accessToken: string) {
623 return yield* SynchronizedRef.modifyEffect(cachedTokens, (tokens) => {
624 const nextTokens = tokens.filter((token) => token.accessToken !== accessToken);
625 if (nextTokens.length === tokens.length) {
626 return Effect.succeed([false, tokens] as const);
627 }
628 return (
629 options.accessTokenStore ? options.accessTokenStore.save(nextTokens) : Effect.void
630 ).pipe(Effect.as([true, nextTokens] as const));
631 });
632 },
633 );
634​
635 const runDpopRequest = <A>(
636 input: {
637 readonly clerkToken: string;
638 readonly scopes: ReadonlyArray<RelayDpopAccessTokenScope>;
639 readonly target: DpopProofTarget;
640 },
641 request: (
642 authorization: ManagedRelayAuthorization,
643 ) => Effect.Effect<A, ManagedRelayClientError>,
644 ): Effect.Effect<A, ManagedRelayClientError> => {
645 const attempt = (refreshRejectedToken: boolean): Effect.Effect<A, ManagedRelayClientError> =>
646 authorize(input).pipe(
647 Effect.flatMap((authorization) =>
648 request(authorization).pipe(
649 Effect.catch((error) => {
650 if (!isRejectedDpopAccessToken(error)) {
651 return Effect.fail(error);
652 }
653 return invalidateAccessToken(authorization.accessToken).pipe(
654 Effect.tap((invalidated) =>
655 Effect.annotateCurrentSpan({
656 "relay.token_cache.invalidated": invalidated,
657 "relay.token_cache.invalidation_reason": "invalid_bearer",
658 "relay.token_cache.retry_after_invalidation": refreshRejectedToken,
659 }),
660 ),
661 Effect.tap((invalidated) =>
662 invalidated && refreshRejectedToken
663 ? Effect.logWarning(
664 "Relay rejected a cached DPoP access token; refreshing it once.",
665 )
666 : Effect.void,
667 ),
668 Effect.andThen(refreshRejectedToken ? attempt(false) : Effect.fail(error)),
669 );
670 }),
671 ),
672 ),
673 );
674 return attempt(true);
675 };
676​
677 const mobileRegistrationRequest = <A>(
678 input: {
679 readonly clerkToken: string;
680 readonly target: DpopProofTarget;
681 },
682 request: (
683 authorization: ManagedRelayAuthorization,
684 ) => Effect.Effect<A, ManagedRelayClientError>,
685 ) =>
686 runDpopRequest(
687 {
688 ...input,
689 scopes: [RelayMobileRegistrationScope],
690 },
691 request,
692 );
693​
694 return ManagedRelayClient.of({
695 relayUrl,
696 listEnvironments: Effect.fnUntraced(
697 function* (input) {
698 return yield* client.client
699 .listEnvironments({ headers: bearerHeaders(input.clerkToken) })
700 .pipe(
701 Effect.map((response) => response.environments),
702 Effect.mapError(relayRequestError("list relay-managed environments")),
703 timeoutRelayRequest("Relay environment listing"),
704 );
705 },
706 Effect.withSpan("clientRuntime.managedRelay.listEnvironments"),
707 withRelayClientTracing,
708 ),
709 listDevices: Effect.fnUntraced(
710 function* (input) {
711 return yield* client.client
712 .listDevices({
713 headers: bearerHeaders(input.clerkToken),
714 })
715 .pipe(
716 Effect.map((response) => response.devices),
717 Effect.mapError(relayRequestError("list relay client devices")),
718 timeoutRelayRequest("Relay client device listing"),
719 );
720 },
721 Effect.withSpan("clientRuntime.managedRelay.listDevices"),
722 withRelayClientTracing,
723 ),
724 createEnvironmentLinkChallenge: Effect.fnUntraced(
725 function* (input) {
726 return yield* client.client
727 .createEnvironmentLinkChallenge({
728 headers: bearerHeaders(input.clerkToken),
729 payload: input.payload,
730 })
731 .pipe(
732 Effect.mapError(relayRequestError("create relay environment link challenge")),
733 timeoutRelayRequest("Relay environment link challenge"),
734 );
735 },
736 Effect.withSpan("clientRuntime.managedRelay.createEnvironmentLinkChallenge"),
737 withRelayClientTracing,
738 ),
739 linkEnvironment: Effect.fnUntraced(
740 function* (input) {
741 return yield* client.client
742 .linkEnvironment({
743 headers: bearerHeaders(input.clerkToken),
744 payload: input.payload,
745 })
746 .pipe(
747 Effect.mapError(relayRequestError("link relay environment")),
748 timeoutRelayRequest("Relay environment linking"),
749 );
750 },
751 Effect.withSpan("clientRuntime.managedRelay.linkEnvironment"),
752 withRelayClientTracing,
753 ),
754 unlinkEnvironment: Effect.fnUntraced(
755 function* (input) {
756 return yield* client.client
757 .unlinkEnvironment({
758 headers: bearerHeaders(input.clerkToken),
759 params: { environmentId: input.environmentId },
760 })
761 .pipe(
762 Effect.mapError(relayRequestError("unlink relay environment")),
763 timeoutRelayRequest("Relay environment unlinking"),
764 );
765 },
766 Effect.withSpan("clientRuntime.managedRelay.unlinkEnvironment"),
767 withRelayClientTracing,
768 ),
769 getEnvironmentStatus: Effect.fnUntraced(
770 function* (input) {
771 yield* Effect.annotateCurrentSpan({
772 "environment.id": input.environmentId,
773 });
774 return yield* runDpopRequest(
775 {
776 clerkToken: input.clerkToken,
777 scopes: input.scopes,
778 target: dpopProofTargets.getEnvironmentStatus(input.environmentId),
779 },
780 (authorization) =>
781 client.dpopClient
782 .getEnvironmentStatus({
783 headers: dpopHeaders(authorization),
784 params: { environmentId: input.environmentId },
785 })
786 .pipe(
787 Effect.mapError(relayRequestError("get relay environment status")),
788 timeoutRelayRequest("Relay environment status request"),
789 ),
790 );
791 },
792 Effect.withSpan("clientRuntime.managedRelay.getEnvironmentStatus"),
793 withRelayClientTracing,
794 ),
795 connectEnvironment: Effect.fnUntraced(
796 function* (input) {
797 yield* Effect.annotateCurrentSpan({
798 "environment.id": input.environmentId,
799 });
800 return yield* runDpopRequest(
801 {
802 clerkToken: input.clerkToken,
803 scopes: input.scopes,
804 target: dpopProofTargets.connectEnvironment(input.environmentId),
805 },
806 (authorization) => {
807 const payload: RelayEnvironmentConnectRequest = {
808 ...(input.deviceId ? { deviceId: input.deviceId } : {}),
809 clientKeyThumbprint: authorization.thumbprint,
810 };
811 return client.dpopClient
812 .connectEnvironment({
813 headers: dpopHeaders(authorization),
814 params: { environmentId: input.environmentId },
815 payload,
816 })
817 .pipe(
818 Effect.mapError(relayRequestError("connect relay environment")),
819 timeoutRelayRequest("Relay environment connection"),
820 );
821 },
822 );
823 },
824 Effect.withSpan("clientRuntime.managedRelay.connectEnvironment"),
825 withRelayClientTracing,
826 ),
827 registerDevice: Effect.fnUntraced(
828 function* (input) {
829 return yield* mobileRegistrationRequest(
830 {
831 clerkToken: input.clerkToken,
832 target: dpopProofTargets.registerDevice(),
833 },
834 (authorization) =>
835 client.mobile
836 .registerDevice({
837 headers: dpopHeaders(authorization),
838 payload: input.payload,
839 })
840 .pipe(
841 Effect.mapError(relayRequestError("register relay mobile device")),
842 timeoutRelayRequest("Relay mobile device registration"),
843 ),
844 );
845 },
846 Effect.withSpan("clientRuntime.managedRelay.registerDevice"),
847 withRelayClientTracing,
848 ),
849 unregisterDevice: Effect.fnUntraced(
850 function* (input) {
851 return yield* mobileRegistrationRequest(
852 {
853 clerkToken: input.clerkToken,
854 target: dpopProofTargets.unregisterDevice(input.deviceId),
855 },
856 (authorization) =>
857 client.mobile
858 .unregisterDevice({
859 headers: dpopHeaders(authorization),
860 params: { deviceId: input.deviceId },
861 })
862 .pipe(
863 Effect.mapError(relayRequestError("unregister relay mobile device")),
864 timeoutRelayRequest("Relay mobile device unregistration"),
865 ),
866 );
867 },
868 Effect.withSpan("clientRuntime.managedRelay.unregisterDevice"),
869 withRelayClientTracing,
870 ),
871 getAgentActivitySnapshot: Effect.fnUntraced(
872 function* (input) {
873 return yield* mobileRegistrationRequest(
874 {
875 clerkToken: input.clerkToken,
876 target: dpopProofTargets.getAgentActivitySnapshot(),
877 },
878 (authorization) =>
879 client.mobile
880 .getAgentActivitySnapshot({
881 headers: dpopHeaders(authorization),
882 })
883 .pipe(
884 Effect.mapError(relayRequestError("read relay agent activity snapshot")),
885 timeoutRelayRequest("Relay agent activity snapshot"),
886 ),
887 );
888 },
889 Effect.withSpan("clientRuntime.managedRelay.getAgentActivitySnapshot"),
890 withRelayClientTracing,
891 ),
892 registerLiveActivity: Effect.fnUntraced(
893 function* (input) {
894 return yield* mobileRegistrationRequest(
895 {
896 clerkToken: input.clerkToken,
897 target: dpopProofTargets.registerLiveActivity(),
898 },
899 (authorization) =>
900 client.mobile
901 .registerLiveActivity({
902 headers: dpopHeaders(authorization),
903 payload: input.payload,
904 })
905 .pipe(
906 Effect.mapError(relayRequestError("register relay live activity")),
907 timeoutRelayRequest("Relay Live Activity registration"),
908 ),
909 );
910 },
911 Effect.withSpan("clientRuntime.managedRelay.registerLiveActivity"),
912 withRelayClientTracing,
913 ),
914 resetTokenCache: SynchronizedRef.set(cachedTokens, []).pipe(
915 Effect.andThen(options.accessTokenStore ? options.accessTokenStore.clear : Effect.void),
916 Effect.withSpan("clientRuntime.managedRelay.resetTokenCache"),
917 withRelayClientTracing,
918 ),
919 });
920});
921​
922export const layer = (options: ManagedRelayClientLayerOptions) =>
923 Layer.effect(ManagedRelayClient, make(options));