from __future__ import annotations import logging logger = logging.getLogger(__name__) class DingTalkSecurity: def __init__(self, dm_policy: str = "open", group_policy: str = "open"): self._dm_policy = dm_policy self._group_policy = group_policy self._allowlist: set[str] = set() self._group_allowlist: set[str] = set() @property def dm_policy(self) -> str: return self._dm_policy def resolve_dm_policy(self) -> str: return self._dm_policy def check_allowlist(self, user_id: str) -> bool: if self._dm_policy == "open": return True return user_id in self._allowlist def check_dm_access(self, sender_id: str) -> tuple[bool, str]: if self._dm_policy == "disabled": return False, "DM is disabled" if self._dm_policy == "open": return True, "open" if self._dm_policy == "allowlist": if sender_id in self._allowlist: return True, "allowlist" return False, f"sender {sender_id} not in allowlist" if self._dm_policy == "pairing": return True, "pairing" return False, f"unknown dm_policy: {self._dm_policy}" def check_group_access(self, conversation_id: str) -> tuple[bool, str]: if self._group_policy == "open": return True, "open" if self._group_policy == "disabled": return False, "group access disabled" if self._group_policy == "allowlist": if conversation_id in self._group_allowlist: return True, "allowlist" return False, f"group {conversation_id} not in allowlist" return False, f"unknown group_policy: {self._group_policy}" def add_to_allowlist(self, user_id: str) -> None: self._allowlist.add(user_id) def remove_from_allowlist(self, user_id: str) -> None: self._allowlist.discard(user_id) def load_allowlist(self, allow_from: list[str]) -> None: self._allowlist = set(allow_from) def add_group_to_allowlist(self, conversation_id: str) -> None: self._group_allowlist.add(conversation_id) def remove_group_from_allowlist(self, conversation_id: str) -> None: self._group_allowlist.discard(conversation_id)