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

linkEnvironment.ts

617 lines21.6 KB

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, "");
49​
50function readRelayUrl(): string | null {
51 return resolveCloudPublicConfig().relay.url;
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;
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 };
93​
94function isDevRuntime(): boolean {
95 return typeof __DEV__ !== "undefined" && __DEV__;
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;
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;
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 // "Not authorized" covers non-auth causes too; surface the reason so a
138 // missing link doesn't read as a credential problem.
139 if (error.reason === "environment_link_not_found") {
140 return "Relay has no active link for this environment. The environment server may not have re-established its link yet.";
141 }
142 return error.reason
143 ? `Relay rejected the environment connection request (${error.reason}).`
144 : "Relay rejected the environment connection request.";
145 case "RelayEnvironmentEndpointUnavailableError":
146 return `Relay could not reach the environment endpoint (${error.reason}).`;
147 case "RelayEnvironmentEndpointTimedOutError":
148 return "Relay timed out while contacting the environment endpoint.";
149 case "RelayEnvironmentLinkFailedError":
150 return `Relay could not link the environment (${error.reason}).`;
151 case "RelayEnvironmentLinkUnavailableError":
152 return `Relay cannot provision the managed endpoint (${error.reason}).`;
153 case "RelayEnvironmentLinkLimitExceededError":
154 return `Relay refused the link: this account already has its maximum of ${error.maxTunnels} managed tunnels. Unlink an environment to free one up.`;
155 case "RelayAgentActivityPublishProofExpiredError":
156 return "Relay rejected an expired agent activity publish proof.";
157 case "RelayAgentActivityPublishProofInvalidError":
158 return `Relay rejected the agent activity publish proof (${error.reason}).`;
159 case "RelayInternalError":
160 return `Relay encountered an internal error (${error.reason}).`;
161 }
163​
164function decodedRelayClientError(message: string) {
165 return (cause: ManagedRelay.ManagedRelayClientError) => {
166 const relayError =
167 cause._tag === "ManagedRelayRequestFailedError" ? cause.relayError : undefined;
168 const traceId = cause._tag === "ManagedRelayRequestFailedError" ? cause.traceId : undefined;
169 const detail = relayError ? relayProtectedErrorMessage(relayError) : null;
170 return new CloudEnvironmentLinkError({
171 message: detail ? `${message}: ${detail}` : message,
172 cause,
173 ...(traceId ? { traceId } : {}),
174 });
175 };
177​
178function findEnvironmentCloudApiError(cause: unknown): { readonly message: string } | null {
179 if (isEnvironmentCloudApiError(cause)) {
180 return cause;
181 }
182 if (typeof cause !== "object" || cause === null) {
183 return null;
184 }
185 return "cause" in cause ? findEnvironmentCloudApiError(cause.cause) : null;
187​
188function requireRelayUrl(): Effect.Effect<string, CloudEnvironmentLinkError> {
189 const relayUrl = readRelayUrl();
190 return relayUrl
191 ? Effect.succeed(relayUrl)
192 : Effect.fail(new CloudEnvironmentLinkError({ message: "Relay URL is not configured." }));
194​
195function endpointOrigin(httpBaseUrl: string) {
196 const url = new URL(httpBaseUrl);
197 return {
198 localHttpHost: "127.0.0.1",
199 localHttpPort: Number(url.port || (url.protocol === "https:" ? 443 : 80)),
200 };
202​
203function ensureLinkedEnvironmentMatches(input: {
204 readonly expectedEnvironmentId: string;
205 readonly expectedProviderKind: RelayManagedEndpointProviderKind;
206 readonly link: RelayEnvironmentLinkResponseType;
207}): Effect.Effect<void, CloudEnvironmentLinkError> {
208 if (input.link.environmentId !== input.expectedEnvironmentId) {
209 return new CloudEnvironmentLinkError({
210 message: "Relay returned credentials for a different environment.",
211 });
212 }
213 if (input.link.endpoint.providerKind !== input.expectedProviderKind) {
214 return new CloudEnvironmentLinkError({
215 message: "Relay returned credentials for a different endpoint provider.",
216 });
217 }
218 return Effect.void;
220​
221function endpointMatches(
222 left: RelayClientEnvironmentRecord["endpoint"],
223 right: RelayClientEnvironmentRecord["endpoint"],
224): boolean {
225 return (
226 left.httpBaseUrl === right.httpBaseUrl &&
227 left.wsBaseUrl === right.wsBaseUrl &&
228 left.providerKind === right.providerKind
229 );
231​
232function ensureStatusMatchesEnvironment(input: {
233 readonly environment: RelayClientEnvironmentRecord;
234 readonly status: RelayEnvironmentStatusResponseType;
235}): Effect.Effect<void, CloudEnvironmentLinkError> {
236 if (input.status.environmentId !== input.environment.environmentId) {
237 return new CloudEnvironmentLinkError({
238 message: "Relay returned status for a different environment.",
239 });
240 }
241 if (!endpointMatches(input.status.endpoint, input.environment.endpoint)) {
242 return new CloudEnvironmentLinkError({
243 message: "Relay returned status for a different endpoint.",
244 });
245 }
246 if (
247 input.status.descriptor &&
248 input.status.descriptor.environmentId !== input.environment.environmentId
249 ) {
250 return new CloudEnvironmentLinkError({
251 message: "Relay returned status descriptor for a different environment.",
252 });
253 }
254 return Effect.void;
256​
257function ensureConnectEndpointMatchesEnvironment(input: {
258 readonly environment: RelayClientEnvironmentRecord;
259 readonly connect: RelayEnvironmentConnectResponseType;
260}): Effect.Effect<void, CloudEnvironmentLinkError> {
261 if (!endpointMatches(input.connect.endpoint, input.environment.endpoint)) {
262 return new CloudEnvironmentLinkError({
263 message: "Relay returned credentials for a different endpoint.",
264 });
265 }
266 return Effect.void;
268​
269interface LinkEnvironmentToCloudInput {
270 readonly connection: SavedRemoteConnection;
271 readonly clerkToken: string;
273​
274type LinkEnvironmentToCloudRequirements =
275 | HttpClient.HttpClient
276 | ManagedRelay.ManagedRelayClient
277 | MobileStorage.MobileStorage;
278​
279export function linkEnvironmentToCloudWithPreference(
280 input: LinkEnvironmentToCloudInput & { readonly liveActivitiesEnabled: boolean },
281): Effect.Effect<void, CloudEnvironmentLinkError, LinkEnvironmentToCloudRequirements> {
282 return Effect.gen(function* () {
283 if (!input.connection.bearerToken) {
284 return yield* new CloudEnvironmentLinkError({
285 message: "Only a locally paired bearer connection can be linked to the cloud.",
286 });
287 }
288 const localBearerToken = input.connection.bearerToken;
289 const relayUrl = yield* requireRelayUrl();
290 const relayClient = yield* ManagedRelay.ManagedRelayClient;
291 const storage = yield* MobileStorage.MobileStorage;
292 const deviceId = yield* storage.loadOrCreateAgentAwarenessDeviceId.pipe(
293 Effect.mapError(cloudEnvironmentLinkError("Could not load the mobile device id.")),
294 );
295 const liveActivitiesEnabled = input.liveActivitiesEnabled;
296 const challenge = yield* relayClient
297 .createEnvironmentLinkChallenge({
298 clerkToken: input.clerkToken,
299 payload: {
300 notificationsEnabled: true,
301 liveActivitiesEnabled,
302 managedTunnelsEnabled: true,
303 },
304 })
305 .pipe(
306 Effect.mapError(
307 decodedRelayClientError(`${relayUrl}/v1/client/environment-link-challenges failed`),
308 ),
309 );
310 const environmentClient = yield* makeEnvironmentHttpApiClient(input.connection.httpBaseUrl);
311 const proof = yield* environmentClient.connect
312 .linkProof({
313 headers: { authorization: `Bearer ${localBearerToken}` },
314 payload: {
315 challenge: challenge.challenge,
316 relayIssuer: relayUrl,
317 endpoint: {
318 httpBaseUrl: input.connection.httpBaseUrl,
319 wsBaseUrl: input.connection.wsBaseUrl,
320 providerKind: MANAGED_ENDPOINT_PROVIDER_KIND,
321 },
322 origin: endpointOrigin(input.connection.httpBaseUrl),
323 },
324 })
325 .pipe(Effect.mapError(cloudEnvironmentLinkError("Could not obtain environment link proof.")));
326 const link = yield* relayClient
327 .linkEnvironment({
328 clerkToken: input.clerkToken,
329 payload: {
330 deviceId,
331 proof,
332 notificationsEnabled: true,
333 liveActivitiesEnabled,
334 managedTunnelsEnabled: true,
335 },
336 })
337 .pipe(
338 Effect.mapError(decodedRelayClientError(`${relayUrl}/v1/client/environment-links failed`)),
339 );
340 yield* ensureLinkedEnvironmentMatches({
341 expectedEnvironmentId: input.connection.environmentId,
342 expectedProviderKind: MANAGED_ENDPOINT_PROVIDER_KIND,
343 link,
344 });
345​
346 yield* environmentClient.connect
347 .relayConfig({
348 headers: { authorization: `Bearer ${localBearerToken}` },
349 payload: {
350 relayUrl,
351 relayIssuer: link.relayIssuer,
352 cloudUserId: link.cloudUserId,
353 environmentCredential: link.environmentCredential,
354 cloudMintPublicKey: link.cloudMintPublicKey,
355 endpointRuntime: link.endpointRuntime,
356 },
357 })
358 .pipe(
359 Effect.mapError(cloudEnvironmentLinkError("Could not configure environment relay access.")),
360 );
361 });
363​
364export function linkEnvironmentToCloud(
365 input: LinkEnvironmentToCloudInput,
366): Effect.Effect<
367 void,
368 CloudEnvironmentLinkError,
369 LinkEnvironmentToCloudRequirements | MobilePreferences.MobilePreferencesStore
370> {
371 return MobilePreferences.MobilePreferencesStore.pipe(
372 Effect.flatMap((preferencesStore) => preferencesStore.load),
373 Effect.mapError(cloudEnvironmentLinkError("Could not load mobile notification preferences.")),
374 Effect.flatMap((preferences) =>
375 linkEnvironmentToCloudWithPreference({
376 ...input,
377 liveActivitiesEnabled: preferences.liveActivitiesEnabled !== false,
378 }),
379 ),
380 );
382​
383export function listCloudEnvironments(input: {
384 readonly clerkToken: string;
385}): Effect.Effect<
386 ReadonlyArray<RelayClientEnvironmentRecord>,
387 CloudEnvironmentLinkError,
388 ManagedRelay.ManagedRelayClient
389> {
390 return Effect.gen(function* () {
391 const relayUrl = yield* requireRelayUrl();
392 const relayClient = yield* ManagedRelay.ManagedRelayClient;
393​
394 return yield* relayClient
395 .listEnvironments({
396 clerkToken: input.clerkToken,
397 })
398 .pipe(Effect.mapError(decodedRelayClientError(`${relayUrl}/v1/environments failed`)));
399 });
401​
402export function getCloudEnvironmentStatus(input: {
403 readonly clerkToken: string;
404 readonly environment: RelayClientEnvironmentRecord;
405 readonly relayScopes?: ReadonlyArray<RelayDpopAccessTokenScope>;
406}): Effect.Effect<
407 RelayEnvironmentStatusResponseType,
408 CloudEnvironmentLinkError,
409 ManagedRelay.ManagedRelayClient
410> {
411 return Effect.gen(function* () {
412 const relayUrl = yield* requireRelayUrl();
413 const relayClient = yield* ManagedRelay.ManagedRelayClient;
414 const status = yield* relayClient
415 .getEnvironmentStatus({
416 clerkToken: input.clerkToken,
417 scopes: input.relayScopes ?? [RelayEnvironmentStatusScope],
418 environmentId: input.environment.environmentId,
419 })
420 .pipe(
421 Effect.mapError(
422 decodedRelayClientError(
423 `${relayUrl}/v1/environments/${encodeURIComponent(input.environment.environmentId)}/status failed`,
424 ),
425 ),
426 );
427 yield* ensureStatusMatchesEnvironment({ environment: input.environment, status });
428 return status;
429 });
431​
432export function cloudEnvironmentsPendingStatus(
433 environments: ReadonlyArray<RelayClientEnvironmentRecord>,
434): ReadonlyArray<CloudEnvironmentRecordWithStatus> {
435 return environments.map((environment) => ({
436 environment,
437 status: null,
438 statusError: "Checking status...",
439 }));
441​
442export function loadCloudEnvironmentStatuses(input: {
443 readonly clerkToken: string;
444 readonly environments: ReadonlyArray<RelayClientEnvironmentRecord>;
445}): Effect.Effect<
446 ReadonlyArray<CloudEnvironmentRecordWithStatus>,
447 CloudEnvironmentLinkError,
448 ManagedRelay.ManagedRelayClient
449> {
450 return Effect.forEach(
451 input.environments,
452 (environment) =>
453 getCloudEnvironmentStatus({
454 clerkToken: input.clerkToken,
455 environment,
456 relayScopes: RELAY_STATUS_AND_CONNECT_SCOPES,
457 }).pipe(
458 Effect.match({
459 onFailure: (error) => ({
460 environment,
461 status: null,
462 statusError: error.message,
463 }),
464 onSuccess: (status) => ({
465 environment,
466 status,
467 statusError: null,
468 }),
469 }),
470 ),
471 { concurrency: "unbounded" },
472 );
474​
475export function listCloudEnvironmentsWithStatus(input: {
476 readonly clerkToken: string;
477}): Effect.Effect<
478 ReadonlyArray<CloudEnvironmentRecordWithStatus>,
479 CloudEnvironmentLinkError,
480 ManagedRelay.ManagedRelayClient
481> {
482 return Effect.gen(function* () {
483 const environments = yield* listCloudEnvironments(input);
484 return yield* loadCloudEnvironmentStatuses({
485 clerkToken: input.clerkToken,
486 environments,
487 });
488 });
490​
491const loadAgentAwarenessDeviceId = Effect.fn("mobile.cloud.loadAgentAwarenessDeviceId")(
492 function* () {
493 const storage = yield* MobileStorage.MobileStorage;
494 return yield* storage.loadOrCreateAgentAwarenessDeviceId.pipe(
495 Effect.mapError(cloudEnvironmentLinkError("Could not load the mobile device id.")),
496 );
497 },
498);
499​
500const connectRelayManagedEnvironment = Effect.fn("mobile.cloud.connectRelayManagedEnvironment")(
501 function* (input: {
502 readonly clerkToken: string;
503 readonly environmentId: RelayClientEnvironmentRecord["environmentId"];
504 readonly expectedEnvironment?: RelayClientEnvironmentRecord;
505 }) {
506 yield* Effect.annotateCurrentSpan({ "environment.id": input.environmentId });
507 const relayUrl = yield* requireRelayUrl();
508 const relayClient = yield* ManagedRelay.ManagedRelayClient;
509​
510 const deviceId = yield* loadAgentAwarenessDeviceId();
511 const connect = yield* relayClient
512 .connectEnvironment({
513 clerkToken: input.clerkToken,
514 scopes: [RelayEnvironmentConnectScope],
515 environmentId: input.environmentId,
516 deviceId,
517 })
518 .pipe(
519 Effect.mapError(
520 decodedRelayClientError(
521 `${relayUrl}/v1/environments/${encodeURIComponent(input.environmentId)}/connect failed`,
522 ),
523 ),
524 );
525 if (connect.environmentId !== input.environmentId) {
526 return yield* new CloudEnvironmentLinkError({
527 message: "Relay returned credentials for a different environment.",
528 });
529 }
530 if (input.expectedEnvironment) {
531 yield* ensureConnectEndpointMatchesEnvironment({
532 environment: input.expectedEnvironment,
533 connect,
534 });
535 }
536​
537 const descriptor = yield* fetchRemoteEnvironmentDescriptor({
538 httpBaseUrl: connect.endpoint.httpBaseUrl,
539 }).pipe(
540 Effect.mapError(
541 cloudEnvironmentLinkError("Could not fetch the connected environment descriptor."),
542 ),
543 );
544 if (descriptor.environmentId !== connect.environmentId) {
545 return yield* new CloudEnvironmentLinkError({
546 message: "Connected endpoint descriptor does not match the selected environment.",
547 });
548 }
549 const signer = yield* ManagedRelay.ManagedRelayDpopSigner;
550 const bootstrapDpop = yield* signer
551 .createProof({
552 method: "POST",
553 url: new URL("/oauth/token", connect.endpoint.httpBaseUrl).toString(),
554 })
555 .pipe(Effect.mapError(cloudEnvironmentLinkError("Could not create bootstrap DPoP proof.")));
556 const bootstrap = yield* exchangeRemoteDpopAccessToken({
557 httpBaseUrl: connect.endpoint.httpBaseUrl,
558 credential: connect.credential,
559 dpopProof: bootstrapDpop,
560 clientMetadata: authClientMetadata(),
561 }).pipe(
562 Effect.mapError(
563 cloudEnvironmentLinkError("Could not exchange a managed endpoint DPoP access token."),
564 ),
565 );
566 const pairingUrl = new URL(connect.endpoint.httpBaseUrl);
567 pairingUrl.hash = new URLSearchParams([["token", connect.credential]]).toString();
568​
569 return {
570 environmentId: descriptor.environmentId,
571 environmentLabel: descriptor.label,
572 pairingUrl: stripPairingTokenFromUrl(pairingUrl).toString(),
573 displayUrl: connect.endpoint.httpBaseUrl,
574 httpBaseUrl: connect.endpoint.httpBaseUrl,
575 wsBaseUrl: connect.endpoint.wsBaseUrl,
576 bearerToken: null,
577 authenticationMethod: "dpop",
578 dpopAccessToken: bootstrap.access_token,
579 relayManaged: true,
580 } satisfies SavedRemoteConnection;
581 },
582);
583​
584export function connectCloudEnvironment(input: {
585 readonly clerkToken: string;
586 readonly environment: RelayClientEnvironmentRecord;
587}): Effect.Effect<
588 SavedRemoteConnection,
589 CloudEnvironmentLinkError,
590 | HttpClient.HttpClient
591 | ManagedRelay.ManagedRelayClient
592 | ManagedRelay.ManagedRelayDpopSigner
593 | MobileStorage.MobileStorage
594> {
595 return connectRelayManagedEnvironment({
596 clerkToken: input.clerkToken,
597 environmentId: input.environment.environmentId,
598 expectedEnvironment: input.environment,
599 });
601​
602export function refreshCloudEnvironmentConnection(input: {
603 readonly clerkToken: string;
604 readonly connection: SavedRemoteConnection;
605}): Effect.Effect<
606 SavedRemoteConnection,
607 CloudEnvironmentLinkError,
608 | HttpClient.HttpClient
609 | ManagedRelay.ManagedRelayClient
610 | ManagedRelay.ManagedRelayDpopSigner
611 | MobileStorage.MobileStorage
612> {
613 return connectRelayManagedEnvironment({
614 clerkToken: input.clerkToken,
615 environmentId: input.connection.environmentId,
616 });