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

managedRelay.ts

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