From af092ce97bd47b07da18d91105c6b74b6eb7fc44 Mon Sep 17 00:00:00 2001 From: Logan Johnson Date: Thu, 27 Aug 2026 17:46:06 -0400 Subject: [PATCH] Wake agents from verified workflow mentions Signed-off-by: Logan Johnson Co-authored-by: Larry <8cf5a83f590ec0955b11647d1c88f796a98e088c30a492c58e0e46c3026ae7a4@buzz.block.builderlab.xyz> Signed-off-by: Larry <8cf5a83f590ec0955b11647d1c88f796a98e088c30a492c58e0e46c3026ae7a4@buzz.block.builderlab.xyz> Signed-off-by: Logan Johnson --- Cargo.lock | 1 + crates/buzz-acp/Cargo.toml | 1 + crates/buzz-acp/src/lib.rs | 51 ++++ crates/buzz-acp/src/relay.rs | 156 +++++++++-- crates/buzz-acp/src/workflow_wake.rs | 347 ++++++++++++++++++++++++ crates/buzz-core/src/kind.rs | 4 + crates/buzz-core/src/lib.rs | 2 + crates/buzz-core/src/workflow_wake.rs | 327 ++++++++++++++++++++++ crates/buzz-relay/src/api/workflows.rs | 90 ++++++ crates/buzz-relay/src/handlers/event.rs | 22 ++ crates/buzz-relay/src/handlers/req.rs | 25 +- crates/buzz-relay/src/router.rs | 4 + crates/buzz-relay/src/workflow_sink.rs | 178 +++++++++++- crates/buzz-workflow/src/action_sink.rs | 24 +- crates/buzz-workflow/src/executor.rs | 8 +- 15 files changed, 1193 insertions(+), 47 deletions(-) create mode 100644 crates/buzz-acp/src/workflow_wake.rs create mode 100644 crates/buzz-core/src/workflow_wake.rs diff --git a/Cargo.lock b/Cargo.lock index 9ad2a913e6..ef1bdc20a5 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -846,6 +846,7 @@ dependencies = [ "rustls", "serde", "serde_json", + "serde_yaml", "sha2 0.11.0", "thiserror 2.0.18", "tokio", diff --git a/crates/buzz-acp/Cargo.toml b/crates/buzz-acp/Cargo.toml index d047849806..6dffb85bc1 100644 --- a/crates/buzz-acp/Cargo.toml +++ b/crates/buzz-acp/Cargo.toml @@ -41,6 +41,7 @@ reqwest = { workspace = true } # Serialization serde = { workspace = true } serde_json = { workspace = true } +serde_yaml = { workspace = true } # IDs uuid = { workspace = true } diff --git a/crates/buzz-acp/src/lib.rs b/crates/buzz-acp/src/lib.rs index d72d4cf482..d17898f9d9 100644 --- a/crates/buzz-acp/src/lib.rs +++ b/crates/buzz-acp/src/lib.rs @@ -14,6 +14,7 @@ mod relay; mod scope; mod setup_mode; mod usage; +mod workflow_wake; pub use usage::TurnUsage; @@ -2581,6 +2582,12 @@ async fn tokio_main() -> Result<()> { tracing::warn!("failed to set startup watermark: {e}"); } + let workflow_relay_pubkey = relay + .rest_client() + .relay_signing_pubkey() + .await + .map_err(|e| anyhow::anyhow!("relay signing identity error: {e}"))?; + tracing::info!("connected to relay at {}", config.relay_url); let relay_rest_client = relay.rest_client(); @@ -2676,6 +2683,7 @@ async fn tokio_main() -> Result<()> { kinds: config.kinds_override.clone().unwrap_or_else(|| { vec![ KIND_STREAM_MESSAGE, + buzz_core::kind::KIND_WORKFLOW_MENTION_WAKE, KIND_WORKFLOW_APPROVAL_REQUESTED, KIND_STREAM_REMINDER, ] @@ -3207,6 +3215,49 @@ async fn tokio_main() -> Result<()> { Some(buzz_event) => { let kind_u32 = buzz_event.event.kind.as_u16() as u32; + let (buzz_event, admission_author_override) = if kind_u32 + == buzz_core::kind::KIND_WORKFLOW_MENTION_WAKE + { + let Some(wake) = buzz_core::workflow_wake::WorkflowMentionWake::parse( + &buzz_event.event, + ) + .ok() + else { + continue; + }; + let authority = match ctx + .rest_client + .workflow_wake_authority(wake.run_id(), &wake.message_event_id()) + .await + { + Ok(authority) => authority, + Err(error) => { + tracing::warn!(%error, "workflow wake authority unavailable"); + continue; + } + }; + let Some((message, signed_author)) = workflow_wake::verify( + &buzz_event.event, + authority, + workflow_relay_pubkey, + config.keys.public_key(), + buzz_event.channel_id, + ) else { + tracing::warn!("workflow wake authority verification failed"); + continue; + }; + ( + relay::BuzzEvent { + channel_id: buzz_event.channel_id, + event: message, + }, + Some(signed_author), + ) + } else { + (buzz_event, None) + }; + let kind_u32 = buzz_event.event.kind.as_u16() as u32; + if kind_u32 == KIND_MEMBER_ADDED_NOTIFICATION || kind_u32 == KIND_MEMBER_REMOVED_NOTIFICATION { diff --git a/crates/buzz-acp/src/relay.rs b/crates/buzz-acp/src/relay.rs index e4e41b4660..0e2224bbb3 100644 --- a/crates/buzz-acp/src/relay.rs +++ b/crates/buzz-acp/src/relay.rs @@ -479,6 +479,55 @@ impl RestClient { .await } + /// Fetch the relay's advertised signing identity from NIP-11 `/info`. + pub async fn relay_signing_pubkey(&self) -> Result { + let url = format!("{}/info", self.base_url.trim_end_matches('/')); + let value: Value = self + .http + .get(&url) + .header("Accept", "application/nostr+json") + .send() + .await + .map_err(|error| RelayError::Http(error.to_string()))? + .json() + .await + .map_err(|error| RelayError::Http(error.to_string()))?; + let relay_self = value + .get("self") + .and_then(Value::as_str) + .ok_or_else(|| RelayError::Http("relay did not advertise a signing identity".into()))?; + nostr::PublicKey::from_hex(relay_self) + .map_err(|error| RelayError::Http(format!("invalid relay signing identity: {error}"))) + } + + async fn bridge_get(&self, path: &str) -> Result { + let url = format!("{}{}", self.base_url, path); + let auth_tag_header = self.auth_tag_json.clone(); + self.request_with_retry("GET", path, || { + let auth = self.nip98_header("GET", &url, None).unwrap_or_default(); + let mut request = self.http.get(&url).header("Authorization", auth); + if let Some(ref tag) = auth_tag_header { + request = request.header("x-auth-tag", tag); + } + request.send() + }) + .await + } + + /// Fetch one exact workflow-wake authority bundle. + pub async fn workflow_wake_authority( + &self, + run_id: uuid::Uuid, + message_id: &nostr::EventId, + ) -> Result { + let path = format!("/workflow-wakes/{run_id}/{}", message_id.to_hex()); + self.bridge_get(&path) + .await? + .json() + .await + .map_err(|error| RelayError::Http(error.to_string())) + } + /// Query events via the HTTP bridge: `POST /query` with NIP-98 auth. /// /// Accepts a slice of `nostr::Filter` (serialized as JSON array). @@ -3384,6 +3433,59 @@ async fn wait_for_reconnect( /// history. On reconnect (`since` is `Some`) subtracts [`SINCE_SKEW_SECS`]. /// /// Returns `true` if the REQ was successfully written to the WebSocket. +fn build_channel_req( + sub_id: &str, + channel_id: Uuid, + agent_pubkey_hex: &str, + since_ts: u64, + filter: &ChannelFilter, +) -> Value { + let mut req_filter = serde_json::Map::new(); + + // The recipient-gated wake kind always gets its own exact #p filter. This + // preserves `--no-mention-filter` for ordinary channel events without + // weakening wake recipient gating or causing the relay to reject the mixed + // subscription. + let wake_kind = buzz_core::kind::KIND_WORKFLOW_MENTION_WAKE; + let includes_wake = filter + .kinds + .as_ref() + .is_some_and(|kinds| kinds.contains(&wake_kind)); + let normal_kinds = filter.kinds.as_ref().map(|kinds| { + kinds + .iter() + .copied() + .filter(|kind| *kind != wake_kind) + .collect::>() + }); + + if let Some(kinds) = normal_kinds.as_ref().filter(|kinds| !kinds.is_empty()) { + req_filter.insert("kinds".into(), json!(kinds)); + } + req_filter.insert("#h".into(), json!([channel_id.to_string()])); + if filter.require_mention { + req_filter.insert("#p".into(), json!([agent_pubkey_hex])); + } + req_filter.insert("since".into(), json!(since_ts)); + + let mut req_filters = Vec::new(); + if normal_kinds.as_ref().is_none_or(|kinds| !kinds.is_empty()) { + req_filters.push(Value::Object(req_filter)); + } + if includes_wake { + let mut wake_filter = serde_json::Map::new(); + wake_filter.insert("kinds".into(), json!([wake_kind])); + wake_filter.insert("#h".into(), json!([channel_id.to_string()])); + wake_filter.insert("#p".into(), json!([agent_pubkey_hex])); + wake_filter.insert("since".into(), json!(since_ts)); + req_filters.push(Value::Object(wake_filter)); + } + + let mut req = vec![json!("REQ"), json!(sub_id)]; + req.extend(req_filters); + Value::Array(req) +} + async fn send_subscribe( ws: &mut WsStream, _state: &BgState, @@ -3393,24 +3495,6 @@ async fn send_subscribe( filter: &ChannelFilter, ) -> bool { let sub_id = channel_sub_id(channel_id); - - let mut req_filter = serde_json::Map::new(); - - // kinds — omit entirely for wildcard subscriptions. - if let Some(ref kinds) = filter.kinds { - req_filter.insert("kinds".into(), json!(kinds)); - } - - // #h — always present (channel scope). - req_filter.insert("#h".into(), json!([channel_id.to_string()])); - - // #p — only when require_mention is true. - if filter.require_mention { - req_filter.insert("#p".into(), json!([agent_pubkey_hex])); - } - - // since — on first subscribe use current time to skip history; on reconnect - // subtract skew buffer to catch events missed during the disconnect window. let since_ts = match since { Some(ts) => ts.saturating_sub(SINCE_SKEW_SECS), None => std::time::SystemTime::now() @@ -3418,9 +3502,7 @@ async fn send_subscribe( .unwrap_or_default() .as_secs(), }; - req_filter.insert("since".into(), json!(since_ts)); - - let req = json!(["REQ", sub_id, Value::Object(req_filter)]); + let req = build_channel_req(&sub_id, channel_id, agent_pubkey_hex, since_ts, filter); match serde_json::to_string(&req) { Ok(text) => { @@ -4363,6 +4445,38 @@ mod tests { server.abort(); } + #[test] + fn workflow_wake_uses_exact_recipient_filter_when_mentions_are_disabled() { + let channel = Uuid::new_v4(); + let agent = nostr::Keys::generate().public_key().to_hex(); + let req = build_channel_req( + "sub", + channel, + &agent, + 123, + &ChannelFilter { + kinds: Some(vec![ + buzz_core::kind::KIND_STREAM_MESSAGE, + buzz_core::kind::KIND_WORKFLOW_MENTION_WAKE, + ]), + require_mention: false, + }, + ); + let filters = req.as_array().expect("REQ array"); + assert_eq!(filters.len(), 4); + assert_eq!( + filters[2]["kinds"], + json!([buzz_core::kind::KIND_STREAM_MESSAGE]) + ); + assert!(filters[2].get("#p").is_none()); + assert_eq!( + filters[3]["kinds"], + json!([buzz_core::kind::KIND_WORKFLOW_MENTION_WAKE]) + ); + assert_eq!(filters[3]["#p"], json!([agent])); + assert_eq!(filters[3]["#h"], json!([channel.to_string()])); + } + #[test] fn relay_ws_to_http_plain() { assert_eq!( diff --git a/crates/buzz-acp/src/workflow_wake.rs b/crates/buzz-acp/src/workflow_wake.rs new file mode 100644 index 0000000000..4c6f4ec925 --- /dev/null +++ b/crates/buzz-acp/src/workflow_wake.rs @@ -0,0 +1,347 @@ +//! Fail-closed verification of relay-signed workflow mention wakes. + +use buzz_core::kind::{KIND_STREAM_MESSAGE, KIND_WORKFLOW_DEF}; +use buzz_core::workflow_wake::WorkflowMentionWake; +use nostr::{Event, PublicKey}; +use serde::Deserialize; +use uuid::Uuid; + +#[derive(Debug, Deserialize)] +struct WorkflowAuthority { + steps: Vec, +} + +#[derive(Debug, Deserialize)] +struct WorkflowAuthorityStep { + id: String, + action: String, + #[serde(default)] + channel: Option, +} + +/// Exact public authority bundle returned by the authenticated relay read. +#[derive(Debug, Deserialize)] +pub struct WorkflowWakeAuthority { + /// Exact run ID. + pub run_id: Uuid, + /// Exact workflow channel. + pub channel_id: Uuid, + /// Workflow ID named by the signed definition. + pub workflow_id: Uuid, + /// Exact signed definition revision ID. + pub definition_event_id: String, + /// Workflow owner authenticated against relay workflow state. + pub workflow_owner: String, + /// Owner-signed workflow definition. + pub definition: Event, + /// Relay-signed visible message. + pub message: Event, +} + +/// Verify every authority edge and return the visible message plus its signed author principal. +pub fn verify( + wake_event: &Event, + authority: WorkflowWakeAuthority, + relay_pubkey: PublicKey, + agent_pubkey: PublicKey, + subscription_channel: Uuid, +) -> Option<(Event, String)> { + if wake_event.pubkey != relay_pubkey || wake_event.verify().is_err() { + return None; + } + let wake = WorkflowMentionWake::parse(wake_event).ok()?; + if wake.recipient() != agent_pubkey + || authority.workflow_owner != authority.definition.pubkey.to_hex() + || wake.run_id() != authority.run_id + || wake.channel_id() != subscription_channel + || wake.channel_id() != authority.channel_id + || wake.definition_event_id().to_hex() != authority.definition_event_id + || wake.message_event_id() != authority.message.id + { + return None; + } + + let definition = authority.definition; + if definition.verify().is_err() + || definition.kind.as_u16() as u32 != KIND_WORKFLOW_DEF + || definition.id != wake.definition_event_id() + || !exact_tag(&definition, "d", &authority.workflow_id.to_string()) + { + return None; + } + let channel = single_tag(&definition, "h")?; + if channel != authority.channel_id.to_string() { + return None; + } + let message = authority.message; + if message.verify().is_err() + || message.pubkey != relay_pubkey + || message.kind.as_u16() as u32 != KIND_STREAM_MESSAGE + || !exact_tag(&message, "h", channel) + || !contains_tag(&message, "p", &agent_pubkey.to_hex()) + || !exact_tag(&message, "workflow-run", &authority.run_id.to_string()) + || !exact_tag(&message, "workflow-definition", &definition.id.to_hex()) + { + return None; + } + let step_id = single_tag(&message, "workflow-step")?; + let workflow: WorkflowAuthority = serde_yaml::from_str(&definition.content).ok()?; + let step = workflow.steps.iter().find(|step| step.id == step_id)?; + if step.action != "send_message" { + return None; + } + if step + .channel + .as_deref() + .map(str::trim) + .filter(|value| !value.is_empty()) + .is_some_and(|value| value != channel) + { + return None; + } + Some((message, definition.pubkey.to_hex())) +} + +fn single_tag<'a>(event: &'a Event, name: &str) -> Option<&'a str> { + let mut matches = event.tags.iter().filter_map(|tag| { + let values = tag.as_slice(); + (values.len() == 2 && values[0] == name).then(|| values[1].as_str()) + }); + let value = matches.next()?; + matches.next().is_none().then_some(value) +} + +fn exact_tag(event: &Event, name: &str, value: &str) -> bool { + single_tag(event, name).is_some_and(|actual| actual.eq_ignore_ascii_case(value)) +} + +fn contains_tag(event: &Event, name: &str, value: &str) -> bool { + event.tags.iter().any(|tag| { + let values = tag.as_slice(); + values.len() == 2 && values[0] == name && values[1].eq_ignore_ascii_case(value) + }) +} + +#[cfg(test)] +mod tests { + use super::*; + use buzz_core::kind::KIND_WORKFLOW_MENTION_WAKE; + use nostr::{EventBuilder, Keys, Kind, Tag}; + + struct Fixture { + relay: Keys, + agent: Keys, + owner: Keys, + channel: Uuid, + run: Uuid, + workflow: Uuid, + definition: Event, + message: Event, + wake: Event, + } + + impl Fixture { + fn new(definition_content: &str, target_channel: Option) -> Self { + let relay = Keys::generate(); + let agent = Keys::generate(); + let owner = Keys::generate(); + let channel = Uuid::new_v4(); + let run = Uuid::new_v4(); + let workflow = Uuid::new_v4(); + let definition = EventBuilder::new( + Kind::Custom(KIND_WORKFLOW_DEF as u16), + definition_content + .replace("$CHANNEL", &target_channel.unwrap_or(channel).to_string()), + ) + .tags([ + Tag::parse(["d", &workflow.to_string()]).expect("d tag"), + Tag::parse(["h", &channel.to_string()]).expect("h tag"), + ]) + .sign_with_keys(&owner) + .expect("definition"); + let message = EventBuilder::new(Kind::Custom(KIND_STREAM_MESSAGE as u16), "do work") + .tags([ + Tag::parse(["h", &channel.to_string()]).expect("h tag"), + Tag::parse(["p", &agent.public_key().to_hex()]).expect("p tag"), + Tag::parse(["workflow-run", &run.to_string()]).expect("run tag"), + Tag::parse(["workflow-definition", &definition.id.to_hex()]) + .expect("definition tag"), + Tag::parse(["workflow-step", "notify"]).expect("step tag"), + ]) + .sign_with_keys(&relay) + .expect("message"); + let wake = WorkflowMentionWake::new( + agent.public_key(), + channel, + run, + definition.id, + message.id, + ) + .sign(&relay) + .expect("wake"); + Self { + relay, + agent, + owner, + channel, + run, + workflow, + definition, + message, + wake, + } + } + + fn valid() -> Self { + Self::new( + "name: wake\ntrigger:\n on: message_posted\nsteps:\n - id: notify\n action: send_message\n text: do work\n channel: $CHANNEL\n", + None, + ) + } + + fn authority(&self) -> WorkflowWakeAuthority { + WorkflowWakeAuthority { + run_id: self.run, + channel_id: self.channel, + workflow_id: self.workflow, + definition_event_id: self.definition.id.to_hex(), + workflow_owner: self.owner.public_key().to_hex(), + definition: self.definition.clone(), + message: self.message.clone(), + } + } + + fn verify(&self, authority: WorkflowWakeAuthority) -> Option<(Event, String)> { + super::verify( + &self.wake, + authority, + self.relay.public_key(), + self.agent.public_key(), + self.channel, + ) + } + } + + #[test] + fn accepts_exact_authority_and_returns_signed_owner() { + let fixture = Fixture::valid(); + let (message, author) = fixture.verify(fixture.authority()).expect("verified"); + assert_eq!(message.id, fixture.message.id); + assert_eq!(author, fixture.owner.public_key().to_hex()); + } + + #[test] + fn rejects_wrong_wake_signer_or_recipient() { + let fixture = Fixture::valid(); + assert!(super::verify( + &fixture.wake, + fixture.authority(), + Keys::generate().public_key(), + fixture.agent.public_key(), + fixture.channel, + ) + .is_none()); + assert!(super::verify( + &fixture.wake, + fixture.authority(), + fixture.relay.public_key(), + Keys::generate().public_key(), + fixture.channel, + ) + .is_none()); + } + + #[test] + fn rejects_mismatched_run_revision_message_channel_and_owner() { + let fixture = Fixture::valid(); + let mut authority = fixture.authority(); + authority.run_id = Uuid::new_v4(); + assert!(fixture.verify(authority).is_none()); + + let mut authority = fixture.authority(); + authority.definition_event_id = EventBuilder::text_note("other") + .sign_with_keys(&Keys::generate()) + .expect("event") + .id + .to_hex(); + assert!(fixture.verify(authority).is_none()); + + let mut authority = fixture.authority(); + authority.message = EventBuilder::text_note("other") + .sign_with_keys(&fixture.relay) + .expect("event"); + assert!(fixture.verify(authority).is_none()); + + let mut authority = fixture.authority(); + authority.channel_id = Uuid::new_v4(); + assert!(fixture.verify(authority).is_none()); + + let mut authority = fixture.authority(); + authority.workflow_owner = Keys::generate().public_key().to_hex(); + assert!(fixture.verify(authority).is_none()); + } + + #[test] + fn rejects_malformed_or_non_send_message_instruction() { + let malformed = Fixture::new("not: [valid", None); + assert!(malformed.verify(malformed.authority()).is_none()); + + let other_action = Fixture::new( + "name: wake\ntrigger:\n on: message_posted\nsteps:\n - id: notify\n action: add_reaction\n emoji: thumbsup\n", + None, + ); + assert!(other_action.verify(other_action.authority()).is_none()); + } + + #[test] + fn rejects_wrong_step_or_target_channel() { + let fixture = Fixture::valid(); + let wrong_step_message = + EventBuilder::new(Kind::Custom(KIND_STREAM_MESSAGE as u16), "do work") + .tags([ + Tag::parse(["h", &fixture.channel.to_string()]).expect("h tag"), + Tag::parse(["p", &fixture.agent.public_key().to_hex()]).expect("p tag"), + Tag::parse(["workflow-run", &fixture.run.to_string()]).expect("run tag"), + Tag::parse(["workflow-definition", &fixture.definition.id.to_hex()]) + .expect("definition tag"), + Tag::parse(["workflow-step", "missing"]).expect("step tag"), + ]) + .sign_with_keys(&fixture.relay) + .expect("message"); + let wrong_step_wake = WorkflowMentionWake::new( + fixture.agent.public_key(), + fixture.channel, + fixture.run, + fixture.definition.id, + wrong_step_message.id, + ) + .sign(&fixture.relay) + .expect("wake"); + let mut authority = fixture.authority(); + authority.message = wrong_step_message; + assert!(super::verify( + &wrong_step_wake, + authority, + fixture.relay.public_key(), + fixture.agent.public_key(), + fixture.channel, + ) + .is_none()); + + let wrong_target = Fixture::new( + "name: wake\ntrigger:\n on: message_posted\nsteps:\n - id: notify\n action: send_message\n text: do work\n channel: $CHANNEL\n", + Some(Uuid::new_v4()), + ); + assert!(wrong_target.verify(wrong_target.authority()).is_none()); + } + + #[test] + fn wake_kind_remains_identifier_only() { + let fixture = Fixture::valid(); + assert_eq!( + fixture.wake.kind.as_u16() as u32, + KIND_WORKFLOW_MENTION_WAKE + ); + assert!(fixture.wake.content.is_empty()); + } +} diff --git a/crates/buzz-core/src/kind.rs b/crates/buzz-core/src/kind.rs index 4e1ab1c7f5..6b3161c5c1 100644 --- a/crates/buzz-core/src/kind.rs +++ b/crates/buzz-core/src/kind.rs @@ -158,6 +158,7 @@ pub const RESULT_GATED_KINDS: &[u32] = &[KIND_DM_VISIBILITY, KIND_AGENT_TURN_MET /// storage-layer search defense does not apply to them. pub const P_GATED_KINDS: &[u32] = &[ KIND_AGENT_OBSERVER_FRAME, + KIND_WORKFLOW_MENTION_WAKE, KIND_MEMBER_ADDED_NOTIFICATION, KIND_MEMBER_REMOVED_NOTIFICATION, KIND_GIFT_WRAP, @@ -467,6 +468,8 @@ pub const KIND_PAIRING: u32 = 24134; pub const KIND_TYPING_INDICATOR: u32 = 20002; /// Ephemeral: owner-scoped encrypted agent observer telemetry and control frame. pub const KIND_AGENT_OBSERVER_FRAME: u32 = 24200; +/// Ephemeral: relay-signed identifier-only workflow mention wake. +pub const KIND_WORKFLOW_MENTION_WAKE: u32 = 24620; /// Ephemeral: huddle emoji reaction burst. Channel-scoped to the ephemeral /// huddle channel with an `h` tag; never stored in the timeline. pub const KIND_HUDDLE_REACTION: u32 = 24810; @@ -700,6 +703,7 @@ pub const ALL_KINDS: &[u32] = &[ KIND_BLOSSOM_AUTH, KIND_PAIRING, KIND_AGENT_OBSERVER_FRAME, + KIND_WORKFLOW_MENTION_WAKE, KIND_HTTP_AUTH, KIND_STREAM_MESSAGE, KIND_STREAM_MESSAGE_V2, diff --git a/crates/buzz-core/src/lib.rs b/crates/buzz-core/src/lib.rs index 36dc772da3..574abc9e88 100644 --- a/crates/buzz-core/src/lib.rs +++ b/crates/buzz-core/src/lib.rs @@ -42,6 +42,8 @@ pub mod relay; pub mod tenant; /// Schnorr signature and event ID verification. pub mod verification; +/// Identifier-only workflow mention wake hints. +pub mod workflow_wake; pub use error::VerificationError; pub use event::StoredEvent; diff --git a/crates/buzz-core/src/workflow_wake.rs b/crates/buzz-core/src/workflow_wake.rs new file mode 100644 index 0000000000..b5d60ab200 --- /dev/null +++ b/crates/buzz-core/src/workflow_wake.rs @@ -0,0 +1,327 @@ +//! Identifier-only wake hints for verified workflow mentions. +//! +//! A wake grants no instruction authority. Receivers must authenticate the +//! relay and fetch the exact run-bound workflow definition and visible message +//! before dispatching anything. + +use nostr::{Event, EventBuilder, EventId, Keys, Kind, PublicKey, Tag}; +use thiserror::Error; +use uuid::Uuid; + +use crate::kind::KIND_WORKFLOW_MENTION_WAKE; + +/// A relay-signed, ephemeral hint that a workflow message mentioned one agent. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct WorkflowMentionWake { + recipient: PublicKey, + channel_id: Uuid, + run_id: Uuid, + definition_event_id: EventId, + message_event_id: EventId, +} + +impl WorkflowMentionWake { + /// Construct an identifier-only wake. + pub const fn new( + recipient: PublicKey, + channel_id: Uuid, + run_id: Uuid, + definition_event_id: EventId, + message_event_id: EventId, + ) -> Self { + Self { + recipient, + channel_id, + run_id, + definition_event_id, + message_event_id, + } + } + + /// Sign the canonical empty-content event with the relay identity. + pub fn sign(self, relay_keys: &Keys) -> Result { + EventBuilder::new(Kind::Custom(KIND_WORKFLOW_MENTION_WAKE as u16), "") + .tags(self.canonical_tags()?) + .sign_with_keys(relay_keys) + .map_err(|error| WorkflowMentionWakeError::Signing(error.to_string())) + } + + /// Parse the exact canonical wire shape. Unknown, duplicate, or malformed + /// identity tags are rejected rather than ignored. + pub fn parse(event: &Event) -> Result { + if event.kind.as_u16() as u32 != KIND_WORKFLOW_MENTION_WAKE { + return Err(WorkflowMentionWakeError::WrongKind(event.kind.as_u16())); + } + if !event.content.is_empty() { + return Err(WorkflowMentionWakeError::NonEmptyContent); + } + if event.tags.len() != 5 { + return Err(WorkflowMentionWakeError::WrongTagCount(event.tags.len())); + } + + let tags: Vec<&[String]> = event.tags.iter().map(|tag| tag.as_slice()).collect(); + let recipient = parse_single(&tags, "p", PublicKey::from_hex)?; + let channel_id = parse_single(&tags, "h", |value| value.parse::())?; + let run_id = parse_single(&tags, "run", |value| { + value + .parse::() + .ok() + .filter(|id| !id.is_nil()) + .ok_or(()) + })?; + let definition_event_id = parse_single(&tags, "definition", EventId::from_hex)?; + let message_event_id = parse_single(&tags, "message", EventId::from_hex)?; + + let wake = Self::new( + recipient, + channel_id, + run_id, + definition_event_id, + message_event_id, + ); + let canonical = [ + vec!["p".to_string(), wake.recipient.to_hex()], + vec!["h".to_string(), wake.channel_id.to_string()], + vec!["run".to_string(), wake.run_id.to_string()], + vec!["definition".to_string(), wake.definition_event_id.to_hex()], + vec!["message".to_string(), wake.message_event_id.to_hex()], + ]; + if tags + .iter() + .zip(canonical.iter()) + .any(|(actual, expected)| *actual != expected.as_slice()) + { + return Err(WorkflowMentionWakeError::NonCanonicalTags); + } + Ok(wake) + } + + /// Intended recipient. + pub const fn recipient(self) -> PublicKey { + self.recipient + } + + /// Workflow channel carrying the visible generated message. + pub const fn channel_id(self) -> Uuid { + self.channel_id + } + + /// Exact workflow run. + pub const fn run_id(self) -> Uuid { + self.run_id + } + + /// Exact signed workflow-definition revision selected by the run. + pub const fn definition_event_id(self) -> EventId { + self.definition_event_id + } + + /// Exact visible workflow message to dispatch after verification. + pub const fn message_event_id(self) -> EventId { + self.message_event_id + } + + fn canonical_tags(self) -> Result, WorkflowMentionWakeError> { + [ + vec!["p".to_string(), self.recipient.to_hex()], + vec!["h".to_string(), self.channel_id.to_string()], + vec!["run".to_string(), self.run_id.to_string()], + vec!["definition".to_string(), self.definition_event_id.to_hex()], + vec!["message".to_string(), self.message_event_id.to_hex()], + ] + .into_iter() + .map(|values| { + Tag::parse(values).map_err(|error| WorkflowMentionWakeError::Tag(error.to_string())) + }) + .collect() + } +} + +fn parse_single( + tags: &[&[String]], + name: &'static str, + parse: impl FnOnce(&str) -> Result, +) -> Result { + let matches: Vec<_> = tags + .iter() + .filter(|tag| tag.first().map(String::as_str) == Some(name)) + .collect(); + if matches.len() != 1 || matches[0].len() != 2 { + return Err(WorkflowMentionWakeError::InvalidTag(name)); + } + parse(&matches[0][1]).map_err(|_| WorkflowMentionWakeError::InvalidTag(name)) +} + +/// Invalid workflow mention wake. +#[derive(Debug, Error, PartialEq, Eq)] +pub enum WorkflowMentionWakeError { + /// Event kind is not the workflow mention wake kind. + #[error("wrong workflow mention wake kind: {0}")] + WrongKind(u16), + /// Wake content must be empty. + #[error("workflow mention wake content must be empty")] + NonEmptyContent, + /// Wake must contain exactly the five canonical identity tags. + #[error("wrong workflow mention wake tag count: {0}")] + WrongTagCount(usize), + /// A required identity tag is missing, duplicated, malformed, or has extra fields. + #[error("invalid workflow mention wake {0} tag")] + InvalidTag(&'static str), + /// Tags are not in canonical order or contain a non-canonical representation. + #[error("workflow mention wake tags are not canonical")] + NonCanonicalTags, + /// Canonical tag construction failed. + #[error("workflow mention wake tag construction failed: {0}")] + Tag(String), + /// Event signing failed. + #[error("workflow mention wake signing failed: {0}")] + Signing(String), +} + +#[cfg(test)] +mod tests { + use super::*; + + fn ids() -> (Keys, PublicKey, Uuid, EventId, EventId) { + let relay = Keys::generate(); + let recipient = Keys::generate().public_key(); + let run = Uuid::new_v4(); + let definition = EventBuilder::text_note("definition") + .sign_with_keys(&Keys::generate()) + .expect("sign definition") + .id; + let message = EventBuilder::text_note("message") + .sign_with_keys(&relay) + .expect("sign message") + .id; + (relay, recipient, run, definition, message) + } + + fn custom_event(content: &str, tags: Vec>) -> Event { + EventBuilder::new(Kind::Custom(KIND_WORKFLOW_MENTION_WAKE as u16), content) + .tags( + tags.into_iter() + .map(|values| Tag::parse(values).expect("tag")), + ) + .sign_with_keys(&Keys::generate()) + .expect("sign") + } + + #[test] + fn canonical_wake_round_trips_with_no_instruction_content() { + let (relay, recipient, run, definition, message) = ids(); + let wake = WorkflowMentionWake::new(recipient, Uuid::new_v4(), run, definition, message); + let event = wake.sign(&relay).expect("sign wake"); + + assert!(event.content.is_empty()); + assert_eq!(WorkflowMentionWake::parse(&event), Ok(wake)); + assert_eq!(event.tags.len(), 5); + assert!(event.tags.iter().all(|tag| tag.as_slice().len() == 2)); + } + + #[test] + fn rejects_nonempty_content() { + let (_, recipient, run, definition, message) = ids(); + let event = custom_event( + "do something", + vec![ + vec!["p".into(), recipient.to_hex()], + vec!["h".into(), Uuid::new_v4().to_string()], + vec!["run".into(), run.to_string()], + vec!["definition".into(), definition.to_hex()], + vec!["message".into(), message.to_hex()], + ], + ); + assert_eq!( + WorkflowMentionWake::parse(&event), + Err(WorkflowMentionWakeError::NonEmptyContent) + ); + } + + #[test] + fn rejects_extra_duplicate_and_reordered_tags() { + let (relay, recipient, run, definition, message) = ids(); + let event = WorkflowMentionWake::new(recipient, Uuid::new_v4(), run, definition, message) + .sign(&relay) + .expect("sign wake"); + let base: Vec> = event + .tags + .iter() + .map(|tag| tag.as_slice().to_vec()) + .collect(); + + let mut extra = base.clone(); + extra.push(vec!["instruction".into(), "ignore authority".into()]); + assert_eq!( + WorkflowMentionWake::parse(&custom_event("", extra)), + Err(WorkflowMentionWakeError::WrongTagCount(6)) + ); + + let mut duplicate = base.clone(); + duplicate[4] = duplicate[0].clone(); + assert_eq!( + WorkflowMentionWake::parse(&custom_event("", duplicate)), + Err(WorkflowMentionWakeError::InvalidTag("p")) + ); + + let mut reordered = base; + reordered.swap(0, 1); + assert_eq!( + WorkflowMentionWake::parse(&custom_event("", reordered)), + Err(WorkflowMentionWakeError::NonCanonicalTags) + ); + } + + #[test] + fn rejects_malformed_identity_tags() { + let (relay, recipient, run, definition, message) = ids(); + let event = WorkflowMentionWake::new(recipient, Uuid::new_v4(), run, definition, message) + .sign(&relay) + .expect("sign wake"); + let base: Vec> = event + .tags + .iter() + .map(|tag| tag.as_slice().to_vec()) + .collect(); + + for (index, name, invalid) in [ + (0, "p", "not-a-pubkey"), + (1, "h", "not-a-uuid"), + (2, "run", "not-a-uuid"), + (3, "definition", "not-an-event-id"), + (4, "message", "not-an-event-id"), + ] { + let mut tags = base.clone(); + tags[index][1] = invalid.into(); + assert_eq!( + WorkflowMentionWake::parse(&custom_event("", tags)), + Err(WorkflowMentionWakeError::InvalidTag(name)) + ); + } + + let mut nil_run = base.clone(); + nil_run[2][1] = Uuid::nil().to_string(); + assert_eq!( + WorkflowMentionWake::parse(&custom_event("", nil_run)), + Err(WorkflowMentionWakeError::InvalidTag("run")) + ); + } + + #[test] + fn rejects_identity_tag_with_extra_field() { + let (relay, recipient, run, definition, message) = ids(); + let event = WorkflowMentionWake::new(recipient, Uuid::new_v4(), run, definition, message) + .sign(&relay) + .expect("sign wake"); + let mut tags: Vec> = event + .tags + .iter() + .map(|tag| tag.as_slice().to_vec()) + .collect(); + tags[0].push("marker".into()); + assert_eq!( + WorkflowMentionWake::parse(&custom_event("", tags)), + Err(WorkflowMentionWakeError::InvalidTag("p")) + ); + } +} diff --git a/crates/buzz-relay/src/api/workflows.rs b/crates/buzz-relay/src/api/workflows.rs index c7fa09bebd..7748941d59 100644 --- a/crates/buzz-relay/src/api/workflows.rs +++ b/crates/buzz-relay/src/api/workflows.rs @@ -228,6 +228,96 @@ fn approval_json(approval: &buzz_db::workflow::ApprovalRecord) -> Value { }) } +/// `GET /workflow-wakes/{run_id}/{message_id}` — exact authority bundle for one wake. +pub async fn workflow_wake_authority( + State(state): State>, + Path((run_id, message_id)): Path<(Uuid, String)>, + headers: HeaderMap, +) -> Result, (StatusCode, Json)> { + let path = format!("/workflow-wakes/{run_id}/{message_id}"); + let raw_host = headers + .get(axum::http::header::HOST) + .and_then(|value| value.to_str().ok()) + .unwrap_or(""); + let tenant = crate::tenant::bind_community(&state.db, raw_host) + .await + .map_err(|_| api_error(StatusCode::NOT_FOUND, "workflow wake not found"))?; + let url = bridge::nip98_expected_url(&state.config.relay_url, &tenant, &path); + let (recipient, auth_event_id) = + bridge::verify_bridge_auth(&headers, "GET", &url, None, state.config.require_auth_token)?; + bridge::enforce_http_admission(&state, &tenant, &recipient).await?; + bridge::check_nip98_replay(&state, &tenant, auth_event_id).await?; + + let run = state + .db + .get_workflow_run(tenant.community(), run_id) + .await + .map_err(|_| api_error(StatusCode::NOT_FOUND, "workflow wake not found"))?; + let workflow = state + .db + .get_workflow(tenant.community(), run.workflow_id) + .await + .map_err(|_| api_error(StatusCode::NOT_FOUND, "workflow wake not found"))?; + let definition_id = run + .definition_event_id + .as_deref() + .filter(|id| id.len() == 32) + .ok_or_else(|| api_error(StatusCode::NOT_FOUND, "workflow wake not found"))?; + let message_id = nostr::EventId::from_hex(&message_id) + .map_err(|_| api_error(StatusCode::BAD_REQUEST, "invalid message id"))?; + let definition = state + .db + .get_event_by_id(tenant.community(), definition_id) + .await + .map_err(|error| internal_error(&format!("workflow definition lookup: {error}")))? + .ok_or_else(|| api_error(StatusCode::NOT_FOUND, "workflow wake not found"))?; + let message = state + .db + .get_event_by_id(tenant.community(), message_id.as_bytes()) + .await + .map_err(|error| internal_error(&format!("workflow message lookup: {error}")))? + .ok_or_else(|| api_error(StatusCode::NOT_FOUND, "workflow wake not found"))?; + + let recipient_hex = recipient.to_hex(); + let exact_tag = |event: &nostr::Event, name: &str, value: &str| { + event.tags.iter().any(|tag| { + let values = tag.as_slice(); + values.len() == 2 && values[0] == name && values[1].eq_ignore_ascii_case(value) + }) + }; + let message_channel = message + .channel_id + .ok_or_else(|| api_error(StatusCode::NOT_FOUND, "workflow wake not found"))?; + if workflow.owner_pubkey != definition.event.pubkey.to_bytes() + || workflow.channel_id != Some(message_channel) + || !exact_tag(&definition.event, "h", &message_channel.to_string()) + || !exact_tag(&definition.event, "d", &run.workflow_id.to_string()) + || !exact_tag(&message.event, "h", &message_channel.to_string()) + || !message.event.tags.iter().any(|tag| { + let values = tag.as_slice(); + values.len() == 2 && values[0] == "p" && values[1].eq_ignore_ascii_case(&recipient_hex) + }) + || !exact_tag(&message.event, "workflow-run", &run_id.to_string()) + || !exact_tag( + &message.event, + "workflow-definition", + &definition.event.id.to_hex(), + ) + { + return Err(api_error(StatusCode::NOT_FOUND, "workflow wake not found")); + } + + Ok(Json(serde_json::json!({ + "run_id": run.id, + "channel_id": message_channel, + "workflow_id": run.workflow_id, + "definition_event_id": definition.event.id.to_hex(), + "workflow_owner": hex::encode(&workflow.owner_pubkey), + "definition": definition.event, + "message": message.event, + }))) +} + #[cfg(test)] mod tests { use super::*; diff --git a/crates/buzz-relay/src/handlers/event.rs b/crates/buzz-relay/src/handlers/event.rs index 66a8ff9e7c..086dfb3001 100644 --- a/crates/buzz-relay/src/handlers/event.rs +++ b/crates/buzz-relay/src/handlers/event.rs @@ -337,6 +337,28 @@ pub async fn fan_out_pubsub_event(state: &Arc, channel_event: buzz_pub } } +/// Fan out one relay-generated ephemeral event without passing through client admission. +/// +/// The event is never stored. Global routing plus `P_GATED_KINDS` ensures only a +/// subscription authenticated as the exact `p` recipient can receive a wake. +pub(crate) async fn dispatch_ephemeral_event( + tenant: &TenantContext, + state: &Arc, + event: Event, + channel_id: Option, +) { + state.mark_local_event(tenant.community(), &event.id); + let topic = channel_id.map_or(EventTopic::Global, EventTopic::Channel); + if let Err(error) = state.pubsub.publish_event(tenant, topic, &event).await { + state + .local_event_ids + .invalidate(&(tenant.community(), event.id.to_bytes())); + warn!(event_id = %event.id, %error, "relay-generated ephemeral publish failed"); + } + let stored = StoredEvent::new(event, channel_id); + fan_out_event_to_local_subscribers(state, tenant.community(), &stored).await; +} + /// Schedule post-commit delivery/side effects for a stored event. /// /// This intentionally returns after only the bounded audit enqueue has completed: diff --git a/crates/buzz-relay/src/handlers/req.rs b/crates/buzz-relay/src/handlers/req.rs index 9a141e86ff..b406774135 100644 --- a/crates/buzz-relay/src/handlers/req.rs +++ b/crates/buzz-relay/src/handlers/req.rs @@ -227,18 +227,21 @@ pub async fn handle_req( // kinds) to harvest indexed-but-globally-stored sensitive events. Search // hits are looked up by event id and returned without the per-filter // post-check the historical-delivery branch applies, so the gate must run - // here, up front. Only applies to GLOBAL subscriptions (channel_id = None): - // channel-scoped subs can never receive globally-stored events because of - // the fan_out() invariant in subscription.rs. + // here, up front. P-gated authorization applies to every subscription; + // the other global-event gates below remain global-only. + // P-gated events require an exact authenticated recipient even when they + // are channel-scoped. Channel membership alone is not authority to observe + // another recipient's ephemeral workflow wake. + let authed_pubkey_hex = hex::encode(&pubkey_bytes); + if !p_gated_filters_authorized(&filters, &authed_pubkey_hex) { + conn.send(RelayMessage::closed( + &sub_id, + "restricted: p-gated events require #p matching your pubkey", + )); + return; + } + if channel_id.is_none() { - let authed_pubkey_hex = hex::encode(&pubkey_bytes); - if !p_gated_filters_authorized(&filters, &authed_pubkey_hex) { - conn.send(RelayMessage::closed( - &sub_id, - "restricted: p-gated events require #p matching your pubkey", - )); - return; - } if !engram_filters_authorized(&filters, &authed_pubkey_hex) { conn.send(RelayMessage::closed( &sub_id, diff --git a/crates/buzz-relay/src/router.rs b/crates/buzz-relay/src/router.rs index 61aedf70be..bca3724641 100644 --- a/crates/buzz-relay/src/router.rs +++ b/crates/buzz-relay/src/router.rs @@ -76,6 +76,10 @@ pub fn build_router(state: Arc) -> Router { // Relay-owned third-party GIF metadata proxy (NIP-98 auth). .route(api::gifs::SEARCH_PATH, post(api::gifs::search)) .route(api::gifs::SHARE_PATH, post(api::gifs::share)) + .route( + "/workflow-wakes/{run_id}/{message_id}", + get(api::workflows::workflow_wake_authority), + ) .route( "/workflows/{workflow_id}/runs", get(api::workflows::workflow_runs), diff --git a/crates/buzz-relay/src/workflow_sink.rs b/crates/buzz-relay/src/workflow_sink.rs index 55905db62a..503bb215a7 100644 --- a/crates/buzz-relay/src/workflow_sink.rs +++ b/crates/buzz-relay/src/workflow_sink.rs @@ -9,8 +9,8 @@ use std::pin::Pin; use std::sync::{Arc, Weak}; use buzz_core::kind::KIND_STREAM_MESSAGE; -use buzz_core::tenant::CommunityId; -use buzz_workflow::action_sink::{ActionSink, ActionSinkError}; +use buzz_core::workflow_wake::WorkflowMentionWake; +use buzz_workflow::action_sink::{ActionSink, ActionSinkError, WorkflowMessageContext}; use chrono::Utc; use nostr::{EventBuilder, Kind, Tag}; use tracing::info; @@ -205,13 +205,19 @@ impl RelayActionSink { impl ActionSink for RelayActionSink { fn send_message( &self, - community_id: CommunityId, + context: WorkflowMessageContext, channel_id: &str, text: &str, authored_text: &str, author_pubkey: &str, reply_to: Option<&str>, ) -> Pin> + Send + '_>> { + let WorkflowMessageContext { + community_id, + run_id, + step_id, + definition_event_id, + } = context; let channel_id = channel_id.to_owned(); let text = text.to_owned(); let authored_text = authored_text.to_owned(); @@ -387,6 +393,37 @@ impl ActionSink for RelayActionSink { &named_members, &author_pubkey_hex, )?; + let mentioned_pubkeys = tags.iter() + .filter(|tag| tag.as_slice().first().map(String::as_str) == Some("buzz:workflow-mention")) + .filter_map(|tag| tag.as_slice().get(1)) + .filter(|pk| *pk != &author_pubkey_hex) + .map(|pk| nostr::PublicKey::from_hex(pk).map_err(|e| ActionSinkError::EventBuild(format!("mention pubkey: {e}")))) + .collect::, _>>()?; + + let definition_event_id = definition_event_id + .as_deref() + .map(nostr::EventId::from_slice) + .transpose() + .map_err(|e| { + ActionSinkError::InvalidInput(format!("invalid definition event id: {e}")) + })?; + if let Some(definition_event_id) = definition_event_id { + tags.push( + Tag::parse(["workflow-run", &run_id.to_string()]).map_err(|e| { + ActionSinkError::EventBuild(format!("workflow run tag: {e}")) + })?, + ); + tags.push( + Tag::parse(["workflow-definition", &definition_event_id.to_hex()]).map_err( + |e| ActionSinkError::EventBuild(format!("workflow definition tag: {e}")), + )?, + ); + tags.push( + Tag::parse(["workflow-step", &step_id]).map_err(|e| { + ActionSinkError::EventBuild(format!("workflow step tag: {e}")) + })?, + ); + } let kind = Kind::from(KIND_STREAM_MESSAGE as u16); let event = EventBuilder::new(kind, &text) @@ -455,6 +492,23 @@ impl ActionSink for RelayActionSink { ) .await; + for wake in build_workflow_wakes( + &state.relay_keypair, + channel_uuid, + run_id, + definition_event_id, + event.id, + mentioned_pubkeys, + )? { + crate::handlers::event::dispatch_ephemeral_event( + &tenant, + &state, + wake, + Some(channel_uuid), + ) + .await; + } + // A threaded reply changed its thread's counters — push a fresh // relay-signed kind:39005 so subscribed clients update badge // counts without refetching the head window, exactly as the @@ -475,6 +529,33 @@ impl ActionSink for RelayActionSink { } } +fn build_workflow_wakes( + relay_keys: &nostr::Keys, + channel_id: Uuid, + run_id: Uuid, + definition_event_id: Option, + message_event_id: nostr::EventId, + recipients: Vec, +) -> Result, ActionSinkError> { + let Some(definition_event_id) = definition_event_id else { + return Ok(Vec::new()); + }; + recipients + .into_iter() + .map(|recipient| { + WorkflowMentionWake::new( + recipient, + channel_id, + run_id, + definition_event_id, + message_event_id, + ) + .sign(relay_keys) + .map_err(|error| ActionSinkError::EventBuild(format!("workflow wake: {error}"))) + }) + .collect() +} + #[cfg(test)] mod tests { use super::*; @@ -488,6 +569,62 @@ mod tests { std::iter::repeat_n(nibble, 64).collect() } + #[test] + fn legacy_message_without_revision_emits_no_wake() { + let relay = nostr::Keys::generate(); + let recipient = nostr::Keys::generate().public_key(); + let message = nostr::EventBuilder::text_note("message") + .sign_with_keys(&relay) + .expect("message"); + let wakes = build_workflow_wakes( + &relay, + Uuid::new_v4(), + Uuid::new_v4(), + None, + message.id, + vec![recipient], + ) + .expect("legacy wake build"); + assert!(wakes.is_empty()); + } + + #[test] + fn revision_bound_message_emits_one_identifier_wake_per_recipient() { + let relay = nostr::Keys::generate(); + let recipients = [ + nostr::Keys::generate().public_key(), + nostr::Keys::generate().public_key(), + ]; + let channel = Uuid::new_v4(); + let run = Uuid::new_v4(); + let definition = nostr::EventBuilder::text_note("definition") + .sign_with_keys(&nostr::Keys::generate()) + .expect("definition"); + let message = nostr::EventBuilder::text_note("message") + .sign_with_keys(&relay) + .expect("message"); + let wakes = build_workflow_wakes( + &relay, + channel, + run, + Some(definition.id), + message.id, + recipients.to_vec(), + ) + .expect("wake build"); + assert_eq!(wakes.len(), recipients.len()); + for (event, recipient) in wakes.iter().zip(recipients) { + let wake = WorkflowMentionWake::parse(event).expect("canonical wake"); + assert!(event.content.is_empty()); + assert_eq!(event.pubkey, relay.public_key()); + assert_eq!(wake.recipient(), recipient); + assert_eq!(wake.channel_id(), channel); + assert_eq!(wake.run_id(), run); + assert_eq!(wake.definition_event_id(), definition.id); + assert_eq!(wake.message_event_id(), message.id); + } + } + #[test] fn resolves_exact_member_name() { let members = vec![m("Robby", &pk('a'))]; @@ -1086,7 +1223,12 @@ mod postgres_tests { // 1. A top-level workflow message becomes the thread root. let root_hex = sink .send_message( - community, + WorkflowMessageContext { + community_id: community, + run_id: Uuid::new_v4(), + step_id: "test-step".into(), + definition_event_id: None, + }, &channel.id.to_string(), "root message", "root message", @@ -1099,7 +1241,12 @@ mod postgres_tests { // 2. A reply_in_thread message threads onto it. let reply_hex = sink .send_message( - community, + WorkflowMessageContext { + community_id: community, + run_id: Uuid::new_v4(), + step_id: "test-step".into(), + definition_event_id: None, + }, &channel.id.to_string(), "threaded reply", "threaded reply", @@ -1242,7 +1389,12 @@ mod postgres_tests { // A workflow reply onto the metadata-less nested parent. let reply_hex = RelayActionSink::new(&state) .send_message( - community, + WorkflowMessageContext { + community_id: community, + run_id: Uuid::new_v4(), + step_id: "test-step".into(), + definition_event_id: None, + }, &channel_hex, "workflow reply", "workflow reply", @@ -1324,7 +1476,12 @@ mod postgres_tests { let root_only_reply_hex = RelayActionSink::new(&state) .send_message( - community, + WorkflowMessageContext { + community_id: community, + run_id: Uuid::new_v4(), + step_id: "test-step".into(), + definition_event_id: None, + }, &channel_hex, "workflow reply to root-only parent", "workflow reply to root-only parent", @@ -1387,7 +1544,12 @@ mod postgres_tests { let unknown = nostr::Keys::generate().public_key().to_hex(); let err = RelayActionSink::new(&state) .send_message( - community, + WorkflowMessageContext { + community_id: community, + run_id: Uuid::new_v4(), + step_id: "test-step".into(), + definition_event_id: None, + }, &channel.id.to_string(), "orphan reply", "orphan reply", diff --git a/crates/buzz-workflow/src/action_sink.rs b/crates/buzz-workflow/src/action_sink.rs index b8c7f4dd80..4f13662615 100644 --- a/crates/buzz-workflow/src/action_sink.rs +++ b/crates/buzz-workflow/src/action_sink.rs @@ -7,6 +7,21 @@ use std::future::Future; use std::pin::Pin; use buzz_core::tenant::CommunityId; +use uuid::Uuid; + +/// Workflow authority carried into a message side effect. +#[derive(Debug, Clone)] +pub struct WorkflowMessageContext { + /// Server-resolved community that owns the workflow run. + pub community_id: CommunityId, + /// Exact workflow run driving this side effect. + pub run_id: Uuid, + /// Exact signed-definition step being executed. + pub step_id: String, + /// Exact signed definition selected when the run was created, or `None` + /// for a legacy run that must not emit an automatic wake. + pub definition_event_id: Option>, +} /// Errors from action sink operations. #[derive(Debug, thiserror::Error)] @@ -48,11 +63,8 @@ impl From for crate::WorkflowError { pub trait ActionSink: Send + Sync { /// Post a message to a channel on behalf of a workflow owner. /// - /// - `community_id`: the server-resolved community that owns the workflow - /// run driving this side effect. The relay-signed message is published - /// under *this* community, never the deployment/default tenant — the run - /// carries its owning community so a workflow in community B posts into B - /// even though the side effect has no inbound connection to bind. + /// - `context`: exact workflow authority driving this side effect, including + /// the server-resolved community and optional signed-definition revision /// - `channel_id`: UUID string of the target channel /// - `text`: rendered message body (must not be empty/whitespace-only) /// - `authored_text`: the workflow owner's stored, unrendered step template; @@ -67,7 +79,7 @@ pub trait ActionSink: Send + Sync { /// Returns the event ID hex string on success. fn send_message( &self, - community_id: CommunityId, + context: WorkflowMessageContext, channel_id: &str, text: &str, authored_text: &str, diff --git a/crates/buzz-workflow/src/executor.rs b/crates/buzz-workflow/src/executor.rs index 90a6a02e02..288ec875ea 100644 --- a/crates/buzz-workflow/src/executor.rs +++ b/crates/buzz-workflow/src/executor.rs @@ -18,6 +18,7 @@ use serde_json::Value as JsonValue; use tracing::{debug, info, warn}; use uuid::Uuid; +use crate::action_sink::WorkflowMessageContext; use crate::error::WorkflowError; use crate::schema::{ActionDef, Step, WorkflowDef}; use crate::WorkflowEngine; @@ -636,7 +637,12 @@ pub async fn dispatch_action( let event_id = engine .action_sink()? .send_message( - community_id, + WorkflowMessageContext { + community_id, + run_id, + step_id: step_id.to_owned(), + definition_event_id: wf_run.definition_event_id.clone(), + }, &channel_id, text, authored_text,