From 3a60771dd97c50c8281e710a540288fd5031702d Mon Sep 17 00:00:00 2001 From: Jean-Pierre Martineau Date: Tue, 3 Nov 2026 23:41:09 -0500 Subject: [PATCH] Del in the admin picker forgets a stored admin password The menu had no way to make MeshTerm forget an admin password (#28). Now Del on a managed node in the node picker asks first (amber, Cancel or Forget), then forgets the password. The list refreshes in place: the node leaves "Managed nodes" and the highlight stays on it. The footer shows "Del forget" only on a managed row, and the PicoCalc lane shows its Delete chip. The first page of the TX optimize dialog has the same rows, so it takes the same Del. A wizard page can now carry a Del key and an on_delete handler, and a turned page brings its own Del key, so the second page shows none. The feature guide also describes the new-password offer of the previous commit. Co-Authored-By: Claude Opus 5.5 --- docs/guide/features.md | 2 +- meshterm/tools/tx_optimize.py | 13 ++++- meshterm/ui/admin_picker.py | 86 +++++++++++++++++++++++++++++++-- meshterm/ui/menus.py | 32 ++++++++++++- meshterm/ui/tui/select.py | 15 +++++- tests/test_managed_nodes.py | 89 +++++++++++++++++++++++++++++++++++ tests/test_navigation.py | 62 ++++++++++++++++++++++++ 7 files changed, 289 insertions(+), 10 deletions(-) diff --git a/docs/guide/features.md b/docs/guide/features.md index d1a1ecb..a501342 100644 --- a/docs/guide/features.md +++ b/docs/guide/features.md @@ -55,7 +55,7 @@ This page lists each interactive screen with its scripted equivalent, where one | Feature | What it does | Scripted | | --- | --- | --- | -| **🗼 Repeater admin** | Set up remote repeaters and room servers over the mesh. First, log in with a remembered password or a password that MeshTerm asks for. Then use an editor in the style of Device config, which speaks the text CLI of the node. It includes the settings that only repeaters have (TX delay, airtime factor, and advert intervals). It also has one-shot actions and a remote command line with readline. A **Regions** page edits the region tree of the repeater: the regions for which it relays floods, and whether it relays unscoped floods. It also edits the home scope and the default scope. | `meshterm repeater-admin ` | +| **🗼 Repeater admin** | Set up remote repeaters and room servers over the mesh. First, log in with a remembered password or a password that MeshTerm asks for. A node does not answer a wrong password. Thus, when a remembered password gets no reply, MeshTerm offers to replace it, because the owner of the node possibly changed it. To forget a remembered password, press Del on its node in the node picker. Then use an editor in the style of Device config, which speaks the text CLI of the node. It includes the settings that only repeaters have (TX delay, airtime factor, and advert intervals). It also has one-shot actions and a remote command line with readline. A **Regions** page edits the region tree of the repeater: the regions for which it relays floods, and whether it relays unscoped floods. It also edits the home scope and the default scope. | `meshterm repeater-admin ` | | **🔖 Regions** | This is not a menu screen. The node page of a repeater lists the regions that the repeater carries. MeshTerm asks the repeater one time, without a login. The repeater answers only a neighbour, or a request over a known route. The packet viewer, the message paths, and the live feed show the region of a scoped flood. | `meshterm regions ` | | **📶 TX optimize** | Sweep the transmit power of a remote node while you watch. The sweep has three steps: coarse, then refine, then verify. You see each level as it lands, and you decide whether to apply the best level. The scripted form applies the best level unless you tell it not to. | `meshterm tx-optimize --path … [--no-apply]` | diff --git a/meshterm/tools/tx_optimize.py b/meshterm/tools/tx_optimize.py index 2d14484..33d7d68 100644 --- a/meshterm/tools/tx_optimize.py +++ b/meshterm/tools/tx_optimize.py @@ -128,7 +128,7 @@ class TxOptimizeTool(Tool): Returns: A :class:`ToolResult` that repeats the stored summary of the sweep. """ - from ..ui.admin_picker import admin_picker_rows + from ..ui.admin_picker import FORGET_HINT, admin_picker_rows, forget_row from ..ui.menus import WizardPage, run_wizard from ..ui.surface import TuiUi from ..ui.tx_screen import open_tx_optimize @@ -149,12 +149,23 @@ class TxOptimizeTool(Tool): def admin_of(values: list) -> Contact: return next(c for c in candidates if c.name == values[0]) + async def forget(value: Any) -> list | None: + nonlocal items + rows = await forget_row(ctx, contacts, value) + if rows is not None: + items = rows # so that a turn back to this page shows the change + return rows + def node_page(values: list) -> WizardPage: + # Delete on a managed node forgets its password, as in the picker of + # repeater admin (refer to :func:`~meshterm.ui.admin_picker.forget_row`). return WizardPage( title="TX optimize — node to tune · step 1 of 2", items=items, prompt="Whose transmit power gets tuned (you need its admin password):", default=values[0], + delete_hint=FORGET_HINT, + on_delete=forget, ) def target_page(values: list) -> WizardPage | Any: diff --git a/meshterm/ui/admin_picker.py b/meshterm/ui/admin_picker.py index ec05d00..c36eb21 100644 --- a/meshterm/ui/admin_picker.py +++ b/meshterm/ui/admin_picker.py @@ -15,6 +15,11 @@ It is drawn as a box, and it is gone when the user answers it. It is never a scr stack under the page of the tool, where Esc would land. It was once kept pushed as a hub for the whole visit. Then, when the user left the admin page, Esc landed on the list from which the user selected the node. This looked like two places where there is one. + +Delete on a managed node forgets its password, after a confirm (``Del forget``). This is +the one place in the menu where the user can make MeshTerm forget an admin password. A +stock node does not answer a wrong password, so MeshTerm cannot find out by itself that a +stored password is stale (GitHub issue 28, and refer to :mod:`meshterm.ui.admin_login`). """ from __future__ import annotations @@ -28,6 +33,9 @@ from ..core.models import NODE_TYPE_REPEATER, NODE_TYPE_ROOM, Contact if TYPE_CHECKING: from ..context import AppContext +#: The footer atom of the Delete key on a managed node. +FORGET_HINT = "Del forget" + def admin_picker_rows(ctx: AppContext, contacts: list[Contact]) -> tuple[list, list[Contact]]: """Build the grouped rows of the admin-node picker and the contacts that they map to. @@ -36,6 +44,8 @@ def admin_picker_rows(ctx: AppContext, contacts: list[Contact]) -> tuple[list, l list. :func:`pick_admin_node` runs these rows as a one-shot dialog. TX optimize turns them as the first page of its dialog with steps. Each row has ``value = contact.name``, so a name that the user selects (or a ``default``) resolves through ``candidates``. + The rows of the managed nodes are :attr:`~meshterm.ui.tui.select.Choice.deletable`: + Delete on one of them forgets its password (refer to :func:`forget_row`). Args: ctx: The shared application context (for the admin store, which sorts the @@ -56,7 +66,7 @@ def admin_picker_rows(ctx: AppContext, contacts: list[Contact]) -> tuple[list, l from .tui import Choice from .widgets import DEFAULT_GLYPH, NODE_GLYPHS - candidates = [c for c in contacts if (c.public_key or c.key_prefix).strip()] + candidates = _candidates(contacts) if not candidates: return [], candidates remembered = [c for c in candidates if ctx.admin_store.get(c) is not None] @@ -80,7 +90,7 @@ def admin_picker_rows(ctx: AppContext, contacts: list[Contact]) -> tuple[list, l contact.name, style=name_style(contact.name, contact.public_key or contact.key_prefix), ) - return Choice(title=label, value=contact.name) + return Choice(title=label, value=contact.name, deletable=contact in remembered) def recency(contact: Contact) -> float: return -(contact.last_seen.timestamp() if contact.last_seen else 0.0) @@ -137,14 +147,75 @@ async def pick_admin_node( await _note_nothing_to_pick(ctx, title) return None - choice = await ctx.ui.select( + from .tui import CANCEL, SelectScreen + from .tui.select import DeleteRequest + + screen = SelectScreen( title, items, prompt=prompt, default=default.name if default is not None else None, - floating=True, + delete_hint=FORGET_HINT, ) - return _resolve(candidates, choice) + # The box stays pushed while the user forgets passwords in it, so the confirm floats + # over the list, and the list refreshes in place. It is popped before the caller + # gets the node, as a one-shot dialog is. + async with ctx.ui.session.stay(screen, dialog=True) as visit: + while True: + choice = await visit.result() + if isinstance(choice, DeleteRequest): + rows = await forget_row(ctx, contacts, choice.value) + if rows is not None: + screen.replace_items(rows) + continue + return None if choice is CANCEL else _resolve(candidates, choice) + + +async def forget_password(ctx: AppContext, node: Contact) -> bool: + """Ask for a confirmation, then forget the stored admin password of ``node``. + + The confirm is amber, as the confirm to forget a room is: the next login asks for the + password again, and a user who does not know it any more cannot log in. + + Args: + ctx: The shared application context (for the dialog and the admin store). + node: The managed node. + + Returns: + ``True`` when MeshTerm forgot the password. + """ + if not await ctx.ui.dialog( + f"Forget the admin password of {node.name}? The next login asks for it again.", + [("Cancel", False), ("Forget", True)], + title=f"Forget password — {node.name}", + default=1, + danger=True, + ): + return False + ctx.admin_store.forget(node) + return True + + +async def forget_row(ctx: AppContext, contacts: list[Contact], value: Any) -> list | None: + """Forget the password of the node on a picker row, and return the new rows. + + This is what Delete does on a row of :func:`admin_picker_rows`, in each list that + shows those rows (:func:`pick_admin_node`, and the first page of the TX optimize + dialog). The node moves out of the managed section, so the caller replaces the rows. + + Args: + ctx: The shared application context. + contacts: The contacts that the rows were built from. + value: The value of the row (the name of the contact). + + Returns: + The new rows, or ``None`` when nothing changed (the user cancelled, or the row + names no node). + """ + node = _resolve(_candidates(contacts), value) + if node is None or not await forget_password(ctx, node): + return None + return admin_picker_rows(ctx, contacts)[0] async def _note_nothing_to_pick(ctx: AppContext, title: str) -> None: @@ -153,6 +224,11 @@ async def _note_nothing_to_pick(ctx: AppContext, title: str) -> None: await ctx.ui.present(title=title) +def _candidates(contacts: list[Contact]) -> list[Contact]: + """The contacts that the picker can offer: those that have a key.""" + return [c for c in contacts if (c.public_key or c.key_prefix).strip()] + + def _resolve(candidates: list[Contact], choice: Any) -> Contact | None: """The contact for the name of a selected row, or ``None`` if the user selected nothing.""" if choice is None: diff --git a/meshterm/ui/menus.py b/meshterm/ui/menus.py index 7748b87..2084a96 100644 --- a/meshterm/ui/menus.py +++ b/meshterm/ui/menus.py @@ -577,12 +577,21 @@ class WizardPage: default: The value to highlight. When the user comes back to a step, the step gives its previous answer here. :func:`run_steps` uses the same convention for its steps. + delete_hint: The ``Del`` atom of the page, for rows marked + :attr:`~meshterm.ui.tui.select.Choice.deletable`. Empty for a page that removes + nothing. + on_delete: What Delete does on a row of this page. It gets the value of the row + and returns the new rows of the page, or ``None`` when nothing changed (for + example, the user cancelled a confirm). The page stays open in both cases, + because a removal is not an answer to the question of the page. """ title: str items: list prompt: str = "" default: Any = None + delete_hint: str = "" + on_delete: Callable[[Any], Awaitable[list | None]] | None = None async def run_wizard( @@ -625,16 +634,31 @@ async def run_wizard( """ from .tui import SelectScreen from .tui.screen import CANCEL + from .tui.select import DeleteRequest values: list = [None] * len(pages) index = 0 step = pages[0](values) if not isinstance(step, WizardPage): raise TypeError("the first step of a wizard must be a WizardPage") - screen = SelectScreen(step.title, step.items, prompt=step.prompt, default=step.default) + screen = SelectScreen( + step.title, + step.items, + prompt=step.prompt, + default=step.default, + delete_hint=step.delete_hint, + ) async with session.stay(screen, dialog=True) as visit: while True: answer = await visit.result() if isinstance(step, WizardPage) else await step + if isinstance(answer, DeleteRequest): + # A removal on the page, not an answer: the page refreshes in place, and the + # highlight follows its row. + if isinstance(step, WizardPage) and step.on_delete is not None: + items = await step.on_delete(answer.value) + if items is not None: + screen.replace_items(items) + continue if answer is CANCEL or answer is None: index -= 1 if index < 0: @@ -649,7 +673,11 @@ async def run_wizard( step = pages[index](values) if isinstance(step, WizardPage): screen.turn_page( - step.items, title=step.title, prompt=step.prompt, default=step.default + step.items, + title=step.title, + prompt=step.prompt, + default=step.default, + delete_hint=step.delete_hint, ) diff --git a/meshterm/ui/tui/select.py b/meshterm/ui/tui/select.py index 0134cfc..f5e4950 100644 --- a/meshterm/ui/tui/select.py +++ b/meshterm/ui/tui/select.py @@ -523,7 +523,15 @@ class SelectScreen(Screen): self._index = i return - def turn_page(self, items: list, *, title: str, prompt: str = "", default: Any = None) -> None: + def turn_page( + self, + items: list, + *, + title: str, + prompt: str = "", + default: Any = None, + delete_hint: str = "", + ) -> None: """Show a different list in the same box: the next or previous page of a stepped dialog. This is the other way that the rows of a list change while the user looks at them. @@ -538,6 +546,8 @@ class SelectScreen(Screen): - The highlight goes to ``default`` or to the first row. (A page that the user turns back to offers its previous answer, exactly as a step of :func:`~meshterm.ui.menus.run_steps` does.) + - The Delete key is the key of the new page. A page that removes nothing gets no + ``Del`` atom and no ``Delete`` chip on the F-key lane. Args: items: The rows of the new page, in the order to show. @@ -545,7 +555,10 @@ class SelectScreen(Screen): is. prompt: The instruction above the rows, or ``""`` for none. default: The choice value to highlight, if it is present. + delete_hint: The ``Del`` atom of the new page (refer to the argument of the + same name of :class:`SelectScreen`), or ``""`` for none. """ + self._delete_hint = delete_hint self._items = items if self._hscroll_auto: self._hscroll = any(getattr(item, "hscroll_from", 0) > 0 for item in items) diff --git a/tests/test_managed_nodes.py b/tests/test_managed_nodes.py index 3af4432..bc500a1 100644 --- a/tests/test_managed_nodes.py +++ b/tests/test_managed_nodes.py @@ -161,6 +161,95 @@ def test_the_admin_picker_lists_managed_nodes_first_with_the_key(tmp_path: Path) ) +def test_only_a_managed_row_of_the_picker_takes_delete(tmp_path: Path) -> None: + """Delete forgets a stored password, so it acts only where a password is stored.""" + from meshterm.ui.admin_picker import admin_picker_rows + from meshterm.ui.tui import Choice + + store = AdminStore(tmp_path / "admin.json") + managed = Contact(name="Hilltop", public_key=KEY, node_type=NODE_TYPE_REPEATER) + other = Contact(name="Valley", public_key="cd" * 32, node_type=NODE_TYPE_REPEATER) + store.remember(managed, "secret") + items, _ = admin_picker_rows(SimpleNamespace(admin_store=store), [other, managed]) + + deletable = {row.value: row.deletable for row in items if isinstance(row, Choice)} + assert deletable == {"Hilltop": True, "Valley": False} + + +async def _picker_top(session, title: str): # noqa: ANN001, ANN202 + """The picker once it is the top screen, or ``None``.""" + from meshterm.ui.tui import SelectScreen + + for _ in range(200): + top = session.top + if isinstance(top, SelectScreen) and top.title == title: + return top + await asyncio.sleep(0) + return None + + +async def _dialog_top(session): # noqa: ANN001, ANN202 + """The button dialog once it is the top screen, or ``None``.""" + from meshterm.ui.tui.prompt import ButtonDialog + + for _ in range(200): + if isinstance(session.top, ButtonDialog): + return session.top + await asyncio.sleep(0) + return None + + +@pytest.mark.parametrize("confirmed", [True, False]) +async def test_delete_in_the_admin_picker_forgets_the_password( + tmp_path: Path, confirmed: bool +) -> None: + """GitHub issue 28: the user changed a password and had no way to clear the stored one. + + Delete on a managed node asks first (amber, Cancel or Forget). Forget removes the + password, and the same list refreshes in place: the node leaves the managed section, + the highlight stays on it, and the list stays open. Cancel changes nothing. + """ + from meshterm.ui.admin_picker import FORGET_HINT, pick_admin_node + from meshterm.ui.surface import TuiUi + from meshterm.ui.tui import CANCEL + from meshterm.ui.tui.session import TuiSession + + store = AdminStore(tmp_path / "admin.json") + managed = Contact(name="Hilltop", public_key=KEY, node_type=NODE_TYPE_REPEATER) + other = Contact(name="Valley", public_key="cd" * 32, node_type=NODE_TYPE_REPEATER) + store.remember(managed, "secret") + ctx = SimpleNamespace(ui=TuiUi(TuiSession()), admin_store=store) + session = ctx.ui.session + + task = asyncio.ensure_future(pick_admin_node(ctx, [other, managed], title="Pick", prompt="")) + try: + box = await _picker_top(session, "Pick") + assert box is not None + assert box._current_choice().value == "Hilltop" + assert FORGET_HINT in box.footer_hint + box.handle("delete") + + confirm = await _dialog_top(session) + assert confirm is not None, "Delete asks before it forgets" + assert [label for label, _ in confirm._buttons] == ["Cancel", "Forget"] + assert confirm.title == "Forget password — Hilltop" + confirm.resolve(confirmed) + + again = await _picker_top(session, "Pick") + assert again is box, "the same list, refreshed in place" + current = box._current_choice() + assert current.value == "Hilltop", "the highlight follows the node" + assert current.deletable is (not confirmed) + box.resolve(CANCEL) + assert await task is None + finally: + if not task.done(): + task.cancel() + + assert (store.get(managed) is None) is confirmed + assert session._stack == [] + + # -- the Clock drift page ------------------------------------------------------------------- diff --git a/tests/test_navigation.py b/tests/test_navigation.py index d91c0aa..afdbac1 100644 --- a/tests/test_navigation.py +++ b/tests/test_navigation.py @@ -374,6 +374,68 @@ def test_turn_page_drops_the_filter_and_highlights_the_named_row() -> None: assert screen._current_choice().value == "a", "no default: the first row" +def test_a_turned_page_brings_its_own_delete_key() -> None: + """A page that removes nothing has no ``Del`` atom, also after a page that had one.""" + screen = SelectScreen( + "Link — step 1 of 2", + [Choice("alpha", "a", deletable=True)], + delete_hint="Del forget", + ) + assert "Del forget" in screen.footer_hint + + screen.turn_page([Choice("beta", "b")], title="Link — step 2 of 2") + assert "Del" not in screen.footer_hint + + screen.turn_page( + [Choice("alpha", "a", deletable=True)], title="Link — step 1 of 2", delete_hint="Del forget" + ) + assert "Del forget" in screen.footer_hint + + +async def test_delete_on_a_wizard_page_refreshes_the_page_and_answers_nothing() -> None: + """Delete is not an answer: the page stays, with the rows that ``on_delete`` returns.""" + from meshterm.ui.menus import WizardPage, run_wizard + from meshterm.ui.tui.session import TuiSession + + removed: list = [] + + async def on_delete(value): # noqa: ANN001, ANN202 + removed.append(value) + return [Choice("alpha", "a"), Choice("beta", "b")] + + def first(values: list) -> WizardPage: + return WizardPage( + "Link — step 1 of 2", + [Choice("alpha", "a", deletable=True), Choice("beta", "b")], + delete_hint="Del forget", + on_delete=on_delete, + ) + + session = TuiSession() + run = asyncio.ensure_future(run_wizard(session, [first])) + try: + for _ in range(200): + if isinstance(session.top, SelectScreen): + break + await asyncio.sleep(0) + box = session.top + box.handle("delete") + for _ in range(200): + if removed: + break + await asyncio.sleep(0) + await asyncio.sleep(0) + assert removed == ["a"] + assert not run.done(), "the page is still asking" + assert session.top is box + assert box._current_choice().value == "a" and not box._current_choice().deletable + box.resolve("b") + assert await asyncio.wait_for(run, timeout=2) == ["b"] + finally: + if not run.done(): + run.cancel() + + # --- a wizard is a stepped chain in one box ------------------------------------