Open History to see the last commit
1import type {
2 BrowserNavigationTarget,
3 EnvironmentId,
4 PreviewUrlResolution,
5} from "@t3tools/contracts";
6import { isLoopbackHost, normalizePreviewUrl } from "@t3tools/shared/preview";
7
8import { readPreparedConnection } from "~/state/session";
9
10export const normalizeHostname = (host: string): string =>
11 host
12 .toLowerCase()
13 .replace(/^\[|\]$/g, "")
14 .replace(/\.+$/u, "");
15
16const parseIpv4Address = (host: string): readonly number[] | null => {
17 const parts = normalizeHostname(host).split(".").map(Number);
18 return parts.length === 4 &&
19 parts.every((part) => Number.isInteger(part) && part >= 0 && part <= 255)
20 ? parts
21 : null;
22};
23
24const parseIpv4MappedIpv6Address = (host: string): readonly number[] | null => {
25 const normalized = normalizeHostname(host);
26 if (!normalized.startsWith("::ffff:")) return null;
27 const suffix = normalized.slice("::ffff:".length);
28 const dotted = parseIpv4Address(suffix);
29 if (dotted) return dotted;
30 const hextets = suffix.split(":");
31 if (hextets.length !== 2 || hextets.some((part) => !/^[\da-f]{1,4}$/u.test(part))) return null;
32 const high = Number.parseInt(hextets[0]!, 16);
33 const low = Number.parseInt(hextets[1]!, 16);
34 return [high >>> 8, high & 0xff, low >>> 8, low & 0xff];
35};
36
37const parseIpv6Address = (host: string): readonly number[] | null => {
38 const normalized = normalizeHostname(host);
39 if (!normalized.includes(":")) return null;
40 const halves = normalized.split("::");
41 if (halves.length > 2) return null;
42 const head = halves[0] ? halves[0].split(":") : [];
43 const tail = halves[1] ? halves[1].split(":") : [];
44 if ([...head, ...tail].some((part) => !/^[\da-f]{1,4}$/u.test(part))) return null;
45 const missing = 8 - head.length - tail.length;
46 if ((halves.length === 1 && missing !== 0) || (halves.length === 2 && missing < 1)) return null;
47 return [...head, ...Array.from({ length: missing }, () => "0"), ...tail].map((part) =>
48 Number.parseInt(part, 16),
49 );
50};
51
52const ipv6PrefixMatches = (
53 address: readonly number[],
54 prefix: readonly number[],
55 prefixLength: number,
56): boolean => {
57 const fullHextets = Math.floor(prefixLength / 16);
58 if (address.slice(0, fullHextets).some((part, index) => part !== prefix[index])) return false;
59 const remainingBits = prefixLength % 16;
60 if (remainingBits === 0) return true;
61 const mask = (0xffff << (16 - remainingBits)) & 0xffff;
62 return (address[fullHextets]! & mask) === (prefix[fullHextets]! & mask);
63};
64
65const isPrivateIpv4Address = (parts: readonly number[]): boolean =>
66 parts[0] === 0 ||
67 parts[0] === 10 ||
68 parts[0] === 127 ||
69 (parts[0] === 100 && parts[1]! >= 64 && parts[1]! <= 127) ||
70 (parts[0] === 172 && parts[1]! >= 16 && parts[1]! <= 31) ||
71 (parts[0] === 192 && parts[1] === 168) ||
72 (parts[0] === 169 && parts[1] === 254) ||
73 (parts[0] === 198 && parts[1]! >= 18 && parts[1]! <= 19);
74
75const isSpecialPurposeIpv4Address = (parts: readonly number[]): boolean =>
76 isPrivateIpv4Address(parts) ||
77 parts[0]! >= 224 ||
78 // Deliberately suppress the whole protocol-assignment block. IANA marks
79 // .9 and .10 globally reachable, but privacy-safe false negatives are
80 // preferable to disclosing another special-purpose address by mistake.
81 (parts[0] === 192 && parts[1] === 0 && parts[2] === 0) ||
82 (parts[0] === 192 && parts[1] === 0 && parts[2] === 2) ||
83 (parts[0] === 192 && parts[1] === 88 && parts[2] === 99) ||
84 (parts[0] === 198 && parts[1] === 51 && parts[2] === 100) ||
85 (parts[0] === 203 && parts[1] === 0 && parts[2] === 113);
86
87export const isLocalLoopbackHost = (host: string): boolean => {
88 const normalized = normalizeHostname(host);
89 if (normalized === "localhost" || normalized === "::1") return true;
90 return parseIpv4Address(normalized)?.[0] === 127;
91};
92
93export const isPrivateNetworkHost = (host: string): boolean => {
94 const normalized = normalizeHostname(host);
95 if (
96 normalized === "::" ||
97 isLocalLoopbackHost(normalized) ||
98 normalized.endsWith(".localhost") ||
99 normalized.endsWith(".local") ||
100 normalized === "home.arpa" ||
101 normalized.endsWith(".home.arpa") ||
102 (!normalized.includes(".") && !normalized.includes(":"))
103 ) {
104 return true;
105 }
106 if (normalized.endsWith(".ts.net")) return true;
107 const parts = parseIpv4Address(normalized) ?? parseIpv4MappedIpv6Address(normalized);
108 if (parts) return isPrivateIpv4Address(parts);
109 const firstIpv6Token = normalized.split(":", 1)[0] ?? "";
110 if (!normalized.includes(":") || !/^[\da-f]{1,4}$/u.test(firstIpv6Token)) return false;
111 const firstIpv6Hextet = Number.parseInt(firstIpv6Token, 16);
112 return (
113 Number.isInteger(firstIpv6Hextet) &&
114 ((firstIpv6Hextet & 0xfe00) === 0xfc00 || (firstIpv6Hextet & 0xffc0) === 0xfe80)
115 );
116};
117
118/** Whether a hostname is eligible to be disclosed to a public favicon provider. */
119export const isPublicFaviconHost = (host: string): boolean => {
120 // A single trailing dot is a valid absolute DNS name. Repeated trailing
121 // dots are malformed and can conceal legacy numeric forms such as 127.1.
122 if (host.endsWith("..")) return false;
123 const normalized = normalizeHostname(host);
124 if (isPrivateNetworkHost(normalized)) return false;
125 if (
126 [".alt", ".example", ".internal", ".invalid", ".onion", ".test"].some(
127 (suffix) => normalized === suffix.slice(1) || normalized.endsWith(suffix),
128 )
129 ) {
130 return false;
131 }
132 const ipv4 = parseIpv4Address(normalized) ?? parseIpv4MappedIpv6Address(normalized);
133 if (ipv4) return !isSpecialPurposeIpv4Address(ipv4);
134 if (!normalized.includes(":")) return true;
135 const ipv6 = parseIpv6Address(normalized);
136 if (!ipv6) return false;
137 if (ipv6PrefixMatches(ipv6, [0x0064, 0xff9b, 0, 0, 0, 0, 0, 0], 96)) {
138 const embeddedIpv4 = [ipv6[6]! >>> 8, ipv6[6]! & 0xff, ipv6[7]! >>> 8, ipv6[7]! & 0xff];
139 return !isSpecialPurposeIpv4Address(embeddedIpv4);
140 }
141 const first = ipv6[0]!;
142 if ((first & 0xe000) !== 0x2000) return false;
143 if (ipv6PrefixMatches(ipv6, [0x2001, 0, 0, 0, 0, 0, 0, 0], 23)) {
144 const publicProtocolAssignment =
145 (ipv6[1] === 1 &&
146 ipv6.slice(2, 7).every((part) => part === 0) &&
147 [1, 2, 3].includes(ipv6[7]!)) ||
148 ipv6PrefixMatches(ipv6, [0x2001, 3, 0, 0, 0, 0, 0, 0], 32) ||
149 ipv6PrefixMatches(ipv6, [0x2001, 4, 0x0112, 0, 0, 0, 0, 0], 48) ||
150 ipv6PrefixMatches(ipv6, [0x2001, 0x20, 0, 0, 0, 0, 0, 0], 28) ||
151 ipv6PrefixMatches(ipv6, [0x2001, 0x30, 0, 0, 0, 0, 0, 0], 28);
152 return publicProtocolAssignment;
153 }
154 if (ipv6PrefixMatches(ipv6, [0x2001, 0x0db8, 0, 0, 0, 0, 0, 0], 32)) return false;
155 if (ipv6PrefixMatches(ipv6, [0x2002, 0, 0, 0, 0, 0, 0, 0], 16)) return false;
156 if (first === 0x3fff && (ipv6[1]! & 0xf000) === 0) return false;
157 return true;
158};
159
160const readEnvironmentUrl = (environmentId: EnvironmentId): URL => {
161 const connection = readPreparedConnection(environmentId);
162 if (!connection) throw new Error(`Environment ${environmentId} is not connected.`);
163 return new URL(connection.httpBaseUrl);
164};
165
166const resolveEnvironmentPortTarget = (
167 environmentId: EnvironmentId,
168 target: Extract<BrowserNavigationTarget, { readonly kind: "environment-port" }>,
169 environmentUrl: URL,
170 requestedUrl?: string,
171 sourceUrl?: URL,
172): PreviewUrlResolution => {
173 if (!isPrivateNetworkHost(environmentUrl.hostname)) {
174 throw new Error(
175 "This environment port needs the planned authenticated preview gateway; its server address is not directly private-network reachable.",
176 );
177 }
178 const protocol = target.protocol ?? "http";
179 const path = target.path?.startsWith("/") ? target.path : `/${target.path ?? ""}`;
180 const normalizedEnvironmentHost = environmentUrl.hostname.replace(/^\[|\]$/g, "");
181 // Local loopback environments should advertise `localhost` so Chromium
182 // dual-stack lookup can reach a Vite server bound only to ::1 or 127.0.0.1.
183 const resolvedHost = isLocalLoopbackHost(normalizedEnvironmentHost)
184 ? "localhost"
185 : normalizedEnvironmentHost.includes(":")
186 ? `[${normalizedEnvironmentHost}]`
187 : normalizedEnvironmentHost;
188 const resolved = sourceUrl
189 ? new URL(sourceUrl)
190 : new URL(path, `${protocol}://${resolvedHost}:${target.port}`);
191 if (sourceUrl) {
192 resolved.hostname = resolvedHost;
193 resolved.port = String(target.port);
194 }
195 return {
196 requestedUrl: requestedUrl ?? `${protocol}://localhost:${target.port}${path}`,
197 resolvedUrl: resolved.toString(),
198 resolutionKind: isLocalLoopbackHost(normalizedEnvironmentHost)
199 ? "direct"
200 : "direct-private-network",
201 environmentId,
202 };
203};
204
205export function resolveBrowserNavigationTarget(
206 environmentId: EnvironmentId,
207 target: BrowserNavigationTarget,
208): PreviewUrlResolution {
209 if (target.kind === "url") {
210 let parsed: URL | null = null;
211 try {
212 parsed = new URL(normalizePreviewUrl(target.url));
213 } catch {
214 // Preserve the existing direct-navigation behavior so the preview host
215 // reports malformed URL errors through its normal navigation path.
216 }
217 if (parsed && isLoopbackHost(parsed.hostname)) {
218 const environmentUrl = readEnvironmentUrl(environmentId);
219 if (parsed.hostname === "0.0.0.0" || !isLocalLoopbackHost(environmentUrl.hostname)) {
220 return resolveEnvironmentPortTarget(
221 environmentId,
222 {
223 kind: "environment-port",
224 port: Number(parsed.port || (parsed.protocol === "https:" ? 443 : 80)),
225 protocol: parsed.protocol === "https:" ? "https" : "http",
226 path: `${parsed.pathname}${parsed.search}${parsed.hash}`,
227 },
228 environmentUrl,
229 target.url,
230 parsed,
231 );
232 }
233 }
234 return {
235 requestedUrl: target.url,
236 resolvedUrl: target.url,
237 resolutionKind: "direct",
238 environmentId,
239 };
240 }
241 return resolveEnvironmentPortTarget(environmentId, target, readEnvironmentUrl(environmentId));
242}
243
244export function resolveDiscoveredServerUrl(environmentId: EnvironmentId, rawUrl: string): string {
245 try {
246 const normalizedUrl = normalizePreviewUrl(rawUrl);
247 return resolveBrowserNavigationTarget(environmentId, {
248 kind: "url",
249 url: normalizedUrl,
250 }).resolvedUrl;
251 } catch {
252 return rawUrl;
253 }
254}