Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Binary file modified locale/ja_JP/LC_MESSAGES/BetterForward.mo
Binary file not shown.
4 changes: 4 additions & 0 deletions locale/ja_JP/LC_MESSAGES/BetterForward.po
Original file line number Diff line number Diff line change
Expand Up @@ -884,6 +884,10 @@ msgstr "このスレッドを削除"
msgid "User banned"
msgstr "ユーザーを禁止された"

#: src/utils/helpers.py
msgid "You have been banned."
msgstr "あなたは禁止されています。"

#: src/handlers/command_handler.py:128 src/handlers/command_handler.py:162
#: src/handlers/command_handler.py:165
msgid "User unbanned"
Expand Down
Binary file modified locale/zh_CN/LC_MESSAGES/BetterForward.mo
Binary file not shown.
4 changes: 4 additions & 0 deletions locale/zh_CN/LC_MESSAGES/BetterForward.po
Original file line number Diff line number Diff line change
Expand Up @@ -872,6 +872,10 @@ msgstr "删除该会话"
msgid "User banned"
msgstr "用户已被封禁"

#: src/utils/helpers.py
msgid "You have been banned."
msgstr "你已被封禁。"

#: src/handlers/command_handler.py:128 src/handlers/command_handler.py:162
#: src/handlers/command_handler.py:165
msgid "User unbanned"
Expand Down
15 changes: 15 additions & 0 deletions src/handlers/callback_handler.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
from telebot import types

from src.config import logger, _
from src.utils.helpers import blocked_user_notice, is_user_blocked


class CallbackHandler:
Expand Down Expand Up @@ -72,6 +73,8 @@ def _handle_verify_button(self, call: types.CallbackQuery, data: dict):
show_alert=True,
)
return
if self._reject_banned_verification(call, user_id):
return

if not self.captcha_manager.is_current_callback(user_id, "button", call.message.message_id):
self.bot.answer_callback_query(
Expand Down Expand Up @@ -99,6 +102,8 @@ def _handle_verify_emoji(self, call: types.CallbackQuery, data: dict):
show_alert=True,
)
return
if self._reject_banned_verification(call, user_id):
return
if not self.captcha_manager.is_current_callback(user_id, "emoji", call.message.message_id):
self.bot.answer_callback_query(
call.id, _("This verification has expired. Send a message to request a new challenge."),
Expand All @@ -119,6 +124,16 @@ def _handle_verify_emoji(self, call: types.CallbackQuery, data: dict):
self.bot.send_message(user_id, _("Verification successful, you can now send messages"))
self.bot.delete_message(call.message.chat.id, call.message.message_id)

def _reject_banned_verification(self, call: types.CallbackQuery, user_id: int) -> bool:
"""Refuse captcha completion for banned users. Returns True when rejected."""
with sqlite3.connect(self.db_path) as db:
if not is_user_blocked(db, user_id):
return False
self.captcha_manager.clear_pending(user_id)
self.bot.answer_callback_query(
call.id, blocked_user_notice(self.captcha_manager.cache), show_alert=True)
return True

def _handle_admin_callback(self, call: types.CallbackQuery, action: str, data: dict):
"""Handle admin callbacks."""
markup = types.InlineKeyboardMarkup()
Expand Down
13 changes: 12 additions & 1 deletion src/handlers/command_handler.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,14 @@

from src.config import logger, _
from src.utils.captcha import VERIFICATION_DAYS_SETTING, verification_days
from src.utils.helpers import build_user_info_pin_text, parse_start_payload, send_and_pin_user_info, to_html
from src.utils.helpers import (
blocked_user_notice,
build_user_info_pin_text,
is_user_blocked,
parse_start_payload,
send_and_pin_user_info,
to_html,
)
from src.utils.message_split import split_caption, split_html_text
from src.utils.message_permissions import classify_message_permissions
from src.utils.stats import get_summary, get_user_stats
Expand Down Expand Up @@ -128,6 +135,10 @@ def help_command(self, message: Message, menu_callback):
menu_callback(message)
else:
if getattr(message.chat, "type", None) == "private":
with sqlite3.connect(self.db_path) as db:
if is_user_blocked(db, message.from_user.id):
self.bot.send_message(message.chat.id, blocked_user_notice(self.cache))
return
self._save_start_tag(message)
default_message = self._get_setting('default_message')
if default_message is None:
Expand Down
68 changes: 38 additions & 30 deletions src/handlers/message_handler.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,14 @@
from src.config import logger, _
from src.utils.captcha import parse_captcha_config, pick_captcha_type
from src.utils.db_helper import get_db_connection
from src.utils.helpers import build_user_info_pin_text, escape_markdown, send_and_pin_user_info, to_html
from src.utils.helpers import (
blocked_user_notice,
build_user_info_pin_text,
escape_markdown,
is_user_blocked,
send_and_pin_user_info,
to_html,
)
from src.utils.message_permissions import classify_message_permissions
from src.utils.message_split import split_caption, split_html_text
from src.utils.stats import record_incoming, record_outgoing
Expand Down Expand Up @@ -77,42 +84,17 @@ def _handle_user_message(self, message: Message, msg_text: str, msg_caption: str
_("Received message from {}, content: {}, type: {}").format(
message.from_user.id, message.text, message.content_type))

# Ban first: never start or complete captcha / TGuard for blocked users.
if self._reject_blocked_user(message, cursor, start_time):
return

# Captcha handler
if not self._check_captcha(message, cursor, db):
processing_time = (time.time() - start_time) * 1000
logger.info(_("Message from user {} blocked by captcha ({:.2f}ms)").format(
message.from_user.id, processing_time))
return

# Check if the user is blocked
is_blocked = cursor.execute("SELECT 1 FROM blocked_users WHERE user_id = ? LIMIT 1",
(message.from_user.id,)).fetchone() is not None

if is_blocked:
# Update user info in blocked_users table
cursor.execute(
"UPDATE blocked_users SET username = ?, first_name = ?, last_name = ? WHERE user_id = ?",
(message.from_user.username, message.from_user.first_name,
message.from_user.last_name, message.from_user.id)
)

processing_time = (time.time() - start_time) * 1000
logger.info(_("Message from blocked user {} rejected ({:.2f}ms)").format(
message.from_user.id, processing_time))

# Send auto-reply if enabled
if self.cache.get("setting_blocked_user_reply_enabled") == "enable":
reply_message = self.cache.get("setting_blocked_user_reply_message")
if reply_message:
try:
self.bot.send_message(message.chat.id, reply_message)
logger.info(_("Sent auto-reply to blocked user {}").format(message.from_user.id))
except Exception as e:
logger.error(_("Failed to send auto-reply to blocked user {}: {}").format(
message.from_user.id, str(e)))

return

denied_permissions = self._get_denied_permissions(message)
if denied_permissions and self._handle_permission_restriction(message, denied_permissions):
processing_time = (time.time() - start_time) * 1000
Expand Down Expand Up @@ -280,13 +262,39 @@ def _handle_permission_restriction(self, message: Message, denied_permissions: l

return True

def _reject_blocked_user(self, message: Message, cursor, start_time: float) -> bool:
"""Notify and stop when the sender is banned. Returns True if rejected."""
if not is_user_blocked(cursor, message.from_user.id):
return False

cursor.execute(
"UPDATE blocked_users SET username = ?, first_name = ?, last_name = ? WHERE user_id = ?",
(message.from_user.username, message.from_user.first_name,
message.from_user.last_name, message.from_user.id)
)

processing_time = (time.time() - start_time) * 1000
logger.info(_("Message from blocked user {} rejected ({:.2f}ms)").format(
message.from_user.id, processing_time))

try:
self.bot.send_message(message.chat.id, blocked_user_notice(self.cache))
logger.info(_("Sent auto-reply to blocked user {}").format(message.from_user.id))
except Exception as e:
logger.error(_("Failed to send auto-reply to blocked user {}: {}").format(
message.from_user.id, str(e)))
return True

def _check_captcha(self, message: Message, cursor, db) -> bool:
"""Check and handle captcha verification."""
config = parse_captcha_config(self.cache.get("setting_captcha"))
if not config.get("methods"):
return True

user_id = message.from_user.id
if is_user_blocked(cursor, user_id):
return False

pending = self.captcha_manager.get_pending(user_id)
if pending:
pending_type = pending.get("type")
Expand Down
19 changes: 19 additions & 0 deletions src/utils/helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,25 @@
START_PAYLOAD_RE = re.compile(r'^[A-Za-z0-9_-]{1,64}$')


def is_user_blocked(cursor, user_id: int) -> bool:
"""Return True when the user is in blocked_users."""
return cursor.execute(
"SELECT 1 FROM blocked_users WHERE user_id = ? LIMIT 1", (user_id,)
).fetchone() is not None


def blocked_user_notice(cache) -> str:
"""Message shown when a banned user contacts the bot.

A configured blocked-user auto-reply overrides the default notice.
"""
if cache.get("setting_blocked_user_reply_enabled") == "enable":
reply = cache.get("setting_blocked_user_reply_message")
if reply:
return reply
return _("You have been banned.")


def to_html(text: str | None, entities) -> str | None:
"""Render message text/caption with its entities as Telegram HTML."""
if text is None:
Expand Down
86 changes: 86 additions & 0 deletions tests/test_captcha.py
Original file line number Diff line number Diff line change
Expand Up @@ -253,3 +253,89 @@ def test_random_selection_excludes_unconfigured_methods(env, monkeypatch):
("button", ["button"]), ("tguard", ["tguard"])])
def test_legacy_captcha_settings_remain_supported(legacy, methods):
assert parse_captcha_config(legacy)["methods"] == methods


def _sent_texts(bot):
texts = []
for call in bot.send_message.call_args_list:
if len(call.args) > 1:
texts.append(call.args[1])
elif "text" in call.kwargs:
texts.append(call.kwargs["text"])
return texts


def test_banned_user_does_not_start_verification(env, monkeypatch):
env.db.execute("INSERT INTO blocked_users (user_id) VALUES (?)", (USER_ID,))
env.db.commit()
env.cache.set("setting_captcha", json.dumps({"methods": ["tguard"]}))
env.cache.set("setting_tguard_api_url", "https://example.com")
env.cache.set("setting_tguard_api_key", "test")
client = MagicMock()
factory = MagicMock()
factory.return_value.__enter__.return_value = client
monkeypatch.setattr("src.utils.captcha.httpx.Client", factory)

generate = MagicMock(wraps=env.captcha.generate_captcha)
monkeypatch.setattr(env.captcha, "generate_captcha", generate)

env.handler.handle_message(make_message(chat_id=USER_ID, user_id=USER_ID, text="hello"))

client.post.assert_not_called()
generate.assert_not_called()
assert env.captcha.get_pending(USER_ID) is None
assert "You have been banned." in _sent_texts(env.bot)
assert not env.captcha.is_user_verified(USER_ID, env.db)


def test_banned_user_receives_custom_reply_instead_of_captcha(env):
env.db.execute("INSERT INTO blocked_users (user_id) VALUES (?)", (USER_ID,))
env.db.commit()
env.cache.set("setting_captcha", json.dumps({"methods": ["math"]}))
env.cache.set("setting_blocked_user_reply_enabled", "enable")
env.cache.set("setting_blocked_user_reply_message", "Stay out")

env.handler.handle_message(make_message(chat_id=USER_ID, user_id=USER_ID, text="hello"))

assert env.captcha.get_pending(USER_ID) is None
assert "Stay out" in _sent_texts(env.bot)
assert not any("Captcha is enabled" in str(text) for text in _sent_texts(env.bot))


def test_banned_user_cannot_complete_callback_verification(env):
env.captcha.generate_captcha(USER_ID, "button")
env.db.execute("INSERT INTO blocked_users (user_id) VALUES (?)", (USER_ID,))
env.db.commit()
env.bot.reset_mock()

click(env, "verify_button")

assert not env.captcha.is_user_verified(USER_ID, env.db)
assert env.captcha.get_pending(USER_ID) is None
assert env.bot.answer_callback_query.call_args.kwargs["show_alert"]
assert env.bot.answer_callback_query.call_args.args[1] == "You have been banned."
env.bot.send_message.assert_not_called()


def test_banned_user_check_captcha_does_not_generate(env, monkeypatch):
env.db.execute("INSERT INTO blocked_users (user_id) VALUES (?)", (USER_ID,))
env.db.commit()
generate = MagicMock()
monkeypatch.setattr(env.captcha, "generate_captcha", generate)
assert check_message(env) is False
generate.assert_not_called()


def test_banned_user_start_gets_notice_not_welcome(env):
env.db.execute("INSERT INTO blocked_users (user_id) VALUES (?)", (USER_ID,))
env.db.commit()
handler = CommandHandler(env.bot, GROUP_ID, env.db_path, env.cache, None, env.captcha)
handler.help_command(make_message(chat_id=USER_ID, user_id=USER_ID, text="/start"), MagicMock())
texts = _sent_texts(env.bot)
assert texts == ["You have been banned."]


def test_non_banned_user_still_starts_verification(env):
assert check_message(env) is False
assert env.captcha.get_pending(USER_ID)["type"] == "math"
assert any("Captcha is enabled" in str(text) for text in _sent_texts(env.bot))