Open History to see the last commit
1import * as Data from "effect/Data";
2import * as Effect from "effect/Effect";
3import * as Schema from "effect/Schema";
4import { HttpClient } from "effect/unstable/http";
5import {
6 EnvironmentCloudEndpointUnavailableError,
7 EnvironmentHttpBadRequestError,
8 EnvironmentHttpConflictError,
9 EnvironmentHttpForbiddenError,
10 EnvironmentHttpInternalServerError,
11 EnvironmentHttpUnauthorizedError,
12} from "@t3tools/contracts";
13import { stripPairingTokenFromUrl } from "@t3tools/shared/remote";
14import {
15 type RelayEnvironmentConnectResponse as RelayEnvironmentConnectResponseType,
16 type RelayEnvironmentLinkResponse as RelayEnvironmentLinkResponseType,
17 RelayEnvironmentConnectScope,
18 RelayEnvironmentStatusScope,
19 type RelayDpopAccessTokenScope,
20 type RelayProtectedError as RelayProtectedErrorType,
21 type RelayClientEnvironmentRecord,
22 type RelayEnvironmentStatusResponse as RelayEnvironmentStatusResponseType,
23 type RelayManagedEndpointProviderKind,
24} from "@t3tools/contracts/relay";
25import { exchangeRemoteDpopAccessToken } from "@t3tools/client-runtime/authorization";
26import { fetchRemoteEnvironmentDescriptor } from "@t3tools/client-runtime/environment";
27import { findErrorTraceId } from "@t3tools/client-runtime/errors";
28import { ManagedRelay } from "@t3tools/client-runtime/relay";
29import { makeEnvironmentHttpApiClient } from "@t3tools/client-runtime/rpc";
30
31import { authClientMetadata } from "../../lib/authClientMetadata";
32import type { SavedRemoteConnection } from "../../lib/connection";
33import { loadOrCreateAgentAwarenessDeviceId, loadPreferences } from "../../lib/storage";
34import { resolveCloudPublicConfig } from "./publicConfig";
35
36const RELAY_STATUS_AND_CONNECT_SCOPES = [
37 RelayEnvironmentStatusScope,
38 RelayEnvironmentConnectScope,
39] satisfies ReadonlyArray<RelayDpopAccessTokenScope>;
40
41export function normalizeRelayBaseUrl(value: string | null | undefined): string | null {
42 const trimmed = value?.trim();
43 if (!trimmed) {
44 return null;
45 }
46 return trimmed.replace(/\/+$/g, "");
47}
48
49function readRelayUrl(): string | null {
50 return resolveCloudPublicConfig().relay.url;
51}
52
53export class CloudEnvironmentLinkError extends Data.TaggedError("CloudEnvironmentLinkError")<{
54 readonly message: string;
55 readonly cause?: unknown;
56 readonly traceId?: string;
57}> {}
58
59export interface CloudEnvironmentRecordWithStatus {
60 readonly environment: RelayClientEnvironmentRecord;
61 readonly status: RelayEnvironmentStatusResponseType | null;
62 readonly statusError: string | null;
63}
64
65const isEnvironmentCloudApiError = Schema.is(
66 Schema.Union([
67 EnvironmentHttpBadRequestError,
68 EnvironmentHttpUnauthorizedError,
69 EnvironmentHttpForbiddenError,
70 EnvironmentHttpConflictError,
71 EnvironmentHttpInternalServerError,
72 EnvironmentCloudEndpointUnavailableError,
73 ]),
74);
75
76const MANAGED_ENDPOINT_PROVIDER_KIND =
77 "cloudflare_tunnel" satisfies RelayManagedEndpointProviderKind;
78
79function cloudEnvironmentLinkError(message: string) {
80 return (cause: unknown) => {
81 const environmentError = findEnvironmentCloudApiError(cause);
82 const traceId = findErrorTraceId(cause);
83 return new CloudEnvironmentLinkError({
84 message: environmentError
85 ? `${message.replace(/[.:]$/, "")}: ${environmentError.message}`
86 : withDevCause(message, cause),
87 cause,
88 ...(traceId === null ? {} : { traceId }),
89 });
90 };
91}
92
93function isDevRuntime(): boolean {
94 return typeof __DEV__ !== "undefined" && __DEV__;
95}
96
97function causeMessage(cause: unknown): string | null {
98 if (cause instanceof Error && cause.message) {
99 return cause.message;
100 }
101 if (typeof cause === "object" && cause !== null) {
102 const record = cause as { readonly message?: unknown; readonly cause?: unknown };
103 if (typeof record.message === "string" && record.message.length > 0) {
104 const nested = causeMessage(record.cause);
105 return nested ? `${record.message}: ${nested}` : record.message;
106 }
107 }
108 return null;
109}
110
111function withDevCause(message: string, cause: unknown): string {
112 if (!isDevRuntime()) {
113 return message;
114 }
115 const detail = causeMessage(cause);
116 return detail ? `${message} (${detail})` : message;
117}
118
119function relayProtectedErrorMessage(error: RelayProtectedErrorType): string {
120 switch (error._tag) {
121 case "RelayAuthInvalidError":
122 switch (error.reason) {
123 case "missing_bearer":
124 case "invalid_bearer":
125 return "Relay rejected the cloud session token.";
126 case "invalid_dpop":
127 return "Relay rejected the DPoP proof.";
128 case "not_authorized":
129 return "Relay rejected the authenticated request.";
130 }
131 case "RelayEnvironmentLinkProofExpiredError":
132 return "Relay rejected an expired environment link proof.";
133 case "RelayEnvironmentLinkProofInvalidError":
134 return `Relay rejected the environment link proof (${error.reason}).`;
135 case "RelayEnvironmentConnectNotAuthorizedError":
136 return "Relay rejected the environment connection request.";
137 case "RelayEnvironmentEndpointUnavailableError":
138 return `Relay could not reach the environment endpoint (${error.reason}).`;
139 case "RelayEnvironmentEndpointTimedOutError":
140 return "Relay timed out while contacting the environment endpoint.";
141 case "RelayEnvironmentLinkFailedError":
142 return `Relay could not link the environment (${error.reason}).`;
143 case "RelayEnvironmentLinkUnavailableError":
144 return `Relay cannot provision the managed endpoint (${error.reason}).`;
145 case "RelayAgentActivityPublishProofExpiredError":
146 return "Relay rejected an expired agent activity publish proof.";
147 case "RelayAgentActivityPublishProofInvalidError":
148 return `Relay rejected the agent activity publish proof (${error.reason}).`;
149 case "RelayInternalError":
150 return `Relay encountered an internal error (${error.reason}).`;
151 }
152}
153
154function decodedRelayClientError(message: string) {
155 return (cause: ManagedRelay.ManagedRelayClientError) => {
156 const relayError =
157 cause._tag === "ManagedRelayRequestFailedError" ? cause.relayError : undefined;
158 const traceId = cause._tag === "ManagedRelayRequestFailedError" ? cause.traceId : undefined;
159 const detail = relayError ? relayProtectedErrorMessage(relayError) : null;
160 return new CloudEnvironmentLinkError({
161 message: detail ? `${message}: ${detail}` : message,
162 cause,
163 ...(traceId ? { traceId } : {}),
164 });
165 };
166}
167
168function findEnvironmentCloudApiError(cause: unknown): { readonly message: string } | null {
169 if (isEnvironmentCloudApiError(cause)) {
170 return cause;
171 }
172 if (typeof cause !== "object" || cause === null) {
173 return null;
174 }
175 return "cause" in cause ? findEnvironmentCloudApiError(cause.cause) : null;
176}
177
178function requireRelayUrl(): Effect.Effect<string, CloudEnvironmentLinkError> {
179 const relayUrl = readRelayUrl();
180 return relayUrl
181 ? Effect.succeed(relayUrl)
182 : Effect.fail(new CloudEnvironmentLinkError({ message: "Relay URL is not configured." }));
183}
184
185function endpointOrigin(httpBaseUrl: string) {
186 const url = new URL(httpBaseUrl);
187 return {
188 localHttpHost: "127.0.0.1",
189 localHttpPort: Number(url.port || (url.protocol === "https:" ? 443 : 80)),
190 };
191}
192
193function ensureLinkedEnvironmentMatches(input: {
194 readonly expectedEnvironmentId: string;
195 readonly expectedProviderKind: RelayManagedEndpointProviderKind;
196 readonly link: RelayEnvironmentLinkResponseType;
197}): Effect.Effect<void, CloudEnvironmentLinkError> {
198 if (input.link.environmentId !== input.expectedEnvironmentId) {
199 return new CloudEnvironmentLinkError({
200 message: "Relay returned credentials for a different environment.",
201 });
202 }
203 if (input.link.endpoint.providerKind !== input.expectedProviderKind) {
204 return new CloudEnvironmentLinkError({
205 message: "Relay returned credentials for a different endpoint provider.",
206 });
207 }
208 return Effect.void;
209}
210
211function endpointMatches(
212 left: RelayClientEnvironmentRecord["endpoint"],
213 right: RelayClientEnvironmentRecord["endpoint"],
214): boolean {
215 return (
216 left.httpBaseUrl === right.httpBaseUrl &&
217 left.wsBaseUrl === right.wsBaseUrl &&
218 left.providerKind === right.providerKind
219 );
220}
221
222function ensureStatusMatchesEnvironment(input: {
223 readonly environment: RelayClientEnvironmentRecord;
224 readonly status: RelayEnvironmentStatusResponseType;
225}): Effect.Effect<void, CloudEnvironmentLinkError> {
226 if (input.status.environmentId !== input.environment.environmentId) {
227 return new CloudEnvironmentLinkError({
228 message: "Relay returned status for a different environment.",
229 });
230 }
231 if (!endpointMatches(input.status.endpoint, input.environment.endpoint)) {
232 return new CloudEnvironmentLinkError({
233 message: "Relay returned status for a different endpoint.",
234 });
235 }
236 if (
237 input.status.descriptor &&
238 input.status.descriptor.environmentId !== input.environment.environmentId
239 ) {
240 return new CloudEnvironmentLinkError({
241 message: "Relay returned status descriptor for a different environment.",
242 });
243 }
244 return Effect.void;
245}
246
247function ensureConnectEndpointMatchesEnvironment(input: {
248 readonly environment: RelayClientEnvironmentRecord;
249 readonly connect: RelayEnvironmentConnectResponseType;
250}): Effect.Effect<void, CloudEnvironmentLinkError> {
251 if (!endpointMatches(input.connect.endpoint, input.environment.endpoint)) {
252 return new CloudEnvironmentLinkError({
253 message: "Relay returned credentials for a different endpoint.",
254 });
255 }
256 return Effect.void;
257}
258
259export function linkEnvironmentToCloud(input: {
260 readonly connection: SavedRemoteConnection;
261 readonly clerkToken: string;
262}): Effect.Effect<
263 void,
264 CloudEnvironmentLinkError,
265 HttpClient.HttpClient | ManagedRelay.ManagedRelayClient
266> {
267 return Effect.gen(function* () {
268 if (!input.connection.bearerToken) {
269 return yield* new CloudEnvironmentLinkError({
270 message: "Only a locally paired bearer connection can be linked to the cloud.",
271 });
272 }
273 const localBearerToken = input.connection.bearerToken;
274 const relayUrl = yield* requireRelayUrl();
275 const relayClient = yield* ManagedRelay.ManagedRelayClient;
276 const deviceId = yield* Effect.tryPromise({
277 try: () => loadOrCreateAgentAwarenessDeviceId(),
278 catch: cloudEnvironmentLinkError("Could not load the mobile device id."),
279 });
280 const preferences = yield* Effect.tryPromise({
281 try: () => loadPreferences(),
282 catch: cloudEnvironmentLinkError("Could not load mobile notification preferences."),
283 });
284 const liveActivitiesEnabled = preferences.liveActivitiesEnabled !== false;
285 const challenge = yield* relayClient
286 .createEnvironmentLinkChallenge({
287 clerkToken: input.clerkToken,
288 payload: {
289 notificationsEnabled: true,
290 liveActivitiesEnabled,
291 managedTunnelsEnabled: true,
292 },
293 })
294 .pipe(
295 Effect.mapError(
296 decodedRelayClientError(`${relayUrl}/v1/client/environment-link-challenges failed`),
297 ),
298 );
299 const environmentClient = yield* makeEnvironmentHttpApiClient(input.connection.httpBaseUrl);
300 const proof = yield* environmentClient.connect
301 .linkProof({
302 headers: { authorization: `Bearer ${localBearerToken}` },
303 payload: {
304 challenge: challenge.challenge,
305 relayIssuer: relayUrl,
306 endpoint: {
307 httpBaseUrl: input.connection.httpBaseUrl,
308 wsBaseUrl: input.connection.wsBaseUrl,
309 providerKind: MANAGED_ENDPOINT_PROVIDER_KIND,
310 },
311 origin: endpointOrigin(input.connection.httpBaseUrl),
312 },
313 })
314 .pipe(Effect.mapError(cloudEnvironmentLinkError("Could not obtain environment link proof.")));
315 const link = yield* relayClient
316 .linkEnvironment({
317 clerkToken: input.clerkToken,
318 payload: {
319 deviceId,
320 proof,
321 notificationsEnabled: true,
322 liveActivitiesEnabled,
323 managedTunnelsEnabled: true,
324 },
325 })
326 .pipe(
327 Effect.mapError(decodedRelayClientError(`${relayUrl}/v1/client/environment-links failed`)),
328 );
329 yield* ensureLinkedEnvironmentMatches({
330 expectedEnvironmentId: input.connection.environmentId,
331 expectedProviderKind: MANAGED_ENDPOINT_PROVIDER_KIND,
332 link,
333 });
334
335 yield* environmentClient.connect
336 .relayConfig({
337 headers: { authorization: `Bearer ${localBearerToken}` },
338 payload: {
339 relayUrl,
340 relayIssuer: link.relayIssuer,
341 cloudUserId: link.cloudUserId,
342 environmentCredential: link.environmentCredential,
343 cloudMintPublicKey: link.cloudMintPublicKey,
344 endpointRuntime: link.endpointRuntime,
345 },
346 })
347 .pipe(
348 Effect.mapError(cloudEnvironmentLinkError("Could not configure environment relay access.")),
349 );
350 });
351}
352
353export function listCloudEnvironments(input: {
354 readonly clerkToken: string;
355}): Effect.Effect<
356 ReadonlyArray<RelayClientEnvironmentRecord>,
357 CloudEnvironmentLinkError,
358 ManagedRelay.ManagedRelayClient
359> {
360 return Effect.gen(function* () {
361 const relayUrl = yield* requireRelayUrl();
362 const relayClient = yield* ManagedRelay.ManagedRelayClient;
363
364 return yield* relayClient
365 .listEnvironments({
366 clerkToken: input.clerkToken,
367 })
368 .pipe(Effect.mapError(decodedRelayClientError(`${relayUrl}/v1/environments failed`)));
369 });
370}
371
372export function getCloudEnvironmentStatus(input: {
373 readonly clerkToken: string;
374 readonly environment: RelayClientEnvironmentRecord;
375 readonly relayScopes?: ReadonlyArray<RelayDpopAccessTokenScope>;
376}): Effect.Effect<
377 RelayEnvironmentStatusResponseType,
378 CloudEnvironmentLinkError,
379 ManagedRelay.ManagedRelayClient
380> {
381 return Effect.gen(function* () {
382 const relayUrl = yield* requireRelayUrl();
383 const relayClient = yield* ManagedRelay.ManagedRelayClient;
384 const status = yield* relayClient
385 .getEnvironmentStatus({
386 clerkToken: input.clerkToken,
387 scopes: input.relayScopes ?? [RelayEnvironmentStatusScope],
388 environmentId: input.environment.environmentId,
389 })
390 .pipe(
391 Effect.mapError(
392 decodedRelayClientError(
393 `${relayUrl}/v1/environments/${encodeURIComponent(input.environment.environmentId)}/status failed`,
394 ),
395 ),
396 );
397 yield* ensureStatusMatchesEnvironment({ environment: input.environment, status });
398 return status;
399 });
400}
401
402export function cloudEnvironmentsPendingStatus(
403 environments: ReadonlyArray<RelayClientEnvironmentRecord>,
404): ReadonlyArray<CloudEnvironmentRecordWithStatus> {
405 return environments.map((environment) => ({
406 environment,
407 status: null,
408 statusError: "Checking status...",
409 }));
410}
411
412export function loadCloudEnvironmentStatuses(input: {
413 readonly clerkToken: string;
414 readonly environments: ReadonlyArray<RelayClientEnvironmentRecord>;
415}): Effect.Effect<
416 ReadonlyArray<CloudEnvironmentRecordWithStatus>,
417 CloudEnvironmentLinkError,
418 ManagedRelay.ManagedRelayClient
419> {
420 return Effect.forEach(
421 input.environments,
422 (environment) =>
423 getCloudEnvironmentStatus({
424 clerkToken: input.clerkToken,
425 environment,
426 relayScopes: RELAY_STATUS_AND_CONNECT_SCOPES,
427 }).pipe(
428 Effect.match({
429 onFailure: (error) => ({
430 environment,
431 status: null,
432 statusError: error.message,
433 }),
434 onSuccess: (status) => ({
435 environment,
436 status,
437 statusError: null,
438 }),
439 }),
440 ),
441 { concurrency: "unbounded" },
442 );
443}
444
445export function listCloudEnvironmentsWithStatus(input: {
446 readonly clerkToken: string;
447}): Effect.Effect<
448 ReadonlyArray<CloudEnvironmentRecordWithStatus>,
449 CloudEnvironmentLinkError,
450 ManagedRelay.ManagedRelayClient
451> {
452 return Effect.gen(function* () {
453 const environments = yield* listCloudEnvironments(input);
454 return yield* loadCloudEnvironmentStatuses({
455 clerkToken: input.clerkToken,
456 environments,
457 });
458 });
459}
460
461const loadAgentAwarenessDeviceId = Effect.fn("mobile.cloud.loadAgentAwarenessDeviceId")(
462 function* () {
463 return yield* Effect.tryPromise({
464 try: () => loadOrCreateAgentAwarenessDeviceId(),
465 catch: cloudEnvironmentLinkError("Could not load the mobile device id."),
466 });
467 },
468);
469
470const connectRelayManagedEnvironment = Effect.fn("mobile.cloud.connectRelayManagedEnvironment")(
471 function* (input: {
472 readonly clerkToken: string;
473 readonly environmentId: RelayClientEnvironmentRecord["environmentId"];
474 readonly expectedEnvironment?: RelayClientEnvironmentRecord;
475 }) {
476 yield* Effect.annotateCurrentSpan({ "environment.id": input.environmentId });
477 const relayUrl = yield* requireRelayUrl();
478 const relayClient = yield* ManagedRelay.ManagedRelayClient;
479
480 const deviceId = yield* loadAgentAwarenessDeviceId();
481 const connect = yield* relayClient
482 .connectEnvironment({
483 clerkToken: input.clerkToken,
484 scopes: [RelayEnvironmentConnectScope],
485 environmentId: input.environmentId,
486 deviceId,
487 })
488 .pipe(
489 Effect.mapError(
490 decodedRelayClientError(
491 `${relayUrl}/v1/environments/${encodeURIComponent(input.environmentId)}/connect failed`,
492 ),
493 ),
494 );
495 if (connect.environmentId !== input.environmentId) {
496 return yield* new CloudEnvironmentLinkError({
497 message: "Relay returned credentials for a different environment.",
498 });
499 }
500 if (input.expectedEnvironment) {
501 yield* ensureConnectEndpointMatchesEnvironment({
502 environment: input.expectedEnvironment,
503 connect,
504 });
505 }
506
507 const descriptor = yield* fetchRemoteEnvironmentDescriptor({
508 httpBaseUrl: connect.endpoint.httpBaseUrl,
509 }).pipe(
510 Effect.mapError(
511 cloudEnvironmentLinkError("Could not fetch the connected environment descriptor."),
512 ),
513 );
514 if (descriptor.environmentId !== connect.environmentId) {
515 return yield* new CloudEnvironmentLinkError({
516 message: "Connected endpoint descriptor does not match the selected environment.",
517 });
518 }
519 const signer = yield* ManagedRelay.ManagedRelayDpopSigner;
520 const bootstrapDpop = yield* signer
521 .createProof({
522 method: "POST",
523 url: new URL("/oauth/token", connect.endpoint.httpBaseUrl).toString(),
524 })
525 .pipe(Effect.mapError(cloudEnvironmentLinkError("Could not create bootstrap DPoP proof.")));
526 const bootstrap = yield* exchangeRemoteDpopAccessToken({
527 httpBaseUrl: connect.endpoint.httpBaseUrl,
528 credential: connect.credential,
529 dpopProof: bootstrapDpop,
530 clientMetadata: authClientMetadata(),
531 }).pipe(
532 Effect.mapError(
533 cloudEnvironmentLinkError("Could not exchange a managed endpoint DPoP access token."),
534 ),
535 );
536 const pairingUrl = new URL(connect.endpoint.httpBaseUrl);
537 pairingUrl.hash = new URLSearchParams([["token", connect.credential]]).toString();
538
539 return {
540 environmentId: descriptor.environmentId,
541 environmentLabel: descriptor.label,
542 pairingUrl: stripPairingTokenFromUrl(pairingUrl).toString(),
543 displayUrl: connect.endpoint.httpBaseUrl,
544 httpBaseUrl: connect.endpoint.httpBaseUrl,
545 wsBaseUrl: connect.endpoint.wsBaseUrl,
546 bearerToken: null,
547 authenticationMethod: "dpop",
548 dpopAccessToken: bootstrap.access_token,
549 relayManaged: true,
550 } satisfies SavedRemoteConnection;
551 },
552);
553
554export function connectCloudEnvironment(input: {
555 readonly clerkToken: string;
556 readonly environment: RelayClientEnvironmentRecord;
557}): Effect.Effect<
558 SavedRemoteConnection,
559 CloudEnvironmentLinkError,
560 HttpClient.HttpClient | ManagedRelay.ManagedRelayClient | ManagedRelay.ManagedRelayDpopSigner
561> {
562 return connectRelayManagedEnvironment({
563 clerkToken: input.clerkToken,
564 environmentId: input.environment.environmentId,
565 expectedEnvironment: input.environment,
566 });
567}
568
569export function refreshCloudEnvironmentConnection(input: {
570 readonly clerkToken: string;
571 readonly connection: SavedRemoteConnection;
572}): Effect.Effect<
573 SavedRemoteConnection,
574 CloudEnvironmentLinkError,
575 HttpClient.HttpClient | ManagedRelay.ManagedRelayClient | ManagedRelay.ManagedRelayDpopSigner
576> {
577 return connectRelayManagedEnvironment({
578 clerkToken: input.clerkToken,
579 environmentId: input.connection.environmentId,
580 });
581}