feat(plugins): let web views embed declared and granted origins (#5618)

A plugin web view, custom editor or editor panel can list origins in a new frames field (API 1.16). Each origin must be https (or http to a loopback host), name one exact host with no path, and be covered by a net: capability of the manifest, so the install page shows it. Pages under that declaration's directory are served with a frame-src of the declared origins the user granted, and are revalidated instead of cached immutable, so declining or revoking a host takes effect on the next load. Without frames the CSP is unchanged, the plugin page cannot widen it, and the embedded page keeps the frame's sandbox without window.openidea.

Closes #5523

Co-authored-by: Rhombicdodecahedron <[email protected]>
Цей коміт міститься в:
Alexis authored and GitHub committed 2026-11-24 23:08:23 +08:00
1 джерело ad81ff442e
коміт 0eef66d793
9 files changed
+351 -10

No files matched your search

Створено
+1
Переглянути файл
@@ -4515,6 +4515,7 @@ dependencies = [
"toml 0.9.12+spec-1.1.0",
"tracing",
"tracing-subscriber",
"url",
"uuid",
"windows-sys 0.61.2",
"zip",
+1
Переглянути файл
@@ -68,6 +68,7 @@ specta.workspace = true
specta-typescript.workspace = true
tokio = { workspace = true, features = ["io-std"] }
tracing.workspace = true
url = "2"
tracing-subscriber.workspace = true
parking_lot.workspace = true
dunce.workspace = true
+146 -3
Переглянути файл
@@ -36,6 +36,7 @@
//! priority = "default" # or "option": only through Open With
//! layout = "tab" # or "split" / "preview": beside the text editor
//! web = "web/index.html" # a web page from the package instead of rendered content
//! frames = ["https://example.com"] # API 1.16: origins the page may embed; each needs `net:<host>`
//!
//! [[contributes.editorPanels]]
//! id = "minimap"
@@ -641,6 +642,65 @@ struct ViewDecl {
/// A web page of the package (`web/index.html`) instead of content the code renders.
#[serde(default, skip_serializing_if = "Option::is_none")]
web: Option<String>,
/// Origins the web page may embed in `<iframe>`s (API 1.16).
#[serde(default, skip_serializing_if = "Vec::is_empty")]
frames: Vec<String>,
}
/// Most origins one web page may declare in `frames`.
const MAX_FRAMES: usize = 16;
/// Checks a web page's `frames` and returns them as origins (`https://host[:port]`).
/// Each is HTTPS, or HTTP to a loopback host, and must be covered by a `net:` or
/// `net.http:` capability of the manifest, so the install page lists it; the page
/// gets only the ones the user granted.
fn frame_origins(pkg: &Package, frames: &[String], web: bool, what: &str) -> Result<Vec<String>, String> {
if frames.is_empty() {
return Ok(Vec::new());
}
pkg.manifest.needs_api(&format!("{what}: `frames`"), 16)?;
if !web {
return Err(format!("{what}: `frames` is for a web page (`web`)"));
}
if frames.len() > MAX_FRAMES {
return Err(format!("{what}: at most {MAX_FRAMES} `frames`"));
}
let mut origins = Vec::new();
for frame in frames {
let origin = frame_origin(frame).map_err(|e| format!("{what}: frames: {frame:?}: {e}"))?;
let cap = ide_plugin::net_capability(&origin).map_err(|e| format!("{what}: frames: {frame:?}: {e}"))?;
if !pkg.manifest.capabilities.all().any(|c| c.covers(&cap)) {
return Err(format!("{what}: frames: {frame:?} needs the `{cap}` capability (required or optional)"));
}
if !origins.contains(&origin) {
origins.push(origin);
}
}
Ok(origins)
}
/// `https://host[:port]` (or `http://` to a loopback host) with nothing after it.
fn frame_origin(frame: &str) -> Result<String, String> {
let url = url::Url::parse(frame).map_err(|e| format!("not a URL ({e})"))?;
let loopback = matches!(
url.host(),
Some(url::Host::Domain("localhost")) | Some(url::Host::Ipv4(std::net::Ipv4Addr::LOCALHOST))
) || url.host() == Some(url::Host::Ipv6(std::net::Ipv6Addr::LOCALHOST));
match url.scheme() {
"https" => {}
"http" if loopback => {}
_ => return Err("an origin is https://, or http:// to localhost".into()),
}
if url.host_str().is_none_or(|h| h.contains('*')) {
return Err("name one exact host".into());
}
if !url.username().is_empty() || url.password().is_some() {
return Err("no user name or password".into());
}
if url.path() != "/" || url.query().is_some() || url.fragment().is_some() {
return Err("an origin only: no path, query or fragment".into());
}
Ok(url.origin().ascii_serialization())
}
/// The files of a `web` entry, or a check that the code renders the view.
@@ -655,7 +715,7 @@ fn web_or_code(pkg: &Package, web: Option<&str>, what: &str) -> Result<Vec<PathB
}
pub(super) fn view(pkg: &Package, decl: toml::Value) -> Result<UiDecl, String> {
let d: ViewDecl = decode(VIEWS, decl)?;
let mut d: ViewDecl = decode(VIEWS, decl)?;
validate_item_id(&d.id, "view id")?;
title(VIEWS, &d.title)?;
if let Some(group) = &d.group {
@@ -668,6 +728,7 @@ pub(super) fn view(pkg: &Package, decl: toml::Value) -> Result<UiDecl, String> {
}
let files = web_or_code(pkg, d.web.as_deref(), &format!("view {:?}", d.id))?;
d.frames = frame_origins(pkg, &d.frames, d.web.is_some(), &format!("view {:?}", d.id))?;
if !["left", "right", "bottom", SERVICES_LOCATION].contains(&d.location.as_str()) {
return Err(format!("view {:?}: `location` is left, right, bottom or services", d.id));
}
@@ -734,6 +795,9 @@ struct CustomEditorDecl {
layout: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
web: Option<String>,
/// Origins the web page may embed (API 1.16).
#[serde(default, skip_serializing_if = "Vec::is_empty")]
frames: Vec<String>,
}
fn default_priority() -> String {
@@ -758,11 +822,12 @@ fn file_patterns(patterns: &[String], what: &str) -> Result<(), String> {
}
pub(super) fn custom_editor(pkg: &Package, decl: toml::Value) -> Result<UiDecl, String> {
let d: CustomEditorDecl = decode(CUSTOM_EDITORS, decl)?;
let mut d: CustomEditorDecl = decode(CUSTOM_EDITORS, decl)?;
validate_item_id(&d.id, "custom editor id")?;
title(CUSTOM_EDITORS, &d.title)?;
let what = format!("custom editor {:?}", d.id);
let files = web_or_code(pkg, d.web.as_deref(), &what)?;
d.frames = frame_origins(pkg, &d.frames, d.web.is_some(), &what)?;
file_patterns(&d.patterns, &what)?;
if d.priority != "default" && d.priority != "option" {
return Err(format!("{what}: `priority` is default or option"));
@@ -783,6 +848,9 @@ struct EditorPanelDecl {
width: u32,
#[serde(default, skip_serializing_if = "Option::is_none")]
when: Option<String>,
/// Origins the page may embed (API 1.16).
#[serde(default, skip_serializing_if = "Vec::is_empty")]
frames: Vec<String>,
}
const EDITOR_PANEL_WIDTH: std::ops::RangeInclusive<u32> = 40..=400;
@@ -791,7 +859,7 @@ const EDITOR_PANEL_WIDTH: std::ops::RangeInclusive<u32> = 40..=400;
/// editor group, beside its text editor. It sees each file the group shows, so it
/// needs `editor.read`.
pub(super) fn editor_panel(pkg: &Package, decl: toml::Value) -> Result<UiDecl, String> {
let d: EditorPanelDecl = decode(EDITOR_PANELS, decl)?;
let mut d: EditorPanelDecl = decode(EDITOR_PANELS, decl)?;
pkg.manifest.needs_api(&format!("contributes.{EDITOR_PANELS}"), 9)?;
validate_item_id(&d.id, "editor panel id")?;
let what = format!("editor panel {:?}", d.id);
@@ -805,6 +873,7 @@ pub(super) fn editor_panel(pkg: &Package, decl: toml::Value) -> Result<UiDecl, S
return Err(format!("{what}: needs the `editor.read` capability (the page sees the files editors show)"));
}
let files = super::web::web_files(pkg, &d.web, &what)?;
d.frames = frame_origins(pkg, &d.frames, true, &what)?;
let mut out = UiDecl::new(d.id.clone(), d.id.clone(), json(&d)?);
out.files = files;
Ok(out)
@@ -1333,6 +1402,80 @@ mod tests {
assert!(check(&optional).is_ok());
}
#[test]
fn web_pages_declare_frames_their_net_capabilities_cover() {
let dir = tempfile::tempdir().unwrap();
std::fs::create_dir(dir.path().join("web")).unwrap();
std::fs::write(dir.path().join("web/index.html"), "<iframe></iframe>").unwrap();
let header = "id = \"p\"\nname = \"P\"\nversion = \"1.0.0\"\nengines.openidea = \"^1.16\"\nwasm = \"p.wasm\"\n\
[capabilities]\nrequired = [\"editor.read\", \"net:example.com\", \"net:*.games.test\", \"net:localhost\"]\n";
let check = |point: &str, body: &str, header: &str| {
let manifest = ide_extension::Manifest::parse(&format!("{header}[[contributes.{point}]]\n{body}"))?;
let decl = manifest.declarations(point).into_iter().next().unwrap();
let pkg = Package::new(manifest, dir.path().to_path_buf());
match point {
VIEWS => view(&pkg, decl),
CUSTOM_EDITORS => custom_editor(&pkg, decl),
_ => editor_panel(&pkg, decl),
}
};
let view_with =
|frames: &str| format!("id = \"v\"\ntitle = \"V\"\nweb = \"web/index.html\"\nframes = {frames}\n");
let ok = check(
VIEWS,
&view_with(r#"["https://EXAMPLE.com/", "https://a.games.test:8443", "http://localhost:5173"]"#),
header,
)
.unwrap();
assert_eq!(
ok.json["frames"],
serde_json::json!(["https://example.com", "https://a.games.test:8443", "http://localhost:5173"])
);
assert!(
check(VIEWS, "id = \"v\"\ntitle = \"V\"\nweb = \"web/index.html\"\n", header)
.unwrap()
.json
.get("frames")
.is_none()
);
let editor = "id = \"e\"\ntitle = \"E\"\npatterns = [\"*.x\"]\nweb = \"web/index.html\"\nframes = [\"https://example.com\"]\n";
assert_eq!(
check(CUSTOM_EDITORS, editor, header).unwrap().json["frames"],
serde_json::json!(["https://example.com"])
);
let panel = "id = \"m\"\nweb = \"web/index.html\"\nwidth = 110\nframes = [\"https://example.com\"]\n";
assert_eq!(
check(EDITOR_PANELS, panel, header).unwrap().json["frames"],
serde_json::json!(["https://example.com"])
);
for (frames, error) in [
(r#"["https://other.com"]"#, "`net:other.com` capability"),
(r#"["https://games.test"]"#, "`net:games.test` capability"),
(r#"["http://example.com"]"#, "https://, or http:// to localhost"),
(r#"["ftp://example.com"]"#, "https://, or http:// to localhost"),
(r#"["https://example.com/room"]"#, "no path"),
(r#"["https://example.com?x"]"#, "no path"),
(r#"["https://example.com/#x"]"#, "no path"),
(r#"["https://*.games.test"]"#, "one exact host"),
(r#"["https://[email protected]"]"#, "user name"),
(r#"["example.com"]"#, "not a URL"),
(r#"["data:text/html,x"]"#, "https://"),
] {
let err = check(VIEWS, &view_with(frames), header).unwrap_err();
assert!(err.contains(error), "{frames} → {err}");
}
let many = format!("[{}]", vec!["\"https://example.com\""; 17].join(", "));
assert!(check(VIEWS, &view_with(&many), header).unwrap_err().contains("at most 16"));
let older = header.replace("^1.16", "^1.15");
assert!(check(VIEWS, &view_with(r#"["https://example.com"]"#), &older).unwrap_err().contains("1.16"));
let code_view = "id = \"v\"\ntitle = \"V\"\nframes = [\"https://example.com\"]\n";
assert!(check(VIEWS, code_view, header).unwrap_err().contains("for a web page"));
// `net:ask` is not a listed host: the install page would not show the origin.
let ask = header.replace("\"net:example.com\"", "\"net:ask\"");
assert!(check(VIEWS, &view_with(r#"["https://example.com"]"#), &ask).unwrap_err().contains("capability"));
}
fn package_with_catalogs(files: &[(&str, &str)]) -> (tempfile::TempDir, Package) {
let dir = tempfile::tempdir().unwrap();
std::fs::create_dir(dir.path().join(LOCALES_DIR)).unwrap();
+38 -1
Переглянути файл
@@ -121,6 +121,10 @@ pub(super) struct WebPtySession {
pub struct WebFile {
pub bytes: Vec<u8>,
pub mime: &'static str,
/// The origins a page may embed: `None` when no web page whose directory holds
/// the file declares `frames` (API 1.16), else the declared origins the user has
/// granted (`net:` / `net.http:`), possibly none.
pub frames: Option<Vec<String>>,
}
impl PluginHost {
@@ -324,6 +328,32 @@ impl PluginHost {
})
}
/// `frames` of the web pages whose directory holds `rel`, kept to those `granted`.
fn web_frames(&self, plugin: &str, rel: &str, granted: &[ide_extension::Capability]) -> Option<Vec<String>> {
let declared: Vec<String> = super::ui_points::WEB_POINTS
.iter()
.flat_map(|point| self.ui.items(point, Some(plugin)))
.filter(|item| {
let dir = item.decl.get("web").and_then(|w| w.as_str()).and_then(|e| e.rsplit_once('/'));
dir.is_some_and(|(dir, _)| rel.starts_with(&format!("{dir}/")))
})
.filter_map(|item| item.decl.get("frames").and_then(|f| f.as_array()).cloned())
.flatten()
.filter_map(|f| f.as_str().map(str::to_owned))
.collect();
if declared.is_empty() {
return None;
}
let mut allowed = Vec::new();
for origin in declared {
let ok = ide_plugin::net_capability(&origin).is_ok_and(|cap| granted.iter().any(|g| g.covers(&cap)));
if ok && !allowed.contains(&origin) {
allowed.push(origin);
}
}
Some(allowed)
}
/// The web roots `plugin` declares (entry directories, package-relative, `/`-terminated).
fn web_dirs(&self, plugin: &str) -> Vec<String> {
super::ui_points::WEB_POINTS
@@ -376,7 +406,14 @@ impl PluginHost {
return Err(IdeError::not_found(format!("{rel}: not part of a web view")));
}
let bytes = plugin.pkg.read_bytes(rel_path).map_err(IdeError::not_found)?;
Ok(WebFile { bytes, mime: mime(rel) })
let mime = mime(rel);
let frames = if mime.starts_with("text/html") {
let granted = plugin.meta.lock().granted.clone();
self.web_frames(plugin_id, rel, &granted)
} else {
None
};
Ok(WebFile { bytes, mime, frames })
}
}
+62
Переглянути файл
@@ -3902,6 +3902,68 @@ path = "templates/new.draw"
assert!(f.host.web_page("web-demo", "draw").is_err());
}
#[test]
fn web_pages_embed_only_declared_and_granted_frames() {
let f = fixture(Limits::default());
let tmp = tempfile::tempdir().unwrap();
let pkg = tmp.path().join("frame-demo");
for (path, text) in [
("hall/index.html", "<iframe src=\"https://play.games.test:8443/room\"></iframe>"),
("hall/rules.html", "<p>rules</p>"),
("hall/app.js", "console.log(1)"),
("panel/index.html", "<p>panel</p>"),
] {
std::fs::create_dir_all(pkg.join(path).parent().unwrap()).unwrap();
std::fs::write(pkg.join(path), text).unwrap();
}
std::fs::write(
pkg.join("plugin.toml"),
r#"id = "frame-demo"
name = "Frame Demo"
version = "1.0.0"
engines.openidea = "^1.16"
[capabilities]
optional = ["net:example.com", "net:*.games.test"]
[[contributes.views]]
id = "hall"
title = "Hall"
web = "hall/index.html"
frames = ["https://example.com/", "https://play.games.test:8443", "https://example.com"]
[[contributes.views]]
id = "panel"
title = "Panel"
web = "panel/index.html"
"#,
)
.unwrap();
let info = f.install(&pkg);
assert_eq!(info.status, PluginStatus::Static, "{:?}", info.error);
assert_eq!(
f.host.ui_items("views").iter().find(|v| v.decl["id"] == "hall").unwrap().decl["frames"],
serde_json::json!(["https://example.com", "https://play.games.test:8443"])
);
let page = f.host.web_page("frame-demo", "hall").unwrap();
let rev = page.path.strip_prefix("frame-demo/").unwrap().split_once('/').unwrap().0.to_owned();
let frames = |path: &str| f.host.web_file("frame-demo", &format!("{rev}/{path}")).unwrap().frames;
let both = Some(vec!["https://example.com".to_owned(), "https://play.games.test:8443".to_owned()]);
// Every page in the declaring view's directory, not its other files nor another view's pages.
assert_eq!(frames("hall/index.html"), both);
assert_eq!(frames("hall/rules.html"), both);
assert_eq!(frames("hall/app.js"), None);
assert_eq!(frames("panel/index.html"), None);
// Only what the user granted: declining a host takes it out of the policy.
f.host.set_capability("frame-demo", "net:example.com", false).unwrap();
assert_eq!(frames("hall/index.html"), Some(vec!["https://play.games.test:8443".to_owned()]));
f.host.set_capability("frame-demo", "net:*.games.test", false).unwrap();
assert_eq!(frames("hall/index.html"), Some(Vec::new()));
f.host.set_capability("frame-demo", "net:example.com", true).unwrap();
assert_eq!(frames("hall/index.html"), Some(vec!["https://example.com".to_owned()]));
}
#[test]
fn file_icons_without_patterns_require_api_1_8_and_project_assets() {
let f = fixture(Limits::default());
+23
Переглянути файл
@@ -270,6 +270,29 @@ corner actions (**Options**, **Hide**) and sets `--openidea-corner-inset-width`
}
```
**Embedded pages** (API 1.16). A web page can embed other sites in `<iframe>`s when its
declaration lists their origins in `frames`. Each origin is `https://host[:port]` (or
`http://` to `localhost`, `127.0.0.1` or `[::1]`), with no path, and must be covered by a
`net:<host>` capability of the manifest, so the install page shows it:
```toml
[capabilities]
optional = ["net:play.example.com"]
[[contributes.views]]
id = "hall"
title = "Game Hall"
web = "web/index.html"
frames = ["https://play.example.com"] # up to 16 origins
```
The pages of that directory get `frame-src` with the declared origins the user granted;
an origin whose capability is declined or revoked is left out, and without `frames` a page
can embed nothing. The embedded page keeps the frame's sandbox (scripts, an opaque origin,
no cookies or storage), gets no `window.openidea`, and the plugin's page still has no
network of its own. A site that refuses to be framed (`X-Frame-Options`,
`frame-ancestors`) stays blank.
[Graphviz](https://github.com/l0ng-ai/openidea/tree/main/plugins/official/graphviz) is a
complete example: a Vite + React page in `web-src/`, built into `web/` by
`plugins/build.sh official/graphviz`, whose code publishes the errors Graphviz reports as
+19
Переглянути файл
@@ -242,6 +242,25 @@ web = "web/index.html" # 页面;它所在的目录就是它能加载的范
}
```
**嵌入页面**(API 1.16)。在声明的 `frames` 中列出来源后,网页可以用 `<iframe>` 嵌入这些站点。每个来源写作
`https://host[:port]`(或指向 `localhost`、`127.0.0.1`、`[::1]` 的 `http://`),不带路径,并且必须被清单中的
`net:<host>` 权限覆盖,这样安装页面会列出它:
```toml
[capabilities]
optional = ["net:play.example.com"]
[[contributes.views]]
id = "hall"
title = "Game Hall"
web = "web/index.html"
frames = ["https://play.example.com"] # 最多 16 个来源
```
该目录下的页面获得的 `frame-src` 只包含用户已授权的声明来源;权限被拒绝或撤销的来源会被去掉,不声明 `frames`
的页面不能嵌入任何内容。被嵌入的页面保留框架的沙箱(可运行脚本、不透明源、没有 cookie 和存储),拿不到
`window.openidea`,插件页面自身仍然没有网络。拒绝被嵌入的站点(`X-Frame-Options`、`frame-ancestors`)会显示为空白。
[Graphviz](https://github.com/l0ng-ai/openidea/tree/main/plugins/official/graphviz) 是完整示例:`web-src/` 中的
Vite + React 页面由 `plugins/build.sh official/graphviz` 构建到 `web/`,插件代码把 Graphviz 报告的错误发布为问题。
+35 -3
Переглянути файл
@@ -154,9 +154,9 @@ work), but 0.1 code no longer runs: rebuild it against the 1.0 SDK.
| `keymaps` | `command`, `key`, `mac?` (`Ctrl+Alt+C`; a chord: `Meta+K Meta+C`); `key = "Escape"` with a required `when` (API 1.10) runs after the editor's own Escape handling | no |
| `statusBar` | `id`, `text`, `tooltip?`, `command?`, `align?`, `priority?` | no |
| `settings` | `schema` (JSON file) or `pages` (API 1.3), `title?` — see _Settings_ | no |
| `views` | `id`, `title`, `icon?` (an icon name or a package SVG), `location` (`left`, `right`, `bottom`, `services`), `web?` (_Web views_), `group?`, `when?` (API 1.3) | without `web` |
| `customEditors` | `id`, `title`, `patterns` (file names), `priority` (`default`, `option`), `layout?`, `web?` | without `web` |
| `editorPanels` | `id`, `web`, `width` (pixels, 40–400), `when?` — needs `editor.read` (API 1.9; _Editor panels_) | no |
| `views` | `id`, `title`, `icon?` (an icon name or a package SVG), `location` (`left`, `right`, `bottom`, `services`), `web?` (_Web views_), `frames?` (API 1.16), `group?`, `when?` (API 1.3) | without `web` |
| `customEditors` | `id`, `title`, `patterns` (file names), `priority` (`default`, `option`), `layout?`, `web?`, `frames?` (API 1.16) | without `web` |
| `editorPanels` | `id`, `web`, `width` (pixels, 40–400), `when?`, `frames?` (API 1.16) — needs `editor.read` (API 1.9; _Editor panels_) | no |
| `fileIcons` | `id`, `patterns` (file names), `icon` (SVG), `iconDark?` — whatever icon theme is in use | no |
| `fileTemplates` | `id`, `name`, `extension`, `path`; API 1.3: `fileName`, `variables = [{ name, prompt }]` — New menu | no |
| `commitChecks` | `id`, `title` — a before-commit check in Commit Options (see _Commits_) | yes |
@@ -442,6 +442,10 @@ matching SDK. Plugins for 1.15 and earlier keep working. New in 1.16:
incomplete again, with the new text, and keeps the language server's list
(when it was complete) and the other plugins' items. Plugins without the
export keep one request, then filtering.
- [Web views](#web-views) can embed other sites: `frames = ["https://…"]` on a
view, custom editor or editor panel lists the origins, each covered by a
`net:<host>` capability; the page's `frame-src` holds the ones the user
granted.
### API 1.15
@@ -2143,6 +2147,34 @@ For example, a page can reserve the corner in its own toolbar:
}
```
With API 1.16 (`engines.openidea = "^1.16"`) a web page can embed other sites
in `<iframe>`s: list their origins in the declaration's `frames` (views, custom
editors and editor panels, up to 16). An origin is `https://host[:port]`, or
`http://` to `localhost` / `127.0.0.1` / `[::1]`, with no path, query or
fragment, and must be covered by a `net:<host>` (or `net.http:<host>`)
capability of the manifest — `net:ask` does not count — so the install page
lists it:
```toml
[capabilities]
optional = ["net:play.example.com"]
[[contributes.views]]
id = "hall"
title = "Game Hall"
web = "web/index.html"
frames = ["https://play.example.com"]
```
The HTML files under that page's directory are served with `frame-src` set to
the declared origins whose capability the user granted (`frame-src 'none'`
when none is), and are revalidated rather than cached, so declining or
revoking a host takes it out on the next load. Without `frames` nothing can be
framed, as before. The embedded page inherits the frame's sandbox (scripts and
an opaque origin: no cookies or storage), never gets `window.openidea`, and
the plugin's own page still has no network. Sites that refuse framing
(`X-Frame-Options`, `frame-ancestors`) stay blank.
`plugins/official/graphviz` is a complete example: a Vite + React page in
`web-src/`, built into `web/` by `plugins/build.sh`, paired with code — the page renders (Graphviz compiled to WebAssembly) and
sends what Graphviz reports to the plugin, which publishes it as problems. The built page is not
+26 -3
Переглянути файл
@@ -5,7 +5,9 @@
//! any origin to read it (module scripts and fonts are fetched in CORS mode),
//! 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.
//! one: still sandboxed, still no network. A page whose declaration lists
//! `frames` (API 1.16) may also embed those origins the user granted; its HTML
//! is revalidated, since the grants can change while the revision stays.
//!
//! [`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
@@ -27,6 +29,15 @@ 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:";
/// [`HTML_CSP`], with a `frame-src` of `frames` when the page declares some.
fn html_csp(frames: Option<&[String]>) -> String {
match frames {
None => HTML_CSP.to_owned(),
Some([]) => format!("{HTML_CSP}; frame-src 'none'"),
Some(origins) => format!("{HTML_CSP}; frame-src {}", origins.join(" ")),
}
}
/// 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";
@@ -93,14 +104,15 @@ fn serve(plugins: &ide_host::plugins::PluginHost, path: &str) -> Response<Vec<u8
let Some((plugin, rest)) = decoded.split_once('/') else { return status(StatusCode::NOT_FOUND) };
match plugins.web_file(plugin, rest) {
Ok(file) => {
let cache = if file.frames.is_some() { "no-cache" } else { "public, max-age=31536000, immutable" };
let mut response = Response::builder()
.header(header::CONTENT_TYPE, file.mime)
.header(header::ACCESS_CONTROL_ALLOW_ORIGIN, "*")
.header(header::CACHE_CONTROL, "public, max-age=31536000, immutable")
.header(header::CACHE_CONTROL, cache)
.header("X-Content-Type-Options", "nosniff");
let mut body = file.bytes;
if file.mime.starts_with("text/html") {
response = response.header(header::CONTENT_SECURITY_POLICY, HTML_CSP);
response = response.header(header::CONTENT_SECURITY_POLICY, html_csp(file.frames.as_deref()));
body = with_bridge(&body);
}
response.body(body).unwrap_or_else(|_| status(StatusCode::INTERNAL_SERVER_ERROR))
@@ -138,6 +150,17 @@ mod tests {
assert!(bare.starts_with("<script>(") && bare.ends_with("<p>x</p>"));
}
#[test]
fn declared_frames_extend_only_frame_src() {
assert_eq!(html_csp(None), HTML_CSP);
assert!(!HTML_CSP.contains("frame-src"));
assert_eq!(html_csp(Some(&[])), format!("{HTML_CSP}; frame-src 'none'"));
let origins = ["https://example.com".to_owned(), "http://localhost:5173".to_owned()];
let csp = html_csp(Some(&origins));
assert_eq!(csp.strip_prefix(HTML_CSP).unwrap(), "; frame-src https://example.com http://localhost:5173");
assert!(csp.starts_with("sandbox allow-scripts; default-src 'none';"), "{csp}");
}
#[test]
fn the_frame_host_follows_the_workbench_frame() {
let frame = include_str!("../../src/features/plugins/views/frame.ts");