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

linkEnvironment.ts

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