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

linkEnvironment.ts

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