diff --git a/README.md b/README.md index 5a97266..2e3669d 100644 --- a/README.md +++ b/README.md @@ -22,9 +22,10 @@ it listens for `meshcore_message` events and replies via the 2. Install **MeshCore Agent**. 3. Restart Home Assistant. 4. Settings → Devices & services → *Add Integration* → **MeshCore Agent**. -5. Fill in the allowlist of senders who may command the agent (public key - prefixes or contact names, comma separated). Leave "Allow all senders" - unchecked; anyone on the mesh could otherwise command your todo list. +5. Fill in the allowlist of senders who may command the agent — **public key + prefixes only** (comma separated; the same format the MeshCore integration + uses). Leave "Allow all senders" unchecked; anyone on the mesh could + otherwise command your todo list. ## Mesh commands @@ -46,6 +47,9 @@ channel's senders are allowlisted): (`todo done buy m`). Messages may optionally start with a wake word: `agent todo`, `bot done 2`. +Commands are accepted over DMs and on private named channels. The public +channel (index 0) and hashtag channels (`#name`) are ignored completely. + ### Reminder times | Syntax | Example | Meaning | @@ -64,8 +68,9 @@ item's due date on the Home Assistant side. - Direct messages are answered as direct messages to the sender's `pubkey_prefix`. -- Channel messages are answered back into the same channel; reminders set from - a channel are delivered back into that channel. +- Private channel messages (from allowlisted, known contacts) are answered + back into the same channel; reminders set from a channel are delivered back + into that channel. - Replies are truncated to the configured maximum length (default 200 chars). ## Home Assistant side @@ -77,9 +82,12 @@ same items can also be added, completed and deleted from the Home Assistant UI ## Security notes - Only allowlisted senders' commands are executed; everything else is ignored. -- The allowlist matches direct-message senders on their 12-hex `pubkey_prefix` - and channel senders on their advertised name. Names on channels are - self-reported — prefer key prefixes when allowlisting channel users. +- The allowlist matches **public key prefixes only** — names are never + trusted. A channel message carries a `pubkey_prefix` only when the sender + is a known contact of the companion, so channel users must be saved as + contacts on the companion to command the agent. +- The public channel (index 0) and all hashtag channels are ignored + unconditionally, regardless of the allowlist. ## Architecture diff --git a/custom_components/meshcore_agent/__init__.py b/custom_components/meshcore_agent/__init__.py index a4c4e88..0e7f303 100644 --- a/custom_components/meshcore_agent/__init__.py +++ b/custom_components/meshcore_agent/__init__.py @@ -28,6 +28,7 @@ from homeassistant.util import dt as dt_util from . import store as storage from .const import ( + ATTR_CHANNEL, ATTR_CHANNEL_IDX, ATTR_MESSAGE, ATTR_MESSAGE_TYPE, @@ -42,7 +43,9 @@ from .const import ( DEFAULT_MAX_REPLY, DOMAIN, EVENT_MESHCORE_MESSAGE, + HASHTAG_CHANNEL_PREFIX, MESH_CORE_DOMAIN, + PUBLIC_CHANNEL_IDX, SERVICE_MESHCORE_SEND_CHANNEL_MESSAGE, SERVICE_MESHCORE_SEND_MESSAGE, SIGNAL_STORE_UPDATED, @@ -139,15 +142,26 @@ class MeshCoreAgent: # -- allowlist ----------------------------------------------------------- def is_allowed(self, event_data: dict) -> bool: + """Only pubkey prefixes count; sender names are never trusted. + + Channel senders must therefore be known contacts of the companion + (the MeshCore integration includes their pubkey_prefix). + """ if self._allow_all: return True if not self._allowlist: return False - prefix = (event_data.get(ATTR_PUBKEY_PREFIX) or "").lower() - name = (event_data.get(ATTR_SENDER_NAME) or "").lower() - return ( - bool(prefix) and prefix in self._allowlist - ) or (bool(name) and name in self._allowlist) + prefix = (event_data.get(ATTR_PUBKEY_PREFIX) or "").strip().lower() + return bool(prefix) and prefix in self._allowlist + + def is_public_channel(self, event_data: dict) -> bool: + """True for the public channel (index 0) and hashtag channels.""" + if event_data.get(ATTR_MESSAGE_TYPE) != "channel": + return False + if event_data.get(ATTR_CHANNEL_IDX) == PUBLIC_CHANNEL_IDX: + return True + channel_name = str(event_data.get(ATTR_CHANNEL) or "") + return channel_name.startswith(HASHTAG_CHANNEL_PREFIX) # -- message handling ------------------------------------------------------ @@ -157,6 +171,13 @@ class MeshCoreAgent: return if data.get(ATTR_MESSAGE_TYPE) not in VALID_MESSAGE_TYPES: return + if self.is_public_channel(data): + _LOGGER.debug( + "Ignoring public/hashtag channel message (idx=%s, channel=%r)", + data.get(ATTR_CHANNEL_IDX), + data.get(ATTR_CHANNEL), + ) + return if not self.is_allowed(data): _LOGGER.debug( "Ignoring message from non-allowlisted sender %s", diff --git a/custom_components/meshcore_agent/config_flow.py b/custom_components/meshcore_agent/config_flow.py index 69c59d7..c924c3b 100644 --- a/custom_components/meshcore_agent/config_flow.py +++ b/custom_components/meshcore_agent/config_flow.py @@ -36,9 +36,22 @@ def _validate(user_input: dict[str, Any]) -> str | None: int(user_input[CONF_MAX_REPLY]) except (KeyError, TypeError, ValueError): return "invalid_max_reply" + allowlist = str(user_input.get(CONF_ALLOWLIST, "")).replace("\n", ",") + for part in allowlist.split(","): + part = part.strip() + if not part: + continue + if not is_hex_prefix(part): + return "invalid_allowlist" return None +def is_hex_prefix(value: str) -> bool: + """An allowlist entry must be 6-64 hex characters (a pubkey prefix).""" + v = value.lower() + return 6 <= len(v) <= 64 and all(c in "0123456789abcdef" for c in v) + + class ConfigFlowHandler(config_entries.ConfigFlow, domain=DOMAIN): """Handle the initial setup of the integration.""" diff --git a/custom_components/meshcore_agent/const.py b/custom_components/meshcore_agent/const.py index 21109d3..a0936bd 100644 --- a/custom_components/meshcore_agent/const.py +++ b/custom_components/meshcore_agent/const.py @@ -26,5 +26,11 @@ ATTR_OUTGOING = "outgoing" ATTR_MESSAGE_TYPE = "message_type" ATTR_SENDER_NAME = "sender_name" ATTR_PUBKEY_PREFIX = "pubkey_prefix" +ATTR_CHANNEL = "channel" ATTR_CHANNEL_IDX = "channel_idx" ATTR_ENTRY_ID = "entry_id" + +# Channel 0 is the public channel; hashtag channels ("#name") are the +# other shared channels. Neither may command the agent. +PUBLIC_CHANNEL_IDX = 0 +HASHTAG_CHANNEL_PREFIX = "#" diff --git a/custom_components/meshcore_agent/strings.json b/custom_components/meshcore_agent/strings.json index 55c2815..5e19aa9 100644 --- a/custom_components/meshcore_agent/strings.json +++ b/custom_components/meshcore_agent/strings.json @@ -4,32 +4,34 @@ "step": { "user": { "title": "MeshCore Agent", - "description": "Allow MeshCore nodes to talk to the agent. The allowlist accepts public key prefixes or contact names, separated by commas.", + "description": "Allow MeshCore nodes to talk to the agent. Only public key prefixes are accepted (channel senders must be known contacts to appear with one).", "data": { - "allowlist": "Allowed senders (pubkey prefixes or names, comma separated)", + "allowlist": "Allowed senders (pubkey prefixes, comma separated)", "allow_all": "Allow all senders (not recommended)", "max_reply": "Maximum reply length (characters)" } } }, "error": { - "invalid_max_reply": "Maximum reply length must be a number between 20 and 500." + "invalid_max_reply": "Maximum reply length must be a number between 20 and 500.", + "invalid_allowlist": "Allowlist entries must be public key prefixes (6-64 hex characters, comma separated)." } }, "options": { "step": { "init": { "title": "MeshCore Agent options", - "description": "Allow MeshCore nodes to talk to the agent. The allowlist accepts public key prefixes or contact names, separated by commas.", + "description": "Allow MeshCore nodes to talk to the agent. Only public key prefixes are accepted (channel senders must be known contacts to appear with one).", "data": { - "allowlist": "Allowed senders (pubkey prefixes or names, comma separated)", + "allowlist": "Allowed senders (pubkey prefixes, comma separated)", "allow_all": "Allow all senders (not recommended)", "max_reply": "Maximum reply length (characters)" } } }, "error": { - "invalid_max_reply": "Maximum reply length must be a number between 20 and 500." + "invalid_max_reply": "Maximum reply length must be a number between 20 and 500.", + "invalid_allowlist": "Allowlist entries must be public key prefixes (6-64 hex characters, comma separated)." } }, "entity": { diff --git a/custom_components/meshcore_agent/translations/en.json b/custom_components/meshcore_agent/translations/en.json index 55c2815..5e19aa9 100644 --- a/custom_components/meshcore_agent/translations/en.json +++ b/custom_components/meshcore_agent/translations/en.json @@ -4,32 +4,34 @@ "step": { "user": { "title": "MeshCore Agent", - "description": "Allow MeshCore nodes to talk to the agent. The allowlist accepts public key prefixes or contact names, separated by commas.", + "description": "Allow MeshCore nodes to talk to the agent. Only public key prefixes are accepted (channel senders must be known contacts to appear with one).", "data": { - "allowlist": "Allowed senders (pubkey prefixes or names, comma separated)", + "allowlist": "Allowed senders (pubkey prefixes, comma separated)", "allow_all": "Allow all senders (not recommended)", "max_reply": "Maximum reply length (characters)" } } }, "error": { - "invalid_max_reply": "Maximum reply length must be a number between 20 and 500." + "invalid_max_reply": "Maximum reply length must be a number between 20 and 500.", + "invalid_allowlist": "Allowlist entries must be public key prefixes (6-64 hex characters, comma separated)." } }, "options": { "step": { "init": { "title": "MeshCore Agent options", - "description": "Allow MeshCore nodes to talk to the agent. The allowlist accepts public key prefixes or contact names, separated by commas.", + "description": "Allow MeshCore nodes to talk to the agent. Only public key prefixes are accepted (channel senders must be known contacts to appear with one).", "data": { - "allowlist": "Allowed senders (pubkey prefixes or names, comma separated)", + "allowlist": "Allowed senders (pubkey prefixes, comma separated)", "allow_all": "Allow all senders (not recommended)", "max_reply": "Maximum reply length (characters)" } } }, "error": { - "invalid_max_reply": "Maximum reply length must be a number between 20 and 500." + "invalid_max_reply": "Maximum reply length must be a number between 20 and 500.", + "invalid_allowlist": "Allowlist entries must be public key prefixes (6-64 hex characters, comma separated)." } }, "entity": { diff --git a/tests/test_adapter.py b/tests/test_adapter.py index 9c9ece4..3198e96 100644 --- a/tests/test_adapter.py +++ b/tests/test_adapter.py @@ -1,6 +1,7 @@ """Tests for the HA-independent parts of the adapter (truncation, targets).""" from custom_components.meshcore_agent import target_from_event, truncate +from custom_components.meshcore_agent.config_flow import _validate, is_hex_prefix from custom_components.meshcore_agent.core.store import Reminder @@ -36,3 +37,21 @@ def test_target_channel(): def test_target_missing(): assert target_from_event({"message_type": "direct"}) is None assert target_from_event({"message_type": "channel"}) is None + + +def test_hex_prefix_validation(): + assert is_hex_prefix("aabbcc") + assert is_hex_prefix("DEF456ABC012") + assert is_hex_prefix("a" * 64) + assert not is_hex_prefix("groupchat") # names are never accepted + assert not is_hex_prefix("abc") # too short + assert not is_hex_prefix("aabbzz") # not hex + assert not is_hex_prefix("") + + +def test_config_validation(): + assert _validate({"allowlist": "aabbcc, def456abc012", "max_reply": "200"}) is None + assert _validate({"allowlist": "", "max_reply": 200}) is None + assert _validate({"allowlist": "myname", "max_reply": 200}) == "invalid_allowlist" + assert _validate({"allowlist": "aabbcc", "max_reply": 5}) is None # max_reply checked separately + assert _validate({"allowlist": "aabbcc"}) == "invalid_max_reply" diff --git a/tests/test_agent_flow.py b/tests/test_agent_flow.py index d74b565..7d3b593 100644 --- a/tests/test_agent_flow.py +++ b/tests/test_agent_flow.py @@ -142,12 +142,14 @@ async def test_allow_all_option(): async def test_channel_message_replies_to_channel(): - agent, hass = make_agent(allowlist="groupchat") + agent, hass = make_agent(allowlist="def456abc012") await deliver( agent, { "message_type": "channel", "channel_idx": 1, + "channel": "friends", + "pubkey_prefix": "def456abc012", "sender_name": "groupchat", "message": "agent todo add From channel", }, @@ -161,6 +163,8 @@ async def test_channel_message_replies_to_channel(): { "message_type": "channel", "channel_idx": 1, + "channel": "friends", + "pubkey_prefix": "def456abc012", "sender_name": "groupchat", "message": "remind 1 in 30m", }, @@ -170,6 +174,70 @@ async def test_channel_message_replies_to_channel(): assert reminder.target == "1" +async def test_public_channel_ignored(): + agent, hass = make_agent(allow_all=True) + await deliver( + agent, + { + "message_type": "channel", + "channel_idx": 0, + "channel": "public", + "pubkey_prefix": "def456abc012", + "message": "agent todo add From public", + }, + ) + assert hass.services.calls == [] + assert agent.todo_store.items == [] + + +async def test_hashtag_channel_ignored(): + agent, hass = make_agent(allow_all=True) + await deliver( + agent, + { + "message_type": "channel", + "channel_idx": 1, + "channel": "#mychannel", + "pubkey_prefix": "def456abc012", + "message": "agent todo add From hashtag", + }, + ) + assert hass.services.calls == [] + assert agent.todo_store.items == [] + + +async def test_channel_non_contact_ignored(): + # Channel messages carry no pubkey_prefix unless the sender is a known + # contact of the companion; names are never matched. + agent, hass = make_agent(allowlist="def456abc012") + await deliver( + agent, + { + "message_type": "channel", + "channel_idx": 1, + "channel": "friends", + "sender_name": "groupchat", + "message": "agent todo add From channel", + }, + ) + assert hass.services.calls == [] + assert agent.todo_store.items == [] + + +async def test_allowlist_never_matches_names(): + agent, hass = make_agent(allowlist="groupchat") + await deliver( + agent, + { + "message_type": "direct", + "sender_name": "groupchat", + "pubkey_prefix": "ffff00", + "message": "todo", + }, + ) + assert hass.services.calls == [] + + async def test_reminder_firing(): agent, hass = make_agent() await deliver(