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
79 changes: 78 additions & 1 deletion crates/plugin-manager/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@ pub mod access;
pub mod imports;
pub mod managed;
mod migrate_agent_flag;
mod relay_kinds;
pub use relay_kinds::{reserved_relay_kind, RelayKind, MAX_RELAY_KINDS};

pub type Result<T> = std::result::Result<T, String>;
pub const LIMIT: u64 = 8 * 1024 * 1024;
Expand Down Expand Up @@ -73,6 +75,11 @@ pub struct HostGrants {
pub commands: Vec<HostCommand>,
#[serde(default)]
pub network_origins: Vec<String>,
/// Event kinds the plugin may sign as the viewer and publish with
/// `host.publish`, each with its purpose; never a reserved kind (see
/// `reserved_relay_kind`).
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub relay_kinds: Vec<RelayKind>,
/// Programs the plugin may start as long-lived processes. Unlike a command,
/// a process takes stdin and the caller appends its own arguments.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
Expand Down Expand Up @@ -331,6 +338,7 @@ impl Manifest {
return Err("Invalid host process declaration".into());
}
}
relay_kinds::validate(&host.relay_kinds)?;
let mut origins = std::collections::HashSet::new();
for origin in &host.network_origins {
let url = url::Url::parse(origin).map_err(err)?;
Expand Down Expand Up @@ -1715,7 +1723,7 @@ fn atomic_write(path: &Path, bytes: &[u8]) -> Result<()> {
mod tests {
use super::{
artifact_from_text, bundled_manifests, enabled_by_default, validate_candidate_path,
Manager, Manifest, Release, MAX_HOST_COMMAND_OUTPUT_BYTES,
Manager, Manifest, RelayKind, Release, MAX_HOST_COMMAND_OUTPUT_BYTES,
};
use std::collections::BTreeMap;
use std::fs;
Expand Down Expand Up @@ -2457,6 +2465,75 @@ mod tests {
}
}

#[test]
fn manifests_declare_up_to_eight_unreserved_relay_kinds() {
let raw = |kinds: serde_json::Value| {
let manifest = serde_json::json!({
"id": "example.page", "name": "Example", "apiVersion": 1,
"host": { "relayKinds": kinds }
});
artifact_from_text(&manifest.to_string(), "export const x = 1".into())
};
let with = |kinds: serde_json::Value| {
let entries = kinds.as_array().unwrap().iter();
raw(entries
.map(|kind| serde_json::json!({ "kind": kind, "purpose": "Example" }))
.collect())
};
let packed = raw(serde_json::json!([
{ "kind": 47000, "purpose": "Create or edit a group" },
{ "kind": 47001, "purpose": "Delete a group" }
]))
.unwrap();
let packed: crate::Artifact = serde_json::from_slice(&packed).unwrap();
assert_eq!(
packed.manifest.host.unwrap().relay_kinds,
[
RelayKind {
kind: 47000,
purpose: "Create or edit a group".into()
},
RelayKind {
kind: 47001,
purpose: "Delete a group".into()
},
]
);
assert!(with(serde_json::json!([1, 65535])).is_ok());
assert!(with(serde_json::json!([
47000, 47001, 47002, 47003, 47004, 47005, 47006, 47007
]))
.is_ok());
for invalid in [
serde_json::json!([47000]),
serde_json::json!([{ "kind": 47000 }]),
serde_json::json!([{ "kind": 47000, "purpose": "" }]),
serde_json::json!([{ "kind": 47000, "purpose": "Example", "label": "Example" }]),
] {
assert!(raw(invalid.clone()).is_err(), "{invalid}");
}
for invalid in [
serde_json::json!([47000, 47001, 47002, 47003, 47004, 47005, 47006, 47007, 47008]),
serde_json::json!([0]),
serde_json::json!([65536]),
serde_json::json!([-1]),
serde_json::json!([47000.5]),
serde_json::json!(["47000"]),
serde_json::json!([47000, 47000]),
serde_json::json!([47000, 9000]),
serde_json::json!([1984]),
serde_json::json!([27235]),
] {
assert!(with(invalid.clone()).is_err(), "{invalid}");
}
let old = artifact_from_text(
r#"{"id":"example.page","name":"Example","apiVersion":1,"host":{"networkOrigins":[]}}"#,
"export const x = 1".into(),
)
.unwrap();
assert!(!String::from_utf8(old).unwrap().contains("relayKinds"));
}

#[test]
fn validates_host_declarations_and_old_manifests() {
let old: Manifest =
Expand Down
172 changes: 172 additions & 0 deletions crates/plugin-manager/src/relay_kinds.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,172 @@
//! `host.relayKinds`: event kinds a plugin may sign as the viewer and publish.
//! The reserved list is the one place that says which kinds Buzz keeps for its
//! own signing or as private; admission and every publish both ask it.
use serde::{Deserialize, Serialize};

/// Most kinds one plugin may declare.
pub const MAX_RELAY_KINDS: usize = 8;
/// Longest purpose, in UTF-8 bytes.
const MAX_PURPOSE_BYTES: usize = 120;

/// One kind a plugin may sign as the viewer, with the plugin's own words for
/// what those events do. The install screen shows the purpose beside the kind.
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct RelayKind {
pub kind: u16,
pub purpose: String,
}

/// Kinds Buzz signs for its own purposes. The sources are
/// the native writer's set (`nativeWriteKinds`, `WORKFLOW_KINDS`), the
/// packaged-relay signer's allow-list (`validate_event` in `relay.rs`), the
/// purpose-bound signers (auth proofs, DM, reminders, read state, sidebar,
/// channel recipes, Huddles, observer archives, pairing, Mesh status) and the
/// kinds the credential provider and app agents sign.
const RESERVED: &[u16] = &[

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: this list is a denylist, so any kind not named here can be granted. Kinds 4, 13, 14, 1059, 10050 and 24133 are not reserved. The drift test only checks nativeWriteKinds and WORKFLOW_KINDS. Please reserve these, and consider a test that fails when a new Buzz signing path uses a kind that is not listed.

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.

🤖 I've kept the list to the kinds Buzz signs itself, as the docs state, so these aren't added. Buzz signs none of 4, 13, 14, 1059, 10050 or 24133. I searched src, src-tauri/src, crates and runtime for the numbers, the nostr Kind:: names and the nip04 and nip59 helpers. The only one Buzz looks at is kind 4: the agent runtime treats a kind 4 that p-tags an agent as addressed to it, and starts nothing from it (src/features/agents/runner.ts:2265-2271).

The list exists so that a plugin can't write a Buzz feature's own records. It isn't a policy on which standard kinds plugins may build on. Each kind still shows at install and needs the owner's approval, and the relay decides what it accepts.

The drift-test limit is real: the test compares only the two TypeScript lists. A new Buzz signing path that uses a new kind has to add that kind to this list by hand. A test that found every signing path would need an inventory of every signer call, so I've left it out of this PR.

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.

🤖 That makes sense: the list protects Buzz's own records, not a policy on standard kinds, and Buzz signs none of these. I'll leave it as a maintainer call. The one thing I'd still flag for them is that a grant for 4, 14 or 1059 lets a plugin send private messages as the owner, and the install row reads the same as for any other kind.

@LordMelkor LordMelkor Nov 17, 2026 •

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.

🤖 Update: these are now reserved, in 83c2743725. You and a second review both flagged it, and the one plugin built on this API doesn't use them. The reserved list also holds 4, 13, 14, 15, 1059, 10050 and 24133 (private messages, the inbox relay list and NIP-46 signer messages). Install and every publish check it, and a test covers each kind. Other standard kinds stay grantable. The drift-test limit from my earlier reply still stands.

0, 3, 5, 7, 9, 1064, 1617, 1618, 1619, 1621, 1984, 10000, 10001, 10002, 10003, 10030, 10100,
13534, 13535, 20001, 20002, 20003, 22242, 24134, 24200, 24242, 24243, 27235, 28936, 30000,
30003, 30023, 30030, 30078, 30174, 30175, 30176, 30177, 30178, 30179, 30300, 30315, 30617,
30618, 30620, 30621, 39002, 40100, 41010, 41011, 41012, 42000, 44100, 44200, 45010, 45011,
46020, 46030, 46031,
];
/// Inclusive ranges. 9000-9999 is every channel admin and command kind.
const RESERVED_RANGES: &[(u16, u16)] = &[
(1630, 1633),
(9000, 9999),
(40002, 40008),
(43001, 43006),
(45001, 45003),
(48100, 48103),
];

/// Private messages and remote signing: NIP-04 kind 4, NIP-17 kinds 14 and 15
/// and its inbox relay list 10050, NIP-59 seal 13 and gift wrap 1059, and
/// NIP-46 signer messages 24133. No plugin may send a private message as the
/// viewer, move where the viewer's private messages arrive, or speak for their
/// signer.
const PRIVATE: &[u16] = &[4, 13, 14, 15, 1059, 10050, 24133];

/// Whether Buzz keeps `kind` for its own signing or as private, so no grant may
/// include it.
pub fn reserved_relay_kind(kind: u16) -> bool {
RESERVED.contains(&kind)
|| PRIVATE.contains(&kind)
|| RESERVED_RANGES
.iter()
.any(|(first, last)| (*first..=*last).contains(&kind))
}

pub(crate) fn validate(kinds: &[RelayKind]) -> Result<(), String> {
if kinds.len() > MAX_RELAY_KINDS {
return Err(format!(
"At most {MAX_RELAY_KINDS} relay kinds may be declared"
));
}
let mut seen = std::collections::HashSet::new();
for RelayKind { kind, purpose } in kinds {
if *kind == 0 || reserved_relay_kind(*kind) || !seen.insert(kind) {
return Err("Invalid relay kind declaration".into());
}
if purpose.trim().is_empty()
|| purpose.len() > MAX_PURPOSE_BYTES
|| purpose.chars().any(char::is_control)
{
return Err(format!(
"A relay kind's purpose must contain 1–{MAX_PURPOSE_BYTES} bytes of text without control characters"
));
}
}
Ok(())
}

#[cfg(test)]
mod tests {
use super::*;

fn declared(kinds: &[u16]) -> Vec<RelayKind> {
kinds
.iter()
.map(|&kind| RelayKind {
kind,
purpose: "Example".into(),
})
.collect()
}

/// The integer literals of the first `[...]` after `marker` in `source`.
fn literals(source: &str, marker: &str) -> Vec<u16> {
let list = &source[source.find(marker).unwrap()..];
let list = &list[list.find('[').unwrap() + 1..list.find(']').unwrap()];
list.split(',')
.filter_map(|item| item.trim().parse().ok())
.collect()
}

#[test]
fn every_kind_the_native_writer_signs_is_reserved() {
let native = include_str!("../../../src/features/relay/native.ts");
let workflows = include_str!("../../../src/features/workflows/protocol.ts");
let kinds: Vec<_> = literals(native, "nativeWriteKinds = [")
.into_iter()
.chain(literals(workflows, "WORKFLOW_KINDS = ["))
.collect();
assert!(kinds.len() > 15, "the TypeScript lists were not found");
for kind in kinds {
assert!(reserved_relay_kind(kind), "{kind} is not reserved");
}
}

#[test]
fn purpose_bound_kinds_are_reserved_and_example_kinds_are_not() {
for kind in [
0, 5, 7, 1984, 9000, 9007, 9999, 22242, 24242, 27235, 30078, 30300, 41010, 41012,
45010, 48103,
] {
assert!(reserved_relay_kind(kind), "{kind}");
}
for kind in [1, 47000, 47001, 65535] {
assert!(!reserved_relay_kind(kind), "{kind}");
}
}

#[test]
fn no_grant_may_include_a_private_message_or_signer_kind() {
for kind in [4, 13, 14, 15, 1059, 10050, 24133] {
assert!(validate(&declared(&[47000, kind])).is_err(), "{kind}");
}
}

#[test]
fn a_declaration_has_at_most_eight_distinct_unreserved_kinds() {
assert!(validate(&[]).is_ok());
assert!(validate(&declared(&[47000, 47001])).is_ok());
assert!(validate(&declared(&[
47000, 47001, 47002, 47003, 47004, 47005, 47006, 47007
]))
.is_ok());
assert!(validate(&declared(&[
47000, 47001, 47002, 47003, 47004, 47005, 47006, 47007, 47008
]))
.is_err());
assert!(validate(&declared(&[47000, 47000])).is_err());
assert!(validate(&declared(&[0])).is_err());
assert!(validate(&declared(&[47000, 9000])).is_err());
}

#[test]
fn each_kind_says_in_one_line_of_text_what_it_is_for() {
let with = |purpose: &str| {
validate(&[RelayKind {
kind: 47000,
purpose: purpose.into(),
}])
};
assert!(with("Create or edit a group").is_ok());
assert!(with(&"a".repeat(MAX_PURPOSE_BYTES)).is_ok());
let long = "a".repeat(MAX_PURPOSE_BYTES + 1);
for purpose in ["", " ", "Two\nlines", "A\ttab", long.as_str()] {
assert!(with(purpose).is_err(), "{purpose:?}");
}
}
}
52 changes: 51 additions & 1 deletion docs/plugin-architecture.md
Original file line number Diff line number Diff line change
Expand Up @@ -1903,7 +1903,8 @@ Plugins can separately declare host access in `manifest.json`:
{
"host": {
"commands": [{ "id": "status", "program": "example-cli", "args": ["status"] }],
"networkOrigins": ["https://api.example.com"]
"networkOrigins": ["https://api.example.com"],
"relayKinds": [{ "kind": 47000, "purpose": "Create or edit a record" }]
}
}
```
Expand Down Expand Up @@ -2360,6 +2361,55 @@ node readers still reject paths outside their configured root: managed membershi
does not widen that namespace. Offline native-file and app-owned-reader fixtures
are composition evidence, not a single native WebView delivery test.

### Signing and publishing declared event kinds

`host.relayKinds` lists the event kinds a plugin may have Buzz sign as the
viewer and publish to the selected community: at most 8 entries, each
`{ kind, purpose }`. `kind` is a distinct integer from 1 to 65535. `purpose`
says what those events do, in 1–120 bytes of text without control characters.
The same list of reserved kinds is checked when the manifest is
admitted and again on every publish, so a manifest naming a reserved kind is
refused at install and no declared kind can reach one at runtime. It holds the
kinds Buzz signs itself, the private-message kinds (4, 13, 14, 15, 1059 and the
inbox relay list 10050) and NIP-46 signer messages (24133). Review shows one
declaration per kind: "Sign and send as you:" and the plugin's purpose, with
the kind number in its details. Adding a kind or rewording a purpose is an
access increase; reordering is not.

Desktop hosts provide two methods; on other hosts both reject.

- `host.publish(template, { scope, generation?, signal? })` takes
`{kind, content, tags, created_at?}`. The kind must be in the plugin's own
grant. Native code reads the grant, signs, and sends once with the viewer's
relay authentication. It keeps a given `created_at` and the tag order, so the
same template is always the same event id, and the host applies no event-age
check of its own. Whether the relay answers an old repeated id from its
receipt is the relay's rule: many relays refuse events far from their clock
(Buzz's relay: `invalid:` beyond 15 minutes) unless the kind's handler
answers repeats first. It resolves
`{event_id, accepted, message}` with the relay's text as sent, at most 512
characters. A relay refusal, including its `duplicate:` and `conflict:` 409
texts and a `429` rate limit, is `accepted: false` with that text, never an
error. Anything else is
an unknown outcome and rejects: a failed transport, an unreadable answer, a
relay error status, cancelling with `signal` after the call was sent, or a
change of community, account or connection while it was pending. The host
never replays a publish; to settle an unknown outcome, send the same template
again or read the relay for its event id.
- `host.relayInfo({ scope, generation?, signal? })` returns the selected
community's NIP-11 document as Buzz read it to connect, as a frozen copy. It
needs no grant and costs no extra relay read.

Both calls are frozen to the community, viewer and connection named by `scope`
(`RelaySnapshot.scope`, `origin:viewer`) and optional `generation`. If another
community or account is selected, or the connection is not live, they reject
before sending anything. There is no broker or web route. The page-side host
checks the scope. Native code checks the grant, the reserved kinds and the
signer, and takes the community from the page, as channel publishing does. Like
the other declarations, the grant is a guardrail for trusted plugins, not a
sandbox. The host adds no per-plugin rate limit; a relay's own limit answers as
a `429` refusal.

`host.upload` requires both `host.files` and the destination in `host.networkOrigins`.
It sends a multipart archive to that origin and reads one absolute
regular `.tar.gz` file under home, up to 100 MiB. This is local-file access in
Expand Down
2 changes: 1 addition & 1 deletion docs/plugin-authoring-guide.md
Original file line number Diff line number Diff line change
Expand Up @@ -198,7 +198,7 @@ presence before offering sharing when supporting those hosts.

## Host access (`manifest.host`)

Everything beyond the services above must be declared in `manifest.json`; the owner reviews it at install. Undeclared commands, origins, processes and file access are refused by the host. Limits: at most 16 each of `commands`, `processes`, `networkOrigins`, `agentHooks`. Program names are bare names (`[A-Za-z0-9._-]`, at most 80 bytes, no paths), at most 16 args of 1024 bytes each.
Everything beyond the services above must be declared in `manifest.json`; the owner reviews it at install. Undeclared commands, origins, processes and file access are refused by the host. Limits: at most 16 each of `commands`, `processes`, `networkOrigins`, `agentHooks`; at most 8 `relayKinds` (`{ "kind": 47000, "purpose": "Create or edit a record" }`: an event kind 1–65535 for `host.publish`, never one Buzz signs itself, a private-message kind (4, 13, 14, 15, 1059, 10050) or NIP-46's 24133, and a purpose of 1–120 bytes that the install screen shows). Program names are bare names (`[A-Za-z0-9._-]`, at most 80 bytes, no paths), at most 16 args of 1024 bytes each.

```json
{
Expand Down
1 change: 1 addition & 0 deletions src-tauri/build.rs
Original file line number Diff line number Diff line change
Expand Up @@ -181,6 +181,7 @@ fn main() {
"plugin_host_run_command",
"plugin_host_call_context",
"plugin_host_request",
"plugin_host_relay_publish",
"plugin_host_request_bytes",
"plugin_host_read_page",
"plugin_host_upload_bytes_once",
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-relay-publish",
"allow-plugin-host-read-page",
"allow-plugin-host-upload-bytes-once",
"allow-plugin-host-save-bytes",
Expand Down
1 change: 1 addition & 0 deletions src-tauri/src/browser_permissions_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -167,6 +167,7 @@ fn native_command_permissions_isolate_webviews() {
"plugin_recover",
"plugin_host_run_command",
"plugin_host_request",
"plugin_host_relay_publish",
"plugin_host_upload",
"plugin_host_process_spawn",
"plugin_host_process_write",
Expand Down
Loading
Loading