Open History to see the last commit
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;
42}
43
44interface DesktopAdvertisedEndpointInput {
45 readonly port: number;
46 readonly exposure: ResolvedDesktopServerExposure;
47 readonly customHttpsEndpointUrls?: readonly string[];
48}
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 }
220}
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 }
232}
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 }
245}
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;
266}
267
268export interface DesktopServerExposureChange {
269 readonly state: DesktopServerExposureState;
270 readonly requiresRelaunch: boolean;
271}
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;
304}
305
306interface ResolvedRuntimeState {
307 readonly state: RuntimeState;
308 readonly unavailable: boolean;
309}
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 };
367}
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 };
410}
411
412// A network-accessible backend binds every interface, so a new Wi-Fi network
413// or DHCP lease changes only the address worth advertising, not the binding.
414const withCurrentAdvertisedHost = (
415 state: RuntimeState,
416 networkInterfaces: DesktopNetworkInterfaces.NetworkInterfaces,
417 advertisedHostOverride: Option.Option<string>,
418): RuntimeState => {
419 if (state.mode !== "network-accessible") {
420 return state;
421 }
422 const override = Option.getOrUndefined(advertisedHostOverride);
423 const exposure = resolveDesktopServerExposure({
424 mode: state.mode,
425 port: state.port,
426 networkInterfaces,
427 ...(override ? { advertisedHostOverride: override } : {}),
428 });
429 return {
430 ...state,
431 endpointUrl: Option.fromNullishOr(exposure.endpointUrl),
432 advertisedHost: Option.fromNullishOr(exposure.advertisedHost),
433 };
434};
435
436const tailscaleIpv4AddressKey = (
437 networkInterfaces: DesktopNetworkInterfaces.NetworkInterfaces,
438): string =>
439 [
440 ...new Set(
441 Object.values(networkInterfaces)
442 .flatMap((addresses) => addresses ?? [])
443 .filter(
444 (address) =>
445 !address.internal &&
446 address.family === "IPv4" &&
447 isTailscaleIpv4Address(address.address),
448 )
449 .map((address) => address.address),
450 ),
451 ]
452 .toSorted()
453 .join(",");
454
455const requiresBackendRelaunch = (previous: RuntimeState, next: RuntimeState): boolean =>
456 previous.port !== next.port ||
457 previous.bindHost !== next.bindHost ||
458 previous.localHttpUrl !== next.localHttpUrl;
459
460/** @public */
461export const make = Effect.gen(function* () {
462 const config = yield* DesktopConfig.DesktopConfig;
463 const networkInterfaces = yield* DesktopNetworkInterfaces.DesktopNetworkInterfaces;
464 const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
465 const httpClient = yield* HttpClient.HttpClient;
466 const desktopSettings = yield* DesktopAppSettings.DesktopAppSettings;
467 const stateRef = yield* Ref.make(initialRuntimeState());
468 // Serialize read-persist-write changes so stale runtime state cannot overwrite another update.
469 const changePermit = yield* Semaphore.make(1);
470
471 // Key status by interface addresses so network changes bypass stale DNS and
472 // identity. Cache unchanged addresses to avoid repeated macOS TCC prompts.
473 const tailscaleStatusCache = yield* Cache.make({
474 capacity: 1,
475 timeToLive: TAILSCALE_STATUS_CACHE_TTL,
476 lookup: (_addresses: string) =>
477 readTailscaleStatus.pipe(
478 Effect.orElseSucceed(() => null),
479 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, childProcessSpawner),
480 ),
481 });
482
483 const readNetworkInterfaces = networkInterfaces.read;
484
485 const readCurrentState = (currentNetworkInterfaces: DesktopNetworkInterfaces.NetworkInterfaces) =>
486 Ref.get(stateRef).pipe(
487 Effect.map((state) =>
488 withCurrentAdvertisedHost(state, currentNetworkInterfaces, config.desktopLanHostOverride),
489 ),
490 );
491
492 const getState = readNetworkInterfaces.pipe(
493 Effect.flatMap(readCurrentState),
494 Effect.map(toContractState),
495 );
496 const backendConfig = Ref.get(stateRef).pipe(Effect.map(toBackendConfig));
497
498 const configureFromSettings = Effect.fn("desktop.serverExposure.configureFromSettings")(
499 function* ({ port }: { readonly port: number }) {
500 yield* Effect.annotateCurrentSpan({ port });
501 const settings = yield* desktopSettings.get;
502 const currentNetworkInterfaces = yield* readNetworkInterfaces;
503 const resolved = resolveRuntimeState({
504 requestedMode: settings.serverExposureMode,
505 settings,
506 port,
507 networkInterfaces: currentNetworkInterfaces,
508 advertisedHostOverride: config.desktopLanHostOverride,
509 });
510 yield* Ref.set(stateRef, resolved.state);
511 return toContractState(resolved.state);
512 },
513 );
514
515 const setMode = Effect.fn("desktop.serverExposure.setMode")(function* (
516 mode: DesktopServerExposureMode,
517 ) {
518 yield* Effect.annotateCurrentSpan({ mode });
519 const previous = yield* Ref.get(stateRef);
520 const currentSettings = yield* desktopSettings.get;
521 const nextSettings = {
522 ...currentSettings,
523 serverExposureMode: mode,
524 };
525 const currentNetworkInterfaces = yield* readNetworkInterfaces;
526 const resolved = resolveRuntimeState({
527 requestedMode: mode,
528 settings: nextSettings,
529 port: previous.port,
530 networkInterfaces: currentNetworkInterfaces,
531 advertisedHostOverride: config.desktopLanHostOverride,
532 });
533
534 if (resolved.unavailable) {
535 return yield* new DesktopServerExposureNoNetworkAddressError({ port: previous.port });
536 }
537
538 const change = yield* desktopSettings.setServerExposureMode(mode).pipe(
539 Effect.mapError(
540 (cause) =>
541 new DesktopServerExposureModePersistenceError({
542 mode,
543 cause,
544 }),
545 ),
546 );
547
548 yield* Ref.set(stateRef, resolved.state);
549 return {
550 state: toContractState(resolved.state),
551 requiresRelaunch: change.changed || requiresBackendRelaunch(previous, resolved.state),
552 };
553 }, changePermit.withPermit);
554
555 const setTailscaleServeEnabled = Effect.fn("desktop.serverExposure.setTailscaleServeEnabled")(
556 function* (input: { readonly enabled: boolean; readonly port?: number }) {
557 yield* Effect.annotateCurrentSpan({
558 enabled: input.enabled,
559 ...(input.port === undefined ? {} : { port: input.port }),
560 });
561 const result = yield* desktopSettings
562 .setTailscaleServe({
563 enabled: input.enabled,
564 port: Option.fromNullishOr(input.port),
565 })
566 .pipe(
567 Effect.mapError(
568 (cause) =>
569 new DesktopTailscaleServePersistenceError({
570 enabled: input.enabled,
571 port: input.port ?? null,
572 cause,
573 }),
574 ),
575 );
576
577 const nextState = yield* Ref.updateAndGet(stateRef, (current) => ({
578 ...current,
579 tailscaleServeEnabled: result.settings.tailscaleServeEnabled,
580 tailscaleServePort: result.settings.tailscaleServePort,
581 }));
582
583 return {
584 state: toContractState(nextState),
585 requiresRelaunch: result.changed,
586 };
587 },
588 changePermit.withPermit,
589 );
590
591 const getAdvertisedEndpoints = Effect.gen(function* () {
592 const currentNetworkInterfaces = yield* readNetworkInterfaces;
593 const state = yield* readCurrentState(currentNetworkInterfaces);
594 const coreEndpoints = resolveDesktopCoreAdvertisedEndpoints({
595 port: state.port,
596 exposure: toResolvedExposure(state),
597 customHttpsEndpointUrls: config.desktopHttpsEndpointUrls,
598 });
599
600 // Spawning Mac App Store Tailscale can prompt for TCC access even when exposure is disabled.
601 if (state.mode !== "network-accessible" && !state.tailscaleServeEnabled) {
602 return coreEndpoints;
603 }
604
605 const tailscaleEndpoints = yield* resolveTailscaleAdvertisedEndpoints({
606 port: state.port,
607 serveEnabled: state.tailscaleServeEnabled,
608 servePort: state.tailscaleServePort,
609 networkInterfaces: currentNetworkInterfaces,
610 readStatus: Cache.get(
611 tailscaleStatusCache,
612 tailscaleIpv4AddressKey(currentNetworkInterfaces),
613 ),
614 }).pipe(
615 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, childProcessSpawner),
616 Effect.provideService(HttpClient.HttpClient, httpClient),
617 );
618 return [...coreEndpoints, ...tailscaleEndpoints];
619 }).pipe(Effect.withSpan("desktop.serverExposure.getAdvertisedEndpoints"));
620
621 return DesktopServerExposure.of({
622 getState,
623 backendConfig,
624 configureFromSettings,
625 setMode,
626 setTailscaleServeEnabled,
627 getAdvertisedEndpoints,
628 });
629});
630
631export const layer = Layer.effect(DesktopServerExposure, make);