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

linkEnvironment.ts

715 lines23.4 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 type EnvironmentCloudLinkStateResult,
8 EnvironmentHttpBadRequestError,
9 EnvironmentHttpConflictError,
10 EnvironmentHttpForbiddenError,
11 EnvironmentHttpInternalServerError,
12 EnvironmentHttpUnauthorizedError,
13 EnvironmentId,
14} from "@t3tools/contracts";
15import {
16 RelayEnvironmentConnectScope,
17 type RelayClientDeviceRecord,
18 type RelayEnvironmentLinkResponse,
19 RelayProtectedError,
20 type RelayClientEnvironmentRecord,
21 type RelayProtectedError as RelayProtectedErrorType,
22 type RelayManagedEndpointProviderKind,
23} from "@t3tools/contracts/relay";
24import {
25 exchangeRemoteDpopAccessToken,
26 fetchRemoteEnvironmentDescriptor,
27 makeEnvironmentHttpApiClient,
28 ManagedRelayClient,
29 ManagedRelayDpopSigner,
30 type WsRpcClient,
31} from "@t3tools/client-runtime";
32​
33import { ensureLocalApi } from "../localApi";
34import {
35 getPrimaryEnvironmentConnection,
36 readEnvironmentConnection,
37 type SavedEnvironmentRecord,
38} from "../environments/runtime";
39import {
40 readPrimaryEnvironmentDescriptor,
41 readPrimaryEnvironmentTarget,
42 resolvePrimaryEnvironmentHttpUrl,
43} from "../environments/primary";
44import { withPrimaryEnvironmentRequestInit } from "../environments/primary/requestInit";
45import { resolveCloudPublicConfig } from "./publicConfig";
46import {
47 finishRelayClientInstall,
48 reportRelayClientInstallProgress,
49 requestRelayClientInstallConfirmation,
50} from "./relayClientInstallDialog";
51​
52export function normalizeRelayBaseUrl(value: string | null | undefined): string | null {
53 const trimmed = value?.trim();
54 if (!trimmed) {
55 return null;
56 }
57 return trimmed.replace(/\/+$/g, "");
59​
60function relayUrl(): string | null {
61 return resolveCloudPublicConfig().relayUrl;
63​
64export class CloudEnvironmentLinkError extends Data.TaggedError("CloudEnvironmentLinkError")<{
65 readonly message: string;
66 readonly cause?: unknown;
67}> {}
68​
69const relayClientRpcError = (message: string) => (cause: unknown) =>
70 new CloudEnvironmentLinkError({
71 message,
72 cause,
73 });
74​
75function ensureRelayClientAvailable(
76 client: WsRpcClient,
77): Effect.Effect<void, CloudEnvironmentLinkError> {
78 return Effect.gen(function* () {
79 const status = yield* Effect.tryPromise({
80 try: () => client.cloud.getRelayClientStatus(),
81 catch: relayClientRpcError("Could not check relay client availability."),
82 });
83 if (status.status === "available") return;
84 if (status.status === "unsupported") {
85 return yield* new CloudEnvironmentLinkError({
86 message: `T3 Code cannot install the relay client automatically on ${status.platform}-${status.arch}.`,
87 });
88 }
89​
90 const confirmed = yield* Effect.tryPromise({
91 try: () => requestRelayClientInstallConfirmation(status.version),
92 catch: relayClientRpcError("Could not confirm relay client installation."),
93 });
94 if (!confirmed) {
95 return yield* new CloudEnvironmentLinkError({
96 message: "Relay client installation was cancelled.",
97 });
98 }
99​
100 const installed = yield* Effect.tryPromise({
101 try: () => client.cloud.installRelayClient(reportRelayClientInstallProgress),
102 catch: relayClientRpcError("Could not install the relay client."),
103 }).pipe(Effect.ensuring(Effect.sync(finishRelayClientInstall)));
104 if (installed.status !== "available") {
105 return yield* new CloudEnvironmentLinkError({
106 message:
107 installed.status === "unsupported"
108 ? `T3 Code cannot install the relay client automatically on ${installed.platform}-${installed.arch}.`
109 : "The relay client is still unavailable after installation.",
110 });
111 }
112 });
114​
115const isRelayProtectedError = Schema.is(RelayProtectedError);
116const isEnvironmentCloudApiError = Schema.is(
117 Schema.Union([
118 EnvironmentHttpBadRequestError,
119 EnvironmentHttpUnauthorizedError,
120 EnvironmentHttpForbiddenError,
121 EnvironmentHttpConflictError,
122 EnvironmentHttpInternalServerError,
123 EnvironmentCloudEndpointUnavailableError,
124 ]),
125);
126​
127function relayProtectedErrorMessage(error: RelayProtectedErrorType): string {
128 switch (error._tag) {
129 case "RelayAuthInvalidError":
130 switch (error.reason) {
131 case "missing_bearer":
132 case "invalid_bearer":
133 return "Relay rejected the cloud session token.";
134 case "invalid_dpop":
135 return "Relay rejected the DPoP proof.";
136 case "not_authorized":
137 return "Relay rejected the authenticated request.";
138 }
139 case "RelayEnvironmentLinkProofExpiredError":
140 return "Relay rejected an expired environment link proof.";
141 case "RelayEnvironmentLinkProofInvalidError":
142 return `Relay rejected the environment link proof (${error.reason}).`;
143 case "RelayEnvironmentConnectNotAuthorizedError":
144 return "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 "RelayAgentActivityPublishProofExpiredError":
154 return "Relay rejected an expired agent activity publish proof.";
155 case "RelayAgentActivityPublishProofInvalidError":
156 return `Relay rejected the agent activity publish proof (${error.reason}).`;
157 case "RelayInternalError":
158 return `Relay encountered an internal error (${error.reason}, trace ${error.traceId}).`;
159 }
161​
162function decodedRelayClientError(message: string) {
163 return (cause: unknown) => {
164 const relayError = findRelayProtectedError(cause);
165 const detail = relayError ? relayProtectedErrorMessage(relayError) : null;
166 return new CloudEnvironmentLinkError({
167 message: detail ? `${message}: ${detail}` : message,
168 cause,
169 });
170 };
172​
173function findRelayProtectedError(cause: unknown): RelayProtectedErrorType | null {
174 if (isRelayProtectedError(cause)) {
175 return cause;
176 }
177 if (typeof cause !== "object" || cause === null) {
178 return null;
179 }
180 return "cause" in cause ? findRelayProtectedError(cause.cause) : null;
182​
183function findEnvironmentCloudApiError(cause: unknown): { readonly message: string } | null {
184 if (isEnvironmentCloudApiError(cause)) {
185 return cause;
186 }
187 if (typeof cause !== "object" || cause === null) {
188 return null;
189 }
190 return "cause" in cause ? findEnvironmentCloudApiError(cause.cause) : null;
192​
193const environmentApiError = (message: string) => (cause: unknown) => {
194 const environmentError = findEnvironmentCloudApiError(cause);
195 return new CloudEnvironmentLinkError({
196 message: environmentError
197 ? `${message.replace(/[.:]$/, "")}: ${environmentError.message}`
198 : message,
199 cause,
200 });
201};
202​
203function endpointOrigin(httpBaseUrl: string) {
204 const url = new URL(httpBaseUrl);
205 return {
206 localHttpHost: "127.0.0.1",
207 localHttpPort: Number(url.port || (url.protocol === "https:" ? 443 : 80)),
208 };
210​
211const MANAGED_ENDPOINT_PROVIDER_KIND =
212 "cloudflare_tunnel" satisfies RelayManagedEndpointProviderKind;
213​
214function ensureLinkedEnvironmentMatches(input: {
215 readonly expectedEnvironmentId: string;
216 readonly expectedProviderKind: RelayManagedEndpointProviderKind;
217 readonly link: RelayEnvironmentLinkResponse;
218}): Effect.Effect<void, CloudEnvironmentLinkError> {
219 if (input.link.environmentId !== input.expectedEnvironmentId) {
220 return new CloudEnvironmentLinkError({
221 message: "Relay returned credentials for a different environment.",
222 });
223 }
224 if (input.link.endpoint.providerKind !== input.expectedProviderKind) {
225 return new CloudEnvironmentLinkError({
226 message: "Relay returned credentials for a different endpoint provider.",
227 });
228 }
229 return Effect.void;
231​
232export interface CloudLinkTarget {
233 readonly environmentId: string;
234 readonly label: string;
235 readonly httpBaseUrl: string;
236 readonly wsBaseUrl: string;
238​
239export type CloudLinkState = EnvironmentCloudLinkStateResult;
240​
241export interface CloudManagedConnection {
242 readonly environmentId: RelayClientEnvironmentRecord["environmentId"];
243 readonly label: string;
244 readonly httpBaseUrl: string;
245 readonly wsBaseUrl: string;
246 readonly relayUrl: string;
247 readonly accessToken: string;
249​
250export function collectCloudLinkTargets(input: {
251 readonly primary: CloudLinkTarget | null;
252 readonly saved: ReadonlyArray<CloudLinkTarget>;
253}): ReadonlyArray<CloudLinkTarget> {
254 const byId = new Map<string, CloudLinkTarget>();
255 if (input.primary) {
256 byId.set(input.primary.environmentId, input.primary);
257 }
258 for (const environment of input.saved) {
259 if (!byId.has(environment.environmentId)) {
260 byId.set(environment.environmentId, environment);
261 }
262 }
263 return [...byId.values()];
265​
266export function readPrimaryCloudLinkTarget(): CloudLinkTarget | null {
267 const descriptor = readPrimaryEnvironmentDescriptor();
268 const target = readPrimaryEnvironmentTarget();
269 if (!descriptor || !target) {
270 return null;
271 }
272 return {
273 environmentId: descriptor.environmentId,
274 label: descriptor.label,
275 httpBaseUrl: target.target.httpBaseUrl,
276 wsBaseUrl: target.target.wsBaseUrl,
277 };
279​
280export function listManagedCloudEnvironments(input: {
281 readonly clerkToken: string;
282}): Effect.Effect<
283 ReadonlyArray<RelayClientEnvironmentRecord>,
284 CloudEnvironmentLinkError,
285 ManagedRelayClient
286> {
287 return Effect.gen(function* () {
288 const configuredRelayUrl = relayUrl();
289 if (!configuredRelayUrl) {
290 return yield* new CloudEnvironmentLinkError({
291 message: "T3CODE_RELAY_URL is not configured.",
292 });
293 }
294 const relayClient = yield* ManagedRelayClient;
295 return yield* relayClient
296 .listEnvironments({
297 clerkToken: input.clerkToken,
298 })
299 .pipe(
300 Effect.mapError(
301 (cause) =>
302 new CloudEnvironmentLinkError({
303 message: "Could not list relay-managed environments.",
304 cause,
305 }),
306 ),
307 );
308 });
310​
311export function listCloudDevices(input: {
312 readonly clerkToken: string;
313}): Effect.Effect<
314 ReadonlyArray<RelayClientDeviceRecord>,
315 CloudEnvironmentLinkError,
316 ManagedRelayClient
317> {
318 return Effect.gen(function* () {
319 if (!relayUrl()) {
320 return yield* new CloudEnvironmentLinkError({
321 message: "T3CODE_RELAY_URL is not configured.",
322 });
323 }
324 const relayClient = yield* ManagedRelayClient;
325 return yield* relayClient.listDevices({ clerkToken: input.clerkToken }).pipe(
326 Effect.mapError(
327 (cause) =>
328 new CloudEnvironmentLinkError({
329 message: "Could not list cloud devices.",
330 cause,
331 }),
332 ),
333 );
334 });
336​
337export function connectManagedCloudEnvironment(input: {
338 readonly clerkToken: string;
339 readonly environment: RelayClientEnvironmentRecord;
340 readonly relayUrl?: string;
341}): Effect.Effect<
342 CloudManagedConnection,
343 CloudEnvironmentLinkError,
344 HttpClient.HttpClient | ManagedRelayClient | ManagedRelayDpopSigner
345> {
346 return Effect.gen(function* () {
347 const configuredRelayUrl = relayUrl();
348 if (!configuredRelayUrl) {
349 return yield* new CloudEnvironmentLinkError({
350 message: "T3CODE_RELAY_URL is not configured.",
351 });
352 }
353 const persistedRelayUrl = normalizeRelayBaseUrl(input.relayUrl);
354 if (persistedRelayUrl && persistedRelayUrl !== configuredRelayUrl) {
355 return yield* new CloudEnvironmentLinkError({
356 message: "The saved environment is linked through a different configured relay.",
357 });
358 }
359 const relayClient = yield* ManagedRelayClient;
360 const connected = yield* relayClient
361 .connectEnvironment({
362 clerkToken: input.clerkToken,
363 scopes: [RelayEnvironmentConnectScope],
364 environmentId: input.environment.environmentId,
365 })
366 .pipe(
367 Effect.mapError(
368 (cause) =>
369 new CloudEnvironmentLinkError({
370 message: "Could not connect to relay-managed environment.",
371 cause,
372 }),
373 ),
374 );
375 if (connected.environmentId !== input.environment.environmentId) {
376 return yield* new CloudEnvironmentLinkError({
377 message: "Relay returned credentials for a different environment.",
378 });
379 }
380 if (
381 connected.endpoint.httpBaseUrl !== input.environment.endpoint.httpBaseUrl ||
382 connected.endpoint.wsBaseUrl !== input.environment.endpoint.wsBaseUrl ||
383 connected.endpoint.providerKind !== input.environment.endpoint.providerKind
384 ) {
385 return yield* new CloudEnvironmentLinkError({
386 message: "Relay returned credentials for a different endpoint.",
387 });
388 }
389 const descriptor = yield* fetchRemoteEnvironmentDescriptor({
390 httpBaseUrl: connected.endpoint.httpBaseUrl,
391 }).pipe(
392 Effect.mapError(
393 (cause) =>
394 new CloudEnvironmentLinkError({
395 message: "Could not read connected environment descriptor.",
396 cause,
397 }),
398 ),
399 );
400 if (descriptor.environmentId !== connected.environmentId) {
401 return yield* new CloudEnvironmentLinkError({
402 message: "Connected endpoint does not match the selected environment.",
403 });
404 }
405 const signer = yield* ManagedRelayDpopSigner;
406 const bootstrapProof = yield* signer
407 .createProof({
408 method: "POST",
409 url: new URL("/oauth/token", connected.endpoint.httpBaseUrl).toString(),
410 })
411 .pipe(
412 Effect.mapError(
413 (cause) =>
414 new CloudEnvironmentLinkError({
415 message: "Could not create environment DPoP proof.",
416 cause,
417 }),
418 ),
419 );
420 const session = yield* exchangeRemoteDpopAccessToken({
421 httpBaseUrl: connected.endpoint.httpBaseUrl,
422 credential: connected.credential,
423 dpopProof: bootstrapProof,
424 }).pipe(
425 Effect.mapError(
426 (cause) =>
427 new CloudEnvironmentLinkError({
428 message: "Could not authorize managed environment.",
429 cause,
430 }),
431 ),
432 );
433 return {
434 environmentId: descriptor.environmentId,
435 label: descriptor.label,
436 httpBaseUrl: connected.endpoint.httpBaseUrl,
437 wsBaseUrl: connected.endpoint.wsBaseUrl,
438 relayUrl: configuredRelayUrl,
439 accessToken: session.access_token,
440 };
441 });
443​
444export function readPrimaryCloudLinkState(): Effect.Effect<
445 CloudLinkState | null,
446 CloudEnvironmentLinkError,
447 HttpClient.HttpClient
448> {
449 return Effect.gen(function* () {
450 if (!readPrimaryCloudLinkTarget()) {
451 return null;
452 }
453 const client = yield* makeEnvironmentHttpApiClient(resolvePrimaryEnvironmentHttpUrl("/"));
454 return yield* client.connect
455 .linkState({ headers: {} })
456 .pipe(
457 withPrimaryEnvironmentRequestInit,
458 Effect.mapError(environmentApiError("Could not read environment cloud link state.")),
459 );
460 });
462​
463export function updatePrimaryCloudPreferences(input: {
464 readonly publishAgentActivity: boolean;
465}): Effect.Effect<CloudLinkState, CloudEnvironmentLinkError, HttpClient.HttpClient> {
466 return Effect.gen(function* () {
467 const client = yield* makeEnvironmentHttpApiClient(resolvePrimaryEnvironmentHttpUrl("/"));
468 return yield* client.connect
469 .preferences({
470 headers: {},
471 payload: input,
472 })
473 .pipe(
474 withPrimaryEnvironmentRequestInit,
475 Effect.mapError(environmentApiError("Could not update environment cloud preferences.")),
476 );
477 });
479​
480export function unlinkPrimaryEnvironmentFromCloud(input: {
481 readonly clerkToken: string | null;
482}): Effect.Effect<void, CloudEnvironmentLinkError, HttpClient.HttpClient | ManagedRelayClient> {
483 return Effect.gen(function* () {
484 const target = readPrimaryCloudLinkTarget();
485 if (!target) {
486 return yield* new CloudEnvironmentLinkError({
487 message: "Local environment is not ready yet.",
488 });
489 }
490 const client = yield* makeEnvironmentHttpApiClient(resolvePrimaryEnvironmentHttpUrl("/"));
491 yield* client.connect
492 .unlink({ headers: {} })
493 .pipe(
494 withPrimaryEnvironmentRequestInit,
495 Effect.mapError(environmentApiError("Could not unlink the environment from cloud.")),
496 );
497​
498 const configuredRelayUrl = relayUrl();
499 if (configuredRelayUrl && input.clerkToken) {
500 const relayClient = yield* ManagedRelayClient;
501 yield* relayClient
502 .unlinkEnvironment({
503 clerkToken: input.clerkToken,
504 environmentId: EnvironmentId.make(target.environmentId),
505 })
506 .pipe(
507 Effect.catch((cause) =>
508 Effect.logWarning("Could not revoke cloud environment link after local unlink.", {
509 cause,
510 }),
511 ),
512 );
513 }
514 });
516​
517export function linkEnvironmentToCloud(input: {
518 readonly environment: SavedEnvironmentRecord;
519 readonly clerkToken: string;
520}): Effect.Effect<void, CloudEnvironmentLinkError, HttpClient.HttpClient | ManagedRelayClient> {
521 return Effect.gen(function* () {
522 const configuredRelayUrl = relayUrl();
523 if (!configuredRelayUrl) {
524 return yield* new CloudEnvironmentLinkError({
525 message: "T3CODE_RELAY_URL is not configured.",
526 });
527 }
528 const relayClient = yield* ManagedRelayClient;
529 const bearerToken = yield* Effect.tryPromise({
530 try: () =>
531 ensureLocalApi().persistence.getSavedEnvironmentSecret(input.environment.environmentId),
532 catch: (cause) =>
533 new CloudEnvironmentLinkError({
534 message: `Could not read saved bearer token for ${input.environment.label}.`,
535 cause,
536 }),
537 });
538 if (!bearerToken) {
539 return yield* new CloudEnvironmentLinkError({
540 message: `No saved bearer token for ${input.environment.label}.`,
541 });
542 }
543​
544 const connection = readEnvironmentConnection(input.environment.environmentId);
545 if (!connection) {
546 return yield* new CloudEnvironmentLinkError({
547 message: `${input.environment.label} is not connected.`,
548 });
549 }
550 yield* ensureRelayClientAvailable(connection.client);
551​
552 const environmentClient = yield* makeEnvironmentHttpApiClient(input.environment.httpBaseUrl);
553 const headers = { authorization: `Bearer ${bearerToken}` };
554​
555 const challenge = yield* relayClient
556 .createEnvironmentLinkChallenge({
557 clerkToken: input.clerkToken,
558 payload: {
559 notificationsEnabled: true,
560 liveActivitiesEnabled: true,
561 managedTunnelsEnabled: true,
562 },
563 })
564 .pipe(
565 Effect.mapError(
566 decodedRelayClientError(
567 `${configuredRelayUrl}/v1/client/environment-link-challenges failed`,
568 ),
569 ),
570 );
571 const proof = yield* environmentClient.connect
572 .linkProof({
573 headers,
574 payload: {
575 challenge: challenge.challenge,
576 relayIssuer: configuredRelayUrl,
577 endpoint: {
578 httpBaseUrl: input.environment.httpBaseUrl,
579 wsBaseUrl: input.environment.wsBaseUrl,
580 providerKind: MANAGED_ENDPOINT_PROVIDER_KIND,
581 },
582 origin: endpointOrigin(input.environment.httpBaseUrl),
583 },
584 })
585 .pipe(Effect.mapError(environmentApiError("Could not obtain environment link proof.")));
586 const link = yield* relayClient
587 .linkEnvironment({
588 clerkToken: input.clerkToken,
589 payload: {
590 proof,
591 notificationsEnabled: true,
592 liveActivitiesEnabled: true,
593 managedTunnelsEnabled: true,
594 },
595 })
596 .pipe(
597 Effect.mapError(
598 decodedRelayClientError(`${configuredRelayUrl}/v1/client/environment-links failed`),
599 ),
600 );
601 yield* ensureLinkedEnvironmentMatches({
602 expectedEnvironmentId: input.environment.environmentId,
603 expectedProviderKind: MANAGED_ENDPOINT_PROVIDER_KIND,
604 link,
605 });
606​
607 yield* environmentClient.connect
608 .relayConfig({
609 headers,
610 payload: {
611 relayUrl: configuredRelayUrl,
612 relayIssuer: link.relayIssuer,
613 cloudUserId: link.cloudUserId,
614 environmentCredential: link.environmentCredential,
615 cloudMintPublicKey: link.cloudMintPublicKey,
616 endpointRuntime: link.endpointRuntime,
617 },
618 })
619 .pipe(Effect.mapError(environmentApiError("Could not configure environment relay access.")));
620 });
622​
623export function linkPrimaryEnvironmentToCloud(input: {
624 readonly clerkToken: string;
625}): Effect.Effect<void, CloudEnvironmentLinkError, HttpClient.HttpClient | ManagedRelayClient> {
626 return Effect.gen(function* () {
627 const configuredRelayUrl = relayUrl();
628 if (!configuredRelayUrl) {
629 return yield* new CloudEnvironmentLinkError({
630 message: "T3CODE_RELAY_URL is not configured.",
631 });
632 }
633 const relayClient = yield* ManagedRelayClient;
634 const target = readPrimaryCloudLinkTarget();
635 if (!target) {
636 return yield* new CloudEnvironmentLinkError({
637 message: "Local environment is not ready yet.",
638 });
639 }
640 const environmentClient = yield* makeEnvironmentHttpApiClient(target.httpBaseUrl);
641 yield* ensureRelayClientAvailable(getPrimaryEnvironmentConnection().client);
642​
643 const challenge = yield* relayClient
644 .createEnvironmentLinkChallenge({
645 clerkToken: input.clerkToken,
646 payload: {
647 notificationsEnabled: true,
648 liveActivitiesEnabled: true,
649 managedTunnelsEnabled: true,
650 },
651 })
652 .pipe(
653 Effect.mapError(
654 decodedRelayClientError(
655 `${configuredRelayUrl}/v1/client/environment-link-challenges failed`,
656 ),
657 ),
658 );
659 const proof = yield* environmentClient.connect
660 .linkProof({
661 headers: {},
662 payload: {
663 challenge: challenge.challenge,
664 relayIssuer: configuredRelayUrl,
665 endpoint: {
666 httpBaseUrl: target.httpBaseUrl,
667 wsBaseUrl: target.wsBaseUrl,
668 providerKind: MANAGED_ENDPOINT_PROVIDER_KIND,
669 },
670 origin: endpointOrigin(target.httpBaseUrl),
671 },
672 })
673 .pipe(
674 withPrimaryEnvironmentRequestInit,
675 Effect.mapError(environmentApiError("Could not obtain environment link proof.")),
676 );
677 const link = yield* relayClient
678 .linkEnvironment({
679 clerkToken: input.clerkToken,
680 payload: {
681 proof,
682 notificationsEnabled: true,
683 liveActivitiesEnabled: true,
684 managedTunnelsEnabled: true,
685 },
686 })
687 .pipe(
688 Effect.mapError(
689 decodedRelayClientError(`${configuredRelayUrl}/v1/client/environment-links failed`),
690 ),
691 );
692 yield* ensureLinkedEnvironmentMatches({
693 expectedEnvironmentId: target.environmentId,
694 expectedProviderKind: MANAGED_ENDPOINT_PROVIDER_KIND,
695 link,
696 });
697​
698 yield* environmentClient.connect
699 .relayConfig({
700 headers: {},
701 payload: {
702 relayUrl: configuredRelayUrl,
703 relayIssuer: link.relayIssuer,
704 cloudUserId: link.cloudUserId,
705 environmentCredential: link.environmentCredential,
706 cloudMintPublicKey: link.cloudMintPublicKey,
707 endpointRuntime: link.endpointRuntime,
708 },
709 })
710 .pipe(
711 withPrimaryEnvironmentRequestInit,
712 Effect.mapError(environmentApiError("Could not configure environment relay access.")),
713 );
714 });