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