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 <noreply@anthropic.com>
This commit is contained in:
Jean-Pierre MartineauandClaude Opus 5.5 committed 2026-11-04 01:59:35 -05:00
1 parent e8a3b439cd
commit 4356bc9012
8 files changed
+406 -7

No files matched your search

+23
View File
@@ -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()}
+153
View File
@@ -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
+54 -4
View File
@@ -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]")