73 lines
2.6 KiB
Python
73 lines
2.6 KiB
Python
from __future__ import annotations
|
|
|
|
from typing import Any
|
|
|
|
from .allowlist import is_likely_bot, match_user_in_list
|
|
from .rooms_config import get_room_users
|
|
|
|
|
|
class MatrixSecurityPolicy:
|
|
def __init__(self, config: dict[str, Any]):
|
|
self._config = config
|
|
self._dm_policy = config.get("dm", {}).get("policy", "pairing")
|
|
self._dm_allow_from = config.get("dm", {}).get("allowFrom", [])
|
|
self._group_policy = config.get("groupPolicy", "allowlist")
|
|
self._group_allow_from = config.get("groupAllowFrom", [])
|
|
self._allow_bots = config.get("allowBots")
|
|
self._allowlist_only = config.get("allowlistOnly", False)
|
|
self._context_visibility = config.get("contextVisibility", "all")
|
|
|
|
def evaluate_dm_access(self, sender_id: str) -> bool:
|
|
if self._allowlist_only:
|
|
return match_user_in_list(sender_id, self._dm_allow_from)
|
|
if self._dm_policy == "open":
|
|
return True
|
|
if self._dm_policy == "disabled":
|
|
return False
|
|
if self._dm_policy == "allowlist":
|
|
return match_user_in_list(sender_id, self._dm_allow_from)
|
|
if self._dm_policy == "pairing":
|
|
return match_user_in_list(sender_id, self._dm_allow_from)
|
|
return False
|
|
|
|
def evaluate_group_access(self, sender_id: str, room_id: str) -> bool:
|
|
room_users = get_room_users(room_id, self._config)
|
|
if room_users:
|
|
return match_user_in_list(sender_id, room_users)
|
|
|
|
if self._allowlist_only:
|
|
return match_user_in_list(sender_id, self._group_allow_from)
|
|
if self._group_policy == "open":
|
|
return True
|
|
if self._group_policy == "disabled":
|
|
return False
|
|
if self._group_policy == "allowlist":
|
|
return match_user_in_list(sender_id, self._group_allow_from)
|
|
return False
|
|
|
|
def should_skip_bot(self, sender_id: str) -> bool:
|
|
if self._allow_bots is None:
|
|
return False
|
|
if self._allow_bots is True:
|
|
return False
|
|
return is_likely_bot(sender_id)
|
|
|
|
def is_context_visible(self, chat_type: str) -> bool:
|
|
if self._context_visibility == "all":
|
|
return True
|
|
if self._context_visibility == "none":
|
|
return False
|
|
if self._context_visibility == "dm":
|
|
return chat_type == "direct"
|
|
if self._context_visibility == "group":
|
|
return chat_type == "group"
|
|
return True
|
|
|
|
@property
|
|
def allowlist_only(self) -> bool:
|
|
return self._allowlist_only
|
|
|
|
@property
|
|
def context_visibility(self) -> str:
|
|
return self._context_visibility
|