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