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.

security(bind): harden bind code authentication (#780)

Call White2db0ec680029
diff --git a/config/v2_settings.py b/config/v2_settings.py
index 7461cef3b..4b7b3c5a5 100644
--- a/config/v2_settings.py
+++ b/config/v2_settings.py
@@ -1,5 +1,6 @@
import json
import logging
+import hmac
import secrets
import string
import threading
@@ -22,8 +23,9 @@ SCOPED_KEY_SEP = "::"
# Bind code prefix and length
_BIND_CODE_PREFIX = "vr-"
-_BIND_CODE_RANDOM_LENGTH = 6
-_BIND_CODE_ALPHABET = string.ascii_lowercase + string.digits
+_BIND_CODE_RANDOM_LENGTH = 10
+_BIND_CODE_ALPHABET = string.ascii_letters + string.digits
+_MAX_ACTIVE_BIND_CODES = 10
def normalize_show_message_types(show_message_types: Optional[List[str]]) -> List[str]:
@@ -33,7 +35,7 @@ def normalize_show_message_types(show_message_types: Optional[List[str]]) -> Lis
def _generate_bind_code() -> str:
- """Generate a random bind code like 'vr-a3x9k2'."""
+ """Generate a random bind code like 'vr-a3X9k2LmN'."""
random_part = "".join(secrets.choice(_BIND_CODE_ALPHABET) for _ in range(_BIND_CODE_RANDOM_LENGTH))
return f"{_BIND_CODE_PREFIX}{random_part}"
@@ -43,6 +45,30 @@ def _now_iso() -> str:
return datetime.now(timezone.utc).isoformat()
+def _parse_bind_code_expiry(bind_code: "BindCode") -> Optional[datetime]:
+ if not bind_code.expires_at:
+ return None
+ try:
+ expires = datetime.fromisoformat(bind_code.expires_at)
+ except (ValueError, TypeError):
+ logger.warning("Bind code has unparseable expires_at: %s", bind_code.expires_at)
+ return datetime.min.replace(tzinfo=timezone.utc)
+ if expires.hour == 0 and expires.minute == 0 and expires.second == 0 and "T" not in bind_code.expires_at:
+ expires = expires.replace(hour=23, minute=59, second=59)
+ if expires.tzinfo is None:
+ expires = expires.replace(tzinfo=timezone.utc)
+ return expires
+
+
+def _is_bind_code_valid(bind_code: "BindCode", *, now: Optional[datetime] = None) -> bool:
+ if not bind_code.is_active:
+ return False
+ expires = _parse_bind_code_expiry(bind_code)
+ if expires is not None and (now or datetime.now(timezone.utc)) > expires:
+ return False
+ return True
+
+
def _make_scoped_key(platform: str, item_id: str) -> str:
return f"{platform}{SCOPED_KEY_SEP}{item_id}"
@@ -720,42 +746,39 @@ class SettingsStore:
def create_bind_code(self, code_type: str = "one_time", expires_at: Optional[str] = None) -> BindCode:
"""Create a new bind code."""
- code = _generate_bind_code()
- bc = BindCode(
- code=code,
- type=code_type,
- created_at=_now_iso(),
- expires_at=expires_at if code_type == "expiring" else None,
- is_active=True,
- )
- self.settings.bind_codes.append(bc)
- self.save()
- return bc
+ with self._bind_lock:
+ self.maybe_reload()
+ now = datetime.now(timezone.utc)
+ active_count = sum(1 for bc in self.settings.bind_codes if _is_bind_code_valid(bc, now=now))
+ if active_count >= _MAX_ACTIVE_BIND_CODES:
+ raise ValueError(f"active bind code limit reached ({_MAX_ACTIVE_BIND_CODES})")
+
+ existing_codes = [bc.code for bc in self.settings.bind_codes]
+ code = _generate_bind_code()
+ while any(hmac.compare_digest(candidate, code) for candidate in existing_codes):
+ code = _generate_bind_code()
+
+ bc = BindCode(
+ code=code,
+ type=code_type,
+ created_at=_now_iso(),
+ expires_at=expires_at if code_type == "expiring" else None,
+ is_active=True,
+ )
+ self.settings.bind_codes.append(bc)
+ self.save()
+ return bc
def validate_bind_code(self, code: str) -> Optional[BindCode]:
"""Validate a bind code. Returns the BindCode if valid, None otherwise."""
+ candidate = str(code or "")
+ matched: Optional[BindCode] = None
for bc in self.settings.bind_codes:
- if bc.code != code:
- continue
- if not bc.is_active:
- return None
- if bc.type == "expiring" and bc.expires_at:
- try:
- expires = datetime.fromisoformat(bc.expires_at)
- # If only a date was provided (no time component), treat as end-of-day
- if expires.hour == 0 and expires.minute == 0 and expires.second == 0 and "T" not in bc.expires_at:
- expires = expires.replace(hour=23, minute=59, second=59)
- # Ensure timezone-aware comparison
- if expires.tzinfo is None:
- expires = expires.replace(tzinfo=timezone.utc)
- if datetime.now(timezone.utc) > expires:
- return None
- except (ValueError, TypeError):
- # Fail closed: reject codes with unparseable expiration
- logger.warning("Bind code %s has unparseable expires_at: %s", code, bc.expires_at)
- return None
- return bc
- return None
+ if hmac.compare_digest(str(bc.code or ""), candidate):
+ matched = matched or bc
+ if matched is None or not _is_bind_code_valid(matched):
+ return None
+ return matched
def use_bind_code(self, code: str, user_id: str) -> bool:
"""Mark a bind code as used by a user. Returns True on success."""
@@ -770,8 +793,9 @@ class SettingsStore:
def deactivate_bind_code(self, code: str) -> bool:
"""Deactivate a bind code. Returns True if found and deactivated."""
+ candidate = str(code or "")
for bc in self.settings.bind_codes:
- if bc.code == code:
+ if hmac.compare_digest(str(bc.code or ""), candidate):
bc.is_active = False
self.save()
return True
diff --git a/core/bind_security.py b/core/bind_security.py
new file mode 100644
index 000000000..530afa7f3
--- /dev/null
+++ b/core/bind_security.py
@@ -0,0 +1,92 @@
+from __future__ import annotations
+
+import math
+import threading
+import time
+from dataclasses import dataclass
+from typing import Callable
+
+BIND_ATTEMPT_FREE_FAILURES = 3
+BIND_ATTEMPT_BACKOFF_BASE_SECONDS = 30.0
+BIND_ATTEMPT_BACKOFF_MAX_SECONDS = 15 * 60.0
+BIND_ATTEMPT_LOCK_FAILURES = 10
+BIND_ATTEMPT_LOCK_SECONDS = 60 * 60.0
+
+
+@dataclass(frozen=True)
+class BindAttemptDecision:
+ allowed: bool
+ retry_after_seconds: int = 0
+
+
+@dataclass
+class _BindAttemptState:
+ failures: int = 0
+ locked_until: float = 0.0
+
+
+class BindAttemptLimiter:
+ """In-process bind-code failure limiter keyed by platform, user, and DM channel."""
+
+ def __init__(
+ self,
+ *,
+ clock: Callable[[], float] = time.monotonic,
+ free_failures: int = BIND_ATTEMPT_FREE_FAILURES,
+ backoff_base_seconds: float = BIND_ATTEMPT_BACKOFF_BASE_SECONDS,
+ backoff_max_seconds: float = BIND_ATTEMPT_BACKOFF_MAX_SECONDS,
+ lock_failures: int = BIND_ATTEMPT_LOCK_FAILURES,
+ lock_seconds: float = BIND_ATTEMPT_LOCK_SECONDS,
+ ) -> None:
+ self._clock = clock
+ self._free_failures = free_failures
+ self._backoff_base_seconds = backoff_base_seconds
+ self._backoff_max_seconds = backoff_max_seconds
+ self._lock_failures = lock_failures
+ self._lock_seconds = lock_seconds
+ self._states: dict[tuple[str, str, str], _BindAttemptState] = {}
+ self._lock = threading.Lock()
+
+ def check(self, *, platform: str, user_id: str, channel_id: str) -> BindAttemptDecision:
+ key = self._key(platform=platform, user_id=user_id, channel_id=channel_id)
+ now = self._clock()
+ with self._lock:
+ state = self._states.get(key)
+ if state is None or state.locked_until <= now:
+ return BindAttemptDecision(allowed=True)
+ return BindAttemptDecision(
+ allowed=False,
+ retry_after_seconds=max(1, int(math.ceil(state.locked_until - now))),
+ )
+
+ def record_failure(self, *, platform: str, user_id: str, channel_id: str) -> BindAttemptDecision:
+ key = self._key(platform=platform, user_id=user_id, channel_id=channel_id)
+ now = self._clock()
+ with self._lock:
+ state = self._states.setdefault(key, _BindAttemptState())
+ state.failures += 1
+ delay = self._delay_for_failure_count(state.failures)
+ if delay > 0:
+ state.locked_until = max(state.locked_until, now + delay)
+ return BindAttemptDecision(
+ allowed=False,
+ retry_after_seconds=max(1, int(math.ceil(state.locked_until - now))),
+ )
+ return BindAttemptDecision(allowed=True)
+
+ def reset(self, *, platform: str, user_id: str, channel_id: str) -> None:
+ key = self._key(platform=platform, user_id=user_id, channel_id=channel_id)
+ with self._lock:
+ self._states.pop(key, None)
+
+ def _delay_for_failure_count(self, failures: int) -> float:
+ if failures >= self._lock_failures:
+ return self._lock_seconds
+ if failures <= self._free_failures:
+ return 0.0
+ exponent = failures - self._free_failures - 1
+ return min(self._backoff_max_seconds, self._backoff_base_seconds * (2**exponent))
+
+ @staticmethod
+ def _key(*, platform: str, user_id: str, channel_id: str) -> tuple[str, str, str]:
+ return (str(platform or ""), str(user_id or ""), str(channel_id or ""))
diff --git a/core/handlers/command_handlers.py b/core/handlers/command_handlers.py
index 00b3ed404..76de0e3c1 100644
--- a/core/handlers/command_handlers.py
+++ b/core/handlers/command_handlers.py
@@ -5,6 +5,7 @@ import os
import time
from typing import Any, Optional
from config.platform_registry import get_platform_descriptor
+from core.bind_security import BindAttemptLimiter
from core.message_context import requires_typed_user_session_key
from modules.agents import get_agent_display_name
from modules.agents.native_sessions.types import NativeResumeSession
@@ -26,6 +27,7 @@ class CommandHandlers(BaseHandler):
self._resume_snapshots: dict[str, dict[str, Any]] = {}
self._resume_snapshot_ttl_seconds = 600.0
self._wechat_resume_page_size = 5
+ self._bind_attempt_limiter = BindAttemptLimiter()
def _get_channel_context(self, context: MessageContext) -> MessageContext:
"""Get context for channel messages (no thread)"""
@@ -928,6 +930,19 @@ class CommandHandlers(BaseHandler):
await im_client.send_message(channel_context, self._t("bind.alreadyBound"))
return
+ limit_decision = self._bind_attempt_limiter.check(
+ platform=platform,
+ user_id=context.user_id,
+ channel_id=context.channel_id,
+ )
+ if not limit_decision.allowed:
+ channel_context = self._get_channel_context(context)
+ await im_client.send_message(
+ channel_context,
+ self._t("bind.rateLimited", seconds=limit_decision.retry_after_seconds),
+ )
+ return
+
# Fetch user info for display name
try:
user_info = await im_client.get_user_info(context.user_id)
@@ -943,13 +958,34 @@ class CommandHandlers(BaseHandler):
if not success:
# Could be already bound (race) or invalid code
if _is_bound_user():
+ self._bind_attempt_limiter.reset(
+ platform=platform,
+ user_id=context.user_id,
+ channel_id=context.channel_id,
+ )
channel_context = self._get_channel_context(context)
await im_client.send_message(channel_context, self._t("bind.alreadyBound"))
else:
+ failure_decision = self._bind_attempt_limiter.record_failure(
+ platform=platform,
+ user_id=context.user_id,
+ channel_id=context.channel_id,
+ )
channel_context = self._get_channel_context(context)
- await im_client.send_message(channel_context, self._t("bind.invalidCode"))
+ if failure_decision.allowed:
+ await im_client.send_message(channel_context, self._t("bind.invalidCode"))
+ else:
+ await im_client.send_message(
+ channel_context,
+ self._t("bind.rateLimited", seconds=failure_decision.retry_after_seconds),
+ )
return
+ self._bind_attempt_limiter.reset(
+ platform=platform,
+ user_id=context.user_id,
+ channel_id=context.channel_id,
+ )
msg = self._build_bind_success_message(
name=display_name,
is_admin=is_admin,
diff --git a/tests/test_bind_code_api.py b/tests/test_bind_code_api.py
new file mode 100644
index 000000000..f3150249c
--- /dev/null
+++ b/tests/test_bind_code_api.py
@@ -0,0 +1,25 @@
+from __future__ import annotations
+
+from config import v2_settings
+from config.v2_settings import SettingsStore
+from vibe import api
+
+
+def test_create_bind_code_api_returns_machine_readable_limit_error(monkeypatch, tmp_path) -> None:
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ monkeypatch.setattr(v2_settings, "_MAX_ACTIVE_BIND_CODES", 1)
+ SettingsStore.reset_instance()
+ try:
+ assert api.create_bind_code()["ok"] is True
+
+ result = api.create_bind_code()
+
+ assert result == {
+ "ok": False,
+ "error": {
+ "code": "bind_code_limit_reached",
+ "message": "active bind code limit reached (1)",
+ },
+ }
+ finally:
+ SettingsStore.reset_instance()
diff --git a/tests/test_bind_security.py b/tests/test_bind_security.py
new file mode 100644
index 000000000..04d15a4de
--- /dev/null
+++ b/tests/test_bind_security.py
@@ -0,0 +1,39 @@
+from core.bind_security import BindAttemptLimiter
+
+
+def test_bind_attempt_limiter_applies_backoff_lock_and_reset() -> None:
+ now = 1000.0
+
+ def clock() -> float:
+ return now
+
+ limiter = BindAttemptLimiter(
+ clock=clock,
+ free_failures=1,
+ backoff_base_seconds=10,
+ backoff_max_seconds=30,
+ lock_failures=4,
+ lock_seconds=120,
+ )
+ key = {"platform": "slack", "user_id": "U1", "channel_id": "D1"}
+
+ assert limiter.check(**key).allowed is True
+ assert limiter.record_failure(**key).allowed is True
+
+ decision = limiter.record_failure(**key)
+ assert decision.allowed is False
+ assert decision.retry_after_seconds == 10
+ assert limiter.check(**key).retry_after_seconds == 10
+
+ now += 10
+ decision = limiter.record_failure(**key)
+ assert decision.allowed is False
+ assert decision.retry_after_seconds == 20
+
+ now += 20
+ decision = limiter.record_failure(**key)
+ assert decision.allowed is False
+ assert decision.retry_after_seconds == 120
+
+ limiter.reset(**key)
+ assert limiter.check(**key).allowed is True
diff --git a/tests/test_command_handler_user_names.py b/tests/test_command_handler_user_names.py
index 1fbb30d91..81b860a03 100644
--- a/tests/test_command_handler_user_names.py
+++ b/tests/test_command_handler_user_names.py
@@ -95,6 +95,7 @@ class _StubIMClient:
class _StubSettingsManager:
def __init__(self):
self.bind_calls = []
+ self.bind_result = (True, False)
self.custom_cwd_calls = []
self.session_row = None
self.session_lookup_calls = []
@@ -104,7 +105,7 @@ class _StubSettingsManager:
def bind_user_with_code(self, user_id, display_name, code, dm_chat_id="", platform=None):
self.bind_calls.append((user_id, display_name, code, dm_chat_id, platform))
- return True, False
+ return self.bind_result
def set_custom_cwd(self, settings_key, cwd):
self.custom_cwd_calls.append((settings_key, cwd))
@@ -184,6 +185,53 @@ class CommandHandlerUserNameTests(unittest.IsolatedAsyncioTestCase):
],
)
+ async def test_bind_rate_limit_blocks_before_code_validation(self):
+ controller = _StubController({"display_name": "Alex"})
+ handler = CommandHandlers(controller)
+ handler._bind_attempt_limiter = type(
+ "Limiter",
+ (),
+ {
+ "check": lambda _self, **_kwargs: types.SimpleNamespace(
+ allowed=False,
+ retry_after_seconds=42,
+ ),
+ "record_failure": lambda _self, **_kwargs: (_ for _ in ()).throw(AssertionError("unexpected")),
+ "reset": lambda _self, **_kwargs: (_ for _ in ()).throw(AssertionError("unexpected")),
+ },
+ )()
+ context = MessageContext(user_id="U0E0FM3QT", channel_id="D123")
+
+ await handler.handle_bind(context, "bad-code")
+
+ self.assertEqual(controller.settings_manager.bind_calls, [])
+ self.assertEqual(controller.im_client.sent_messages, [("D123", "❌ 绑定码错误次数过多,请 42 秒后再试。")])
+
+ async def test_bind_invalid_code_records_failed_attempt(self):
+ controller = _StubController({"display_name": "Alex"})
+ controller.settings_manager.bind_result = (False, False)
+ handler = CommandHandlers(controller)
+ calls = []
+
+ class Limiter:
+ def check(self, **kwargs):
+ return types.SimpleNamespace(allowed=True)
+
+ def record_failure(self, **kwargs):
+ calls.append(kwargs)
+ return types.SimpleNamespace(allowed=False, retry_after_seconds=30)
+
+ def reset(self, **kwargs):
+ raise AssertionError("unexpected")
+
+ handler._bind_attempt_limiter = Limiter()
+ context = MessageContext(user_id="U0E0FM3QT", channel_id="D123")
+
+ await handler.handle_bind(context, "bad-code")
+
+ self.assertEqual(calls, [{"platform": "slack", "user_id": "U0E0FM3QT", "channel_id": "D123"}])
+ self.assertEqual(controller.im_client.sent_messages, [("D123", "❌ 绑定码错误次数过多,请 30 秒后再试。")])
+
async def test_wechat_bind_success_points_to_start_menu(self):
controller = _StubController({"display_name": "小王"})
setattr(controller.config, "platform", "wechat")
diff --git a/tests/test_im_base_auth.py b/tests/test_im_base_auth.py
index b252abf27..9737d1fd1 100644
--- a/tests/test_im_base_auth.py
+++ b/tests/test_im_base_auth.py
@@ -84,6 +84,11 @@ def test_parse_text_command():
assert BaseIMClient.parse_text_command("/set_cwd /tmp") == ("set_cwd", "/tmp")
assert BaseIMClient.parse_text_command("bind code") is None
assert BaseIMClient.parse_text_command("bind code", allow_plain_bind=True) == ("bind", "code")
+ assert BaseIMClient.parse_text_command("bind vr-aB3X9kLmN0", allow_plain_bind=True) == (
+ "bind",
+ "vr-aB3X9kLmN0",
+ )
+ assert BaseIMClient.parse_text_command("/bind vr-aB3X9kLmN0") == ("bind", "vr-aB3X9kLmN0")
assert BaseIMClient.parse_text_command("hello") is None
assert BaseIMClient.parse_text_command("/") is None
diff --git a/tests/test_sqlite_settings_store.py b/tests/test_sqlite_settings_store.py
index 6f0276b2d..bc5677ffa 100644
--- a/tests/test_sqlite_settings_store.py
+++ b/tests/test_sqlite_settings_store.py
@@ -3,9 +3,11 @@ from __future__ import annotations
import json
from pathlib import Path
+import pytest
from sqlalchemy import select
from config import paths
+from config import v2_settings
from config.v2_settings import ChannelSettings, RoutingSettings, SettingsState, SettingsStore, UserSettings
from storage import projects_service
from storage.db import create_sqlite_engine
@@ -130,6 +132,54 @@ def test_bind_user_promotes_when_only_admin_is_disabled(tmp_path: Path) -> None:
store.close()
+def test_create_bind_code_uses_high_entropy_format(tmp_path: Path) -> None:
+ store = SettingsStore(tmp_path / "settings.json")
+ try:
+ code = store.create_bind_code().code
+
+ assert code.startswith("vr-")
+ random_part = code.removeprefix("vr-")
+ assert len(random_part) >= 8
+ assert set(random_part) <= set(v2_settings._BIND_CODE_ALPHABET)
+ finally:
+ store.close()
+
+
+def test_validate_bind_code_uses_constant_time_compare(tmp_path: Path, monkeypatch) -> None:
+ store = SettingsStore(tmp_path / "settings.json")
+ try:
+ first_code = store.create_bind_code()
+ bind_code = store.create_bind_code()
+ comparisons: list[tuple[str, str]] = []
+
+ def compare_digest(left: str, right: str) -> bool:
+ comparisons.append((left, right))
+ return left == right
+
+ monkeypatch.setattr(v2_settings.hmac, "compare_digest", compare_digest)
+
+ assert store.validate_bind_code(bind_code.code) == bind_code
+ assert comparisons == [(first_code.code, bind_code.code), (bind_code.code, bind_code.code)]
+ finally:
+ store.close()
+
+
+def test_create_bind_code_limits_active_codes(tmp_path: Path, monkeypatch) -> None:
+ monkeypatch.setattr(v2_settings, "_MAX_ACTIVE_BIND_CODES", 2)
+ store = SettingsStore(tmp_path / "settings.json")
+ try:
+ first = store.create_bind_code()
+ store.create_bind_code()
+
+ with pytest.raises(ValueError, match="active bind code limit reached"):
+ store.create_bind_code()
+
+ assert store.deactivate_bind_code(first.code) is True
+ assert store.create_bind_code().is_active is True
+ finally:
+ store.close()
+
+
def test_disabled_user_cannot_rebind_with_active_code(tmp_path: Path) -> None:
settings_path = tmp_path / "settings.json"
store = SettingsStore(settings_path)
diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.json
index 22965de16..10620673a 100644
--- a/ui/src/i18n/en.json
+++ b/ui/src/i18n/en.json
@@ -614,7 +614,8 @@
"cloudflared_spawn_failed": "Connector startup failed. Check that cloudflared is executable, or inspect the runtime logs.",
"cloudflared_exited": "The connector exited immediately after startup. This usually means the Tunnel credential is invalid or the Cloudflare config is not ready. Pair again and retry.",
"cloudflared_stop_failed": "The connector could not be stopped. Try again later, or manually stop the cloudflared process.",
- "cloudflared_process_unknown": "Avibe found a connector-like process but could not verify ownership. To avoid killing the wrong process, it did not change it. Check the cloudflared process manually and retry."
+ "cloudflared_process_unknown": "Avibe found a connector-like process but could not verify ownership. To avoid killing the wrong process, it did not change it. Check the cloudflared process manually and retry.",
+ "bind_code_limit_reached": "Too many active bind codes. Revoke an unused code before creating another."
},
"apps": {
"title": "Apps",
diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.json
index ecdfe6d8e..df9a97855 100644
--- a/ui/src/i18n/zh.json
+++ b/ui/src/i18n/zh.json
@@ -614,7 +614,8 @@
"cloudflared_spawn_failed": "连接器启动失败。请检查 cloudflared 是否可执行,或查看运行日志。",
"cloudflared_exited": "连接器启动后立即退出。通常是 Tunnel 凭证无效或 Cloudflare 配置未生效,请重新配对后再试。",
"cloudflared_stop_failed": "连接器暂时无法停止。请稍后重试,或在系统进程里手动结束 cloudflared。",
- "cloudflared_process_unknown": "检测到一个无法确认归属的连接器进程。为避免误杀其它进程,Avibe 没有自动处理。请手动检查 cloudflared 进程后再启动。"
+ "cloudflared_process_unknown": "检测到一个无法确认归属的连接器进程。为避免误杀其它进程,Avibe 没有自动处理。请手动检查 cloudflared 进程后再启动。",
+ "bind_code_limit_reached": "可用绑定码过多,请先撤销一个未使用的绑定码,再创建新的绑定码。"
},
"apps": {
"title": "应用",
diff --git a/vibe/api.py b/vibe/api.py
index 6e2172beb..71e3fc169 100644
--- a/vibe/api.py
+++ b/vibe/api.py
@@ -9742,7 +9742,16 @@ def create_bind_code(code_type: str = "one_time", expires_at: Optional[str] = No
if code_type == "expiring" and not expires_at:
return {"ok": False, "error": "expires_at is required for expiring bind codes"}
store = SettingsStore.get_instance()
- bc = store.create_bind_code(code_type, expires_at)
+ try:
+ bc = store.create_bind_code(code_type, expires_at)
+ except ValueError as exc:
+ return {
+ "ok": False,
+ "error": {
+ "code": "bind_code_limit_reached",
+ "message": str(exc),
+ },
+ }
return {
"ok": True,
"bind_code": {
diff --git a/vibe/i18n/en.json b/vibe/i18n/en.json
index 3266eeb0a..ec9756116 100644
--- a/vibe/i18n/en.json
+++ b/vibe/i18n/en.json
@@ -415,6 +415,7 @@
"menuHintStart": "Send `/start` to open more action menus.",
"alreadyBound": "You are already bound. No action needed.",
"invalidCode": "❌ Invalid or expired bind code. Please check and try again.",
+ "rateLimited": "❌ Too many invalid bind attempts. Try again in {seconds} second(s).",
"usage": "Usage: `bind <code>`\n\n`/bind <code>` also works. Please enter the bind code provided by an admin.",
"dmOnly": "The bind command can only be used in a direct message. Please DM the bot with `bind <code>`.",
"dmNotBound": "🔒 You haven't bound your account yet.\nUse `bind <code>` to get started. (`/bind <code>` is also supported.)",
diff --git a/vibe/i18n/zh.json b/vibe/i18n/zh.json
index 6cbbb974e..3cbbf06c0 100644
--- a/vibe/i18n/zh.json
+++ b/vibe/i18n/zh.json
@@ -415,6 +415,7 @@
"menuHintStart": "发送 `/start` 即可唤起更多操作菜单。",
"alreadyBound": "你已经绑定过了,无需再次操作。",
"invalidCode": "❌ 无效或已过期的绑定码,请检查后重试。",
+ "rateLimited": "❌ 绑定码错误次数过多,请 {seconds} 秒后再试。",
"usage": "用法:`bind <绑定码>`\n\n也兼容 `/bind <绑定码>`。请输入管理员提供的绑定码。",
"dmOnly": "绑定命令只能在私信中使用。请私聊机器人并发送 `bind <绑定码>`。",
"dmNotBound": "🔒 你还未绑定账号。\n使用 `bind <绑定码>` 开始使用。(也兼容 `/bind <绑定码>`)",