From f04fa100faa31f3a7eae1ad459ff8e34e768f856 Mon Sep 17 00:00:00 2001 From: LordMelkor Date: Thu, 19 Nov 2026 00:03:44 -0500 Subject: [PATCH] feat(plugins): let a plugin ask to reach a network origin at runtime A public plugin for a self-hosted service can't reach the server the person types, because host.request reaches only the origins fixed in the plugin's manifest. Add host.requestOrigin(origin): Promise. A dedicated native command checks the origin and the calling plugin, shows a native dialog naming the plugin and the origin, and saves the origin only when the person allows it. Plugin code shares the host's web view, so only a dialog the saving command shows proves the person answered. The save repeats its checks under the registry lock, so a plugin disabled, updated or removed while the dialog is open saves nothing. An origin the plugin already reaches resolves true with no dialog, declining resolves false, and a call while a dialog is open rejects. The dialog gets the plugin's name without control characters, which the Linux backend refuses and the Windows one ends the text at. On Linux the message escapes `%`, because GTK reads it as a printf format. Approved origins are stored per plugin and kept apart from host_grants: a separate grant read adds them only for host.request, byte reads and uploads, so gateway forwarding and every other grant check read the manifest alone. An install, update, reload or rollback keeps them only when the code comes from the same location and publisher. Settings and the agent enable dialog list them in the plugin's access review. Co-authored-by: Clod Co-Authored-By: Claude Opus 5.5 Signed-off-by: LordMelkor --- crates/plugin-manager/src/lib.rs | 378 ++++++++++++++++++++- crates/plugin-manager/src/managed.rs | 1 + docs/plugin-architecture.md | 28 ++ docs/plugin-authoring-guide.md | 32 ++ src-tauri/build.rs | 1 + src-tauri/capabilities/default.json | 1 + src-tauri/src/host_forward/tests.rs | 40 +++ src-tauri/src/host_request.rs | 87 ++++- src-tauri/src/host_request/origin_tests.rs | 153 +++++++++ src-tauri/src/host_request/replay_tests.rs | 33 ++ src-tauri/src/lib.rs | 4 +- src/app/AgentPluginRequests.test.tsx | 7 +- src/app/AgentPluginRequests.tsx | 4 +- src/app/PluginAccessReview.tsx | 15 + src/app/PluginMenu.tsx | 4 +- src/app/PluginUpdates.test.tsx | 13 + src/features/host/service.test.ts | 35 ++ src/features/host/service.ts | 22 ++ src/plugins/author.test.mjs | 1 + src/plugins/types.ts | 2 + 20 files changed, 842 insertions(+), 19 deletions(-) create mode 100644 src-tauri/src/host_request/origin_tests.rs diff --git a/crates/plugin-manager/src/lib.rs b/crates/plugin-manager/src/lib.rs index 32e5b2922a..fc496b9a52 100644 --- a/crates/plugin-manager/src/lib.rs +++ b/crates/plugin-manager/src/lib.rs @@ -29,6 +29,9 @@ const MAX_ICON_PIXELS: u64 = 1024 * 1024; pub const DEFAULT_HOST_COMMAND_OUTPUT_BYTES: u64 = 4096; pub const MAX_HOST_COMMAND_OUTPUT_BYTES: u64 = 1024 * 1024; pub const MAX_HOST_COMMAND_INPUT_BYTES: u64 = 64 * 1024; +/// Origins the person may approve for one plugin. Every host request reads +/// them, so the plugin's registry entry stays small. +const MAX_APPROVED_ORIGINS: usize = 64; #[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq)] #[serde(rename_all = "camelCase", deny_unknown_fields)] @@ -335,13 +338,7 @@ impl Manifest { } let mut origins = std::collections::HashSet::new(); for origin in &host.network_origins { - let url = url::Url::parse(origin).map_err(err)?; - if url.scheme() != "https" - || !url.username().is_empty() - || url.password().is_some() - || url.origin().ascii_serialization() != *origin - || !origins.insert(origin) - { + if valid_origin(origin).is_err() || !origins.insert(origin) { return Err("Invalid HTTPS origin declaration".into()); } } @@ -349,6 +346,40 @@ impl Manifest { Ok(()) } } +/// A bare HTTPS origin: no credentials, path, query or default port, so it +/// equals what a request URL's origin serializes to. +fn valid_origin(origin: &str) -> Result<()> { + const INVALID: &str = "Invalid HTTPS origin: use https://host[:port], with no path"; + let url = url::Url::parse(origin).map_err(|_| INVALID)?; + if url.scheme() != "https" + || !url.username().is_empty() + || url.password().is_some() + || url.origin().ascii_serialization() != origin + { + return Err(INVALID.into()); + } + Ok(()) +} +/// Whether two releases share a publisher (or are both unsigned) and an install +/// location, whatever version each pins, so origins the person approved for one +/// carry over to the other. An unknown source, such as a dropped folder, +/// matches nothing. +fn same_publisher_and_location( + (a, a_signature): (Option<&InstallSource>, Option<&Event>), + (b, b_signature): (Option<&InstallSource>, Option<&Event>), +) -> bool { + a_signature.map(|e| e.pubkey) == b_signature.map(|e| e.pubkey) + && match (a, b) { + (Some(InstallSource::Folder(a)), Some(InstallSource::Folder(b))) => { + a.root.join(&a.path) == b.root.join(&b.path) + } + (Some(InstallSource::Git(a)), Some(InstallSource::Git(b))) => { + a.repository == b.repository && a.path == b.path + } + (Some(InstallSource::Url(a)), Some(InstallSource::Url(b))) => a.url == b.url, + _ => false, + } +} pub fn valid_id(id: &str) -> Result<()> { if id.is_empty() || id.len() > 80 @@ -650,6 +681,10 @@ struct Installed { icon_png_revision: Option, #[serde(default, skip_serializing_if = "Option::is_none")] icon_jpg_revision: Option, + /// HTTPS origins the person approved for the plugin at runtime, beyond the + /// manifest's. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + approved_origins: Vec, } #[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq)] #[serde(rename_all = "camelCase", deny_unknown_fields)] @@ -916,6 +951,7 @@ pub struct PluginInfo { pub readme_revision: Option, pub icon_png_revision: Option, pub icon_jpg_revision: Option, + pub approved_origins: Vec, } #[derive(Default, Serialize)] @@ -1148,6 +1184,11 @@ impl Manager { if *id != p.manifest.id || is_reserved(id) { return Err("Invalid installed plugin identity".into()); } + if p.approved_origins.len() > MAX_APPROVED_ORIGINS + || p.approved_origins.iter().any(|o| valid_origin(o).is_err()) + { + return Err("Invalid approved origin".into()); + } valid_hash(&p.current)?; if let Some(h) = &p.previous { valid_hash(h)?; @@ -1227,6 +1268,7 @@ impl Manager { readme_revision: None, icon_png_revision: None, icon_jpg_revision: None, + approved_origins: Vec::new(), } }) .collect(); @@ -1267,6 +1309,7 @@ impl Manager { readme_revision: p.readme_revision, icon_png_revision: p.icon_png_revision, icon_jpg_revision: p.icon_jpg_revision, + approved_origins: p.approved_origins, }); } Ok(Catalog { @@ -1331,6 +1374,14 @@ impl Manager { }); let enabled = enable || old.is_some_and(|p| p.enabled); let update_checks = old.and_then(|p| p.update_checks); + let approved_origins = old + .filter(|p| { + same_publisher_and_location( + (p.current_source.as_ref(), p.current_signature.as_ref()), + (source.as_ref(), release.signature.as_ref()), + ) + }) + .map_or_else(Vec::new, |p| p.approved_origins.clone()); let previous_signature = old.and_then(|p| { if p.current == revision { p.previous_signature.clone() @@ -1354,6 +1405,7 @@ impl Manager { readme_revision, icon_png_revision, icon_jpg_revision, + approved_origins, }, ); self.save(®istry)?; @@ -1411,6 +1463,12 @@ impl Manager { return Err(SIGNED_ROLLBACK_ERROR.into()); } let a = self.artifact(id, &previous, p.previous_signature.as_ref())?; + if !same_publisher_and_location( + (p.current_source.as_ref(), p.current_signature.as_ref()), + (p.previous_source.as_ref(), p.previous_signature.as_ref()), + ) { + p.approved_origins.clear(); + } p.current = previous; p.current_signature = p.previous_signature.take(); p.current_source = p.previous_source.take(); @@ -1529,6 +1587,15 @@ impl Manager { plugin.current_signature.clone() }; atomic_write(&self.artifact_path(&manifest.id, &revision), &release.bytes)?; + if !same_publisher_and_location( + ( + plugin.current_source.as_ref(), + plugin.current_signature.as_ref(), + ), + (Some(&snapshot.1), release.signature.as_ref()), + ) { + plugin.approved_origins.clear(); + } plugin.manifest = manifest; plugin.current = revision; plugin.current_signature = release.signature; @@ -1585,7 +1652,87 @@ impl Manager { .host .unwrap_or_default()) } + /// `host_grants` plus the origins the person approved for this plugin at + /// runtime. Only `host.request`, its byte reads and uploads use it; every + /// other grant check reads the manifest alone. + pub fn request_grants(&self, id: &str, revision: &str) -> Result { + if revision == "bundled" { + return self.host_grants(id, revision); + } + let (artifact, approved) = self.current_artifact_with_approvals(id, revision)?; + let mut grants = artifact.manifest.host.unwrap_or_default(); + for origin in approved { + if !grants.network_origins.contains(&origin) { + grants.network_origins.push(origin); + } + } + Ok(grants) + } + /// Checks, before Buzz asks the person, that `id` at `revision` may add + /// `origin`. Returns the plugin's name to ask with, or `None` when the + /// plugin can already reach the origin. + pub fn origin_request(&self, id: &str, revision: &str, origin: &str) -> Result> { + let _lock = self.lock()?; + let mut registry = self.read()?; + Ok(self + .unreached_origin(&mut registry, id, revision, origin)? + .map(|p| p.manifest.name.clone())) + } + /// Saves `origin` for `id` once the person allowed it. The checks repeat + /// under this lock, so a plugin disabled, updated or removed while Buzz + /// asked saves nothing. + pub fn approve_origin(&self, id: &str, revision: &str, origin: &str) -> Result<()> { + let _lock = self.lock()?; + let mut registry = self.read()?; + if let Some(p) = self.unreached_origin(&mut registry, id, revision, origin)? { + p.approved_origins.push(origin.into()); + self.save(®istry)?; + } + Ok(()) + } + fn unreached_origin<'a>( + &self, + registry: &'a mut Registry, + id: &str, + revision: &str, + origin: &str, + ) -> Result> { + valid_origin(origin)?; + // `*` is a valid host character to the URL parser. + if origin.contains('*') { + return Err("Wildcard origins cannot be approved".into()); + } + if self.safe_mode { + return Err("External plugins are disabled in safe mode".into()); + } + let p = registry + .installed + .get_mut(id) + .ok_or("Plugin is not installed")?; + if !p.enabled || p.current != revision { + return Err("Plugin was disabled or updated; refresh the catalog".into()); + } + let declared = p + .manifest + .host + .as_ref() + .is_some_and(|host| host.network_origins.iter().any(|o| o == origin)); + if declared || p.approved_origins.iter().any(|o| o == origin) { + return Ok(None); + } + if p.approved_origins.len() >= MAX_APPROVED_ORIGINS { + return Err("Too many approved origins".into()); + } + Ok(Some(p)) + } fn current_artifact(&self, id: &str, revision: &str) -> Result { + Ok(self.current_artifact_with_approvals(id, revision)?.0) + } + fn current_artifact_with_approvals( + &self, + id: &str, + revision: &str, + ) -> Result<(Artifact, Vec)> { if self.safe_mode { return Err("External plugins are disabled in safe mode".into()); } @@ -1595,7 +1742,8 @@ impl Manager { if !p.enabled || p.current != revision { return Err("Plugin was disabled or updated; refresh the catalog".into()); } - self.artifact(id, revision, p.current_signature.as_ref()) + let artifact = self.artifact(id, revision, p.current_signature.as_ref())?; + Ok((artifact, p.approved_origins.clone())) } pub fn recover(&self) -> Result { { @@ -3113,6 +3261,220 @@ mod tests { ); } + #[test] + fn approved_origins_extend_only_that_plugins_requests_and_persist() { + let temp = tempfile::tempdir().unwrap(); + let manager = Manager::open(Some(temp.path().into()), "test", false).unwrap(); + let install = |id: &str, extra: &str| { + let source = temp.path().join(format!("build-{id}")); + fs::create_dir_all(&source).unwrap(); + fs::write(source.join("plugin.js"), "export function apply() {}").unwrap(); + fs::write( + source.join("manifest.json"), + format!( + r#"{{"id":"{id}","name":"Example","apiVersion":1,"host":{{"networkOrigins":["https://declared.example"{extra}]}}}}"# + ), + ) + .unwrap(); + let revision = manager + .install(&source) + .unwrap() + .plugins + .into_iter() + .find(|plugin| plugin.manifest.id == id) + .unwrap() + .revision; + manager.change("enable", id).unwrap(); + revision + }; + let first = install("example.first", ""); + let other = install("example.other", ""); + let origins = |m: &Manager, id: &str, revision: &str| { + m.request_grants(id, revision).unwrap().network_origins + }; + let origin = "https://mcp.example:8443"; + assert_eq!( + manager.origin_request("example.first", &first, origin), + Ok(Some("Example".into())) + ); + manager + .approve_origin("example.first", &first, origin) + .unwrap(); + // Once approved, or when the manifest declares it, there is nothing to ask. + for reached in [origin, "https://declared.example"] { + assert_eq!( + manager.origin_request("example.first", &first, reached), + Ok(None) + ); + } + let catalog = manager.catalog().unwrap(); + let info = catalog + .plugins + .iter() + .find(|plugin| plugin.manifest.id == "example.first") + .unwrap(); + assert_eq!(info.approved_origins, [origin]); + assert_eq!( + origins(&manager, "example.first", &first), + ["https://declared.example", origin] + ); + // Another plugin is not granted it. + assert_eq!( + origins(&manager, "example.other", &other), + ["https://declared.example"] + ); + + // It survives a restart and an update from the same folder. + let reopened = Manager::open(Some(temp.path().into()), "test", false).unwrap(); + assert!(origins(&reopened, "example.first", &first).contains(&origin.to_string())); + let updated = install("example.first", r#","https://extra.example""#); + assert_ne!(updated, first); + assert!(origins(&manager, "example.first", &updated).contains(&origin.to_string())); + + // A stale revision, safe mode and a disabled plugin all refuse. + let late = "https://late.example"; + assert!(manager + .origin_request("example.first", &first, late) + .is_err()); + let paused = Manager::open(Some(temp.path().into()), "test", true).unwrap(); + assert!(paused + .origin_request("example.first", &updated, late) + .is_err()); + manager.change("disable", "example.first").unwrap(); + assert!(manager + .origin_request("example.first", &updated, late) + .is_err()); + + // Removing the plugin forgets its origins for any reinstall. + manager.change("remove", "example.first").unwrap(); + let reinstalled = install("example.first", ""); + assert_eq!( + origins(&manager, "example.first", &reinstalled), + ["https://declared.example"] + ); + } + + #[test] + fn a_new_install_location_or_publisher_clears_approved_origins() { + let temp = tempfile::tempdir().unwrap(); + let manager = Manager::open(Some(temp.path().into()), "test", false).unwrap(); + let origin = "https://mcp.example"; + let key = "01".repeat(32); + let write = |id: &str, folder: &str, version: &str, key: Option<&str>| { + let source = temp.path().join(folder); + fs::create_dir_all(&source).unwrap(); + fs::write(source.join("plugin.js"), "export function apply() {}").unwrap(); + fs::write( + source.join("manifest.json"), + format!( + r#"{{"id":"{id}","name":"Example","description":"{version}","apiVersion":1}}"# + ), + ) + .unwrap(); + if let Some(key) = key { + super::sign_release(&source, key).unwrap(); + } + source + }; + let current = |id: &str| { + let catalog = manager.catalog().unwrap(); + let plugin = catalog.plugins.into_iter().find(|p| p.manifest.id == id); + plugin.unwrap().revision + }; + let install = |folder: &str, version: &str, key: Option<&str>| { + let source = write("example.page", folder, version, key); + manager.install(&source).unwrap(); + manager.change("enable", "example.page").unwrap(); + current("example.page") + }; + let approved = |id: &str| { + manager + .request_grants(id, ¤t(id)) + .unwrap() + .network_origins + }; + let approve = |id: &str| manager.approve_origin(id, ¤t(id), origin).unwrap(); + install("a", "1.0.0", None); + approve("example.page"); + install("a", "1.0.1", None); + assert_eq!(approved("example.page"), [origin]); + + install("a", "1.0.2", Some(&key)); + assert!(approved("example.page").is_empty()); + + approve("example.page"); + install("b", "1.0.3", Some(&key)); + assert!(approved("example.page").is_empty()); + + approve("example.page"); + manager.change("rollback", "example.page").unwrap(); + assert!(approved("example.page").is_empty()); + + // Reloading a folder that is now signed changes its publisher too. + let source = write("example.reload", "c", "1.0.0", None); + manager.install(&source).unwrap(); + manager.change("enable", "example.reload").unwrap(); + approve("example.reload"); + write("example.reload", "c", "1.0.1", Some(&key)); + manager.change("disable", "example.reload").unwrap(); + manager.reload("example.reload").unwrap(); + manager.change("enable", "example.reload").unwrap(); + assert!(approved("example.reload").is_empty()); + } + + #[test] + fn only_bare_https_origins_can_be_requested() { + let temp = tempfile::tempdir().unwrap(); + let manager = Manager::open(Some(temp.path().into()), "test", false).unwrap(); + let source = temp.path().join("build"); + fs::create_dir(&source).unwrap(); + fs::write(source.join("plugin.js"), "export function apply() {}").unwrap(); + fs::write( + source.join("manifest.json"), + r#"{"id":"example.page","name":"Example","apiVersion":1}"#, + ) + .unwrap(); + let revision = manager + .install(&source) + .unwrap() + .plugins + .pop() + .unwrap() + .revision; + manager.change("enable", "example.page").unwrap(); + for invalid in [ + "http://mcp.example", + "https://mcp.example/path", + "https://mcp.example/", + "https://mcp.example?q=1", + "https://user@mcp.example", + "https://mcp.example:443", + "https://*.example", + "ftp://mcp.example", + "mcp.example", + "", + ] { + assert!( + manager + .origin_request("example.page", &revision, invalid) + .is_err(), + "{invalid}" + ); + } + for n in 0..super::MAX_APPROVED_ORIGINS { + manager + .approve_origin("example.page", &revision, &format!("https://h{n}.example")) + .unwrap(); + } + assert!(manager + .origin_request("example.page", &revision, "https://one-too-many.example") + .is_err()); + // Bundled plugins have no registry entry to extend. + assert!(manager + .origin_request("buzz.reminders", "bundled", "https://mcp.example") + .is_err()); + } + #[test] fn reload_rejects_changed_host_grants_before_enable() { let temp = tempfile::tempdir().unwrap(); diff --git a/crates/plugin-manager/src/managed.rs b/crates/plugin-manager/src/managed.rs index be86f012eb..7c31ecd301 100644 --- a/crates/plugin-manager/src/managed.rs +++ b/crates/plugin-manager/src/managed.rs @@ -702,6 +702,7 @@ pub(crate) mod tests { readme_revision: None, icon_png_revision: None, icon_jpg_revision: None, + approved_origins: Vec::new(), } } fn git(repository: &str, commit: Option<&str>, path: &str) -> Option { diff --git a/docs/plugin-architecture.md b/docs/plugin-architecture.md index 320543808f..694361d5ac 100644 --- a/docs/plugin-architecture.md +++ b/docs/plugin-architecture.md @@ -2091,6 +2091,34 @@ for long operations such as Apps initialization. Archive uploads have a Existing bundled GitHub requests retain their first-party renderer fetch and CSP entry. +A plugin that needs an origin its manifest cannot name, such as the server URL +each person types for a self-hosted service, calls +`await host.requestOrigin?.("https://board.example.org")`. The +[authoring guide](plugin-authoring-guide.md#host-access-manifesthost) has a +settings-card recipe: the person types the address in the plugin's own +settings, the plugin calls this, and on `true` it calls `request`. The native +command shows a dialog, drawn by Buzz and parented to the window, that names +the plugin and the exact origin, with Allow and Don't Allow buttons. The prompt +is native because plugin modules run in the host's own web view: a prompt drawn +there, or a token minted there, is one plugin code could draw or mint itself, +so only a dialog shown by the command that saves proves the person answered. +The origin must be `https://host[:port]` with no path, credentials, default +port or wildcard, the same shape a manifest accepts. Native code checks it, +and that the plugin is installed, enabled and at the calling revision, before +it asks, and again under the registry lock when it saves, so a plugin +disabled, updated or removed while the dialog is open saves nothing. An origin +the manifest declares, or one already approved, resolves `true` without a +dialog. Declining resolves `false` and saves nothing. One dialog is open at a +time; a call while one is open rejects. An installed plugin may have up to 64 +approved origins. They are stored in the plugin registry beside the plugin, not +in its manifest, and only the `request`, byte and upload checks add them to +that plugin's declared origins. Every other grant, such as gateway forwarding, +reads the manifest alone. Approved origins survive restarts, updates, reloads +and rollbacks from the same install location (the same folder, Git repository and +path, or URL) and publisher (both unsigned or the same signer), and are cleared +otherwise. They are listed under "What this plugin can do" in Settings and are +forgotten when the plugin is removed. Approving one leaves the plugin running. + `host.requestOnce?.(request, { callId })` is an explicit opt-in, desktop-only POST primitive for non-idempotent submissions on compatible hosts. Ordinary `request`, byte GET/save, archive uploads, processes and publication do not diff --git a/docs/plugin-authoring-guide.md b/docs/plugin-authoring-guide.md index c580f3aa08..f8faecef66 100644 --- a/docs/plugin-authoring-guide.md +++ b/docs/plugin-authoring-guide.md @@ -218,9 +218,41 @@ Add `"host"` to `inject`, then: - `await ctx.host.runCommand("status", input?)` runs a declared command (no shell, 5 s deadline, stdin only if `maxInputBytes` is declared). It returns stdout (4096 bytes by default, up to `maxOutputBytes`, at most 1048576), or `null` on failure or when output exceeds the bound. A command may declare `artifact: { path, sha256, siblings?: [{ name, sha256 }] }` (an absolute or `~/…` path, lowercase SHA-256 hex, and files beside it that must match too) to run only those verified bytes, never a program on PATH; `program` is then just its label and the declared `args` are passed to it. Interpreters and programs it calls by name are still found on PATH, so give it an absolute shebang such as `#!/bin/sh` and call programs by absolute path. - `await ctx.host.request({ url, method?, headers?, body?, timeoutMs? })` returns `{ status, headers, body }` and throws on an undeclared origin or timeout. `url` must use an exact declared HTTPS origin (origin only in the manifest: scheme + host, no path or trailing slash). No redirects, no cookies. Plain `fetch` to other origins is blocked by the app's content security policy, so use this. +- `await ctx.host.requestOrigin?.(origin)` asks the person to let `request` (and the byte and upload calls) reach an origin your manifest cannot declare, such as the server URL each person types for a self-hosted service. `origin` is `https://host[:port]` only; pass `new URL(typed).origin`. Buzz shows its own prompt naming your plugin and that origin. It resolves `true` once allowed (at once, without a prompt, if your plugin can already reach the origin, so it is safe to call on every start) and `false` if the person declines. It rejects on a malformed origin, while another such prompt is open, or when your plugin was disabled or updated meanwhile. An allowed origin stays allowed for your plugin only, across restarts and updates from the same source and publisher, is listed in Settings under what the plugin can do, and is dropped when the plugin is removed. No `networkOrigins` entry is needed. Desktop only: check `typeof ctx.host.requestOrigin === "function"` first. - `ctx.host.spawn?.(id, { args?, cwd?, env?, onStdout?, onStderr? })` starts a declared `processes` entry (desktop only; check it exists). Returns `{ write, end, kill, exited }`. Your `args` follow the declared ones. - `files: true` enables `ctx.host.readFile(path, { cwd? })` (bytes, at most 50 MB), `ctx.host.resolveDirectory(path, { create? })` and `ctx.agents.assignConversationFolder`. Other grants: `mcp: true` (`host.serveMcp`), `managedFiles: true`, `publicImages: true` (`host.requestBytes` may also read PNG, JPEG, GIF, WebP and AVIF images from any public HTTPS site, one hop at a time; check each redirect's `Location` yourself), `publicPages: true` (`host.readPage(url)` returns a public HTTPS page's title, description, site name, image and icon, never its HTML; redirects come back as `location`), `agentHooks: ["plugin/kind", ...]` (agent type keys such as `buzz.claude-code/claude-code`). +A settings card (inject `react`, `settingsCards` and `host`) that connects to the person's own server: they type the address, Buzz asks whether your plugin may reach it, and the plugin sends its first request only after a yes. Keep the address in your own namespaced `localStorage` key if you need it after a restart; the allowed origin itself persists. + +```js +ctx.settingsCards.register({ + id: "server", + title: "Server", + component: function Server() { + const h = ctx.react.createElement; + const [typed, setTyped] = ctx.react.useState(""); + const [status, setStatus] = ctx.react.useState(""); + if (typeof ctx.host.requestOrigin !== "function") + return h("p", null, "Update Buzz to connect your server."); + const connect = async () => { + try { + const origin = new URL(typed).origin; + if (!(await ctx.host.requestOrigin(origin))) + return setStatus("Not connected: Buzz was not allowed to reach it."); + const reply = await ctx.host.request({ url: `${origin}/api/me` }); + setStatus(`Connected (${reply.status})`); + } catch (error) { + setStatus(String(error)); + } + }; + return h("div", null, + h("input", { "aria-label": "Server address", value: typed, placeholder: "https://board.example.org", onChange: (e) => setTyped(e.target.value) }), + h("button", { type: "button", onClick: connect }, "Connect"), + status && h("p", null, status)); + }, +}); +``` + ## UI - `ctx.conversation.ui.Workspace` shows a permanent conversation in a plugin page. diff --git a/src-tauri/build.rs b/src-tauri/build.rs index 7a34adaca9..f71743a7bc 100644 --- a/src-tauri/build.rs +++ b/src-tauri/build.rs @@ -182,6 +182,7 @@ fn main() { "plugin_host_call_context", "plugin_host_request", "plugin_host_request_bytes", + "plugin_host_request_origin", "plugin_host_read_page", "plugin_host_upload_bytes_once", "plugin_host_save_bytes", diff --git a/src-tauri/capabilities/default.json b/src-tauri/capabilities/default.json index d14f8c2cbd..0f5b51f7b2 100644 --- a/src-tauri/capabilities/default.json +++ b/src-tauri/capabilities/default.json @@ -128,6 +128,7 @@ "allow-plugin-host-call-context", "allow-plugin-host-request", "allow-plugin-host-request-bytes", + "allow-plugin-host-request-origin", "allow-plugin-host-read-page", "allow-plugin-host-upload-bytes-once", "allow-plugin-host-save-bytes", diff --git a/src-tauri/src/host_forward/tests.rs b/src-tauri/src/host_forward/tests.rs index 7c10706f3f..b161b8a990 100644 --- a/src-tauri/src/host_forward/tests.rs +++ b/src-tauri/src/host_forward/tests.rs @@ -1466,3 +1466,43 @@ fn ipc_shapes_match_the_typescript_bindings() { Harness::Goose ); } + +#[tokio::test] +async fn an_origin_approved_at_runtime_does_not_grant_forwarding() { + use tauri::Manager as _; + let root = tempfile::tempdir().unwrap(); + let manager = + buzzodz_plugins::Manager::open(Some(root.path().join("data")), "test", false).unwrap(); + let source = root.path().join("plugin"); + std::fs::create_dir(&source).unwrap(); + std::fs::write(source.join("plugin.js"), "export function apply() {}").unwrap(); + std::fs::write( + source.join("manifest.json"), + r#"{"id":"example.forward","name":"Forward","apiVersion":1}"#, + ) + .unwrap(); + let revision = manager + .install(&source) + .unwrap() + .plugins + .into_iter() + .find(|p| p.manifest.id == "example.forward") + .unwrap() + .revision; + manager.change("enable", "example.forward").unwrap(); + manager + .approve_origin("example.forward", &revision, "https://gateway.example") + .unwrap(); + let app = tauri::test::mock_app(); + app.manage(crate::PluginManager(Ok(manager))); + assert_eq!( + granted( + app.state(), + "https://gateway.example".into(), + "example.forward".into(), + revision + ) + .await, + Err("The agent gateway is not declared".into()) + ); +} diff --git a/src-tauri/src/host_request.rs b/src-tauri/src/host_request.rs index 7e1569c039..0dadb6b96e 100644 --- a/src-tauri/src/host_request.rs +++ b/src-tauri/src/host_request.rs @@ -6,6 +6,7 @@ use reqwest::header::{HeaderMap, HeaderName, HeaderValue}; use serde::{Deserialize, Serialize}; use sha2::{Digest, Sha256}; use std::sync::{Mutex, OnceLock}; +use tauri_plugin_dialog::{DialogExt, MessageDialogButtons, MessageDialogKind}; mod public_image; mod public_page; @@ -222,6 +223,77 @@ struct UploadFile { content_type: String, } +/// Held while Buzz shows a network access prompt, so prompts never stack. +static ASKING: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(()); + +/// Lets the calling plugin's `request`, byte reads and uploads reach `origin` +/// once the person allows it in a native prompt. Plugin code shares the +/// host's web view, so only a prompt drawn here proves the person answered. +#[tauri::command] +pub(crate) async fn plugin_host_request_origin( + window: tauri::Window, + manager: tauri::State<'_, PluginManager>, + id: String, + revision: String, + origin: String, +) -> Result { + let shown = origin.clone(); + request_origin(manager, &ASKING, id, revision, origin, |name| { + let (sender, receiver) = tokio::sync::oneshot::channel(); + let message = format!( + "Let \u{201c}{name}\u{201d} connect to {shown}? The plugin can then make HTTPS \ + requests to this address until you remove it." + ); + // GTK reads the message as a printf format. + #[cfg(target_os = "linux")] + let message = message.replace('%', "%%"); + window + .dialog() + .message(message) + .title("Allow network access?") + .kind(MessageDialogKind::Warning) + .buttons(MessageDialogButtons::OkCancelCustom( + "Allow".into(), + "Don't Allow".into(), + )) + .parent(&window) + .show(move |allowed| { + let _ = sender.send(allowed); + }); + async move { receiver.await.unwrap_or(false) } + }) + .await +} + +/// Checks, asks, then saves. An origin the plugin already reaches returns +/// `true` without asking; the save checks the plugin again, so one disabled +/// or updated while `ask` was open saves nothing. +async fn request_origin>( + manager: tauri::State<'_, PluginManager>, + asking: &tokio::sync::Mutex<()>, + id: String, + revision: String, + origin: String, + ask: impl FnOnce(String) -> Asked, +) -> Result { + let (plugin, at, requested) = (id.clone(), revision.clone(), origin.clone()); + let name = with_manager(manager.clone(), move |m| { + m.origin_request(&plugin, &at, &requested) + }) + .await?; + let Some(name) = name else { + return Ok(true); + }; + let _open = asking + .try_lock() + .map_err(|_| "Another network access request is open")?; + if !ask(name.chars().filter(|c| !c.is_control()).collect()).await { + return Ok(false); + } + with_manager(manager, move |m| m.approve_origin(&id, &revision, &origin)).await?; + Ok(true) +} + #[derive(Debug, Serialize)] pub(crate) struct HostResponse { pub(crate) status: u16, @@ -244,7 +316,7 @@ pub(crate) async fn plugin_host_request( let operation = async { let (plugin_id, artifact) = (id.clone(), revision.clone()); let grants = with_manager(manager, move |manager| { - manager.host_grants(&plugin_id, &artifact) + manager.request_grants(&plugin_id, &artifact) }) .await .map_err(|_| "Host request is unavailable")?; @@ -537,7 +609,7 @@ async fn byte_grants( revision: &str, ) -> Result { let (id, revision) = (id.to_owned(), revision.to_owned()); - with_manager(manager, move |m| m.host_grants(&id, &revision)) + with_manager(manager, move |m| m.request_grants(&id, &revision)) .await .map_err(|_| "Host byte request is unavailable".into()) } @@ -606,9 +678,11 @@ pub(crate) async fn plugin_host_upload( timeout_ms: None, })?; let operation = async { - let grants = with_manager(manager, move |manager| manager.host_grants(&id, &revision)) - .await - .map_err(|_| "Host request is unavailable")?; + let grants = with_manager(manager, move |manager| { + manager.request_grants(&id, &revision) + }) + .await + .map_err(|_| "Host request is unavailable")?; let home = std::env::var_os("HOME").map(std::path::PathBuf::from); let path = upload_path(&grants, &url, &upload.file.path, home.as_deref())?; let bytes = tokio::fs::read(&path) @@ -1260,6 +1334,9 @@ mod tests { #[cfg(test)] mod replay_tests; +#[cfg(test)] +mod origin_tests; + #[cfg(test)] #[path = "host_request/byte_tests.rs"] mod byte_tests; diff --git a/src-tauri/src/host_request/origin_tests.rs b/src-tauri/src/host_request/origin_tests.rs new file mode 100644 index 0000000000..13e71a6101 --- /dev/null +++ b/src-tauri/src/host_request/origin_tests.rs @@ -0,0 +1,153 @@ +//! The native route that saves an origin: check, ask, then save. Each test +//! answers in place of the dialog. +use super::*; +use std::future::{ready, Future, Ready}; +use tauri::{test::MockRuntime, Manager as _}; + +const ID: &str = "example.origins"; +const OPEN: &str = "Another network access request is open"; + +struct Fixture { + _root: tempfile::TempDir, + source: std::path::PathBuf, + manager: buzzodz_plugins::Manager, + app: tauri::App, + revision: String, +} +fn install(manager: &buzzodz_plugins::Manager, source: &std::path::Path, about: &str) -> String { + std::fs::write( + source.join("manifest.json"), + serde_json::to_vec(&serde_json::json!({ + "id": ID, "name": "Origins\u{0} fixture", "description": about, "apiVersion": 1, + "host": {"networkOrigins": ["https://declared.example"]} + })) + .unwrap(), + ) + .unwrap(); + let catalog = manager.install(source).unwrap(); + catalog + .plugins + .into_iter() + .find(|p| p.manifest.id == ID) + .unwrap() + .revision +} +fn fixture() -> Fixture { + let root = tempfile::tempdir().unwrap(); + let manager = + buzzodz_plugins::Manager::open(Some(root.path().join("data")), "test", false).unwrap(); + let source = root.path().join("plugin"); + std::fs::create_dir(&source).unwrap(); + std::fs::write(source.join("plugin.js"), "export function apply() {}").unwrap(); + let revision = install(&manager, &source, "first"); + manager.change("enable", ID).unwrap(); + let app = tauri::test::mock_app(); + app.manage(PluginManager(Ok(manager.clone()))); + Fixture { + _root: root, + source, + manager, + app, + revision, + } +} +fn ask>( + f: &Fixture, + asking: &tokio::sync::Mutex<()>, + origin: &str, + answer: impl FnOnce(String) -> Asked, +) -> Result { + tauri::async_runtime::block_on(request_origin( + f.app.state(), + asking, + ID.into(), + f.revision.clone(), + origin.into(), + answer, + )) +} +fn never_asked(_: String) -> Ready { + panic!("Buzz asked") +} +fn approved(f: &Fixture) -> Vec { + let catalog = f.manager.catalog().unwrap(); + let plugin = catalog.plugins.into_iter().find(|p| p.manifest.id == ID); + plugin.unwrap().approved_origins +} + +#[test] +fn asks_with_the_printable_name_once_then_returns_true_without_asking() { + let f = fixture(); + let asking = tokio::sync::Mutex::new(()); + assert_eq!( + ask(&f, &asking, "https://mcp.example", |name| { + assert_eq!(name, "Origins fixture"); + ready(true) + }), + Ok(true) + ); + for reached in ["https://declared.example", "https://mcp.example"] { + assert_eq!(ask(&f, &asking, reached, never_asked), Ok(true)); + } + assert_eq!(approved(&f), ["https://mcp.example"]); +} + +#[test] +fn a_malformed_origin_errors_before_asking() { + let f = fixture(); + for origin in [ + "https://mcp.example/path", + "https://*.example", + "http://mcp.example", + ] { + assert!(ask(&f, &tokio::sync::Mutex::new(()), origin, never_asked).is_err()); + } +} + +#[test] +fn a_plugin_disabled_or_updated_while_asked_saves_nothing() { + for update in [false, true] { + let f = fixture(); + let outcome = ask( + &f, + &tokio::sync::Mutex::new(()), + "https://mcp.example", + |_| { + if update { + install(&f.manager, &f.source, "second"); + } else { + f.manager.change("disable", ID).unwrap(); + } + ready(true) + }, + ); + assert_eq!( + outcome, + Err("Plugin was disabled or updated; refresh the catalog".into()) + ); + assert!(approved(&f).is_empty()); + } +} + +#[test] +fn a_second_request_while_one_is_open_rejects() { + let f = fixture(); + let asking = tokio::sync::Mutex::new(()); + let first = ask(&f, &asking, "https://first.example", |_| async { + let second = request_origin( + f.app.state(), + &asking, + ID.into(), + f.revision.clone(), + "https://second.example".into(), + never_asked, + ); + assert_eq!(second.await, Err(OPEN.into())); + false + }); + assert_eq!(first, Ok(false)); + assert_eq!( + ask(&f, &asking, "https://second.example", |_| ready(true)), + Ok(true) + ); +} diff --git a/src-tauri/src/host_request/replay_tests.rs b/src-tauri/src/host_request/replay_tests.rs index 9a963f3cd2..e80a00659c 100644 --- a/src-tauri/src/host_request/replay_tests.rs +++ b/src-tauri/src/host_request/replay_tests.rs @@ -280,6 +280,39 @@ fn denied_ipc_requests_never_consume_dispatch_authority() { assert!(calls.claims.lock().unwrap().consumed.is_empty()); } +#[test] +fn a_request_reaches_an_origin_only_after_the_person_allows_it() { + // As above, loopback TLS is untrusted: a request that passes the origin + // check reaches the listener and then fails. + let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + let url = format!("https://{}/api/me", listener.local_addr().unwrap()); + let origin = reqwest::Url::parse(&url) + .unwrap() + .origin() + .ascii_serialization(); + let fixture = App::new("https://declared.example"); + let server = std::thread::spawn(move || drop(listener.accept().unwrap())); + let body = fixture.body(&url, None); + let request = || ipc(&fixture.view, "plugin_host_request", body.clone()); + let answer = |allowed: bool| { + tauri::async_runtime::block_on(request_origin( + fixture.app.state(), + &tokio::sync::Mutex::new(()), + "example.replay".into(), + fixture.revision.clone(), + origin.clone(), + |_| std::future::ready(allowed), + )) + }; + assert_eq!(answer(false), Ok(false)); + assert!(request() + .unwrap_err() + .contains("Host request origin is not declared")); + assert_eq!(answer(true), Ok(true)); + assert!(request().unwrap_err().contains("Host request failed")); + server.join().unwrap(); +} + #[test] fn full_claims_reset_only_on_page_advance_and_stale_boot_poison_overflow_fail_closed() { let calls = HostCalls::default(); diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index 1420622662..aad1501db2 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -146,7 +146,8 @@ use host_process::{ }; use host_request::{ plugin_host_call_context, plugin_host_read_page, plugin_host_request, - plugin_host_request_bytes, plugin_host_upload, plugin_host_upload_bytes_once, HostCalls, + plugin_host_request_bytes, plugin_host_request_origin, plugin_host_upload, + plugin_host_upload_bytes_once, HostCalls, }; use notifications::{notification_show, Notifications}; #[cfg(target_os = "macos")] @@ -839,6 +840,7 @@ fn commands() -> impl Fn(tauri::ipc::Invoke) -> bool + Sen plugin_host_call_context, plugin_host_request, plugin_host_request_bytes, + plugin_host_request_origin, plugin_host_read_page, plugin_host_upload_bytes_once, plugin_host_save_bytes, diff --git a/src/app/AgentPluginRequests.test.tsx b/src/app/AgentPluginRequests.test.tsx index 4bdf6a9e80..b4d5e862ca 100644 --- a/src/app/AgentPluginRequests.test.tsx +++ b/src/app/AgentPluginRequests.test.tsx @@ -209,7 +209,9 @@ it("updates at the pinned commit and keeps the plugin's enabled state", async () }); it("shows a plugin's access before enabling it", async () => { - const { manager, agent } = await harness([installed()]); + const { manager, agent } = await harness([ + installed({ approvedOrigins: ["https://mcp.example:8443"] }), + ]); const { requestId } = await agent.request({ action: "enable", id: "example.tasks", @@ -225,6 +227,9 @@ it("shows a plugin's access before enabling it", async () => { ).toBeVisible(); expect(within(dialog).getByText(reason)).toBeVisible(); expect(within(dialog).getByText(/tasks\.example\.com/)).toBeVisible(); + expect( + within(dialog).getByText("Connect to https://mcp.example:8443"), + ).toBeVisible(); fireEvent.click( within(dialog).getByRole("button", { name: "Enable plugin" }), ); diff --git a/src/app/AgentPluginRequests.tsx b/src/app/AgentPluginRequests.tsx index aa51405093..b1991711da 100644 --- a/src/app/AgentPluginRequests.tsx +++ b/src/app/AgentPluginRequests.tsx @@ -9,7 +9,7 @@ import type { PluginManager } from "../plugins/manager"; import type { PluginRequest } from "../plugins/requests"; import type { Catalog } from "../plugins/types"; import { ManagedPluginReview } from "./ManagedPlugins"; -import { PluginAccessReview } from "./PluginAccessReview"; +import { PluginAccessReview, withApprovedOrigins } from "./PluginAccessReview"; import styles from "./Settings.module.css"; type Authorize = NonNullable< @@ -297,7 +297,7 @@ function ChangeReview({ } > {body} - {plugin && } + {plugin && } ); } diff --git a/src/app/PluginAccessReview.tsx b/src/app/PluginAccessReview.tsx index e01b2e85aa..d9f173e361 100644 --- a/src/app/PluginAccessReview.tsx +++ b/src/app/PluginAccessReview.tsx @@ -3,6 +3,7 @@ import { AgentsContext } from "../features/agents/react"; import type { RegisteredAgentType } from "../features/agents/service"; import type { PluginManifest } from "../plugins/api"; +import type { PluginInfo } from "../plugins/types"; import { Accordion } from "../shared/design-system/ui/Accordion"; import { Button } from "../shared/design-system/ui/Button"; import { @@ -274,6 +275,20 @@ export function pluginAccessIncreases( ); } +export function withApprovedOrigins({ manifest, approvedOrigins }: PluginInfo) { + if (!approvedOrigins?.length) return manifest; + return { + ...manifest, + host: { + ...manifest.host, + networkOrigins: [ + ...(manifest.host?.networkOrigins ?? []), + ...approvedOrigins, + ], + }, + }; +} + export function PluginAccessReview({ manifest, previousManifest, diff --git a/src/app/PluginMenu.tsx b/src/app/PluginMenu.tsx index e3b67590ec..6111576f70 100644 --- a/src/app/PluginMenu.tsx +++ b/src/app/PluginMenu.tsx @@ -13,7 +13,7 @@ import { IconButton } from "../shared/design-system/ui/IconButton"; import { Button } from "../shared/design-system/ui/Button"; import { AlertDialog } from "../shared/design-system/ui/AlertDialog"; import { Dialog } from "../shared/design-system/ui/Dialog"; -import { PluginAccessReview } from "./PluginAccessReview"; +import { PluginAccessReview, withApprovedOrigins } from "./PluginAccessReview"; export function PluginMenu({ plugin, @@ -129,7 +129,7 @@ export function PluginMenu({ finalFocus={deleteTrigger} actions={} > - + {confirmRollback && ( { + const f = fixture(); + f.plugin.approvedOrigins = ["https://mcp.example:8443"]; + render(); + fireEvent.click(screen.getByRole("button", { name: "More plugin actions" })); + fireEvent.click( + await screen.findByRole("menuitem", { name: "Review access" }), + ); + expect( + await screen.findByText("Connect to https://mcp.example:8443"), + ).toBeInTheDocument(); +}); + it.each(["checks disabled", "signature repaired"] as const)( "retires a pending preview when the installed plugin changes: %s", async (change) => { diff --git a/src/features/host/service.test.ts b/src/features/host/service.test.ts index 677f235d05..5b68411319 100644 --- a/src/features/host/service.test.ts +++ b/src/features/host/service.test.ts @@ -1849,3 +1849,38 @@ it("renderer disposal suppresses an opted-in acknowledgement without claiming na expect.anything(), ); }); + +it.each([true, false])( + "asks Buzz to allow an origin for the calling plugin and returns its answer: %s", + async (allowed) => { + const { plugin } = pluginContext(); + vi.mocked(invoke).mockResolvedValue(allowed); + await expect( + plugin.host.requestOrigin?.("https://plane.example.org:8443"), + ).resolves.toBe(allowed); + expect(invoke).toHaveBeenCalledExactlyOnceWith( + "plugin_host_request_origin", + { + id: "example.plugin", + revision: "abc", + origin: "https://plane.example.org:8443", + }, + ); + }, +); + +it("refuses to request an origin outside an installed desktop plugin", async () => { + const { root, plugin } = pluginContext(); + const bundled = root.extend({ + pluginOwner: { id: "buzz.channels", revision: "bundled" }, + }); + for (const host of [root.host, bundled.host]) + await expect(host.requestOrigin?.("https://a.example")).rejects.toThrow( + "installed desktop plugin", + ); + vi.mocked(isTauri).mockReturnValue(false); + await expect( + plugin.host.requestOrigin?.("https://a.example"), + ).rejects.toThrow("installed desktop plugin"); + expect(invoke).not.toHaveBeenCalled(); +}); diff --git a/src/features/host/service.ts b/src/features/host/service.ts index d9f7c7da23..4b13a26efe 100644 --- a/src/features/host/service.ts +++ b/src/features/host/service.ts @@ -242,6 +242,15 @@ export interface Host { signal: AbortSignal, ) => Promise; request(input: HostRequest): Promise; + /** Asks the person, in a prompt Buzz draws naming this plugin and the + * origin, to let this plugin's `request`, byte and upload calls reach one + * more exact origin: `https://host[:port]` with no path or wildcard, such as + * a server URL the person typed. Resolves `true` when allowed, at once and + * without asking when the plugin can already reach it, and `false` when the + * person declines. Rejects on a malformed origin or while another prompt is + * open. An allowed origin lasts across restarts and same-source updates + * until the plugin is removed. Installed desktop plugins only. */ + requestOrigin?: (origin: string) => Promise; /** POST-only, desktop and compatible native host required. A repeated call * authority rejects with unknown outcome, never resubmits or caches success. * Blocks IPC-fallback resends only, not fresh calls or upstream retries. @@ -695,6 +704,19 @@ export class HostService extends Service implements Host { }).catch(rethrow); } + async requestOrigin(origin: string) { + const owner = this.ctx.pluginOwner; + if (!owner || !isTauri() || owner.revision === "bundled") + throw new Error( + "Requesting an origin requires an installed desktop plugin", + ); + return await invoke("plugin_host_request_origin", { + id: owner.id, + revision: owner.revision, + origin, + }).catch(rethrow); + } + async requestOnce( input: HostRequest, { callId, isEligible }: HostRequestOnceOptions, diff --git a/src/plugins/author.test.mjs b/src/plugins/author.test.mjs index 7a4079178e..2744803193 100644 --- a/src/plugins/author.test.mjs +++ b/src/plugins/author.test.mjs @@ -135,6 +135,7 @@ export function apply(ctx: Context) { headers: { Authorization: "Bearer sample" }, body: "{}", }).then((response) => void response.status); + if (typeof host.requestOrigin === "function") void host.requestOrigin("https://plane.example.com:8443").then((allowed: boolean) => allowed); // Final synchronous eligibility is part of the optional protected method. if (typeof host.requestOnce === "function") { const options: HostRequestOnceOptions = { diff --git a/src/plugins/types.ts b/src/plugins/types.ts index 4fb8e2a7b9..fb2bebe8a7 100644 --- a/src/plugins/types.ts +++ b/src/plugins/types.ts @@ -20,6 +20,8 @@ export type PluginInfo = { readmeRevision?: string | null; iconPngRevision?: string | null; iconJpgRevision?: string | null; + /** HTTPS origins the person approved for the plugin at runtime, beyond the manifest's. */ + approvedOrigins?: readonly string[]; }; export type PluginRelease = Pick;