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