fix(plugins): run the scripts of plugin html views in release builds (#3087)

A view's html body was loaded as a srcdoc frame, which inherits the workbench CSP; its script-src 'self' blocks inline scripts, so in every build that serves the CSP html views rendered but ran no script. In the app the body is now written into a page of the openidea-plugin scheme (.frame) whose response carries only the frame's own policy, sandboxed as before. Web views already load from the scheme; notebook HTML output never runs scripts.
This commit is contained in:
l0ng-ai
2026-11-13 14:44:26 +08:00
committed by GitHub
parent 835c44615b
commit cdecb5916c
4 changed files with 112 additions and 9 deletions
+43
View File
@@ -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#"<!doctype html><meta charset="utf-8"><script>
addEventListener("message", (e) => {
const d = e.data;
if (e.source !== parent || !d || d.tag !== "openidea-view" || typeof d.document !== "string") return;
document.open();
document.write(d.document);
document.close();
});
parent.postMessage({ tag: "openidea-view", ready: true }, "*");
</script>"#;
/// `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<R: Runtime>(ctx: UriSchemeContext<'_, R>, request: Request<Vec<u8>
fn serve(plugins: &ide_host::plugins::PluginHost, path: &str) -> Response<Vec<u8>> {
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"<p>x</p>")).unwrap();
assert!(bare.starts_with("<script>(") && bare.ends_with("<p>x</p>"));
}
#[test]
fn the_frame_host_follows_the_workbench_frame() {
let frame = include_str!("../../src/features/plugins/views/frame.ts");
let csp = frame.split("FRAME_CSP =").nth(1).and_then(|s| s.split('"').nth(1)).unwrap();
assert_eq!(FRAME_HOST_CSP.strip_prefix("sandbox allow-scripts; ").unwrap(), csp);
let tag = frame.split("FRAME_TAG =").nth(1).and_then(|s| s.split('"').nth(1)).unwrap();
assert!(FRAME_HOST.contains(&format!("d.tag !== \"{tag}\"")), "{FRAME_HOST}");
assert!(frame.contains(&format!("FRAME_HOST_PATH = \"{FRAME_HOST_PATH}\"")));
}
}
@@ -0,0 +1,43 @@
import { describe, expect, it, vi } from "vitest";
import { render, waitFor } from "@testing-library/react";
import type { View } from "@/bindings";
import { createMemoryPluginsBackend, setPluginsBackend } from "../backend";
import { FRAME_TAG } from "../views/frame";
import { PluginView } from "../views/PluginView";
vi.mock("@/platform/ipc", async (original) => ({ ...(await original()), isTauri: () => true }));
describe("html bodies in the app", () => {
it("writes the document into the plugin scheme's host page, not a srcdoc that inherits the workbench CSP", async () => {
const view: View = {
toolbar: [],
body: { kind: "html", value: "<p>chart</p><script>draw()</script>" },
status: null,
};
setPluginsBackend({ ...createMemoryPluginsBackend([]), renderView: vi.fn(async () => view) });
const { container } = render(<PluginView pluginId="charts" view="chart" />);
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("<p>chart</p><script>draw()</script>") },
"*",
);
const doc = (post.mock.calls[0]![0] as { document: string }).document;
expect(doc).toContain('<meta http-equiv="Content-Security-Policy"');
expect(doc).toContain("window.openidea");
});
});
+19 -9
View File
@@ -18,6 +18,7 @@ import {
} from "react";
import clsx from "clsx";
import type { View, ViewEvent, ViewField, ViewTable, ViewTreeItem, Viewport } from "@/bindings";
import { isTauri } from "@/platform/ipc";
import { tx, VerbatimTextContext } from "@/platform/i18n";
import {
Checkbox,
@@ -34,9 +35,9 @@ import {
showContextMenu,
type MenuItem,
} from "@/ui";
import { pluginsBackend } from "../backend";
import { pluginsBackend, webSchemeUrl } from "../backend";
import { subscribeTheme, themeKey } from "@/platform/themeWatch";
import { FRAME_TAG, frameDocument, frameTheme, frameThemeMessage } from "./frame";
import { FRAME_HOST_PATH, FRAME_TAG, frameDocument, frameTheme, frameThemeMessage } from "./frame";
import { localizeView, usePluginT } from "../pluginText";
import { currentViewLocation, onViewMessage, useViewLocation, useViewRevision } from "./viewStore";
import { ServicePane } from "./ServicePane";
@@ -674,7 +675,10 @@ function HtmlBody({
const frame = useRef<HTMLIFrameElement>(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 ? (
<iframe
key={doc}
ref={frame}
className={styles.frame}
title={view}
sandbox="allow-scripts"
srcDoc={srcDoc}
src={host}
onLoad={postTheme}
/>
) : (
<iframe ref={frame} className={styles.frame} title={view} sandbox="allow-scripts" srcDoc={doc} onLoad={postTheme} />
);
}
+7
View File
@@ -19,6 +19,13 @@ export const FRAME_CSP =
/** Marks frame ↔ workbench messages. */
export const FRAME_TAG = "openidea-view";
/**
* The page of the `openidea-plugin` scheme that a rendered document is written into
* (src-tauri/src/plugin_web.rs). A `srcdoc` frame would inherit the workbench's CSP,
* which blocks inline scripts; this page has only {@link FRAME_CSP}.
*/
export const FRAME_HOST_PATH = ".frame";
/**
* The theme variables a frame gets: public name → IDE token. Part of the
* plugin API: names are only ever added, so the IDE's own tokens can change.