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

startupAccess.ts

279 lines9.7 KB

1// @effect-diagnostics nodeBuiltinImport:off - The private-network gate guards the node:http server.
2import type * as NodeHttp from "node:http";
3import * as NodeNet from "node:net";
4import * as NodeOS from "node:os";
5​
6import {
7 formatHostForUrl,
8 isPrivateNetworkHost,
9 isSharedAddressSpaceHost,
10 isWildcardHost,
11} from "@t3tools/shared/hostClassification";
12import * as HostProcess from "@t3tools/shared/HostProcess";
13import { QrCode } from "@t3tools/shared/qrCode";
14import { buildPairingAppLink } from "@t3tools/shared/remote";
15import * as Clock from "effect/Clock";
16import * as Effect from "effect/Effect";
17import { HttpServer } from "effect/http";
18import * as NetAddress from "effect/net/NetAddress";
19​
20import * as ServerConfig from "./config.ts";
21import * as EnvironmentAuth from "./auth/EnvironmentAuth.ts";
22​
23export interface HeadlessServeAccessInfo {
24 readonly connectionString: string;
25 readonly token: string;
26 readonly pairingUrl: string;
28​
29type NetworkInterfacesMap = ReturnType<typeof NodeOS.networkInterfaces>;
30​
31export const isLoopbackHost = (host: string | undefined): boolean => {
32 if (!host || host.length === 0) {
33 return true;
34 }
35​
36 return (
37 host === "localhost" ||
38 host === "127.0.0.1" ||
39 host === "::1" ||
40 host === "[::1]" ||
41 host.startsWith("127.")
42 );
43};
44​
45/**
46 * Container and VM networks (Docker, libvirt, VMware, VirtualBox, Hyper-V, and
47 * macOS's `bridge100`+) have private addresses only this machine reaches. A
48 * host bridge such as `br0` or Proxmox's `vmbr0` carries the LAN address, so
49 * it stays listed.
50 */
51const VIRTUAL_INTERFACE =
52 /^(docker|br-|veth|virbr|vmnet|vboxnet|vEthernet|podman|cni|flannel|cali|lxcbr|lxdbr|bridge[1-9]\d\d)/;
53​
54// VirtualBox and VMware host-only adapters on Windows. Their names are mutable; Linux bridges can inherit these MACs.
55export const WINDOWS_HOST_ADAPTER_MAC = /^(0a:00:27|00:50:56:c0:00):/i;
56​
57/**
58 * systemd-nspawn's `ve-*`/`vz-*` and NixOS containers' `vb-*` name host-side
59 * veths after the machine. Windows aliases are user-renameable, so these
60 * prefixes only apply to Linux interface discovery.
61 */
62const LINUX_CONTAINER_INTERFACE = /^(ve-|vb-|vz-)/;
63​
64export const isVirtualInterface = (name: string, platform: NodeJS.Platform): boolean =>
65 VIRTUAL_INTERFACE.test(name) || (platform === "linux" && LINUX_CONTAINER_INTERFACE.test(name));
66​
67/**
68 * Loopback or private-range IPv4 (LAN, tailnet, CGNAT), not link-local, in
69 * plain or IPv4-mapped IPv6 form.
70 */
71export const isPrivateNetworkAddress = (address: string): boolean => {
72 const ipv4 = address.replace(/^::ffff:/i, "");
73 return NodeNet.isIPv4(ipv4) && !ipv4.startsWith("169.254.") && isPrivateNetworkHost(ipv4);
74};
75​
76/**
77 * A private-network listener binds every interface but serves only
78 * connections that stay on loopback, a LAN, or the tailnet. Both ends must be
79 * private: a cloud VM or a router port forward hands public clients to a
80 * private local address.
81 */
82export const acceptsPrivateNetworkConnection = (socket: {
83 readonly localAddress?: string | undefined;
84 readonly remoteAddress?: string | undefined;
85}): boolean =>
86 [socket.localAddress, socket.remoteAddress].every(
87 (address) => address !== undefined && isPrivateNetworkAddress(address),
88 );
89​
90const CLOSED_CONNECTION_LOG_INTERVAL_NANOS = 60_000_000_000n;
91​
92/**
93 * Closing is silent to the client, so closed connections are logged with both
94 * addresses: the first at once, then at most one line a minute with a count, so
95 * a connect flood from outside cannot grow the service log without bound.
96 */
97// Untraced: the captured context would otherwise tie every later warning to a span that ended at startup.
98export const closeNonPrivateNetworkConnections = Effect.fnUntraced(function* (
99 server: NodeHttp.Server,
100) {
101 const runSync = Effect.runSyncWith(yield* Effect.context<never>());
102 let nextLogAt: bigint | undefined;
103 let closedSinceLastLog = 0;
104 server.on("connection", (socket) => {
105 if (acceptsPrivateNetworkConnection(socket)) return;
106 // Read before destroy: Node forgets localAddress once the handle closes.
107 const addresses = { localAddress: socket.localAddress, remoteAddress: socket.remoteAddress };
108 socket.destroy();
109 runSync(
110 Effect.gen(function* () {
111 // Monotonic: a wall clock set backwards must not silence the warnings.
112 const now = yield* Clock.monotonicTimeNanos;
113 if (nextLogAt !== undefined && now < nextLogAt) {
114 closedSinceLastLog += 1;
115 return;
116 }
117 nextLogAt = now + CLOSED_CONNECTION_LOG_INTERVAL_NANOS;
118 yield* Effect.logWarning("closed a connection outside the private network", {
119 ...addresses,
120 ...(closedSinceLastLog > 0 ? { closedSinceLastLog } : {}),
121 });
122 closedSinceLastLog = 0;
123 }),
124 );
125 });
126});
127​
128export const loopbackUrlHostForAddress = (address: NetAddress.InetAddress): string =>
129 NetAddress.isUnspecified(address.address)
130 ? "127.0.0.1"
131 : NetAddress.formatUrlHostString(NetAddress.formatIp(address.address));
132​
133const normalizeHost = (host: string): string =>
134 host.startsWith("[") && host.endsWith("]") ? host.slice(1, -1) : host;
135​
136const isIpv4Family = (family: string | number): boolean => family === "IPv4" || family === 4;
137​
138const isIpv6Family = (family: string | number): boolean => family === "IPv6" || family === 6;
139​
140const resolveHeadlessConnectionHost = (
141 host: string | undefined,
142 interfaces: NetworkInterfacesMap,
143 privateNetworkOnly: boolean,
144 platform: NodeJS.Platform,
145): string => {
146 if (!host) {
147 return "localhost";
148 }
149​
150 if (!isWildcardHost(host)) {
151 return normalizeHost(host);
152 }
153​
154 const interfaceEntries = Object.entries(interfaces).flatMap(([name, entries]) =>
155 privateNetworkOnly && isVirtualInterface(name, platform) ? [] : (entries ?? []),
156 );
157 const externalIpv4Entries = interfaceEntries.filter(
158 (entry) =>
159 !entry.internal &&
160 isIpv4Family(entry.family) &&
161 (!privateNetworkOnly ||
162 (isPrivateNetworkAddress(entry.address) &&
163 !(platform === "win32" && WINDOWS_HOST_ADAPTER_MAC.test(entry.mac)))),
164 );
165 // A tailnet or other CGNAT address reaches fewer devices than the LAN one.
166 const externalIpv4 = privateNetworkOnly
167 ? (externalIpv4Entries.find((entry) => !isSharedAddressSpaceHost(entry.address)) ??
168 externalIpv4Entries[0])
169 : externalIpv4Entries[0];
170 if (externalIpv4) {
171 return externalIpv4.address;
172 }
173 if (privateNetworkOnly) {
174 return "localhost";
175 }
176​
177 const externalIpv6 = interfaceEntries.find(
178 (entry) => !entry.internal && isIpv6Family(entry.family),
179 );
180 return externalIpv6 ? normalizeHost(externalIpv6.address) : "localhost";
181};
182​
183export const resolveHeadlessConnectionString = (
184 host: string | undefined,
185 port: number,
186 options: {
187 readonly interfaces?: NetworkInterfacesMap;
188 readonly privateNetworkOnly?: boolean | undefined;
189 readonly platform: NodeJS.Platform;
190 },
191): string => {
192 const connectionHost = resolveHeadlessConnectionHost(
193 host,
194 options.interfaces ?? NodeOS.networkInterfaces(),
195 options.privateNetworkOnly === true,
196 options.platform,
197 );
198 return `http://${formatHostForUrl(connectionHost)}:${port}`;
199};
200​
201const resolveListeningPort = (address: unknown, fallbackPort: number): number => {
202 if (
203 typeof address === "object" &&
204 address !== null &&
205 "port" in address &&
206 typeof address.port === "number"
207 ) {
208 return address.port;
209 }
210 return fallbackPort;
211};
212​
213export const buildPairingUrl = (connectionString: string, token: string): string => {
214 const url = new URL(connectionString);
215 url.pathname = "/pair";
216 url.searchParams.delete("token");
217 url.hash = new URLSearchParams([["token", token]]).toString();
218 return url.toString();
219};
220​
221export const renderTerminalQrCode = (value: string, margin = 2): string => {
222 const qrCode = QrCode.encodeText(value, QrCode.Ecc.MEDIUM);
223 const rows: Array<string> = [];
224 const isDark = (x: number, y: number): boolean =>
225 x >= 0 && x < qrCode.size && y >= 0 && y < qrCode.size && qrCode.getModule(x, y);
226​
227 for (let y = -margin; y < qrCode.size + margin; y += 2) {
228 let row = "";
229​
230 for (let x = -margin; x < qrCode.size + margin; x += 1) {
231 const topDark = isDark(x, y);
232 const bottomDark = isDark(x, y + 1);
233​
234 row += topDark ? (bottomDark ? "█" : "▀") : bottomDark ? "▄" : " ";
235 }
236​
237 rows.push(row);
238 }
239​
240 return rows.join("\n");
241};
242​
243export const formatHeadlessServeOutput = (accessInfo: HeadlessServeAccessInfo): string =>
244 [
245 "T3 Code server is ready.",
246 `Connection string: ${accessInfo.connectionString}`,
247 `Token: ${accessInfo.token}`,
248 `Pairing URL: ${accessInfo.pairingUrl}`,
249 `App link: ${buildPairingAppLink(accessInfo.pairingUrl)}`,
250 ...(isLoopbackHost(new URL(accessInfo.connectionString).hostname)
251 ? []
252 : [
253 "",
254 "Warning: this address uses plain HTTP. Anyone on the same network can read the",
255 "token and control this machine. Use it over a VPN or tailnet you trust.",
256 ]),
257 "",
258 renderTerminalQrCode(accessInfo.pairingUrl),
259 "",
260 ].join("\n");
261​
262export const issueHeadlessServeAccessInfo = Effect.fn("issueHeadlessServeAccessInfo")(function* () {
263 const serverConfig = yield* ServerConfig.ServerConfig;
264 const httpServer = yield* HttpServer.HttpServer;
265 const serverAuth = yield* EnvironmentAuth.EnvironmentAuth;
266 const platform = yield* HostProcess.Platform;
267 const connectionString = resolveHeadlessConnectionString(
268 serverConfig.host,
269 resolveListeningPort(httpServer.address, serverConfig.port),
270 { privateNetworkOnly: serverConfig.privateNetworkOnly, platform },
271 );
272 const issued = yield* serverAuth.issueStartupPairingCredential();
273​
274 return {
275 connectionString,
276 token: issued.credential,
277 pairingUrl: buildPairingUrl(connectionString, issued.credential),
278 } satisfies HeadlessServeAccessInfo;
279});