Open History to see the last commit
1import type { BrowserNavigationTarget, EnvironmentId, PreviewUrlResolution } from "@v12/contracts";
2import { isLoopbackHost, normalizePreviewUrl } from "@v12/shared/preview";
3
4import { readPreparedConnection } from "~/state/session";
5
6const normalizeHostname = (host: string): string => host.toLowerCase().replace(/^\[|\]$/g, "");
7
8const parseIpv4Address = (host: string): readonly number[] | null => {
9 const parts = normalizeHostname(host).split(".").map(Number);
10 return parts.length === 4 &&
11 parts.every((part) => Number.isInteger(part) && part >= 0 && part <= 255)
12 ? parts
13 : null;
14};
15
16const isLocalLoopbackHost = (host: string): boolean => {
17 const normalized = normalizeHostname(host);
18 if (normalized === "localhost" || normalized === "::1") return true;
19 return parseIpv4Address(normalized)?.[0] === 127;
20};
21
22const isPrivateNetworkHost = (host: string): boolean => {
23 const normalized = normalizeHostname(host);
24 if (isLocalLoopbackHost(normalized) || normalized.endsWith(".local")) {
25 return true;
26 }
27 if (normalized.endsWith(".ts.net")) return true;
28 const parts = parseIpv4Address(normalized);
29 if (parts) {
30 return (
31 parts[0] === 10 ||
32 (parts[0] === 100 && parts[1]! >= 64 && parts[1]! <= 127) ||
33 (parts[0] === 172 && parts[1]! >= 16 && parts[1]! <= 31) ||
34 (parts[0] === 192 && parts[1] === 168) ||
35 (parts[0] === 169 && parts[1] === 254)
36 );
37 }
38 const firstIpv6Token = normalized.split(":", 1)[0] ?? "";
39 if (!normalized.includes(":") || !/^[\da-f]{1,4}$/u.test(firstIpv6Token)) return false;
40 const firstIpv6Hextet = Number.parseInt(firstIpv6Token, 16);
41 return (
42 Number.isInteger(firstIpv6Hextet) &&
43 ((firstIpv6Hextet & 0xfe00) === 0xfc00 || (firstIpv6Hextet & 0xffc0) === 0xfe80)
44 );
45};
46
47const readEnvironmentUrl = (environmentId: EnvironmentId): URL => {
48 const connection = readPreparedConnection(environmentId);
49 if (!connection) throw new Error(`Environment ${environmentId} is not connected.`);
50 return new URL(connection.httpBaseUrl);
51};
52
53const resolveEnvironmentPortTarget = (
54 environmentId: EnvironmentId,
55 target: Extract<BrowserNavigationTarget, { readonly kind: "environment-port" }>,
56 environmentUrl: URL,
57 requestedUrl?: string,
58 sourceUrl?: URL,
59): PreviewUrlResolution => {
60 if (!isPrivateNetworkHost(environmentUrl.hostname)) {
61 throw new Error(
62 "This environment port needs the planned authenticated preview gateway; its server address is not directly private-network reachable.",
63 );
64 }
65 const protocol = target.protocol ?? "http";
66 const path = target.path?.startsWith("/") ? target.path : `/${target.path ?? ""}`;
67 const normalizedEnvironmentHost = environmentUrl.hostname.replace(/^\[|\]$/g, "");
68 const resolvedHost = normalizedEnvironmentHost.includes(":")
69 ? `[${normalizedEnvironmentHost}]`
70 : normalizedEnvironmentHost;
71 const resolved = sourceUrl
72 ? new URL(sourceUrl)
73 : new URL(path, `${protocol}://${resolvedHost}:${target.port}`);
74 if (sourceUrl) {
75 resolved.hostname = resolvedHost;
76 resolved.port = String(target.port);
77 }
78 return {
79 requestedUrl: requestedUrl ?? `${protocol}://localhost:${target.port}${path}`,
80 resolvedUrl: resolved.toString(),
81 resolutionKind: isLocalLoopbackHost(normalizedEnvironmentHost)
82 ? "direct"
83 : "direct-private-network",
84 environmentId,
85 };
86};
87
88export function resolveBrowserNavigationTarget(
89 environmentId: EnvironmentId,
90 target: BrowserNavigationTarget,
91): PreviewUrlResolution {
92 if (target.kind === "url") {
93 let parsed: URL | null = null;
94 try {
95 parsed = new URL(normalizePreviewUrl(target.url));
96 } catch {
97 // Preserve the existing direct-navigation behavior so the preview host
98 // reports malformed URL errors through its normal navigation path.
99 }
100 if (parsed && isLoopbackHost(parsed.hostname)) {
101 const environmentUrl = readEnvironmentUrl(environmentId);
102 if (parsed.hostname === "0.0.0.0" || !isLocalLoopbackHost(environmentUrl.hostname)) {
103 return resolveEnvironmentPortTarget(
104 environmentId,
105 {
106 kind: "environment-port",
107 port: Number(parsed.port || (parsed.protocol === "https:" ? 443 : 80)),
108 protocol: parsed.protocol === "https:" ? "https" : "http",
109 path: `${parsed.pathname}${parsed.search}${parsed.hash}`,
110 },
111 environmentUrl,
112 target.url,
113 parsed,
114 );
115 }
116 }
117 return {
118 requestedUrl: target.url,
119 resolvedUrl: target.url,
120 resolutionKind: "direct",
121 environmentId,
122 };
123 }
124 return resolveEnvironmentPortTarget(environmentId, target, readEnvironmentUrl(environmentId));
125}
126
127export function resolveDiscoveredServerUrl(environmentId: EnvironmentId, rawUrl: string): string {
128 try {
129 const normalizedUrl = normalizePreviewUrl(rawUrl);
130 return resolveBrowserNavigationTarget(environmentId, {
131 kind: "url",
132 url: normalizedUrl,
133 }).resolvedUrl;
134 } catch {
135 return rawUrl;
136 }
137}