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

linkEnvironment.ts

485 lines16.6 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 "RelayAgentActivityPublishProofExpiredError":
158 return "Relay rejected an expired agent activity publish proof.";
159 case "RelayAgentActivityPublishProofInvalidError":
160 return `Relay rejected the agent activity publish proof (${error.reason}).`;
161 case "RelayInternalError":
162 return `Relay encountered an internal error (${error.reason}).`;
163 }
165​
166function decodedRelayClientError(message: string) {
167 return (cause: ManagedRelay.ManagedRelayClientError) => {
168 const relayError =
169 cause._tag === "ManagedRelayRequestFailedError" ? cause.relayError : undefined;
170 const traceId = cause._tag === "ManagedRelayRequestFailedError" ? cause.traceId : undefined;
171 const detail = relayError ? relayProtectedErrorMessage(relayError) : null;
172 return new CloudEnvironmentLinkError({
173 message: detail ? `${message}: ${detail}` : message,
174 cause,
175 ...(traceId ? { traceId } : {}),
176 });
177 };
179​
180function findEnvironmentCloudApiError(cause: unknown): { readonly message: string } | null {
181 if (isEnvironmentCloudApiError(cause)) {
182 return cause;
183 }
184 if (typeof cause !== "object" || cause === null) {
185 return null;
186 }
187 return "cause" in cause ? findEnvironmentCloudApiError(cause.cause) : null;
189​
190const environmentApiError = (message: string) => (cause: unknown) => {
191 const environmentError = findEnvironmentCloudApiError(cause);
192 return new CloudEnvironmentLinkError({
193 message: environmentError
194 ? `${message.replace(/[.:]$/, "")}: ${environmentError.message}`
195 : message,
196 cause,
197 });
198};
199​
200function endpointOrigin(httpBaseUrl: string) {
201 const url = new URL(httpBaseUrl);
202 return {
203 localHttpHost: "127.0.0.1",
204 localHttpPort: Number(url.port || (url.protocol === "https:" ? 443 : 80)),
205 };
207​
208const MANAGED_ENDPOINT_PROVIDER_KIND =
209 "cloudflare_tunnel" satisfies RelayManagedEndpointProviderKind;
210​
211function ensureLinkedEnvironmentMatches(input: {
212 readonly expectedEnvironmentId: string;
213 readonly expectedProviderKind: RelayManagedEndpointProviderKind;
214 readonly link: RelayEnvironmentLinkResponse;
215}): Effect.Effect<void, CloudEnvironmentLinkError> {
216 if (input.link.environmentId !== input.expectedEnvironmentId) {
217 return new CloudEnvironmentLinkError({
218 message: "Relay returned credentials for a different environment.",
219 });
220 }
221 if (input.link.endpoint.providerKind !== input.expectedProviderKind) {
222 return new CloudEnvironmentLinkError({
223 message: "Relay returned credentials for a different endpoint provider.",
224 });
225 }
226 return Effect.void;
228​
229export interface CloudLinkTarget {
230 readonly environmentId: string;
231 readonly label: string;
232 readonly httpBaseUrl: string;
233 readonly wsBaseUrl: string;
235​
236export type CloudLinkState = EnvironmentCloudLinkStateResult;
237​
238export function collectCloudLinkTargets(input: {
239 readonly primary: CloudLinkTarget | null;
240 readonly saved: ReadonlyArray<CloudLinkTarget>;
241}): ReadonlyArray<CloudLinkTarget> {
242 const byId = new Map<string, CloudLinkTarget>();
243 if (input.primary) {
244 byId.set(input.primary.environmentId, input.primary);
245 }
246 for (const environment of input.saved) {
247 if (!byId.has(environment.environmentId)) {
248 byId.set(environment.environmentId, environment);
249 }
250 }
251 return [...byId.values()];
253​
254export function readPrimaryCloudLinkTarget(): CloudLinkTarget | null {
255 const descriptor = readPrimaryEnvironmentDescriptor();
256 const target = readPrimaryEnvironmentTarget();
257 if (!descriptor || !target) {
258 return null;
259 }
260 return {
261 environmentId: descriptor.environmentId,
262 label: descriptor.label,
263 httpBaseUrl: target.target.httpBaseUrl,
264 wsBaseUrl: target.target.wsBaseUrl,
265 };
267​
268export function listManagedCloudEnvironments(input: {
269 readonly clerkToken: string;
270}): Effect.Effect<
271 ReadonlyArray<RelayClientEnvironmentRecord>,
272 CloudEnvironmentLinkError,
273 ManagedRelay.ManagedRelayClient
274> {
275 return Effect.gen(function* () {
276 const configuredRelayUrl = relayUrl();
277 if (!configuredRelayUrl) {
278 return yield* new CloudEnvironmentLinkError({
279 message: "T3CODE_RELAY_URL is not configured.",
280 });
281 }
282 const relayClient = yield* ManagedRelay.ManagedRelayClient;
283 return yield* relayClient
284 .listEnvironments({
285 clerkToken: input.clerkToken,
286 })
287 .pipe(
288 Effect.mapError(
289 (cause) =>
290 new CloudEnvironmentLinkError({
291 message: "Could not list relay-managed environments.",
292 cause,
293 }),
294 ),
295 );
296 });
298​
299export function listCloudDevices(input: {
300 readonly clerkToken: string;
301}): Effect.Effect<
302 ReadonlyArray<RelayClientDeviceRecord>,
303 CloudEnvironmentLinkError,
304 ManagedRelay.ManagedRelayClient
305> {
306 return Effect.gen(function* () {
307 if (!relayUrl()) {
308 return yield* new CloudEnvironmentLinkError({
309 message: "T3CODE_RELAY_URL is not configured.",
310 });
311 }
312 const relayClient = yield* ManagedRelay.ManagedRelayClient;
313 return yield* relayClient.listDevices({ clerkToken: input.clerkToken }).pipe(
314 Effect.mapError(
315 (cause) =>
316 new CloudEnvironmentLinkError({
317 message: "Could not list cloud devices.",
318 cause,
319 }),
320 ),
321 );
322 });
324​
325export function readPrimaryCloudLinkState(input: {
326 readonly target: CloudLinkTarget;
327}): Effect.Effect<CloudLinkState | null, CloudEnvironmentLinkError, HttpClient.HttpClient> {
328 return Effect.gen(function* () {
329 const client = yield* makeEnvironmentHttpApiClient(input.target.httpBaseUrl);
330 return yield* client.connect
331 .linkState({ headers: {} })
332 .pipe(Effect.mapError(environmentApiError("Could not read environment cloud link state.")));
333 }).pipe(Effect.provide(primaryEnvironmentHttpLayer));
335​
336export function updatePrimaryCloudPreferences(input: {
337 readonly target: CloudLinkTarget;
338 readonly publishAgentActivity: boolean;
339}): Effect.Effect<CloudLinkState, CloudEnvironmentLinkError, HttpClient.HttpClient> {
340 return Effect.gen(function* () {
341 const client = yield* makeEnvironmentHttpApiClient(input.target.httpBaseUrl);
342 return yield* client.connect
343 .preferences({
344 headers: {},
345 payload: input,
346 })
347 .pipe(
348 Effect.mapError(environmentApiError("Could not update environment cloud preferences.")),
349 );
350 }).pipe(Effect.provide(primaryEnvironmentHttpLayer));
352​
353export function unlinkPrimaryEnvironmentFromCloud(input: {
354 readonly target: CloudLinkTarget;
355 readonly clerkToken: string | null;
356}): Effect.Effect<
357 void,
358 CloudEnvironmentLinkError,
359 HttpClient.HttpClient | ManagedRelay.ManagedRelayClient
360> {
361 return Effect.gen(function* () {
362 const client = yield* makeEnvironmentHttpApiClient(input.target.httpBaseUrl);
363 yield* client.connect
364 .unlink({ headers: {} })
365 .pipe(Effect.mapError(environmentApiError("Could not unlink the environment from cloud.")));
366​
367 const configuredRelayUrl = relayUrl();
368 if (configuredRelayUrl && input.clerkToken) {
369 const relayClient = yield* ManagedRelay.ManagedRelayClient;
370 yield* relayClient
371 .unlinkEnvironment({
372 clerkToken: input.clerkToken,
373 environmentId: EnvironmentId.make(input.target.environmentId),
374 })
375 .pipe(
376 Effect.catch((cause) =>
377 Effect.logWarning("Could not revoke cloud environment link after local unlink.", {
378 cause,
379 }),
380 ),
381 );
382 }
383 }).pipe(Effect.provide(primaryEnvironmentHttpLayer));
385​
386// "publish_only" links the environment to the relay for agent-activity
387// publishing alone: no managed tunnel is provisioned, so it can be toggled
388// independently of T3 Connect while clients reach the environment out of band.
389export type CloudLinkMode = "managed" | "publish_only";
390​
391const PUBLISH_ONLY_PROVIDER_KIND = "manual" satisfies RelayManagedEndpointProviderKind;
392​
393export function linkPrimaryEnvironmentToCloud(input: {
394 readonly target: CloudLinkTarget;
395 readonly clerkToken: string;
396 readonly mode?: CloudLinkMode;
397}): Effect.Effect<
398 void,
399 CloudEnvironmentLinkError,
400 EnvironmentRegistry | HttpClient.HttpClient | ManagedRelay.ManagedRelayClient
401> {
402 return Effect.gen(function* () {
403 const configuredRelayUrl = relayUrl();
404 if (!configuredRelayUrl) {
405 return yield* new CloudEnvironmentLinkError({
406 message: "T3CODE_RELAY_URL is not configured.",
407 });
408 }
409 const managedTunnelsEnabled = (input.mode ?? "managed") === "managed";
410 const providerKind = managedTunnelsEnabled
411 ? MANAGED_ENDPOINT_PROVIDER_KIND
412 : PUBLISH_ONLY_PROVIDER_KIND;
413 const relayClient = yield* ManagedRelay.ManagedRelayClient;
414 const environmentClient = yield* makeEnvironmentHttpApiClient(input.target.httpBaseUrl);
415 if (managedTunnelsEnabled) {
416 yield* ensureRelayClientAvailable(EnvironmentId.make(input.target.environmentId));
417 }
418​
419 const challenge = yield* relayClient
420 .createEnvironmentLinkChallenge({
421 clerkToken: input.clerkToken,
422 payload: {
423 notificationsEnabled: true,
424 liveActivitiesEnabled: true,
425 managedTunnelsEnabled,
426 },
427 })
428 .pipe(
429 Effect.mapError(
430 decodedRelayClientError(
431 `${configuredRelayUrl}/v1/client/environment-link-challenges failed`,
432 ),
433 ),
434 );
435 const proof = yield* environmentClient.connect
436 .linkProof({
437 headers: {},
438 payload: {
439 challenge: challenge.challenge,
440 relayIssuer: configuredRelayUrl,
441 endpoint: {
442 httpBaseUrl: input.target.httpBaseUrl,
443 wsBaseUrl: input.target.wsBaseUrl,
444 providerKind,
445 },
446 origin: endpointOrigin(input.target.httpBaseUrl),
447 },
448 })
449 .pipe(Effect.mapError(environmentApiError("Could not obtain environment link proof.")));
450 const link = yield* relayClient
451 .linkEnvironment({
452 clerkToken: input.clerkToken,
453 payload: {
454 proof,
455 notificationsEnabled: true,
456 liveActivitiesEnabled: true,
457 managedTunnelsEnabled,
458 },
459 })
460 .pipe(
461 Effect.mapError(
462 decodedRelayClientError(`${configuredRelayUrl}/v1/client/environment-links failed`),
463 ),
464 );
465 yield* ensureLinkedEnvironmentMatches({
466 expectedEnvironmentId: input.target.environmentId,
467 expectedProviderKind: providerKind,
468 link,
469 });
470​
471 yield* environmentClient.connect
472 .relayConfig({
473 headers: {},
474 payload: {
475 relayUrl: configuredRelayUrl,
476 relayIssuer: link.relayIssuer,
477 cloudUserId: link.cloudUserId,
478 environmentCredential: link.environmentCredential,
479 cloudMintPublicKey: link.cloudMintPublicKey,
480 endpointRuntime: link.endpointRuntime,
481 },
482 })
483 .pipe(Effect.mapError(environmentApiError("Could not configure environment relay access.")));
484 }).pipe(Effect.provide(primaryEnvironmentHttpLayer));