aboutsummaryrefslogtreecommitdiffstats
path: root/packages/meshbay-hub/tests
diff options
context:
space:
mode:
authorChristophe Besson <cbesson@gmail.com>2026-10-05 11:53:57 +0200
committerChristophe Besson <cbesson@gmail.com>2026-10-05 11:53:57 +0200
commit8f25294b0f6bc3f292442edd69a2e149f0717b52 (patch)
tree58cfe661b15fce395ab5116f19341bdb6a5b07fe /packages/meshbay-hub/tests
parent28752696f376eb11feb686580a435b166750a723 (diff)
downloadmeshbay-8f25294b0f6bc3f292442edd69a2e149f0717b52.tar.gz
feat: open a group, a folder or a file from a #/name@owner link
A group can now be reached by the handle shown under its name, and a path after it points inside the group: #/name@owner/root/dir/file downloads the file and opens Files on its folder; a folder opens Files there. The handle is resolved in the client against the account's own /v1/groups/mine, so no hub route answers for a name and nobody can probe for one. While a group is open the address shows the handle (replace, no history entry); a linked path is taken out of the address once acted on, so a reload does not download twice. Signing in no longer sends everyone home: the form stood in for the page the address named, and that is where a link opened signed out was going. group-link.js holds the parsing and lookups, executed whole by test_group_link.py; harness/group_link_probe.py drives the router in Chrome. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Diffstat (limited to 'packages/meshbay-hub/tests')
-rw-r--r--packages/meshbay-hub/tests/harness/group_link_probe.py176
-rw-r--r--packages/meshbay-hub/tests/test_group_link.py170
-rw-r--r--packages/meshbay-hub/tests/test_group_link_flow.py67
3 files changed, 413 insertions, 0 deletions
diff --git a/packages/meshbay-hub/tests/harness/group_link_probe.py b/packages/meshbay-hub/tests/harness/group_link_probe.py
new file mode 100644
index 0000000..2d7c0d7
--- /dev/null
+++ b/packages/meshbay-hub/tests/harness/group_link_probe.py
@@ -0,0 +1,176 @@
+#!/usr/bin/env python3
+"""
+A group link, `#/name@owner[/path]`, opened in the real application.
+
+`test_group_link.py` runs `group-link.js` on its own; this is where it meets
+the router, the account's group list and the sign-in state. Loads the shipped
+`app.js` in a real browser with `fetch` stubbed (no node answers, so a group
+page goes as far as "offline"), once per case:
+
+ handle — `#/demo@someowner`: the group page, the address left as it is
+ uuid — `#/group/<id>`: the same page, the address showing the handle
+ file — `#/demo@someowner/<path>`: the page, the path kept in the address
+ until the index can say what it is (no node here: never)
+ unknown — `#/demo@stranger1`: not among the account's groups
+ signed_out — `#/demo@someowner/<path>` with no session: the sign-in form, and
+ the address untouched under it
+
+ group_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 = 8774
+RECORDS = []
+socketserver.TCPServer.allow_reuse_address = True
+
+GROUP = "0f8fad5b-d9cb-469f-a165-70867728950e"
+FILE = "backup/city_2015/backup/IMG_0001.JPG"
+LINKS = {
+ "handle": "#/demo@someowner",
+ "uuid": f"#/group/{GROUP}",
+ "file": f"#/demo@someowner/{FILE}",
+ "unknown": "#/demo@stranger1",
+ "signed_out": f"#/demo@someowner/{FILE}",
+}
+CASES = list(LINKS)
+
+PAGE = r"""<!doctype html><html><head><meta charset=utf-8></head><body>
+<div id="app"></div>
+<script type="module">
+const CASE = new URLSearchParams(location.search).get('case');
+const LINKS = __LINKS__;
+const realFetch = window.fetch.bind(window);
+const post = (o) => realFetch('/log', { method: 'POST', body: JSON.stringify(o) });
+const calls = [];
+const json = (body, status = 200) => ({
+ ok: status < 400, status, statusText: '', headers: new Headers(),
+ json: async () => body, text: async () => JSON.stringify(body),
+});
+window.fetch = async (url, init = {}) => {
+ const u = String(url);
+ calls.push(u);
+ if (u.includes('/v1/users/me/preferences')) return json({});
+ if (u.includes('/v1/users/me')) return json({ user_id: 'u-1', role: 'user' });
+ if (u.includes('/v1/groups/mine')) return json({ groups: [
+ { id: '__GROUP__', name: 'demo', owner_username: 'someowner', visibility: 'private',
+ created_at: '2026-01-01T00:00:00+00:00', description: '' },
+ { id: 'other-group', name: 'demo', owner_username: 'otherowner', visibility: 'private',
+ created_at: '2026-01-01T00:00:00+00:00', description: '' },
+ ] });
+ if (u.includes('/nodes')) return json({ nodes: [] });
+ return json({});
+};
+if (CASE === 'signed_out') {
+ localStorage.removeItem('mb_auth');
+} else {
+ localStorage.setItem('mb_auth', JSON.stringify({
+ username: 'member-account', userId: 'u-1', token: 'tok', refreshToken: 'ref',
+ role: 'user' }));
+}
+sessionStorage.clear();
+history.replaceState(null, '', '/?case=' + CASE + LINKS[CASE]);
+
+const wait = (ms) => new Promise((r) => setTimeout(r, ms));
+(async () => {
+ const out = { case: CASE };
+ try {
+ await import('/app.js');
+ await wait(2000);
+ out.hash = decodeURI(location.hash);
+ out.history_length = history.length;
+ out.group_page = Boolean(document.querySelector('.group-header'));
+ out.group_title = (document.querySelector('.group-header h2') || {}).innerText || '';
+ out.active_sidebar = [...document.querySelectorAll('.sidebar-group.active')]
+ .map((a) => a.getAttribute('href'));
+ out.message = (document.querySelector('main .page-message') || {}).innerText || '';
+ out.spinner = Boolean(document.querySelector('main .page-message .spinner'));
+ out.login_form = Boolean(document.querySelector('input[type=password]'));
+ out.hub_calls = calls.map((c) => c.replace(/^https?:\/\/[^/]+/, ''));
+ } catch (e) {
+ out.error = String(e && e.stack || e);
+ }
+ post(out);
+})();
+</script></body></html>
+""".replace("__GROUP__", GROUP).replace("__LINKS__", json.dumps(LINKS))
+
+
+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(case) for case in CASES]
+ 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_group_link.py b/packages/meshbay-hub/tests/test_group_link.py
new file mode 100644
index 0000000..e71df20
--- /dev/null
+++ b/packages/meshbay-hub/tests/test_group_link.py
@@ -0,0 +1,170 @@
+"""
+A group named in the address: `#/name@owner[/path]`.
+
+The handle under every group's name is also a link to it, and a path after it
+names a folder to open or a file to download. `group-link.js` parses it,
+builds it, finds the group among the account's own and the entry in the
+group's index; the module is executed whole, as `test_search_source_merge.py`
+does with `source-merge.js`, so these rules are the ones the page runs.
+
+Also held here, at source level: the sign-in form no longer sends everyone
+home, which is what made any link opened signed out land on the home page.
+"""
+
+import json
+import re
+import shutil
+import subprocess
+from pathlib import Path
+
+import pytest
+
+STATIC = Path(__file__).resolve().parents[1] / "src" / "meshbay_hub" / "static"
+SRC = STATIC / "group-link.js"
+
+IMPORT = re.compile(r"^\s*import\b", re.M)
+EXPORT = re.compile(r"^export \{[^}]*\};?\s*$", re.M)
+
+needs_node = pytest.mark.skipif(
+ shutil.which("node") is None or not SRC.exists(),
+ reason="node or the SPA sources are not available")
+
+
+@pytest.fixture(scope="module")
+def module_source():
+ text = SRC.read_text(encoding="utf-8")
+ assert not IMPORT.search(text), (
+ "group-link.js has gained an import; this test runs it standalone")
+ stripped, n = EXPORT.subn("", text)
+ assert n == 1
+ return stripped
+
+
+def _run(tmp_path, module_source, expr):
+ script = tmp_path / "case.js"
+ script.write_text(f"{module_source}\nconsole.log(JSON.stringify({expr}));\n",
+ encoding="utf-8")
+ out = subprocess.run(["node", str(script)], capture_output=True, text=True,
+ encoding="utf-8", timeout=30)
+ assert out.returncode == 0, out.stderr
+ return json.loads(out.stdout)
+
+
+GROUPS = [
+ {"id": "g1", "name": "demo", "owner_username": "someowner"},
+ {"id": "g2", "name": "demo", "owner_username": "otherowner"},
+ {"id": "g3", "name": "trips@home", "owner_username": "someowner"},
+ {"id": "g4", "name": "a/b c", "owner_username": "someowner"},
+]
+
+ENTRIES = [
+ {"path": "backup/city_2015/backup", "name": "IMG_0001.JPG"},
+ {"path": "backup/city_2015", "name": "notes.txt"},
+ {"path": "music", "name": "track 01.flac"},
+]
+
+
+@needs_node
+@pytest.mark.parametrize("route, expected", [
+ ("/demo@someowner", {"name": "demo", "owner": "someowner", "path": ""}),
+ ("/demo@someowner/backup/city_2015/backup/IMG_0001.JPG",
+ {"name": "demo", "owner": "someowner",
+ "path": "backup/city_2015/backup/IMG_0001.JPG"}),
+ # The owner is after the last `@`: a group name may hold one, a username not.
+ ("/trips@home@someowner", {"name": "trips@home", "owner": "someowner", "path": ""}),
+ # Each segment decoded on its own: an escaped `/` stays inside its segment.
+ ("/a%2Fb%20c@someowner/music/track%2001.flac",
+ {"name": "a/b c", "owner": "someowner", "path": "music/track 01.flac"}),
+ ("/demo@someowner/music/", {"name": "demo", "owner": "someowner", "path": "music"}),
+ # Every other route, and anything that is not a well-formed handle.
+ ("/group/0f8fad5b-d9cb-469f-a165-70867728950e", None),
+ ("/login", None), ("/", None), ("", None),
+ ("/@someowner", None), ("/demo@", None),
+ ("/demo@someowner/%E0%A4%A", None),
+ ("/demo@someowner/music/../../etc", None),
+])
+def test_parse(tmp_path, module_source, route, expected):
+ assert _run(tmp_path, module_source, f"parseGroupLink({json.dumps(route)})") == expected
+
+
+@needs_node
+@pytest.mark.parametrize("group, path", [
+ (GROUPS[0], ""),
+ (GROUPS[0], "backup/city_2015/backup/IMG_0001.JPG"),
+ (GROUPS[2], ""),
+ (GROUPS[3], "music/track 01.flac"),
+ ({"name": "Été à la mer", "owner_username": "someowner"}, "photos/plage #1.jpg"),
+])
+def test_built_routes_parse_back(tmp_path, module_source, group, path):
+ out = _run(tmp_path, module_source,
+ f"(() => {{ const r = groupLinkRoute({json.dumps(group)}, {json.dumps(path)});"
+ f" return [r, parseGroupLink(r)]; }})()")
+ route, parsed = out
+ assert parsed == {"name": group["name"], "owner": group["owner_username"], "path": path}
+ # Nothing that ends or splits a fragment is left bare.
+ assert not re.search(r"[#?\s%](?![0-9A-F]{2})", route)
+
+
+@needs_node
+def test_a_plain_handle_stays_readable(tmp_path, module_source):
+ route = _run(tmp_path, module_source,
+ f"groupLinkRoute({json.dumps(GROUPS[0])}, 'backup/city_2015/IMG_1.JPG')")
+ assert route == "/demo@someowner/backup/city_2015/IMG_1.JPG"
+
+
+@needs_node
+@pytest.mark.parametrize("link, expected", [
+ ({"name": "demo", "owner": "someowner"}, "g1"),
+ ({"name": "demo", "owner": "otherowner"}, "g2"),
+ # The hub keeps names unique on lower(name).
+ ({"name": "DEMO", "owner": "someowner"}, "g1"),
+ ({"name": "demo", "owner": "SomeOwner"}, "g1"),
+ # Not among the account's groups: nothing, and nothing asked of the hub.
+ ({"name": "demo", "owner": "stranger1"}, None),
+ ({"name": "secret", "owner": "someowner"}, None),
+])
+def test_find_among_own_groups(tmp_path, module_source, link, expected):
+ out = _run(tmp_path, module_source,
+ f"(findLinkedGroup({json.dumps(GROUPS)}, {json.dumps(link)}) || {{}}).id || null")
+ assert out == expected
+
+
+@needs_node
+@pytest.mark.parametrize("path, expected", [
+ ("backup/city_2015/backup/IMG_0001.JPG",
+ {"kind": "file", "entry": ENTRIES[0]}),
+ ("backup/city_2015/notes.txt", {"kind": "file", "entry": ENTRIES[1]}),
+ ("backup/city_2015", {"kind": "dir", "dir": "backup/city_2015"}),
+ ("backup", {"kind": "dir", "dir": "backup"}),
+ # An empty folder exists only in the node's own listing.
+ ("backup/empty", {"kind": "dir", "dir": "backup/empty"}),
+ # A prefix of a folder name is not that folder.
+ ("backup/city", None),
+ ("backup/city_2015/backup/img_0001.jpg", None),
+ ("", None),
+])
+def test_resolve_in_index(tmp_path, module_source, path, expected):
+ out = _run(tmp_path, module_source,
+ f"resolveLinkedPath({json.dumps(ENTRIES)}, ['backup/empty'], {json.dumps(path)})")
+ assert out == expected
+
+
+def test_signing_in_keeps_the_page_the_address_names():
+ """A group or file link opened signed out shows the sign-in form in its
+ place; signing in must leave the address alone, not send everyone home."""
+ source = (STATIC / "auth-page.js").read_text(encoding="utf-8")
+ body = source[source.index("export function LoginPage"):]
+ body = body[:body.index("\n}\n")]
+ assert "navigate('/')" not in body and 'navigate("/")' not in body
+ assert "if (loadPending()) navigate('/invite');" in body
+
+
+def test_the_router_resolves_a_handle_and_shows_it():
+ source = (STATIC / "app.js").read_text(encoding="utf-8")
+ body = source[source.index("\nfunction App() {"):]
+ assert "parseGroupLink(route)" in body
+ assert "findLinkedGroup(groups, groupLink)" in body
+ # Rewritten with `replace`: showing the handle is not a history entry.
+ assert "window.location.replace('#' + shownGroupRoute)" in body
+ # The sidebar highlights the group whichever form opened it.
+ assert re.search(r"<\$\{Sidebar\}[\s\S]*?route=\$\{groupRoute\}", body)
diff --git a/packages/meshbay-hub/tests/test_group_link_flow.py b/packages/meshbay-hub/tests/test_group_link_flow.py
new file mode 100644
index 0000000..eb6a353
--- /dev/null
+++ b/packages/meshbay-hub/tests/test_group_link_flow.py
@@ -0,0 +1,67 @@
+"""
+A group link, opened in the real application (harness/group_link_probe.py).
+
+`test_group_link.py` holds the parsing and the lookups; this is where they meet
+the router. A handle opens the group's page, and an id opens it with the handle
+in the address; a path waits in the address for the index to say what it is; a
+handle the account does not know is said to be unknown without the hub ever
+being asked about it; and signed out, the sign-in form stands in for the page
+with the address left alone, which is what lets signing in land there.
+"""
+
+import json
+import shutil
+import subprocess
+import sys
+from pathlib import Path
+
+import pytest
+
+HARNESS = Path(__file__).parent / "harness" / "group_link_probe.py"
+GROUP_HREF = "#/group/0f8fad5b-d9cb-469f-a165-70867728950e"
+FILE_LINK = "#/demo@someowner/backup/city_2015/backup/IMG_0001.JPG"
+
+
+@pytest.fixture(scope="module")
+def cases():
+ if shutil.which("google-chrome") is None:
+ pytest.skip("Chrome is not available")
+ proc = subprocess.run([sys.executable, str(HARNESS)],
+ capture_output=True, text=True, timeout=240)
+ assert proc.returncode == 0, f"probe failed: {proc.stdout}{proc.stderr}"
+ out = {c["case"]: c for c in json.loads(proc.stdout)}
+ for c in out.values():
+ assert "error" not in c, c["error"]
+ return out
+
+
+@pytest.mark.parametrize("case", ["handle", "uuid", "file"])
+def test_a_handle_or_an_id_opens_the_group(cases, case):
+ c = cases[case]
+ assert c["group_page"] and c["group_title"] == "demo@someowner"
+ # Of two groups called "demo", the one whose owner the handle names.
+ assert c["active_sidebar"] == [GROUP_HREF]
+
+
+@pytest.mark.parametrize("case", ["handle", "uuid"])
+def test_the_address_shows_the_handle_without_a_history_entry(cases, case):
+ assert cases[case]["hash"] == "#/demo@someowner"
+ assert cases[case]["history_length"] == 1
+
+
+def test_a_path_stays_in_the_address_until_it_has_been_acted_on(cases):
+ assert cases["file"]["hash"] == FILE_LINK
+
+
+def test_an_unknown_handle_is_said_so_without_asking_the_hub(cases):
+ c = cases["unknown"]
+ assert not c["group_page"] and c["message"] and not c["spinner"]
+ assert c["hash"] == "#/demo@stranger1"
+ for case in cases.values():
+ assert not any("stranger1" in u or "@" in u for u in case["hub_calls"])
+
+
+def test_signed_out_the_form_stands_in_for_the_page(cases):
+ c = cases["signed_out"]
+ assert c["login_form"] and not c["group_page"]
+ assert c["hash"] == FILE_LINK