From 35a7764db3f58a93c32206cb3ce74bb2f03967e7 Mon Sep 17 00:00:00 2001 From: Christophe Besson Date: Wed, 23 Sep 2026 18:05:14 +0200 Subject: feat(hub): open, create and join invitation links in the interface #/invite takes the link out of the address on load and keeps it in the tab through registration and sign-in; joining is one click, only the ticket goes to the hub, and the code goes only to the node the link names once it has signed its challenge. Members tab gains "Invite by link" (shared e-mail box, pending list, cancel both halves); home page takes a pasted link. Browser probe drives the real app, signed out and in. Co-Authored-By: Claude Opus 5.5 --- .../meshbay-hub/tests/harness/invite_link_probe.py | 181 +++++++++++++++++++ .../meshbay-hub/tests/test_invite_link_client.py | 194 +++++++++++++++++++++ .../meshbay-hub/tests/test_invite_link_flow.py | 61 +++++++ .../test_signed_in_never_sees_the_login_form.py | 6 +- 4 files changed, 441 insertions(+), 1 deletion(-) create mode 100644 packages/meshbay-hub/tests/harness/invite_link_probe.py create mode 100644 packages/meshbay-hub/tests/test_invite_link_client.py create mode 100644 packages/meshbay-hub/tests/test_invite_link_flow.py (limited to 'packages/meshbay-hub/tests') diff --git a/packages/meshbay-hub/tests/harness/invite_link_probe.py b/packages/meshbay-hub/tests/harness/invite_link_probe.py new file mode 100644 index 0000000..97ee893 --- /dev/null +++ b/packages/meshbay-hub/tests/harness/invite_link_probe.py @@ -0,0 +1,181 @@ +#!/usr/bin/env python3 +""" +An invitation link, opened in the real application. + +`test_invite_link_client.py` runs the link's functions one by one. What only the +running application can show is how they meet the router, the sign-in state and +the hub calls: that the code is out of the address before anything routes on +it, that a signed-out reader is sent to register with the invitation kept, and +that a signed-in reader is shown the invitation, joins with one click and lands +on the group — with the code never in a request to the hub. + +Loads the shipped `app.js` in a real browser with `fetch` stubbed, twice: + + signed_out — a link, no session + signed_in — the same link, a session; then the Join button is clicked + + invite_link_probe.py + +Prints JSON: one object per case. +""" + +import http.server +import json +import socketserver +import subprocess +import sys +import tempfile +import threading +import time +from pathlib import Path + +STATIC = Path(__file__).resolve().parents[2] / "src" / "meshbay_hub" / "static" +PORT = 8771 +RECORDS = [] +socketserver.TCPServer.allow_reuse_address = True + +GROUP = "0f8fad5b-d9cb-469f-a165-70867728950e" +TICKET = "AbCdEfGhIjKlMnOpQr-_12" +NODE = "A" * 43 +CODE = "K7P2-9WQX" +LINK = f"#/invite?v=1&g={GROUP}&t={TICKET}&n={NODE}&c={CODE}" + +PAGE = r""" +
+ +""".replace("__GROUP__", GROUP).replace("__LINK__", LINK).replace("__CODE__", CODE) + + +class H(http.server.SimpleHTTPRequestHandler): + def log_message(self, *a): + pass + + def do_POST(self): + length = int(self.headers.get("Content-Length") or 0) + body = self.rfile.read(length) + if self.path == "/log": + RECORDS.append(json.loads(body.decode())) + self.send_response(204) + self.end_headers() + + def _send(self, body: bytes, ctype: str) -> None: + self.send_response(200) + self.send_header("Content-Type", ctype) + self.send_header("Content-Length", str(len(body))) + self.end_headers() + self.wfile.write(body) + + def do_GET(self): + path = self.path.split("?")[0] + if path == "/": + self._send(PAGE.encode(), "text/html; charset=utf-8") + return + asset = (STATIC / path.lstrip("/")).resolve() + if not str(asset).startswith(str(STATIC)) or not asset.is_file(): + self.send_response(404) + self.end_headers() + return + ctype = "text/javascript" if asset.suffix in (".js", ".mjs") else ( + "application/wasm" if asset.suffix == ".wasm" else "application/octet-stream") + self._send(asset.read_bytes(), ctype) + + +def _run(case: str) -> dict | None: + before = len(RECORDS) + with tempfile.TemporaryDirectory(ignore_cleanup_errors=True) as profile: + proc = subprocess.Popen( + ["google-chrome", "--headless=new", "--disable-gpu", "--no-sandbox", + f"--user-data-dir={profile}", f"http://127.0.0.1:{PORT}/?case={case}"], + stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) + for _ in range(300): + if len(RECORDS) > before: + break + time.sleep(0.1) + proc.terminate() + try: + proc.wait(timeout=10) + except subprocess.TimeoutExpired: + proc.kill() + proc.wait() + return RECORDS[before] if len(RECORDS) > before else None + + +def main() -> int: + with socketserver.TCPServer(("127.0.0.1", PORT), H) as srv: + threading.Thread(target=srv.serve_forever, daemon=True).start() + results = [_run("signed_out"), _run("signed_in")] + if not all(results): + print(json.dumps({"error": "no measurement", "got": results}), file=sys.stderr) + return 1 + print(json.dumps(results, indent=1)) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/packages/meshbay-hub/tests/test_invite_link_client.py b/packages/meshbay-hub/tests/test_invite_link_client.py new file mode 100644 index 0000000..c5c0101 --- /dev/null +++ b/packages/meshbay-hub/tests/test_invite_link_client.py @@ -0,0 +1,194 @@ +""" +The browser's half of an invitation link (docs/MESHBAY_DESIGN.md §3.4). + +Three properties, each run against the shipped code rather than restated: + +- **one shape.** The hub writes a link when it mails one (`invite_url`), the + page writes one when it shows one (`buildInviteLink`), and the page reads both + (`parseInvite`). A disagreement is a link that opens on nothing. +- **the code leaves the address at once, and the tab keeps it.** Run in node + against a stand-in `window`: `captureFromLocation` rewrites the address and + stores what it read, and a malformed link is cleaned out without being kept. +- **the code goes to the node the link names, and to no other.** The transport's + `_linkJoinRefusal` is what stops it; this runs it. + +The rest are read from the source, which is the evidence there is for them: the +hub is never handed the code except when the inviter ticked the mail box, the +capture is the first thing `app.js` loads, and signing out forgets the +invitation. +""" + +import base64 +import json +import re +import shutil +import subprocess +from pathlib import Path + +import pytest +from meshbay_hub import mail as mail_mod +from meshbay_hub.api import invite_links + +STATIC = Path(__file__).resolve().parents[1] / "src" / "meshbay_hub" / "static" +LINK_JS = STATIC / "invite-link.js" + +pytestmark = pytest.mark.skipif(shutil.which("node") is None, reason="node is not available") + +GROUP = "0f8fad5b-d9cb-469f-a165-70867728950e" +TICKET = "AbCdEfGhIjKlMnOpQr-_12" +NODE_PK_STD = base64.b64encode(bytes(range(32))).decode() # has '+', '/', '=' +CODE = "K7P2-9WQX" + + +def _module_body() -> str: + """invite-link.js with its import, its exports and its load-time capture + removed — the functions as shipped, runnable against a stand-in window.""" + src = LINK_JS.read_text(encoding="utf-8") + src = re.sub(r"^import .*?;\n", "", src, flags=re.M) + src = src.replace("export function", "function") + tail = "\ncaptureFromLocation();\nwindow.addEventListener('hashchange', captureFromLocation);\n" + assert src.endswith(tail), "invite-link.js no longer ends with its load-time capture" + return src[: -len(tail)] + + +def _run(tmp_path, script: str): + harness = tmp_path / "h.js" + harness.write_text(script) + out = subprocess.run(["node", str(harness)], capture_output=True, text=True, timeout=60) + assert out.returncode == 0, out.stderr + return json.loads(out.stdout) + + +_WINDOW = r""" +const store = new Map(); +globalThis.sessionStorage = { + getItem: (k) => (store.has(k) ? store.get(k) : null), + setItem: (k, v) => store.set(k, String(v)), + removeItem: (k) => store.delete(k), +}; +const replaced = []; +globalThis.window = { + location: { hash: '', pathname: '/', search: '' }, + history: { replaceState: (_s, _t, url) => replaced.push(url) }, + addEventListener() {}, +}; +const platform = { hubOrigin: () => 'https://hub.example' }; +""" + + +def test_one_shape_between_the_hub_and_the_page(tmp_path, monkeypatch): + monkeypatch.setattr(mail_mod, "_hub_url", "https://hub.example") + n = NODE_PK_STD.replace("+", "-").replace("/", "_").rstrip("=") + from_hub = invite_links.invite_url(GROUP, TICKET, n, CODE) + got = _run(tmp_path, _WINDOW + _module_body() + f""" + const fields = {{ g: '{GROUP}', t: '{TICKET}', + n: nodePkForLink('{NODE_PK_STD}'), c: '{CODE}' }}; + process.stdout.write(JSON.stringify({{ + parsed: parseInvite({json.dumps(from_hub)}), + built: buildInviteLink('https://hub.example', fields), + back: nodePkFromLink(fields.n), + lower: parseInvite({json.dumps(from_hub.replace(CODE, CODE.lower()))}), + }})); + """) + assert got["parsed"] == {"g": GROUP, "t": TICKET, "n": n, "c": CODE} + assert got["built"] == from_hub + assert got["back"] == NODE_PK_STD, "the key the transport compares must come back exact" + assert got["lower"]["c"] == CODE + + +@pytest.mark.parametrize("tamper", [ + lambda u: u.replace("v=1", "v=2"), + lambda u: u.replace(CODE, "K7P2-9WQ"), + lambda u: u.replace(CODE, "K7P2-9WQX