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

managedRelay.ts

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