Skip to content

The all-in-one local AI studio for your desktop: chat, image and video generation and a coding agent in one free, open source app. Windows and Linux. No Docker, no terminal, no cloud required.

feat(chat): the HTML preview runs on a loopback server, not a scheme (B29, second wall)

purple5e8d39ee54a3
diff --git a/dev-server/__tests__/mlx-media-endpoint-coverage.test.ts b/dev-server/__tests__/mlx-media-endpoint-coverage.test.ts
index 0f592cce..46717557 100644
--- a/dev-server/__tests__/mlx-media-endpoint-coverage.test.ts
+++ b/dev-server/__tests__/mlx-media-endpoint-coverage.test.ts
@@ -211,9 +211,9 @@ describe('endpointMap covers every backendCall/invokeMedia site the frontend can
// from the system reaches the desktop app, never the browser build.
'hf_link_take',
// The chat's HTML preview page (B29, 3.0.9, lib/html-preview-source.ts).
- // Put up only behind isTauri(): the browser build loads the page as
- // srcdoc and has no scheme to serve it from.
- 'html_preview_put',
+ // Put up and closed only behind isTauri(): the browser build loads the
+ // page as srcdoc and has no loopback server to serve it from.
+ 'html_preview_close', 'html_preview_put',
'exit_app', 'file_read', 'find_orphan_downloads', 'fix_comfyui_cors', 'funnel_ping',
'get_comfy_gpu_status', 'get_current_time', 'import_local_model', 'install_character_trainer',
'install_lmstudio', 'install_lmstudio_status', 'install_method', 'install_python',
diff --git a/src-tauri/src/html_preview.rs b/src-tauri/src/html_preview.rs
index 4bcdceba..93424838 100644
--- a/src-tauri/src/html_preview.rs
+++ b/src-tauri/src/html_preview.rs
@@ -1,52 +1,69 @@
//! The page behind the chat's HTML preview (B29, 3.0.9).
//!
-//! Why a scheme of its own and not `srcdoc`: an `about:srcdoc` frame inherits
+//! Why a server of its own and not `srcdoc`: an `about:srcdoc` frame inherits
//! the policy of the page that holds it, and the app's policy says
//! `script-src 'self'`. The model's inline script was therefore never run in
-//! the shipped app, only in the browser build without that policy. A document
-//! served from `luprev://` has its own response and so its own policy, the one
-//! [`preview_csp`] writes, and nothing of the app's.
+//! the shipped app. A document served here has its own response and so its
+//! own policy, the one [`preview_csp`] writes, and nothing of the app's.
+//!
+//! Why 127.0.0.1 and not a custom scheme (owner decision 30.10.2026, "zweite
+//! Mauer"): Tauri counts every scheme the app registers as a LOCAL origin
+//! (`Webview::is_local_url`), so a frame on one would carry the app's ACL.
+//! `http://127.0.0.1:<port>` matches neither the app URL nor a registered
+//! scheme, so Tauri treats the frame as REMOTE, and no capability of this app
+//! names a remote URL (tested in `html-preview-b29.test.tsx`). What stays the
+//! one lock for the app's own commands is Tauri's invoke key: this app has no
+//! app ACL manifest, and Tauri checks the ACL for plugin commands only then.
+//! The key is injected into the main frame only.
//!
//! What keeps the preview away from the app, in layers:
//!
-//! * The frame is sandboxed without `allow-same-origin` (frontend, tested in
-//! `html-preview.test.ts`), and the response says the same once more with
-//! the CSP `sandbox` directive, so even a top-level load of the URL gets an
-//! opaque origin.
+//! * The frame is sandboxed without `allow-same-origin` (frontend), and the
+//! response says the same once more with the CSP `sandbox` directive.
//! * The policy has no `connect-src`, no `frame-src`, no `form-action`, no
-//! worker and no remote source of any kind. Network only when the user
-//! allowed it for this one preview, and then `https:` alone: never
-//! `http://localhost`, so Ollama, the engine and the app's own ports stay
-//! out of reach either way.
-//! * The page does not exist until the user clicks Preview: the frontend puts
-//! the document here at that moment ([`html_preview_put`]) and gets a fresh
-//! random id back. Opening a chat runs nothing.
-//! * The store keeps the last [`KEEP`] documents and nothing on disk.
-use std::borrow::Cow;
+//! worker and no remote source. Network only after the user allowed it for
+//! this one page, and then `https:` alone, never `http:` or localhost.
+//! * The server binds 127.0.0.1 on a random port, answers GET only, wants the
+//! `Host` it was reached under (no DNS rebinding) and a 128-bit token per
+//! page in the path. It starts with the first open preview and stops when
+//! the last one closes ([`html_preview_close`]).
+//! * The page does not exist until the user clicks Preview. Opening a chat
+//! runs nothing. Nothing is written to disk; at most [`KEEP`] pages live.
use std::collections::VecDeque;
-use std::sync::{LazyLock, Mutex};
-
-use tauri::http::{header, Request, Response, StatusCode};
-
-/// The scheme name. On Windows and Android Tauri serves it as
-/// `http://luprev.localhost/`, elsewhere as `luprev://localhost/`; the
-/// frontend builds the URL with `convertFileSrc(id, 'luprev')`.
-pub const SCHEME: &str = "luprev";
+use std::io::{Read, Write};
+use std::net::{Shutdown, TcpListener, TcpStream};
+use std::sync::atomic::{AtomicBool, Ordering};
+use std::sync::{Arc, LazyLock, Mutex};
+use std::time::Duration;
-/// How many previews stay servable. A reload asks for a new id, so this only
+/// How many previews stay servable. A reload asks for a new page, so this only
/// has to cover the frames that are open at the same time.
const KEEP: usize = 16;
/// The biggest document the preview takes. A model answer is far below.
pub const MAX_BYTES: usize = 2 * 1024 * 1024;
+/// The longest request head the server reads. A GET with a token is tiny.
+const MAX_HEAD: usize = 8 * 1024;
+
struct Entry {
id: String,
doc: String,
allow_network: bool,
}
-static STORE: LazyLock<Mutex<VecDeque<Entry>>> = LazyLock::new(|| Mutex::new(VecDeque::new()));
+struct Running {
+ port: u16,
+ stop: Arc<AtomicBool>,
+}
+
+#[derive(Default)]
+struct State {
+ pages: VecDeque<Entry>,
+ server: Option<Running>,
+}
+
+static STATE: LazyLock<Mutex<State>> = LazyLock::new(|| Mutex::new(State::default()));
/// The policy of a preview page.
///
@@ -81,18 +98,78 @@ fn new_id() -> String {
b.iter().map(|x| format!("{x:02x}")).collect()
}
-/// Keep `doc` for one preview and hand back its id.
-pub fn put(doc: String, allow_network: bool) -> Result<String, String> {
+/// What the frontend gets for one page.
+#[derive(serde::Serialize, Debug, Clone)]
+pub struct PreviewPage {
+ /// Hand back to [`close`] when the preview goes.
+ pub id: String,
+ /// `http://127.0.0.1:<port>/<id>`, the frame's src.
+ pub url: String,
+}
+
+/// Keep `doc` for one preview, start the server if it is not running, and
+/// hand back where the frame loads it.
+pub fn put(doc: String, allow_network: bool) -> Result<PreviewPage, String> {
if doc.len() > MAX_BYTES {
return Err("This page is too large to preview.".into());
}
+ let mut st = STATE.lock().map_err(|_| "preview store poisoned".to_string())?;
+ if st.server.is_none() {
+ st.server = Some(start()?);
+ }
+ let port = st.server.as_ref().map(|s| s.port).unwrap_or_default();
let id = new_id();
- let mut store = STORE.lock().map_err(|_| "preview store poisoned".to_string())?;
- store.push_back(Entry { id: id.clone(), doc, allow_network });
- while store.len() > KEEP {
- store.pop_front();
+ st.pages.push_back(Entry { id: id.clone(), doc, allow_network });
+ while st.pages.len() > KEEP {
+ st.pages.pop_front();
}
- Ok(id)
+ Ok(PreviewPage { url: format!("http://127.0.0.1:{port}/{id}"), id })
+}
+
+/// Forget one page. The last one closed stops the server.
+pub fn close(id: &str) {
+ let Ok(mut st) = STATE.lock() else { return };
+ st.pages.retain(|e| e.id != id);
+ if st.pages.is_empty() {
+ if let Some(s) = st.server.take() {
+ stop(s);
+ }
+ }
+}
+
+/// The port the server listens on, while it runs.
+#[cfg(test)]
+fn running_port() -> Option<u16> {
+ STATE.lock().ok().and_then(|s| s.server.as_ref().map(|r| r.port))
+}
+
+fn start() -> Result<Running, String> {
+ let listener = TcpListener::bind(("127.0.0.1", 0)).map_err(|e| format!("preview server: {e}"))?;
+ let port = listener.local_addr().map_err(|e| e.to_string())?.port();
+ let stop = Arc::new(AtomicBool::new(false));
+ let flag = stop.clone();
+ std::thread::Builder::new()
+ .name("html-preview".into())
+ .spawn(move || {
+ for conn in listener.incoming() {
+ if flag.load(Ordering::SeqCst) {
+ break;
+ }
+ if let Ok(s) = conn {
+ serve(s, port);
+ }
+ }
+ })
+ .map_err(|e| e.to_string())?;
+ tracing::info!(port, "html preview server started");
+ Ok(Running { port, stop })
+}
+
+fn stop(r: Running) {
+ r.stop.store(true, Ordering::SeqCst);
+ // Wake the blocking accept so the thread sees the flag and drops the socket.
+ let _ = TcpStream::connect_timeout(&([127, 0, 0, 1], r.port).into(), Duration::from_millis(300));
+ tracing::info!(port = r.port, "html preview server stopped");
}
/// The id from a request path: `/<32 hex>`, nothing else.
@@ -101,112 +178,211 @@ fn id_of(path: &str) -> Option<&str> {
(id.len() == 32 && id.bytes().all(|b| b.is_ascii_hexdigit())).then_some(id)
}
-/// Answer one request on the scheme.
-pub fn respond(path: &str) -> Response<Cow<'static, [u8]>> {
+/// One answer, as status, headers and body. Pure, so the tests read it whole.
+pub fn respond(method: &str, path: &str, host: Option<&str>, port: u16) -> (u16, Vec<(String, String)>, Vec<u8>) {
+ let closed = vec![
+ ("Content-Type".to_string(), "text/plain; charset=utf-8".to_string()),
+ ("Content-Security-Policy".to_string(), preview_csp(false)),
+ ];
+ if host != Some(format!("127.0.0.1:{port}").as_str()) {
+ return (403, closed, b"forbidden".to_vec());
+ }
+ if method != "GET" {
+ let mut h = closed;
+ h.push(("Allow".into(), "GET".into()));
+ return (405, h, b"method not allowed".to_vec());
+ }
let hit = id_of(path).and_then(|id| {
- let store = STORE.lock().ok()?;
- store.iter().find(|e| e.id == id).map(|e| (e.doc.clone(), e.allow_network))
+ let st = STATE.lock().ok()?;
+ st.pages.iter().find(|e| e.id == id).map(|e| (e.doc.clone(), e.allow_network))
});
let Some((doc, allow_network)) = hit else {
- return Response::builder()
- .status(StatusCode::NOT_FOUND)
- .header(header::CONTENT_TYPE, "text/plain; charset=utf-8")
- .header(header::CONTENT_SECURITY_POLICY, preview_csp(false))
- .body(Cow::Borrowed(&b"not found"[..]))
- .expect("static response");
+ return (404, closed, b"not found".to_vec());
};
- Response::builder()
- .status(StatusCode::OK)
- .header(header::CONTENT_TYPE, "text/html; charset=utf-8")
- .header(header::CONTENT_SECURITY_POLICY, preview_csp(allow_network))
- .header(header::X_CONTENT_TYPE_OPTIONS, "nosniff")
- .header(header::REFERRER_POLICY, "no-referrer")
- .header(header::CACHE_CONTROL, "no-store")
- .body(Cow::Owned(doc.into_bytes()))
- .expect("preview response")
+ (
+ 200,
+ vec![
+ ("Content-Type".into(), "text/html; charset=utf-8".into()),
+ ("Content-Security-Policy".into(), preview_csp(allow_network)),
+ ("X-Content-Type-Options".into(), "nosniff".into()),
+ ("Referrer-Policy".into(), "no-referrer".into()),
+ ("Cache-Control".into(), "no-store".into()),
+ ("Cross-Origin-Resource-Policy".into(), "same-origin".into()),
+ ],
+ doc.into_bytes(),
+ )
}
-/// The scheme handler Tauri calls.
-pub fn handle(request: Request<Vec<u8>>) -> Response<Cow<'static, [u8]>> {
- respond(request.uri().path())
+fn reason(code: u16) -> &'static str {
+ match code {
+ 200 => "OK",
+ 403 => "Forbidden",
+ 404 => "Not Found",
+ 405 => "Method Not Allowed",
+ _ => "Bad Request",
+ }
+}
+
+fn serve(mut s: TcpStream, port: u16) {
+ let _ = s.set_read_timeout(Some(Duration::from_secs(3)));
+ let _ = s.set_write_timeout(Some(Duration::from_secs(10)));
+ let mut head = Vec::with_capacity(512);
+ let mut buf = [0u8; 1024];
+ while !head.windows(4).any(|w| w == b"\r\n\r\n") {
+ match s.read(&mut buf) {
+ Ok(0) | Err(_) => break,
+ Ok(n) => head.extend_from_slice(&buf[..n]),
+ }
+ if head.len() > MAX_HEAD {
+ break;
+ }
+ }
+ let text = String::from_utf8_lossy(&head);
+ let mut lines = text.split("\r\n");
+ let mut first = lines.next().unwrap_or("").split_whitespace();
+ let method = first.next().unwrap_or("");
+ let path = first.next().unwrap_or("");
+ let host = lines
+ .take_while(|l| !l.is_empty())
+ .find_map(|l| l.split_once(':').filter(|(k, _)| k.trim().eq_ignore_ascii_case("host")).map(|(_, v)| v.trim().to_string()));
+ let (code, headers, body) = if method.is_empty() {
+ (400, Vec::new(), Vec::new())
+ } else {
+ respond(method, path, host.as_deref(), port)
+ };
+ let mut out = format!("HTTP/1.1 {code} {}\r\n", reason(code));
+ for (k, v) in &headers {
+ out.push_str(&format!("{k}: {v}\r\n"));
+ }
+ out.push_str(&format!("Content-Length: {}\r\nConnection: close\r\n\r\n", body.len()));
+ let _ = s.write_all(out.as_bytes());
+ let _ = s.write_all(&body);
+ let _ = s.shutdown(Shutdown::Both);
}
/// Put a document up for preview. Called on the user's click, never on load.
#[tauri::command]
-pub fn html_preview_put(doc: String, allow_network: bool) -> Result<String, String> {
+pub fn html_preview_put(doc: String, allow_network: bool) -> Result<PreviewPage, String> {
put(doc, allow_network)
}
+/// The preview went (closed, reloaded, network switched, chat left).
+#[tauri::command]
+pub fn html_preview_close(id: String) {
+ close(&id)
+}
+
#[cfg(test)]
mod tests {
use super::*;
- /// The store is one per process; the eviction test fills it, so the
- /// tests take turns instead of racing each other's ids out.
+ /// The state is one per process; the tests take turns.
static TURN: Mutex<()> = Mutex::new(());
- fn csp_of(r: &Response<Cow<'static, [u8]>>) -> String {
- r.headers().get(header::CONTENT_SECURITY_POLICY).unwrap().to_str().unwrap().to_string()
+ fn turn() -> std::sync::MutexGuard<'static, ()> {
+ let g = TURN.lock().unwrap_or_else(|e| e.into_inner());
+ let ids: Vec<String> = STATE.lock().unwrap().pages.iter().map(|e| e.id.clone()).collect();
+ for id in ids {
+ close(&id);
+ }
+ g
+ }
+
+ fn http(port: u16, raw: &str) -> String {
+ let mut s = TcpStream::connect(("127.0.0.1", port)).expect("connect");
+ s.write_all(raw.as_bytes()).unwrap();
+ let mut out = String::new();
+ let _ = s.read_to_string(&mut out);
+ out
+ }
+
+ fn csp_line(resp: &str) -> String {
+ resp.lines().find(|l| l.starts_with("Content-Security-Policy:")).unwrap_or("").to_string()
}
#[test]
- fn served_page_has_its_own_closed_policy() {
- let _turn = TURN.lock().unwrap_or_else(|e| e.into_inner());
- let id = put("<script>1</script>".into(), false).unwrap();
- let r = respond(&format!("/{id}"));
- assert_eq!(r.status(), StatusCode::OK);
- let csp = csp_of(&r);
- assert!(csp.contains("default-src 'none'"));
- assert!(csp.contains("connect-src 'none'"));
- assert!(csp.contains("frame-src 'none'"));
- assert!(csp.contains("form-action 'none'"));
- assert!(csp.contains("sandbox allow-scripts"));
+ fn served_over_loopback_with_its_own_closed_policy() {
+ let _t = turn();
+ let p = put("<script>1</script>".into(), false).unwrap();
+ let port = running_port().unwrap();
+ assert_eq!(p.url, format!("http://127.0.0.1:{port}/{}", p.id));
+ let r = http(port, &format!("GET /{} HTTP/1.1\r\nHost: 127.0.0.1:{port}\r\n\r\n", p.id));
+ assert!(r.starts_with("HTTP/1.1 200 OK"), "{r}");
+ assert!(r.ends_with("<script>1</script>"));
+ let csp = csp_line(&r);
+ for d in ["default-src 'none'", "connect-src 'none'", "frame-src 'none'", "form-action 'none'", "sandbox allow-scripts"] {
+ assert!(csp.contains(d), "{d} missing: {csp}");
+ }
assert!(!csp.contains("allow-same-origin"));
assert!(!csp.contains("http:"), "no plain http source, so no localhost: {csp}");
assert!(!csp.contains("https:"), "no network without the user's yes: {csp}");
assert!(!csp.contains("'self'"));
- assert_eq!(&r.body()[..], b"<script>1</script>");
}
#[test]
fn network_only_https_and_only_when_allowed() {
- let _turn = TURN.lock().unwrap_or_else(|e| e.into_inner());
- let id = put("x".into(), true).unwrap();
- let csp = csp_of(&respond(&format!("/{id}")));
+ let _t = turn();
+ let p = put("x".into(), true).unwrap();
+ let port = running_port().unwrap();
+ let (_, h, _) = respond("GET", &format!("/{}", p.id), Some(&format!("127.0.0.1:{port}")), port);
+ let csp = &h.iter().find(|(k, _)| k == "Content-Security-Policy").unwrap().1;
assert!(csp.contains("connect-src https:"));
- assert!(!csp.contains("http:"));
- assert!(!csp.contains("localhost"));
- assert!(!csp.contains("ws:"));
+ assert!(!csp.contains("http:") && !csp.contains("localhost") && !csp.contains("ws:"));
assert!(csp.contains("sandbox allow-scripts"));
}
#[test]
- fn unknown_or_malformed_ids_are_not_found() {
- let _turn = TURN.lock().unwrap_or_else(|e| e.into_inner());
- assert_eq!(respond("/").status(), StatusCode::NOT_FOUND);
- assert_eq!(respond("/../etc/passwd").status(), StatusCode::NOT_FOUND);
- assert_eq!(respond(&format!("/{}", "a".repeat(32))).status(), StatusCode::NOT_FOUND);
- let id = put("x".into(), false).unwrap();
- assert_eq!(respond(&format!("/{id}/x")).status(), StatusCode::NOT_FOUND);
+ fn only_get_only_its_own_host_only_known_tokens() {
+ let _t = turn();
+ let p = put("x".into(), false).unwrap();
+ let port = running_port().unwrap();
+ let host = format!("Host: 127.0.0.1:{port}");
+ assert!(http(port, &format!("POST /{} HTTP/1.1\r\n{host}\r\nContent-Length: 0\r\n\r\n", p.id)).starts_with("HTTP/1.1 405"));
+ assert!(http(port, &format!("GET /{} HTTP/1.1\r\nHost: evil.example:{port}\r\n\r\n", p.id)).starts_with("HTTP/1.1 403"));
+ assert!(http(port, &format!("GET /{} HTTP/1.1\r\n\r\n", p.id)).starts_with("HTTP/1.1 403"));
+ assert!(http(port, &format!("GET / HTTP/1.1\r\n{host}\r\n\r\n")).starts_with("HTTP/1.1 404"));
+ assert!(http(port, &format!("GET /{} HTTP/1.1\r\n{host}\r\n\r\n", "a".repeat(32))).starts_with("HTTP/1.1 404"));
+ assert!(http(port, &format!("GET /{}/x HTTP/1.1\r\n{host}\r\n\r\n", p.id)).starts_with("HTTP/1.1 404"));
+ assert!(http(port, &format!("GET /../etc/passwd HTTP/1.1\r\n{host}\r\n\r\n")).starts_with("HTTP/1.1 404"));
+ }
+
+ #[test]
+ fn the_server_runs_only_while_a_preview_is_open() {
+ let _t = turn();
+ assert_eq!(running_port(), None, "no server before the first preview");
+ let a = put("a".into(), false).unwrap();
+ let b = put("b".into(), false).unwrap();
+ let port = running_port().unwrap();
+ close(&a.id);
+ assert_eq!(running_port(), Some(port), "one preview still open");
+ let r = http(port, &format!("GET /{} HTTP/1.1\r\nHost: 127.0.0.1:{port}\r\n\r\n", a.id));
+ assert!(r.starts_with("HTTP/1.1 404"), "a closed page is gone");
+ close(&b.id);
+ assert_eq!(running_port(), None);
+ std::thread::sleep(Duration::from_millis(200));
+ assert!(TcpStream::connect(("127.0.0.1", port)).is_err(), "the port is closed after the last preview");
}
#[test]
- fn ids_are_fresh_and_old_pages_drop_out() {
- let _turn = TURN.lock().unwrap_or_else(|e| e.into_inner());
+ fn tokens_are_fresh_and_old_pages_drop_out() {
+ let _t = turn();
let first = put("first".into(), false).unwrap();
- let mut ids = vec![first.clone()];
+ let mut ids = vec![first.id.clone()];
for i in 0..KEEP {
- ids.push(put(format!("p{i}"), false).unwrap());
+ ids.push(put(format!("p{i}"), false).unwrap().id);
}
let unique: std::collections::HashSet<_> = ids.iter().collect();
assert_eq!(unique.len(), ids.len());
- assert_eq!(respond(&format!("/{first}")).status(), StatusCode::NOT_FOUND);
- assert_eq!(respond(&format!("/{}", ids.last().unwrap())).status(), StatusCode::OK);
+ let port = running_port().unwrap();
+ let host = Some(format!("127.0.0.1:{port}"));
+ assert_eq!(respond("GET", &format!("/{}", first.id), host.as_deref(), port).0, 404);
+ assert_eq!(respond("GET", &format!("/{}", ids.last().unwrap()), host.as_deref(), port).0, 200);
}
#[test]
fn oversized_documents_are_refused() {
- let _turn = TURN.lock().unwrap_or_else(|e| e.into_inner());
+ let _t = turn();
assert!(put("a".repeat(MAX_BYTES + 1), false).is_err());
+ assert_eq!(running_port(), None, "a refused page starts no server");
}
}
diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs
index 67859cad..72a408d0 100644
--- a/src-tauri/src/lib.rs
+++ b/src-tauri/src/lib.rs
@@ -650,9 +650,6 @@ pub fn run() {
use commands::mobile_guard::GuardExt as _;
builder
.manage(app_state)
- // The chat's HTML preview: its own scheme so its page carries its own
- // closed policy instead of inheriting the app's (html_preview.rs).
- .register_uri_scheme_protocol(html_preview::SCHEME, |_ctx, request| html_preview::handle(request))
.manage(commands::oauth::OauthPending::default())
// Entries marked `#[cfg(desktop)]` are not registered on a phone:
// ComfyUI's websocket, every installer, the character trainer, the
@@ -665,7 +662,10 @@ pub fn run() {
// commands/mobile_guard.rs), on the desktop it does nothing.
.mobile_guard()
.invoke_handler(tauri::generate_handler![
+ // The chat's HTML preview: a loopback page with its own closed
+ // policy, served while a preview is open (html_preview.rs).
html_preview::html_preview_put,
+ html_preview::html_preview_close,
// Hugging Face "Use this model": the page takes the waiting link
#[cfg(desktop)]
hf_link::hf_link_take,
diff --git a/src-tauri/tauri.conf.json b/src-tauri/tauri.conf.json
index 641f140c..146f5904 100644
--- a/src-tauri/tauri.conf.json
+++ b/src-tauri/tauri.conf.json
@@ -25,7 +25,7 @@
}
],
"security": {
- "csp": "default-src 'self' http://ipc.localhost; connect-src 'self' blob: http://ipc.localhost http://tauri.localhost http://localhost:* http://127.0.0.1:* https://lu-labs.ai https://lrrhheztdytyfpizvuup.supabase.co https://civitai.com https://*.civitai.com https://huggingface.co https://*.huggingface.co https://ollama.com https://openrouter.ai https://api.openai.com https://api.groq.com https://api.together.xyz https://api.deepseek.com https://api.mistral.ai https://api.anthropic.com ws://localhost:* ws://127.0.0.1:*; img-src 'self' data: blob: http://localhost:* http://127.0.0.1:* https://lrrhheztdytyfpizvuup.supabase.co https://*.civitai.com https://*.githubusercontent.com; media-src 'self' blob: http://localhost:* http://127.0.0.1:* https://lrrhheztdytyfpizvuup.supabase.co https://lu-labs.ai; font-src 'self' data:; style-src 'self' 'unsafe-inline'; script-src 'self' 'wasm-unsafe-eval'; frame-src 'self' luprev: http://luprev.localhost"
+ "csp": "default-src 'self' http://ipc.localhost; connect-src 'self' blob: http://ipc.localhost http://tauri.localhost http://localhost:* http://127.0.0.1:* https://lu-labs.ai https://lrrhheztdytyfpizvuup.supabase.co https://civitai.com https://*.civitai.com https://huggingface.co https://*.huggingface.co https://ollama.com https://openrouter.ai https://api.openai.com https://api.groq.com https://api.together.xyz https://api.deepseek.com https://api.mistral.ai https://api.anthropic.com ws://localhost:* ws://127.0.0.1:*; img-src 'self' data: blob: http://localhost:* http://127.0.0.1:* https://lrrhheztdytyfpizvuup.supabase.co https://*.civitai.com https://*.githubusercontent.com; media-src 'self' blob: http://localhost:* http://127.0.0.1:* https://lrrhheztdytyfpizvuup.supabase.co https://lu-labs.ai; font-src 'self' data:; style-src 'self' 'unsafe-inline'; script-src 'self' 'wasm-unsafe-eval'; frame-src 'self' http://127.0.0.1:*"
}
},
"plugins": {
diff --git a/src-tauri/tauri.ios.conf.json b/src-tauri/tauri.ios.conf.json
index 5d4d0d27..4eaa2627 100644
--- a/src-tauri/tauri.ios.conf.json
+++ b/src-tauri/tauri.ios.conf.json
@@ -16,7 +16,7 @@
}
],
"security": {
- "csp": "default-src 'self' ipc: http://ipc.localhost; connect-src 'self' blob: ipc: http://ipc.localhost http://tauri.localhost http://localhost:* http://127.0.0.1:* https://lu-labs.ai https://lrrhheztdytyfpizvuup.supabase.co https://civitai.com https://*.civitai.com https://huggingface.co https://*.huggingface.co https://ollama.com https://openrouter.ai https://api.openai.com https://api.groq.com https://api.together.xyz https://api.deepseek.com https://api.mistral.ai https://api.anthropic.com ws://localhost:* ws://127.0.0.1:*; img-src 'self' data: blob: http://localhost:* http://127.0.0.1:* https://lrrhheztdytyfpizvuup.supabase.co https://*.civitai.com https://*.githubusercontent.com; media-src 'self' blob: http://localhost:* http://127.0.0.1:* https://lrrhheztdytyfpizvuup.supabase.co https://lu-labs.ai; font-src 'self' data:; style-src 'self' 'unsafe-inline'; script-src 'self' 'wasm-unsafe-eval'; frame-src 'self' luprev: http://luprev.localhost"
+ "csp": "default-src 'self' ipc: http://ipc.localhost; connect-src 'self' blob: ipc: http://ipc.localhost http://tauri.localhost http://localhost:* http://127.0.0.1:* https://lu-labs.ai https://lrrhheztdytyfpizvuup.supabase.co https://civitai.com https://*.civitai.com https://huggingface.co https://*.huggingface.co https://ollama.com https://openrouter.ai https://api.openai.com https://api.groq.com https://api.together.xyz https://api.deepseek.com https://api.mistral.ai https://api.anthropic.com ws://localhost:* ws://127.0.0.1:*; img-src 'self' data: blob: http://localhost:* http://127.0.0.1:* https://lrrhheztdytyfpizvuup.supabase.co https://*.civitai.com https://*.githubusercontent.com; media-src 'self' blob: http://localhost:* http://127.0.0.1:* https://lrrhheztdytyfpizvuup.supabase.co https://lu-labs.ai; font-src 'self' data:; style-src 'self' 'unsafe-inline'; script-src 'self' 'wasm-unsafe-eval'; frame-src 'self' http://127.0.0.1:*"
}
},
"bundle": {
diff --git a/src/components/chat/HtmlPreviewFrame.tsx b/src/components/chat/HtmlPreviewFrame.tsx
index 54d90be3..9cc7fa96 100644
--- a/src/components/chat/HtmlPreviewFrame.tsx
+++ b/src/components/chat/HtmlPreviewFrame.tsx
@@ -16,7 +16,7 @@ import { sandboxAttr } from '../../lib/file-preview'
interface FrameProps {
/** The page as text, loaded as srcdoc. Ignored when `src` is given. */
doc?: string
- /** The page on the `luprev` scheme (chat snippets in the app, B29). It
+ /** The page on the loopback preview server (chat snippets in the app, B29). It
* carries its own policy instead of inheriting the app's. */
src?: string
viewport: Viewport
diff --git a/src/components/chat/HtmlPreviewModal.tsx b/src/components/chat/HtmlPreviewModal.tsx
index 5142e750..bc103453 100644
--- a/src/components/chat/HtmlPreviewModal.tsx
+++ b/src/components/chat/HtmlPreviewModal.tsx
@@ -12,7 +12,8 @@ interface Props {
/**
* The large view of a snippet the MODEL produced (B29). The page and its
* rules are the inline panel's (HtmlPreviewPanel): scripts run, never with
- * `allow-same-origin`, on the `luprev` scheme with its own closed policy.
+ * `allow-same-origin`, from the loopback preview server with its own closed
+ * policy.
*
* The old "open in browser" button is gone: it handed a data: URL to
* openExternal, which refuses data: URLs, so it never did anything.
diff --git a/src/components/chat/__tests__/html-preview-b29.test.tsx b/src/components/chat/__tests__/html-preview-b29.test.tsx
index 09aafe94..0d4b9ed2 100644
--- a/src/components/chat/__tests__/html-preview-b29.test.tsx
+++ b/src/components/chat/__tests__/html-preview-b29.test.tsx
@@ -5,9 +5,13 @@
*
* - nothing runs when a chat is shown: no frame until the user clicks Preview;
* - the frame is sandboxed with scripts but never with same-origin;
- * - in the app the page comes from the `luprev` scheme, whose response has
- * its own closed policy (Rust tests in src-tauri/src/html_preview.rs), not
- * as srcdoc, which inherits the app policy and ran no script at all;
+ * - in the app the page comes from a loopback server on 127.0.0.1 with a
+ * token per page and its own closed policy (Rust tests in
+ * src-tauri/src/html_preview.rs), not as srcdoc, which inherits the app
+ * policy and ran no script at all, and not from a custom scheme, which
+ * Tauri counts as the app's own origin (owner decision 30.10.2026);
+ * - the server runs only while a preview is open: every page is closed;
+ * - no capability gives a remote origin anything;
* - the network is off and opens only after a second, explicit yes, for
* that one page;
* - the app's own policy is not loosened for it: it only allows the frame.
@@ -15,7 +19,7 @@
* Run: npx vitest run src/components/chat/__tests__/html-preview-b29.test.tsx
*/
import { describe, it, expect, afterEach, vi, beforeEach } from 'vitest'
-import { readFileSync } from 'node:fs'
+import { readFileSync, readdirSync } from 'node:fs'
import { resolve } from 'node:path'
import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'
@@ -25,12 +29,10 @@ vi.mock('../../../api/backend', async (orig) => ({
isTauri: () => tauri.on,
backendCall: async (cmd: string, args?: Record<string, unknown>) => {
tauri.calls.push({ cmd, args })
- return 'ab'.repeat(16)
+ const id = String(tauri.calls.filter((c) => c.cmd === 'html_preview_put').length).padStart(32, 'a')
+ return cmd === 'html_preview_put' ? { id, url: `http://127.0.0.1:51234/${id}` } : null
},
}))
-vi.mock('@tauri-apps/api/core', () => ({
- convertFileSrc: (path: string, protocol: string) => `${protocol}://localhost/${path}`,
-}))
import { CodeBlock } from '../CodeBlock'
import { putPreviewDocument } from '../../../lib/html-preview-source'
@@ -66,23 +68,44 @@ describe('B29: preview only on the user\'s click', () => {
})
})
-describe('B29: in the app the page comes from the luprev scheme', () => {
- it('the frame loads luprev://, not srcdoc, and the page went up with the network off', async () => {
+describe('B29: in the app the page comes from the loopback server', () => {
+ it('the frame loads http://127.0.0.1, not srcdoc, and the page went up with the network off', async () => {
tauri.on = true
const { container } = render(<CodeBlock code={PAGE} language="html" />)
fireEvent.click(screen.getByTestId('code-preview-button'))
await waitFor(() => expect(container.querySelector('iframe')).not.toBeNull())
const frame = container.querySelector('iframe')!
- expect(frame.getAttribute('src')).toBe(`luprev://localhost/${'ab'.repeat(16)}`)
+ expect(frame.getAttribute('src')).toBe(`http://127.0.0.1:51234/${'1'.padStart(32, 'a')}`)
expect(frame.hasAttribute('srcdoc')).toBe(false)
expect(tauri.calls).toEqual([{ cmd: 'html_preview_put', args: { doc: PAGE, allowNetwork: false } }])
})
+ it('leaving the preview closes its page, so the server can stop', async () => {
+ tauri.on = true
+ const { container, unmount } = render(<CodeBlock code={PAGE} language="html" />)
+ fireEvent.click(screen.getByTestId('code-preview-button'))
+ await waitFor(() => expect(container.querySelector('iframe')).not.toBeNull())
+ fireEvent.click(screen.getByTestId('code-preview-button'))
+ await waitFor(() => expect(tauri.calls.filter((c) => c.cmd === 'html_preview_close')).toHaveLength(1))
+ expect(tauri.calls.at(-1)).toEqual({ cmd: 'html_preview_close', args: { id: '1'.padStart(32, 'a') } })
+ // A reload replaces the page: the old one is closed, one stays open.
+ fireEvent.click(screen.getByTestId('code-preview-button'))
+ await waitFor(() => expect(container.querySelector('iframe')).not.toBeNull())
+ fireEvent.click(screen.getByRole('button', { name: 'Reload preview' }))
+ await waitFor(() => expect(tauri.calls.filter((c) => c.cmd === 'html_preview_put')).toHaveLength(3))
+ await waitFor(() => expect(tauri.calls.filter((c) => c.cmd === 'html_preview_close')).toHaveLength(2))
+ unmount()
+ await waitFor(() => expect(tauri.calls.filter((c) => c.cmd === 'html_preview_close')).toHaveLength(3))
+ const puts = tauri.calls.filter((c) => c.cmd === 'html_preview_put').length
+ expect(tauri.calls.filter((c) => c.cmd === 'html_preview_close')).toHaveLength(puts)
+ })
+
it('the network needs a second yes and goes up as a new page', async () => {
tauri.on = true
render(<CodeBlock code={PAGE} language="html" />)
fireEvent.click(screen.getByTestId('code-preview-button'))
await waitFor(() => expect(tauri.calls).toHaveLength(1))
+ tauri.calls = tauri.calls.filter((c) => c.cmd === 'html_preview_put')
fireEvent.click(screen.getByTestId('html-preview-network'))
// One click only asks.
const ask = screen.getByTestId('html-preview-network-ask')
@@ -97,8 +120,8 @@ describe('B29: in the app the page comes from the luprev scheme', () => {
expect(tauri.calls).toHaveLength(1)
fireEvent.click(screen.getByTestId('html-preview-network'))
fireEvent.click(screen.getByText('Allow for this page'))
- await waitFor(() => expect(tauri.calls).toHaveLength(2))
- expect(tauri.calls[1].args).toEqual({ doc: PAGE, allowNetwork: true })
+ await waitFor(() => expect(tauri.calls.filter((c) => c.cmd === 'html_preview_put')).toHaveLength(2))
+ expect(tauri.calls.filter((c) => c.cmd === 'html_preview_put')[1].args).toEqual({ doc: PAGE, allowNetwork: true })
expect(screen.getByTestId('html-preview-panel').dataset.network).toBe('on')
})
@@ -117,17 +140,27 @@ describe('B29: the app policy is not loosened for the preview', () => {
const csp: string = conf.app.security.csp
const directive = (name: string) => (csp.split(';').map((d) => d.trim()).find((d) => d.startsWith(name + ' ')) ?? '')
- it('frames may come from luprev, and from nowhere new besides', () => {
- expect(directive('frame-src').split(/\s+/).slice(1).sort()).toEqual(["'self'", 'http://luprev.localhost', 'luprev:'].sort())
+ it('frames may come from loopback, and from nowhere new besides', () => {
+ expect(directive('frame-src').split(/\s+/).slice(1).sort()).toEqual(["'self'", 'http://127.0.0.1:*'].sort())
+ expect(csp).not.toMatch(/luprev/)
})
it('the app itself still runs no inline script', () => {
- expect(directive('script-src')).not.toMatch(/unsafe-inline|luprev/)
+ expect(directive('script-src')).not.toMatch(/unsafe-inline|127\.0\.0\.1/)
})
- it('the scheme is registered and its command is in the handler list', () => {
+ it('no custom scheme any more: the frame must not count as the app to Tauri', () => {
const lib = readFileSync(resolve(root, 'src-tauri/src/lib.rs'), 'utf8')
- expect(lib).toMatch(/register_uri_scheme_protocol\(html_preview::SCHEME/)
+ expect(lib).not.toMatch(/register_uri_scheme_protocol|register_asynchronous_uri_scheme_protocol/)
expect(lib).toMatch(/html_preview::html_preview_put,/)
+ expect(lib).toMatch(/html_preview::html_preview_close,/)
+ })
+
+ it('no capability grants a remote origin anything', () => {
+ const dir = resolve(root, 'src-tauri/capabilities')
+ for (const f of readdirSync(dir).filter((n) => n.endsWith('.json'))) {
+ const cap = JSON.parse(readFileSync(resolve(dir, f), 'utf8'))
+ expect(cap.remote, `${f} has a remote section`).toBeUndefined()
+ }
})
})
diff --git a/src/components/chat/usePreviewSource.ts b/src/components/chat/usePreviewSource.ts
index ebf299c3..eaf36621 100644
--- a/src/components/chat/usePreviewSource.ts
+++ b/src/components/chat/usePreviewSource.ts
@@ -1,6 +1,6 @@
import { useEffect, useState } from 'react'
import { buildDocument } from '../../lib/html-preview'
-import { putPreviewDocument, type PreviewSource } from '../../lib/html-preview-source'
+import { closePreviewDocument, putPreviewDocument, type PreviewSource } from '../../lib/html-preview-source'
export type PreviewState =
| { status: 'loading' }
@@ -11,18 +11,28 @@ export type PreviewState =
* The page for a model snippet, put up when the preview mounts. A component
* that uses this only mounts on the user's click, so loading a chat runs
* nothing. Every reload and every change of the network switch asks for a new
- * page, so a page never keeps a permission it was not shown with.
+ * page, so a page never keeps a permission it was not shown with, and the old
+ * page is closed; unmounting closes the last one, which stops the server.
*/
export function usePreviewSource(code: string, language: string | undefined, allowNetwork: boolean, reloadKey: number): PreviewState {
const [state, setState] = useState<{ key: string; value: PreviewState } | null>(null)
const key = `${reloadKey}:${allowNetwork ? 1 : 0}`
useEffect(() => {
let live = true
+ let opened: PreviewSource | null = null
putPreviewDocument(buildDocument(code, language), allowNetwork).then(
- (source) => { if (live) setState({ key, value: { status: 'ready', source } }) },
+ (source) => {
+ // Gone before the page was up: close it at once.
+ if (!live) { closePreviewDocument(source); return }
+ opened = source
+ setState({ key, value: { status: 'ready', source } })
+ },
(err) => { if (live) setState({ key, value: { status: 'error', message: String(err instanceof Error ? err.message : err) } }) },
)
- return () => { live = false }
+ return () => {
+ live = false
+ if (opened) closePreviewDocument(opened)
+ }
// The code is read at the moment of the click and of every reload, not
// followed while a reply is still streaming in.
// eslint-disable-next-line react-hooks/exhaustive-deps
diff --git a/src/lib/html-preview-source.ts b/src/lib/html-preview-source.ts
index fd7e609a..d704b6b2 100644
--- a/src/lib/html-preview-source.ts
+++ b/src/lib/html-preview-source.ts
@@ -1,10 +1,14 @@
/**
* Where a chat HTML preview gets its page from (B29, 3.0.9).
*
- * In the app the page is put up on the `luprev` scheme (src-tauri/src/
- * html_preview.rs) and the frame loads it by URL. That response carries its
- * own closed policy; a srcdoc frame would inherit the app's, which allows no
- * inline script, so a generated page never ran in the installed app.
+ * In the app the page is put up on a loopback server (src-tauri/src/
+ * html_preview.rs, http://127.0.0.1:<random port>/<token>) and the frame
+ * loads it by URL. That response carries its own closed policy; a srcdoc
+ * frame would inherit the app's, which allows no inline script, so a
+ * generated page never ran in the installed app. Loopback and not a custom
+ * scheme because Tauri counts its registered schemes as the app's own origin;
+ * a frame on 127.0.0.1 is a remote origin to Tauri. The server runs while a
+ * preview is open: every page put up here is closed again by its caller.
*
* In the browser build there is no scheme. The page goes in as srcdoc with a
* closed policy as its first tag (same rule as the phone preview's
@@ -15,11 +19,8 @@
*/
import { isTauri, backendCall } from '../api/backend'
-/** The scheme the Rust side registers. */
-export const PREVIEW_SCHEME = 'luprev'
-
export type PreviewSource =
- | { kind: 'src'; src: string }
+ | { kind: 'src'; src: string; id: string }
| { kind: 'doc'; doc: string }
/** The closed policy of the browser fallback: inline script and style, pictures it carries, nothing else. */
@@ -34,16 +35,15 @@ export function withClosedPolicy(doc: string): string {
return doc.slice(0, at) + `<meta http-equiv="Content-Security-Policy" content="${FALLBACK_CSP}">` + doc.slice(at)
}
-/** The URL of a stored page: `luprev://localhost/<id>` on macOS and Linux,
- * `http://luprev.localhost/<id>` on Windows and Android (Tauri's own rule). */
-export async function previewUrl(id: string): Promise<string> {
- const { convertFileSrc } = await import('@tauri-apps/api/core')
- return convertFileSrc(id, PREVIEW_SCHEME)
-}
-
/** Put the document up for one preview and say how the frame loads it. */
export async function putPreviewDocument(doc: string, allowNetwork: boolean): Promise<PreviewSource> {
if (!isTauri()) return { kind: 'doc', doc: withClosedPolicy(doc) }
- const id = await backendCall<string>('html_preview_put', { doc, allowNetwork })
- return { kind: 'src', src: await previewUrl(id) }
+ const page = await backendCall<{ id: string; url: string }>('html_preview_put', { doc, allowNetwork })
+ return { kind: 'src', src: page.url, id: page.id }
+}
+
+/** The preview went. The last one closed stops the loopback server. */
+export function closePreviewDocument(source: PreviewSource): void {
+ if (source.kind !== 'src') return
+ void backendCall('html_preview_close', { id: source.id }).catch(() => {})
}