Open History to see the last commit
1import * as NodeNet from "node:net";
2import * as NodeOS from "node:os";
3
4import {
5 formatHostForUrl,
6 isPrivateNetworkHost,
7 isSharedAddressSpaceHost,
8 isWildcardHost,
9} from "@t3tools/shared/hostClassification";
10import * as HostProcess from "@t3tools/shared/HostProcess";
11import { QrCode } from "@t3tools/shared/qrCode";
12import { buildPairingAppLink } from "@t3tools/shared/remote";
13import * as Effect from "effect/Effect";
14import { HttpServer } from "effect/http";
15import * as NetAddress from "effect/net/NetAddress";
16
17import * as ServerConfig from "./config.ts";
18import * as EnvironmentAuth from "./auth/EnvironmentAuth.ts";
19
20export interface HeadlessServeAccessInfo {
21 readonly connectionString: string;
22 readonly token: string;
23 readonly pairingUrl: string;
24}
25
26type NetworkInterfacesMap = ReturnType<typeof NodeOS.networkInterfaces>;
27
28export const isLoopbackHost = (host: string | undefined): boolean => {
29 if (!host || host.length === 0) {
30 return true;
31 }
32
33 return (
34 host === "localhost" ||
35 host === "127.0.0.1" ||
36 host === "::1" ||
37 host === "[::1]" ||
38 host.startsWith("127.")
39 );
40};
41
42/**
43 * Container and VM networks (Docker, libvirt, VMware, VirtualBox, Hyper-V, and
44 * macOS's `bridge100`+) have private addresses only this machine reaches. A
45 * host bridge such as `br0` or Proxmox's `vmbr0` carries the LAN address, so
46 * it stays listed.
47 */
48const VIRTUAL_INTERFACE =
49 /^(docker|br-|veth|virbr|vmnet|vboxnet|vEthernet|podman|cni|flannel|cali|lxcbr|lxdbr|bridge[1-9]\d\d)/;
50
51/**
52 * systemd-nspawn's `ve-*`/`vz-*` and NixOS containers' `vb-*` name host-side
53 * veths after the machine. Windows aliases are user-renameable, so these
54 * prefixes only apply to Linux interface discovery.
55 */
56const LINUX_CONTAINER_INTERFACE = /^(ve-|vb-|vz-)/;
57
58export const isVirtualInterface = (name: string, platform: NodeJS.Platform): boolean =>
59 VIRTUAL_INTERFACE.test(name) || (platform === "linux" && LINUX_CONTAINER_INTERFACE.test(name));
60
61/**
62 * Loopback or private-range IPv4 (LAN, tailnet, CGNAT), not link-local, in
63 * plain or IPv4-mapped IPv6 form.
64 */
65export const isPrivateNetworkAddress = (address: string): boolean => {
66 const ipv4 = address.replace(/^::ffff:/i, "");
67 return NodeNet.isIPv4(ipv4) && !ipv4.startsWith("169.254.") && isPrivateNetworkHost(ipv4);
68};
69
70/**
71 * A private-network listener binds every interface but serves only
72 * connections that stay on loopback, a LAN, or the tailnet. Both ends must be
73 * private: a cloud VM or a router port forward hands public clients to a
74 * private local address.
75 */
76export const acceptsPrivateNetworkConnection = (socket: {
77 readonly localAddress?: string | undefined;
78 readonly remoteAddress?: string | undefined;
79}): boolean =>
80 [socket.localAddress, socket.remoteAddress].every(
81 (address) => address !== undefined && isPrivateNetworkAddress(address),
82 );
83
84export const loopbackUrlHostForAddress = (address: NetAddress.InetAddress): string =>
85 NetAddress.isUnspecified(address.address)
86 ? "127.0.0.1"
87 : NetAddress.formatUrlHostString(NetAddress.formatIp(address.address));
88
89const normalizeHost = (host: string): string =>
90 host.startsWith("[") && host.endsWith("]") ? host.slice(1, -1) : host;
91
92const isIpv4Family = (family: string | number): boolean => family === "IPv4" || family === 4;
93
94const isIpv6Family = (family: string | number): boolean => family === "IPv6" || family === 6;
95
96const resolveHeadlessConnectionHost = (
97 host: string | undefined,
98 interfaces: NetworkInterfacesMap,
99 privateNetworkOnly: boolean,
100 platform: NodeJS.Platform,
101): string => {
102 if (!host) {
103 return "localhost";
104 }
105
106 if (!isWildcardHost(host)) {
107 return normalizeHost(host);
108 }
109
110 const interfaceEntries = Object.entries(interfaces).flatMap(([name, entries]) =>
111 privateNetworkOnly && isVirtualInterface(name, platform) ? [] : (entries ?? []),
112 );
113 const externalIpv4Entries = interfaceEntries.filter(
114 (entry) =>
115 !entry.internal &&
116 isIpv4Family(entry.family) &&
117 (!privateNetworkOnly || isPrivateNetworkAddress(entry.address)),
118 );
119 // A tailnet or other CGNAT address reaches fewer devices than the LAN one.
120 const externalIpv4 = privateNetworkOnly
121 ? (externalIpv4Entries.find((entry) => !isSharedAddressSpaceHost(entry.address)) ??
122 externalIpv4Entries[0])
123 : externalIpv4Entries[0];
124 if (externalIpv4) {
125 return externalIpv4.address;
126 }
127 if (privateNetworkOnly) {
128 return "localhost";
129 }
130
131 const externalIpv6 = interfaceEntries.find(
132 (entry) => !entry.internal && isIpv6Family(entry.family),
133 );
134 return externalIpv6 ? normalizeHost(externalIpv6.address) : "localhost";
135};
136
137export const resolveHeadlessConnectionString = (
138 host: string | undefined,
139 port: number,
140 options: {
141 readonly interfaces?: NetworkInterfacesMap;
142 readonly privateNetworkOnly?: boolean | undefined;
143 readonly platform: NodeJS.Platform;
144 },
145): string => {
146 const connectionHost = resolveHeadlessConnectionHost(
147 host,
148 options.interfaces ?? NodeOS.networkInterfaces(),
149 options.privateNetworkOnly === true,
150 options.platform,
151 );
152 return `http://${formatHostForUrl(connectionHost)}:${port}`;
153};
154
155const resolveListeningPort = (address: unknown, fallbackPort: number): number => {
156 if (
157 typeof address === "object" &&
158 address !== null &&
159 "port" in address &&
160 typeof address.port === "number"
161 ) {
162 return address.port;
163 }
164 return fallbackPort;
165};
166
167export const buildPairingUrl = (connectionString: string, token: string): string => {
168 const url = new URL(connectionString);
169 url.pathname = "/pair";
170 url.searchParams.delete("token");
171 url.hash = new URLSearchParams([["token", token]]).toString();
172 return url.toString();
173};
174
175export const renderTerminalQrCode = (value: string, margin = 2): string => {
176 const qrCode = QrCode.encodeText(value, QrCode.Ecc.MEDIUM);
177 const rows: Array<string> = [];
178 const isDark = (x: number, y: number): boolean =>
179 x >= 0 && x < qrCode.size && y >= 0 && y < qrCode.size && qrCode.getModule(x, y);
180
181 for (let y = -margin; y < qrCode.size + margin; y += 2) {
182 let row = "";
183
184 for (let x = -margin; x < qrCode.size + margin; x += 1) {
185 const topDark = isDark(x, y);
186 const bottomDark = isDark(x, y + 1);
187
188 row += topDark ? (bottomDark ? "█" : "▀") : bottomDark ? "▄" : " ";
189 }
190
191 rows.push(row);
192 }
193
194 return rows.join("\n");
195};
196
197export const formatHeadlessServeOutput = (accessInfo: HeadlessServeAccessInfo): string =>
198 [
199 "T3 Code server is ready.",
200 `Connection string: ${accessInfo.connectionString}`,
201 `Token: ${accessInfo.token}`,
202 `Pairing URL: ${accessInfo.pairingUrl}`,
203 `App link: ${buildPairingAppLink(accessInfo.pairingUrl)}`,
204 "",
205 renderTerminalQrCode(accessInfo.pairingUrl),
206 "",
207 ].join("\n");
208
209export const issueHeadlessServeAccessInfo = Effect.fn("issueHeadlessServeAccessInfo")(function* () {
210 const serverConfig = yield* ServerConfig.ServerConfig;
211 const httpServer = yield* HttpServer.HttpServer;
212 const serverAuth = yield* EnvironmentAuth.EnvironmentAuth;
213 const platform = yield* HostProcess.Platform;
214 const connectionString = resolveHeadlessConnectionString(
215 serverConfig.host,
216 resolveListeningPort(httpServer.address, serverConfig.port),
217 { privateNetworkOnly: serverConfig.privateNetworkOnly, platform },
218 );
219 const issued = yield* serverAuth.issueStartupPairingCredential();
220
221 return {
222 connectionString,
223 token: issued.credential,
224 pairingUrl: buildPairingUrl(connectionString, issued.credential),
225 } satisfies HeadlessServeAccessInfo;
226});