diff --git a/src/crates/assembly/core/src/service/remote_connect/bot/feishu.rs b/src/crates/assembly/core/src/service/remote_connect/bot/feishu.rs index 1e39d3512b..15757f3f74 100644 --- a/src/crates/assembly/core/src/service/remote_connect/bot/feishu.rs +++ b/src/crates/assembly/core/src/service/remote_connect/bot/feishu.rs @@ -18,43 +18,95 @@ use tokio::sync::RwLock; use super::command_router::{ complete_im_bot_pairing, current_bot_language, execute_forwarded_turn, handle_command, - parse_command, welcome_message, BotAction, BotChatState, BotInteractionHandler, - BotInteractiveRequest, BotLanguage, BotMessageSender, HandleResult, + parse_command, BotAction, BotChatState, BotInteractionHandler, BotInteractiveRequest, + BotLanguage, BotMessageSender, HandleResult, }; +use super::pairing_gate::{PairingGate, UnpairedDecision}; use super::{ - load_bot_persistence, update_bot_persistence, BotConfig, BotRuntimeFence, SavedBotConnection, + load_bot_persistence, BotConfig, BotRuntimeFence, SavedBotConnection, WorkspaceFileContent, }; use crate::service::remote_connect::remote_server::ImageAttachment; -#[derive(Debug, Clone)] -struct PendingPairing { - created_at: i64, +/// Feishu Open Platform calls this adapter makes. The provider client is the +/// production implementation; unit tests substitute a recording fake. +#[async_trait::async_trait] +pub(crate) trait FeishuPlatform: Send + Sync { + fn config(&self) -> &FeishuConfig; + async fn send_message(&self, chat_id: &str, content: &str) -> Result<()>; + async fn send_action_card( + &self, + chat_id: &str, + language: BotLanguage, + content: &str, + actions: &[BotAction], + ) -> Result<()>; + async fn download_image_resource( + &self, + message_id: &str, + file_key: &str, + ) -> Result; + async fn send_artifact_to_chat( + &self, + chat_id: &str, + content: WorkspaceFileContent, + ) -> Result<()>; + async fn get_ws_endpoint(&self) -> Result; + async fn connect_ws(&self, url: &str) -> Result; +} + +#[async_trait::async_trait] +impl FeishuPlatform for FeishuBotApi { + fn config(&self) -> &FeishuConfig { + FeishuBotApi::config(self) + } + + async fn send_message(&self, chat_id: &str, content: &str) -> Result<()> { + FeishuBotApi::send_message(self, chat_id, content).await + } + + async fn send_action_card( + &self, + chat_id: &str, + language: BotLanguage, + content: &str, + actions: &[BotAction], + ) -> Result<()> { + FeishuBotApi::send_action_card(self, chat_id, language, content, actions).await + } + + async fn download_image_resource( + &self, + message_id: &str, + file_key: &str, + ) -> Result { + FeishuBotApi::download_image_resource(self, message_id, file_key).await + } + + async fn send_artifact_to_chat( + &self, + chat_id: &str, + content: WorkspaceFileContent, + ) -> Result<()> { + FeishuBotApi::send_artifact_to_chat(self, chat_id, content).await + } + + async fn get_ws_endpoint(&self) -> Result { + FeishuBotApi::get_ws_endpoint(self).await + } + + async fn connect_ws(&self, url: &str) -> Result { + FeishuBotApi::connect_ws(self, url).await + } } pub struct FeishuBot { - api: FeishuBotApi, - pending_pairings: Arc>>, + api: Arc, + pairing_gate: PairingGate, chat_states: Arc>>, runtime_fence: BotRuntimeFence, } impl FeishuBot { - fn invalid_pairing_code_message(language: BotLanguage) -> &'static str { - if language.is_chinese() { - "\u{914d}\u{5bf9}\u{7801}\u{65e0}\u{6548}\u{6216}\u{5df2}\u{8fc7}\u{671f}\u{ff0c}\u{8bf7}\u{91cd}\u{8bd5}\u{3002}" - } else { - "Invalid or expired pairing code. Please try again." - } - } - - fn enter_pairing_code_message(language: BotLanguage) -> &'static str { - if language.is_chinese() { - "\u{8bf7}\u{8f93}\u{5165} OpenBitFun Desktop \u{4e2d}\u{663e}\u{793a}\u{7684} 6 \u{4f4d}\u{914d}\u{5bf9}\u{7801}\u{3002}" - } else { - "Please enter the 6-digit pairing code from OpenBitFun Desktop." - } - } - fn unsupported_message_type_message(language: BotLanguage) -> &'static str { if language.is_chinese() { "\u{6682}\u{4e0d}\u{652f}\u{6301}\u{8fd9}\u{79cd}\u{6d88}\u{606f}\u{7c7b}\u{578b}\u{ff0c}\u{8bf7}\u{53d1}\u{9001}\u{6587}\u{672c}\u{6216}\u{56fe}\u{7247}\u{3002}" @@ -93,9 +145,13 @@ impl FeishuBot { } pub(crate) fn new_fenced(config: FeishuConfig, runtime_fence: BotRuntimeFence) -> Self { + Self::with_platform(Arc::new(FeishuBotApi::new(config)), runtime_fence) + } + + fn with_platform(api: Arc, runtime_fence: BotRuntimeFence) -> Self { Self { - api: FeishuBotApi::new(config), - pending_pairings: Arc::new(RwLock::new(HashMap::new())), + api, + pairing_gate: PairingGate::new(), chat_states: Arc::new(RwLock::new(HashMap::new())), runtime_fence, } @@ -216,6 +272,11 @@ impl FeishuBot { } async fn send_handle_result(&self, chat_id: &str, result: &HandleResult) -> Result<()> { + if !self.runtime_fence.is_lifecycle_current() + || !super::chat_is_paired(&self.chat_states, chat_id).await + { + return Ok(()); + } let language = current_bot_language().await; let text = if result.menu.items.is_empty() && result.menu.title.is_empty() { result.reply.clone() @@ -245,6 +306,7 @@ impl FeishuBot { for reference in super::extract_output_file_references(text) { if !self.runtime_fence.is_lifecycle_current() || self.runtime_fence.identity_epoch() != identity_epoch + || !super::chat_is_paired(&self.chat_states, chat_id).await { return; } @@ -261,6 +323,7 @@ impl FeishuBot { .await; if !self.runtime_fence.is_lifecycle_current() || self.runtime_fence.identity_epoch() != identity_epoch + || !super::chat_is_paired(&self.chat_states, chat_id).await { return; } @@ -284,75 +347,80 @@ impl FeishuBot { } } + /// Only a valid code can replace the chat that owns this connection. + /// Keep admission serialized with commands, and never create state for a refusal. + async fn handle_pairing_message(&self, chat_id: &str, text: &str) -> bool { + let epoch = self.runtime_fence.identity_epoch(); + let mut states = self.chat_states.write().await; + if !self.runtime_fence.is_lifecycle_current() { + return false; + } + self.runtime_fence.reconcile_states(&mut states); + if states.get(chat_id).is_some_and(|state| state.paired) { + return true; + } + let connected_elsewhere = states.values().any(|state| state.paired); + match self + .pairing_gate + .evaluate(chat_id, text, connected_elsewhere) + { + UnpairedDecision::Pair => { + let mut state = BotChatState::new(chat_id.to_string()); + let result = complete_im_bot_pairing(&mut state).await; + if !self.runtime_fence.is_lifecycle_current() + || self.runtime_fence.identity_epoch() != epoch + { + return false; + } + states.clear(); + states.insert(chat_id.to_string(), state.clone()); + self.persist_chat_state(chat_id, &state).await; + drop(states); + self.send_handle_result(chat_id, &result).await.ok(); + true + } + UnpairedDecision::Reply(reply) => { + drop(states); + let language = current_bot_language().await; + if self.runtime_fence.is_lifecycle_current() + && self.runtime_fence.identity_epoch() == epoch + { + let _ = self.send_message(chat_id, &reply.text(language)).await; + } + false + } + UnpairedDecision::Silent => false, + } + } + pub async fn register_pairing(&self, pairing_code: &str) -> Result<()> { - self.pending_pairings.write().await.insert( - pairing_code.to_string(), - PendingPairing { - created_at: chrono::Utc::now().timestamp(), - }, - ); + self.pairing_gate.register(pairing_code); Ok(()) } pub async fn verify_pairing_code(&self, code: &str) -> bool { - let mut pairings = self.pending_pairings.write().await; - if let Some(p) = pairings.remove(code) { - let age = chrono::Utc::now().timestamp() - p.created_at; - return age < 300; - } - false + self.pairing_gate.consume(code) } async fn handle_pairing_event_payload(&self, payload: &[u8]) -> Option { + if !self.runtime_fence.is_lifecycle_current() { + return None; + } let event: serde_json::Value = serde_json::from_slice(payload).ok()?; - - if let Some(parsed) = feishu_provider::parse_message_event_full(&event) { - let language = current_bot_language().await; - let chat_id = parsed.chat_id; - let msg_text = parsed.text; - let trimmed = msg_text.trim(); - - if trimmed == "/start" { - self.send_message(&chat_id, welcome_message(language)) - .await - .ok(); - } else if trimmed.len() == 6 && trimmed.chars().all(|c| c.is_ascii_digit()) { - if self.verify_pairing_code(trimmed).await { - info!("Feishu pairing successful, chat_id={chat_id}"); - let mut state = BotChatState::new(chat_id.clone()); - let identity_epoch = self.runtime_fence.identity_epoch(); - let result = complete_im_bot_pairing(&mut state).await; - if !self.runtime_fence.is_lifecycle_current() { - return None; - } - let mut states = self.chat_states.write().await; - self.runtime_fence.reconcile_states(&mut states); - self.runtime_fence - .sanitize_after_epoch(identity_epoch, &mut state); - states.insert(chat_id.clone(), state.clone()); - drop(states); - self.persist_chat_state(&chat_id, &state).await; - self.send_handle_result(&chat_id, &result).await.ok(); - - return Some(chat_id); - } else { - self.send_message(&chat_id, Self::invalid_pairing_code_message(language)) - .await - .ok(); - } + let (chat_id, text) = + if let Some(parsed) = feishu_provider::parse_message_event_full(&event) { + (parsed.chat_id, parsed.text) } else { - self.send_message(&chat_id, Self::enter_pairing_code_message(language)) - .await - .ok(); - } - } else if let Some(chat_id) = feishu_provider::extract_message_chat_id(&event) { - let language = current_bot_language().await; - self.send_message(&chat_id, Self::enter_pairing_code_message(language)) - .await - .ok(); - } - None + ( + feishu_provider::extract_message_chat_id(&event)?, + String::new(), + ) + }; + self.handle_pairing_message(&chat_id, &text) + .await + .then_some(chat_id) } + pub async fn wait_for_pairing( &self, stop_rx: &mut tokio::sync::watch::Receiver, @@ -486,49 +554,58 @@ impl FeishuBot { let Ok(event) = serde_json::from_slice::(payload) else { return; }; + let bot = self.clone(); + tokio::spawn(async move { + bot.dispatch_event(event).await; + }); + } + async fn dispatch_event(self: &Arc, event: serde_json::Value) { + if !self.runtime_fence.is_lifecycle_current() { + return; + } if let Some(parsed) = feishu_provider::parse_message_event_full(&event) { - let bot = self.clone(); - tokio::spawn(async move { - const MAX_IMAGES: usize = 5; - let language = current_bot_language().await; - let truncated = parsed.image_keys.len() > MAX_IMAGES; - let keys_to_use = if truncated { - &parsed.image_keys[..MAX_IMAGES] - } else { - &parsed.image_keys - }; - let images = if keys_to_use.is_empty() { - vec![] - } else { - bot.download_images(&parsed.message_id, keys_to_use).await - }; - if truncated { - let discarded = parsed.image_keys.len() - MAX_IMAGES; - let msg = Self::image_truncated_message(language, MAX_IMAGES, discarded); - bot.send_message(&parsed.chat_id, &msg).await.ok(); - } - let text = if parsed.text.is_empty() && !images.is_empty() { - Self::image_placeholder_message(language) - } else { - parsed.text - }; - bot.handle_incoming_message(&parsed.chat_id, &text, images) + if !super::chat_is_paired(&self.chat_states, parsed.chat_id.as_str()).await { + self.handle_pairing_message(&parsed.chat_id, &parsed.text) .await; - }); + return; + } + const MAX_IMAGES: usize = 5; + let language = current_bot_language().await; + let truncated = parsed.image_keys.len() > MAX_IMAGES; + let keys_to_use = if truncated { + &parsed.image_keys[..MAX_IMAGES] + } else { + &parsed.image_keys + }; + let images = if keys_to_use.is_empty() { + vec![] + } else { + self.download_images(&parsed.message_id, keys_to_use).await + }; + if truncated { + let discarded = parsed.image_keys.len() - MAX_IMAGES; + let msg = Self::image_truncated_message(language, MAX_IMAGES, discarded); + self.send_message(&parsed.chat_id, &msg).await.ok(); + } + let text = if parsed.text.is_empty() && !images.is_empty() { + Self::image_placeholder_message(language) + } else { + parsed.text + }; + self.handle_incoming_message(&parsed.chat_id, &text, images) + .await; } else if let Some((chat_id, cmd)) = feishu_provider::parse_card_action_event(&event) { - let bot = self.clone(); - tokio::spawn(async move { - bot.handle_incoming_message(&chat_id, &cmd, vec![]).await; - }); + self.handle_incoming_message(&chat_id, &cmd, vec![]).await; } else if let Some(chat_id) = feishu_provider::extract_message_chat_id(&event) { - let bot = self.clone(); - tokio::spawn(async move { - let language = current_bot_language().await; - bot.send_message(&chat_id, Self::unsupported_message_type_message(language)) - .await - .ok(); - }); + if !super::chat_is_paired(&self.chat_states, chat_id.as_str()).await { + self.handle_pairing_message(&chat_id, "").await; + return; + } + let language = current_bot_language().await; + self.send_message(&chat_id, Self::unsupported_message_type_message(language)) + .await + .ok(); } } async fn handle_incoming_message( @@ -543,45 +620,12 @@ impl FeishuBot { let mut states = self.chat_states.write().await; let command_identity_epoch = self.runtime_fence.identity_epoch(); self.runtime_fence.reconcile_states(&mut states); - let state = states.entry(chat_id.to_string()).or_insert_with(|| { - let mut s = BotChatState::new(chat_id.to_string()); - s.paired = true; - s - }); - let language = current_bot_language().await; - - if !state.paired { - let trimmed = text.trim(); - if trimmed == "/start" { - self.send_message(chat_id, welcome_message(language)) - .await - .ok(); - return; - } - if trimmed.len() == 6 && trimmed.chars().all(|c| c.is_ascii_digit()) { - if self.verify_pairing_code(trimmed).await { - let identity_epoch = self.runtime_fence.identity_epoch(); - let result = complete_im_bot_pairing(state).await; - self.runtime_fence - .sanitize_after_epoch(identity_epoch, state); - if !self.runtime_fence.is_lifecycle_current() { - return; - } - self.send_handle_result(chat_id, &result).await.ok(); - self.persist_chat_state(chat_id, state).await; - return; - } else { - self.send_message(chat_id, Self::invalid_pairing_code_message(language)) - .await - .ok(); - return; - } - } - self.send_message(chat_id, Self::enter_pairing_code_message(language)) - .await - .ok(); + if !states.get(chat_id).is_some_and(|state| state.paired) { + drop(states); + self.handle_pairing_message(chat_id, text).await; return; } + let state = states.get_mut(chat_id).expect("paired chat exists"); if self.runtime_fence.identity_epoch() != command_identity_epoch { return; @@ -634,6 +678,7 @@ impl FeishuBot { Box::pin(async move { if !msg_bot.runtime_fence.is_lifecycle_current() || msg_bot.runtime_fence.identity_epoch() != output_identity_epoch + || !super::chat_is_paired(&msg_bot.chat_states, msg_cid.as_str()).await { return; } @@ -654,6 +699,7 @@ impl FeishuBot { .await; if !bot.runtime_fence.is_lifecycle_current() || bot.runtime_fence.identity_epoch() != output_identity_epoch + || !super::chat_is_paired(&bot.chat_states, cid.as_str()).await { return; } @@ -698,11 +744,9 @@ impl FeishuBot { } let mut states = self.chat_states.write().await; self.runtime_fence.reconcile_states(&mut states); - let state = states.entry(chat_id.to_string()).or_insert_with(|| { - let mut s = BotChatState::new(chat_id.to_string()); - s.paired = true; - s - }); + let Some(state) = states.get_mut(chat_id).filter(|state| state.paired) else { + return; + }; if self.runtime_fence.identity_epoch() != identity_epoch { return; } @@ -734,15 +778,435 @@ impl FeishuBot { chat_state: snapshot, connected_at: chrono::Utc::now().timestamp(), }; - self.runtime_fence.commit_if_current(|| { - update_bot_persistence(|data| data.upsert(connection)); - }); + self.runtime_fence.persist_connection(connection); } } #[cfg(test)] mod tests { - use super::feishu_provider; + use super::super::test_support::{ + legacy_saved_connection, paired_state, question, PAIRING_CODE, + }; + use super::*; + use std::sync::atomic::{AtomicUsize, Ordering}; + use std::sync::Mutex as StdMutex; + + const OWNER: &str = "oc_owner"; + const STRANGER: &str = "oc_stranger"; + + #[derive(Debug, Clone, PartialEq, Eq)] + enum Sent { + Text { chat_id: String, text: String }, + Card { chat_id: String }, + Artifact { chat_id: String }, + } + + impl Sent { + fn chat_id(&self) -> &str { + match self { + Self::Text { chat_id, .. } + | Self::Card { chat_id } + | Self::Artifact { chat_id } => chat_id, + } + } + } + + /// Records every outbound call; the event socket is driven by the tests. + struct FakeFeishu { + config: FeishuConfig, + sent: StdMutex>, + image_downloads: AtomicUsize, + } + + impl FakeFeishu { + fn record(&self, sent: Sent) { + self.sent.lock().unwrap().push(sent); + } + + fn sent_to(&self, chat_id: &str) -> Vec { + self.sent + .lock() + .unwrap() + .iter() + .filter(|sent| sent.chat_id() == chat_id) + .cloned() + .collect() + } + } + + #[async_trait::async_trait] + impl FeishuPlatform for FakeFeishu { + fn config(&self) -> &FeishuConfig { + &self.config + } + + async fn send_message(&self, chat_id: &str, content: &str) -> Result<()> { + self.record(Sent::Text { + chat_id: chat_id.to_string(), + text: content.to_string(), + }); + Ok(()) + } + + async fn send_action_card( + &self, + chat_id: &str, + _language: BotLanguage, + _content: &str, + _actions: &[BotAction], + ) -> Result<()> { + self.record(Sent::Card { + chat_id: chat_id.to_string(), + }); + Ok(()) + } + + async fn download_image_resource( + &self, + _message_id: &str, + _file_key: &str, + ) -> Result { + self.image_downloads.fetch_add(1, Ordering::SeqCst); + Ok(feishu_provider::FeishuDownloadedImage { + content_type: "image/png".to_string(), + bytes: vec![1, 2, 3], + }) + } + + async fn send_artifact_to_chat( + &self, + chat_id: &str, + _content: WorkspaceFileContent, + ) -> Result<()> { + self.record(Sent::Artifact { + chat_id: chat_id.to_string(), + }); + Ok(()) + } + + async fn get_ws_endpoint(&self) -> Result { + Err(anyhow!("the fake has no event socket")) + } + + async fn connect_ws(&self, _url: &str) -> Result { + Err(anyhow!("the fake has no event socket")) + } + } + + fn fake_bot() -> (Arc, Arc) { + let fake = Arc::new(FakeFeishu { + config: FeishuConfig { + app_id: "fixture-app".to_string(), + app_secret: "fixture-secret".to_string(), + }, + sent: StdMutex::default(), + image_downloads: AtomicUsize::new(0), + }); + let bot = Arc::new(FeishuBot::with_platform( + fake.clone(), + BotRuntimeFence::standalone(), + )); + (fake, bot) + } + + /// A bot whose first pairing already completed with `OWNER`. + async fn connected_bot() -> (Arc, Arc) { + let (fake, bot) = fake_bot(); + bot.restore_chat_state(OWNER, paired_state(OWNER)).await; + (fake, bot) + } + + fn saved_chat_id(bot: &FeishuBot) -> Option { + bot.runtime_fence + .saved_connection("feishu") + .map(|saved| saved.chat_id) + } + + fn message_event(chat_id: &str, message_type: &str, content: serde_json::Value) -> Vec { + serde_json::to_vec(&serde_json::json!({ + "header": { "event_type": "im.message.receive_v1" }, + "event": { + "message": { + "message_id": "om_fixture", + "message_type": message_type, + "chat_id": chat_id, + "content": content.to_string() + } + } + })) + .unwrap() + } + + fn text_event(chat_id: &str, text: &str) -> Vec { + message_event(chat_id, "text", serde_json::json!({ "text": text })) + } + + fn image_event(chat_id: &str) -> Vec { + message_event( + chat_id, + "image", + serde_json::json!({ "image_key": "img_fixture" }), + ) + } + + fn file_event(chat_id: &str) -> Vec { + message_event( + chat_id, + "file", + serde_json::json!({ "file_key": "file_fixture" }), + ) + } + + async fn dispatch(bot: &Arc, payload: Vec) { + bot.dispatch_event(serde_json::from_slice(&payload).unwrap()) + .await; + } + + #[tokio::test] + async fn unknown_chat_after_first_pairing_is_refused_and_cannot_run_a_command() { + let (fake, bot) = connected_bot().await; + + dispatch(&bot, text_event(STRANGER, "/help")).await; + + assert!( + !bot.chat_states.read().await.contains_key(STRANGER), + "a chat that never paired must not gain state" + ); + let replies = fake.sent_to(STRANGER); + assert_eq!(replies.len(), 1, "one explanatory reply: {replies:?}"); + assert!( + matches!(replies[0], Sent::Text { .. }), + "an unpaired chat must not receive a command menu: {replies:?}" + ); + assert_eq!(saved_chat_id(&bot).as_deref(), Some(OWNER)); + + dispatch(&bot, text_event(OWNER, "/help")).await; + assert!( + fake.sent_to(OWNER) + .iter() + .any(|sent| matches!(sent, Sent::Card { .. })), + "the paired chat keeps its commands" + ); + } + + #[tokio::test] + async fn outbound_paths_never_create_state_or_reach_an_unpaired_chat() { + let (fake, bot) = connected_bot().await; + let epoch = bot.runtime_fence.identity_epoch(); + + bot.deliver_interaction(STRANGER, question("tool-1"), epoch) + .await; + bot.notify_files_ready( + STRANGER, + "missing-session", + None, + "[report](computer://report.pdf)", + epoch, + ) + .await; + + assert!(!bot.chat_states.read().await.contains_key(STRANGER)); + assert_eq!(fake.sent_to(STRANGER), Vec::::new()); + assert_eq!(saved_chat_id(&bot).as_deref(), Some(OWNER)); + + // A chat that is known but never completed pairing is treated the same. + bot.chat_states.write().await.insert( + STRANGER.to_string(), + BotChatState::new(STRANGER.to_string()), + ); + bot.deliver_interaction(STRANGER, question("tool-2"), epoch) + .await; + assert_eq!(fake.sent_to(STRANGER), Vec::::new()); + let states = bot.chat_states.read().await; + let stranger = states.get(STRANGER).expect("state was inserted above"); + assert!(!stranger.paired); + assert!(stranger.pending_action.is_none()); + drop(states); + + // The paired chat still receives its interaction. + bot.deliver_interaction(OWNER, question("tool-3"), epoch) + .await; + assert_eq!(fake.sent_to(OWNER).len(), 1); + } + + #[tokio::test] + async fn wrong_codes_are_limited_per_chat_without_locking_the_owner_or_burning_the_code() { + let (fake, bot) = fake_bot(); + bot.register_pairing(PAIRING_CODE).await.unwrap(); + + for _ in 0..5 { + let paired = bot + .handle_pairing_event_payload(&text_event(STRANGER, "000000")) + .await; + assert_eq!(paired, None); + } + // The right code no longer helps a chat that used up its attempts. + let paired = bot + .handle_pairing_event_payload(&text_event(STRANGER, PAIRING_CODE)) + .await; + assert_eq!(paired, None); + let paired = bot + .handle_pairing_event_payload(&text_event(OWNER, "111111")) + .await; + assert_eq!(paired, None); + let paired = bot + .handle_pairing_event_payload(&text_event(OWNER, PAIRING_CODE)) + .await; + assert_eq!(paired.as_deref(), Some(OWNER)); + + let states = bot.chat_states.read().await; + assert!(states.get(OWNER).is_some_and(|state| state.paired)); + assert!(!states.contains_key(STRANGER)); + drop(states); + // Four "wrong code" replies, then one lockout notice, then silence. + assert_eq!(fake.sent_to(STRANGER).len(), 5); + assert_eq!(saved_chat_id(&bot).as_deref(), Some(OWNER)); + } + + #[tokio::test] + async fn repeated_messages_from_an_unpaired_chat_get_a_bounded_number_of_replies() { + // While the first pairing is still pending. + let (fake, bot) = fake_bot(); + bot.register_pairing(PAIRING_CODE).await.unwrap(); + for index in 0..20 { + let payload = match index % 3 { + 0 => text_event(STRANGER, "hello"), + 1 => image_event(STRANGER), + _ => file_event(STRANGER), + }; + assert_eq!(bot.handle_pairing_event_payload(&payload).await, None); + } + let paired = bot + .handle_pairing_event_payload(&text_event(OWNER, PAIRING_CODE)) + .await; + assert_eq!(paired.as_deref(), Some(OWNER)); + let replies = fake.sent_to(STRANGER).len(); + assert!( + (1..=3).contains(&replies), + "replies while pairing: {replies}" + ); + + // After pairing, in the message loop: text, images and other types. + for index in 0..20 { + let payload = match index % 3 { + 0 => text_event(STRANGER, "hello again"), + 1 => image_event(STRANGER), + _ => file_event(STRANGER), + }; + dispatch(&bot, payload).await; + } + let replies = fake.sent_to(STRANGER).len() - replies; + assert!( + (1..=3).contains(&replies), + "replies when connected: {replies}" + ); + assert!(!bot.chat_states.read().await.contains_key(STRANGER)); + assert_eq!( + fake.image_downloads.load(Ordering::SeqCst), + 0, + "an unpaired chat must not make the host download its images" + ); + } + + #[tokio::test] + async fn code_issued_for_a_connected_bot_moves_the_connection_to_the_chat_that_presents_it() { + let (fake, bot) = connected_bot().await; + bot.register_pairing(PAIRING_CODE).await.unwrap(); + + dispatch(&bot, text_event(STRANGER, "111111")).await; + assert!(!bot.chat_states.read().await.contains_key(STRANGER)); + assert_eq!(saved_chat_id(&bot).as_deref(), Some(OWNER)); + + dispatch(&bot, text_event(STRANGER, PAIRING_CODE)).await; + let states = bot.chat_states.read().await; + assert!(states.get(STRANGER).is_some_and(|state| state.paired)); + assert!( + !states.contains_key(OWNER), + "one connection has one chat: the previous chat is no longer paired" + ); + drop(states); + assert_eq!(saved_chat_id(&bot).as_deref(), Some(STRANGER)); + assert!( + !bot.verify_pairing_code(PAIRING_CODE).await, + "the pairing code is single use" + ); + assert!(!fake.sent_to(STRANGER).is_empty()); + } + + #[tokio::test] + async fn legacy_persisted_paired_chat_is_restored_without_pairing_again() { + let saved = legacy_saved_connection( + "feishu", + OWNER, + serde_json::json!({ + "bot_type": "feishu", + "app_id": "fixture-app", + "app_secret": "fixture-secret" + }), + ); + let (fake, bot) = fake_bot(); + + bot.restore_chat_state(OWNER, saved.chat_state.clone()) + .await; + dispatch(&bot, text_event(OWNER, "/help")).await; + + assert_eq!( + fake.sent_to(OWNER) + .iter() + .filter(|sent| matches!(sent, Sent::Card { .. })) + .count(), + 1, + "the restored chat reaches the command router without a pairing prompt" + ); + let resaved = bot + .runtime_fence + .saved_connection("feishu") + .expect("restored connection is saved"); + assert_eq!(resaved.chat_id, OWNER); + assert!(resaved.chat_state.paired); + // The stored shape is unchanged: an older build reads it back. + let stored = serde_json::to_value(&resaved.chat_state).unwrap(); + let legacy = serde_json::to_value(&saved.chat_state).unwrap(); + assert_eq!(stored, legacy); + assert_eq!(stored["paired"], serde_json::json!(true)); + } + + #[tokio::test] + async fn retired_or_reidentified_bot_neither_answers_nor_delivers() { + let (fake, bot) = connected_bot().await; + let epoch = bot.runtime_fence.identity_epoch(); + + // An account change invalidates deliveries that started before it. + bot.runtime_fence + .account_identity_epoch + .fetch_add(1, Ordering::AcqRel); + bot.deliver_interaction(OWNER, question("tool-1"), epoch) + .await; + bot.notify_files_ready( + OWNER, + "missing-session", + None, + "[report](computer://report.pdf)", + epoch, + ) + .await; + assert_eq!(fake.sent_to(OWNER), Vec::::new()); + + // A replaced instance stays silent for paired and unpaired chats alike. + bot.runtime_fence.slot.advance(); + dispatch(&bot, text_event(OWNER, "/help")).await; + dispatch(&bot, text_event(STRANGER, "/help")).await; + dispatch(&bot, file_event(STRANGER)).await; + bot.deliver_interaction( + OWNER, + question("tool-2"), + bot.runtime_fence.identity_epoch(), + ) + .await; + assert_eq!(fake.sent.lock().unwrap().len(), 0); + assert!(!bot.chat_states.read().await.contains_key(STRANGER)); + assert_eq!(saved_chat_id(&bot).as_deref(), Some(OWNER)); + } #[test] fn parse_text_message_event() { diff --git a/src/crates/assembly/core/src/service/remote_connect/bot/mod.rs b/src/crates/assembly/core/src/service/remote_connect/bot/mod.rs index d7e87bdf1b..e401e0eeb2 100644 --- a/src/crates/assembly/core/src/service/remote_connect/bot/mod.rs +++ b/src/crates/assembly/core/src/service/remote_connect/bot/mod.rs @@ -9,6 +9,7 @@ pub mod command_router; pub mod feishu; pub mod locale; pub mod menu; +pub(crate) mod pairing_gate; pub mod telegram; pub mod weixin; @@ -27,11 +28,30 @@ pub use openbitfun_services_integrations::remote_connect::bot::{ RemoteConnectFormState, RemoteDeviceTarget, SavedBotConnection, WorkspaceFileContent, }; +use std::borrow::Borrow; use std::collections::HashMap; use std::hash::Hash; use std::sync::atomic::{AtomicU64, Ordering}; use std::sync::{Arc, Mutex as StdMutex}; +/// Authorization is never implied by missing state: a chat counts as paired +/// only when its own state exists and says so. The check never creates state, +/// so every outbound path can ask it about a chat it is about to address. +pub(crate) async fn chat_is_paired( + states: &tokio::sync::RwLock>, + chat_id: &Q, +) -> bool +where + K: Eq + Hash + Borrow, + Q: Eq + Hash + ?Sized, +{ + states + .read() + .await + .get(chat_id) + .is_some_and(|state| state.paired) +} + /// Serializes persistence commits with lifecycle generation changes for one /// bot platform. A retired polling task can finish later, but it can no longer /// overwrite the replacement instance's persisted state. @@ -77,6 +97,15 @@ impl BotSlotFence { } } +/// Where a bot instance commits its saved connection. A standalone test fence +/// keeps the document in memory, so a unit test can never replace a saved +/// connection in the product home. +enum BotConnectionStore { + Product, + #[cfg(test)] + Memory(StdMutex), +} + /// Shared account-identity epoch plus a per-platform lifecycle owner. Network /// work is not awaited during account replacement; instead every state commit /// is fenced and sanitized if it started under an older account epoch. @@ -86,6 +115,7 @@ pub(crate) struct BotRuntimeFence { observed_identity_epoch: AtomicU64, slot: Arc, lifecycle_generation: u64, + connection_store: BotConnectionStore, } impl BotRuntimeFence { @@ -101,6 +131,7 @@ impl BotRuntimeFence { account_user_id: String::new(), slot, lifecycle_generation, + connection_store: BotConnectionStore::Product, } } @@ -118,7 +149,37 @@ impl BotRuntimeFence { let account_identity_epoch = Arc::new(AtomicU64::new(0)); let slot = Arc::new(BotSlotFence::default()); let lifecycle_generation = slot.advance(); - Self::new(account_identity_epoch, slot, lifecycle_generation) + let mut fence = Self::new(account_identity_epoch, slot, lifecycle_generation); + fence.connection_store = BotConnectionStore::Memory(StdMutex::default()); + fence + } + + /// The connection a standalone fence saved for `bot_type`. + #[cfg(test)] + pub(crate) fn saved_connection(&self, bot_type: &str) -> Option { + match &self.connection_store { + BotConnectionStore::Product => None, + BotConnectionStore::Memory(data) => data + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()) + .get(bot_type) + .cloned(), + } + } + + /// Saves `connection` as the single connection of its bot type, unless + /// this instance's lifecycle slot was replaced. + pub(crate) fn persist_connection(&self, connection: SavedBotConnection) { + self.commit_if_current(|| match &self.connection_store { + BotConnectionStore::Product => { + update_bot_persistence(|data| data.upsert(connection)); + } + #[cfg(test)] + BotConnectionStore::Memory(data) => data + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()) + .upsert(connection), + }); } pub(crate) fn identity_epoch(&self) -> u64 { @@ -157,6 +218,7 @@ impl BotRuntimeFence { .store(current, Ordering::Release); } + #[cfg(test)] pub(crate) fn sanitize_after_epoch(&self, started_epoch: u64, state: &mut BotChatState) { if started_epoch != self.identity_epoch() { state.clear_delegated_identity(); @@ -177,6 +239,73 @@ impl BotRuntimeFence { } } +/// Fixtures shared by the platform adapter tests. +#[cfg(test)] +pub(crate) mod test_support { + use super::command_router::{BotInteractiveRequest, PendingAction}; + use super::{BotChatState, BotPersistenceData, MenuView, SavedBotConnection}; + + /// A pairing code no test fixture guesses by accident. + pub(crate) const PAIRING_CODE: &str = "482913"; + + pub(crate) fn paired_state(chat_id: &str) -> BotChatState { + let mut state = BotChatState::new(chat_id.to_string()); + state.paired = true; + state + } + + /// A question a running turn asks the chat that started it. + pub(crate) fn question(tool_id: &str) -> BotInteractiveRequest { + BotInteractiveRequest { + remote_target: None, + reply: "Pick one".into(), + actions: Vec::new(), + menu: MenuView::plain("Pick one"), + pending_action: PendingAction::AskUserQuestion { + tool_id: tool_id.into(), + questions: Vec::new(), + current_index: 0, + answers: Vec::new(), + awaiting_custom_text: false, + pending_answer: None, + }, + } + } + + /// The persistence document as a release before the pairing gate fix + /// wrote it: no optional fields, a bare workspace path, `paired: true`. + pub(crate) fn legacy_saved_connection( + bot_type: &str, + chat_id: &str, + config: serde_json::Value, + ) -> SavedBotConnection { + let document = serde_json::json!({ + "connections": [{ + "account_user_id": "account", + "bot_type": bot_type, + "chat_id": chat_id, + "config": config, + "chat_state": { + "chat_id": chat_id, + "paired": true, + "current_workspace": "/legacy/workspace", + "current_assistant": null, + "current_session_id": "legacy-session", + "display_mode": "pro" + }, + "connected_at": 1 + }], + "form_state": {}, + "verbose_mode": false + }); + let data: BotPersistenceData = + serde_json::from_value(document).expect("legacy bot persistence must deserialize"); + data.get(bot_type) + .cloned() + .expect("legacy connection must be present") + } +} + #[cfg(test)] mod lifecycle_tests { use super::*; @@ -287,5 +416,7 @@ pub(crate) async fn retire_remote_interactions( if !fence.is_lifecycle_current() || fence.identity_epoch() != epoch { return None; } - command_router::retire_completed_remote_tools(states.get_mut(chat_id)?, target, tool_ids) + // A chat that is no longer paired has no prompt left to show or retire. + let state = states.get_mut(chat_id).filter(|state| state.paired)?; + command_router::retire_completed_remote_tools(state, target, tool_ids) } diff --git a/src/crates/assembly/core/src/service/remote_connect/bot/pairing_gate.rs b/src/crates/assembly/core/src/service/remote_connect/bot/pairing_gate.rs new file mode 100644 index 0000000000..aa9f0c230d --- /dev/null +++ b/src/crates/assembly/core/src/service/remote_connect/bot/pairing_gate.rs @@ -0,0 +1,644 @@ +//! Pairing authorization gate shared by the Telegram, Feishu and Weixin bots. +//! +//! A chat is authorized only by state that says it completed pairing; a chat +//! without such state is unpaired. Everything an adapter does for an unpaired +//! chat is decided here: the gate owns the pending pairing codes, limits wrong +//! codes per chat, and bounds the replies an unpaired chat can cause. + +use super::locale::{strings_for, BotLanguage}; +use std::collections::HashMap; +use std::sync::Mutex as StdMutex; + +/// How long a pairing code shown on the host stays valid. +pub(crate) const PAIRING_CODE_TTL_SECS: i64 = 300; + +/// Wrong codes one chat may send against the pending code. Reaching the limit +/// locks that chat out until the code expires, is used, or is replaced. This +/// throttles authentication guesses; it is unrelated to agent execution. +pub(crate) const MAX_WRONG_PAIRING_CODES: u8 = 5; + +/// Explanatory replies one unpaired chat receives before the bot stops +/// answering it. The count starts again when the explanation changes (a code +/// is issued, used or expires) or after the chat stayed quiet. +pub(crate) const MAX_UNPAIRED_NOTICES: u8 = 3; + +/// An unpaired chat that stayed silent this long is answered again. +pub(crate) const UNPAIRED_QUIET_SECS: i64 = 10 * 60; + +/// Unpaired chats tracked individually. Chats beyond it share one record, so +/// neither memory, replies, nor guesses grow with the number of strangers. +pub(crate) const MAX_TRACKED_UNPAIRED_CHATS: usize = 4096; + +/// What an adapter tells an unpaired chat. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) enum UnpairedReply { + /// `/start` while a pairing code is pending. + Welcome, + /// A pairing code is pending and the chat has not sent one. + EnterCode, + /// The chat sent a code that is not the pending one. + WrongCode { attempts_left: u8 }, + /// The chat used up its attempts for the pending code. + LockedOut, + /// No chat is connected and no pairing code is pending. + NoActiveCode, + /// Another chat owns the connection and no pairing code is pending. + ConnectedElsewhere, +} + +/// How an adapter handles one message from an unpaired chat. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) enum UnpairedDecision { + /// The chat presented a valid, unexpired, unused code, which is now + /// consumed. The adapter completes pairing for this chat. + Pair, + Reply(UnpairedReply), + /// The chat already got its replies; answering again would be spam. + Silent, +} + +#[derive(Debug, Default, Clone, Copy)] +struct UnpairedChat { + /// Gate phase the counters below belong to. + phase: u64, + last_seen_at: i64, + notices: u8, + wrong_codes: u8, +} + +impl UnpairedChat { + fn refresh(&mut self, phase: u64, now: i64) { + if self.phase != phase { + self.phase = phase; + self.notices = 0; + self.wrong_codes = 0; + } else if now.saturating_sub(self.last_seen_at) >= UNPAIRED_QUIET_SECS { + self.notices = 0; + } + self.last_seen_at = now; + } +} + +#[derive(Default)] +struct GateState { + /// Pending codes and when each was issued. + codes: HashMap, + /// Advances when a code is issued and when the last pending code is used + /// or expires. Counters of an older phase are reset on next use, so a + /// lockout lasts exactly as long as the code it protected. + phase: u64, + chats: HashMap, + /// Shared by the chats that arrive while every record is in use. + overflow: UnpairedChat, +} + +impl GateState { + /// Drops expired codes and reports whether a usable one is still pending. + fn expire_codes(&mut self, now: i64) -> bool { + if self.codes.is_empty() { + return false; + } + self.codes + .retain(|_, issued_at| now.saturating_sub(*issued_at) < PAIRING_CODE_TTL_SECS); + if self.codes.is_empty() { + self.phase = self.phase.wrapping_add(1); + } + !self.codes.is_empty() + } + + /// Consumes the pending code equal to `candidate`. + fn take_code(&mut self, candidate: &str) -> bool { + let Some(code) = self + .codes + .keys() + .find(|code| constant_time_eq(code.as_bytes(), candidate.as_bytes())) + .cloned() + else { + return false; + }; + self.codes.remove(&code); + if self.codes.is_empty() { + self.phase = self.phase.wrapping_add(1); + } + true + } + + fn chat(&mut self, chat: &str, now: i64) -> &mut UnpairedChat { + let phase = self.phase; + if !self.chats.contains_key(chat) && self.chats.len() >= MAX_TRACKED_UNPAIRED_CHATS { + // Only chats that went quiet make room. A record that still + // counts wrong codes was seen within the code lifetime, which is + // shorter than the quiet period, so cycling through many chats + // can never reset an attempt counter. + self.chats + .retain(|_, record| now.saturating_sub(record.last_seen_at) < UNPAIRED_QUIET_SECS); + } + let record = + if self.chats.contains_key(chat) || self.chats.len() < MAX_TRACKED_UNPAIRED_CHATS { + self.chats.entry(chat.to_string()).or_default() + } else { + &mut self.overflow + }; + record.refresh(phase, now); + record + } +} + +pub(crate) struct PairingGate { + state: StdMutex, +} + +impl PairingGate { + pub(crate) fn new() -> Self { + Self { + state: StdMutex::new(GateState::default()), + } + } + + fn lock(&self) -> std::sync::MutexGuard<'_, GateState> { + self.state + .lock() + .unwrap_or_else(|poisoned| poisoned.into_inner()) + } + + /// Makes `code` the pairing code the host is showing right now. + pub(crate) fn register(&self, code: &str) { + self.register_issued_at(code, now_secs()); + } + + pub(crate) fn register_issued_at(&self, code: &str, issued_at: i64) { + let mut gate = self.lock(); + gate.codes.clear(); + gate.codes.insert(code.to_string(), issued_at); + gate.phase = gate.phase.wrapping_add(1); + } + + /// Compatibility entry point for host-side verification. Inbound messages + /// use `evaluate`, which also checks the requesting chat's attempt budget. + pub(crate) fn consume(&self, code: &str) -> bool { + let mut gate = self.lock(); + gate.expire_codes(now_secs()) && gate.take_code(code) + } + + /// Decides one message from a chat that has not completed pairing. + /// `connected_elsewhere` says whether another chat owns the connection. + pub(crate) fn evaluate( + &self, + chat: &str, + text: &str, + connected_elsewhere: bool, + ) -> UnpairedDecision { + self.evaluate_at(chat, text, connected_elsewhere, now_secs()) + } + + fn evaluate_at( + &self, + chat: &str, + text: &str, + connected_elsewhere: bool, + now: i64, + ) -> UnpairedDecision { + let mut gate = self.lock(); + let code_pending = gate.expire_codes(now); + let text = text.trim(); + + if code_pending && is_pairing_code(text) { + if gate.chat(chat, now).wrong_codes >= MAX_WRONG_PAIRING_CODES { + // A locked out chat is not even compared with the code: the + // limit cannot be bypassed and the code is not consumed. + return UnpairedDecision::Silent; + } + if gate.take_code(text) { + gate.chats.remove(chat); + return UnpairedDecision::Pair; + } + let record = gate.chat(chat, now); + record.wrong_codes += 1; + return UnpairedDecision::Reply(if record.wrong_codes >= MAX_WRONG_PAIRING_CODES { + UnpairedReply::LockedOut + } else { + UnpairedReply::WrongCode { + attempts_left: MAX_WRONG_PAIRING_CODES - record.wrong_codes, + } + }); + } + + let record = gate.chat(chat, now); + if record.wrong_codes >= MAX_WRONG_PAIRING_CODES || record.notices >= MAX_UNPAIRED_NOTICES { + return UnpairedDecision::Silent; + } + record.notices += 1; + UnpairedDecision::Reply(if !code_pending { + if connected_elsewhere { + UnpairedReply::ConnectedElsewhere + } else { + UnpairedReply::NoActiveCode + } + } else if text == "/start" { + UnpairedReply::Welcome + } else { + UnpairedReply::EnterCode + }) + } + + #[cfg(test)] + pub(crate) fn tracks(&self, chat: &str) -> bool { + self.lock().chats.contains_key(chat) + } +} + +fn now_secs() -> i64 { + chrono::Utc::now().timestamp() +} + +/// A pairing code attempt is exactly six ASCII digits. +fn is_pairing_code(text: &str) -> bool { + text.len() == 6 && text.bytes().all(|byte| byte.is_ascii_digit()) +} + +fn constant_time_eq(left: &[u8], right: &[u8]) -> bool { + left.len() == right.len() + && left + .iter() + .zip(right) + .fold(0u8, |difference, (a, b)| difference | (a ^ b)) + == 0 +} + +impl UnpairedReply { + /// The reply in the host's language. The host can be Desktop or the CLI + /// daemon, so the new wording says "on your computer". + pub(crate) fn text(self, language: BotLanguage) -> String { + match self { + Self::Welcome => strings_for(language).welcome.to_string(), + Self::EnterCode => strings_for(language).need_pairing.to_string(), + Self::WrongCode { attempts_left } => match language { + BotLanguage::ZhCN => format!( + "\u{914d}\u{5bf9}\u{7801}\u{4e0d}\u{6b63}\u{786e}\u{3002}\u{8bf7}\u{6838}\u{5bf9}\u{7535}\u{8111}\u{4e0a} OpenBitFun \u{663e}\u{793a}\u{7684}\u{914d}\u{5bf9}\u{7801}\u{540e}\u{91cd}\u{8bd5}\u{3002}\u{5269}\u{4f59}\u{5c1d}\u{8bd5}\u{6b21}\u{6570}\u{ff1a}{attempts_left}\u{3002}" + ), + BotLanguage::ZhTW => format!( + "\u{914d}\u{5c0d}\u{78bc}\u{4e0d}\u{6b63}\u{78ba}\u{3002}\u{8acb}\u{6838}\u{5c0d}\u{96fb}\u{8166}\u{4e0a} OpenBitFun \u{986f}\u{793a}\u{7684}\u{914d}\u{5c0d}\u{78bc}\u{5f8c}\u{91cd}\u{8a66}\u{3002}\u{5269}\u{9918}\u{5617}\u{8a66}\u{6b21}\u{6578}\u{ff1a}{attempts_left}\u{3002}" + ), + BotLanguage::EnUS => format!( + "Incorrect pairing code. Check the code shown by OpenBitFun on your computer and try again. Attempts left: {attempts_left}." + ), + }, + Self::LockedOut => match language { + BotLanguage::ZhCN => { + "\u{914d}\u{5bf9}\u{7801}\u{9519}\u{8bef}\u{6b21}\u{6570}\u{8fc7}\u{591a}\u{ff0c}\u{6b64}\u{804a}\u{5929}\u{5df2}\u{65e0}\u{6cd5}\u{518d}\u{4f7f}\u{7528}\u{5f53}\u{524d}\u{914d}\u{5bf9}\u{7801}\u{3002}\u{8bf7}\u{5728}\u{7535}\u{8111}\u{4e0a}\u{7684} OpenBitFun \u{4e2d}\u{91cd}\u{65b0}\u{5f00}\u{59cb}\u{914d}\u{5bf9}\u{ff0c}\u{4ee5}\u{83b7}\u{53d6}\u{65b0}\u{7684}\u{914d}\u{5bf9}\u{7801}\u{3002}" + } + BotLanguage::ZhTW => { + "\u{914d}\u{5c0d}\u{78bc}\u{932f}\u{8aa4}\u{6b21}\u{6578}\u{904e}\u{591a}\u{ff0c}\u{6b64}\u{804a}\u{5929}\u{5df2}\u{7121}\u{6cd5}\u{518d}\u{4f7f}\u{7528}\u{76ee}\u{524d}\u{7684}\u{914d}\u{5c0d}\u{78bc}\u{3002}\u{8acb}\u{5728}\u{96fb}\u{8166}\u{4e0a}\u{7684} OpenBitFun \u{4e2d}\u{91cd}\u{65b0}\u{958b}\u{59cb}\u{914d}\u{5c0d}\u{ff0c}\u{4ee5}\u{53d6}\u{5f97}\u{65b0}\u{7684}\u{914d}\u{5c0d}\u{78bc}\u{3002}" + } + BotLanguage::EnUS => { + "Too many incorrect pairing codes. This chat can no longer use the current pairing code. Start pairing again from OpenBitFun on your computer to get a new code." + } + } + .to_string(), + Self::NoActiveCode => match language { + BotLanguage::ZhCN => { + "\u{6b64}\u{673a}\u{5668}\u{4eba}\u{5f53}\u{524d}\u{6ca1}\u{6709}\u{53ef}\u{7528}\u{7684}\u{914d}\u{5bf9}\u{7801}\u{3002}\u{8bf7}\u{5728}\u{7535}\u{8111}\u{4e0a}\u{7684} OpenBitFun \u{4e2d}\u{5f00}\u{59cb}\u{914d}\u{5bf9}\u{ff0c}\u{7136}\u{540e}\u{53d1}\u{9001}\u{5176}\u{663e}\u{793a}\u{7684} 6 \u{4f4d}\u{914d}\u{5bf9}\u{7801}\u{3002}" + } + BotLanguage::ZhTW => { + "\u{6b64}\u{6a5f}\u{5668}\u{4eba}\u{76ee}\u{524d}\u{6c92}\u{6709}\u{53ef}\u{7528}\u{7684}\u{914d}\u{5c0d}\u{78bc}\u{3002}\u{8acb}\u{5728}\u{96fb}\u{8166}\u{4e0a}\u{7684} OpenBitFun \u{4e2d}\u{958b}\u{59cb}\u{914d}\u{5c0d}\u{ff0c}\u{7136}\u{5f8c}\u{50b3}\u{9001}\u{5176}\u{986f}\u{793a}\u{7684} 6 \u{4f4d}\u{914d}\u{5c0d}\u{78bc}\u{3002}" + } + BotLanguage::EnUS => { + "There is no active pairing code for this bot. Start pairing from OpenBitFun on your computer, then send the 6-digit pairing code it shows." + } + } + .to_string(), + Self::ConnectedElsewhere => match language { + BotLanguage::ZhCN => { + "\u{6b64}\u{673a}\u{5668}\u{4eba}\u{5df2}\u{8fde}\u{63a5}\u{5230}\u{53e6}\u{4e00}\u{4e2a}\u{804a}\u{5929}\u{ff0c}\u{4e0d}\u{63a5}\u{53d7}\u{6b64}\u{804a}\u{5929}\u{7684}\u{6d88}\u{606f}\u{3002}\u{5982}\u{9700}\u{5728}\u{8fd9}\u{91cc}\u{4f7f}\u{7528}\u{ff0c}\u{8bf7}\u{5728}\u{7535}\u{8111}\u{4e0a}\u{7684} OpenBitFun \u{4e2d}\u{4e3a}\u{6b64}\u{804a}\u{5929}\u{8fdb}\u{884c}\u{914d}\u{5bf9}\u{3002}" + } + BotLanguage::ZhTW => { + "\u{6b64}\u{6a5f}\u{5668}\u{4eba}\u{5df2}\u{9023}\u{63a5}\u{5230}\u{53e6}\u{4e00}\u{500b}\u{804a}\u{5929}\u{ff0c}\u{4e0d}\u{63a5}\u{53d7}\u{6b64}\u{804a}\u{5929}\u{7684}\u{8a0a}\u{606f}\u{3002}\u{5982}\u{9700}\u{5728}\u{9019}\u{88e1}\u{4f7f}\u{7528}\u{ff0c}\u{8acb}\u{5728}\u{96fb}\u{8166}\u{4e0a}\u{7684} OpenBitFun \u{4e2d}\u{70ba}\u{6b64}\u{804a}\u{5929}\u{9032}\u{884c}\u{914d}\u{5c0d}\u{3002}" + } + BotLanguage::EnUS => { + "This bot is already connected to another chat and does not accept messages from this one. To use it here, pair this chat from OpenBitFun on your computer." + } + } + .to_string(), + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + const CODE: &str = "482913"; + const T0: i64 = 1_800_000_000; + + fn gate_with_code() -> PairingGate { + let gate = PairingGate::new(); + gate.register_issued_at(CODE, T0); + gate + } + + fn wrong(attempts_left: u8) -> UnpairedDecision { + UnpairedDecision::Reply(UnpairedReply::WrongCode { attempts_left }) + } + + fn reply(reply: UnpairedReply) -> UnpairedDecision { + UnpairedDecision::Reply(reply) + } + + #[test] + fn valid_code_pairs_exactly_once() { + let gate = gate_with_code(); + assert_eq!( + gate.evaluate_at("owner", &format!(" {CODE}\n"), false, T0 + 10), + UnpairedDecision::Pair + ); + // The used code is gone: a second chat is told the truth instead of + // being asked for a code that no longer exists. + assert_eq!( + gate.evaluate_at("second", CODE, true, T0 + 11), + reply(UnpairedReply::ConnectedElsewhere) + ); + assert_eq!( + gate.evaluate_at("third", CODE, false, T0 + 12), + reply(UnpairedReply::NoActiveCode) + ); + assert!(!gate.tracks("owner")); + } + + #[test] + fn code_expires_after_its_lifetime() { + let gate = gate_with_code(); + assert_eq!( + gate.evaluate_at("late", CODE, false, T0 + PAIRING_CODE_TTL_SECS), + reply(UnpairedReply::NoActiveCode) + ); + + let gate = gate_with_code(); + assert_eq!( + gate.evaluate_at("in-time", CODE, false, T0 + PAIRING_CODE_TTL_SECS - 1), + UnpairedDecision::Pair + ); + } + + #[test] + fn replacing_a_code_revokes_the_previous_code() { + let gate = gate_with_code(); + gate.register_issued_at("735144", T0 + 1); + assert_eq!(gate.evaluate_at("old-holder", CODE, true, T0 + 2), wrong(4)); + assert_eq!( + gate.evaluate_at("owner", "735144", true, T0 + 2), + UnpairedDecision::Pair + ); + assert!(!gate.lock().expire_codes(T0 + 3)); + } + + #[test] + fn wrong_codes_lock_out_one_chat_without_burning_the_code() { + let gate = gate_with_code(); + for attempts_left in (1..MAX_WRONG_PAIRING_CODES).rev() { + assert_eq!( + gate.evaluate_at("stranger", "000000", false, T0 + 1), + wrong(attempts_left) + ); + } + assert_eq!( + gate.evaluate_at("stranger", "000000", false, T0 + 2), + reply(UnpairedReply::LockedOut) + ); + // Locked out: silent for guesses, the right code and anything else. + assert_eq!( + gate.evaluate_at("stranger", "000001", false, T0 + 3), + UnpairedDecision::Silent + ); + assert_eq!( + gate.evaluate_at("stranger", CODE, false, T0 + 3), + UnpairedDecision::Silent + ); + assert_eq!( + gate.evaluate_at("stranger", "let me in", false, T0 + 3), + UnpairedDecision::Silent + ); + + // Another chat is unaffected and the code is still usable. + assert_eq!( + gate.evaluate_at("owner", "111111", false, T0 + 4), + wrong(MAX_WRONG_PAIRING_CODES - 1) + ); + assert_eq!( + gate.evaluate_at("owner", CODE, false, T0 + 5), + UnpairedDecision::Pair + ); + } + + #[test] + fn lockout_ends_with_the_code_it_protected() { + let lock_out = |gate: &PairingGate, now: i64| { + for _ in 0..MAX_WRONG_PAIRING_CODES { + gate.evaluate_at("chat", "000000", false, now); + } + assert_eq!( + gate.evaluate_at("chat", CODE, false, now), + UnpairedDecision::Silent + ); + }; + + // A new code from the host gives every chat a fresh set of attempts. + let gate = gate_with_code(); + lock_out(&gate, T0 + 1); + gate.register_issued_at("735144", T0 + 20); + assert_eq!( + gate.evaluate_at("chat", "000000", false, T0 + 21), + wrong(MAX_WRONG_PAIRING_CODES - 1) + ); + assert_eq!( + gate.evaluate_at("chat", "735144", false, T0 + 22), + UnpairedDecision::Pair + ); + + // After expiry the chat is told there is nothing left to guess. + let gate = gate_with_code(); + lock_out(&gate, T0 + 1); + assert_eq!( + gate.evaluate_at("chat", "000000", false, T0 + PAIRING_CODE_TTL_SECS), + reply(UnpairedReply::NoActiveCode) + ); + } + + #[test] + fn six_digits_without_a_pending_code_are_not_attempts() { + let gate = PairingGate::new(); + for _ in 0..20 { + gate.evaluate_at("chat", "000000", true, T0); + } + gate.register_issued_at(CODE, T0 + 1); + assert_eq!( + gate.evaluate_at("chat", "000000", true, T0 + 2), + wrong(MAX_WRONG_PAIRING_CODES - 1) + ); + } + + #[test] + fn only_six_ascii_digits_count_as_a_code_attempt() { + let gate = gate_with_code(); + for text in ["48291", "4829133", "48291a", "\u{ff14}82913", "482 913"] { + assert_eq!( + gate.evaluate_at(text, text, false, T0 + 1), + reply(UnpairedReply::EnterCode), + "{text:?}" + ); + } + assert!(constant_time_eq(b"482913", b"482913")); + assert!(!constant_time_eq(b"482913", b"482914")); + assert!(!constant_time_eq(b"482913", b"48291")); + } + + #[test] + fn notices_tell_the_truth_about_what_the_chat_can_do() { + let gate = gate_with_code(); + assert_eq!( + gate.evaluate_at("a", "/start", false, T0 + 1), + reply(UnpairedReply::Welcome) + ); + assert_eq!( + gate.evaluate_at("b", "hello", true, T0 + 1), + reply(UnpairedReply::EnterCode) + ); + + let gate = PairingGate::new(); + assert_eq!( + gate.evaluate_at("a", "/start", false, T0), + reply(UnpairedReply::NoActiveCode) + ); + assert_eq!( + gate.evaluate_at("b", "/start", true, T0), + reply(UnpairedReply::ConnectedElsewhere) + ); + assert_eq!( + gate.evaluate_at("c", "", true, T0), + reply(UnpairedReply::ConnectedElsewhere) + ); + } + + #[test] + fn notices_are_bounded_until_the_chat_goes_quiet_or_the_situation_changes() { + let gate = PairingGate::new(); + let mut replies = 0; + for second in 0..500 { + if gate.evaluate_at("chat", "hello", true, T0 + second) != UnpairedDecision::Silent { + replies += 1; + } + } + assert_eq!(replies, usize::from(MAX_UNPAIRED_NOTICES)); + + // Still chatty: the quiet period is measured from the last message. + let last = T0 + 499; + assert_eq!( + gate.evaluate_at("chat", "hello", true, last + UNPAIRED_QUIET_SECS - 1), + UnpairedDecision::Silent + ); + // Quiet for the whole period: the explanation is given again. + let last = last + UNPAIRED_QUIET_SECS - 1; + assert_eq!( + gate.evaluate_at("chat", "hello", true, last + UNPAIRED_QUIET_SECS), + reply(UnpairedReply::ConnectedElsewhere) + ); + + // A code issued by the host changes what the chat should do, so the + // new explanation is delivered even to a chat that was muted. + let now = last + UNPAIRED_QUIET_SECS; + for _ in 0..10 { + gate.evaluate_at("chat", "hello", true, now); + } + gate.register_issued_at(CODE, now); + assert_eq!( + gate.evaluate_at("chat", "hello", true, now + 1), + reply(UnpairedReply::EnterCode) + ); + } + + #[test] + fn tracking_is_bounded_and_overflow_chats_share_one_budget() { + let gate = gate_with_code(); + for index in 0..MAX_TRACKED_UNPAIRED_CHATS { + assert_eq!( + gate.evaluate_at(&format!("chat-{index}"), "000000", false, T0 + 1), + wrong(MAX_WRONG_PAIRING_CODES - 1) + ); + } + // Every record is in use by a chat that guessed: later chats share + // the overflow record, so the table and the guesses stay bounded. + for attempts_left in (1..MAX_WRONG_PAIRING_CODES).rev() { + assert_eq!( + gate.evaluate_at(&format!("late-{attempts_left}"), "000000", false, T0 + 2), + wrong(attempts_left) + ); + } + assert_eq!( + gate.evaluate_at("late-last", "000000", false, T0 + 2), + reply(UnpairedReply::LockedOut) + ); + assert_eq!( + gate.evaluate_at("late-after", CODE, false, T0 + 2), + UnpairedDecision::Silent + ); + assert_eq!(gate.lock().chats.len(), MAX_TRACKED_UNPAIRED_CHATS); + assert!(!gate.tracks("late-after")); + // A tracked chat keeps its own attempts and can still pair. + assert_eq!( + gate.evaluate_at("chat-0", CODE, false, T0 + 3), + UnpairedDecision::Pair + ); + assert_eq!( + gate.evaluate_at("recent", "hello", false, T0 + 4), + reply(UnpairedReply::NoActiveCode) + ); + assert_eq!(gate.lock().chats.len(), MAX_TRACKED_UNPAIRED_CHATS); + + // Records of chats that went quiet make room again. + let later = T0 + 3 + UNPAIRED_QUIET_SECS; + assert_eq!( + gate.evaluate_at("newcomer", "hello", false, later), + reply(UnpairedReply::NoActiveCode) + ); + assert!(gate.tracks("recent")); + assert!(gate.tracks("newcomer")); + assert_eq!(gate.lock().chats.len(), 2); + } + + #[test] + fn every_reply_is_localized_for_each_supported_language() { + let has_cjk = |text: &str| text.chars().any(|c| ('\u{4e00}'..='\u{9fff}').contains(&c)); + for reply in [ + UnpairedReply::Welcome, + UnpairedReply::EnterCode, + UnpairedReply::WrongCode { attempts_left: 3 }, + UnpairedReply::LockedOut, + UnpairedReply::NoActiveCode, + UnpairedReply::ConnectedElsewhere, + ] { + let english = reply.text(BotLanguage::EnUS); + let simplified = reply.text(BotLanguage::ZhCN); + let traditional = reply.text(BotLanguage::ZhTW); + assert!(!has_cjk(&english), "{reply:?}: {english}"); + assert!(has_cjk(&simplified), "{reply:?}"); + assert!(has_cjk(&traditional), "{reply:?}"); + assert_ne!(simplified, traditional, "{reply:?}"); + for text in [&english, &simplified, &traditional] { + assert!(!text.trim().is_empty()); + assert!(!text.contains('{'), "unformatted placeholder: {text}"); + } + } + for language in [BotLanguage::EnUS, BotLanguage::ZhCN, BotLanguage::ZhTW] { + assert!(UnpairedReply::WrongCode { attempts_left: 3 } + .text(language) + .contains('3')); + for reply in [ + UnpairedReply::WrongCode { attempts_left: 3 }, + UnpairedReply::LockedOut, + UnpairedReply::NoActiveCode, + UnpairedReply::ConnectedElsewhere, + ] { + assert!(reply.text(language).contains("OpenBitFun")); + } + } + } +} diff --git a/src/crates/assembly/core/src/service/remote_connect/bot/telegram.rs b/src/crates/assembly/core/src/service/remote_connect/bot/telegram.rs index de92d8b5fa..a5dbdf6f29 100644 --- a/src/crates/assembly/core/src/service/remote_connect/bot/telegram.rs +++ b/src/crates/assembly/core/src/service/remote_connect/bot/telegram.rs @@ -6,7 +6,9 @@ use anyhow::{anyhow, Result}; use log::{error, info, warn}; -use openbitfun_services_integrations::remote_connect::bot::telegram::TelegramBotApi; +use openbitfun_services_integrations::remote_connect::bot::telegram::{ + TelegramBotApi, TelegramIncomingMessage, +}; pub use openbitfun_services_integrations::remote_connect::bot::telegram::{ TelegramConfig, MAX_TELEGRAM_FILE_BYTES, }; @@ -16,53 +18,92 @@ use tokio::sync::RwLock; use super::command_router::{ complete_im_bot_pairing, current_bot_language, execute_forwarded_turn, handle_command, - parse_command, welcome_message, BotAction, BotChatState, BotInteractionHandler, - BotInteractiveRequest, BotLanguage, BotMessageSender, HandleResult, + parse_command, BotAction, BotChatState, BotInteractionHandler, BotInteractiveRequest, + BotMessageSender, HandleResult, }; +use super::pairing_gate::{PairingGate, UnpairedDecision}; use super::{ - load_bot_persistence, update_bot_persistence, BotConfig, BotRuntimeFence, SavedBotConnection, + load_bot_persistence, BotConfig, BotRuntimeFence, SavedBotConnection, WorkspaceFileContent, }; use crate::service::remote_connect::remote_server::ImageAttachment; -pub struct TelegramBot { - api: TelegramBotApi, - pending_pairings: Arc>>, - last_update_id: Arc>, - chat_states: Arc>>, - runtime_fence: BotRuntimeFence, +/// Telegram Bot API calls this adapter makes. The provider client is the +/// production implementation; unit tests substitute a scripted fake. +#[async_trait::async_trait] +pub(crate) trait TelegramPlatform: Send + Sync { + fn bot_token(&self) -> &str; + async fn send_message(&self, chat_id: i64, text: &str) -> Result<()>; + async fn send_message_with_keyboard( + &self, + chat_id: i64, + text: &str, + actions: &[BotAction], + ) -> Result<()>; + async fn send_artifact(&self, chat_id: i64, content: WorkspaceFileContent) -> Result<()>; + async fn set_bot_commands(&self) -> Result<()>; + async fn poll_updates( + &self, + last_update_id: i64, + ) -> Result<(i64, Vec)>; } -#[derive(Debug, Clone)] -struct PendingPairing { - created_at: i64, -} +#[async_trait::async_trait] +impl TelegramPlatform for TelegramBotApi { + fn bot_token(&self) -> &str { + &self.config().bot_token + } -impl TelegramBot { - fn invalid_pairing_code_message(language: BotLanguage) -> &'static str { - if language.is_chinese() { - "配对码无效或已过期,请重试。" - } else { - "Invalid or expired pairing code. Please try again." - } + async fn send_message(&self, chat_id: i64, text: &str) -> Result<()> { + TelegramBotApi::send_message(self, chat_id, text).await } - fn enter_pairing_code_message(language: BotLanguage) -> &'static str { - if language.is_chinese() { - "请输入 OpenBitFun Desktop 中显示的 6 位配对码。" - } else { - "Please enter the 6-digit pairing code from OpenBitFun Desktop." - } + async fn send_message_with_keyboard( + &self, + chat_id: i64, + text: &str, + actions: &[BotAction], + ) -> Result<()> { + TelegramBotApi::send_message_with_keyboard(self, chat_id, text, actions).await + } + + async fn send_artifact(&self, chat_id: i64, content: WorkspaceFileContent) -> Result<()> { + TelegramBotApi::send_artifact(self, chat_id, content).await } + async fn set_bot_commands(&self) -> Result<()> { + TelegramBotApi::set_bot_commands(self).await + } + + async fn poll_updates( + &self, + last_update_id: i64, + ) -> Result<(i64, Vec)> { + TelegramBotApi::poll_updates(self, last_update_id).await + } +} + +pub struct TelegramBot { + api: Arc, + pairing_gate: PairingGate, + last_update_id: Arc>, + chat_states: Arc>>, + runtime_fence: BotRuntimeFence, +} + +impl TelegramBot { #[cfg(test)] pub fn new(config: TelegramConfig) -> Self { Self::new_fenced(config, BotRuntimeFence::standalone()) } pub(crate) fn new_fenced(config: TelegramConfig, runtime_fence: BotRuntimeFence) -> Self { + Self::with_platform(Arc::new(TelegramBotApi::new(config)), runtime_fence) + } + + fn with_platform(api: Arc, runtime_fence: BotRuntimeFence) -> Self { Self { - api: TelegramBotApi::new(config), - pending_pairings: Arc::new(RwLock::new(HashMap::new())), + api, + pairing_gate: PairingGate::new(), last_update_id: Arc::new(RwLock::new(0)), chat_states: Arc::new(RwLock::new(HashMap::new())), runtime_fence, @@ -146,6 +187,7 @@ impl TelegramBot { for reference in super::extract_output_file_references(text) { if !self.runtime_fence.is_lifecycle_current() || self.runtime_fence.identity_epoch() != identity_epoch + || !super::chat_is_paired(&self.chat_states, &chat_id).await { return; } @@ -162,6 +204,7 @@ impl TelegramBot { .await; if !self.runtime_fence.is_lifecycle_current() || self.runtime_fence.identity_epoch() != identity_epoch + || !super::chat_is_paired(&self.chat_states, &chat_id).await { return; } @@ -191,6 +234,11 @@ impl TelegramBot { /// text is replaced with a friendlier prompt, and a Cancel Task button is /// added via the inline keyboard. async fn send_handle_result(&self, chat_id: i64, result: &HandleResult) { + if !self.runtime_fence.is_lifecycle_current() + || !super::chat_is_paired(&self.chat_states, &chat_id).await + { + return; + } let text = if result.menu.items.is_empty() && result.menu.title.is_empty() { result.reply.clone() } else { @@ -222,23 +270,60 @@ impl TelegramBot { self.api.set_bot_commands().await } + /// Only a valid code can replace the chat that owns this connection. + /// Keep admission serialized with commands, and never create state for a refusal. + async fn handle_pairing_message(&self, chat_id: i64, text: &str) -> bool { + let epoch = self.runtime_fence.identity_epoch(); + let mut states = self.chat_states.write().await; + if !self.runtime_fence.is_lifecycle_current() { + return false; + } + self.runtime_fence.reconcile_states(&mut states); + if states.get(&chat_id).is_some_and(|state| state.paired) { + return true; + } + let connected_elsewhere = states.values().any(|state| state.paired); + match self + .pairing_gate + .evaluate(&chat_id.to_string(), text, connected_elsewhere) + { + UnpairedDecision::Pair => { + let mut state = BotChatState::new(chat_id.to_string()); + let result = complete_im_bot_pairing(&mut state).await; + if !self.runtime_fence.is_lifecycle_current() + || self.runtime_fence.identity_epoch() != epoch + { + return false; + } + states.clear(); + states.insert(chat_id, state.clone()); + self.persist_chat_state(chat_id, &state).await; + drop(states); + self.send_handle_result(chat_id, &result).await; + self.set_bot_commands().await.ok(); + true + } + UnpairedDecision::Reply(reply) => { + drop(states); + let language = current_bot_language().await; + if self.runtime_fence.is_lifecycle_current() + && self.runtime_fence.identity_epoch() == epoch + { + let _ = self.send_message(chat_id, &reply.text(language)).await; + } + false + } + UnpairedDecision::Silent => false, + } + } + pub async fn register_pairing(&self, pairing_code: &str) -> Result<()> { - self.pending_pairings.write().await.insert( - pairing_code.to_string(), - PendingPairing { - created_at: chrono::Utc::now().timestamp(), - }, - ); + self.pairing_gate.register(pairing_code); Ok(()) } pub async fn verify_pairing_code(&self, code: &str) -> bool { - let mut pairings = self.pending_pairings.write().await; - if let Some(p) = pairings.remove(code) { - let age = chrono::Utc::now().timestamp() - p.created_at; - return age < 300; - } - false + self.pairing_gate.consume(code) } /// Returns `(chat_id, text, images)` tuples for each incoming message. @@ -275,48 +360,11 @@ impl TelegramBot { match poll_result { Ok(messages) => { for (chat_id, text, _images) in messages { - let trimmed = text.trim(); - let language = current_bot_language().await; - - if trimmed == "/start" { - self.send_message(chat_id, welcome_message(language)) - .await - .ok(); - continue; + if *stop_rx.borrow() || !self.runtime_fence.is_lifecycle_current() { + return Err(anyhow!("bot lifecycle replaced during pairing")); } - - if trimmed.len() == 6 && trimmed.chars().all(|c| c.is_ascii_digit()) { - if self.verify_pairing_code(trimmed).await { - info!("Telegram pairing successful, chat_id={chat_id}"); - let mut state = BotChatState::new(chat_id.to_string()); - let identity_epoch = self.runtime_fence.identity_epoch(); - let result = complete_im_bot_pairing(&mut state).await; - if *stop_rx.borrow() || !self.runtime_fence.is_lifecycle_current() { - return Err(anyhow!("bot lifecycle replaced during pairing")); - } - let mut states = self.chat_states.write().await; - self.runtime_fence.reconcile_states(&mut states); - self.runtime_fence - .sanitize_after_epoch(identity_epoch, &mut state); - states.insert(chat_id, state.clone()); - drop(states); - self.persist_chat_state(chat_id, &state).await; - self.send_handle_result(chat_id, &result).await; - self.set_bot_commands().await.ok(); - - return Ok(chat_id); - } else { - self.send_message( - chat_id, - Self::invalid_pairing_code_message(language), - ) - .await - .ok(); - } - } else { - self.send_message(chat_id, Self::enter_pairing_code_message(language)) - .await - .ok(); + if self.handle_pairing_message(chat_id, &text).await { + return Ok(chat_id); } } } @@ -377,46 +425,12 @@ impl TelegramBot { let mut states = self.chat_states.write().await; let command_identity_epoch = self.runtime_fence.identity_epoch(); self.runtime_fence.reconcile_states(&mut states); - let state = states.entry(chat_id).or_insert_with(|| { - let mut s = BotChatState::new(chat_id.to_string()); - s.paired = true; - s - }); - let language = current_bot_language().await; - - if !state.paired { - let trimmed = text.trim(); - if trimmed == "/start" { - self.send_message(chat_id, welcome_message(language)) - .await - .ok(); - return; - } - if trimmed.len() == 6 && trimmed.chars().all(|c| c.is_ascii_digit()) { - if self.verify_pairing_code(trimmed).await { - let identity_epoch = self.runtime_fence.identity_epoch(); - let result = complete_im_bot_pairing(state).await; - self.runtime_fence - .sanitize_after_epoch(identity_epoch, state); - self.persist_chat_state(chat_id, state).await; - if !self.runtime_fence.is_lifecycle_current() { - return; - } - self.send_handle_result(chat_id, &result).await; - self.set_bot_commands().await.ok(); - return; - } else { - self.send_message(chat_id, Self::invalid_pairing_code_message(language)) - .await - .ok(); - return; - } - } - self.send_message(chat_id, Self::enter_pairing_code_message(language)) - .await - .ok(); + if !states.get(&chat_id).is_some_and(|state| state.paired) { + drop(states); + self.handle_pairing_message(chat_id, text).await; return; } + let state = states.get_mut(&chat_id).expect("paired chat exists"); if self.runtime_fence.identity_epoch() != command_identity_epoch { return; @@ -460,6 +474,7 @@ impl TelegramBot { Box::pin(async move { if !msg_bot.runtime_fence.is_lifecycle_current() || msg_bot.runtime_fence.identity_epoch() != output_identity_epoch + || !super::chat_is_paired(&msg_bot.chat_states, &chat_id).await { return; } @@ -478,6 +493,7 @@ impl TelegramBot { .await; if !bot.runtime_fence.is_lifecycle_current() || bot.runtime_fence.identity_epoch() != output_identity_epoch + || !super::chat_is_paired(&bot.chat_states, &chat_id).await { return; } @@ -520,11 +536,9 @@ impl TelegramBot { } let mut states = self.chat_states.write().await; self.runtime_fence.reconcile_states(&mut states); - let state = states.entry(chat_id).or_insert_with(|| { - let mut s = BotChatState::new(chat_id.to_string()); - s.paired = true; - s - }); + let Some(state) = states.get_mut(&chat_id).filter(|state| state.paired) else { + return; + }; if self.runtime_fence.identity_epoch() != identity_epoch { return; } @@ -550,20 +564,370 @@ impl TelegramBot { bot_type: "telegram".to_string(), chat_id: chat_id.to_string(), config: BotConfig::Telegram { - bot_token: self.api.config().bot_token.clone(), + bot_token: self.api.bot_token().to_string(), }, chat_state: snapshot, connected_at: chrono::Utc::now().timestamp(), }; - self.runtime_fence.commit_if_current(|| { - update_bot_persistence(|data| data.upsert(connection)); - }); + self.runtime_fence.persist_connection(connection); } } #[cfg(test)] mod tests { + use super::super::test_support::{ + legacy_saved_connection, paired_state, question, PAIRING_CODE, + }; use super::*; + use std::collections::VecDeque; + use std::sync::Mutex as StdMutex; + use std::time::Duration; + + const OWNER: i64 = 1001; + const STRANGER: i64 = 2002; + + #[derive(Debug, Clone, PartialEq, Eq)] + enum Sent { + Text { chat_id: i64, text: String }, + Keyboard { chat_id: i64 }, + Artifact { chat_id: i64 }, + } + + impl Sent { + fn chat_id(&self) -> i64 { + match self { + Self::Text { chat_id, .. } + | Self::Keyboard { chat_id } + | Self::Artifact { chat_id } => *chat_id, + } + } + } + + /// Records every outbound call and replays scripted update batches. + #[derive(Default)] + struct FakeTelegram { + sent: StdMutex>, + updates: StdMutex>>, + } + + impl FakeTelegram { + fn record(&self, sent: Sent) { + self.sent.lock().unwrap().push(sent); + } + + fn sent_to(&self, chat_id: i64) -> Vec { + self.sent + .lock() + .unwrap() + .iter() + .filter(|sent| sent.chat_id() == chat_id) + .cloned() + .collect() + } + + fn script(&self, batch: Vec<(i64, &str)>) { + self.updates.lock().unwrap().push_back( + batch + .into_iter() + .map(|(chat_id, text)| TelegramIncomingMessage { + chat_id, + text: text.to_string(), + images: Vec::new(), + }) + .collect(), + ); + } + } + + #[async_trait::async_trait] + impl TelegramPlatform for FakeTelegram { + fn bot_token(&self) -> &str { + "fixture-token" + } + + async fn send_message(&self, chat_id: i64, text: &str) -> Result<()> { + self.record(Sent::Text { + chat_id, + text: text.to_string(), + }); + Ok(()) + } + + async fn send_message_with_keyboard( + &self, + chat_id: i64, + _text: &str, + _actions: &[BotAction], + ) -> Result<()> { + self.record(Sent::Keyboard { chat_id }); + Ok(()) + } + + async fn send_artifact(&self, chat_id: i64, _content: WorkspaceFileContent) -> Result<()> { + self.record(Sent::Artifact { chat_id }); + Ok(()) + } + + async fn set_bot_commands(&self) -> Result<()> { + Ok(()) + } + + async fn poll_updates( + &self, + last_update_id: i64, + ) -> Result<(i64, Vec)> { + let next = self.updates.lock().unwrap().pop_front(); + match next { + Some(batch) => Ok((last_update_id + 1, batch)), + None => std::future::pending().await, + } + } + } + + fn fake_bot() -> (Arc, Arc) { + let fake = Arc::new(FakeTelegram::default()); + let bot = Arc::new(TelegramBot::with_platform( + fake.clone(), + BotRuntimeFence::standalone(), + )); + (fake, bot) + } + + /// A bot whose first pairing already completed with `OWNER`. + async fn connected_bot() -> (Arc, Arc) { + let (fake, bot) = fake_bot(); + bot.restore_chat_state(OWNER, paired_state(&OWNER.to_string())) + .await; + (fake, bot) + } + + fn saved_chat_id(bot: &TelegramBot) -> Option { + bot.runtime_fence + .saved_connection("telegram") + .map(|saved| saved.chat_id) + } + + async fn pair_through_updates(bot: &TelegramBot) -> i64 { + let (_stop_tx, mut stop_rx) = tokio::sync::watch::channel(false); + tokio::time::timeout(Duration::from_secs(5), bot.wait_for_pairing(&mut stop_rx)) + .await + .expect("pairing must finish with the scripted updates") + .expect("pairing must succeed") + } + + #[tokio::test] + async fn unknown_chat_after_first_pairing_is_refused_and_cannot_run_a_command() { + let (fake, bot) = connected_bot().await; + + bot.handle_incoming_message(STRANGER, "/help", vec![]).await; + + assert!( + !bot.chat_states.read().await.contains_key(&STRANGER), + "a chat that never paired must not gain state" + ); + let replies = fake.sent_to(STRANGER); + assert_eq!(replies.len(), 1, "one explanatory reply: {replies:?}"); + assert!( + matches!(replies[0], Sent::Text { .. }), + "an unpaired chat must not receive a command menu: {replies:?}" + ); + assert_eq!(saved_chat_id(&bot), Some(OWNER.to_string())); + + bot.handle_incoming_message(OWNER, "/help", vec![]).await; + assert!( + fake.sent_to(OWNER) + .iter() + .any(|sent| matches!(sent, Sent::Keyboard { .. })), + "the paired chat keeps its commands" + ); + } + + #[tokio::test] + async fn outbound_paths_never_create_state_or_reach_an_unpaired_chat() { + let (fake, bot) = connected_bot().await; + let epoch = bot.runtime_fence.identity_epoch(); + + bot.deliver_interaction(STRANGER, question("tool-1"), epoch) + .await; + bot.notify_files_ready( + STRANGER, + "missing-session", + None, + "[report](computer://report.pdf)", + epoch, + ) + .await; + + assert!(!bot.chat_states.read().await.contains_key(&STRANGER)); + assert_eq!(fake.sent_to(STRANGER), Vec::::new()); + assert_eq!(saved_chat_id(&bot), Some(OWNER.to_string())); + + // A chat that is known but never completed pairing is treated the same. + bot.chat_states + .write() + .await + .insert(STRANGER, BotChatState::new(STRANGER.to_string())); + bot.deliver_interaction(STRANGER, question("tool-2"), epoch) + .await; + assert_eq!(fake.sent_to(STRANGER), Vec::::new()); + let states = bot.chat_states.read().await; + let stranger = states.get(&STRANGER).expect("state was inserted above"); + assert!(!stranger.paired); + assert!(stranger.pending_action.is_none()); + drop(states); + + // The paired chat still receives its interaction. + bot.deliver_interaction(OWNER, question("tool-3"), epoch) + .await; + assert_eq!(fake.sent_to(OWNER).len(), 1); + } + + #[tokio::test] + async fn wrong_codes_are_limited_per_chat_without_locking_the_owner_or_burning_the_code() { + let (fake, bot) = fake_bot(); + bot.register_pairing(PAIRING_CODE).await.unwrap(); + let mut batch = vec![(STRANGER, "000000"); 5]; + // The right code no longer helps a chat that used up its attempts. + batch.push((STRANGER, PAIRING_CODE)); + batch.push((OWNER, "111111")); + batch.push((OWNER, PAIRING_CODE)); + fake.script(batch); + + assert_eq!(pair_through_updates(&bot).await, OWNER); + + let states = bot.chat_states.read().await; + assert!(states.get(&OWNER).is_some_and(|state| state.paired)); + assert!(!states.contains_key(&STRANGER)); + drop(states); + // Four "wrong code" replies, then one lockout notice, then silence. + assert_eq!(fake.sent_to(STRANGER).len(), 5); + assert_eq!(saved_chat_id(&bot), Some(OWNER.to_string())); + } + + #[tokio::test] + async fn repeated_messages_from_an_unpaired_chat_get_a_bounded_number_of_replies() { + // While the first pairing is still pending. + let (fake, bot) = fake_bot(); + bot.register_pairing(PAIRING_CODE).await.unwrap(); + let mut batch = vec![(STRANGER, "hello"); 20]; + batch.push((OWNER, PAIRING_CODE)); + fake.script(batch); + assert_eq!(pair_through_updates(&bot).await, OWNER); + let replies = fake.sent_to(STRANGER).len(); + assert!( + (1..=3).contains(&replies), + "replies while pairing: {replies}" + ); + + // After pairing, in the message loop. + for index in 0..20 { + bot.handle_incoming_message(STRANGER, &format!("hello again {index}"), vec![]) + .await; + } + let replies = fake.sent_to(STRANGER).len() - replies; + assert!( + (1..=3).contains(&replies), + "replies when connected: {replies}" + ); + assert!(!bot.chat_states.read().await.contains_key(&STRANGER)); + } + + #[tokio::test] + async fn code_issued_for_a_connected_bot_moves_the_connection_to_the_chat_that_presents_it() { + let (fake, bot) = connected_bot().await; + bot.register_pairing(PAIRING_CODE).await.unwrap(); + + bot.handle_incoming_message(STRANGER, "111111", vec![]) + .await; + assert!(!bot.chat_states.read().await.contains_key(&STRANGER)); + assert_eq!(saved_chat_id(&bot), Some(OWNER.to_string())); + + bot.handle_incoming_message(STRANGER, PAIRING_CODE, vec![]) + .await; + let states = bot.chat_states.read().await; + assert!(states.get(&STRANGER).is_some_and(|state| state.paired)); + assert!( + !states.contains_key(&OWNER), + "one connection has one chat: the previous chat is no longer paired" + ); + drop(states); + assert_eq!(saved_chat_id(&bot), Some(STRANGER.to_string())); + assert!( + !bot.verify_pairing_code(PAIRING_CODE).await, + "the pairing code is single use" + ); + assert!(!fake.sent_to(STRANGER).is_empty()); + } + + #[tokio::test] + async fn legacy_persisted_paired_chat_is_restored_without_pairing_again() { + let saved = legacy_saved_connection( + "telegram", + &OWNER.to_string(), + serde_json::json!({ "bot_type": "telegram", "bot_token": "fixture-token" }), + ); + let (fake, bot) = fake_bot(); + + bot.restore_chat_state(OWNER, saved.chat_state.clone()) + .await; + bot.handle_incoming_message(OWNER, "/help", vec![]).await; + + assert_eq!( + fake.sent_to(OWNER) + .iter() + .filter(|sent| matches!(sent, Sent::Keyboard { .. })) + .count(), + 1, + "the restored chat reaches the command router without a pairing prompt" + ); + let resaved = bot + .runtime_fence + .saved_connection("telegram") + .expect("restored connection is saved"); + assert_eq!(resaved.chat_id, OWNER.to_string()); + assert!(resaved.chat_state.paired); + // The stored shape is unchanged: an older build reads it back. + let stored = serde_json::to_value(&resaved.chat_state).unwrap(); + let legacy = serde_json::to_value(&saved.chat_state).unwrap(); + assert_eq!(stored, legacy); + assert_eq!(stored["paired"], serde_json::json!(true)); + } + + #[tokio::test] + async fn retired_or_reidentified_bot_neither_answers_nor_delivers() { + let (fake, bot) = connected_bot().await; + let epoch = bot.runtime_fence.identity_epoch(); + + // An account change invalidates deliveries that started before it. + bot.runtime_fence + .account_identity_epoch + .fetch_add(1, std::sync::atomic::Ordering::AcqRel); + bot.deliver_interaction(OWNER, question("tool-1"), epoch) + .await; + bot.notify_files_ready( + OWNER, + "missing-session", + None, + "[report](computer://report.pdf)", + epoch, + ) + .await; + assert_eq!(fake.sent_to(OWNER), Vec::::new()); + + // A replaced instance stays silent for paired and unpaired chats alike. + bot.runtime_fence.slot.advance(); + bot.handle_incoming_message(OWNER, "/help", vec![]).await; + bot.handle_incoming_message(STRANGER, "/help", vec![]).await; + bot.deliver_interaction( + OWNER, + question("tool-2"), + bot.runtime_fence.identity_epoch(), + ) + .await; + assert_eq!(fake.sent.lock().unwrap().len(), 0); + assert!(!bot.chat_states.read().await.contains_key(&STRANGER)); + assert_eq!(saved_chat_id(&bot), Some(OWNER.to_string())); + } #[tokio::test] async fn account_clear_is_bounded_by_epoch_when_a_command_holds_state_lock() { diff --git a/src/crates/assembly/core/src/service/remote_connect/bot/weixin.rs b/src/crates/assembly/core/src/service/remote_connect/bot/weixin.rs index a72f110baf..be1cc49b2e 100644 --- a/src/crates/assembly/core/src/service/remote_connect/bot/weixin.rs +++ b/src/crates/assembly/core/src/service/remote_connect/bot/weixin.rs @@ -21,12 +21,11 @@ use tokio::sync::{Mutex, Notify, RwLock}; use super::command_router::{ complete_im_bot_pairing, current_bot_language, execute_forwarded_turn_with_submission, - handle_command, parse_command, welcome_message, BotChatState, BotInteractionHandler, - BotInteractiveRequest, BotMessageSender, HandleResult, -}; -use super::{ - load_bot_persistence, update_bot_persistence, BotConfig, BotRuntimeFence, SavedBotConnection, + handle_command, parse_command, BotChatState, BotInteractionHandler, BotInteractiveRequest, + BotMessageSender, HandleResult, }; +use super::pairing_gate::{PairingGate, UnpairedDecision}; +use super::{load_bot_persistence, BotConfig, BotRuntimeFence, SavedBotConnection}; use crate::agentic::coordination::get_global_coordinator; use crate::agentic::events::{AgenticEvent, EventSubscriber}; use crate::service::remote_connect::remote_server::ImageAttachment; @@ -237,14 +236,9 @@ fn merge_pending(pending: &[PendingOutbound]) -> String { kept.join(PENDING_SEPARATOR) } -#[derive(Debug, Clone)] -struct PendingPairing { - created_at: i64, -} - pub struct WeixinBot { api: Arc, - pending_pairings: Arc>>, + pairing_gate: PairingGate, chat_states: Arc>>, context_tokens: Arc>>, runtime_fence: BotRuntimeFence, @@ -296,7 +290,7 @@ impl WeixinBot { let context_tokens = weixin_provider::load_context_tokens(&config.bot_account_id); Self { api: Arc::new(WeixinProviderClient::new(config)), - pending_pairings: Arc::new(RwLock::new(HashMap::new())), + pairing_gate: PairingGate::new(), chat_states: Arc::new(RwLock::new(HashMap::new())), context_tokens: Arc::new(RwLock::new(context_tokens)), runtime_fence, @@ -344,23 +338,60 @@ impl WeixinBot { } } + /// Only a valid code can replace the chat that owns this connection. + /// Keep admission serialized with commands, and never create state for a refusal. + async fn handle_pairing_message(&self, peer_id: &str, text: &str) -> bool { + let epoch = self.runtime_fence.identity_epoch(); + let mut states = self.chat_states.write().await; + if !self.runtime_fence.is_lifecycle_current() { + return false; + } + self.runtime_fence.reconcile_states(&mut states); + if states.get(peer_id).is_some_and(|state| state.paired) { + return true; + } + let connected_elsewhere = states.values().any(|state| state.paired); + match self + .pairing_gate + .evaluate(peer_id, text, connected_elsewhere) + { + UnpairedDecision::Pair => { + let mut state = BotChatState::new(peer_id.to_string()); + let result = complete_im_bot_pairing(&mut state).await; + if !self.runtime_fence.is_lifecycle_current() + || self.runtime_fence.identity_epoch() != epoch + { + return false; + } + states.clear(); + states.insert(peer_id.to_string(), state.clone()); + self.persist_chat_state(peer_id, &state).await; + drop(states); + self.send_handle_result(peer_id, &result).await; + true + } + UnpairedDecision::Reply(reply) => { + drop(states); + let language = current_bot_language().await; + if self.runtime_fence.is_lifecycle_current() + && self.runtime_fence.identity_epoch() == epoch + { + self.try_send_text(peer_id, &reply.text(language), "pairing-prompt") + .await; + } + false + } + UnpairedDecision::Silent => false, + } + } + pub async fn register_pairing(&self, pairing_code: &str) -> Result<()> { - self.pending_pairings.write().await.insert( - pairing_code.to_string(), - PendingPairing { - created_at: chrono::Utc::now().timestamp(), - }, - ); + self.pairing_gate.register(pairing_code); Ok(()) } pub async fn verify_pairing_code(&self, code: &str) -> bool { - let mut pairings = self.pending_pairings.write().await; - if let Some(pairing) = pairings.remove(code) { - let age = chrono::Utc::now().timestamp() - pairing.created_at; - return age < 300; - } - false + self.pairing_gate.consume(code) } pub async fn send_text(&self, peer_id: &str, text: &str) -> Result<()> { @@ -738,6 +769,11 @@ impl WeixinBot { } async fn send_handle_result(&self, peer_id: &str, result: &HandleResult) { + if !self.runtime_fence.is_lifecycle_current() + || !super::chat_is_paired(&self.chat_states, peer_id).await + { + return; + } let language = current_bot_language().await; let text = if result.menu.items.is_empty() && result.menu.title.is_empty() { result.reply.clone() @@ -802,6 +838,7 @@ impl WeixinBot { for reference in super::extract_output_file_references(text) { if !self.runtime_fence.is_lifecycle_current() || self.runtime_fence.identity_epoch() != identity_epoch + || !super::chat_is_paired(&self.chat_states, peer_id).await { return; } @@ -818,6 +855,7 @@ impl WeixinBot { .await; if !self.runtime_fence.is_lifecycle_current() || self.runtime_fence.identity_epoch() != identity_epoch + || !super::chat_is_paired(&self.chat_states, peer_id).await { return; } @@ -860,9 +898,7 @@ impl WeixinBot { chat_state: snapshot, connected_at: chrono::Utc::now().timestamp(), }; - self.runtime_fence.commit_if_current(|| { - update_bot_persistence(|data| data.upsert(connection)); - }); + self.runtime_fence.persist_connection(connection); } pub async fn wait_for_pairing( @@ -933,61 +969,11 @@ impl WeixinBot { self.remember_context_token(&peer, token).await; } let text = weixin_provider::body_from_message(msg).trim().to_string(); - let language = current_bot_language().await; - - if text == "/start" { - self.try_send_text(&peer, welcome_message(language), "welcome") - .await; - continue; + if *stop_rx.borrow() || !self.runtime_fence.is_lifecycle_current() { + return Err(anyhow!("bot lifecycle replaced during pairing")); } - - if text.len() == 6 && text.chars().all(|c| c.is_ascii_digit()) { - if self.verify_pairing_code(&text).await { - info!("Weixin pairing successful peer={peer}"); - let mut state = BotChatState::new(peer.clone()); - let identity_epoch = self.runtime_fence.identity_epoch(); - let result = complete_im_bot_pairing(&mut state).await; - if *stop_rx.borrow() || !self.runtime_fence.is_lifecycle_current() { - return Err(anyhow!("bot lifecycle replaced during pairing")); - } - let mut states = self.chat_states.write().await; - self.runtime_fence.reconcile_states(&mut states); - self.runtime_fence - .sanitize_after_epoch(identity_epoch, &mut state); - states.insert(peer.clone(), state.clone()); - drop(states); - self.persist_chat_state(&peer, &state).await; - - self.send_handle_result(&peer, &result).await; - return Ok(peer); - } - let err = if language.is_chinese() { - "\u{914d}\u{5bf9}\u{7801}\u{65e0}\u{6548}\u{6216}\u{5df2}\u{8fc7}\u{671f}\u{ff0c}\u{8bf7}\u{91cd}\u{8bd5}\u{3002}" - } else { - "Invalid or expired pairing code." - }; - self.try_send_text(&peer, err, "pairing-invalid").await; - } else if !text.is_empty() { - let err = if language.is_chinese() { - "\u{8bf7}\u{8f93}\u{5165} OpenBitFun \u{684c}\u{9762}\u{7aef}\u{8fdc}\u{7a0b}\u{8fde}\u{63a5}\u{4e2d}\u{663e}\u{793a}\u{7684} 6 \u{4f4d}\u{914d}\u{5bf9}\u{7801}\u{3002}" - } else { - "Please send the 6-digit pairing code from OpenBitFun Desktop Remote Connect." - }; - self.try_send_text(&peer, err, "pairing-prompt").await; - } else if weixin_provider::has_inbound_file_items(msg) { - self.try_send_text( - &peer, - super::locale::strings_for(language).need_pairing, - "pairing-file-hint", - ) - .await; - } else if weixin_provider::has_inbound_image_items(msg) { - let err = if language.is_chinese() { - "\u{914d}\u{5bf9}\u{8bf7}\u{76f4}\u{63a5}\u{53d1}\u{9001} 6 \u{4f4d}\u{6570}\u{5b57}\u{914d}\u{5bf9}\u{7801}\u{ff1b}\u{5b8c}\u{6210}\u{914d}\u{5bf9}\u{540e}\u{518d}\u{53d1}\u{9001}\u{56fe}\u{7247}\u{4e0e}\u{52a9}\u{624b}\u{5bf9}\u{8bdd}\u{3002}" - } else { - "To pair, send the 6-digit code only. After pairing you can send images to chat." - }; - self.try_send_text(&peer, err, "pairing-image-hint").await; + if self.handle_pairing_message(&peer, &text).await { + return Ok(peer); } } } @@ -1119,6 +1105,11 @@ impl WeixinBot { { return; } + if !super::chat_is_paired(&self.chat_states, peer.as_str()).await { + self.handle_pairing_message(&peer, &weixin_provider::body_from_message(&message)) + .await; + return; + } let language = current_bot_language().await; if weixin_provider::has_unsupported_media_items(&message) { self.try_send_text( @@ -1271,55 +1262,13 @@ impl WeixinBot { } let mut states = self.chat_states.write().await; self.runtime_fence.reconcile_states(&mut states); - let state = states.entry(peer_id.clone()).or_insert_with(|| { - let mut state = BotChatState::new(peer_id.clone()); - state.paired = true; - state - }); - let language = current_bot_language().await; - - if !state.paired { - let trimmed = text.trim(); - if trimmed == "/start" { - drop(states); - self.try_send_text(&peer_id, welcome_message(language), "welcome") - .await; - return; - } - if trimmed.len() == 6 && trimmed.chars().all(|c| c.is_ascii_digit()) { - if self.verify_pairing_code(trimmed).await { - let identity_epoch = self.runtime_fence.identity_epoch(); - let result = complete_im_bot_pairing(state).await; - self.runtime_fence - .sanitize_after_epoch(identity_epoch, state); - self.persist_chat_state(&peer_id, state).await; - drop(states); - if !self.runtime_fence.is_lifecycle_current() - || self.runtime_fence.identity_epoch() != command_identity_epoch - { - return; - } - self.send_handle_result(&peer_id, &result).await; - return; - } - let err = if language.is_chinese() { - "\u{914d}\u{5bf9}\u{7801}\u{65e0}\u{6548}\u{6216}\u{5df2}\u{8fc7}\u{671f}\u{3002}" - } else { - "Invalid or expired pairing code." - }; - drop(states); - self.try_send_text(&peer_id, err, "pairing-invalid").await; - return; - } + if !states.get(&peer_id).is_some_and(|state| state.paired) { drop(states); - let err = if language.is_chinese() { - "\u{8bf7}\u{8f93}\u{5165} 6 \u{4f4d}\u{914d}\u{5bf9}\u{7801}\u{3002}" - } else { - "Please send the 6-digit pairing code." - }; - self.try_send_text(&peer_id, err, "pairing-prompt").await; + self.handle_pairing_message(&peer_id, text).await; return; } + let state = states.get_mut(&peer_id).expect("paired chat exists"); + let language = current_bot_language().await; if self.runtime_fence.identity_epoch() != command_identity_epoch { return; @@ -1413,6 +1362,7 @@ impl WeixinBot { Box::pin(async move { if !msg_bot.runtime_fence.is_lifecycle_current() || msg_bot.runtime_fence.identity_epoch() != output_identity_epoch + || !super::chat_is_paired(&msg_bot.chat_states, peer_s.as_str()).await { return; } @@ -1436,6 +1386,7 @@ impl WeixinBot { .await; if !bot.runtime_fence.is_lifecycle_current() || bot.runtime_fence.identity_epoch() != output_identity_epoch + || !super::chat_is_paired(&bot.chat_states, peer.as_str()).await { return; } @@ -1482,11 +1433,9 @@ impl WeixinBot { } let mut states = self.chat_states.write().await; self.runtime_fence.reconcile_states(&mut states); - let state = states.entry(peer_id.clone()).or_insert_with(|| { - let mut state = BotChatState::new(peer_id.clone()); - state.paired = true; - state - }); + let Some(state) = states.get_mut(&peer_id).filter(|state| state.paired) else { + return; + }; if self.runtime_fence.identity_epoch() != identity_epoch { return; } @@ -1878,7 +1827,7 @@ mod tests { async fn unsupported_media_and_empty_input_never_route_partial_or_empty_turns() { let (base, mut requests, server) = mock_outbound(vec!["{}"; 3], None).await; let bot = test_bot(base).await; - bot.chat_states.write().await.clear(); + let original = serde_json::to_value(&*bot.chat_states.read().await).unwrap(); let epoch = bot.runtime_fence.identity_epoch(); for message in [ json!({"item_list":[{"type":3,"voice_item":{}},{"type":1,"text_item":{"text":"transcribe this voice"}}]}), @@ -1892,7 +1841,10 @@ mod tests { .as_str() .unwrap() .contains("Agent")); - assert!(bot.chat_states.read().await.is_empty()); + assert_eq!( + serde_json::to_value(&*bot.chat_states.read().await).unwrap(), + original + ); } server.await.unwrap(); assert!(!weixin_provider::has_unsupported_media_items( @@ -1905,7 +1857,6 @@ mod tests { let (release, gate) = tokio::sync::oneshot::channel(); let (base, mut requests, server) = mock_outbound(vec!["{}", "{}"], Some(gate)).await; let bot = test_bot(base).await; - bot.chat_states.write().await.clear(); let (stop, stopped) = tokio::sync::watch::channel(false); let sender = bot.spawn_inbound_peer("peer".into(), stopped); let epoch = bot.runtime_fence.identity_epoch(); @@ -1923,23 +1874,18 @@ mod tests { .contains("Agent")); sender .send(( - json!({"item_list":[{"type":1,"text_item":{"text":"hello"}}]}), + json!({"item_list":[{"type":1,"text_item":{"text":"/help"}}]}), epoch, )) .await .unwrap(); // The failed media reply is still in flight. The subsequent text must - // not route/create state until that first input finishes. - assert!(tokio::time::timeout(Duration::from_millis(30), async { - loop { - if bot.chat_states.read().await.contains_key("peer") { - break; - } - tokio::task::yield_now().await; - } - }) - .await - .is_err()); + // not route or answer until that first input finishes. + assert!( + tokio::time::timeout(Duration::from_millis(30), requests.recv()) + .await + .is_err() + ); release.send(()).unwrap(); tokio::time::timeout(Duration::from_secs(5), requests.recv()) .await @@ -2147,4 +2093,417 @@ mod tests { "scheduled result" ); } + + const OWNER: &str = "owner-peer"; + const STRANGER: &str = "stranger-peer"; + + /// A loopback provider that answers every call until the test ends. + /// `getupdates` polls replay `update_batches` and then stay open, like a + /// long poll with no traffic; every other call succeeds and is recorded. + async fn mock_provider( + update_batches: Vec, + ) -> ( + String, + tokio::sync::mpsc::UnboundedReceiver, + tokio::task::JoinHandle<()>, + ) { + use tokio::io::{AsyncReadExt, AsyncWriteExt}; + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let base = format!("http://{}/", listener.local_addr().unwrap()); + let (tx, rx) = tokio::sync::mpsc::unbounded_channel(); + let updates = Arc::new(std::sync::Mutex::new(VecDeque::from(update_batches))); + let task = tokio::spawn(async move { + loop { + let (mut stream, _) = listener.accept().await.unwrap(); + let tx = tx.clone(); + let updates = updates.clone(); + tokio::spawn(async move { + let mut request = Vec::new(); + let mut chunk = [0; 4096]; + let body: Value = loop { + let count = stream.read(&mut chunk).await.unwrap_or(0); + if count == 0 { + return; + } + request.extend_from_slice(&chunk[..count]); + let Some(end) = request.windows(4).position(|w| w == b"\r\n\r\n") else { + continue; + }; + let headers = String::from_utf8_lossy(&request[..end]); + let length: usize = headers + .lines() + .find_map(|line| { + let (name, value) = line.split_once(':')?; + name.eq_ignore_ascii_case("content-length") + .then(|| value.trim().parse().unwrap()) + }) + .unwrap_or(0); + if request.len() >= end + 4 + length { + break serde_json::from_slice(&request[end + 4..end + 4 + length]) + .unwrap(); + } + }; + let response = if body.get("get_updates_buf").is_some() { + let next = updates.lock().unwrap().pop_front(); + match next { + Some(batch) => batch.to_string(), + None => std::future::pending().await, + } + } else { + let _ = tx.send(body); + "{}".to_string() + }; + let _ = stream + .write_all( + format!( + "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}", + response.len(), + response + ) + .as_bytes(), + ) + .await; + }); + } + }); + (base, rx, task) + } + + /// A bot that can answer `OWNER` and `STRANGER`, with no chat paired yet. + async fn gate_bot(base_url: String) -> Arc { + let bot = Arc::new(WeixinBot::new(WeixinConfig { + ilink_token: "fixture-token".into(), + base_url, + bot_account_id: format!("gate-test-{}", uuid::Uuid::new_v4()), + })); + let mut tokens = bot.context_tokens.write().await; + tokens.insert(OWNER.into(), "owner-context".into()); + tokens.insert(STRANGER.into(), "stranger-context".into()); + drop(tokens); + bot + } + + /// A bot whose first pairing already completed with `OWNER`. + async fn connected_bot(base_url: String) -> Arc { + let bot = gate_bot(base_url).await; + bot.restore_chat_state(OWNER, super::super::test_support::paired_state(OWNER)) + .await; + bot + } + + fn text_message(text: &str) -> Value { + json!({"item_list":[{"type":1,"text_item":{"text":text}}]}) + } + + fn update(peer: &str, text: &str) -> Value { + let mut message = text_message(text); + message["message_type"] = json!(1); + message["from_user_id"] = json!(peer); + message + } + + fn updates(messages: Vec) -> Value { + json!({ "ret": 0, "msgs": messages }) + } + + /// The texts sent to `peer` since the previous call. + fn replies_to( + requests: &mut tokio::sync::mpsc::UnboundedReceiver, + peer: &str, + ) -> Vec { + let mut replies = Vec::new(); + while let Ok(request) = requests.try_recv() { + if request["msg"]["to_user_id"] == peer { + replies.push( + request["msg"]["item_list"][0]["text_item"]["text"] + .as_str() + .unwrap_or_default() + .to_string(), + ); + } + } + replies + } + + fn saved_chat_id(bot: &WeixinBot) -> Option { + bot.runtime_fence + .saved_connection("weixin") + .map(|saved| saved.chat_id) + } + + async fn pair_through_updates(bot: &WeixinBot) -> String { + let (_stop_tx, mut stop_rx) = tokio::sync::watch::channel(false); + tokio::time::timeout(Duration::from_secs(10), bot.wait_for_pairing(&mut stop_rx)) + .await + .expect("pairing must finish with the scripted updates") + .expect("pairing must succeed") + } + + #[tokio::test] + async fn unknown_peer_after_first_pairing_is_refused_and_cannot_run_a_command() { + let (base, mut requests, server) = mock_provider(vec![]).await; + let bot = connected_bot(base).await; + let epoch = bot.runtime_fence.identity_epoch(); + + bot.process_provider_message(STRANGER.into(), text_message("/help"), epoch) + .await; + + assert!( + !bot.chat_states.read().await.contains_key(STRANGER), + "a peer that never paired must not gain state" + ); + assert_eq!(replies_to(&mut requests, STRANGER).len(), 1); + assert_eq!(saved_chat_id(&bot).as_deref(), Some(OWNER)); + + bot.process_provider_message(OWNER.into(), text_message("/help"), epoch) + .await; + assert!( + !bot.chat_states.read().await[OWNER] + .last_menu_commands + .is_empty(), + "the paired peer keeps its commands" + ); + server.abort(); + } + + #[tokio::test] + async fn outbound_paths_never_create_state_or_reach_an_unpaired_peer() { + let (base, mut requests, server) = mock_provider(vec![]).await; + let bot = connected_bot(base).await; + let epoch = bot.runtime_fence.identity_epoch(); + + bot.deliver_interaction( + STRANGER.into(), + super::super::test_support::question("tool-1"), + epoch, + ) + .await; + bot.notify_files_ready( + STRANGER, + "missing-session", + None, + "[report](computer://report.pdf)", + epoch, + ) + .await; + assert!(!bot.chat_states.read().await.contains_key(STRANGER)); + assert_eq!(replies_to(&mut requests, STRANGER), Vec::::new()); + assert_eq!(saved_chat_id(&bot).as_deref(), Some(OWNER)); + + // A peer that is known but never completed pairing is treated the + // same, including by the proactive session-output channel. + let mut unpaired = BotChatState::new(STRANGER.into()); + unpaired.current_session_id = Some("session".into()); + bot.chat_states + .write() + .await + .insert(STRANGER.into(), unpaired); + bot.deliver_interaction( + STRANGER.into(), + super::super::test_support::question("tool-2"), + epoch, + ) + .await; + bot.notify_session_output("session", "scheduled result") + .await; + bot.flush_pending_outbound().await; + assert_eq!(replies_to(&mut requests, STRANGER), Vec::::new()); + assert!(bot.pending_snapshot(STRANGER).await.is_empty()); + let states = bot.chat_states.read().await; + assert!(!states[STRANGER].paired); + assert!(states[STRANGER].pending_action.is_none()); + drop(states); + + // The paired peer still receives its interaction. + bot.deliver_interaction( + OWNER.into(), + super::super::test_support::question("tool-3"), + epoch, + ) + .await; + assert_eq!(replies_to(&mut requests, OWNER).len(), 1); + server.abort(); + } + + #[tokio::test] + async fn wrong_codes_are_limited_per_peer_without_locking_the_owner_or_burning_the_code() { + use super::super::test_support::PAIRING_CODE; + let mut messages = vec![update(STRANGER, "000000"); 5]; + // The right code no longer helps a peer that used up its attempts. + messages.push(update(STRANGER, PAIRING_CODE)); + messages.push(update(OWNER, "111111")); + messages.push(update(OWNER, PAIRING_CODE)); + let (base, mut requests, server) = mock_provider(vec![updates(messages)]).await; + let bot = gate_bot(base).await; + bot.register_pairing(PAIRING_CODE).await.unwrap(); + + assert_eq!(pair_through_updates(&bot).await, OWNER); + + let states = bot.chat_states.read().await; + assert!(states.get(OWNER).is_some_and(|state| state.paired)); + assert!(!states.contains_key(STRANGER)); + drop(states); + // Four "wrong code" replies, then one lockout notice, then silence. + assert_eq!(replies_to(&mut requests, STRANGER).len(), 5); + assert_eq!(saved_chat_id(&bot).as_deref(), Some(OWNER)); + server.abort(); + } + + #[tokio::test] + async fn repeated_messages_from_an_unpaired_peer_get_a_bounded_number_of_replies() { + use super::super::test_support::PAIRING_CODE; + // While the first pairing is still pending. + let mut messages = vec![update(STRANGER, "hello"); 20]; + messages.push(update(OWNER, PAIRING_CODE)); + let (base, mut requests, server) = mock_provider(vec![updates(messages)]).await; + let bot = gate_bot(base).await; + bot.register_pairing(PAIRING_CODE).await.unwrap(); + assert_eq!(pair_through_updates(&bot).await, OWNER); + let replies = replies_to(&mut requests, STRANGER).len(); + assert!( + (1..=3).contains(&replies), + "replies while pairing: {replies}" + ); + + // After pairing, in the message loop: text, raw voice and empty input. + let epoch = bot.runtime_fence.identity_epoch(); + for index in 0..20 { + let message = match index % 3 { + 0 => text_message("hello again"), + 1 => json!({"item_list":[{"type":3,"voice_item":{}}]}), + _ => text_message(" "), + }; + bot.process_provider_message(STRANGER.into(), message, epoch) + .await; + } + let replies = replies_to(&mut requests, STRANGER).len(); + assert!( + (1..=3).contains(&replies), + "replies when connected: {replies}" + ); + assert!(!bot.chat_states.read().await.contains_key(STRANGER)); + server.abort(); + } + + #[tokio::test] + async fn code_issued_for_a_connected_bot_moves_the_connection_to_the_peer_that_presents_it() { + use super::super::test_support::PAIRING_CODE; + let (base, mut requests, server) = mock_provider(vec![]).await; + let bot = connected_bot(base).await; + let epoch = bot.runtime_fence.identity_epoch(); + bot.register_pairing(PAIRING_CODE).await.unwrap(); + + bot.process_provider_message(STRANGER.into(), text_message("111111"), epoch) + .await; + assert!(!bot.chat_states.read().await.contains_key(STRANGER)); + assert_eq!(saved_chat_id(&bot).as_deref(), Some(OWNER)); + + bot.process_provider_message(STRANGER.into(), text_message(PAIRING_CODE), epoch) + .await; + let states = bot.chat_states.read().await; + assert!(states.get(STRANGER).is_some_and(|state| state.paired)); + assert!( + !states.contains_key(OWNER), + "one connection has one chat: the previous peer is no longer paired" + ); + drop(states); + assert_eq!(saved_chat_id(&bot).as_deref(), Some(STRANGER)); + assert!( + !bot.verify_pairing_code(PAIRING_CODE).await, + "the pairing code is single use" + ); + assert!(!replies_to(&mut requests, STRANGER).is_empty()); + server.abort(); + } + + #[tokio::test] + async fn legacy_persisted_paired_peer_is_restored_without_pairing_again() { + let saved = super::super::test_support::legacy_saved_connection( + "weixin", + OWNER, + json!({ + "bot_type": "weixin", + "ilink_token": "fixture-token", + "base_url": "https://ilinkai.weixin.qq.com", + "bot_account_id": "fixture-bot" + }), + ); + let (base, mut requests, server) = mock_provider(vec![]).await; + let bot = gate_bot(base).await; + let epoch = bot.runtime_fence.identity_epoch(); + + bot.restore_chat_state(OWNER, saved.chat_state.clone()) + .await; + bot.process_provider_message(OWNER.into(), text_message("/help"), epoch) + .await; + + assert_eq!(replies_to(&mut requests, OWNER).len(), 1); + assert!( + !bot.chat_states.read().await[OWNER] + .last_menu_commands + .is_empty(), + "the restored peer reaches the command router without a pairing prompt" + ); + let resaved = bot + .runtime_fence + .saved_connection("weixin") + .expect("restored connection is saved"); + assert_eq!(resaved.chat_id, OWNER); + assert!(resaved.chat_state.paired); + // The stored shape is unchanged: an older build reads it back. + let stored = serde_json::to_value(&resaved.chat_state).unwrap(); + let legacy = serde_json::to_value(&saved.chat_state).unwrap(); + assert_eq!(stored, legacy); + assert_eq!(stored["paired"], json!(true)); + server.abort(); + } + + #[tokio::test] + async fn retired_or_reidentified_bot_neither_answers_nor_delivers() { + let (base, mut requests, server) = mock_provider(vec![]).await; + let bot = connected_bot(base).await; + let epoch = bot.runtime_fence.identity_epoch(); + + // An account change invalidates work that started before it. + bot.runtime_fence + .account_identity_epoch + .fetch_add(1, std::sync::atomic::Ordering::AcqRel); + bot.process_provider_message(OWNER.into(), text_message("/help"), epoch) + .await; + bot.process_provider_message(STRANGER.into(), text_message("/help"), epoch) + .await; + bot.deliver_interaction( + OWNER.into(), + super::super::test_support::question("tool-1"), + epoch, + ) + .await; + bot.notify_files_ready( + OWNER, + "missing-session", + None, + "[report](computer://report.pdf)", + epoch, + ) + .await; + + // A replaced instance stays silent for paired and unpaired peers alike. + let epoch = bot.runtime_fence.identity_epoch(); + bot.runtime_fence.slot.advance(); + bot.process_provider_message(OWNER.into(), text_message("/help"), epoch) + .await; + bot.process_provider_message(STRANGER.into(), text_message("/help"), epoch) + .await; + bot.deliver_interaction( + OWNER.into(), + super::super::test_support::question("tool-2"), + epoch, + ) + .await; + + assert!(requests.try_recv().is_err()); + assert!(!bot.chat_states.read().await.contains_key(STRANGER)); + assert_eq!(saved_chat_id(&bot).as_deref(), Some(OWNER)); + server.abort(); + } }