Open History to see the last commit
1import * as NodeOS from "node:os";
2
3import { QrCode } from "@t3tools/shared/qrCode";
4import * as Effect from "effect/Effect";
5import { HttpServer } from "effect/http";
6import * as NetAddress from "effect/net/NetAddress";
7
8import * as ServerConfig from "./config.ts";
9import * as EnvironmentAuth from "./auth/EnvironmentAuth.ts";
10
11export interface HeadlessServeAccessInfo {
12 readonly connectionString: string;
13 readonly token: string;
14 readonly pairingUrl: string;
15}
16
17type NetworkInterfacesMap = ReturnType<typeof NodeOS.networkInterfaces>;
18
19export const isLoopbackHost = (host: string | undefined): boolean => {
20 if (!host || host.length === 0) {
21 return true;
22 }
23
24 return (
25 host === "localhost" ||
26 host === "127.0.0.1" ||
27 host === "::1" ||
28 host === "[::1]" ||
29 host.startsWith("127.")
30 );
31};
32
33export const isWildcardHost = (host: string | undefined): boolean =>
34 host === "0.0.0.0" || host === "::" || host === "[::]";
35
36export const formatHostForUrl = (host: string): string =>
37 host.includes(":") && !host.startsWith("[") ? `[${host}]` : host;
38
39export const loopbackUrlHostForAddress = (address: NetAddress.InetAddress): string =>
40 address._tag === "InetAddressV6" && NetAddress.isLoopback(address.address)
41 ? "[::1]"
42 : "127.0.0.1";
43
44const normalizeHost = (host: string): string =>
45 host.startsWith("[") && host.endsWith("]") ? host.slice(1, -1) : host;
46
47const isIpv4Family = (family: string | number): boolean => family === "IPv4" || family === 4;
48
49const isIpv6Family = (family: string | number): boolean => family === "IPv6" || family === 6;
50
51export const resolveHeadlessConnectionHost = (
52 host: string | undefined,
53 interfaces: NetworkInterfacesMap = NodeOS.networkInterfaces(),
54): string => {
55 if (!host) {
56 return "localhost";
57 }
58
59 if (!isWildcardHost(host)) {
60 return normalizeHost(host);
61 }
62
63 const interfaceEntries = Object.values(interfaces).flatMap((entries) => entries ?? []);
64 const externalIpv4 = interfaceEntries.find(
65 (entry) => !entry.internal && isIpv4Family(entry.family),
66 );
67 if (externalIpv4) {
68 return externalIpv4.address;
69 }
70
71 const externalIpv6 = interfaceEntries.find(
72 (entry) => !entry.internal && isIpv6Family(entry.family),
73 );
74 return externalIpv6 ? normalizeHost(externalIpv6.address) : "localhost";
75};
76
77export const resolveHeadlessConnectionString = (
78 host: string | undefined,
79 port: number,
80 interfaces: NetworkInterfacesMap = NodeOS.networkInterfaces(),
81): string => {
82 const connectionHost = resolveHeadlessConnectionHost(host, interfaces);
83 return `http://${formatHostForUrl(connectionHost)}:${port}`;
84};
85
86export const resolveListeningPort = (address: unknown, fallbackPort: number): number => {
87 if (
88 typeof address === "object" &&
89 address !== null &&
90 "port" in address &&
91 typeof address.port === "number"
92 ) {
93 return address.port;
94 }
95 return fallbackPort;
96};
97
98export const buildPairingUrl = (connectionString: string, token: string): string => {
99 const url = new URL(connectionString);
100 url.pathname = "/pair";
101 url.searchParams.delete("token");
102 url.hash = new URLSearchParams([["token", token]]).toString();
103 return url.toString();
104};
105
106export const renderTerminalQrCode = (value: string, margin = 2): string => {
107 const qrCode = QrCode.encodeText(value, QrCode.Ecc.MEDIUM);
108 const rows: Array<string> = [];
109 const isDark = (x: number, y: number): boolean =>
110 x >= 0 && x < qrCode.size && y >= 0 && y < qrCode.size && qrCode.getModule(x, y);
111
112 for (let y = -margin; y < qrCode.size + margin; y += 2) {
113 let row = "";
114
115 for (let x = -margin; x < qrCode.size + margin; x += 1) {
116 const topDark = isDark(x, y);
117 const bottomDark = isDark(x, y + 1);
118
119 row += topDark ? (bottomDark ? "█" : "▀") : bottomDark ? "▄" : " ";
120 }
121
122 rows.push(row);
123 }
124
125 return rows.join("\n");
126};
127
128export const formatHeadlessServeOutput = (accessInfo: HeadlessServeAccessInfo): string =>
129 [
130 "T3 Code server is ready.",
131 `Connection string: ${accessInfo.connectionString}`,
132 `Token: ${accessInfo.token}`,
133 `Pairing URL: ${accessInfo.pairingUrl}`,
134 "",
135 renderTerminalQrCode(accessInfo.pairingUrl),
136 "",
137 ].join("\n");
138
139export const issueHeadlessServeAccessInfo = Effect.fn("issueHeadlessServeAccessInfo")(function* () {
140 const serverConfig = yield* ServerConfig.ServerConfig;
141 const httpServer = yield* HttpServer.HttpServer;
142 const serverAuth = yield* EnvironmentAuth.EnvironmentAuth;
143 const connectionString = resolveHeadlessConnectionString(
144 serverConfig.host,
145 resolveListeningPort(httpServer.address, serverConfig.port),
146 );
147 const issued = yield* serverAuth.issueStartupPairingCredential();
148
149 return {
150 connectionString,
151 token: issued.credential,
152 pairingUrl: buildPairingUrl(connectionString, issued.credential),
153 } satisfies HeadlessServeAccessInfo;
154});