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

DirectEndpoints.ts

143 lines5.7 KB

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