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