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

linkEnvironment.ts

487 lines16.8 KB

1import * as Data from "effect/Data";
2import * as Effect from "effect/Effect";
3import * as Option from "effect/Option";
4import * as Schema from "effect/Schema";
5import * as Stream from "effect/Stream";
6import { HttpClient } from "effect/unstable/http";
7import {
8 EnvironmentCloudEndpointUnavailableError,
9 type EnvironmentCloudLinkStateResult,
10 EnvironmentHttpBadRequestError,
11 EnvironmentHttpConflictError,
12 EnvironmentHttpForbiddenError,
13 EnvironmentHttpInternalServerError,
14 EnvironmentHttpUnauthorizedError,
15 EnvironmentId,
16 WS_METHODS,
17} from "@t3tools/contracts";
18import {
19 type RelayClientDeviceRecord,
20 type RelayClientEnvironmentRecord,
21 type RelayEnvironmentLinkResponse,
22 type RelayProtectedError as RelayProtectedErrorType,
23 type RelayManagedEndpointProviderKind,
24} from "@t3tools/contracts/relay";
25import { EnvironmentRegistry } from "@t3tools/client-runtime/connection";
26import { request, runStream } from "@t3tools/client-runtime/rpc";
27import { makeEnvironmentHttpApiClient } from "@t3tools/client-runtime/rpc";
28import { ManagedRelay } from "@t3tools/client-runtime/relay";
29​
30import {
31 readPrimaryEnvironmentDescriptor,
32 readPrimaryEnvironmentTarget,
33} from "../environments/primary";
34import { primaryEnvironmentHttpLayer } from "../environments/primary/httpLayer";
35import { resolveCloudPublicConfig } from "./publicConfig";
36import {
37 finishRelayClientInstall,
38 reportRelayClientInstallProgress,
39 requestRelayClientInstallConfirmation,
40} from "./relayClientInstallDialog";
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 relayUrl(): string | null {
51 return resolveCloudPublicConfig().relayUrl;
53​
54export class CloudEnvironmentLinkError extends Data.TaggedError("CloudEnvironmentLinkError")<{
55 readonly message: string;
56 readonly cause?: unknown;
57 readonly traceId?: string;
58}> {}
59​
60const relayClientRpcError = (message: string) => (cause: unknown) =>
61 new CloudEnvironmentLinkError({
62 message,
63 cause,
64 });
65​
66function ensureRelayClientAvailable(
67 environmentId: EnvironmentId,
68): Effect.Effect<void, CloudEnvironmentLinkError, EnvironmentRegistry> {
69 return Effect.gen(function* () {
70 const registry = yield* EnvironmentRegistry;
71 const status = yield* registry
72 .run(environmentId, request(WS_METHODS.cloudGetRelayClientStatus, {}))
73 .pipe(Effect.mapError(relayClientRpcError("Could not check relay client availability.")));
74 if (status.status === "available") return;
75 if (status.status === "unsupported") {
76 return yield* new CloudEnvironmentLinkError({
77 message: `T3 Code cannot install the relay client automatically on ${status.platform}-${status.arch}.`,
78 });
79 }
80​
81 const confirmed = yield* Effect.tryPromise({
82 try: () => requestRelayClientInstallConfirmation(status.version),
83 catch: relayClientRpcError("Could not confirm relay client installation."),
84 });
85 if (!confirmed) {
86 return yield* new CloudEnvironmentLinkError({
87 message: "Relay client installation was cancelled.",
88 });
89 }
90​
91 const installed = yield* registry
92 .runStream(
93 environmentId,
94 runStream(WS_METHODS.cloudInstallRelayClient, {}).pipe(
95 Stream.tap((event) => Effect.sync(() => reportRelayClientInstallProgress(event))),
96 ),
97 )
98 .pipe(
99 Stream.runLast,
100 Effect.mapError(relayClientRpcError("Could not install the relay client.")),
101 Effect.ensuring(Effect.sync(finishRelayClientInstall)),
102 );
103 if (Option.isNone(installed) || installed.value.type !== "complete") {
104 return yield* new CloudEnvironmentLinkError({
105 message: "The relay client install completed without a final status.",
106 });
107 }
108 const installedStatus = installed.value.status;
109 if (installedStatus.status !== "available") {
110 return yield* new CloudEnvironmentLinkError({
111 message:
112 installedStatus.status === "unsupported"
113 ? `T3 Code cannot install the relay client automatically on ${installedStatus.platform}-${installedStatus.arch}.`
114 : "The relay client is still unavailable after installation.",
115 });
116 }
117 });
119​
120const isEnvironmentCloudApiError = Schema.is(
121 Schema.Union([
122 EnvironmentHttpBadRequestError,
123 EnvironmentHttpUnauthorizedError,
124 EnvironmentHttpForbiddenError,
125 EnvironmentHttpConflictError,
126 EnvironmentHttpInternalServerError,
127 EnvironmentCloudEndpointUnavailableError,
128 ]),
129);
130​
131function relayProtectedErrorMessage(error: RelayProtectedErrorType): string {
132 switch (error._tag) {
133 case "RelayAuthInvalidError":
134 switch (error.reason) {
135 case "missing_bearer":
136 case "invalid_bearer":
137 return "Relay rejected the cloud session token.";
138 case "invalid_dpop":
139 return "Relay rejected the DPoP proof.";
140 case "not_authorized":
141 return "Relay rejected the authenticated request.";
142 }
143 case "RelayEnvironmentLinkProofExpiredError":
144 return "Relay rejected an expired environment link proof.";
145 case "RelayEnvironmentLinkProofInvalidError":
146 return `Relay rejected the environment link proof (${error.reason}).`;
147 case "RelayEnvironmentConnectNotAuthorizedError":
148 return "Relay rejected the environment connection request.";
149 case "RelayEnvironmentEndpointUnavailableError":
150 return `Relay could not reach the environment endpoint (${error.reason}).`;
151 case "RelayEnvironmentEndpointTimedOutError":
152 return "Relay timed out while contacting the environment endpoint.";
153 case "RelayEnvironmentLinkFailedError":
154 return `Relay could not link the environment (${error.reason}).`;
155 case "RelayEnvironmentLinkUnavailableError":
156 return `Relay cannot provision the managed endpoint (${error.reason}).`;
157 case "RelayEnvironmentLinkLimitExceededError":
158 return `Relay refused the link: this account already has its maximum of ${error.maxTunnels} managed tunnels. Unlink an environment to free one up.`;
159 case "RelayAgentActivityPublishProofExpiredError":
160 return "Relay rejected an expired agent activity publish proof.";
161 case "RelayAgentActivityPublishProofInvalidError":
162 return `Relay rejected the agent activity publish proof (${error.reason}).`;
163 case "RelayInternalError":
164 return `Relay encountered an internal error (${error.reason}).`;
165 }
167​
168function decodedRelayClientError(message: string) {
169 return (cause: ManagedRelay.ManagedRelayClientError) => {
170 const relayError =
171 cause._tag === "ManagedRelayRequestFailedError" ? cause.relayError : undefined;
172 const traceId = cause._tag === "ManagedRelayRequestFailedError" ? cause.traceId : undefined;
173 const detail = relayError ? relayProtectedErrorMessage(relayError) : null;
174 return new CloudEnvironmentLinkError({
175 message: detail ? `${message}: ${detail}` : message,
176 cause,
177 ...(traceId ? { traceId } : {}),
178 });
179 };
181​
182function findEnvironmentCloudApiError(cause: unknown): { readonly message: string } | null {
183 if (isEnvironmentCloudApiError(cause)) {
184 return cause;
185 }
186 if (typeof cause !== "object" || cause === null) {
187 return null;
188 }
189 return "cause" in cause ? findEnvironmentCloudApiError(cause.cause) : null;
191​
192const environmentApiError = (message: string) => (cause: unknown) => {
193 const environmentError = findEnvironmentCloudApiError(cause);
194 return new CloudEnvironmentLinkError({
195 message: environmentError
196 ? `${message.replace(/[.:]$/, "")}: ${environmentError.message}`
197 : message,
198 cause,
199 });
200};
201​
202function endpointOrigin(httpBaseUrl: string) {
203 const url = new URL(httpBaseUrl);
204 return {
205 localHttpHost: "127.0.0.1",
206 localHttpPort: Number(url.port || (url.protocol === "https:" ? 443 : 80)),
207 };
209​
210const MANAGED_ENDPOINT_PROVIDER_KIND =
211 "cloudflare_tunnel" satisfies RelayManagedEndpointProviderKind;
212​
213function ensureLinkedEnvironmentMatches(input: {
214 readonly expectedEnvironmentId: string;
215 readonly expectedProviderKind: RelayManagedEndpointProviderKind;
216 readonly link: RelayEnvironmentLinkResponse;
217}): Effect.Effect<void, CloudEnvironmentLinkError> {
218 if (input.link.environmentId !== input.expectedEnvironmentId) {
219 return new CloudEnvironmentLinkError({
220 message: "Relay returned credentials for a different environment.",
221 });
222 }
223 if (input.link.endpoint.providerKind !== input.expectedProviderKind) {
224 return new CloudEnvironmentLinkError({
225 message: "Relay returned credentials for a different endpoint provider.",
226 });
227 }
228 return Effect.void;
230​
231export interface CloudLinkTarget {
232 readonly environmentId: string;
233 readonly label: string;
234 readonly httpBaseUrl: string;
235 readonly wsBaseUrl: string;
237​
238export type CloudLinkState = EnvironmentCloudLinkStateResult;
239​
240export function collectCloudLinkTargets(input: {
241 readonly primary: CloudLinkTarget | null;
242 readonly saved: ReadonlyArray<CloudLinkTarget>;
243}): ReadonlyArray<CloudLinkTarget> {
244 const byId = new Map<string, CloudLinkTarget>();
245 if (input.primary) {
246 byId.set(input.primary.environmentId, input.primary);
247 }
248 for (const environment of input.saved) {
249 if (!byId.has(environment.environmentId)) {
250 byId.set(environment.environmentId, environment);
251 }
252 }
253 return [...byId.values()];
255​
256export function readPrimaryCloudLinkTarget(): CloudLinkTarget | null {
257 const descriptor = readPrimaryEnvironmentDescriptor();
258 const target = readPrimaryEnvironmentTarget();
259 if (!descriptor || !target) {
260 return null;
261 }
262 return {
263 environmentId: descriptor.environmentId,
264 label: descriptor.label,
265 httpBaseUrl: target.target.httpBaseUrl,
266 wsBaseUrl: target.target.wsBaseUrl,
267 };
269​
270export function listManagedCloudEnvironments(input: {
271 readonly clerkToken: string;
272}): Effect.Effect<
273 ReadonlyArray<RelayClientEnvironmentRecord>,
274 CloudEnvironmentLinkError,
275 ManagedRelay.ManagedRelayClient
276> {
277 return Effect.gen(function* () {
278 const configuredRelayUrl = relayUrl();
279 if (!configuredRelayUrl) {
280 return yield* new CloudEnvironmentLinkError({
281 message: "T3CODE_RELAY_URL is not configured.",
282 });
283 }
284 const relayClient = yield* ManagedRelay.ManagedRelayClient;
285 return yield* relayClient
286 .listEnvironments({
287 clerkToken: input.clerkToken,
288 })
289 .pipe(
290 Effect.mapError(
291 (cause) =>
292 new CloudEnvironmentLinkError({
293 message: "Could not list relay-managed environments.",
294 cause,
295 }),
296 ),
297 );
298 });
300​
301export function listCloudDevices(input: {
302 readonly clerkToken: string;
303}): Effect.Effect<
304 ReadonlyArray<RelayClientDeviceRecord>,
305 CloudEnvironmentLinkError,
306 ManagedRelay.ManagedRelayClient
307> {
308 return Effect.gen(function* () {
309 if (!relayUrl()) {
310 return yield* new CloudEnvironmentLinkError({
311 message: "T3CODE_RELAY_URL is not configured.",
312 });
313 }
314 const relayClient = yield* ManagedRelay.ManagedRelayClient;
315 return yield* relayClient.listDevices({ clerkToken: input.clerkToken }).pipe(
316 Effect.mapError(
317 (cause) =>
318 new CloudEnvironmentLinkError({
319 message: "Could not list cloud devices.",
320 cause,
321 }),
322 ),
323 );
324 });
326​
327export function readPrimaryCloudLinkState(input: {
328 readonly target: CloudLinkTarget;
329}): Effect.Effect<CloudLinkState | null, CloudEnvironmentLinkError, HttpClient.HttpClient> {
330 return Effect.gen(function* () {
331 const client = yield* makeEnvironmentHttpApiClient(input.target.httpBaseUrl);
332 return yield* client.connect
333 .linkState({ headers: {} })
334 .pipe(Effect.mapError(environmentApiError("Could not read environment cloud link state.")));
335 }).pipe(Effect.provide(primaryEnvironmentHttpLayer));
337​
338export function updatePrimaryCloudPreferences(input: {
339 readonly target: CloudLinkTarget;
340 readonly publishAgentActivity: boolean;
341}): Effect.Effect<CloudLinkState, CloudEnvironmentLinkError, HttpClient.HttpClient> {
342 return Effect.gen(function* () {
343 const client = yield* makeEnvironmentHttpApiClient(input.target.httpBaseUrl);
344 return yield* client.connect
345 .preferences({
346 headers: {},
347 payload: input,
348 })
349 .pipe(
350 Effect.mapError(environmentApiError("Could not update environment cloud preferences.")),
351 );
352 }).pipe(Effect.provide(primaryEnvironmentHttpLayer));
354​
355export function unlinkPrimaryEnvironmentFromCloud(input: {
356 readonly target: CloudLinkTarget;
357 readonly clerkToken: string | null;
358}): Effect.Effect<
359 void,
360 CloudEnvironmentLinkError,
361 HttpClient.HttpClient | ManagedRelay.ManagedRelayClient
362> {
363 return Effect.gen(function* () {
364 const client = yield* makeEnvironmentHttpApiClient(input.target.httpBaseUrl);
365 yield* client.connect
366 .unlink({ headers: {} })
367 .pipe(Effect.mapError(environmentApiError("Could not unlink the environment from cloud.")));
368​
369 const configuredRelayUrl = relayUrl();
370 if (configuredRelayUrl && input.clerkToken) {
371 const relayClient = yield* ManagedRelay.ManagedRelayClient;
372 yield* relayClient
373 .unlinkEnvironment({
374 clerkToken: input.clerkToken,
375 environmentId: EnvironmentId.make(input.target.environmentId),
376 })
377 .pipe(
378 Effect.catch((cause) =>
379 Effect.logWarning("Could not revoke cloud environment link after local unlink.", {
380 cause,
381 }),
382 ),
383 );
384 }
385 }).pipe(Effect.provide(primaryEnvironmentHttpLayer));
387​
388// "publish_only" links the environment to the relay for agent-activity
389// publishing alone: no managed tunnel is provisioned, so it can be toggled
390// independently of T3 Connect while clients reach the environment out of band.
391export type CloudLinkMode = "managed" | "publish_only";
392​
393const PUBLISH_ONLY_PROVIDER_KIND = "manual" satisfies RelayManagedEndpointProviderKind;
394​
395export function linkPrimaryEnvironmentToCloud(input: {
396 readonly target: CloudLinkTarget;
397 readonly clerkToken: string;
398 readonly mode?: CloudLinkMode;
399}): Effect.Effect<
400 void,
401 CloudEnvironmentLinkError,
402 EnvironmentRegistry | HttpClient.HttpClient | ManagedRelay.ManagedRelayClient
403> {
404 return Effect.gen(function* () {
405 const configuredRelayUrl = relayUrl();
406 if (!configuredRelayUrl) {
407 return yield* new CloudEnvironmentLinkError({
408 message: "T3CODE_RELAY_URL is not configured.",
409 });
410 }
411 const managedTunnelsEnabled = (input.mode ?? "managed") === "managed";
412 const providerKind = managedTunnelsEnabled
413 ? MANAGED_ENDPOINT_PROVIDER_KIND
414 : PUBLISH_ONLY_PROVIDER_KIND;
415 const relayClient = yield* ManagedRelay.ManagedRelayClient;
416 const environmentClient = yield* makeEnvironmentHttpApiClient(input.target.httpBaseUrl);
417 if (managedTunnelsEnabled) {
418 yield* ensureRelayClientAvailable(EnvironmentId.make(input.target.environmentId));
419 }
420​
421 const challenge = yield* relayClient
422 .createEnvironmentLinkChallenge({
423 clerkToken: input.clerkToken,
424 payload: {
425 notificationsEnabled: true,
426 liveActivitiesEnabled: true,
427 managedTunnelsEnabled,
428 },
429 })
430 .pipe(
431 Effect.mapError(
432 decodedRelayClientError(
433 `${configuredRelayUrl}/v1/client/environment-link-challenges failed`,
434 ),
435 ),
436 );
437 const proof = yield* environmentClient.connect
438 .linkProof({
439 headers: {},
440 payload: {
441 challenge: challenge.challenge,
442 relayIssuer: configuredRelayUrl,
443 endpoint: {
444 httpBaseUrl: input.target.httpBaseUrl,
445 wsBaseUrl: input.target.wsBaseUrl,
446 providerKind,
447 },
448 origin: endpointOrigin(input.target.httpBaseUrl),
449 },
450 })
451 .pipe(Effect.mapError(environmentApiError("Could not obtain environment link proof.")));
452 const link = yield* relayClient
453 .linkEnvironment({
454 clerkToken: input.clerkToken,
455 payload: {
456 proof,
457 notificationsEnabled: true,
458 liveActivitiesEnabled: true,
459 managedTunnelsEnabled,
460 },
461 })
462 .pipe(
463 Effect.mapError(
464 decodedRelayClientError(`${configuredRelayUrl}/v1/client/environment-links failed`),
465 ),
466 );
467 yield* ensureLinkedEnvironmentMatches({
468 expectedEnvironmentId: input.target.environmentId,
469 expectedProviderKind: providerKind,
470 link,
471 });
472​
473 yield* environmentClient.connect
474 .relayConfig({
475 headers: {},
476 payload: {
477 relayUrl: configuredRelayUrl,
478 relayIssuer: link.relayIssuer,
479 cloudUserId: link.cloudUserId,
480 environmentCredential: link.environmentCredential,
481 cloudMintPublicKey: link.cloudMintPublicKey,
482 endpointRuntime: link.endpointRuntime,
483 },
484 })
485 .pipe(Effect.mapError(environmentApiError("Could not configure environment relay access.")));
486 }).pipe(Effect.provide(primaryEnvironmentHttpLayer));