# Copyright (c) 2026 Krzysztof Rudnicki. MIT licence. """Is the account actually *in* the groups it is configured to watch? Split out of transport_rest.py because it answers a different question from "how do I send a message": a pending invitation is indistinguishable from membership from the outside, and the whole point of this module is that the difference is checked before the bot is allowed to start. """ from __future__ import annotations import logging from typing import TYPE_CHECKING, Any from urllib.parse import quote import httpx from signal_bot.groups import group_id_aliases if TYPE_CHECKING: from signal_bot.config import Config logger = logging.getLogger(__name__) class MembershipError(RuntimeError): """Raised when the account is not a full member of a watched group.""" class MembershipVerifier: """Checks each watched group, joining one it was only invited to.""" def __init__(self, config: Config, client: httpx.AsyncClient) -> None: """Wire the verifier to its config and HTTP client.""" self._config = config self._client = client async def _fetch_groups(self) -> list[dict[str, Any]]: """Return the groups the account knows about, as raw dicts.""" response = await self._client.get(self._config.groups_url) response.raise_for_status() return [group for group in response.json() if isinstance(group, dict)] @staticmethod def _find_group(groups: list[dict[str, Any]], group_id: str) -> dict[str, Any] | None: """Return the entry for one configured group, in either spelling.""" aliases = group_id_aliases(group_id) for group in groups: if {group.get("id"), group.get("internal_id")} & aliases: return group return None async def _attempt_join(self, group_id: str) -> str: """Try to accept a pending invitation, reporting what the API said. This never raises: the join endpoint is a best-effort self-heal and the authority on whether it worked is the membership re-check by the caller, not this response. Returning the outcome as text keeps it in the error message when the re-check still says non-member. Args: group_id: The canonical group id to join. Returns: A short description of the attempt, for the error message. """ # The prefixed spelling, percent-encoded: the internal form contains # '/' and '+', which do not survive being a path segment. quoted = quote(group_id, safe="") url = f"{self._config.api_base_url}/v1/groups/{self._config.phone_number}/{quoted}/join" try: response = await self._client.post(url) except httpx.HTTPError as exc: return f"join request failed: {exc}" return f"join returned HTTP {response.status_code}: {response.text.strip()[:200]}" async def verify(self) -> None: """Raise unless the account is a full member of every watched group. A pending invitation is indistinguishable from membership from the outside: /v1/groups lists the group, the websocket connects, /healthz answers, and not one message ever arrives. Signal only adds an account to a group outright when the inviter already holds its profile key; otherwise it creates an invite. Observed live on 2026-08-29, where the bot looked perfectly healthy for hours while being a non-member. Startup is the only honest place to catch it. Each configured group is checked on its own. One joined group satisfying the check for another is exactly how a bot ends up silently deaf in the group nobody was watching. Raises: MembershipError: A watched group is missing, or the account is not a full member of it and could not join. """ groups = await self._fetch_groups() for group_id in self._config.group_ids: await self._verify_one(groups, group_id) async def _verify_one(self, groups: list[dict[str, Any]], group_id: str) -> None: """Check one configured group, joining it if it is only an invite. Args: groups: The current /v1/groups listing. group_id: The canonical group id to check. Raises: MembershipError: The group is unknown, or still not joined after the join attempt. """ state = self._find_group(groups, group_id) if state is None: msg = ( f"the account is in no group matching {group_id!r}. Check GROUP_IDS " "in .env against: curl -s $API_BASE_URL/v1/groups/$PHONE_NUMBER" ) raise MembershipError(msg) if state.get("member"): return name = state.get("name") logger.warning("invited to %r but not a member; attempting to join", name) detail = await self._attempt_join(group_id) # The join endpoint's own response is not trusted: only the listing # decides, so the gate cannot degrade into an optimistic warning. rechecked = self._find_group(await self._fetch_groups(), group_id) if rechecked is not None and rechecked.get("member"): logger.info("joined %r on startup (%s)", name, detail) return msg = ( f"the account is invited to {name!r} ({group_id}) but has not joined " f"it, so it will receive nothing there, and joining did not work: " f"{detail}. Have an admin remove the pending invite and add the bot " "again now that it has a profile, or have the bot create the group." ) raise MembershipError(msg)