The best way to control Claude Code, Codex and more from any computer or phone

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