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