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