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

startupAccess.ts

288 lines10.3 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​
140// A startup URL names the address the server bound; `localhost` can resolve to the other
141// address family, where this server is not listening.
142const loopbackAddressFor = (host: string | undefined): string =>
143 host !== undefined && normalizeHost(host) === "::" ? "::1" : "127.0.0.1";
144​
145/** The origin a browser on this machine uses to reach a server bound to `host`. */
146export const resolveLocalOrigin = (host: string | undefined, port: number): string =>
147 `http://${formatHostForUrl(host && !isWildcardHost(host) ? normalizeHost(host) : loopbackAddressFor(host))}:${port}`;
148​
149const resolveHeadlessConnectionHost = (
150 host: string | undefined,
151 interfaces: NetworkInterfacesMap,
152 privateNetworkOnly: boolean,
153 platform: NodeJS.Platform,
154): string => {
155 if (!host) {
156 return loopbackAddressFor(host);
157 }
158​
159 if (!isWildcardHost(host)) {
160 return normalizeHost(host);
161 }
162​
163 const interfaceEntries = Object.entries(interfaces).flatMap(([name, entries]) =>
164 privateNetworkOnly && isVirtualInterface(name, platform) ? [] : (entries ?? []),
165 );
166 const externalIpv4Entries = interfaceEntries.filter(
167 (entry) =>
168 !entry.internal &&
169 isIpv4Family(entry.family) &&
170 (!privateNetworkOnly ||
171 (isPrivateNetworkAddress(entry.address) &&
172 !(platform === "win32" && WINDOWS_HOST_ADAPTER_MAC.test(entry.mac)))),
173 );
174 // A tailnet or other CGNAT address reaches fewer devices than the LAN one.
175 const externalIpv4 = privateNetworkOnly
176 ? (externalIpv4Entries.find((entry) => !isSharedAddressSpaceHost(entry.address)) ??
177 externalIpv4Entries[0])
178 : externalIpv4Entries[0];
179 if (externalIpv4) {
180 return externalIpv4.address;
181 }
182 if (privateNetworkOnly) {
183 return loopbackAddressFor(host);
184 }
185​
186 const externalIpv6 = interfaceEntries.find(
187 (entry) => !entry.internal && isIpv6Family(entry.family),
188 );
189 return externalIpv6 ? normalizeHost(externalIpv6.address) : loopbackAddressFor(host);
190};
191​
192export const resolveHeadlessConnectionString = (
193 host: string | undefined,
194 port: number,
195 options: {
196 readonly interfaces?: NetworkInterfacesMap;
197 readonly privateNetworkOnly?: boolean | undefined;
198 readonly platform: NodeJS.Platform;
199 },
200): string => {
201 const connectionHost = resolveHeadlessConnectionHost(
202 host,
203 options.interfaces ?? NodeOS.networkInterfaces(),
204 options.privateNetworkOnly === true,
205 options.platform,
206 );
207 return `http://${formatHostForUrl(connectionHost)}:${port}`;
208};
209​
210const resolveListeningPort = (address: unknown, fallbackPort: number): number => {
211 if (
212 typeof address === "object" &&
213 address !== null &&
214 "port" in address &&
215 typeof address.port === "number"
216 ) {
217 return address.port;
218 }
219 return fallbackPort;
220};
221​
222export const buildPairingUrl = (connectionString: string, token: string): string => {
223 const url = new URL(connectionString);
224 url.pathname = "/pair";
225 url.searchParams.delete("token");
226 url.hash = new URLSearchParams([["token", token]]).toString();
227 return url.toString();
228};
229​
230export const renderTerminalQrCode = (value: string, margin = 2): string => {
231 const qrCode = QrCode.encodeText(value, QrCode.Ecc.MEDIUM);
232 const rows: Array<string> = [];
233 const isDark = (x: number, y: number): boolean =>
234 x >= 0 && x < qrCode.size && y >= 0 && y < qrCode.size && qrCode.getModule(x, y);
235​
236 for (let y = -margin; y < qrCode.size + margin; y += 2) {
237 let row = "";
238​
239 for (let x = -margin; x < qrCode.size + margin; x += 1) {
240 const topDark = isDark(x, y);
241 const bottomDark = isDark(x, y + 1);
242​
243 row += topDark ? (bottomDark ? "█" : "▀") : bottomDark ? "▄" : " ";
244 }
245​
246 rows.push(row);
247 }
248​
249 return rows.join("\n");
250};
251​
252export const formatHeadlessServeOutput = (accessInfo: HeadlessServeAccessInfo): string =>
253 [
254 "T3 Code server is ready.",
255 `Connection string: ${accessInfo.connectionString}`,
256 `Token: ${accessInfo.token}`,
257 `Pairing URL: ${accessInfo.pairingUrl}`,
258 `App link: ${buildPairingAppLink(accessInfo.pairingUrl)}`,
259 ...(isLoopbackHost(new URL(accessInfo.connectionString).hostname)
260 ? []
261 : [
262 "",
263 "Warning: this address uses plain HTTP. Anyone on the same network can read the",
264 "token and control this machine. Use it over a VPN or tailnet you trust.",
265 ]),
266 "",
267 renderTerminalQrCode(accessInfo.pairingUrl),
268 "",
269 ].join("\n");
270​
271export const issueHeadlessServeAccessInfo = Effect.fn("issueHeadlessServeAccessInfo")(function* () {
272 const serverConfig = yield* ServerConfig.ServerConfig;
273 const httpServer = yield* HttpServer.HttpServer;
274 const serverAuth = yield* EnvironmentAuth.EnvironmentAuth;
275 const platform = yield* HostProcess.Platform;
276 const connectionString = resolveHeadlessConnectionString(
277 serverConfig.host,
278 resolveListeningPort(httpServer.address, serverConfig.port),
279 { privateNetworkOnly: serverConfig.privateNetworkOnly, platform },
280 );
281 const issued = yield* serverAuth.issueStartupPairingCredential();
282​
283 return {
284 connectionString,
285 token: issued.credential,
286 pairingUrl: buildPairingUrl(connectionString, issued.credential),
287 } satisfies HeadlessServeAccessInfo;
288});