Skip to content

armgit / avibe

Public Imported from GitHub
0

Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.

fix(telegram): guard callbacks and foreign bot commands

cyh47e76f3d6f1f
diff --git a/modules/agents/native_sessions/__init__.py b/modules/agents/native_sessions/__init__.py
index 602c61e56..2ee09d0f8 100644
--- a/modules/agents/native_sessions/__init__.py
+++ b/modules/agents/native_sessions/__init__.py
@@ -1,9 +1,11 @@
"""Backend-native session catalog helpers for the resume picker."""
from .display import format_display_summary, format_display_time
+from .service import AgentNativeSessionService
from .types import NativeResumeSession
__all__ = [
+ "AgentNativeSessionService",
"NativeResumeSession",
"format_display_summary",
"format_display_time",
diff --git a/modules/agents/native_sessions/service.py b/modules/agents/native_sessions/service.py
index bacd9ec6d..223c5beca 100644
--- a/modules/agents/native_sessions/service.py
+++ b/modules/agents/native_sessions/service.py
@@ -5,6 +5,7 @@ import logging
from collections import Counter
from .base import NativeSessionProvider
+from .display import format_display_summary, format_display_time
from .providers import DEFAULT_PROVIDER_SPECS, NativeSessionProviderSpec
from .types import NativeResumeSession
@@ -12,6 +13,9 @@ logger = logging.getLogger(__name__)
class AgentNativeSessionService:
+ format_display_summary = staticmethod(format_display_summary)
+ format_display_time = staticmethod(format_display_time)
+
def __init__(
self,
providers: list[NativeSessionProvider] | None = None,
diff --git a/modules/im/telegram.py b/modules/im/telegram.py
index f80b2b1b5..f23746f5f 100644
--- a/modules/im/telegram.py
+++ b/modules/im/telegram.py
@@ -173,6 +173,8 @@ class TelegramBot(BaseIMClient):
text = message.get("text") or message.get("caption") or ""
text = self._normalize_command_text(text)
+ if self._is_command_for_other_bot(text):
+ return
if await self._consume_cwd_prompt(context, text):
return
@@ -336,6 +338,21 @@ class TelegramBot(BaseIMClient):
"callback_query": payload,
}
callback_data = str(payload.get("data", ""))
+ auth_result = self.check_authorization(
+ user_id=context.user_id,
+ channel_id=context.channel_id,
+ is_dm=bool(context.platform_specific.get("is_dm")),
+ action=self._resolve_callback_action(callback_data),
+ settings_manager=self.settings_manager,
+ )
+ if not auth_result.allowed:
+ denial_text = self.build_auth_denial_text(auth_result.denial, context.channel_id)
+ await self.answer_callback(
+ callback_id,
+ denial_text,
+ show_alert=bool(denial_text),
+ )
+ return
if await self._handle_internal_callback(context, callback_data):
await self.answer_callback(callback_id)
return
@@ -436,12 +453,38 @@ class TelegramBot(BaseIMClient):
if not stripped.startswith("/"):
return stripped
head, *tail = stripped.split(maxsplit=1)
- if "@" in head and self._bot_user and self._bot_user.get("username"):
- command, _, username = head.partition("@")
- if username.lower() == str(self._bot_user.get("username")).lower():
- head = command
+ command, username = self._split_command_target(head)
+ bot_username = str((self._bot_user or {}).get("username") or "")
+ if username and bot_username and username.lower() == bot_username.lower():
+ head = command
return " ".join([head, *tail]).strip()
+ def _split_command_target(self, head: str) -> tuple[str, str]:
+ command, sep, username = str(head or "").partition("@")
+ if not sep:
+ return command, ""
+ return command, username
+
+ def _is_command_for_other_bot(self, text: str) -> bool:
+ stripped = (text or "").strip()
+ if not stripped.startswith("/"):
+ return False
+ head = stripped.split(maxsplit=1)[0]
+ _, username = self._split_command_target(head)
+ if not username:
+ return False
+ bot_username = str((self._bot_user or {}).get("username") or "")
+ return bool(bot_username) and username.lower() != bot_username.lower()
+
+ def _resolve_callback_action(self, callback_data: str) -> str:
+ if callback_data.startswith("tg_cwd:"):
+ return "cmd_change_cwd"
+ if callback_data.startswith("tg_route:"):
+ return "cmd_routing"
+ if callback_data.startswith("toggle_msg_") or callback_data in {"open_settings_modal", "info_msg_types"}:
+ return "cmd_settings"
+ return callback_data
+
def _interaction_scope_key(self, context: MessageContext) -> str:
payload = context.platform_specific or {}
is_dm = bool(payload.get("is_dm"))
@@ -482,7 +525,12 @@ class TelegramBot(BaseIMClient):
def _is_explicitly_addressed(self, message: dict[str, Any], text: str) -> bool:
if text.startswith("/"):
- return True
+ head = text.split(maxsplit=1)[0]
+ _, username = self._split_command_target(head)
+ if not username:
+ return True
+ bot_username = str((self._bot_user or {}).get("username") or "")
+ return bool(bot_username) and username.lower() == bot_username.lower()
reply_to = message.get("reply_to_message") or {}
reply_from = reply_to.get("from") or {}
if self._bot_user and str(reply_from.get("id")) == str(self._bot_user.get("id")):
diff --git a/tests/test_telegram_bot.py b/tests/test_telegram_bot.py
index a53f92463..6eb00fbcc 100644
--- a/tests/test_telegram_bot.py
+++ b/tests/test_telegram_bot.py
@@ -95,6 +95,27 @@ def test_build_message_context_records_discovered_chat(tmp_path, monkeypatch) ->
DiscoveredChatsStore.reset_instance()
+def test_handle_message_ignores_foreign_bot_command() -> None:
+ bot = TelegramBot(TelegramConfig(bot_token="123456:test-token"))
+ bot._bot_user = {"id": 1, "username": "vibe_remote_bot"}
+ bot.on_message_callback = AsyncMock()
+ bot.on_command_callbacks["start"] = AsyncMock()
+
+ asyncio.run(
+ bot._handle_message(
+ {
+ "message_id": 77,
+ "chat": {"id": -100123, "type": "supergroup", "title": "Core Forum"},
+ "from": {"id": 42},
+ "text": "/start@other_bot hello",
+ }
+ )
+ )
+
+ bot.on_command_callbacks["start"].assert_not_awaited()
+ bot.on_message_callback.assert_not_awaited()
+
+
def test_pending_cwd_prompt_consumes_next_plain_message() -> None:
bot = TelegramBot(TelegramConfig(bot_token="123456:test-token"))
context = MessageContext(
@@ -285,3 +306,28 @@ def test_question_callback_finalizes_with_synthetic_modal_payload() -> None:
forwarded = bot.on_callback_query_callback.await_args.args[1]
assert forwarded.startswith("claude_question:modal:")
assert '"Claude"' in forwarded
+
+
+def test_handle_callback_query_denies_unauthorized_protected_action() -> None:
+ bot = TelegramBot(TelegramConfig(bot_token="123456:test-token"))
+ bot.check_authorization = lambda **kwargs: SimpleNamespace(allowed=False, denial="not_admin")
+ bot.build_auth_denial_text = lambda denial, channel_id=None: "Admin only"
+ bot.on_callback_query_callback = AsyncMock()
+
+ with patch.object(bot, "answer_callback", new=AsyncMock(return_value=True)) as answer_mock:
+ asyncio.run(
+ bot._handle_callback_query(
+ {
+ "id": "cb-1",
+ "data": "cmd_settings",
+ "from": {"id": 42},
+ "message": {
+ "message_id": 99,
+ "chat": {"id": -100123, "type": "supergroup", "title": "Core Forum"},
+ },
+ }
+ )
+ )
+
+ answer_mock.assert_awaited_once_with("cb-1", "Admin only", show_alert=True)
+ bot.on_callback_query_callback.assert_not_awaited()