Open History to see the last commit
1import {
2 ClientPresentation,
3 CloudSession,
4 EnvironmentOwnedDataCleanup,
5 PlatformConnectionSource,
6 PrimaryEnvironmentAuth,
7 RelayDeviceIdentity,
8 SshEnvironmentGateway,
9} from "@t3tools/client-runtime/platform";
10import {
11 BearerConnectionCredential,
12 BearerConnectionProfile,
13 BearerConnectionRegistration,
14 BearerConnectionTarget,
15 ConnectionBlockedError,
16 ConnectionTransientError,
17 Connectivity,
18 mapRemoteEnvironmentError,
19 type PlatformConnectionRegistration,
20 PrimaryConnectionRegistration,
21 PrimaryConnectionTarget,
22 Wakeups,
23} from "@t3tools/client-runtime/connection";
24import { bootstrapRemoteBearerSession } from "@t3tools/client-runtime/authorization";
25import { fetchRemoteEnvironmentDescriptor } from "@t3tools/client-runtime/environment";
26import { managedRelayAccountChanges, managedRelaySessionAtom } from "@t3tools/client-runtime/relay";
27import { EnvironmentRpcRequestObserver } from "@t3tools/client-runtime/rpc";
28import {
29 AuthStandardClientScopes,
30 type DesktopBridge,
31 type DesktopEnvironmentBootstrap,
32 type DesktopSshEnvironmentTarget,
33 PRIMARY_LOCAL_ENVIRONMENT_ID,
34} from "@t3tools/contracts";
35import * as Clock from "effect/Clock";
36import * as Context from "effect/Context";
37import * as Effect from "effect/Effect";
38import * as Layer from "effect/Layer";
39import * as Option from "effect/Option";
40import * as Queue from "effect/Queue";
41import * as Ref from "effect/Ref";
42import * as Stream from "effect/Stream";
43import { FetchHttpClient } from "effect/unstable/http";
44
45import { APP_VERSION } from "../branding";
46import { readDesktopPrimaryBearerToken } from "../environments/primary/desktopAuth";
47import { primaryEnvironmentHttpLayer } from "../environments/primary/httpLayer";
48import {
49 readPrimaryEnvironmentTarget,
50 type PrimaryEnvironmentTarget,
51} from "../environments/primary/target";
52import { clearComposerDraftsEnvironment } from "../composerDraftStore";
53import { isHostedStaticApp } from "../hostedPairing";
54import { appAtomRegistry } from "../rpc/atomRegistry";
55import { acknowledgeRpcRequest, trackRpcRequestSent } from "../rpc/requestLatencyState";
56import {
57 desktopLocalConnectionId,
58 readDesktopSecondaryBootstrapsResult,
59 type DesktopSecondaryBootstrapsRead,
60} from "./desktopLocal";
61import { connectionStorageLayer } from "./storage";
62import { clientPresentationMetadata } from "./clientMetadata";
63
64let nextObservedRpcRequestId = 0;
65
66function currentNetworkStatus(): "unknown" | "offline" | "online" {
67 if (typeof navigator === "undefined") {
68 return "unknown";
69 }
70 return navigator.onLine ? "online" : "offline";
71}
72
73const connectivityLayer = Connectivity.layer({
74 status: Effect.sync(currentNetworkStatus),
75 changes: Stream.callback((queue) =>
76 Effect.acquireRelease(
77 Effect.sync(() => {
78 const online = () => Queue.offerUnsafe(queue, "online");
79 const offline = () => Queue.offerUnsafe(queue, "offline");
80 window.addEventListener("online", online);
81 window.addEventListener("offline", offline);
82 return { online, offline };
83 }),
84 ({ online, offline }) =>
85 Effect.sync(() => {
86 window.removeEventListener("online", online);
87 window.removeEventListener("offline", offline);
88 }),
89 ).pipe(Effect.asVoid),
90 ),
91});
92
93const wakeupsLayer = Wakeups.layer({
94 changes: Stream.merge(
95 Stream.callback<"application-active">((queue) =>
96 Effect.acquireRelease(
97 Effect.sync(() => {
98 const listener = () => {
99 if (document.visibilityState === "visible") {
100 Queue.offerUnsafe(queue, "application-active");
101 }
102 };
103 document.addEventListener("visibilitychange", listener);
104 return listener;
105 }),
106 (listener) =>
107 Effect.sync(() => {
108 document.removeEventListener("visibilitychange", listener);
109 }),
110 ).pipe(Effect.asVoid),
111 ),
112 managedRelayAccountChanges(appAtomRegistry).pipe(
113 Stream.map(() => "credentials-changed" as const),
114 ),
115 ),
116});
117
118function clientMetadata() {
119 return clientPresentationMetadata({
120 appVersion: APP_VERSION,
121 hosted: isHostedStaticApp(),
122 identity: {
123 userAgent: navigator.userAgent,
124 platform: navigator.platform,
125 maxTouchPoints: navigator.maxTouchPoints,
126 },
127 desktopBridge: window.desktopBridge,
128 });
129}
130
131function sshPreparationError(cause: unknown) {
132 const message = cause instanceof Error ? cause.message : String(cause);
133 if (message.toLowerCase().includes("cancel")) {
134 return new ConnectionBlockedError({
135 reason: "authentication",
136 detail: message,
137 });
138 }
139 return new ConnectionTransientError({
140 reason: "remote-unavailable",
141 detail: `Could not prepare the SSH environment: ${message}`,
142 });
143}
144
145export const provisionDesktopSshEnvironment = Effect.fn(
146 "web.connectionPlatform.ssh.provisionDesktop",
147)(function* (bridge: DesktopBridge, target: DesktopSshEnvironmentTarget) {
148 const bootstrap = yield* Effect.tryPromise({
149 try: () =>
150 bridge.ensureSshEnvironment(target, {
151 issuePairingToken: true,
152 }),
153 catch: sshPreparationError,
154 });
155 const pairingToken = bootstrap.pairingToken;
156 if (pairingToken === null) {
157 return yield* new ConnectionBlockedError({
158 reason: "authentication",
159 detail: "The SSH environment did not issue a pairing credential.",
160 });
161 }
162 const descriptor = yield* Effect.tryPromise({
163 try: () => bridge.fetchSshEnvironmentDescriptor(bootstrap.httpBaseUrl),
164 catch: sshPreparationError,
165 });
166 const access = yield* Effect.tryPromise({
167 try: () => bridge.bootstrapSshBearerSession(bootstrap.httpBaseUrl, pairingToken),
168 catch: sshPreparationError,
169 });
170 return {
171 environmentId: descriptor.environmentId,
172 label: descriptor.label,
173 bootstrap,
174 bearerToken: access.access_token,
175 };
176});
177
178const capabilitiesLayer = Layer.effectContext(
179 Effect.sync(() => {
180 const presentation = ClientPresentation.of({
181 metadata: clientMetadata(),
182 scopes: AuthStandardClientScopes,
183 });
184 const cloudSession = CloudSession.of({
185 clerkToken: Effect.gen(function* () {
186 const session = appAtomRegistry.get(managedRelaySessionAtom);
187 if (session === null) {
188 return yield* new ConnectionBlockedError({
189 reason: "authentication",
190 detail: "Sign in to T3 Connect to connect this environment.",
191 });
192 }
193 const token = yield* session.readClerkToken().pipe(
194 Effect.mapError(
195 (error) =>
196 new ConnectionTransientError({
197 reason: "network",
198 detail: error.message,
199 }),
200 ),
201 );
202 if (token === null) {
203 return yield* new ConnectionBlockedError({
204 reason: "authentication",
205 detail: "The T3 Connect session is unavailable.",
206 });
207 }
208 return token;
209 }),
210 });
211 const identity = RelayDeviceIdentity.of({
212 deviceId: Effect.succeed(Option.none()),
213 });
214 const primaryAuth = PrimaryEnvironmentAuth.of({
215 bearerToken: Effect.tryPromise({
216 try: readDesktopPrimaryBearerToken,
217 catch: (cause) =>
218 new ConnectionTransientError({
219 reason: "remote-unavailable",
220 detail: `Could not load the desktop primary credential: ${String(cause)}`,
221 }),
222 }).pipe(Effect.map(Option.fromNullishOr)),
223 });
224 const ssh = SshEnvironmentGateway.of({
225 provision: Effect.fn("web.connectionPlatform.ssh.provision")(function* (target) {
226 const bridge = window.desktopBridge;
227 if (bridge === undefined) {
228 return yield* new ConnectionBlockedError({
229 reason: "unsupported",
230 detail: "SSH environments are only available in the desktop app.",
231 });
232 }
233 return yield* provisionDesktopSshEnvironment(bridge, target);
234 }),
235 prepare: Effect.fn("web.connectionPlatform.ssh.prepare")(function* (input) {
236 const bridge = window.desktopBridge;
237 if (bridge === undefined) {
238 return yield* new ConnectionBlockedError({
239 reason: "unsupported",
240 detail: "SSH environments are only available in the desktop app.",
241 });
242 }
243 const bootstrap = yield* Effect.tryPromise({
244 try: () =>
245 bridge.ensureSshEnvironment(input.target, {
246 issuePairingToken: true,
247 }),
248 catch: sshPreparationError,
249 });
250 if (bootstrap.pairingToken === null) {
251 return yield* new ConnectionBlockedError({
252 reason: "authentication",
253 detail: "The SSH environment did not issue a pairing credential.",
254 });
255 }
256 const access = yield* Effect.tryPromise({
257 try: () =>
258 bridge.bootstrapSshBearerSession(bootstrap.httpBaseUrl, bootstrap.pairingToken!),
259 catch: sshPreparationError,
260 });
261 return {
262 bootstrap,
263 bearerToken: access.access_token,
264 };
265 }),
266 disconnect: Effect.fn("web.connectionPlatform.ssh.disconnect")(function* (target) {
267 const bridge = window.desktopBridge;
268 if (bridge === undefined) {
269 return;
270 }
271 yield* Effect.tryPromise({
272 try: () => bridge.disconnectSshEnvironment(target),
273 catch: (cause) =>
274 new ConnectionTransientError({
275 reason: "remote-unavailable",
276 detail: `Could not disconnect the SSH environment: ${String(cause)}`,
277 }),
278 });
279 }),
280 });
281
282 return Context.make(CloudSession, cloudSession).pipe(
283 Context.add(PrimaryEnvironmentAuth, primaryAuth),
284 Context.add(RelayDeviceIdentity, identity),
285 Context.add(ClientPresentation, presentation),
286 Context.add(SshEnvironmentGateway, ssh),
287 );
288 }),
289);
290
291const loadPrimaryConnectionRegistration = Effect.fn(
292 "web.connectionPlatform.loadPrimaryConnectionRegistration",
293)(function* (resolved: PrimaryEnvironmentTarget) {
294 const descriptor = yield* fetchRemoteEnvironmentDescriptor({
295 httpBaseUrl: resolved.target.httpBaseUrl,
296 }).pipe(Effect.provide(primaryEnvironmentHttpLayer), Effect.mapError(mapRemoteEnvironmentError));
297 return new PrimaryConnectionRegistration({
298 target: new PrimaryConnectionTarget({
299 environmentId: descriptor.environmentId,
300 label: descriptor.label,
301 httpBaseUrl: resolved.target.httpBaseUrl,
302 wsBaseUrl: resolved.target.wsBaseUrl,
303 }),
304 });
305});
306
307// A desktop-local secondary backend (e.g. a parallel WSL backend) lives on its
308// own loopback origin, so — unlike the same-origin primary — it authenticates
309// with a bearer token minted from the bootstrap credential the desktop issues.
310const loadSecondaryConnectionRegistration = Effect.fn(
311 "web.connectionPlatform.loadSecondaryConnectionRegistration",
312)(function* (entry: DesktopEnvironmentBootstrap) {
313 if (
314 entry.httpBaseUrl === null ||
315 entry.wsBaseUrl === null ||
316 entry.bootstrapToken === undefined
317 ) {
318 return yield* new ConnectionTransientError({
319 reason: "endpoint-unavailable",
320 detail: `Desktop-local backend ${entry.id} is not ready yet.`,
321 });
322 }
323 const httpBaseUrl = entry.httpBaseUrl;
324 const wsBaseUrl = entry.wsBaseUrl;
325 const descriptor = yield* fetchRemoteEnvironmentDescriptor({ httpBaseUrl }).pipe(
326 Effect.mapError(mapRemoteEnvironmentError),
327 );
328 const issuedAtEpochMs = yield* Clock.currentTimeMillis;
329 const access = yield* bootstrapRemoteBearerSession({
330 httpBaseUrl,
331 credential: entry.bootstrapToken,
332 scopes: AuthStandardClientScopes,
333 clientMetadata: clientMetadata(),
334 }).pipe(Effect.mapError(mapRemoteEnvironmentError));
335 // Keep the desktop pool's stable backend id in the connection id. The
336 // descriptor environment id still scopes projects and RPC state, while the
337 // backend id lets desktop-only operations (notably the WSL folder picker)
338 // route back to the instance that owns the environment.
339 const connectionId = desktopLocalConnectionId(entry.id);
340 // Prefer the desktop's bootstrap label (it identifies the backend and distro,
341 // e.g. "WSL: Ubuntu") over the generic descriptor label, so consumers can show
342 // a meaningful name without recovering it from the bootstrap list later.
343 const label = entry.label || descriptor.label;
344 return {
345 registration: new BearerConnectionRegistration({
346 target: new BearerConnectionTarget({
347 environmentId: descriptor.environmentId,
348 label,
349 connectionId,
350 }),
351 profile: new BearerConnectionProfile({
352 connectionId,
353 environmentId: descriptor.environmentId,
354 label,
355 httpBaseUrl,
356 wsBaseUrl,
357 }),
358 credential: new BearerConnectionCredential({ token: access.access_token }),
359 }),
360 expiresAtEpochMs: secondaryBearerExpiresAtEpochMs(issuedAtEpochMs, access.expires_in),
361 refreshAtEpochMs: secondaryBearerRefreshAtEpochMs(issuedAtEpochMs, access.expires_in),
362 };
363});
364
365// Poll cadence for the desktop bootstrap topology. There is no change event on
366// the bridge, so the renderer polls; successful registrations are cached by a
367// signature of their endpoint + token until bearer credentials approach expiry.
368const PLATFORM_POLL_INTERVAL = "3 seconds";
369const SECONDARY_BEARER_REFRESH_SKEW_MS = 5_000;
370
371export function secondaryBearerExpiresAtEpochMs(
372 issuedAtEpochMs: number,
373 expiresInSeconds: number,
374): number {
375 return issuedAtEpochMs + Math.max(0, expiresInSeconds * 1_000);
376}
377
378export function secondaryBearerRefreshAtEpochMs(
379 issuedAtEpochMs: number,
380 expiresInSeconds: number,
381): number {
382 return Math.max(
383 issuedAtEpochMs,
384 secondaryBearerExpiresAtEpochMs(issuedAtEpochMs, expiresInSeconds) -
385 SECONDARY_BEARER_REFRESH_SKEW_MS,
386 );
387}
388
389interface CachedPlatformRegistration {
390 readonly signature: string;
391 readonly registration: PlatformConnectionRegistration;
392 readonly expiresAtEpochMs?: number;
393 readonly refreshAtEpochMs?: number;
394}
395
396export type PrimaryEnvironmentTargetRead =
397 | {
398 readonly _tag: "Success";
399 readonly target: PrimaryEnvironmentTarget | null;
400 }
401 | {
402 readonly _tag: "Failure";
403 readonly cause: unknown;
404 };
405
406export function readPrimaryEnvironmentTargetResult(
407 readTarget: () => PrimaryEnvironmentTarget | null = readPrimaryEnvironmentTarget,
408): PrimaryEnvironmentTargetRead {
409 try {
410 return { _tag: "Success", target: readTarget() };
411 } catch (cause) {
412 return { _tag: "Failure", cause };
413 }
414}
415
416export function primaryRegistrationToRetainAfterTopologyRead(
417 previous: ReadonlyMap<string, CachedPlatformRegistration>,
418 topologyRead: PrimaryEnvironmentTargetRead,
419): CachedPlatformRegistration | undefined {
420 return topologyRead._tag === "Failure" ? previous.get(PRIMARY_LOCAL_ENVIRONMENT_ID) : undefined;
421}
422
423export function canReuseCachedPlatformRegistration(
424 cached: CachedPlatformRegistration,
425 signature: string,
426 nowEpochMs: number,
427): boolean {
428 return (
429 cached.signature === signature &&
430 (cached.refreshAtEpochMs === undefined || nowEpochMs < cached.refreshAtEpochMs)
431 );
432}
433
434export function canRetainCachedPlatformRegistrationAfterRefreshFailure(
435 cached: CachedPlatformRegistration,
436 signature: string,
437 nowEpochMs: number,
438): boolean {
439 return (
440 cached.signature === signature &&
441 cached.expiresAtEpochMs !== undefined &&
442 nowEpochMs < cached.expiresAtEpochMs
443 );
444}
445
446export function secondaryRegistrationsToRetainAfterTopologyRead(
447 previous: ReadonlyMap<string, CachedPlatformRegistration>,
448 topologyRead: DesktopSecondaryBootstrapsRead,
449 nowEpochMs: number,
450): ReadonlyMap<string, CachedPlatformRegistration> {
451 if (topologyRead._tag === "Success") {
452 return new Map();
453 }
454 return new Map(
455 [...previous].filter(
456 ([, cached]) => cached.expiresAtEpochMs !== undefined && nowEpochMs < cached.expiresAtEpochMs,
457 ),
458 );
459}
460
461const platformConnectionSourceLayer = Layer.effect(
462 PlatformConnectionSource,
463 Effect.gen(function* () {
464 if (isHostedStaticApp()) {
465 return PlatformConnectionSource.of({
466 registrations: Stream.empty,
467 });
468 }
469 const cacheRef = yield* Ref.make(new Map<string, CachedPlatformRegistration>());
470
471 // Resolve the full set of platform-managed environments the host currently
472 // reports: the primary (same-origin cookie auth) plus any desktop-local
473 // backends running alongside it (bearer auth). Reused registrations come
474 // from the cache; a failed entry is skipped and retried on the next poll.
475 const buildPlatformRegistrations = Effect.gen(function* () {
476 const previous = yield* Ref.get(cacheRef);
477 const nowEpochMs = yield* Clock.currentTimeMillis;
478 const next = new Map<string, CachedPlatformRegistration>();
479 const registrations: Array<PlatformConnectionRegistration> = [];
480
481 const primaryTopologyRead = readPrimaryEnvironmentTargetResult();
482 const retainedPrimary = primaryRegistrationToRetainAfterTopologyRead(
483 previous,
484 primaryTopologyRead,
485 );
486 if (retainedPrimary !== undefined) {
487 next.set(PRIMARY_LOCAL_ENVIRONMENT_ID, retainedPrimary);
488 registrations.push(retainedPrimary.registration);
489 }
490
491 if (primaryTopologyRead._tag === "Failure") {
492 yield* Effect.logWarning("Could not read the primary environment topology.", {
493 cause: primaryTopologyRead.cause,
494 });
495 } else if (primaryTopologyRead.target !== null) {
496 const primaryTarget = primaryTopologyRead.target;
497 const signature = `primary|${primaryTarget.target.httpBaseUrl}|${primaryTarget.target.wsBaseUrl}`;
498 const cached = previous.get(PRIMARY_LOCAL_ENVIRONMENT_ID);
499 if (
500 cached !== undefined &&
501 canReuseCachedPlatformRegistration(cached, signature, nowEpochMs)
502 ) {
503 next.set(PRIMARY_LOCAL_ENVIRONMENT_ID, cached);
504 registrations.push(cached.registration);
505 } else {
506 const built = yield* loadPrimaryConnectionRegistration(primaryTarget).pipe(
507 Effect.tapError((error) =>
508 Effect.logWarning("Could not discover the primary environment.", { error }),
509 ),
510 Effect.option,
511 );
512 if (Option.isSome(built)) {
513 const cacheEntry = { signature, registration: built.value };
514 next.set(PRIMARY_LOCAL_ENVIRONMENT_ID, cacheEntry);
515 registrations.push(built.value);
516 }
517 }
518 }
519
520 const topologyRead = readDesktopSecondaryBootstrapsResult();
521 for (const [id, cached] of secondaryRegistrationsToRetainAfterTopologyRead(
522 previous,
523 topologyRead,
524 nowEpochMs,
525 )) {
526 next.set(id, cached);
527 registrations.push(cached.registration);
528 }
529
530 if (topologyRead._tag === "Failure") {
531 yield* Effect.logWarning("Could not read the desktop-local backend topology.", {
532 cause: topologyRead.cause,
533 });
534 } else {
535 for (const bootstrap of topologyRead.bootstraps) {
536 const signature = `${bootstrap.httpBaseUrl}|${bootstrap.wsBaseUrl}|${bootstrap.bootstrapToken ?? ""}`;
537 const cached = previous.get(bootstrap.id);
538 if (
539 cached !== undefined &&
540 canReuseCachedPlatformRegistration(cached, signature, nowEpochMs)
541 ) {
542 next.set(bootstrap.id, cached);
543 registrations.push(cached.registration);
544 continue;
545 }
546 const built = yield* loadSecondaryConnectionRegistration(bootstrap).pipe(
547 Effect.tapError((error) =>
548 Effect.logWarning("Could not connect a desktop-local backend.", {
549 id: bootstrap.id,
550 error,
551 }),
552 ),
553 Effect.option,
554 );
555 if (Option.isSome(built)) {
556 const cacheEntry = { signature, ...built.value };
557 next.set(bootstrap.id, cacheEntry);
558 registrations.push(built.value.registration);
559 } else if (
560 cached !== undefined &&
561 canRetainCachedPlatformRegistrationAfterRefreshFailure(cached, signature, nowEpochMs)
562 ) {
563 next.set(bootstrap.id, cached);
564 registrations.push(cached.registration);
565 }
566 }
567 }
568
569 yield* Ref.set(cacheRef, next);
570 return registrations as ReadonlyArray<PlatformConnectionRegistration>;
571 }).pipe(Effect.provide(FetchHttpClient.layer));
572
573 return PlatformConnectionSource.of({
574 registrations: Stream.tick(PLATFORM_POLL_INTERVAL).pipe(
575 Stream.mapEffect(() => buildPlatformRegistrations),
576 ),
577 });
578 }),
579);
580
581const environmentOwnedDataCleanupLayer = Layer.succeed(
582 EnvironmentOwnedDataCleanup,
583 EnvironmentOwnedDataCleanup.of({
584 clear: (environmentId) =>
585 Effect.sync(() => {
586 clearComposerDraftsEnvironment(environmentId);
587 }),
588 }),
589);
590
591const rpcRequestObserverLayer = Layer.succeed(
592 EnvironmentRpcRequestObserver,
593 EnvironmentRpcRequestObserver.of({
594 observe: ({ environmentId, method }) =>
595 Effect.sync(() => {
596 nextObservedRpcRequestId += 1;
597 const requestId = `${environmentId}:${nextObservedRpcRequestId}`;
598 trackRpcRequestSent(requestId, method, `${method} · ${environmentId}`);
599 return Effect.sync(() => {
600 acknowledgeRpcRequest(requestId);
601 });
602 }),
603 }),
604);
605
606type ConnectionPlatformLayerSource =
607 | typeof connectionStorageLayer
608 | typeof connectivityLayer
609 | typeof wakeupsLayer
610 | typeof capabilitiesLayer
611 | typeof platformConnectionSourceLayer
612 | typeof environmentOwnedDataCleanupLayer
613 | typeof rpcRequestObserverLayer;
614
615export const connectionPlatformLayer: Layer.Layer<
616 Layer.Success<ConnectionPlatformLayerSource>,
617 Layer.Error<ConnectionPlatformLayerSource>,
618 Layer.Services<ConnectionPlatformLayerSource>
619> = Layer.mergeAll(
620 connectionStorageLayer,
621 connectivityLayer,
622 wakeupsLayer,
623 capabilitiesLayer,
624 platformConnectionSourceLayer,
625 environmentOwnedDataCleanupLayer,
626 rpcRequestObserverLayer,
627);