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(admin): address review findings — security, atomicity, and correctness fixes

cyh2f683aaf3ebf
diff --git a/config/v2_settings.py b/config/v2_settings.py
index 1fd33290f..7e05f274f 100644
--- a/config/v2_settings.py
+++ b/config/v2_settings.py
@@ -2,10 +2,11 @@ import json
import logging
import secrets
import string
+import threading
from dataclasses import dataclass, field
from datetime import datetime, timezone
from pathlib import Path
-from typing import Dict, List, Optional
+from typing import Dict, List, Optional, Tuple
from config import paths
@@ -128,6 +129,7 @@ class SettingsStore:
def __init__(self, settings_path: Optional[Path] = None):
self.settings_path = settings_path or paths.get_settings_path()
self.settings: SettingsState = SettingsState()
+ self._bind_lock = threading.Lock() # Guards atomic bind operations
self._load()
def _load(self) -> None:
@@ -284,6 +286,42 @@ class SettingsStore:
self.save()
return user
+ def bind_user_with_code(self, user_id: str, display_name: str, code: str) -> Tuple[bool, bool]:
+ """Atomically validate code, create user, and consume code.
+
+ Returns (success, is_admin).
+ Thread-safe: uses a lock to prevent concurrent bind races.
+ """
+ with self._bind_lock:
+ # Check already bound
+ if self.is_bound_user(user_id):
+ return False, False
+
+ # Validate code
+ bc = self.validate_bind_code(code)
+ if bc is None:
+ return False, False
+
+ # Auto-admin for first user
+ is_admin = not self.has_any_admin()
+
+ # Create user
+ user = UserSettings(
+ display_name=display_name,
+ is_admin=is_admin,
+ bound_at=_now_iso(),
+ enabled=True,
+ )
+ self.settings.users[user_id] = user
+
+ # Consume code
+ bc.used_by.append(user_id)
+ if bc.type == "one_time":
+ bc.is_active = False
+
+ self.save()
+ return True, is_admin
+
def update_user(self, user_id: str, settings: UserSettings) -> None:
self.settings.users[user_id] = settings
self.save()
@@ -335,10 +373,15 @@ class SettingsStore:
if bc.type == "expiring" and bc.expires_at:
try:
expires = datetime.fromisoformat(bc.expires_at)
+ # 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):
- pass
+ # 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
diff --git a/core/controller.py b/core/controller.py
index 5595533d0..79f6e4bb0 100644
--- a/core/controller.py
+++ b/core/controller.py
@@ -274,13 +274,36 @@ class Controller:
def _setup_callbacks(self):
"""Setup callback connections between modules"""
+
+ # Admin guard wrapper for sensitive text commands
+ def _admin_guard(handler):
+ """Wrap a command handler with admin permission check."""
+ from functools import wraps
+
+ @wraps(handler)
+ async def guarded(context, args=""):
+ store = self.settings_manager.store
+ if store.has_any_admin() and not store.is_admin(context.user_id):
+ logger.info(f"Permission denied: {context.user_id} attempted text command")
+ try:
+ from vibe.i18n import t as i18n_t
+
+ msg = i18n_t("permission.adminOnly")
+ await self.im_client.send_message(context, msg)
+ except Exception:
+ pass
+ return
+ await handler(context, args)
+
+ return guarded
+
# Create command handlers dict
command_handlers = {
"start": self.command_handler.handle_start,
"clear": self.command_handler.handle_clear,
"cwd": self.command_handler.handle_cwd,
- "set_cwd": self.command_handler.handle_set_cwd,
- "settings": self.settings_handler.handle_settings,
+ "set_cwd": _admin_guard(self.command_handler.handle_set_cwd),
+ "settings": _admin_guard(self.settings_handler.handle_settings),
"stop": self.command_handler.handle_stop,
"bind": self.command_handler.handle_bind,
}
@@ -354,8 +377,31 @@ class Controller:
return os.getcwd()
def _get_settings_key(self, context: MessageContext) -> str:
- """Get settings key based on context"""
- # Slack only in V2
+ """Get settings key based on context.
+
+ For DM contexts, returns user_id so per-user settings apply.
+ For channel contexts, returns channel_id for per-channel settings.
+ """
+ platform = getattr(self.config, "platform", "slack")
+ if platform == "slack" and context.channel_id.startswith("D"):
+ return context.user_id
+ if platform == "discord":
+ # Check if this is a DM by looking at platform_specific or channel type
+ ps = context.platform_specific or {}
+ msg = ps.get("message")
+ if msg is not None:
+ try:
+ import discord
+
+ if isinstance(msg.channel, discord.DMChannel) or msg.guild is None:
+ return context.user_id
+ except Exception:
+ pass
+ if platform == "lark":
+ ps = context.platform_specific or {}
+ event = ps.get("event", {})
+ if isinstance(event, dict) and event.get("message", {}).get("chat_type") == "p2p":
+ return context.user_id
return context.channel_id
def _get_target_context(self, context: MessageContext) -> MessageContext:
diff --git a/core/handlers/command_handlers.py b/core/handlers/command_handlers.py
index bc22460b5..8a861a62b 100644
--- a/core/handlers/command_handlers.py
+++ b/core/handlers/command_handlers.py
@@ -414,8 +414,19 @@ class CommandHandlers:
await self.im_client.send_message(channel_context, f"❌ {self._t('error.resumeFailed')}")
async def handle_bind(self, context: MessageContext, args: str = ""):
- """Handle /bind command - bind a user to this Vibe Remote instance via bind code"""
+ """Handle /bind command - bind a user to this Vibe Remote instance via bind code.
+
+ Only allowed in DM context. In channels, instructs the user to DM the bot.
+ """
try:
+ # Check if this is a DM context (settings_key == user_id means DM)
+ settings_key = self.controller._get_settings_key(context)
+ if settings_key != context.user_id:
+ # Not a DM — instruct user to use DM
+ channel_context = self._get_channel_context(context)
+ await self.im_client.send_message(channel_context, self._t("bind.dmOnly"))
+ return
+
code = args.strip()
if not code:
channel_context = self._get_channel_context(context)
@@ -430,13 +441,6 @@ class CommandHandlers:
await self.im_client.send_message(channel_context, self._t("bind.alreadyBound"))
return
- # Validate the bind code
- bind_code = store.validate_bind_code(code)
- if bind_code is None:
- channel_context = self._get_channel_context(context)
- await self.im_client.send_message(channel_context, self._t("bind.invalidCode"))
- return
-
# Fetch user info for display name
try:
user_info = await self.im_client.get_user_info(context.user_id)
@@ -448,12 +452,18 @@ class CommandHandlers:
user_info.get("display_name") or user_info.get("real_name") or user_info.get("name") or context.user_id
)
- # Auto-admin: if no admins exist, first user becomes admin
- is_admin = not store.has_any_admin()
+ # Atomic bind: validate code + create user + consume code in one operation
+ success, is_admin = store.bind_user_with_code(context.user_id, display_name, code)
- # Add user and consume the bind code
- store.add_user(context.user_id, display_name, is_admin=is_admin)
- store.use_bind_code(code, context.user_id)
+ if not success:
+ # Could be already bound (race) or invalid code
+ if store.is_bound_user(context.user_id):
+ channel_context = self._get_channel_context(context)
+ await self.im_client.send_message(channel_context, self._t("bind.alreadyBound"))
+ else:
+ channel_context = self._get_channel_context(context)
+ await self.im_client.send_message(channel_context, self._t("bind.invalidCode"))
+ return
if is_admin:
msg = self._t("bind.successAdmin", name=display_name)
diff --git a/core/update_checker.py b/core/update_checker.py
index 8db34f139..41ff49a10 100644
--- a/core/update_checker.py
+++ b/core/update_checker.py
@@ -428,16 +428,22 @@ class UpdateChecker:
]
for uid in admin_ids:
try:
- await im_client.send_dm(uid, text, blocks=blocks)
- logger.info(f"Sent update notification to admin {uid}")
+ result = await im_client.send_dm(uid, text, blocks=blocks)
+ if result:
+ logger.info(f"Sent update notification to admin {uid}")
+ else:
+ logger.warning(f"Failed to send update notification to admin {uid}: send_dm returned None")
except Exception as e:
logger.error(f"Failed to send update notification to admin {uid}: {e}")
elif platform == "discord":
text = f"🚀 **Vibe Remote Update Available**\n\nUpdate from `{current}` → `{latest}`"
for uid in admin_ids:
try:
- await im_client.send_dm(uid, text)
- logger.info(f"Sent update notification to admin {uid}")
+ result = await im_client.send_dm(uid, text)
+ if result:
+ logger.info(f"Sent update notification to admin {uid}")
+ else:
+ logger.warning(f"Failed to send update notification to admin {uid}: send_dm returned None")
except Exception as e:
logger.error(f"Failed to send update notification to admin {uid}: {e}")
else:
@@ -445,8 +451,11 @@ class UpdateChecker:
text = f"🚀 Vibe Remote Update Available\n\nUpdate from {current} → {latest}"
for uid in admin_ids:
try:
- await im_client.send_dm(uid, text)
- logger.info(f"Sent update notification to admin {uid}")
+ result = await im_client.send_dm(uid, text)
+ if result:
+ logger.info(f"Sent update notification to admin {uid}")
+ else:
+ logger.warning(f"Failed to send update notification to admin {uid}: send_dm returned None")
except Exception as e:
logger.error(f"Failed to send update notification to admin {uid}: {e}")
diff --git a/modules/im/discord.py b/modules/im/discord.py
index 443e385c7..96fc0e9a7 100644
--- a/modules/im/discord.py
+++ b/modules/im/discord.py
@@ -449,13 +449,32 @@ class DiscordBot(BaseIMClient):
if not content and not files:
return
- # Authorization
- if not await self._is_authorized_channel(channel_id):
- await self._send_unauthorized_message(channel_id)
- return
+ # Determine if this is a DM
+ is_dm = isinstance(channel, discord.DMChannel) or message.guild is None
+
+ # DM authorization gate: require user to be bound for DM access
+ # Must run before channel authorization so unbound DM users get bind hint (not channel error)
+ if is_dm and self.settings_manager:
+ store = self.settings_manager.store
+ if not store.is_bound_user(str(message.author.id)):
+ # Allow /bind command through for unbound users
+ if content.startswith("/bind ") or content == "/bind":
+ pass # Will be handled by command routing below
+ else:
+ try:
+ hint = self._t("bind.dmNotBound", channel_id)
+ await channel.send(content=hint)
+ except Exception as e:
+ logger.error(f"Failed to send DM bind hint: {e}")
+ return
+
+ # Channel authorization (skip for DMs — DMs are authorized via bind system)
+ if not is_dm:
+ if not await self._is_authorized_channel(channel_id):
+ await self._send_unauthorized_message(channel_id)
+ return
# Mention logic for guild channels
- is_dm = isinstance(channel, discord.DMChannel) or message.guild is None
effective_require_mention = self.config.require_mention
if self.settings_manager:
effective_require_mention = self.settings_manager.get_require_mention(
@@ -480,21 +499,6 @@ class DiscordBot(BaseIMClient):
bot_id = str(self.client.user.id)
content = content.replace(f"<@{bot_id}>", "").replace(f"<@!{bot_id}>", "").strip()
- # DM authorization gate: require user to be bound for DM access
- if is_dm and self.settings_manager:
- store = self.settings_manager.store
- if not store.is_bound_user(str(message.author.id)):
- # Allow /bind command through for unbound users
- if content.startswith("/bind ") or content == "/bind":
- pass # Will be handled by command routing below
- else:
- try:
- hint = self._t("bind.dmNotBound", channel_id)
- await channel.send(content=hint)
- except Exception as e:
- logger.error(f"Failed to send DM bind hint: {e}")
- return
-
# Handle slash-like commands in plain messages
if content.startswith("/"):
command_context = MessageContext(
diff --git a/modules/im/feishu.py b/modules/im/feishu.py
index 07eed404c..3577bcdf7 100644
--- a/modules/im/feishu.py
+++ b/modules/im/feishu.py
@@ -1113,8 +1113,8 @@ class FeishuBot(BaseIMClient):
logger.error("Failed to send DM bind hint: %s", exc)
return
- # Channel authorisation
- if not await self._is_authorized_channel(chat_id):
+ # Channel authorisation (skip for p2p/DM — authorized via bind system)
+ if not is_p2p and not await self._is_authorized_channel(chat_id):
logger.info("Unauthorized message from channel: %s", chat_id)
await self._send_unauthorized_message(chat_id)
return
diff --git a/modules/im/slack.py b/modules/im/slack.py
index 4fb3a5052..c9b088e29 100644
--- a/modules/im/slack.py
+++ b/modules/im/slack.py
@@ -910,8 +910,9 @@ class SlackBot(BaseIMClient):
logger.error(f"Failed to send DM bind hint: {e}")
return
- # Only check channel authorization for messages we're actually going to process
- if not await self._is_authorized_channel(channel_id):
+ # Only check channel authorization for non-DM messages
+ # DMs are authorized via the bind system above
+ if not channel_id.startswith("D") and not await self._is_authorized_channel(channel_id):
logger.info(f"Unauthorized message from channel: {channel_id}")
await self._send_unauthorized_message(channel_id)
return
@@ -1112,6 +1113,14 @@ class SlackBot(BaseIMClient):
# Check for update button click (handled before channel authorization)
for action in actions:
if action.get("action_id") == "vibe_update_now":
+ # Admin permission check for update button
+ user_id = payload.get("user", {}).get("id")
+ if self.settings_manager:
+ store = self.settings_manager.store
+ if store.has_any_admin() and not store.is_admin(user_id):
+ logger.info(f"Permission denied: {user_id} attempted update via Slack button")
+ return
+
from core.update_checker import handle_update_button_click
if hasattr(self, "_controller") and self._controller:
diff --git a/modules/settings_manager.py b/modules/settings_manager.py
index 34761d476..1f25582f0 100644
--- a/modules/settings_manager.py
+++ b/modules/settings_manager.py
@@ -8,6 +8,7 @@ from pathlib import Path
from config import paths
from config.v2_sessions import SessionsStore
from config.v2_settings import SettingsStore, ChannelSettings, RoutingSettings
+from config.v2_settings import UserSettings as BoundUserSettings
logger = logging.getLogger(__name__)
@@ -139,6 +140,25 @@ class SettingsManager:
enabled=channel_settings.enabled,
)
+ def _from_bound_user_settings(self, bound_user: BoundUserSettings) -> UserSettings:
+ """Convert a bound user's settings (from v2_settings.UserSettings) to runtime UserSettings."""
+ routing = ChannelRouting(
+ agent_backend=bound_user.routing.agent_backend,
+ opencode_agent=bound_user.routing.opencode_agent,
+ opencode_model=bound_user.routing.opencode_model,
+ opencode_reasoning_effort=bound_user.routing.opencode_reasoning_effort,
+ claude_agent=bound_user.routing.claude_agent,
+ claude_model=bound_user.routing.claude_model,
+ codex_model=bound_user.routing.codex_model,
+ codex_reasoning_effort=bound_user.routing.codex_reasoning_effort,
+ )
+ return UserSettings(
+ show_message_types=self._normalize_show_message_types(bound_user.show_message_types),
+ custom_cwd=bound_user.custom_cwd,
+ channel_routing=routing,
+ enabled=bound_user.enabled,
+ )
+
def _to_channel_settings(self, settings: UserSettings) -> ChannelSettings:
routing = settings.channel_routing or ChannelRouting()
return ChannelSettings(
@@ -231,7 +251,11 @@ class SettingsManager:
logger.error(f"Error saving settings: {e}")
def get_user_settings(self, user_id: Union[int, str]) -> UserSettings:
- """Get settings for a specific user"""
+ """Get settings for a specific user/channel context.
+
+ Checks channels dict first, then bound users dict (for DM contexts
+ where _get_settings_key returns user_id).
+ """
normalized_id = self._normalize_user_id(user_id)
self._reload_if_changed()
@@ -241,6 +265,8 @@ class SettingsManager:
settings = UserSettings()
if normalized_id in self.store.settings.channels:
settings = self._from_channel_settings(self.store.settings.channels[normalized_id])
+ elif normalized_id in self.store.settings.users:
+ settings = self._from_bound_user_settings(self.store.settings.users[normalized_id])
self.settings[normalized_id] = settings
self._save_settings()
return self.settings[normalized_id]
diff --git a/ui/src/components/steps/Summary.tsx b/ui/src/components/steps/Summary.tsx
index a006bbb37..aeae19179 100644
--- a/ui/src/components/steps/Summary.tsx
+++ b/ui/src/components/steps/Summary.tsx
@@ -104,7 +104,7 @@ export const Summary: React.FC<SummaryProps> = ({ data, onBack }) => {
<CheckCircle2 size={40} />
</div>
<h2 className="text-2xl font-display font-bold text-text mb-2">{t('summary.title')}</h2>
- <p className="text-muted mb-8">Vibe Remote is running!</p>
+ <p className="text-muted mb-8">{t('summary.serviceRunning')}</p>
<div className="bg-panel border border-border rounded-lg p-6 shadow-sm w-full max-w-md">
<div className="flex items-center gap-3 mb-4">
@@ -135,7 +135,7 @@ export const Summary: React.FC<SummaryProps> = ({ data, onBack }) => {
onClick={() => navigate('/dashboard')}
className="mt-8 px-8 py-3 bg-primary hover:bg-primary/90 text-white rounded-lg font-bold transition-colors shadow-sm"
>
- Go to Dashboard
+ {t('summary.goToDashboard')}
</button>
</div>
);
diff --git a/ui/src/components/steps/UserList.tsx b/ui/src/components/steps/UserList.tsx
index cbe00c13e..3d864a782 100644
--- a/ui/src/components/steps/UserList.tsx
+++ b/ui/src/components/steps/UserList.tsx
@@ -178,7 +178,7 @@ const BindCodeSection: React.FC = () => {
)}
{codes.length === 0 ? (
- <p className="text-sm text-muted">{t('userList.noUsers')}</p>
+ <p className="text-sm text-muted">{t('bindCode.noCodes')}</p>
) : (
<div className="divide-y divide-border">
{codes.map((bc) => {
diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.json
index 7ddc8685c..34dfc1b50 100644
--- a/ui/src/i18n/en.json
+++ b/ui/src/i18n/en.json
@@ -327,6 +327,8 @@
"tipThread": "Thread = Session",
"tipThreadDesc": "Each thread is an isolated session. Start multiple threads for parallel tasks.",
"finishAndStart": "Finish & Start",
+ "serviceRunning": "Vibe Remote is running!",
+ "goToDashboard": "Go to Dashboard",
"bindCodeTitle": "Your First Bind Code",
"bindCodeDesc": "Send this command to the bot in a DM to become the first admin:",
"bindCodeCommand": "/bind",
@@ -457,6 +459,7 @@
"codeType": "Type",
"expirationDate": "Expiration date",
"created": "Bind code created",
- "deleted": "Bind code deleted"
+ "deleted": "Bind code deleted",
+ "noCodes": "No bind codes yet. Create one to get started."
}
}
diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.json
index 4bb38d9db..e323e0655 100644
--- a/ui/src/i18n/zh.json
+++ b/ui/src/i18n/zh.json
@@ -327,6 +327,8 @@
"tipThread": "Thread = 会话",
"tipThreadDesc": "每个 Thread 是独立会话,可开多个 Thread 并行执行任务。",
"finishAndStart": "完成并启动",
+ "serviceRunning": "Vibe Remote 已启动!",
+ "goToDashboard": "前往控制台",
"bindCodeTitle": "您的首个绑定码",
"bindCodeDesc": "在私聊中向机器人发送以下命令,成为第一个管理员:",
"bindCodeCommand": "/bind",
@@ -457,6 +459,7 @@
"codeType": "类型",
"expirationDate": "到期日期",
"created": "绑定码已创建",
- "deleted": "绑定码已删除"
+ "deleted": "绑定码已删除",
+ "noCodes": "暂无绑定码,创建一个开始使用。"
}
}
diff --git a/vibe/api.py b/vibe/api.py
index cb3f8beb6..544b4d653 100644
--- a/vibe/api.py
+++ b/vibe/api.py
@@ -1114,8 +1114,13 @@ def get_users() -> dict:
def save_users(payload: dict) -> dict:
- """Save user settings (bulk update from UI)."""
+ """Save user settings (bulk update from UI).
+
+ Preserves admin invariant: if there were admins before, at least one must remain.
+ """
store = SettingsStore()
+ had_admins = store.has_any_admin()
+
users = {}
for user_id, up in (payload.get("users") or {}).items():
if not isinstance(up, dict):
@@ -1129,6 +1134,13 @@ def save_users(payload: dict) -> dict:
custom_cwd=up.get("custom_cwd"),
routing=_parse_routing(up.get("routing") or {}),
)
+
+ # Enforce admin invariant: if admins existed before, at least one must remain
+ if had_admins:
+ new_admin_count = sum(1 for u in users.values() if u.is_admin)
+ if new_admin_count == 0:
+ return {"ok": False, "error": "Cannot remove all admins"}
+
store.settings.users = users
store.save()
return get_users()
diff --git a/vibe/i18n/en.json b/vibe/i18n/en.json
index ac16da8c1..dd0682e3a 100644
--- a/vibe/i18n/en.json
+++ b/vibe/i18n/en.json
@@ -249,6 +249,7 @@
"alreadyBound": "You are already bound. No action needed.",
"invalidCode": "❌ Invalid or expired bind code. Please check and try again.",
"usage": "Usage: `/bind <code>`\n\nPlease 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.",
"error": "❌ Bind failed: {error}"
},
diff --git a/vibe/i18n/zh.json b/vibe/i18n/zh.json
index 76dbd81e6..7bc445a9f 100644
--- a/vibe/i18n/zh.json
+++ b/vibe/i18n/zh.json
@@ -249,6 +249,7 @@
"alreadyBound": "你已经绑定过了,无需再次操作。",
"invalidCode": "❌ 无效或已过期的绑定码,请检查后重试。",
"usage": "用法:`/bind <绑定码>`\n\n请输入管理员提供的绑定码。",
+ "dmOnly": "`/bind` 命令只能在私信中使用。请私聊机器人并发送 `/bind <绑定码>`。",
"dmNotBound": "🔒 你还未绑定账号。\n使用 `/bind <绑定码>` 开始使用。",
"error": "❌ 绑定失败:{error}"
},