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

preview.ts

244 lines9.0 KB

1import type { BrowserSearchEngine } from "@t3tools/contracts";
2import * as Schema from "effect/Schema";
3​
4import { isLocalLoopbackHost, isWildcardHost, normalizeHostname } from "./hostClassification.ts";
5​
6const TAB_ID_PREFIX = "tab_";
7let nextPreviewTabSequence = 0;
8​
9export function previewPdfAssetUrl(rawUrl: string, httpBaseUrl: string | null): string | null {
10 if (httpBaseUrl === null) return null;
11 try {
12 const url = new URL(rawUrl);
13 const baseUrl = new URL(httpBaseUrl);
14 if (
15 (url.protocol !== "http:" && url.protocol !== "https:") ||
16 !url.pathname.startsWith("/api/assets/") ||
17 !/\.pdf$/i.test(url.pathname)
18 ) {
19 return null;
20 }
21 // Any site can serve a page at this path; one the client embedded would run in the user's
22 // own browser instead of the preview's. Only this environment's assets are loaded here.
23 if (
24 url.origin !== baseUrl.origin &&
25 !isLocalLoopbackHost(url.hostname) &&
26 url.hostname !== "0.0.0.0"
27 ) {
28 return null;
29 }
30 // The browser may run on the host's loopback address. Fetch signed bytes
31 // through this client's environment connection, including remote routes.
32 return new URL(`${url.pathname}${url.search}${url.hash}`, baseUrl).href;
33 } catch {
34 return null;
35 }
37​
38export function newPreviewTabId(): string {
39 nextPreviewTabSequence += 1;
40 return `${TAB_ID_PREFIX}${nextPreviewTabSequence.toString(36)}`;
42​
43const LOOPBACK_HOSTS: ReadonlySet<string> = new Set(["localhost", "127.0.0.1", "0.0.0.0", "::1"]);
44​
45export const LSOF_LOCAL_HOST_TOKENS: ReadonlySet<string> = new Set([
46 ...LOOPBACK_HOSTS,
47 "*",
48 "[::]",
49 "[::1]",
50]);
51​
52const LOOPBACK_PREFIX_PATTERN = /^(?:localhost|127\.0\.0\.1|0\.0\.0\.0|\[::1?\])(?::|\/|$)/i;
53​
54export function isLoopbackHost(host: string): boolean {
55 if (LOOPBACK_HOSTS.has(host)) return true;
56 if (host === "[::1]") return true;
57 return false;
59​
60export class PreviewUrlNormalizationError extends Schema.TaggedError<PreviewUrlNormalizationError>()(
61 "PreviewUrlNormalizationError",
62 {
63 inputLength: Schema.Number,
64 reason: Schema.Literals(["empty", "parse", "unsupported-protocol"]),
65 protocol: Schema.optional(Schema.String),
66 cause: Schema.optional(Schema.Defect()),
67 },
68) {
69 override get message(): string {
70 const protocol = this.protocol === undefined ? "" : `: ${this.protocol}`;
71 return `Invalid preview URL (${this.reason}${protocol}; input length ${this.inputLength}). Use an http(s) URL or a schemeless host such as localhost:5173. With preview_open, omit url when creating a new tab to open a blank tab.`;
72 }
74​
75export const isPreviewUrlNormalizationError = Schema.is(PreviewUrlNormalizationError);
76​
77function previewUrlProtocol(rawUrl: string): string | undefined {
78 return /^([A-Za-z][A-Za-z\d+.-]*):/.exec(rawUrl)?.[1]?.toLowerCase().concat(":");
80​
81const ADDRESS_HOST_PATTERN = /^(?:localhost\.?|\d{1,3}(?:\.\d{1,3}){3}|\[[\da-f:.]+\])$/i;
82const BARE_HOST_PORT_PATTERN = /^[^/?#:@]+:\d+(?:[/?#]|$)/;
83const URL_SCHEME_WITH_AUTHORITY_PATTERN = /^(?:[a-z][a-z\d+.-]*:\/\/|https?:\/)/i;
84const PROTOCOL_RELATIVE_AUTHORITY_PATTERN = /^\/\/[^/?#\\\s]/;
85const KNOWN_NON_WEB_SCHEMES: ReadonlySet<string> = new Set([
86 "about:",
87 "blob:",
88 "chrome:",
89 "data:",
90 "file:",
91 "ftp:",
92 "javascript:",
93 "mailto:",
94 "sms:",
95 "ssh:",
96 "tel:",
97 "view-source:",
98 "ws:",
99 "wss:",
100]);
101​
102/** Address bar search URL templates; `%s` is replaced with the encoded query. */
103const BROWSER_SEARCH_URL_TEMPLATES = {
104 duckduckgo: "https://duckduckgo.com/?q=%s",
105 google: "https://www.google.com/search?q=%s",
106 bing: "https://www.bing.com/search?q=%s",
107 brave: "https://search.brave.com/search?q=%s",
108 kagi: "https://kagi.com/search?q=%s",
109 ecosia: "https://www.ecosia.org/search?q=%s",
110} satisfies Record<Exclude<BrowserSearchEngine, "custom">, string>;
111​
112function fillSearchUrlTemplate(template: string, query: string): string {
113 return template.replaceAll("%s", encodeURIComponent(query));
115​
116/**
117 * Whether a custom search URL is an http(s) URL with `%s` where the query goes.
118 * `%s` in the host or credentials is rejected: the query would never reach a
119 * search page, and a query with spaces would make the host unreachable.
120 */
121export function isValidSearchUrlTemplate(template: string): boolean {
122 if (!template.includes("%s")) return false;
123 try {
124 // Two queries land on different authorities only when `%s` sits before the path.
125 const authority = (url: URL) => `${url.username}:${url.password}@${url.host}`;
126 const url = new URL(fillSearchUrlTemplate(template, "a"));
127 const other = new URL(fillSearchUrlTemplate(template, "b"));
128 return (
129 (url.protocol === "http:" || url.protocol === "https:") && authority(url) === authority(other)
130 );
131 } catch {
132 return false;
133 }
135​
136/**
137 * The search URL template for the chosen engine. An unusable custom template
138 * falls back to DuckDuckGo so a query typed in the address bar always searches.
139 */
140export function resolveSearchUrlTemplate(settings: {
141 readonly browserSearchEngine: BrowserSearchEngine;
142 readonly browserCustomSearchUrl: string;
143}): string {
144 if (settings.browserSearchEngine !== "custom") {
145 return BROWSER_SEARCH_URL_TEMPLATES[settings.browserSearchEngine];
146 }
147 const custom = settings.browserCustomSearchUrl.trim();
148 return isValidSearchUrlTemplate(custom) ? custom : BROWSER_SEARCH_URL_TEMPLATES.duckduckgo;
150​
151export function resolveAddressBarInput(
152 rawInput: string,
153 searchUrlTemplate: string = BROWSER_SEARCH_URL_TEMPLATES.duckduckgo,
154): string {
155 const trimmed = rawInput.trim();
156 if (URL_SCHEME_WITH_AUTHORITY_PATTERN.test(trimmed) || trimmed.length === 0)
157 return normalizePreviewUrl(trimmed);
158 const protocolRelative = PROTOCOL_RELATIVE_AUTHORITY_PATTERN.test(trimmed);
159 const address = protocolRelative ? trimmed.slice(2) : trimmed;
160 if (/\s/.test(address)) {
161 // Text with spaces is a search unless it starts with localhost or an IP address, a port and a
162 // path. A bare IP is not enough ("10.0.0.0/8 vs 172.16.0.0/12"), nor a port ("16:9/4:3 ratio").
163 const [, host] = /^([^/?#:@]+|\[[^/?#@]+\]):\d+\//.exec(address) ?? [];
164 if (host !== undefined && ADDRESS_HOST_PATTERN.test(host)) {
165 try {
166 return normalizePreviewUrl(trimmed);
167 } catch {}
168 }
169 } else {
170 // Reject explicit schemes before URL normalization can misread mailto as bare-host credentials.
171 const protocol = previewUrlProtocol(trimmed);
172 if (
173 protocol !== undefined &&
174 (KNOWN_NON_WEB_SCHEMES.has(protocol) || !BARE_HOST_PORT_PATTERN.test(trimmed))
175 ) {
176 if (protocol !== "http:" && protocol !== "https:") {
177 throw new PreviewUrlNormalizationError({
178 inputLength: rawInput.length,
179 reason: "unsupported-protocol",
180 protocol,
181 });
182 }
183 return normalizePreviewUrl(trimmed);
184 }
185 const authority = address.split(/[/?#]/, 1)[0] ?? "";
186 const host = authority.replace(/^[^@]*@/, "").replace(/:\d+$/, "");
187 const hasPort = host.length < authority.replace(/^[^@]*@/, "").length;
188 if (hasPort || ADDRESS_HOST_PATTERN.test(host) || /^[^.]+(?:\.[^.]+)+\.?$/.test(host)) {
189 try {
190 return normalizePreviewUrl(trimmed);
191 } catch {}
192 }
193 }
194 return fillSearchUrlTemplate(searchUrlTemplate, trimmed);
196​
197export function normalizePreviewUrl(rawUrl: string): string {
198 const trimmed = rawUrl.trim();
199 if (trimmed.length === 0) {
200 throw new PreviewUrlNormalizationError({ inputLength: rawUrl.length, reason: "empty" });
201 }
202 const explicitProtocol = previewUrlProtocol(trimmed);
203 if (explicitProtocol !== undefined && KNOWN_NON_WEB_SCHEMES.has(explicitProtocol)) {
204 throw new PreviewUrlNormalizationError({
205 inputLength: rawUrl.length,
206 reason: "unsupported-protocol",
207 protocol: explicitProtocol,
208 });
209 }
210 const useHttp = LOOPBACK_PREFIX_PATTERN.test(trimmed);
211 const hasExplicitScheme =
212 URL_SCHEME_WITH_AUTHORITY_PATTERN.test(trimmed) ||
213 ((explicitProtocol === "http:" || explicitProtocol === "https:") &&
214 !BARE_HOST_PORT_PATTERN.test(trimmed));
215 const candidate = hasExplicitScheme ? trimmed : `${useHttp ? "http" : "https"}://${trimmed}`;
216 let parsed: URL;
217 try {
218 parsed = new URL(candidate);
219 } catch (cause) {
220 throw new PreviewUrlNormalizationError({
221 inputLength: rawUrl.length,
222 reason: "parse",
223 protocol: previewUrlProtocol(candidate),
224 cause,
225 });
226 }
227 if (parsed.protocol !== "http:" && parsed.protocol !== "https:") {
228 throw new PreviewUrlNormalizationError({
229 inputLength: rawUrl.length,
230 reason: "unsupported-protocol",
231 protocol: parsed.protocol,
232 });
233 }
234 // RFC 6761 keeps every *.localhost name on loopback, and Chromium resolves them there.
235 const loopback =
236 isLocalLoopbackHost(parsed.hostname) ||
237 isWildcardHost(parsed.hostname) ||
238 normalizeHostname(parsed.hostname).endsWith(".localhost");
239 // Re-parse rather than swap the protocol so an explicit :443 survives as a non-default HTTP port.
240 if (!hasExplicitScheme && !useHttp && loopback) {
241 return new URL(`http://${trimmed}`).href;
242 }
243 return parsed.href;