""" Ordering guards for the SPA's connect() flow. These are source-level checks, which is not how one would normally test behaviour. They exist because a specific class of bug shipped to a live browser twice and no other test could see it: `connect()` is a long sequence in which later steps read values earlier steps set, and the Python end-to-end client in QE/deploy/ cannot catch a mistake there — it is a different implementation, written in the right order by construction, so it passes while the browser fails. Concretely: join_request signs a transcript over the node key and the node nonce, and runs *before* the GEK proof, because a first-time member has no GEK to prove. Both values were being read further down, next to the proof that also uses them, so every invited member hit "Handshake incomplete — reconnect and retry". If you restructure connect(), these will fail. Check the invariant still holds — that nothing reads a value assigned later — and then move the markers. """ from pathlib import Path import pytest STATIC = (Path(__file__).resolve().parents[1] / "src" / "meshbay_hub" / "static") TRANSPORT = STATIC / "transport.js" pytestmark = pytest.mark.skipif( not TRANSPORT.exists(), reason="SPA sources not present") def _positions(*needles: str) -> list[int]: source = TRANSPORT.read_text() out = [] for needle in needles: idx = source.find(needle) assert idx != -1, f"{needle!r} is gone from transport.js — update this test" out.append(idx) return out def test_challenge_values_are_captured_before_joining(): """ joinGroup() signs over node_pk and nonce_node, so both must be recorded when the challenge arrives — not later, beside the proof. """ # Deliberately loose markers: what matters is where the assignment happens, # not how it is spelled, so a reordering fails on the ordering assertion # below rather than on a missing string. node_pk, nonce_node, join_call = _positions( "this.nodePk = reply.node_pk", "this._nonceNode = ", "await this.joinGroup(", ) assert node_pk < join_call, ( "node_pk is read from the challenge after joinGroup() runs — the join " "would sign a transcript naming nothing") assert nonce_node < join_call, ( "nonce_node is captured after joinGroup() runs — the join would not be " "bound to this connection") def test_join_happens_before_the_gek_proof(): """ The whole point of joining in the pre-proof window: someone who has never held the group key cannot produce a proof, so the key has to arrive first. """ join_call, proof = _positions( "await this.joinGroup(", "await C.handshakeProof(", ) assert join_call < proof, ( "the join must happen before the GEK proof — a first-time member has no " "key to prove with") def test_keys_are_recovered_before_the_join_is_attempted(): """ A second browser holds nothing but a password. It recovers its identity keys from the node's encrypted keypair bundle, and only then can it sign a join — so the recovery has to come first. Getting this order wrong is invisible on the browser that registered, and breaks every other one. """ recover, join_call = _positions( "type: 'keypair_bundle_fetch'", "await this.joinGroup(", ) assert recover < join_call, ( "the keypair bundle must be fetched before joinGroup() — otherwise a " "browser that did not register has no key to sign the join with") def test_the_ack_still_verifies_the_announced_node_key(): """ Taking node_pk from the challenge is only safe because the ack proves it and the client compares the two. Losing that check would leave the announcement trusted on its own. """ source = TRANSPORT.read_text() assert "Node identity changed during the handshake" in source, ( "the challenge's node_pk must be checked against the ack's") assert "verifyNodeSignature" in source, ( "the ack's signature over the handshake transcript must still be verified") # ── Component boundaries ──────────────────────────────────────────────────── # # A second class of bug this file exists for. Moving a block between components # is a plain cut and paste, and nothing checks that the paste landed somewhere # the names it uses exist: the invite form and the member list were cut out of # MembersPanel and pasted into AdminPage, which left a standard member seeing an # empty Members tab, the group owner seeing only a pairing form, and the hub's # Users tab referencing `doInvite`, `members` and `adminId` — none of which are # defined there. APP = STATIC / "app.js" def _component(name: str) -> str: """The source of one top-level `function Name(...)`, up to the next one.""" source = APP.read_text() start = source.find(f"\nfunction {name}(") assert start != -1, f"{name} is gone from app.js — update this test" end = source.find("\nfunction ", start + 1) return source[start:end if end != -1 else len(source)] def test_members_panel_renders_what_it_owns(): panel = _component("MembersPanel") assert "members.map(" in panel, "the member list is not rendered" assert "onSubmit=${doInvite}" in panel, "the invite form is not rendered" assert "onSubmit=${doPair}" in panel, "the pairing form is not rendered" def test_the_invite_form_comes_before_the_list(): panel = _component("MembersPanel") assert panel.index("onSubmit=${doInvite}") < panel.index("members.map("), \ "the invite form belongs above the member list" def test_admin_page_does_not_borrow_the_members_panel_state(): admin = _component("AdminPage") for name in ("doInvite", "adminId", "inviteCode", "setInviteUser"): assert name not in admin, \ f"AdminPage references {name}, which only exists in MembersPanel" # ── Upload pipelining ─────────────────────────────────────────────────────── # # The upload loop waited for the node to acknowledge each 48 KB chunk before # reading the next one, which caps throughput at one chunk per round trip no # matter how much bandwidth there is — and keeps SCTP's congestion window shut, # so the transport never speeds up either. Measured over a 100 ms path: 0.16 MB/s # waiting for every ack, 3.47 MB/s with 32 chunks in flight. def test_the_uploader_keeps_several_chunks_in_flight(): src = TRANSPORT.read_text() body = src[src.index("async uploadFile("):] body = body[:body.index("\n async ", 1)] assert "UPLOAD_WINDOW" in body, "the send window is gone — uploads are serial again" assert "bufferedAmount" in body, ( "without backpressure the file lands in the send buffer in seconds and " "the progress bar becomes fiction") def test_no_caller_waits_for_one_chunk_at_a_time(): app = APP.read_text() assert "uploadChunk(" not in app, ( "a per-chunk await is back in the SPA; use transport.uploadFile()") # ── Transfers outlive the page ────────────────────────────────────────────── # # Downloads and uploads used to be state inside GroupPage, so leaving a group # unmounted the component, its cleanup closed the DataChannel, and a half-written # file was all you had. The store in transfers.js owns them now; these check the # two ends of that, since neither shows up in any Python test. def test_leaving_a_group_hands_the_transport_over_rather_than_closing_it(): app = APP.read_text() cleanup = app[app.index(" return () => {\n cancelled = true;"):] cleanup = cleanup[:cleanup.index("\n }, [groupId")] assert "releaseWhenIdle" in cleanup, ( "the group page closes its transport directly again — a running " "download would die with the page") assert ".close()" not in cleanup def test_signing_out_stops_them(): app = APP.read_text() logout = app[app.index(" logout: () => {"):] logout = logout[:logout.index("navigate('/login')")] assert "transfers.reset()" in logout, ( "logout must cancel transfers: they run on tokens that stop being ours") def test_the_files_panel_no_longer_carries_its_own_progress_bars(): """They moved next to the bell, where they stay visible across the app.""" app = APP.read_text() for gone in ("setUlState", "setDlState", "dl-bar"): assert gone not in app, f"{gone} survived the move to the transfer widget" # ── Downloading a selection ───────────────────────────────────────────────── def test_a_multi_file_download_waits_for_each_picker(): """ A browser allows one file picker at a time. Firing every download at once meant the first opened a dialog and the rest were rejected — two files selected, one file downloaded. """ app = APP.read_text() block = app[app.index("${selectedFiles.length > 0 && html`"):] block = block[:block.index("`}")] assert "await downloadFile(e)" in block, ( "downloads are fired without awaiting again; only the first will ask " "for a save location and the others will be rejected") def test_links_in_chat_are_built_as_elements_not_markup(): """ A message is something another member wrote. It becomes an anchor element, never HTML, and only for http(s) — otherwise javascript: would be one message away from running here. """ app = APP.read_text() fn = app[app.index("function linkify("):] fn = fn[:fn.index("\nfunction ", 1)] assert "innerHTML" not in fn and "dangerouslySetInnerHTML" not in fn assert 'rel="noopener noreferrer"' in fn assert "https?" in app[app.index("const URL_RE"):app.index("function linkify(")]