Open History to see the last commit
1import type { ServerDirectEndpoint } from "@t3tools/contracts";
2import {
3 buildTailscaleHttpsBaseUrl,
4 probeTailscaleHttpsEndpoint,
5 readTailscaleStatus,
6} from "@t3tools/tailscale";
7import * as Context from "effect/Context";
8import * as Duration from "effect/Duration";
9import * as Effect from "effect/Effect";
10import * as Layer from "effect/Layer";
11import * as Option from "effect/Option";
12import { HttpClient } from "effect/http";
13import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
14import * as NodeNet from "node:net";
15import * as NodeOS from "node:os";
16
17import { isPrivateNetworkHost, isTailnetHost } from "@t3tools/shared/hostClassification";
18
19import * as ServerConfig from "../config.ts";
20import { formatHostForUrl, isLoopbackHost, isWildcardHost } from "../startupAccess.ts";
21
22type NetworkInterfacesMap = ReturnType<typeof NodeOS.networkInterfaces>;
23
24/**
25 * Stays under the config read's own discovery timeout, so a slow `tailscale`
26 * CLI drops only the tailnet name and never the LAN addresses.
27 */
28const TAILSCALE_ENDPOINT_TIMEOUT = Duration.seconds(3);
29
30export class DirectEndpoints extends Context.Service<
31 DirectEndpoints,
32 {
33 readonly resolve: () => Effect.Effect<ReadonlyArray<ServerDirectEndpoint>>;
34 }
35>()("t3/environment/DirectEndpoints") {}
36
37/**
38 * These routes are plain HTTP and carry the client's credential, so a public
39 * address would send it across the internet unencrypted, and a name
40 * (`server.local`) can resolve to a different machine on each client's network.
41 */
42const isAdvertisableAddress = (address: string): boolean =>
43 NodeNet.isIPv4(address) &&
44 !address.startsWith("127.") &&
45 !address.startsWith("169.254.") &&
46 isPrivateNetworkHost(address);
47
48/**
49 * Container and VM networks (Docker, libvirt, VMware, VirtualBox, Hyper-V, and
50 * macOS's `bridge100`+) have private addresses only this machine reaches. A
51 * host bridge such as `br0` or Proxmox's `vmbr0` carries the LAN address, so
52 * it stays listed.
53 */
54const VIRTUAL_INTERFACE =
55 /^(docker|br-|veth|virbr|vmnet|vboxnet|vEthernet|podman|cni|flannel|cali|lxcbr|lxdbr|bridge1\d\d)/;
56
57/**
58 * Tailscale's own interface: `tailscale0` on Linux, "Tailscale" on Windows.
59 * macOS names every tunnel `utunN`, so there it is the one that also carries
60 * an address in Tailscale's IPv6 range. Cloudflare WARP and other VPNs assign
61 * from the same IPv4 range, so the IPv4 address alone proves nothing.
62 */
63const isTailscaleInterface = (
64 name: string,
65 entries: ReadonlyArray<NodeOS.NetworkInterfaceInfo>,
66): boolean =>
67 /^tailscale/i.test(name) ||
68 entries.some((entry) => entry.family === "IPv6" && isTailnetHost(entry.address));
69
70export function resolveBoundEndpoints(input: {
71 readonly host: string | undefined;
72 readonly port: number;
73 readonly interfaces: NetworkInterfacesMap;
74}): ReadonlyArray<ServerDirectEndpoint> {
75 if (isLoopbackHost(input.host)) return [];
76 const tailscaleAddresses = new Set(
77 Object.entries(input.interfaces).flatMap(([name, entries = []]) =>
78 isTailscaleInterface(name, entries) ? entries.map((entry) => entry.address) : [],
79 ),
80 );
81 const addresses = isWildcardHost(input.host)
82 ? Object.entries(input.interfaces)
83 .flatMap(([name, entries]) => (VIRTUAL_INTERFACE.test(name) ? [] : (entries ?? [])))
84 .filter(
85 (entry) =>
86 !entry.internal && entry.family === "IPv4" && isAdvertisableAddress(entry.address),
87 )
88 .map((entry) => entry.address)
89 : [input.host!].filter(isAdvertisableAddress);
90 return [...new Set(addresses)].map((address) => ({
91 kind: tailscaleAddresses.has(address) ? "tailnet" : "lan",
92 httpBaseUrl: `http://${formatHostForUrl(address)}:${input.port}/`,
93 }));
94}
95
96/** @public Service construction is part of the canonical Effect module API. */
97export const make = Effect.gen(function* () {
98 const config = yield* ServerConfig.ServerConfig;
99 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
100 const httpClient = yield* HttpClient.HttpClient;
101
102 const resolve = Effect.gen(function* () {
103 const endpoints = [
104 ...resolveBoundEndpoints({
105 host: config.host,
106 port: config.port,
107 interfaces: NodeOS.networkInterfaces(),
108 }),
109 ];
110 // Tailscale Serve terminates HTTPS on the tailnet name and forwards to
111 // loopback, so it works even for a loopback-only server. The name is only
112 // listed once it answers as this server: Serve setup can fail without
113 // stopping startup. Anything slower than the probe leaves it out rather
114 // than holding back the addresses already found.
115 if (config.tailscaleServeEnabled) {
116 const servedUrl = yield* readTailscaleStatus.pipe(
117 Effect.map((status) => status.magicDnsName),
118 Effect.flatMap((magicDnsName) => {
119 if (magicDnsName === null) return Effect.succeed(null);
120 const httpBaseUrl = buildTailscaleHttpsBaseUrl({
121 magicDnsName,
122 servePort: config.tailscaleServePort,
123 });
124 return probeTailscaleHttpsEndpoint({ baseUrl: httpBaseUrl }).pipe(
125 Effect.map((reachable) => (reachable ? httpBaseUrl : null)),
126 );
127 }),
128 Effect.timeoutOption(TAILSCALE_ENDPOINT_TIMEOUT),
129 Effect.map(Option.flatMap(Option.fromNullishOr)),
130 Effect.orElseSucceed(() => Option.none<string>()),
131 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
132 Effect.provideService(HttpClient.HttpClient, httpClient),
133 );
134 if (Option.isSome(servedUrl)) {
135 endpoints.push({ kind: "tailnet", httpBaseUrl: servedUrl.value });
136 }
137 }
138 return endpoints;
139 });
140
141 return DirectEndpoints.of({ resolve: () => resolve });
142});
143
144export const layer = Layer.effect(DirectEndpoints, make);