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

DesktopServerExposure.ts

597 lines20.0 KB

1import {
2 createAdvertisedEndpoint,
3 type CreateAdvertisedEndpointInput,
4} from "@t3tools/shared/advertisedEndpoint";
5import {
6 DesktopServerExposureModeSchema,
7 type AdvertisedEndpoint,
8 type AdvertisedEndpointProvider,
9 type DesktopServerExposureMode,
10 type DesktopServerExposureState,
11} from "@t3tools/contracts";
12import { isTailscaleIpv4Address, readTailscaleStatus } from "@t3tools/tailscale";
13import * as Cache from "effect/Cache";
14import * as Context from "effect/Context";
15import * as Duration from "effect/Duration";
16import * as Effect from "effect/Effect";
17import * as Layer from "effect/Layer";
18import * as Option from "effect/Option";
19import * as Ref from "effect/Ref";
20import * as Schema from "effect/Schema";
21import * as Semaphore from "effect/Semaphore";
22import * as HttpClient from "effect/http/HttpClient";
23import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
24​
25import * as DesktopAppSettings from "../settings/DesktopAppSettings.ts";
26import * as DesktopConfig from "../app/DesktopConfig.ts";
27import * as DesktopNetworkInterfaces from "./DesktopNetworkInterfaces.ts";
28import { resolveTailscaleAdvertisedEndpoints } from "./tailscaleEndpointProvider.ts";
29​
30const TAILSCALE_STATUS_CACHE_TTL = Duration.seconds(60);
31​
32const DESKTOP_LOOPBACK_HOST = "127.0.0.1";
33const DESKTOP_LAN_BIND_HOST = "0.0.0.0";
34​
35interface ResolvedDesktopServerExposure {
36 readonly mode: DesktopServerExposureMode;
37 readonly bindHost: string;
38 readonly localHttpUrl: string;
39 readonly localWsUrl: string;
40 readonly endpointUrl: string | null;
41 readonly advertisedHost: string | null;
43​
44interface DesktopAdvertisedEndpointInput {
45 readonly port: number;
46 readonly exposure: ResolvedDesktopServerExposure;
47 readonly customHttpsEndpointUrls?: readonly string[];
49​
50const DESKTOP_CORE_ENDPOINT_PROVIDER: AdvertisedEndpointProvider = {
51 id: "desktop-core",
52 label: "Desktop",
53 kind: "core",
54 isAddon: false,
55};
56​
57const DESKTOP_MANUAL_ENDPOINT_PROVIDER: AdvertisedEndpointProvider = {
58 id: "manual",
59 label: "Manual",
60 kind: "manual",
61 isAddon: false,
62};
63​
64const normalizeOptionalHost = (value: string | undefined): string | undefined => {
65 const normalized = value?.trim();
66 return normalized && normalized.length > 0 ? normalized : undefined;
67};
68​
69const isUsableLanIpv4Address = (address: string): boolean =>
70 !address.startsWith("127.") &&
71 !address.startsWith("169.254.") &&
72 !isTailscaleIpv4Address(address);
73​
74// Private bridges and VM adapters are fallbacks; host bridges can carry the real LAN address.
75const HOST_ONLY_INTERFACE =
76 /^(bridge\d|utun|ipsec|ppp|tun|tap|wg|docker|br-|veth|virbr|vmnet|vboxnet|VirtualBox|VMware)/;
77​
78const isHttpsEndpointUrl = (value: string): boolean => {
79 try {
80 return new URL(value).protocol === "https:";
81 } catch {
82 return false;
83 }
84};
85​
86const resolveLanAdvertisedHost = (
87 networkInterfaces: DesktopNetworkInterfaces.NetworkInterfaces,
88 explicitHost: string | undefined,
89): string | null => {
90 const normalizedExplicitHost = normalizeOptionalHost(explicitHost);
91 if (normalizedExplicitHost) {
92 return normalizedExplicitHost;
93 }
94​
95 const lanAddresses = Object.entries(networkInterfaces).flatMap(([name, addresses]) =>
96 (addresses ?? [])
97 .filter(
98 (address) =>
99 !address.internal && address.family === "IPv4" && isUsableLanIpv4Address(address.address),
100 )
101 .map((address) => ({ name, address: address.address })),
102 );
103 const preferred =
104 lanAddresses.find(({ name }) => !HOST_ONLY_INTERFACE.test(name)) ?? lanAddresses[0];
105 return preferred?.address ?? null;
106};
107​
108const resolveDesktopServerExposure = (input: {
109 readonly mode: DesktopServerExposureMode;
110 readonly port: number;
111 readonly networkInterfaces: DesktopNetworkInterfaces.NetworkInterfaces;
112 readonly advertisedHostOverride?: string;
113}): ResolvedDesktopServerExposure => {
114 const localHttpUrl = `http://${DESKTOP_LOOPBACK_HOST}:${input.port}`;
115 const localWsUrl = `ws://${DESKTOP_LOOPBACK_HOST}:${input.port}`;
116​
117 if (input.mode === "local-only") {
118 return {
119 mode: input.mode,
120 bindHost: DESKTOP_LOOPBACK_HOST,
121 localHttpUrl,
122 localWsUrl,
123 endpointUrl: null,
124 advertisedHost: null,
125 };
126 }
127​
128 const advertisedHost = resolveLanAdvertisedHost(
129 input.networkInterfaces,
130 input.advertisedHostOverride,
131 );
132​
133 return {
134 mode: input.mode,
135 bindHost: DESKTOP_LAN_BIND_HOST,
136 localHttpUrl,
137 localWsUrl,
138 endpointUrl: advertisedHost ? `http://${advertisedHost}:${input.port}` : null,
139 advertisedHost,
140 };
141};
142​
143const createDesktopEndpoint = (
144 input: Omit<CreateAdvertisedEndpointInput, "provider" | "source">,
145): AdvertisedEndpoint =>
146 createAdvertisedEndpoint({
147 ...input,
148 provider: DESKTOP_CORE_ENDPOINT_PROVIDER,
149 source: "desktop-core",
150 });
151​
152const createManualEndpoint = (
153 input: Omit<CreateAdvertisedEndpointInput, "provider" | "source">,
154): AdvertisedEndpoint =>
155 createAdvertisedEndpoint({
156 ...input,
157 provider: DESKTOP_MANUAL_ENDPOINT_PROVIDER,
158 source: "user",
159 });
160​
161const resolveDesktopCoreAdvertisedEndpoints = (
162 input: DesktopAdvertisedEndpointInput,
163): readonly AdvertisedEndpoint[] => {
164 const endpoints: AdvertisedEndpoint[] = [
165 createDesktopEndpoint({
166 id: `desktop-loopback:${input.port}`,
167 label: "This machine",
168 httpBaseUrl: input.exposure.localHttpUrl,
169 reachability: "loopback",
170 status: "available",
171 description: "Loopback endpoint for this desktop app.",
172 }),
173 ];
174​
175 if (input.exposure.endpointUrl) {
176 endpoints.push(
177 createDesktopEndpoint({
178 id: `desktop-lan:${input.exposure.endpointUrl}`,
179 label: "Local network",
180 httpBaseUrl: input.exposure.endpointUrl,
181 reachability: "lan",
182 status: "available",
183 isDefault: true,
184 description: "Reachable from devices on the same network.",
185 }),
186 );
187 }
188​
189 for (const customEndpointUrl of input.customHttpsEndpointUrls ?? []) {
190 try {
191 const isHttpsEndpoint = isHttpsEndpointUrl(customEndpointUrl);
192 endpoints.push(
193 createManualEndpoint({
194 id: `manual:${customEndpointUrl}`,
195 label: isHttpsEndpoint ? "Custom HTTPS" : "Custom endpoint",
196 httpBaseUrl: customEndpointUrl,
197 reachability: "public",
198 ...(isHttpsEndpoint ? ({ hostedHttpsCompatibility: "compatible" } as const) : {}),
199 status: "unknown",
200 description: isHttpsEndpoint
201 ? "User-configured HTTPS endpoint for this desktop backend."
202 : "User-configured endpoint for this desktop backend.",
203 }),
204 );
205 } catch {}
206 }
207​
208 return endpoints;
209};
210​
211export class DesktopServerExposureNoNetworkAddressError extends Schema.TaggedError<DesktopServerExposureNoNetworkAddressError>()(
212 "DesktopServerExposureNoNetworkAddressError",
213 {
214 port: Schema.Number,
215 },
216) {
217 override get message(): string {
218 return `No reachable network address is available for desktop network access on port ${this.port}.`;
219 }
221​
222export class DesktopServerExposureModePersistenceError extends Schema.TaggedError<DesktopServerExposureModePersistenceError>()(
223 "DesktopServerExposureModePersistenceError",
224 {
225 mode: DesktopServerExposureModeSchema,
226 cause: Schema.instanceOf(DesktopAppSettings.DesktopSettingsWriteError),
227 },
228) {
229 override get message(): string {
230 return `Failed to persist desktop server exposure mode ${this.mode}.`;
231 }
233​
234export class DesktopTailscaleServePersistenceError extends Schema.TaggedError<DesktopTailscaleServePersistenceError>()(
235 "DesktopTailscaleServePersistenceError",
236 {
237 enabled: Schema.Boolean,
238 port: Schema.NullOr(Schema.Number),
239 cause: Schema.instanceOf(DesktopAppSettings.DesktopSettingsWriteError),
240 },
241) {
242 override get message(): string {
243 return `Failed to persist desktop Tailscale Serve settings (enabled: ${this.enabled}, port: ${this.port ?? "unchanged"}).`;
244 }
246​
247export const DesktopServerExposureSetModeError = Schema.Union([
248 DesktopServerExposureNoNetworkAddressError,
249 DesktopServerExposureModePersistenceError,
250]);
251export type DesktopServerExposureSetModeError = typeof DesktopServerExposureSetModeError.Type;
252​
253export const DesktopServerExposureError = Schema.Union([
254 DesktopServerExposureNoNetworkAddressError,
255 DesktopServerExposureModePersistenceError,
256 DesktopTailscaleServePersistenceError,
257]);
258export type DesktopServerExposureError = typeof DesktopServerExposureError.Type;
259​
260export interface DesktopServerExposureBackendConfig {
261 readonly port: number;
262 readonly bindHost: string;
263 readonly httpBaseUrl: URL;
264 readonly tailscaleServeEnabled: boolean;
265 readonly tailscaleServePort: number;
267​
268export interface DesktopServerExposureChange {
269 readonly state: DesktopServerExposureState;
270 readonly requiresRelaunch: boolean;
272​
273export class DesktopServerExposure extends Context.Service<
274 DesktopServerExposure,
275 {
276 readonly getState: Effect.Effect<DesktopServerExposureState>;
277 readonly backendConfig: Effect.Effect<DesktopServerExposureBackendConfig>;
278 readonly configureFromSettings: (input: {
279 readonly port: number;
280 }) => Effect.Effect<DesktopServerExposureState>;
281 readonly setMode: (
282 mode: DesktopServerExposureMode,
283 ) => Effect.Effect<DesktopServerExposureChange, DesktopServerExposureSetModeError>;
284 readonly setTailscaleServeEnabled: (input: {
285 readonly enabled: boolean;
286 readonly port?: number;
287 }) => Effect.Effect<DesktopServerExposureChange, DesktopTailscaleServePersistenceError>;
288 readonly getAdvertisedEndpoints: Effect.Effect<readonly AdvertisedEndpoint[]>;
289 }
290>()("@t3tools/desktop/backend/DesktopServerExposure") {}
291​
292interface RuntimeState {
293 readonly requestedMode: DesktopServerExposureMode;
294 readonly mode: DesktopServerExposureMode;
295 readonly port: number;
296 readonly bindHost: string;
297 readonly localHttpUrl: string;
298 readonly localWsUrl: string;
299 readonly httpBaseUrl: URL;
300 readonly endpointUrl: Option.Option<string>;
301 readonly advertisedHost: Option.Option<string>;
302 readonly tailscaleServeEnabled: boolean;
303 readonly tailscaleServePort: number;
305​
306interface ResolvedRuntimeState {
307 readonly state: RuntimeState;
308 readonly unavailable: boolean;
310​
311const initialRuntimeState = (): RuntimeState =>
312 runtimeStateFromResolvedExposure({
313 requestedMode: DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS.serverExposureMode,
314 settings: DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS,
315 exposure: resolveDesktopServerExposure({
316 mode: DesktopAppSettings.DEFAULT_DESKTOP_SETTINGS.serverExposureMode,
317 port: 0,
318 networkInterfaces: {},
319 }),
320 port: 0,
321 });
322​
323const toContractState = (state: RuntimeState): DesktopServerExposureState => ({
324 mode: state.mode,
325 endpointUrl: Option.getOrNull(state.endpointUrl),
326 advertisedHost: Option.getOrNull(state.advertisedHost),
327 tailscaleServeEnabled: state.tailscaleServeEnabled,
328 tailscaleServePort: state.tailscaleServePort,
329});
330​
331const toBackendConfig = (state: RuntimeState): DesktopServerExposureBackendConfig => ({
332 port: state.port,
333 bindHost: state.bindHost,
334 httpBaseUrl: state.httpBaseUrl,
335 tailscaleServeEnabled: state.tailscaleServeEnabled,
336 tailscaleServePort: state.tailscaleServePort,
337});
338​
339const toResolvedExposure = (state: RuntimeState): ResolvedDesktopServerExposure => ({
340 mode: state.mode,
341 bindHost: state.bindHost,
342 localHttpUrl: state.localHttpUrl,
343 localWsUrl: state.localWsUrl,
344 endpointUrl: Option.getOrNull(state.endpointUrl),
345 advertisedHost: Option.getOrNull(state.advertisedHost),
346});
347​
348function runtimeStateFromResolvedExposure(input: {
349 readonly requestedMode: DesktopServerExposureMode;
350 readonly settings: DesktopAppSettings.DesktopSettings;
351 readonly exposure: ResolvedDesktopServerExposure;
352 readonly port: number;
353}): RuntimeState {
354 return {
355 requestedMode: input.requestedMode,
356 mode: input.exposure.mode,
357 port: input.port,
358 bindHost: input.exposure.bindHost,
359 localHttpUrl: input.exposure.localHttpUrl,
360 localWsUrl: input.exposure.localWsUrl,
361 httpBaseUrl: new URL(input.exposure.localHttpUrl),
362 endpointUrl: Option.fromNullishOr(input.exposure.endpointUrl),
363 advertisedHost: Option.fromNullishOr(input.exposure.advertisedHost),
364 tailscaleServeEnabled: input.settings.tailscaleServeEnabled,
365 tailscaleServePort: input.settings.tailscaleServePort,
366 };
368​
369function resolveRuntimeState(input: {
370 readonly requestedMode: DesktopServerExposureMode;
371 readonly settings: DesktopAppSettings.DesktopSettings;
372 readonly port: number;
373 readonly networkInterfaces: DesktopNetworkInterfaces.NetworkInterfaces;
374 readonly advertisedHostOverride: Option.Option<string>;
375}): ResolvedRuntimeState {
376 const advertisedHostOverride = Option.getOrUndefined(input.advertisedHostOverride);
377 const requestedExposure = resolveDesktopServerExposure({
378 mode: input.requestedMode,
379 port: input.port,
380 networkInterfaces: input.networkInterfaces,
381 ...(advertisedHostOverride ? { advertisedHostOverride } : {}),
382 });
383 const unavailable =
384 input.requestedMode === "network-accessible" &&
385 requestedExposure.endpointUrl === null &&
386 !Object.values(input.networkInterfaces).some((addresses) =>
387 addresses?.some(
388 (address) =>
389 !address.internal && address.family === "IPv4" && isTailscaleIpv4Address(address.address),
390 ),
391 );
392 const exposure = unavailable
393 ? resolveDesktopServerExposure({
394 mode: "local-only",
395 port: input.port,
396 networkInterfaces: input.networkInterfaces,
397 ...(advertisedHostOverride ? { advertisedHostOverride } : {}),
398 })
399 : requestedExposure;
400​
401 return {
402 state: runtimeStateFromResolvedExposure({
403 requestedMode: input.requestedMode,
404 settings: input.settings,
405 exposure,
406 port: input.port,
407 }),
408 unavailable,
409 };
411​
412const tailscaleIpv4AddressKey = (
413 networkInterfaces: DesktopNetworkInterfaces.NetworkInterfaces,
414): string =>
415 [
416 ...new Set(
417 Object.values(networkInterfaces)
418 .flatMap((addresses) => addresses ?? [])
419 .filter(
420 (address) =>
421 !address.internal &&
422 address.family === "IPv4" &&
423 isTailscaleIpv4Address(address.address),
424 )
425 .map((address) => address.address),
426 ),
427 ]
428 .toSorted()
429 .join(",");
430​
431const requiresBackendRelaunch = (previous: RuntimeState, next: RuntimeState): boolean =>
432 previous.port !== next.port ||
433 previous.bindHost !== next.bindHost ||
434 previous.localHttpUrl !== next.localHttpUrl;
435​
436/** @public */
437export const make = Effect.gen(function* () {
438 const config = yield* DesktopConfig.DesktopConfig;
439 const networkInterfaces = yield* DesktopNetworkInterfaces.DesktopNetworkInterfaces;
440 const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
441 const httpClient = yield* HttpClient.HttpClient;
442 const desktopSettings = yield* DesktopAppSettings.DesktopAppSettings;
443 const stateRef = yield* Ref.make(initialRuntimeState());
444 // Serialize read-persist-write changes so stale runtime state cannot overwrite another update.
445 const changePermit = yield* Semaphore.make(1);
446​
447 // Key status by interface addresses so network changes bypass stale DNS and
448 // identity. Cache unchanged addresses to avoid repeated macOS TCC prompts.
449 const tailscaleStatusCache = yield* Cache.make({
450 capacity: 1,
451 timeToLive: TAILSCALE_STATUS_CACHE_TTL,
452 lookup: (_addresses: string) =>
453 readTailscaleStatus.pipe(
454 Effect.orElseSucceed(() => null),
455 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, childProcessSpawner),
456 ),
457 });
458​
459 const readNetworkInterfaces = networkInterfaces.read;
460​
461 const getState = Ref.get(stateRef).pipe(Effect.map(toContractState));
462 const backendConfig = Ref.get(stateRef).pipe(Effect.map(toBackendConfig));
463​
464 const configureFromSettings = Effect.fn("desktop.serverExposure.configureFromSettings")(
465 function* ({ port }: { readonly port: number }) {
466 yield* Effect.annotateCurrentSpan({ port });
467 const settings = yield* desktopSettings.get;
468 const currentNetworkInterfaces = yield* readNetworkInterfaces;
469 const resolved = resolveRuntimeState({
470 requestedMode: settings.serverExposureMode,
471 settings,
472 port,
473 networkInterfaces: currentNetworkInterfaces,
474 advertisedHostOverride: config.desktopLanHostOverride,
475 });
476 yield* Ref.set(stateRef, resolved.state);
477 return toContractState(resolved.state);
478 },
479 );
480​
481 const setMode = Effect.fn("desktop.serverExposure.setMode")(function* (
482 mode: DesktopServerExposureMode,
483 ) {
484 yield* Effect.annotateCurrentSpan({ mode });
485 const previous = yield* Ref.get(stateRef);
486 const currentSettings = yield* desktopSettings.get;
487 const nextSettings = {
488 ...currentSettings,
489 serverExposureMode: mode,
490 };
491 const currentNetworkInterfaces = yield* readNetworkInterfaces;
492 const resolved = resolveRuntimeState({
493 requestedMode: mode,
494 settings: nextSettings,
495 port: previous.port,
496 networkInterfaces: currentNetworkInterfaces,
497 advertisedHostOverride: config.desktopLanHostOverride,
498 });
499​
500 if (resolved.unavailable) {
501 return yield* new DesktopServerExposureNoNetworkAddressError({ port: previous.port });
502 }
503​
504 const change = yield* desktopSettings.setServerExposureMode(mode).pipe(
505 Effect.mapError(
506 (cause) =>
507 new DesktopServerExposureModePersistenceError({
508 mode,
509 cause,
510 }),
511 ),
512 );
513​
514 yield* Ref.set(stateRef, resolved.state);
515 return {
516 state: toContractState(resolved.state),
517 requiresRelaunch: change.changed || requiresBackendRelaunch(previous, resolved.state),
518 };
519 }, changePermit.withPermit);
520​
521 const setTailscaleServeEnabled = Effect.fn("desktop.serverExposure.setTailscaleServeEnabled")(
522 function* (input: { readonly enabled: boolean; readonly port?: number }) {
523 yield* Effect.annotateCurrentSpan({
524 enabled: input.enabled,
525 ...(input.port === undefined ? {} : { port: input.port }),
526 });
527 const result = yield* desktopSettings
528 .setTailscaleServe({
529 enabled: input.enabled,
530 port: Option.fromNullishOr(input.port),
531 })
532 .pipe(
533 Effect.mapError(
534 (cause) =>
535 new DesktopTailscaleServePersistenceError({
536 enabled: input.enabled,
537 port: input.port ?? null,
538 cause,
539 }),
540 ),
541 );
542​
543 const nextState = yield* Ref.updateAndGet(stateRef, (current) => ({
544 ...current,
545 tailscaleServeEnabled: result.settings.tailscaleServeEnabled,
546 tailscaleServePort: result.settings.tailscaleServePort,
547 }));
548​
549 return {
550 state: toContractState(nextState),
551 requiresRelaunch: result.changed,
552 };
553 },
554 changePermit.withPermit,
555 );
556​
557 const getAdvertisedEndpoints = Effect.gen(function* () {
558 const state = yield* Ref.get(stateRef);
559 const currentNetworkInterfaces = yield* readNetworkInterfaces;
560 const coreEndpoints = resolveDesktopCoreAdvertisedEndpoints({
561 port: state.port,
562 exposure: toResolvedExposure(state),
563 customHttpsEndpointUrls: config.desktopHttpsEndpointUrls,
564 });
565​
566 // Spawning Mac App Store Tailscale can prompt for TCC access even when exposure is disabled.
567 if (state.mode !== "network-accessible" && !state.tailscaleServeEnabled) {
568 return coreEndpoints;
569 }
570​
571 const tailscaleEndpoints = yield* resolveTailscaleAdvertisedEndpoints({
572 port: state.port,
573 serveEnabled: state.tailscaleServeEnabled,
574 servePort: state.tailscaleServePort,
575 networkInterfaces: currentNetworkInterfaces,
576 readStatus: Cache.get(
577 tailscaleStatusCache,
578 tailscaleIpv4AddressKey(currentNetworkInterfaces),
579 ),
580 }).pipe(
581 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, childProcessSpawner),
582 Effect.provideService(HttpClient.HttpClient, httpClient),
583 );
584 return [...coreEndpoints, ...tailscaleEndpoints];
585 }).pipe(Effect.withSpan("desktop.serverExposure.getAdvertisedEndpoints"));
586​
587 return DesktopServerExposure.of({
588 getState,
589 backendConfig,
590 configureFromSettings,
591 setMode,
592 setTailscaleServeEnabled,
593 getAdvertisedEndpoints,
594 });
595});
596​
597export const layer = Layer.effect(DesktopServerExposure, make);