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.
Python agentagent-osaiai-agentsai-partnerchatopsclaudeclaude-codecodexdevtoolsdiscord-botlark-botllmlocal-firstlong-term-memoryopencodeslack-botvibe-codingvibeywechat
refactor(auth): centralized auth pipeline replacing 8 inline checks across 3 platforms
cyhb7d43713a7be
diff --git a/core/auth.py b/core/auth.pynew file mode 100644index 000000000..b809a51b0--- /dev/null+++ b/core/auth.py@@ -0,0 +1,97 @@+"""Centralized authorization pipeline.++Every IM entry point calls ``check_auth`` before dispatching to handlers.+This eliminates duplicated inline auth checks across 8 separate code paths.+"""++from dataclasses import dataclass+from typing import TYPE_CHECKING++if TYPE_CHECKING:+ from config.v2_settings import SettingsStore++# ---------------------------------------------------------------------------+# Actions that require admin permission+# ---------------------------------------------------------------------------+ADMIN_PROTECTED_ACTIONS: frozenset = frozenset(+ {+ # Button / callback_data callbacks+ "cmd_settings",+ "cmd_routing",+ "cmd_change_cwd",+ "vibe_update_now",+ # Feishu form submit button names+ "cwd_submit",+ "settings_submit",+ "routing_backend_select",+ "routing_submit",+ # Text commands (used with _admin_guard)+ "set_cwd",+ "settings",+ }+)++# Commands exempt from DM bind gate (unbound users can use these)+BIND_EXEMPT_COMMANDS: frozenset = frozenset({"bind"})+++@dataclass+class AuthResult:+ """Result of an authorization check."""++ allowed: bool+ denial: str = "" # "" | "unbound_dm" | "unauthorized_channel" | "not_admin"+ is_dm: bool = False+++def check_auth(+ *,+ user_id: str,+ channel_id: str,+ is_dm: bool,+ action: str = "",+ store: "SettingsStore | None" = None,+) -> AuthResult:+ """Run the centralized authorization pipeline.++ Order of checks:+ 1. DM bind gate — DM users must be bound (except ``/bind``)+ 2. Channel auth — channel messages must come from enabled channels+ 3. Admin check — protected actions require admin++ Parameters+ ----------+ user_id: The actor's platform user ID.+ channel_id: The channel / chat ID.+ is_dm: Whether this is a direct-message context.+ action: The action being performed (command name, callback_data,+ or Feishu form button_name). Used for admin check and+ bind-gate exemption.+ store: ``SettingsStore`` instance for permission lookups.+ When *None* (no settings configured), everything is allowed.+ """+ if store is None:+ return AuthResult(allowed=True, is_dm=is_dm)++ # Ensure we have fresh data+ store.maybe_reload()++ # 1. DM bind gate+ if is_dm:+ if action in BIND_EXEMPT_COMMANDS:+ return AuthResult(allowed=True, is_dm=True)+ if not store.is_bound_user(user_id):+ return AuthResult(allowed=False, denial="unbound_dm", is_dm=True)+ # DM users skip channel authorization+ else:+ # 2. Channel authorization+ ch = store.settings.channels.get(channel_id)+ if not ch or not ch.enabled:+ return AuthResult(allowed=False, denial="unauthorized_channel", is_dm=False)++ # 3. Admin check for protected actions+ if action in ADMIN_PROTECTED_ACTIONS:+ if store.has_any_admin() and not store.is_admin(user_id):+ return AuthResult(allowed=False, denial="not_admin", is_dm=is_dm)++ return AuthResult(allowed=True, is_dm=is_dm)diff --git a/core/controller.py b/core/controller.pyindex 1a5436cb9..3fc785f12 100644--- a/core/controller.py+++ b/core/controller.py@@ -275,35 +275,15 @@ 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 dict+ # Admin protection for "set_cwd" and "settings" is now handled by+ # the centralized auth pipeline (core.auth.check_auth) in IM entry points.command_handlers = {"start": self.command_handler.handle_start,"clear": self.command_handler.handle_clear,"cwd": self.command_handler.handle_cwd,- "set_cwd": _admin_guard(self.command_handler.handle_set_cwd),- "settings": _admin_guard(self.settings_handler.handle_settings),+ "set_cwd": self.command_handler.handle_set_cwd,+ "settings": self.settings_handler.handle_settings,"stop": self.command_handler.handle_stop,"bind": self.command_handler.handle_bind,}diff --git a/core/handlers/message_handler.py b/core/handlers/message_handler.pyindex 18aa670f3..209906b46 100644--- a/core/handlers/message_handler.py+++ b/core/handlers/message_handler.py@@ -301,20 +301,10 @@ class MessageHandler:settings_handler = SettingsHandler(self.controller)command_handlers = CommandHandlers(self.controller)- # --- Admin permission check for protected operations ---- admin_protected = ("cmd_settings", "cmd_routing", "cmd_change_cwd", "vibe_update_now")- if any(callback_data.startswith(p) for p in admin_protected):- store = self.settings_manager.store- # Only enforce if at least one admin exists (backward compat)- if store.has_any_admin() and not store.is_admin(context.user_id):- logger.info(f"Permission denied: {context.user_id} attempted {callback_data}")- try:- await self.im_client.send_message(context, self._t("permission.adminOnly"))- except Exception:- pass- return-# Route based on callback data+ # Note: admin permission for protected callbacks is enforced by+ # the centralized auth pipeline (core.auth.check_auth) in IM+ # entry points before reaching this handler.if callback_data.startswith("toggle_msg_"):# Toggle message type visibilitymsg_type = callback_data.replace("toggle_msg_", "")diff --git a/modules/im/discord.py b/modules/im/discord.pyindex 7364a76fd..f34d840da 100644--- a/modules/im/discord.py+++ b/modules/im/discord.py@@ -9,6 +9,7 @@ import discordfrom .base import BaseIMClient, MessageContext, InlineKeyboard, InlineButton, FileAttachmentfrom config.v2_config import DiscordConfig+from core.auth import check_authfrom .formatters import DiscordFormatterfrom vibe.i18n import get_supported_languages, t as i18n_tfrom modules.agents.opencode.utils import (@@ -400,6 +401,29 @@ class DiscordBot(BaseIMClient):except Exception as err:logger.debug("Failed to send unauthorized message: %s", err)+ async def _send_auth_denial(self, channel_id: str, user_id: str, auth_result, interaction=None):+ """Send denial message for failed auth check."""+ if auth_result.denial == "unbound_dm":+ hint = self._t("bind.dmNotBound", channel_id)+ if interaction:+ try:+ await interaction.response.send_message(hint, ephemeral=True)+ except Exception:+ pass+ else:+ channel = self.client.get_channel(int(channel_id))+ if channel:+ await channel.send(content=hint)+ elif auth_result.denial == "unauthorized_channel":+ await self._send_unauthorized_message(channel_id)+ elif auth_result.denial == "not_admin":+ msg = i18n_t("permission.adminOnly")+ if interaction:+ try:+ await interaction.response.send_message(msg, ephemeral=True)+ except Exception:+ pass+async def _maybe_create_thread(self, message: discord.Message) -> Optional[discord.Thread]:if isinstance(message.channel, discord.Thread):return message.channel@@ -452,27 +476,18 @@ class DiscordBot(BaseIMClient):# Determine if this is a DMis_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+ # Centralized auth check+ action = "bind" if (content.startswith("/bind ") or content == "/bind") else ""+ auth_result = check_auth(+ user_id=str(message.author.id),+ channel_id=channel_id,+ is_dm=is_dm,+ action=action,+ store=self.settings_manager.store if self.settings_manager else None,+ )+ if not auth_result.allowed:+ await self._send_auth_denial(channel_id, str(message.author.id), auth_result)+ return# Mention logic for guild channelseffective_require_mention = self.config.require_mention@@ -1495,10 +1510,18 @@ class _PersistentStartView(discord.ui.View):guild_id = str(interaction.guild_id) if interaction.guild_id else Noneif guild_id and not self.outer._is_allowed_guild(guild_id):return- # Skip channel auth for DM interactions (authorized via bind system)is_dm = interaction.guild is None or isinstance(interaction.channel, discord.DMChannel)- if not is_dm and not await self.outer._is_authorized_channel(channel_id):- await self.outer._send_unauthorized_message(channel_id)+ auth_result = check_auth(+ user_id=str(interaction.user.id),+ channel_id=channel_id,+ is_dm=is_dm,+ action=data,+ store=self.outer.settings_manager.store if self.outer.settings_manager else None,+ )+ if not auth_result.allowed:+ await self.outer._send_auth_denial(+ channel_id, str(interaction.user.id), auth_result, interaction=interaction+ )returncontext = MessageContext(user_id=str(interaction.user.id),@@ -1552,17 +1575,6 @@ class _DiscordButtonView(discord.ui.View):"cmd_routing","cmd_resume",}- if data.startswith("vibe_update_now") and interaction.guild:- is_owner = interaction.user.id == interaction.guild.owner_id- is_admin = getattr(interaction.user, "guild_permissions", None)- if not (is_owner or (is_admin and is_admin.administrator)):- try:- await interaction.response.send_message(- "You do not have permission to run updates.", ephemeral=True- )- except Exception:- pass- returnif data == "opencode_question:open_modal":try:await interaction.response.defer(ephemeral=True)@@ -1577,10 +1589,18 @@ class _DiscordButtonView(discord.ui.View):guild_id = str(interaction.guild_id) if interaction.guild_id else Noneif guild_id and not self.outer._is_allowed_guild(guild_id):return- # Skip channel auth for DM interactionsis_dm = interaction.guild is None or isinstance(interaction.channel, discord.DMChannel)- if not is_dm and not await self.outer._is_authorized_channel(channel_id):- await self.outer._send_unauthorized_message(channel_id)+ auth_result = check_auth(+ user_id=str(interaction.user.id),+ channel_id=channel_id,+ is_dm=is_dm,+ action=data,+ store=self.outer.settings_manager.store if self.outer.settings_manager else None,+ )+ if not auth_result.allowed:+ await self.outer._send_auth_denial(+ channel_id, str(interaction.user.id), auth_result, interaction=interaction+ )returncontext = MessageContext(user_id=str(interaction.user.id),diff --git a/modules/im/feishu.py b/modules/im/feishu.pyindex 561303afa..86814f942 100644--- a/modules/im/feishu.py+++ b/modules/im/feishu.py@@ -258,6 +258,18 @@ class FeishuBot(BaseIMClient):except Exception as exc:logger.error("Failed to send unauthorized message to %s: %s", channel_id, exc)+ async def _send_auth_denial(self, chat_id: str, user_id: str, auth_result):+ """Send denial message for failed auth check."""+ ctx = MessageContext(user_id="system", channel_id=chat_id)+ if auth_result.denial == "unbound_dm":+ hint = self._t("bind.dmNotBound", chat_id)+ await self.send_message(ctx, hint)+ elif auth_result.denial == "unauthorized_channel":+ await self._send_unauthorized_message(chat_id)+ elif auth_result.denial == "not_admin":+ msg = i18n_t("permission.adminOnly")+ await self.send_message(ctx, msg)+# ------------------------------------------------------------------# Sending messages# ------------------------------------------------------------------@@ -1107,26 +1119,22 @@ class FeishuBot(BaseIMClient):else:return- # DM (p2p) authorization gate: require user to be bound for DM access- if is_p2p and self.settings_manager:- store = self.settings_manager.store- if not store.is_bound_user(user_id):- # Allow /bind command through for unbound users- if text.startswith("/bind ") or text == "/bind":- pass # Will be handled by command routing below- else:- try:- hint_ctx = MessageContext(user_id="system", channel_id=chat_id)- hint = self._t("bind.dmNotBound", chat_id)- await self.send_message(hint_ctx, hint)- except Exception as exc:- logger.error("Failed to send DM bind hint: %s", exc)- return+ # Centralized auth check+ from core.auth import check_auth- # 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)+ _action = "bind" if (text.startswith("/bind ") or text == "/bind") else ""+ auth_result = check_auth(+ user_id=user_id,+ channel_id=chat_id,+ is_dm=is_p2p,+ action=_action,+ store=self.settings_manager.store if self.settings_manager else None,+ )+ if not auth_result.allowed:+ try:+ await self._send_auth_denial(chat_id, user_id, auth_result)+ except Exception as exc:+ logger.error("Failed to send auth denial: %s", exc)return# Determine thread ID: use root_id if in thread, else use message_id as thread root@@ -1224,15 +1232,30 @@ class FeishuBot(BaseIMClient):if self._is_duplicate_event(dedup_key):return- # --- Channel authorization ---- # Use positive DM lookup instead of fragile heuristics.- # _dm_chat_ids is populated from real p2p messages and persisted- # user settings, so it reliably identifies DM chats.+ # --- Centralized auth check ---is_dm = chat_id in self._dm_chat_ids- if not is_dm:- if not chat_id or not await self._is_authorized_channel(chat_id):- logger.info("Card action from unauthorized/unknown channel %s, ignoring", chat_id)- return+ _card_action = button_name if form_value is not None else (callback_data or "")+ from core.auth import check_auth++ auth_result = check_auth(+ user_id=user_id,+ channel_id=chat_id,+ is_dm=is_dm,+ action=_card_action,+ store=self.settings_manager.store if self.settings_manager else None,+ )+ if not auth_result.allowed:+ if auth_result.denial == "not_admin":+ logger.info("Permission denied: %s attempted card action %s", user_id, _card_action)+ else:+ logger.info(+ "Card action from unauthorized context %s (denial=%s), ignoring", chat_id, auth_result.denial+ )+ try:+ await self._send_auth_denial(chat_id, user_id, auth_result)+ except Exception as exc:+ logger.error("Failed to send card auth denial: %s", exc)+ returncontext = MessageContext(user_id=user_id,@@ -1253,16 +1276,6 @@ class FeishuBot(BaseIMClient):# --- Form submissions (action_type: form_submit) ---if form_value is not None:- # Admin-only form submissions: settings, CWD, routing- # Feishu cards are shared in the channel, so any member can- # submit them — enforce admin check here.- admin_forms = ("cwd_submit", "settings_submit", "routing_backend_select", "routing_submit")- if button_name in admin_forms and self.settings_manager:- store = self.settings_manager.store- if store.has_any_admin() and not store.is_admin(user_id):- logger.info("Permission denied: %s attempted form %s", user_id, button_name)- return-if button_name == "cwd_submit":await self._handle_cwd_form_submit(context, form_value)elif button_name == "settings_submit":diff --git a/modules/im/slack.py b/modules/im/slack.pyindex 0075b90fb..d374954c5 100644--- a/modules/im/slack.py+++ b/modules/im/slack.py@@ -13,6 +13,7 @@ from markdown_to_mrkdwn import SlackMarkdownConverterfrom .base import BaseIMClient, MessageContext, InlineKeyboard, InlineButton, FileAttachmentfrom config.v2_config import SlackConfig+from core.auth import check_auth, AuthResultfrom .formatters import SlackFormatterfrom vibe.i18n import get_supported_languages, t as i18n_tfrom modules.agents.opencode.utils import (@@ -894,27 +895,18 @@ class SlackBot(BaseIMClient):logger.debug(f"No settings_manager, ignoring thread message: '{text}'")return- # DM authorization gate: require user to be bound for DM access- if channel_id.startswith("D") and self.settings_manager:- store = self.settings_manager.store- if not store.is_bound_user(user_id):- # Allow /bind command through for unbound users- if text.startswith("/bind ") or text == "/bind":- pass # Will be handled by command routing below- else:- try:- self._ensure_clients()- hint = self._t("bind.dmNotBound", channel_id)- await self.web_client.chat_postMessage(channel=channel_id, text=hint)- except Exception as e:- logger.error(f"Failed to send DM bind hint: {e}")- return-- # 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)+ # Centralized auth gate+ is_dm = channel_id.startswith("D")+ auth_action = "bind" if (text.startswith("/bind ") or text == "/bind") else ""+ auth = check_auth(+ user_id=user_id,+ channel_id=channel_id,+ is_dm=is_dm,+ action=auth_action,+ store=self.settings_manager.store if self.settings_manager else None,+ )+ if not auth.allowed:+ await self._send_auth_denial(channel_id, user_id, auth)return# Now extract shared/forwarded message content (after authorization)@@ -972,10 +964,17 @@ class SlackBot(BaseIMClient):# Handle @mentionschannel_id = event.get("channel")- # Check if channel is authorized based on whitelist- if not await self._is_authorized_channel(channel_id):- logger.info(f"Unauthorized mention from channel: {channel_id}")- await self._send_unauthorized_message(channel_id)+ # Centralized auth gate (app_mention is always in a channel, not DM)+ user_id_mention = event.get("user")+ auth = check_auth(+ user_id=user_id_mention or "",+ channel_id=channel_id,+ is_dm=False,+ action="",+ store=self.settings_manager.store if self.settings_manager else None,+ )+ if not auth.allowed:+ await self._send_auth_denial(channel_id, user_id_mention or "", auth)return# For Slack: if no thread_ts, use the message's own ts as thread_id (start of thread)@@ -1046,32 +1045,20 @@ class SlackBot(BaseIMClient):"""Handle native Slack slash commands"""command = payload.get("command", "").lstrip("/")channel_id = payload.get("channel_id")+ user_id = payload.get("user_id", "")+ response_url = payload.get("response_url")- # Check if channel is authorized based on whitelist- # Skip channel auth for DM channels (authorized via bind system)+ # Centralized auth gateis_dm = isinstance(channel_id, str) and channel_id.startswith("D")- if is_dm:- # DM slash commands require the user to be bound (except /bind itself)- user_id = payload.get("user_id", "")- if self.settings_manager and command != "bind":- store = self.settings_manager.store- if not store.is_bound_user(user_id):- response_url = payload.get("response_url")- if response_url:- await self.send_slash_response(- response_url,- f"🔑 {self._t('bind.dmNotBound', channel_id)}",- )- return- elif not await self._is_authorized_channel(channel_id):- logger.info(f"Unauthorized slash command from channel: {channel_id}")- # Send a response to user about unauthorized channel- response_url = payload.get("response_url")- if response_url:- await self.send_slash_response(- response_url,- f"❌ {self._t('error.channelNotEnabled', channel_id)}",- )+ auth = check_auth(+ user_id=user_id,+ channel_id=channel_id,+ is_dm=is_dm,+ action=command,+ store=self.settings_manager.store if self.settings_manager else None,+ )+ if not auth.allowed:+ await self._send_auth_denial(channel_id, user_id, auth, response_url=response_url)return# Map Slack slash commands to internal commands@@ -1096,7 +1083,6 @@ class SlackBot(BaseIMClient):)# Send immediate acknowledgment to Slack- response_url = payload.get("response_url")# Try to handle as registered commandif actual_command in self.on_command_callbacks:@@ -1134,23 +1120,6 @@ class SlackBot(BaseIMClient):actions = payload.get("actions", [])view = payload.get("view", {})- # 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:- await handle_update_button_click(self._controller, payload)- return-# In Slack modals, `channel` is often missing. We store the originating# channel_id in `view.private_metadata` when opening the modal.channel_id = payload.get("channel", {}).get("id") or payload.get("container", {}).get("channel_id")@@ -1168,18 +1137,34 @@ class SlackBot(BaseIMClient):# Fallback: treat private_metadata as channel_id directly (legacy behavior)channel_id = private_metadata- # Check if channel is authorized for interactive components- # Skip channel auth for DM channels (authorized via bind system)+ # Determine the primary action for auth check+ primary_action = actions[0].get("action_id", "") if actions else ""++ # Centralized auth gateis_dm = isinstance(channel_id, str) and channel_id.startswith("D")- if not is_dm and not await self._is_authorized_channel(channel_id):- logger.info(f"Unauthorized interactive action from channel: {channel_id}")+ auth = check_auth(+ user_id=user.get("id", ""),+ channel_id=channel_id or "",+ is_dm=is_dm,+ action=primary_action,+ store=self.settings_manager.store if self.settings_manager else None,+ )+ if not auth.allowed:try:- await self._send_unauthorized_message(channel_id)+ await self._send_auth_denial(channel_id or "", user.get("id", ""), auth)except Exception as e:- logger.debug("Failed to send unauthorized message to channel %s: %s", channel_id, e)+ logger.debug("Failed to send auth denial to channel %s: %s", channel_id, e)return- view = payload.get("view", {})+ # Handle update button click+ for action in actions:+ if action.get("action_id") == "vibe_update_now":+ from core.update_checker import handle_update_button_click++ if hasattr(self, "_controller") and self._controller:+ await handle_update_button_click(self._controller, payload)+ return+for action in actions:action_type = action.get("type")if action_type == "button":@@ -3182,6 +3167,34 @@ class SlackBot(BaseIMClient):logger.info("Channel not enabled in settings.json: %s", channel_id)return False+ async def _send_auth_denial(self, channel_id: str, user_id: str, auth: AuthResult, response_url: str = None):+ """Send appropriate denial message based on auth result."""+ if auth.denial == "unbound_dm":+ hint = self._t("bind.dmNotBound", channel_id)+ if response_url:+ await self.send_slash_response(response_url, f"🔑 {hint}")+ else:+ try:+ self._ensure_clients()+ await self.web_client.chat_postMessage(channel=channel_id, text=hint)+ except Exception as e:+ logger.error(f"Failed to send DM bind hint: {e}")+ elif auth.denial == "unauthorized_channel":+ if response_url:+ await self.send_slash_response(response_url, f"❌ {self._t('error.channelNotEnabled', channel_id)}")+ else:+ await self._send_unauthorized_message(channel_id)+ elif auth.denial == "not_admin":+ msg = i18n_t("permission.adminOnly")+ if response_url:+ await self.send_slash_response(response_url, msg)+ else:+ try:+ self._ensure_clients()+ await self.web_client.chat_postMessage(channel=channel_id, text=msg)+ except Exception as e:+ logger.error(f"Failed to send admin denial: {e}")+async def _send_unauthorized_message(self, channel_id: str):"""Send unauthorized access message to channel"""try: