Files
meshcore-ansible/plugins/modules/meshcore_companion_acl.py
T
tthandClaude Opus 5.5 0a4cfafc78
ci / test (push) Successful in 2m39s
tth.meshcore: MeshCore repeaters as code, over RF
Ansible collection that converges MeshCore repeaters through a companion
radio (TCP, USB serial or BLE): admin ACL, CLI prefs, region tree,
firmware facts, companion remote-CLI ACL, and the meshcore-tth extras
(BLE on/off and own BLE PIN, channel-hash filter, message age, advert
fairness). Every change is read, diffed, sent and read back; --check
only reads. ansible-test sanity, unit tests and a galaxy build in CI.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-03 02:23:24 +01:00

218 lines
8.5 KiB
Python

# Copyright: (c) 2026, TeTeHacko <tth@rfa.cz>
# GNU General Public License v3.0+ (see LICENSE or https://www.gnu.org/licenses/gpl-3.0.txt)
DOCUMENTATION = r"""
module: meshcore_companion_acl
short_description: Remote-CLI ACL of a MeshCore companion (contact flag 0x10), over its BLE link
author: TeTeHacko (@TeTeHacko)
description:
- A companion (fw 1.18+, Solo 2.0+) runs a CLI command that arrives as
TXT_TYPE_CLI_COMMAND only from a contact flagged "remote CLI"
(ContactInfo flags bit 0x10). That flag IS its ACL, and the remote CLI can
do everything (radio, name, PIN, reboot), so the set is converged exactly
like a repeater's ACL - the listed keys get it, every other contact loses it.
- Flags live on the companion and can only be changed over its own link, so
this runs on a host with BLE in range (bleak, NUS, one write = one frame) and
needs a bond with the node. A listed key the companion does not know is
added as a chat contact; when its table is full, the contact heard longest
ago that is neither a favourite nor in the list is removed to make room
(what the firmware's own auto-add does) and reported in C(evicted).
- Each contact is read, only its flags byte changed, and written back
(CMD_ADD_UPDATE_CONTACT takes the CONTACT frame layout), so path, name and
the other flag bits (favourite, telemetry, Solo's kept route) are kept.
options:
mac: {description: BLE MAC of the companion., type: str, required: true}
admins: {description: Pubkeys (64 hex) that get remote CLI., type: list, elements: str, required: true}
names: {description: pubkey -> name for contacts that have to be added., type: dict, default: {}}
timeout: {description: Seconds for the whole BLE session., type: int, default: 120}
"""
EXAMPLES = r"""
- name: Remote CLI only for these keys
tth.meshcore.meshcore_companion_acl:
mac: "AA:BB:CC:DD:EE:FF"
admins:
- "{{ my_phone_pubkey }}"
names:
"{{ my_phone_pubkey }}": my-phone
"""
import asyncio
import re
import struct
from ansible.module_utils.basic import AnsibleModule
try:
from bleak import BleakClient
HAS_BLEAK = True
except ImportError:
HAS_BLEAK = False
RX = "6e400002-b5a3-f393-e0a9-e50e24dcca9e"
TX = "6e400003-b5a3-f393-e0a9-e50e24dcca9e"
CMD_APP_START = 1
CMD_GET_CONTACTS = 4
CMD_ADD_UPDATE_CONTACT = 9
CMD_REMOVE_CONTACT = 15
ERR_TABLE_FULL = 3
FLAG_FAV = 0x01
RESP_OK = 0
RESP_ERR = 1
RESP_CONTACTS_START = 2
RESP_CONTACT = 3
RESP_END = 4
RESP_SELF_INFO = 5
FLAG_REMOTE_CLI = 0x10
HEX64 = re.compile(r"^[0-9a-f]{64}$")
# CONTACT frame: code pub[32] type flags out_path_len out_path[64] name[32]
# last_advert[4] lat[4] lon[4] lastmod[4]
OFF_FLAGS = 1 + 32 + 1
OFF_NAME = 1 + 32 + 3 + 64
OFF_LAST_ADVERT = OFF_NAME + 32
CONTACT_LEN = 1 + 32 + 3 + 64 + 32 + 16
class Ble:
def __init__(self, client):
self.c = client
self.q = asyncio.Queue()
async def start(self):
await self.c.start_notify(TX, lambda _, d: self.q.put_nowait(bytes(d)))
async def send(self, frame, want, timeout=10):
await self.c.write_gatt_char(RX, frame, response=True)
while True:
f = await asyncio.wait_for(self.q.get(), timeout)
if f and f[0] in want:
return f
def new_contact_frame(pubkey, name, flags):
nm = name.encode()[:31].ljust(32, b"\0")
return (
bytes([CMD_ADD_UPDATE_CONTACT])
+ bytes.fromhex(pubkey)
+ bytes([1, flags, 0xFF])
+ bytes(64)
+ nm
+ struct.pack("<I", 0)
)
async def work(module, mac, admins, names):
want = {pk.lower(): names.get(pk) or ("acl-" + pk[:8]) for pk in admins}
async with BleakClient(mac, timeout=30) as client:
ble = Ble(client)
await ble.start()
si = await ble.send(bytes([CMD_APP_START, 3]) + bytes(6) + b"ansible", {RESP_SELF_INFO})
self_pub = si[4:36].hex()
await ble.send(bytes([CMD_GET_CONTACTS]), {RESP_CONTACTS_START})
contacts = {}
while True:
f = await asyncio.wait_for(ble.q.get(), 15)
if f[0] == RESP_END:
break
if f[0] == RESP_CONTACT and len(f) >= CONTACT_LEN - 4:
contacts[f[1:33].hex()] = f
plan = [] # (pubkey, name, old_flags or None, new_flags)
for pk, f in contacts.items():
has = bool(f[OFF_FLAGS] & FLAG_REMOTE_CLI)
if has != (pk in want):
plan.append(
(
pk,
f[OFF_NAME : OFF_NAME + 32].split(b"\0")[0].decode(errors="replace") or pk[:8],
f[OFF_FLAGS],
f[OFF_FLAGS] ^ FLAG_REMOTE_CLI,
)
)
for pk, name in want.items():
if pk not in contacts and pk != self_pub:
plan.append((pk, name, None, FLAG_REMOTE_CLI))
evicted = []
def victim():
cands = [
(struct.unpack_from("<I", f, OFF_LAST_ADVERT)[0], pk)
for pk, f in contacts.items()
if pk not in want and not f[OFF_FLAGS] & (FLAG_FAV | FLAG_REMOTE_CLI)
]
return min(cands)[1] if cands else None
if not module.check_mode:
for pk, name, old, new in plan:
if old is None:
frame = new_contact_frame(pk, name, new)
else:
f = bytearray(contacts[pk])
f[0] = CMD_ADD_UPDATE_CONTACT
f[OFF_FLAGS] = new
frame = bytes(f[: CONTACT_LEN - 4]) # without lastmod: the node stamps it
r = await ble.send(frame, {RESP_OK, RESP_ERR})
if r[0] == RESP_ERR and r[1:2] == bytes([ERR_TABLE_FULL]) and old is None:
v = victim()
if v is None:
raise RuntimeError("contact table full and nothing safe to remove")
vf = contacts.pop(v)
rr = await ble.send(bytes([CMD_REMOVE_CONTACT]) + bytes.fromhex(v), {RESP_OK, RESP_ERR})
if rr[0] != RESP_OK:
raise RuntimeError(f"could not remove {v[:12]} to make room")
evicted.append(
{"pubkey": v, "name": vf[OFF_NAME : OFF_NAME + 32].split(b"\0")[0].decode(errors="replace")}
)
r = await ble.send(frame, {RESP_OK, RESP_ERR})
if r[0] != RESP_OK:
raise RuntimeError(f"companion refused {name} ({pk[:12]}): error {r[1:2].hex()}")
return self_pub, len(contacts), plan, evicted
def main():
module = AnsibleModule(
argument_spec={
"mac": {"type": "str", "required": True},
"admins": {"type": "list", "elements": "str", "required": True},
"names": {"type": "dict", "default": {}},
"timeout": {"type": "int", "default": 120},
},
supports_check_mode=True,
)
if not HAS_BLEAK:
module.fail_json(msg="bleak is required on the BLE host")
for pk in module.params["admins"]:
if not HEX64.match(pk.lower()):
module.fail_json(msg=f"admin pubkey must be 64 hex: {pk}")
mac = module.params["mac"]
_rc, info, _err = module.run_command(["bluetoothctl", "info", mac])
if "Connected: yes" in info:
module.fail_json(msg=f"{mac} is held by another client on this host (a phone or desktop app?) -- nothing sent")
if "Bonded: yes" not in info:
module.fail_json(msg=f"{mac} has no bond on this host -- pair it first (bluetoothctl pair)")
try:
self_pub, n, plan, evicted = asyncio.run(
asyncio.wait_for(
work(module, mac, module.params["admins"], module.params["names"]), module.params["timeout"]
)
)
except Exception as e: # noqa: BLE001 -- BLE/GATT errors come in many types
module.fail_json(msg=f"{type(e).__name__}: {e}")
lines_before = sorted(
f"{pk[:12]} {name}" for pk, name, old, new in plan if old is not None and old & FLAG_REMOTE_CLI
)
lines_after = sorted(f"{pk[:12]} {name}" for pk, name, old, new in plan if new & FLAG_REMOTE_CLI)
module.exit_json(
changed=bool(plan),
self_pubkey=self_pub,
contacts=n,
evicted=evicted,
plan=[
{"pubkey": pk, "name": name, "add_contact": old is None, "remote_cli": bool(new & FLAG_REMOTE_CLI)}
for pk, name, old, new in plan
],
diff={"before": "\n".join(lines_before) + "\n", "after": "\n".join(lines_after) + "\n"},
)
if __name__ == "__main__":
main()