Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
378 changes: 370 additions & 8 deletions crates/plugin-manager/src/lib.rs

Large diffs are not rendered by default.

1 change: 1 addition & 0 deletions crates/plugin-manager/src/managed.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<InstallSource> {
Expand Down
28 changes: 28 additions & 0 deletions docs/plugin-architecture.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
32 changes: 32 additions & 0 deletions docs/plugin-authoring-guide.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
1 change: 1 addition & 0 deletions src-tauri/build.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
1 change: 1 addition & 0 deletions src-tauri/capabilities/default.json
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
40 changes: 40 additions & 0 deletions src-tauri/src/host_forward/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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())
);
}
87 changes: 82 additions & 5 deletions src-tauri/src/host_request.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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<R: tauri::Runtime>(
window: tauri::Window<R>,
manager: tauri::State<'_, PluginManager>,
id: String,
revision: String,
origin: String,
) -> Result<bool, String> {
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 \

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🤖 P2: The dialog is a real gate, but it is weaker as a trust signal than it looks. (1) id and revision are caller-supplied, like every other host command (HostCalls::consume binds them only to the call, not to a plugin). Plugin code shares the main web view, so plugin A can invoke('plugin_host_request_origin', {id: 'B', revision: <B's revision from the catalog>, origin}). The dialog then reads "Let B connect to evil", and on Allow the origin goes to B. A then reaches it through B's id, as it already can with B's manifest origins. It cannot forge consent, but it can borrow another plugin's name. (2) The only identity shown is the self-declared manifest name (<=80 bytes, only Cc control chars stripped). Any plugin can call itself "Buzz". Bidi format characters such as U+202E are not stripped either, so they can reorder the text around the origin. Show the plugin id plus publisher or source, and strip Cf characters. (3) A "Don't Allow" is not remembered, so a plugin can re-prompt in a loop and the dialog is parented to the window. Add a per-plugin cooldown or deny-until-restart after a decline. Not a blocker.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🤖 @joahg Thanks. I'm keeping all three out of this PR. Each one is now under Known limitations in the description:

  1. Another plugin's id. Agreed. Every host command takes id and revision from its caller, so plugin A can raise the dialog under plugin B's name. On Allow, the origin is saved for B, and A can then reach it through B's id, as it already can with B's manifest origins. Binding host calls to the calling plugin would change every host command, not just this one.
  2. The name alone. The dialog uses the manifest name, as the access review and the agent enable dialog do. Showing the id and the source would fit all three. Bidi format characters such as U+202E are listed too.
  3. Asking again after Don't Allow. A decline isn't remembered, so a plugin can ask again. Only one dialog can be open at a time. A cooldown after a decline would be a reasonable follow-up.

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<Asked: std::future::Future<Output = bool>>(
manager: tauri::State<'_, PluginManager>,
asking: &tokio::sync::Mutex<()>,
id: String,
revision: String,
origin: String,
ask: impl FnOnce(String) -> Asked,
) -> Result<bool, String> {
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,
Expand All @@ -244,7 +316,7 @@ pub(crate) async fn plugin_host_request<R: tauri::Runtime>(
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")?;
Expand Down Expand Up @@ -537,7 +609,7 @@ async fn byte_grants(
revision: &str,
) -> Result<HostGrants, String> {
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())
}
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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;
Expand Down
Loading
Loading