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