From ae0f41070fffec37229821dce4dababea0e030f0 Mon Sep 17 00:00:00 2001 From: Logan Johnson Date: Mon, 31 Aug 2026 14:56:18 -0400 Subject: [PATCH] feat: checkpoint private host inventory and fenced execution foundations Preserve the reconciled Multiverse candidate: owner-private encrypted host history and run presence, exact signed execution commands/receipts, durable generation-fenced journal, and disabled native execution seams. Preserve derived-channel h matching in shared SQL query/count for mixed host filters, with isolated database regression. Remote command admission/receiver, Start UI and Move are not enabled. Root-only teardown remains insufficient for replacement. Move semantics are approved: selected-run stop-confirm, fresh same-agent destination session, no automatic workspace/file transfer. Core/DB/pubsub/ACP suites and explicit history integrations pass; the unchanged mesh demo echo test still times out (504 vs 200) in the full relay suite and isolated retry. This is a source checkpoint, not a packaged or deployment-ready feature. Signed-off-by: Logan Johnson --- crates/buzz-acp/src/lib.rs | 36 +- crates/buzz-acp/src/run_presence.rs | 84 ++++ crates/buzz-core/src/filter.rs | 2 +- crates/buzz-core/src/host.rs | 385 +++++++++++++++ crates/buzz-core/src/host_execution.rs | 440 +++++++++++++++++ crates/buzz-core/src/kind.rs | 12 +- crates/buzz-core/src/lib.rs | 8 + crates/buzz-core/src/run_presence.rs | 184 +++++++ crates/buzz-db/src/runtime/migration.rs | 8 +- crates/buzz-db/src/store/event.rs | 33 ++ crates/buzz-pubsub/src/error.rs | 3 + crates/buzz-pubsub/src/lib.rs | 33 +- crates/buzz-pubsub/src/run_presence.rs | 127 +++++ crates/buzz-relay/src/api/bridge.rs | 89 +++- crates/buzz-relay/src/handlers/event.rs | 254 +++++++--- .../event/tests/host_transport_tests.rs | 357 ++++++++++++++ crates/buzz-relay/src/handlers/history.rs | 73 +++ .../buzz-relay/src/handlers/history/tests.rs | 299 ++++++++++++ .../src/handlers/history/tests/mixed_tags.rs | 95 ++++ .../src/handlers/history/tests/paging.rs | 142 ++++++ crates/buzz-relay/src/handlers/hosts.rs | 163 +++++++ crates/buzz-relay/src/handlers/ingest.rs | 12 +- crates/buzz-relay/src/handlers/mod.rs | 5 + crates/buzz-relay/src/handlers/req.rs | 92 +++- crates/buzz-relay/src/main.rs | 79 ++- crates/buzz-relay/src/metrics.rs | 8 +- desktop/src-tauri/Cargo.lock | 1 + desktop/src-tauri/Cargo.toml | 1 + .../src-tauri/src/commands/host_execution.rs | 150 ++++++ desktop/src-tauri/src/commands/hosts.rs | 452 ++++++++++++++++++ desktop/src-tauri/src/commands/mod.rs | 4 + desktop/src-tauri/src/commands/profile.rs | 3 +- desktop/src-tauri/src/lib.rs | 10 + .../src-tauri/src/managed_agents/execution.rs | 270 +++++++++++ .../src/managed_agents/execution_ledger.rs | 328 +++++++++++++ .../src/managed_agents/host_location.rs | 17 + desktop/src-tauri/src/managed_agents/mod.rs | 5 + .../src/managed_agents/reserved_env_keys.rs | 2 + .../src-tauri/src/managed_agents/restore.rs | 1 + .../src-tauri/src/managed_agents/runtime.rs | 43 +- .../src/managed_agents/runtime/process.rs | 81 ++++ .../src/managed_agents/runtime/spawn_entry.rs | 41 ++ .../managed_agents/runtime/test_fixtures.rs | 12 + .../src/managed_agents/runtime/tests.rs | 12 +- .../src/managed_agents/runtime_commands.rs | 3 + .../src/managed_agents/runtime_types.rs | 5 + desktop/src-tauri/src/secret_store.rs | 385 +-------------- .../src-tauri/src/secret_store/host_key.rs | 20 + desktop/src-tauri/src/secret_store/tests.rs | 380 +++++++++++++++ .../src/app/useAppShellLifecycleEffects.ts | 10 + .../agents/lib/otherSetupAgent.test.mjs | 42 +- .../features/agents/lib/otherSetupAgent.ts | 26 +- .../features/agents/ui/AgentHostMarker.tsx | 46 ++ desktop/src/features/agents/ui/AgentsView.tsx | 2 + .../agents/ui/LiveAgentHostMarker.tsx | 22 + .../agents/ui/OtherSetupAgentMarker.tsx | 32 +- .../agents/useKnownAgentPubkeys.test.mjs | 73 +++ .../features/agents/useKnownAgentPubkeys.tsx | 71 ++- .../channels/ui/ChannelScreenHeader.tsx | 15 +- .../channels/ui/MembersSidebarMemberCard.tsx | 12 +- .../features/communities/useCommunityInit.ts | 3 + desktop/src/features/hosts/HostsSection.tsx | 104 ++++ desktop/src/features/hosts/history.test.mjs | 108 +++++ desktop/src/features/hosts/history.ts | 50 ++ .../features/hosts/hostNativeDrain.test.mjs | 113 +++++ desktop/src/features/hosts/hostNativeDrain.ts | 15 + .../src/features/hosts/hostTestFixtures.mjs | 135 ++++++ .../hosts/pendingPublication.test.mjs | 319 ++++++++++++ .../src/features/hosts/pendingPublication.ts | 123 +++++ .../src/features/hosts/projection.test.mjs | 266 +++++++++++ .../src/features/hosts/registration.test.mjs | 249 ++++++++++ desktop/src/features/hosts/registration.ts | 307 ++++++++++++ .../hosts/registrationLifecycle.test.mjs | 189 ++++++++ .../features/hosts/registrationLifecycle.ts | 69 +++ .../src/features/hosts/reportValidation.ts | 74 +++ desktop/src/features/hosts/transport.test.mjs | 362 ++++++++++++++ desktop/src/features/hosts/useHostPresence.ts | 66 +++ .../src/features/hosts/useHostRegistration.ts | 135 ++++++ .../messages/ui/LiveMentionAutocomplete.tsx | 21 + .../messages/ui/MentionAutocomplete.test.mjs | 36 ++ .../messages/ui/MentionAutocomplete.tsx | 22 +- .../messages/ui/MessageAgentAddressPrefix.tsx | 5 + .../features/messages/ui/MessageComposer.tsx | 2 +- .../features/messages/ui/MessageHeader.tsx | 40 ++ .../src/features/messages/ui/MessageRow.tsx | 25 +- desktop/src/features/presence/hooks.ts | 45 +- .../features/presence/runPresence.test.mjs | 26 + desktop/src/features/presence/runPresence.ts | 34 ++ .../presence/usePresenceRuns.test.mjs | 156 ++++++ .../src/features/presence/usePresenceRuns.ts | 52 ++ .../ui/UserProfilePanelHeaderContent.tsx | 10 + .../profile/ui/UserProfilePanelSections.tsx | 6 + .../profile/ui/UserProfilePopover.tsx | 7 + .../features/sidebar/ui/SidebarSection.tsx | 7 + desktop/src/shared/api/readOnlyRelayClient.ts | 37 +- desktop/src/shared/ui/markdown.tsx | 48 +- .../shared/ui/markdown/MarkdownMention.tsx | 52 ++ docs/host-execution.md | 106 ++++ migrations/0041_host_fts.sql | 26 + schema/schema.sql | 4 +- 100 files changed, 8403 insertions(+), 651 deletions(-) create mode 100644 crates/buzz-acp/src/run_presence.rs create mode 100644 crates/buzz-core/src/host.rs create mode 100644 crates/buzz-core/src/host_execution.rs create mode 100644 crates/buzz-core/src/run_presence.rs create mode 100644 crates/buzz-pubsub/src/run_presence.rs create mode 100644 crates/buzz-relay/src/handlers/event/tests/host_transport_tests.rs create mode 100644 crates/buzz-relay/src/handlers/history.rs create mode 100644 crates/buzz-relay/src/handlers/history/tests.rs create mode 100644 crates/buzz-relay/src/handlers/history/tests/mixed_tags.rs create mode 100644 crates/buzz-relay/src/handlers/history/tests/paging.rs create mode 100644 crates/buzz-relay/src/handlers/hosts.rs create mode 100644 desktop/src-tauri/src/commands/host_execution.rs create mode 100644 desktop/src-tauri/src/commands/hosts.rs create mode 100644 desktop/src-tauri/src/managed_agents/execution.rs create mode 100644 desktop/src-tauri/src/managed_agents/execution_ledger.rs create mode 100644 desktop/src-tauri/src/managed_agents/host_location.rs create mode 100644 desktop/src-tauri/src/managed_agents/runtime/spawn_entry.rs create mode 100644 desktop/src-tauri/src/secret_store/host_key.rs create mode 100644 desktop/src-tauri/src/secret_store/tests.rs create mode 100644 desktop/src/features/agents/ui/AgentHostMarker.tsx create mode 100644 desktop/src/features/agents/ui/LiveAgentHostMarker.tsx create mode 100644 desktop/src/features/agents/useKnownAgentPubkeys.test.mjs create mode 100644 desktop/src/features/hosts/HostsSection.tsx create mode 100644 desktop/src/features/hosts/history.test.mjs create mode 100644 desktop/src/features/hosts/history.ts create mode 100644 desktop/src/features/hosts/hostNativeDrain.test.mjs create mode 100644 desktop/src/features/hosts/hostNativeDrain.ts create mode 100644 desktop/src/features/hosts/hostTestFixtures.mjs create mode 100644 desktop/src/features/hosts/pendingPublication.test.mjs create mode 100644 desktop/src/features/hosts/pendingPublication.ts create mode 100644 desktop/src/features/hosts/projection.test.mjs create mode 100644 desktop/src/features/hosts/registration.test.mjs create mode 100644 desktop/src/features/hosts/registration.ts create mode 100644 desktop/src/features/hosts/registrationLifecycle.test.mjs create mode 100644 desktop/src/features/hosts/registrationLifecycle.ts create mode 100644 desktop/src/features/hosts/reportValidation.ts create mode 100644 desktop/src/features/hosts/transport.test.mjs create mode 100644 desktop/src/features/hosts/useHostPresence.ts create mode 100644 desktop/src/features/hosts/useHostRegistration.ts create mode 100644 desktop/src/features/messages/ui/LiveMentionAutocomplete.tsx create mode 100644 desktop/src/features/presence/runPresence.test.mjs create mode 100644 desktop/src/features/presence/runPresence.ts create mode 100644 desktop/src/features/presence/usePresenceRuns.test.mjs create mode 100644 desktop/src/features/presence/usePresenceRuns.ts create mode 100644 desktop/src/shared/ui/markdown/MarkdownMention.tsx create mode 100644 docs/host-execution.md create mode 100644 migrations/0041_host_fts.sql diff --git a/crates/buzz-acp/src/lib.rs b/crates/buzz-acp/src/lib.rs index 2de474ac1e..b5f16737ef 100644 --- a/crates/buzz-acp/src/lib.rs +++ b/crates/buzz-acp/src/lib.rs @@ -84,29 +84,8 @@ fn current_working_directory() -> Result { Ok(cwd.to_string_lossy().into_owned()) } -/// Publish a kind:20001 presence update event via the WebSocket connection. -/// -/// Ephemeral kinds (20000-29999) are rejected by the HTTP bridge, so presence -/// updates must be routed through the WS path. -/// -/// Content is a bare status string (`"online"`, `"away"`, `"offline"`) matching -/// the desktop client's format. The relay stores this in Redis and synthesizes -/// it back on presence queries. -async fn publish_presence( - publisher: &relay::RelayEventPublisher, - keys: &nostr::Keys, - status: &str, -) -> Result<(), relay::RelayError> { - use buzz_core::kind::KIND_PRESENCE_UPDATE; - use nostr::{EventBuilder, Kind}; - - let event = EventBuilder::new(Kind::Custom(KIND_PRESENCE_UPDATE as u16), status) - .tags([]) - .sign_with_keys(keys) - .map_err(|e| relay::RelayError::Http(format!("presence sign error: {e}")))?; - publisher.publish_event(event).await?; - Ok(()) -} +mod run_presence; +use run_presence::PresencePublisher; fn emit_runtime_lifecycle( observer: Option<&observer::ObserverHandle>, @@ -2649,8 +2628,12 @@ async fn tokio_main() -> Result<()> { // Online means the harness can receive work, not merely that its socket is // connected. Publishing after channel subscriptions gives desktop callers // a durable readiness boundary before they send a startup mention. + let run_presence = PresencePublisher::from_env().map_err(anyhow::Error::msg)?; if config.presence_enabled { - match publish_presence(&presence_publisher, &presence_keys, "online").await { + match run_presence + .publish(&presence_publisher, &presence_keys, "online") + .await + { Ok(_) => tracing::info!("presence set to online"), Err(e) => tracing::warn!("failed to set initial presence: {e}"), } @@ -3509,8 +3492,9 @@ async fn tokio_main() -> Result<()> { } let pp = presence_publisher.clone(); let pk = presence_keys.clone(); + let pulse = run_presence.clone(); presence_task = Some(tokio::spawn(async move { - if let Err(e) = publish_presence(&pp, &pk, "online").await { + if let Err(e) = pulse.publish(&pp, &pk, "online").await { tracing::warn!("presence heartbeat failed: {e}"); } })); @@ -3916,7 +3900,7 @@ async fn tokio_main() -> Result<()> { if config.presence_enabled { match tokio::time::timeout( Duration::from_secs(2), - publish_presence(&presence_publisher, &presence_keys, "offline"), + run_presence.publish(&presence_publisher, &presence_keys, "offline"), ) .await { diff --git a/crates/buzz-acp/src/run_presence.rs b/crates/buzz-acp/src/run_presence.rs new file mode 100644 index 0000000000..f80b84ccf2 --- /dev/null +++ b/crates/buzz-acp/src/run_presence.rs @@ -0,0 +1,84 @@ +//! One presence generation per harness process, independent of parallel sessions. +use crate::relay::{RelayError, RelayEventPublisher}; +use buzz_core::run_presence::{self, Location}; +use std::sync::{ + atomic::{AtomicU64, Ordering}, + Arc, +}; + +#[derive(Clone)] +pub(crate) struct PresencePublisher { + run: String, + seq: Arc, + location: Option, +} +impl PresencePublisher { + pub(crate) fn from_env() -> Result { + let location = std::env::var("BUZZ_ACP_HOST_PUBKEY") + .ok() + .zip(std::env::var("BUZZ_ACP_HOST_LABEL").ok()) + .map(|(host, label)| Location { host, label }) + .filter(|l| l.validate().is_ok()); + let launcher = match std::env::var("BUZZ_MANAGED_AGENT_START_NONCE") { + Ok(value) => Some(value), + Err(std::env::VarError::NotPresent) => None, + Err(_) => return Err("invalid launcher run generation".into()), + }; + Ok(Self { + run: run_generation(launcher.as_deref())?, + seq: Arc::new(AtomicU64::new(0)), + location, + }) + } + pub(crate) async fn publish( + &self, + publisher: &RelayEventPublisher, + keys: &nostr::Keys, + status: &str, + ) -> Result<(), RelayError> { + let event = run_presence::pulse( + keys, + &self.run, + self.seq.fetch_add(1, Ordering::SeqCst), + status, + self.location.as_ref(), + None, + nostr::Timestamp::now().as_secs(), + ) + .map_err(RelayError::Http)?; + publisher.publish_event(event).await?; + Ok(()) + } +} + +// The launcher generation is the public run ID, not a second random identity. +// Standalone harnesses still generate their own run. A malformed launcher ID +// must fail startup rather than publish a run the controller cannot fence. +fn run_generation(launcher: Option<&str>) -> Result { + match launcher { + Some(id) + if id.len() == 32 + && id + .bytes() + .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b)) => + { + Ok(id.to_owned()) + } + Some(_) => Err("invalid launcher run generation".into()), + None => Ok(uuid::Uuid::new_v4().simple().to_string()), + } +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn presence_uses_exact_launcher_generation() { + let id = "ab".repeat(16); + assert_eq!(run_generation(Some(&id)).unwrap(), id); + for bad in ["", "test-generation", &"AB".repeat(16), &"aa".repeat(32)] { + assert!(run_generation(Some(bad)).is_err()); + } + assert_ne!(run_generation(None).unwrap(), run_generation(None).unwrap()); + } +} diff --git a/crates/buzz-core/src/filter.rs b/crates/buzz-core/src/filter.rs index 32e3a7ad16..389b56b7ec 100644 --- a/crates/buzz-core/src/filter.rs +++ b/crates/buzz-core/src/filter.rs @@ -22,7 +22,7 @@ pub fn filters_match(filters: &[Filter], event: &StoredEvent) -> bool { /// a known event id) still cannot read another user's private event. pub fn reader_authorized_for_event(event: &nostr::Event, reader_pubkey_hex: &str) -> bool { let kind = crate::kind::event_kind_u32(event); - if kind != crate::kind::KIND_DM_VISIBILITY && kind != crate::kind::KIND_AGENT_TURN_METRIC { + if !crate::kind::RESULT_GATED_KINDS.contains(&kind) { return true; } let p = nostr::SingleLetterTag::lowercase(nostr::Alphabet::P); diff --git a/crates/buzz-core/src/host.rs b/crates/buzz-core/src/host.rs new file mode 100644 index 0000000000..e20e4afaf0 --- /dev/null +++ b/crates/buzz-core/src/host.rs @@ -0,0 +1,385 @@ +//! Versioned, owner-private host events. Kind 50000 is append-only, not NIP-33. +use base64::Engine; +use nostr::{nips::nip44, Event, EventBuilder, Keys, Kind, PublicKey, Tag, Timestamp}; +use serde::{Deserialize, Serialize}; + +use crate::kind::KIND_HOST; + +/// Namespace for host labels (NIP-32-shaped tags). +pub const NAMESPACE: &str = "buzz.host.v1"; +/// Maximum lifetime of a host report, independent of agent presence. +pub const REPORT_TTL: u64 = 180; + +/// Validated public routing envelope. Machine metadata is never in tags. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Envelope { + /// Owner allowed to read the event. + pub owner: PublicKey, + /// Stable host key (also the host identifier). + pub host: PublicKey, + /// Registration or report. + pub label: String, + /// Owner-signed registration referenced by a report. + pub registration: Option, + /// Readiness deadline; not a NIP-40 deletion deadline. + pub valid_until: Option, +} + +fn one<'a>(event: &'a Event, key: &str, size: usize) -> Result<&'a [String], String> { + let mut tags = event.tags.iter().filter(|t| t.as_slice()[0] == key); + let tag = tags.next().ok_or_else(|| format!("missing {key} tag"))?; + if tags.next().is_some() || tag.as_slice().len() != size { + return Err(format!("invalid {key} tag cardinality")); + } + Ok(tag.as_slice()) +} + +fn pubkey(value: &str) -> Result { + if value.len() != 64 + || !value + .bytes() + .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b)) + { + return Err("expected lowercase hex pubkey".into()); + } + PublicKey::from_hex(value).map_err(|e| e.to_string()) +} + +/// Validate routing and signatures without decrypting private machine details. +pub fn validate(event: &Event) -> Result { + if event.kind.as_u16() as u32 != KIND_HOST { + return Err("not a host event".into()); + } + crate::verify_event(event).map_err(|e| e.to_string())?; + if one(event, "L", 2)?[1] != NAMESPACE { + return Err("unknown host namespace".into()); + } + let l = one(event, "l", 3)?; + if l[2] != NAMESPACE || !matches!(l[1].as_str(), "registration" | "report" | "profile") { + return Err("unknown host label".into()); + } + let owner = pubkey(&one(event, "p", 2)?[1])?; + let host = pubkey(&one(event, "x", 2)?[1])?; + let report = l[1] != "registration"; + let allowed = if report { + if l[1] == "report" { + &["L", "l", "p", "x", "e", "valid_until"][..] + } else { + &["L", "l", "p", "x", "e"][..] + } + } else { + &["L", "l", "p", "x"][..] + }; + if event + .tags + .iter() + .any(|t| !allowed.contains(&t.as_slice()[0].as_str())) + { + return Err("unexpected host tag".into()); + } + if event.pubkey != if report { host } else { owner } { + return Err("host event signer does not match its role".into()); + } + // Reject cleartext and malformed NIP-44 envelopes before storage. The owner + // alone can authenticate/decrypt the encrypted bytes. + let bytes = base64::engine::general_purpose::STANDARD + .decode(&event.content) + .map_err(|_| "invalid encrypted host content")?; + if !(99..=36_000).contains(&bytes.len()) || bytes.first() != Some(&2) { + return Err("invalid encrypted host content".into()); + } + let (registration, valid_until) = if report { + let id = one(event, "e", 2)?[1].clone(); + if id.len() != 64 + || !id + .bytes() + .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b)) + { + return Err("invalid registration reference".into()); + } + let until = if l[1] == "report" { + let until = one(event, "valid_until", 2)?[1] + .parse::() + .map_err(|_| "invalid report deadline")?; + let ts = event.created_at.as_secs(); + if until <= ts || until > ts.saturating_add(REPORT_TTL) { + return Err("report lifetime exceeds limit".into()); + } + Some(until) + } else { + None + }; + (Some(id), until) + } else { + (None, None) + }; + Ok(Envelope { + owner, + host, + label: l[1].clone(), + registration, + valid_until, + }) +} + +/// Small allowlisted runtime projection; never commands, paths or environment. +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct Runtime { + /// Catalog identifier. + pub id: String, + /// Human-facing catalog label. + pub label: String, + /// Catalog availability, not an assertion that a launch will succeed. + pub availability: String, + /// Cached catalog authentication observation. + pub auth_status: String, +} + +/// Encrypted machine report. Registration alone does not enable remote launch. +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct Report { + /// Protocol version. + pub v: u8, + /// OS-reported machine name. + pub name: String, + /// Operating system. + pub os: String, + /// CPU architecture. + pub arch: String, + /// Reporting launcher version. + pub launcher_version: String, + /// Observed catalog, with sensitive fields omitted. + pub runtimes: Vec, + /// False until the host implements launch request handling. + pub accepts_start: bool, +} + +impl Report { + /// Check bounded data before encryption and after authenticated decryption. + pub fn validate(&self) -> Result<(), String> { + if !matches!(self.v, 1 | 2) || self.accepts_start || self.runtimes.len() > 128 { + return Err("unsupported host report".into()); + } + let strings = [&self.name, &self.os, &self.arch, &self.launcher_version]; + if strings + .into_iter() + .chain( + self.runtimes + .iter() + .flat_map(|r| [&r.id, &r.label, &r.availability, &r.auth_status]), + ) + .any(|s| s.is_empty() || s.len() > 256 || s.chars().any(char::is_control)) + { + return Err("invalid host report text".into()); + } + Ok(()) + } +} + +fn build( + signer: &Keys, + owner: PublicKey, + host: PublicKey, + label: &str, + plaintext: &str, + extra: Vec>, + now: u64, +) -> Result { + let content = nip44::encrypt(signer.secret_key(), &owner, plaintext, nip44::Version::V2) + .map_err(|e| e.to_string())?; + let mut tags = vec![ + vec!["L".into(), NAMESPACE.into()], + vec!["l".into(), label.into(), NAMESPACE.into()], + vec!["p".into(), owner.to_hex()], + vec!["x".into(), host.to_hex()], + ]; + tags.extend(extra); + let tags = tags + .into_iter() + .map(Tag::parse) + .collect::, _>>() + .map_err(|e| e.to_string())?; + let event = EventBuilder::new(Kind::Custom(KIND_HOST as u16), content) + .allow_self_tagging() + .tags(tags) + .custom_created_at(Timestamp::from(now)) + .sign_with_keys(signer) + .map_err(|e| e.to_string())?; + validate(&event)?; + Ok(event) +} + +/// Build an owner-approved registration. Reuse an existing registration on restart. +pub fn registration(owner: &Keys, host: PublicKey, now: u64) -> Result { + build( + owner, + owner.public_key(), + host, + "registration", + r#"{"v":1}"#, + vec![], + now, + ) +} + +/// Build a report signed by the host and encrypted to the registered owner. +pub fn report( + host: &Keys, + registration: &Event, + payload: &Report, + now: u64, +) -> Result { + let env = validate(registration)?; + if env.label != "registration" || env.host != host.public_key() { + return Err("registration does not authorize this host".into()); + } + payload.validate()?; + build( + host, + env.owner, + env.host, + "report", + &serde_json::to_string(payload).map_err(|e| e.to_string())?, + vec![ + vec!["e".into(), registration.id.to_hex()], + vec![ + "valid_until".into(), + now.saturating_add(REPORT_TTL).to_string(), + ], + ], + now, + ) +} + +/// Durable change-only profile, signed by the host and encrypted to its owner. +pub fn profile( + host: &Keys, + registration: &Event, + payload: &Report, + now: u64, +) -> Result { + let env = validate(registration)?; + if env.label != "registration" || env.host != host.public_key() || payload.v != 2 { + return Err("invalid host profile binding or version".into()); + } + payload.validate()?; + build( + host, + env.owner, + env.host, + "profile", + &serde_json::to_string(payload).map_err(|e| e.to_string())?, + vec![vec!["e".into(), registration.id.to_hex()]], + now, + ) +} + +/// Verify both signatures and their binding before decrypting machine data. +pub fn decrypt_report( + owner: &Keys, + registration: &Event, + report: &Event, +) -> Result { + let reg = validate(registration)?; + let env = validate(report)?; + if reg.label != "registration" + || !matches!(env.label.as_str(), "report" | "profile") + || env.owner != owner.public_key() + || reg.owner != env.owner + || reg.host != env.host + || env.registration.as_deref() != Some(registration.id.to_hex().as_str()) + { + return Err("host report binding mismatch".into()); + } + let text = nip44::decrypt(owner.secret_key(), &env.host, &report.content) + .map_err(|e| e.to_string())?; + let result: Report = serde_json::from_str(&text).map_err(|e| e.to_string())?; + result.validate()?; + if (env.label == "profile") != (result.v == 2) { + return Err("host payload/envelope version mismatch".into()); + } + Ok(result) +} + +#[cfg(test)] +mod tests { + use super::*; + fn payload() -> Report { + Report { + v: 1, + name: "Actual machine".into(), + os: "macos".into(), + arch: "aarch64".into(), + launcher_version: "test".into(), + runtimes: vec![], + accepts_start: false, + } + } + #[test] + fn round_trip_and_foreign_owner_rejected() { + let owner = Keys::generate(); + let host = Keys::generate(); + let reg = registration(&owner, host.public_key(), 100).unwrap(); + let rep = report(&host, ®, &payload(), 101).unwrap(); + assert_eq!( + decrypt_report(&owner, ®, &rep).unwrap().name, + "Actual machine" + ); + assert!(decrypt_report(&Keys::generate(), ®, &rep).is_err()); + assert_eq!(validate(&rep).unwrap().valid_until, Some(281)); + assert!(!rep.content.contains("Actual machine")); + for event in [®, &rep] { + assert!(crate::filter::reader_authorized_for_event( + event, + &owner.public_key().to_hex() + )); + assert!(!crate::filter::reader_authorized_for_event( + event, + &Keys::generate().public_key().to_hex() + )); + assert!(!crate::filter::reader_authorized_for_event( + event, + &host.public_key().to_hex() + )); + } + assert!(!crate::kind::is_parameterized_replaceable(KIND_HOST)); + } + #[test] + fn mismatched_registration_and_signature_rejected() { + let owner = Keys::generate(); + let host = Keys::generate(); + let reg = registration(&owner, host.public_key(), 100).unwrap(); + assert!(report(&Keys::generate(), ®, &payload(), 101).is_err()); + let rep = report(&host, ®, &payload(), 101).unwrap(); + let other = registration(&owner, host.public_key(), 99).unwrap(); + assert!(decrypt_report(&owner, &other, &rep).is_err()); + let mut tampered = rep.clone(); + tampered.content.push('A'); + assert!(validate(&tampered).is_err()); + } + #[test] + fn malformed_envelopes_rejected_even_when_signed() { + let owner = Keys::generate(); + let host = Keys::generate(); + let reg = registration(&owner, host.public_key(), 100).unwrap(); + for extra in [ + vec!["p", &owner.public_key().to_hex()], + vec!["h", "channel"], + vec!["L", "unknown"], + ] { + let mut tags: Vec = reg.tags.iter().cloned().collect(); + tags.push(Tag::parse(extra).unwrap()); + let bad = EventBuilder::new(reg.kind, reg.content.clone()) + .allow_self_tagging() + .tags(tags) + .sign_with_keys(&owner) + .unwrap(); + assert!(validate(&bad).is_err()); + } + let mut p = payload(); + p.accepts_start = true; + assert!(report(&host, ®, &p, 101).is_err()); + } +} diff --git a/crates/buzz-core/src/host_execution.rs b/crates/buzz-core/src/host_execution.rs new file mode 100644 index 0000000000..cfb84b57de --- /dev/null +++ b/crates/buzz-core/src/host_execution.rs @@ -0,0 +1,440 @@ +//! Private, owner-authorized executor protocol. Registration is NOT host login. +//! +//! The caller must supply a freshly fetched, nondeleted registration from the +//! selected community, never a cached/caller-provided assertion of revocation. +//! This module is a protocol foundation; relays/executors must explicitly wire +//! authorization and a durable operation ledger before advertising Start. +use nostr::{nips::nip44, Event, EventBuilder, Keys, Kind, PublicKey, Tag, Timestamp}; +use serde::{Deserialize, Serialize}; + +use crate::{ + host, + kind::{KIND_HOST_COMMAND, KIND_HOST_RECEIPT}, +}; + +/// Maximum command lifetime; expiry is not evidence of process termination. +pub const COMMAND_TTL: u64 = 300; +/// Executor protocol namespace. +pub const NAMESPACE: &str = "buzz.host.execution.v1"; + +/// Explicit destination-local configuration, or one exact run to stop. +/// No source paths, shell strings, environment or credentials are accepted. +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] +#[serde(tag = "action", rename_all = "snake_case", deny_unknown_fields)] +pub enum Action { + /// Start only a pre-provisioned agent with this exact destination revision. + Start { + /// Rust runtime catalog ID, checked again on the destination. + runtime: String, + /// SHA-256 of destination launch configuration, not source configuration. + revision: String, + }, + /// Stop only the clicked launcher generation; never agent-wide shutdown. + Stop { + /// Public run ID, identical to the launcher's persisted generation. + run: String, + }, +} + +/// Encrypted immutable request. Retries must reuse the same signed event. +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] +#[serde(deny_unknown_fields)] +pub struct Command { + /// Protocol version. + pub v: u8, + /// Random 128-bit lowercase hex operation ID, also Start's run generation. + pub operation: String, + /// Canonical selected community URL. A command cannot cross communities. + pub relay: String, + /// Agent identity, independent of its placements. + pub agent: String, + /// Bounded execution deadline in Unix seconds. + pub expires_at: u64, + /// Requested transition. + pub action: Action, +} + +/// Process observations, never inferred from relay acceptance or online presence. +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] +#[serde(rename_all = "snake_case")] +pub enum Outcome { + /// Intent persisted; no process claim. + Accepted, + /// A child was created, not necessarily listening or ready. + Spawned, + /// Authenticated same-generation harness lifecycle report. + Listening, + /// Authenticated same-generation harness readiness report. + Ready, + /// Selected root and its group exited, but separately grouped descendants + /// have not been proven terminated. This MUST NOT authorize replacement. + RootExited, + /// Controller proved teardown of the full managed execution containment. + Stopped, + /// Proven pre-side-effect rejection (safe enum, no private diagnostics). + Rejected, + /// Side effect cannot be proved; must block replacement. + Unknown, +} + +/// Encrypted host-signed result, correlated to an exact immutable command. +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] +#[serde(deny_unknown_fields)] +pub struct Receipt { + /// Protocol version. + pub v: u8, + /// Signed command event ID, not just a caller-selected operation ID. + pub command: String, + /// Original immutable request. Contains identifiers only, no launch secrets. + pub request: Command, + /// Exact process generation the observation describes. + pub run: String, + /// Original observation time, retained on receipt retransmission. + pub observed_at: u64, + /// Observed state; Unknown is not Stopped. + pub outcome: Outcome, +} + +/// Validate a fixed-length lowercase hex identifier. +pub fn hex_id(value: &str, len: usize) -> bool { + value.len() == len + && value + .bytes() + .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b)) +} + +impl Command { + /// Validate immutable structure; use `decrypt_command` for execution freshness. + pub fn validate(&self) -> Result<(), String> { + if self.v != 1 + || !hex_id(&self.operation, 32) + || !hex_id(&self.agent, 64) + || crate::relay::normalize_relay_url(&self.relay) + .ok() + .as_deref() + != Some(&self.relay) + { + return Err("invalid execution command".into()); + } + PublicKey::from_hex(&self.agent).map_err(|_| "invalid agent key")?; + match &self.action { + Action::Start { runtime, revision } + if runtime.is_empty() + || runtime.len() > 128 + || !runtime + .bytes() + .all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_') + || !hex_id(revision, 64) => + { + Err("invalid destination configuration reference".into()) + } + Action::Stop { run } if !hex_id(run, 32) => Err("invalid stop generation".into()), + _ => Ok(()), + } + } + + /// Generation this operation is allowed to affect. + pub fn run(&self) -> &str { + match &self.action { + Action::Start { .. } => &self.operation, + Action::Stop { run } => run, + } + } +} + +fn registration(reg: &Event) -> Result { + let binding = host::validate(reg)?; + if binding.label != "registration" { + return Err("expected current registration".into()); + } + Ok(binding) +} + +fn build( + signer: &Keys, + recipient: PublicKey, + reg: &Event, + kind: u32, + body: &impl Serialize, + now: u64, +) -> Result { + let binding = registration(reg)?; + let content = nip44::encrypt( + signer.secret_key(), + &recipient, + serde_json::to_string(body).map_err(|_| "invalid execution payload")?, + nip44::Version::V2, + ) + .map_err(|_| "execution encryption failed")?; + let tags = [ + ["L".to_owned(), NAMESPACE.into()], + ["p".into(), binding.owner.to_hex()], + ["x".into(), binding.host.to_hex()], + ["e".into(), reg.id.to_hex()], + ] + .into_iter() + .map(Tag::parse) + .collect::, _>>() + .map_err(|_| "invalid routing")?; + EventBuilder::new(Kind::Custom(kind as u16), content) + .allow_self_tagging() + .tags(tags) + .custom_created_at(Timestamp::from(now)) + .sign_with_keys(signer) + .map_err(|_| "execution signing failed".into()) +} + +fn envelope(event: &Event, reg: &Event, kind: u32, signer: PublicKey) -> Result<(), String> { + crate::verify_event(event).map_err(|_| "invalid execution signature")?; + let binding = registration(reg)?; + let expected = [ + ("L", NAMESPACE.to_owned()), + ("p", binding.owner.to_hex()), + ("x", binding.host.to_hex()), + ("e", reg.id.to_hex()), + ]; + if event.kind.as_u16() as u32 != kind + || event.pubkey != signer + || event.tags.len() != expected.len() + || event.content.len() > 16_384 + { + return Err("invalid execution envelope".into()); + } + for (key, value) in expected { + if event + .tags + .iter() + .filter(|tag| tag.as_slice() == [key, value.as_str()]) + .count() + != 1 + { + return Err("execution audience or registration mismatch".into()); + } + } + Ok(()) +} + +/// Encrypt to one registered host and sign as its owner. Existing owner transport +/// is required; possession of the host key grants no broader relay authority. +pub fn command(owner: &Keys, reg: &Event, request: &Command, now: u64) -> Result { + let binding = registration(reg)?; + if binding.owner != owner.public_key() { + return Err("foreign execution owner".into()); + } + request.validate()?; + freshness(request, now, now)?; + build(owner, binding.host, reg, KIND_HOST_COMMAND, request, now) +} + +fn freshness(request: &Command, created: u64, now: u64) -> Result<(), String> { + if created > now.saturating_add(30) + || request.expires_at <= now + || request.expires_at <= created + || request.expires_at > created.saturating_add(COMMAND_TTL) + { + return Err("execution command expired or lifetime invalid".into()); + } + Ok(()) +} + +/// Authenticate destination/owner/current registration, decrypt and check deadline +/// and community before consulting the durable dedup ledger or doing any work. +pub fn decrypt_command( + host: &Keys, + current_reg: &Event, + event: &Event, + relay: &str, + now: u64, +) -> Result { + let binding = registration(current_reg)?; + if binding.host != host.public_key() { + return Err("wrong executor".into()); + } + envelope(event, current_reg, KIND_HOST_COMMAND, binding.owner)?; + let text = nip44::decrypt(host.secret_key(), &binding.owner, &event.content) + .map_err(|_| "invalid command ciphertext")?; + let request: Command = serde_json::from_str(&text).map_err(|_| "invalid execution payload")?; + request.validate()?; + if request.relay != relay { + return Err("wrong execution community".into()); + } + freshness(&request, event.created_at.as_secs(), now)?; + Ok(request) +} + +/// Sign only an observed, durably recorded result; this helper does not turn an +/// online pulse or successful publish into an execution observation. +pub fn receipt(host: &Keys, reg: &Event, result: &Receipt, now: u64) -> Result { + let binding = registration(reg)?; + if binding.host != host.public_key() { + return Err("wrong receipt signer".into()); + } + validate_receipt(result)?; + if result.observed_at > now { + return Err("receipt observation is in the future".into()); + } + build(host, binding.owner, reg, KIND_HOST_RECEIPT, result, now) +} + +fn validate_receipt(result: &Receipt) -> Result<(), String> { + result.request.validate()?; + if result.v != 1 || !hex_id(&result.command, 64) || result.run != result.request.run() { + return Err("invalid execution receipt correlation".into()); + } + let valid = match result.request.action { + Action::Start { .. } => !matches!(result.outcome, Outcome::Stopped | Outcome::RootExited), + Action::Stop { .. } => matches!( + result.outcome, + Outcome::Accepted + | Outcome::RootExited + | Outcome::Stopped + | Outcome::Rejected + | Outcome::Unknown + ), + }; + if !valid { + return Err("invalid receipt outcome for action".into()); + } + Ok(()) +} + +/// Verify host authority and exact command/generation correlation. Late receipts +/// may resolve their original operation, never a newer operation. Unlike commands, +/// persisted results remain readable after expiry; expiry is not termination. +pub fn decrypt_receipt( + owner: &Keys, + reg: &Event, + event: &Event, + command_event: &Event, + request: &Command, +) -> Result { + let binding = registration(reg)?; + if binding.owner != owner.public_key() { + return Err("foreign receipt owner".into()); + } + envelope(command_event, reg, KIND_HOST_COMMAND, binding.owner)?; + // Bind the supplied request to the signed bytes, not caller-provided metadata. + let sent = nip44::decrypt(owner.secret_key(), &binding.host, &command_event.content) + .map_err(|_| "invalid command ciphertext")?; + let sent: Command = serde_json::from_str(&sent).map_err(|_| "invalid command payload")?; + if &sent != request { + return Err("request differs from signed command".into()); + } + envelope(event, reg, KIND_HOST_RECEIPT, binding.host)?; + let text = nip44::decrypt(owner.secret_key(), &binding.host, &event.content) + .map_err(|_| "invalid receipt ciphertext")?; + let result: Receipt = serde_json::from_str(&text).map_err(|_| "invalid receipt payload")?; + validate_receipt(&result)?; + if result.observed_at > event.created_at.as_secs() { + return Err("receipt observation is in the future".into()); + } + if result.command != command_event.id.to_hex() || &result.request != request { + return Err("receipt belongs to another operation".into()); + } + Ok(result) +} + +#[cfg(test)] +mod tests { + use super::*; + fn request() -> Command { + Command { + v: 1, + operation: "ab".repeat(16), + relay: "wss://one.example".into(), + agent: Keys::generate().public_key().to_hex(), + expires_at: 200, + action: Action::Start { + runtime: "goose".into(), + revision: "cd".repeat(32), + }, + } + } + #[test] + fn encrypted_start_and_exact_authenticated_result() { + let owner = Keys::generate(); + let host = Keys::generate(); + let reg = host::registration(&owner, host.public_key(), 99).unwrap(); + let req = request(); + let cmd = command(&owner, ®, &req, 100).unwrap(); + assert!(!cmd.content.contains(&req.agent)); + assert!(!cmd + .tags + .iter() + .any(|t| t.as_slice().iter().any(|v| v.contains(&req.agent)))); + assert_eq!( + decrypt_command(&host, ®, &cmd, &req.relay, 101).unwrap(), + req + ); + let result = Receipt { + v: 1, + command: cmd.id.to_hex(), + request: req.clone(), + run: req.run().into(), + observed_at: 101, + outcome: Outcome::Spawned, + }; + let event = receipt(&host, ®, &result, 101).unwrap(); + assert!(receipt(&host, ®, &result, 100).is_err()); + let replay = receipt(&host, ®, &result, 300).unwrap(); + assert_eq!( + decrypt_receipt(&owner, ®, &replay, &cmd, &req) + .unwrap() + .observed_at, + 101 + ); + assert_eq!( + decrypt_receipt(&owner, ®, &event, &cmd, &req).unwrap(), + result + ); + let mut different = req.clone(); + different.operation = "ef".repeat(16); + assert!(decrypt_receipt(&owner, ®, &event, &cmd, &different).is_err()); + assert!(decrypt_receipt(&Keys::generate(), ®, &event, &cmd, &req).is_err()); + } + #[test] + fn rejects_wrong_owner_host_tenant_registration_expiry_and_tampering() { + let owner = Keys::generate(); + let host = Keys::generate(); + let req = request(); + let reg = host::registration(&owner, host.public_key(), 99).unwrap(); + assert!(command(&Keys::generate(), ®, &req, 100).is_err()); + let cmd = command(&owner, ®, &req, 100).unwrap(); + assert!(decrypt_command(&Keys::generate(), ®, &cmd, &req.relay, 101).is_err()); + assert!(decrypt_command(&host, ®, &cmd, "wss://two.example", 101).is_err()); + assert!(decrypt_command(&host, ®, &cmd, &req.relay, 200).is_err()); + assert!(decrypt_command(&host, ®, &cmd, &req.relay, 60).is_err()); + let renewed = host::registration(&owner, host.public_key(), 100).unwrap(); + assert!(decrypt_command(&host, &renewed, &cmd, &req.relay, 101).is_err()); + let mut tampered = cmd; + tampered.content.push('x'); + assert!(decrypt_command(&host, ®, &tampered, &req.relay, 101).is_err()); + } + #[test] + fn exact_stop_and_confused_outcomes_rejected() { + let owner = Keys::generate(); + let host = Keys::generate(); + let reg = host::registration(&owner, host.public_key(), 99).unwrap(); + let mut req = request(); + req.action = Action::Stop { + run: "12".repeat(16), + }; + let cmd = command(&owner, ®, &req, 100).unwrap(); + let mut result = Receipt { + v: 1, + command: cmd.id.to_hex(), + request: req.clone(), + run: req.run().into(), + observed_at: 101, + outcome: Outcome::Stopped, + }; + assert!(receipt(&host, ®, &result, 201).is_ok()); + result.run = req.operation.clone(); + assert!(receipt(&host, ®, &result, 201).is_err()); + result.run = req.run().into(); + result.outcome = Outcome::Ready; + assert!(receipt(&host, ®, &result, 201).is_err()); + req.expires_at = 401; + assert!(command(&owner, ®, &req, 100).is_err()); + } +} diff --git a/crates/buzz-core/src/kind.rs b/crates/buzz-core/src/kind.rs index 3c6f1d5913..385f6ba7c1 100644 --- a/crates/buzz-core/src/kind.rs +++ b/crates/buzz-core/src/kind.rs @@ -117,6 +117,14 @@ pub const KIND_PUSH_LEASE: u32 = 30350; /// plus exact public projection bindings. See `docs/nips/NIP-PMA.md`. pub const KIND_PRIVATE_MANAGED_AGENT: u32 = 30179; +/// Private host registration and reports, distinguished by `buzz.host.v1` labels. +/// Append-only; reports are host-signed and readable only by the tagged owner. +pub const KIND_HOST: u32 = 50000; +/// Owner-signed, destination-encrypted execution command (not yet relay-enabled). +pub const KIND_HOST_COMMAND: u32 = 50001; +/// Host-signed, owner-encrypted execution observation (not yet relay-enabled). +pub const KIND_HOST_RECEIPT: u32 = 50002; + /// Kinds whose stored events are readable only by their author. /// /// The relay must never reveal the existence, count, tags, content, schedule, @@ -139,7 +147,7 @@ pub const AUTHOR_ONLY_KINDS: &[u32] = &[ /// /// Used by `filter_can_match_result_gated_kinds` to force the per-event /// fallback path in COUNT rather than the fast SQL `count_events()`. -pub const RESULT_GATED_KINDS: &[u32] = &[KIND_DM_VISIBILITY, KIND_AGENT_TURN_METRIC]; +pub const RESULT_GATED_KINDS: &[u32] = &[KIND_DM_VISIBILITY, KIND_AGENT_TURN_METRIC, KIND_HOST]; /// Kinds whose stored events have `#p`-bound read access — readable only by /// subscribers whose pubkey appears in the event's `#p` tag. @@ -157,6 +165,7 @@ pub const RESULT_GATED_KINDS: &[u32] = &[KIND_DM_VISIBILITY, KIND_AGENT_TURN_MET /// included for filter-layer enforcement but are never stored, so the /// storage-layer search defense does not apply to them. pub const P_GATED_KINDS: &[u32] = &[ + KIND_HOST, KIND_AGENT_OBSERVER_FRAME, KIND_MEMBER_ADDED_NOTIFICATION, KIND_MEMBER_REMOVED_NOTIFICATION, @@ -633,6 +642,7 @@ pub const KIND_PROJECT: u32 = 30621; /// All registered kind constants — used for duplicate detection and iteration. pub const ALL_KINDS: &[u32] = &[ + KIND_HOST, KIND_PROFILE, KIND_TEXT_NOTE, KIND_CONTACT_LIST, diff --git a/crates/buzz-core/src/lib.rs b/crates/buzz-core/src/lib.rs index 36dc772da3..6ba8bb7631 100644 --- a/crates/buzz-core/src/lib.rs +++ b/crates/buzz-core/src/lib.rs @@ -20,6 +20,8 @@ pub mod event; pub mod filter; /// Git permission types — ref patterns, protection rules, policy evaluation. pub mod git_perms; +/// Private host registration and expiring reports. +pub mod host; /// Shared invite-link contract constants. pub mod invite; /// Buzz kind number registry — custom event type constants. @@ -79,3 +81,9 @@ pub mod test_helpers { StoredEvent::with_received_at(make_event(kind), Utc::now(), channel_id, true) } } + +/// Per-run presence and public placement wire contract. +pub mod run_presence; + +/// Authenticated, private host execution protocol foundations. +pub mod host_execution; diff --git a/crates/buzz-core/src/run_presence.rs b/crates/buzz-core/src/run_presence.rs new file mode 100644 index 0000000000..ef9cae64b0 --- /dev/null +++ b/crates/buzz-core/src/run_presence.rs @@ -0,0 +1,184 @@ +//! Bounded per-run presence. Location is a launcher assertion, not launch authority. +use nostr::{Event, EventBuilder, Keys, Kind, PublicKey, Tag, Timestamp}; +use serde::{Deserialize, Serialize}; + +/// Presence lifetime, shared by publishers, relay and consumers. +pub const LEASE_SECONDS: u64 = 180; +/// A single live launcher run; offline records remain as ordering tombstones. +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] +pub struct RunPresence { + /// Random process-generation identifier (32 lowercase hex characters). + pub run: String, + /// Monotonically increasing pulse sequence within this generation. + pub seq: u64, + /// Bare online, away or offline status. + pub status: String, + /// Actual publisher deadline, never renewed by reading a snapshot. + pub expires_at: u64, + /// Deliberately public host reference and display alias, if supplied. + pub location: Option, + /// Owner-signed host binding for owner-transported host pulses only. + pub registration: Option, +} +/// Minimal public placement descriptor; never includes private capabilities. +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] +pub struct Location { + /// Stable launcher installation key. + pub host: String, + /// Public display alias, not an implicitly exported OS hostname. + pub label: String, +} +fn hex(s: &str, len: usize) -> bool { + s.len() == len + && s.bytes() + .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b)) +} +impl Location { + /// Reject unbounded, misleading control text and malformed identifiers. + pub fn validate(&self) -> Result<(), String> { + if !hex(&self.host, 64) + || PublicKey::from_hex(&self.host).is_err() + || self.label.trim().is_empty() + || self.label.len() > 80 + || self.label.chars().any(|c| { + c.is_control() || matches!(c, '\u{202a}'..='\u{202e}' | '\u{2066}'..='\u{2069}') + }) + { + return Err("invalid public host location".into()); + } + Ok(()) + } +} +/// Parse the upgraded wire format; legacy no-run presence stays on its old path. +/// Callers must separately verify event signature and transport authority. +pub fn parse_run(event: &Event, now: u64) -> Result, String> { + if !event.tags.iter().any(|t| { + matches!( + t.as_slice()[0].as_str(), + "run" | "seq" | "host" | "host_registration" + ) + }) { + return Ok(None); + } + if event.kind.as_u16() as u32 != crate::kind::KIND_PRESENCE_UPDATE + || !matches!(event.content.as_str(), "online" | "away" | "offline") + { + return Err("invalid run presence status".into()); + } + let ts = event.created_at.as_secs(); + if ts > now.saturating_add(30) || ts.saturating_add(LEASE_SECONDS) <= now { + return Err("run presence timestamp outside lease window".into()); + } + let mut run = None; + let mut seq = None; + let mut location = None; + let mut registration = None; + for tag in event.tags.iter() { + let t = tag.as_slice(); + match t[0].as_str() { + "run" if t.len() == 2 && run.is_none() && hex(&t[1], 32) => run = Some(t[1].clone()), + "seq" if t.len() == 2 && seq.is_none() => { + let n = t[1] + .parse::() + .map_err(|_| "invalid presence sequence")?; + // Lua compares exactly representable integers. + if n > 9_007_199_254_740_991 { + return Err("presence sequence too large".into()); + } + seq = Some(n); + } + "host" if t.len() == 3 && location.is_none() => { + let l = Location { + host: t[1].clone(), + label: t[2].clone(), + }; + l.validate()?; + location = Some(l); + } + "host_registration" if t.len() == 2 && registration.is_none() && hex(&t[1], 64) => { + registration = Some(t[1].clone()) + } + _ => return Err("invalid run presence tags".into()), + } + } + Ok(Some(RunPresence { + run: run.ok_or("missing presence run")?, + seq: seq.ok_or("missing presence sequence")?, + status: event.content.clone(), + expires_at: ts + .saturating_add(LEASE_SECONDS) + .min(now.saturating_add(LEASE_SECONDS)), + location, + registration, + })) +} +/// Sign one pulse with a process-stable run and increasing sequence. +pub fn pulse( + keys: &Keys, + run: &str, + seq: u64, + status: &str, + location: Option<&Location>, + registration: Option<&str>, + now: u64, +) -> Result { + let mut tags = vec![ + vec!["run".into(), run.into()], + vec!["seq".into(), seq.to_string()], + ]; + if let Some(l) = location { + tags.push(vec!["host".into(), l.host.clone(), l.label.clone()]); + } + if let Some(id) = registration { + tags.push(vec!["host_registration".into(), id.into()]); + } + let tags = tags + .into_iter() + .map(Tag::parse) + .collect::, _>>() + .map_err(|e| e.to_string())?; + let event = EventBuilder::new( + Kind::Custom(crate::kind::KIND_PRESENCE_UPDATE as u16), + status, + ) + .tags(tags) + .custom_created_at(Timestamp::from(now)) + .sign_with_keys(keys) + .map_err(|e| e.to_string())?; + parse_run(&event, now)?; + Ok(event) +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn run_wire_is_bounded_and_legacy_is_separate() { + let keys = Keys::generate(); + let location = Location { + host: Keys::generate().public_key().to_hex(), + label: "Workshop".into(), + }; + let event = pulse( + &keys, + &"a".repeat(32), + 1, + "online", + Some(&location), + None, + 100, + ) + .unwrap(); + let parsed = parse_run(&event, 110).unwrap().unwrap(); + assert_eq!(parsed.expires_at, 280); + assert_eq!(parsed.location, Some(location)); + assert!(parse_run(&event, 280).is_err()); + assert!(parse_run(&event, 69).is_err()); + assert!(pulse(&keys, "bad", 0, "online", None, None, 100).is_err()); + assert!(pulse(&keys, &"a".repeat(32), 0, "ready", None, None, 100).is_err()); + let legacy = EventBuilder::new(Kind::Custom(20001), "online") + .sign_with_keys(&keys) + .unwrap(); + assert_eq!(parse_run(&legacy, 100).unwrap(), None); + } +} diff --git a/crates/buzz-db/src/runtime/migration.rs b/crates/buzz-db/src/runtime/migration.rs index 00cd81c694..4c8c3f1810 100644 --- a/crates/buzz-db/src/runtime/migration.rs +++ b/crates/buzz-db/src/runtime/migration.rs @@ -699,7 +699,7 @@ mod tests { let mut migrations: Vec<_> = MIGRATOR.iter().collect(); migrations.sort_by_key(|migration| migration.version); - assert_eq!(migrations.len(), 40); + assert_eq!(migrations.len(), 41); assert_eq!(migrations[0].version, 1); assert_eq!(&*migrations[0].description, "initial schema"); assert!(migrations[0] @@ -908,7 +908,11 @@ mod tests { assert!(migrations[32].sql.as_str().contains("search_tsv")); assert!(!migrations[0].sql.as_str().contains("30179")); assert!(include_str!("../../../../schema/schema.sql") - .contains("kind IN (1059, 30179, 30300, 30350, 30622, 44100, 44101, 44200)")); + .contains("kind IN (1059, 30179, 30300, 30350, 30622, 44100, 44101, 44200, 50000)")); + // Host privacy is additive too; never rewrite historical checksums. + assert_eq!(migrations[40].version, 41); + assert!(migrations[40].sql.as_str().contains("kind = 50000")); + assert!(!migrations[0].sql.as_str().contains("50000")); // Public push-gateway authority is intentionally deployment-global and // durable: immediate revocation and hostile-relay admission cannot be diff --git a/crates/buzz-db/src/store/event.rs b/crates/buzz-db/src/store/event.rs index 60e6b05ef9..0a8a1ee5e2 100644 --- a/crates/buzz-db/src/store/event.rs +++ b/crates/buzz-db/src/store/event.rs @@ -32,6 +32,28 @@ pub use crate::reminder::{ /// the advertised ceiling and the enforced one cannot drift. pub const DEFAULT_MAX_PAGE_LIMIT: i64 = 1_000; +// Query and COUNT share the core matcher's generic-tag semantics. In particular, +// #h falls back to the stored channel only when NO explicit h tag exists. +fn push_exact_tags( + qb: &mut QueryBuilder, + tags: &[(String, Vec)], + col_prefix: &str, +) { + for (name, values) in tags { + qb.push(format!(" AND (EXISTS (SELECT 1 FROM jsonb_array_elements({col_prefix}tags) AS exact_tag WHERE exact_tag->>0 = ")) + .push_bind(name) + .push(" AND exact_tag->>1 = ANY(") + .push_bind(values) + .push("))"); + if name == "h" { + qb.push(format!(" OR (NOT EXISTS (SELECT 1 FROM jsonb_array_elements({col_prefix}tags) AS channel_tag WHERE channel_tag->>0 = 'h') AND {col_prefix}channel_id::text = ANY(")) + .push_bind(values) + .push("))"); + } + qb.push(")"); + } +} + /// Optional filters for [`query_events`]. #[derive(Debug, Clone)] pub struct EventQuery { @@ -81,6 +103,12 @@ pub struct EventQuery { /// Restrict results to events with an exact custom tag pair. /// Uses JSONB containment against `tags` before SQL `LIMIT`. pub custom_tag: Option<(String, String)>, + /// Exact tag-name/value filters applied before LIMIT. Names are AND-ed, + /// values within each name are OR-ed, matching NIP-01 generic tag semantics. + /// `h` uses stored channel_id only in the absence of explicit h tags, + /// matching the core filter matcher. Host inventory uses this instead of + /// best-effort mention indexes. + pub exact_tags: Vec<(String, Vec)>, /// Restrict results to events in any of these channels. By default, /// channel-less global events are retained so this can enforce a viewer's /// accessible-channel scope without hiding global events. Set @@ -140,6 +168,7 @@ impl EventQuery { ids: None, e_tags: None, custom_tag: None, + exact_tags: Vec::new(), channel_ids: None, channel_ids_include_global: true, max_limit: None, @@ -525,6 +554,8 @@ pub(crate) async fn query_events_on( .push_bind(containment); } + push_exact_tags(&mut qb, &q.exact_tags, col_prefix); + if let Some(s) = q.since { qb.push(format!(" AND {col_prefix}created_at >= ")) .push_bind(s); @@ -784,6 +815,8 @@ pub(crate) async fn count_events_on(conn: &mut sqlx::PgConnection, q: &EventQuer } } + push_exact_tags(&mut qb, &q.exact_tags, col_prefix); + if let Some(s) = q.since { qb.push(format!(" AND {col_prefix}created_at >= ")) .push_bind(s); diff --git a/crates/buzz-pubsub/src/error.rs b/crates/buzz-pubsub/src/error.rs index 96bc1016c9..f216d79ee0 100644 --- a/crates/buzz-pubsub/src/error.rs +++ b/crates/buzz-pubsub/src/error.rs @@ -3,6 +3,9 @@ use thiserror::Error; /// Errors that can occur in pub/sub, presence, and typing operations. #[derive(Debug, Error)] pub enum PubSubError { + /// Bounded per-identity presence run capacity reached. + #[error("presence run limit reached")] + PresenceRunLimit, /// A Redis command failed. #[error("Redis error: {0}")] Redis(#[from] redis::RedisError), diff --git a/crates/buzz-pubsub/src/lib.rs b/crates/buzz-pubsub/src/lib.rs index 4f1690beef..b0fde8a952 100644 --- a/crates/buzz-pubsub/src/lib.rs +++ b/crates/buzz-pubsub/src/lib.rs @@ -36,6 +36,8 @@ pub mod presence; pub mod publisher; /// Redis-backed rate limiter (fixed-window INCR + EXPIRE). pub mod rate_limiter; +/// Per-run presence leases and ordering fences. +pub mod run_presence; /// Redis SUBSCRIBE for channel event delivery. pub mod subscriber; /// Community-scoped Redis event topics. @@ -328,6 +330,26 @@ impl PubSubManager { publisher::publish_event(&self.pool, ctx, topic, event).await } + /// Accept a newer per-run pulse without erasing other placements. + pub async fn update_run_presence( + &self, + ctx: &TenantContext, + author: &PublicKey, + pulse: &buzz_core::run_presence::RunPresence, + now: u64, + ) -> Result { + run_presence::update(&self.pool, ctx, author, pulse, now).await + } + /// Return unexpired runs with original expiry deadlines. + pub async fn active_presence_runs( + &self, + ctx: &TenantContext, + author: &PublicKey, + now: u64, + ) -> Result, PubSubError> { + run_presence::active(&self.pool, ctx, author, now).await + } + /// Set presence with 180s TTL. Call on connect and every 60s heartbeat. pub async fn set_presence( &self, @@ -368,8 +390,11 @@ impl PubSubManager { #[cfg(test)] pub(crate) mod test_util { + pub fn redis_url() -> String { + std::env::var("REDIS_URL").unwrap_or_else(|_| "redis://127.0.0.1:6379".into()) + } pub fn make_test_pool() -> deadpool_redis::Pool { - let cfg = deadpool_redis::Config::from_url("redis://127.0.0.1:6379"); + let cfg = deadpool_redis::Config::from_url(redis_url()); cfg.create_pool(Some(deadpool_redis::Runtime::Tokio1)) .expect("Failed to create Redis pool") } @@ -386,7 +411,7 @@ mod tests { async fn make_manager() -> Arc { let pool = make_test_pool(); Arc::new( - PubSubManager::new("redis://127.0.0.1:6379", pool) + PubSubManager::new(&crate::test_util::redis_url(), pool) .await .expect("Failed to create PubSubManager"), ) @@ -513,7 +538,7 @@ mod tests { let pool = make_test_pool(); let manager = Arc::new( PubSubManager::with_config( - PubSubConfig::new("redis://127.0.0.1:6379") + PubSubConfig::new(crate::test_util::redis_url()) .with_unsubscribe_debounce(Duration::from_millis(25)), pool, ) @@ -593,7 +618,7 @@ mod tests { async fn retain_release_refcounts_and_debounces_last_release() { let pool = make_test_pool(); let manager = PubSubManager::with_config( - PubSubConfig::new("redis://127.0.0.1:6379") + PubSubConfig::new(crate::test_util::redis_url()) .with_unsubscribe_debounce(Duration::from_millis(1)), pool, ) diff --git a/crates/buzz-pubsub/src/run_presence.rs b/crates/buzz-pubsub/src/run_presence.rs new file mode 100644 index 0000000000..01730c6e3b --- /dev/null +++ b/crates/buzz-pubsub/src/run_presence.rs @@ -0,0 +1,127 @@ +//! Atomic per-run leases, shared across relay nodes. Disconnect never erases peers. +use crate::error::PubSubError; +use buzz_core::{run_presence::RunPresence, TenantContext}; +use deadpool_redis::Pool; +use nostr::PublicKey; + +fn key(ctx: &TenantContext, author: &PublicKey) -> String { + format!("buzz:{}:presence-runs:{}", ctx.community(), author.to_hex()) +} +// Bound active runs AND ordering tombstones. Retain offline fences beyond the +// maximum admissible timestamp window, without a process-local connection count. +const UPDATE: &str = r#" +local values = redis.call('HGETALL', KEYS[1]) +local now = tonumber(ARGV[3]) +for i = 1, #values, 2 do + local value = cjson.decode(values[i+1]) + if value.expires_at + 180 <= now then redis.call('HDEL', KEYS[1], values[i]) end +end +local old = redis.call('HGET', KEYS[1], ARGV[1]) +local incoming = cjson.decode(ARGV[2]) +if old then + old = cjson.decode(old) + if old.seq >= incoming.seq or old.status == 'offline' then return 0 end +elseif redis.call('HLEN', KEYS[1]) >= 32 then + return -1 +end +redis.call('HSET', KEYS[1], ARGV[1], ARGV[2]) +redis.call('EXPIRE', KEYS[1], 360) +return 1 +"#; + +/// Atomically accept a newer pulse; duplicates/reordered pulses do not renew TTL. +/// Returns false for obsolete pulses; saturation is a visible error, not eviction. +pub async fn update( + pool: &Pool, + ctx: &TenantContext, + author: &PublicKey, + pulse: &RunPresence, + now: u64, +) -> Result { + let mut conn = pool.get().await?; + let result: i64 = redis::Script::new(UPDATE) + .key(key(ctx, author)) + .arg(&pulse.run) + .arg(serde_json::to_string(pulse)?) + .arg(now) + .invoke_async(&mut conn) + .await?; + if result < 0 { + return Err(PubSubError::PresenceRunLimit); + } + Ok(result == 1) +} +/// Read live leases with their original deadlines. Errors are not empty/offline. +pub async fn active( + pool: &Pool, + ctx: &TenantContext, + author: &PublicKey, + now: u64, +) -> Result, PubSubError> { + let mut conn = pool.get().await?; + let values: Vec = redis::cmd("HVALS") + .arg(key(ctx, author)) + .query_async(&mut conn) + .await?; + let mut runs = Vec::new(); + for value in values { + let run: RunPresence = serde_json::from_str(&value)?; + if run.status != "offline" && run.expires_at > now { + runs.push(run); + } + } + runs.sort_by(|a, b| a.run.cmp(&b.run)); + Ok(runs) +} + +#[cfg(test)] +mod tests { + use super::*; + use buzz_core::{run_presence::Location, CommunityId}; + #[tokio::test] + #[ignore = "requires Redis"] + async fn parallel_runs_ordering_offline_and_tenant_isolation() { + let pool = crate::test_util::make_test_pool(); + let ctx = + TenantContext::resolved(CommunityId::from_uuid(uuid::Uuid::new_v4()), "test.example"); + let other = TenantContext::resolved( + CommunityId::from_uuid(uuid::Uuid::new_v4()), + "other.example", + ); + let author = nostr::Keys::generate().public_key(); + let first = RunPresence { + run: "a".repeat(32), + seq: 0, + status: "online".into(), + expires_at: 280, + location: Some(Location { + host: author.to_hex(), + label: "One".into(), + }), + registration: None, + }; + let mut second = first.clone(); + second.run = "b".repeat(32); + assert!(update(&pool, &ctx, &author, &first, 100).await.unwrap()); + assert!(update(&pool, &ctx, &author, &second, 100).await.unwrap()); + assert!(!update(&pool, &ctx, &author, &first, 120).await.unwrap()); + assert_eq!(active(&pool, &ctx, &author, 120).await.unwrap().len(), 2); + assert!(active(&pool, &other, &author, 120) + .await + .unwrap() + .is_empty()); + let mut stop = first.clone(); + stop.seq = 1; + stop.status = "offline".into(); + assert!(update(&pool, &ctx, &author, &stop, 130).await.unwrap()); + assert!(!update(&pool, &ctx, &author, &first, 140).await.unwrap()); + let mut late = first.clone(); + late.seq = 2; + assert!(!update(&pool, &ctx, &author, &late, 150).await.unwrap()); + assert_eq!( + active(&pool, &ctx, &author, 150).await.unwrap(), + vec![second] + ); + assert!(active(&pool, &ctx, &author, 280).await.unwrap().is_empty()); + } +} diff --git a/crates/buzz-relay/src/api/bridge.rs b/crates/buzz-relay/src/api/bridge.rs index 31fdb019bf..e51670398d 100644 --- a/crates/buzz-relay/src/api/bridge.rs +++ b/crates/buzz-relay/src/api/bridge.rs @@ -1158,6 +1158,15 @@ async fn query_events_authed( .await?; if filters.iter().any(|f| f.search.is_some()) { + if filters + .iter() + .any(crate::handlers::history::explicitly_requests_hosts) + { + return Err(api_error( + StatusCode::BAD_REQUEST, + "error: host history search is unsupported", + )); + } if has_mixed_search_filters(&filters) { return Err(api_error( StatusCode::BAD_REQUEST, @@ -1476,7 +1485,13 @@ async fn query_events_authed( let db = state.db.clone(); let mut catchall_results = stream::iter(catchall_queries.into_iter().map(|(idx, query)| { let db = db.clone(); - async move { (idx, db.query_events_routed("bridge_query", &query).await) } + let filter = &filters[idx]; + async move { + ( + idx, + crate::handlers::history::query(&db, "bridge_query", filter, query).await, + ) + } })) .buffered(crate::handlers::req::FILTER_QUERY_CONCURRENCY); @@ -1506,6 +1521,10 @@ async fn query_events_authed( } } Err(e) => { + if crate::handlers::history::requires_primary(filter) { + tracing::warn!("Host-capable historical query failed: {e}"); + return Err(internal_error(e.wire_message())); + } return Err(internal_error(&format!("query error: {e}"))); } } @@ -2285,28 +2304,52 @@ async fn synthesize_presence( // Look up Redis. A lookup failure must surface as an error, not a // fake-empty success — otherwise a Redis outage is indistinguishable from // an authoritative all-offline snapshot to the consumer. - let presence_map = match pubsub.get_presence_bulk(tenant, &all_pubkeys).await { + let mut presence_map = match pubsub.get_presence_bulk(tenant, &all_pubkeys).await { Ok(map) => map, Err(e) => return Some(Err(internal_error(&format!("presence lookup: {e}")))), }; - - if presence_map.is_empty() { - return Some(Ok(Vec::new())); - } - - // Synthesize kind:20001 events signed by the relay. - let now = std::time::SystemTime::now() - .duration_since(std::time::UNIX_EPOCH) - .unwrap_or_default() - .as_secs(); - - let mut events = Vec::with_capacity(presence_map.len()); - for (pubkey_hex, status) in &presence_map { - // Build a synthetic event: relay-signed, content = status, p-tag = subject. - // A build/sign failure here is an internal fault, not a "not a presence - // query" signal, so surface it as an error rather than falling through. - let tags = match nostr::Tag::parse(["p", pubkey_hex]) { - Ok(tag) => vec![tag], + let now = nostr::Timestamp::now().as_secs(); + let detailed = filters.iter().any(|f| { + f.kinds.as_ref().is_some_and(|ks| { + ks.iter() + .any(|k| k.as_u16() as u32 == KIND_PRESENCE_SNAPSHOT) + }) + }); + let mut events = Vec::new(); + for author in all_pubkeys { + let runs = match pubsub.active_presence_runs(tenant, &author, now).await { + Ok(runs) => runs, + Err(e) => return Some(Err(internal_error(&format!("presence runs: {e}")))), + }; + let pk = author.to_hex(); + let legacy = presence_map.remove(&pk); + let status = + if runs.iter().any(|r| r.status == "online") || legacy.as_deref() == Some("online") { + "online" + } else if !runs.is_empty() { + "away" + } else { + legacy.as_deref().unwrap_or("offline") + }; + if !detailed && status == "offline" { + continue; + } + let mut raw_tags = vec![vec!["p".to_string(), pk]]; + if detailed { + let payload = match serde_json::to_string(&runs) { + Ok(value) => value, + Err(e) => { + return Some(Err(internal_error(&format!("presence serialization: {e}")))) + } + }; + raw_tags.push(vec!["presence_runs".into(), "1".into(), payload]); + } + let tags = match raw_tags + .into_iter() + .map(nostr::Tag::parse) + .collect::, _>>() + { + Ok(tags) => tags, Err(e) => return Some(Err(internal_error(&format!("presence tag: {e}")))), }; let event = match nostr::EventBuilder::new( @@ -2320,9 +2363,9 @@ async fn synthesize_presence( Ok(event) => event, Err(e) => return Some(Err(internal_error(&format!("presence sign: {e}")))), }; - - if let Ok(v) = serde_json::to_value(&event) { - events.push(v); + match serde_json::to_value(&event) { + Ok(value) => events.push(value), + Err(e) => return Some(Err(internal_error(&format!("presence serialization: {e}")))), } } diff --git a/crates/buzz-relay/src/handlers/event.rs b/crates/buzz-relay/src/handlers/event.rs index ccba40f328..b462d1a5a7 100644 --- a/crates/buzz-relay/src/handlers/event.rs +++ b/crates/buzz-relay/src/handlers/event.rs @@ -174,6 +174,28 @@ pub async fn filter_fanout_by_access( matches }; + // This is the shared fence for local ingest, direct sends and Redis fan-out. + // A subscription (including a kindless known-id lookup) is not read authority. + let matches = + if buzz_core::kind::RESULT_GATED_KINDS.contains(&event_kind_u32(&stored_event.event)) { + matches + .into_iter() + .filter(|(conn_id, _)| { + state + .conn_manager + .pubkey_for_conn(*conn_id) + .is_some_and(|pk| { + buzz_core::filter::reader_authorized_for_event( + &stored_event.event, + &hex::encode(pk), + ) + }) + }) + .collect() + } else { + matches + }; + let Some(channel_id) = stored_event.channel_id else { return matches; }; @@ -234,10 +256,8 @@ pub async fn filter_fanout_by_access( /// /// All relay-local live fan-out routes through here. The two exceptions are /// `dispatch_persistent_event` (persistent ingest) and `fan_out_pubsub_event` -/// (Redis cross-node), which call `filter_fanout_by_access` inline: the former -/// layers an additional per-recipient DM-visibility-owner gate on top, the -/// latter skips local echoes — both are equivalent to this helper plus their -/// own extra step. +/// (Redis cross-node), which call `filter_fanout_by_access` inline. The latter +/// also skips local echoes; neither bypasses the shared private-event gates. pub(crate) async fn fan_out_event_to_local_subscribers( state: &AppState, community_id: CommunityId, @@ -454,40 +474,10 @@ async fn dispatch_persistent_event_inner( return 0; } }; - // For viewer-private events (kind:30622 DM visibility, kind:44200 agent turn - // metrics), live fan-out must reach only the owner — a kindless `ids:[…]` - // subscription can otherwise match it. Pull paths (HTTP /query, WS historical) - // are gated separately by reader_authorized_for_event. - let owner_only_kind = kind_u32 == buzz_core::kind::KIND_DM_VISIBILITY - || kind_u32 == buzz_core::kind::KIND_AGENT_TURN_METRIC; - let private_event_owner: Option = owner_only_kind - .then(|| { - let p = nostr::SingleLetterTag::lowercase(nostr::Alphabet::P); - stored_event - .event - .tags - .filter(nostr::TagKind::SingleLetter(p)) - .find_map(|t| t.content().map(|s| s.to_string())) - }) - .flatten(); - // Author-only delivery gating (NIP-ER reminders) is enforced centrally in - // filter_fanout_by_access, applied to `matches` above before this loop. The - // DM visibility owner gate is an additional delivery fence, so build shared - // frames only after applying it to the already access-filtered recipient set. + // All private-event gates have already run in filter_fanout_by_access. let recipients: Vec<_> = matches .iter() - .filter_map(|(target_conn_id, sub_id)| { - if let Some(ref owner_hex) = private_event_owner { - let is_owner = state - .conn_manager - .pubkey_for(*target_conn_id) - .is_some_and(|pk| hex::encode(pk) == *owner_hex); - if !is_owner { - return None; - } - } - Some((*target_conn_id, sub_id.as_str())) - }) + .map(|(conn_id, sub_id)| (*conn_id, sub_id.as_str())) .collect(); let frames = fanout_frame_cache(recipients.iter().map(|(_, sub_id)| *sub_id), &event_json); let drop_count = send_fanout_frames(state, recipients, &frames); @@ -653,11 +643,36 @@ pub async fn handle_event(event: Event, conn: Arc, state: Arc(&raw) - .ok() - .and_then(|v| v.get("status")?.as_str().map(String::from)) - .unwrap_or(raw) - } else if raw.len() > 128 { - let mut end = 128; - while !raw.is_char_boundary(end) { - end -= 1; + if let Some(pulse) = + buzz_core::run_presence::parse_run(&event, nostr::Timestamp::now().as_secs())? + { + // No process-local disconnect cleanup and no shared pubkey slot: + // one run stopping must not erase another node's live placement. + if !state + .pubsub + .update_run_presence( + &conn.tenant, + &event.pubkey, + &pulse, + nostr::Timestamp::now().as_secs(), + ) + .await + .map_err(|_| "error: presence store unavailable")? + { + return Ok(()); // stale/duplicate updates are never fanned out } - raw[..end].to_string() } else { - raw - }; + // Accept both bare strings ("online") and legacy JSON ({"status":"online"}). + let raw = event.content.to_string(); + let status = if raw.starts_with('{') { + serde_json::from_str::(&raw) + .ok() + .and_then(|v| v.get("status")?.as_str().map(String::from)) + .unwrap_or(raw) + } else if raw.len() > 128 { + let mut end = 128; + while !raw.is_char_boundary(end) { + end -= 1; + } + raw[..end].to_string() + } else { + raw + }; - if status == "offline" { - let _ = state - .pubsub - .clear_presence(&conn.tenant, &auth_pubkey) - .await; - } else { - let _ = state - .pubsub - .set_presence(&conn.tenant, &auth_pubkey, &status) - .await; + if status == "offline" { + let _ = state + .pubsub + .clear_presence(&conn.tenant, &auth_pubkey) + .await; + } else { + let _ = state + .pubsub + .set_presence(&conn.tenant, &auth_pubkey, &status) + .await; + } } - // Presence is a channel-less ephemeral event. After updating Redis // presence state, let it fall through to the shared global ephemeral // publish/fan-out path below so other relay nodes receive the live delta. @@ -1165,6 +1199,8 @@ fn single_tag_content<'a>(event: &'a Event, tag_name: &str) -> Result<&'a str, S #[cfg(test)] mod tests { + mod host_transport_tests; + use std::collections::HashMap; use std::sync::atomic::AtomicU8; use std::sync::Arc; @@ -1659,6 +1695,92 @@ mod tests { ); } + #[tokio::test] + async fn private_hosts_only_reach_owner_across_all_live_delivery_paths() { + let owner = Keys::generate(); + let host = Keys::generate(); + let outsider = Keys::generate(); + let reg = buzz_core::host::registration(&owner, host.public_key(), 100).unwrap(); + let rep = buzz_core::host::report( + &host, + ®, + &buzz_core::host::Report { + v: 1, + name: "private machine".into(), + os: "macos".into(), + arch: "aarch64".into(), + launcher_version: "test".into(), + runtimes: vec![], + accepts_start: false, + }, + 101, + ) + .unwrap(); + for event in [reg, rep] { + for path in ["pubsub", "direct", "ingest"] { + let state = test_state().await; + let filter = Filter::new().id(event.id); // no kind or #p gate + let mut receivers = Vec::new(); + for (name, key) in [ + ("owner", Some(&owner)), + ("outsider", Some(&outsider)), + ("host", Some(&host)), + ("anonymous", None), + ] { + let (_, rx) = register_global_sub( + &state, + name, + filter.clone(), + key.map(|k| k.public_key().to_bytes().to_vec()), + ); + receivers.push((name, rx)); + } + let community = buzz_core::tenant::CommunityId::from_uuid(Uuid::nil()); + let stored = buzz_core::StoredEvent::new(event.clone(), None); + match path { + "pubsub" => { + fan_out_pubsub_event( + &state, + ChannelEvent { + community_id: community, + topic: EventTopic::Global, + event: event.clone(), + }, + ) + .await + } + "direct" => { + super::super::fan_out_event_to_local_subscribers( + &state, community, &stored, + ) + .await + } + _ => { + super::super::dispatch_persistent_event_inner( + &buzz_core::tenant::TenantContext::resolved(community, "test"), + &state, + &stored, + buzz_core::kind::KIND_HOST, + &owner.public_key().to_hex(), + false, + None, + ) + .await; + } + } + for (name, mut rx) in receivers { + if name == "owner" { + assert_eq!(event_from_ws_message(rx.try_recv().unwrap()).id, event.id); + } + assert!( + rx.try_recv().is_err(), + "{path}: unexpected delivery to {name}" + ); + } + } + } + } + async fn redis_url_if_available() -> Option { let redis_url = std::env::var("REDIS_URL").unwrap_or_else(|_| "redis://127.0.0.1:6379".to_string()); diff --git a/crates/buzz-relay/src/handlers/event/tests/host_transport_tests.rs b/crates/buzz-relay/src/handlers/event/tests/host_transport_tests.rs new file mode 100644 index 0000000000..3f1f1412c0 --- /dev/null +++ b/crates/buzz-relay/src/handlers/event/tests/host_transport_tests.rs @@ -0,0 +1,357 @@ +//! Parse EVENT frames and exercise the WS handler, shared ingest, and primary DB. +use super::*; +use axum::extract::ws::Message; +use buzz_auth::{AuthContext, AuthMethod, Scope}; +use buzz_core::{host, tenant::TenantContext}; +use nostr::{Event, Timestamp}; +use serde_json::{json, Value}; + +fn connection( + tenant: TenantContext, + keys: &Keys, +) -> ( + Arc, + mpsc::Receiver, +) { + let (send_tx, rx) = mpsc::channel(32); + let (ctrl_tx, _) = mpsc::channel(8); + ( + Arc::new(crate::connection::ConnectionState { + conn_id: Uuid::new_v4(), + tenant, + remote_addr: "127.0.0.1:1".parse().unwrap(), + auth_state: RwLock::new(crate::connection::AuthState::Authenticated(AuthContext { + pubkey: keys.public_key(), + scopes: vec![Scope::UsersWrite, Scope::MessagesWrite], + channel_ids: None, + auth_method: AuthMethod::Nip42, + agent_owner_pubkey: None, + })), + subscriptions: Arc::new(Mutex::new(HashMap::new())), + send_tx, + ctrl_tx, + cancel: CancellationToken::new(), + backpressure_count: Arc::new(AtomicU8::new(0)), + grace_limit: 3, + }), + rx, + ) +} + +async fn publish( + state: &Arc, + conn: &Arc, + rx: &mut mpsc::Receiver, + event: &Event, +) -> Value { + let crate::protocol::ClientMessage::Event(parsed) = + crate::protocol::ClientMessage::parse(&json!(["EVENT", event]).to_string()).unwrap() + else { + panic!("EVENT frame"); + }; + super::super::handle_event(parsed, conn.clone(), state.clone()).await; + let Message::Text(frame) = rx.try_recv().expect("handler must send ACK") else { + panic!("text ACK"); + }; + let ack: Value = serde_json::from_str(&frame).unwrap(); + assert_eq!(ack[0], "OK"); + assert_eq!(ack[1], event.id.to_hex()); + assert!(rx.try_recv().is_err()); + ack +} + +fn resign(event: &Event, keys: &Keys, tags: Vec, kind: Kind) -> Event { + EventBuilder::new(kind, event.content.clone()) + .tags(tags) + .sign_with_keys(keys) + .unwrap() +} + +#[tokio::test] +#[ignore = "requires isolated MULTIVERSE_TEST_DATABASE_URL and REDIS_URL; no skip fallback"] +async fn host_report_owner_ws_handler_ack_and_strict_negatives() { + let url = std::env::var("MULTIVERSE_TEST_DATABASE_URL").expect("isolated PG required"); + assert_eq!(std::env::var("DATABASE_URL").unwrap(), url); + let redis = std::env::var("REDIS_URL").expect("isolated Redis required"); + let state = super::fanout_access::test_state_with_redis_url(&redis).await; + let community = state + .db + .ensure_configured_community(&format!("host-event-{}.test", Uuid::new_v4())) + .await + .unwrap(); + let tenant = TenantContext::resolved(community.id, community.host); + let owner = Keys::generate(); + let host = Keys::generate(); + let outsider = Keys::generate(); + let (conn, mut rx) = connection(tenant.clone(), &owner); + let now = Timestamp::now().as_secs(); + let reg = host::registration(&owner, host.public_key(), now).unwrap(); + let rep = host::report( + &host, + ®, + &host::Report { + v: 1, + name: "synthetic".into(), + os: "test".into(), + arch: "test".into(), + launcher_version: "test".into(), + runtimes: vec![], + accepts_start: false, + }, + now, + ) + .unwrap(); + for event in [®, &rep] { + let ack = publish(&state, &conn, &mut rx, event).await; + assert_eq!(ack[2], true, "{ack}"); + let stored = state + .db + .get_event_by_id(tenant.community(), &event.id.to_bytes()) + .await + .unwrap() + .unwrap(); + assert_eq!(stored.event, *event, "ACK must follow writer commit"); + } + // Authorization precedes duplicate detection: even an accepted event is not + // portable to an outsider, a host-authenticated socket, or a scoped token. + for keys in [&outsider, &host] { + let (foreign, mut foreign_rx) = connection(tenant.clone(), keys); + let ack = publish(&state, &foreign, &mut foreign_rx, &rep).await; + assert_eq!(ack[2], false, "{ack}"); + assert!(ack[3] + .as_str() + .unwrap() + .contains("owner's global connection")); + } + let (scoped, mut scoped_rx) = connection(tenant.clone(), &owner); + if let crate::connection::AuthState::Authenticated(ctx) = &mut *scoped.auth_state.write().await + { + ctx.channel_ids = Some(vec![]); + } + assert_eq!( + publish(&state, &scoped, &mut scoped_rx, &rep).await[2], + false + ); + + let tags: Vec = rep.tags.iter().cloned().collect(); + let replace = |key: &str, value: String| -> Vec { + tags.iter() + .map(|t| { + if t.as_slice()[0] == key { + Tag::parse([key.to_owned(), value.clone()]).unwrap() + } else { + t.clone() + } + }) + .collect() + }; + let mut duplicate_owner = tags.clone(); + duplicate_owner.push(Tag::parse(["p", &owner.public_key().to_hex()]).unwrap()); + let negatives = [ + ( + resign(&rep, &outsider, tags.clone(), rep.kind), + "signer does not match", + ), + ( + resign( + &rep, + &outsider, + replace("x", outsider.public_key().to_hex()), + rep.kind, + ), + "binding mismatch", + ), + ( + resign( + &rep, + &host, + replace("L", "forged.namespace".into()), + rep.kind, + ), + "namespace", + ), + ( + resign(&rep, &host, replace("e", "00".repeat(32)), rep.kind), + "registration not found", + ), + ( + resign( + &rep, + &host, + replace("valid_until", (now + 1000).to_string()), + rep.kind, + ), + "lifetime", + ), + ( + resign(&rep, &host, duplicate_owner, rep.kind), + "cardinality", + ), + ( + resign(&rep, &host, tags.clone(), Kind::Metadata), + "pubkey does not match", + ), + ( + resign( + &rep, + &host, + tags.clone(), + Kind::Custom(KIND_PRESENCE_UPDATE as u16), + ), + "pubkey does not match", + ), + ( + resign( + &rep, + &host, + tags, + Kind::Custom(KIND_AGENT_OBSERVER_FRAME as u16), + ), + "pubkey does not match", + ), + ]; + for (event, reason) in negatives { + let ack = publish(&state, &conn, &mut rx, &event).await; + assert_eq!(ack[2], false, "{ack}"); + assert!( + ack[3].as_str().unwrap().contains(reason), + "{ack}: expected {reason}" + ); + assert!(state + .db + .get_event_by_id(tenant.community(), &event.id.to_bytes()) + .await + .unwrap() + .is_none()); + } + let (anonymous, mut anon_rx) = connection(tenant, &owner); + *anonymous.auth_state.write().await = crate::connection::AuthState::Pending { + challenge: "test".into(), + }; + assert_eq!( + publish(&state, &anonymous, &mut anon_rx, &rep).await[2], + false + ); +} + +#[tokio::test] +#[ignore = "requires isolated MULTIVERSE_TEST_DATABASE_URL and REDIS_URL; no skip fallback"] +async fn host_and_agent_runs_require_authority_and_preserve_other_placements() { + let url = std::env::var("MULTIVERSE_TEST_DATABASE_URL").expect("isolated PG required"); + assert_eq!(std::env::var("DATABASE_URL").unwrap(), url); + let redis = std::env::var("REDIS_URL").expect("isolated Redis required"); + let state = super::fanout_access::test_state_with_redis_url(&redis).await; + let community = state + .db + .ensure_configured_community(&format!("runs-{}.test", Uuid::new_v4())) + .await + .unwrap(); + let tenant = TenantContext::resolved(community.id, community.host); + let other_community = state + .db + .ensure_configured_community(&format!("runs-other-{}.test", Uuid::new_v4())) + .await + .unwrap(); + let other_tenant = TenantContext::resolved(other_community.id, other_community.host); + let owner = Keys::generate(); + let host = Keys::generate(); + let agent = Keys::generate(); + let outsider = Keys::generate(); + let (conn, mut rx) = connection(tenant.clone(), &owner); + let now = Timestamp::now().as_secs(); + let reg = host::registration(&owner, host.public_key(), now).unwrap(); + assert_eq!(publish(&state, &conn, &mut rx, ®).await[2], true); + let host_pulse = buzz_core::run_presence::pulse( + &host, + &"a".repeat(32), + 0, + "online", + None, + Some(®.id.to_hex()), + now, + ) + .unwrap(); + assert_eq!(publish(&state, &conn, &mut rx, &host_pulse).await[2], true); + for (scope, signer) in [ + (tenant.clone(), &host), + (tenant.clone(), &outsider), + (other_tenant.clone(), &owner), + ] { + let (foreign, mut foreign_rx) = connection(scope, signer); + assert_eq!( + publish(&state, &foreign, &mut foreign_rx, &host_pulse).await[2], + false + ); + } + let (scoped, mut scoped_rx) = connection(tenant.clone(), &owner); + if let crate::connection::AuthState::Authenticated(auth) = &mut *scoped.auth_state.write().await + { + auth.channel_ids = Some(vec![]); + } + assert_eq!( + publish(&state, &scoped, &mut scoped_rx, &host_pulse).await[2], + false + ); + let mut tampered = host_pulse.clone(); + tampered.content = "offline".into(); + assert_eq!(publish(&state, &conn, &mut rx, &tampered).await[2], false); + assert_eq!( + state + .pubsub + .active_presence_runs(&tenant, &host.public_key(), now) + .await + .unwrap() + .len(), + 1 + ); + assert!(state + .pubsub + .active_presence_runs(&other_tenant, &host.public_key(), now) + .await + .unwrap() + .is_empty()); + + let (agent_conn, mut agent_rx) = connection(tenant.clone(), &agent); + let location = buzz_core::run_presence::Location { + host: host.public_key().to_hex(), + label: "Workshop".into(), + }; + let pulse = |run: &str, seq, status| { + buzz_core::run_presence::pulse(&agent, run, seq, status, Some(&location), None, now) + .unwrap() + }; + let first = pulse(&"b".repeat(32), 0, "online"); + let second = pulse(&"c".repeat(32), 0, "online"); + // Possessing the owner connection never permits impersonating an agent pulse. + assert_eq!(publish(&state, &conn, &mut rx, &first).await[2], false); + for event in [&first, &second] { + assert_eq!( + publish(&state, &agent_conn, &mut agent_rx, event).await[2], + true + ); + } + let stop = pulse(&"b".repeat(32), 1, "offline"); + assert_eq!( + publish(&state, &agent_conn, &mut agent_rx, &stop).await[2], + true + ); + // Delayed pulses are ACKed but cannot resurrect a stopped generation. + assert_eq!( + publish(&state, &agent_conn, &mut agent_rx, &first).await[2], + true + ); + let runs = state + .pubsub + .active_presence_runs(&tenant, &agent.public_key(), now) + .await + .unwrap(); + assert_eq!(runs.len(), 1); + assert_eq!(runs[0].run, "c".repeat(32)); + assert_eq!(runs[0].location, Some(location)); + assert!(state + .pubsub + .active_presence_runs(&tenant, &agent.public_key(), now + 180) + .await + .unwrap() + .is_empty()); +} diff --git a/crates/buzz-relay/src/handlers/history.rs b/crates/buzz-relay/src/handlers/history.rs new file mode 100644 index 0000000000..5068f77ba7 --- /dev/null +++ b/crates/buzz-relay/src/handlers/history.rs @@ -0,0 +1,73 @@ +//! Historical reads used by WS REQ and the HTTP bridge. +//! +//! Host reconciliation is a write decision, not a bounded-stale display read. +use buzz_core::{kind::KIND_HOST, StoredEvent}; +use buzz_db::{Db, EventQuery}; +use nostr::Filter; + +#[derive(Debug, thiserror::Error)] +pub(crate) enum HistoryError { + #[error("database error: {0}")] + Database(#[from] buzz_db::DbError), +} + +impl HistoryError { + // Never put database diagnostics or private query metadata on the wire. + pub(crate) fn wire_message(&self) -> &'static str { + match self { + Self::Database(_) => "error: database error", + } + } +} + +pub(crate) fn explicitly_requests_hosts(filter: &Filter) -> bool { + filter.kinds.as_ref().is_some_and(|kinds| { + kinds + .iter() + .any(|kind| u32::from(kind.as_u16()) == KIND_HOST) + }) +} + +pub(crate) fn requires_primary(filter: &Filter) -> bool { + // Kindless known-ID reads can also return a host. Do not let that spelling + // turn a reconciliation read into a replica read. Explicit unrelated kinds + // keep their existing routing. Kind 50000 currently admits only buzz.host.v1. + filter.kinds.is_none() || explicitly_requests_hosts(filter) +} + +pub(crate) async fn query( + db: &Db, + path: &'static str, + filter: &Filter, + mut params: EventQuery, +) -> Result, HistoryError> { + if !requires_primary(filter) { + return Ok(db.query_events_routed(path, ¶ms).await?); + } + // event_mentions is a best-effort index written AFTER the event commit. + // Even on the primary that join can transiently (or permanently, on index + // write failure) hide an existing registration. Use the authoritative event + // tags for host-capable reads. All other per-result gates still run. + // The bridge's unrelated buzz-channel extension also uses custom_tag; + // retain it rather than changing the semantics of a kindless query. + if params.custom_tag.is_none() { + if let Some(owner) = params.p_tag_hex.take() { + params.custom_tag = Some(("p".into(), owner)); + } + } + if explicitly_requests_hosts(filter) { + // Push every generic tag into the authoritative query. A short page + // now proves exhaustion, even when thousands of unrelated profiles or + // other owners' records would otherwise consume the candidate LIMIT. + params.p_tag_hex = None; + params.exact_tags = filter + .generic_tags + .iter() + .map(|(name, values)| (name.to_string(), values.iter().cloned().collect())) + .collect(); + } + Ok(db.query_events(¶ms).await?) +} + +#[cfg(test)] +mod tests; diff --git a/crates/buzz-relay/src/handlers/history/tests.rs b/crates/buzz-relay/src/handlers/history/tests.rs new file mode 100644 index 0000000000..6a57324480 --- /dev/null +++ b/crates/buzz-relay/src/handlers/history/tests.rs @@ -0,0 +1,299 @@ +//! Drive parsed REQs through the real handler and inspect outbound WS frames. +use std::collections::HashMap; +use std::sync::atomic::{AtomicU8, AtomicUsize, Ordering}; +use std::sync::Arc; +use std::time::Duration; + +use axum::extract::ws::Message; +use buzz_auth::{AuthContext, AuthMethod}; +use buzz_core::tenant::{CommunityId, TenantContext}; +use buzz_db::Db; +use nostr::Keys; +use serde_json::{json, Value}; +use sqlx::postgres::PgPoolOptions; +use tokio::sync::{mpsc, Mutex, RwLock}; +use tokio_util::sync::CancellationToken; +use uuid::Uuid; + +use crate::connection::{AuthState, ConnectionState}; +use crate::protocol::ClientMessage; +use crate::state::AppState; + +async fn state(db: Db, pool: sqlx::PgPool) -> Arc { + state_with_redis(db, pool, "redis://127.0.0.1:1".into()).await +} + +async fn state_with_redis(db: Db, pool: sqlx::PgPool, redis_url: String) -> Arc { + let mut config = crate::config::Config::from_env().unwrap(); + config.require_relay_membership = false; + config.redis_url = redis_url; + config.require_auth_token = true; + let redis = deadpool_redis::Config::from_url(&config.redis_url) + .create_pool(Some(deadpool_redis::Runtime::Tokio1)) + .unwrap(); + let pubsub = Arc::new( + buzz_pubsub::PubSubManager::new(&config.redis_url, redis.clone()) + .await + .unwrap(), + ); + let audit = buzz_audit::AuditService::new(pool.clone()); + let auth = buzz_auth::AuthService::new(config.auth.clone()); + let search = buzz_search::SearchService::new(pool); + let workflow = Arc::new(buzz_workflow::WorkflowEngine::new( + db.clone(), + Default::default(), + )); + let media = buzz_media::MediaStorage::new(&config.media).unwrap(); + let (state, _) = AppState::new( + config, + db, + redis, + audit, + pubsub, + auth, + search, + workflow, + Keys::generate(), + media, + ); + Arc::new(state) +} + +fn connection( + state: &AppState, + tenant: TenantContext, + keys: &Keys, +) -> (Arc, mpsc::Receiver) { + let (send_tx, rx) = mpsc::channel(2048); + let (ctrl_tx, _) = mpsc::channel(8); + state.accessible_channels_cache.insert( + (tenant.community(), keys.public_key().to_bytes().to_vec()), + vec![], + ); + ( + Arc::new(ConnectionState { + conn_id: Uuid::new_v4(), + tenant, + remote_addr: "127.0.0.1:1".parse().unwrap(), + auth_state: RwLock::new(AuthState::Authenticated(AuthContext { + pubkey: keys.public_key(), + scopes: vec![], + channel_ids: None, + auth_method: AuthMethod::Nip42, + agent_owner_pubkey: None, + })), + subscriptions: Arc::new(Mutex::new(HashMap::new())), + send_tx, + ctrl_tx, + cancel: CancellationToken::new(), + backpressure_count: Arc::new(AtomicU8::new(0)), + grace_limit: 3, + }), + rx, + ) +} + +async fn req( + state: &Arc, + conn: &Arc, + rx: &mut mpsc::Receiver, + filters: Vec, +) -> Vec { + let mut wire = vec![json!("REQ"), json!("host-history")]; + wire.extend(filters); + let ClientMessage::Req { sub_id, filters } = + ClientMessage::parse(&Value::Array(wire).to_string()).unwrap() + else { + panic!("REQ") + }; + crate::handlers::req::handle_req(sub_id, filters, conn.clone(), state.clone()).await; + let mut frames = vec![]; + while let Ok(frame) = rx.try_recv() { + let Message::Text(text) = frame else { + panic!("text frame") + }; + frames.push(serde_json::from_str(&text).unwrap()); + } + frames +} + +fn host_filter(keys: &Keys, label: &str) -> Value { + json!({"kinds":[50000], "authors":[keys.public_key().to_hex()], "#p":[keys.public_key().to_hex()], "#L":["buzz.host.v1"], "#l":[label], "limit":1000}) +} + +/// A listening TCP endpoint counts attempted replica checkouts. The fence and +/// bounded-read budget are open; a control REQ proves routing reaches it. No PG +/// or Redis service is required and no real configuration credentials are used. +#[tokio::test] +async fn host_req_failure_is_closed_and_bypasses_eligible_replica() { + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let address = listener.local_addr().unwrap(); + let attempts = Arc::new(AtomicUsize::new(0)); + let count = attempts.clone(); + let server = tokio::spawn(async move { + while let Ok((socket, _)) = listener.accept().await { + count.fetch_add(1, Ordering::SeqCst); + drop(socket); + } + }); + let writer = PgPoolOptions::new() + .connect_lazy("postgres://test:test@127.0.0.1:1/test") + .unwrap(); + writer.close().await; // Deterministic query failure, not access-cache failure. + let reader = PgPoolOptions::new() + .acquire_timeout(Duration::from_millis(100)) + .connect_lazy(&format!( + "postgres://test:test@{address}/test?sslmode=disable" + )) + .unwrap(); + let mut db = Db::from_pools(writer.clone(), reader); + db.set_replica_read_max_age_for_tests(Some(Duration::from_secs(60))); + db.fence().force_open_for_tests(chrono::Utc::now()); + let state = state(db, writer).await; + let owner = Keys::generate(); + let tenant = + TenantContext::resolved(CommunityId::from_uuid(Uuid::new_v4()), "host-history.test"); + let (conn, mut rx) = connection(&state, tenant, &owner); + for filters in [ + vec![host_filter(&owner, "registration")], + vec![host_filter(&owner, "report")], + vec![json!({"ids":["aa".repeat(32)]})], + // Failure in another filter must not turn a host-containing REQ into + // partial success. The whole multi-filter history is one read outcome. + vec![json!({"kinds":[0]}), host_filter(&owner, "registration")], + ] { + let before = attempts.load(Ordering::SeqCst); + let mixed = filters.len() > 1; + let frames = req(&state, &conn, &mut rx, filters).await; + assert_eq!( + frames, + vec![json!(["CLOSED", "host-history", "error: database error"])] + ); + assert!(conn.subscriptions.lock().await.is_empty()); + assert_eq!(state.sub_registry.total_subscriptions(), 0); + if !mixed { + assert_eq!( + attempts.load(Ordering::SeqCst), + before, + "host reads must never attempt a replica checkout" + ); + } + } + let before = attempts.load(Ordering::SeqCst); + let frames = req(&state, &conn, &mut rx, vec![json!({"kinds":[0]})]).await; + assert_eq!(frames, vec![json!(["EOSE", "host-history"])]); + assert!( + attempts.load(Ordering::SeqCst) > before, + "negative control must attempt routed history" + ); + assert_eq!( + state.sub_registry.total_subscriptions(), + 1, + "legacy unrelated error behavior retained" + ); + server.abort(); +} + +#[tokio::test] +async fn host_req_authorization_and_search_fail_before_history() { + let pool = PgPoolOptions::new() + .connect_lazy("postgres://test:test@127.0.0.1:1/test") + .unwrap(); + pool.close().await; + let state = state(Db::from_pool(pool.clone()), pool).await; + let owner = Keys::generate(); + let other = Keys::generate(); + let tenant = + TenantContext::resolved(CommunityId::from_uuid(Uuid::new_v4()), "host-history.test"); + let (conn, mut rx) = connection(&state, tenant, &other); + let frames = req( + &state, + &conn, + &mut rx, + vec![host_filter(&owner, "registration")], + ) + .await; + assert_eq!(frames[0][0], "CLOSED"); + assert!(frames[0][2].as_str().unwrap().starts_with("restricted:")); + let mut search = host_filter(&other, "registration"); + search["search"] = json!("test"); + assert_eq!( + req(&state, &conn, &mut rx, vec![search]).await, + vec![json!([ + "CLOSED", + "host-history", + "error: host history search is unsupported" + ])] + ); + assert_eq!(state.sub_registry.total_subscriptions(), 0); +} + +/// Opt-in transport integration against an isolated, migrated database. Does +/// not silently skip or use the configured/shared relay database. +#[tokio::test] +#[ignore = "requires isolated migrated Postgres: MULTIVERSE_TEST_DATABASE_URL"] +async fn host_req_primary_exact_tags_precede_limit_and_private_results_are_safe() { + let url = + std::env::var("MULTIVERSE_TEST_DATABASE_URL").expect("isolated database URL required"); + let pool = sqlx::PgPool::connect(&url).await.unwrap(); + let db = Db::from_pool(pool.clone()); + let host_name = format!("host-history-{}.test", Uuid::new_v4()); + let community = db.ensure_configured_community(&host_name).await.unwrap(); + let tenant = TenantContext::resolved(community.id, host_name); + let owner = Keys::generate(); + let registration = buzz_core::host::registration( + &owner, + Keys::generate().public_key(), + nostr::Timestamp::now().as_secs(), + ) + .unwrap(); + // Deliberately omit event_mentions. It is not authoritative registration state. + buzz_db::event::insert_event(&pool, tenant.community(), ®istration, None) + .await + .unwrap(); + let state = state(db, pool.clone()).await; + let (conn, mut rx) = connection(&state, tenant.clone(), &owner); + let frames = req( + &state, + &conn, + &mut rx, + vec![host_filter(&owner, "registration")], + ) + .await; + assert_eq!(frames.len(), 2); + assert_eq!(frames[0][2]["id"], registration.id.to_hex()); + assert_eq!(frames[1], json!(["EOSE", "host-history"])); + + // Unrelated registrations cannot consume a report page before LIMIT. + let mut capped = host_filter(&owner, "report"); + capped["limit"] = json!(1); + assert_eq!( + req(&state, &conn, &mut rx, vec![capped]).await, + vec![json!(["EOSE", "host-history"])] + ); + assert_eq!(state.sub_registry.total_subscriptions(), 1); + + // Known-ID requests still apply owner-only visibility on every returned row. + for keys in [&owner, &Keys::generate()] { + let (conn, mut rx) = connection(&state, tenant.clone(), keys); + let frames = req( + &state, + &conn, + &mut rx, + vec![json!({"ids":[registration.id.to_hex()], "limit":1})], + ) + .await; + if keys.public_key() == owner.public_key() { + assert_eq!(frames.len(), 2); + assert_eq!(frames[0][2]["id"], registration.id.to_hex()); + } else { + assert_eq!(frames, vec![json!(["EOSE", "host-history"])]); + } + } + // This fixture uses a unique community; leave service lifecycle to its owner. + pool.close().await; +} + +mod paging; + +mod mixed_tags; diff --git a/crates/buzz-relay/src/handlers/history/tests/mixed_tags.rs b/crates/buzz-relay/src/handlers/history/tests/mixed_tags.rs new file mode 100644 index 0000000000..e003b548f4 --- /dev/null +++ b/crates/buzz-relay/src/handlers/history/tests/mixed_tags.rs @@ -0,0 +1,95 @@ +//! The shared SQL predicate must agree with the core matcher, even when a +//! host-capable filter also requests derived-channel reactions/deletions. +use super::*; +use buzz_core::filter::filters_match; +use buzz_db::EventQuery; +use nostr::{EventBuilder, Filter, Kind, Tag}; + +#[tokio::test] +#[ignore = "requires isolated migrated Postgres: MULTIVERSE_TEST_DATABASE_URL"] +async fn mixed_host_h_filter_preserves_derived_channels_and_explicit_tag_authority() { + let url = std::env::var("MULTIVERSE_TEST_DATABASE_URL").expect("isolated DB required"); + let pool = sqlx::PgPool::connect(&url).await.unwrap(); + let db = Db::from_pool(pool.clone()); + let community = db + .ensure_configured_community(&format!("mixed-tags-{}.test", Uuid::new_v4())) + .await + .unwrap(); + let owner = Keys::generate(); + let author = Keys::generate(); + let channel = Uuid::new_v4(); + let other_channel = Uuid::new_v4().to_string(); + let channel_text = channel.to_string(); + let owner_text = owner.public_key().to_hex(); + let mut expected = vec![]; + for (index, h_tags) in [ + vec![], + vec![vec!["h", channel_text.as_str()]], + vec![vec!["h", other_channel.as_str()]], + vec![vec!["h"]], + vec![vec!["h", other_channel.as_str(), channel_text.as_str()]], + ] + .into_iter() + .enumerate() + { + let mut tags = vec![Tag::parse(["p", &owner_text]).unwrap()]; + tags.extend(h_tags.into_iter().map(|t| Tag::parse(t).unwrap())); + let event = EventBuilder::new(Kind::Reaction, index.to_string()) + .tags(tags) + .sign_with_keys(&author) + .unwrap(); + buzz_db::event::insert_event(&pool, community.id, &event, Some(channel)) + .await + .unwrap(); + if index < 2 { + expected.push(event.id); + } + } + for kinds in [json!([7]), json!([7, 50000])] { + for values in [ + json!([channel_text]), + json!([Uuid::new_v4().to_string(), channel_text]), + json!([]), + ] { + let filter: Filter = serde_json::from_value(json!({ + "kinds": kinds, "#h": values, "#p": [owner_text], "limit": 1000 + })) + .unwrap(); + let mut params = EventQuery::for_community(community.id); + params.kinds = Some(if kinds == json!([7]) { + vec![7] + } else { + vec![7, 50000] + }); + params.exact_tags = filter + .generic_tags + .iter() + .map(|(k, v)| (k.to_string(), v.iter().cloned().collect())) + .collect(); + // No event_mentions index: exact p predicates use primary tags. + let rows = + crate::handlers::history::query(&db, "mixed-tags-test", &filter, params.clone()) + .await + .unwrap(); + let count = buzz_db::event::count_events(&pool, ¶ms).await.unwrap(); + assert_eq!( + count as usize, + rows.len(), + "COUNT shares the query predicate" + ); + assert!(rows + .iter() + .all(|row| filters_match(std::slice::from_ref(&filter), row))); + let mut actual: Vec<_> = rows.iter().map(|row| row.event.id).collect(); + actual.sort(); + let mut want = if values == json!([]) { + vec![] + } else { + expected.clone() + }; + want.sort(); + assert_eq!(actual, want, "kinds={kinds}, h={values}"); + } + } + pool.close().await; +} diff --git a/crates/buzz-relay/src/handlers/history/tests/paging.rs b/crates/buzz-relay/src/handlers/history/tests/paging.rs new file mode 100644 index 0000000000..702a4a1c51 --- /dev/null +++ b/crates/buzz-relay/src/handlers/history/tests/paging.rs @@ -0,0 +1,142 @@ +//! Actual HTTP handler + signed NIP-98 + isolated Postgres/Redis, no fake pages. +use super::*; +use axum::{ + extract::State, + http::{HeaderMap, StatusCode}, + Json, +}; +use base64::Engine; +use nostr::{Event, EventBuilder, Kind, Tag}; +use sha2::{Digest, Sha256}; + +async fn query_http( + state: Arc, + host: &str, + signer: &Keys, + filter: Value, +) -> Result, (StatusCode, Json)> { + let body = serde_json::to_vec(&json!([filter])).unwrap(); + let url = format!( + "{}://{host}/query", + if state.config.relay_url.starts_with("wss:") { + "https" + } else { + "http" + } + ); + let auth = EventBuilder::new(Kind::HttpAuth, "") + .tags([ + Tag::parse(["u", &url]).unwrap(), + Tag::parse(["method", "POST"]).unwrap(), + Tag::parse(["payload", &hex::encode(Sha256::digest(&body))]).unwrap(), + Tag::parse(["nonce", &Uuid::new_v4().to_string()]).unwrap(), + ]) + .sign_with_keys(signer) + .unwrap(); + let mut headers = HeaderMap::new(); + headers.insert("host", host.parse().unwrap()); + headers.insert( + "authorization", + format!( + "Nostr {}", + base64::engine::general_purpose::STANDARD.encode(serde_json::to_vec(&auth).unwrap()) + ) + .parse() + .unwrap(), + ); + crate::api::bridge::query_events(State(state), headers, body.into()).await +} + +#[tokio::test] +#[ignore = "requires isolated Postgres MULTIVERSE_TEST_DATABASE_URL and Redis REDIS_URL"] +async fn host_http_pages_exhaust_timestamp_ties_and_never_leak_other_owners() { + let url = std::env::var("MULTIVERSE_TEST_DATABASE_URL").expect("isolated DB required"); + let pool = sqlx::PgPool::connect(&url).await.unwrap(); + let db = Db::from_pool(pool.clone()); + let hostname = format!("host-pages-{}.test", Uuid::new_v4()); + let community = db.ensure_configured_community(&hostname).await.unwrap(); + let owner = Keys::generate(); + let host = Keys::generate(); + let other = Keys::generate(); + let timestamp = nostr::Timestamp::now().as_secs(); + let mut registrations = vec![]; + let mut profiles = vec![]; + let report = buzz_core::host::Report { + v: 2, + name: "Private test machine".into(), + os: "test".into(), + arch: "test".into(), + launcher_version: "test".into(), + runtimes: vec![], + accepts_start: false, + }; + // All records tie on timestamp. No event_mentions are populated. The + // profile query must not lose its rows to a registration candidate page. + for _ in 0..1001 { + let reg = buzz_core::host::registration(&owner, host.public_key(), timestamp).unwrap(); + let profile = buzz_core::host::profile(&host, ®, &report, timestamp).unwrap(); + for e in [®, &profile] { + buzz_db::event::insert_event(&pool, community.id, e, None) + .await + .unwrap(); + } + registrations.push(reg.id.to_hex()); + profiles.push(profile.id.to_hex()); + } + let foreign = buzz_core::host::registration(&other, host.public_key(), timestamp + 1).unwrap(); + buzz_db::event::insert_event(&pool, community.id, &foreign, None) + .await + .unwrap(); + let state = state_with_redis( + db, + pool.clone(), + std::env::var("REDIS_URL").expect("isolated Redis required"), + ) + .await; + let tenant = TenantContext::resolved(community.id, &hostname); + let (_conn, _rx) = connection(&state, tenant, &owner); + for (label, author, mut expected) in [ + ("registration", owner.public_key(), registrations), + ("profile", host.public_key(), profiles), + ] { + let mut filter = json!({"kinds":[50000], "authors":[author.to_hex()], "#p":[owner.public_key().to_hex()], "#L":["buzz.host.v1"], "#l":[label], "#x":[host.public_key().to_hex()], "limit":1000}); + let mut ids = vec![]; + let mut sizes = vec![]; + loop { + let Json(value) = query_http(state.clone(), &hostname, &owner, filter.clone()) + .await + .unwrap(); + let mut events: Vec = serde_json::from_value(value).unwrap(); + events.sort_by_key(|e| e.id.to_hex()); + sizes.push(events.len()); + ids.extend(events.iter().map(|e| e.id.to_hex())); + if events.len() < 1000 { + break; + } + let last = events.last().unwrap(); + filter["until"] = json!(last.created_at.as_secs()); + filter["before_id"] = json!(last.id.to_hex()); + } + expected.sort(); + assert_eq!(ids, expected); + assert_eq!(sizes, [1000, 1]); + // Reusing an owner's filters from a different signed identity is denied. + let denied = query_http(state.clone(), &hostname, &other, filter) + .await + .unwrap_err(); + assert_eq!(denied.0, StatusCode::FORBIDDEN); + } + let Json(rows) = query_http( + state.clone(), + &hostname, + &owner, + json!({"ids":[foreign.id.to_hex()], "limit":1}), + ) + .await + .unwrap(); + assert_eq!(rows, json!([])); + // Malformed composite cursor is a failure, never an empty successful page. + let bad = query_http(state, &hostname, &owner, json!({"kinds":[50000], "#p":[owner.public_key().to_hex()], "before_id":"bad", "until":timestamp})).await.unwrap_err(); + assert_eq!(bad.0, StatusCode::BAD_REQUEST); + pool.close().await; +} diff --git a/crates/buzz-relay/src/handlers/hosts.rs b/crates/buzz-relay/src/handlers/hosts.rs new file mode 100644 index 0000000000..f7c4a29058 --- /dev/null +++ b/crates/buzz-relay/src/handlers/hosts.rs @@ -0,0 +1,163 @@ +//! Host transport is not delegation: only the registered owner may submit it. +use buzz_core::{host, tenant::TenantContext}; +use nostr::Event; + +use super::ingest::{IngestAuth, IngestError}; +use crate::state::AppState; + +fn invalid(error: String) -> IngestError { + IngestError::Rejected(format!("invalid: {error}")) +} + +fn envelope(event: &Event, auth: &IngestAuth, now: u64) -> Result { + let env = host::validate(event).map_err(invalid)?; + if env.owner != *auth.pubkey() || auth.channel_ids().is_some() { + return Err(IngestError::AuthFailed( + "restricted: host events require their owner's global connection".into(), + )); + } + if event.created_at.as_secs() > now.saturating_add(30) { + return Err(invalid("host timestamp is in the future".into())); + } + if env.valid_until.is_some_and(|until| until <= now) { + return Err(invalid("expired host report".into())); + } + Ok(env) +} + +fn binding(env: &host::Envelope, registration: &Event) -> Result<(), IngestError> { + let reg = host::validate(registration).map_err(invalid)?; + if reg.label != "registration" + || reg.host != env.host + || reg.owner != env.owner + || env.registration.as_deref() != Some(registration.id.to_hex().as_str()) + { + return Err(invalid("host registration binding mismatch".into())); + } + Ok(()) +} + +pub(super) async fn authorize( + tenant: &TenantContext, + state: &AppState, + event: &Event, + auth: &IngestAuth, +) -> Result<(), IngestError> { + let env = envelope(event, auth, nostr::Timestamp::now().as_secs())?; + if let Some(id) = env.registration.as_deref() { + let bytes = hex::decode(id).map_err(|e| invalid(e.to_string()))?; + // A registration from another community or a deleted registration is + // not authority. The owner check above runs before this existence lookup. + let stored = state + .db + .get_event_by_id(tenant.community(), &bytes) + .await + .map_err(|e| IngestError::Internal(e.to_string()))? + .ok_or_else(|| invalid("host registration not found".into()))?; + binding(&env, &stored.event)?; + } + Ok(()) +} + +/// Owner-transported, host-signed pulse. Registration is NOT a host login grant. +pub(super) async fn authorize_presence( + tenant: &TenantContext, + state: &AppState, + event: &Event, + owner: nostr::PublicKey, + channel_scoped: bool, +) -> Result<(), String> { + let pulse = buzz_core::run_presence::parse_run(event, nostr::Timestamp::now().as_secs())? + .ok_or("host presence requires a run")?; + let id = pulse + .registration + .as_deref() + .ok_or("host presence requires registration")?; + if channel_scoped || pulse.location.is_some() { + return Err("invalid host presence transport".into()); + } + let stored = state + .db + .get_event_by_id( + tenant.community(), + &hex::decode(id).map_err(|_| "invalid registration")?, + ) + .await + .map_err(|_| "host registration lookup failed")? + .ok_or("host registration not found")?; + let binding = host::validate(&stored.event)?; + if binding.label != "registration" || binding.owner != owner || binding.host != event.pubkey { + return Err("host presence registration mismatch".into()); + } + // The owner remains the authenticated principal. No host key admission, + // general EVENT, REQ or HTTP privileges are created by this exception. + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + use buzz_auth::Scope; + use nostr::Keys; + use uuid::Uuid; + + fn auth(keys: &Keys) -> IngestAuth { + IngestAuth::Nip42 { + pubkey: keys.public_key(), + scopes: vec![Scope::UsersWrite], + channel_ids: None, + conn_id: Uuid::new_v4(), + } + } + + #[test] + fn transport_and_registration_binding_fail_closed() { + let owner = Keys::generate(); + let host = Keys::generate(); + let other = Keys::generate(); + let reg = host::registration(&owner, host.public_key(), 100).unwrap(); + let rep = host::report( + &host, + ®, + &host::Report { + v: 1, + name: "test".into(), + os: "macos".into(), + arch: "aarch64".into(), + launcher_version: "test".into(), + runtimes: vec![], + accepts_start: false, + }, + 101, + ) + .unwrap(); + let owner_auth = auth(&owner); + for event in [®, &rep] { + assert!(envelope(event, &owner_auth, 101).is_ok()); + assert!(envelope(event, &auth(&other), 101).is_err()); + // Independent host connections are deliberately not enabled yet. + assert!(envelope(event, &auth(&host), 101).is_err()); + let mut scoped = owner_auth.clone(); + if let IngestAuth::Nip42 { channel_ids, .. } = &mut scoped { + *channel_ids = Some(vec![]); + } + assert!(envelope(event, &scoped, 101).is_err()); + assert!(envelope(event, &owner_auth, 0).is_err()); + } + assert!(envelope(&rep, &owner_auth, 280).is_ok()); + assert!(envelope(&rep, &owner_auth, 281).is_err()); + let env = envelope(&rep, &owner_auth, 101).unwrap(); + assert!(binding(&env, ®).is_ok()); + for wrong in [ + host::registration(&other, host.public_key(), 100).unwrap(), + host::registration(&owner, other.public_key(), 100).unwrap(), + host::registration(&owner, host.public_key(), 99).unwrap(), + rep.clone(), + ] { + assert!(binding(&env, &wrong).is_err()); + } + let mut tampered = rep; + tampered.content.push('A'); + assert!(envelope(&tampered, &owner_auth, 101).is_err()); + } +} diff --git a/crates/buzz-relay/src/handlers/ingest.rs b/crates/buzz-relay/src/handlers/ingest.rs index dd2fa6e93e..7c7c9e5fa3 100644 --- a/crates/buzz-relay/src/handlers/ingest.rs +++ b/crates/buzz-relay/src/handlers/ingest.rs @@ -436,7 +436,7 @@ fn map_push_accept_error(error: super::push_lease::AcceptError) -> IngestError { /// Returns `Err` for unknown kinds — the relay rejects them. fn required_scope_for_kind(kind: u32, event: &Event) -> Result { match kind { - KIND_PROFILE => Ok(Scope::UsersWrite), + KIND_PROFILE | buzz_core::kind::KIND_HOST => Ok(Scope::UsersWrite), KIND_TEXT_NOTE | KIND_LONG_FORM => Ok(Scope::MessagesWrite), KIND_CONTACT_LIST | KIND_READ_STATE | KIND_USER_STATUS | KIND_AGENT_ENGRAM | KIND_EVENT_REMINDER | KIND_PERSONA | KIND_TEAM | KIND_MANAGED_AGENT @@ -695,6 +695,7 @@ pub(crate) fn is_global_only_kind(kind: u32) -> bool { // NIP-AM: agent turn metrics are owner-scoped global events. // Channel identity is encrypted inside the payload — no `h` tag. | KIND_AGENT_TURN_METRIC + | buzz_core::kind::KIND_HOST // NIP-PL leases are author-owned, addressable global state. | super::push_lease::KIND_PUSH_LEASE ) @@ -2240,7 +2241,14 @@ async fn ingest_event_inner( } let is_gift_wrap = kind_u32 == KIND_GIFT_WRAP; - if event.pubkey != *auth.pubkey() && !is_gift_wrap { + // Only validated host events have this narrow transport exception. + let host_owner_transport = if kind_u32 == buzz_core::kind::KIND_HOST { + super::hosts::authorize(tenant, state, &event, &auth).await?; + true + } else { + false + }; + if event.pubkey != *auth.pubkey() && !is_gift_wrap && !host_owner_transport { return Err(IngestError::AuthFailed( "invalid: event pubkey does not match authenticated identity".into(), )); diff --git a/crates/buzz-relay/src/handlers/mod.rs b/crates/buzz-relay/src/handlers/mod.rs index d1c56a2b48..5ff67e3277 100644 --- a/crates/buzz-relay/src/handlers/mod.rs +++ b/crates/buzz-relay/src/handlers/mod.rs @@ -64,3 +64,8 @@ pub fn resolve_ttl(event: &nostr::Event, ephemeral_ttl_override: Option) -> (ttl, _) => ttl, } } + +/// Authoritative host history shared by WebSocket and HTTP reads. +pub(crate) mod history; +/// Private host registration authorization. +mod hosts; diff --git a/crates/buzz-relay/src/handlers/req.rs b/crates/buzz-relay/src/handlers/req.rs index d299cc045f..c291fde5f4 100644 --- a/crates/buzz-relay/src/handlers/req.rs +++ b/crates/buzz-relay/src/handlers/req.rs @@ -7,8 +7,8 @@ use tracing::{debug, warn}; use buzz_core::filter::filters_match; use buzz_core::kind::{ - is_unshared_gated_event, AUTHOR_ONLY_KINDS, KIND_AGENT_ENGRAM, KIND_AGENT_TURN_METRIC, - KIND_DM_VISIBILITY, P_GATED_KINDS, RESULT_GATED_KINDS, SHARED_GATED_KINDS, + is_unshared_gated_event, AUTHOR_ONLY_KINDS, KIND_AGENT_ENGRAM, P_GATED_KINDS, + RESULT_GATED_KINDS, SHARED_GATED_KINDS, }; use buzz_core::tenant::TenantContext; use buzz_db::EventQuery; @@ -246,6 +246,17 @@ pub async fn handle_req( // already ran, so an authed member cannot use search to bypass author/#p // rules for kind:30174 or other globally-stored gated kinds. let has_search = filters.iter().any(|f| f.search.is_some()); + if has_search + && filters + .iter() + .any(super::history::explicitly_requests_hosts) + { + conn.send(RelayMessage::closed( + &sub_id, + "error: host history search is unsupported", + )); + return; + } if has_search { if filters.iter().any(|f| f.search.is_none()) { conn.send(RelayMessage::closed( @@ -359,16 +370,19 @@ pub async fn handle_req( .collect(); // Phase 2 — DB reads, bounded-concurrent. `buffered` (not `buffer_unordered`) - // yields results in input order, so phase 3 observes filters in their - // original order and NIP-01 dedupe / conformance-trace / error semantics are - // byte-identical to the previous serial loop. + // yields results in input order, so phase 3 preserves NIP-01 dedupe and + // conformance-trace ordering. Host-capable query failures below explicitly + // close the entire history rather than reporting partial success. use futures_util::stream::{self, StreamExt}; let db = state.db.clone(); + let requires_primary = filters.iter().any(super::history::requires_primary); let mut results = stream::iter(filter_queries.into_iter().map( |(idx, per_filter_channel, params)| { let db = db.clone(); + let filter = &filters[idx]; async move { - let filter_events = db.query_events_routed("req_historical", ¶ms).await; + let filter_events = + super::history::query(&db, "req_historical", filter, params).await; (idx, per_filter_channel, filter_events) } }, @@ -382,7 +396,20 @@ pub async fn handle_req( Ok(evs) => evs, Err(e) => { warn!(conn_id = %conn_id, sub_id = %sub_id, "Historical query failed: {e}"); - conn.send(RelayMessage::eose(&sub_id)); + if requires_primary { + // CLOSED is failure, EOSE is successful completion. Remove + // the live subscription as well: no continuing fan-out on a + // read whose partial history the client must discard. + conn.subscriptions.lock().await.remove(&sub_id); + if let Some(removed) = state.sub_registry.remove_subscription(conn_id, &sub_id) + { + release_subscription_topics(&state, &conn.tenant, &removed.scope).await; + } + conn.send(RelayMessage::closed(&sub_id, e.wire_message())); + } else { + // Preserve legacy behavior for unrelated history reads. + conn.send(RelayMessage::eose(&sub_id)); + } return; } }; @@ -1202,7 +1229,7 @@ pub(crate) fn p_gated_filters_authorized(filters: &[Filter], authed_pubkey_hex: let explicitly_no_ids_exemption = filter.kinds.as_ref().is_some_and(|ks| { ks.iter().any(|kind| { let k = kind.as_u16() as u32; - k == KIND_DM_VISIBILITY || k == KIND_AGENT_TURN_METRIC + RESULT_GATED_KINDS.contains(&k) }) }); if !explicitly_no_ids_exemption && filter.ids.as_ref().is_some_and(|ids| !ids.is_empty()) { @@ -1877,6 +1904,55 @@ mod tests { assert!(filters.iter().any(|f| f.search.is_some())); } + #[test] + fn private_host_filters_and_known_id_counts_require_owner() { + let owner = nostr::Keys::generate(); + let other = nostr::Keys::generate(); + let host = nostr::Keys::generate(); + let event = buzz_core::host::registration(&owner, host.public_key(), 100).unwrap(); + let kind = nostr::Kind::Custom(buzz_core::kind::KIND_HOST as u16); + let p = SingleLetterTag::lowercase(Alphabet::P); + let owner_hex = owner.public_key().to_hex(); + let other_hex = other.public_key().to_hex(); + for filter in [ + Filter::new().kind(kind), + Filter::new().kind(kind).id(event.id), + Filter::new().kind(kind).custom_tags(p, [&owner_hex]), + Filter::new() + .kind(kind) + .custom_tags(p, [&owner_hex, &other_hex]), + Filter::new() + .kinds([kind, nostr::Kind::TextNote]) + .custom_tags(p, [&owner_hex]), + ] { + assert!(!p_gated_filters_authorized( + std::slice::from_ref(&filter), + &other_hex + )); + assert!(filter_can_match_result_gated_kinds(&filter)); + } + let own = Filter::new() + .kind(kind) + .id(event.id) + .custom_tags(p, [&owner_hex]); + assert!(p_gated_filters_authorized(&[own], &owner_hex)); + // A kindless ID query passes the filter gate, but must count/return no + // private rows to a foreign reader. Pin both sides of that composition. + let ids = Filter::new().id(event.id); + assert!(p_gated_filters_authorized( + std::slice::from_ref(&ids), + &other_hex + )); + assert!(filter_can_match_result_gated_kinds(&ids)); + assert!(!result_gated_count_safe_for_pushdown(&ids, &other_hex)); + assert!(!buzz_core::filter::reader_authorized_for_event( + &event, &other_hex + )); + assert!(buzz_core::filter::reader_authorized_for_event( + &event, &owner_hex + )); + } + #[test] fn dm_visibility_requires_p_tag_even_with_ids() { let p_tag = SingleLetterTag::lowercase(Alphabet::P); diff --git a/crates/buzz-relay/src/main.rs b/crates/buzz-relay/src/main.rs index d81602e201..f0b617da76 100644 --- a/crates/buzz-relay/src/main.rs +++ b/crates/buzz-relay/src/main.rs @@ -1,4 +1,5 @@ use std::collections::{HashMap, HashSet}; +use std::net::SocketAddr; use std::sync::atomic::Ordering; use std::sync::Arc; @@ -47,6 +48,13 @@ async fn connect_audit_pool(config: &DbConfig) -> anyhow::Result { .map_err(Into::into) } +// Health and metrics must honor the main listener's interface restriction. +// The default main address is 0.0.0.0, so default wildcard behavior is unchanged. +fn auxiliary_listener_addr(mut bind_addr: SocketAddr, port: u16) -> SocketAddr { + bind_addr.set_port(port); + bind_addr +} + fn relay_keypair_from_config(relay_private_key: Option<&str>) -> anyhow::Result { let hex = relay_private_key.ok_or_else(|| { anyhow::anyhow!( @@ -179,7 +187,10 @@ async fn main() -> anyhow::Result<()> { let usage_interval_secs = usage_metrics_interval_secs(); let usage_idle_timeout_secs = usage_metrics_idle_timeout_secs(usage_interval_secs); - relay_metrics::install(config.metrics_port, usage_idle_timeout_secs); + relay_metrics::install( + auxiliary_listener_addr(config.bind_addr, config.metrics_port), + usage_idle_timeout_secs, + ); metrics::gauge!("buzz_audit_enabled").set(if config.audit_enabled { 1.0 } else { 0.0 }); metrics::gauge!("buzz_push_enabled").set(if config.push_enabled { 1.0 } else { 0.0 }); info!( @@ -1303,9 +1314,12 @@ async fn serve( ) -> anyhow::Result<()> { let config = &state.config; - let health_listener = tokio::net::TcpListener::bind(("0.0.0.0", config.health_port)) - .await - .map_err(|e| anyhow::anyhow!("Failed to bind health port {}: {e}", config.health_port))?; + let health_listener = tokio::net::TcpListener::bind(auxiliary_listener_addr( + config.bind_addr, + config.health_port, + )) + .await + .map_err(|e| anyhow::anyhow!("Failed to bind health port {}: {e}", config.health_port))?; info!(port = config.health_port, "Health probe listener started"); tokio::spawn(async move { axum::serve(health_listener, health_router).await.ok(); @@ -2159,6 +2173,63 @@ mod tests { .expect("release audit advisory lock"); } + #[test] + fn auxiliary_listeners_preserve_main_interface_and_override_only_port() { + for main in [ + "127.0.0.1:53001", + "[::1]:53001", + "0.0.0.0:3000", + "[::]:3000", + "192.0.2.1:3000", + "[fe80::1%3]:3000", + ] { + let main: std::net::SocketAddr = main.parse().unwrap(); + for port in [58081, 59101] { + let actual = super::auxiliary_listener_addr(main, port); + assert_eq!(actual.ip(), main.ip()); + assert_eq!(actual.port(), port); + let mut restored = actual; + restored.set_port(main.port()); + assert_eq!(restored, main, "preserve IPv6 scope and flow information"); + } + } + } + + #[tokio::test] + async fn auxiliary_listener_binds_only_configured_loopback() { + for main in ["127.0.0.1:53001", "[::1]:53001"] { + let main: std::net::SocketAddr = main.parse().unwrap(); + let listener = tokio::net::TcpListener::bind(super::auxiliary_listener_addr(main, 0)) + .await + .unwrap(); + assert_eq!(listener.local_addr().unwrap().ip(), main.ip()); + assert_ne!(listener.local_addr().unwrap().port(), 0); + } + } + + // Keep the global recorder install in the binary test process, separate + // from library tests. This exercises the real exporter, not just addresses. + #[tokio::test] + async fn metrics_exporter_uses_configured_loopback_interface() { + let reservation = std::net::TcpListener::bind("[::1]:0").unwrap(); + let addr = reservation.local_addr().unwrap(); + // A hard-coded IPv4 wildcard exporter would collide with this socket. + let _ipv4_guard = std::net::TcpListener::bind(("127.0.0.1", addr.port())).unwrap(); + drop(reservation); + super::relay_metrics::install(addr, 600); + + let response = reqwest::Client::builder() + .no_proxy() + .timeout(Duration::from_secs(5)) + .build() + .unwrap() + .get(format!("http://{addr}/metrics")) + .send() + .await + .unwrap(); + assert_eq!(response.status(), reqwest::StatusCode::OK); + } + #[test] fn buzz_auto_migrate_is_opt_in() { assert!(!buzz_auto_migrate_enabled(None)); diff --git a/crates/buzz-relay/src/metrics.rs b/crates/buzz-relay/src/metrics.rs index 16e521a44e..2eb1407675 100644 --- a/crates/buzz-relay/src/metrics.rs +++ b/crates/buzz-relay/src/metrics.rs @@ -14,6 +14,7 @@ //! recorded by [`track_metrics`] middleware on the app router. Buzz-specific //! metrics are recorded inline at their call sites. +use std::net::SocketAddr; use std::time::{Duration, Instant}; use axum::{ @@ -61,11 +62,12 @@ const FANOUT_BUCKETS: [f64; 9] = [0.0, 1.0, 5.0, 10.0, 25.0, 50.0, 100.0, 500.0, /// `build()` returns the recorder + exporter future and internally spawns /// the upkeep task, so no separate upkeep call is needed. /// +/// Binds exactly `addr`, including its IP/interface restriction. /// Must be called from within a Tokio runtime. -/// Panics if a recorder is already installed or the port is in use. -pub fn install(port: u16, gauge_idle_timeout_secs: u64) { +/// Panics if a recorder is already installed or the address is unavailable. +pub fn install(addr: SocketAddr, gauge_idle_timeout_secs: u64) { let (recorder, exporter) = PrometheusBuilder::new() - .with_http_listener(([0, 0, 0, 0], port)) + .with_http_listener(addr) // Remove gauge series that the relay intentionally stops emitting. .idle_timeout( MetricKindMask::GAUGE, diff --git a/desktop/src-tauri/Cargo.lock b/desktop/src-tauri/Cargo.lock index 68b702431a..39531d9ad3 100644 --- a/desktop/src-tauri/Cargo.lock +++ b/desktop/src-tauri/Cargo.lock @@ -1107,6 +1107,7 @@ dependencies = [ "ed25519-dalek", "flate2", "futures-util", + "gethostname", "getrandom 0.2.17", "hex", "image", diff --git a/desktop/src-tauri/Cargo.toml b/desktop/src-tauri/Cargo.toml index f41fa2d6e3..aa3ab4f5fb 100644 --- a/desktop/src-tauri/Cargo.toml +++ b/desktop/src-tauri/Cargo.toml @@ -68,6 +68,7 @@ keyring = { version = "3.6.3", default-features = false, features = ["windows-na user-idle = { version = "0.6", default-features = false } [dependencies] +gethostname = "1.1.0" atomic-write-file = "0.3" anyhow = "1" dirs = "6" diff --git a/desktop/src-tauri/src/commands/host_execution.rs b/desktop/src-tauri/src/commands/host_execution.rs new file mode 100644 index 0000000000..5d5e77881e --- /dev/null +++ b/desktop/src-tauri/src/commands/host_execution.rs @@ -0,0 +1,150 @@ +//! Native executor entry point. Transport subscription/publication and the host +//! picker remain gated off; a relay ACK is never a launch result. No host-key-only +//! connection is created: every query uses the existing active owner authority. +use crate::{ + app_state::AppState, + managed_agents::{self, AcpAvailabilityStatus, AuthStatus}, +}; +use buzz_core_pkg::host_execution::{self, Action, Receipt}; +use nostr::{Event, JsonUtil, Timestamp}; +use tauri::{AppHandle, State}; + +/// Inspect the destination's own provisioned configuration. Only an opaque +/// revision and Rust catalog ID cross IPC; no key, env, path or OS hostname. +#[tauri::command] +pub async fn inspect_local_execution_config( + app: AppHandle, + state: State<'_, AppState>, + expected_owner: String, + expected_relay: String, + agent: String, +) -> Result { + super::hosts::owner_keys(&state, &expected_owner)?; + crate::relay::assert_expected_relay_scope( + Some(&expected_relay), + &crate::relay::relay_api_base_url_with_override(&state), + )?; + let result = tokio::task::spawn_blocking(move || { + let records = managed_agents::load_managed_agents(&app)?; + let record = records + .iter() + .find(|r| r.pubkey == agent) + .ok_or("agent is not provisioned on this executor")?; + serde_json::to_value(managed_agents::local_execution_config(&app, record)?) + .map_err(|_| "cannot serialize execution config".into()) + }) + .await + .map_err(|_| "execution config task failed")?; + super::hosts::owner_keys(&state, &expected_owner)?; + crate::relay::assert_expected_relay_scope( + Some(&expected_relay), + &crate::relay::relay_api_base_url_with_override(&state), + )?; + result +} + +/// Execute an owner-signed, destination-encrypted request using only this +/// Desktop's own approved configuration. Fresh registration lookup is mandatory +/// even on retry. An unreachable/deleted registration blocks work, not merely UI. +#[tauri::command] +pub async fn execute_host_command( + app: AppHandle, + state: State<'_, AppState>, + expected_owner: String, + expected_relay: String, + event: serde_json::Value, +) -> Result { + let owner = super::hosts::owner_keys(&state, &expected_owner)?; + let relay = buzz_core_pkg::relay::normalize_relay_url(&expected_relay) + .map_err(|_| "invalid execution relay")?; + crate::relay::assert_expected_relay_scope( + Some(&relay), + &crate::relay::relay_api_base_url_with_override(&state), + )?; + let event = Event::from_json(event.to_string()).map_err(|_| "invalid execution event")?; + buzz_core_pkg::verify_event(&event).map_err(|_| "invalid execution signature")?; + if event.pubkey != owner.public_key() + || event.kind.as_u16() as u32 != buzz_core_pkg::kind::KIND_HOST_COMMAND + { + return Err("foreign execution command".into()); + } + let registrations: Vec<_> = event + .tags + .iter() + .filter(|t| t.as_slice().first().is_some_and(|s| s == "e")) + .collect(); + let [registration_tag] = registrations.as_slice() else { + return Err("invalid execution registration reference".into()); + }; + let tag = registration_tag.as_slice(); + if tag.len() != 2 || !host_execution::hex_id(&tag[1], 64) { + return Err("invalid execution registration reference".into()); + } + let registration_id = tag[1].clone(); + // Discovery happens before the final authority read, not after a registration + // cached during a potentially long-running CLI probe. Diagnostics stay native. + let catalog = super::discover_acp_providers(app.clone(), Some(true)) + .await + .unwrap_or_default(); + let registrations = crate::relay::query_relay_at_with_keys(&state, + &crate::relay::relay_http_base_url(&relay), + &[serde_json::json!({"kinds": [50000], "ids": [registration_id], "#p": [expected_owner], "limit": 2})], + &owner, None).await.map_err(|_| "cannot revalidate execution registration")?; + let [registration] = registrations.as_slice() else { + return Err("execution registration is absent or revoked".into()); + }; + if registration.id.to_hex() != registration_id { + return Err("wrong execution registration returned".into()); + } + let host = super::hosts::host_keys(&owner)?; + let request = host_execution::decrypt_command( + &host, + registration, + &event, + &relay, + Timestamp::now().as_secs(), + )?; + let compatible_runtime = match &request.action { + Action::Start { runtime, .. } => catalog.iter().any(|entry| { + entry.id == *runtime + && entry.availability == AcpAvailabilityStatus::Available + && matches!( + entry.auth_status, + AuthStatus::LoggedIn | AuthStatus::NotApplicable + ) + }), + Action::Stop { .. } => true, + }; + // Bind the identity/relay again after the awaited query. The transition uses + // these exact checked inputs and rechecks while holding the runtime locks. + super::hosts::owner_keys(&state, &expected_owner)?; + crate::relay::assert_expected_relay_scope( + Some(&relay), + &crate::relay::relay_api_base_url_with_override(&state), + )?; + let registration = registration.clone(); + let result = tokio::task::spawn_blocking(move || { + let entry = managed_agents::execute_host_operation( + &app, + &expected_owner, + &event.id.to_hex(), + &request, + compatible_runtime, + )?; + let result = Receipt { + v: 1, + command: entry.command_id, + run: entry.request.run().into(), + request: entry.request, + outcome: entry.outcome, + observed_at: entry.observed_at, + }; + // Encrypted host-signed observation; no raw process error text escapes. + let event = + host_execution::receipt(&host, ®istration, &result, Timestamp::now().as_secs())?; + serde_json::to_value(event).map_err(|_| "cannot serialize execution receipt".into()) + }) + .await + .map_err(|_| "execution task failed; outcome unknown")?; + result +} diff --git a/desktop/src-tauri/src/commands/hosts.rs b/desktop/src-tauri/src/commands/hosts.rs new file mode 100644 index 0000000000..3f69a09246 --- /dev/null +++ b/desktop/src-tauri/src/commands/hosts.rs @@ -0,0 +1,452 @@ +//! Desktop self-registration. All keys remain in Rust/keychain, never IPC. +use buzz_core_pkg::host::{self, Report, Runtime}; +use nostr::{Event, JsonUtil, Keys, Timestamp}; +use serde::Serialize; +use tauri::State; + +use crate::app_state::AppState; +use crate::managed_agents::AuthStatus; + +#[derive(Serialize)] +pub struct LocalHost { + pub host: String, + pub report: Report, +} + +pub(super) fn owner_keys(state: &AppState, expected_owner: &str) -> Result { + let keys = state.signing_keys()?; + if keys.public_key().to_hex() != expected_owner { + return Err("Identity changed during host registration".into()); + } + Ok(keys) +} + +pub(super) fn host_keys(owner: &Keys) -> Result { + let store = crate::secret_store::SecretStore::shared(crate::app_state::keyring_service()); + let secret = store.host_key(&format!("host:v1:{}", owner.public_key().to_hex()))?; + Keys::parse(&secret).map_err(|e| format!("Invalid stored host key: {e}")) +} + +fn parse(value: serde_json::Value) -> Result { + Event::from_json(value.to_string()).map_err(|e| e.to_string()) +} + +fn value(event: Event) -> Result { + serde_json::to_value(event).map_err(|e| e.to_string()) +} + +fn catalog_string(value: T) -> Result { + serde_json::to_value(value) + .map_err(|e| e.to_string())? + .as_str() + .map(str::to_owned) + .ok_or_else(|| "Invalid runtime catalog status".into()) +} + +// AuthStatus is a tagged union, not a string enum. Never serialize its +// diagnostic: CLI errors may include credentials, paths, or configuration. +fn auth_status(value: &AuthStatus) -> &'static str { + match value { + AuthStatus::LoggedIn => "logged_in", + AuthStatus::LoggedOut => "logged_out", + AuthStatus::ConfigInvalid { .. } => "config_invalid", + AuthStatus::NotApplicable => "not_applicable", + AuthStatus::Unknown => "unknown", + } +} + +/// Real OS metadata and the existing runtime catalog, with a strict allowlist. +#[tauri::command] +pub async fn get_local_host( + app: tauri::AppHandle, + state: State<'_, AppState>, + expected_owner: String, +) -> Result { + let owner = owner_keys(&state, &expected_owner)?; + let catalog = super::discover_acp_providers(app, Some(false)).await?; + let result = tokio::task::spawn_blocking(move || { + let host = host_keys(&owner)?; + let mut runtimes = catalog + .into_iter() + .map(|r| { + Ok(Runtime { + id: r.id, + label: r.label, + availability: catalog_string(r.availability)?, + auth_status: auth_status(&r.auth_status).into(), + }) + }) + .collect::, String>>()?; + runtimes.sort_by(|a, b| a.id.cmp(&b.id)); + let report = Report { + v: 2, + name: gethostname::gethostname().to_string_lossy().into_owned(), + os: std::env::consts::OS.into(), + arch: std::env::consts::ARCH.into(), + launcher_version: env!("CARGO_PKG_VERSION").into(), + runtimes, + accepts_start: false, + }; + report.validate()?; + Ok(LocalHost { + host: host.public_key().to_hex(), + report, + }) + }) + .await + .map_err(|e| e.to_string())?; + owner_keys(&state, &expected_owner)?; + result +} + +/// Owner-signed binding for a persisted host key; caller first queries the relay. +#[tauri::command] +pub async fn create_host_registration( + state: State<'_, AppState>, + expected_owner: String, +) -> Result { + let owner = owner_keys(&state, &expected_owner)?; + let result = tokio::task::spawn_blocking(move || { + let host = host_keys(&owner)?; + value(host::registration( + &owner, + host.public_key(), + Timestamp::now().as_secs(), + )?) + }) + .await + .map_err(|e| e.to_string())?; + owner_keys(&state, &expected_owner)?; + result +} + +/// Produce a report from native discovery, not caller-provided machine metadata. +#[tauri::command] +pub async fn create_host_report( + app: tauri::AppHandle, + state: State<'_, AppState>, + expected_owner: String, + registration: serde_json::Value, +) -> Result { + let local = get_local_host(app, state.clone(), expected_owner.clone()).await?; + let owner = owner_keys(&state, &expected_owner)?; + let result = tokio::task::spawn_blocking(move || { + let reg = parse(registration)?; + if host::validate(®)?.owner != owner.public_key() { + return Err("Foreign host registration".into()); + } + value(host::profile( + &host_keys(&owner)?, + ®, + &local.report, + Timestamp::now().as_secs(), + )?) + }) + .await + .map_err(|e| e.to_string())?; + owner_keys(&state, &expected_owner)?; + result +} + +/// Verify a registration before displaying it or using it to suppress a write. +#[tauri::command] +pub async fn inspect_host_registration( + state: State<'_, AppState>, + expected_owner: String, + registration: serde_json::Value, +) -> Result { + let owner = owner_keys(&state, &expected_owner)?; + let reg = parse(registration)?; + let env = host::validate(®)?; + if env.label != "registration" || env.owner != owner.public_key() { + return Err("Foreign host registration".into()); + } + let text = nostr::nips::nip44::decrypt(owner.secret_key(), &owner.public_key(), ®.content) + .map_err(|e| e.to_string())?; + let body: serde_json::Value = serde_json::from_str(&text).map_err(|e| e.to_string())?; + if body != serde_json::json!({"v": 1}) { + return Err("Unknown host registration version".into()); + } + Ok(env.host.to_hex()) +} + +/// Verify signatures and owner/host binding before decrypting an incoming report. +#[tauri::command] +pub async fn decode_host_report( + state: State<'_, AppState>, + expected_owner: String, + registration: serde_json::Value, + report: serde_json::Value, +) -> Result { + let owner = owner_keys(&state, &expected_owner)?; + host::decrypt_report(&owner, &parse(registration)?, &parse(report)?) +} + +/// Sign a liveness pulse without exporting keys or tying it to human idle state. +#[tauri::command] +pub async fn create_host_presence( + state: State<'_, AppState>, + expected_owner: String, + registration: serde_json::Value, + run: String, + seq: u64, + status: String, +) -> Result { + let owner = owner_keys(&state, &expected_owner)?; + let result = tokio::task::spawn_blocking(move || { + let host = host_keys(&owner)?; + let reg = parse(registration)?; + let binding = host::validate(®)?; + if binding.label != "registration" + || binding.owner != owner.public_key() + || binding.host != host.public_key() + { + return Err("Foreign host registration".into()); + } + value(buzz_core_pkg::run_presence::pulse( + &host, + &run, + seq, + &status, + None, + Some(®.id.to_hex()), + Timestamp::now().as_secs(), + )?) + }) + .await + .map_err(|e| e.to_string())?; + owner_keys(&state, &expected_owner)?; + result +} + +/// Public location for local launches. Never export the private OS name by default. +pub(crate) fn local_launch_location( + owner_hex: &str, +) -> Result { + let store = crate::secret_store::SecretStore::shared(crate::app_state::keyring_service()); + let secret = store.host_key(&format!("host:v1:{owner_hex}"))?; + let host = Keys::parse(&secret) + .map_err(|e| e.to_string())? + .public_key() + .to_hex(); + Ok(buzz_core_pkg::run_presence::Location { + label: format!("Desktop {}", &host[..8]), + host, + }) +} + +/// Detailed presence snapshot. Missing protocol support and query errors stay unknown. +#[tauri::command] +pub async fn get_presence_runs( + state: State<'_, AppState>, + expected_owner: String, + relay_url: String, + pubkeys: Vec, +) -> Result>, String> +{ + let owner = owner_keys(&state, &expected_owner)?; + if pubkeys.len() > 256 { + return Err("Too many presence subjects".into()); + } + if pubkeys.is_empty() { + return Ok(Default::default()); + } + let relay_self = super::identity_archive::fetch_relay_self_at(&state, &relay_url) + .await? + .ok_or("Relay did not advertise a presence snapshot signer")?; + let events = crate::relay::query_relay_at_with_keys( + &state, + &crate::relay::relay_http_base_url(&relay_url), + &[serde_json::json!({ "kinds": [40902], "authors": pubkeys })], + &owner, + None, + ) + .await?; + owner_keys(&state, &expected_owner)?; + decode_presence_snapshot(events, &pubkeys, &relay_self, Timestamp::now().as_secs()) +} + +fn decode_presence_snapshot( + events: Vec, + pubkeys: &[String], + relay_self: &str, + now: u64, +) -> Result>, String> +{ + let mut result = std::collections::HashMap::new(); + for event in events { + buzz_core_pkg::verify_event(&event).map_err(|e| e.to_string())?; + if event.kind.as_u16() != 20001 || event.pubkey.to_hex() != relay_self { + return Err("Invalid presence snapshot authority".into()); + } + let subject = event + .tags + .iter() + .find_map(|t| { + let t = t.as_slice(); + (t.len() == 2 && t[0] == "p").then(|| t[1].clone()) + }) + .ok_or("Missing presence subject")?; + if !pubkeys.contains(&subject) { + return Err("Unexpected presence subject".into()); + } + let payload = event + .tags + .iter() + .find_map(|t| { + let t = t.as_slice(); + (t.len() == 3 && t[0] == "presence_runs" && t[1] == "1").then(|| t[2].clone()) + }) + .ok_or("Relay does not support live host locations")?; + let runs: Vec = + serde_json::from_str(&payload).map_err(|e| e.to_string())?; + validate_snapshot_runs(&runs, now)?; + if result.insert(subject, runs).is_some() { + return Err("Duplicate presence snapshot subject".into()); + } + } + if result.len() + != pubkeys + .iter() + .collect::>() + .len() + { + return Err("Incomplete presence snapshot".into()); + } + Ok(result) +} + +fn validate_snapshot_runs( + runs: &[buzz_core_pkg::run_presence::RunPresence], + now: u64, +) -> Result<(), String> { + let mut ids = std::collections::HashSet::new(); + if runs.len() > 32 { + return Err("Invalid presence snapshot".into()); + } + for run in runs { + if run.run.len() != 32 + || !run + .run + .bytes() + .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b)) + || !ids.insert(&run.run) + || run.seq > 9_007_199_254_740_991 + || !matches!(run.status.as_str(), "online" | "away") + || run.expires_at > now.saturating_add(buzz_core_pkg::run_presence::LEASE_SECONDS) + { + return Err("Invalid presence run".into()); + } + if let Some(location) = &run.location { + location.validate()?; + } + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::managed_agents::AcpAvailabilityStatus; + + #[test] + fn snapshots_require_the_selected_relays_signature_and_complete_subjects() { + let relay = Keys::generate(); + let impostor = Keys::generate(); + let subject = Keys::generate().public_key().to_hex(); + let snapshot = |signer: &Keys| { + nostr::EventBuilder::new(nostr::Kind::Custom(20001), "offline") + .tags([ + nostr::Tag::parse(["p", subject.as_str()]).unwrap(), + nostr::Tag::parse(["presence_runs", "1", "[]"]).unwrap(), + ]) + .sign_with_keys(signer) + .unwrap() + }; + let subjects = vec![subject.clone()]; + let signer = relay.public_key().to_hex(); + let good = snapshot(&relay); + assert!(decode_presence_snapshot(vec![good.clone()], &subjects, &signer, 100).is_ok()); + assert!( + decode_presence_snapshot(vec![snapshot(&impostor)], &subjects, &signer, 100).is_err() + ); + assert!(decode_presence_snapshot(vec![], &subjects, &signer, 100).is_err()); + assert!( + decode_presence_snapshot(vec![good.clone(), good], &subjects, &signer, 100).is_err() + ); + } + + #[test] + fn every_auth_status_projects_without_diagnostics() { + let sensitive = "/private/credentials TOKEN=do-not-publish"; + for (status, expected) in [ + (AuthStatus::LoggedIn, "logged_in"), + (AuthStatus::LoggedOut, "logged_out"), + ( + AuthStatus::ConfigInvalid { + diagnostic: sensitive.into(), + }, + "config_invalid", + ), + (AuthStatus::NotApplicable, "not_applicable"), + (AuthStatus::Unknown, "unknown"), + ] { + // Pin the projection to the real native tagged-union contract. + assert_eq!(serde_json::to_value(&status).unwrap()["status"], expected); + let runtime = Runtime { + id: "test-runtime".into(), + label: "Test runtime".into(), + availability: catalog_string(AcpAvailabilityStatus::Available).unwrap(), + auth_status: auth_status(&status).into(), + }; + let serialized = serde_json::to_value(runtime).unwrap(); + assert_eq!(serialized["auth_status"], expected); + assert_eq!(serialized.as_object().unwrap().len(), 4); + assert!(!serialized.to_string().contains(sensitive)); + assert!(!serialized.to_string().contains("diagnostic")); + } + } + + #[test] + fn every_availability_is_a_string_enum() { + for (status, expected) in [ + (AcpAvailabilityStatus::Available, "available"), + (AcpAvailabilityStatus::AdapterMissing, "adapter_missing"), + (AcpAvailabilityStatus::AdapterOutdated, "adapter_outdated"), + (AcpAvailabilityStatus::CliMissing, "cli_missing"), + (AcpAvailabilityStatus::NotInstalled, "not_installed"), + ] { + assert_eq!(catalog_string(status).unwrap(), expected); + } + } +} + +/// Read one exact owner-private inventory page on the selected relay. The HTTP +/// bridge preserves the timestamp + event-ID cursor (ordinary WS REQ does not). +#[tauri::command] +pub async fn get_host_history_page( + state: State<'_, AppState>, + expected_owner: String, + relay_url: String, + filter: serde_json::Value, +) -> Result, String> { + let owner = owner_keys(&state, &expected_owner)?; + if filter.get("kinds") != Some(&serde_json::json!([50000])) + || filter.get("#p") != Some(&serde_json::json!([expected_owner])) + || filter.get("#L") != Some(&serde_json::json!(["buzz.host.v1"])) + || filter.get("limit") != Some(&serde_json::json!(1000)) + { + return Err("Invalid host history scope".into()); + } + let events = crate::relay::query_relay_at_with_keys( + &state, + &crate::relay::relay_http_base_url(&relay_url), + &[filter], + &owner, + None, + ) + .await + .map_err(|_| "Host history query failed".to_string())?; + owner_keys(&state, &expected_owner)?; + Ok(events) +} diff --git a/desktop/src-tauri/src/commands/mod.rs b/desktop/src-tauri/src/commands/mod.rs index 7cb2d8e3b8..e1058cef88 100644 --- a/desktop/src-tauri/src/commands/mod.rs +++ b/desktop/src-tauri/src/commands/mod.rs @@ -21,6 +21,8 @@ mod dms; mod engrams; mod export_util; mod global_agent_config; +mod host_execution; +mod hosts; mod identity; mod identity_archive; mod join_policy; @@ -90,6 +92,8 @@ pub use clipboard::*; pub use dms::*; pub use engrams::*; pub use global_agent_config::*; +pub use host_execution::*; +pub use hosts::*; pub use identity::*; pub use identity_archive::*; pub use join_policy::*; diff --git a/desktop/src-tauri/src/commands/profile.rs b/desktop/src-tauri/src/commands/profile.rs index ef67fac570..3dfa7fe696 100644 --- a/desktop/src-tauri/src/commands/profile.rs +++ b/desktop/src-tauri/src/commands/profile.rs @@ -353,8 +353,7 @@ pub async fn get_presence( "authors": pubkeys, })], ) - .await - .unwrap_or_default(); + .await?; let mut latest: HashMap = HashMap::new(); for ev in &events { diff --git a/desktop/src-tauri/src/lib.rs b/desktop/src-tauri/src/lib.rs index 2dde312d77..8503fdefe5 100644 --- a/desktop/src-tauri/src/lib.rs +++ b/desktop/src-tauri/src/lib.rs @@ -611,6 +611,14 @@ pub fn run() { build_observer_control_event, create_auth_event, nip44_encrypt_to_self, + get_local_host, + get_host_history_page, + create_host_registration, + create_host_report, + create_host_presence, + get_presence_runs, + inspect_host_registration, + decode_host_report, nip44_decrypt_from_self, get_channels, get_open_channel_directory, @@ -689,6 +697,8 @@ pub fn run() { list_managed_agent_runtimes, start_managed_agent_runtime, stop_managed_agent_runtime, + commands::execute_host_command, + commands::inspect_local_execution_config, restart_managed_agent_runtime, reconcile_managed_agent_runtimes, put_managed_agent_runtime_lifecycle, diff --git a/desktop/src-tauri/src/managed_agents/execution.rs b/desktop/src-tauri/src/managed_agents/execution.rs new file mode 100644 index 0000000000..ee6d96a83c --- /dev/null +++ b/desktop/src-tauri/src/managed_agents/execution.rs @@ -0,0 +1,270 @@ +//! Native transition seam for authenticated host commands. The relay receiver/UI +//! is deliberately not enabled yet. Only destination-local provisioned configs +//! are supported: no source workspace, environment, loopback endpoint or key copy. +use buzz_core_pkg::host_execution::{Action, Command, Outcome}; +use serde::Serialize; +use sha2::{Digest, Sha256}; +use tauri::{AppHandle, Manager}; + +use super::{ + execution_ledger::{Begin, Entry, Ledger}, + *, +}; + +#[derive(Serialize)] +pub(crate) struct LocalExecutionConfig { + pub runtime: String, + pub revision: String, +} + +pub(super) fn config_revision( + record: &ManagedAgentRecord, + personas: &[AgentDefinition], + global: &GlobalAgentConfig, + teams: &[TeamRecord], + descriptor: &super::readiness::EffectiveHarnessDescriptor, +) -> Result { + // Hash in memory; never persist/return these secret-bearing input bytes. + let bytes = serde_json::to_vec(&( + env!("CARGO_PKG_VERSION"), + record, + personas, + global, + teams, + &descriptor.command, + &descriptor.args, + &descriptor.env, + )) + .map_err(|_| "cannot fingerprint destination config")?; + Ok(hex::encode(Sha256::digest(bytes))) +} + +pub(crate) fn local_execution_config( + app: &AppHandle, + record: &ManagedAgentRecord, +) -> Result { + if record.backend != BackendKind::Local { + return Err("destination agent is not locally provisioned".into()); + } + let personas = load_personas(app)?; + let teams = load_teams(app)?; + let global = load_global_agent_config(app)?; + let descriptor = resolve_effective_harness_descriptor(record, &personas, &global)?; + let runtime = known_acp_runtime(&descriptor.command) + .ok_or("destination runtime is not in the Rust catalog")?; + let effective = effective_config::resolve_effective_config(record, &personas, &global) + .require_resolved()?; + // Destination-local mesh preflight needs its own readiness gate. Do not + // mistake a source machine's loopback endpoint for a portable provider. + if effective.relay_mesh_model_id().is_some() { + return Err("host command mesh preflight is not supported yet".into()); + } + if !matches!( + agent_readiness(&resolve_effective_agent_env( + record, + &personas, + Some(runtime), + &global + )), + AgentReadiness::Ready + ) { + return Err("destination agent configuration is not ready".into()); + } + Ok(LocalExecutionConfig { + runtime: runtime.id.into(), + revision: config_revision(record, &personas, &global, &teams, &descriptor)?, + }) +} + +fn ledger(app: &AppHandle, key: &ManagedAgentRuntimeKey, owner: &str) -> Result { + if !buzz_core_pkg::host_execution::hex_id(owner, 64) { + return Err("invalid execution owner".into()); + } + Ledger::open( + &managed_agents_base_dir(app)?.join("execution-ledger"), + &format!("{owner}__{}", key.runtime_id()), + ) +} + +pub(super) fn legacy_spawn_guard( + app: &AppHandle, + record: &ManagedAgentRecord, + relay: &str, + owner: Option<&str>, +) -> Result { + let owner = owner.ok_or("managed launch requires an owner")?; + let key = ManagedAgentRuntimeKey::new(&record.pubkey, relay)?; + let ledger = ledger(app, &key, owner)?; + if ledger.is_fenced() { + return Err( + "placement is controlled by a durable execution operation; explicit Start required" + .into(), + ); + } + Ok(ledger) +} + +/// Called only after signature, live registration, destination and runtime +/// compatibility checks. Caller retains owner authority, never a host-only login. +pub(crate) fn execute_host_operation( + app: &AppHandle, + owner: &str, + command_id: &str, + request: &Command, + compatible_runtime: bool, +) -> Result { + let state = app.state::(); + let _transition = state + .managed_agent_runtime_transition + .lock() + .map_err(|_| "runtime transition lock unavailable")?; + let _store = state + .managed_agents_store_lock + .lock() + .map_err(|_| "agent store lock unavailable")?; + if state + .shutdown_started + .load(std::sync::atomic::Ordering::Acquire) + { + return Err("desktop is shutting down".into()); + } + crate::relay::assert_expected_signer( + Some(owner), + &state.signing_keys()?.public_key().to_hex(), + )?; + crate::relay::assert_expected_relay_scope( + Some(&request.relay), + &crate::relay::relay_api_base_url_with_override(&state), + )?; + if request.expires_at <= nostr::Timestamp::now().as_secs() { + return Err("execution command expired".into()); + } + let key = ManagedAgentRuntimeKey::new(&request.agent, &request.relay)?; + let mut ledger = ledger(app, &key, owner)?; + // Retry is resolved before inspecting current config/process state. Config + // drift after success must not turn an ACK-loss retry into another launch. + if let Some(entry) = ledger.replay(command_id, request)? { + return Ok(entry); + } + let mut records = load_managed_agents(app)?; + let record = find_managed_agent_mut(&mut records, &request.agent)?; + let mut runtimes = state + .managed_agent_processes + .lock() + .map_err(|_| "runtime lock unavailable")?; + if let Action::Stop { run } = &request.action { + // Validate before persisting a new Stop fence. A stale clicked run must + // neither kill nor take ownership of a newer local placement. + let selected = runtimes + .get(&key) + .ok_or("selected run is not tracked; stop outcome unknown")?; + if !exact_generation_matches(&selected.start_nonce, run) { + return Err("selected generation is no longer current".into()); + } + } + if let Begin::Replay(entry) = ledger.begin(command_id, request)? { + return Ok(entry); + } + match &request.action { + Action::Start { runtime, revision } => { + // No adoption or teardown of a peer, even one whose root has exited. + // A legacy receipt (including corrupt data) is an unresolved conflict. + let receipt_path = managed_agents_base_dir(app)? + .join("agent-pids") + .join(format!("{}.json", key.runtime_id())); + let preflight = local_execution_config(app, record); + let compatible = preflight + .is_ok_and(|config| config.runtime == *runtime && config.revision == *revision); + if !compatible_runtime + || !compatible + || runtimes.contains_key(&key) + || receipt_path + .try_exists() + .map_err(|_| "cannot inspect prior receipt")? + { + return ledger.finish(&request.operation, Outcome::Rejected); + } + let process = match super::runtime::spawn_agent_child_for_run( + app, + record, + &key.relay_url, + false, + Some(owner), + Some((&request.operation, revision)), + ) { + Ok(process) => process, + Err(_) => return ledger.finish(&request.operation, Outcome::Rejected), + }; + let now = crate::util::now_iso(); + let receipt = ManagedAgentRuntimeReceipt { + key: key.clone(), + pid: process.child.id(), + desktop_instance_id: current_instance_id(app), + started_at: now.clone(), + run_id: Some(process.start_nonce.clone()), + }; + if write_agent_runtime_receipt(app, &receipt).is_err() { + // Preserve a possibly surviving child in memory, even if durable + // observation failed. Never report definite failure after spawn. + runtimes.insert(key, ManagedAgentPairRuntime::starting(process)); + return ledger.finish(&request.operation, Outcome::Unknown); + } + // Process observation only: not Ready, not online, not an LLM turn. + record.updated_at = now.clone(); + record.last_started_at = Some(now); + record.last_stopped_at = None; + record.last_error = None; + record.runtime_pid = None; + runtimes.insert(key, ManagedAgentPairRuntime::starting(process)); + if save_managed_agents(app, &records).is_err() { + return ledger.finish(&request.operation, Outcome::Unknown); + } + ledger.finish(&request.operation, Outcome::Spawned) + } + Action::Stop { run } => { + let Some(runtime) = runtimes.get_mut(&key) else { + // Absence, legacy PID receipts and presence expiry are not proof. + return ledger.finish(&request.operation, Outcome::Unknown); + }; + if !exact_generation_matches(&runtime.start_nonce, run) { + // A delayed selected-run Stop must not kill this newer peer. + return ledger.finish(&request.operation, Outcome::Unknown); + } + if super::runtime::terminate_exact_owned_group(&mut runtime.child).is_err() { + return ledger.finish(&request.operation, Outcome::Unknown); + } + // ACP/agent/MCP children can own separate process groups. Root/group + // exit is real evidence, but NOT a full execution teardown certificate. + // Keep the placement fenced until stronger containment/reconciliation + // can prove Stopped; no Move or replacement may use this observation. + let result = ledger.finish(&request.operation, Outcome::RootExited)?; + runtimes.remove(&key); + remove_agent_runtime_receipt(app, &key); + state.clear_agent_session_cache(&key); + record.runtime_pid = None; + record.updated_at = crate::util::now_iso(); + record.last_stopped_at = Some(record.updated_at.clone()); + save_managed_agents(app, &records)?; + Ok(result) + } + } +} + +fn exact_generation_matches(actual: &str, expected: &str) -> bool { + buzz_core_pkg::host_execution::hex_id(expected, 32) && actual == expected +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn stop_fences_successor_and_malformed_or_legacy_generation() { + assert!(exact_generation_matches(&"aa".repeat(16), &"aa".repeat(16))); + assert!(!exact_generation_matches( + &"aa".repeat(16), + &"bb".repeat(16) + )); + assert!(!exact_generation_matches("", "")); + assert!(!exact_generation_matches("legacy", "legacy")); + } +} diff --git a/desktop/src-tauri/src/managed_agents/execution_ledger.rs b/desktop/src-tauri/src/managed_agents/execution_ledger.rs new file mode 100644 index 0000000000..4009989029 --- /dev/null +++ b/desktop/src-tauri/src/managed_agents/execution_ledger.rs @@ -0,0 +1,328 @@ +//! Secret-free, durable per-placement execution journal. Callers authenticate and +//! revalidate authorization BEFORE opening it. No replay ever repeats a side +//! effect, including after a crash in the intent→spawn/stop window. +use std::{ + collections::BTreeMap, + fs::{self, File, OpenOptions}, + path::{Path, PathBuf}, +}; + +use buzz_core_pkg::host_execution::{hex_id, Action, Command, Outcome}; +use serde::{Deserialize, Serialize}; + +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] +#[serde(deny_unknown_fields)] +pub(crate) struct Entry { + pub command_id: String, + pub request: Command, + pub outcome: Outcome, + pub observed_at: u64, +} + +#[derive(Default, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +struct Journal { + entries: BTreeMap, + // A placement stays fenced even after a confirmed Stop. Only a new explicit + // durable Start may release it; config edits/auto-reconcile may not resurrect. + current: Option, +} + +pub(crate) enum Begin { + Execute, + Replay(Entry), +} + +/// An OS file lock also serializes two controller processes sharing one store. +/// Never unlink the lock file: doing so would permit locks on different inodes. +pub(crate) struct Ledger { + _lock: File, + path: PathBuf, + journal: Journal, +} + +impl Ledger { + pub(crate) fn open(directory: &Path, placement: &str) -> Result { + if placement.is_empty() + || !placement + .bytes() + .all(|b| b.is_ascii_alphanumeric() || b == b'_') + { + return Err("invalid execution placement".into()); + } + fs::create_dir_all(directory).map_err(|_| "execution journal unavailable")?; + let mut options = OpenOptions::new(); + options.read(true).write(true).create(true).truncate(false); + #[cfg(unix)] + { + use std::os::unix::fs::OpenOptionsExt; + options.mode(0o600); + } + let lock = options + .open(directory.join(format!("{placement}.lock"))) + .map_err(|_| "execution lock unavailable")?; + lock.try_lock().map_err(|_| "execution placement busy")?; + let path = directory.join(format!("{placement}.json")); + let journal: Journal = match fs::read(&path) { + Ok(bytes) => serde_json::from_slice(&bytes).map_err(|_| "execution journal corrupt")?, + Err(e) if e.kind() == std::io::ErrorKind::NotFound => Journal::default(), + Err(_) => return Err("execution journal unreadable".into()), + }; + if journal.entries.len() > 4096 + || journal + .current + .as_ref() + .is_some_and(|id| !journal.entries.contains_key(id)) + || (journal.current.is_none() && !journal.entries.is_empty()) + || journal.entries.iter().any(|(id, entry)| { + id != &entry.request.operation + || !hex_id(&entry.command_id, 64) + || entry.request.validate().is_err() + }) + { + return Err("execution journal invariants invalid".into()); + } + Ok(Self { + _lock: lock, + path, + journal, + }) + } + + fn save(&self) -> Result<(), String> { + let bytes = serde_json::to_vec(&self.journal) + .map_err(|_| "execution journal serialization failed")?; + super::atomic_write_json_restricted(&self.path, &bytes) + .map_err(|_| "execution journal write failed")?; + // Atomic rename is not a durable intent unless directory metadata is + // synced too. On unsupported filesystems fail before a side effect. + #[cfg(unix)] + { + let parent = self.path.parent().ok_or("invalid journal directory")?; + File::open(parent) + .and_then(|dir| dir.sync_all()) + .map_err(|_| "execution journal sync failed")?; + } + Ok(()) + } + + pub(crate) fn replay( + &self, + command_id: &str, + request: &Command, + ) -> Result, String> { + if let Some(entry) = self.journal.entries.get(&request.operation) { + if entry.command_id != command_id || entry.request != *request { + return Err("operation ID already belongs to another command".into()); + } + // Accepted is deliberately not resumed: creation/termination could + // have happened before the result write. Reconciliation must prove + // the old generation, not manufacture a replacement. + let mut result = entry.clone(); + if result.outcome == Outcome::Accepted { + result.outcome = Outcome::Unknown; + } + return Ok(Some(result)); + } + Ok(None) + } + + pub(crate) fn begin(&mut self, command_id: &str, request: &Command) -> Result { + request.validate()?; + if !hex_id(command_id, 64) { + return Err("invalid execution command ID".into()); + } + if let Some(entry) = self.replay(command_id, request)? { + return Ok(Begin::Replay(entry)); + } + if self.journal.entries.len() >= 4096 { + return Err("execution journal requires archival".into()); + } + if let Some(current) = self + .journal + .current + .as_ref() + .and_then(|id| self.journal.entries.get(id)) + { + if request.agent != current.request.agent || request.relay != current.request.relay { + return Err("execution placement binding mismatch".into()); + } + match &request.action { + Action::Start { .. } + if current.outcome != Outcome::Stopped + && current.outcome != Outcome::Rejected => + { + return Err("previous execution is not proven stopped".into()); + } + Action::Stop { run } if run != current.request.run() => { + return Err("stop generation does not match placement fence".into()); + } + _ => {} + } + } + self.journal.entries.insert( + request.operation.clone(), + Entry { + command_id: command_id.into(), + request: request.clone(), + outcome: Outcome::Accepted, + observed_at: nostr::Timestamp::now().as_secs(), + }, + ); + self.journal.current = Some(request.operation.clone()); + self.save()?; + Ok(Begin::Execute) + } + + pub(crate) fn finish(&mut self, operation: &str, outcome: Outcome) -> Result { + if self.journal.current.as_deref() != Some(operation) { + return Err("stale execution result".into()); + } + let entry = self + .journal + .entries + .get_mut(operation) + .ok_or("unknown execution operation")?; + // A terminal state cannot be overwritten by a late asynchronous result. + if matches!(entry.outcome, Outcome::Stopped | Outcome::Rejected) && entry.outcome != outcome + { + return Err("execution result is terminal".into()); + } + if outcome == Outcome::Rejected && entry.outcome != Outcome::Accepted { + return Err("cannot reject after a possible side effect".into()); + } + let allowed = match entry.request.action { + Action::Start { .. } => matches!( + outcome, + Outcome::Spawned + | Outcome::Listening + | Outcome::Ready + | Outcome::Rejected + | Outcome::Unknown + ), + Action::Stop { .. } => matches!( + outcome, + Outcome::RootExited | Outcome::Stopped | Outcome::Unknown + ), + }; + if !allowed { + return Err("invalid execution transition".into()); + } + entry.outcome = outcome; + entry.observed_at = nostr::Timestamp::now().as_secs(); + let result = entry.clone(); + self.save()?; + Ok(result) + } + + /// All legacy/config-driven starts must fail while a durable placement fence + /// exists. The owning durable Start holds this lock through launch instead. + pub(crate) fn is_fenced(&self) -> bool { + self.journal.current.is_some() + } +} + +#[cfg(test)] +mod tests { + use super::*; + fn request(operation: &str, action: Action) -> Command { + Command { + v: 1, + operation: operation.repeat(16), + relay: "wss://relay.example".into(), + agent: nostr::Keys::generate().public_key().to_hex(), + expires_at: 200, + action, + } + } + fn start() -> Command { + request( + "aa", + Action::Start { + runtime: "goose".into(), + revision: "bb".repeat(32), + }, + ) + } + #[test] + fn crash_and_ack_loss_never_repeat_start() { + let dir = tempfile::tempdir().unwrap(); + let req = start(); + let id = "cc".repeat(32); + { + let mut ledger = Ledger::open(dir.path(), "placement").unwrap(); + assert!(matches!(ledger.begin(&id, &req).unwrap(), Begin::Execute)); + assert!(Ledger::open(dir.path(), "placement").is_err()); + } + let mut ledger = Ledger::open(dir.path(), "placement").unwrap(); + assert!(matches!( + ledger.begin(&id, &req).unwrap(), + Begin::Replay(Entry { + outcome: Outcome::Unknown, + .. + }) + )); + let mut replacement = req.clone(); + replacement.operation = "dd".repeat(16); + assert!(ledger.begin(&"ee".repeat(32), &replacement).is_err()); + assert!(ledger.begin(&"ff".repeat(32), &req).is_err()); + ledger.finish(&req.operation, Outcome::Spawned).unwrap(); + assert!(matches!( + ledger.begin(&id, &req).unwrap(), + Begin::Replay(Entry { + outcome: Outcome::Spawned, + .. + }) + )); + } + #[test] + fn only_exact_confirmed_stop_allows_replacement_and_late_results_are_fenced() { + let dir = tempfile::tempdir().unwrap(); + let req = start(); + let mut ledger = Ledger::open(dir.path(), "placement").unwrap(); + ledger.begin(&"cc".repeat(32), &req).unwrap(); + ledger.finish(&req.operation, Outcome::Spawned).unwrap(); + let mut stop = req.clone(); + stop.operation = "dd".repeat(16); + stop.action = Action::Stop { + run: "ee".repeat(16), + }; + assert!(ledger.begin(&"ff".repeat(32), &stop).is_err()); + stop.action = Action::Stop { + run: req.operation.clone(), + }; + ledger.begin(&"ff".repeat(32), &stop).unwrap(); + ledger.finish(&stop.operation, Outcome::Unknown).unwrap(); + let mut next = req.clone(); + next.operation = "12".repeat(16); + assert!(ledger.begin(&"34".repeat(32), &next).is_err()); + ledger.finish(&stop.operation, Outcome::RootExited).unwrap(); + assert!( + ledger.begin(&"34".repeat(32), &next).is_err(), + "root exit is not a stop certificate" + ); + ledger.finish(&stop.operation, Outcome::Stopped).unwrap(); + assert!(ledger.is_fenced()); + ledger.begin(&"34".repeat(32), &next).unwrap(); + assert!(ledger.finish(&stop.operation, Outcome::Unknown).is_err()); + assert!(ledger.finish(&req.operation, Outcome::Ready).is_err()); + } + #[test] + fn corruption_and_traversal_fail_closed_and_ledger_contains_no_payload_secrets() { + let dir = tempfile::tempdir().unwrap(); + assert!(Ledger::open(dir.path(), "../escape").is_err()); + fs::write(dir.path().join("placement.json"), b"{").unwrap(); + assert!(Ledger::open(dir.path(), "placement").is_err()); + fs::write( + dir.path().join("placement.json"), + br#"{"entries":{},"current":"missing"}"#, + ) + .unwrap(); + assert!(Ledger::open(dir.path(), "placement").is_err()); + let mut ledger = Ledger::open(dir.path(), "other").unwrap(); + ledger.begin(&"cc".repeat(32), &start()).unwrap(); + let text = fs::read_to_string(dir.path().join("other.json")).unwrap(); + assert!(!text.contains("private_key")); + assert!(!text.contains("environment")); + } +} diff --git a/desktop/src-tauri/src/managed_agents/host_location.rs b/desktop/src-tauri/src/managed_agents/host_location.rs new file mode 100644 index 0000000000..d8023b270a --- /dev/null +++ b/desktop/src-tauri/src/managed_agents/host_location.rs @@ -0,0 +1,17 @@ +//! Stamp the actual local launcher, never saved provider routing or ambient env. +pub(super) fn apply( + command: &mut std::process::Command, + owner: Option<&str>, +) -> Result<(), String> { + command + .env_remove("BUZZ_ACP_HOST_PUBKEY") + .env_remove("BUZZ_ACP_HOST_LABEL"); + let Some(owner) = owner else { + return Ok(()); + }; + let location = crate::commands::local_launch_location(owner)?; + command + .env("BUZZ_ACP_HOST_PUBKEY", location.host) + .env("BUZZ_ACP_HOST_LABEL", location.label); + Ok(()) +} diff --git a/desktop/src-tauri/src/managed_agents/mod.rs b/desktop/src-tauri/src/managed_agents/mod.rs index c005e8858b..8fdda484a4 100644 --- a/desktop/src-tauri/src/managed_agents/mod.rs +++ b/desktop/src-tauri/src/managed_agents/mod.rs @@ -16,6 +16,8 @@ mod definition_validation; mod discovery; pub(crate) mod effective_config; mod env_vars; +mod execution; +mod execution_ledger; pub(crate) mod git_bash; pub(crate) mod global_config; mod managed_node_paths; @@ -34,6 +36,7 @@ mod restore; pub mod retention; mod runtime; mod runtime_commands; +pub(crate) use execution::{execute_host_operation, local_execution_config}; mod runtime_types; pub(crate) mod snapshot_avatar; pub(crate) mod spawn_snapshot; @@ -124,3 +127,5 @@ pub fn default_agent_workdir() -> Option { fn is_real_dir(path: &std::path::Path) -> bool { path.symlink_metadata().map(|m| m.is_dir()).unwrap_or(false) } + +mod host_location; diff --git a/desktop/src-tauri/src/managed_agents/reserved_env_keys.rs b/desktop/src-tauri/src/managed_agents/reserved_env_keys.rs index afaaa2b4eb..d7c6180dc4 100644 --- a/desktop/src-tauri/src/managed_agents/reserved_env_keys.rs +++ b/desktop/src-tauri/src/managed_agents/reserved_env_keys.rs @@ -73,6 +73,8 @@ pub(crate) const RESERVED_ENV_KEYS: &[&str] = &[ // for same-session sweep decisions. "BUZZ_MANAGED_AGENT", "BUZZ_MANAGED_AGENT_START_NONCE", + "BUZZ_ACP_HOST_PUBKEY", + "BUZZ_ACP_HOST_LABEL", ]; pub(crate) fn is_reserved_env_key(key: &str) -> bool { diff --git a/desktop/src-tauri/src/managed_agents/restore.rs b/desktop/src-tauri/src/managed_agents/restore.rs index a225f492d3..e30206943a 100644 --- a/desktop/src-tauri/src/managed_agents/restore.rs +++ b/desktop/src-tauri/src/managed_agents/restore.rs @@ -390,6 +390,7 @@ pub async fn restore_managed_agents_on_launch( pid: process.child.id(), desktop_instance_id: super::current_instance_id(app), started_at: now.clone(), + run_id: Some(process.start_nonce.clone()), }; if let Err(error) = super::write_agent_runtime_receipt(app, &receipt) { let _ = super::terminate_process(process.child.id()); diff --git a/desktop/src-tauri/src/managed_agents/runtime.rs b/desktop/src-tauri/src/managed_agents/runtime.rs index 0ce5ca7b21..5119b9a222 100644 --- a/desktop/src-tauri/src/managed_agents/runtime.rs +++ b/desktop/src-tauri/src/managed_agents/runtime.rs @@ -42,7 +42,8 @@ use process::{ }; pub(crate) use process::{ current_instance_id, process_belongs_to_us, process_has_buzz_marker, process_is_running, - terminate_process, terminate_untracked_pair_runtime, valid_agent_runtime_receipt, + terminate_exact_owned_group, terminate_process, terminate_untracked_pair_runtime, + valid_agent_runtime_receipt, }; mod orphan_sweep; @@ -68,6 +69,9 @@ mod lifecycle; #[cfg(test)] use lifecycle::kill_stale_tracked_processes_with; pub use lifecycle::{kill_stale_tracked_processes, sync_managed_agent_processes}; +mod spawn_entry; +use spawn_entry::child_rust_log_filter; +pub use spawn_entry::spawn_agent_child; mod spawn_key; // production spawn-key derivation + its regressions pub(crate) use spawn_key::bound_runtime_key; @@ -397,18 +401,13 @@ pub(crate) fn configure_runtime_cli( } } -/// Spawn an agent process without holding any locks on records or runtimes. -/// Returns the child process and log path on success. The caller is responsible -/// for updating `ManagedAgentRecord` fields and inserting into the runtimes map. -/// -/// `owner_hex`: the workspace owner's pubkey, used as a fallback for legacy -/// records that have no NIP-OA `auth_tag`. See `build_respond_to_env`. -pub fn spawn_agent_child( +pub(super) fn spawn_agent_child_for_run( app: &AppHandle, record: &ManagedAgentRecord, relay_url: &str, lazy: bool, owner_hex: Option<&str>, + generation: Option<(&str, &str)>, ) -> Result { if let Some(error) = spawn_key_refusal(record) { return Err(error); @@ -457,6 +456,13 @@ pub fn spawn_agent_child( crate::managed_agents::user_facing_harness_error(&e) ) })?; + if let Some((_, expected_revision)) = generation { + if super::execution::config_revision(record, &personas, &global, &teams, &descriptor)? + != expected_revision + { + return Err("destination configuration changed before spawn".into()); + } + } let effective_command = &descriptor.command; let agent_args = &descriptor.args; @@ -810,12 +816,9 @@ pub fn spawn_agent_child( command.env(key, value); } - // B5: carry persisted effort; harness resolves thought_level configId at first session. - // Written AFTER descriptor.env so the canonical persisted value wins over any - // user-supplied BUZZ_ACP_EFFORT_LEVEL entry, mirroring the A1 model-authority pattern - // (ANTHROPIC_MODEL is applied post-loop for the same reason). When effort_level is - // None there is no canonical value to assert, so env passthrough stands — user env - // legitimately seeds startup effort in that case. + // B5: carry persisted effort after user env; the harness resolves thought_level + // at first session. Canonical persisted effort wins, like ANTHROPIC_MODEL below. + // With no persisted effort, preserve user env to seed startup configuration. apply_effort_env(&mut command, record.effort_level.as_deref()); // A1: for local claude agents, ANTHROPIC_MODEL is the single startup model authority. @@ -826,6 +829,7 @@ pub fn spawn_agent_child( apply_claude_model_env(&mut command, effective_model.as_deref()); } configure_runtime_cli(&mut command, runtime_meta); + super::host_location::apply(&mut command, owner_hex)?; // Buzz shared compute is stored as a native provider; derive the OpenAI-compatible // transport at spawn time and scrub any unrelated ambient OpenAI key. @@ -842,7 +846,7 @@ pub fn spawn_agent_child( } // Stamp desktop ownership and an unpredictable harness-generation identity. - let start_nonce = uuid::Uuid::new_v4().simple().to_string(); + let start_nonce = spawn_entry::launcher_generation(generation)?; command .env("BUZZ_MANAGED_AGENT", current_instance_id(app)) .env("BUZZ_MANAGED_AGENT_START_NONCE", &start_nonce); @@ -928,14 +932,6 @@ pub fn spawn_agent_child( }) } -fn child_rust_log_filter() -> String { - match std::env::var("RUST_LOG") { - Ok(existing) if existing.contains("buzz_acp") => existing, - Ok(existing) if !existing.trim().is_empty() => format!("{existing},buzz_acp=info"), - _ => "buzz_acp=info".to_string(), - } -} - /// Spawn (or adopt) the runtime pair for `record` on the caller's bound /// workspace relay. `workspace_relay` can only be produced by /// `bind_expected_relay_scope`, so this spawn consumes — by construction — the @@ -974,6 +970,7 @@ pub fn start_managed_agent_process( pid: process.child.id(), desktop_instance_id: current_instance_id(app), started_at: now.clone(), + run_id: Some(process.start_nonce.clone()), }; if let Err(error) = super::write_agent_runtime_receipt(app, &receipt) { let _ = terminate_process(process.child.id()); diff --git a/desktop/src-tauri/src/managed_agents/runtime/process.rs b/desktop/src-tauri/src/managed_agents/runtime/process.rs index 26aa26f074..00dea18b6c 100644 --- a/desktop/src-tauri/src/managed_agents/runtime/process.rs +++ b/desktop/src-tauri/src/managed_agents/runtime/process.rs @@ -467,3 +467,84 @@ pub(crate) fn terminate_untracked_pair_runtime( super::super::remove_agent_runtime_receipt_path, ) } + +/// Teardown observation for generation-fenced operations. Unlike the legacy +/// helper, root exit alone is insufficient: kill remaining owned group members, +/// reap the root and wait for the group to disappear. Detached groups are outside +/// this containment boundary; this is NOT arbitrary process-tree migration proof. +#[cfg(unix)] +pub(crate) fn terminate_exact_owned_group(child: &mut std::process::Child) -> Result<(), String> { + if child + .try_wait() + .map_err(|_| "cannot inspect selected run")? + .is_some() + { + // Already reaped roots may have recycled PIDs. Never signal by a stale + // PID after restart/retry; lack of containment evidence remains unknown. + return Err("selected root already exited; group teardown is unconfirmed".into()); + } + let pid = child.id(); + terminate_process(pid)?; + signal_process_group_or_leader(pid, libc::SIGKILL, "kill remaining group")?; + child.wait().map_err(|_| "failed to reap selected run")?; + for _ in 0..20 { + let output = std::process::Command::new("/bin/ps") + .args(["-axo", "pgid="]) + .output() + .map_err(|_| "cannot observe process groups")?; + if !output.status.success() { + return Err("cannot observe process groups".into()); + } + let text = + std::str::from_utf8(&output.stdout).map_err(|_| "invalid process group observation")?; + let groups = text + .split_whitespace() + .map(str::parse::) + .collect::, _>>() + .map_err(|_| "invalid process group observation")?; + if !groups.contains(&pid) { + return Ok(()); + } + std::thread::sleep(std::time::Duration::from_millis(100)); + } + Err("selected run group teardown is unconfirmed".into()) +} + +#[cfg(not(unix))] +pub(crate) fn terminate_exact_owned_group(_child: &mut std::process::Child) -> Result<(), String> { + Err("exact run teardown observation is not supported on this platform".into()) +} + +#[cfg(all(test, unix))] +mod exact_run_tests { + use super::*; + use std::os::unix::process::CommandExt; + + struct ChildGuard(std::process::Child); + impl Drop for ChildGuard { + fn drop(&mut self) { + let _ = self.0.kill(); + let _ = self.0.wait(); + } + } + fn child() -> ChildGuard { + ChildGuard( + std::process::Command::new("/bin/sleep") + .arg("60") + .process_group(0) + .spawn() + .unwrap(), + ) + } + #[test] + fn exact_group_teardown_reaps_root_and_leaves_peer_alive() { + let mut selected = child(); + let mut peer = child(); + terminate_exact_owned_group(&mut selected.0).unwrap(); + assert!(selected.0.try_wait().unwrap().is_some()); + assert!(peer.0.try_wait().unwrap().is_none()); + // Retry after the root was reaped cannot signal a potentially reused PID. + assert!(terminate_exact_owned_group(&mut selected.0).is_err()); + assert!(peer.0.try_wait().unwrap().is_none()); + } +} diff --git a/desktop/src-tauri/src/managed_agents/runtime/spawn_entry.rs b/desktop/src-tauri/src/managed_agents/runtime/spawn_entry.rs new file mode 100644 index 0000000000..77ce042b79 --- /dev/null +++ b/desktop/src-tauri/src/managed_agents/runtime/spawn_entry.rs @@ -0,0 +1,41 @@ +use crate::managed_agents::ManagedAgentRecord; +use tauri::AppHandle; + +/// Spawn an agent process without holding any locks on records or runtimes. +/// Returns the child process and log path on success. The caller is responsible +/// for updating `ManagedAgentRecord` fields and inserting into the runtimes map. +/// +/// `owner_hex`: the workspace owner's pubkey, used as a fallback for legacy +/// records that have no NIP-OA `auth_tag`. See `build_respond_to_env`. +pub fn spawn_agent_child( + app: &AppHandle, + record: &ManagedAgentRecord, + relay_url: &str, + lazy: bool, + owner_hex: Option<&str>, +) -> Result { + // Durable Stop fences config-driven and legacy starts too. Hold the OS lock + // through spawn so a concurrent executor cannot persist Stop between check + // and process creation. + let _fence = + crate::managed_agents::execution::legacy_spawn_guard(app, record, relay_url, owner_hex)?; + super::spawn_agent_child_for_run(app, record, relay_url, lazy, owner_hex, None) +} + +pub(super) fn child_rust_log_filter() -> String { + match std::env::var("RUST_LOG") { + Ok(existing) if existing.contains("buzz_acp") => existing, + Ok(existing) if !existing.trim().is_empty() => format!("{existing},buzz_acp=info"), + _ => "buzz_acp=info".to_string(), + } +} + +pub(super) fn launcher_generation(generation: Option<(&str, &str)>) -> Result { + let run = generation + .map(|(run, _)| run.to_owned()) + .unwrap_or_else(|| uuid::Uuid::new_v4().simple().to_string()); + if !buzz_core_pkg::host_execution::hex_id(&run, 32) { + return Err("invalid launcher generation".into()); + } + Ok(run) +} diff --git a/desktop/src-tauri/src/managed_agents/runtime/test_fixtures.rs b/desktop/src-tauri/src/managed_agents/runtime/test_fixtures.rs index ec78cc14ef..f531632cbd 100644 --- a/desktop/src-tauri/src/managed_agents/runtime/test_fixtures.rs +++ b/desktop/src-tauri/src/managed_agents/runtime/test_fixtures.rs @@ -94,3 +94,15 @@ pub(super) fn fixture( effort_level: None, } } + +pub(super) fn receipt_fixture( + key: crate::managed_agents::ManagedAgentRuntimeKey, +) -> crate::managed_agents::ManagedAgentRuntimeReceipt { + crate::managed_agents::ManagedAgentRuntimeReceipt { + key, + pid: std::process::id(), + desktop_instance_id: "test-instance".into(), + started_at: "now".into(), + run_id: None, + } +} diff --git a/desktop/src-tauri/src/managed_agents/runtime/tests.rs b/desktop/src-tauri/src/managed_agents/runtime/tests.rs index 24fad1461c..99a6a8221b 100644 --- a/desktop/src-tauri/src/managed_agents/runtime/tests.rs +++ b/desktop/src-tauri/src/managed_agents/runtime/tests.rs @@ -1,3 +1,4 @@ +use super::test_fixtures::receipt_fixture; use crate::managed_agents::known_acp_runtime; #[path = "cli_tests.rs"] @@ -856,17 +857,6 @@ fn own_group_grandchild_detected_by_ancestor_walk() { // ── pair receipt validation tests ─────────────────────────────────────── -fn receipt_fixture( - key: crate::managed_agents::ManagedAgentRuntimeKey, -) -> crate::managed_agents::ManagedAgentRuntimeReceipt { - crate::managed_agents::ManagedAgentRuntimeReceipt { - key, - pid: std::process::id(), - desktop_instance_id: "test-instance".into(), - started_at: "now".into(), - } -} - #[test] fn receipt_validation_rejects_noncanonical_identity() { let mut receipt = receipt_fixture( diff --git a/desktop/src-tauri/src/managed_agents/runtime_commands.rs b/desktop/src-tauri/src/managed_agents/runtime_commands.rs index 135224d01d..65d71a62c1 100644 --- a/desktop/src-tauri/src/managed_agents/runtime_commands.rs +++ b/desktop/src-tauri/src/managed_agents/runtime_commands.rs @@ -66,6 +66,7 @@ fn status_for_with( .map(|runtime| runtime.lifecycle.clone()) .unwrap_or(ManagedAgentRuntimeLifecycle::Stopped), pid: runtime.map(|runtime| runtime.child.id()), + run_id: runtime.map(|runtime| runtime.start_nonce.clone()), error: runtime.and_then(|runtime| runtime.error.clone()), log_path: managed_agent_runtime_log_path(app, key) .ok() @@ -295,6 +296,7 @@ fn start_pair( pid: process.child.id(), desktop_instance_id: current_instance_id(&app), started_at: now.clone(), + run_id: Some(process.start_nonce.clone()), }; if let Err(error) = write_agent_runtime_receipt(&app, &receipt) { let _ = terminate_process(process.child.id()); @@ -446,6 +448,7 @@ fn unkeyable_failed_status( local_setup: matches!(agent_readiness(&effective), AgentReadiness::Ready), lifecycle: ManagedAgentRuntimeLifecycle::Failed, pid: None, + run_id: None, error: Some(error), log_path: None, } diff --git a/desktop/src-tauri/src/managed_agents/runtime_types.rs b/desktop/src-tauri/src/managed_agents/runtime_types.rs index 4862cedbae..15067ec86d 100644 --- a/desktop/src-tauri/src/managed_agents/runtime_types.rs +++ b/desktop/src-tauri/src/managed_agents/runtime_types.rs @@ -90,6 +90,8 @@ pub struct ManagedAgentRuntimeStatus { pub local_setup: bool, pub lifecycle: ManagedAgentRuntimeLifecycle, pub pid: Option, + /// Launcher generation, also the public run-presence ID. + pub run_id: Option, pub error: Option, pub log_path: Option, } @@ -117,4 +119,7 @@ pub struct ManagedAgentRuntimeReceipt { pub pid: u32, pub desktop_instance_id: String, pub started_at: String, + /// Absent on legacy receipts; never infer an exact-run stop from their PID. + #[serde(default)] + pub run_id: Option, } diff --git a/desktop/src-tauri/src/secret_store.rs b/desktop/src-tauri/src/secret_store.rs index 43854761b5..fffd6c4c99 100644 --- a/desktop/src-tauri/src/secret_store.rs +++ b/desktop/src-tauri/src/secret_store.rs @@ -20,6 +20,8 @@ //! adding an env tier here would duplicate that precedence and create a //! divergent-behavior trap. +mod host_key; + use std::collections::HashMap; use std::path::PathBuf; use std::sync::Mutex; @@ -922,385 +924,4 @@ impl SecretStore { } #[cfg(all(test, feature = "system-keyring"))] -mod tests { - use super::*; - - // Test-only constructor: pre-seed the cache without touching the OS keychain. - impl SecretStore { - fn with_cache(service: &str, cache: Option>) -> Self { - SecretStore { - service: service.to_string(), - cache: Mutex::new(cache), - } - } - } - - #[test] - fn probe_returns_present_when_key_in_cache() { - let mut map = HashMap::new(); - map.insert("identity".to_string(), "nsec1test".to_string()); - let store = SecretStore::with_cache("buzz-test-cache-hit", Some(map)); - // Cache is warm and contains "identity" — probe must return Present - // without touching the keychain. - assert_eq!(store.probe("identity"), KeyringProbe::Present); - } - - #[test] - fn load_returns_value_when_key_in_cache() { - let mut map = HashMap::new(); - map.insert("identity".to_string(), "nsec1test".to_string()); - let store = SecretStore::with_cache("buzz-test-load-cache-hit", Some(map)); - // Cache is warm and contains "identity" — load must return the value - // without touching the keychain. - assert_eq!( - store.load("identity").unwrap(), - Some("nsec1test".to_string()) - ); - } - - // ── Cross-process race tests (require real OS keychain) ──────────────── - - #[ignore = "requires real OS keychain (run locally)"] - #[test] - fn test_stale_warm_cache_add_observes_prior_write() { - // Simulates the cross-process race that stranded Will's agent keys. - // - // Setup: two SecretStore instances for the same service (= two - // "processes" with separate caches). Process A warms its cache to - // {k1}. Process B then writes {k1, k2}. Without the fix, A's next - // mutate_blob would build from its stale {k1} cache and write - // {k1, k3}, silently dropping k2. With the fix, A always re-reads - // from the keychain inside the lock, so the result is {k1, k2, k3}. - let svc = "buzz-test-race-stale-cache"; - - // Clean state. - let setup = SecretStore::keyring(svc); - let _ = setup.delete("k1"); - let _ = setup.delete("k2"); - let _ = setup.delete("k3"); - - // Process A: write k1, warming its cache. - let store_a = SecretStore::keyring(svc); - store_a.store("k1", "v1").unwrap(); - - // Process B: write k2 (separate instance = separate cache). - let store_b = SecretStore::keyring(svc); - store_b.store("k2", "v2").unwrap(); - - // Process A: write k3. With the fix, A re-reads inside the lock and - // sees {k1, k2} before appending k3 — result must be {k1, k2, k3}. - store_a.store("k3", "v3").unwrap(); - - // Verify via a third reader (clean cache). - let reader = SecretStore::keyring(svc); - assert_eq!( - reader.load("k1").unwrap(), - Some("v1".to_string()), - "k1 must survive" - ); - assert_eq!( - reader.load("k2").unwrap(), - Some("v2".to_string()), - "k2 must not be dropped" - ); - assert_eq!( - reader.load("k3").unwrap(), - Some("v3".to_string()), - "k3 must be written" - ); - - // Cleanup. - let _ = reader.delete("k1"); - let _ = reader.delete("k2"); - let _ = reader.delete("k3"); - } - - #[ignore = "requires real OS keychain (run locally)"] - #[test] - fn test_concurrent_adds_neither_key_dropped() { - // Two sequential stores from distinct instances (simulating two - // processes each adding one key) must both be durably visible. - let svc = "buzz-test-race-concurrent-add"; - - let setup = SecretStore::keyring(svc); - let _ = setup.delete("agent_a"); - let _ = setup.delete("agent_b"); - - let store1 = SecretStore::keyring(svc); - store1.store("agent_a", "nsec1aaa").unwrap(); - - let store2 = SecretStore::keyring(svc); - store2.store("agent_b", "nsec1bbb").unwrap(); - - let reader = SecretStore::keyring(svc); - assert_eq!( - reader.load("agent_a").unwrap(), - Some("nsec1aaa".to_string()), - "agent_a must not be dropped" - ); - assert_eq!( - reader.load("agent_b").unwrap(), - Some("nsec1bbb".to_string()), - "agent_b must not be dropped" - ); - - // Cleanup. - let _ = reader.delete("agent_a"); - let _ = reader.delete("agent_b"); - } - - #[test] - fn test_blob_lockfile_path_is_in_tmp_with_uid() { - // The lockfile must be at a deterministic per-user path under /tmp — - // invariant to $TMPDIR — so both a GUI-launched DMG (env-stripped by - // launchd) and a terminal-launched dev build resolve the same inode and - // achieve mutual exclusion. - let path = blob_lockfile_path("buzz-desktop"); - #[cfg(unix)] - { - let uid = unsafe { libc::getuid() }; - assert!( - path.starts_with("/tmp"), - "lockfile {path:?} must start with /tmp (not $TMPDIR)" - ); - let name = path - .file_name() - .and_then(|n| n.to_str()) - .unwrap_or_default(); - assert!( - name.contains(&uid.to_string()), - "lockfile {path:?} must contain uid {uid}" - ); - assert!( - name.contains("buzz-keychain"), - "lockfile name must contain 'buzz-keychain'" - ); - } - #[cfg(not(unix))] - { - assert!( - path.file_name() - .and_then(|n| n.to_str()) - .is_some_and(|n| n.contains("buzz-keychain")), - "lockfile name must contain 'buzz-keychain'" - ); - } - } - - #[test] - fn test_blob_lock_acquire_and_release() { - // Verify the advisory lock can be acquired and released without errors. - // This exercises the real flock/mutex path on the current platform. - let guard = acquire_blob_lock("buzz-test-lock-smoke"); - assert!( - guard.is_ok(), - "advisory lock acquire must succeed: {:?}", - guard.err() - ); - // Drop the guard — lock is released. A second acquire must succeed. - drop(guard); - let guard2 = acquire_blob_lock("buzz-test-lock-smoke"); - assert!( - guard2.is_ok(), - "advisory lock re-acquire after release must succeed: {:?}", - guard2.err() - ); - } - - #[ignore = "requires real OS keychain (run locally)"] - #[test] - fn mutate_blob_does_not_advance_cache_on_write_failure() { - // Copy-on-write safety: if `write_blob_raw` fails (denied prompt, - // transient outage, ACL rejection), the cache must stay at the last - // known durable state. A subsequent `store()` for the same key/value - // must NOT be skipped as a no-op — the equality check must compare - // against the durable cache, not an unpersisted candidate. - // - // This is a real-keychain integration test. Run locally with: - // cargo test -p buzz-desktop -- --ignored mutate_blob_does_not_advance - // - // On a machine with a reachable keychain the `store()` call succeeds - // (result.is_ok()) and the write-failure branch is skipped — the test - // still passes. On a machine where the write is denied (e.g., user - // clicks Deny in the macOS prompt) result.is_err() and the assertions - // below verify the cache invariant. We verify that after an error: - // 1. The cache is not advanced (the previously cached key is intact). - // 2. The failed key is not present (the dirty candidate was discarded). - let mut map = HashMap::new(); - map.insert("existing".to_string(), "durable_val".to_string()); - let store = SecretStore::with_cache("buzz-test-cow-write-fail", Some(map)); - - // Attempt to add a new key — this calls write_blob_raw against the - // real keychain; with copy-on-write the cache must remain at {existing} - // if the write fails. - let result = store.store("new_key", "new_val"); - - if result.is_err() { - // Write failed (e.g., user denied the keychain prompt): confirm - // cache was not advanced — the existing key is still intact and - // the new key was never committed to the in-memory state. - assert_eq!( - store.load("existing").unwrap(), - Some("durable_val".to_string()), - "cache must remain at last durable state after write failure" - ); - // load("new_key") goes through the unchanged cache (no entry), - // then attempts migrate_legacy_key which also fails on a denied - // keychain, returning either Ok(None) or Err — either is correct - // since the key was never durably stored. - let after = store.load("new_key"); - assert!( - matches!(after, Ok(None) | Err(_)), - "a key whose write failed must not be visible via load: {after:?}" - ); - } - // If result.is_ok() the write succeeded — the cache-integrity invariant - // does not apply to the success path; no assertion needed here. - } - - #[test] - fn availability_error_discriminator() { - assert!(is_keyring_availability_error("dbus connection failed")); - assert!(is_keyring_availability_error( - "org.freedesktop.secrets not provided" - )); - assert!(is_keyring_availability_error("No Secret Service")); - assert!(is_keyring_availability_error( - "Platform secure storage failure" - )); - // A plain "not found" is per-entry, not an availability failure. - assert!(!is_keyring_availability_error("entry not found")); - } - - #[cfg(target_os = "macos")] - #[test] - fn dpk_error_discriminators() { - // errSecMissingEntitlement = -34018 signals unsigned dev build. - let e = SFError::from_code(-34018); - assert!(is_dpk_unavailable(&e)); - assert!(!is_not_found(&e)); - // errSecItemNotFound = -25300 is not a DPK-unavailable error. - let e = SFError::from_code(-25300); - assert!(is_not_found(&e)); - assert!(!is_dpk_unavailable(&e)); - } - - // Integration tests that exercise the real OS keychain. Skipped in CI - // (unsigned builds lack keychain entitlements); run locally with: - // cargo test -p buzz-desktop -- --ignored blob_ - // - // Each test uses a unique service name to avoid cross-test pollution. - - #[ignore = "requires real OS keychain (run locally)"] - #[test] - fn blob_stores_and_retrieves_multiple_keys() { - let store = SecretStore::keyring("buzz-test-blob-multi"); - store.store("key_a", "val_a").unwrap(); - store.store("key_b", "val_b").unwrap(); - assert_eq!(store.load("key_a").unwrap(), Some("val_a".to_string())); - assert_eq!(store.load("key_b").unwrap(), Some("val_b".to_string())); - assert_eq!(store.load("key_c").unwrap(), None); - // Cleanup. - let _ = store.delete("key_a"); - let _ = store.delete("key_b"); - } - - #[ignore = "requires real OS keychain (run locally)"] - #[test] - fn blob_probe_present_absent_unreachable() { - let store = SecretStore::keyring("buzz-test-blob-probe"); - // No blob yet — key absent, backend reachable. - assert_eq!(store.probe("identity"), KeyringProbe::ReachableButEmpty); - store.store("identity", "nsec1test").unwrap(); - // Key now present. - assert_eq!(store.probe("identity"), KeyringProbe::Present); - // Different key — blob exists but key absent. - assert_eq!(store.probe("other"), KeyringProbe::ReachableButEmpty); - // Cleanup. - let _ = store.delete("identity"); - } - - #[ignore = "requires real OS keychain (run locally)"] - #[test] - fn blob_delete_removes_key_not_others() { - let store = SecretStore::keyring("buzz-test-blob-delete"); - store.store("keep", "keep_val").unwrap(); - store.store("remove", "remove_val").unwrap(); - store.delete("remove").unwrap(); - assert_eq!(store.load("keep").unwrap(), Some("keep_val".to_string())); - assert_eq!(store.load("remove").unwrap(), None); - // Cleanup. - let _ = store.delete("keep"); - } - - #[ignore = "requires real OS keychain (run locally)"] - #[test] - fn blob_migration_from_per_key_entry() { - let svc = "buzz-test-blob-migration"; - let key = "identity"; - let value = "nsec1migrationtest"; - - // Seed a per-key entry (old format) — no blob exists. - let entry = keyring_entry(svc, key).unwrap(); - entry.set_password(value).unwrap(); - - // Fresh store — no blob in the keychain yet. - let store = SecretStore::keyring(svc); - - // probe should find the legacy key. - assert_eq!(store.probe(key), KeyringProbe::Present); - - // load should migrate it into the blob and return the value. - assert_eq!(store.load(key).unwrap(), Some(value.to_string())); - - // Old per-key entry should be cleaned up. - let entry = keyring_entry(svc, key).unwrap(); - assert!(matches!(entry.get_password(), Err(keyring::Error::NoEntry))); - - // Key is now in the blob — probe confirms. - let store2 = SecretStore::keyring(svc); - assert_eq!(store2.probe(key), KeyringProbe::Present); - assert_eq!(store2.load(key).unwrap(), Some(value.to_string())); - - // Cleanup. - let _ = store2.delete(key); - } - - #[ignore = "requires real OS keychain (run locally)"] - #[test] - fn delete_all_with_legacy_cleanup_removes_per_key_identity() { - let svc = "buzz-test-delete-all-legacy"; - let key = "identity"; - let value = "nsec1legacytest"; - - // Seed a legacy per-key entry (old format, pre-blob migration). - let entry = keyring_entry(svc, key).unwrap(); - entry.set_password(value).unwrap(); - - // Also seed a blob with a different key to exercise the full path. - let store = SecretStore::keyring(svc); - store.store("agent:abc123", "nsec1agent").unwrap(); - - // Legacy per-key identity should be discoverable via probe. - let store2 = SecretStore::keyring(svc); - assert_eq!(store2.probe(key), KeyringProbe::Present); - - // Wipe everything via the sign-out path. - store2.delete_all_with_legacy_cleanup().unwrap(); - - // Fresh store — neither the blob nor the per-key entry should remain. - let store3 = SecretStore::keyring(svc); - assert_eq!( - store3.probe(key), - KeyringProbe::ReachableButEmpty, - "per-key identity must not survive delete_all_with_legacy_cleanup" - ); - assert_eq!( - store3.load(key).unwrap(), - None, - "load must not resurrect the legacy per-key identity" - ); - // Agent key should also be gone. - assert_eq!(store3.load("agent:abc123").unwrap(), None); - } -} +mod tests; diff --git a/desktop/src-tauri/src/secret_store/host_key.rs b/desktop/src-tauri/src/secret_store/host_key.rs new file mode 100644 index 0000000000..c171bda016 --- /dev/null +++ b/desktop/src-tauri/src/secret_store/host_key.rs @@ -0,0 +1,20 @@ +//! Host key creation uses the same cross-process keychain transaction as agents. +impl super::SecretStore { + /// Atomically keep an existing secret or insert a candidate. Never overwrite. + pub(crate) fn host_key(&self, name: &str) -> Result { + #[cfg(feature = "system-keyring")] + { + let candidate = nostr::Keys::generate().secret_key().to_secret_hex(); + let mut result = String::new(); + self.mutate_blob(|blob| { + result = blob.entry(name.to_owned()).or_insert(candidate).clone(); + })?; + Ok(result) + } + #[cfg(not(feature = "system-keyring"))] + { + let _ = name; + Err("Host registration requires secure key storage in this build".into()) + } + } +} diff --git a/desktop/src-tauri/src/secret_store/tests.rs b/desktop/src-tauri/src/secret_store/tests.rs new file mode 100644 index 0000000000..b498fb5c5d --- /dev/null +++ b/desktop/src-tauri/src/secret_store/tests.rs @@ -0,0 +1,380 @@ +use super::*; + +// Test-only constructor: pre-seed the cache without touching the OS keychain. +impl SecretStore { + fn with_cache(service: &str, cache: Option>) -> Self { + SecretStore { + service: service.to_string(), + cache: Mutex::new(cache), + } + } +} + +#[test] +fn probe_returns_present_when_key_in_cache() { + let mut map = HashMap::new(); + map.insert("identity".to_string(), "nsec1test".to_string()); + let store = SecretStore::with_cache("buzz-test-cache-hit", Some(map)); + // Cache is warm and contains "identity" — probe must return Present + // without touching the keychain. + assert_eq!(store.probe("identity"), KeyringProbe::Present); +} + +#[test] +fn load_returns_value_when_key_in_cache() { + let mut map = HashMap::new(); + map.insert("identity".to_string(), "nsec1test".to_string()); + let store = SecretStore::with_cache("buzz-test-load-cache-hit", Some(map)); + // Cache is warm and contains "identity" — load must return the value + // without touching the keychain. + assert_eq!( + store.load("identity").unwrap(), + Some("nsec1test".to_string()) + ); +} + +// ── Cross-process race tests (require real OS keychain) ──────────────── + +#[ignore = "requires real OS keychain (run locally)"] +#[test] +fn test_stale_warm_cache_add_observes_prior_write() { + // Simulates the cross-process race that stranded Will's agent keys. + // + // Setup: two SecretStore instances for the same service (= two + // "processes" with separate caches). Process A warms its cache to + // {k1}. Process B then writes {k1, k2}. Without the fix, A's next + // mutate_blob would build from its stale {k1} cache and write + // {k1, k3}, silently dropping k2. With the fix, A always re-reads + // from the keychain inside the lock, so the result is {k1, k2, k3}. + let svc = "buzz-test-race-stale-cache"; + + // Clean state. + let setup = SecretStore::keyring(svc); + let _ = setup.delete("k1"); + let _ = setup.delete("k2"); + let _ = setup.delete("k3"); + + // Process A: write k1, warming its cache. + let store_a = SecretStore::keyring(svc); + store_a.store("k1", "v1").unwrap(); + + // Process B: write k2 (separate instance = separate cache). + let store_b = SecretStore::keyring(svc); + store_b.store("k2", "v2").unwrap(); + + // Process A: write k3. With the fix, A re-reads inside the lock and + // sees {k1, k2} before appending k3 — result must be {k1, k2, k3}. + store_a.store("k3", "v3").unwrap(); + + // Verify via a third reader (clean cache). + let reader = SecretStore::keyring(svc); + assert_eq!( + reader.load("k1").unwrap(), + Some("v1".to_string()), + "k1 must survive" + ); + assert_eq!( + reader.load("k2").unwrap(), + Some("v2".to_string()), + "k2 must not be dropped" + ); + assert_eq!( + reader.load("k3").unwrap(), + Some("v3".to_string()), + "k3 must be written" + ); + + // Cleanup. + let _ = reader.delete("k1"); + let _ = reader.delete("k2"); + let _ = reader.delete("k3"); +} + +#[ignore = "requires real OS keychain (run locally)"] +#[test] +fn test_concurrent_adds_neither_key_dropped() { + // Two sequential stores from distinct instances (simulating two + // processes each adding one key) must both be durably visible. + let svc = "buzz-test-race-concurrent-add"; + + let setup = SecretStore::keyring(svc); + let _ = setup.delete("agent_a"); + let _ = setup.delete("agent_b"); + + let store1 = SecretStore::keyring(svc); + store1.store("agent_a", "nsec1aaa").unwrap(); + + let store2 = SecretStore::keyring(svc); + store2.store("agent_b", "nsec1bbb").unwrap(); + + let reader = SecretStore::keyring(svc); + assert_eq!( + reader.load("agent_a").unwrap(), + Some("nsec1aaa".to_string()), + "agent_a must not be dropped" + ); + assert_eq!( + reader.load("agent_b").unwrap(), + Some("nsec1bbb".to_string()), + "agent_b must not be dropped" + ); + + // Cleanup. + let _ = reader.delete("agent_a"); + let _ = reader.delete("agent_b"); +} + +#[test] +fn test_blob_lockfile_path_is_in_tmp_with_uid() { + // The lockfile must be at a deterministic per-user path under /tmp — + // invariant to $TMPDIR — so both a GUI-launched DMG (env-stripped by + // launchd) and a terminal-launched dev build resolve the same inode and + // achieve mutual exclusion. + let path = blob_lockfile_path("buzz-desktop"); + #[cfg(unix)] + { + let uid = unsafe { libc::getuid() }; + assert!( + path.starts_with("/tmp"), + "lockfile {path:?} must start with /tmp (not $TMPDIR)" + ); + let name = path + .file_name() + .and_then(|n| n.to_str()) + .unwrap_or_default(); + assert!( + name.contains(&uid.to_string()), + "lockfile {path:?} must contain uid {uid}" + ); + assert!( + name.contains("buzz-keychain"), + "lockfile name must contain 'buzz-keychain'" + ); + } + #[cfg(not(unix))] + { + assert!( + path.file_name() + .and_then(|n| n.to_str()) + .is_some_and(|n| n.contains("buzz-keychain")), + "lockfile name must contain 'buzz-keychain'" + ); + } +} + +#[test] +fn test_blob_lock_acquire_and_release() { + // Verify the advisory lock can be acquired and released without errors. + // This exercises the real flock/mutex path on the current platform. + let guard = acquire_blob_lock("buzz-test-lock-smoke"); + assert!( + guard.is_ok(), + "advisory lock acquire must succeed: {:?}", + guard.err() + ); + // Drop the guard — lock is released. A second acquire must succeed. + drop(guard); + let guard2 = acquire_blob_lock("buzz-test-lock-smoke"); + assert!( + guard2.is_ok(), + "advisory lock re-acquire after release must succeed: {:?}", + guard2.err() + ); +} + +#[ignore = "requires real OS keychain (run locally)"] +#[test] +fn mutate_blob_does_not_advance_cache_on_write_failure() { + // Copy-on-write safety: if `write_blob_raw` fails (denied prompt, + // transient outage, ACL rejection), the cache must stay at the last + // known durable state. A subsequent `store()` for the same key/value + // must NOT be skipped as a no-op — the equality check must compare + // against the durable cache, not an unpersisted candidate. + // + // This is a real-keychain integration test. Run locally with: + // cargo test -p buzz-desktop -- --ignored mutate_blob_does_not_advance + // + // On a machine with a reachable keychain the `store()` call succeeds + // (result.is_ok()) and the write-failure branch is skipped — the test + // still passes. On a machine where the write is denied (e.g., user + // clicks Deny in the macOS prompt) result.is_err() and the assertions + // below verify the cache invariant. We verify that after an error: + // 1. The cache is not advanced (the previously cached key is intact). + // 2. The failed key is not present (the dirty candidate was discarded). + let mut map = HashMap::new(); + map.insert("existing".to_string(), "durable_val".to_string()); + let store = SecretStore::with_cache("buzz-test-cow-write-fail", Some(map)); + + // Attempt to add a new key — this calls write_blob_raw against the + // real keychain; with copy-on-write the cache must remain at {existing} + // if the write fails. + let result = store.store("new_key", "new_val"); + + if result.is_err() { + // Write failed (e.g., user denied the keychain prompt): confirm + // cache was not advanced — the existing key is still intact and + // the new key was never committed to the in-memory state. + assert_eq!( + store.load("existing").unwrap(), + Some("durable_val".to_string()), + "cache must remain at last durable state after write failure" + ); + // load("new_key") goes through the unchanged cache (no entry), + // then attempts migrate_legacy_key which also fails on a denied + // keychain, returning either Ok(None) or Err — either is correct + // since the key was never durably stored. + let after = store.load("new_key"); + assert!( + matches!(after, Ok(None) | Err(_)), + "a key whose write failed must not be visible via load: {after:?}" + ); + } + // If result.is_ok() the write succeeded — the cache-integrity invariant + // does not apply to the success path; no assertion needed here. +} + +#[test] +fn availability_error_discriminator() { + assert!(is_keyring_availability_error("dbus connection failed")); + assert!(is_keyring_availability_error( + "org.freedesktop.secrets not provided" + )); + assert!(is_keyring_availability_error("No Secret Service")); + assert!(is_keyring_availability_error( + "Platform secure storage failure" + )); + // A plain "not found" is per-entry, not an availability failure. + assert!(!is_keyring_availability_error("entry not found")); +} + +#[cfg(target_os = "macos")] +#[test] +fn dpk_error_discriminators() { + // errSecMissingEntitlement = -34018 signals unsigned dev build. + let e = SFError::from_code(-34018); + assert!(is_dpk_unavailable(&e)); + assert!(!is_not_found(&e)); + // errSecItemNotFound = -25300 is not a DPK-unavailable error. + let e = SFError::from_code(-25300); + assert!(is_not_found(&e)); + assert!(!is_dpk_unavailable(&e)); +} + +// Integration tests that exercise the real OS keychain. Skipped in CI +// (unsigned builds lack keychain entitlements); run locally with: +// cargo test -p buzz-desktop -- --ignored blob_ +// +// Each test uses a unique service name to avoid cross-test pollution. + +#[ignore = "requires real OS keychain (run locally)"] +#[test] +fn blob_stores_and_retrieves_multiple_keys() { + let store = SecretStore::keyring("buzz-test-blob-multi"); + store.store("key_a", "val_a").unwrap(); + store.store("key_b", "val_b").unwrap(); + assert_eq!(store.load("key_a").unwrap(), Some("val_a".to_string())); + assert_eq!(store.load("key_b").unwrap(), Some("val_b".to_string())); + assert_eq!(store.load("key_c").unwrap(), None); + // Cleanup. + let _ = store.delete("key_a"); + let _ = store.delete("key_b"); +} + +#[ignore = "requires real OS keychain (run locally)"] +#[test] +fn blob_probe_present_absent_unreachable() { + let store = SecretStore::keyring("buzz-test-blob-probe"); + // No blob yet — key absent, backend reachable. + assert_eq!(store.probe("identity"), KeyringProbe::ReachableButEmpty); + store.store("identity", "nsec1test").unwrap(); + // Key now present. + assert_eq!(store.probe("identity"), KeyringProbe::Present); + // Different key — blob exists but key absent. + assert_eq!(store.probe("other"), KeyringProbe::ReachableButEmpty); + // Cleanup. + let _ = store.delete("identity"); +} + +#[ignore = "requires real OS keychain (run locally)"] +#[test] +fn blob_delete_removes_key_not_others() { + let store = SecretStore::keyring("buzz-test-blob-delete"); + store.store("keep", "keep_val").unwrap(); + store.store("remove", "remove_val").unwrap(); + store.delete("remove").unwrap(); + assert_eq!(store.load("keep").unwrap(), Some("keep_val".to_string())); + assert_eq!(store.load("remove").unwrap(), None); + // Cleanup. + let _ = store.delete("keep"); +} + +#[ignore = "requires real OS keychain (run locally)"] +#[test] +fn blob_migration_from_per_key_entry() { + let svc = "buzz-test-blob-migration"; + let key = "identity"; + let value = "nsec1migrationtest"; + + // Seed a per-key entry (old format) — no blob exists. + let entry = keyring_entry(svc, key).unwrap(); + entry.set_password(value).unwrap(); + + // Fresh store — no blob in the keychain yet. + let store = SecretStore::keyring(svc); + + // probe should find the legacy key. + assert_eq!(store.probe(key), KeyringProbe::Present); + + // load should migrate it into the blob and return the value. + assert_eq!(store.load(key).unwrap(), Some(value.to_string())); + + // Old per-key entry should be cleaned up. + let entry = keyring_entry(svc, key).unwrap(); + assert!(matches!(entry.get_password(), Err(keyring::Error::NoEntry))); + + // Key is now in the blob — probe confirms. + let store2 = SecretStore::keyring(svc); + assert_eq!(store2.probe(key), KeyringProbe::Present); + assert_eq!(store2.load(key).unwrap(), Some(value.to_string())); + + // Cleanup. + let _ = store2.delete(key); +} + +#[ignore = "requires real OS keychain (run locally)"] +#[test] +fn delete_all_with_legacy_cleanup_removes_per_key_identity() { + let svc = "buzz-test-delete-all-legacy"; + let key = "identity"; + let value = "nsec1legacytest"; + + // Seed a legacy per-key entry (old format, pre-blob migration). + let entry = keyring_entry(svc, key).unwrap(); + entry.set_password(value).unwrap(); + + // Also seed a blob with a different key to exercise the full path. + let store = SecretStore::keyring(svc); + store.store("agent:abc123", "nsec1agent").unwrap(); + + // Legacy per-key identity should be discoverable via probe. + let store2 = SecretStore::keyring(svc); + assert_eq!(store2.probe(key), KeyringProbe::Present); + + // Wipe everything via the sign-out path. + store2.delete_all_with_legacy_cleanup().unwrap(); + + // Fresh store — neither the blob nor the per-key entry should remain. + let store3 = SecretStore::keyring(svc); + assert_eq!( + store3.probe(key), + KeyringProbe::ReachableButEmpty, + "per-key identity must not survive delete_all_with_legacy_cleanup" + ); + assert_eq!( + store3.load(key).unwrap(), + None, + "load must not resurrect the legacy per-key identity" + ); + // Agent key should also be gone. + assert_eq!(store3.load("agent:abc123").unwrap(), None); +} diff --git a/desktop/src/app/useAppShellLifecycleEffects.ts b/desktop/src/app/useAppShellLifecycleEffects.ts index fcdc29fc5f..0fee9df1bf 100644 --- a/desktop/src/app/useAppShellLifecycleEffects.ts +++ b/desktop/src/app/useAppShellLifecycleEffects.ts @@ -1,5 +1,8 @@ import * as React from "react"; import { useQueryClient } from "@tanstack/react-query"; +import { useCommunities } from "@/features/communities/useCommunities"; +import { useHostRegistration } from "@/features/hosts/useHostRegistration"; +import { useIdentityQuery } from "@/shared/api/hooks"; import { startBootWarm } from "@/features/agents/acpRuntimesQuery"; import { setDesktopAppBadge } from "@/features/notifications/lib/desktop"; @@ -22,6 +25,13 @@ export function useAppShellLifecycleEffects({ }: AppShellLifecycleEffectsOptions) { // Event-driven reconnect: network online / focus / visibility short-circuit // the backoff timer when the relay session is degraded (CMD+R gap G1). + const { activeCommunity } = useCommunities(); + const { data: identity } = useIdentityQuery(); + // Huddle companion windows must not create a second host publisher. + useHostRegistration( + desktopBadgeEnabled ? identity?.pubkey : undefined, + activeCommunity?.relayUrl, + ); useRelayResumeTriggers(); useForegroundQueryRefresh(); diff --git a/desktop/src/features/agents/lib/otherSetupAgent.test.mjs b/desktop/src/features/agents/lib/otherSetupAgent.test.mjs index f57c7f8154..a45ddb5e64 100644 --- a/desktop/src/features/agents/lib/otherSetupAgent.test.mjs +++ b/desktop/src/features/agents/lib/otherSetupAgent.test.mjs @@ -1,7 +1,10 @@ import assert from "node:assert/strict"; import test from "node:test"; -import { isOtherSetupAgent } from "./otherSetupAgent.ts"; +import { + isOtherSetupAgent, + isOwnedAgentNotManagedOnDevice, +} from "./otherSetupAgent.ts"; const OWNER = "a".repeat(64); const AGENT = "b".repeat(64); @@ -20,7 +23,7 @@ test("fails closed while the local managed directory is unresolved", () => { ); }); -test("labels a viewer-owned non-local identity as another setup", () => { +test("labels a viewer-owned identity as not managed on this device", () => { assert.equal( isOtherSetupAgent({ agentDirectoriesReady: true, @@ -33,3 +36,38 @@ test("labels a viewer-owned non-local identity as another setup", () => { true, ); }); + +test("a locally managed provider is not labeled as another device", () => { + assert.equal( + isOtherSetupAgent({ + agentDirectoriesReady: true, + currentPubkey: OWNER, + managedAgents: [{ pubkey: AGENT, backend: { type: "provider" } }], + profileOwnerPubkey: OWNER, + pubkey: AGENT, + relayAgents: [], + }), + false, + ); +}); + +for (const [name, overrides, expected] of [ + ["owned absent key", {}, true], + ["loading local inventory", { localInventoryReady: false }, false], + ["exact local provider record", { isLocallyManaged: true }, false], + ["different owner", { ownerPubkey: "b".repeat(64) }, false], + ["unknown ownership", { ownerPubkey: null }, false], +]) { + test(`shared provenance: ${name}`, () => { + assert.equal( + isOwnedAgentNotManagedOnDevice({ + currentPubkey: "a".repeat(64), + ownerPubkey: "A".repeat(64), + localInventoryReady: true, + isLocallyManaged: false, + ...overrides, + }), + expected, + ); + }); +} diff --git a/desktop/src/features/agents/lib/otherSetupAgent.ts b/desktop/src/features/agents/lib/otherSetupAgent.ts index 63438a983f..f94215e1f3 100644 --- a/desktop/src/features/agents/lib/otherSetupAgent.ts +++ b/desktop/src/features/agents/lib/otherSetupAgent.ts @@ -1,6 +1,7 @@ import type { ManagedAgent, RelayAgent } from "@/shared/api/types"; import { normalizePubkey } from "@/shared/lib/pubkey"; +/** Owned identity absent from the loaded local inventory; not evidence of hosting location. */ export function isOtherSetupAgent({ agentDirectoriesReady, currentPubkey, @@ -32,8 +33,31 @@ export function isOtherSetupAgent({ )?.ownerPubkey; const ownerPubkey = profileOwnerPubkey ?? relayOwnerPubkey; + return isOwnedAgentNotManagedOnDevice({ + currentPubkey, + ownerPubkey, + localInventoryReady: agentDirectoriesReady, + isLocallyManaged: false, + }); +} + +/** Presentation provenance only; neither hosting location nor availability. */ +export function isOwnedAgentNotManagedOnDevice({ + currentPubkey, + ownerPubkey, + localInventoryReady, + isLocallyManaged, +}: { + currentPubkey?: string; + ownerPubkey?: string | null; + localInventoryReady: boolean; + isLocallyManaged: boolean; +}): boolean { return Boolean( - ownerPubkey && + localInventoryReady && + !isLocallyManaged && + currentPubkey && + ownerPubkey && normalizePubkey(ownerPubkey) === normalizePubkey(currentPubkey), ); } diff --git a/desktop/src/features/agents/ui/AgentHostMarker.tsx b/desktop/src/features/agents/ui/AgentHostMarker.tsx new file mode 100644 index 0000000000..4d42c8b634 --- /dev/null +++ b/desktop/src/features/agents/ui/AgentHostMarker.tsx @@ -0,0 +1,46 @@ +import { cn } from "@/shared/lib/cn"; +import { Cloud } from "lucide-react"; +import { + locationLabels, + type PresenceRun, +} from "@/features/presence/runPresence"; +import { OtherSetupAgentMarker } from "./OtherSetupAgentMarker"; + +/** Provenance never supplies location; only unexpired relay run leases do. */ +export function AgentHostMarker({ + runs, + now, + otherSetup = false, + className, + testId, +}: { + runs?: PresenceRun[]; + now: number; + otherSetup?: boolean; + className?: string; + testId?: string; +}) { + const labels = locationLabels(runs, now); + if (!labels.length) + return otherSetup ? ( + + ) : null; + const title = `Running on ${labels.join(", ")}`; + return ( + + + ); +} diff --git a/desktop/src/features/agents/ui/AgentsView.tsx b/desktop/src/features/agents/ui/AgentsView.tsx index 22b5326223..7c955bb4b6 100644 --- a/desktop/src/features/agents/ui/AgentsView.tsx +++ b/desktop/src/features/agents/ui/AgentsView.tsx @@ -1,4 +1,5 @@ import * as React from "react"; +import { HostsSection } from "@/features/hosts/HostsSection"; import { EllipsisVertical, OctagonX, Settings2 } from "lucide-react"; import { consumePendingSnapshotImport, @@ -218,6 +219,7 @@ export function AgentsView() { title="Agents" />
+ + ); +} diff --git a/desktop/src/features/agents/ui/OtherSetupAgentMarker.tsx b/desktop/src/features/agents/ui/OtherSetupAgentMarker.tsx index 19ef31bd75..2bd68473c7 100644 --- a/desktop/src/features/agents/ui/OtherSetupAgentMarker.tsx +++ b/desktop/src/features/agents/ui/OtherSetupAgentMarker.tsx @@ -1,8 +1,14 @@ import { Cloud } from "lucide-react"; +import { LiveAgentHostMarker } from "./LiveAgentHostMarker"; +import { + useKnownAgentPubkeys, + useIsOtherSetupAgent, +} from "../useKnownAgentPubkeys"; + import { cn } from "@/shared/lib/cn"; -const OTHER_SETUP_LABEL = "From another Buzz setup"; +const OTHER_SETUP_LABEL = "Not managed on this device"; export function OtherSetupAgentMarker({ className, @@ -23,3 +29,27 @@ export function OtherSetupAgentMarker({ ); } + +/** Connected marker for identity details; shares the app's directory subscriptions. */ +export function AgentManagementMarker({ + pubkey, + ownerPubkey, + className, + testId, +}: { + pubkey?: string | null; + ownerPubkey?: string | null; + className?: string; + testId?: string; +}) { + const show = useIsOtherSetupAgent(pubkey, ownerPubkey); + const knownAgents = useKnownAgentPubkeys(); + return pubkey && (show || knownAgents.has(pubkey.toLowerCase())) ? ( + + ) : null; +} diff --git a/desktop/src/features/agents/useKnownAgentPubkeys.test.mjs b/desktop/src/features/agents/useKnownAgentPubkeys.test.mjs new file mode 100644 index 0000000000..7c2c82f0bf --- /dev/null +++ b/desktop/src/features/agents/useKnownAgentPubkeys.test.mjs @@ -0,0 +1,73 @@ +import assert from "node:assert/strict"; +import { after, test } from "node:test"; +import { createElement } from "react"; +import { JSDOM } from "jsdom"; +import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; +import { + KnownAgentPubkeysProvider, + useIsOtherSetupAgent, +} from "./useKnownAgentPubkeys.tsx"; + +const dom = new JSDOM("", { + url: "http://localhost", +}); +Object.assign(globalThis, { + window: dom.window, + document: dom.window.document, + HTMLElement: dom.window.HTMLElement, + IS_REACT_ACT_ENVIRONMENT: true, +}); +after(() => dom.window.close()); + +test("provenance context follows exact local inventory and rejects failed cached reads", async () => { + const { act, renderHook, cleanup } = await import("@testing-library/react"); + const owner = "a".repeat(64), + remote = "b".repeat(64), + local = "c".repeat(64); + const client = new QueryClient({ + defaultOptions: { + queries: { enabled: false, retry: false, staleTime: Infinity }, + }, + }); + client.setQueryData(["identity"], { pubkey: owner }); + client.setQueryData( + ["managed-agents"], + [{ pubkey: local, status: "stopped" }], + ); + client.setQueryData( + ["relay-agents"], + [{ pubkey: remote, ownerPubkey: owner }], + ); + const wrapper = ({ children }) => + createElement( + QueryClientProvider, + { client }, + createElement(KnownAgentPubkeysProvider, null, children), + ); + const { result } = renderHook( + () => [ + useIsOtherSetupAgent(remote), + useIsOtherSetupAgent(local, owner), + useIsOtherSetupAgent("d".repeat(64), owner), + ], + { wrapper }, + ); + assert.deepEqual(result.current, [true, false, true]); + await act(async () => + client.setQueryData( + ["managed-agents"], + [{ pubkey: remote, status: "deployed" }], + ), + ); + assert.deepEqual(result.current, [false, true, true]); + await act(async () => { + client + .getQueryCache() + .find({ queryKey: ["managed-agents"] }) + .setState({ error: new Error("inventory unavailable"), status: "error" }); + await new Promise((resolve) => setTimeout(resolve, 5)); + }); + assert.deepEqual(result.current, [false, false, false]); + cleanup(); + client.clear(); +}); diff --git a/desktop/src/features/agents/useKnownAgentPubkeys.tsx b/desktop/src/features/agents/useKnownAgentPubkeys.tsx index e9fe7b9a9b..49f80054bc 100644 --- a/desktop/src/features/agents/useKnownAgentPubkeys.tsx +++ b/desktop/src/features/agents/useKnownAgentPubkeys.tsx @@ -5,10 +5,25 @@ import { useRelayAgentsQuery, } from "@/features/agents/hooks"; import { mergeKnownAgentPubkeys } from "@/features/agents/knownAgentPubkeys"; -import { useStableSet } from "@/shared/hooks/useStableReference"; +import { useStableMap, useStableSet } from "@/shared/hooks/useStableReference"; +import { useIdentityQuery } from "@/shared/api/hooks"; +import { normalizePubkey } from "@/shared/lib/pubkey"; +import { isAgentDirectoryReady } from "./lib/agentAutocompleteEligibility"; +import { isOwnedAgentNotManagedOnDevice } from "./lib/otherSetupAgent"; const EMPTY_KNOWN_AGENT_PUBKEYS: ReadonlySet = new Set(); +const AgentManagementContext = React.createContext<{ + currentPubkey?: string; + localInventoryReady: boolean; + localPubkeys: ReadonlySet; + relayOwners: ReadonlyMap; +}>({ + localInventoryReady: false, + localPubkeys: new Set(), + relayOwners: new Map(), +}); + const KnownAgentPubkeysContext = React.createContext>( EMPTY_KNOWN_AGENT_PUBKEYS, ); @@ -39,8 +54,36 @@ export function KnownAgentPubkeysProvider({ }: { children: React.ReactNode; }) { - const managedAgents = useManagedAgentsQuery().data; - const relayAgents = useRelayAgentsQuery().data; + const managedQuery = useManagedAgentsQuery(); + const relayQuery = useRelayAgentsQuery(); + const currentPubkey = useIdentityQuery().data?.pubkey; + const managedAgents = managedQuery.data; + const relayAgents = relayQuery.data; + const localPubkeys = useStableSet( + new Set( + (managedAgents ?? []).map((agent) => normalizePubkey(agent.pubkey)), + ), + ); + const relayOwners = useStableMap( + new Map( + isAgentDirectoryReady(relayQuery) + ? (relayAgents ?? []).map((agent) => [ + normalizePubkey(agent.pubkey), + agent.ownerPubkey, + ]) + : [], + ), + ); + const localInventoryReady = isAgentDirectoryReady(managedQuery); + const management = React.useMemo( + () => ({ + currentPubkey, + localInventoryReady, + localPubkeys, + relayOwners, + }), + [currentPubkey, localInventoryReady, localPubkeys, relayOwners], + ); const merged = React.useMemo( () => mergeKnownAgentPubkeys(managedAgents, relayAgents), @@ -50,7 +93,9 @@ export function KnownAgentPubkeysProvider({ return ( - {children} + + {children} + ); } @@ -82,3 +127,21 @@ export function KnownAgentPubkeysProvider({ export function useKnownAgentPubkeys(): ReadonlySet { return React.useContext(KnownAgentPubkeysContext); } + +/** Shared provenance without per-row query observers; exact keys, never personas. */ +export function useIsOtherSetupAgent( + pubkey?: string | null, + profileOwnerPubkey?: string | null, +): boolean { + const state = React.useContext(AgentManagementContext); + const key = normalizePubkey(pubkey ?? ""); + return ( + Boolean(key) && + isOwnedAgentNotManagedOnDevice({ + currentPubkey: state.currentPubkey, + ownerPubkey: profileOwnerPubkey ?? state.relayOwners.get(key), + localInventoryReady: state.localInventoryReady, + isLocallyManaged: state.localPubkeys.has(key), + }) + ); +} diff --git a/desktop/src/features/channels/ui/ChannelScreenHeader.tsx b/desktop/src/features/channels/ui/ChannelScreenHeader.tsx index 3ccabdf753..e61979efc2 100644 --- a/desktop/src/features/channels/ui/ChannelScreenHeader.tsx +++ b/desktop/src/features/channels/ui/ChannelScreenHeader.tsx @@ -14,6 +14,7 @@ import { ProfileAvatarWithStatus, scaleProfileAvatarStatusGeometry, } from "@/features/profile/ui/ProfileAvatarWithStatus"; +import { AgentManagementMarker } from "@/features/agents/ui/OtherSetupAgentMarker"; import { UserProfilePopover } from "@/features/profile/ui/UserProfilePopover"; import { Button } from "@/shared/ui/button"; import type { Channel, PresenceStatus } from "@/shared/api/types"; @@ -194,9 +195,17 @@ export function ChannelScreenHeader({ ) : undefined } statusBadge={ - + <> + + {!isGroupDm && activeDmParticipant ? ( + + ) : null} + } title={activeChannelTitle} transparentChrome={transparentChrome} diff --git a/desktop/src/features/channels/ui/MembersSidebarMemberCard.tsx b/desktop/src/features/channels/ui/MembersSidebarMemberCard.tsx index c6f32d5fc9..ebefb737ca 100644 --- a/desktop/src/features/channels/ui/MembersSidebarMemberCard.tsx +++ b/desktop/src/features/channels/ui/MembersSidebarMemberCard.tsx @@ -18,7 +18,7 @@ import { getManagedAgentPrimaryActionLabel, isManagedAgentActive, } from "@/features/agents/lib/managedAgentControlActions"; -import { OtherSetupAgentMarker } from "@/features/agents/ui/OtherSetupAgentMarker"; +import { LiveAgentHostMarker } from "@/features/agents/ui/LiveAgentHostMarker"; import { ProfileAvatar } from "@/features/profile/ui/ProfileAvatar"; import { PresenceDot } from "@/features/presence/ui/PresenceBadge"; import { @@ -198,11 +198,11 @@ export function MembersSidebarMemberCard({
- {showOtherSetupMarker ? ( - - ) : null} + ) : (
diff --git a/desktop/src/features/communities/useCommunityInit.ts b/desktop/src/features/communities/useCommunityInit.ts index c565ee0f7b..9062097b38 100644 --- a/desktop/src/features/communities/useCommunityInit.ts +++ b/desktop/src/features/communities/useCommunityInit.ts @@ -49,6 +49,9 @@ import type { Community } from "./types"; * community starts with a clean slate. Hook-managed singletons * (e.g. ChannelMuteSyncManager, ChannelSectionSyncManager) are * destroyed via effect cleanup and do not need entries here. + * Host publication has no decrypted singleton cache: its scoped pending + * journal contains signed ciphertext only. hostNativeDrain is a data-free + * native-work barrier and deliberately survives switching/keyed remounts. * See AGENTS.md "Community Switching" for the full contract. */ async function resetCommunityState({ diff --git a/desktop/src/features/hosts/HostsSection.tsx b/desktop/src/features/hosts/HostsSection.tsx new file mode 100644 index 0000000000..9409d0d4df --- /dev/null +++ b/desktop/src/features/hosts/HostsSection.tsx @@ -0,0 +1,104 @@ +import { Laptop, LockKeyhole, RefreshCw } from "lucide-react"; +import { Button } from "@/shared/ui/button"; +import { activeRuns } from "@/features/presence/runPresence"; +import { usePresenceRuns } from "@/features/presence/usePresenceRuns"; +import { HOST_REFRESH, useHostSnapshot } from "./useHostRegistration"; + +export function HostsSection() { + const snapshot = useHostSnapshot(); + const presence = usePresenceRuns(snapshot.rows.map((row) => row.host)); + return ( +
+
+
+

+ Your hosts +

+

+ + Only visible to you in this community. +

+
+ +
+ {snapshot.error ? ( +

+ Host sync failed: {snapshot.error}. Registration requires a relay with + host support. +

+ ) : null} + {!snapshot.rows.length ? ( +

+ {snapshot.checking + ? "Checking this computer and its registration…" + : "No relay-confirmed hosts to show."} +

+ ) : null} +
+ {snapshot.rows.map((row) => ( +
+
+
+ +

+ {row.report?.name ?? "Registered host"} +

+
+ + {presence.isError || !presence.data + ? "Presence unknown" + : activeRuns(presence.data[row.host], presence.now).length + ? "Online" + : "Offline"} + +
+

+ {row.host === snapshot.local?.host + ? `This computer · Public name: Desktop ${row.host.slice(0, 8)} · ` + : ""} + {row.report + ? `${row.report.os} · ${row.report.arch} · Desktop ${row.report.launcher_version}` + : "Waiting for a capability profile"} +

+ {row.report ? ( +
    + {row.report.runtimes.map((runtime) => ( +
  • + {runtime.label} + + {runtime.availability.replaceAll("_", " ")} ·{" "} + {runtime.auth_status.replaceAll("_", " ")} + +
  • + ))} +
+ ) : null} +

+ {row.event + ? `Profile updated ${new Date(row.event.created_at * 1000).toLocaleTimeString()}. ` + : ""} + Registration only; remote Start is not enabled. +

+
+ ))} +
+

+ Capabilities update only when they change and remain visible offline. + Online means Desktop is renewing its three-minute presence lease, not + that an agent can start. History is checked across all pages before + publishing registration or capability changes. +

+
+ ); +} diff --git a/desktop/src/features/hosts/history.test.mjs b/desktop/src/features/hosts/history.test.mjs new file mode 100644 index 0000000000..1a2f7ecfd2 --- /dev/null +++ b/desktop/src/features/hosts/history.test.mjs @@ -0,0 +1,108 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import { fetchHostHistory } from "./history.ts"; +import { fixture } from "./hostTestFixtures.mjs"; + +const filter = { kinds: [50000], limit: 1000 }; +const event = (id, created_at = 100) => ({ + id: id.toString(16).padStart(64, "0"), + created_at, +}); + +test("keyset exhausts more than two full pages of same-second events", async () => { + const rows = Array.from({ length: 2501 }, (_, i) => event(i + 1)); + const calls = []; + const result = await fetchHostHistory( + async (f) => { + calls.push(f); + return rows + .filter((e) => !f.before_id || e.id > f.before_id) + .slice(0, f.limit) + .reverse(); + }, + filter, + () => {}, + ); + assert.deepEqual(result, rows); + assert.equal(calls.length, 3); + assert.equal(calls[1].until, 100); + assert.equal(calls[1].before_id, rows[999].id); +}); + +test("exact full page needs an empty successor, not an incomplete-history error", async () => { + let calls = 0; + const result = await fetchHostHistory( + async (f) => { + calls++; + return f.before_id + ? [] + : Array.from({ length: 1000 }, (_, i) => event(i + 1)); + }, + filter, + () => {}, + ); + assert.equal(result.length, 1000); + assert.equal(calls, 2); +}); + +test("old server ignoring the cursor fails closed rather than loops or suppresses a write", async () => { + const page = Array.from({ length: 1000 }, (_, i) => event(i + 1)); + await assert.rejects( + fetchHostHistory( + async () => [...page], + filter, + () => {}, + ), + /cursor/, + ); +}); + +test("failure or cancellation on a later page discards the partial history", async () => { + for (const cancel of [false, true]) { + let active = true; + let calls = 0; + await assert.rejects( + fetchHostHistory( + async () => { + calls++; + if (calls === 2) { + if (!cancel) throw new Error("offline"); + active = false; + return []; + } + return Array.from({ length: 1000 }, (_, i) => event(i + 1)); + }, + filter, + () => { + if (!active) throw new Error("cancelled"); + }, + ), + /offline|cancelled/, + ); + assert.equal(calls, 2); + } +}); + +test("registration and profile reconciliation both exceed 1000, preserving newest valid profile", async () => { + const f = fixture(); + await f.run(); + const registration = f.events[0]; + const profile = f.events[1]; + // All bindings target this host, as can happen after repeated older-client + // registration attempts. Newest profiles include unreadable ciphertext. + for (let i = 1; i <= 1100; i++) { + f.events.push({ ...registration, id: event(i + 500000).id }); + f.events.push({ + ...profile, + id: event(i + 600000).id, + created_at: 101, + decoded: undefined, + }); + } + f.setNow(103); + f.writes.length = 0; + const result = await f.run(); + assert.equal(result.rows.length, 1); + assert.equal(result.rows[0].event.id, profile.id); + assert.equal(f.writes.length, 0); +}); diff --git a/desktop/src/features/hosts/history.ts b/desktop/src/features/hosts/history.ts new file mode 100644 index 0000000000..b0c691240a --- /dev/null +++ b/desktop/src/features/hosts/history.ts @@ -0,0 +1,50 @@ +import type { RelayEvent } from "@/shared/api/types"; +import type { RelaySubscriptionFilter } from "@/shared/api/relayClientShared"; + +/** HTTP /query keyset extension; do not send this through a NIP-01 socket. */ +export type HostHistoryFilter = RelaySubscriptionFilter & { + before_id?: string; +}; + +/** Exhaust exact, primary-backed host pages before making a publication decision. */ +export async function fetchHostHistory( + fetchPage: (filter: HostHistoryFilter) => Promise, + filter: HostHistoryFilter, + check: () => void, +): Promise { + const events: RelayEvent[] = []; + const seen = new Set(); + let cursor: RelayEvent | undefined; + for (;;) { + check(); + const page = await fetchPage({ + ...filter, + ...(cursor ? { until: cursor.created_at, before_id: cursor.id } : {}), + }); + check(); + if (page.length > filter.limit || filter.limit <= 0) + throw new Error("Invalid host history page"); + // HTTP result order is not part of the client contract. Sort using the + // database's DESC timestamp / ASC event-ID keyset order. + page.sort( + (a, b) => + b.created_at - a.created_at || (a.id < b.id ? -1 : a.id > b.id ? 1 : 0), + ); + for (const event of page) { + if ( + !/^[0-9a-f]{64}$/.test(event.id) || + !Number.isSafeInteger(event.created_at) || + event.created_at < 0 || + seen.has(event.id) || + (cursor && + (event.created_at > cursor.created_at || + (event.created_at === cursor.created_at && event.id <= cursor.id))) + ) + throw new Error("Host history cursor did not advance"); + seen.add(event.id); + events.push(event); + } + if (page.length < filter.limit) return events; + cursor = page[page.length - 1]; + } +} diff --git a/desktop/src/features/hosts/hostNativeDrain.test.mjs b/desktop/src/features/hosts/hostNativeDrain.test.mjs new file mode 100644 index 0000000000..fc117e2a69 --- /dev/null +++ b/desktop/src/features/hosts/hostNativeDrain.test.mjs @@ -0,0 +1,113 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import { JSDOM } from "jsdom"; +import React, { act } from "react"; +import { createRoot } from "react-dom/client"; +import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; +import { useHostRegistration } from "./useHostRegistration.ts"; +import { hostNativeDrain } from "./hostNativeDrain.ts"; +import { hostQueryKey } from "./registration.ts"; +import { fixture } from "./hostTestFixtures.mjs"; + +const flush = () => new Promise((resolve) => setImmediate(resolve)); +for (const switchKind of ["identity", "community"]) { + test(`actual registration hook waits across keyed ${switchKind} + query-provider remount`, async (t) => { + const saved = Object.fromEntries( + ["window", "document", "IS_REACT_ACT_ENVIRONMENT"].map((key) => [ + key, + globalThis[key], + ]), + ); + const dom = new JSDOM("
", { + url: "https://fixture.invalid", + }); + Object.assign(globalThis, { + window: dom.window, + document: dom.window.document, + IS_REACT_ACT_ENVIRONMENT: true, + }); + const root = createRoot(document.getElementById("root")); + const calls = []; + const releases = []; + const f = fixture(); + dom.window.__TAURI_INTERNALS__ = { + invoke: (command, args) => { + assert.equal( + command, + "get_local_host", + "cancelled mounts must not connect or publish", + ); + calls.push(args.expectedOwner); + return new Promise((resolve) => + releases.push(async () => resolve(await f.bridge.local())), + ); + }, + }; + t.after(async () => { + await act(async () => root.unmount()); + for (const release of releases) await release(); + await hostNativeDrain.wait(); + await new Promise((resolve) => setTimeout(resolve, 10)); + dom.window.close(); + for (const [key, value] of Object.entries(saved)) { + if (value === undefined) delete globalThis[key]; + else globalThis[key] = value; + } + }); + const first = new QueryClient({ + defaultOptions: { queries: { gcTime: Infinity } }, + }); + const second = new QueryClient({ + defaultOptions: { queries: { gcTime: Infinity } }, + }); + const owner = "a".repeat(64), + relay = "wss://fixture.invalid"; + const nextOwner = switchKind === "identity" ? "c".repeat(64) : owner; + const nextRelay = + switchKind === "community" ? "wss://other.invalid" : relay; + function Publisher({ owner, relay }) { + useHostRegistration(owner, relay); + return null; + } + const tree = (key, client, owner, relay) => + React.createElement( + QueryClientProvider, + { key, client }, + React.createElement(Publisher, { key, owner, relay }), + ); + await act(async () => { + root.render(tree("old", first, owner, relay)); + await flush(); + }); + assert.deepEqual(calls, [owner]); + assert.ok(first.getQueryData(hostQueryKey(relay, owner))); + await act(async () => { + root.render(tree("new", second, nextOwner, nextRelay)); + await flush(); + }); + assert.deepEqual( + calls, + [owner], + "new native work cannot overtake old native discovery", + ); + assert.equal(first.getQueryData(hostQueryKey(relay, owner)), undefined); + assert.equal( + second.getQueryData(hostQueryKey(nextRelay, nextOwner)), + undefined, + ); + await act(async () => { + await releases[0](); + await flush(); + }); + assert.deepEqual(calls, [owner, nextOwner]); + await act(async () => root.unmount()); + await releases[1](); + await hostNativeDrain.wait(); + assert.equal( + second.getQueryData(hostQueryKey(nextRelay, nextOwner)), + undefined, + ); + first.clear(); + second.clear(); + }); +} diff --git a/desktop/src/features/hosts/hostNativeDrain.ts b/desktop/src/features/hosts/hostNativeDrain.ts new file mode 100644 index 0000000000..5f83a05113 --- /dev/null +++ b/desktop/src/features/hosts/hostNativeDrain.ts @@ -0,0 +1,15 @@ +/** + * Data-free native-work barrier shared across keyed React remounts. Only a + * Promise survives: no owner, relay, event, report, or query cache. This + * deliberately must NOT reset on community switching (that would lose the + * outstanding native work); decrypted state remains in the scoped component. + */ +export const hostNativeDrain = { + pending: Promise.resolve() as Promise, + wait(): Promise { + return this.pending; + }, + hold(drain: Promise): void { + this.pending = Promise.allSettled([this.pending, drain]).then(() => {}); + }, +}; diff --git a/desktop/src/features/hosts/hostTestFixtures.mjs b/desktop/src/features/hosts/hostTestFixtures.mjs new file mode 100644 index 0000000000..b7fedfe4c9 --- /dev/null +++ b/desktop/src/features/hosts/hostTestFixtures.mjs @@ -0,0 +1,135 @@ +import { reconcileHost, HOST_KIND, HOST_NAMESPACE } from "./registration.ts"; + +import { createHostPublicationJournal } from "./pendingPublication.ts"; + +export function memoryStorage() { + const entries = new Map(); + return { + entries, + getItem: (key) => entries.get(key) ?? null, + setItem: (key, value) => entries.set(key, value), + removeItem: (key) => entries.delete(key), + }; +} + +export function fixture({ legacy = false } = {}) { + let now = 100; + const owner = "a".repeat(64), + host = "b".repeat(64); + const payload = { + v: legacy ? 1 : 2, + name: "computer", + os: "macos", + arch: "aarch64", + launcher_version: "test", + runtimes: [ + { + id: "one", + label: "One", + availability: "available", + auth_status: "unknown", + }, + ], + accepts_start: false, + }; + const storage = memoryStorage(); + const journal = createHostPublicationJournal( + "wss://fixture.invalid", + owner, + storage, + ); + const decoded = new Map(); + const events = []; + const writes = []; + let count = 0; + let active = true; + const make = (label, extra = []) => ({ + id: String(now * 1000 + ++count).padStart(64, "0"), + kind: HOST_KIND, + pubkey: label === "registration" ? owner : host, + content: "random-ciphertext", + sig: "f".repeat(128), + created_at: now, + tags: [ + ["L", HOST_NAMESPACE], + ["l", label, HOST_NAMESPACE], + ["p", owner], + ["x", host], + ...extra, + ], + }); + const bridge = { + local: async () => ({ host, report: payload }), + registration: async () => make("registration"), + report: async (registration) => { + const event = { + ...make(legacy ? "report" : "profile", [ + ["e", registration.id], + ...(legacy ? [["valid_until", String(now + 180)]] : []), + ]), + decoded: structuredClone(payload), + }; + decoded.set(event.id, event.decoded); + return event; + }, + inspect: async (registration) => { + if (registration.pubkey !== owner) + throw new Error("foreign registration"); + return host; + }, + decode: async (_registration, report) => + report.decoded ?? decoded.get(report.id), + }; + const relay = { + fetchEvents: async (filter) => + events + .filter( + (e) => + (!filter.authors || filter.authors.includes(e.pubkey)) && + (filter.until === undefined || + e.created_at < filter.until || + (e.created_at === filter.until && + (!filter.before_id || e.id > filter.before_id))) && + Object.entries(filter) + .filter(([k]) => k.startsWith("#")) + .every(([k, values]) => + e.tags.some( + (t) => t[0] === k.slice(1) && values.includes(t[1]), + ), + ), + ) + .sort((a, b) => b.created_at - a.created_at || a.id.localeCompare(b.id)) + .slice(0, filter.limit), + publishEvent: async (event) => { + writes.push(event); + if (!events.some((stored) => stored.id === event.id)) events.push(event); + }, + }; + const run = (overrides = {}) => + reconcileHost({ + owner, + relay, + bridge, + journal, + active: () => active, + now: () => now, + ...overrides, + }); + return { + run, + journal, + storage, + decoded, + relay, + bridge, + writes, + events, + payload, + setNow: (t) => { + now = t; + }, + stop: () => { + active = false; + }, + }; +} diff --git a/desktop/src/features/hosts/pendingPublication.test.mjs b/desktop/src/features/hosts/pendingPublication.test.mjs new file mode 100644 index 0000000000..56542d4239 --- /dev/null +++ b/desktop/src/features/hosts/pendingPublication.test.mjs @@ -0,0 +1,319 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import { fixture, memoryStorage } from "./hostTestFixtures.mjs"; +import { + canonicalHostEvent, + createHostPublicationJournal, +} from "./pendingPublication.ts"; + +async function uncertain(f, stage) { + const publish = f.relay.publishEvent; + let held; + f.relay.publishEvent = async (event) => { + if ( + event.tags.some((t) => t[1] === (stage === "report" ? "profile" : stage)) + ) { + held = event; + throw new Error("uncertain"); + } + return publish(event); + }; + await assert.rejects(f.run(), /uncertain/); + f.relay.publishEvent = publish; + return held; +} + +for (const stage of ["registration", "report"]) { + test(`${stage} journal stores only canonical ciphertext before first send and survives repeated rejection`, async () => { + const f = fixture(); + f.payload.name = "PRIVATE-HOSTNAME"; + const held = await uncertain(f, stage); + const raw = [...f.storage.entries.values()][0]; + assert.ok(!raw.includes("PRIVATE-HOSTNAME")); + assert.ok(!raw.includes("decoded")); + assert.ok(!raw.includes("runtimes")); + assert.equal(Object.keys(held).length, 7); + f.relay.publishEvent = async (event) => { + assert.deepEqual(event, held); + assert.equal([...f.storage.entries.values()][0], raw); + throw new Error("rejected again"); + }; + f.bridge.registration = f.bridge.report = async () => + assert.fail("must not rebuild"); + await assert.rejects(f.run(), /rejected again/); + assert.equal([...f.storage.entries.values()][0], raw); + }); + + for (const mode of ["failed", "capped", "unreadable"]) { + test(`pending ${stage} recovery waits for all ${mode} history before any send`, async () => { + const f = fixture(); + await uncertain(f, stage); + const raw = [...f.storage.entries.values()][0]; + const fetch = f.relay.fetchEvents; + f.relay.fetchEvents = async (filter) => { + if (filter["#l"][0] === "report") { + if (mode === "failed") throw new Error("history failed"); + const report = await f.bridge.report(f.journal.load().registration); + if (mode === "capped") return Array(1000).fill(report); + return [{ ...report, tags: [] }]; + } + return fetch(filter); + }; + f.relay.publishEvent = async () => + assert.fail("send after unsafe history"); + await assert.rejects( + f.run(), + /history failed|cursor did not advance|Cannot establish/, + ); + assert.equal([...f.storage.entries.values()][0], raw); + }); + } + + test(`switch during pending ${stage} native validation fences recovery and preserves journal`, async () => { + const f = fixture(); + await uncertain(f, stage); + const raw = [...f.storage.entries.values()][0]; + const operation = stage === "registration" ? "inspect" : "decode"; + const native = f.bridge[operation]; + f.bridge[operation] = async (...args) => { + const result = await native(...args); + f.stop(); + return result; + }; + f.relay.publishEvent = async () => assert.fail("stale send"); + await assert.rejects(f.run(), /cancelled/); + assert.equal([...f.storage.entries.values()][0], raw); + }); + + test(`crash after saving ${stage} but before send recovers solely from persisted signed event`, async () => { + const f = fixture(); + const registration = canonicalHostEvent(await f.bridge.registration()); + const report = + stage === "report" + ? canonicalHostEvent(await f.bridge.report(registration)) + : undefined; + if (report) f.events.push(registration); + f.journal.save({ v: 1, registration, ...(report ? { report } : {}) }); + const restarted = createHostPublicationJournal( + "wss://fixture.invalid", + "a".repeat(64), + f.storage, + ); + f.bridge.registration = async () => + assert.fail("rebuilding pending registration"); + if (report) + f.bridge.report = async () => assert.fail("rebuilding pending report"); + await f.run({ journal: restarted }); + assert.deepEqual(f.writes[0], report ?? registration); + assert.equal(restarted.load(), undefined); + }); +} + +for (const raw of [ + "", + "{", + "null", + "[]", + '{"v":2}', + '{"v":1,"registration":{}}', +]) { + test(`malformed journal ${JSON.stringify(raw)} is not discarded or treated as absence`, async () => { + const f = fixture(); + await uncertain(f, "registration"); + const key = [...f.storage.entries.keys()][0]; + f.storage.entries.set(key, raw); + f.relay.publishEvent = async () => assert.fail("must fail closed"); + await assert.rejects(f.run(), /pending publication/); + assert.equal(f.storage.entries.get(key), raw); + }); +} + +for (const field of ["content", "sig", "pubkey"]) { + for (const stage of ["registration", "report"]) { + test(`native validation rejects shape-valid tampered ${stage} ${field} without sending or clearing`, async () => { + const f = fixture(); + const held = await uncertain(f, stage); + const [key, raw] = [...f.storage.entries][0]; + const pending = JSON.parse(raw); + pending[stage][field] = + field === "content" + ? "tampered-ciphertext" + : "e".repeat(field === "sig" ? 128 : 64); + f.storage.entries.set(key, JSON.stringify(pending)); + // Simulated native cryptographic boundary: native receives and rejects + // the changed signed fields. JS shape validation must not replace it. + let validations = 0; + const operation = stage === "registration" ? "inspect" : "decode"; + const original = f.bridge[operation]; + f.bridge[operation] = async (...args) => { + validations++; + if (args.at(-1)[field] !== held[field]) + throw new Error("native verification failed"); + return original(...args); + }; + f.relay.publishEvent = async () => assert.fail("tampered send"); + await assert.rejects(f.run(), /native verification failed/); + assert.equal(validations, 1); + assert.equal(f.storage.entries.has(key), true); + }); + } +} + +test("foreign local host and missing report binding fail closed on recovery", async () => { + const f = fixture(); + await uncertain(f, "report"); + f.bridge.local = async () => ({ host: "c".repeat(64), report: f.payload }); + await assert.rejects(f.run(), /different local host/); + f.bridge.local = async () => ({ host: "b".repeat(64), report: f.payload }); + f.events.length = 0; + await assert.rejects(f.run(), /registration is missing/); + assert.ok(f.journal.load()); +}); + +test("identity/community scopes are independent and switching back restores the exact pending event", async () => { + const f = fixture(); + const held = await uncertain(f, "registration"); + const otherOwner = createHostPublicationJournal( + "wss://fixture.invalid", + "c".repeat(64), + f.storage, + ); + const otherRelay = createHostPublicationJournal( + "wss://other.invalid", + "a".repeat(64), + f.storage, + ); + assert.equal(otherOwner.load(), undefined); + assert.equal(otherRelay.load(), undefined); + const registration = await f.bridge.registration(); + otherRelay.save({ v: 1, registration }); + otherOwner.save({ + v: 1, + registration: { ...registration, pubkey: "c".repeat(64) }, + }); + await f.run({ + journal: createHostPublicationJournal( + "wss://fixture.invalid", + "a".repeat(64), + f.storage, + ), + }); + assert.deepEqual(f.writes[0], held); + assert.ok(otherRelay.load()); + assert.ok(otherOwner.load()); + // A copied foreign slot is not authority: the expected-owner native bridge + // rejects the registration, even though its stored shape is valid. + await assert.rejects(f.run({ journal: otherOwner }), /foreign registration/); +}); + +for (const failure of ["read", "write", "silent-write"]) { + test(`${failure} storage failure blocks first send`, async () => { + const f = fixture(); + const storage = memoryStorage(); + if (failure === "read") + storage.getItem = () => { + throw new Error("private diagnostic"); + }; + else + storage.setItem = () => { + if (failure === "write") throw new Error("private diagnostic"); + }; + const journal = createHostPublicationJournal( + "wss://fixture.invalid", + "a".repeat(64), + storage, + ); + await assert.rejects( + f.run({ journal }), + (e) => + /pending publication/.test(e.message) && !e.message.includes("private"), + ); + assert.equal(f.writes.length, 0); + }); +} + +test("clear failure after accepted send preserves pending state for read-based recovery", async () => { + const f = fixture(); + const remove = f.storage.removeItem; + f.storage.removeItem = () => { + throw new Error("private diagnostic"); + }; + await assert.rejects(f.run(), /pending publication/); + assert.equal(f.writes.length, 1); + assert.ok(f.journal.load()); + f.storage.removeItem = remove; + await f.run(); + assert.equal(f.writes.length, 2); + assert.equal(f.journal.load(), undefined); +}); + +test("unconfirmed durable profile retries the exact event even after many lease windows", async () => { + const f = fixture(); + const held = await uncertain(f, "report"); + f.setNow(10000); + const snapshot = await f.run(); + assert.equal(f.writes.length, 2); + assert.deepEqual(f.writes[1], held); + assert.equal(snapshot.rows[0].event.id, held.id); + assert.equal(f.journal.load(), undefined); +}); + +test("pending older report cannot replace newer relay-confirmed capabilities", async () => { + const f = fixture(); + const held = await uncertain(f, "report"); + f.setNow(110); + f.payload.name = "newer"; + const newer = await f.bridge.report(f.events[0]); + f.events.push(newer); + const snapshot = await f.run(); + assert.deepEqual(f.writes.at(-1), held); + assert.equal(snapshot.rows[0].event.id, newer.id); + assert.equal(snapshot.rows[0].report.name, "newer"); +}); + +for (const [name, mutate] of [ + [ + "extra plaintext field", + (p) => { + p.registration.decoded = { name: "PRIVATE-HOSTNAME" }; + }, + ], + [ + "wrong timestamp", + (p) => { + p.registration.created_at = -1; + }, + ], + [ + "malformed tag", + (p) => { + p.registration.tags = [null]; + }, + ], + [ + "wrong signature shape", + (p) => { + p.registration.sig = "bad"; + }, + ], + [ + "oversized journal", + (p) => { + p.registration.content = "x".repeat(1024 * 1024); + }, + ], +]) { + test(`${name} in stored journal fails closed before native recovery`, async () => { + const f = fixture(); + await uncertain(f, "registration"); + const [key, raw] = [...f.storage.entries][0]; + const pending = JSON.parse(raw); + mutate(pending); + f.storage.entries.set(key, JSON.stringify(pending)); + f.bridge.inspect = async () => + assert.fail("malformed journal passed to native"); + await assert.rejects(f.run(), /pending publication/); + assert.equal(f.writes.length, 0); + assert.ok(f.storage.entries.has(key)); + }); +} diff --git a/desktop/src/features/hosts/pendingPublication.ts b/desktop/src/features/hosts/pendingPublication.ts new file mode 100644 index 0000000000..6256c11500 --- /dev/null +++ b/desktop/src/features/hosts/pendingPublication.ts @@ -0,0 +1,123 @@ +import type { RelayEvent } from "@/shared/api/types"; + +/** Only canonical signed, encrypted events; never decoded host metadata or keys. */ +export type PendingHostPublication = { + v: 1; + registration: RelayEvent; + report?: RelayEvent; +}; +export type HostPublicationJournal = { + load(): PendingHostPublication | undefined; + save(pending: PendingHostPublication): void; + clear(): void; +}; + +const FIELDS = ["id", "pubkey", "kind", "content", "created_at", "tags", "sig"]; +const HEX = /^[0-9a-f]{64}$/; +const MAX_BYTES = 1024 * 1024; +const invalid = () => + new Error("Host pending publication is unavailable or invalid"); + +/** Strip transport/native adornments before saving or sending a signed event. */ +export function canonicalHostEvent(event: RelayEvent): RelayEvent { + return { + id: event.id, + pubkey: event.pubkey, + kind: event.kind, + content: event.content, + created_at: event.created_at, + tags: event.tags.map((tag) => [...tag]), + sig: event.sig, + }; +} + +function eventShape(value: unknown): value is RelayEvent { + if (!value || typeof value !== "object" || Array.isArray(value)) return false; + const e = value as RelayEvent; + return ( + Object.keys(e).length === FIELDS.length && + Object.keys(e).every((key) => FIELDS.includes(key)) && + typeof e.id === "string" && + HEX.test(e.id) && + typeof e.pubkey === "string" && + HEX.test(e.pubkey) && + e.kind === 50000 && + typeof e.content === "string" && + e.content.length > 0 && + Number.isSafeInteger(e.created_at) && + e.created_at >= 0 && + typeof e.sig === "string" && + /^[0-9a-f]{128}$/.test(e.sig) && + Array.isArray(e.tags) && + e.tags.every( + (tag) => Array.isArray(tag) && tag.every((s) => typeof s === "string"), + ) + ); +} + +function parse(raw: string): PendingHostPublication { + if (raw.length * 2 > MAX_BYTES) throw invalid(); + const value = JSON.parse(raw); + if ( + value?.v !== 1 || + Object.keys(value).some( + (key) => !["v", "registration", "report"].includes(key), + ) || + !eventShape(value.registration) || + ("report" in value && !eventShape(value.report)) + ) + throw invalid(); + return value; +} + +/** + * Load-bearing localStorage journal, scoped by exact relay URL and signer. + * Storage/corruption errors fail closed, never become absence. Unlike caches it + * must not be evicted or fall back to memory on quota failure. Native inspection + * and decryption remain authoritative: shape checks are NOT signature checks. + */ +export function createHostPublicationJournal( + relay: string, + owner: string, + storage?: Pick, +): HostPublicationJournal { + const getStorage = () => storage ?? localStorage; + const key = `buzz-host-pending.v1:${JSON.stringify([relay, owner])}`; + return { + load() { + try { + const raw = getStorage().getItem(key); + return raw === null ? undefined : parse(raw); + } catch { + throw invalid(); + } + }, + save(pending) { + try { + // Refuse overwriting an unresolved or malformed attempt. + if (getStorage().getItem(key) !== null) throw invalid(); + const raw = JSON.stringify({ + v: 1, + registration: canonicalHostEvent(pending.registration), + ...(pending.report + ? { report: canonicalHostEvent(pending.report) } + : {}), + }); + parse(raw); + getStorage().setItem(key, raw); + if (getStorage().getItem(key) !== raw) throw invalid(); + } catch { + // Never include diagnostics which could echo payloads or private paths. + throw invalid(); + } + }, + clear() { + try { + getStorage().removeItem(key); + if (getStorage().getItem(key) !== null) throw invalid(); + } catch { + throw invalid(); + } + }, + }; +} diff --git a/desktop/src/features/hosts/projection.test.mjs b/desktop/src/features/hosts/projection.test.mjs new file mode 100644 index 0000000000..3ee48cb90b --- /dev/null +++ b/desktop/src/features/hosts/projection.test.mjs @@ -0,0 +1,266 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import { fixture } from "./hostTestFixtures.mjs"; +import { validateHostReport } from "./reportValidation.ts"; + +for (const label of ["registration", "report"]) { + test(`newer invalid ${label} does not erase valid remembered state`, async () => { + const f = fixture(); + const first = await f.run(); + f.writes.length = 0; + const valid = f.events[label === "registration" ? 0 : 1]; + f.events.push({ + ...valid, + id: "f".repeat(64), + created_at: 101, + invalid: true, + }); + const operation = label === "registration" ? "inspect" : "decode"; + const original = f.bridge[operation]; + f.bridge[operation] = async (...args) => { + if (args.at(-1).invalid) throw new Error("invalid encrypted record"); + return original(...args); + }; + f.setNow(110); + const result = await f.run(); + assert.equal(result.rows[0].registration.id, first.rows[0].registration.id); + assert.equal(result.rows[0].event.id, first.rows[0].event.id); + assert.equal(f.writes.length, 0); + }); +} + +test("latest valid registration uses timestamp DESC, id ASC independent of arrival", async () => { + const f = fixture(); + const registration = await f.bridge.registration(); + const low = { ...registration, id: "1".repeat(64), created_at: 101 }; + const high = { ...registration, id: "2".repeat(64), created_at: 101 }; + f.events.push(high, registration, low); + f.events.push(await f.bridge.report(low)); + const result = await f.run(); + assert.equal(result.rows[0].registration.id, low.id); + assert.equal(f.writes.length, 0); +}); + +test("latest valid report uses timestamp DESC, id ASC and keeps expired capabilities", async () => { + const f = fixture(); + const registration = await f.bridge.registration(); + const report = await f.bridge.report(registration); + const low = { ...report, id: "1".repeat(64), created_at: 101 }; + const high = { ...report, id: "2".repeat(64), created_at: 101 }; + f.events.push(registration, high, report, low); + let result = await f.run(); + assert.equal(result.rows[0].event.id, low.id); + // A remembered nonlocal host remains durable when its lease expires. + f.bridge.local = async () => ({ host: "c".repeat(64), report: f.payload }); + const other = { + ...registration, + id: "3".repeat(64), + tags: registration.tags.map((t) => + t[0] === "x" ? ["x", "c".repeat(64)] : t, + ), + }; + f.events.push(other); + f.bridge.inspect = async (event) => event.tags.find((t) => t[0] === "x")[1]; + // Keep the local fixture's renewed lease fresh so only remembered state is tested. + const otherReport = { + ...report, + pubkey: "c".repeat(64), + id: "4".repeat(64), + created_at: 300, + tags: report.tags.map((t) => + t[0] === "x" + ? ["x", "c".repeat(64)] + : t[0] === "e" + ? ["e", other.id] + : t[0] === "valid_until" + ? ["valid_until", "480"] + : t, + ), + }; + f.events.push(otherReport); + f.setNow(300); + result = await f.run(); + assert.equal( + result.rows.find((row) => row.host === "b".repeat(64)).event.id, + low.id, + ); + assert.equal(f.writes.length, 0); +}); + +test("incomplete report history blocks all event construction/publication", async () => { + const f = fixture(); + const registration = await f.bridge.registration(); + f.events.push( + registration, + ...Array(1000).fill(await f.bridge.report(registration)), + ); + f.bridge.registration = f.bridge.report = async () => + assert.fail("construction after incomplete history"); + await assert.rejects(f.run(), /cursor did not advance/); + assert.equal(f.writes.length, 0); +}); + +test("unreadable report history is not mistaken for no report", async () => { + const f = fixture(); + await f.run(); + f.writes.length = 0; + f.bridge.decode = async () => { + throw new Error("decode failed"); + }; + await assert.rejects(f.run(), /Cannot establish host capabilities/); + assert.equal(f.writes.length, 0); +}); + +const invalidPayloads = [ + [ + "unknown availability", + (r) => { + r.runtimes[0].availability = "ready"; + }, + ], + [ + "unknown auth status", + (r) => { + r.runtimes[0].auth_status = "ready"; + }, + ], + [ + "duplicate runtime", + (r) => { + r.runtimes.push({ ...r.runtimes[0] }); + }, + ], + [ + "unknown field", + (r) => { + r.diagnostic = "not allowed"; + }, + ], + [ + "runtime extra field", + (r) => { + r.runtimes[0].path = "not allowed"; + }, + ], + [ + "oversized text bytes", + (r) => { + r.name = "é".repeat(129); + }, + ], + [ + "control text", + (r) => { + r.name = "bad\u0085text"; + }, + ], + [ + "empty text", + (r) => { + r.name = ""; + }, + ], + [ + "unsupported version", + (r) => { + r.v = 3; + }, + ], + [ + "start enabled", + (r) => { + r.accepts_start = true; + }, + ], + [ + "oversized catalog", + (r) => { + r.runtimes = Array(129).fill(r.runtimes[0]); + }, + ], + [ + "missing runtime id", + (r) => { + delete r.runtimes[0].id; + }, + ], +]; +for (const [name, mutate] of invalidPayloads) { + test(`${name} is skipped in history and cannot be published from discovery`, async () => { + const f = fixture(); + await f.run(); + f.writes.length = 0; + const invalid = structuredClone(f.events[1]); + invalid.decoded = structuredClone(f.decoded.get(invalid.id)); + invalid.id = "f".repeat(64); + invalid.created_at++; + mutate(invalid.decoded); + assert.throws(() => validateHostReport(invalid.decoded), /Invalid host/); + f.events.push(invalid); + await f.run(); + assert.equal(f.writes.length, 0); + mutate(f.payload); + await assert.rejects(f.run(), /Invalid host/); + assert.equal(f.writes.length, 0); + }); +} + +test("all real native runtime statuses and empty catalogs are supported", () => { + const f = fixture(); + for (const availability of [ + "available", + "adapter_missing", + "adapter_outdated", + "cli_missing", + "not_installed", + ]) { + for (const auth_status of [ + "logged_in", + "logged_out", + "config_invalid", + "not_applicable", + "unknown", + ]) { + f.payload.runtimes[0] = { + id: "one", + label: "One", + availability, + auth_status, + }; + validateHostReport(f.payload); + } + } + f.payload.runtimes = []; + validateHostReport(f.payload); +}); + +test("a newer duplicate registration reuses unchanged capabilities bound to the older registration", async () => { + const f = fixture(); + const first = await f.run(); + f.writes.length = 0; + const newer = { ...f.events[0], id: "f".repeat(64), created_at: 101 }; + f.events.push(newer); + f.setNow(110); + const result = await f.run(); + assert.equal(result.rows[0].registration.id, newer.id); + assert.equal(result.rows[0].event.id, first.rows[0].event.id); + assert.equal(f.writes.length, 0); +}); + +test("a report with unknown registration cannot supersede a verified host report", async () => { + const f = fixture(); + const first = await f.run(); + f.writes.length = 0; + const invalid = { + ...f.events[1], + id: "f".repeat(64), + created_at: 101, + tags: f.events[1].tags.map((tag) => + tag[0] === "e" ? ["e", "unknown"] : tag, + ), + }; + f.events.push(invalid); + const result = await f.run(); + assert.equal(result.rows[0].event.id, first.rows[0].event.id); + assert.equal(f.writes.length, 0); +}); diff --git a/desktop/src/features/hosts/registration.test.mjs b/desktop/src/features/hosts/registration.test.mjs new file mode 100644 index 0000000000..60c5bc6458 --- /dev/null +++ b/desktop/src/features/hosts/registration.test.mjs @@ -0,0 +1,249 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import { needsReport, isFresh } from "./registration.ts"; +import { fixture } from "./hostTestFixtures.mjs"; + +test("register once; an unchanged current host does not append on restart/reconnect", async () => { + const f = fixture(); + const first = await f.run(); + assert.equal(f.writes.length, 2); + assert.equal(first.rows.length, 1); + const second = await f.run(); + assert.equal(f.writes.length, 2); + assert.equal(second.rows[0].registration.id, first.rows[0].registration.id); +}); + +test("unchanged profiles do not renew across multiple lease windows", async () => { + const f = fixture(); + await f.run(); + f.setNow(220); + await f.run(); + assert.equal(f.writes.length, 2); + f.setNow(240); + await f.run(); + assert.equal(f.writes.length, 2); + f.setNow(10000); + await f.run(); + assert.equal(f.writes.length, 2); +}); + +test("capability changes publish a report without re-registering", async () => { + const f = fixture(); + await f.run(); + f.payload.runtimes[0].availability = "cli_missing"; + f.setNow(110); + await f.run(); + assert.equal(f.writes.length, 3); +}); + +test("ciphertext, property order, and runtime ordering are not change detectors", async () => { + const f = fixture(); + const state = await f.run(); + const current = { + accepts_start: false, + ...f.payload, + runtimes: [...f.payload.runtimes].reverse(), + }; + assert.equal(needsReport(state.rows[0], current, 101), false); +}); + +test("failed relay read does not blindly append", async () => { + const f = fixture(); + f.relay.fetchEvents = async () => { + throw new Error("offline"); + }; + await assert.rejects(f.run(), /offline/); + assert.equal(f.writes.length, 0); +}); + +test("failed registration acknowledgement prevents reports and success", async () => { + const f = fixture(); + f.relay.publishEvent = async () => { + throw new Error("rejected"); + }; + await assert.rejects(f.run(), /rejected/); + assert.equal(f.events.length, 0); +}); + +test("accepted registration is reused after failed report acknowledgement", async () => { + const f = fixture(); + const publish = f.relay.publishEvent; + f.relay.publishEvent = async (event) => { + if (event.tags.some((t) => t[0] === "l" && t[1] === "profile")) + throw new Error("report rejected"); + await publish(event); + }; + await assert.rejects(f.run(), /report rejected/); + f.relay.publishEvent = publish; + await f.run(); + assert.equal(f.writes.length, 2); +}); + +test("identity/relay switch fences delayed native results from publication", async () => { + const f = fixture(); + const local = f.bridge.local; + f.bridge.local = async () => { + f.stop(); + return local(); + }; + await assert.rejects(f.run(), /cancelled/); + assert.equal(f.writes.length, 0); +}); + +test("malformed or foreign registration fails closed", async () => { + const f = fixture(); + await f.run(); + f.bridge.inspect = async () => { + throw new Error("foreign registration"); + }; + await assert.rejects(f.run(), /Cannot establish local host registration/); + assert.equal(f.writes.length, 2); +}); + +test("legacy report freshness remains bounded", async () => { + const f = fixture({ legacy: true }); + const state = await f.run(); + const event = state.rows[0].event; + assert.equal(isFresh(event, 279), true); + assert.equal(isFresh(event, 280), false); + assert.equal(isFresh(undefined, 100), false); +}); + +test("fresh process reads correct relay state and performs zero publication calls", async () => { + const original = fixture(); + await original.run(); + const restarted = fixture(); + restarted.events.push(...structuredClone(original.events)); + for (const [id, report] of original.decoded) + restarted.decoded.set(id, report); + // No in-memory publication cache from the original process survives. + restarted.bridge.registration = async () => { + throw new Error("unexpected registration"); + }; + restarted.bridge.report = async () => { + throw new Error("unexpected report"); + }; + for (const trigger of ["restart", "reconnect", "manual refresh"]) { + restarted.setNow(110); + const result = await restarted.run(); + assert.equal(result.rows.length, 1, trigger); + assert.equal(restarted.writes.length, 0, trigger); + } +}); + +test("failed report read never appends to an existing registration", async () => { + const f = fixture(); + await f.run(); + f.writes.length = 0; + const fetch = f.relay.fetchEvents; + f.relay.fetchEvents = async (filter) => { + if (filter["#l"][0] === "report") throw new Error("read failed"); + return fetch(filter); + }; + f.setNow(1000); + await assert.rejects(f.run(), /read failed/); + assert.equal(f.writes.length, 0); +}); + +test("a same-second capability change waits instead of creating ambiguous heads", async () => { + const f = fixture(); + await f.run(); + f.payload.name = "changed"; + await assert.rejects(f.run(), /current second/); + assert.equal(f.writes.length, 2); + f.setNow(101); + await f.run(); + assert.equal(f.writes.length, 3); + await f.run(); + assert.equal(f.writes.length, 3); +}); + +test("a future profile does not cause needless publication", async () => { + const f = fixture(); + const state = await f.run(); + state.rows[0].event.created_at = 150; + assert.equal(needsReport(state.rows[0], f.payload, 100), false); +}); + +test("incomplete registration history fails closed without publishing", async () => { + const f = fixture(); + const event = await f.bridge.registration(); + f.events.push(...Array(1000).fill(event)); + await assert.rejects(f.run(), /cursor did not advance/); + assert.equal(f.writes.length, 0); +}); + +test("failed remembered-host read prevents even a new local registration", async () => { + const f = fixture(); + await f.run(); + f.writes.length = 0; + f.bridge.local = async () => ({ host: "c".repeat(64), report: f.payload }); + let constructions = 0; + f.bridge.registration = async () => { + constructions++; + throw new Error("must not construct"); + }; + const fetch = f.relay.fetchEvents; + f.relay.fetchEvents = async (filter) => { + if (filter["#l"][0] === "report") throw new Error("history unavailable"); + return fetch(filter); + }; + await assert.rejects(f.run(), /history unavailable/); + assert.equal(constructions, 0); + assert.equal(f.writes.length, 0); +}); + +for (const label of ["registration", "profile"]) { + test(`accepted ${label} with lost ACK is reused after reconnect`, async () => { + const f = fixture(); + const publish = f.relay.publishEvent; + f.relay.publishEvent = async (event) => { + await publish(event); + if (event.tags.some((t) => t[0] === "l" && t[1] === label)) + throw new Error("ACK lost"); + }; + await assert.rejects(f.run(), /ACK lost/); + f.relay.publishEvent = publish; + const result = await f.run(); + assert.equal(result.rows.length, 1); + assert.equal(f.writes.length, 2); + assert.equal(f.events.length, 2); + }); +} + +for (const operation of ["registration", "report", "inspect", "decode"]) { + test(`identity switch during ${operation} prevents later publication`, async () => { + const f = fixture(); + await f.run(); + f.writes.length = 0; + // Force the native stage under test to be reached. + if (operation === "registration") f.events.length = 0; + if (operation === "report") { + f.setNow(240); + f.payload.name = "Changed"; + } + const original = f.bridge[operation]; + f.bridge[operation] = async (...args) => { + const result = await original(...args); + f.stop(); + return result; + }; + await assert.rejects(f.run(), /cancelled/); + assert.equal(f.writes.length, 0); + }); +} + +test("legacy report is upgraded once to a durable profile", async () => { + const legacy = fixture({ legacy: true }); + await legacy.run(); + const current = fixture(); + current.events.push(...structuredClone(legacy.events)); + for (const [id, report] of legacy.decoded) current.decoded.set(id, report); + current.setNow(300); + await current.run(); + assert.equal(current.writes.length, 1); + assert.equal(current.writes[0].tags.find((t) => t[0] === "l")[1], "profile"); + current.setNow(10000); + await current.run(); + assert.equal(current.writes.length, 1); +}); diff --git a/desktop/src/features/hosts/registration.ts b/desktop/src/features/hosts/registration.ts new file mode 100644 index 0000000000..5aef62c1f6 --- /dev/null +++ b/desktop/src/features/hosts/registration.ts @@ -0,0 +1,307 @@ +import type { RelayEvent } from "@/shared/api/types"; +import { fetchHostHistory, type HostHistoryFilter } from "./history"; +import { + canonicalHostEvent, + type HostPublicationJournal, +} from "./pendingPublication"; +import { validateHostReport } from "./reportValidation"; + +export const HOST_KIND = 50000; +export const HOST_NAMESPACE = "buzz.host.v1"; +export type HostReport = { + v: number; + name: string; + os: string; + arch: string; + launcher_version: string; + runtimes: { + id: string; + label: string; + availability: string; + auth_status: string; + }[]; + accepts_start: boolean; +}; +export type LocalHost = { host: string; report: HostReport }; +export type HostRow = { + host: string; + registration: RelayEvent; + event?: RelayEvent; + report?: HostReport; +}; +export type HostSnapshot = { + rows: HostRow[]; + local?: LocalHost; + error?: string; + checking: boolean; +}; +export type HostBridge = { + local(): Promise; + registration(): Promise; + report(registration: RelayEvent): Promise; + inspect(registration: RelayEvent): Promise; + decode(registration: RelayEvent, report: RelayEvent): Promise; +}; +export type HostRelay = { + fetchEvents(filter: HostHistoryFilter): Promise; + publishEvent(event: RelayEvent): Promise; +}; +export const hostQueryKey = ( + relay: string | undefined, + owner: string | undefined, +) => ["hosts", relay, owner] as const; +export function tag(event: RelayEvent, name: string) { + return event.tags.find((t) => t[0] === name)?.[1]; +} +function sameSignedEvent(a: RelayEvent, b: RelayEvent) { + try { + return ( + JSON.stringify(canonicalHostEvent(a)) === + JSON.stringify(canonicalHostEvent(b)) + ); + } catch { + return false; + } +} +function newest(events: RelayEvent[]) { + return [...events].sort((a, b) => { + // Native inspection is authoritative; tolerate malformed transport objects + // here so one invalid record cannot prevent inspecting the valid candidates. + const timestamp = (e: RelayEvent) => + Number.isSafeInteger(e?.created_at) ? e.created_at : 0; + const id = (e: RelayEvent) => (typeof e?.id === "string" ? e.id : ""); + return ( + timestamp(b) - timestamp(a) || + (id(a) < id(b) ? -1 : id(a) > id(b) ? 1 : 0) + ); + }); +} +export function isFresh(event: RelayEvent | undefined, now: number) { + return ( + !!event && + event.created_at <= now + 30 && + Number(tag(event, "valid_until")) > now + ); +} +export function needsReport( + previous: HostRow | undefined, + current: HostReport, + _now: number, +) { + // Compare structured data, not randomized NIP-44 ciphertext or object key order. + const canonical = (r: HostReport) => + JSON.stringify([ + r.v, + r.name, + r.os, + r.arch, + r.launcher_version, + r.accepts_start, + [...r.runtimes] + .sort((a, b) => a.id.localeCompare(b.id)) + .map((x) => [x.id, x.label, x.availability, x.auth_status]), + ]); + return ( + !previous?.report || + !previous.event || + tag(previous.event, "l") !== "profile" || + canonical(previous.report) !== canonical(current) + ); +} + +/** One serialized read-before-write pass. Failed reads never become empty state. */ +export async function reconcileHost(args: { + owner: string; + relay: HostRelay; + bridge: HostBridge; + journal: HostPublicationJournal; + active: () => boolean; + now: () => number; +}): Promise { + const { owner, relay, bridge, journal, now } = args; + const check = () => { + if (!args.active()) throw new Error("Host registration cancelled"); + }; + const filter = (label: string): HostHistoryFilter => ({ + kinds: [HOST_KIND], + "#p": [owner], + "#L": [HOST_NAMESPACE], + "#l": [label], + limit: 1000, + }); + check(); + const local = await bridge.local(); + check(); + validateHostReport(local.report); + const pending = journal.load(); + let pendingReport: HostReport | undefined; + if (pending) { + // Disk is untrusted. Do not use cached plaintext or trust a stored host ID. + if ((await bridge.inspect(pending.registration)) !== local.host) + throw new Error("Pending publication belongs to a different local host"); + check(); + if (pending.report) { + pendingReport = await bridge.decode(pending.registration, pending.report); + check(); + validateHostReport(pendingReport); + } + } + const registrations = await fetchHostHistory( + (page) => relay.fetchEvents(page), + { ...filter("registration"), authors: [owner] }, + check, + ); + check(); + const rows = new Map(); + const bindings = new Map< + string, + { host: string; registration: RelayEvent } + >(); + let unreadableRegistration = false; + for (const registration of newest(registrations)) { + let host: string; + try { + host = await bridge.inspect(registration); + } catch { + // A newer invalid record must not hide an older verified binding. + // IPC errors are not typed: absence is unsafe if no local binding survives. + unreadableRegistration = true; + check(); + continue; + } + check(); + bindings.set(registration.id, { host, registration }); + if (!rows.has(host)) rows.set(host, { host, registration }); + } + if (unreadableRegistration && !rows.has(local.host)) + throw new Error("Cannot establish local host registration from history"); + const pendingRegistrationKnown = + pending && bindings.has(pending.registration.id); + if (pending?.report && !pendingRegistrationKnown) + throw new Error("Pending report registration is missing from history"); + if (pending && !pending.report && !pendingRegistrationKnown) { + // Include the pending host in the read set, but do not return/promote this + // row until the exact registration has received an accepted ACK below. + bindings.set(pending.registration.id, { + host: local.host, + registration: pending.registration, + }); + if (!rows.has(local.host)) + rows.set(local.host, { + host: local.host, + registration: pending.registration, + }); + } + let pendingReportKnown = false; + // Complete every history read before constructing or publishing anything. + // In particular, an unreadable remembered host must not cause a new local + // registration to be appended on an otherwise failed reconciliation pass. + for (const row of rows.values()) { + const events = await fetchHostHistory( + (page) => relay.fetchEvents(page), + { + ...filter("report"), + "#l": ["report", "profile"], + authors: [row.host], + "#x": [row.host], + }, + check, + ); + check(); + if (row.host === local.host && pending?.report) + pendingReportKnown = events.some( + (event) => pending.report && sameSignedEvent(event, pending.report), + ); + for (const event of newest(events)) { + let report: HostReport; + try { + // Duplicate durable bindings can exist from older clients. Reuse the + // latest valid report for this owner+host even if it references an older + // binding; a newer registration must not force duplicate capabilities. + const binding = bindings.get(tag(event, "e") ?? ""); + if (!binding || binding.host !== row.host) + throw new Error("Unknown host report binding"); + report = await bridge.decode(binding.registration, event); + validateHostReport(report); + } catch { + check(); + continue; + } + check(); + row.event = event; + row.report = report; + break; + } + // An empty completed history is known absence; unreadable history is not. + if (events.length && !row.report) + throw new Error("Cannot establish host capabilities from history"); + } + let own = rows.get(local.host); + if (pending) { + const event = pending.report ?? pending.registration; + if (!(pending.report ? pendingReportKnown : pendingRegistrationKnown)) { + check(); + // The relay rejects expired reports, but an earlier ingest may still + // commit. Do not abandon the ID or mint a replacement: wait for history. + if ( + pending.report && + tag(pending.report, "l") === "report" && + Number(tag(pending.report, "valid_until")) <= now() + ) + throw new Error( + "Unconfirmed host report expired; waiting for relay history", + ); + // A completed primary read can overtake an old EVENT's commit. Re-send + // its EXACT signed fields, never a new randomized event. Relay event-ID + // uniqueness does the rest, regardless of which attempt commits first. + await relay.publishEvent(event); + check(); + } + journal.clear(); + if ( + pending.report && + pendingReport && + own && + (!own.event || + newest([own.event, pending.report])[0].id === pending.report.id) + ) { + own.event = pending.report; + own.report = pendingReport; + } + // Legacy reports are recovered by exact ID before upgrading to a durable profile. + } + if (!own) { + const registration = canonicalHostEvent(await bridge.registration()); + check(); + if ((await bridge.inspect(registration)) !== local.host) + throw new Error("Local host identity changed"); + check(); + journal.save({ v: 1, registration }); + check(); + await relay.publishEvent(registration); + check(); + journal.clear(); + own = { host: local.host, registration }; + rows.set(local.host, own); + } + if (needsReport(own, local.report, now())) { + // Kind 50000 uses (timestamp DESC, id ASC). Two changed reports in one + // second could select the old payload forever. Retry at the next tick + // rather than mint randomized ciphertext repeatedly at a tied timestamp. + if (own.event && own.event.created_at >= now()) + throw new Error("Host changed within the current second; retry shortly"); + const event = canonicalHostEvent(await bridge.report(own.registration)); + check(); + const report = await bridge.decode(own.registration, event); + check(); + validateHostReport(report); + journal.save({ v: 1, registration: own.registration, report: event }); + check(); + await relay.publishEvent(event); + check(); + journal.clear(); + own.event = event; + own.report = report; + } + return { rows: [...rows.values()], local, checking: false }; +} diff --git a/desktop/src/features/hosts/registrationLifecycle.test.mjs b/desktop/src/features/hosts/registrationLifecycle.test.mjs new file mode 100644 index 0000000000..49434fdb7a --- /dev/null +++ b/desktop/src/features/hosts/registrationLifecycle.test.mjs @@ -0,0 +1,189 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import { createHostRegistrationLifecycle } from "./registrationLifecycle.ts"; +import { fixture } from "./hostTestFixtures.mjs"; + +const flush = () => new Promise((resolve) => setImmediate(resolve)); +function deferred() { + let resolve; + const promise = new Promise((r) => { + resolve = r; + }); + return { promise, resolve }; +} +function lifecycle(f, extra = {}) { + const snapshots = []; + const errors = []; + let connections = 0; + let disconnections = 0; + const controller = createHostRegistrationLifecycle({ + owner: "a".repeat(64), + bridge: f.bridge, + journal: f.journal, + now: () => 100, + connect: () => { + connections++; + return { + ...f.relay, + disconnect: () => { + disconnections++; + }, + }; + }, + checking: () => {}, + success: (s) => snapshots.push(s), + failure: (e) => errors.push(e), + ...extra, + }); + return { + ...controller, + snapshots, + errors, + counts: () => ({ connections, disconnections }), + }; +} + +test("focus/online/manual/timer bursts coalesce into a serialized read-before-write retry", async () => { + const f = fixture(); + const gate = deferred(); + const local = f.bridge.local; + let calls = 0; + f.bridge.local = async () => { + calls++; + await gate.promise; + return local(); + }; + const controller = lifecycle(f); + const first = controller.refresh(); + await flush(); + for (let i = 0; i < 10; i++) assert.equal(controller.refresh(), first); + assert.equal(calls, 1); + gate.resolve(); + await first; + assert.equal(calls, 2); + assert.equal(f.writes.length, 2); + assert.equal(controller.snapshots.length, 2); + assert.deepEqual(controller.counts(), { connections: 2, disconnections: 2 }); + await controller.stop(); +}); + +for (const operation of [ + "local", + "registration", + "report", + "inspect", + "decode", +]) { + test(`unmount during ${operation} fences publication, snapshots, errors and queued refresh`, async () => { + const f = fixture(); + const gate = deferred(); + const entered = deferred(); + const original = f.bridge[operation]; + f.bridge[operation] = async (...args) => { + entered.resolve(); + await gate.promise; + return original(...args); + }; + const controller = lifecycle(f); + const first = controller.refresh(); + await entered.promise; + const before = f.writes.length; + void controller.refresh(); + const stopped = controller.stop(); + gate.resolve(); + await Promise.all([first, stopped]); + await controller.refresh(); + assert.equal(f.writes.length, before); + assert.equal(controller.snapshots.length, 0); + assert.equal(controller.errors.length, 0); + assert.equal(controller.counts().connections, 1); + }); +} + +test("identity effect replacement waits for previous native work to drain", async () => { + const f = fixture(); + const gate = deferred(); + const local = f.bridge.local; + f.bridge.local = async () => { + await gate.promise; + return local(); + }; + const old = lifecycle(f); + void old.refresh(); + await flush(); + const next = lifecycle(fixture(), { after: old.stop() }); + const pending = next.refresh(); + await flush(); + assert.equal(next.counts().connections, 0); + gate.resolve(); + await pending; + assert.equal(f.writes.length, 0); + assert.equal(old.snapshots.length, 0); + assert.equal(next.snapshots.length, 1); + await next.stop(); +}); + +test("failed refresh preserves last confirmed snapshot and a later retry recovers without duplicates", async () => { + const f = fixture(); + const fetch = f.relay.fetchEvents; + let fail = false; + f.relay.fetchEvents = async (...args) => { + if (fail) throw new Error("offline"); + return fetch(...args); + }; + const controller = lifecycle(f); + await controller.refresh(); + fail = true; + await controller.refresh(); + assert.equal(controller.snapshots.length, 1); + assert.equal(controller.errors.length, 1); + fail = false; + await controller.refresh(); + assert.equal(controller.snapshots.length, 2); + assert.equal(f.writes.length, 2); + assert.equal(controller.counts().disconnections, 3); + await controller.stop(); +}); + +test("unmount during publication suppresses stale success and prevents the following report", async () => { + const f = fixture(); + const gate = deferred(); + const entered = deferred(); + const publish = f.relay.publishEvent; + f.relay.publishEvent = async (event) => { + await publish(event); + entered.resolve(); + await gate.promise; + }; + const controller = lifecycle(f); + const first = controller.refresh(); + await entered.promise; + const stopped = controller.stop(); + gate.resolve(); + await Promise.all([first, stopped]); + assert.equal(controller.snapshots.length, 0); + assert.equal(controller.errors.length, 0); + assert.equal(f.writes.length, 1); + f.relay.publishEvent = publish; + const next = lifecycle(f); + await next.refresh(); + assert.equal(f.writes.length, 2); + await next.stop(); +}); + +test("refresh at the completion microtask boundary is not lost", async () => { + const f = fixture(); + let successes = 0; + const controller = lifecycle(f, { + success: () => { + if (++successes === 1) + queueMicrotask(() => { + void controller.refresh(); + }); + }, + }); + await controller.refresh(); + assert.equal(successes, 2); + assert.equal(f.writes.length, 2); + await controller.stop(); +}); diff --git a/desktop/src/features/hosts/registrationLifecycle.ts b/desktop/src/features/hosts/registrationLifecycle.ts new file mode 100644 index 0000000000..b194fa0ec8 --- /dev/null +++ b/desktop/src/features/hosts/registrationLifecycle.ts @@ -0,0 +1,69 @@ +import type { HostPublicationJournal } from "./pendingPublication"; +import { + reconcileHost, + type HostBridge, + type HostRelay, + type HostSnapshot, +} from "./registration"; + +/** One effect's cancellable publisher. Refresh bursts coalesce, never overlap. */ +export function createHostRegistrationLifecycle(args: { + owner: string; + bridge: HostBridge; + journal: HostPublicationJournal; + connect: () => HostRelay & { disconnect(): void }; + now: () => number; + checking: () => void; + success: (snapshot: HostSnapshot) => void; + failure: (error: unknown) => void; + after?: Promise; +}) { + let active = true; + let pending = false; + let running: Promise | undefined; + let client: ReturnType | undefined; + const drain = async () => { + await args.after; + while (active && pending) { + pending = false; + args.checking(); + try { + client = args.connect(); + const snapshot = await reconcileHost({ + owner: args.owner, + relay: client, + bridge: args.bridge, + journal: args.journal, + active: () => active, + now: args.now, + }); + if (active) args.success(snapshot); + } catch (error) { + if (active) args.failure(error); + } finally { + client?.disconnect(); + client = undefined; + } + } + }; + const refresh = (): Promise => { + if (!active) return running ?? Promise.resolve(); + pending = true; + if (!running) + running = drain().finally(() => { + running = undefined; + // A refresh may arrive after drain returns but before this microtask. + if (active && pending) return refresh(); + }); + return running; + }; + return { + refresh, + stop(): Promise { + active = false; + pending = false; + client?.disconnect(); + return running ?? Promise.resolve(); + }, + }; +} diff --git a/desktop/src/features/hosts/reportValidation.ts b/desktop/src/features/hosts/reportValidation.ts new file mode 100644 index 0000000000..21da2d27ac --- /dev/null +++ b/desktop/src/features/hosts/reportValidation.ts @@ -0,0 +1,74 @@ +import type { HostReport } from "./registration"; + +const availability = new Set([ + "available", + "adapter_missing", + "adapter_outdated", + "cli_missing", + "not_installed", +]); +const authStatus = new Set([ + "logged_in", + "logged_out", + "config_invalid", + "not_applicable", + "unknown", +]); +const encoder = new TextEncoder(); +function text(value: unknown): value is string { + return ( + typeof value === "string" && + value.length > 0 && + encoder.encode(value).length <= 256 && + !Array.from(value).some((c) => { + const code = c.charCodeAt(0); + return code < 32 || (code >= 127 && code <= 159); + }) + ); +} +function object(value: unknown): value is Record { + return typeof value === "object" && value !== null && !Array.isArray(value); +} +function fields(value: Record, allowed: string[]) { + return Object.keys(value).every((key) => allowed.includes(key)); +} + +/** Validate the decoded IPC payload before comparison, display or publication. */ +export function validateHostReport( + value: unknown, +): asserts value is HostReport { + if ( + !object(value) || + !fields(value, [ + "v", + "name", + "os", + "arch", + "launcher_version", + "runtimes", + "accepts_start", + ]) || + (value.v !== 1 && value.v !== 2) || + value.accepts_start !== false || + ![value.name, value.os, value.arch, value.launcher_version].every(text) || + !Array.isArray(value.runtimes) || + value.runtimes.length > 128 + ) + throw new Error("Invalid host report payload"); + const ids = new Set(); + for (const runtime of value.runtimes) { + if ( + !object(runtime) || + !fields(runtime, ["id", "label", "availability", "auth_status"]) || + !text(runtime.id) || + !text(runtime.label) || + !text(runtime.availability) || + !availability.has(runtime.availability) || + !text(runtime.auth_status) || + !authStatus.has(runtime.auth_status) || + ids.has(runtime.id) + ) + throw new Error("Invalid host runtime payload"); + ids.add(runtime.id); + } +} diff --git a/desktop/src/features/hosts/transport.test.mjs b/desktop/src/features/hosts/transport.test.mjs new file mode 100644 index 0000000000..f06a1af4ac --- /dev/null +++ b/desktop/src/features/hosts/transport.test.mjs @@ -0,0 +1,362 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import { ReadOnlyRelayClient } from "../../shared/api/readOnlyRelayClient.ts"; +import { createHostPublicationJournal } from "./pendingPublication.ts"; +import { reconcileHost } from "./registration.ts"; +import { fixture } from "./hostTestFixtures.mjs"; + +const flush = () => new Promise((resolve) => setImmediate(resolve)); +function transport(t, { history, publish, connect } = {}) { + const previousWindow = globalThis.window; + const sent = []; + const closed = []; + const timers = new Map(); + let timerId = 0; + let channel; + const emit = (...frames) => + channel.onmessage( + frames.map((frame) => ({ type: "Text", data: JSON.stringify(frame) })), + ); + globalThis.window = { + setTimeout: (callback) => { + timers.set(++timerId, callback); + return timerId; + }, + clearTimeout: (id) => timers.delete(id), + __TAURI_INTERNALS__: { + transformCallback: () => 1, + invoke: async (command, args) => { + if (command === "plugin:websocket|connect") { + channel = args.onMessage; + if (connect) return connect(); + setImmediate(() => emit(["AUTH", "challenge"])); + return 7; + } + if (command === "create_auth_event") + return JSON.stringify({ id: "auth" }); + if (command === "plugin:websocket|disconnect") { + closed.push(args.id); + return; + } + if (command === "plugin:websocket|send") { + const frame = JSON.parse(args.message.data); + sent.push(frame); + if (frame[0] === "AUTH") emit(["OK", "auth", true, ""]); + if (frame[0] === "REQ") await history?.(frame, emit); + if (frame[0] === "EVENT") { + if (publish) await publish(frame, emit); + else emit(["OK", frame[1].id, true, ""]); + } + return; + } + throw new Error(`Unexpected IPC command: ${command}`); + }, + }, + }; + const client = new ReadOnlyRelayClient("wss://fixture.invalid"); + t.after(() => { + client.disconnect(); + globalThis.window = previousWindow; + }); + return { + client, + sent, + closed, + timers, + emit, + native: (frame) => channel.onmessage(frame), + }; +} +const run = (f, client, journal = f.journal) => + reconcileHost({ + owner: "a".repeat(64), + relay: client, + bridge: f.bridge, + journal, + active: () => true, + now: () => 100, + }); + +for (const stage of ["registration", "report"]) { + for (const mode of [ + "closed", + "closed-then-eose", + "partial-closed-then-eose", + "timeout", + "close", + "error", + "send-failed", + ]) { + test(`${stage} history ${mode} blocks all publication through the actual client`, async (t) => { + const f = fixture(); + const registration = await f.bridge.registration(); + const report = await f.bridge.report(registration); + let reached = false; + const wire = transport(t, { + history: ([, id, filter], emit) => { + if (filter["#l"][0] !== stage) { + emit(["EVENT", id, registration], ["EOSE", id]); + return; + } + reached = true; + if (mode.startsWith("partial")) + emit([ + "EVENT", + id, + stage === "registration" ? registration : report, + ]); + if (mode.includes("closed")) + emit(["CLOSED", id, "error: host history unavailable"]); + if (mode.endsWith("eose")) emit(["EOSE", id]); + if (mode === "close" || mode === "error") + wire.native({ type: mode === "close" ? "Close" : "Error" }); + if (mode === "send-failed") throw new Error("send failed"); + }, + }); + const rejected = assert.rejects( + run(f, wire.client), + /closed|disconnected|Timed out|send failed/, + ); + while (!reached) await flush(); + if (mode === "timeout") + for (const callback of [...wire.timers.values()]) callback(); + await rejected; + assert.equal(wire.sent.filter((frame) => frame[0] === "EVENT").length, 0); + }); + } +} + +test("EOSE with complete empty history permits publication only after accepted ACK", async (t) => { + const f = fixture(); + let acknowledge; + const wire = transport(t, { + history: ([, id], emit) => emit(["EOSE", id]), + publish: ([, event], emit) => { + acknowledge = () => emit(["OK", event.id, true, ""]); + }, + }); + let completed = false; + const result = run(f, wire.client).then((value) => { + completed = true; + return value; + }); + while (!acknowledge) await flush(); + assert.equal(completed, false); + assert.equal(wire.sent.filter((frame) => frame[0] === "EVENT").length, 1); + acknowledge(); + await flush(); + assert.equal(completed, false); + assert.equal(wire.sent.filter((frame) => frame[0] === "EVENT").length, 2); + acknowledge(); + assert.equal((await result).rows.length, 1); +}); + +test("negative registration ACK blocks report construction and success", async (t) => { + const f = fixture(); + f.bridge.report = async () => + assert.fail("report before accepted registration"); + const wire = transport(t, { + history: ([, id], emit) => emit(["EOSE", id]), + publish: ([, event], emit) => emit(["OK", event.id, false, "rejected"]), + }); + await assert.rejects(run(f, wire.client), /rejected/); + assert.equal(wire.sent.filter((frame) => frame[0] === "EVENT").length, 1); +}); + +test("disconnect during delayed native connect closes the orphan and cannot resurrect a publisher", async (t) => { + let resolve; + const wire = transport(t, { + connect: () => + new Promise((r) => { + resolve = r; + }), + }); + const pending = wire.client.fetchEvents({ kinds: [50000], limit: 1000 }); + const rejected = assert.rejects(pending, /cancelled/); + wire.client.disconnect(); + resolve(99); + await rejected; + assert.deepEqual(wire.closed, [99]); + assert.equal(wire.sent.length, 0); + assert.equal(wire.timers.size, 0); +}); + +test("concurrent reads cannot bypass pending authentication", async (t) => { + let resolve; + const wire = transport(t, { + connect: () => + new Promise((r) => { + resolve = r; + }), + }); + const first = wire.client.fetchEvents({ kinds: [50000], limit: 1000 }); + const rejectedFirst = assert.rejects(first, /disconnected/); + resolve(99); + await flush(); + const second = wire.client.fetchEvents({ kinds: [50000], limit: 1000 }); + const rejectedSecond = assert.rejects(second, /disconnected/); + await flush(); + assert.equal(wire.sent.length, 0); + wire.client.disconnect(); + await Promise.all([rejectedFirst, rejectedSecond]); +}); + +test("AUTH delivered before native connect resolves is not lost", async (t) => { + let resolve; + const wire = transport(t, { + connect: () => + new Promise((r) => { + resolve = r; + }), + history: ([, id], emit) => emit(["EOSE", id]), + }); + const pending = wire.client.fetchEvents({ kinds: [50000], limit: 1000 }); + wire.emit(["AUTH", "early challenge"]); + resolve(99); + assert.deepEqual(await pending, []); + assert.equal(wire.sent[0][0], "AUTH"); +}); + +for (const stage of ["registration", "report"]) { + test(`a duplicate ${stage} history through the actual client blocks construction`, async (t) => { + const f = fixture(); + const registration = await f.bridge.registration(); + const report = await f.bridge.report(registration); + f.bridge.registration = f.bridge.report = async () => + assert.fail("construction after non-advancing history"); + const wire = transport(t, { + history: ([, id, filter], emit) => { + assert.equal(filter.limit, 1000); + const event = + filter["#l"][0] === "registration" ? registration : report; + const count = filter["#l"][0] === stage ? 1000 : 1; + for (let i = 0; i < count; i++) emit(["EVENT", id, event]); + emit(["EOSE", id]); + }, + }); + await assert.rejects(run(f, wire.client), /cursor did not advance/); + assert.equal(wire.sent.filter((frame) => frame[0] === "EVENT").length, 0); + }); + + test(`accepted ${stage} with lost transport ACK is not duplicated on reconnect`, async (t) => { + const f = fixture(); + let lost = false; + let loseAck = true; + const wire = transport(t, { + history: async ([, id, filter], emit) => { + for (const event of await f.relay.fetchEvents(filter)) + emit(["EVENT", id, event]); + emit(["EOSE", id]); + }, + publish: async ([, event], emit) => { + await f.relay.publishEvent(event); + if ( + loseAck && + event.tags.some( + (tag) => + tag[0] === "l" && + tag[1] === (stage === "report" ? "profile" : stage), + ) + ) { + lost = true; + return; + } + emit(["OK", event.id, true, ""]); + }, + }); + const rejected = assert.rejects( + run(f, wire.client), + /Timed out publishing/, + ); + while (!lost) await flush(); + for (const callback of [...wire.timers.values()]) callback(); + await rejected; + wire.client.disconnect(); + loseAck = false; + const snapshot = await run(f, wire.client); + assert.equal(snapshot.rows.length, 1); + assert.equal(f.writes.length, 2); + assert.equal(wire.sent.filter((frame) => frame[0] === "EVENT").length, 2); + }); +} + +for (const stage of ["registration", "report"]) { + for (const reload of [false, true]) { + test(`late ${stage} commit AFTER retry history reuses exact signed event${reload ? " after journal reload" : ""}`, async (t) => { + const f = fixture(); + let held; + let retryRead = false; + let retrying = false; + const wire = transport(t, { + history: async ([, id, filter], emit) => { + const events = await f.relay.fetchEvents(filter); + if (retrying && filter["#l"][0] === stage) { + assert.ok(!events.some((e) => e.id === held.id)); + retryRead = true; + } + for (const event of events) emit(["EVENT", id, event]); + emit(["EOSE", id]); + }, + publish: async ([, event], emit) => { + if ( + event.tags.some( + (tag) => + tag[0] === "l" && + tag[1] === (stage === "report" ? "profile" : stage), + ) + ) { + if (!held) { + held = event; + assert.deepEqual( + f.journal.load()[ + stage === "report" ? "report" : "registration" + ], + event, + ); + return; // Detached old ingest remains uncommitted past timeout. + } + assert.equal(retryRead, true); + assert.deepEqual(event, held); // All seven signed fields, not just ID. + await f.relay.publishEvent(event); + await f.relay.publishEvent(held); // Old EVENT commits after retry read/send. + } else { + await f.relay.publishEvent(event); + } + emit(["OK", event.id, true, ""]); + }, + }); + const rejected = assert.rejects( + run(f, wire.client), + /Timed out publishing/, + ); + while (!held) await flush(); + for (const callback of [...wire.timers.values()]) callback(); + await rejected; + wire.client.disconnect(); + retrying = true; + f.setNow(130); + // A fresh journal object reads only serialized storage; no uncertain-event + // object or decrypted report is retained by the restarted controller. + const journal = reload + ? createHostPublicationJournal( + "wss://fixture.invalid", + "a".repeat(64), + f.storage, + ) + : f.journal; + const snapshot = await run(f, wire.client, journal); + assert.equal(snapshot.rows.length, 1); + assert.equal(f.events.length, 2); + assert.equal( + f.events.filter((e) => + e.tags.some( + (tag) => tag[1] === (stage === "report" ? "profile" : stage), + ), + ).length, + 1, + ); + assert.equal(wire.sent.filter((frame) => frame[0] === "EVENT").length, 3); + assert.equal(journal.load(), undefined); + }); + } +} diff --git a/desktop/src/features/hosts/useHostPresence.ts b/desktop/src/features/hosts/useHostPresence.ts new file mode 100644 index 0000000000..af1bfd5594 --- /dev/null +++ b/desktop/src/features/hosts/useHostPresence.ts @@ -0,0 +1,66 @@ +import { useEffect } from "react"; +import { ReadOnlyRelayClient } from "@/shared/api/readOnlyRelayClient"; +import { invokeTauri } from "@/shared/api/tauri"; +import type { RelayEvent } from "@/shared/api/types"; + +/** Launcher reachability is independent of human idle/away and profile refreshes. */ +export function useHostPresence( + owner: string | undefined, + relayUrl: string | undefined, + registration: RelayEvent | undefined, +) { + const binding = registration ? JSON.stringify(registration) : undefined; + useEffect(() => { + if (!owner || !relayUrl || !binding) return; + const registration = JSON.parse(binding) as RelayEvent; + let active = true; + let seq = 0; + let pending = false; + const run = crypto.randomUUID().replaceAll("-", ""); + const client = new ReadOnlyRelayClient(relayUrl); + const pulse = async () => { + if (!active || pending) return; + pending = true; + try { + const event = await invokeTauri("create_host_presence", { + expectedOwner: owner, + registration, + run, + seq: seq++, + status: "online", + }); + if (active) await client.publishEvent(event); + } catch { + // No optimistic liveness. Retry next heartbeat; prior leases expire. + client.disconnect(); + } finally { + pending = false; + } + }; + void pulse(); + const timer = window.setInterval(() => void pulse(), 60_000); + const wake = () => void pulse(); + window.addEventListener("online", wake); + window.addEventListener("focus", wake); + return () => { + active = false; + window.clearInterval(timer); + window.removeEventListener("online", wake); + window.removeEventListener("focus", wake); + client.disconnect(); + // Best effort on unmount; identity switches are rejected natively, then TTL wins. + const shutdown = new ReadOnlyRelayClient(relayUrl); + void invokeTauri("create_host_presence", { + expectedOwner: owner, + registration, + run, + seq: seq++, + status: "offline", + }) + .then((event) => shutdown.publishEvent(event)) + .catch(() => {}) + .finally(() => shutdown.disconnect()); + }; + // The signed binding is immutable; refreshed snapshot objects must not restart a run. + }, [owner, relayUrl, binding]); +} diff --git a/desktop/src/features/hosts/useHostRegistration.ts b/desktop/src/features/hosts/useHostRegistration.ts new file mode 100644 index 0000000000..e4f1d75ef9 --- /dev/null +++ b/desktop/src/features/hosts/useHostRegistration.ts @@ -0,0 +1,135 @@ +import { useHostPresence } from "./useHostPresence"; +import { useEffect } from "react"; +import { useQuery, useQueryClient } from "@tanstack/react-query"; +import { useCommunities } from "@/features/communities/useCommunities"; +import { useIdentityQuery } from "@/shared/api/hooks"; +import { invokeTauri } from "@/shared/api/tauri"; +import { ReadOnlyRelayClient } from "@/shared/api/readOnlyRelayClient"; +import type { RelayEvent } from "@/shared/api/types"; +import { + hostQueryKey, + type HostBridge, + type HostSnapshot, + type HostReport, + type LocalHost, +} from "./registration"; + +import { createHostRegistrationLifecycle } from "./registrationLifecycle"; +import { createHostPublicationJournal } from "./pendingPublication"; +import { hostNativeDrain } from "./hostNativeDrain"; + +export const HOST_REFRESH = "buzz:refresh-hosts"; +const EMPTY: HostSnapshot = { rows: [], checking: true }; + +export function useHostSnapshot() { + const { activeCommunity } = useCommunities(); + const { data: identity } = useIdentityQuery(); + return ( + useQuery({ + queryKey: hostQueryKey(activeCommunity?.relayUrl, identity?.pubkey), + queryFn: async () => EMPTY, + enabled: false, + }).data ?? EMPTY + ); +} + +/** App lifecycle, not Agents-page lifecycle. No cross-community singleton cache. */ +export function useHostRegistration( + owner: string | undefined, + relayUrl: string | undefined, +) { + const queryClient = useQueryClient(); + const snapshot = + useQuery({ + queryKey: hostQueryKey(relayUrl, owner), + queryFn: async () => EMPTY, + enabled: false, + }).data ?? EMPTY; + const localRegistration = snapshot.rows.find( + (row) => row.host === snapshot.local?.host, + )?.registration; + useHostPresence(owner, relayUrl, localRegistration); + useEffect(() => { + if (!owner || !relayUrl) return; + const key = hostQueryKey(relayUrl, owner); + const bridge: HostBridge = { + local: () => + invokeTauri("get_local_host", { expectedOwner: owner }), + registration: () => + invokeTauri("create_host_registration", { + expectedOwner: owner, + }), + report: (registration) => + invokeTauri("create_host_report", { + expectedOwner: owner, + registration, + }), + inspect: (registration) => + invokeTauri("inspect_host_registration", { + expectedOwner: owner, + registration, + }), + decode: (registration, report) => + invokeTauri("decode_host_report", { + expectedOwner: owner, + registration, + report, + }), + }; + const lifecycle = createHostRegistrationLifecycle({ + owner, + bridge, + journal: createHostPublicationJournal(relayUrl, owner), + connect: () => { + const client = new ReadOnlyRelayClient(relayUrl); + return { + // Only HTTP preserves the before_id keyset extension. Owner signing + // stays native; the socket is used solely for acknowledged writes. + fetchEvents: (filter) => + invokeTauri("get_host_history_page", { + expectedOwner: owner, + relayUrl, + filter, + }), + publishEvent: (event) => client.publishEvent(event), + disconnect: () => client.disconnect(), + }; + }, + now: () => Math.floor(Date.now() / 1000), + after: hostNativeDrain.wait(), + checking: () => + queryClient.setQueryData(key, (previous) => ({ + ...(previous ?? EMPTY), + checking: true, + })), + success: (result) => { + queryClient.setQueryData(key, result); + }, + failure: () => + queryClient.setQueryData(key, (previous) => ({ + ...(previous ?? EMPTY), + checking: false, + // Native/transport diagnostics may contain private paths or payloads. + error: + "Could not verify host history or relay acceptance; retry shortly", + })), + }); + const refresh = () => { + void lifecycle.refresh(); + }; + refresh(); + const timer = window.setInterval(refresh, 30_000); + window.addEventListener(HOST_REFRESH, refresh); + window.addEventListener("online", refresh); + window.addEventListener("focus", refresh); + return () => { + hostNativeDrain.hold(lifecycle.stop()); + window.clearInterval(timer); + window.removeEventListener(HOST_REFRESH, refresh); + window.removeEventListener("online", refresh); + window.removeEventListener("focus", refresh); + // Decrypted private metadata must not survive an identity/community switch. + queryClient.removeQueries({ queryKey: key, exact: true }); + }; + }, [owner, relayUrl, queryClient]); +} diff --git a/desktop/src/features/messages/ui/LiveMentionAutocomplete.tsx b/desktop/src/features/messages/ui/LiveMentionAutocomplete.tsx new file mode 100644 index 0000000000..686010d19a --- /dev/null +++ b/desktop/src/features/messages/ui/LiveMentionAutocomplete.tsx @@ -0,0 +1,21 @@ +import type { ComponentProps } from "react"; +import { usePresenceRuns } from "@/features/presence/usePresenceRuns"; +import { MentionAutocomplete as MentionAutocompleteView } from "./MentionAutocomplete"; + +/** Fetch only visible agent placements, once per picker rather than per row. */ +export function MentionAutocomplete( + props: ComponentProps, +) { + const presence = usePresenceRuns( + props.suggestions.flatMap((suggestion) => + suggestion.isAgent && suggestion.pubkey ? [suggestion.pubkey] : [], + ), + ); + return ( + + ); +} diff --git a/desktop/src/features/messages/ui/MentionAutocomplete.test.mjs b/desktop/src/features/messages/ui/MentionAutocomplete.test.mjs index be3ec6938e..ea0d30f681 100644 --- a/desktop/src/features/messages/ui/MentionAutocomplete.test.mjs +++ b/desktop/src/features/messages/ui/MentionAutocomplete.test.mjs @@ -407,3 +407,39 @@ test("agents without trustworthy provenance omit management provenance", () => { false, ); }); + +test("live host names use the cloud marker even without a name collision", async () => { + const React = await import("react"); + const { render } = await import("@testing-library/react"); + const { MentionAutocomplete } = await import("./MentionAutocomplete.tsx"); + const pubkey = "b".repeat(64); + const props = { + suggestions: [{ pubkey, displayName: "Agent Ada", isAgent: true }], + selectedIndex: 0, + onSelect: () => {}, + presenceNow: 100, + presenceRuns: { + [pubkey]: [ + { + run: "c".repeat(32), + seq: 0, + status: "online", + expires_at: 101, + location: { host: "a".repeat(64), label: "Workshop" }, + registration: null, + }, + ], + }, + }; + const view = render(React.createElement(MentionAutocomplete, props)); + const marker = view.getByRole("img", { name: "Running on Workshop" }); + assert.match( + marker.querySelector("svg").getAttribute("class"), + /lucide-cloud/, + ); + assert.equal(marker.textContent, "Workshop"); + view.rerender( + React.createElement(MentionAutocomplete, { ...props, presenceNow: 101 }), + ); + assert.equal(view.queryByRole("img", { name: "Running on Workshop" }), null); +}); diff --git a/desktop/src/features/messages/ui/MentionAutocomplete.tsx b/desktop/src/features/messages/ui/MentionAutocomplete.tsx index 08b7dfb37c..910d730666 100644 --- a/desktop/src/features/messages/ui/MentionAutocomplete.tsx +++ b/desktop/src/features/messages/ui/MentionAutocomplete.tsx @@ -1,6 +1,7 @@ import * as React from "react"; +import type { PresenceRuns } from "@/features/presence/runPresence"; import { Bot, ChevronRight, Pin, Users } from "lucide-react"; -import { OtherSetupAgentMarker } from "@/features/agents/ui/OtherSetupAgentMarker"; +import { AgentHostMarker } from "@/features/agents/ui/AgentHostMarker"; import { motion } from "motion/react"; import type { TeamMentionMember } from "@/features/messages/lib/mentionCandidates"; @@ -36,6 +37,8 @@ export type MentionSuggestion = { type MentionAutocompleteProps = { suggestions: MentionSuggestion[]; + presenceRuns?: PresenceRuns; + presenceNow?: number; selectedIndex: number; onFetchMore?: () => void; onSelect: (suggestion: MentionSuggestion) => void; @@ -58,6 +61,8 @@ export function showMentionAgentProvenanceMarker( export const MentionAutocomplete = React.memo(function MentionAutocomplete({ suggestions, + presenceRuns, + presenceNow = Date.now() / 1000, selectedIndex, onFetchMore, onSelect, @@ -363,9 +368,18 @@ export const MentionAutocomplete = React.memo(function MentionAutocomplete({ data-testid="mention-agent-icon" /> agent - {showAgentProvenanceMarker ? ( - - ) : null} + ) : suggestion.role ? ( {label} + {" "} diff --git a/desktop/src/features/messages/ui/MessageComposer.tsx b/desktop/src/features/messages/ui/MessageComposer.tsx index 0cc8650795..d3448a277e 100644 --- a/desktop/src/features/messages/ui/MessageComposer.tsx +++ b/desktop/src/features/messages/ui/MessageComposer.tsx @@ -50,7 +50,7 @@ import { ChannelAutocomplete } from "./ChannelAutocomplete"; import { ComposerReplyEditBanner } from "./ComposerReplyEditBanner"; import { ComposerAttachments, DropZoneOverlay } from "./ComposerAttachments"; import { EmojiAutocomplete } from "./EmojiAutocomplete"; -import { MentionAutocomplete } from "./MentionAutocomplete"; +import { MentionAutocomplete } from "./LiveMentionAutocomplete"; import { ComposerDockToolbar } from "./ComposerDockToolbar"; import { ComposerUploadProgressPill } from "./ComposerUploadProgressPill"; import { NonMemberMentionDialog } from "./NonMemberMentionDialog"; diff --git a/desktop/src/features/messages/ui/MessageHeader.tsx b/desktop/src/features/messages/ui/MessageHeader.tsx index 24bef0f542..c74bb6706a 100644 --- a/desktop/src/features/messages/ui/MessageHeader.tsx +++ b/desktop/src/features/messages/ui/MessageHeader.tsx @@ -1,5 +1,8 @@ import * as React from "react"; +import { AgentManagementMarker } from "@/features/agents/ui/OtherSetupAgentMarker"; +import { UserProfilePopover } from "@/features/profile/ui/UserProfilePopover"; + import { cn } from "@/shared/lib/cn"; type MessageHeaderRowProps = { @@ -104,3 +107,40 @@ export function MessageAuthorText({ ); } + +/** Author navigation and provenance always refer to the same exact identity. */ +export function MessageAuthorIdentity({ + pubkey, + ownerPubkey, + role, + displayName, + children, +}: { + pubkey?: string | null; + ownerPubkey?: string | null; + role?: string; + displayName: string; + children: React.ReactNode; +}) { + return ( + <> + {pubkey ? ( + + + + ) : ( + children + )} + + + ); +} diff --git a/desktop/src/features/messages/ui/MessageRow.tsx b/desktop/src/features/messages/ui/MessageRow.tsx index 02858dac6a..33fc26d13f 100644 --- a/desktop/src/features/messages/ui/MessageRow.tsx +++ b/desktop/src/features/messages/ui/MessageRow.tsx @@ -50,6 +50,7 @@ import { toast } from "sonner"; import { MessageAgentOwner } from "./MessageAgentOwner"; import { MessageAuthorText, + MessageAuthorIdentity, MessageHeaderRow, MessageMetaSegments, } from "./MessageHeader"; @@ -646,22 +647,14 @@ export const MessageRow = React.memo( const headerNode = isDisplayedAsContinuation ? null : ( - {message.pubkey ? ( - - - - ) : ( - authorNode - )} + + {authorNode} + {/* Author is not a segment: "Alice 9:53 AM" needs no divider. */} | null = null; - function handlePresenceEvent(event: { pubkey: string; content: string }) { + function handlePresenceEvent(event: RelayEvent) { if (isCancelled) return; const parsed = parseLivePresenceEvent(event); if (!parsed) return; const { pubkey, status } = parsed; + void queryClient.invalidateQueries({ + queryKey: ["presence-runs"], + predicate: (query) => query.queryKey.slice(3).includes(pubkey), + }); + if (event.tags.some((tag) => tag[0] === "run")) { + // Offline ends one run, not the identity. Ask the relay for the aggregate. + void queryClient.invalidateQueries({ + queryKey: ["presence"], + predicate: (query) => + presenceQueryWantsPubkey(query.queryKey, pubkey), + }); + return; + } queryClient.setQueriesData( { queryKey: ["presence"], @@ -150,9 +167,23 @@ export function usePresenceSubscription() { }); function reconcileActiveQueries() { - reconciler.setAuthors( - activePresencePubkeys(queryClient.getQueryCache().getAll()), - ); + reconciler.setAuthors([ + ...new Set([ + ...activePresencePubkeys(queryClient.getQueryCache().getAll()), + ...queryClient + .getQueryCache() + .getAll() + .filter( + (query) => + query.isActive() && query.queryKey[0] === "presence-runs", + ) + .flatMap((query) => + query.queryKey + .slice(3) + .filter((key): key is string => typeof key === "string"), + ), + ]), + ]); } function scheduleReconcile() { @@ -175,8 +206,10 @@ export function usePresenceSubscription() { reconcileActiveQueries(); const unsubReconnect = relayClient.subscribeToReconnects(() => { - if (!isCancelled) + if (!isCancelled) { void queryClient.invalidateQueries({ queryKey: ["presence"] }); + void queryClient.invalidateQueries({ queryKey: ["presence-runs"] }); + } }); return () => { diff --git a/desktop/src/features/presence/runPresence.test.mjs b/desktop/src/features/presence/runPresence.test.mjs new file mode 100644 index 0000000000..0592582df0 --- /dev/null +++ b/desktop/src/features/presence/runPresence.test.mjs @@ -0,0 +1,26 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import { activeRuns, locationLabels, nextRunExpiry } from "./runPresence.ts"; +const run = (id, label, expires_at = 280) => ({ + run: id, + seq: 1, + status: "online", + expires_at, + location: label ? { host: id, label } : null, + registration: null, +}); +test("location requires its own unexpired run, never aggregate presence", () => { + const runs = [run("a", "Workshop"), run("b", "Office", 300), run("c", null)]; + assert.deepEqual(locationLabels(runs, 100), ["Office", "Workshop"]); + assert.deepEqual(locationLabels(runs, 280), ["Office"]); + assert.deepEqual(locationLabels(runs, 300), []); + assert.equal(nextRunExpiry({ agent: runs }, 280), 300); + assert.equal(nextRunExpiry({ agent: runs }, 300), undefined); +}); +test("stopping one placement leaves the other; repeated labels coalesce", () => { + const first = { ...run("a", "Workshop"), status: "offline" }; + const runs = [first, run("b", "Office"), run("c", "Office")]; + assert.equal(activeRuns(runs, 100).length, 2); + assert.deepEqual(locationLabels(runs, 100), ["Office"]); + assert.deepEqual(locationLabels(undefined, 100), []); +}); diff --git a/desktop/src/features/presence/runPresence.ts b/desktop/src/features/presence/runPresence.ts new file mode 100644 index 0000000000..a412d67c06 --- /dev/null +++ b/desktop/src/features/presence/runPresence.ts @@ -0,0 +1,34 @@ +/** Relay-bounded leases; snapshot reads never renew these deadlines. */ +export type PresenceRun = { + run: string; + seq: number; + status: "online" | "away" | "offline"; + expires_at: number; + location: { host: string; label: string } | null; + registration: string | null; +}; +export type PresenceRuns = Record; + +export function activeRuns(runs: PresenceRun[] | undefined, now: number) { + return (runs ?? []).filter( + (run) => run.status !== "offline" && run.expires_at > now, + ); +} + +export function locationLabels(runs: PresenceRun[] | undefined, now: number) { + return [ + ...new Set( + activeRuns(runs, now).flatMap((run) => + run.location ? [run.location.label] : [], + ), + ), + ].sort(); +} + +export function nextRunExpiry(data: PresenceRuns | undefined, now: number) { + const deadlines = Object.values(data ?? {}) + .flat() + .map((run) => run.expires_at) + .filter((deadline) => deadline > now); + return deadlines.length ? Math.min(...deadlines) : undefined; +} diff --git a/desktop/src/features/presence/usePresenceRuns.test.mjs b/desktop/src/features/presence/usePresenceRuns.test.mjs new file mode 100644 index 0000000000..33a08c8fbc --- /dev/null +++ b/desktop/src/features/presence/usePresenceRuns.test.mjs @@ -0,0 +1,156 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import { JSDOM } from "jsdom"; +import React, { act } from "react"; +import { createRoot } from "react-dom/client"; +import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; +import { + CommunitiesProvider, + useCommunities, +} from "../communities/useCommunities.tsx"; +import { usePresenceRuns } from "./usePresenceRuns.ts"; +import { AgentHostMarker } from "../agents/ui/AgentHostMarker.tsx"; + +const flush = () => new Promise((resolve) => setTimeout(resolve, 15)); +test("live markers expire without a network callback and reject late previous-scope data", async (t) => { + const dom = new JSDOM("
", { + url: "https://fixture.invalid", + }); + const globals = [ + "window", + "document", + "localStorage", + "IS_REACT_ACT_ENVIRONMENT", + ]; + const saved = Object.fromEntries( + globals.map((key) => [key, globalThis[key]]), + ); + Object.assign(globalThis, { + window: dom.window, + document: dom.window.document, + localStorage: dom.window.localStorage, + IS_REACT_ACT_ENVIRONMENT: true, + }); + localStorage.setItem( + "buzz-communities", + JSON.stringify([ + { id: "a", name: "A", relayUrl: "wss://a.invalid" }, + { id: "b", name: "B", relayUrl: "wss://b.invalid" }, + ]), + ); + localStorage.setItem("buzz-active-community-id", "a"); + const client = new QueryClient({ + defaultOptions: { queries: { gcTime: Infinity, retry: false } }, + }); + const owner = "a".repeat(64), + agent = "b".repeat(64); + client.setQueryData(["identity"], { pubkey: owner }); + const calls = [], + replies = []; + dom.window.__TAURI_INTERNALS__ = { + invoke: (command, args) => { + assert.equal(command, "get_presence_runs"); + calls.push(args); + return new Promise((resolve, reject) => + replies.push({ resolve, reject }), + ); + }, + }; + const root = createRoot(document.getElementById("root")); + let communities, latest; + function View() { + communities = useCommunities(); + latest = usePresenceRuns([agent]); + return React.createElement(AgentHostMarker, { + runs: latest.data?.[agent], + now: latest.now, + }); + } + t.after(async () => { + await act(async () => root.unmount()); + client.clear(); + await flush(); + dom.window.close(); + for (const [key, value] of Object.entries(saved)) { + if (value === undefined) delete globalThis[key]; + else globalThis[key] = value; + } + }); + await act(async () => { + root.render( + React.createElement( + QueryClientProvider, + { client }, + React.createElement( + CommunitiesProvider, + null, + React.createElement(View), + ), + ), + ); + await flush(); + }); + assert.deepEqual(calls[0], { + expectedOwner: owner, + relayUrl: "wss://a.invalid", + pubkeys: [agent], + }); + const run = { + run: "c".repeat(32), + seq: 0, + status: "online", + expires_at: Date.now() / 1000 + 0.15, + location: { host: owner, label: "Workshop" }, + registration: null, + }; + await act(async () => { + replies[0].resolve({ [agent]: [run] }); + await flush(); + }); + assert.equal( + document.querySelector('[title="Running on Workshop"]')?.textContent, + "Workshop", + ); + await act(async () => { + await new Promise((resolve) => setTimeout(resolve, 180)); + }); + assert.equal(document.querySelector('[title="Running on Workshop"]'), null); + assert.equal(calls.length, 1, "expiry must not need a poll"); + void latest.refetch(); + await act(async () => { + communities.switchCommunity("b"); + await flush(); + }); + assert.equal(calls[2].relayUrl, "wss://b.invalid"); + await act(async () => { + replies[1].resolve({ + [agent]: [{ ...run, expires_at: Date.now() / 1000 + 100 }], + }); + await flush(); + }); + assert.equal( + document.querySelector('[title="Running on Workshop"]'), + null, + "old community response must not render in B", + ); + await act(async () => { + replies[2].reject(new Error("unavailable")); + await flush(); + }); + assert.equal(latest.isError, true); + assert.equal( + latest.data, + undefined, + "failed snapshot is unknown, not an empty offline snapshot", + ); + await act(async () => { + client.setQueryData(["identity"], { pubkey: "d".repeat(64) }); + await flush(); + }); + assert.equal(calls[3].expectedOwner, "d".repeat(64)); + await act(async () => { + replies[3].resolve({ [agent]: [] }); + await flush(); + }); + assert.deepEqual(latest.data, { [agent]: [] }); +}); diff --git a/desktop/src/features/presence/usePresenceRuns.ts b/desktop/src/features/presence/usePresenceRuns.ts new file mode 100644 index 0000000000..29f8027d71 --- /dev/null +++ b/desktop/src/features/presence/usePresenceRuns.ts @@ -0,0 +1,52 @@ +import { useEffect, useState } from "react"; +import { useQuery } from "@tanstack/react-query"; +import { useCommunities } from "@/features/communities/useCommunities"; +import { useIdentityQuery } from "@/shared/api/hooks"; +import { invokeTauri } from "@/shared/api/tauri"; +import { useRelayConnection } from "@/shared/api/useRelayConnection"; +import { nextRunExpiry, type PresenceRuns } from "./runPresence"; + +/** Scope snapshots to the captured reader and community; errors are not offline. */ +export function usePresenceRuns(pubkeys: string[]) { + const { activeCommunity } = useCommunities(); + const { data: identity } = useIdentityQuery(); + const connected = useRelayConnection() === "connected"; + const owner = identity?.pubkey; + const relay = activeCommunity?.relayUrl; + const authors = [...new Set(pubkeys.map((key) => key.toLowerCase()))].sort(); + const query = useQuery({ + queryKey: ["presence-runs", relay, owner, ...authors], + enabled: !!owner && !!relay && authors.length > 0, + queryFn: () => + invokeTauri("get_presence_runs", { + expectedOwner: owner, + relayUrl: relay, + pubkeys: authors, + }), + refetchInterval: connected ? 60_000 : false, + staleTime: 30_000, + retry: false, + }); + const [now, setNow] = useState(() => Date.now() / 1000); + const expiry = nextRunExpiry(query.data, now); + useEffect(() => { + // Also reevaluate after a background/sleep interval; do not wait for a poll. + const update = () => setNow(Date.now() / 1000); + update(); + const timer = + expiry === undefined + ? undefined + : window.setTimeout( + update, + Math.max(0, expiry * 1000 - Date.now()) + 1, + ); + window.addEventListener("focus", update); + document.addEventListener("visibilitychange", update); + return () => { + window.clearTimeout(timer); + window.removeEventListener("focus", update); + document.removeEventListener("visibilitychange", update); + }; + }, [expiry]); + return { ...query, now: Math.max(now, Date.now() / 1000) }; +} diff --git a/desktop/src/features/profile/ui/UserProfilePanelHeaderContent.tsx b/desktop/src/features/profile/ui/UserProfilePanelHeaderContent.tsx index 531222f0ba..148d57aa8e 100644 --- a/desktop/src/features/profile/ui/UserProfilePanelHeaderContent.tsx +++ b/desktop/src/features/profile/ui/UserProfilePanelHeaderContent.tsx @@ -1,5 +1,6 @@ import type { ReactNode } from "react"; +import { AgentManagementMarker } from "@/features/agents/ui/OtherSetupAgentMarker"; import { CopyButton } from "@/features/agents/ui/CopyButton"; import { MemoryRefreshButton } from "@/features/agent-memory/ui/MemorySection"; import { @@ -16,6 +17,7 @@ import { Button } from "@/shared/ui/button"; export function getUserProfilePanelHeaderContent({ agentSettingsMenu, effectivePubkey, + ownerPubkey, logCopyValue, logSubtitle, onBack, @@ -25,6 +27,7 @@ export function getUserProfilePanelHeaderContent({ }: { agentSettingsMenu: ReactNode; effectivePubkey: string | null; + ownerPubkey?: string | null; logCopyValue?: string | null; logSubtitle?: string | null; onBack: () => void; @@ -47,6 +50,13 @@ export function getUserProfilePanelHeaderContent({ subtitleTitle={logSubtitle ?? undefined} title={title} /> + {view !== "summary" ? ( + + ) : null} ); const headerActions = ( diff --git a/desktop/src/features/profile/ui/UserProfilePanelSections.tsx b/desktop/src/features/profile/ui/UserProfilePanelSections.tsx index 30da0f2241..1244e324a2 100644 --- a/desktop/src/features/profile/ui/UserProfilePanelSections.tsx +++ b/desktop/src/features/profile/ui/UserProfilePanelSections.tsx @@ -1,3 +1,4 @@ +import { LiveAgentHostMarker } from "@/features/agents/ui/LiveAgentHostMarker"; import * as React from "react"; import { ChevronDown, ChevronUp, Pencil } from "lucide-react"; @@ -410,6 +411,11 @@ export function ProfileSummaryView({ profile={profile} userStatus={userStatus} /> + {isBot && pubkey ? ( +
+ +
+ ) : null}
{canInstantiateAgent ? ( diff --git a/desktop/src/features/profile/ui/UserProfilePopover.tsx b/desktop/src/features/profile/ui/UserProfilePopover.tsx index d19a5fa19d..af4431e76b 100644 --- a/desktop/src/features/profile/ui/UserProfilePopover.tsx +++ b/desktop/src/features/profile/ui/UserProfilePopover.tsx @@ -1,6 +1,8 @@ import * as React from "react"; import { Activity, Headphones, MessageSquare } from "lucide-react"; +import { AgentManagementMarker } from "@/features/agents/ui/OtherSetupAgentMarker"; + import { useChannelsQuery } from "@/features/channels/hooks"; import { useUserProfileQuery, @@ -391,6 +393,11 @@ function UserProfilePopoverBody({
+ {isBotProfile && botIdenticonValue ? ( ) : null} + {channel.channelType === "dm" && dmParticipants?.length === 1 ? ( + + ) : null} {activeWorking ? ( (); private publishes = new Map(); private generation = 0; + private pendingChallenge: string | null = null; private readonly relayUrl: string; @@ -55,8 +56,8 @@ export class ReadOnlyRelayClient { } async connect(): Promise { - if (this.wsId !== null) return; if (this.connectPromise) return this.connectPromise; + if (this.wsId !== null) return; const promise = this.openConnection(); this.connectPromise = promise; @@ -98,6 +99,7 @@ export class ReadOnlyRelayClient { this.onMessageChannel = null; this.connectPromise = null; + this.pendingChallenge = null; } async fetchEvents(filter: RelaySubscriptionFilter): Promise { @@ -135,15 +137,22 @@ export class ReadOnlyRelayClient { const generation = ++this.generation; this.onMessageChannel = new Channel((delivery) => { for (const message of toRelayFrames(delivery)) { - void this.handleWsMessage(message, generation); + void this.handleWsMessage(message, generation).catch(() => { + if (generation === this.generation) this.disconnect(); + }); } }); - this.wsId = await invoke("plugin:websocket|connect", { + const wsId = await invoke("plugin:websocket|connect", { url: this.relayUrl, onMessage: this.onMessageChannel, config: {}, }); + if (generation !== this.generation) { + void closeWebSocket(wsId, "observer connection cancelled"); + throw new Error("Observer relay connection cancelled."); + } + this.wsId = wsId; await new Promise((resolve, reject) => { const timeout = window.setTimeout(() => { @@ -158,6 +167,14 @@ export class ReadOnlyRelayClient { reject, timeout, }; + // Native delivery can beat resolution of the connect IPC command. + if (this.pendingChallenge !== null) { + const challenge = this.pendingChallenge; + this.pendingChallenge = null; + void this.handleAuthChallenge(challenge, generation).catch(() => { + if (generation === this.generation) this.disconnect(); + }); + } }); } @@ -235,6 +252,10 @@ export class ReadOnlyRelayClient { const [type, ...rest] = data; if (type === "AUTH" && typeof rest[0] === "string") { + if (this.wsId === null) { + this.pendingChallenge = rest[0]; + return; + } await this.handleAuthChallenge(rest[0], generation); return; } @@ -254,6 +275,16 @@ export class ReadOnlyRelayClient { ); return; } + if (type === "CLOSED" && typeof rest[0] === "string") { + const pending = this.histories.get(rest[0]); + if (pending) { + window.clearTimeout(pending.timeout); + this.histories.delete(rest[0]); + // Discard partial history. A later EOSE cannot turn failure into absence. + pending.reject(new Error("Observer relay history request was closed.")); + } + return; + } if (type === "EOSE" && typeof rest[0] === "string") { this.handleEose(rest[0]); } diff --git a/desktop/src/shared/ui/markdown.tsx b/desktop/src/shared/ui/markdown.tsx index e9d4b1e8ec..8965b1041a 100644 --- a/desktop/src/shared/ui/markdown.tsx +++ b/desktop/src/shared/ui/markdown.tsx @@ -13,7 +13,6 @@ import { resolveMessageLinkRenderTarget, type ParsedMessageLink, } from "@/features/messages/lib/messageLink"; -import { UserProfilePopover } from "@/features/profile/ui/UserProfilePopover"; import { invokeTauri } from "@/shared/api/tauri"; import { useChannelNavigation } from "@/shared/context/ChannelNavigationContext"; import { cn } from "@/shared/lib/cn"; @@ -23,7 +22,7 @@ import { rewriteRelayUrl } from "@/shared/lib/mediaUrl"; import { useRelayOrigin } from "@/shared/lib/useRelayOrigin"; import { AttachmentGroup } from "@/shared/ui/attachment"; import { ConfigNudgeCard } from "@/shared/ui/config-nudge-attachment"; -import { InlineChip } from "@/shared/ui/InlineChip"; +import { MarkdownMention } from "./markdown/MarkdownMention"; import { LinkPreviewList } from "@/shared/ui/link-preview-list"; import { useSmoothCorners } from "@/shared/ui/smoothCorners"; import { @@ -1578,48 +1577,9 @@ export function createMarkdownComponents( ul: ({ children }) => (
    {children}
), - mention: function MarkdownMention({ - children, - }: { - children?: React.ReactNode; - }) { - const { agentMentionPubkeysByName, mentionPubkeysByName } = - useMarkdownRuntime(); - const mentionText = String(children ?? ""); - const mentionName = mentionText.replace(/^@/, "").trim().toLowerCase(); - const pubkey = mentionPubkeysByName?.[mentionName]; - const isAgentMention = - pubkey !== undefined && - agentMentionPubkeysByName?.[mentionName] === pubkey; - const mentionLabel = mentionText.replace(/^@/, ""); - // Only chips that actually open a profile get the clickable affordance. - // A mention whose pubkey didn't resolve stays a plain chip — a pointer - // cursor there promises a click that does nothing. - const opensProfile = interactive && pubkey !== undefined; - const mentionNode = ( - - {mentionLabel} - - ); - - return opensProfile ? ( - - {mentionNode} - - ) : ( - mentionNode - ); - }, + mention: ({ children }: { children?: React.ReactNode }) => ( + {children} + ), emoji: ({ src, alt }: { src?: string; alt?: string }) => { const resolvedSrc = src ? rewriteRelayUrl(src) : src; if (!resolvedSrc) { diff --git a/desktop/src/shared/ui/markdown/MarkdownMention.tsx b/desktop/src/shared/ui/markdown/MarkdownMention.tsx new file mode 100644 index 0000000000..cef35b24b8 --- /dev/null +++ b/desktop/src/shared/ui/markdown/MarkdownMention.tsx @@ -0,0 +1,52 @@ +import type * as React from "react"; +import { AgentManagementMarker } from "@/features/agents/ui/OtherSetupAgentMarker"; +import { UserProfilePopover } from "@/features/profile/ui/UserProfilePopover"; +import { InlineChip } from "@/shared/ui/InlineChip"; +import { cn } from "@/shared/lib/cn"; +import { useMarkdownRuntime } from "./runtimeContext"; + +/** Exact-identity mention chip and its shared management provenance. */ +export function MarkdownMention({ + children, + interactive, +}: { + children?: React.ReactNode; + interactive: boolean; +}) { + const { agentMentionPubkeysByName, mentionPubkeysByName } = + useMarkdownRuntime(); + const mentionText = String(children ?? ""); + const mentionName = mentionText.replace(/^@/, "").trim().toLowerCase(); + const pubkey = mentionPubkeysByName?.[mentionName]; + const isAgentMention = + pubkey !== undefined && agentMentionPubkeysByName?.[mentionName] === pubkey; + const mentionLabel = mentionText.replace(/^@/, ""); + // Only chips that actually open a profile get the clickable affordance. + // A mention whose pubkey didn't resolve stays a plain chip — a pointer + // cursor there promises a click that does nothing. + const opensProfile = interactive && pubkey !== undefined; + const mentionNode = ( + + {mentionLabel} + {isAgentMention ? : null} + + ); + + return opensProfile ? ( + + {mentionNode} + + ) : ( + mentionNode + ); +} diff --git a/docs/host-execution.md b/docs/host-execution.md new file mode 100644 index 0000000000..699f24440c --- /dev/null +++ b/docs/host-execution.md @@ -0,0 +1,106 @@ +# Host execution foundations (not yet an enabled remote feature) + +The native transition seam exists, but host discovery still advertises +`accepts_start: false`. There is no Start/Move host-picker wiring or relay command +receiver/publication yet. Kinds 50001/50002 are reserved protocol constants, **not +admitted relay operations**. Do not enable the advertisement merely because a +command can be signed or a native IPC call returns. + +## Native seams + +- `inspect_local_execution_config`: owner/community-scoped inspection of an agent + already provisioned on this Desktop. Returns only Rust catalog runtime ID and + a destination configuration digest; never a launch payload/key/environment. +- `execute_host_command`: verifies an owner-signed NIP-44 command addressed to this + host, reads the exact nondeleted registration using the **existing owner's** + selected-community authority, checks freshness, then runs the native transition. + No independent host login or owner credentials export is introduced. +- Start uses the existing launch machinery and destination configuration. Its + revision is rechecked against the actual resolved inputs at the spawn boundary. + Unknown/missing runtime or authentication, setup mode, provider-backed records, + unsupported mesh preflight, prior receipt or live destination peer fail closed. + There is no arbitrary received command/env/path or source-host loopback endpoint. + This does **not** yet provision a source-only agent onto a second Desktop. +- The Start operation's random ID governs the launcher `start_nonce`, durable + receipt `run_id`, authenticated lifecycle correlation and public ACP run ID. + Ordinary local starts get a fresh generation as before. Legacy receipts deserialize + with no generation and cannot establish selected-run Stop authority. + +## Durable semantics + +A secret-free journal is keyed by local owner plus canonical agent/community +placement. An OS file lock serializes controllers sharing the store. Atomic +restricted writes and directory sync persist intent **before** side effects. +The immutable signed command event ID and request are retained with outcomes. +Retries reuse the same event/operation, return the recorded observation and never +repeat launch. A crash after intent but before a recorded result is `unknown`, +not an invitation to spawn again. A different command reusing an operation ID is +rejected. Journal corruption/unreadability and retention saturation fail closed. +There is no automatic garbage collection or recovery override. + +The placement remains fenced through Stop and unknown outcomes. Ordinary/config- +driven starts consult that fence too. A stale Stop checks the tracked generation +under the transition locks **before** writing a new fence, so it neither signals +nor takes control of a successor. Other agent/community placements are untouched. + +`spawned` means a child was actually created, **not** listening, ready, a model turn +or conversational presence. The protocol reserves listening/ready observations; +the native executor currently records spawn only, not asynchronous receipt updates. +Results are host-signed, encrypted to the owner, and correlated to the exact signed +command, request, host registration and generation. Expired presence is never an +execution result. Authorization and command lifetime are rechecked even on retry; +after expiry the future receiver needs an authenticated history/reconciliation +path, not a replay with a new operation ID. + +## Exact Stop: important containment limit + +The current native Stop only signals an exact tracked generation and waits for its +root and owned process group to exit. An already-reaped root cannot be signaled by +its potentially recycled PID. Unknown teardown retains the fence. + +**This does not prove full tree teardown.** ACP agents and buzz-agent MCP servers +create their own process groups (`buzz-acp/src/acp.rs`, `buzz-agent/src/mcp.rs`). +The executor therefore records **`root_exited`**, never `stopped`, after observing +root-group teardown. `root_exited` is explicitly insufficient to permit a new +Start. The journal's `stopped` state is reserved for a future containment-backed +proof; no production native path currently emits it. A healthy goodbye, exit code, +lease expiry or relay acknowledgement cannot substitute for that proof. + +Move remains unimplemented, but its product meaning is approved: stop-confirm +only the selected generation, then a fresh runtime session for the same agent on +the destination, with **no automatic workspace or file transfer**. Unknown or +root-only outcomes continue blocking replacement; unrelated placements must not +be touched. Do not use identity-wide `!shutdown`. + +The first workload-owner correction is in `buzz-dev-mcp`: connection EOF/error +closes shell admission and cancels running shell calls before the MCP response +drain, and server teardown waits for those calls. Shell cancellation signals its +own process group, waits for its direct child, and joins its output-reader tasks. +A real-process test drives MCP EOF with a shell/grandchild in a separate group and +checks that an unrelated peer survives. This fixes cooperative MCP connection +teardown, **not** the full Desktop Stop chain or arbitrary daemon containment. + +The remaining concrete ownership gap is upstream: native escalation currently +allows only one second; ACP immediately kills its agent group; buzz-agent spawns +session/prompt tasks without joining them on EOF and kills MCP groups in Drop +instead of awaiting rmcp's existing graceful transport close. Those owners must +propagate cancellation, join their work and await child teardown before an +exact-generation authenticated completion can be trusted. A killed/hung owner, +unobserved cleanup or unsupported runtime must remain unknown, not stopped. +There is no universal containment promise for arbitrary programs that detach from +managed groups. + +## Remaining integration gates + +1. Admit the private command/receipt kinds through existing relay authorization, + registration revocation, owner-only result gates/queries and FTS exclusion. + Add tenant, malicious payload and revocation integration tests before admission. +2. Owner-operated Desktop receiver/outbox, durable receipt retry/history and actual + authenticated lifecycle receipt updates. Do not grant host keys general access. +3. Destination provisioning/minimal encrypted handoff if the agent is absent; + explicit destination-local credentials and config, not exported source files. +4. Workload-owner teardown and confirmed selected-run Stop, then the approved + fresh-runtime/no-file-transfer Move. No workspace migration. +5. Native two-executor tracer bullet and UI, second-host/provider prerequisites, + real workload verification, final mesh-enabled packaging and matching captures. + Two local processes prove routing, not two physical machines. diff --git a/migrations/0041_host_fts.sql b/migrations/0041_host_fts.sql new file mode 100644 index 0000000000..059d8b559e --- /dev/null +++ b/migrations/0041_host_fts.sql @@ -0,0 +1,26 @@ +-- Private host metadata must not be indexed. Same heap-rewrite operational +-- cost as 0033: schedule a maintenance window for large databases. +DO $$ +DECLARE + existing_expression TEXT; +BEGIN + SELECT pg_get_expr(d.adbin, d.adrelid) + INTO existing_expression + FROM pg_attrdef d + JOIN pg_attribute a + ON a.attrelid = d.adrelid + AND a.attnum = d.adnum + WHERE d.adrelid = 'events'::regclass + AND a.attname = 'search_tsv'; + + IF existing_expression IS NULL THEN + RAISE EXCEPTION 'events.search_tsv generated expression not found'; + END IF; + + ALTER TABLE events DROP COLUMN search_tsv; + EXECUTE format( + 'ALTER TABLE events ADD COLUMN search_tsv TSVECTOR GENERATED ALWAYS AS (CASE WHEN kind = 50000 THEN NULL::tsvector ELSE (%s) END) STORED', + existing_expression + ); + CREATE INDEX idx_events_search_tsv ON events USING GIN (search_tsv); +END $$; diff --git a/schema/schema.sql b/schema/schema.sql index 5456610333..fceae1de5f 100644 --- a/schema/schema.sql +++ b/schema/schema.sql @@ -219,9 +219,9 @@ CREATE TABLE events ( -- Privacy: encrypted/private routing wrappers and p-gated membership notices -- must never be discoverable through NIP-50 full-text search. NULL tsvector -- never matches `@@`. - -- Keep in sync with migrations (final state: 0001 + 0005 + 0014 + 0033). + -- Keep in sync with migrations (final state: 0001 + 0005 + 0014 + 0033 + 0040). search_tsv TSVECTOR GENERATED ALWAYS AS ( - CASE WHEN kind IN (1059, 30179, 30300, 30350, 30622, 44100, 44101, 44200) THEN NULL::tsvector + CASE WHEN kind IN (1059, 30179, 30300, 30350, 30622, 44100, 44101, 44200, 50000) THEN NULL::tsvector ELSE to_tsvector('simple', content) END ) STORED,