fix(channels): reject unauthorized inbound before side effects

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
Xubin Ren
2026-05-05 23:16:36 +08:00
committed by Xubin Ren
co-authored by Cursor
parent 1813fc5021
commit 4db50f2e32
14 changed files with 273 additions and 53 deletions
+6
View File
@@ -407,6 +407,12 @@ class EmailChannel(BaseChannel):
self._remember_processed_uid(uid, dedupe, cycle_uids)
continue
if not self.is_allowed(sender):
self._remember_processed_uid(uid, dedupe, cycle_uids)
if mark_seen:
client.store(imap_id, "+FLAGS", "\\Seen")
continue
subject = self._decode_header_value(parsed.get("Subject", ""))
date_value = parsed.get("Date", "")
message_id = parsed.get("Message-ID", "").strip()
+12 -8
View File
@@ -1644,15 +1644,7 @@ class FeishuChannel(BaseChannel):
logger.debug("Feishu raw message: {}", message.content)
logger.debug("Feishu mentions: {}", getattr(message, "mentions", None))
# Deduplication check
message_id = message.message_id
if message_id in self._processed_message_ids:
return
self._processed_message_ids[message_id] = None
# Trim cache
while len(self._processed_message_ids) > 1000:
self._processed_message_ids.popitem(last=False)
# Skip bot messages
if sender.sender_type == "bot":
@@ -1663,10 +1655,22 @@ class FeishuChannel(BaseChannel):
chat_type = message.chat_type
msg_type = message.message_type
if not self.is_allowed(sender_id):
return
if chat_type == "group" and not self._is_group_message_for_bot(message):
logger.debug("Feishu: skipping group message (not mentioned)")
return
# Deduplication check
if message_id in self._processed_message_ids:
return
self._processed_message_ids[message_id] = None
# Trim cache
while len(self._processed_message_ids) > 1000:
self._processed_message_ids.popitem(last=False)
# Add reaction (non-blocking — tracked background task)
task = asyncio.create_task(
self._add_reaction(message_id, self.config.react_emoji)
+10 -6
View File
@@ -474,24 +474,28 @@ class QQChannel(BaseChannel):
async def _on_message(self, data: C2CMessage | GroupMessage, is_group: bool = False) -> None:
"""Parse inbound message, download attachments, and publish to the bus."""
try:
if data.id in self._processed_ids:
return
self._processed_ids.append(data.id)
if is_group:
chat_id = data.group_openid
user_id = data.author.member_openid
self._chat_type_cache[chat_id] = "group"
chat_type = "group"
else:
chat_id = str(
getattr(data.author, "id", None)
or getattr(data.author, "user_openid", "unknown")
)
user_id = chat_id
self._chat_type_cache[chat_id] = "c2c"
chat_type = "c2c"
content = (data.content or "").strip()
if not self.is_allowed(user_id):
return
if data.id in self._processed_ids:
return
self._processed_ids.append(data.id)
self._chat_type_cache[chat_id] = chat_type
# the data used by tests don't contain attachments property
# so we use getattr with a default of [] to avoid AttributeError in tests
attachments = getattr(data, "attachments", None) or []
+6 -1
View File
@@ -993,6 +993,9 @@ class TelegramChannel(BaseChannel):
return
message = update.message
user = update.effective_user
sender_id = self._sender_id(user)
if not self.is_allowed(sender_id):
return
self._remember_thread_context(message)
# Strip @bot_username suffix if present
@@ -1004,7 +1007,7 @@ class TelegramChannel(BaseChannel):
content = self._normalize_telegram_command(content)
await self._handle_message(
sender_id=self._sender_id(user),
sender_id=sender_id,
chat_id=str(message.chat_id),
content=content,
metadata=self._build_message_metadata(message, user),
@@ -1264,6 +1267,8 @@ class TelegramChannel(BaseChannel):
if not chat_id:
logger.warning("Callback query without chat_id")
return
if not self.is_allowed(sender_id):
return
button_label = query.data or ""
await query.answer()
if query.message:
+12 -7
View File
@@ -11,13 +11,13 @@ from pathlib import Path
from typing import Any
from loguru import logger
from pydantic import Field
from nanobot.bus.events import OutboundMessage
from nanobot.bus.queue import MessageBus
from nanobot.channels.base import BaseChannel
from nanobot.config.paths import get_media_dir
from nanobot.config.schema import Base
from pydantic import Field
WECOM_AVAILABLE = importlib.util.find_spec("wecom_aibot_sdk") is not None
@@ -204,6 +204,9 @@ class WecomChannel(BaseChannel):
chat_id = body.get("chatid", "") if isinstance(body, dict) else ""
if chat_id and not self.is_allowed(chat_id):
return
if chat_id and self.config.welcome_message:
await self._client.reply_welcome(frame, {
"msgtype": "text",
@@ -233,6 +236,12 @@ class WecomChannel(BaseChannel):
if not msg_id:
msg_id = f"{body.get('chatid', '')}_{body.get('sendertime', '')}"
# Extract sender info from "from" field (SDK format)
from_info = body.get("from", {})
sender_id = from_info.get("userid", "unknown") if isinstance(from_info, dict) else "unknown"
if not self.is_allowed(sender_id):
return
# Deduplication check
if msg_id in self._processed_message_ids:
return
@@ -242,10 +251,6 @@ class WecomChannel(BaseChannel):
while len(self._processed_message_ids) > 1000:
self._processed_message_ids.popitem(last=False)
# Extract sender info from "from" field (SDK format)
from_info = body.get("from", {})
sender_id = from_info.get("userid", "unknown") if isinstance(from_info, dict) else "unknown"
# For single chat, chatid is the sender's userid
# For group chat, chatid is provided in body
chat_type = body.get("chattype", "single")
@@ -424,9 +429,9 @@ class WecomChannel(BaseChannel):
# MD5 is used for file integrity only, not cryptographic security
md5_hash = hashlib.md5(data).hexdigest()
CHUNK_SIZE = 512 * 1024 # 512 KB raw (before base64)
chunk_size = 512 * 1024 # 512 KB raw (before base64)
mv = memoryview(data)
chunk_list = [bytes(mv[i : i + CHUNK_SIZE]) for i in range(0, file_size, CHUNK_SIZE)]
chunk_list = [bytes(mv[i : i + chunk_size]) for i in range(0, file_size, chunk_size)]
n_chunks = len(chunk_list)
del mv, data
+9 -5
View File
@@ -588,20 +588,24 @@ class WeixinChannel(BaseChannel):
if msg.get("message_type") == MESSAGE_TYPE_BOT:
return
# Deduplication by message_id
msg_id = str(msg.get("message_id", "") or msg.get("seq", ""))
if not msg_id:
msg_id = f"{msg.get('from_user_id', '')}_{msg.get('create_time_ms', '')}"
from_user_id = msg.get("from_user_id", "") or ""
if not from_user_id:
return
if not self.is_allowed(from_user_id):
return
# Deduplication by message_id
if msg_id in self._processed_ids:
return
self._processed_ids[msg_id] = None
while len(self._processed_ids) > 1000:
self._processed_ids.popitem(last=False)
from_user_id = msg.get("from_user_id", "") or ""
if not from_user_id:
return
# Cache context_token (required for all replies — inbound.ts:23-27)
ctx_token = msg.get("context_token", "")
if ctx_token:
+12 -9
View File
@@ -8,8 +8,8 @@ import os
import secrets
import shutil
import subprocess
from contextlib import suppress
from collections import OrderedDict
from contextlib import suppress
from pathlib import Path
from typing import Any, Literal
@@ -214,13 +214,6 @@ class WhatsAppChannel(BaseChannel):
content = data.get("content", "")
message_id = data.get("id", "")
if message_id:
if message_id in self._processed_message_ids:
return
self._processed_message_ids[message_id] = None
while len(self._processed_message_ids) > 1000:
self._processed_message_ids.popitem(last=False)
# Extract just the phone number or lid as chat_id
is_group = data.get("isGroup", False)
was_mentioned = data.get("wasMentioned", False)
@@ -246,9 +239,19 @@ class WhatsAppChannel(BaseChannel):
elif extracted and not phone_id:
phone_id = extracted # best guess for bare values
sender_id = phone_id or self._lid_to_phone.get(lid_id, "") or lid_id or id_a or id_b
if not self.is_allowed(sender_id):
return
if message_id:
if message_id in self._processed_message_ids:
return
self._processed_message_ids[message_id] = None
while len(self._processed_message_ids) > 1000:
self._processed_message_ids.popitem(last=False)
if phone_id and lid_id:
self._lid_to_phone[lid_id] = phone_id
sender_id = phone_id or self._lid_to_phone.get(lid_id, "") or lid_id or id_a or id_b
logger.info("Sender phone={} lid={} → sender_id={}", phone_id or "(empty)", lid_id or "(empty)", sender_id)