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