From 1e8eae1f3de765fcd8163716de6e5fe5aab5a034 Mon Sep 17 00:00:00 2001 From: Christophe Besson Date: Thu, 15 Oct 2026 09:33:28 +0200 Subject: feat(hub): one account, several linked nodes An account links up to MAX_NODES_PER_ACCOUNT node keys (node_keys table) instead of the one users.pk_node_ed25519; the migration carries each account's key over and the downgrade keeps the last one linked. /v1/nodes/auth accepts any linked key, and its token names the key that won it (nk). PUT /me/node_key adds a key, idempotently, 409 past the limit; DELETE /me/node_key names the key: a browser session any of its own, a node only its own. Unlinking a key closes that node's socket and refuses its tokens at once, on REST and on the socket; the account's other nodes are untouched. /pubkeys no longer gives a node key to other accounts, and gives the caller its last linked one, which installed desktop apps read. The node reports waiting_for_node_key while its key is unlinked and signs in again as soon as the hub says so, so a key linked again is back within seconds; unlinking itself signs in first to hold a token naming its key. Profile -> Linked nodes lists each node (connected, last seen, IP, linked since, This machine in the desktop app) with Copy and Unlink, and adds a key by hand. The Node page banner, Create group and the desktop app add this machine's key instead of replacing another's. Messages that pointed at Settings -> Link Node point at Profile -> Linked nodes. Co-Authored-By: Claude Opus 5.5 --- .../meshbay-node/src/meshbay_node/cli/setup.py | 2 +- .../meshbay-node/src/meshbay_node/cli/status.py | 2 +- packages/meshbay-node/src/meshbay_node/daemon.py | 10 +- .../meshbay-node/src/meshbay_node/hub_client.py | 48 +++++- .../meshbay-node/tests/test_node_key_unlinked.py | 180 +++++++++++++++++++++ .../tests/test_patch_targets_are_live.py | 4 +- .../tests/test_windows_node_lifecycle.py | 7 +- 7 files changed, 238 insertions(+), 15 deletions(-) create mode 100644 packages/meshbay-node/tests/test_node_key_unlinked.py (limited to 'packages/meshbay-node') diff --git a/packages/meshbay-node/src/meshbay_node/cli/setup.py b/packages/meshbay-node/src/meshbay_node/cli/setup.py index 48a55ef..44224fb 100644 --- a/packages/meshbay-node/src/meshbay_node/cli/setup.py +++ b/packages/meshbay-node/src/meshbay_node/cli/setup.py @@ -105,7 +105,7 @@ def init(args) -> None: print(f"Node key: {keys.pk_ed25519_b64}") print() print("Next steps:") - print(f" 1. Link this node key on {hub_url} → Settings → Link Node") + print(f" 1. Link this node key on {hub_url} → Profile → Linked nodes") if sys.platform == "win32": print(" 2. meshbay-node autostart install (run at each sign-in)") print(" — or just: meshbay-node (start it now, this session)") diff --git a/packages/meshbay-node/src/meshbay_node/cli/status.py b/packages/meshbay-node/src/meshbay_node/cli/status.py index ebc6c77..51e4c87 100644 --- a/packages/meshbay-node/src/meshbay_node/cli/status.py +++ b/packages/meshbay-node/src/meshbay_node/cli/status.py @@ -47,7 +47,7 @@ def status(args) -> None: "node_key_link": ( "Link node key", f"Copy the node key above and paste it in " - f"Settings → Link Node on {cfg.hub.url}"), + f"Profile → Linked nodes on {cfg.hub.url}"), "group_add": ( "Add a group", "meshbay-node group add --dir /path/to/files"), diff --git a/packages/meshbay-node/src/meshbay_node/daemon.py b/packages/meshbay-node/src/meshbay_node/daemon.py index 557b523..46b4ae1 100644 --- a/packages/meshbay-node/src/meshbay_node/daemon.py +++ b/packages/meshbay-node/src/meshbay_node/daemon.py @@ -645,8 +645,15 @@ class NodeDaemon(EnrichmentMixin): log.warning("Invalid revocation token: %s", e) async def on_connected(): + # Back from an unlink: the key was linked again and the hub let + # this node in, so it is serving once more. + if self._state.get("status") == "waiting_for_node_key": + self._state["status"] = "running" await self._sync_blocklist(hub) + def on_unlinked(): + self._state["status"] = "waiting_for_node_key" + ws_task = asyncio.create_task(hub.maintain_ws( on_incoming=on_incoming, on_revocation=on_revocation, @@ -654,6 +661,7 @@ class NodeDaemon(EnrichmentMixin): group_ids=lambda: list((self._state.get("groups_ctx") or {}).keys()), on_connected=on_connected, on_blocklist=self._on_blocklist_update, + on_unlinked=on_unlinked, )) self._tasks.append(ws_task) log.info("Hub WS task started") @@ -1043,7 +1051,7 @@ class NodeDaemon(EnrichmentMixin): self._state["status"] = "waiting_for_node_key" log.warning( "Node key not linked. Get it from `meshbay-node " - "status` and paste it in Settings > Link Node on %s " + "status` and paste it in Profile > Linked nodes on %s " "(the desktop client links it automatically). " "Retrying in %ds...", self._config.hub.url, self.LINK_WAIT_S, diff --git a/packages/meshbay-node/src/meshbay_node/hub_client.py b/packages/meshbay-node/src/meshbay_node/hub_client.py index 54f87f0..020903d 100644 --- a/packages/meshbay-node/src/meshbay_node/hub_client.py +++ b/packages/meshbay-node/src/meshbay_node/hub_client.py @@ -230,12 +230,21 @@ class HubClient: return r.json().get("email", "") async def unlink_node_key(self) -> None: - """Clear pk_node_ed25519 on the hub (best-effort before reset).""" + """Unlink this node's key from its account; the account's other nodes keep theirs.""" if self._session is None: return - await self.ensure_fresh_token() - r = await self._http.delete("/v1/users/me/node_key", - headers=self._session.auth_headers) + # A fresh token, not merely an unexpired one: the hub lets a node unlink + # the key its token names, and a token issued before that claim existed + # names none. A key already unlinked has nothing left to let go of. + try: + await self.login() + except httpx.HTTPStatusError as e: + if e.response.status_code == 401 and "No node key" in e.response.text: + return + raise + r = await self._http.request("DELETE", "/v1/users/me/node_key", + json={"pk_node_ed25519": self._keys.pk_ed25519_b64}, + headers=self._session.auth_headers) r.raise_for_status() # ── User pubkey lookup ──────────────────────────────────────────────────── @@ -336,6 +345,7 @@ class HubClient: group_ids: list[str] | None = None, # static list or callable returning one on_connected: Any = None, on_blocklist: Any = None, + on_unlinked: Any = None, ) -> None: """ Maintain a persistent WebSocket connection to the hub. @@ -385,12 +395,18 @@ class HubClient: auth_resp = json.loads( await asyncio.wait_for(ws.recv(), timeout=15)) if auth_resp.get("type") != "auth_ok": - # Not fatal: the token may simply have expired while we - # were disconnected. Refresh on the next pass rather than - # ending the task, which used to strand the node for good. + # Not fatal: the token may have expired while we were + # disconnected, or this node's key was unlinked from the + # account (which ends its tokens at once). Sign in again + # rather than wait for the token to near its expiry: a key + # linked again is then back within seconds, and one still + # unlinked says so through `on_unlinked`. log.warning("WS auth refused: %s — retrying in 5s", auth_resp) await asyncio.sleep(5) - await self.ensure_fresh_token() + if "no longer linked" in str(auth_resp.get("detail", "")): + await self._sign_in_again(on_unlinked) + else: + await self.ensure_fresh_token() continue self._ws = ws @@ -447,6 +463,22 @@ class HubClient: finally: self._ws = None + async def _sign_in_again(self, on_unlinked: Any) -> None: + """Sign in afresh; tell `on_unlinked` when the hub no longer knows this key.""" + try: + await self.login() + except httpx.HTTPStatusError as e: + if e.response.status_code == 401 and "No node key" in e.response.text: + log.warning("This node's key is no longer linked to %r — waiting " + "for it to be linked again", self._config.username) + if on_unlinked: + on_unlinked() + # Ten seconds a round in all: the hub allows 10 node sign-ins a + # minute, and a node waiting for its link must stay under it. + await asyncio.sleep(5) + return + raise + async def _answer_offer(self, ws, on_webrtc_offer, msg: dict) -> None: """Negotiate one WebRTC offer and return the answer, off the read loop.""" try: diff --git a/packages/meshbay-node/tests/test_node_key_unlinked.py b/packages/meshbay-node/tests/test_node_key_unlinked.py new file mode 100644 index 0000000..85674e1 --- /dev/null +++ b/packages/meshbay-node/tests/test_node_key_unlinked.py @@ -0,0 +1,180 @@ +""" +A node whose key was unlinked from its account notices, and comes back when it is linked again. + +The hub ends an unlinked node's tokens at once and refuses its socket with +"Node key no longer linked". The node then signs in afresh instead of waiting +for its token to near expiry — so a key linked again is back within seconds — +and while the hub answers "No node key", it reports `waiting_for_node_key` +rather than `running`. +""" + +import asyncio +import json + +import httpx +import pytest +from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey +from cryptography.hazmat.primitives.asymmetric.x25519 import X25519PrivateKey +from meshbay_node import hub_client as hc +from meshbay_node.hub_client import HubClient, HubConfig +from meshbay_node.keystore import NodeKeys + + +def _client(tmp_path): + keys = NodeKeys(sk_ed25519=Ed25519PrivateKey.generate(), + sk_x25519=X25519PrivateKey.generate()) + return HubClient(HubConfig(hub_url="http://fake-hub", username="testuser", + cache_dir=tmp_path), keys) + + +def _status_error(status, detail): + req = httpx.Request("POST", "http://fake-hub/v1/nodes/auth") + resp = httpx.Response(status, json={"detail": detail}, request=req) + return httpx.HTTPStatusError(detail, request=req, response=resp) + + +@pytest.fixture(autouse=True) +def _no_wait(monkeypatch): + async def _instant(_s): + return None + monkeypatch.setattr(hc.asyncio, "sleep", _instant) + + +@pytest.mark.asyncio +async def test_an_unlinked_key_is_reported(tmp_path, monkeypatch): + hub = _client(tmp_path) + + async def login(): + raise _status_error(401, "No node key registered for this node — link it") + monkeypatch.setattr(hub, "login", login) + + told = [] + await hub._sign_in_again(lambda: told.append(True)) + assert told == [True] + + +@pytest.mark.asyncio +async def test_a_key_linked_again_signs_in_without_reporting(tmp_path, monkeypatch): + hub = _client(tmp_path) + calls = [] + + async def login(): + calls.append(True) + monkeypatch.setattr(hub, "login", login) + + told = [] + await hub._sign_in_again(lambda: told.append(True)) + assert calls == [True] + assert told == [] + + +@pytest.mark.asyncio +async def test_other_failures_are_not_mistaken_for_an_unlink(tmp_path, monkeypatch): + hub = _client(tmp_path) + + async def login(): + raise _status_error(429, "Too many requests") + monkeypatch.setattr(hub, "login", login) + + told = [] + with pytest.raises(httpx.HTTPStatusError): + await hub._sign_in_again(lambda: told.append(True)) + assert told == [] + + +class _RefusingSocket: + """A hub that refuses the node's socket once, with `detail`.""" + + def __init__(self, detail, stop): + self.detail, self.stop, self.sent = detail, stop, [] + + async def __aenter__(self): + return self + + async def __aexit__(self, *exc): + return False + + async def send(self, data): + self.sent.append(data) + + async def recv(self): + self.stop.set() + return json.dumps({"type": "error", "detail": self.detail}) + + +@pytest.mark.parametrize("detail, signs_in_again", [ + ("Node key no longer linked to this account", True), + ("Node already connected", False), +]) +@pytest.mark.asyncio +async def test_only_an_unlink_refusal_signs_in_again(tmp_path, monkeypatch, detail, + signs_in_again): + """Any other refusal keeps the old pace, so `/auth`'s rate limit is not spent on it.""" + import types + + import websockets + + hub = _client(tmp_path) + hub._session = types.SimpleNamespace(hub_url="http://fake-hub", access_token="t", + node_id="n1") + stop = asyncio.Event() + monkeypatch.setattr(websockets, "connect", + lambda *a, **k: _RefusingSocket(detail, stop)) + signed_in, refreshed = [], [] + + async def sign_in_again(_cb): + signed_in.append(True) + raise asyncio.CancelledError + + async def ensure_fresh(): + refreshed.append(True) + raise asyncio.CancelledError + monkeypatch.setattr(hub, "_sign_in_again", sign_in_again) + monkeypatch.setattr(hub, "ensure_fresh_token", ensure_fresh) + + with pytest.raises(asyncio.CancelledError): + await hub.maintain_ws(group_ids=[]) + assert bool(signed_in) is signs_in_again + assert bool(refreshed) is not signs_in_again + + +@pytest.mark.asyncio +async def test_unlinking_itself_signs_in_first_and_names_its_key(tmp_path, monkeypatch): + """A token from before the hub named keys cannot unlink; a fresh one names this node's.""" + import types + + hub = _client(tmp_path) + hub._session = types.SimpleNamespace(auth_headers={"Authorization": "Bearer fresh"}) + order, sent = [], {} + + async def login(): + order.append("login") + monkeypatch.setattr(hub, "login", login) + + async def request(method, url, json=None, headers=None): + order.append(method) + sent.update(json or {}) + return httpx.Response(200, json={}, request=httpx.Request(method, "http://h" + url)) + monkeypatch.setattr(hub._http, "request", request) + + await hub.unlink_node_key() + assert order == ["login", "DELETE"] + assert sent == {"pk_node_ed25519": hub._keys.pk_ed25519_b64} + + +@pytest.mark.asyncio +async def test_unlinking_a_key_already_unlinked_is_not_an_error(tmp_path, monkeypatch): + import types + + hub = _client(tmp_path) + hub._session = types.SimpleNamespace(auth_headers={}) + + async def login(): + raise _status_error(401, "No node key registered for this node — link it") + monkeypatch.setattr(hub, "login", login) + + async def request(*a, **k): + raise AssertionError("nothing to unlink, nothing should be sent") + monkeypatch.setattr(hub._http, "request", request) + + await hub.unlink_node_key() diff --git a/packages/meshbay-node/tests/test_patch_targets_are_live.py b/packages/meshbay-node/tests/test_patch_targets_are_live.py index c1dd905..7728ae6 100644 --- a/packages/meshbay-node/tests/test_patch_targets_are_live.py +++ b/packages/meshbay-node/tests/test_patch_targets_are_live.py @@ -75,7 +75,9 @@ def _patches(path: Path): and isinstance(first, ast.Name) \ and isinstance(node.args[1], ast.Constant) \ and isinstance(node.args[1].value, str): - target = _resolve(aliases.get(first.id, "")) + if first.id not in aliases: + continue # a local object, not a module: an attribute lookup, always live + target = _resolve(aliases[first.id]) yield target, node.args[1].value, node.lineno elif name in ("setattr", "patch") and isinstance(first, ast.Constant) \ and isinstance(first.value, str) and "." in first.value: diff --git a/packages/meshbay-node/tests/test_windows_node_lifecycle.py b/packages/meshbay-node/tests/test_windows_node_lifecycle.py index 6ca301b..d98fd01 100644 --- a/packages/meshbay-node/tests/test_windows_node_lifecycle.py +++ b/packages/meshbay-node/tests/test_windows_node_lifecycle.py @@ -314,9 +314,10 @@ def test_signing_in_sets_up_this_machines_node(): assert "process.platform !== 'win32' || !hasBundledNode()" in ensure # A node set up for someone else is left as it is... assert ensure.index("return { state: 'other_account' }") < ensure.index("provisionNode(") - # ...and so is an account already linked to another node. - assert "if (linked && linked !== p.pk_node_ed25519) return { state: 'other_node' };" in ensure - assert ensure.index("state: 'other_node'") < ensure.index("linkNodeKeyAndAwaitRunning(") + # An account with nodes on other machines keeps them: this one's key is + # added beside theirs, so there is no other node to protect from it. + assert "other_node" not in ensure + assert "linkNodeKeyAndAwaitRunning(" in ensure # Started however this machine is set up, through the CLI like every start. assert "winNodeStartVia(['autostart', 'start'])" in ensure # One start at a time. -- cgit v1.2.3