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.
TypeScript agentai-chatai-studioall-in-onecoding-agentdesktop-appfluximage-generationlinuxllmlocal-ailocal-llmopen-sourceprivacyself-hostedstable-diffusionuncensoreduncensored-aivideo-generationwindows
fix(chat): the HTML preview frame gets no hold on the app's invoke key (B29, Windows)
purplec1bc7984458b
diff --git a/e2e/html-preview-guard.spec.ts b/e2e/html-preview-guard.spec.tsnew file mode 100644index 00000000..e50ab90b--- /dev/null+++ b/e2e/html-preview-guard.spec.ts@@ -0,0 +1,155 @@+/**+ * B29 on Windows (I1, box 31.10.2026): WebView2 puts Tauri's init scripts into+ * every frame, the HTML preview's too. A model's page could then hook+ * `Headers`, call `invoke`, and read the app's invoke key off the header Tauri+ * sets. The preview server puts html_preview_guard.js in front of every page;+ * this proves in Chromium (the engine of WebView2) that the key stays put.+ *+ * Playwright's init script runs in every frame, as WebView2's does. It stands+ * in for Tauri 2.10.3's injection: the same non-configurable properties, the+ * key in a closure, `invoke` -> `postMessage` -> `new Headers` ->+ * `headers.set('Tauri-Invoke-Key', key)` -> `fetch`, and on a failed fetch the+ * `window.ipc.postMessage` path with the key in the message.+ *+ * Run: npx playwright test e2e/html-preview-guard.spec.ts --project=chromium+ */+import { test, expect, type Page } from '@playwright/test'+import { readFileSync } from 'node:fs'+import { dirname, resolve } from 'node:path'+import { fileURLToPath } from 'node:url'++const GUARD = readFileSync(resolve(dirname(fileURLToPath(import.meta.url)), '../src-tauri/src/html_preview_guard.js'), 'utf8')+const KEY = 'K3Y-of-the-app-0123456789'++function tauriLike(key: string) {+ const w = window as unknown as Record<string, unknown>+ const sent: { where: string; headerKey: string | null; viaIpc: boolean }[] = []+ Object.defineProperty(window, '__lu_sent', { value: sent })+ Object.defineProperty(window, 'isTauri', { value: true })+ Object.defineProperty(window, 'ipc', {+ // wry: `postMessage: s => window.chrome.webview.postMessage(s)`+ value: Object.freeze({+ postMessage: (s: string) => {+ sent.push({ where: location.href, headerKey: null, viaIpc: s.includes(key) })+ const c = (window as unknown as { chrome?: { webview?: { postMessage: (s: string) => void } } }).chrome+ if (c && c.webview) c.webview.postMessage(s)+ },+ }),+ })+ Object.defineProperty(window, '__TAURI_INTERNALS__', { value: { plugins: {} } })+ const internals = w.__TAURI_INTERNALS__ as Record<string, unknown>+ ;(function () {+ const __TAURI_INVOKE_KEY__ = key+ let failed = false+ function sendIpcMessage(message: { cmd: string; payload: unknown; options?: { headers?: Record<string, string> } }) {+ if (!failed) {+ const headers = new Headers((message.options && message.options.headers) || {})+ headers.set('Content-Type', 'application/json')+ headers.set('Tauri-Invoke-Key', __TAURI_INVOKE_KEY__)+ return fetch('http://ipc.localhost/' + message.cmd, { method: 'POST', body: JSON.stringify(message.payload), headers }).then(+ (r) => r,+ () => {+ failed = true+ return sendIpcMessage(message)+ },+ )+ }+ ;(window as unknown as { ipc: { postMessage: (s: string) => void } }).ipc.postMessage(+ JSON.stringify({ cmd: message.cmd, payload: message.payload, __TAURI_INVOKE_KEY__ }),+ )+ return Promise.resolve()+ }+ Object.defineProperty(internals, 'postMessage', { value: sendIpcMessage })+ Object.defineProperty(internals, 'invoke', {+ value: (cmd: string, payload: unknown) => new Promise((ok, no) => { try { sendIpcMessage({ cmd, payload }).then(ok, no) } catch (e) { no(e) } }),+ })+ })()+ // What reaches the "app": the transport records the header it was given.+ const realFetch = window.fetch+ Object.defineProperty(window, '__lu_fetch', { value: realFetch })+ window.fetch = ((url: string, init?: RequestInit) => {+ if (String(url).startsWith('http://ipc.localhost/')) {+ sent.push({ where: location.href, headerKey: new Headers(init?.headers).get('Tauri-Invoke-Key'), viaIpc: false })+ return Promise.resolve(new Response('{}'))+ }+ return realFetch(url, init)+ }) as typeof fetch+}++/** The model's page: every hook it can set after the guard, then `invoke`. */+const ATTACK = `<script>+ window.stolen = [];+ const grab = (v) => { if (typeof v === 'string' && v.indexOf('K3Y') === 0) window.stolen.push(v) };+ try { const P = Headers.prototype; const s = P.set; P.set = function (k, v) { grab(v); return s.call(this, k, v) } } catch (e) {}+ try { const P = Headers.prototype; const a = P.append; P.append = function (k, v) { grab(v); return a.call(this, k, v) } } catch (e) {}+ try { const R = Headers; window.Headers = function (i) { const h = new R(i); const s = h.set.bind(h); h.set = (k, v) => { grab(v); return s(k, v) }; return h } } catch (e) {}+ try { Object.defineProperty(window, 'Headers', { value: function (i) { return { set: (k, v) => grab(v), append: () => {} } } }) } catch (e) {}+ try { const d = Object.defineProperty; Object.defineProperty = function (o, k, x) { if (x && typeof x.value === 'function') return o; return d(o, k, x) } } catch (e) {}+ try { const ap = Reflect.apply; Reflect.apply = function (f, t, args) { (args || []).forEach(grab); return ap(f, t, args) } } catch (e) {}+ try { const tl = String.prototype.toLowerCase; String.prototype.toLowerCase = function () { return 'x' } } catch (e) {}+ try { window.fetch = (u, i) => { try { new (window.__lu_fetch ? Headers : Headers)(i && i.headers) } catch (e) {} ; return Promise.reject(new TypeError('blocked')) } } catch (e) {}+ try { window.chrome = { webview: { postMessage: (s) => grab(JSON.parse(s).__TAURI_INVOKE_KEY__) } } } catch (e) {}+ window.result = (async () => {+ let invoke = 'none'+ try { await window.__TAURI_INTERNALS__.invoke('log_write', { line: 'from the frame' }); invoke = 'resolved' } catch (e) { invoke = 'rejected: ' + e.message }+ try { await window.__TAURI_INTERNALS__.postMessage({ cmd: 'log_write', payload: {} }) } catch (e) {}+ return { invoke, stolen: window.stolen.slice(), internals: typeof window.__TAURI_INTERNALS__, sent: (window.__lu_sent || []).slice() }+ })()+</script>`++/** The app's window, loaded by navigation so the init script runs in it. */+async function open(page: Page, html: string) {+ await page.route('http://lu-app.test/', (r) => r.fulfill({ contentType: 'text/html', body: html }))+ await page.goto('http://lu-app.test/')+}++async function frameResult(page: Page, withGuard: boolean) {+ const doc = (withGuard ? `<script>${GUARD}</script>` : '') + ATTACK+ await open(page, `<iframe id="f" sandbox="allow-scripts"></iframe>`)+ await page.locator('#f').evaluate((f, d) => { (f as HTMLIFrameElement).srcdoc = d }, doc)+ const frame = await (await page.locator('#f').elementHandle())!.contentFrame()+ await expect.poll(async () => frame!.evaluate(() => typeof (window as unknown as { result?: unknown }).result)).toBe('object')+ return frame!.evaluate(() => (window as unknown as { result: Promise<{ invoke: string; stolen: string[]; internals: string; sent: unknown[] }> }).result)+}++test.describe('B29 preview guard (Windows: Tauri in every frame)', () => {+ test.beforeEach(async ({ page }) => {+ await page.addInitScript(tauriLike, KEY)+ })++ test('COUNTER-CHECK: without the guard the page reads the key', async ({ page }) => {+ const r = await frameResult(page, false)+ expect(r.stolen).toContain(KEY)+ })++ test('with the guard no hook gets the key, and no call reaches the app', async ({ page }) => {+ const r = await frameResult(page, true)+ expect(r.stolen).toEqual([])+ expect(r.invoke).toMatch(/^rejected: No app access from the preview/)+ // Nothing left the frame, neither over "fetch" nor over window.ipc.+ expect(r.sent).toEqual([])+ // The globals are there (non-configurable, as on WebView2) and of no use.+ expect(r.internals).toBe('object')+ })++ test('the app window keeps its IPC: the guard does nothing in a top frame', async ({ page }) => {+ await open(page, `<script>${GUARD}</script><p>app</p>`)+ const r = await page.evaluate(async () => {+ const t = (window as unknown as { __TAURI_INTERNALS__: { invoke: (c: string, p: unknown) => Promise<unknown> } }).__TAURI_INTERNALS__+ await t.invoke('log_write', { line: 'from the app' })+ return (window as unknown as { __lu_sent: { headerKey: string | null }[] }).__lu_sent+ })+ expect(r).toEqual([expect.objectContaining({ headerKey: KEY })])+ })++ test('a page of its own still builds headers and calls the network the normal way', async ({ page }) => {+ await open(page, `<iframe id="f" sandbox="allow-scripts"></iframe>`)+ const doc = `<script>${GUARD}</script><script>+ const h = new Headers({ 'X-A': '1' }); h.set('X-B', '2'); h.append('X-B', '3');+ window.out = { a: h.get('X-A'), b: h.get('X-B'), inst: h instanceof Headers, req: new Request('https://example.com/', { headers: h }).headers.get('X-B') }+ </script>`+ await page.locator('#f').evaluate((f, d) => { (f as HTMLIFrameElement).srcdoc = d }, doc)+ const frame = await (await page.locator('#f').elementHandle())!.contentFrame()+ await expect.poll(async () => frame!.evaluate(() => (window as unknown as { out?: unknown }).out)).toEqual({ a: '1', b: '2, 3', inst: true, req: '2, 3' })+ })+})diff --git a/src-tauri/src/html_preview.rs b/src-tauri/src/html_preview.rsindex 93424838..fa6f4206 100644--- a/src-tauri/src/html_preview.rs+++ b/src-tauri/src/html_preview.rs@@ -14,7 +14,8 @@//! 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.+//! The key is injected into the main frame only on macOS and Linux; for+//! Windows see [`GUARD`].//!//! What keeps the preview away from the app, in layers://!@@ -27,6 +28,10 @@//! `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`]).+//! * Every page starts with [`GUARD`], before any script of its own. WebView2+//! (Windows) puts Tauri's init scripts into every frame, so there the+//! frame has `__TAURI_INTERNALS__`, non-configurable. The guard locks the+//! one door a page could take the invoke key through (html_preview_guard.js).//! * 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;@@ -36,6 +41,43 @@ use std::sync::atomic::{AtomicBool, Ordering};use std::sync::{Arc, LazyLock, Mutex};use std::time::Duration;+/// The script in front of every page (see html_preview_guard.js).+pub const GUARD: &str = include_str!("html_preview_guard.js");++/// `doc` with [`GUARD`] as its first script. It goes right behind a leading+/// doctype (before it a script would switch the page to quirks mode), else at+/// the very start. Only whitespace and comments can stand in front of a+/// doctype, so no script of the page runs before the guard.+pub fn with_guard(doc: &str) -> String {+ let tag = format!("<script>{GUARD}</script>");+ let at = doctype_end(doc).unwrap_or(0);+ format!("{}{tag}{}", &doc[..at], &doc[at..])+}++/// Where a leading `<!doctype …>` ends, past BOM, whitespace and comments.+fn doctype_end(doc: &str) -> Option<usize> {+ let mut i = 0;+ let b = doc.as_bytes();+ if doc.starts_with('\u{feff}') {+ i = '\u{feff}'.len_utf8();+ }+ loop {+ while i < b.len() && b[i].is_ascii_whitespace() {+ i += 1;+ }+ if doc[i..].starts_with("<!--") {+ i += doc[i..].find("-->")? + 3;+ continue;+ }+ break;+ }+ let rest = doc.get(i..i + 9)?;+ if !rest.eq_ignore_ascii_case("<!doctype") {+ return None;+ }+ Some(i + doc[i..].find('>')? + 1)+}+/// 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;@@ -209,7 +251,7 @@ pub fn respond(method: &str, path: &str, host: Option<&str>, port: u16) -> (u16,("Cache-Control".into(), "no-store".into()),("Cross-Origin-Resource-Policy".into(), "same-origin".into()),],- doc.into_bytes(),+ with_guard(&doc).into_bytes(),)}@@ -385,4 +427,36 @@ mod tests {assert!(put("a".repeat(MAX_BYTES + 1), false).is_err());assert_eq!(running_port(), None, "a refused page starts no server");}++ /// Windows (I1, box 31.10.): Tauri's globals reach the frame there. The+ /// guard has to run before any script of the page, on every page served.+ #[test]+ fn every_page_starts_with_the_guard_before_its_own_scripts() {+ let _t = turn();+ let tag = format!("<script>{GUARD}</script>");+ for (doc, before) in [+ ("<!DOCTYPE html><html><head><script>evil()</script>", "<!DOCTYPE html>"),+ ("\u{feff} <!-- a --> <!doctype html>\n<script>evil()</script>", "\u{feff} <!-- a --> <!doctype html>"),+ ("<script>evil()</script><!DOCTYPE html>", ""),+ ("<p>no doctype</p><script>evil()</script>", ""),+ ("<!-- open comment <script>evil()</script>", ""),+ ("", ""),+ ] {+ let out = with_guard(doc);+ assert!(out.starts_with(&format!("{before}{tag}")), "{doc:?} -> {out:?}");+ assert_eq!(out.find("<script"), Some(before.len()), "{doc:?}");+ assert_eq!(out.replacen(&tag, "", 1), doc);+ }+ // And over the wire.+ let p = put("<!doctype html><script>evil()</script>".into(), false).unwrap();+ let port = running_port().unwrap();+ let (code, _, body) = respond("GET", &format!("/{}", p.id), Some(&format!("127.0.0.1:{port}")), port);+ assert_eq!(code, 200);+ let body = String::from_utf8(body).unwrap();+ assert!(body.starts_with(&format!("<!doctype html>{tag}<script>evil()")), "{body}");+ // The guard keeps the key's header out and leaves the app's window alone.+ assert!(GUARD.contains("if (window === window.top) return"));+ assert!(GUARD.contains("'tauri-invoke-key'"));+ }+}diff --git a/src-tauri/src/html_preview_guard.js b/src-tauri/src/html_preview_guard.jsnew file mode 100644index 00000000..84e2fe5e--- /dev/null+++ b/src-tauri/src/html_preview_guard.js@@ -0,0 +1,59 @@+// The first script of every page the HTML preview server hands out (B29,+// html_preview.rs puts it in front of the page's own). It runs before any+// script of the model's page.+//+// Why: WebView2 (Windows) puts Tauri's init scripts into every frame, the+// preview's too (wry: "scripts are always added to subframes regardless of+// the `for_main_frame_only` option"). Tauri defines `__TAURI_INTERNALS__` and+// its functions non-configurable there, so no script can take them away.+// What a page could do with them: replace `Headers` or `Headers.prototype.set`+// and call `invoke`. Tauri's IPC then hands the app's invoke key to+// `headers.set('Tauri-Invoke-Key', key)`, that is to the page.+//+// So this script:+// * deletes the Tauri globals wherever they can be deleted;+// * puts a `Headers` on the window that no page can replace or hook, whose+// `set` and `append` refuse the invoke key's header before the value goes+// anywhere. Tauri's IPC throws there, so the key never leaves its closure,+// and the fallback path (`window.ipc.postMessage`) is never reached.+// Everything it calls later is taken now, before the page can change it.+// The app's own window is never touched: the script does nothing in a top+// frame, and the preview page is only ever shown in a frame.+;(function () {+ if (window === window.top) return+ var names = ['__TAURI_INTERNALS__', '__TAURI__', '__TAURI_EVENT_PLUGIN_INTERNALS__', '__TAURI_IPC__', '__TAURI_METADATA__', 'isTauri']+ for (var i = 0; i < names.length; i++) {+ try { delete window[names[i]] } catch (e) { /* not configurable */ }+ }+ var Real = window.Headers+ if (typeof Real !== 'function') return+ var apply = Reflect.apply+ var define = Object.defineProperty+ var lower = String.prototype.toLowerCase+ var Str = String+ var Err = TypeError+ var realSet = Real.prototype.set+ var realAppend = Real.prototype.append+ var KEY = 'tauri-invoke-key'+ function refused(name) {+ return apply(lower, Str(name), []) === KEY+ }+ function SafeHeaders(init) {+ var h = new Real(init)+ define(h, 'set', {+ value: function (name, value) {+ if (refused(name)) throw new Err('No app access from the preview')+ return apply(realSet, h, [name, value])+ },+ })+ define(h, 'append', {+ value: function (name, value) {+ if (refused(name)) throw new Err('No app access from the preview')+ return apply(realAppend, h, [name, value])+ },+ })+ return h+ }+ SafeHeaders.prototype = Real.prototype+ define(window, 'Headers', { value: SafeHeaders, writable: false, configurable: false, enumerable: false })+})()