Open History to see the last commit
1import * as Effect from "effect/Effect";
2import * as Option from "effect/Option";
3import * as SubscriptionRef from "effect/SubscriptionRef";
4import * as Schema from "effect/Schema";
5import type { HttpClientResponse } from "effect/http";
6import {
7 EnvironmentCloudEndpointUnavailableError,
8 EnvironmentHttpBadRequestError,
9 EnvironmentHttpConflictError,
10 EnvironmentHttpForbiddenError,
11 EnvironmentHttpInternalServerError,
12 EnvironmentHttpUnauthorizedError,
13} from "@t3tools/contracts";
14import {
15 RelayOkResponse,
16 type RelayEnvironmentLinkResponse as RelayEnvironmentLinkResponseType,
17 type RelayManagedEndpointProviderKind,
18} from "@t3tools/contracts/relay";
19import { EnvironmentSupervisor } from "@t3tools/client-runtime/connection";
20import { findErrorTraceId } from "@t3tools/client-runtime/errors";
21import { ManagedRelay, relayRequestFailureDetail } from "@t3tools/client-runtime/relay";
22
23import { executeConnectedEnvironmentHttpRequest } from "@t3tools/client-runtime/state/environmentHttpAuth";
24import { msg } from "gt-react-native";
25
26import { m } from "../../i18n/messages";
27import * as MobileStorage from "../../persistence/mobile-storage";
28import { resolveCloudPublicConfig } from "./publicConfig";
29
30function readRelayUrl(): string | null {
31 return resolveCloudPublicConfig().relay.url;
32}
33
34export class CloudEnvironmentLinkError extends Schema.TaggedError<CloudEnvironmentLinkError>()(
35 "CloudEnvironmentLinkError",
36 {
37 message: Schema.String,
38 cause: Schema.optional(Schema.Defect()),
39 traceId: Schema.optional(Schema.String),
40 relayLinkCommitted: Schema.optionalKey(Schema.Literal(true)),
41 },
42) {}
43
44const isEnvironmentCloudApiError = Schema.is(
45 Schema.Union([
46 EnvironmentHttpBadRequestError,
47 EnvironmentHttpUnauthorizedError,
48 EnvironmentHttpForbiddenError,
49 EnvironmentHttpConflictError,
50 EnvironmentHttpInternalServerError,
51 EnvironmentCloudEndpointUnavailableError,
52 ]),
53);
54
55// Live Activities need only agent activity, so a phone never starts a tunnel on the host.
56const PUBLISH_ONLY_PROVIDER_KIND = "manual" satisfies RelayManagedEndpointProviderKind;
57
58function cloudEnvironmentLinkError(
59 message: string,
60 withDetail: (detail: string) => string,
61 options?: { readonly relayLinkCommitted: true },
62) {
63 return (cause: unknown) => {
64 const environmentError = findEnvironmentCloudApiError(cause);
65 const traceId = findErrorTraceId(cause);
66 const detail = environmentError
67 ? withDetail(environmentError.message)
68 : withDevCause(message, cause);
69 return new CloudEnvironmentLinkError({
70 message: detail,
71 cause,
72 ...options,
73 ...(traceId === null ? {} : { traceId }),
74 });
75 };
76}
77
78function isDevRuntime(): boolean {
79 return typeof __DEV__ !== "undefined" && __DEV__;
80}
81
82function causeMessage(cause: unknown): string | null {
83 if (cause instanceof Error && cause.message) {
84 return cause.message;
85 }
86 if (typeof cause === "object" && cause !== null) {
87 const record = cause as { readonly message?: unknown; readonly cause?: unknown };
88 if (typeof record.message === "string" && record.message.length > 0) {
89 const nested = causeMessage(record.cause);
90 return nested ? `${record.message}: ${nested}` : record.message;
91 }
92 }
93 return null;
94}
95
96function withDevCause(message: string, cause: unknown): string {
97 if (!isDevRuntime()) {
98 return message;
99 }
100 const detail = causeMessage(cause);
101 return detail ? `${message} (${detail})` : message;
102}
103
104function decodedRelayClientError(url: string) {
105 return (cause: ManagedRelay.ManagedRelayClientError) => {
106 const failed = cause._tag === "ManagedRelayRequestFailedError" ? cause : undefined;
107 const traceId = failed?.traceId;
108 const detail = failed ? relayRequestFailureDetail(failed, m) : null;
109 return new CloudEnvironmentLinkError({
110 message: detail ? m(msg`${{ url }} failed: ${{ detail }}`) : m(msg`${{ url }} failed`),
111 cause,
112 ...(traceId ? { traceId } : {}),
113 });
114 };
115}
116
117function findEnvironmentCloudApiError(cause: unknown): { readonly message: string } | null {
118 if (isEnvironmentCloudApiError(cause)) {
119 return cause;
120 }
121 if (typeof cause !== "object" || cause === null) {
122 return null;
123 }
124 return "cause" in cause ? findEnvironmentCloudApiError(cause.cause) : null;
125}
126
127function requireRelayUrl(): Effect.Effect<string, CloudEnvironmentLinkError> {
128 const relayUrl = readRelayUrl();
129 return relayUrl
130 ? Effect.succeed(relayUrl)
131 : Effect.fail(
132 new CloudEnvironmentLinkError({ message: m(msg("Relay URL is not configured.")) }),
133 );
134}
135
136function endpointOrigin(httpBaseUrl: string) {
137 const url = new URL(httpBaseUrl);
138 return {
139 localHttpHost: "127.0.0.1",
140 localHttpPort: Number(url.port || (url.protocol === "https:" ? 443 : 80)),
141 };
142}
143
144function ensureLinkedEnvironmentMatches(input: {
145 readonly expectedEnvironmentId: string;
146 readonly expectedProviderKind: RelayManagedEndpointProviderKind;
147 readonly link: RelayEnvironmentLinkResponseType;
148}): Effect.Effect<void, CloudEnvironmentLinkError> {
149 if (input.link.environmentId !== input.expectedEnvironmentId) {
150 return new CloudEnvironmentLinkError({
151 message: m(msg("Relay returned credentials for a different environment.")),
152 });
153 }
154 if (input.link.endpoint.providerKind !== input.expectedProviderKind) {
155 return new CloudEnvironmentLinkError({
156 message: m(msg("Relay returned credentials for a different endpoint provider.")),
157 });
158 }
159 return Effect.void;
160}
161
162const decodeRelayOkResponse = Schema.decodeUnknownEffect(RelayOkResponse);
163
164export const updateLinkedEnvironmentLiveActivityPreference = Effect.fn(
165 "linkEnvironment.updateLinkedEnvironmentLiveActivityPreference",
166)(function* (liveActivitiesEnabled: boolean) {
167 const supervisor = yield* EnvironmentSupervisor.EnvironmentSupervisor;
168 if (Option.isNone(yield* SubscriptionRef.get(supervisor.prepared))) {
169 return "disconnected" as const;
170 }
171
172 return yield* executeConnectedEnvironmentHttpRequest<
173 "connect",
174 HttpClientResponse.HttpClientResponse,
175 unknown,
176 never
177 >({
178 group: "connect",
179 method: "POST",
180 url: (urls) => urls.liveActivityPreference(),
181 timeoutMs: 8_000,
182 requestInit: { redirect: "error" },
183 isUnauthorizedResponse: (response) => response.status === 401,
184 request: ({ client, headers }) =>
185 client.liveActivityPreference({
186 headers,
187 payload: { liveActivitiesEnabled },
188 responseMode: "response-only",
189 }),
190 }).pipe(
191 Effect.flatMap((response) =>
192 Effect.gen(function* () {
193 if (response.status === 404) return "unsupported" as const;
194 if (response.status === 200) {
195 const json = yield* response.json;
196 const result = yield* decodeRelayOkResponse(json);
197 return result.ok ? ("updated" as const) : ("unlinked" as const);
198 }
199 return yield* new CloudEnvironmentLinkError({
200 message: m(msg`Environment returned HTTP ${{ status: response.status }}.`),
201 });
202 }),
203 ),
204 Effect.mapError(
205 cloudEnvironmentLinkError(
206 m(msg("Could not update the environment's Live Activity preference.")),
207 (detail) =>
208 m(msg`Could not update the environment's Live Activity preference: ${{ detail }}`),
209 ),
210 ),
211 );
212});
213
214// Linking can install the relay client and start a managed tunnel before it answers.
215const CLOUD_LINK_REQUEST_TIMEOUT_MS = 60_000;
216
217/** Links the supervised environment, signing its requests with this device's own credential. */
218export const linkEnvironmentToCloudWithPreference = Effect.fn(
219 "linkEnvironment.linkEnvironmentToCloudWithPreference",
220)(function* (input: { readonly clerkToken: string; readonly liveActivitiesEnabled: boolean }) {
221 const supervisor = yield* EnvironmentSupervisor.EnvironmentSupervisor;
222 const prepared = yield* SubscriptionRef.get(supervisor.prepared);
223 if (Option.isNone(prepared)) {
224 return yield* new CloudEnvironmentLinkError({
225 message: m(msg("The environment is not connected.")),
226 });
227 }
228 const { environmentId, httpBaseUrl, target } = prepared.value;
229 const wsBaseUrl =
230 target._tag === "PrimaryConnectionTarget"
231 ? target.wsBaseUrl
232 : httpBaseUrl.replace(/^http/, "ws");
233 const relayUrl = yield* requireRelayUrl();
234 // Publishing is a host-local setting, so enable it before committing a link a retry would skip.
235 yield* executeConnectedEnvironmentHttpRequest({
236 group: "connect",
237 method: "POST",
238 url: (urls) => urls.preferences(),
239 timeoutMs: CLOUD_LINK_REQUEST_TIMEOUT_MS,
240 request: ({ client, headers }) =>
241 client.preferences({ headers, payload: { publishAgentActivity: true } }),
242 }).pipe(
243 Effect.mapError(
244 cloudEnvironmentLinkError(m(msg("Could not turn on agent activity publishing.")), (detail) =>
245 m(msg`Could not turn on agent activity publishing: ${{ detail }}`),
246 ),
247 ),
248 );
249 const relayClient = yield* ManagedRelay.ManagedRelayClient;
250 const storage = yield* MobileStorage.MobileStorage;
251 const deviceId = yield* storage.loadOrCreateAgentAwarenessDeviceId.pipe(
252 Effect.mapError(
253 cloudEnvironmentLinkError(m(msg("Could not load the mobile device id.")), (detail) =>
254 m(msg`Could not load the mobile device id: ${{ detail }}`),
255 ),
256 ),
257 );
258 const liveActivitiesEnabled = input.liveActivitiesEnabled;
259 const challenge = yield* relayClient
260 .createEnvironmentLinkChallenge({
261 clerkToken: input.clerkToken,
262 payload: {
263 notificationsEnabled: true,
264 liveActivitiesEnabled,
265 managedTunnelsEnabled: false,
266 },
267 })
268 .pipe(
269 Effect.mapError(
270 decodedRelayClientError(`${relayUrl}/v1/client/environment-link-challenges failed`),
271 ),
272 );
273 const proof = yield* executeConnectedEnvironmentHttpRequest({
274 group: "connect",
275 method: "POST",
276 url: (urls) => urls.linkProof(),
277 timeoutMs: CLOUD_LINK_REQUEST_TIMEOUT_MS,
278 request: ({ client, headers }) =>
279 client.linkProof({
280 headers,
281 payload: {
282 challenge: challenge.challenge,
283 relayIssuer: relayUrl,
284 endpoint: { httpBaseUrl, wsBaseUrl, providerKind: PUBLISH_ONLY_PROVIDER_KIND },
285 origin: endpointOrigin(httpBaseUrl),
286 },
287 }),
288 }).pipe(
289 Effect.mapError(
290 cloudEnvironmentLinkError(m(msg("Could not obtain environment link proof.")), (detail) =>
291 m(msg`Could not obtain environment link proof: ${{ detail }}`),
292 ),
293 ),
294 );
295 const link = yield* relayClient
296 .linkEnvironment({
297 clerkToken: input.clerkToken,
298 payload: {
299 deviceId,
300 proof,
301 notificationsEnabled: true,
302 liveActivitiesEnabled,
303 managedTunnelsEnabled: false,
304 },
305 })
306 .pipe(
307 Effect.mapError(decodedRelayClientError(`${relayUrl}/v1/client/environment-links failed`)),
308 );
309 yield* ensureLinkedEnvironmentMatches({
310 expectedEnvironmentId: environmentId,
311 expectedProviderKind: PUBLISH_ONLY_PROVIDER_KIND,
312 link,
313 });
314
315 yield* executeConnectedEnvironmentHttpRequest({
316 group: "connect",
317 method: "POST",
318 url: (urls) => urls.relayConfig(),
319 timeoutMs: CLOUD_LINK_REQUEST_TIMEOUT_MS,
320 request: ({ client, headers }) =>
321 client.relayConfig({
322 headers,
323 payload: {
324 relayUrl,
325 relayIssuer: link.relayIssuer,
326 cloudUserId: link.cloudUserId,
327 environmentCredential: link.environmentCredential,
328 cloudMintPublicKey: link.cloudMintPublicKey,
329 endpointRuntime: link.endpointRuntime,
330 },
331 }),
332 }).pipe(
333 Effect.mapError(
334 cloudEnvironmentLinkError(
335 m(msg("Could not configure environment relay access.")),
336 (detail) => m(msg`Could not configure environment relay access: ${{ detail }}`),
337 { relayLinkCommitted: true },
338 ),
339 ),
340 );
341});