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 FileSystem from "effect/FileSystem";
11import * as Layer from "effect/Layer";
12import * as Option from "effect/Option";
13import * as Ref from "effect/Ref";
14import { HttpClient } from "effect/http";
15import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
16import * as NodeNet from "node:net";
17import * as NodeOS from "node:os";
18
19import * as HostProcess from "@t3tools/shared/HostProcess";
20import {
21 formatHostForUrl,
22 isTailnetHost,
23 isWildcardHost,
24} from "@t3tools/shared/hostClassification";
25
26import * as ServerConfig from "../config.ts";
27import * as ServerEnvironment from "./ServerEnvironment.ts";
28import {
29 isLoopbackHost,
30 isPrivateNetworkAddress,
31 isVirtualInterface,
32 WINDOWS_HOST_ADAPTER_MAC,
33} from "../startupAccess.ts";
34
35type NetworkInterfacesMap = ReturnType<typeof NodeOS.networkInterfaces>;
36
37// Stay below the config discovery timeout so slow Tailscale drops only the tailnet name.
38const TAILSCALE_ENDPOINT_TIMEOUT = Duration.seconds(3);
39
40export class DirectEndpoints extends Context.Service<
41 DirectEndpoints,
42 {
43 readonly resolveAvailable: () => Effect.Effect<ReadonlyArray<ServerDirectEndpoint>>;
44 readonly resolve: () => Effect.Effect<ReadonlyArray<ServerDirectEndpoint>>;
45 }
46>()("t3/environment/DirectEndpoints") {}
47
48// Credentials travel over HTTP; public IPs leak them and hostnames can resolve differently per client.
49// Wildcard binds stay IPv4: the private-network listener check accepts only IPv4 peers.
50const isAdvertisableAddress = (address: string): boolean =>
51 NodeNet.isIPv4(address) && !address.startsWith("127.") && isPrivateNetworkAddress(address);
52
53// macOS utun names need Tailscale's IPv6 range to identify them; WARP shares its IPv4 range.
54const isTailscaleInterface = (
55 name: string,
56 entries: ReadonlyArray<NodeOS.NetworkInterfaceInfo>,
57): boolean =>
58 /^tailscale/i.test(name) ||
59 entries.some((entry) => entry.family === "IPv6" && isTailnetHost(entry.address));
60
61export function resolveBoundEndpoints(input: {
62 readonly platform: NodeJS.Platform;
63 readonly host: string | undefined;
64 readonly port: number;
65 readonly interfaces: NetworkInterfacesMap;
66 /** A cloud VM's private network is its provider's, which no client shares. */
67 readonly onCloudVm?: boolean;
68 readonly isolatedBridges?: ReadonlySet<string>;
69}): ReadonlyArray<ServerDirectEndpoint> {
70 if (isLoopbackHost(input.host)) return [];
71 const tailscaleAddresses = new Set(
72 Object.entries(input.interfaces).flatMap(([name, entries = []]) =>
73 isTailscaleInterface(name, entries) ? entries.map((entry) => entry.address) : [],
74 ),
75 );
76 const addresses = isWildcardHost(input.host)
77 ? Object.entries(input.interfaces)
78 .flatMap(([name, entries]) =>
79 isVirtualInterface(name, input.platform) || input.isolatedBridges?.has(name)
80 ? []
81 : (entries ?? []),
82 )
83 .filter(
84 (entry) =>
85 !entry.internal &&
86 entry.family === "IPv4" &&
87 isAdvertisableAddress(entry.address) &&
88 !(input.platform === "win32" && WINDOWS_HOST_ADAPTER_MAC.test(entry.mac)),
89 )
90 .map((entry) => entry.address)
91 : [input.host!].filter(
92 (address) =>
93 isAdvertisableAddress(address) || (NodeNet.isIPv6(address) && isTailnetHost(address)),
94 );
95 return [...new Set(addresses)]
96 .filter((address) => !input.onCloudVm || tailscaleAddresses.has(address))
97 .map((address) => ({
98 kind: tailscaleAddresses.has(address) ? "tailnet" : "lan",
99 httpBaseUrl: `http://${formatHostForUrl(address)}:${input.port}/`,
100 }));
101}
102
103const SYSFS_NET = "/sys/class/net";
104
105/**
106 * Linux bridges with no port leading to a NIC, such as a container network
107 * under any name. A host bridge like `br0` enslaves the NIC, directly or
108 * through a bond or VLAN, and stays listed.
109 */
110export const readIsolatedLinuxBridges = Effect.fn("DirectEndpoints.readIsolatedLinuxBridges")(
111 function* (names: ReadonlyArray<string>, root = SYSFS_NET) {
112 const fs = yield* FileSystem.FileSystem;
113 const exists = (path: string) => fs.exists(path).pipe(Effect.orElseSucceed(() => false));
114 const list = (path: string) =>
115 fs.readDirectory(path).pipe(Effect.orElseSucceed((): ReadonlyArray<string> => []));
116 const reachesHardware: (name: string, depth: number) => Effect.Effect<boolean> =
117 Effect.fnUntraced(function* (name: string, depth: number) {
118 if (yield* exists(`${root}/${name}/device`)) return true;
119 if (depth === 0) return false;
120 const lowers = (yield* list(`${root}/${name}`)).flatMap((entry) =>
121 entry.startsWith("lower_") ? [entry.slice("lower_".length)] : [],
122 );
123 for (const lower of lowers) {
124 if (yield* reachesHardware(lower, depth - 1)) return true;
125 }
126 return false;
127 });
128 const isolated = new Set<string>();
129 for (const name of names) {
130 if (!(yield* exists(`${root}/${name}/bridge`))) continue;
131 let uplinked = false;
132 for (const port of yield* list(`${root}/${name}/brif`)) {
133 if (yield* reachesHardware(port, 3)) {
134 uplinked = true;
135 break;
136 }
137 }
138 if (!uplinked) isolated.add(name);
139 }
140 return isolated;
141 },
142);
143
144/**
145 * AWS, GCP, Azure, DigitalOcean, Hetzner, Linode, Vultr, and Oracle all serve
146 * instance metadata at this address. A plain TCP connect skips HTTP proxies,
147 * which would otherwise answer for a machine that is not in a cloud.
148 */
149const CLOUD_METADATA_ADDRESS = "169.254.169.254";
150const CLOUD_METADATA_TIMEOUT_MS = 300;
151
152const probeCloudMetadata = Effect.callback<boolean>((resume) => {
153 const socket = NodeNet.connect({
154 host: CLOUD_METADATA_ADDRESS,
155 port: 80,
156 timeout: CLOUD_METADATA_TIMEOUT_MS,
157 });
158 let settled = false;
159 const settle = (found: boolean) => {
160 if (settled) return;
161 settled = true;
162 socket.destroy();
163 resume(Effect.succeed(found));
164 };
165 socket.once("connect", () => settle(true));
166 socket.once("timeout", () => settle(false));
167 socket.once("error", () => settle(false));
168 return Effect.sync(() => socket.destroy());
169});
170
171/** @public */
172export const make = Effect.gen(function* () {
173 const config = yield* ServerConfig.ServerConfig;
174 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
175 const httpClient = yield* HttpClient.HttpClient;
176 const platform = yield* HostProcess.Platform;
177 const fileSystem = yield* FileSystem.FileSystem;
178 const environmentId = yield* (yield* ServerEnvironment.ServerEnvironment).getEnvironmentId;
179 // Only the service default listens on every interface without being asked,
180 // so only it checks once whether it runs in a cloud. The check starts now so
181 // the first client does not wait for its timeout.
182 const onCloudVm = config.privateNetworkOnly
183 ? yield* Effect.cached(probeCloudMetadata)
184 : Effect.succeed(false);
185 yield* Effect.forkDetach(onCloudVm);
186
187 const servedEndpoint = yield* Ref.make<Option.Option<string>>(Option.none());
188 const resolveAvailable = Effect.fn("DirectEndpoints.resolveAvailable")(function* () {
189 const interfaces = NodeOS.networkInterfaces();
190 const isolatedBridges =
191 platform === "linux" && isWildcardHost(config.host)
192 ? yield* readIsolatedLinuxBridges(Object.keys(interfaces)).pipe(
193 Effect.provideService(FileSystem.FileSystem, fileSystem),
194 )
195 : undefined;
196 const endpoints = [
197 ...resolveBoundEndpoints({
198 platform,
199 host: config.host,
200 port: config.port,
201 interfaces,
202 onCloudVm: yield* onCloudVm,
203 ...(isolatedBridges === undefined ? {} : { isolatedBridges }),
204 }),
205 ];
206 const servedUrl = yield* Ref.get(servedEndpoint);
207 if (Option.isSome(servedUrl)) endpoints.push({ kind: "tailnet", httpBaseUrl: servedUrl.value });
208 return endpoints;
209 });
210
211 const resolve = Effect.gen(function* () {
212 // Serve setup can fail without stopping startup; advertise only after it answers as this server.
213 if (config.tailscaleServeEnabled) {
214 const servedUrl = yield* readTailscaleStatus.pipe(
215 Effect.map((status) => status.magicDnsName),
216 Effect.flatMap((magicDnsName) => {
217 if (magicDnsName === null) return Effect.succeed(null);
218 const httpBaseUrl = buildTailscaleHttpsBaseUrl({
219 magicDnsName,
220 servePort: config.tailscaleServePort,
221 });
222 return probeTailscaleHttpsEndpoint({ baseUrl: httpBaseUrl, environmentId }).pipe(
223 Effect.map((reachable) => (reachable ? httpBaseUrl : null)),
224 );
225 }),
226 Effect.timeoutOption(TAILSCALE_ENDPOINT_TIMEOUT),
227 Effect.map(Option.flatMap(Option.fromNullishOr)),
228 Effect.orElseSucceed(() => Option.none<string>()),
229 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
230 Effect.provideService(HttpClient.HttpClient, httpClient),
231 );
232 yield* Ref.set(servedEndpoint, servedUrl);
233 }
234 return yield* resolveAvailable();
235 });
236
237 return DirectEndpoints.of({
238 resolveAvailable,
239 resolve: Effect.fn("DirectEndpoints.resolve")(function () {
240 return resolve;
241 }),
242 });
243});
244
245export const layer = Layer.effect(DirectEndpoints, make);