Allowlist pubkey prefixes only; ignore public and hashtag channels

- is_allowed matches pubkey_prefix only; sender names are never trusted
  (channel senders must be known contacts of the companion for the
  MeshCore integration to include their pubkey_prefix)
- channel messages on channel index 0 (public) and hashtag channels
  ('#name') are ignored unconditionally, before the allowlist check
- config flow validates allowlist entries as 6-64 hex characters
  (invalid_allowlist error) and UI strings/README updated
This commit is contained in:
Dejvino
2026-12-01 19:45:36 +01:00
parent 8eba7fa24c
commit 5d60a91964
8 changed files with 165 additions and 26 deletions
+16 -8
View File
@@ -22,9 +22,10 @@ it listens for `meshcore_message` events and replies via the
2. Install **MeshCore Agent**. 2. Install **MeshCore Agent**.
3. Restart Home Assistant. 3. Restart Home Assistant.
4. Settings → Devices & services → *Add Integration* → **MeshCore Agent**. 4. Settings → Devices & services → *Add Integration* → **MeshCore Agent**.
5. Fill in the allowlist of senders who may command the agent (public key 5. Fill in the allowlist of senders who may command the agent — **public key
prefixes or contact names, comma separated). Leave "Allow all senders" prefixes only** (comma separated; the same format the MeshCore integration
unchecked; anyone on the mesh could otherwise command your todo list. uses). Leave "Allow all senders" unchecked; anyone on the mesh could
otherwise command your todo list.
## Mesh commands ## Mesh commands
@@ -46,6 +47,9 @@ channel's senders are allowlisted):
(`todo done buy m`). Messages may optionally start with a wake word: (`todo done buy m`). Messages may optionally start with a wake word:
`agent todo`, `bot done 2`. `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 ### Reminder times
| Syntax | Example | Meaning | | 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 - Direct messages are answered as direct messages to the sender's
`pubkey_prefix`. `pubkey_prefix`.
- Channel messages are answered back into the same channel; reminders set from - Private channel messages (from allowlisted, known contacts) are answered
a channel are delivered back into that channel. 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). - Replies are truncated to the configured maximum length (default 200 chars).
## Home Assistant side ## Home Assistant side
@@ -77,9 +82,12 @@ same items can also be added, completed and deleted from the Home Assistant UI
## Security notes ## Security notes
- Only allowlisted senders' commands are executed; everything else is ignored. - Only allowlisted senders' commands are executed; everything else is ignored.
- The allowlist matches direct-message senders on their 12-hex `pubkey_prefix` - The allowlist matches **public key prefixes only** — names are never
and channel senders on their advertised name. Names on channels are trusted. A channel message carries a `pubkey_prefix` only when the sender
self-reported — prefer key prefixes when allowlisting channel users. 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 ## Architecture
+26 -5
View File
@@ -28,6 +28,7 @@ from homeassistant.util import dt as dt_util
from . import store as storage from . import store as storage
from .const import ( from .const import (
ATTR_CHANNEL,
ATTR_CHANNEL_IDX, ATTR_CHANNEL_IDX,
ATTR_MESSAGE, ATTR_MESSAGE,
ATTR_MESSAGE_TYPE, ATTR_MESSAGE_TYPE,
@@ -42,7 +43,9 @@ from .const import (
DEFAULT_MAX_REPLY, DEFAULT_MAX_REPLY,
DOMAIN, DOMAIN,
EVENT_MESHCORE_MESSAGE, EVENT_MESHCORE_MESSAGE,
HASHTAG_CHANNEL_PREFIX,
MESH_CORE_DOMAIN, MESH_CORE_DOMAIN,
PUBLIC_CHANNEL_IDX,
SERVICE_MESHCORE_SEND_CHANNEL_MESSAGE, SERVICE_MESHCORE_SEND_CHANNEL_MESSAGE,
SERVICE_MESHCORE_SEND_MESSAGE, SERVICE_MESHCORE_SEND_MESSAGE,
SIGNAL_STORE_UPDATED, SIGNAL_STORE_UPDATED,
@@ -139,15 +142,26 @@ class MeshCoreAgent:
# -- allowlist ----------------------------------------------------------- # -- allowlist -----------------------------------------------------------
def is_allowed(self, event_data: dict) -> bool: 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: if self._allow_all:
return True return True
if not self._allowlist: if not self._allowlist:
return False return False
prefix = (event_data.get(ATTR_PUBKEY_PREFIX) or "").lower() prefix = (event_data.get(ATTR_PUBKEY_PREFIX) or "").strip().lower()
name = (event_data.get(ATTR_SENDER_NAME) or "").lower() return bool(prefix) and prefix in self._allowlist
return (
bool(prefix) and prefix in self._allowlist def is_public_channel(self, event_data: dict) -> bool:
) or (bool(name) and name in self._allowlist) """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 ------------------------------------------------------ # -- message handling ------------------------------------------------------
@@ -157,6 +171,13 @@ class MeshCoreAgent:
return return
if data.get(ATTR_MESSAGE_TYPE) not in VALID_MESSAGE_TYPES: if data.get(ATTR_MESSAGE_TYPE) not in VALID_MESSAGE_TYPES:
return 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): if not self.is_allowed(data):
_LOGGER.debug( _LOGGER.debug(
"Ignoring message from non-allowlisted sender %s", "Ignoring message from non-allowlisted sender %s",
@@ -36,9 +36,22 @@ def _validate(user_input: dict[str, Any]) -> str | None:
int(user_input[CONF_MAX_REPLY]) int(user_input[CONF_MAX_REPLY])
except (KeyError, TypeError, ValueError): except (KeyError, TypeError, ValueError):
return "invalid_max_reply" 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 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): class ConfigFlowHandler(config_entries.ConfigFlow, domain=DOMAIN):
"""Handle the initial setup of the integration.""" """Handle the initial setup of the integration."""
@@ -26,5 +26,11 @@ ATTR_OUTGOING = "outgoing"
ATTR_MESSAGE_TYPE = "message_type" ATTR_MESSAGE_TYPE = "message_type"
ATTR_SENDER_NAME = "sender_name" ATTR_SENDER_NAME = "sender_name"
ATTR_PUBKEY_PREFIX = "pubkey_prefix" ATTR_PUBKEY_PREFIX = "pubkey_prefix"
ATTR_CHANNEL = "channel"
ATTR_CHANNEL_IDX = "channel_idx" ATTR_CHANNEL_IDX = "channel_idx"
ATTR_ENTRY_ID = "entry_id" 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 = "#"
@@ -4,32 +4,34 @@
"step": { "step": {
"user": { "user": {
"title": "MeshCore Agent", "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": { "data": {
"allowlist": "Allowed senders (pubkey prefixes or names, comma separated)", "allowlist": "Allowed senders (pubkey prefixes, comma separated)",
"allow_all": "Allow all senders (not recommended)", "allow_all": "Allow all senders (not recommended)",
"max_reply": "Maximum reply length (characters)" "max_reply": "Maximum reply length (characters)"
} }
} }
}, },
"error": { "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": { "options": {
"step": { "step": {
"init": { "init": {
"title": "MeshCore Agent options", "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": { "data": {
"allowlist": "Allowed senders (pubkey prefixes or names, comma separated)", "allowlist": "Allowed senders (pubkey prefixes, comma separated)",
"allow_all": "Allow all senders (not recommended)", "allow_all": "Allow all senders (not recommended)",
"max_reply": "Maximum reply length (characters)" "max_reply": "Maximum reply length (characters)"
} }
} }
}, },
"error": { "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": { "entity": {
@@ -4,32 +4,34 @@
"step": { "step": {
"user": { "user": {
"title": "MeshCore Agent", "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": { "data": {
"allowlist": "Allowed senders (pubkey prefixes or names, comma separated)", "allowlist": "Allowed senders (pubkey prefixes, comma separated)",
"allow_all": "Allow all senders (not recommended)", "allow_all": "Allow all senders (not recommended)",
"max_reply": "Maximum reply length (characters)" "max_reply": "Maximum reply length (characters)"
} }
} }
}, },
"error": { "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": { "options": {
"step": { "step": {
"init": { "init": {
"title": "MeshCore Agent options", "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": { "data": {
"allowlist": "Allowed senders (pubkey prefixes or names, comma separated)", "allowlist": "Allowed senders (pubkey prefixes, comma separated)",
"allow_all": "Allow all senders (not recommended)", "allow_all": "Allow all senders (not recommended)",
"max_reply": "Maximum reply length (characters)" "max_reply": "Maximum reply length (characters)"
} }
} }
}, },
"error": { "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": { "entity": {
+19
View File
@@ -1,6 +1,7 @@
"""Tests for the HA-independent parts of the adapter (truncation, targets).""" """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 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 from custom_components.meshcore_agent.core.store import Reminder
@@ -36,3 +37,21 @@ def test_target_channel():
def test_target_missing(): def test_target_missing():
assert target_from_event({"message_type": "direct"}) is None assert target_from_event({"message_type": "direct"}) is None
assert target_from_event({"message_type": "channel"}) 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"
+69 -1
View File
@@ -142,12 +142,14 @@ async def test_allow_all_option():
async def test_channel_message_replies_to_channel(): async def test_channel_message_replies_to_channel():
agent, hass = make_agent(allowlist="groupchat") agent, hass = make_agent(allowlist="def456abc012")
await deliver( await deliver(
agent, agent,
{ {
"message_type": "channel", "message_type": "channel",
"channel_idx": 1, "channel_idx": 1,
"channel": "friends",
"pubkey_prefix": "def456abc012",
"sender_name": "groupchat", "sender_name": "groupchat",
"message": "agent todo add From channel", "message": "agent todo add From channel",
}, },
@@ -161,6 +163,8 @@ async def test_channel_message_replies_to_channel():
{ {
"message_type": "channel", "message_type": "channel",
"channel_idx": 1, "channel_idx": 1,
"channel": "friends",
"pubkey_prefix": "def456abc012",
"sender_name": "groupchat", "sender_name": "groupchat",
"message": "remind 1 in 30m", "message": "remind 1 in 30m",
}, },
@@ -170,6 +174,70 @@ async def test_channel_message_replies_to_channel():
assert reminder.target == "1" 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(): async def test_reminder_firing():
agent, hass = make_agent() agent, hass = make_agent()
await deliver( await deliver(