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/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, relayRequestFailureDetail } from "@t3tools/client-runtime/relay";
26
27import * as 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
51const ensureRelayClientAvailable = Effect.fn("linkEnvironment.ensureRelayClientAvailable")(
52 function* (
53 environmentId: EnvironmentId,
54 ): Effect.fn.Return<void, CloudEnvironmentLinkError, EnvironmentRegistry.EnvironmentRegistry> {
55 const registry = yield* EnvironmentRegistry.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 failed = cause._tag === "ManagedRelayRequestFailedError" ? cause : undefined;
119 const traceId = failed?.traceId;
120 const detail = failed ? relayRequestFailureDetail(failed) : null;
121 return new CloudEnvironmentLinkError({
122 message: detail ? `${message}: ${detail}` : message,
123 cause,
124 ...(traceId ? { traceId } : {}),
125 });
126 };
127}
128
129function findEnvironmentCloudApiError(cause: unknown): { readonly message: string } | null {
130 if (isEnvironmentCloudApiError(cause)) {
131 return cause;
132 }
133 if (typeof cause !== "object" || cause === null) {
134 return null;
135 }
136 return "cause" in cause ? findEnvironmentCloudApiError(cause.cause) : null;
137}
138
139const environmentApiError = (message: string) => (cause: unknown) => {
140 const environmentError = findEnvironmentCloudApiError(cause);
141 return new CloudEnvironmentLinkError({
142 message: environmentError
143 ? `${message.replace(/[.:]$/, "")}: ${environmentError.message}`
144 : message,
145 cause,
146 });
147};
148
149function endpointOrigin(httpBaseUrl: string) {
150 const url = new URL(httpBaseUrl);
151 return {
152 localHttpHost: "127.0.0.1",
153 localHttpPort: Number(url.port || (url.protocol === "https:" ? 443 : 80)),
154 };
155}
156
157const MANAGED_ENDPOINT_PROVIDER_KIND =
158 "cloudflare_tunnel" satisfies RelayManagedEndpointProviderKind;
159
160function ensureLinkedEnvironmentMatches(input: {
161 readonly expectedEnvironmentId: string;
162 readonly expectedProviderKind: RelayManagedEndpointProviderKind;
163 readonly link: RelayEnvironmentLinkResponse;
164}): Effect.Effect<void, CloudEnvironmentLinkError> {
165 if (input.link.environmentId !== input.expectedEnvironmentId) {
166 return new CloudEnvironmentLinkError({
167 message: "Relay returned credentials for a different environment.",
168 });
169 }
170 if (input.link.endpoint.providerKind !== input.expectedProviderKind) {
171 return new CloudEnvironmentLinkError({
172 message: "Relay returned credentials for a different endpoint provider.",
173 });
174 }
175 return Effect.void;
176}
177
178export interface CloudLinkTarget {
179 readonly environmentId: string;
180 readonly label: string;
181 readonly httpBaseUrl: string;
182 readonly wsBaseUrl: string;
183}
184
185export type CloudLinkState = EnvironmentCloudLinkStateResult;
186
187export const readPrimaryCloudLinkState: (input: {
188 readonly target: CloudLinkTarget;
189}) => Effect.Effect<CloudLinkState | null, CloudEnvironmentLinkError, HttpClient.HttpClient> =
190 Effect.fn("linkEnvironment.readPrimaryCloudLinkState")(function* (input: {
191 readonly target: CloudLinkTarget;
192 }) {
193 const client = yield* makeEnvironmentHttpApiClient(input.target.httpBaseUrl);
194 return yield* client.connect
195 .linkState({ headers: {} })
196 .pipe(Effect.mapError(environmentApiError("Could not read environment cloud link state.")));
197 }, Effect.provide(PrimaryEnvironmentHttpLayer.layer));
198
199export const updatePrimaryCloudPreferences: (input: {
200 readonly target: CloudLinkTarget;
201 readonly publishAgentActivity: boolean;
202 readonly holdWebhooksWhileOffline?: boolean;
203}) => Effect.Effect<CloudLinkState, CloudEnvironmentLinkError, HttpClient.HttpClient> = Effect.fn(
204 "linkEnvironment.updatePrimaryCloudPreferences",
205)(function* (input: {
206 readonly target: CloudLinkTarget;
207 readonly publishAgentActivity: boolean;
208 readonly holdWebhooksWhileOffline?: boolean;
209}) {
210 const client = yield* makeEnvironmentHttpApiClient(input.target.httpBaseUrl);
211 const { target: _target, ...payload } = input;
212 return yield* client.connect
213 .preferences({
214 headers: {},
215 payload,
216 })
217 .pipe(Effect.mapError(environmentApiError("Could not update environment cloud preferences.")));
218}, Effect.provide(PrimaryEnvironmentHttpLayer.layer));
219
220export const unlinkPrimaryEnvironmentFromCloud: (input: {
221 readonly target: CloudLinkTarget;
222 readonly clerkToken: string | null;
223}) => Effect.Effect<
224 void,
225 CloudEnvironmentLinkError,
226 HttpClient.HttpClient | ManagedRelay.ManagedRelayClient
227> = Effect.fn("linkEnvironment.unlinkPrimaryEnvironmentFromCloud")(function* (input: {
228 readonly target: CloudLinkTarget;
229 readonly clerkToken: string | null;
230}) {
231 const client = yield* makeEnvironmentHttpApiClient(input.target.httpBaseUrl);
232 yield* client.connect
233 .unlink({ headers: {} })
234 .pipe(Effect.mapError(environmentApiError("Could not unlink the environment from cloud.")));
235
236 const configuredRelayUrl = relayUrl();
237 if (configuredRelayUrl && input.clerkToken) {
238 const relayClient = yield* ManagedRelay.ManagedRelayClient;
239 yield* relayClient
240 .unlinkEnvironment({
241 clerkToken: input.clerkToken,
242 environmentId: EnvironmentId.make(input.target.environmentId),
243 })
244 .pipe(
245 Effect.catch((cause) =>
246 Effect.logWarning("Could not revoke cloud environment link after local unlink.", {
247 cause,
248 }),
249 ),
250 );
251 }
252}, Effect.provide(PrimaryEnvironmentHttpLayer.layer));
253
254export type CloudLinkMode = "managed" | "publish_only";
255
256const PUBLISH_ONLY_PROVIDER_KIND = "manual" satisfies RelayManagedEndpointProviderKind;
257
258export const linkPrimaryEnvironmentToCloud: (input: {
259 readonly target: CloudLinkTarget;
260 readonly clerkToken: string;
261 readonly mode?: CloudLinkMode;
262}) => Effect.Effect<
263 void,
264 CloudEnvironmentLinkError,
265 EnvironmentRegistry.EnvironmentRegistry | HttpClient.HttpClient | ManagedRelay.ManagedRelayClient
266> = Effect.fn("linkEnvironment.linkPrimaryEnvironmentToCloud")(function* (input: {
267 readonly target: CloudLinkTarget;
268 readonly clerkToken: string;
269 readonly mode?: CloudLinkMode;
270}) {
271 const configuredRelayUrl = relayUrl();
272 if (!configuredRelayUrl) {
273 return yield* new CloudEnvironmentLinkError({
274 message: "T3CODE_RELAY_URL is not configured.",
275 });
276 }
277 const managedTunnelsEnabled = (input.mode ?? "managed") === "managed";
278 const providerKind = managedTunnelsEnabled
279 ? MANAGED_ENDPOINT_PROVIDER_KIND
280 : PUBLISH_ONLY_PROVIDER_KIND;
281 const relayClient = yield* ManagedRelay.ManagedRelayClient;
282 const environmentClient = yield* makeEnvironmentHttpApiClient(input.target.httpBaseUrl);
283 if (managedTunnelsEnabled) {
284 yield* ensureRelayClientAvailable(EnvironmentId.make(input.target.environmentId));
285 }
286
287 const challenge = yield* relayClient
288 .createEnvironmentLinkChallenge({
289 clerkToken: input.clerkToken,
290 payload: {
291 notificationsEnabled: true,
292 liveActivitiesEnabled: true,
293 managedTunnelsEnabled,
294 },
295 })
296 .pipe(
297 Effect.mapError(
298 decodedRelayClientError(
299 `${configuredRelayUrl}/v1/client/environment-link-challenges failed`,
300 ),
301 ),
302 );
303 const proof = yield* environmentClient.connect
304 .linkProof({
305 headers: {},
306 payload: {
307 challenge: challenge.challenge,
308 relayIssuer: configuredRelayUrl,
309 endpoint: {
310 httpBaseUrl: input.target.httpBaseUrl,
311 wsBaseUrl: input.target.wsBaseUrl,
312 providerKind,
313 },
314 origin: endpointOrigin(input.target.httpBaseUrl),
315 },
316 })
317 .pipe(Effect.mapError(environmentApiError("Could not obtain environment link proof.")));
318 const link = yield* relayClient
319 .linkEnvironment({
320 clerkToken: input.clerkToken,
321 payload: {
322 proof,
323 notificationsEnabled: true,
324 liveActivitiesEnabled: true,
325 managedTunnelsEnabled,
326 },
327 })
328 .pipe(
329 Effect.mapError(
330 decodedRelayClientError(`${configuredRelayUrl}/v1/client/environment-links failed`),
331 ),
332 );
333 yield* ensureLinkedEnvironmentMatches({
334 expectedEnvironmentId: input.target.environmentId,
335 expectedProviderKind: providerKind,
336 link,
337 });
338
339 yield* environmentClient.connect
340 .relayConfig({
341 headers: {},
342 payload: {
343 relayUrl: configuredRelayUrl,
344 relayIssuer: link.relayIssuer,
345 cloudUserId: link.cloudUserId,
346 environmentCredential: link.environmentCredential,
347 cloudMintPublicKey: link.cloudMintPublicKey,
348 endpointRuntime: link.endpointRuntime,
349 },
350 })
351 .pipe(Effect.mapError(environmentApiError("Could not configure environment relay access.")));
352}, Effect.provide(PrimaryEnvironmentHttpLayer.layer));