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