The best way to control Claude Code, Codex and more from any computer or phone

main
ts 224 lines 7.94 KB
Raw
1 import type { BrowserSearchEngine } from "@t3tools/contracts";
2 import * as Schema from "effect/Schema";
3
4 import { isLocalLoopbackHost } from "./hostClassification.ts";
5
6 const TAB_ID_PREFIX = "tab_";
7 let nextPreviewTabSequence = 0;
8
9 export 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 }
36 }
37
38 export function newPreviewTabId(): string {
39 nextPreviewTabSequence += 1;
40 return `${TAB_ID_PREFIX}${nextPreviewTabSequence.toString(36)}`;
41 }
42
43 const LOOPBACK_HOSTS: ReadonlySet<string> = new Set(["localhost", "127.0.0.1", "0.0.0.0", "::1"]);
44
45 export const LSOF_LOCAL_HOST_TOKENS: ReadonlySet<string> = new Set([
46 ...LOOPBACK_HOSTS,
47 "*",
48 "[::]",
49 "[::1]",
50 ]);
51
52 const LOOPBACK_PREFIX_PATTERN = /^(?:localhost|127\.0\.0\.1|0\.0\.0\.0|\[::1?\])(?::|\/|$)/i;
53
54 export function isLoopbackHost(host: string): boolean {
55 if (LOOPBACK_HOSTS.has(host)) return true;
56 if (host === "[::1]") return true;
57 return false;
58 }
59
60 export 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 }
73 }
74
75 export const isPreviewUrlNormalizationError = Schema.is(PreviewUrlNormalizationError);
76
77 function previewUrlProtocol(rawUrl: string): string | undefined {
78 return /^([A-Za-z][A-Za-z\d+.-]*):/.exec(rawUrl)?.[1]?.toLowerCase().concat(":");
79 }
80
81 const ADDRESS_HOST_PATTERN = /^(?:localhost|\d{1,3}(?:\.\d{1,3}){3}|\[[\da-f:.]+\])$/i;
82 const BARE_HOST_PORT_PATTERN = /^[^/?#:@]+:\d+(?:[/?#]|$)/;
83 const URL_SCHEME_WITH_AUTHORITY_PATTERN = /^[a-z][a-z\d+.-]*:\/\//i;
84 const KNOWN_NON_WEB_SCHEMES: ReadonlySet<string> = new Set([
85 "about:",
86 "blob:",
87 "chrome:",
88 "data:",
89 "file:",
90 "ftp:",
91 "javascript:",
92 "mailto:",
93 "sms:",
94 "ssh:",
95 "tel:",
96 "view-source:",
97 "ws:",
98 "wss:",
99 ]);
100
101 /** Address bar search URL templates; `%s` is replaced with the encoded query. */
102 const BROWSER_SEARCH_URL_TEMPLATES = {
103 duckduckgo: "https://duckduckgo.com/?q=%s",
104 google: "https://www.google.com/search?q=%s",
105 bing: "https://www.bing.com/search?q=%s",
106 brave: "https://search.brave.com/search?q=%s",
107 kagi: "https://kagi.com/search?q=%s",
108 ecosia: "https://www.ecosia.org/search?q=%s",
109 } satisfies Record<Exclude<BrowserSearchEngine, "custom">, string>;
110
111 function fillSearchUrlTemplate(template: string, query: string): string {
112 return template.replaceAll("%s", encodeURIComponent(query));
113 }
114
115 /**
116 * Whether a custom search URL is an http(s) URL with `%s` where the query goes.
117 * `%s` in the host or credentials is rejected: the query would never reach a
118 * search page, and a query with spaces would make the host unreachable.
119 */
120 export function isValidSearchUrlTemplate(template: string): boolean {
121 if (!template.includes("%s")) return false;
122 try {
123 // Two queries land on different authorities only when `%s` sits before the path.
124 const authority = (url: URL) => `${url.username}:${url.password}@${url.host}`;
125 const url = new URL(fillSearchUrlTemplate(template, "a"));
126 const other = new URL(fillSearchUrlTemplate(template, "b"));
127 return (
128 (url.protocol === "http:" || url.protocol === "https:") && authority(url) === authority(other)
129 );
130 } catch {
131 return false;
132 }
133 }
134
135 /**
136 * The search URL template for the chosen engine. An unusable custom template
137 * falls back to DuckDuckGo so a query typed in the address bar always searches.
138 */
139 export function resolveSearchUrlTemplate(settings: {
140 readonly browserSearchEngine: BrowserSearchEngine;
141 readonly browserCustomSearchUrl: string;
142 }): string {
143 if (settings.browserSearchEngine !== "custom") {
144 return BROWSER_SEARCH_URL_TEMPLATES[settings.browserSearchEngine];
145 }
146 const custom = settings.browserCustomSearchUrl.trim();
147 return isValidSearchUrlTemplate(custom) ? custom : BROWSER_SEARCH_URL_TEMPLATES.duckduckgo;
148 }
149
150 export function resolveAddressBarInput(
151 rawInput: string,
152 searchUrlTemplate: string = BROWSER_SEARCH_URL_TEMPLATES.duckduckgo,
153 ): string {
154 const trimmed = rawInput.trim();
155 if (URL_SCHEME_WITH_AUTHORITY_PATTERN.test(trimmed) || trimmed.length === 0)
156 return normalizePreviewUrl(trimmed);
157 if (!/\s/.test(trimmed)) {
158 // Reject explicit schemes before URL normalization can misread mailto as bare-host credentials.
159 const protocol = previewUrlProtocol(trimmed);
160 if (
161 protocol !== undefined &&
162 (KNOWN_NON_WEB_SCHEMES.has(protocol) || !BARE_HOST_PORT_PATTERN.test(trimmed))
163 ) {
164 if (protocol !== "http:" && protocol !== "https:") {
165 throw new PreviewUrlNormalizationError({
166 inputLength: rawInput.length,
167 reason: "unsupported-protocol",
168 protocol,
169 });
170 }
171 return normalizePreviewUrl(trimmed);
172 }
173 const authority = trimmed.split(/[/?#]/, 1)[0] ?? "";
174 const host = authority.replace(/^[^@]*@/, "").replace(/:\d+$/, "");
175 const hasPort = host.length < authority.replace(/^[^@]*@/, "").length;
176 if (hasPort || ADDRESS_HOST_PATTERN.test(host) || /^[^.]+(?:\.[^.]+)+\.?$/.test(host)) {
177 try {
178 return normalizePreviewUrl(trimmed);
179 } catch {}
180 }
181 }
182 return fillSearchUrlTemplate(searchUrlTemplate, trimmed);
183 }
184
185 export function normalizePreviewUrl(rawUrl: string): string {
186 const trimmed = rawUrl.trim();
187 if (trimmed.length === 0) {
188 throw new PreviewUrlNormalizationError({ inputLength: rawUrl.length, reason: "empty" });
189 }
190 const explicitProtocol = previewUrlProtocol(trimmed);
191 if (explicitProtocol !== undefined && KNOWN_NON_WEB_SCHEMES.has(explicitProtocol)) {
192 throw new PreviewUrlNormalizationError({
193 inputLength: rawUrl.length,
194 reason: "unsupported-protocol",
195 protocol: explicitProtocol,
196 });
197 }
198 const useHttp = LOOPBACK_PREFIX_PATTERN.test(trimmed);
199 const hasExplicitScheme = URL_SCHEME_WITH_AUTHORITY_PATTERN.test(trimmed);
200 const candidate = hasExplicitScheme ? trimmed : `${useHttp ? "http" : "https"}://${trimmed}`;
201 let parsed: URL;
202 try {
203 parsed = new URL(candidate);
204 } catch (cause) {
205 throw new PreviewUrlNormalizationError({
206 inputLength: rawUrl.length,
207 reason: "parse",
208 protocol: previewUrlProtocol(candidate),
209 cause,
210 });
211 }
212 if (parsed.protocol !== "http:" && parsed.protocol !== "https:") {
213 throw new PreviewUrlNormalizationError({
214 inputLength: rawUrl.length,
215 reason: "unsupported-protocol",
216 protocol: parsed.protocol,
217 });
218 }
219 // Re-parse rather than swap the protocol so an explicit :443 survives as a non-default HTTP port.
220 if (!hasExplicitScheme && !useHttp && isLocalLoopbackHost(parsed.hostname)) {
221 return new URL(`http://${trimmed}`).href;
222 }
223 return parsed.href;
224 }