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 { isTailnetHost } from "@t3tools/shared/hostClassification";
18
19import * as ServerConfig from "../config.ts";
20import {
21 formatHostForUrl,
22 isLoopbackHost,
23 isPrivateNetworkAddress,
24 isWildcardHost,
25 VIRTUAL_INTERFACE,
26} from "../startupAccess.ts";
27
28type NetworkInterfacesMap = ReturnType<typeof NodeOS.networkInterfaces>;
29
30/**
31 * Stays under the config read's own discovery timeout, so a slow `tailscale`
32 * CLI drops only the tailnet name and never the LAN addresses.
33 */
34const TAILSCALE_ENDPOINT_TIMEOUT = Duration.seconds(3);
35
36export class DirectEndpoints extends Context.Service<
37 DirectEndpoints,
38 {
39 readonly resolve: () => Effect.Effect<ReadonlyArray<ServerDirectEndpoint>>;
40 }
41>()("t3/environment/DirectEndpoints") {}
42
43/**
44 * These routes are plain HTTP and carry the client's credential, so a public
45 * address would send it across the internet unencrypted, and a name
46 * (`server.local`) can resolve to a different machine on each client's network.
47 */
48const isAdvertisableAddress = (address: string): boolean =>
49 NodeNet.isIPv4(address) && !address.startsWith("127.") && isPrivateNetworkAddress(address);
50
51/**
52 * Tailscale's own interface: `tailscale0` on Linux, "Tailscale" on Windows.
53 * macOS names every tunnel `utunN`, so there it is the one that also carries
54 * an address in Tailscale's IPv6 range. Cloudflare WARP and other VPNs assign
55 * from the same IPv4 range, so the IPv4 address alone proves nothing.
56 */
57const isTailscaleInterface = (
58 name: string,
59 entries: ReadonlyArray<NodeOS.NetworkInterfaceInfo>,
60): boolean =>
61 /^tailscale/i.test(name) ||
62 entries.some((entry) => entry.family === "IPv6" && isTailnetHost(entry.address));
63
64export function resolveBoundEndpoints(input: {
65 readonly host: string | undefined;
66 readonly port: number;
67 readonly interfaces: NetworkInterfacesMap;
68 /** A cloud VM's private network is its provider's, which no client shares. */
69 readonly onCloudVm?: boolean;
70}): ReadonlyArray<ServerDirectEndpoint> {
71 if (isLoopbackHost(input.host)) return [];
72 const tailscaleAddresses = new Set(
73 Object.entries(input.interfaces).flatMap(([name, entries = []]) =>
74 isTailscaleInterface(name, entries) ? entries.map((entry) => entry.address) : [],
75 ),
76 );
77 const addresses = isWildcardHost(input.host)
78 ? Object.entries(input.interfaces)
79 .flatMap(([name, entries]) => (VIRTUAL_INTERFACE.test(name) ? [] : (entries ?? [])))
80 .filter(
81 (entry) =>
82 !entry.internal && entry.family === "IPv4" && isAdvertisableAddress(entry.address),
83 )
84 .map((entry) => entry.address)
85 : [input.host!].filter(isAdvertisableAddress);
86 return [...new Set(addresses)]
87 .filter((address) => !input.onCloudVm || tailscaleAddresses.has(address))
88 .map((address) => ({
89 kind: tailscaleAddresses.has(address) ? "tailnet" : "lan",
90 httpBaseUrl: `http://${formatHostForUrl(address)}:${input.port}/`,
91 }));
92}
93
94/**
95 * AWS, GCP, Azure, DigitalOcean, Hetzner, Linode, Vultr, and Oracle all serve
96 * instance metadata at this address. A plain TCP connect skips HTTP proxies,
97 * which would otherwise answer for a machine that is not in a cloud.
98 */
99const CLOUD_METADATA_ADDRESS = "169.254.169.254";
100const CLOUD_METADATA_TIMEOUT_MS = 300;
101
102const probeCloudMetadata = Effect.callback<boolean>((resume) => {
103 const socket = NodeNet.connect({
104 host: CLOUD_METADATA_ADDRESS,
105 port: 80,
106 timeout: CLOUD_METADATA_TIMEOUT_MS,
107 });
108 let settled = false;
109 const settle = (found: boolean) => {
110 if (settled) return;
111 settled = true;
112 socket.destroy();
113 resume(Effect.succeed(found));
114 };
115 socket.once("connect", () => settle(true));
116 socket.once("timeout", () => settle(false));
117 socket.once("error", () => settle(false));
118 return Effect.sync(() => socket.destroy());
119});
120
121/** @public Service construction is part of the canonical Effect module API. */
122export const make = Effect.gen(function* () {
123 const config = yield* ServerConfig.ServerConfig;
124 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
125 const httpClient = yield* HttpClient.HttpClient;
126 // Only the service default listens on every interface without being asked,
127 // so only it checks once whether it runs in a cloud. The check starts now so
128 // the first client does not wait for its timeout.
129 const onCloudVm = config.privateNetworkOnly
130 ? yield* Effect.cached(probeCloudMetadata)
131 : Effect.succeed(false);
132 yield* Effect.forkDetach(onCloudVm);
133
134 const resolve = Effect.gen(function* () {
135 const endpoints = [
136 ...resolveBoundEndpoints({
137 host: config.host,
138 port: config.port,
139 interfaces: NodeOS.networkInterfaces(),
140 onCloudVm: yield* onCloudVm,
141 }),
142 ];
143 // Tailscale Serve terminates HTTPS on the tailnet name and forwards to
144 // loopback, so it works even for a loopback-only server. The name is only
145 // listed once it answers as this server: Serve setup can fail without
146 // stopping startup. Anything slower than the probe leaves it out rather
147 // than holding back the addresses already found.
148 if (config.tailscaleServeEnabled) {
149 const servedUrl = yield* readTailscaleStatus.pipe(
150 Effect.map((status) => status.magicDnsName),
151 Effect.flatMap((magicDnsName) => {
152 if (magicDnsName === null) return Effect.succeed(null);
153 const httpBaseUrl = buildTailscaleHttpsBaseUrl({
154 magicDnsName,
155 servePort: config.tailscaleServePort,
156 });
157 return probeTailscaleHttpsEndpoint({ baseUrl: httpBaseUrl }).pipe(
158 Effect.map((reachable) => (reachable ? httpBaseUrl : null)),
159 );
160 }),
161 Effect.timeoutOption(TAILSCALE_ENDPOINT_TIMEOUT),
162 Effect.map(Option.flatMap(Option.fromNullishOr)),
163 Effect.orElseSucceed(() => Option.none<string>()),
164 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
165 Effect.provideService(HttpClient.HttpClient, httpClient),
166 );
167 if (Option.isSome(servedUrl)) {
168 endpoints.push({ kind: "tailnet", httpBaseUrl: servedUrl.value });
169 }
170 }
171 return endpoints;
172 });
173
174 return DirectEndpoints.of({ resolve: () => resolve });
175});
176
177export const layer = Layer.effect(DirectEndpoints, make);