diff --git a/crates/plugin-manager/src/lib.rs b/crates/plugin-manager/src/lib.rs index cbefa92146..5d6616ab77 100644 --- a/crates/plugin-manager/src/lib.rs +++ b/crates/plugin-manager/src/lib.rs @@ -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 = std::result::Result; pub const LIMIT: u64 = 8 * 1024 * 1024; @@ -73,6 +75,11 @@ pub struct HostGrants { pub commands: Vec, #[serde(default)] pub network_origins: Vec, + /// 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, /// 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")] @@ -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)?; @@ -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; @@ -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 = diff --git a/crates/plugin-manager/src/relay_kinds.rs b/crates/plugin-manager/src/relay_kinds.rs new file mode 100644 index 0000000000..d8f03b4322 --- /dev/null +++ b/crates/plugin-manager/src/relay_kinds.rs @@ -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] = &[ + 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 { + 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 { + 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:?}"); + } + } +} diff --git a/docs/plugin-architecture.md b/docs/plugin-architecture.md index e3a484d6a3..8105e3bb8a 100644 --- a/docs/plugin-architecture.md +++ b/docs/plugin-architecture.md @@ -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" }] } } ``` @@ -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 diff --git a/docs/plugin-authoring-guide.md b/docs/plugin-authoring-guide.md index 13e79d3b0a..5a7b4cb8e4 100644 --- a/docs/plugin-authoring-guide.md +++ b/docs/plugin-authoring-guide.md @@ -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 { diff --git a/src-tauri/build.rs b/src-tauri/build.rs index 651c8554ea..2eaac7a797 100644 --- a/src-tauri/build.rs +++ b/src-tauri/build.rs @@ -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", diff --git a/src-tauri/capabilities/default.json b/src-tauri/capabilities/default.json index 4d745b266a..4184e65e91 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-relay-publish", "allow-plugin-host-read-page", "allow-plugin-host-upload-bytes-once", "allow-plugin-host-save-bytes", diff --git a/src-tauri/src/browser_permissions_tests.rs b/src-tauri/src/browser_permissions_tests.rs index 0eaa307141..117e862aaa 100644 --- a/src-tauri/src/browser_permissions_tests.rs +++ b/src-tauri/src/browser_permissions_tests.rs @@ -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", diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index 5d2dd555d4..789cb585ee 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -104,14 +104,14 @@ use identity::{ }; use relay::{ file_download, media_copy_image, media_download, media_lift_subject, media_stream_base, - relay_agent_library, relay_agent_log_proof, relay_agent_memories_read, relay_agent_observer, - relay_agent_resolve, relay_channel_publish, relay_channel_sign, relay_decode_read_state, - relay_decode_reminders, relay_decode_sidebar, relay_direct_message, relay_git_authorization, - relay_http, relay_http_cancel, relay_kit_decode, relay_kit_prepare, relay_kit_sign, - relay_project_git, relay_project_git_cancel, relay_publish_read_state, relay_sign, - relay_sign_read_state, relay_sign_reminder, relay_sign_sidebar, relay_upload, - relay_upload_begin, relay_upload_cancel, relay_upload_chunk, relay_verify_signatures, - relay_workflow_runs, + plugin_host_relay_publish, relay_agent_library, relay_agent_log_proof, + relay_agent_memories_read, relay_agent_observer, relay_agent_resolve, relay_channel_publish, + relay_channel_sign, relay_decode_read_state, relay_decode_reminders, relay_decode_sidebar, + relay_direct_message, relay_git_authorization, relay_http, relay_http_cancel, relay_kit_decode, + relay_kit_prepare, relay_kit_sign, relay_project_git, relay_project_git_cancel, + relay_publish_read_state, relay_sign, relay_sign_read_state, relay_sign_reminder, + relay_sign_sidebar, relay_upload, relay_upload_begin, relay_upload_cancel, relay_upload_chunk, + relay_verify_signatures, relay_workflow_runs, }; use relay::{huddle_close, huddle_open, huddle_pcm, huddle_touch, Huddles}; mod terminal; @@ -774,6 +774,7 @@ fn commands() -> impl Fn(tauri::ipc::Invoke) -> bool + Sen relay_git_authorization, relay_channel_sign, relay_channel_publish, + plugin_host_relay_publish, relay_kit_sign, relay_kit_prepare, relay_kit_decode, diff --git a/src-tauri/src/relay.rs b/src-tauri/src/relay.rs index b3bf2063e4..64c369f727 100644 --- a/src-tauri/src/relay.rs +++ b/src-tauri/src/relay.rs @@ -39,6 +39,8 @@ mod upload_spool; pub(crate) use upload_spool::Spools; mod media_stream; pub(crate) use media_stream::{media_stream_base, MediaStream}; +mod plugin_publish; +pub(crate) use plugin_publish::plugin_host_relay_publish; mod project_git; pub(crate) use project_git::{relay_project_git, relay_project_git_cancel}; type Result = std::result::Result; diff --git a/src-tauri/src/relay/plugin_publish.rs b/src-tauri/src/relay/plugin_publish.rs new file mode 100644 index 0000000000..d0430ebbca --- /dev/null +++ b/src-tauri/src/relay/plugin_publish.rs @@ -0,0 +1,449 @@ +//! `host.publish`: signs and publishes one event of a kind the calling plugin's +//! manifest declares in `host.relayKinds`. The grant and the reserved kinds are +//! read here, not trusted from the page. The event is signed once, sent once and +//! never replayed: a retry is a new call whose same template makes the same id. +use super::*; +use crate::{with_manager, PluginManager}; +use buzzodz_plugins::{reserved_relay_kind, HostGrants}; + +/// Longest relay text handed back, in characters. +const MESSAGE_CHARS: usize = 512; +/// Statuses in which the relay refuses the event itself, with its own words. +const REFUSALS: [u16; 8] = [400, 401, 403, 404, 409, 413, 422, 429]; + +#[derive(Serialize)] +pub(crate) struct Publication { + event_id: String, + accepted: bool, + message: String, +} + +fn admit(grants: &HostGrants, event: &EventTemplate) -> Result<()> { + if !grants + .relay_kinds + .iter() + .any(|declared| declared.kind == event.kind) + { + return Err("This plugin did not declare that event kind".into()); + } + if reserved_relay_kind(event.kind) { + return Err("Buzz keeps that event kind for its own use".into()); + } + if event.created_at > 9_007_199_254_740_991 { + return Err("Invalid event time".into()); + } + buzz_agent_controller::bounded(event.kind, &event.content, &event.tags) +} + +fn text(value: &str) -> String { + value.chars().take(MESSAGE_CHARS).collect() +} + +/// The relay's answer for `id`. Only its own receipt or refusal is an outcome; +/// anything else may have reached it, so the caller must not treat it as a no. +fn outcome(response: RelayResponse, id: &str) -> Result { + let body: Option = serde_json::from_str(&response.body).ok(); + let field = |name: &str| body.as_ref().and_then(|body| body[name].as_str()); + let publication = |accepted: bool, message: &str| Publication { + event_id: id.into(), + accepted, + message: text(message), + }; + if (200..300).contains(&response.status) { + let accepted = body.as_ref().and_then(|body| body["accepted"].as_bool()); + return match (accepted, field("event_id")) { + (Some(accepted), Some(received)) if received == id => { + Ok(publication(accepted, field("message").unwrap_or_default())) + } + _ => Err("Relay returned an invalid delivery receipt; outcome unknown".into()), + }; + } + if REFUSALS.contains(&response.status) { + let status = format!("Relay rejected the event ({})", response.status); + return Ok(publication(false, field("error").unwrap_or(&status))); + } + Err(format!( + "Relay delivery could not be confirmed ({}); outcome unknown", + response.status + )) +} + +pub(super) async fn publish( + host: &IdentityHost, + fi: Option<&FederatedIdentity>, + url: Url, + grants: &HostGrants, + viewer: &str, + event: EventTemplate, +) -> Result { + admit(grants, &event)?; + if host.viewer().await? != viewer { + return Err("Your identity changed. Try again.".into()); + } + let signed = host.sign(event).await?; + let id = signed["id"] + .as_str() + .ok_or("Invalid signed event")? + .to_owned(); + if signed["pubkey"] != viewer { + return Err("Your identity changed. Try again.".into()); + } + // No host age check: whether an old event is accepted is the relay's answer. + let response = send( + host, + fi, + url, + "POST", + Some(signed.to_string()), + true, + 64 * 1024, + ) + .await?; + outcome(response, &id) +} + +/// `viewer` and `community` are what the page's selected session named when it +/// asked; a different signed-in key refuses before anything is signed. +#[tauri::command] +#[allow(clippy::too_many_arguments)] +pub(crate) async fn plugin_host_relay_publish( + manager: tauri::State<'_, PluginManager>, + host: tauri::State<'_, IdentityHost>, + fi: tauri::State<'_, FederatedIdentity>, + id: String, + revision: String, + community: String, + viewer: String, + event: EventTemplate, +) -> Result { + let url = request_url(&community, "/events", "POST")?; + let grants = with_manager(manager, move |manager| manager.host_grants(&id, &revision)) + .await + .map_err(|_| "Relay publishing is unavailable")?; + publish(host.inner(), Some(fi.inner()), url, &grants, &viewer, event).await +} + +#[cfg(test)] +mod tests { + use super::super::tests::fixture_server; + use super::*; + use std::net::TcpListener; + + fn grants(kinds: &[u16]) -> HostGrants { + HostGrants { + relay_kinds: kinds + .iter() + .map(|&kind| buzzodz_plugins::RelayKind { + kind, + purpose: "Example".into(), + }) + .collect(), + ..Default::default() + } + } + fn template(kind: u16, created_at: u64) -> EventTemplate { + EventTemplate { + kind, + created_at, + tags: vec![ + vec!["z".into(), "second".into()], + vec!["a".into(), "first".into()], + ], + content: "{\"n\":1}".into(), + } + } + /// What the fixture relay answers: the body is the relay's own JSON. + fn reply(status: &str, body: &str) -> String { + format!( + "HTTP/1.1 {status}\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}", + body.len() + ) + } + async fn id_of(host: &IdentityHost, event: EventTemplate) -> String { + host.sign(event).await.unwrap()["id"] + .as_str() + .unwrap() + .to_owned() + } + /// A relay that must never be asked. + fn silent() -> (Url, TcpListener) { + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + listener.set_nonblocking(true).unwrap(); + let url = Url::parse(&format!("http://{}/events", listener.local_addr().unwrap())).unwrap(); + (url, listener) + } + fn untouched(listener: &TcpListener) { + assert_eq!( + listener.accept().unwrap_err().kind(), + std::io::ErrorKind::WouldBlock + ); + } + + #[tokio::test] + async fn a_declared_kind_is_signed_by_the_viewer_and_sent_in_order() { + let host = IdentityHost::fixture(); + let viewer = host.viewer().await.unwrap(); + let id = id_of(&host, template(47000, 1_700_000_000)).await; + let (url, relay) = fixture_server(reply( + "200 OK", + &format!(r#"{{"event_id":"{id}","accepted":true,"message":"stored"}}"#), + )); + let result = publish( + &host, + None, + url, + &grants(&[47001, 47000]), + &viewer, + template(47000, 1_700_000_000), + ) + .await + .unwrap(); + assert_eq!( + (result.event_id, result.accepted, result.message), + (id.clone(), true, "stored".to_owned()) + ); + let (_, body) = relay.join().unwrap(); + let sent: serde_json::Value = serde_json::from_str(&body).unwrap(); + assert_eq!( + (sent["kind"].as_u64(), sent["id"].as_str()), + (Some(47000), Some(id.as_str())) + ); + assert_eq!(sent["pubkey"], viewer.as_str()); + assert_eq!(sent["created_at"], 1_700_000_000); + assert_eq!( + sent["tags"], + serde_json::json!([["z", "second"], ["a", "first"]]) + ); + verify_signature(&sent).unwrap(); + } + + #[tokio::test] + async fn an_undeclared_kind_never_reaches_the_relay() { + let host = IdentityHost::fixture(); + let viewer = host.viewer().await.unwrap(); + let (url, relay) = silent(); + for declared in [&[][..], &[47001][..]] { + let error = publish( + &host, + None, + url.clone(), + &grants(declared), + &viewer, + template(47000, 1), + ) + .await + .err() + .unwrap(); + assert_eq!(error, "This plugin did not declare that event kind"); + } + untouched(&relay); + } + + #[tokio::test] + async fn a_reserved_kind_is_refused_even_when_a_grant_lists_it() { + let host = IdentityHost::fixture(); + let viewer = host.viewer().await.unwrap(); + let (url, relay) = silent(); + for kind in [1984, 9007, 22242, 27235, 30078, 41010, 45010] { + let error = publish( + &host, + None, + url.clone(), + &grants(&[kind]), + &viewer, + template(kind, 1), + ) + .await + .err() + .unwrap(); + assert_eq!( + error, "Buzz keeps that event kind for its own use", + "{kind}" + ); + } + untouched(&relay); + } + + #[tokio::test] + async fn another_signed_in_key_or_an_oversized_event_is_refused_before_signing() { + let host = IdentityHost::fixture(); + let (url, relay) = silent(); + let other = "ab".repeat(32); + let error = publish( + &host, + None, + url.clone(), + &grants(&[47000]), + &other, + template(47000, 1), + ) + .await + .err() + .unwrap(); + assert_eq!(error, "Your identity changed. Try again."); + let viewer = host.viewer().await.unwrap(); + let mut large = template(47000, 1); + large.content = "x".repeat(64 * 1024 + 1); + let error = publish(&host, None, url, &grants(&[47000]), &viewer, large) + .await + .err() + .unwrap(); + assert_eq!(error, "Event is too large"); + untouched(&relay); + } + + #[tokio::test] + async fn the_relays_own_refusal_text_comes_back_unchanged_for_every_conflict() { + let host = IdentityHost::fixture(); + let viewer = host.viewer().await.unwrap(); + let id = id_of(&host, template(47000, 1)).await; + for (status, body, message) in [ + ( + "409 Conflict", + r#"{"error":"duplicate: that name is taken"}"#, + "duplicate: that name is taken", + ), + ( + "409 Conflict", + r#"{"error":"conflict: expected revision abc"}"#, + "conflict: expected revision abc", + ), + ( + "403 Forbidden", + r#"{"error":"restricted: members only"}"#, + "restricted: members only", + ), + ( + "429 Too Many Requests", + r#"{"error":"rate-limited: slow down"}"#, + "rate-limited: slow down", + ), + ( + "422 Unprocessable Entity", + "not json", + "Relay rejected the event (422)", + ), + ] { + let (url, relay) = fixture_server(reply(status, body)); + let result = publish( + &host, + None, + url, + &grants(&[47000]), + &viewer, + template(47000, 1), + ) + .await + .unwrap(); + relay.join().unwrap(); + assert_eq!( + ( + result.event_id.as_str(), + result.accepted, + result.message.as_str() + ), + (id.as_str(), false, message) + ); + } + let (url, relay) = fixture_server(reply( + "200 OK", + &format!(r#"{{"event_id":"{id}","accepted":false,"message":"blocked: not allowed"}}"#), + )); + let result = publish( + &host, + None, + url, + &grants(&[47000]), + &viewer, + template(47000, 1), + ) + .await + .unwrap(); + relay.join().unwrap(); + assert_eq!( + (result.accepted, result.message.as_str()), + (false, "blocked: not allowed") + ); + } + + #[tokio::test] + async fn an_answer_that_is_not_the_relays_receipt_is_an_unknown_outcome() { + let host = IdentityHost::fixture(); + let viewer = host.viewer().await.unwrap(); + for (status, body) in [ + ("500 Internal Server Error", r#"{"error":"error: boom"}"#), + ("503 Service Unavailable", r#"{"sent":false}"#), + ("200 OK", r#"{"event_id":"other","accepted":true}"#), + ("200 OK", "captive portal"), + ] { + let (url, relay) = fixture_server(reply(status, body)); + let error = publish( + &host, + None, + url, + &grants(&[47000]), + &viewer, + template(47000, 1), + ) + .await + .err() + .unwrap(); + relay.join().unwrap(); + assert!(error.contains("outcome unknown"), "{status}: {error}"); + } + } + + #[tokio::test] + async fn a_long_relay_text_is_cut_by_characters() { + let host = IdentityHost::fixture(); + let viewer = host.viewer().await.unwrap(); + let long = "é".repeat(MESSAGE_CHARS + 100); + let (url, relay) = + fixture_server(reply("409 Conflict", &format!(r#"{{"error":"{long}"}}"#))); + let result = publish( + &host, + None, + url, + &grants(&[47000]), + &viewer, + template(47000, 1), + ) + .await + .unwrap(); + relay.join().unwrap(); + assert_eq!(result.message.chars().count(), MESSAGE_CHARS); + } + + #[tokio::test] + async fn the_same_template_is_sent_as_the_same_event_even_when_hours_old() { + let host = IdentityHost::fixture(); + let viewer = host.viewer().await.unwrap(); + let old = 1_700_000_000; + let id = id_of(&host, template(47000, old)).await; + let mut sent = Vec::new(); + for _ in 0..2 { + let (url, relay) = fixture_server(reply( + "200 OK", + &format!( + r#"{{"event_id":"{id}","accepted":true,"message":"duplicate: already stored"}}"# + ), + )); + let result = publish( + &host, + None, + url, + &grants(&[47000]), + &viewer, + template(47000, old), + ) + .await + .unwrap(); + assert_eq!(result.message, "duplicate: already stored"); + let (_, body) = relay.join().unwrap(); + sent.push(serde_json::from_str::(&body).unwrap()); + } + assert_eq!(sent[0]["id"], sent[1]["id"]); + assert_eq!(sent[0]["id"], id.as_str()); + assert_eq!(sent[1]["created_at"], old); + } +} diff --git a/src-tauri/src/relay/tests.rs b/src-tauri/src/relay/tests.rs index e9ab7c2daf..861477352e 100644 --- a/src-tauri/src/relay/tests.rs +++ b/src-tauri/src/relay/tests.rs @@ -198,7 +198,7 @@ fn member_commands_sign_only_the_broker_shape() { } } -fn fixture_server(response: String) -> (Url, std::thread::JoinHandle<(String, String)>) { +pub(super) fn fixture_server(response: String) -> (Url, std::thread::JoinHandle<(String, String)>) { let listener = TcpListener::bind("127.0.0.1:0").unwrap(); let url = Url::parse(&format!("http://{}/query", listener.local_addr().unwrap())).unwrap(); let task = std::thread::spawn(move || { diff --git a/src/app/PluginAccessReview.test.tsx b/src/app/PluginAccessReview.test.tsx index d3b053de74..442035c765 100644 --- a/src/app/PluginAccessReview.test.tsx +++ b/src/app/PluginAccessReview.test.tsx @@ -12,7 +12,10 @@ import { afterEach, expect, it } from "vitest"; import { AgentsContext } from "../features/agents/react"; import type { Agents } from "../features/agents/service"; import type { PluginManifest } from "../plugins/api"; -import { PluginAccessReview } from "./PluginAccessReview"; +import { + PluginAccessReview, + pluginAccessIncreases, +} from "./PluginAccessReview"; afterEach(cleanup); @@ -267,3 +270,89 @@ it.each([ ).toBeVisible(); }, ); + +const PURPOSES: Record = { + 47000: "Create or edit a group", + 47001: "Delete a group", + 47002: "Change who can manage groups", +}; +const withKinds = ( + kinds?: readonly number[], + purposes: Record = PURPOSES, +): PluginManifest => ({ + id: "example.kinds", + name: "Kind publisher", + apiVersion: 1, + host: kinds + ? { + relayKinds: kinds.map((kind) => ({ + kind, + purpose: purposes[kind] ?? "", + })), + } + : {}, +}); + +it("shows what each declared relay kind does, sent as the viewer", () => { + render(); + expect( + screen.getByRole("button", { + name: /Sign and send as you: Create or edit a group.*Buzz signs these events with your key/, + }), + ).toBeVisible(); + expect( + screen.getByRole("button", { + name: /Sign and send as you: Delete a group/, + }), + ).toBeVisible(); +}); + +it("lists an added relay kind as added and ignores their order", () => { + render( + , + ); + const added = within( + screen.getByRole("region", { name: "Added declarations" }), + ); + expect( + added.getByRole("button", { name: /Change who can manage groups/ }), + ).toBeVisible(); + expect( + added.queryByRole("button", { name: /Create or edit a group/ }), + ).toBeNull(); +}); + +it("lists a reworded relay kind purpose as changed", () => { + render( + , + ); + expect( + within( + screen.getByRole("region", { name: "Changed declarations" }), + ).getByRole("button", { + name: /Create, edit or rename a group \(changed\)/, + }), + ).toBeVisible(); +}); + +it("treats an added kind or a reworded purpose as an access increase, but not a reorder or removal", () => { + const before = withKinds([47000, 47001]); + expect(pluginAccessIncreases(withKinds([47000, 47001, 47002]), before)).toBe( + true, + ); + expect( + pluginAccessIncreases( + withKinds([47000, 47001], { ...PURPOSES, 47001: "Delete any group" }), + before, + ), + ).toBe(true); + expect(pluginAccessIncreases(withKinds([47001, 47000]), before)).toBe(false); + expect(pluginAccessIncreases(withKinds([47000]), before)).toBe(false); + expect(pluginAccessIncreases(before, withKinds())).toBe(true); +}); diff --git a/src/app/PluginAccessReview.tsx b/src/app/PluginAccessReview.tsx index e01b2e85aa..2a0b90152a 100644 --- a/src/app/PluginAccessReview.tsx +++ b/src/app/PluginAccessReview.tsx @@ -105,6 +105,23 @@ function hostDeclarations( icon: GlobeIcon, details: {origin}, })), + ...(manifest.host?.relayKinds ?? []).map(({ kind, purpose }) => ({ + key: `relayKind:${kind}`, + signature: `Relay event kind: ${kind} · purpose: ${JSON.stringify(purpose)}`, + title: "Relay event kind:", + name: `Relay event kind ${kind}`, + label: `Sign and send as you: ${purpose}`, + hint: "The plugin wrote this purpose. Buzz signs these events with your key and sends them to your community as you.", + icon: GlobeIcon, + details: ( + <> + {kind} +

+ Purpose, as the plugin describes it: {purpose} +

+ + ), + })), ...(manifest.host?.publicImages ? [ { diff --git a/src/features/host/service.test.ts b/src/features/host/service.test.ts index 8dc4eaa438..a288dbdf19 100644 --- a/src/features/host/service.test.ts +++ b/src/features/host/service.test.ts @@ -2,6 +2,8 @@ import { Context } from "@deepseek-ai/cordis"; import { invoke, isTauri } from "@tauri-apps/api/core"; import { afterEach, beforeEach, expect, it, vi } from "vitest"; import { HostService, type Host } from "./service"; +import { provideRelay } from "../relay/service"; +import type { ReadTransport } from "../relay/transport"; vi.mock("@tauri-apps/api/core", () => ({ isTauri: vi.fn(), @@ -1757,3 +1759,172 @@ it("stops a process after a failed streamed frame and rejects queued writes", as expect.objectContaining({ handle: 7 }), ); }); + +const VIEWER = "ab".repeat(32); +const ORIGIN = "https://relay.test"; +const INFO = { name: "Relay", self: "cd".repeat(32), limitation: { max: 3 } }; +const roots: Context[] = []; +afterEach(async () => { + for (const root of roots.splice(0)) await root.fiber.dispose(); +}); + +/** The real relay service, connected to a community that publishes `info`. */ +async function connectedPlugin(info: Record | undefined) { + const root = new Context(); + roots.push(root); + new HostService(root); + const connect = vi.fn( + async (): Promise => ({ + viewer: VIEWER, + relayAuthor: "cd".repeat(32), + scope: ORIGIN, + media: () => undefined, + query: async () => [], + ...(info ? { info } : {}), + }), + ); + const relay = provideRelay(root, connect); + await vi.waitFor(() => expect(relay.snapshot().status).toBe("ready")); + const plugin = root.extend({ + pluginOwner: { id: "example.plugin", revision: "abc" }, + }); + return { plugin, relay, scope: relay.snapshot().scope ?? "" }; +} +const template = { + kind: 47000, + content: "{}", + tags: [ + ["z", "1"], + ["a", "2"], + ], + created_at: 1_600_000_000, +}; +const receipt = { event_id: "ef".repeat(32), accepted: true, message: "" }; + +it("signs and sends the template for the selected community and viewer, unchanged", async () => { + const { plugin, scope, relay } = await connectedPlugin(INFO); + vi.mocked(invoke).mockResolvedValue(receipt); + const { generation } = relay.snapshot(); + expect(await plugin.host.publish?.(template, { scope, generation })).toEqual( + receipt, + ); + expect(invoke).toHaveBeenCalledWith("plugin_host_relay_publish", { + id: "example.plugin", + revision: "abc", + community: ORIGIN, + viewer: VIEWER, + event: { + kind: 47000, + content: "{}", + tags: [ + ["z", "1"], + ["a", "2"], + ], + created_at: 1_600_000_000, + }, + }); + const { created_at: _, ...undated } = template; + await plugin.host.publish?.(undated, { scope }); + const sent = vi.mocked(invoke).mock.calls[1]?.[1] as { + event: { created_at: number }; + }; + expect(Math.abs(sent.event.created_at - Date.now() / 1000)).toBeLessThan(60); +}); + +it.each([ + ["duplicate: that name is taken"], + ["conflict: expected revision abc"], +])("hands the relay's refusal %s to the caller unchanged", async (message) => { + const { plugin, scope } = await connectedPlugin(INFO); + vi.mocked(invoke).mockResolvedValue({ ...receipt, accepted: false, message }); + expect(await plugin.host.publish?.(template, { scope })).toEqual({ + ...receipt, + accepted: false, + message, + }); +}); + +it("surfaces a native refusal as an error, never as an accepted result", async () => { + const { plugin, scope } = await connectedPlugin(INFO); + vi.mocked(invoke).mockRejectedValue( + "This plugin did not declare that event kind", + ); + await expect(plugin.host.publish?.(template, { scope })).rejects.toThrow( + "did not declare", + ); +}); + +it("refuses a scope or generation that is not the selected connection", async () => { + const { plugin, scope, relay } = await connectedPlugin(INFO); + const { generation } = relay.snapshot(); + for (const options of [ + { scope: `https://other.test:${VIEWER}` }, + { scope: `${ORIGIN}:${"cd".repeat(32)}` }, + { scope, generation: generation + 1 }, + ]) { + await expect(plugin.host.publish?.(template, options)).rejects.toThrow( + "not the one selected", + ); + await expect(plugin.host.relayInfo?.(options)).rejects.toThrow( + "not the one selected", + ); + } + expect(invoke).not.toHaveBeenCalled(); +}); + +it("does not deliver a result as accepted once the session was replaced", async () => { + const { plugin, scope, relay } = await connectedPlugin(INFO); + let settle!: (value: unknown) => void; + vi.mocked(invoke).mockReturnValue( + new Promise((resolve) => (settle = resolve)), + ); + const pending = plugin.host.publish?.(template, { scope }); + const outcome = expect(pending).rejects.toThrow("outcome is unknown"); + await vi.waitFor(() => expect(invoke).toHaveBeenCalledTimes(1)); + relay.disconnect(); + relay.retry(); + await vi.waitFor(() => expect(relay.snapshot().status).toBe("ready")); + settle(receipt); + await outcome; +}); + +it("treats cancellation after dispatch as an unknown outcome and before it as an abort", async () => { + const { plugin, scope } = await connectedPlugin(INFO); + const early = new AbortController(); + early.abort(); + await expect( + plugin.host.publish?.(template, { scope, signal: early.signal }), + ).rejects.toMatchObject({ name: "AbortError" }); + expect(invoke).not.toHaveBeenCalled(); + let settle!: (value: unknown) => void; + vi.mocked(invoke).mockReturnValue( + new Promise((resolve) => (settle = resolve)), + ); + const late = new AbortController(); + const pending = plugin.host.publish?.(template, { + scope, + signal: late.signal, + }); + const outcome = expect(pending).rejects.toThrow("outcome is unknown"); + await vi.waitFor(() => expect(invoke).toHaveBeenCalledTimes(1)); + late.abort(); + await outcome; + settle(receipt); +}); + +it("returns the connected community's own document, frozen, and nothing else", async () => { + const { plugin, scope } = await connectedPlugin(INFO); + const info = await plugin.host.relayInfo?.({ scope }); + expect(info).toEqual(INFO); + expect(Object.isFrozen(info)).toBe(true); + expect(Object.isFrozen((info as typeof INFO).limitation)).toBe(true); + expect(info).not.toBe(INFO); + expect(invoke).not.toHaveBeenCalled(); +}); + +it("has no document to return when the connection carried none", async () => { + const { plugin, scope } = await connectedPlugin(undefined); + await expect(plugin.host.relayInfo?.({ scope })).rejects.toThrow( + "unavailable", + ); +}); diff --git a/src/features/host/service.ts b/src/features/host/service.ts index 7704957f16..ee557cbc3b 100644 --- a/src/features/host/service.ts +++ b/src/features/host/service.ts @@ -4,6 +4,8 @@ import type {} from "../../plugins/api"; import { nativeIdentityEnabled } from "../identity/service"; import type { SoloRegionBinding } from "../channel-navigation/solo-navigation-contract"; import { repositoryFolders } from "../communities/repositories"; +import { relayDocument, type RelayData } from "../relay/service"; +import type { RelaySession } from "../relay/session"; export type HostRequest = Readonly<{ url: string; @@ -41,6 +43,32 @@ export type HostByteUpload = Readonly<{ /** At most 16 text fields, safe names, each value at most 8192 UTF-8 bytes. */ fields?: Readonly>; }>; +/** An event to sign as the viewer. `created_at` defaults to now; when given it + * is kept, with the tags in order, so the same template is the same event. */ +export type HostEventTemplate = Readonly<{ + kind: number; + content: string; + tags: readonly (readonly string[])[]; + created_at?: number; +}>; +/** The community a call is for, as `RelaySnapshot` names it. A call refuses + * when another community, account or connection is selected. */ +export type HostRelayScope = Readonly<{ + /** `origin:viewer`, as `RelaySnapshot.scope`. */ + scope: string; + /** `RelaySnapshot.generation`; omitted, any connection of that scope. */ + generation?: number; + signal?: AbortSignal; +}>; +/** The relay's own answer, its OK or refusal text kept as sent (at most 512 + * characters). `accepted: false` is a refusal; a rejection is an unknown + * outcome. Sending the same template again sends the same event id; whether + * the relay answers it from its receipt, at any age, is up to the relay. */ +export type HostPublication = Readonly<{ + event_id: string; + accepted: boolean; + message: string; +}>; export type HostResponse = Readonly<{ status: number; headers: Readonly>; @@ -239,6 +267,20 @@ export interface Host { binding: SoloRegionBinding, signal: AbortSignal, ) => Promise; + /** Signs `template` as the viewer and publishes it to the selected community, + * for a plugin whose manifest declares its kind in `host.relayKinds`. Never + * a kind Buzz reserves. Sent once, never replayed: resolve it by calling + * again with the same template, which the relay answers by event id. Desktop + * only. */ + publish?: ( + template: HostEventTemplate, + options: HostRelayScope, + ) => Promise; + /** The selected community's NIP-11 document as Buzz read it to connect, a + * frozen copy. Needs no grant. Desktop only. */ + relayInfo?: ( + options: HostRelayScope, + ) => Promise>>; request(input: HostRequest): Promise; /** POST-only, desktop and compatible native host required. A repeated call * authority rejects with unknown outcome, never resubmits or caches success. @@ -676,6 +718,57 @@ export class HostService extends Service implements Host { ); } + async publish( + template: HostEventTemplate, + { scope, generation, signal }: HostRelayScope, + ): Promise { + const owner = this.ctx.pluginOwner; + if (!owner || !isTauri()) + throw new Error("Publishing requires an installed desktop plugin"); + signal?.throwIfAborted(); + const selected = selectedRelay(this.ctx, scope, generation); + const { kind, content, tags, created_at } = template; + const event = { + kind, + content, + tags: tags.map((tag) => [...tag]), + created_at: created_at ?? Math.floor(Date.now() / 1000), + }; + // Dispatched: from here the relay may have the event, whatever follows. + const sent = invoke("plugin_host_relay_publish", { + id: owner.id, + revision: owner.revision, + community: selected.origin, + viewer: selected.viewer, + event, + }).catch(rethrow); + let stop: (() => void) | undefined; + const cancelled = new Promise((_, reject) => { + stop = () => reject(new Error(UNKNOWN_PUBLISH)); + signal?.addEventListener("abort", stop, { once: true }); + }); + try { + const result = await Promise.race([sent, cancelled]); + if (!sameRelay(this.ctx, selected)) throw new Error(UNKNOWN_PUBLISH); + return result; + } finally { + if (stop) signal?.removeEventListener("abort", stop); + } + } + + async relayInfo({ + scope, + generation, + signal, + }: HostRelayScope): Promise>> { + signal?.throwIfAborted(); + const info = relayDocument( + selectedRelay(this.ctx, scope, generation).session, + ); + if (!info) throw new Error("This community's information is unavailable"); + return deepFreeze(structuredClone(info)); + } + async request(input: HostRequest): Promise { const owner = this.ctx.pluginOwner; if (!owner || !isTauri()) @@ -879,6 +972,59 @@ export class HostService extends Service implements Host { } } +const UNKNOWN_PUBLISH = + "The publish was cut short after it was sent; its outcome is unknown. Publish the same template again to find out."; + +type SelectedRelay = Readonly<{ + origin: string; + viewer: string; + scope: string; + generation: number; + session: RelaySession; +}>; +/** The one connected, live community `scope` and `generation` name. */ +function selectedRelay( + ctx: Context, + scope: string, + generation: number | undefined, +): SelectedRelay { + const relay: RelayData | undefined = ctx.relay; + const snapshot = relay?.snapshot(); + if ( + snapshot?.status !== "ready" || + snapshot.cached || + !snapshot.origin || + !snapshot.viewer || + snapshot.scope !== scope || + (generation !== undefined && snapshot.generation !== generation) + ) + throw new Error("That community is not the one selected"); + return { + origin: snapshot.origin, + viewer: snapshot.viewer, + scope, + generation: snapshot.generation, + session: snapshot.session, + }; +} +/** Whether `selected` is still the connection in use. */ +function sameRelay(ctx: Context, selected: SelectedRelay) { + const now = ctx.relay?.snapshot(); + return ( + now?.status === "ready" && + now.scope === selected.scope && + now.generation === selected.generation && + now.session === selected.session + ); +} +function deepFreeze(value: T): T { + if (value && typeof value === "object" && !Object.isFrozen(value)) { + Object.freeze(value); + for (const child of Object.values(value)) deepFreeze(child); + } + return value; +} + const UPLOAD_METADATA_LIMIT = 16 * 1024; // HTTP IPC headers are ASCII; JSON escapes preserve Unicode field values. function asciiJson(value: unknown): string { diff --git a/src/features/relay/native.test.ts b/src/features/relay/native.test.ts index 891c50e3c2..9f86e58697 100644 --- a/src/features/relay/native.test.ts +++ b/src/features/relay/native.test.ts @@ -192,6 +192,17 @@ it("requires the relay self key, never its operator contact pubkey", async () => ); }); +it("keeps the community's NIP-11 document from connecting, without another read", async () => { + discovery = { name: "Example", supported_extensions: ["nip-cl"] }; + const transport = await connectNativeTransport(community); + expect(transport.info).toEqual({ + self: relay.pubkey, + name: "Example", + supported_extensions: ["nip-cl"], + }); + expect(requests.filter(({ path }) => path === "/")).toHaveLength(1); +}); + it("sends combined search operators through packaged native signed HTTP without a dev broker", async () => { const transport = await connectNativeTransport(community); const hit = message(viewer, "channel", "deploy matched", 1700000000); diff --git a/src/features/relay/native.ts b/src/features/relay/native.ts index 8e202c6ad4..5a017183ef 100644 --- a/src/features/relay/native.ts +++ b/src/features/relay/native.ts @@ -521,6 +521,7 @@ export async function connectNativeTransport( // Capabilities describe implemented host operations, not everything this key can sign. return { ...transport, + info, observeRefusal, ...(artifactIncrementalCapability(info) ? { diff --git a/src/features/relay/service.ts b/src/features/relay/service.ts index 9696244bb5..9484363047 100644 --- a/src/features/relay/service.ts +++ b/src/features/relay/service.ts @@ -25,6 +25,14 @@ const REFUSAL_ERRORS: Record = { const WAKE_TICK_MS = 5_000; const WAKE_GAP_MS = 15_000; +/** Each connected session's NIP-11 document, read once while connecting. */ +const documents = new WeakMap< + RelaySession, + Readonly> +>(); +/** The NIP-11 document `session`'s community answered when it connected. */ +export const relayDocument = (session: RelaySession) => documents.get(session); + export type RelaySnapshot = Readonly<{ status: "disconnected" | "connecting" | "ready" | "error"; generation: number; @@ -372,6 +380,7 @@ export function provideRelay( ), }); await successor.restore(); + if (transport.info) documents.set(successor.session, transport.info); if ( disposed || signal.aborted || diff --git a/src/features/relay/transport.ts b/src/features/relay/transport.ts index f7558cf6e4..3b15e66c71 100644 --- a/src/features/relay/transport.ts +++ b/src/features/relay/transport.ts @@ -197,6 +197,8 @@ export interface ReadTransport { readonly scope?: string; /** Relay HTTP base for display only, such as a workflow's webhook address. */ readonly relayHttpUrl?: string; + /** The community's NIP-11 document, as the host fetched it to connect. */ + readonly info?: Readonly>; /** Optional host-owned write capability, exposed to plugins only through the outbox. */ readonly writer?: RelayWriter; /** The signed-in viewer whose channel roster is authoritative. */ diff --git a/src/plugins/api.ts b/src/plugins/api.ts index 3c6647bd8c..7a474f8913 100644 --- a/src/plugins/api.ts +++ b/src/plugins/api.ts @@ -40,6 +40,11 @@ export type PluginManifest = Readonly<{ }>; }>[]; networkOrigins?: readonly string[]; + /** Event kinds the plugin may sign as the viewer and publish with + * `host.publish`: distinct integers 1–65535, at most 8, never a kind Buzz + * reserves. `purpose` says what those events do, in 1–120 bytes of text + * without control characters; the install screen shows it. */ + relayKinds?: readonly Readonly<{ kind: number; purpose: string }>[]; /** Separate authority access; ordinary HTTPS grants never authorize a session. */ federatedIdentity?: Readonly<{ authority: string;