Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

browserTargetResolver.ts

141 lines4.9 KB

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