Skip to content

The agent that grows with you

refactor(gateway): unify pairing allowlist writes/json IO, split _build_slack, extract authz own-policy helpers

Teknium24fd09be1061
diff --git a/gateway/authz_mixin.py b/gateway/authz_mixin.py
index 04094779a0e..82f5ce28afc 100644
--- a/gateway/authz_mixin.py
+++ b/gateway/authz_mixin.py
@@ -22,6 +22,7 @@ from gateway.whatsapp_identity import (
)
_GROUP_CHAT_TYPES = frozenset({"group", "forum", "channel"})
+_GROUP_FORUM_TYPES = frozenset({"group", "forum"})
_TRUTHY = frozenset({"true", "1", "yes"})
# Platform -> ``<PLATFORM>_ALLOWED_USERS`` / ``<PLATFORM>_ALLOW_ALL_USERS``.
@@ -70,6 +71,10 @@ def _platform_gate_env(name: str, default: str = "") -> str:
_auth_env = _platform_gate_env
+def _env_truthy(name: str) -> bool:
+ return _auth_env(name).lower() in _TRUTHY
+
+
def _registry_entry(platform):
"""Platform-registry entry for a (plugin) platform, or None."""
if platform is None:
@@ -82,18 +87,6 @@ def _registry_entry(platform):
return None
-def _platform_declares_allowed_users_env(platform) -> bool:
- """Whether a plugin platform's registry entry declares ``allowed_users_env``.
-
- Such platforms (Buzz, DingTalk, ...) document ``PlatformConfig.extra
- .allowed_users`` as the config-file spelling of that env allowlist, so the
- live adapter's extra is a valid authorization source when the env var is
- absent. Built-in platforms and unknown entries return False.
- """
- entry = _registry_entry(platform)
- return bool(entry and entry.allowed_users_env)
-
-
def _coerce_allow_set(raw) -> set[str]:
"""Parse an allowlist (YAML list or comma-separated scalar) into a set of strings."""
if raw is None:
@@ -107,6 +100,10 @@ def _allows(allowed: set[str], candidate: Optional[str]) -> bool:
return "*" in allowed or candidate in allowed
+def _adapter_config_extra(adapter) -> dict:
+ return getattr(getattr(adapter, "config", None), "extra", None) or {}
+
+
# ---------------------------------------------------------------------------
# Nostr npub -> hex (Buzz). ``BUZZ_ALLOWED_USERS`` accepts hex or ``npub1…``
# but inbound pubkeys are always hex, so npub entries must be decoded.
@@ -186,6 +183,9 @@ class GatewayAuthorizationMixin:
# ``getattr(self, ...)`` throughout: test helpers build bare runners via
# ``object.__new__`` without ``adapters`` / ``config`` (pitfalls.md #17).
+ def _primary_adapters(self) -> dict:
+ return getattr(self, "adapters", None) or {}
+
def _authorization_adapter(
self,
platform: Optional[Platform],
@@ -218,12 +218,12 @@ class GatewayAuthorizationMixin:
except Exception:
primary_profile = None
if profile_name == primary_profile:
- return (getattr(self, "adapters", None) or {}).get(platform)
+ return self._primary_adapters().get(platform)
# Fail closed: a stamped secondary profile with no registry entry
# (adapter failed to connect) must NOT fall back to the default
# profile's adapter -- that sends replies out the wrong bot.
return None
- return (getattr(self, "adapters", None) or {}).get(platform)
+ return self._primary_adapters().get(platform)
def _adapter_for_source(self, source: Optional[SessionSource]):
"""Resolve the live adapter for an inbound ``SessionSource``."""
@@ -238,7 +238,7 @@ class GatewayAuthorizationMixin:
# not register their own, so a profile-aware lookup would silently
# disable streaming/typing/tool progress.
if getattr(source, "delivered_via_upstream_relay", False) is True:
- return (getattr(self, "adapters", None) or {}).get(Platform.RELAY)
+ return self._primary_adapters().get(Platform.RELAY)
# ``getattr``: test fixtures build bare SimpleNamespace sources without ``profile``.
return self._authorization_adapter(
getattr(source, "platform", None),
@@ -247,7 +247,7 @@ class GatewayAuthorizationMixin:
def _owning_profile(self, adapter, platform):
"""Return (registered, profile) for a live adapter: profile is None for primary."""
- if adapter is (getattr(self, "adapters", None) or {}).get(platform):
+ if adapter is self._primary_adapters().get(platform):
return True, None
for profile, profile_adapters in (getattr(self, "_profile_adapters", None) or {}).items():
if adapter is profile_adapters.get(platform):
@@ -341,6 +341,11 @@ class GatewayAuthorizationMixin:
value = self._config_extra(platform).get(extra_key)
return value
+ def _adapter_policy(self, platform, attr: str, extra_key: str, profile) -> str:
+ if not platform:
+ return ""
+ return str(self._adapter_setting(platform, attr, extra_key, profile) or "").strip().lower()
+
def _adapter_dm_policy(
self,
platform: Optional[Platform],
@@ -353,10 +358,7 @@ class GatewayAuthorizationMixin:
``allowlist`` case; ``open`` forwards everyone and ``pairing`` forwards
unpaired DMs for the handshake.
"""
- if not platform:
- return ""
- policy = self._adapter_setting(platform, "_dm_policy", "dm_policy", profile)
- return str(policy or "").strip().lower()
+ return self._adapter_policy(platform, "_dm_policy", "dm_policy", profile)
def _adapter_group_policy(
self,
@@ -365,10 +367,7 @@ class GatewayAuthorizationMixin:
profile: Optional[str] = None,
) -> str:
"""Lowercased effective ``group_policy`` (open/allowlist/disabled), ``""`` if unknown."""
- if not platform:
- return ""
- policy = self._adapter_setting(platform, "_group_policy", "group_policy", profile)
- return str(policy or "").strip().lower()
+ return self._adapter_policy(platform, "_group_policy", "group_policy", profile)
def _adapter_group_has_sender_allowlist(
self,
@@ -393,12 +392,10 @@ class GatewayAuthorizationMixin:
group_cfg = groups.get(chat_id_str)
if not isinstance(group_cfg, dict):
lowered = chat_id_str.lower()
- for key, value in groups.items():
- if isinstance(key, str) and key.lower() == lowered and isinstance(value, dict):
- group_cfg = value
- break
- if not isinstance(group_cfg, dict):
- group_cfg = groups.get("*")
+ group_cfg = next(
+ (v for k, v in groups.items() if isinstance(k, str) and k.lower() == lowered and isinstance(v, dict)),
+ groups.get("*"),
+ )
if not isinstance(group_cfg, dict):
return False
@@ -418,10 +415,62 @@ class GatewayAuthorizationMixin:
return getattr(self, "pairing_store", None)
def _adapter_extra_for_source(self, source) -> dict:
+ return _adapter_config_extra(self._adapter_for_source(source))
+
+ def _own_policy_authorizes(self, source, user_id, is_group, adapter_profile) -> Optional[bool]:
+ """Own-policy adapter verdict when no env allowlist exists; None = no verdict.
+
+ Trusted only when the effective policy for THIS chat type is ``allowlist``:
+ ``open`` forwards EVERY sender (the fail-open SECURITY.md §2.6 forbids),
+ ``disabled`` never forwards, ``pairing`` forwards unpaired DMs for the
+ handshake (already denied by the pairing-store check). Anything else falls
+ through to default-deny; GATEWAY_ALLOW_ALL_USERS, the per-platform
+ ALLOW_ALL flag and pairing stay the explicit opt-ins.
+ """
+ if is_group:
+ if self._adapter_group_has_sender_allowlist(source.platform, source.chat_id, profile=adapter_profile):
+ return True
+ effective_policy = self._adapter_group_policy(source.platform, profile=adapter_profile)
+ else:
+ effective_policy = self._adapter_dm_policy(source.platform, profile=adapter_profile)
+ if effective_policy != "allowlist":
+ return None
+ # Re-check DMs against the live adapter when it exposes ``_is_dm_allowed``:
+ # pairing revoke can clear WHATSAPP_ALLOWED_USERS while a construction-time
+ # ``_allow_from`` snapshot would keep authorizing until restart. Adapters
+ # without the helper keep the historical "reached the gateway under
+ # allowlist policy" rubber-stamp.
+ if not is_group:
+ adapter = self._authorization_adapter(source.platform, profile=adapter_profile)
+ dm_check = getattr(adapter, "_is_dm_allowed", None) if adapter is not None else None
+ if callable(dm_check):
+ return bool(dm_check(user_id))
+ return True
+
+ def _adapter_extra_allowlist_authorizes(self, source, user_id, is_group) -> bool:
+ """Adapters (e.g. Telegram) that gate via config.extra.allow_from / group_allow_from
+ without setting enforces_own_access_policy."""
adapter = self._adapter_for_source(source)
if adapter is None:
- return {}
- return getattr(getattr(adapter, "config", None), "extra", None) or {}
+ return False
+ extra = _adapter_config_extra(adapter)
+ adapter_allow = extra.get("group_allow_from" if is_group else "allow_from")
+ if not adapter_allow:
+ # Plugin platforms (Buzz, DingTalk, ...) document ``extra.allowed_users`` as
+ # the config-file spelling of their env allowlist. Under multiplex the
+ # YAML->env bridge is first-writer-wins, so only the default profile's list
+ # reaches the env read; consult the live profile-routed adapter instead.
+ entry = _registry_entry(source.platform)
+ if entry and entry.allowed_users_env:
+ adapter_allow = extra.get("allowed_users")
+ if not adapter_allow:
+ return False
+ allowed = _coerce_allow_set(adapter_allow)
+ normalize = getattr(adapter, "normalize_user_id", None)
+ if callable(normalize):
+ # Ids and entries may spell the same principal differently (Buzz hex vs npub).
+ allowed = {normalize(entry) or entry for entry in allowed}
+ return _allows(allowed, user_id)
def _is_user_authorized(
self,
@@ -444,6 +493,7 @@ class GatewayAuthorizationMixin:
adapter_profile = self._adapter_profile_for_source(source)
is_group = source.chat_type in _GROUP_CHAT_TYPES
+ is_group_or_forum = source.chat_type in _GROUP_FORUM_TYPES
# Trusted-upstream delegation (relay): the Team Gateway connector
# authenticates this gateway's WS and resolves owner-only author
@@ -478,12 +528,8 @@ class GatewayAuthorizationMixin:
# observe-unmentioned mode strips user_id from triggered group
# messages, so the env-only check above misses config allowlists.
try:
- adapter_group_allowed = self._adapter_extra_for_source(source).get(
- "group_allowed_chats"
- )
- if adapter_group_allowed and _allows(
- _coerce_allow_set(adapter_group_allowed), source.chat_id
- ):
+ adapter_group_allowed = self._adapter_extra_for_source(source).get("group_allowed_chats")
+ if adapter_group_allowed and _allows(_coerce_allow_set(adapter_group_allowed), source.chat_id):
return True
except Exception:
pass
@@ -499,21 +545,17 @@ class GatewayAuthorizationMixin:
if not user_id:
return False
- platform_env_map = dict(_ALLOWED_USERS_ENV)
- platform_allow_all_map = dict(_ALLOW_ALL_ENV)
- if source.platform not in platform_env_map:
+ platform_allow_env = _ALLOWED_USERS_ENV.get(source.platform, "")
+ platform_allow_all_var = _ALLOW_ALL_ENV.get(source.platform, "")
+ if source.platform not in _ALLOWED_USERS_ENV:
+ entry = _registry_entry(source.platform)
try:
- entry = _registry_entry(source.platform)
- if entry:
- if entry.allowed_users_env:
- platform_env_map[source.platform] = entry.allowed_users_env
- if entry.allow_all_env:
- platform_allow_all_map[source.platform] = entry.allow_all_env
+ platform_allow_env = getattr(entry, "allowed_users_env", "") or platform_allow_env
+ platform_allow_all_var = getattr(entry, "allow_all_env", "") or platform_allow_all_var
except Exception:
pass
- platform_allow_all_var = platform_allow_all_map.get(source.platform, "")
- if platform_allow_all_var and _auth_env(platform_allow_all_var).lower() in _TRUTHY:
+ if platform_allow_all_var and _env_truthy(platform_allow_all_var):
return True
# Adapter-verified role auth (Discord confirmed DISCORD_ALLOWED_ROLES
@@ -530,86 +572,38 @@ class GatewayAuthorizationMixin:
if pairing_store is not None and pairing_store.is_approved(platform_name, user_id):
return True
- platform_allowlist = _auth_env(platform_env_map.get(source.platform, ""))
+ platform_allowlist = _auth_env(platform_allow_env)
group_user_allowlist = ""
group_chat_allowlist = ""
- if source.chat_type in {"group", "forum"}:
+ if is_group_or_forum:
group_user_allowlist = _auth_env(_GROUP_USER_ENV.get(source.platform, ""))
group_chat_allowlist = _auth_env(_GROUP_CHAT_ENV.get(source.platform, ""))
global_allowlist = _auth_env("GATEWAY_ALLOWED_USERS")
- if not platform_allowlist and not group_user_allowlist and not group_chat_allowlist and not global_allowlist:
- # No env allowlist. Own-policy adapters gate at intake, but their
- # decision is only trusted when the effective policy for THIS chat
- # type is ``allowlist``: ``open`` forwards EVERY sender (trusting it
- # is the fail-open SECURITY.md §2.6 forbids), ``disabled`` never
- # forwards, ``pairing`` forwards unpaired DMs for the handshake
- # (already denied by the pairing-store check above). Anything else
- # falls through to default-deny; GATEWAY_ALLOW_ALL_USERS, the
- # per-platform ALLOW_ALL flag and pairing stay the explicit opt-ins.
+ if not (platform_allowlist or group_user_allowlist or group_chat_allowlist or global_allowlist):
+ # No env allowlist: own-policy adapters gate at intake (see _own_policy_authorizes).
if allow_adapter_delegation and self._adapter_enforces_own_access_policy(
source.platform, profile=adapter_profile
):
- if is_group:
- effective_policy = self._adapter_group_policy(source.platform, profile=adapter_profile)
- if self._adapter_group_has_sender_allowlist(
- source.platform, source.chat_id, profile=adapter_profile
- ):
- return True
- else:
- effective_policy = self._adapter_dm_policy(source.platform, profile=adapter_profile)
- if effective_policy == "allowlist":
- # Re-check DMs against the live adapter when it exposes
- # ``_is_dm_allowed``: pairing revoke can clear
- # WHATSAPP_ALLOWED_USERS while a construction-time
- # ``_allow_from`` snapshot would keep authorizing until
- # restart. Adapters without the helper keep the historical
- # "reached the gateway under allowlist policy" rubber-stamp.
- if not is_group:
- adapter = self._authorization_adapter(source.platform, profile=adapter_profile)
- dm_check = getattr(adapter, "_is_dm_allowed", None) if adapter is not None else None
- if callable(dm_check):
- return bool(dm_check(user_id))
- return True
- # Adapters (e.g. Telegram) that gate via config.extra.allow_from /
- # group_allow_from without setting enforces_own_access_policy.
- adapter = self._adapter_for_source(source)
- if adapter is not None:
- extra = getattr(getattr(adapter, "config", None), "extra", None) or {}
- adapter_allow = extra.get("group_allow_from" if is_group else "allow_from")
- if not adapter_allow and _platform_declares_allowed_users_env(source.platform):
- # Plugin platforms (Buzz) carry the env allowlist as
- # ``extra.allowed_users``. Under multiplex the YAML->env
- # bridge is first-writer-wins, so only the default profile's
- # list reaches the env read above; consult the live
- # profile-routed adapter's config instead.
- adapter_allow = extra.get("allowed_users")
- if adapter_allow:
- allowed = _coerce_allow_set(adapter_allow)
- normalize = getattr(adapter, "normalize_user_id", None)
- if callable(normalize):
- # Ids and entries may spell the same principal
- # differently (Buzz hex vs npub).
- allowed = {normalize(entry) or entry for entry in allowed}
- if _allows(allowed, user_id):
- return True
- return _auth_env("GATEWAY_ALLOW_ALL_USERS").lower() in _TRUTHY
+ verdict = self._own_policy_authorizes(source, user_id, is_group, adapter_profile)
+ if verdict is not None:
+ return verdict
+ if self._adapter_extra_allowlist_authorizes(source, user_id, is_group):
+ return True
+ return _env_truthy("GATEWAY_ALLOW_ALL_USERS")
# Telegram group traffic authorized by chat ID (separate from
# TELEGRAM_GROUP_ALLOWED_USERS, which gates the sender).
- if group_chat_allowlist and source.chat_type in {"group", "forum"} and source.chat_id:
- if _allows(_coerce_allow_set(group_chat_allowlist), source.chat_id):
- return True
+ if (
+ group_chat_allowlist and is_group_or_forum and source.chat_id
+ and _allows(_coerce_allow_set(group_chat_allowlist), source.chat_id)
+ ):
+ return True
# Backward-compat: TELEGRAM_GROUP_ALLOWED_USERS was once (mis)used as a
# chat-ID allowlist. "-"-prefixed values are chat IDs, so honor them as
# such and warn once; the correct var is TELEGRAM_GROUP_ALLOWED_CHATS.
- if (
- source.platform == Platform.TELEGRAM
- and group_user_allowlist
- and source.chat_type in {"group", "forum"}
- and source.chat_id
- ):
+ if source.platform == Platform.TELEGRAM and group_user_allowlist and is_group_or_forum and source.chat_id:
legacy_chat_ids = {
v.strip() for v in group_user_allowlist.split(",") if v.strip().startswith("-")
}
@@ -722,16 +716,17 @@ class GatewayAuthorizationMixin:
"""
config = getattr(self, "config", None)
- if config and hasattr(config, "get_unauthorized_dm_behavior") and platform:
- if "unauthorized_dm_behavior" in self._config_extra(platform):
- return config.get_unauthorized_dm_behavior(platform)
+ if (
+ config and hasattr(config, "get_unauthorized_dm_behavior") and platform
+ and "unauthorized_dm_behavior" in self._config_extra(platform)
+ ):
+ return config.get_unauthorized_dm_behavior(platform)
if platform == Platform.EMAIL:
return "ignore"
- if config and hasattr(config, "unauthorized_dm_behavior"):
- if config.unauthorized_dm_behavior != "pair":
- return config.unauthorized_dm_behavior
+ if config and hasattr(config, "unauthorized_dm_behavior") and config.unauthorized_dm_behavior != "pair":
+ return config.unauthorized_dm_behavior
if platform:
dm_policy = self._adapter_dm_policy(platform, profile=profile)
diff --git a/gateway/channel_directory.py b/gateway/channel_directory.py
index b7558325e15..a1a1ff2326b 100644
--- a/gateway/channel_directory.py
+++ b/gateway/channel_directory.py
@@ -92,7 +92,7 @@ def _normalize_channel_query(value: str) -> str:
def _channel_target_name(platform_name: str, channel: Dict[str, Any]) -> str:
- """Return the human-facing target label shown to users for a channel entry."""
+ """Human-facing target label for a channel entry."""
name = channel["name"]
if platform_name == "discord" and channel.get("guild"):
return f"#{name}"
@@ -118,8 +118,11 @@ def _session_entry_name(origin: Dict[str, Any]) -> str:
return f"{base_name} / {topic_label}"
-def _warn_slack_directory(team_id: str, detail: str) -> None:
- """Warn once per team/error per interval for recurring Slack refresh failures."""
+def _report_slack_failure(team_id: str, error_code: Optional[str], detail: str) -> None:
+ """missing_scope is expected (session-history fallback); anything else warns once per interval."""
+ if error_code == "missing_scope":
+ logger.debug("Channel directory: Slack team %s lacks channels:read; using session history only", team_id)
+ return
key = (str(team_id), str(detail))
now = time.monotonic()
last = _slack_directory_warning_last.get(key)
@@ -130,14 +133,6 @@ def _warn_slack_directory(team_id: str, detail: str) -> None:
logger.debug("Channel directory: suppressed repeated Slack channel list failure for team %s: %s", team_id, detail)
-def _report_slack_failure(team_id: str, error_code: Optional[str], detail: str) -> None:
- """missing_scope is expected (session-history fallback); anything else warns."""
- if error_code == "missing_scope":
- logger.debug("Channel directory: Slack team %s lacks channels:read; using session history only", team_id)
- else:
- _warn_slack_directory(team_id, detail)
-
-
# --- Build / refresh -------------------------------------------------------
async def build_channel_directory(adapters: Dict[Any, Any]) -> Dict[str, Any]:
@@ -222,7 +217,7 @@ def _build_discord(adapter) -> List[Dict[str, str]]:
def _slack_api_error_code(error: Exception) -> Optional[str]:
- """Return Slack Web API error code from SlackApiError-like exceptions."""
+ """Slack Web API error code from SlackApiError-like exceptions."""
response = getattr(error, "response", None)
if response is None:
return None
@@ -260,47 +255,91 @@ def _slack_base_id(entry_id: str) -> str:
return entry_id.split(":", 1)[0]
-async def _build_slack(adapter) -> List[Dict[str, Any]]:
- """List Slack channels the bot has joined across all workspaces.
+def _slack_has_raw_name(entry: Dict[str, Any]) -> bool:
+ return entry.get("name", "").startswith(_SLACK_RAW_ID_PREFIXES)
- ``users.conversations`` per workspace client (public + private member channels),
- then merge DMs from session history. Missing channels:read falls back to
- session history quietly rather than warning on every refresh.
- """
+
+async def _slack_team_channels(team_id: str, client, seen_ids: set) -> List[Dict[str, Any]]:
+ """``users.conversations`` for one workspace (public + private member channels), paginated."""
+ channels: List[Dict[str, Any]] = []
+ try:
+ cursor: Optional[str] = None
+ for _page in range(20): # safety cap on pagination
+ response = await client.users_conversations(
+ types="public_channel,private_channel",
+ exclude_archived=True,
+ limit=200,
+ cursor=cursor,
+ )
+ if not response.get("ok"):
+ error_code = response.get("error", "unknown")
+ _report_slack_failure(team_id, error_code, f"users.conversations not ok: {error_code}")
+ break
+ for ch in response.get("channels", []):
+ cid = ch.get("id")
+ name = ch.get("name")
+ if not cid or not name or cid in seen_ids:
+ continue
+ seen_ids.add(cid)
+ channels.append({"id": cid, "name": name, "type": "private" if ch.get("is_private") else "channel"})
+ cursor = (response.get("response_metadata") or {}).get("next_cursor")
+ if not cursor:
+ break
+ except Exception as e:
+ _report_slack_failure(team_id, _slack_api_error_code(e), str(e))
+ return channels
+
+
+async def _slack_resolve_raw_names(client, channels: List[Dict[str, Any]]) -> None:
+ """Name remaining raw-ID entries (DMs, channels outside bot scope) via
+ conversations.info + users.info once per base conversation, concurrently."""
+ unresolved_by_base: Dict[str, list] = {}
+ for entry in channels:
+ if _slack_has_raw_name(entry):
+ unresolved_by_base.setdefault(_slack_base_id(entry["id"]), []).append(entry)
+ if not unresolved_by_base:
+ return
+
+ async def _resolve_base(base_id: str, entries: list) -> None:
+ try:
+ resp = await client.conversations_info(channel=base_id)
+ if not resp.get("ok"):
+ return
+ ch_info = resp.get("channel", {})
+ resolved_name = None
+ resolved_type = None
+ if ch_info.get("is_im"):
+ peer_user = ch_info.get("user", "")
+ if peer_user:
+ user_resp = await client.users_info(user=peer_user)
+ if user_resp.get("ok"):
+ u = user_resp["user"]
+ resolved_name = u.get("profile", {}).get("display_name") or u.get("real_name") or u.get("name")
+ resolved_type = "dm"
+ else:
+ resolved_name = ch_info.get("name") or ch_info.get("name_normalized")
+ if resolved_name:
+ for entry in entries:
+ entry["name"] = resolved_name
+ if resolved_type:
+ entry["type"] = resolved_type
+ except Exception as e:
+ logger.debug("Channel directory: failed to resolve %s: %s", base_id, e)
+
+ await asyncio.gather(*[_resolve_base(bid, ents) for bid, ents in unresolved_by_base.items()])
+
+
+async def _build_slack(adapter) -> List[Dict[str, Any]]:
+ """List Slack channels the bot has joined across all workspaces, merged with
+ session-history DMs. Missing channels:read falls back to session history quietly."""
team_clients = getattr(adapter, "_team_clients", None) or {}
if not team_clients:
return await asyncio.to_thread(_build_from_sessions, "slack")
channels: List[Dict[str, Any]] = []
seen_ids: set = set()
-
for team_id, client in team_clients.items():
- try:
- cursor: Optional[str] = None
- for _page in range(20): # safety cap on pagination
- response = await client.users_conversations(
- types="public_channel,private_channel",
- exclude_archived=True,
- limit=200,
- cursor=cursor,
- )
- if not response.get("ok"):
- error_code = response.get("error", "unknown")
- _report_slack_failure(team_id, error_code, f"users.conversations not ok: {error_code}")
- break
- for ch in response.get("channels", []):
- cid = ch.get("id")
- name = ch.get("name")
- if not cid or not name or cid in seen_ids:
- continue
- seen_ids.add(cid)
- channels.append({"id": cid, "name": name, "type": "private" if ch.get("is_private") else "channel"})
- cursor = (response.get("response_metadata") or {}).get("next_cursor")
- if not cursor:
- break
- except Exception as e:
- _report_slack_failure(team_id, _slack_api_error_code(e), str(e))
- continue
+ channels.extend(await _slack_team_channels(team_id, client, seen_ids))
# Merge session-history DM/group entries, naming raw-ID entries from the
# API-discovered channels where the base conversation ID is known.
@@ -309,50 +348,14 @@ async def _build_slack(adapter) -> List[Dict[str, Any]]:
eid = entry.get("id")
if not isinstance(eid, str) or eid in seen_ids:
continue
- if entry.get("name", "").startswith(_SLACK_RAW_ID_PREFIXES):
+ if _slack_has_raw_name(entry):
base_id = _slack_base_id(eid)
if base_id in api_name_lookup:
entry["name"] = api_name_lookup[base_id]
channels.append(entry)
seen_ids.add(eid)
- # Resolve remaining raw-ID entries (DMs, channels outside bot scope) via
- # conversations.info + users.info once per base conversation, concurrently.
- unresolved = [ch for ch in channels if ch.get("name", "").startswith(_SLACK_RAW_ID_PREFIXES)]
- if unresolved:
- client = next(iter(team_clients.values()))
- unresolved_by_base: Dict[str, list] = {}
- for entry in unresolved:
- unresolved_by_base.setdefault(_slack_base_id(entry["id"]), []).append(entry)
-
- async def _resolve_base(base_id: str, entries: list) -> None:
- try:
- resp = await client.conversations_info(channel=base_id)
- if not resp.get("ok"):
- return
- ch_info = resp.get("channel", {})
- resolved_name = None
- resolved_type = None
- if ch_info.get("is_im"):
- peer_user = ch_info.get("user", "")
- if peer_user:
- user_resp = await client.users_info(user=peer_user)
- if user_resp.get("ok"):
- u = user_resp["user"]
- resolved_name = u.get("profile", {}).get("display_name") or u.get("real_name") or u.get("name")
- resolved_type = "dm"
- else:
- resolved_name = ch_info.get("name") or ch_info.get("name_normalized")
- if resolved_name:
- for entry in entries:
- entry["name"] = resolved_name
- if resolved_type:
- entry["type"] = resolved_type
- except Exception as e:
- logger.debug("Channel directory: failed to resolve %s: %s", base_id, e)
-
- await asyncio.gather(*[_resolve_base(bid, ents) for bid, ents in unresolved_by_base.items()])
-
+ await _slack_resolve_raw_names(next(iter(team_clients.values())), channels)
return channels
@@ -365,51 +368,54 @@ def _build_from_sessions(platform_name: str) -> List[Dict[str, str]]:
return _build_from_sessions_db(platform_name) or _build_from_sessions_json(platform_name)
-def _extend_from_origins(entries: List[Dict[str, Any]], origins: Iterable[Tuple[Dict[str, Any], Any]]) -> None:
- """Append deduped directory entries for (origin, chat_type) pairs to *entries*.
+def _entries_from_origins(platform_name: str, source: str, origins_fn) -> List[Dict[str, Any]]:
+ """Deduped directory entries for the (origin, chat_type) pairs yielded by ``origins_fn()``.
Appends incrementally so a mid-iteration failure keeps the entries read so far.
"""
- seen_ids = set()
- for origin, chat_type in origins:
- entry_id = _session_entry_id(origin)
- if not entry_id or entry_id in seen_ids:
- continue
- seen_ids.add(entry_id)
- entries.append({
- "id": entry_id, "name": _session_entry_name(origin),
- "type": chat_type, "thread_id": origin.get("thread_id"),
- })
+ entries: List[Dict[str, Any]] = []
+ try:
+ seen_ids = set()
+ for origin, chat_type in origins_fn():
+ entry_id = _session_entry_id(origin)
+ if not entry_id or entry_id in seen_ids:
+ continue
+ seen_ids.add(entry_id)
+ entries.append({
+ "id": entry_id, "name": _session_entry_name(origin),
+ "type": chat_type, "thread_id": origin.get("thread_id"),
+ })
+ except Exception as e:
+ logger.debug("Channel directory: %s for %s: %s", source, platform_name, e)
+ return entries
def _build_from_sessions_db(platform_name: str) -> List[Dict[str, str]]:
"""Pull channels/contacts from state.db gateway session rows."""
- entries: List[Dict[str, Any]] = []
- try:
+ def _origins() -> Iterable[Tuple[Dict[str, Any], Any]]:
from hermes_state import get_shared_session_db, release_or_close
db = get_shared_session_db()
try:
lister = getattr(db, "list_gateway_sessions", None)
if not callable(lister):
- return []
+ return
rows = lister(platform=platform_name, active_only=False)
finally:
release_or_close(db)
-
- def _origin(row) -> Dict[str, Any]:
+ for row in rows:
+ origin = None
if row.get("origin_json"):
try:
parsed = json.loads(row["origin_json"])
if isinstance(parsed, dict) and parsed:
- return parsed
+ origin = parsed
except (TypeError, ValueError):
pass
- return {"chat_id": row.get("chat_id"), "thread_id": row.get("thread_id"), "chat_name": row.get("display_name")}
+ if origin is None:
+ origin = {"chat_id": row.get("chat_id"), "thread_id": row.get("thread_id"), "chat_name": row.get("display_name")}
+ yield origin, row.get("chat_type") or "dm"
- _extend_from_origins(entries, ((_origin(row), row.get("chat_type") or "dm") for row in rows))
- except Exception as e:
- logger.debug("Channel directory: state.db session read failed for %s: %s", platform_name, e)
- return entries
+ return _entries_from_origins(platform_name, "state.db session read failed", _origins)
def _build_from_sessions_json(platform_name: str) -> List[Dict[str, str]]:
@@ -417,25 +423,19 @@ def _build_from_sessions_json(platform_name: str) -> List[Dict[str, str]]:
sessions_path = get_hermes_home() / "sessions" / "sessions.json"
if not sessions_path.exists():
return []
- entries: List[Dict[str, Any]] = []
- try:
+
+ def _origins() -> Iterable[Tuple[Dict[str, Any], Any]]:
with open(sessions_path, encoding="utf-8") as f:
data = json.load(f)
+ for _key, session in data.items():
+ # Keys starting with "_" (e.g. the gateway's "_README") are metadata sentinels.
+ if str(_key).startswith("_") or not isinstance(session, dict):
+ continue
+ origin = session.get("origin") or {}
+ if origin.get("platform") == platform_name:
+ yield origin, session.get("chat_type", "dm")
- def _origins():
- for _key, session in data.items():
- # Keys starting with "_" (e.g. the gateway's "_README") are
- # metadata sentinels, not sessions.
- if str(_key).startswith("_") or not isinstance(session, dict):
- continue
- origin = session.get("origin") or {}
- if origin.get("platform") == platform_name:
- yield origin, session.get("chat_type", "dm")
-
- _extend_from_origins(entries, _origins())
- except Exception as e:
- logger.debug("Channel directory: failed to read sessions for %s: %s", platform_name, e)
- return entries
+ return _entries_from_origins(platform_name, "failed to read sessions", _origins)
# --- Read / resolve --------------------------------------------------------
@@ -458,7 +458,7 @@ def load_directory() -> Dict[str, Any]:
def lookup_channel_type(platform_name: str, chat_id: str) -> Optional[str]:
- """Return the channel ``type`` string (e.g. ``"channel"``, ``"forum"``) for *chat_id*, or *None* if unknown."""
+ """Channel ``type`` string (e.g. ``"channel"``, ``"forum"``) for *chat_id*, or None if unknown."""
for ch in load_directory().get("platforms", {}).get(platform_name, []):
if ch.get("id") == chat_id:
return ch.get("type")
@@ -487,9 +487,7 @@ def resolve_channel_name(platform_name: str, name: str) -> Optional[str]:
# 1. Exact name match, including the display labels shown by send_message(action="list")
for ch in channels:
- if _normalize_channel_query(ch["name"]) == query:
- return ch["id"]
- if _normalize_channel_query(_channel_target_name(platform_name, ch)) == query:
+ if query in (_normalize_channel_query(ch["name"]), _normalize_channel_query(_channel_target_name(platform_name, ch))):
return ch["id"]
# 2. Guild-qualified match for Discord ("GuildName/channel")
diff --git a/gateway/pairing.py b/gateway/pairing.py
index 67697dc6cef..6f9d752cfd9 100644
--- a/gateway/pairing.py
+++ b/gateway/pairing.py
@@ -1,8 +1,6 @@
-"""
-DM Pairing System
+"""DM pairing: code-based approval of new users on messaging platforms.
-Code-based approval flow for authorizing new users on messaging platforms:
-unknown users receive a one-time pairing code that the bot owner approves via
+Unknown users receive a one-time pairing code that the bot owner approves via
the CLI, instead of maintaining static user-ID allowlists.
Security properties (OWASP + NIST SP 800-63-4): 8-char codes from a 32-char
@@ -50,27 +48,25 @@ MAX_FAILED_ATTEMPTS = 5 # Failed approvals before lockout
# Default (non-profile-scoped) pairing directory. Deliberately ``None``: the
# long-lived gateway imports this module at boot, and an eagerly computed path
# would freeze whatever HERMES_HOME/profile context existed then, ignoring later
-# context-local overrides (hermes_constants.set_hermes_home_override) -- so the
-# gateway and the short-lived ``hermes pairing`` CLI ended up writing different
-# directories. ``_default_pairing_dir()`` resolves fresh on every call; tests
-# patch this attribute to a concrete path (``patch("gateway.pairing.PAIRING_DIR", tmp)``)
-# and a non-``None`` value takes precedence.
+# context-local overrides -- so the gateway and the short-lived ``hermes pairing``
+# CLI ended up writing different directories. ``_default_pairing_dir()`` resolves
+# fresh on every call; tests patch this attribute to a concrete path
+# (``patch("gateway.pairing.PAIRING_DIR", tmp)``) and a non-``None`` value wins.
PAIRING_DIR = None
def _default_pairing_dir() -> Path:
- """Resolve the default pairing directory fresh (see ``PAIRING_DIR``)."""
if PAIRING_DIR is not None:
return PAIRING_DIR
return get_hermes_dir("platforms/pairing", "pairing")
-# Platform value -> per-platform allowlist env var. When an operator already
-# runs an allowlist for a platform, approving a pairing code also writes the
-# user into it (and revoking removes them), so the operator's list stays the
-# single visible source of truth instead of drifting from an opaque
-# approved.json. Platforms absent here (or with no allowlist configured) keep
-# the pairing store as the sole grant record, honored by the authz union.
+# Platform value -> per-platform allowlist env var. When an operator already runs
+# an allowlist for a platform, approving a pairing code also writes the user into
+# it (and revoking removes them), so the operator's list stays the single visible
+# source of truth instead of drifting from an opaque approved.json. Platforms
+# absent here (or with no allowlist configured) keep the pairing store as the
+# sole grant record, honored by the authz union.
_PLATFORM_ALLOWLIST_ENV = {
"telegram": "TELEGRAM_ALLOWED_USERS",
"discord": "DISCORD_ALLOWED_USERS",
@@ -128,11 +124,10 @@ def _normalize_user_id(platform: str, user_id: str) -> str:
def _user_id_aliases(platform: str, user_id: str) -> set[str]:
- """Return all known equivalent user IDs for auth / allowlist matching."""
+ """All known equivalent user IDs for auth / allowlist matching."""
raw_user_id = str(user_id or "").strip()
if not raw_user_id:
return set()
-
aliases = {raw_user_id, _normalize_user_id(platform, raw_user_id)}
if _platform_uses_whatsapp_identity(platform):
aliases.update(expand_whatsapp_aliases(raw_user_id))
@@ -141,10 +136,13 @@ def _user_id_aliases(platform: str, user_id: str) -> set[str]:
def _user_ids_match(platform: str, left: str, right: str) -> bool:
- """Return True when two user IDs represent the same principal."""
+ """True when two user IDs represent the same principal."""
left_aliases = _user_id_aliases(platform, left)
- right_aliases = _user_id_aliases(platform, right)
- return bool(left_aliases and right_aliases and (left_aliases & right_aliases))
+ return bool(left_aliases and left_aliases & _user_id_aliases(platform, right))
+
+
+def _matching_ids(platform: str, approved: dict, user_id: str) -> list:
+ return [uid for uid in approved if _user_ids_match(platform, uid, user_id)]
def _read_allowlist_env(env_var: str) -> str:
@@ -153,10 +151,10 @@ def _read_allowlist_env(env_var: str) -> str:
Under multiplexing the process env may hold ANOTHER profile's allowlist
(first-writer-wins YAML→env bridges), so a scoped miss must return empty
rather than borrow the process value. Unscoped callers (single-profile
- CLI / admin endpoints) keep the legacy ``os.getenv`` read. Writes go
- through ``hermes_cli.config.save_env_value`` / ``remove_env_value``, which
- target the active profile's ``.env`` and, under multiplexing, publish into
- the installed scope mapping rather than the shared ``os.environ``.
+ CLI / admin endpoints) keep the legacy ``os.getenv`` read. Writes go through
+ ``hermes_cli.config.save_env_value`` / ``remove_env_value``, which target the
+ active profile's ``.env`` and, under multiplexing, publish into the installed
+ scope mapping rather than the shared ``os.environ``.
"""
try:
from agent.secret_scope import UnscopedSecretError, get_secret
@@ -171,18 +169,25 @@ def _read_allowlist_env(env_var: str) -> str:
def _configured_allowlist(platform: str):
- """Return ``(env_var, ids)`` for a platform whose allowlist is configured, else None.
+ """``(env_var, ids)`` for a platform whose allowlist is configured, else None.
An unconfigured allowlist means an open gateway: the pairing store stays the
sole grant record and we must never lock the gateway by materializing one.
"""
env_var = _allowlist_env_for_platform(platform)
- if not env_var:
- return None
- current = _read_allowlist_env(env_var)
- if not current:
- return None
- return env_var, _split_allowlist(current)
+ current = _read_allowlist_env(env_var) if env_var else ""
+ return (env_var, _split_allowlist(current)) if current else None
+
+
+def _write_allowlist_env(env_var: str, ids: list) -> None:
+ """Best-effort persist (empty list removes the key); the pairing store grant still authorizes via the union."""
+ with contextlib.suppress(Exception):
+ from hermes_cli.config import save_env_value, remove_env_value
+
+ if ids:
+ save_env_value(env_var, ",".join(ids))
+ else:
+ remove_env_value(env_var)
def _sync_allowlist_add(platform: str, user_id: str) -> None:
@@ -192,15 +197,8 @@ def _sync_allowlist_add(platform: str, user_id: str) -> None:
return
env_var, ids = configured
if "*" in ids or str(user_id) in ids:
- return # Already covered.
- ids.append(str(user_id))
- try:
- from hermes_cli.config import save_env_value
-
- save_env_value(env_var, ",".join(ids))
- except Exception:
- # Best-effort: the pairing store grant still authorizes via the union.
- pass
+ return
+ _write_allowlist_env(env_var, [*ids, str(user_id)])
def _iter_live_gateway_adapters():
@@ -213,10 +211,9 @@ def _iter_live_gateway_adapters():
return
if runner is None:
return
- for adapter in (getattr(runner, "adapters", None) or {}).values():
- if adapter is not None:
- yield adapter
- for mapping in (getattr(runner, "_profile_adapters", None) or {}).values():
+ mappings = [getattr(runner, "adapters", None) or {}]
+ mappings.extend((getattr(runner, "_profile_adapters", None) or {}).values())
+ for mapping in mappings:
for adapter in (mapping or {}).values():
if adapter is not None:
yield adapter
@@ -285,26 +282,44 @@ def _sync_allowlist_remove(platform: str, user_id: str) -> None:
remaining = _purge_allowlist_entries(ids, platform, user_id)
if len(remaining) == len(ids):
return # Not present.
- try:
- from hermes_cli.config import save_env_value, remove_env_value
-
- if remaining:
- save_env_value(env_var, ",".join(remaining))
- else:
- remove_env_value(env_var)
- except Exception:
- pass
+ _write_allowlist_env(env_var, remaining)
_sync_live_adapter_allowlist_remove(platform, user_id)
def _load_json_file(path: Path) -> dict:
- if path.exists():
+ """Read a JSON object; {} when missing, malformed, unreadable, or not a dict.
+
+ PermissionError is logged loudly: a 0600 file owned by another uid (Docker:
+ ``docker exec`` as root wrote it, the gosu-dropped gateway can't read it)
+ would otherwise silently leave the user unauthorized.
+ """
+ if not path.exists():
+ return {}
+ try:
+ data = json.loads(path.read_text(encoding="utf-8"))
+ return data if isinstance(data, dict) else {}
+ except PermissionError as e:
try:
- data = json.loads(path.read_text(encoding="utf-8"))
- return data if isinstance(data, dict) else {}
- except (json.JSONDecodeError, OSError):
- return {}
- return {}
+ st = path.stat()
+ owner_info = f"owner_uid={st.st_uid} mode={oct(st.st_mode)[-4:]}"
+ except OSError:
+ owner_info = "<stat failed>"
+ euid = os.geteuid() if hasattr(os, "geteuid") else "n/a" # no geteuid on Windows
+ logger.warning(
+ "Pairing file %s exists but is not readable as uid=%s (%s; %s). "
+ "If you ran `docker exec <container> hermes pairing approve ...` as root, "
+ "re-run with `docker exec -u hermes <container> ...` and "
+ "chown the existing file to the hermes user, or restart the "
+ "container so the entrypoint can fix ownership.",
+ path, euid, owner_info, e,
+ )
+ return {}
+ except (json.JSONDecodeError, OSError):
+ return {}
+
+
+def _save_json_file(path: Path, data: dict) -> None:
+ _secure_write(path, json.dumps(data, indent=2, ensure_ascii=False))
def _merge_pairing_dir(active_dir: Path, alternate_dir: Path) -> None:
@@ -328,7 +343,7 @@ def _merge_pairing_dir(active_dir: Path, alternate_dir: Path) -> None:
# Active data wins on key conflict; otherwise union the inactive data.
merged.update(current)
if merged != before:
- _secure_write(dest, json.dumps(merged, indent=2, ensure_ascii=False))
+ _save_json_file(dest, merged)
def _migrate_split_pairing_dirs(
@@ -362,9 +377,12 @@ def _secure_write(path: Path, data: str) -> None:
raise
+def _is_hashed_entry(entry) -> bool:
+ return isinstance(entry, dict) and "salt" in entry and "hash" in entry
+
+
class PairingStore:
- """
- Manages pairing codes and approved user lists.
+ """Manages pairing codes and approved user lists.
Data files per platform: ``{platform}-pending.json``,
``{platform}-approved.json``, plus shared ``_rate_limits.json``.
@@ -409,51 +427,20 @@ class PairingStore:
def _rate_limit_path(self) -> Path:
return self._dir / "_rate_limits.json"
- def _load_json(self, path: Path) -> dict:
- if path.exists():
- try:
- return json.loads(path.read_text(encoding="utf-8"))
- except PermissionError as e:
- # Loud warning: a 0600 file owned by another uid (Docker:
- # `docker exec` as root writes it, the gosu-dropped gateway
- # can't read it) would otherwise be swallowed by the OSError
- # branch and silently leave the user unauthorized.
- try:
- st = path.stat()
- owner_info = f"owner_uid={st.st_uid} mode={oct(st.st_mode)[-4:]}"
- except OSError:
- owner_info = "<stat failed>"
- euid = os.geteuid() if hasattr(os, "geteuid") else "n/a" # no geteuid on Windows
- logger.warning(
- "Pairing file %s exists but is not readable as uid=%s (%s; %s). "
- "If you ran `docker exec <container> hermes pairing approve ...` as root, "
- "re-run with `docker exec -u hermes <container> ...` and "
- "chown the existing file to the hermes user, or restart the "
- "container so the entrypoint can fix ownership.",
- path, euid, owner_info, e,
- )
- return {}
- except (json.JSONDecodeError, OSError):
- return {}
- return {}
-
- def _save_json(self, path: Path, data: dict) -> None:
- _secure_write(path, json.dumps(data, indent=2, ensure_ascii=False))
+ _load_json = staticmethod(_load_json_file)
+ _save_json = staticmethod(_save_json_file)
# ----- Approved users -----
def is_approved(self, platform: str, user_id: str) -> bool:
"""Check if a user is approved (paired) on a platform."""
- approved = self._load_json(self._approved_path(platform))
- return any(_user_ids_match(platform, uid, user_id) for uid in approved)
+ return bool(_matching_ids(platform, self._load_json(self._approved_path(platform)), user_id))
def list_approved(self, platform: str = None) -> list:
"""List approved users, optionally filtered by platform."""
results = []
- platforms = [platform] if platform else self._all_platforms("approved")
- for p in platforms:
- approved = self._load_json(self._approved_path(p))
- for uid, info in approved.items():
+ for p in [platform] if platform else self._all_platforms("approved"):
+ for uid, info in self._load_json(self._approved_path(p)).items():
results.append({"platform": p, "user_id": uid, **info})
return results
@@ -461,11 +448,8 @@ class PairingStore:
"""Add a user to the approved list. Must be called under self._lock."""
approved = self._load_json(self._approved_path(platform))
normalized_user_id = _normalize_user_id(platform, user_id)
- for approved_user_id in [
- uid for uid in approved if _user_ids_match(platform, uid, normalized_user_id)
- ]:
+ for approved_user_id in _matching_ids(platform, approved, normalized_user_id):
del approved[approved_user_id]
-
approved[normalized_user_id] = {
"user_name": user_name,
"approved_at": time.time(),
@@ -479,9 +463,7 @@ class PairingStore:
path = self._approved_path(platform)
with self._lock:
approved = self._load_json(path)
- matching_ids = [
- uid for uid in approved if _user_ids_match(platform, uid, user_id)
- ]
+ matching_ids = _matching_ids(platform, approved, user_id)
if not matching_ids:
return False
for approved_user_id in matching_ids:
@@ -495,7 +477,6 @@ class PairingStore:
@staticmethod
def _hash_code(code: str, salt: bytes) -> str:
- """Hash a pairing code with the given salt using SHA-256."""
return hashlib.sha256(salt + code.encode("utf-8")).hexdigest()
def _finish_approval(
@@ -533,9 +514,7 @@ class PairingStore:
self._cleanup_expired(platform)
normalized_user_id = _normalize_user_id(platform, user_id)
- if self._is_locked_out(platform):
- return None
- if self._is_rate_limited(platform, user_id):
+ if self._is_locked_out(platform) or self._is_rate_limited(platform, user_id):
return None
pending = self._load_json(self._pending_path(platform))
if len(pending) >= MAX_PENDING_PER_PLATFORM:
@@ -579,7 +558,7 @@ class PairingStore:
# Skip legacy/malformed entries rather than KeyError so an in-place
# upgrade over an existing pending.json doesn't crash.
for entry_id, entry in pending.items():
- if not isinstance(entry, dict) or "salt" not in entry or "hash" not in entry:
+ if not _is_hashed_entry(entry):
continue
try:
salt = bytes.fromhex(entry["salt"])
@@ -623,11 +602,8 @@ class PairingStore:
pending = self._load_json(self._pending_path(platform))
for entry_id, entry in pending.items():
- if not isinstance(entry, dict) or "salt" not in entry or "hash" not in entry:
- continue
- if secrets.compare_digest(str(entry_id).lower(), request_id):
+ if _is_hashed_entry(entry) and secrets.compare_digest(str(entry_id).lower(), request_id):
return self._finish_approval(platform, pending, entry_id, entry)
-
return None
def list_pending(self, platform: str = None) -> list:
@@ -639,19 +615,15 @@ class PairingStore:
"""
results = []
with self._lock:
- platforms = [platform] if platform else self._all_platforms("pending")
- for p in platforms:
+ for p in [platform] if platform else self._all_platforms("pending"):
self._cleanup_expired(p)
- pending = self._load_json(self._pending_path(p))
- for entry_id, info in pending.items():
+ for entry_id, info in self._load_json(self._pending_path(p)).items():
if not isinstance(info, dict):
continue
created_at = info.get("created_at")
if not isinstance(created_at, (int, float)):
continue
- is_modern = isinstance(info.get("hash"), str) and isinstance(
- info.get("salt"), str
- )
+ is_modern = isinstance(info.get("hash"), str) and isinstance(info.get("salt"), str)
results.append({
"platform": p,
"request_id": str(entry_id) if is_modern else "",
@@ -665,17 +637,15 @@ class PairingStore:
"""Clear all pending requests. Returns count removed."""
with self._lock:
count = 0
- platforms = [platform] if platform else self._all_platforms("pending")
- for p in platforms:
- pending = self._load_json(self._pending_path(p))
- count += len(pending)
+ for p in [platform] if platform else self._all_platforms("pending"):
+ count += len(self._load_json(self._pending_path(p)))
self._save_json(self._pending_path(p), {})
return count
# ----- Rate limiting and lockout -----
def _is_rate_limited(self, platform: str, user_id: str) -> bool:
- """Check if a user (under any alias) has requested a code too recently."""
+ """Whether a user (under any alias) has requested a code too recently."""
limits = self._load_json(self._rate_limit_path())
return any(
(time.time() - limits.get(f"{platform}:{alias}", 0)) < RATE_LIMIT_SECONDS
@@ -683,7 +653,6 @@ class PairingStore:
)
def _record_rate_limit(self, platform: str, user_id: str) -> None:
- """Record the time of a pairing request for rate limiting."""
limits = self._load_json(self._rate_limit_path())
now = time.time()
for alias in _user_id_aliases(platform, user_id):
@@ -691,12 +660,11 @@ class PairingStore:
self._save_json(self._rate_limit_path(), limits)
def _is_locked_out(self, platform: str) -> bool:
- """Check if a platform is in lockout due to failed approval attempts."""
limits = self._load_json(self._rate_limit_path())
return time.time() < limits.get(f"_lockout:{platform}", 0)
def _record_failed_attempt(self, platform: str) -> None:
- """Record a failed approval attempt. Triggers lockout after MAX_FAILED_ATTEMPTS."""
+ """Record a failed approval attempt; triggers lockout after MAX_FAILED_ATTEMPTS."""
limits = self._load_json(self._rate_limit_path())
fail_key = f"_failures:{platform}"
fails = limits.get(fail_key, 0) + 1
@@ -735,7 +703,7 @@ class PairingStore:
self._save_json(path, pending)
def _all_platforms(self, suffix: str) -> list:
- """List all platforms that have data files of a given suffix."""
+ """Platforms that have a ``-<suffix>.json`` data file (``_``-prefixed files are shared state)."""
tail = f"-{suffix}.json"
platforms = [f.name.replace(tail, "") for f in self._dir.iterdir() if f.name.endswith(tail)]
return [p for p in platforms if not p.startswith("_")]