From 1d169141f3a5542efda2f7fdb0bb88308c06191b Mon Sep 17 00:00:00 2001 From: Christophe Besson Date: Wed, 23 Sep 2026 18:16:02 +0200 Subject: feat(node): member invite --link and member cancel in the CLI MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The CLI makes both halves itself — the node's code, then the hub's ticket bound to the address — and prints the link; a refused ticket takes the code back, and cancel takes back both. The CLI never asks the hub to mail. Co-Authored-By: Claude Opus 5.5 --- packages/meshbay-node/src/meshbay_node/daemon.py | 42 +++++++++++- .../meshbay-node/src/meshbay_node/hub_client.py | 42 ++++++++++++ packages/meshbay-node/src/meshbay_node/ops.py | 78 ++++++++++++++++++++++ packages/meshbay-node/src/meshbay_node/ui/app.py | 8 ++- 4 files changed, 164 insertions(+), 6 deletions(-) (limited to 'packages/meshbay-node/src') diff --git a/packages/meshbay-node/src/meshbay_node/daemon.py b/packages/meshbay-node/src/meshbay_node/daemon.py index 34d186a..a3bde8f 100644 --- a/packages/meshbay-node/src/meshbay_node/daemon.py +++ b/packages/meshbay-node/src/meshbay_node/daemon.py @@ -33,6 +33,7 @@ import sys import time from dataclasses import asdict, replace from pathlib import Path +from urllib.parse import quote import uvicorn from meshbay_common import MNP_VERSION @@ -1959,7 +1960,7 @@ def main() -> None: help="init: provision config + keystore | reset: erase all " "node state | status: node state and keys " "| operator pair: pair a " - "browser with this node | member list|invite|revoke|unpin " + "browser with this node | member list|invite|cancel|revoke|unpin " "| group list|add|remove " "| root list|add|remove|set|eject|plug " "| gek init|rotate | file list|rm " @@ -1993,7 +1994,8 @@ def main() -> None: "install|remove|start|stop|status for autostart and " "for service") parser.add_argument("target", nargs="?", - help="username for member invite|revoke|unpin; group name " + help="username for member invite|revoke|unpin (an e-mail address with " + "--link, a link id for member cancel); group name " "for group add; file id for file rm; identifier for " "denylist clear; download cap for transfers set; " "size in GB for transfers max-size") @@ -2012,6 +2014,9 @@ def main() -> None: help="Config file path") parser.add_argument("--group", default=None, help="group id (optional if only one is configured)") + parser.add_argument("--link", action="store_true", + help="member invite: an invitation link for this e-mail " + "address, for someone who may have no account yet") parser.add_argument("--writable", action="store_true", default=None, dest="writable", help="root accepts member uploads (root add/set)") @@ -2383,6 +2388,26 @@ def main() -> None: print(f"usage: meshbay-node member {sub} ") sys.exit(1) + if sub == "invite" and args.link: + # A link for someone who may have no account yet, bound to their + # address on the hub. The code and the ticket are both in it, so + # it goes to them and to nobody else — the CLI mails nothing. + group_id = _resolve_group(cfg, args.group) + out = _daemon_api( + cfg, f"/api/groups/{group_id}/invite-links?email={quote(args.target)}", + method="POST") + from meshbay_node.roster import write_code_file + write_code_file(cfg.data_dir, out["link"], out.get("expires_at", ""), + name="invite-link") + print(f"INVITATION LINK {out['link']}") + print(f"valid until {out.get('expires_at', '?')}") + print(f"cancel with meshbay-node member cancel {out['invite_id']}") + print() + print(f"Send it to {args.target} yourself. It works once, and only for an") + print("account registered with that address: they open it, create their") + print("account or sign in, and land in the group without typing a code.") + return + if sub == "invite": group_id = _resolve_group(cfg, args.group) out = _daemon_api( @@ -2402,6 +2427,17 @@ def main() -> None: print(f"also written to {path}") return + if sub == "cancel": + # Takes back a link that has not been used, on the node and the hub. + group_id = _resolve_group(cfg, args.group) + out = _daemon_api( + cfg, f"/api/groups/{group_id}/invite-links/{quote(args.target)}", + method="DELETE") + print(f"invitation link {args.target[:8]} cancelled") + if not out.get("hub", True): + print("The hub's half could not be reached; it expires on its own.") + return + # revoke and unpin both name a person; the daemon resolves the account. # It tries its own roster first and falls back to the hub, so a node that # pinned someone before invitations carried a name is still manageable. @@ -2432,7 +2468,7 @@ def main() -> None: print(f"issue a code: meshbay-node member invite {args.target}") return - print("usage: meshbay-node member list|invite|revoke|unpin") + print("usage: meshbay-node member list|invite|cancel|revoke|unpin") sys.exit(1) if args.command in ("gek-init", "gek"): diff --git a/packages/meshbay-node/src/meshbay_node/hub_client.py b/packages/meshbay-node/src/meshbay_node/hub_client.py index 58bf657..06d3503 100644 --- a/packages/meshbay-node/src/meshbay_node/hub_client.py +++ b/packages/meshbay-node/src/meshbay_node/hub_client.py @@ -85,6 +85,11 @@ class HubClient: async def __aenter__(self): return self + @property + def hub_url(self) -> str: + """The hub's address as this node was configured with it.""" + return self._config.hub_url + async def __aexit__(self, *_): await self.close() @@ -258,6 +263,43 @@ class HubClient: r.raise_for_status() return r.json() + async def create_invite_link(self, group_id: str, email: str, expires_at: str, + node_invite_id: str) -> dict: + """ + The hub's half of an invitation link: a ticket bound to `email`. + + Never with `send_email`: the hub refuses mail to a node token, and the + CLI mails nothing — the operator sends the link (docs/USERGUIDE.md §7). + """ + if self._session is None: + raise RuntimeError("Not logged in") + await self.ensure_fresh_token() + r = await self._http.post( + f"/v1/groups/{group_id}/invite-links", + json={"email": email, "expires_at": expires_at, + "node_invite_id": node_invite_id}, + headers=self._session.auth_headers, + ) + r.raise_for_status() + return r.json() + + async def list_invite_links(self, group_id: str) -> list[dict]: + if self._session is None: + raise RuntimeError("Not logged in") + await self.ensure_fresh_token() + r = await self._http.get(f"/v1/groups/{group_id}/invite-links", + headers=self._session.auth_headers) + r.raise_for_status() + return r.json().get("links", []) + + async def delete_invite_link(self, group_id: str, link_id: str) -> None: + if self._session is None: + raise RuntimeError("Not logged in") + await self.ensure_fresh_token() + r = await self._http.delete(f"/v1/groups/{group_id}/invite-links/{link_id}", + headers=self._session.auth_headers) + r.raise_for_status() + # ── Persistent WebSocket (signaling + revocations) ────────────────────── async def send_ws(self, data: str) -> None: diff --git a/packages/meshbay-node/src/meshbay_node/ops.py b/packages/meshbay-node/src/meshbay_node/ops.py index aae0a33..bdcb130 100644 --- a/packages/meshbay-node/src/meshbay_node/ops.py +++ b/packages/meshbay-node/src/meshbay_node/ops.py @@ -29,11 +29,13 @@ import time as _time from dataclasses import asdict from pathlib import Path from typing import Any +from urllib.parse import urlsplit from meshbay_common.background import spawn from meshbay_common.chatbox import new_epoch_key from meshbay_common.crypto import ( generate_gek, + pk_to_b64, unwrap_gek_aes, wrap_gek_aes, ) @@ -271,6 +273,82 @@ async def cancel_invite(state: dict, group_id: str, invite_id: str) -> dict: return {"cancelled": True, "invite_id": invite_id, "group_id": group_id} +def _invite_url(hub_url: str, group_id: str, ticket: str, node_pk_b64: str, code: str) -> str: + """ + An invitation link, in the one shape the hub and the interface also write + (docs/MESHBAY_DESIGN.md §3.4): everything after `#`, and the node key + URL-safe and unpadded. `test_invite_link_client.py` (hub) holds it to the hub's. + """ + parts = urlsplit(hub_url) + origin = f"{parts.scheme}://{parts.netloc}" + n = node_pk_b64.replace("+", "-").replace("/", "_").rstrip("=") + return f"{origin}/#/invite?v=1&g={group_id}&t={ticket}&n={n}&c={code}" + + +async def create_link_invitation(state: dict, group_id: str, email: str, *, + created_by: str = "local-cli") -> dict: + """ + A whole invitation link, from the operator's own machine: the node's code, + then the hub's ticket bound to `email`, then the link. + + In that order because the ticket names the code's handle. A ticket the hub + refuses takes the code back with it — a code nobody can reach the node with + would only hold one of the group's places. The hub is never asked to mail: + the operator sends the link. + """ + email = (email or "").strip() + if "@" not in email: + raise OpError("An invitation link is bound to an e-mail address", status=422) + hub = _hub(state) + sk_node = state.get("sk_node") + if sk_node is None: + raise OpError("Node key not loaded", status=503) + node = await create_link_invite(state, group_id, created_by=created_by) + try: + ticket = await hub.create_invite_link( + group_id, email, node["expires_at"], node["invite_id"]) + except Exception as e: + await _roster(state).cancel_invite(group_id, node["invite_id"]) + raise OpError(f"The hub refused the link, so none was made: {e}", + status=502) from e + return { + "link": _invite_url(hub.hub_url, group_id, ticket["ticket"], + pk_to_b64(sk_node.public_key()), node["code"]), + "expires_at": ticket["expires_at"], + "invite_id": node["invite_id"], + "email": email, + } + + +async def cancel_link_invitation(state: dict, group_id: str, invite_id: str) -> dict: + """ + Take a link back, both halves: the node's code first, which is what stops + anyone joining, then the hub's ticket — attempted even when the first half + finds nothing to cancel, so neither is left behind (the member-removal rule). + """ + roster = _roster(state) + _group_ctx(state, group_id) + node_cancelled = await roster.cancel_invite(group_id, invite_id) + hub_cancelled = False + hub = state.get("hub") + if hub and hub._session: + try: + for link in await hub.list_invite_links(group_id): + if link.get("node_invite_id") == invite_id and link.get("status") == "pending": + await hub.delete_invite_link(group_id, link["link_id"]) + hub_cancelled = True + except Exception as e: + log.warning("Invitation link %s: the hub half was not cancelled: %s", + invite_id[:8], e) + if not node_cancelled and not hub_cancelled: + raise OpError("No unredeemed invitation link with that id in this group", + status=404) + log.info("Invitation link cancelled: group=%s invite=%s node=%s hub=%s", + group_id[:8], invite_id[:8], node_cancelled, hub_cancelled) + return {"cancelled": True, "invite_id": invite_id, + "node": node_cancelled, "hub": hub_cancelled} + + async def revoke_member(state: dict, user_id: str, group_id: str) -> dict: """ Stop serving the group key to someone. diff --git a/packages/meshbay-node/src/meshbay_node/ui/app.py b/packages/meshbay-node/src/meshbay_node/ui/app.py index f6b93ea..ff28e53 100644 --- a/packages/meshbay-node/src/meshbay_node/ui/app.py +++ b/packages/meshbay-node/src/meshbay_node/ui/app.py @@ -322,13 +322,15 @@ def create_ui_app(state: dict) -> FastAPI: async def create_invite(group_id: str, username: str): return await _op(lambda: ops.create_invite(state, group_id, username)) + # Both halves, node and hub, for the CLI: an operator at the machine gets a + # whole link, not a code without a ticket. @app.post("/api/groups/{group_id}/invite-links") - async def create_link_invite(group_id: str): - return await _op(lambda: ops.create_link_invite(state, group_id)) + async def create_link_invite(group_id: str, email: str): + return await _op(lambda: ops.create_link_invitation(state, group_id, email)) @app.delete("/api/groups/{group_id}/invite-links/{invite_id}") async def cancel_invite(group_id: str, invite_id: str): - return await _op(lambda: ops.cancel_invite(state, group_id, invite_id)) + return await _op(lambda: ops.cancel_link_invitation(state, group_id, invite_id)) @app.get("/api/resolve") async def resolve_user(username: str): -- cgit v1.2.3