diff --git a/src-tauri/src/plugin_web.rs b/src-tauri/src/plugin_web.rs index c7698d652..9dabd6b71 100644 --- a/src-tauri/src/plugin_web.rs +++ b/src-tauri/src/plugin_web.rs @@ -6,6 +6,11 @@ //! and is immutable: the revision in the URL changes with the installed //! package. HTML gets a CSP of its own, in case a page navigates its frame to //! one: still sandboxed, still no network. +//! +//! [`FRAME_HOST_PATH`] is the page that the `html` bodies plugin code renders are +//! written into. A `srcdoc` frame would inherit the workbench's CSP, whose +//! `script-src` blocks the inline scripts of those bodies; a page of this scheme +//! has only the policy of its own response. use crate::state::AppState; use tauri::http::{Request, Response, StatusCode, header}; @@ -22,6 +27,25 @@ const HTML_CSP: &str = "sandbox allow-scripts; default-src 'none'; \ media-src openidea-plugin: http://openidea-plugin.localhost data: blob:; \ connect-src openidea-plugin: http://openidea-plugin.localhost data: blob:"; +/// The host page of `html` bodies: it tells the workbench it is ready and writes +/// the document it gets back (`frameDocument` in src/features/plugins/views/frame.ts). +pub const FRAME_HOST_PATH: &str = ".frame"; + +/// The policy of rendered `html` bodies (`FRAME_CSP` in frame.ts), sandboxed as their frame is. +const FRAME_HOST_CSP: &str = "sandbox allow-scripts; default-src 'none'; script-src 'unsafe-inline'; \ + style-src 'unsafe-inline'; img-src data:; font-src data:; media-src data:"; + +const FRAME_HOST: &str = r#""#; + /// `window.openidea` (one function expression taking the initial theme), the same /// source the workbench inlines into rendered `html` bodies. const BRIDGE: &str = include_str!("../../src/features/plugins/views/frame-bridge.js"); @@ -57,6 +81,15 @@ pub fn handle(ctx: UriSchemeContext<'_, R>, request: Request fn serve(plugins: &ide_host::plugins::PluginHost, path: &str) -> Response> { let decoded = percent_encoding::percent_decode_str(path.trim_start_matches('/')).decode_utf8_lossy(); + if decoded == FRAME_HOST_PATH { + return Response::builder() + .header(header::CONTENT_TYPE, "text/html; charset=utf-8") + .header(header::CONTENT_SECURITY_POLICY, FRAME_HOST_CSP) + .header(header::CACHE_CONTROL, "no-cache") + .header("X-Content-Type-Options", "nosniff") + .body(FRAME_HOST.as_bytes().to_vec()) + .unwrap_or_else(|_| status(StatusCode::INTERNAL_SERVER_ERROR)); + } let Some((plugin, rest)) = decoded.split_once('/') else { return status(StatusCode::NOT_FOUND) }; match plugins.web_file(plugin, rest) { Ok(file) => { @@ -104,4 +137,14 @@ mod tests { let bare = String::from_utf8(with_bridge(b"

x

")).unwrap(); assert!(bare.starts_with("" }, + status: null, + }; + setPluginsBackend({ ...createMemoryPluginsBackend([]), renderView: vi.fn(async () => view) }); + const { container } = render(); + await waitFor(() => expect(container.querySelector("iframe")).not.toBeNull()); + const frame = container.querySelector("iframe")!; + expect(frame.hasAttribute("srcdoc")).toBe(false); + expect(frame.getAttribute("src")).toMatch( + /^(openidea-plugin:\/\/localhost|http:\/\/openidea-plugin\.localhost)\/\.frame$/, + ); + expect(frame.getAttribute("sandbox")).toBe("allow-scripts"); + + const post = vi.spyOn(frame.contentWindow!, "postMessage"); + // Not from the frame: ignored. + window.dispatchEvent(new MessageEvent("message", { data: { tag: FRAME_TAG, ready: true }, source: window })); + expect(post).not.toHaveBeenCalled(); + + window.dispatchEvent( + new MessageEvent("message", { data: { tag: FRAME_TAG, ready: true }, source: frame.contentWindow }), + ); + expect(post).toHaveBeenCalledWith( + { tag: FRAME_TAG, document: expect.stringContaining("

chart

") }, + "*", + ); + const doc = (post.mock.calls[0]![0] as { document: string }).document; + expect(doc).toContain('(null); // The theme at load time is in the document; later changes are posted, so a // theme switch doesn't reload the frame and lose its state. - const srcDoc = useMemo(() => frameDocument(html, frameTheme()), [html]); + const doc = useMemo(() => frameDocument(html, frameTheme()), [html]); + // In the app the document is written into a page of the plugin scheme: a `srcdoc` frame + // would inherit the workbench's CSP, which blocks the document's inline scripts. + const host = isTauri() ? webSchemeUrl(FRAME_HOST_PATH) : null; const theme = useSyncExternalStore(subscribeTheme, themeKey, () => ""); const postTheme = useCallback( () => frame.current?.contentWindow?.postMessage(frameThemeMessage(frameTheme()), "*"), @@ -685,8 +689,10 @@ function HtmlBody({ useEffect(() => { const onMessage = (e: MessageEvent) => { if (e.source !== frame.current?.contentWindow) return; - const data = e.data as { tag?: unknown; text?: unknown } | null; - if (data?.tag === FRAME_TAG && typeof data.text === "string") send({ kind: "message", text: data.text }); + const data = e.data as { tag?: unknown; text?: unknown; ready?: unknown } | null; + if (data?.tag !== FRAME_TAG) return; + if (data.ready === true) frame.current?.contentWindow?.postMessage({ tag: FRAME_TAG, document: doc }, "*"); + else if (typeof data.text === "string") send({ kind: "message", text: data.text }); }; window.addEventListener("message", onMessage); const off = onViewMessage(pluginId, view, (text) => @@ -696,18 +702,22 @@ function HtmlBody({ window.removeEventListener("message", onMessage); off(); }; - }, [pluginId, view, send]); + }, [pluginId, view, send, doc]); // No `allow-same-origin`: an opaque origin without access to the IDE. - // `onLoad` re-sends the theme in case it changed between building `srcDoc` and the frame loading. - return ( + // `onLoad` re-sends the theme in case it changed between building the document and the frame loading. + // A new document loads a new frame (`key`), as a changed `srcdoc` does. + return host ? (