Skip to main content

Mountain/Binary/Build/
LocalhostPlugin.rs

1//! # Localhost Plugin Module
2//!
3//! Configures and creates the Tauri localhost plugin with CORS headers for
4//! Service Workers and an OTLP proxy for build-baked telemetry.
5
6use std::{
7	io::{Read, Write},
8	net::TcpStream,
9	time::Duration,
10};
11
12use tauri::plugin::TauriPlugin;
13
14/// OTLP collector host:port. OTELBridge.ts sends to `/v1/traces` (same-origin),
15/// this proxy forwards to the real collector via raw TCP. Zero CORS issues.
16///
17/// Currently unused - the OTLP proxy path requires `Response::set_handled` /
18/// `set_status` / `Request::body()` from a patched fork of
19/// `tauri-plugin-localhost`. After resetting the vendored copy to upstream
20/// (`Dependency/Tauri/Dependency/PluginsWorkspace/plugins/localhost`),
21/// those methods are gone;
22#[allow(dead_code)]
23const OTLP_HOST:&str = "127.0.0.1:4318";
24
25/// Resolve the correct `Content-Type` for a request URL by its file extension.
26///
27/// The vendored `tauri-plugin-localhost` asset resolver sometimes reports
28/// `text/html` for disk-served `.js` / `.css` assets, which breaks module
29/// loading in the webview (the browser refuses JS with `'text/html' is not a
30/// valid JavaScript MIME type'`). By pre-setting `Content-Type` in
31/// `on_request`, we guarantee the right MIME for the extensions the workbench
32/// actually loads; the patched plugin keeps our value instead of overwriting.
33///
34/// Fonts are listed explicitly. WKWebView is strict about font MIME types -
35/// when the asset resolver falls back to `application/octet-stream` for a
36/// `.ttf` (which `infer` does on some macOS versions because TrueType has
37/// no magic header), the browser silently refuses to use the font and the
38/// workbench renders icons as blank squares with no console error. The
39/// codicon font is the visible symptom; KaTeX and Seti fonts under
40/// `/Static/Application/extensions/...` follow the same path.
41///
42/// Returns `None` for unknown extensions so the plugin's `asset.mime_type`
43/// fallback still applies (images, WASM, etc.).
44fn MimeFromUrl(Url:&str) -> Option<&'static str> {
45	// Strip query string / fragment before extension match.
46	let Path = Url.split(['?', '#']).next().unwrap_or(Url);
47
48	let Extension = Path.rsplit('.').next()?.to_ascii_lowercase();
49
50	match Extension.as_str() {
51		"js" | "mjs" | "cjs" => Some("application/javascript; charset=utf-8"),
52		"css" => Some("text/css; charset=utf-8"),
53		"json" | "map" => Some("application/json; charset=utf-8"),
54		"html" | "htm" => Some("text/html; charset=utf-8"),
55		"svg" => Some("image/svg+xml"),
56		"wasm" => Some("application/wasm"),
57		"txt" => Some("text/plain; charset=utf-8"),
58		"ttf" => Some("font/ttf"),
59		"otf" => Some("font/otf"),
60		"woff" => Some("font/woff"),
61		"woff2" => Some("font/woff2"),
62		"eot" => Some("application/vnd.ms-fontobject"),
63		_ => None,
64	}
65}
66
67/// Forward a JSON body to the OTLP collector via raw HTTP/1.1 POST.
68/// Returns true if the collector accepted (2xx), false otherwise.
69///
70/// See `OTLP_HOST` for why this is currently unused.
71#[allow(dead_code)]
72fn ProxyToOTLP(Body:&[u8]) -> bool {
73	let Ok(mut Stream) = TcpStream::connect_timeout(&OTLP_HOST.parse().unwrap(), Duration::from_millis(500)) else {
74		return false;
75	};
76
77	let _ = Stream.set_write_timeout(Some(Duration::from_millis(500)));
78	let _ = Stream.set_read_timeout(Some(Duration::from_millis(500)));
79
80	let Request = format!(
81		"POST /v1/traces HTTP/1.1\r\nHost: {}\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: \
82		 close\r\n\r\n",
83		OTLP_HOST,
84		Body.len(),
85	);
86
87	if Stream.write_all(Request.as_bytes()).is_err() {
88		return false;
89	}
90	if Stream.write_all(Body).is_err() {
91		return false;
92	}
93
94	let mut ResponseBuffer = [0u8; 32];
95	let _ = Stream.read(&mut ResponseBuffer);
96	// Check for "HTTP/1.1 2" - any 2xx status
97	ResponseBuffer.starts_with(b"HTTP/1.1 2") || ResponseBuffer.starts_with(b"HTTP/1.0 2")
98}
99
100/// Creates and configures the localhost plugin with CORS headers preconfigured.
101///
102/// # CORS Configuration
103///
104/// - Access-Control-Allow-Origin: * (allows all origins)
105/// - Access-Control-Allow-Methods: GET, POST, OPTIONS, HEAD
106/// - Access-Control-Allow-Headers: Content-Type, Authorization, Origin, Accept
107///
108/// # OTLP Proxy
109///
110/// Requests to `/v1/traces` are forwarded to the local OTLP collector
111/// (Jaeger, OTEL Collector, etc.) so OTELBridge.ts can send telemetry
112/// without cross-origin issues. Uses raw TCP - no extra HTTP client dependency.
113pub fn LocalhostPlugin<R:tauri::Runtime>(ServerPort:u16) -> TauriPlugin<R> {
114	// Resolve the user's home directory once at startup. Used to seed
115	// the vendored localhost plugin's `extension_root` allowlist for
116	// the `/Extension/<abs-fs-path>` URL prefix, which serves
117	// extension-contributed assets (icon fonts, webview resources,
118	// images) directly from the user's extension installation dirs.
119	//
120	// Without this, every workbench `@font-face` rule emitted by
121	// `iconsStyleSheet.js` for a sideloaded extension (GitLens,
122	// dart-code, ...) lands as a missing-glyph blank box - the
123	// upstream URL is `vscode-file://vscode-app/<absolute-fs-path>`
124	// which WKWebView cannot resolve under Tauri. Land's Output
125	// transform `RewriteIconsStyleSheetURLs` rewrites those to
126	// `<origin>/Extension/<absolute-fs-path>`; this allowlist is
127	// the receiving end.
128	let HomeDirectory = std::env::var_os("HOME")
129		.or_else(|| std::env::var_os("USERPROFILE"))
130		.map(std::path::PathBuf::from);
131
132	let LandExtensionsRoot = HomeDirectory.as_ref().map(|Home| Home.join(".land/extensions"));
133	let VSCodeExtensionsRoot = HomeDirectory.as_ref().map(|Home| Home.join(".vscode/extensions"));
134
135	// Bundle-resident built-ins. When the app is shipped as a `.app`,
136	// the 93 built-in extensions live under
137	// `Contents/Resources/extensions/`. Without this entry their
138	// icon-stylesheet URLs (rewritten to `/Extension/<abs-path>`) are
139	// rejected by the localhost plugin's allowlist and render as blank
140	// boxes. Two probe paths cover both bundle conventions: the Tauri
141	// default (`Contents/Resources/extensions`) and the VS Code-style
142	// nested `Contents/Resources/app/extensions` some tooling produces.
143	// The repo-layout fallback covers raw `Target/release/<bin>`
144	// launches that resolve from inside the monorepo.
145	let ExeParent = std::env::current_exe()
146		.ok()
147		.and_then(|Exe| Exe.parent().map(|P| P.to_path_buf()));
148	let BundleExtensionsRoot = ExeParent.as_ref().and_then(|Parent| {
149		let Candidate = Parent.join("../Resources/extensions");
150		Candidate.canonicalize().ok().or(Some(Candidate))
151	});
152	let BundleExtensionsAppRoot = ExeParent.as_ref().and_then(|Parent| {
153		let Candidate = Parent.join("../Resources/app/extensions");
154		Candidate.canonicalize().ok().or(Some(Candidate))
155	});
156	let RepoExtensionsRoot = ExeParent.as_ref().and_then(|Parent| {
157		let Candidate = Parent.join("../../../Sky/Target/Static/Application/extensions");
158		Candidate.canonicalize().ok().or(Some(Candidate))
159	});
160
161	let mut Builder = tauri_plugin_localhost::Builder::new(ServerPort);
162	if let Some(Root) = LandExtensionsRoot {
163		Builder = Builder.extension_root(Root);
164	}
165	if let Some(Root) = VSCodeExtensionsRoot {
166		Builder = Builder.extension_root(Root);
167	}
168	if let Some(Root) = BundleExtensionsRoot {
169		Builder = Builder.extension_root(Root);
170	}
171	if let Some(Root) = BundleExtensionsAppRoot {
172		Builder = Builder.extension_root(Root);
173	}
174	if let Some(Root) = RepoExtensionsRoot {
175		Builder = Builder.extension_root(Root);
176	}
177
178	Builder
179		.on_request(|Request, Response| {
180			// CORS headers for Service Workers and frontend integration.
181			Response.add_header("Access-Control-Allow-Origin", "*");
182			Response.add_header("Access-Control-Allow-Methods", "GET, POST, OPTIONS, HEAD");
183			Response.add_header("Access-Control-Allow-Headers", "Content-Type, Authorization, Origin, Accept");
184
185			let Url = Request.url();
186
187			// LAND-PATCH B1.X: the upstream tauri-plugin-localhost `Response`
188			// only exposes `add_header` - no `set_handled` / `set_status`,
189			// and `Request` exposes only `url()` (no `body()`). Mountain's
190			// previous OTLP proxy + status override depended on a patched
191			// fork. After resetting the vendored copy to upstream those
192			// methods are gone. The OTLP proxy is moved to the dev OTEL
193			// collector (run separately from Tauri); the status override
194			// is no longer needed because the upstream plugin always emits
195			// 200 OK on a successful asset hit and the asset resolver's
196			// 404 path is sufficient for the un-mocked case.
197			//
198			// To restore the OTLP-proxy / status-override path, patch the
199			// vendored `tauri-plugin-localhost` (`Dependency/Tauri/
200			// Dependency/PluginsWorkspace/plugins/localhost/src/lib.rs`)
201			// to add `Response::set_handled(bool)`, `Response::set_status(
202			// u16)`, and `Request::body() -> &[u8]`.
203
204			// Pre-set the correct `Content-Type` for known asset extensions.
205			// The upstream plugin sets `Content-Type` from `asset.mime_type`
206			// before invoking the on_request callback, but the user-set
207			// value via `add_header` overrides it (HashMap insert).
208			if let Some(Mime) = MimeFromUrl(Url) {
209				Response.add_header("Content-Type", Mime);
210			}
211		})
212		.build()
213}