Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

linkEnvironment.ts

582 lines19.6 KB

1import * as Data from "effect/Data";
2import * as Effect from "effect/Effect";
3import * as Schema from "effect/Schema";
4import { HttpClient } from "effect/unstable/http";
5import {
6 EnvironmentCloudEndpointUnavailableError,
7 EnvironmentHttpBadRequestError,
8 EnvironmentHttpConflictError,
9 EnvironmentHttpForbiddenError,
10 EnvironmentHttpInternalServerError,
11 EnvironmentHttpUnauthorizedError,
12} from "@t3tools/contracts";
13import { stripPairingTokenFromUrl } from "@t3tools/shared/remote";
14import {
15 type RelayEnvironmentConnectResponse as RelayEnvironmentConnectResponseType,
16 type RelayEnvironmentLinkResponse as RelayEnvironmentLinkResponseType,
17 RelayEnvironmentConnectScope,
18 RelayEnvironmentStatusScope,
19 RelayProtectedError,
20 type RelayDpopAccessTokenScope,
21 type RelayProtectedError as RelayProtectedErrorType,
22 type RelayClientEnvironmentRecord,
23 type RelayEnvironmentStatusResponse as RelayEnvironmentStatusResponseType,
24 type RelayManagedEndpointProviderKind,
25} from "@t3tools/contracts/relay";
26import {
27 exchangeRemoteDpopAccessToken,
28 fetchRemoteEnvironmentDescriptor,
29 makeEnvironmentHttpApiClient,
30 ManagedRelayClient,
31 ManagedRelayDpopSigner,
32} from "@t3tools/client-runtime";
33​
34import { mobileAuthClientMetadata } from "../../lib/authClientMetadata";
35import type { SavedRemoteConnection } from "../../lib/connection";
36import { loadOrCreateAgentAwarenessDeviceId, loadPreferences } from "../../lib/storage";
37import { resolveCloudPublicConfig } from "./publicConfig";
38​
39const RELAY_STATUS_AND_CONNECT_SCOPES = [
40 RelayEnvironmentStatusScope,
41 RelayEnvironmentConnectScope,
42] satisfies ReadonlyArray<RelayDpopAccessTokenScope>;
43​
44export function normalizeRelayBaseUrl(value: string | null | undefined): string | null {
45 const trimmed = value?.trim();
46 if (!trimmed) {
47 return null;
48 }
49 return trimmed.replace(/\/+$/g, "");
51​
52function readRelayUrl(): string | null {
53 return resolveCloudPublicConfig().relayUrl;
55​
56export class CloudEnvironmentLinkError extends Data.TaggedError("CloudEnvironmentLinkError")<{
57 readonly message: string;
58 readonly cause?: unknown;
59}> {}
60​
61export interface CloudEnvironmentRecordWithStatus {
62 readonly environment: RelayClientEnvironmentRecord;
63 readonly status: RelayEnvironmentStatusResponseType | null;
64 readonly statusError: string | null;
66​
67const isRelayProtectedError = Schema.is(RelayProtectedError);
68const isEnvironmentCloudApiError = Schema.is(
69 Schema.Union([
70 EnvironmentHttpBadRequestError,
71 EnvironmentHttpUnauthorizedError,
72 EnvironmentHttpForbiddenError,
73 EnvironmentHttpConflictError,
74 EnvironmentHttpInternalServerError,
75 EnvironmentCloudEndpointUnavailableError,
76 ]),
77);
78​
79const MANAGED_ENDPOINT_PROVIDER_KIND =
80 "cloudflare_tunnel" satisfies RelayManagedEndpointProviderKind;
81​
82function cloudEnvironmentLinkError(message: string) {
83 return (cause: unknown) => {
84 const environmentError = findEnvironmentCloudApiError(cause);
85 return new CloudEnvironmentLinkError({
86 message: environmentError
87 ? `${message.replace(/[.:]$/, "")}: ${environmentError.message}`
88 : withDevCause(message, cause),
89 cause,
90 });
91 };
93​
94function isDevRuntime(): boolean {
95 return typeof __DEV__ !== "undefined" && __DEV__;
97​
98function causeMessage(cause: unknown): string | null {
99 if (cause instanceof Error && cause.message) {
100 return cause.message;
101 }
102 if (typeof cause === "object" && cause !== null) {
103 const record = cause as { readonly message?: unknown; readonly cause?: unknown };
104 if (typeof record.message === "string" && record.message.length > 0) {
105 const nested = causeMessage(record.cause);
106 return nested ? `${record.message}: ${nested}` : record.message;
107 }
108 }
109 return null;
111​
112function withDevCause(message: string, cause: unknown): string {
113 if (!isDevRuntime()) {
114 return message;
115 }
116 const detail = causeMessage(cause);
117 return detail ? `${message} (${detail})` : message;
119​
120function relayProtectedErrorMessage(error: RelayProtectedErrorType): string {
121 switch (error._tag) {
122 case "RelayAuthInvalidError":
123 switch (error.reason) {
124 case "missing_bearer":
125 case "invalid_bearer":
126 return "Relay rejected the cloud session token.";
127 case "invalid_dpop":
128 return "Relay rejected the DPoP proof.";
129 case "not_authorized":
130 return "Relay rejected the authenticated request.";
131 }
132 case "RelayEnvironmentLinkProofExpiredError":
133 return "Relay rejected an expired environment link proof.";
134 case "RelayEnvironmentLinkProofInvalidError":
135 return `Relay rejected the environment link proof (${error.reason}).`;
136 case "RelayEnvironmentConnectNotAuthorizedError":
137 return "Relay rejected the environment connection request.";
138 case "RelayEnvironmentEndpointUnavailableError":
139 return `Relay could not reach the environment endpoint (${error.reason}).`;
140 case "RelayEnvironmentEndpointTimedOutError":
141 return "Relay timed out while contacting the environment endpoint.";
142 case "RelayEnvironmentLinkFailedError":
143 return `Relay could not link the environment (${error.reason}).`;
144 case "RelayEnvironmentLinkUnavailableError":
145 return `Relay cannot provision the managed endpoint (${error.reason}).`;
146 case "RelayAgentActivityPublishProofExpiredError":
147 return "Relay rejected an expired agent activity publish proof.";
148 case "RelayAgentActivityPublishProofInvalidError":
149 return `Relay rejected the agent activity publish proof (${error.reason}).`;
150 case "RelayInternalError":
151 return `Relay encountered an internal error (${error.reason}, trace ${error.traceId}).`;
152 }
154​
155function decodedRelayClientError(message: string) {
156 return (cause: unknown) => {
157 const relayError = findRelayProtectedError(cause);
158 const detail = relayError ? relayProtectedErrorMessage(relayError) : null;
159 return new CloudEnvironmentLinkError({
160 message: detail ? `${message}: ${detail}` : message,
161 cause,
162 });
163 };
165​
166function findRelayProtectedError(cause: unknown): RelayProtectedErrorType | null {
167 if (isRelayProtectedError(cause)) {
168 return cause;
169 }
170 if (typeof cause !== "object" || cause === null) {
171 return null;
172 }
173 return "cause" in cause ? findRelayProtectedError(cause.cause) : null;
175​
176function findEnvironmentCloudApiError(cause: unknown): { readonly message: string } | null {
177 if (isEnvironmentCloudApiError(cause)) {
178 return cause;
179 }
180 if (typeof cause !== "object" || cause === null) {
181 return null;
182 }
183 return "cause" in cause ? findEnvironmentCloudApiError(cause.cause) : null;
185​
186function requireRelayUrl(): Effect.Effect<string, CloudEnvironmentLinkError> {
187 const relayUrl = readRelayUrl();
188 return relayUrl
189 ? Effect.succeed(relayUrl)
190 : Effect.fail(new CloudEnvironmentLinkError({ message: "Relay URL is not configured." }));
192​
193function endpointOrigin(httpBaseUrl: string) {
194 const url = new URL(httpBaseUrl);
195 return {
196 localHttpHost: "127.0.0.1",
197 localHttpPort: Number(url.port || (url.protocol === "https:" ? 443 : 80)),
198 };
200​
201function ensureLinkedEnvironmentMatches(input: {
202 readonly expectedEnvironmentId: string;
203 readonly expectedProviderKind: RelayManagedEndpointProviderKind;
204 readonly link: RelayEnvironmentLinkResponseType;
205}): Effect.Effect<void, CloudEnvironmentLinkError> {
206 if (input.link.environmentId !== input.expectedEnvironmentId) {
207 return new CloudEnvironmentLinkError({
208 message: "Relay returned credentials for a different environment.",
209 });
210 }
211 if (input.link.endpoint.providerKind !== input.expectedProviderKind) {
212 return new CloudEnvironmentLinkError({
213 message: "Relay returned credentials for a different endpoint provider.",
214 });
215 }
216 return Effect.void;
218​
219function endpointMatches(
220 left: RelayClientEnvironmentRecord["endpoint"],
221 right: RelayClientEnvironmentRecord["endpoint"],
222): boolean {
223 return (
224 left.httpBaseUrl === right.httpBaseUrl &&
225 left.wsBaseUrl === right.wsBaseUrl &&
226 left.providerKind === right.providerKind
227 );
229​
230function ensureStatusMatchesEnvironment(input: {
231 readonly environment: RelayClientEnvironmentRecord;
232 readonly status: RelayEnvironmentStatusResponseType;
233}): Effect.Effect<void, CloudEnvironmentLinkError> {
234 if (input.status.environmentId !== input.environment.environmentId) {
235 return new CloudEnvironmentLinkError({
236 message: "Relay returned status for a different environment.",
237 });
238 }
239 if (!endpointMatches(input.status.endpoint, input.environment.endpoint)) {
240 return new CloudEnvironmentLinkError({
241 message: "Relay returned status for a different endpoint.",
242 });
243 }
244 if (
245 input.status.descriptor &&
246 input.status.descriptor.environmentId !== input.environment.environmentId
247 ) {
248 return new CloudEnvironmentLinkError({
249 message: "Relay returned status descriptor for a different environment.",
250 });
251 }
252 return Effect.void;
254​
255function ensureConnectEndpointMatchesEnvironment(input: {
256 readonly environment: RelayClientEnvironmentRecord;
257 readonly connect: RelayEnvironmentConnectResponseType;
258}): Effect.Effect<void, CloudEnvironmentLinkError> {
259 if (!endpointMatches(input.connect.endpoint, input.environment.endpoint)) {
260 return new CloudEnvironmentLinkError({
261 message: "Relay returned credentials for a different endpoint.",
262 });
263 }
264 return Effect.void;
266​
267export function linkEnvironmentToCloud(input: {
268 readonly connection: SavedRemoteConnection;
269 readonly clerkToken: string;
270}): Effect.Effect<void, CloudEnvironmentLinkError, HttpClient.HttpClient | ManagedRelayClient> {
271 return Effect.gen(function* () {
272 if (!input.connection.bearerToken) {
273 return yield* new CloudEnvironmentLinkError({
274 message: "Only a locally paired bearer connection can be linked to the cloud.",
275 });
276 }
277 const localBearerToken = input.connection.bearerToken;
278 const relayUrl = yield* requireRelayUrl();
279 const relayClient = yield* ManagedRelayClient;
280 const deviceId = yield* Effect.tryPromise({
281 try: () => loadOrCreateAgentAwarenessDeviceId(),
282 catch: cloudEnvironmentLinkError("Could not load the mobile device id."),
283 });
284 const preferences = yield* Effect.tryPromise({
285 try: () => loadPreferences(),
286 catch: cloudEnvironmentLinkError("Could not load mobile notification preferences."),
287 });
288 const liveActivitiesEnabled = preferences.liveActivitiesEnabled !== false;
289 const challenge = yield* relayClient
290 .createEnvironmentLinkChallenge({
291 clerkToken: input.clerkToken,
292 payload: {
293 notificationsEnabled: true,
294 liveActivitiesEnabled,
295 managedTunnelsEnabled: true,
296 },
297 })
298 .pipe(
299 Effect.mapError(
300 decodedRelayClientError(`${relayUrl}/v1/client/environment-link-challenges failed`),
301 ),
302 );
303 const environmentClient = yield* makeEnvironmentHttpApiClient(input.connection.httpBaseUrl);
304 const proof = yield* environmentClient.cloud
305 .linkProof({
306 headers: { authorization: `Bearer ${localBearerToken}` },
307 payload: {
308 challenge: challenge.challenge,
309 relayIssuer: relayUrl,
310 endpoint: {
311 httpBaseUrl: input.connection.httpBaseUrl,
312 wsBaseUrl: input.connection.wsBaseUrl,
313 providerKind: MANAGED_ENDPOINT_PROVIDER_KIND,
314 },
315 origin: endpointOrigin(input.connection.httpBaseUrl),
316 },
317 })
318 .pipe(Effect.mapError(cloudEnvironmentLinkError("Could not obtain environment link proof.")));
319 const link = yield* relayClient
320 .linkEnvironment({
321 clerkToken: input.clerkToken,
322 payload: {
323 deviceId,
324 proof,
325 notificationsEnabled: true,
326 liveActivitiesEnabled,
327 managedTunnelsEnabled: true,
328 },
329 })
330 .pipe(
331 Effect.mapError(decodedRelayClientError(`${relayUrl}/v1/client/environment-links failed`)),
332 );
333 yield* ensureLinkedEnvironmentMatches({
334 expectedEnvironmentId: input.connection.environmentId,
335 expectedProviderKind: MANAGED_ENDPOINT_PROVIDER_KIND,
336 link,
337 });
338​
339 yield* environmentClient.cloud
340 .relayConfig({
341 headers: { authorization: `Bearer ${localBearerToken}` },
342 payload: {
343 relayUrl,
344 relayIssuer: link.relayIssuer,
345 cloudUserId: link.cloudUserId,
346 environmentCredential: link.environmentCredential,
347 cloudMintPublicKey: link.cloudMintPublicKey,
348 endpointRuntime: link.endpointRuntime,
349 },
350 })
351 .pipe(
352 Effect.mapError(cloudEnvironmentLinkError("Could not configure environment relay access.")),
353 );
354 });
356​
357export function listCloudEnvironments(input: {
358 readonly clerkToken: string;
359}): Effect.Effect<
360 ReadonlyArray<RelayClientEnvironmentRecord>,
361 CloudEnvironmentLinkError,
362 ManagedRelayClient
363> {
364 return Effect.gen(function* () {
365 const relayUrl = yield* requireRelayUrl();
366 const relayClient = yield* ManagedRelayClient;
367​
368 return yield* relayClient
369 .listEnvironments({
370 clerkToken: input.clerkToken,
371 })
372 .pipe(Effect.mapError(decodedRelayClientError(`${relayUrl}/v1/environments failed`)));
373 });
375​
376export function getCloudEnvironmentStatus(input: {
377 readonly clerkToken: string;
378 readonly environment: RelayClientEnvironmentRecord;
379 readonly relayScopes?: ReadonlyArray<RelayDpopAccessTokenScope>;
380}): Effect.Effect<
381 RelayEnvironmentStatusResponseType,
382 CloudEnvironmentLinkError,
383 ManagedRelayClient
384> {
385 return Effect.gen(function* () {
386 const relayUrl = yield* requireRelayUrl();
387 const relayClient = yield* ManagedRelayClient;
388 const status = yield* relayClient
389 .getEnvironmentStatus({
390 clerkToken: input.clerkToken,
391 scopes: input.relayScopes ?? [RelayEnvironmentStatusScope],
392 environmentId: input.environment.environmentId,
393 })
394 .pipe(
395 Effect.mapError(
396 decodedRelayClientError(
397 `${relayUrl}/v1/environments/${encodeURIComponent(input.environment.environmentId)}/status failed`,
398 ),
399 ),
400 );
401 yield* ensureStatusMatchesEnvironment({ environment: input.environment, status });
402 return status;
403 });
405​
406export function cloudEnvironmentsPendingStatus(
407 environments: ReadonlyArray<RelayClientEnvironmentRecord>,
408): ReadonlyArray<CloudEnvironmentRecordWithStatus> {
409 return environments.map((environment) => ({
410 environment,
411 status: null,
412 statusError: "Checking status...",
413 }));
415​
416export function loadCloudEnvironmentStatuses(input: {
417 readonly clerkToken: string;
418 readonly environments: ReadonlyArray<RelayClientEnvironmentRecord>;
419}): Effect.Effect<
420 ReadonlyArray<CloudEnvironmentRecordWithStatus>,
421 CloudEnvironmentLinkError,
422 ManagedRelayClient
423> {
424 return Effect.forEach(
425 input.environments,
426 (environment) =>
427 getCloudEnvironmentStatus({
428 clerkToken: input.clerkToken,
429 environment,
430 relayScopes: RELAY_STATUS_AND_CONNECT_SCOPES,
431 }).pipe(
432 Effect.match({
433 onFailure: (error) => ({
434 environment,
435 status: null,
436 statusError: error.message,
437 }),
438 onSuccess: (status) => ({
439 environment,
440 status,
441 statusError: null,
442 }),
443 }),
444 ),
445 { concurrency: "unbounded" },
446 );
448​
449export function listCloudEnvironmentsWithStatus(input: {
450 readonly clerkToken: string;
451}): Effect.Effect<
452 ReadonlyArray<CloudEnvironmentRecordWithStatus>,
453 CloudEnvironmentLinkError,
454 ManagedRelayClient
455> {
456 return Effect.gen(function* () {
457 const environments = yield* listCloudEnvironments(input);
458 return yield* loadCloudEnvironmentStatuses({
459 clerkToken: input.clerkToken,
460 environments,
461 });
462 });
464​
465function connectRelayManagedEnvironment(input: {
466 readonly clerkToken: string;
467 readonly environmentId: RelayClientEnvironmentRecord["environmentId"];
468 readonly expectedEnvironment?: RelayClientEnvironmentRecord;
469}): Effect.Effect<
470 SavedRemoteConnection,
471 CloudEnvironmentLinkError,
472 HttpClient.HttpClient | ManagedRelayClient | ManagedRelayDpopSigner
473> {
474 return Effect.gen(function* () {
475 const relayUrl = yield* requireRelayUrl();
476 const relayClient = yield* ManagedRelayClient;
477​
478 const deviceId = yield* Effect.tryPromise({
479 try: () => loadOrCreateAgentAwarenessDeviceId(),
480 catch: cloudEnvironmentLinkError("Could not load the mobile device id."),
481 });
482 const connect = yield* relayClient
483 .connectEnvironment({
484 clerkToken: input.clerkToken,
485 scopes: [RelayEnvironmentConnectScope],
486 environmentId: input.environmentId,
487 deviceId,
488 })
489 .pipe(
490 Effect.mapError(
491 decodedRelayClientError(
492 `${relayUrl}/v1/environments/${encodeURIComponent(input.environmentId)}/connect failed`,
493 ),
494 ),
495 );
496 if (connect.environmentId !== input.environmentId) {
497 return yield* new CloudEnvironmentLinkError({
498 message: "Relay returned credentials for a different environment.",
499 });
500 }
501 if (input.expectedEnvironment) {
502 yield* ensureConnectEndpointMatchesEnvironment({
503 environment: input.expectedEnvironment,
504 connect,
505 });
506 }
507​
508 const descriptor = yield* fetchRemoteEnvironmentDescriptor({
509 httpBaseUrl: connect.endpoint.httpBaseUrl,
510 }).pipe(
511 Effect.mapError(
512 cloudEnvironmentLinkError("Could not fetch the connected environment descriptor."),
513 ),
514 );
515 if (descriptor.environmentId !== connect.environmentId) {
516 return yield* new CloudEnvironmentLinkError({
517 message: "Connected endpoint descriptor does not match the selected environment.",
518 });
519 }
520 const signer = yield* ManagedRelayDpopSigner;
521 const bootstrapDpop = yield* signer
522 .createProof({
523 method: "POST",
524 url: new URL("/oauth/token", connect.endpoint.httpBaseUrl).toString(),
525 })
526 .pipe(Effect.mapError(cloudEnvironmentLinkError("Could not create bootstrap DPoP proof.")));
527 const bootstrap = yield* exchangeRemoteDpopAccessToken({
528 httpBaseUrl: connect.endpoint.httpBaseUrl,
529 credential: connect.credential,
530 dpopProof: bootstrapDpop,
531 clientMetadata: mobileAuthClientMetadata(),
532 }).pipe(
533 Effect.mapError(
534 cloudEnvironmentLinkError("Could not exchange a managed endpoint DPoP access token."),
535 ),
536 );
537 const pairingUrl = new URL(connect.endpoint.httpBaseUrl);
538 pairingUrl.hash = new URLSearchParams([["token", connect.credential]]).toString();
539​
540 return {
541 environmentId: descriptor.environmentId,
542 environmentLabel: descriptor.label,
543 pairingUrl: stripPairingTokenFromUrl(pairingUrl).toString(),
544 displayUrl: connect.endpoint.httpBaseUrl,
545 httpBaseUrl: connect.endpoint.httpBaseUrl,
546 wsBaseUrl: connect.endpoint.wsBaseUrl,
547 bearerToken: null,
548 authenticationMethod: "dpop",
549 dpopAccessToken: bootstrap.access_token,
550 relayManaged: true,
551 };
552 });
554​
555export function connectCloudEnvironment(input: {
556 readonly clerkToken: string;
557 readonly environment: RelayClientEnvironmentRecord;
558}): Effect.Effect<
559 SavedRemoteConnection,
560 CloudEnvironmentLinkError,
561 HttpClient.HttpClient | ManagedRelayClient | ManagedRelayDpopSigner
562> {
563 return connectRelayManagedEnvironment({
564 clerkToken: input.clerkToken,
565 environmentId: input.environment.environmentId,
566 expectedEnvironment: input.environment,
567 });
569​
570export function refreshCloudEnvironmentConnection(input: {
571 readonly clerkToken: string;
572 readonly connection: SavedRemoteConnection;
573}): Effect.Effect<
574 SavedRemoteConnection,
575 CloudEnvironmentLinkError,
576 HttpClient.HttpClient | ManagedRelayClient | ManagedRelayDpopSigner
577> {
578 return connectRelayManagedEnvironment({
579 clerkToken: input.clerkToken,
580 environmentId: input.connection.environmentId,
581 });