From 4356bc9012deb6edc0053656044cbfced8f295dc Mon Sep 17 00:00:00 2001 From: Jean-Pierre Martineau Date: Wed, 4 Nov 2026 01:59:35 -0500 Subject: [PATCH] Forget passwords clears every stored admin password in one step The reporter of #28 asked for a way to clear one or all of the stored admin passwords. Del in the node picker forgets one. This adds the other: a "Forget passwords" row in the Managed nodes section of the menu, behind the red typed confirm (type FORGET), which names the nodes it will forget. It also forgets the password of a node that is no longer a contact, which no list shows. With nothing stored, it says so and asks nothing. On the CLI it is `forget-admin-passwords --yes`: without --yes it is a usage error, and with it the answer lists the nodes it forgot (NAME, LAST_LOGIN, KEY). It exits 5 when nothing was stored, and works with no device. Co-Authored-By: Claude Opus 5.5 --- docs/cli/README.md | 36 +++++++ docs/guide/features.md | 3 +- meshterm/core/admin_store.py | 23 +++++ meshterm/tools/forget_passwords.py | 153 +++++++++++++++++++++++++++++ meshterm/ui/admin_picker.py | 58 ++++++++++- tests/test_cli_contract.py | 34 ++++++- tests/test_managed_nodes.py | 104 ++++++++++++++++++++ tests/test_menus.py | 2 +- 8 files changed, 406 insertions(+), 7 deletions(-) create mode 100644 meshterm/tools/forget_passwords.py diff --git a/docs/cli/README.md b/docs/cli/README.md index 3db81ab..10a601f 100644 --- a/docs/cli/README.md +++ b/docs/cli/README.md @@ -1771,6 +1771,42 @@ is known to be something other than a repeater. `regions` never holds the wildcard `*`. That is `unscoped`, because it names no region. +#### `meshterm forget-admin-passwords` + +Forget all the admin passwords that MeshTerm remembers. + +``` +meshterm forget-admin-passwords --yes +``` + +| Option | What it does | +| --- | --- | +| `--yes` | **Required.** Confirm the deletion. Without it, the command is a usage error (`2`) and forgets nothing. | + +```console +$ meshterm forget-admin-passwords --yes +NAME LAST_LOGIN KEY +Yagi-Repeater 2d a1b2c3d400000000000000000000000000000000000000000000000000000000 +``` + +The command lists the nodes whose passwords it forgot, with the time of the last good +login to each node. It also forgets the password of a node that is not a contact any more. +After this command, a login to each node needs its password again: give it with +`--password`, or type it in the prompt of the menu. You cannot undo this command. The +command sends nothing, and it works with no device connected. It returns `5` when MeshTerm +remembered no password. + +To forget the password of one node, press Del on that node in the node picker of the menu. + +**`--json`** is an array, with one object for each node: + +```json +[{"node":{"name":"Yagi-Repeater","key":"a1b2c3d400000000000000000000000000000000000000000000000000000000","hash":null,"type":null,"place":null,"self":false},"last_login_at":"2026-11-02T06:51:52Z"}] +``` + +`hash`, `type`, and `place` are `null`, because MeshTerm keeps only the name and the key +of a node with its password. + --- ### MeshTerm itself diff --git a/docs/guide/features.md b/docs/guide/features.md index a501342..2ef6d8f 100644 --- a/docs/guide/features.md +++ b/docs/guide/features.md @@ -55,9 +55,10 @@ 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. 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 ` | +| **🗼 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. To forget all of them, use **Forget passwords**. 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]` | +| **🗑 Forget passwords** | Forget the remembered admin password of each managed node in one step. This includes the password of a node that is not a contact any more. You cannot undo this step, so MeshTerm asks you to type FORGET first. Then the next login to each node asks for its password again. | `meshterm forget-admin-passwords --yes` | ## ⚙ This app: the program in front of you diff --git a/meshterm/core/admin_store.py b/meshterm/core/admin_store.py index d5564d6..ba8ad71 100644 --- a/meshterm/core/admin_store.py +++ b/meshterm/core/admin_store.py @@ -182,6 +182,29 @@ class AdminStore: if records.pop(admin_key(node), None) is not None: self._write(records) + def credentials(self) -> list[AdminCredential]: + """Return all the remembered passwords, in the order of the file. + + The list includes the password of a node that the device does not know any more, + because the store keys a password by the node and not by the contact list. + """ + return list(self._load().values()) + + def forget_all(self) -> list[AdminCredential]: + """Delete all the remembered passwords. + + Each next login asks for the password again. The method writes the file only when + it held a password. + + Returns: + The credentials that the store forgot. The list is empty when the store held + none. + """ + records = self._load() + if records: + self._write({}) + return list(records.values()) + def _write(self, records: dict[str, AdminCredential]) -> None: """Store ``records`` atomically, with owner-only permissions where they are supported.""" data = {key: record.to_json() for key, record in records.items()} diff --git a/meshterm/tools/forget_passwords.py b/meshterm/tools/forget_passwords.py new file mode 100644 index 0000000..a43f6fb --- /dev/null +++ b/meshterm/tools/forget_passwords.py @@ -0,0 +1,153 @@ +# SPDX-License-Identifier: Apache-2.0 +"""The ``forget-admin-passwords`` tool: forget all the admin passwords that MeshTerm stores. + +MeshTerm stores the admin password of each node that accepted a login (refer to +:mod:`meshterm.core.admin_store`), so that the next login asks nothing. A user who changed +the passwords of their nodes, or who gives the machine to another person, must be able to +remove all of them in one step (GitHub issue 28). Del in the node picker forgets one +password (refer to :mod:`meshterm.ui.admin_picker`). This tool forgets all of them, +including the password of a node that the device does not know any more. + +In the menu, the row is ``Forget passwords`` in the Managed nodes section. It is a +``popup`` tool: the red typed confirm floats over the menu, and so does the result. The +row says "passwords" and not "admin passwords", because the heading of its section already +says whose passwords they are, and the shorter title keeps the column of the titles at its +width. On the CLI, the command name says "admin", because a room has passwords too, and a +command line has no section heading. + +On the CLI, ``forget-admin-passwords --yes`` forgets all the passwords and lists the nodes +that it forgot. Without ``--yes`` it is a usage error, as each command that deletes data +is. The exit status is ``5`` when the store held no password. +""" + +from __future__ import annotations + +import re +from datetime import datetime +from typing import TYPE_CHECKING, Any + +import typer + +from ..context import AppContext +from ..core import exitcodes +from .base import Tool, ToolResult, register + +if TYPE_CHECKING: # pragma: no cover - typing only + from ..core.admin_store import AdminCredential + from ..ui.report import Listing + +#: A full public key in hex. The store keys a password by the key prefix or by the name +#: when a contact has no full key, and neither of these goes into the ``key`` of a node. +_FULL_KEY = re.compile(r"[0-9a-f]{64}") + + +@register +class ForgetPasswordsTool(Tool): + """Forget all the stored admin passwords of remote nodes.""" + + name = "forget-admin-passwords" + title = "Forget passwords" + icon = "🗑" + help = "Clear every saved admin password" + category = "Managed nodes" + order = 30 # after the two tools that log in: it undoes what they stored + popup = True # dialog-sized: float over the menu, and do not replace it + + async def prompt_params(self, ctx: AppContext) -> dict[str, Any] | None: + """Ask for the typed confirm. + + Refer to :func:`~meshterm.ui.admin_picker.confirm_forget_all`. + + Args: + ctx: The shared application context. + + Returns: + ``{"yes": True}`` when the user typed the word, or ``None`` when the user backed + out or the store held no password. + """ + from ..ui.admin_picker import confirm_forget_all + + if not await confirm_forget_all(ctx, title=self.title): + return None + return {"yes": True} + + async def run(self, ctx: AppContext, params: dict[str, Any]) -> ToolResult: + """Forget all the stored admin passwords. + + Args: + ctx: The shared application context. + params: ``yes``: the confirm. The menu and the CLI both ask for it before they + call this method. + + Returns: + A :class:`ToolResult` with the number of passwords that MeshTerm forgot, and + ``NO_RESULT`` when the store held none. + """ + from ..ui.surface import TuiUi + + forgotten = ctx.admin_store.forget_all() + count = len(forgotten) + plural = "" if count == 1 else "s" + return ToolResult( + summary={"forgotten": count}, + message=f"[ok]✓[/ok] forgot [brand]{count}[/brand] admin password{plural}" + if count + else None, + report=None if isinstance(ctx.ui, TuiUi) else (_forgotten(forgotten),), + exit_code=exitcodes.OK if count else exitcodes.NO_RESULT, + ) + + def register_cli(self, app: typer.Typer) -> None: + """Register the ``forget-admin-passwords`` subcommand. + + Args: + app: The Typer application. + """ + from ..cli import run_tool_command + + @app.command(name=self.name, help=self.help) + def _forget( + yes: bool = typer.Option(False, "--yes", help="Confirm this destructive action"), + ) -> None: + if not yes: + raise typer.BadParameter( + "this forgets every saved admin password; each next login needs it " + "again. Re-run with --yes to confirm." + ) + run_tool_command(self, {"yes": True}) + + +def _forgotten(credentials: list[AdminCredential]) -> Listing: + """The nodes whose passwords MeshTerm forgot, one row for each node. + + The store keeps the name of a node from its last good login, and the time of that + login. It keeps no other fact about the node, so the row has no type and no hash. + """ + from ..ui import fields + from ..ui.report import Listing + + return Listing( + key="forgotten", + columns=( + fields.node(lanes=(("name", "NAME"), ("key", "KEY"))), + fields.when("last_login_at", "LAST_LOGIN"), + ), + rows=[ + { + "node": fields.NodeRef( + name=c.label or None, key=c.key if _FULL_KEY.fullmatch(c.key) else None + ), + "last_login_at": _instant(c.last_used), + } + for c in credentials + ], + order=("NAME", "LAST_LOGIN", "KEY"), + ) + + +def _instant(text: str) -> datetime | None: + """The stored ISO-8601 time of a login, or ``None`` if the store has none it can read.""" + try: + return datetime.fromisoformat(text) if text else None + except ValueError: + return None diff --git a/meshterm/ui/admin_picker.py b/meshterm/ui/admin_picker.py index c36eb21..f2791d5 100644 --- a/meshterm/ui/admin_picker.py +++ b/meshterm/ui/admin_picker.py @@ -16,10 +16,12 @@ stack under the page of the tool, where Esc would land. It was once kept pushed 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`). +Delete on a managed node forgets its password, after a confirm (``Del forget``). The +``Forget passwords`` row of the menu forgets all of them, after a typed confirm (refer to +:func:`confirm_forget_all`). These are the two places 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 @@ -36,6 +38,13 @@ if TYPE_CHECKING: #: The footer atom of the Delete key on a managed node. FORGET_HINT = "Del forget" +#: The word that the user types to forget all the stored admin passwords. +FORGET_ALL_WORD = "FORGET" + +#: The most node names that the confirm to forget all the passwords shows. It counts the +#: other nodes. +_NAMES_SHOWN = 5 + 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. @@ -218,6 +227,47 @@ async def forget_row(ctx: AppContext, contacts: list[Contact], value: Any) -> li return admin_picker_rows(ctx, contacts)[0] +async def confirm_forget_all(ctx: AppContext, *, title: str) -> bool: + """Ask the user to type a word before MeshTerm forgets all the stored admin passwords. + + This is a bulk deletion that the user cannot undo, so the confirm is the red typed + confirm, not a button dialog. It names the nodes, because the store also holds the + password of a node that the device does not know any more, and no list shows that + node. When the store holds no password, the function says so, and asks nothing. + + Args: + ctx: The shared application context (for the dialogs and the admin store). + title: The title of the dialogs (the name of the menu row). + + Returns: + ``True`` when the user typed the word. Then the caller forgets the passwords. + """ + stored = ctx.admin_store.credentials() + if not stored: + await ctx.ui.session.message_dialog( + Text("no saved admin passwords — MeshTerm saves one when a login works", "muted"), + title=title, + ) + return False + names = [c.label or c.key[:12] for c in stored] + if len(names) > _NAMES_SHOWN: + names = [*names[:_NAMES_SHOWN], f"{len(names) - _NAMES_SHOWN} more"] + if len(stored) == 1: + warning = ( + f"This forgets the saved admin password of {names[0]}. " + "The next login asks for it again." + ) + else: + listed = ( + " and ".join(names) if len(names) == 2 else f"{', '.join(names[:-1])}, and {names[-1]}" + ) + warning = ( + f"This forgets the saved admin passwords of {len(stored)} managed nodes: " + f"{listed}. Each next login asks for the password again." + ) + return await ctx.ui.typed_confirm(warning, FORGET_ALL_WORD, title=title) + + async def _note_nothing_to_pick(ctx: AppContext, title: str) -> None: """Say that no node can be offered, and show this. MeshTerm opens no list.""" ctx.ui.note("[err]no contacts with a key — receive an advert first[/err]") diff --git a/tests/test_cli_contract.py b/tests/test_cli_contract.py index f968835..6e03e72 100644 --- a/tests/test_cli_contract.py +++ b/tests/test_cli_contract.py @@ -581,8 +581,16 @@ def test_a_failure_says_so_on_stderr_and_never_on_stdout(run) -> None: # noqa: ("config", "import-key", "00" * 32), ("channels", "clear", "1"), ("preferences", "reset"), + ("forget-admin-passwords",), + ], + ids=[ + "reboot", + "factory-reset", + "import-key", + "channels-clear", + "preferences-reset", + "forget-admin-passwords", ], - ids=["reboot", "factory-reset", "import-key", "channels-clear", "preferences-reset"], ) def test_a_destructive_command_without_yes_is_a_silent_usage_error(run, args) -> None: # noqa: ANN001 """A missing confirmation is a bad argument, and the message goes where errors go. @@ -597,6 +605,30 @@ def test_a_destructive_command_without_yes_is_a_silent_usage_error(run, args) -> assert "--yes" in result.stderr +def test_forget_admin_passwords_lists_what_it_forgot_and_exits_5_on_nothing( + run, tmp_path: Path +) -> None: # noqa: ANN001 + """GitHub issue 28: one command forgets all the stored admin passwords. + + The answer is the list of the nodes that it forgot, and the ✓ goes to stderr. A second + run finds nothing, so it exits with ``5`` and its document is the empty array. + """ + assert run("repeater-admin", "Yagi-Repeater", "ver", "--password", "admin").exit_code == 0 + assert (tmp_path / "home" / "admin.json").read_text(encoding="utf-8").strip() != "{}" + + result = run("forget-admin-passwords", "--yes") + assert result.exit_code == exitcodes.OK, result.output + header, row = result_lines(result) + assert header.split() == ["NAME", "LAST_LOGIN", "KEY"] + assert row.split()[:2] == ["Yagi-Repeater", "now"] + assert "forgot 1 admin password" in result.stderr + assert json.loads((tmp_path / "home" / "admin.json").read_text(encoding="utf-8")) == {} + + again = run("--json", "forget-admin-passwords", "--yes") + assert again.exit_code == exitcodes.NO_RESULT + assert json.loads(again.stdout) == [] + + def test_import_key_reads_a_file_and_keeps_the_key_out_of_the_run_log(run, tmp_path: Path) -> None: # noqa: ANN001 """The run log stores the parameters of each run, and a private key is not one to keep. diff --git a/tests/test_managed_nodes.py b/tests/test_managed_nodes.py index bc500a1..30fc633 100644 --- a/tests/test_managed_nodes.py +++ b/tests/test_managed_nodes.py @@ -250,6 +250,110 @@ async def test_delete_in_the_admin_picker_forgets_the_password( assert session._stack == [] +def test_forget_all_empties_the_store_and_returns_what_it_held(tmp_path: Path) -> None: + """It also forgets a password whose node the device does not know any more.""" + store = AdminStore(tmp_path / "admin.json") + assert store.forget_all() == [] + assert not (tmp_path / "admin.json").exists(), "nothing to forget writes nothing" + + store.remember(Contact(name="Hilltop", public_key=KEY), "one") + store.remember(Contact(name="Valley", public_key="cd" * 32), "two") + forgotten = store.forget_all() + + assert sorted(c.label for c in forgotten) == ["Hilltop", "Valley"] + assert store.credentials() == [] + + +async def _typed_top(session): # noqa: ANN001, ANN202 + """The typed confirm once it is the top screen, or ``None``.""" + from meshterm.ui.tui.prompt import TypedConfirmDialog + + for _ in range(200): + if isinstance(session.top, TypedConfirmDialog): + return session.top + await asyncio.sleep(0) + return None + + +@pytest.mark.parametrize("typed", [True, False]) +async def test_forget_passwords_asks_for_the_typed_word_and_names_the_nodes( + tmp_path: Path, typed: bool +) -> None: + """GitHub issue 28: one step forgets all the passwords, behind the red typed confirm. + + The confirm names each node, also a node that is not a contact any more, because no + list shows that node. Esc keeps all the passwords. + """ + from meshterm.tools.forget_passwords import ForgetPasswordsTool + 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") + for name, key in (("Hilltop", KEY), ("Valley", "cd" * 32), ("Ridge", "ef" * 32)): + store.remember(Contact(name=name, public_key=key), "secret") + ctx = SimpleNamespace(ui=TuiUi(TuiSession()), admin_store=store) + tool = ForgetPasswordsTool() + + task = asyncio.ensure_future(tool.prompt_params(ctx)) + try: + confirm = await _typed_top(ctx.ui.session) + assert confirm is not None, "a bulk deletion asks for the typed word" + assert confirm.title == tool.title + assert "3 managed nodes: Hilltop, Valley, and Ridge" in confirm._warning + confirm.resolve(True if typed else CANCEL) + params = await task + finally: + if not task.done(): + task.cancel() + + if not typed: + assert params is None + assert len(store.credentials()) == 3 + return + result = await tool.run(ctx, params) + assert store.credentials() == [] + assert result.summary == {"forgotten": 3} + assert "forgot" in result.message + assert result.report is None, "the menu path has no report" + + +async def test_forget_passwords_with_nothing_stored_says_so_and_asks_nothing( + tmp_path: Path, +) -> None: + """An empty store gets the empty state in a message dialog, and no typed confirm.""" + from meshterm.tools.forget_passwords import ForgetPasswordsTool + from meshterm.ui.surface import TuiUi + from meshterm.ui.tui.session import TuiSession + + ctx = SimpleNamespace(ui=TuiUi(TuiSession()), admin_store=AdminStore(tmp_path / "a.json")) + task = asyncio.ensure_future(ForgetPasswordsTool().prompt_params(ctx)) + try: + note = await _dialog_top(ctx.ui.session) + assert note is not None + assert "no saved admin passwords" in note._prompt.plain + assert [label for label, _ in note._buttons] == ["OK"] + note.resolve("ok") + assert await task is None + finally: + if not task.done(): + task.cancel() + + +def test_forget_passwords_is_a_managed_nodes_row_that_keeps_the_title_column() -> None: + """The row floats its dialogs over the menu, and its title is no wider than the widest. + + A wider title moves the description of each row of the menu to the right. + """ + from meshterm.tools import all_tools, get_tool + + tool = get_tool("forget-admin-passwords") + assert tool is not None and tool.menu_visible and tool.popup + assert tool.category == "Managed nodes" + others = [t for t in all_tools() if t.menu_visible and t is not tool] + assert len(tool.title) <= max(len(t.title or t.name) for t in others) + + # -- the Clock drift page ------------------------------------------------------------------- diff --git a/tests/test_menus.py b/tests/test_menus.py index 23075e2..3111ab3 100644 --- a/tests/test_menus.py +++ b/tests/test_menus.py @@ -205,7 +205,7 @@ def test_main_menu_sections_answer_the_menus_own_question() -> None: "Watch": ["dashboard", "livefeed", "watchtower", "clocks", "timemachine"], "Explore": ["map", "walk", "trace", "trace-path", "records"], "This node": ["info", "config", "advert"], - "Managed nodes": ["repeater-admin", "tx-optimize"], + "Managed nodes": ["repeater-admin", "tx-optimize", "forget-admin-passwords"], "This app": [ "preferences", "diagnostics",