From ed9fb22ed703db38f9b07c00d17076f90aa4cbc8 Mon Sep 17 00:00:00 2001 From: Christophe Besson Date: Thu, 13 Aug 2026 04:10:14 +0200 Subject: fix(node)!: remove unauthenticated HTTP file API and TCP transport MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Phase 11.5.A — findings C1 and C6 (see second-review.md). C1: the per-group HTTP file API bound 0.0.0.0 for every configured group, private ones included, and served two endpoints with no authentication at all: GET /index (full Mesh Group Index) and GET /file/{id} (raw plaintext file via FileResponse). Anyone able to reach the port — LAN, forwarded port, permissive IPv6 — read every private file. This bypassed the entire GEK-proof and node sovereignty layer. Deleted rather than patched: it duplicated MNP without any of its controls. C6: the TCP+TLS chunk server accepted a bare JWT with no GEK proof, leaving a second non-compliant handshake path. Deleted; QUIC remains and will be brought to parity with WebRTC by the unified handshake in 11.5.4. Transport decision recorded in transport/__init__.py: WebRTC/ICE is primary for browser and native clients (the only NAT traversal validated here — 2 ISPs, IPv4 STUN + IPv6, 4G CGNAT); QUIC is kept for LAN, port-forwarded and hub-less group:// access. punch_nat() is a direct-connection helper, not a traversal stack. Also removed server_ssl_context()/client_ssl_context() from tls_cert.py (no remaining callers) and a dead import of the former in quic_server.py. generate_self_signed_cert() stays: QUIC uses it, and the certificate hash is the intended channel-binding anchor for 11.5.6, since QUIC has no DTLS fingerprint to bind the GEK proof to. BREAKING CHANGE: node.toml keys `port` and `http_port` are gone. Regenerate config with `meshbay-node init`. Env var MESHBAY_PORT -> MESHBAY_QUIC_PORT. Tests: 198 passed (209 - 7 test_http_server - 4 test_transport). No other test changed status. Net -1300 lines. Co-Authored-By: Claude Opus 5 --- packages/meshbay-node/src/meshbay_node/config.py | 29 +- packages/meshbay-node/src/meshbay_node/daemon.py | 61 +--- .../src/meshbay_node/transport/__init__.py | 21 +- .../src/meshbay_node/transport/client.py | 148 --------- .../src/meshbay_node/transport/http_server.py | 336 --------------------- .../src/meshbay_node/transport/quic_server.py | 1 - .../src/meshbay_node/transport/server.py | 286 ------------------ .../src/meshbay_node/transport/tls_cert.py | 36 +-- packages/meshbay-node/src/meshbay_node/ui/app.py | 6 +- packages/meshbay-node/tests/test_daemon.py | 18 +- packages/meshbay-node/tests/test_http_server.py | 227 -------------- packages/meshbay-node/tests/test_transport.py | 222 -------------- 12 files changed, 45 insertions(+), 1346 deletions(-) delete mode 100644 packages/meshbay-node/src/meshbay_node/transport/client.py delete mode 100644 packages/meshbay-node/src/meshbay_node/transport/http_server.py delete mode 100644 packages/meshbay-node/src/meshbay_node/transport/server.py delete mode 100644 packages/meshbay-node/tests/test_http_server.py delete mode 100644 packages/meshbay-node/tests/test_transport.py diff --git a/packages/meshbay-node/src/meshbay_node/config.py b/packages/meshbay-node/src/meshbay_node/config.py index a7a0785..b681355 100644 --- a/packages/meshbay-node/src/meshbay_node/config.py +++ b/packages/meshbay-node/src/meshbay_node/config.py @@ -26,27 +26,24 @@ url = "https://meshbay.org" username = "myusername" [node] -port = 19000 # TCP+TLS (MNP v1) -quic_port = 19010 # QUIC (MNP v2) -http_port = 19001 # HTTP file API (public content) -ui_port = 18000 # local web UI +quic_port = 19010 # QUIC (MNP) — LAN, port-forwarded, hub-less direct access +ui_port = 18000 # local admin UI (127.0.0.1 only) -# Multiple groups — each with its own directory and ports +# Browser and native clients reach this node over WebRTC DataChannel via hub +# signaling — no inbound port to open. QUIC is the optional direct path. + +# Multiple groups — each with its own directory [[groups]] id = "" # set after joining name = "My Media" shared_dir = "/home/user/Media" -port = 19000 quic_port = 19010 -http_port = 19001 [[groups]] id = "" name = "Public Archive" shared_dir = "/home/user/Archive" -port = 19002 quic_port = 19012 -http_port = 19003 visibility = "public" [keystore] @@ -68,9 +65,7 @@ class HubConfig: @dataclass class NodeConfig: - port: int = 19000 quic_port: int = 19010 - http_port: int = 19001 ui_port: int = 18000 @@ -80,9 +75,7 @@ class GroupConfig: name: str = "" shared_dir: str = "" visibility: str = "private" # public|private - port: int = 19000 # TCP+TLS MNP port for this group quic_port: int = 19010 # QUIC MNP port - http_port: int = 19001 # HTTP file API port @dataclass @@ -121,9 +114,9 @@ def load_config(path: Path = DEFAULT_CONFIG_PATH) -> Config: cfg.hub.username = hub.get("username", cfg.hub.username) nd = raw.get("node", {}) - cfg.node.port = nd.get("port", cfg.node.port) + # `port` (TCP+TLS) and `http_port` no longer exist — both listeners were removed + # in Phase 11.5 (findings C1, C6). Regenerate node.toml with `meshbay-node init`. cfg.node.quic_port = nd.get("quic_port", cfg.node.quic_port) - cfg.node.http_port = nd.get("http_port", cfg.node.http_port) cfg.node.ui_port = nd.get("ui_port", cfg.node.ui_port) # Multi-group: [[groups]] array @@ -134,9 +127,7 @@ def load_config(path: Path = DEFAULT_CONFIG_PATH) -> Config: name=g.get("name", ""), shared_dir=g.get("shared_dir", ""), visibility=g.get("visibility", "private"), - port=g.get("port", cfg.node.port), quic_port=g.get("quic_port", cfg.node.quic_port), - http_port=g.get("http_port", cfg.node.http_port), )) # Back-compat: single [group] section elif "group" in raw: @@ -163,8 +154,8 @@ def load_config(path: Path = DEFAULT_CONFIG_PATH) -> Config: cfg.hub.url = url if user := os.environ.get("MESHBAY_USERNAME"): cfg.hub.username = user - if port := os.environ.get("MESHBAY_PORT"): - cfg.node.port = int(port) + if port := os.environ.get("MESHBAY_QUIC_PORT"): + cfg.node.quic_port = int(port) return cfg diff --git a/packages/meshbay-node/src/meshbay_node/daemon.py b/packages/meshbay-node/src/meshbay_node/daemon.py index fe12909..c930e54 100644 --- a/packages/meshbay-node/src/meshbay_node/daemon.py +++ b/packages/meshbay-node/src/meshbay_node/daemon.py @@ -8,9 +8,9 @@ Startup sequence: 4. Fetch GEK bundle from hub (if group configured) 5. Start directory indexer (watchdog) 6. Create chat stores (one SQLite DB per group) - 7. Create WebRTC transport (browser clients via DataChannel) - 8. Start QUIC+TCP chunk servers (native clients) - 9. Start HTTP file API (public content) + 7. Create WebRTC transport (browser + native clients via DataChannel) + 8. Start QUIC chunk server (LAN / port-forwarded / hub-less direct access) + 9. (Phase 11.5: the unauthenticated HTTP file API and the TCP+TLS server were removed) 10. Start hub WebSocket (signaling, revocations, WebRTC offers) 11. Start local web UI on node.ui_port (localhost only) 12. Run until SIGINT/SIGTERM @@ -43,11 +43,9 @@ from meshbay_node.hub_client import HubClient, HubConfig from meshbay_node.indexer import DirectoryIndexer from meshbay_node.keystore import NodeKeys, load_or_create_keystore from meshbay_node.transport import ( - ChunkServer, Denylist, QUIC_AVAILABLE, WEBRTC_AVAILABLE, - create_http_app, ) if QUIC_AVAILABLE: @@ -103,12 +101,10 @@ class NodeDaemon: "hub_url": config.hub.url, "username": config.hub.username, "groups": [g.name for g in config.groups], - "node_port": config.node.port, "quic_port": config.node.quic_port, "endpoint_hint": None, "indexes": {}, } - self._tcp_server: ChunkServer | None = None self._quic_server = None self._webrtc = None self._denylist = Denylist() if Denylist else None @@ -118,7 +114,6 @@ class NodeDaemon: self._indexers: list[DirectoryIndexer] = [] self._tasks: list[asyncio.Task] = [] self._hub: HubClient | None = None - self._http_servers: list[uvicorn.Server] = [] async def run(self) -> None: log.info("MeshBay Node starting up") @@ -265,7 +260,7 @@ class NodeDaemon: else: log.warning("WebRTC not available (aiortc not installed)") - # 7. QUIC + TCP chunk servers + # 7. QUIC chunk server (LAN / port-forwarded / hub-less direct access) if QUIC_AVAILABLE: self._quic_server = QuicChunkServer( sk_node=keys.sk_ed25519, @@ -282,19 +277,6 @@ class NodeDaemon: log.info("QUIC server on port %d (%d groups)", self._config.node.quic_port, len(groups_ctx)) - self._tcp_server = ChunkServer( - sk_node=keys.sk_ed25519, - hub_pk_pem=session.hub_pk_pem, - gek=first["gek"], - shared_root=first["shared_root"], - index=first["index"], - host="0.0.0.0", - port=self._config.node.port, - groups=groups_ctx, - ) - await self._tcp_server.start() - log.info("TCP+TLS server on port %d", self._config.node.port) - # 8. Hub WebSocket (signaling + revocations + WebRTC offers) async def on_webrtc_offer(sdp, peer_id, ice_candidates): if not self._webrtc: @@ -338,32 +320,10 @@ class NodeDaemon: self._tasks.append(ws_task) log.info("Hub WS task started") - # 9. HTTP file API (one per group) - for gid, gctx in groups_ctx.items(): - group_cfg = next( - (g for g in self._config.groups if g.id == gid), None) - if not group_cfg: - continue - http_app = create_http_app( - sk_node=keys.sk_ed25519, - hub_pk_pem=session.hub_pk_pem, - shared_root=gctx["shared_root"], - index=gctx["index"], - group_id=gid, - group_name=group_cfg.name, - gek=gctx.get("gek"), - ) - http_cfg = uvicorn.Config( - http_app, - host="0.0.0.0", - port=group_cfg.http_port, - log_level="warning", - ) - http_server = uvicorn.Server(http_cfg) - self._http_servers.append(http_server) - self._tasks.append(asyncio.create_task(http_server.serve())) - log.info("HTTP API on port %d for group %s", - group_cfg.http_port, group_cfg.name) + # 9. (removed in Phase 11.5) The per-group HTTP file API used to start here. + # It served the Mesh Group Index and raw plaintext files on 0.0.0.0 with no + # authentication, for private groups too — finding C1. Every client path now + # goes through the MNP handshake (JWT + group claim + GEK proof). # 10. Update admin UI state (UI already running from step 2) self._state["groups_ctx"] = groups_ctx @@ -541,11 +501,6 @@ class NodeDaemon: if self._quic_server: await self._quic_server.stop() - if self._tcp_server: - await self._tcp_server.stop() - - for server in self._http_servers: - server.should_exit = True log.info("Node stopped") diff --git a/packages/meshbay-node/src/meshbay_node/transport/__init__.py b/packages/meshbay-node/src/meshbay_node/transport/__init__.py index df9c209..e423e35 100644 --- a/packages/meshbay-node/src/meshbay_node/transport/__init__.py +++ b/packages/meshbay-node/src/meshbay_node/transport/__init__.py @@ -1,7 +1,17 @@ -"""MeshBay Node transport layer — TCP+TLS (v1), QUIC (v2), WebRTC (browsers).""" -from .server import ChunkServer -from .client import ChunkClient -from .http_server import create_http_app +""" +MeshBay Node transport layer — WebRTC DataChannel (primary), QUIC (direct/LAN). + +Transport decision (2026-08-13, second security review): + - WebRTC/ICE is the primary path for browser AND native clients. ICE/STUN is the + only NAT traversal validated on this project (2 ISPs, IPv4 STUN + IPv6, 4G CGNAT). + - QUIC is kept at parity for LAN, port-forwarded and hub-less `group://` access. + `punch_nat()` is a direct-connection helper, not a traversal stack. + - TCP+TLS (`server.py`/`client.py`) and the node HTTP file API (`http_server.py`) + were REMOVED in Phase 11.5. The HTTP API served private group indexes and + plaintext files with no authentication on 0.0.0.0 (finding C1); the TCP server + accepted a bare JWT with no GEK proof (finding C6). Neither is coming back — + every client path must go through the unified MNP handshake. +""" # QUIC transport (MNP v2) — requires aioquic>=1.0 try: @@ -14,7 +24,7 @@ except ImportError: Denylist = None # type: ignore[assignment,misc] QUIC_AVAILABLE = False -# WebRTC transport (browsers) — requires aiortc>=1.9 +# WebRTC transport (browsers + native clients) — requires aiortc>=1.9 try: from .webrtc_server import WebRTCTransport, WebRTCPeerSession WEBRTC_AVAILABLE = True @@ -24,7 +34,6 @@ except ImportError: WEBRTC_AVAILABLE = False __all__ = [ - "ChunkServer", "ChunkClient", "create_http_app", "QuicChunkServer", "QuicChunkClient", "Denylist", "QUIC_AVAILABLE", "WebRTCTransport", "WebRTCPeerSession", "WEBRTC_AVAILABLE", ] diff --git a/packages/meshbay-node/src/meshbay_node/transport/client.py b/packages/meshbay-node/src/meshbay_node/transport/client.py deleted file mode 100644 index 63d50af..0000000 --- a/packages/meshbay-node/src/meshbay_node/transport/client.py +++ /dev/null @@ -1,148 +0,0 @@ -""" -MeshBay — TCP+TLS chunk client (MNP v1). - -Used by the web client (or other nodes) to fetch files from a Mesh Node. -Verifies Ed25519 chunk signatures using the node's public key from the hub. -""" - -import asyncio -import base64 -import logging -import struct -from pathlib import Path - -import blake3 -import msgpack -from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey - -from meshbay_common import MNP_VERSION -from meshbay_common.crypto import ( - chunk_key as derive_chunk_key, - decrypt_chunk, - verify_chunk_signature, -) -from meshbay_common.protocol import MNP -from meshbay_node.transport.tls_cert import client_ssl_context - -log = logging.getLogger(__name__) - -MAX_MSG = 64 * 1024 * 1024 - - -async def _send(writer, obj): - data = msgpack.packb(obj, use_bin_type=True) - writer.write(struct.pack(">I", len(data)) + data) - await writer.drain() - -async def _recv(reader): - header = await reader.readexactly(4) - length = struct.unpack(">I", header)[0] - if length > MAX_MSG: - raise ValueError(f"Message too large: {length}") - return msgpack.unpackb(await reader.readexactly(length), raw=False) - - -class ChunkClient: - """ - Async client for fetching encrypted chunks from a ChunkServer. - - Usage: - async with ChunkClient(host, port, jwt_token, gek, pk_node_b64) as client: - data = await client.fetch_chunk(file_id, chunk_index=0) - """ - - def __init__( - self, - host: str, - port: int, - jwt_token: str, - gek: bytes, - pk_node_b64: str, # node's Ed25519 PK from hub — used for sig verification - group_id: str = "", - ): - self._host = host - self._port = port - self._jwt_token = jwt_token - self._gek = gek - self._group_id = group_id - self._pk_node = Ed25519PublicKey.from_public_bytes( - base64.b64decode(pk_node_b64)) - self._reader: asyncio.StreamReader | None = None - self._writer: asyncio.StreamWriter | None = None - - async def __aenter__(self): - await self.connect() - return self - - async def __aexit__(self, *_): - await self.close() - - async def connect(self) -> None: - ssl_ctx = client_ssl_context() - self._reader, self._writer = await asyncio.open_connection( - self._host, self._port, ssl=ssl_ctx) - - handshake_msg = { - "type": MNP.HANDSHAKE, - "v": MNP_VERSION, - "token": self._jwt_token, - } - if self._group_id: - handshake_msg["group_id"] = self._group_id - await _send(self._writer, handshake_msg) - ack = await _recv(self._reader) - if ack.get("type") != MNP.HANDSHAKE_ACK: - raise ConnectionError(f"Handshake rejected: {ack}") - log.debug("Connected to node %s:%d", self._host, self._port) - - async def close(self) -> None: - if self._writer: - self._writer.close() - await self._writer.wait_closed() - - async def fetch_index(self) -> bytes: - """Request the Mesh Group Index. Returns raw wire bytes (encrypted).""" - await _send(self._writer, {"type": MNP.INDEX_SYNC, "v": MNP_VERSION}) - msg = await _recv(self._reader) - return base64.b64decode(msg["index_b64"]) - - async def fetch_chunk(self, file_id: str, chunk_index: int) -> bytes: - """ - Fetch, verify, and decrypt one chunk. - Returns plaintext bytes. - """ - await _send(self._writer, { - "type": MNP.FILE_REQUEST, - "v": MNP_VERSION, - "file_id": file_id, - "chunk_index": chunk_index, - }) - msg = await _recv(self._reader) - - if msg.get("type") == "error": - raise LookupError(msg.get("detail", "Unknown error")) - - ct = base64.b64decode(msg["ct_b64"]) - nonce = base64.b64decode(msg["nonce_b64"]) - ct_hash = base64.b64decode(msg["ct_hash_b64"]) - pt_hash = base64.b64decode(msg["pt_hash_b64"]) - sig = base64.b64decode(msg["sig_b64"]) - file_hash = base64.b64decode(msg["file_hash_b64"]) - ci = msg["chunk_index"] - - # 1. Verify Ed25519 signature - verify_chunk_signature(self._pk_node, ci, nonce, ct_hash, sig) - - # 2. Verify ciphertext hash - if blake3.blake3(ct).digest() != ct_hash: - raise ValueError("Ciphertext hash mismatch") - - # 3. Decrypt - ckey = derive_chunk_key(self._gek, file_hash, ci) - plaintext = decrypt_chunk(ckey, nonce, ct) - - # 4. Verify plaintext hash - if blake3.blake3(plaintext).digest() != pt_hash: - raise ValueError("Plaintext hash mismatch after decryption") - - return plaintext diff --git a/packages/meshbay-node/src/meshbay_node/transport/http_server.py b/packages/meshbay-node/src/meshbay_node/transport/http_server.py deleted file mode 100644 index 151c2e8..0000000 --- a/packages/meshbay-node/src/meshbay_node/transport/http_server.py +++ /dev/null @@ -1,336 +0,0 @@ -""" -MeshBay Node — HTTP file API (port 19001, public content). - -Serves public group content over standard HTTP so browsers can -access files without any special protocol. - -Endpoints: - GET / node info (JSON) - GET /index public Mesh Group Index (JSON) - GET /file/{file_id} full file download (streaming) - GET /file/{file_id}/{chunk} single encrypted chunk (JSON) - GET /hls/{file_id}/playlist.m3u8 HLS playlist - GET /hls/{file_id}/{segment}.ts HLS segment (binary TS) - -Auth: Bearer JWT in Authorization header (or ?token= query param). -For public groups: auth optional (anonymous browse allowed). -For chunk download: auth required (JWT verified offline with hub PK). - -Note: this server handles PUBLIC content only (no GEK decryption). -Private group content requires a client that can do ChaCha20 (Phase 5). -""" - -import asyncio -import base64 -import json -import logging -import os -import struct -import subprocess -import tempfile -from pathlib import Path - -import blake3 -import jwt -from fastapi import FastAPI, Header, HTTPException, Query, Request -from fastapi.responses import FileResponse, JSONResponse, StreamingResponse -from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey - -from meshbay_common import MNP_VERSION -from meshbay_common.crypto import sign_chunk, pk_to_b64 -from meshbay_common.webcrypto import chunk_key_aes as derive_chunk_key, encrypt_chunk_aes as encrypt_chunk -from meshbay_node import __version__ -from meshbay_node.indexer import GroupIndex -from meshbay_node.indexer.group_index import GroupIndex - -log = logging.getLogger(__name__) - -CHUNK_SIZE = 1024 * 1024 # 1 MB -HLS_SEGMENT_DURATION = 4 # seconds per HLS segment - - -def create_http_app( - sk_node: Ed25519PrivateKey, - hub_pk_pem: bytes, - shared_root: Path, - index: GroupIndex, - group_id: str, - group_name: str, - gek: bytes | None = None, # None for public groups -) -> FastAPI: - """ - Create the node's public HTTP API FastAPI app. - Bind to 0.0.0.0:19001 (or configured port) for external access. - """ - app = FastAPI( - title="MeshBay Node HTTP API", - version=__version__, - docs_url=None, - redoc_url=None, - ) - - # ── Auth helper ─────────────────────────────────────────────────────────── - - def _verify_token_optional( - authorization: str | None, - token_param: str | None, - ) -> dict | None: - """Verify JWT if provided. Returns decoded payload or None.""" - raw = None - if authorization and authorization.lower().startswith("bearer "): - raw = authorization[7:] - elif token_param: - raw = token_param - if not raw: - return None - try: - return jwt.decode(raw, hub_pk_pem, algorithms=["EdDSA"]) - except Exception: - return None - - def _require_token( - authorization: str | None, - token_param: str | None, - ) -> dict: - decoded = _verify_token_optional(authorization, token_param) - if decoded is None: - raise HTTPException(status_code=401, detail="Authentication required") - return decoded - - # ── Node info ───────────────────────────────────────────────────────────── - - @app.get("/") - async def node_info(): - return { - "node_version": __version__, - "mnp_version": MNP_VERSION, - "group_id": group_id, - "group_name": group_name, - "file_count": index.count, - "pk_node": pk_to_b64(sk_node.public_key()), - } - - # ── Public index ────────────────────────────────────────────────────────── - - @app.get("/index") - async def get_index( - authorization: str | None = Header(default=None), - token: str | None = Query(default=None), - ): - """Public Mesh Group Index as JSON. No auth required for public groups.""" - entries = [ - { - "id": e.id, - "name": e.name, - "path": e.path, - "size": e.size, - "type": e.type, - "duration": e.duration, - } - for e in index.entries - ] - return { - "group_id": group_id, - "group_name": group_name, - "version": index.version, - "entries": entries, - } - - # ── Full file download (streaming) ──────────────────────────────────────── - - @app.get("/file/{file_id}") - async def download_file( - file_id: str, - authorization: str | None = Header(default=None), - token: str | None = Query(default=None), - ): - """Stream an entire file. Public groups: no auth needed.""" - entry = index.get_entry(file_id) - if not entry: - raise HTTPException(status_code=404, detail="File not found in index") - - file_path = shared_root / entry.path / entry.name - if not file_path.exists(): - raise HTTPException(status_code=404, detail="File not on disk") - - return FileResponse( - path=str(file_path), - filename=entry.name, - media_type=_media_type(entry.name), - ) - - # ── Chunk endpoint (encrypted, for MNP-aware clients) ──────────────────── - - @app.get("/file/{file_id}/{chunk_index}") - async def get_chunk( - file_id: str, - chunk_index: int, - authorization: str | None = Header(default=None), - token: str | None = Query(default=None), - ): - """ - Serve one encrypted chunk (JSON). Auth required. - Clients that understand MNP can decrypt with the GEK they got from the hub. - """ - _require_token(authorization, token) - - entry = index.get_entry(file_id) - if not entry: - raise HTTPException(status_code=404, detail="File not found") - - file_path = shared_root / entry.path / entry.name - if not file_path.exists(): - raise HTTPException(status_code=404, detail="File not on disk") - - # Read chunk - with open(file_path, "rb") as f: - f.seek(chunk_index * CHUNK_SIZE) - plaintext = f.read(CHUNK_SIZE) - - if not plaintext: - raise HTTPException(status_code=416, detail="Chunk out of range") - - file_hash = bytes.fromhex(entry.id) - pt_hash = blake3.blake3(plaintext).digest() - - if gek: - # Private group: encrypt chunk - ckey = derive_chunk_key(gek, file_hash, chunk_index) - nonce, ct = encrypt_chunk(ckey, plaintext) - ct_hash = blake3.blake3(ct).digest() - sig = sign_chunk(sk_node, chunk_index, nonce, ct_hash) - return { - "chunk_index": chunk_index, - "plaintext_size": len(plaintext), - "encrypted": True, - "nonce_b64": base64.b64encode(nonce).decode(), - "ct_b64": base64.b64encode(ct).decode(), - "ct_hash_b64": base64.b64encode(ct_hash).decode(), - "pt_hash_b64": base64.b64encode(pt_hash).decode(), - "sig_b64": base64.b64encode(sig).decode(), - "pk_node_b64": pk_to_b64(sk_node.public_key()), - "file_hash_b64": base64.b64encode(file_hash).decode(), - } - else: - # Public group: serve plaintext chunk (TLS provides transport encryption) - pt_hash_b = blake3.blake3(plaintext).digest() - sig_payload = chunk_index.to_bytes(4, "big") + bytes(12) + pt_hash_b - sig = sk_node.sign(sig_payload) - return { - "chunk_index": chunk_index, - "plaintext_size": len(plaintext), - "encrypted": False, - "data_b64": base64.b64encode(plaintext).decode(), - "pt_hash_b64": base64.b64encode(pt_hash).decode(), - "sig_b64": base64.b64encode(sig).decode(), - "pk_node_b64": pk_to_b64(sk_node.public_key()), - } - - # ── HLS streaming ───────────────────────────────────────────────────────── - - @app.get("/hls/{file_id}/playlist.m3u8") - async def hls_playlist( - file_id: str, - authorization: str | None = Header(default=None), - token: str | None = Query(default=None), - ): - """Generate HLS playlist for a video file.""" - entry = index.get_entry(file_id) - if not entry or entry.type != "video": - raise HTTPException(status_code=404, detail="Video file not found") - - file_path = shared_root / entry.path / entry.name - if not file_path.exists(): - raise HTTPException(status_code=404, detail="File not on disk") - - duration = entry.duration or _probe_duration(file_path) - if not duration: - raise HTTPException(status_code=422, detail="Cannot determine video duration") - - n_segments = max(1, int(duration / HLS_SEGMENT_DURATION) + 1) - token_param = f"?token={token}" if token else "" - - lines = [ - "#EXTM3U", - "#EXT-X-VERSION:3", - f"#EXT-X-TARGETDURATION:{HLS_SEGMENT_DURATION}", - "#EXT-X-MEDIA-SEQUENCE:0", - ] - for i in range(n_segments): - seg_dur = min(HLS_SEGMENT_DURATION, duration - i * HLS_SEGMENT_DURATION) - if seg_dur <= 0: - break - lines.append(f"#EXTINF:{seg_dur:.3f},") - lines.append(f"/hls/{file_id}/{i}.ts{token_param}") - lines.append("#EXT-X-ENDLIST") - - return StreamingResponse( - iter(["\n".join(lines)]), - media_type="application/vnd.apple.mpegurl", - ) - - @app.get("/hls/{file_id}/{segment_index}.ts") - async def hls_segment( - file_id: str, - segment_index: int, - authorization: str | None = Header(default=None), - token: str | None = Query(default=None), - ): - """Serve one HLS segment as MPEG-TS via ffmpeg transcoding.""" - entry = index.get_entry(file_id) - if not entry or entry.type != "video": - raise HTTPException(status_code=404, detail="Video not found") - - file_path = shared_root / entry.path / entry.name - if not file_path.exists(): - raise HTTPException(status_code=404, detail="File not on disk") - - start_time = segment_index * HLS_SEGMENT_DURATION - - async def generate(): - proc = await asyncio.create_subprocess_exec( - "ffmpeg", "-hide_banner", "-loglevel", "error", - "-ss", str(start_time), - "-i", str(file_path), - "-t", str(HLS_SEGMENT_DURATION), - "-c:v", "copy", "-c:a", "copy", - "-f", "mpegts", "pipe:1", - stdout=asyncio.subprocess.PIPE, - stderr=asyncio.subprocess.DEVNULL, - ) - assert proc.stdout - while chunk := await proc.stdout.read(65536): - yield chunk - await proc.wait() - - return StreamingResponse(generate(), media_type="video/mp2t") - - return app - - -# ── Helpers ─────────────────────────────────────────────────────────────────── - -def _media_type(filename: str) -> str: - ext = Path(filename).suffix.lower() - return { - ".mp4": "video/mp4", ".mkv": "video/x-matroska", - ".webm": "video/webm", ".avi": "video/x-msvideo", - ".mp3": "audio/mpeg", ".flac": "audio/flac", - ".ogg": "audio/ogg", ".opus": "audio/opus", - ".jpg": "image/jpeg", ".png": "image/png", - ".pdf": "application/pdf", - }.get(ext, "application/octet-stream") - - -def _probe_duration(path: Path) -> float | None: - """Use ffprobe to get video duration in seconds.""" - try: - result = subprocess.run( - ["ffprobe", "-v", "quiet", "-print_format", "json", - "-show_format", str(path)], - capture_output=True, text=True, timeout=10, - ) - data = json.loads(result.stdout) - return float(data["format"]["duration"]) - except Exception: - return None diff --git a/packages/meshbay-node/src/meshbay_node/transport/quic_server.py b/packages/meshbay-node/src/meshbay_node/transport/quic_server.py index f439e62..ede756e 100644 --- a/packages/meshbay-node/src/meshbay_node/transport/quic_server.py +++ b/packages/meshbay-node/src/meshbay_node/transport/quic_server.py @@ -41,7 +41,6 @@ from meshbay_common.crypto import ( from meshbay_common.webcrypto import chunk_key_aes as derive_chunk_key, encrypt_chunk_aes as encrypt_chunk from meshbay_common.protocol import MNP from meshbay_node.indexer import GroupIndex -from meshbay_node.transport.tls_cert import server_ssl_context log = logging.getLogger(__name__) diff --git a/packages/meshbay-node/src/meshbay_node/transport/server.py b/packages/meshbay-node/src/meshbay_node/transport/server.py deleted file mode 100644 index b77f1f2..0000000 --- a/packages/meshbay-node/src/meshbay_node/transport/server.py +++ /dev/null @@ -1,286 +0,0 @@ -""" -MeshBay Node — TCP+TLS chunk server (MNP v1). - -Serves encrypted file chunks to authenticated clients over TLS. -Each connection: - 1. Client sends MNP handshake with JWT bearer token - 2. Server verifies JWT offline (hub PK cached) - 3. Client sends chunk requests - 4. Server reads from disk, encrypts on-the-fly, signs, sends - -Wire protocol: length-prefixed msgpack (4-byte big-endian length header). -All messages carry {"type": ..., "v": MNP_VERSION}. -""" - -import asyncio -import base64 -import logging -import struct -import time -from pathlib import Path - -import blake3 -import jwt -import msgpack -from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey - -from meshbay_common import MNP_VERSION -from meshbay_common.crypto import ( - chunk_key as derive_chunk_key, - encrypt_chunk, - sign_chunk, - pk_to_b64, -) -from meshbay_common.protocol import MNP -from meshbay_node.indexer import GroupIndex -from meshbay_node.transport.tls_cert import server_ssl_context - -log = logging.getLogger(__name__) - -CHUNK_SIZE = 1024 * 1024 # 1 MB -MAX_MSG = 64 * 1024 * 1024 # 64 MB max message size (safety) - - -# ── Wire helpers ────────────────────────────────────────────────────────────── - -async def _send(writer: asyncio.StreamWriter, obj: dict) -> None: - data = msgpack.packb(obj, use_bin_type=True) - writer.write(struct.pack(">I", len(data)) + data) - await writer.drain() - -async def _recv(reader: asyncio.StreamReader) -> dict: - header = await reader.readexactly(4) - length = struct.unpack(">I", header)[0] - if length > MAX_MSG: - raise ValueError(f"Message too large: {length}") - data = await reader.readexactly(length) - return msgpack.unpackb(data, raw=False) - - -# ── Chunk serving ───────────────────────────────────────────────────────────── - -def _serve_chunk( - sk_node: Ed25519PrivateKey, - gek: bytes, - file_path: Path, - file_hash: bytes, - chunk_index: int, -) -> dict: - """Read, encrypt, sign one chunk. Blocking — run in executor.""" - with open(file_path, "rb") as f: - f.seek(chunk_index * CHUNK_SIZE) - plaintext = f.read(CHUNK_SIZE) - - pt_hash = blake3.blake3(plaintext).digest() - ckey = derive_chunk_key(gek, file_hash, chunk_index) - nonce, ct = encrypt_chunk(ckey, plaintext) - ct_hash = blake3.blake3(ct).digest() - sig = sign_chunk(sk_node, chunk_index, nonce, ct_hash) - - return { - "type": MNP.FILE_CHUNK, - "v": MNP_VERSION, - "chunk_index": chunk_index, - "plaintext_size": len(plaintext), - "nonce_b64": base64.b64encode(nonce).decode(), - "ct_b64": base64.b64encode(ct).decode(), - "ct_hash_b64": base64.b64encode(ct_hash).decode(), - "pt_hash_b64": base64.b64encode(pt_hash).decode(), - "sig_b64": base64.b64encode(sig).decode(), - "pk_node_b64": pk_to_b64(sk_node.public_key()), - "file_hash_b64": base64.b64encode(file_hash).decode(), - } - - -# ── Connection handler ──────────────────────────────────────────────────────── - -class _ConnectionHandler: - def __init__( - self, - reader: asyncio.StreamReader, - writer: asyncio.StreamWriter, - sk_node: Ed25519PrivateKey, - hub_pk_pem: bytes, - gek: bytes, - shared_root: Path, - index: GroupIndex, - groups: dict[str, dict] | None = None, - ): - self._reader = reader - self._writer = writer - self._sk_node = sk_node - self._hub_pk_pem = hub_pk_pem - self._gek = gek - self._shared_root = shared_root - self._index = index - self._groups = groups - self._peer = writer.get_extra_info("peername") - self._user_id: str | None = None - self._group_id: str | None = None - - async def handle(self) -> None: - try: - await self._handshake() - await self._serve_loop() - except asyncio.IncompleteReadError: - log.debug("[%s] Client disconnected", self._peer) - except Exception as e: - log.warning("[%s] Error: %s", self._peer, e) - await _send(self._writer, {"type": "error", "detail": str(e)}) - finally: - self._writer.close() - - async def _handshake(self) -> None: - msg = await _recv(self._reader) - if msg.get("type") != MNP.HANDSHAKE: - raise ValueError(f"Expected handshake, got {msg.get('type')!r}") - - token = msg.get("token", "") - group_id = msg.get("group_id", "") - try: - decoded = jwt.decode(token, self._hub_pk_pem, algorithms=["EdDSA"]) - except Exception as e: - raise PermissionError(f"Invalid JWT: {e}") from e - - if group_id and group_id not in decoded.get("groups", []): - raise PermissionError("Not a member of this group") - - if group_id and self._groups and group_id not in self._groups: - raise PermissionError("Group not hosted on this node") - - self._user_id = decoded["sub"] - self._group_id = group_id - - if group_id and self._groups and group_id in self._groups: - ctx = self._groups[group_id] - self._gek = ctx["gek"] - self._shared_root = ctx["shared_root"] - self._index = ctx["index"] - - log.info("[%s] Handshake OK — user=%s group=%s", self._peer, self._user_id[:8], group_id[:8] if group_id else "none") - - await _send(self._writer, { - "type": MNP.HANDSHAKE_ACK, - "v": MNP_VERSION, - "node_pk": pk_to_b64(self._sk_node.public_key()), - }) - - async def _serve_loop(self) -> None: - loop = asyncio.get_event_loop() - while True: - msg = await _recv(self._reader) - mtype = msg.get("type") - - if mtype == MNP.INDEX_SYNC: - wire = self._index.serialize() - await _send(self._writer, { - "type": MNP.INDEX_SYNC, - "v": MNP_VERSION, - "index_b64": base64.b64encode(wire).decode(), - }) - - elif mtype == MNP.FILE_REQUEST: - file_id = msg["file_id"] - chunk_index = msg["chunk_index"] - - entry = self._index.get_entry(file_id) - if entry is None: - await _send(self._writer, { - "type": "error", - "detail": f"File not found: {file_id[:8]}", - }) - continue - - file_path = self._shared_root / entry.path / entry.name - if not file_path.exists(): - await _send(self._writer, { - "type": "error", "detail": "File not on disk"}) - continue - - file_hash = bytes.fromhex(entry.id) - chunk = await loop.run_in_executor( - None, _serve_chunk, - self._sk_node, self._gek, file_path, file_hash, chunk_index) - await _send(self._writer, chunk) - - else: - log.warning("[%s] Unknown message type: %s", self._peer, mtype) - - -# ── Server ──────────────────────────────────────────────────────────────────── - -class ChunkServer: - """ - Async TCP+TLS server that serves encrypted file chunks. - - Usage: - server = ChunkServer( - host="0.0.0.0", port=19000, - sk_node=sk, hub_pk_pem=pk_pem, - gek=gek, shared_root=Path("/data"), - index=group_index, - ) - await server.start() - # ... when shutting down: - await server.stop() - """ - - def __init__( - self, - sk_node: Ed25519PrivateKey, - hub_pk_pem: bytes, - gek: bytes, - shared_root: Path, - index: GroupIndex, - host: str = "0.0.0.0", - port: int = 19000, - cert_path: Path | None = None, - key_path: Path | None = None, - groups: dict[str, dict] | None = None, - ): - self._sk_node = sk_node - self._hub_pk_pem = hub_pk_pem - self._gek = gek - self._shared_root = shared_root - self._index = index - self._host = host - self._port = port - self._cert_path = cert_path - self._key_path = key_path - self._groups = groups - self._server: asyncio.Server | None = None - - @property - def port(self) -> int: - return self._port - - async def start(self) -> None: - ssl_ctx = server_ssl_context( - cert_path=self._cert_path or Path.home() / ".config/meshbay/node_tls.crt", - key_path=self._key_path or Path.home() / ".config/meshbay/node_tls.key", - ) - self._server = await asyncio.start_server( - self._handle_connection, - host=self._host, - port=self._port, - ssl=ssl_ctx, - ) - log.info("ChunkServer listening on %s:%d (TLS)", self._host, self._port) - - async def stop(self) -> None: - if self._server: - self._server.close() - await self._server.wait_closed() - self._server = None - log.info("ChunkServer stopped") - - async def _handle_connection( - self, reader: asyncio.StreamReader, writer: asyncio.StreamWriter - ) -> None: - handler = _ConnectionHandler( - reader, writer, - self._sk_node, self._hub_pk_pem, - self._gek, self._shared_root, self._index, - groups=self._groups, - ) - await handler.handle() diff --git a/packages/meshbay-node/src/meshbay_node/transport/tls_cert.py b/packages/meshbay-node/src/meshbay_node/transport/tls_cert.py index 1354ac9..374fd08 100644 --- a/packages/meshbay-node/src/meshbay_node/transport/tls_cert.py +++ b/packages/meshbay-node/src/meshbay_node/transport/tls_cert.py @@ -1,17 +1,18 @@ """ -Self-signed TLS certificate generation for the node. +Self-signed TLS certificate generation for the node's QUIC listener. The cert is used for transport confidentiality only. Node identity is verified via Ed25519 PK (from hub), not TLS cert chain. -Clients connect with ssl.CERT_NONE + verify Ed25519 at the MNP handshake layer. -Certificate is generated once and cached at ~/.config/meshbay/node_tls.pem/.key. +Phase 11.5 note: the certificate hash is also the intended channel-binding anchor for +the QUIC handshake proof (11.5.6), since QUIC has no DTLS fingerprint to bind to. + +Certificate is generated once and cached at ~/.config/meshbay/node_tls.crt/.key. """ import logging import os from pathlib import Path -import ssl import datetime import ipaddress @@ -69,27 +70,6 @@ def generate_self_signed_cert( return cert_path, key_path -def server_ssl_context( - cert_path: Path = DEFAULT_CERT, - key_path: Path = DEFAULT_KEY, -) -> ssl.SSLContext: - """SSL context for the node's TCP server.""" - if not cert_path.exists() or not key_path.exists(): - generate_self_signed_cert(cert_path, key_path) - - ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER) - ctx.load_cert_chain(certfile=cert_path, keyfile=key_path) - ctx.minimum_version = ssl.TLSVersion.TLSv1_3 - return ctx - - -def client_ssl_context() -> ssl.SSLContext: - """ - SSL context for clients connecting to a node. - CERT_NONE because we verify node identity via Ed25519 PK at the MNP layer. - """ - ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) - ctx.check_hostname = False - ctx.verify_mode = ssl.CERT_NONE - ctx.minimum_version = ssl.TLSVersion.TLSv1_3 - return ctx +# `server_ssl_context()` / `client_ssl_context()` were removed in Phase 11.5 along with +# the TCP+TLS transport they served. QUIC builds its own QuicConfiguration and calls +# generate_self_signed_cert() directly. diff --git a/packages/meshbay-node/src/meshbay_node/ui/app.py b/packages/meshbay-node/src/meshbay_node/ui/app.py index b4885af..31deb66 100644 --- a/packages/meshbay-node/src/meshbay_node/ui/app.py +++ b/packages/meshbay-node/src/meshbay_node/ui/app.py @@ -48,7 +48,6 @@ def create_ui_app(state: dict) -> FastAPI: "status": state.get("status", "starting"), "hub_url": state.get("hub_url", ""), "username": state.get("username", ""), - "node_port": state.get("node_port", 0), "quic_port": state.get("quic_port", 0), "endpoint_hint": state.get("endpoint_hint"), "group_count": len(groups_ctx), @@ -154,9 +153,7 @@ def create_ui_app(state: dict) -> FastAPI: return { "hub_url": config.hub.url, "username": config.hub.username, - "node_port": config.node.port, "quic_port": config.node.quic_port, - "http_port": config.node.http_port, "ui_port": config.node.ui_port, "data_dir": str(config.data_dir), "groups": [ @@ -493,8 +490,7 @@ def _render_page(state: dict) -> str:

Node Configuration

Hub: {state.get("hub_url", "—")}

-

QUIC port: {state.get("quic_port", "—")} — - TCP port: {state.get("node_port", "—")}

+

QUIC port: {state.get("quic_port", "—")}

Node ID: {state.get("endpoint_hint") or "—"}

diff --git a/packages/meshbay-node/tests/test_daemon.py b/packages/meshbay-node/tests/test_daemon.py index 1c5a07e..e899639 100644 --- a/packages/meshbay-node/tests/test_daemon.py +++ b/packages/meshbay-node/tests/test_daemon.py @@ -21,7 +21,6 @@ from meshbay_node.config import Config, HubConfig, NodeConfig, GroupConfig, Keys from meshbay_node.daemon import NodeDaemon from meshbay_node.indexer import DirectoryIndexer - def _mock_keystore_keys(sk_ed): """Create a mock keystore with real Ed25519 + X25519 key material.""" sk_x = X25519PrivateKey.generate() @@ -35,23 +34,19 @@ def _mock_keystore_keys(sk_ed): mock_keys.pk_x25519_b64 = base64.b64encode(pk_x_raw).decode() return mock_keys - @pytest.fixture def sk_hub(): return Ed25519PrivateKey.generate() - @pytest.fixture def hub_pk_pem(sk_hub): return sk_hub.public_key().public_bytes( serialization.Encoding.PEM, serialization.PublicFormat.SubjectPublicKeyInfo) - @pytest.fixture def gek(): return generate_gek() - @pytest.fixture def shared_dir(tmp_path): d = tmp_path / "shared" @@ -60,26 +55,22 @@ def shared_dir(tmp_path): (d / "hello.txt").write_bytes(b"hello daemon test " * 50) return d - @pytest.fixture def node_config(tmp_path, shared_dir): return Config( hub=HubConfig(url="http://localhost:9999", username="testuser"), - node=NodeConfig(port=29000, quic_port=29010, http_port=29001, ui_port=28000), + node=NodeConfig(quic_port=29010, ui_port=28000), groups=[GroupConfig( id="g" * 32, name="test-group", shared_dir=str(shared_dir), visibility="private", - port=29000, quic_port=29010, - http_port=29001, )], keystore=KeystoreConfig(path=tmp_path / "keystore.enc"), data_dir=tmp_path / "data", ) - @pytest.mark.asyncio async def test_daemon_creates_chat_store(tmp_path, node_config, gek, hub_pk_pem): """Daemon creates ChatStore for each group and shuts down cleanly.""" @@ -146,7 +137,6 @@ async def test_daemon_creates_chat_store(tmp_path, node_config, gek, hub_pk_pem) for store in daemon._chat_stores.values(): assert store._db is None - @pytest.mark.asyncio async def test_daemon_no_groups_exits(tmp_path): """Daemon with no valid groups exits cleanly.""" @@ -188,19 +178,18 @@ async def test_daemon_no_groups_exits(tmp_path): assert len(daemon._chat_stores) == 0 - @pytest.mark.asyncio async def test_daemon_index_change_pushes_to_peers(tmp_path, shared_dir, gek, hub_pk_pem): """Index change callback pushes updated index to WebRTC peers.""" config = Config( hub=HubConfig(url="http://localhost:9999", username="testuser"), - node=NodeConfig(port=29000, quic_port=29010, http_port=29001, ui_port=28000), + node=NodeConfig(quic_port=29010, ui_port=28000), groups=[GroupConfig( id="a" * 32, name="test-group", shared_dir=str(shared_dir), visibility="private", - port=29000, quic_port=29010, http_port=29001, + quic_port=29010, )], keystore=KeystoreConfig(path=tmp_path / "keystore.enc"), data_dir=tmp_path / "data", @@ -237,7 +226,6 @@ async def test_daemon_index_change_pushes_to_peers(tmp_path, shared_dir, gek, hu call_args = daemon._hub.register_swarm.call_args assert len(call_args[0][0]) == indexer.index.count - @pytest.mark.asyncio async def test_daemon_index_change_skips_other_group_peers( tmp_path, shared_dir, gek, hub_pk_pem diff --git a/packages/meshbay-node/tests/test_http_server.py b/packages/meshbay-node/tests/test_http_server.py deleted file mode 100644 index d4ccc32..0000000 --- a/packages/meshbay-node/tests/test_http_server.py +++ /dev/null @@ -1,227 +0,0 @@ -"""Tests for the node HTTP file API.""" - -import asyncio -import base64 -import json -import os -import time -import pytest -import jwt -import httpx -from pathlib import Path -from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey -from cryptography.hazmat.primitives import serialization - -from meshbay_common.crypto import generate_gek, pk_to_b64 -from meshbay_node.indexer import DirectoryIndexer -from meshbay_node.transport.http_server import create_http_app - - -@pytest.fixture -def sk_node(): - return Ed25519PrivateKey.generate() - -@pytest.fixture -def sk_hub(): - return Ed25519PrivateKey.generate() - -@pytest.fixture -def hub_pk_pem(sk_hub): - return sk_hub.public_key().public_bytes( - serialization.Encoding.PEM, serialization.PublicFormat.SubjectPublicKeyInfo) - -@pytest.fixture -def gek(): - return generate_gek() - -@pytest.fixture -def shared_dir(tmp_path): - d = tmp_path / "shared" - d.mkdir() - (d / "video.mp4").write_bytes(os.urandom(3 * 1024 * 1024)) # 3MB - (d / "doc.pdf").write_bytes(os.urandom(512 * 1024)) - (d / "song.mp3").write_bytes(os.urandom(256 * 1024)) - return d - -def make_token(sk_hub, pk_node_b64, ttl=3600): - sk_pem = sk_hub.private_bytes( - serialization.Encoding.PEM, serialization.PrivateFormat.PKCS8, - serialization.NoEncryption()) - now = int(time.time()) - return jwt.encode({ - "iss": "test-hub", "sub": "user-001", - "pk_user": pk_node_b64, "hub_id": "test-hub", - "jti": "test-jti", "iat": now, "exp": now + ttl, - }, sk_pem, algorithm="EdDSA") - - -@pytest.mark.asyncio -async def test_node_info(sk_node, sk_hub, hub_pk_pem, gek, shared_dir): - indexer = DirectoryIndexer(root=shared_dir, group_id="g", sk_node=sk_node, gek=gek) - await indexer.initial_scan() - - app = create_http_app( - sk_node=sk_node, hub_pk_pem=hub_pk_pem, - shared_root=shared_dir, index=indexer.index, - group_id="test-group", group_name="Test Group", - ) - async with httpx.AsyncClient( - transport=httpx.ASGITransport(app=app), base_url="http://test" - ) as c: - r = await c.get("/") - assert r.status_code == 200 - data = r.json() - assert data["group_id"] == "test-group" - assert data["file_count"] == 3 - assert "pk_node" in data - - -@pytest.mark.asyncio -async def test_public_index(sk_node, sk_hub, hub_pk_pem, shared_dir): - """Public group: index accessible without auth.""" - indexer = DirectoryIndexer(root=shared_dir, group_id="g", sk_node=sk_node, gek=None) - await indexer.initial_scan() - - app = create_http_app( - sk_node=sk_node, hub_pk_pem=hub_pk_pem, - shared_root=shared_dir, index=indexer.index, - group_id="pub-group", group_name="Public Group", - gek=None, - ) - async with httpx.AsyncClient( - transport=httpx.ASGITransport(app=app), base_url="http://test" - ) as c: - r = await c.get("/index") - assert r.status_code == 200 - data = r.json() - assert len(data["entries"]) == 3 - names = {e["name"] for e in data["entries"]} - assert "video.mp4" in names - assert "doc.pdf" in names - - -@pytest.mark.asyncio -async def test_file_download(sk_node, sk_hub, hub_pk_pem, shared_dir): - """Full file download via HTTP.""" - indexer = DirectoryIndexer(root=shared_dir, group_id="g", sk_node=sk_node, gek=None) - await indexer.initial_scan() - - app = create_http_app( - sk_node=sk_node, hub_pk_pem=hub_pk_pem, - shared_root=shared_dir, index=indexer.index, - group_id="g", group_name="G", - ) - entry = next(e for e in indexer.index.entries if e.name == "doc.pdf") - original = (shared_dir / "doc.pdf").read_bytes() - - async with httpx.AsyncClient( - transport=httpx.ASGITransport(app=app), base_url="http://test" - ) as c: - r = await c.get(f"/file/{entry.id}") - assert r.status_code == 200 - assert r.content == original - - -@pytest.mark.asyncio -async def test_chunk_public_group(sk_node, sk_hub, hub_pk_pem, shared_dir): - """Public group chunk: plaintext, signed, auth required.""" - indexer = DirectoryIndexer(root=shared_dir, group_id="g", sk_node=sk_node, gek=None) - await indexer.initial_scan() - - app = create_http_app( - sk_node=sk_node, hub_pk_pem=hub_pk_pem, - shared_root=shared_dir, index=indexer.index, - group_id="g", group_name="G", gek=None, - ) - entry = next(e for e in indexer.index.entries if e.name == "video.mp4") - token = make_token(sk_hub, pk_to_b64(sk_node.public_key())) - - async with httpx.AsyncClient( - transport=httpx.ASGITransport(app=app), base_url="http://test" - ) as c: - r = await c.get(f"/file/{entry.id}/0", - headers={"Authorization": f"Bearer {token}"}) - assert r.status_code == 200 - chunk = r.json() - assert chunk["encrypted"] is False - assert chunk["chunk_index"] == 0 - assert "data_b64" in chunk - - # Verify the chunk data matches original - original = (shared_dir / "video.mp4").read_bytes() - data = base64.b64decode(chunk["data_b64"]) - assert data == original[:len(data)] - - -@pytest.mark.asyncio -async def test_chunk_private_group(sk_node, sk_hub, hub_pk_pem, gek, shared_dir): - """Private group chunk: encrypted with GEK.""" - from meshbay_common.webcrypto import chunk_key_aes as derive_chunk_key, decrypt_chunk_aes as decrypt_chunk - import blake3 - - indexer = DirectoryIndexer(root=shared_dir, group_id="g", sk_node=sk_node, gek=gek) - await indexer.initial_scan() - - app = create_http_app( - sk_node=sk_node, hub_pk_pem=hub_pk_pem, - shared_root=shared_dir, index=indexer.index, - group_id="g", group_name="G", gek=gek, - ) - entry = next(e for e in indexer.index.entries if e.name == "doc.pdf") - token = make_token(sk_hub, pk_to_b64(sk_node.public_key())) - - async with httpx.AsyncClient( - transport=httpx.ASGITransport(app=app), base_url="http://test" - ) as c: - r = await c.get(f"/file/{entry.id}/0", - headers={"Authorization": f"Bearer {token}"}) - assert r.status_code == 200 - chunk = r.json() - assert chunk["encrypted"] is True - - # Decrypt and verify - file_hash = base64.b64decode(chunk["file_hash_b64"]) - nonce = base64.b64decode(chunk["nonce_b64"]) - ct = base64.b64decode(chunk["ct_b64"]) - ckey = derive_chunk_key(gek, file_hash, 0) - plaintext = decrypt_chunk(ckey, nonce, ct) - original = (shared_dir / "doc.pdf").read_bytes() - assert plaintext == original[:len(plaintext)] - - -@pytest.mark.asyncio -async def test_chunk_requires_auth(sk_node, hub_pk_pem, shared_dir): - """Chunk endpoint rejects unauthenticated requests.""" - indexer = DirectoryIndexer(root=shared_dir, group_id="g", sk_node=sk_node, gek=None) - await indexer.initial_scan() - app = create_http_app( - sk_node=sk_node, hub_pk_pem=hub_pk_pem, - shared_root=shared_dir, index=indexer.index, - group_id="g", group_name="G", - ) - entry = indexer.index.entries[0] - - async with httpx.AsyncClient( - transport=httpx.ASGITransport(app=app), base_url="http://test" - ) as c: - r = await c.get(f"/file/{entry.id}/0") # no token - assert r.status_code == 401 - - -@pytest.mark.asyncio -async def test_unknown_file_404(sk_node, hub_pk_pem, sk_hub, shared_dir): - indexer = DirectoryIndexer(root=shared_dir, group_id="g", sk_node=sk_node, gek=None) - await indexer.initial_scan() - app = create_http_app( - sk_node=sk_node, hub_pk_pem=hub_pk_pem, - shared_root=shared_dir, index=indexer.index, - group_id="g", group_name="G", - ) - token = make_token(sk_hub, pk_to_b64(sk_node.public_key())) - - async with httpx.AsyncClient( - transport=httpx.ASGITransport(app=app), base_url="http://test" - ) as c: - r = await c.get("/file/nonexistent-hash/0", - headers={"Authorization": f"Bearer {token}"}) - assert r.status_code == 404 diff --git a/packages/meshbay-node/tests/test_transport.py b/packages/meshbay-node/tests/test_transport.py deleted file mode 100644 index 0e70d72..0000000 --- a/packages/meshbay-node/tests/test_transport.py +++ /dev/null @@ -1,222 +0,0 @@ -""" -Integration test: ChunkServer ↔ ChunkClient over TLS. - -Starts a real TLS server on localhost, connects a client, -fetches index and a chunk, verifies signature+hash+decryption. -""" - -import asyncio -import base64 -import os -import time -import jwt -import pytest -from pathlib import Path -from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey -from cryptography.hazmat.primitives import serialization - -from meshbay_common.crypto import generate_gek, pk_to_b64 -from meshbay_node.indexer import DirectoryIndexer, GroupIndex -from meshbay_node.transport.server import ChunkServer -from meshbay_node.transport.client import ChunkClient - - -@pytest.fixture -def sk_node(): - return Ed25519PrivateKey.generate() - -@pytest.fixture -def sk_hub(): - return Ed25519PrivateKey.generate() - -@pytest.fixture -def gek(): - return generate_gek() - -@pytest.fixture -def shared_dir(tmp_path): - d = tmp_path / "shared" - d.mkdir() - (d / "test.mp4").write_bytes(os.urandom(2 * 1024 * 1024)) # 2 MB - (d / "small.txt").write_bytes(b"hello meshbay " * 100) - return d - -def make_jwt(sk_hub, pk_node_b64, user_id="user-001", ttl=3600, groups=None): - sk_pem = sk_hub.private_bytes( - serialization.Encoding.PEM, - serialization.PrivateFormat.PKCS8, - serialization.NoEncryption(), - ) - now = int(time.time()) - return jwt.encode({ - "iss": "test-hub", "sub": user_id, - "pk_user": pk_node_b64, "hub_id": "test-hub", - "jti": "test-jti", - "iat": now, "exp": now + ttl, - "groups": groups or [], - }, sk_pem, algorithm="EdDSA") - - -@pytest.mark.asyncio -async def test_chunk_server_client_roundtrip( - sk_node, sk_hub, gek, shared_dir, tmp_path): - """Full integration: server serves a chunk, client verifies and decrypts.""" - - # Build index - indexer = DirectoryIndexer( - root=shared_dir, group_id="g", sk_node=sk_node, gek=gek) - await indexer.initial_scan() - assert indexer.index.count == 2 - - # Hub PK for JWT verification - hub_pk_pem = sk_hub.public_key().public_bytes( - serialization.Encoding.PEM, - serialization.PublicFormat.SubjectPublicKeyInfo) - - # TLS cert in tmp dir - cert_path = tmp_path / "node.crt" - key_path = tmp_path / "node.key" - - server = ChunkServer( - sk_node=sk_node, - hub_pk_pem=hub_pk_pem, - gek=gek, - shared_root=shared_dir, - index=indexer.index, - host="127.0.0.1", - port=0, # OS picks a free port - cert_path=cert_path, - key_path=key_path, - ) - await server.start() - port = server._server.sockets[0].getsockname()[1] - - token = make_jwt(sk_hub, pk_to_b64(sk_node.public_key())) - - # Find the large test file in the index - entry = next(e for e in indexer.index.entries if e.name == "test.mp4") - - async with ChunkClient( - host="127.0.0.1", - port=port, - jwt_token=token, - gek=gek, - pk_node_b64=pk_to_b64(sk_node.public_key()), - ) as client: - # Fetch first chunk - chunk0 = await client.fetch_chunk(entry.id, chunk_index=0) - assert len(chunk0) == 1024 * 1024 # first 1MB of 2MB file - - # Fetch second chunk - chunk1 = await client.fetch_chunk(entry.id, chunk_index=1) - assert len(chunk1) == 1024 * 1024 # second 1MB - - # Reassembled file matches original - original = (shared_dir / "test.mp4").read_bytes() - assert chunk0 + chunk1 == original - - await server.stop() - - -@pytest.mark.asyncio -async def test_invalid_jwt_rejected(sk_node, sk_hub, gek, shared_dir, tmp_path): - hub_pk_pem = sk_hub.public_key().public_bytes( - serialization.Encoding.PEM, serialization.PublicFormat.SubjectPublicKeyInfo) - - indexer = DirectoryIndexer(root=shared_dir, group_id="g", - sk_node=sk_node, gek=gek) - await indexer.initial_scan() - - cert_path = tmp_path / "node.crt" - key_path = tmp_path / "node.key" - - server = ChunkServer( - sk_node=sk_node, hub_pk_pem=hub_pk_pem, gek=gek, - shared_root=shared_dir, index=indexer.index, - host="127.0.0.1", port=0, - cert_path=cert_path, key_path=key_path, - ) - await server.start() - port = server._server.sockets[0].getsockname()[1] - - # Use a different hub key to sign the token - sk_other_hub = Ed25519PrivateKey.generate() - bad_token = make_jwt(sk_other_hub, pk_to_b64(sk_node.public_key())) - - with pytest.raises(Exception): - async with ChunkClient( - host="127.0.0.1", port=port, - jwt_token=bad_token, gek=gek, - pk_node_b64=pk_to_b64(sk_node.public_key()), - ) as client: - pass - - await server.stop() - - -@pytest.mark.asyncio -async def test_wrong_group_rejected(sk_node, sk_hub, gek, shared_dir, tmp_path): - """TCP+TLS server rejects a client whose JWT groups don't include the requested group_id.""" - hub_pk_pem = sk_hub.public_key().public_bytes( - serialization.Encoding.PEM, serialization.PublicFormat.SubjectPublicKeyInfo) - - indexer = DirectoryIndexer(root=shared_dir, group_id="g", - sk_node=sk_node, gek=gek) - await indexer.initial_scan() - - cert_path = tmp_path / "node.crt" - key_path = tmp_path / "node.key" - - server = ChunkServer( - sk_node=sk_node, hub_pk_pem=hub_pk_pem, gek=gek, - shared_root=shared_dir, index=indexer.index, - host="127.0.0.1", port=0, - cert_path=cert_path, key_path=key_path, - ) - await server.start() - port = server._server.sockets[0].getsockname()[1] - - token = make_jwt(sk_hub, pk_to_b64(sk_node.public_key()), groups=["group-a"]) - - with pytest.raises(ConnectionError, match="rejected"): - async with ChunkClient( - host="127.0.0.1", port=port, - jwt_token=token, gek=gek, - pk_node_b64=pk_to_b64(sk_node.public_key()), - group_id="group-b", - ) as client: - pass - - await server.stop() - - -@pytest.mark.asyncio -async def test_fetch_index(sk_node, sk_hub, gek, shared_dir, tmp_path): - hub_pk_pem = sk_hub.public_key().public_bytes( - serialization.Encoding.PEM, serialization.PublicFormat.SubjectPublicKeyInfo) - indexer = DirectoryIndexer(root=shared_dir, group_id="g", - sk_node=sk_node, gek=gek) - await indexer.initial_scan() - - cert_path = tmp_path / "node.crt" - key_path = tmp_path / "node.key" - - server = ChunkServer( - sk_node=sk_node, hub_pk_pem=hub_pk_pem, gek=gek, - shared_root=shared_dir, index=indexer.index, - host="127.0.0.1", port=0, - cert_path=cert_path, key_path=key_path, - ) - await server.start() - port = server._server.sockets[0].getsockname()[1] - token = make_jwt(sk_hub, pk_to_b64(sk_node.public_key())) - - async with ChunkClient( - host="127.0.0.1", port=port, jwt_token=token, - gek=gek, pk_node_b64=pk_to_b64(sk_node.public_key()), - ) as client: - wire = await client.fetch_index() - recovered = GroupIndex.deserialize(wire, sk_node=sk_node, gek=gek) - assert recovered.count == 2 - - await server.stop() -- cgit v1.2.3 From 3ce051e134a432417fcaca4e8b5775d98f614a31 Mon Sep 17 00:00:00 2001 From: Christophe Besson Date: Thu, 13 Aug 2026 10:42:20 +0200 Subject: fix(node): group isolation, upload confinement, GEK seizure, admin challenge MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Phase 11.5 — findings H1, C5a, H2, C5b, H5 (see second-review.md). Batched together because the node-side changes share webrtc_server.py and cannot be separated into working commits. H1 — cross-group chat leak. chat_store, the peer registry and the display-name cache were read from the shared transport context, and daemon.py hoisted the FIRST group's chat store onto it. On a node hosting several groups every group's messages went to one database, chat_history served them back to members of every other group, and chat broadcast reached all peers regardless of group. All three now resolve through _group_ctx(). C5a — upload confinement. Uploads landed in the shared root under a client-chosen name and overwrote whatever was there. Any member could destroy the operator's files, and by becoming the recorded uploader of the replaced file could then delete it through the uploader path, bypassing the Ed25519 admin challenge. Uploads now go to a per-user quarantine (.uploads/{user_id}/), refuse to overwrite, and enforce chunk ordering, a filename allowlist and a size cap. H2 — stored XSS in the node admin UI. Filenames chosen by any group member were interpolated raw into the localhost UI, which has no authentication, so script execution there equals control of the node admin API. Now html.escape() throughout, textContent in the audit table, plus CSP/nosniff/no-referrer. The CSP contains exfiltration but cannot stop injected inline script — escaping is the fix. C5b — group key seizure. gek_bundle_store wrote whatever any member sent and auto-activated bundles addressed to the node operator. The operator's X25519 public key is public (the node publishes it in handshake_ack), so any member could wrap a key of their choosing for it and take over the group, locking every legitimate member out. Storing now requires an operator signature and _try_activate_gek is removed: nothing arriving over MNP can set a live GEK. H5 — unbound signing oracle. The node challenged with 32 raw random bytes and the client signed them blind, so a signature named no operation, subject, node or time. New meshbay_common/adminop.py defines a length-prefixed, domain-separated transcript; both sides build it independently and the client refuses to sign when the announced op/subject do not match its request. BREAKING: a group admin who does not operate the node can no longer store GEK bundles on it. Invites must be performed by the node operator. Adds tests/test_security_regressions.py. Verified against pre-fix source via git stash. Three pre-existing tests asserted the vulnerable behaviour as a feature and were inverted: gek auto-activation, and the transport-wide chat_store in test_daemon. Tests: 109 node, 132 hub+common. Co-Authored-By: Claude Opus 5 --- .../meshbay-common/src/meshbay_common/adminop.py | 70 ++++ packages/meshbay-hub/src/meshbay_hub/static/app.js | 15 +- .../meshbay-hub/src/meshbay_hub/static/crypto.js | 38 ++- .../src/meshbay_hub/static/keyderive.js | 14 +- .../src/meshbay_hub/static/transport.js | 57 +++- packages/meshbay-node/src/meshbay_node/daemon.py | 6 +- .../src/meshbay_node/transport/webrtc_server.py | 318 ++++++++++++------ packages/meshbay-node/src/meshbay_node/ui/app.py | 79 ++++- packages/meshbay-node/tests/test_daemon.py | 9 +- .../tests/test_security_regressions.py | 372 +++++++++++++++++++++ .../meshbay-node/tests/test_webrtc_transport.py | 96 ++++-- 11 files changed, 919 insertions(+), 155 deletions(-) create mode 100644 packages/meshbay-common/src/meshbay_common/adminop.py create mode 100644 packages/meshbay-node/tests/test_security_regressions.py diff --git a/packages/meshbay-common/src/meshbay_common/adminop.py b/packages/meshbay-common/src/meshbay_common/adminop.py new file mode 100644 index 0000000..71446ca --- /dev/null +++ b/packages/meshbay-common/src/meshbay_common/adminop.py @@ -0,0 +1,70 @@ +""" +Admin operation challenge transcripts (MNP). + +Destructive and privileged node operations are authorized by an Ed25519 signature +from the node operator, not by a JWT — the hub controls JWT issuance, so a JWT can +never establish node-level authority (see draft-v4 §4.2.x). + +Finding H5: the node used to challenge the client with 32 raw random bytes and the +client signed them blind. That is an unbound signing oracle — the signed message +named no operation, no subject, no node and no time, so a signature obtained for one +purpose was structurally valid for any other, and a malicious node could ask a user +to sign bytes meaningful in a different protocol. + +The transcript below fixes that: + + - a fixed domain-separation prefix, so these signatures can never collide with + node_auth, revocation tokens, chunk signatures or anything added later; + - the operation and its subject, so the client can display and verify what it is + authorizing before signing; + - the node's public key, so a signature for node A is not valid on node B; + - the group, so authority does not leak across groups on a multi-group node; + - a node-chosen nonce, so signatures cannot be replayed; + - a timestamp, so stale challenges can be rejected. + +Every field is length-prefixed. Plain concatenation would let a crafted subject +impersonate a following field (finding L4 applies the same rule to the GEK proof). + +Both sides MUST build the transcript with this function — the client from the +fields it received, the node from the state it stored. They are compared by +producing the same bytes, never by trusting a value off the wire. +""" + +ADMIN_TRANSCRIPT_PREFIX = b"meshbay:admin:v1" + +# Operations that require node-operator authority. +OP_FILE_DELETE = "file_delete" +OP_GEK_BUNDLE_STORE = "gek_bundle_store" + +# A challenge older than this is refused, so a signature captured from a stale +# exchange cannot be replayed later. +ADMIN_CHALLENGE_TTL = 120 # seconds + + +def admin_transcript( + op: str, + node_pk_b64: str, + group_id: str, + subject: str, + nonce: bytes, + ts: int, +) -> bytes: + """ + Build the exact byte string signed for an admin operation. + + `subject` identifies what is being acted on: a file_id for OP_FILE_DELETE, the + target user_id for OP_GEK_BUNDLE_STORE. + """ + fields = [ + op.encode(), + node_pk_b64.encode(), + group_id.encode(), + subject.encode(), + nonce, + str(ts).encode(), + ] + out = bytearray(ADMIN_TRANSCRIPT_PREFIX) + for field in fields: + out += len(field).to_bytes(4, "big") + out += field + return bytes(out) diff --git a/packages/meshbay-hub/src/meshbay_hub/static/app.js b/packages/meshbay-hub/src/meshbay_hub/static/app.js index ddff928..dee47ec 100644 --- a/packages/meshbay-hub/src/meshbay_hub/static/app.js +++ b/packages/meshbay-hub/src/meshbay_hub/static/app.js @@ -979,8 +979,10 @@ function GroupPage({ groupId, group, token, username, userId }) { const transport = transportRef.current; if (!transport || !transport.connected) return; try { + // Signs an explicit transcript built by transport.js, not opaque bytes from + // the node — see MeshBayCrypto.adminTranscript and finding H5. const signFn = (_sessionKeys && window.MeshBayKeys) - ? (challenge) => window.MeshBayKeys.signChallenge(_sessionKeys.skEdB64, challenge) + ? (transcript) => window.MeshBayKeys.signBytes(_sessionKeys.skEdB64, transcript) : null; await transport.deleteFile(entry.id, signFn); const indexMsg = await transport.fetchIndex(); @@ -1405,9 +1407,16 @@ function MembersPanel({ groupId, group, token, transportRef, gekRef }) { } const gekBytes = transport.gekRaw; - // Wrap GEK for invitee and store on node via P2P + // Wrap GEK for invitee and store on node via P2P. + // The node requires the operator's Ed25519 signature to accept the bundle + // (C5b), so inviting from a browser that is not the node operator's will be + // refused by the node — deliberately: only the operator decides what is + // stored on their machine. + const signFn = (_sessionKeys && window.MeshBayKeys) + ? (transcript) => window.MeshBayKeys.signBytes(_sessionKeys.skEdB64, transcript) + : null; const bundle = await window.MeshBayCrypto.wrapGEK(gekBytes, pkXBytes); - await transport.storeGekBundle(pubkeys.user_id, groupId, bundle); + await transport.storeGekBundle(pubkeys.user_id, groupId, bundle, signFn); // Add member on hub (membership management only) await hubFetch(`/v1/groups/${groupId}/members/${username}`, { diff --git a/packages/meshbay-hub/src/meshbay_hub/static/crypto.js b/packages/meshbay-hub/src/meshbay_hub/static/crypto.js index 5ebf624..2346fa2 100644 --- a/packages/meshbay-hub/src/meshbay_hub/static/crypto.js +++ b/packages/meshbay-hub/src/meshbay_hub/static/crypto.js @@ -230,6 +230,42 @@ function b64encode(bytes) { return btoa(String.fromCharCode(...bytes)); } +// ── Admin operation transcript ─────────────────────────────────────────────── +// Mirrors meshbay_common/adminop.py::admin_transcript(). Both sides build these +// bytes independently; they are never taken off the wire. +// +// Finding H5: the client used to sign 32 raw random bytes chosen by the node — a +// blind signing oracle. It now reconstructs a domain-separated, length-prefixed +// transcript naming the operation, subject, node and group, so the UI can show the +// user what they are authorizing and a signature cannot be reused elsewhere. + +const ADMIN_TRANSCRIPT_PREFIX = new TextEncoder().encode('meshbay:admin:v1'); + +function adminTranscript(op, nodePkB64, groupId, subject, nonceB64, ts) { + const enc = new TextEncoder(); + const fields = [ + enc.encode(op), + enc.encode(nodePkB64), + enc.encode(groupId), + enc.encode(subject), + b64decode(nonceB64), + enc.encode(String(ts)), + ]; + let total = ADMIN_TRANSCRIPT_PREFIX.length; + for (const f of fields) total += 4 + f.length; + + const out = new Uint8Array(total); + out.set(ADMIN_TRANSCRIPT_PREFIX, 0); + let off = ADMIN_TRANSCRIPT_PREFIX.length; + for (const f of fields) { + new DataView(out.buffer).setUint32(off, f.length, false); + off += 4; + out.set(f, off); + off += f.length; + } + return out; +} + // ── GEK proof (HMAC-SHA256 for handshake challenge) ───────────────────────── async function hmacGEK(gekRaw, nonceB64, offerFp, answerFp) { @@ -249,5 +285,5 @@ async function hmacGEK(gekRaw, nonceB64, offerFp, answerFp) { window.MeshBayCrypto = { importGEK, deriveChunkKey, decryptChunk, decryptChunkBin, decryptFile, generateGEK, wrapGEK, unwrapGEK, encryptChunk, b64encode, b64decode, - hmacGEK, + hmacGEK, adminTranscript, }; diff --git a/packages/meshbay-hub/src/meshbay_hub/static/keyderive.js b/packages/meshbay-hub/src/meshbay_hub/static/keyderive.js index ff3da33..3d9c3c6 100644 --- a/packages/meshbay-hub/src/meshbay_hub/static/keyderive.js +++ b/packages/meshbay-hub/src/meshbay_hub/static/keyderive.js @@ -246,16 +246,22 @@ async function regenerateKeys(token, username, password) { }; } -async function signChallenge(skEdPkcs8B64, challengeB64) { +/** + * Sign an explicit byte string with the user's Ed25519 identity key. + * + * Takes bytes rather than a base64 blob from the wire: callers are expected to + * build the message themselves (see MeshBayCrypto.adminTranscript) so that the + * user's identity key is never applied to content the peer chose. Finding H5. + */ +async function signBytes(skEdPkcs8B64, message) { const skRaw = Uint8Array.from(atob(skEdPkcs8B64), c => c.charCodeAt(0)); const sk = await crypto.subtle.importKey( 'pkcs8', skRaw, { name: 'Ed25519' }, false, ['sign']); - const challenge = Uint8Array.from(atob(challengeB64), c => c.charCodeAt(0)); - const sig = await crypto.subtle.sign('Ed25519', sk, challenge); + const sig = await crypto.subtle.sign('Ed25519', sk, message); return btoa(String.fromCharCode(...new Uint8Array(sig))); } window.MeshBayKeys = { - registerUser, loginAndRecover, regenerateKeys, generateKeypairs, signChallenge, + registerUser, loginAndRecover, regenerateKeys, generateKeypairs, signBytes, deriveAuthKey, decryptBundleWithKey, }; diff --git a/packages/meshbay-hub/src/meshbay_hub/static/transport.js b/packages/meshbay-hub/src/meshbay_hub/static/transport.js index ca9c60e..d636085 100644 --- a/packages/meshbay-hub/src/meshbay_hub/static/transport.js +++ b/packages/meshbay-hub/src/meshbay_hub/static/transport.js @@ -266,6 +266,39 @@ class MeshBayTransport { return msg; } + /** + * Authorize a privileged node operation with the user's Ed25519 identity key. + * + * The client rebuilds the signed transcript from the challenge fields and refuses + * to sign unless the operation and subject match what the user actually asked for. + * Previously the node sent 32 opaque random bytes and the client signed them + * blind, which let any peer obtain a signature over content of its choosing + * (finding H5). + */ + async _authorizeAdminOp(challenge, expectedOp, expectedSubject, signFn) { + if (challenge.op !== expectedOp || challenge.subject !== expectedSubject) { + throw new Error( + `Refusing to sign: node asked to authorize "${challenge.op}" on ` + + `"${challenge.subject}", but the requested action was "${expectedOp}" ` + + `on "${expectedSubject}"`); + } + if (!signFn) throw new Error('Admin challenge received but no signing key available'); + + const transcript = window.MeshBayCrypto.adminTranscript( + challenge.op, challenge.node_pk, challenge.group_id, + challenge.subject, challenge.nonce, challenge.ts); + + const signature = await signFn(transcript); + const ack = await this._sendAndWait({ + type: 'admin_response', + v: '0.1', + op_id: challenge.op_id, + signature, + }); + if (ack.type === 'error') throw new Error(ack.detail); + return ack; + } + async deleteFile(fileId, signFn) { const msg = await this._sendAndWait({ type: 'file_delete', @@ -274,16 +307,7 @@ class MeshBayTransport { }); if (msg.type === 'error') throw new Error(msg.detail); if (msg.type === 'admin_challenge') { - if (!signFn) throw new Error('Admin challenge received but no signing key available'); - const signature = await signFn(msg.challenge); - const ack = await this._sendAndWait({ - type: 'admin_response', - v: '0.1', - file_id: fileId, - signature, - }); - if (ack.type === 'error') throw new Error(ack.detail); - return ack; + return this._authorizeAdminOp(msg, 'file_delete', fileId, signFn); } return msg; } @@ -304,7 +328,15 @@ class MeshBayTransport { return msg; } - async storeGekBundle(userId, groupId, bundle) { + /** + * Store a wrapped GEK bundle on the node for a member. + * + * Node-operator operation: the node answers with an admin challenge and only the + * pinned operator key is accepted. Any member used to be able to write bundles — + * including one addressed to the operator, which the node then auto-adopted as the + * live group key (finding C5b). + */ + async storeGekBundle(userId, groupId, bundle, signFn) { const msg = await this._sendAndWait({ type: 'gek_bundle_store', v: '0.1', @@ -315,6 +347,9 @@ class MeshBayTransport { wrapped_b64: bundle.wrapped_b64, }); if (msg.type === 'error') throw new Error(msg.detail); + if (msg.type === 'admin_challenge') { + return this._authorizeAdminOp(msg, 'gek_bundle_store', userId, signFn); + } return msg; } diff --git a/packages/meshbay-node/src/meshbay_node/daemon.py b/packages/meshbay-node/src/meshbay_node/daemon.py index c930e54..c75c721 100644 --- a/packages/meshbay-node/src/meshbay_node/daemon.py +++ b/packages/meshbay-node/src/meshbay_node/daemon.py @@ -241,7 +241,11 @@ class NodeDaemon: groups=groups_ctx, denylist=denylist, ) - self._webrtc._ctx["chat_store"] = first.get("chat_store") + # No global chat_store here: each group's store lives in + # groups_ctx[gid]["chat_store"] and is resolved per session via + # _group_ctx(). Assigning the first group's store transport-wide + # sent every group's chat to one database and served it back to + # members of every other group (finding H1). self._webrtc._ctx["hub_ws"] = _WsSender(hub) self._webrtc._ctx["node_user_id"] = session.user_id self._webrtc._ctx["audit_store"] = self._audit_store diff --git a/packages/meshbay-node/src/meshbay_node/transport/webrtc_server.py b/packages/meshbay-node/src/meshbay_node/transport/webrtc_server.py index 13e90c8..9fb9ef2 100644 --- a/packages/meshbay-node/src/meshbay_node/transport/webrtc_server.py +++ b/packages/meshbay-node/src/meshbay_node/transport/webrtc_server.py @@ -28,7 +28,9 @@ import hashlib import hmac import logging import os +import re import struct +import time from pathlib import Path from typing import Any @@ -41,6 +43,12 @@ from cryptography.hazmat.primitives.asymmetric.ed25519 import ( ) from meshbay_common import MNP_VERSION +from meshbay_common.adminop import ( + ADMIN_CHALLENGE_TTL, + OP_FILE_DELETE, + OP_GEK_BUNDLE_STORE, + admin_transcript, +) from meshbay_common.crypto import pk_to_b64 from meshbay_common.webcrypto import chunk_key_aes, encrypt_chunk_aes from meshbay_common.protocol import MNP @@ -51,6 +59,16 @@ log = logging.getLogger(__name__) CHUNK_SIZE = 1024 * 1024 MAX_MSG = 64 * 1024 * 1024 +# Upload limits (finding C5a). Uploads used to land directly in the shared root under +# a name the client chose, overwriting whatever was already there — which both violated +# node sovereignty and defeated the delete authorization (overwrite a file, become its +# recorded uploader, then delete it legitimately). +MAX_UPLOAD_BYTES = 4 * 1024 * 1024 * 1024 # 4 GB per file +UPLOAD_DIR_NAME = ".uploads" +# Conservative allowlist: also what keeps markup out of filenames, which the node admin +# UI used to render unescaped (finding H2). +SAFE_UPLOAD_NAME = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._ -]{0,127}$") + def _extract_dtls_fingerprint(sdp: str) -> bytes: """Extract the DTLS SHA-256 fingerprint from SDP as raw 32 bytes.""" @@ -170,7 +188,8 @@ class WebRTCPeerSession: self._username: str = "" self._pk_user: str = "" self._gek_challenge: bytes | None = None - self._admin_challenges: dict[str, bytes] = {} + self._admin_ops: dict[str, dict] = {} # op_id → pending admin operation + self._uploads: dict[str, dict] = {} # filename → {next_index, bytes} def _setup_channel(self, channel: RTCDataChannel) -> None: self._channel = channel @@ -214,7 +233,7 @@ class WebRTCPeerSession: elif mtype == MNP.ADMIN_RESPONSE: self._do_admin_response(msg) elif mtype == MNP.GEK_BUNDLE_STORE: - asyncio.ensure_future(self._do_gek_bundle_store(msg)) + self._do_gek_bundle_store(msg) elif mtype == MNP.KEYPAIR_BUNDLE_STORE: asyncio.ensure_future(self._do_keypair_bundle_store(msg)) elif mtype == MNP.STREAM_REQUEST: @@ -340,9 +359,7 @@ class WebRTCPeerSession: self._username = self._pending_username self._pk_user = self._pending_pk_user - peers = self._ctx.get("_peers") - if peers is not None: - peers[self._user_id] = self + self._peer_registry()[self._user_id] = self node_user_id = self._ctx.get("node_user_id") log.info("WebRTC handshake OK — user=%s group=%s", @@ -388,8 +405,21 @@ class WebRTCPeerSession: else: self._send({"type": MNP.GEK_BUNDLE_RESP, "v": MNP_VERSION, "found": False}) - async def _do_gek_bundle_store(self, msg: dict) -> None: - """Store a wrapped GEK bundle for a target user (admin operation).""" + def _do_gek_bundle_store(self, msg: dict) -> None: + """ + Request to store a wrapped GEK bundle for a target user. + + Finding C5b: this used to write whatever any authenticated member sent, with + INSERT OR REPLACE semantics, and then auto-activate the bundle if it was + addressed to the node operator. Since the operator's X25519 public key is + public — the node even hands it out in handshake_ack — any member could wrap + a GEK of their own choosing for the operator and make the node adopt it, + locking every legitimate member out of the group and taking over the key. + + Storing a bundle is now a node-operator operation gated by an Ed25519 + challenge, and nothing arriving over MNP can activate a GEK: activation + happens only through the local admin UI or the CLI. + """ bundle_store = self._ctx.get("bundle_store") if not bundle_store: self._send({"type": "error", "detail": "Bundle store not available"}) @@ -405,49 +435,21 @@ class WebRTCPeerSession: self._send({"type": "error", "detail": "Missing bundle fields"}) return - await bundle_store.store(group_id, target_user_id, pk_eph, nonce, wrapped) - log.info("GEK bundle stored: group=%s user=%s", group_id[:8], target_user_id[:8]) - self._audit("gek_bundle_store", f"target={target_user_id[:8]}") + if not self._ctx.get("admin_pk_ed25519"): + self._send({ + "type": "error", + "detail": "No admin key pinned — bundle storage refused", + }) + return - self._send({ - "type": "ack", "v": MNP_VERSION, - "detail": "gek_bundle_stored", + self._issue_admin_challenge(OP_GEK_BUNDLE_STORE, target_user_id, { + "group_id": group_id, "user_id": target_user_id, + "pk_eph_b64": pk_eph, + "nonce_b64": nonce, + "wrapped_b64": wrapped, }) - # Auto-activate GEK if the bundle is for the node operator - node_user_id = self._ctx.get("node_user_id") - if node_user_id and target_user_id == node_user_id and group_id: - await self._try_activate_gek(group_id, target_user_id) - - async def _try_activate_gek(self, group_id: str, user_id: str) -> None: - """Unwrap and activate GEK for the node when the operator's bundle arrives.""" - from meshbay_common.crypto import unwrap_gek_aes - - bundle_store = self._ctx.get("bundle_store") - sk_x_raw = self._ctx.get("sk_x25519_raw") - pk_x_raw = self._ctx.get("pk_x25519_raw") - if not bundle_store or not sk_x_raw or not pk_x_raw: - return - - bundle = await bundle_store.fetch(group_id, user_id) - if not bundle: - return - - try: - gek = unwrap_gek_aes(bundle, sk_x_raw, pk_x_raw) - except Exception as e: - log.warning("Failed to unwrap GEK for auto-activation: %s", e) - return - - groups = self._ctx.get("groups") - if groups and group_id in groups: - groups[group_id]["gek"] = gek - log.info("GEK auto-activated for group %s", group_id[:8]) - elif "gek" in self._ctx: - self._ctx["gek"] = gek - log.info("GEK auto-activated (single-group mode)") - async def _do_keypair_bundle_fetch(self) -> None: """Serve the caller's encrypted keypair bundle during the handshake window.""" bundle_store = self._ctx.get("bundle_store") @@ -508,6 +510,20 @@ class WebRTCPeerSession: return self._ctx["groups"][self._group_id] return self._ctx + def _peer_registry(self) -> dict: + """ + Connected peers for THIS group only. + + Finding H1: this used to live on the shared transport context, so a chat + message was broadcast to every peer on the node regardless of which group + they had authenticated to. + """ + return self._group_ctx().setdefault("_peers", {}) + + def _user_names(self) -> dict: + """Display-name cache, per group — same leak as _peer_registry (H1).""" + return self._group_ctx().setdefault("_user_names", {}) + def _do_index_sync(self) -> None: ctx = self._group_ctx() idx = ctx["index"] @@ -599,11 +615,14 @@ class WebRTCPeerSession: }) def _do_chat_message(self, msg: dict) -> None: - chat_store = self._ctx.get("chat_store") + # Per-group store — see _peer_registry() and finding H1. Reading chat_store + # off the shared transport context sent every group's messages to the first + # group's database, and served them back to anyone on the node. + chat_store = self._group_ctx().get("chat_store") payload = msg.get("payload", "") sender_name = msg.get("sender_name", "") if sender_name: - self._ctx.setdefault("_user_names", {})[self._user_id] = sender_name + self._user_names()[self._user_id] = sender_name if chat_store: raw = payload.encode() if isinstance(payload, str) else payload asyncio.ensure_future(chat_store.save_message( @@ -614,7 +633,7 @@ class WebRTCPeerSession: sender_name=sender_name, )) - peers = self._ctx.get("_peers", {}) + peers = self._peer_registry() broadcast = { "type": MNP.CHAT_MESSAGE, "v": MNP_VERSION, @@ -647,7 +666,7 @@ class WebRTCPeerSession: self._audit("chat_message") def _do_chat_history(self, msg: dict) -> None: - chat_store = self._ctx.get("chat_store") + chat_store = self._group_ctx().get("chat_store") if not chat_store: self._send({ "type": MNP.CHAT_HISTORY_RESPONSE, @@ -662,7 +681,7 @@ class WebRTCPeerSession: async def _send_chat_history(self, chat_store, since: float, limit: int) -> None: msgs = await chat_store.get_messages(since=since, limit=limit) - names = self._ctx.get("_user_names", {}) + names = self._user_names() self._send({ "type": MNP.CHAT_HISTORY_RESPONSE, "v": MNP_VERSION, @@ -691,24 +710,55 @@ class WebRTCPeerSession: self._send({"type": "error", "detail": "Missing filename or data"}) return + if not SAFE_UPLOAD_NAME.match(filename): + self._send({"type": "error", "detail": "Invalid filename"}) + return + shared_root = ctx.get("shared_root") if not shared_root: self._send({"type": "error", "detail": "No shared directory"}) return - upload_dir = shared_root / ".uploads" - upload_dir.mkdir(exist_ok=True) - safe_name = filename.replace("/", "_").replace("\\", "_").replace("..", "_") - tmp_path = upload_dir / f"{safe_name}.part" + # Per-user quarantine: a member can only ever write inside their own directory, + # so they cannot overwrite the operator's files or another member's (C5a). + rel_dir = f"{UPLOAD_DIR_NAME}/{self._user_id}" + user_dir = shared_root / UPLOAD_DIR_NAME / self._user_id + user_dir.mkdir(parents=True, exist_ok=True) + tmp_path = user_dir / f"{filename}.part" + final_path = user_dir / filename + + state = self._uploads.get(filename) + if chunk_index == 0: + if final_path.exists(): + self._send({"type": "error", "detail": "File already exists"}) + return + state = {"next_index": 0, "bytes": 0} + self._uploads[filename] = state + elif state is None: + self._send({"type": "error", "detail": "Upload not started"}) + return + + # Reject out-of-order or replayed chunks — otherwise chunk_index>0 appends + # blindly to whatever .part file is already on disk. + if chunk_index != state["next_index"]: + self._send({"type": "error", "detail": "Unexpected chunk index"}) + return if isinstance(data, str): chunk_bytes = base64.b64decode(data) else: chunk_bytes = bytes(data) - mode = "ab" if chunk_index > 0 else "wb" - with open(tmp_path, mode) as f: + if state["bytes"] + len(chunk_bytes) > MAX_UPLOAD_BYTES: + self._uploads.pop(filename, None) + tmp_path.unlink(missing_ok=True) + self._send({"type": "error", "detail": "Upload exceeds size limit"}) + return + + with open(tmp_path, "wb" if chunk_index == 0 else "ab") as f: f.write(chunk_bytes) + state["next_index"] = chunk_index + 1 + state["bytes"] += len(chunk_bytes) self._send({ "type": MNP.FILE_UPLOAD_ACK, @@ -718,19 +768,20 @@ class WebRTCPeerSession: }) if chunk_index + 1 >= total_chunks: - final_path = shared_root / safe_name + self._uploads.pop(filename, None) tmp_path.rename(final_path) - log.info("Upload complete: %s (%d chunks)", safe_name, total_chunks) - self._audit("file_upload", safe_name) - self._register_uploader(ctx, safe_name) + log.info("Upload complete: %s (%d chunks, %d bytes)", + filename, total_chunks, state["bytes"]) + self._audit("file_upload", f"{rel_dir}/{filename}") + self._register_uploader(ctx, rel_dir, filename) - def _register_uploader(self, ctx: dict, filename: str) -> None: - """Tag the index entry with the uploader's user_id after upload completes.""" + def _register_uploader(self, ctx: dict, rel_dir: str, filename: str) -> None: + """Tag the index entry with the uploader's identity after upload completes.""" idx = ctx.get("index") if not idx: return for entry in idx.entries: - if entry.name == filename and entry.path == "": + if entry.name == filename and entry.path == rel_dir: entry.uploader_id = self._user_id entry.uploader_pk = self._pk_user return @@ -753,22 +804,64 @@ class WebRTCPeerSession: self._send({"type": "error", "detail": "No authorized key for deletion"}) return - challenge = os.urandom(32) - self._admin_challenges[file_id] = challenge + self._issue_admin_challenge(OP_FILE_DELETE, file_id) + + # ── Admin operation challenge/response (finding H5) ────────────────────── + + def _node_pk_b64(self) -> str: + return pk_to_b64(self._ctx["sk_node"].public_key()) + + def _issue_admin_challenge( + self, op: str, subject: str, payload: dict | None = None, + ) -> None: + """ + Ask the client to authorize `op` on `subject` with its Ed25519 identity key. + + The client is sent the transcript *fields*, not opaque bytes, so it can + rebuild and inspect what it signs. The node keeps the authoritative copy and + rebuilds the transcript itself at verification time — nothing signed is ever + taken from the response message. + """ + nonce = os.urandom(32) + ts = int(time.time()) + op_id = base64.b64encode(os.urandom(16)).decode() + self._admin_ops[op_id] = { + "op": op, "subject": subject, "nonce": nonce, "ts": ts, + "payload": payload or {}, + } self._send({ "type": MNP.ADMIN_CHALLENGE, "v": MNP_VERSION, - "challenge": base64.b64encode(challenge).decode(), - "file_id": file_id, + "op_id": op_id, + "op": op, + "subject": subject, + "nonce": base64.b64encode(nonce).decode(), + "ts": ts, + "node_pk": self._node_pk_b64(), + "group_id": self._group_id or "", }) + @staticmethod + def _verify_sig(pk: Ed25519PublicKey | None, transcript: bytes, sig: bytes) -> bool: + if pk is None: + return False + try: + pk.verify(sig, transcript) + return True + except Exception: + return False + def _do_admin_response(self, msg: dict) -> None: - file_id = msg.get("file_id", "") + op_id = msg.get("op_id", "") sig_b64 = msg.get("signature", "") - challenge = self._admin_challenges.pop(file_id, None) - if not challenge: - self._send({"type": "error", "detail": "No pending admin challenge"}) + pending = self._admin_ops.pop(op_id, None) + if not pending: + self._send({"type": "error", "detail": "No pending admin operation"}) + return + + if time.time() - pending["ts"] > ADMIN_CHALLENGE_TTL: + self._send({"type": "error", "detail": "Admin challenge expired"}) return try: @@ -777,40 +870,80 @@ class WebRTCPeerSession: self._send({"type": "error", "detail": "Invalid signature encoding"}) return + transcript = admin_transcript( + op=pending["op"], + node_pk_b64=self._node_pk_b64(), + group_id=self._group_id or "", + subject=pending["subject"], + nonce=pending["nonce"], + ts=pending["ts"], + ) + + if pending["op"] == OP_FILE_DELETE: + self._admin_exec_file_delete(pending, transcript, sig_bytes) + elif pending["op"] == OP_GEK_BUNDLE_STORE: + asyncio.ensure_future( + self._admin_exec_bundle_store(pending, transcript, sig_bytes)) + else: + self._send({"type": "error", "detail": "Unknown admin operation"}) + + def _admin_exec_file_delete( + self, pending: dict, transcript: bytes, sig: bytes, + ) -> None: + file_id = pending["subject"] ctx = self._group_ctx() entry = ctx["index"].get_entry(file_id) if not entry: self._send({"type": "error", "detail": "File not found"}) return - verified = False - - # Try admin key (locally pinned) - admin_pk = self._ctx.get("admin_pk_ed25519") - if admin_pk: - try: - admin_pk.verify(sig_bytes, challenge) - verified = True - except Exception: - pass - - # Try uploader key (stored at upload time) - if not verified and entry.uploader_pk: + uploader_pk = None + if entry.uploader_pk: try: - uploader_key = Ed25519PublicKey.from_public_bytes( + uploader_pk = Ed25519PublicKey.from_public_bytes( base64.b64decode(entry.uploader_pk)) - uploader_key.verify(sig_bytes, challenge) - verified = True except Exception: - pass + uploader_pk = None - if not verified: + # Node operator, or the user who uploaded this file — verified by the key + # recorded at upload time, never by a JWT claim (the hub controls those). + if not (self._verify_sig(self._ctx.get("admin_pk_ed25519"), transcript, sig) + or self._verify_sig(uploader_pk, transcript, sig)): self._send({"type": "error", "detail": "Signature verification failed"}) self._audit("admin_auth_failed", f"file_delete:{file_id[:16]}") return self._exec_file_delete(ctx, file_id, entry) + async def _admin_exec_bundle_store( + self, pending: dict, transcript: bytes, sig: bytes, + ) -> None: + # Node operator only. A group admin who does not run the node has no + # authority over what this node stores (draft-v4 §4.2.x, deny by default). + if not self._verify_sig(self._ctx.get("admin_pk_ed25519"), transcript, sig): + self._send({"type": "error", "detail": "Signature verification failed"}) + self._audit("admin_auth_failed", f"gek_bundle_store:{pending['subject'][:16]}") + return + + payload = pending["payload"] + bundle_store = self._ctx.get("bundle_store") + if not bundle_store: + self._send({"type": "error", "detail": "Bundle store not available"}) + return + + await bundle_store.store( + payload["group_id"], payload["user_id"], + payload["pk_eph_b64"], payload["nonce_b64"], payload["wrapped_b64"], + ) + log.info("GEK bundle stored: group=%s user=%s", + payload["group_id"][:8], payload["user_id"][:8]) + self._audit("gek_bundle_store", f"target={payload['user_id'][:8]}") + self._send({ + "type": "ack", "v": MNP_VERSION, + "detail": "gek_bundle_stored", + "user_id": payload["user_id"], + }) + def _exec_file_delete(self, ctx: dict, file_id: str, entry) -> None: file_path = ctx["shared_root"] / entry.path / entry.name if file_path.exists(): @@ -914,9 +1047,8 @@ class WebRTCPeerSession: async def close(self) -> None: self._audit("disconnect") - peers = self._ctx.get("_peers") - if peers and self._user_id: - peers.pop(self._user_id, None) + if self._user_id: + self._peer_registry().pop(self._user_id, None) await self._pc.close() diff --git a/packages/meshbay-node/src/meshbay_node/ui/app.py b/packages/meshbay-node/src/meshbay_node/ui/app.py index 31deb66..d2c3429 100644 --- a/packages/meshbay-node/src/meshbay_node/ui/app.py +++ b/packages/meshbay-node/src/meshbay_node/ui/app.py @@ -16,6 +16,7 @@ import base64 import json import logging import time +from html import escape from pathlib import Path from fastapi import FastAPI, WebSocket, WebSocketDisconnect, Query @@ -35,6 +36,33 @@ def create_ui_app(state: dict) -> FastAPI: redoc_url=None, ) + @app.middleware("http") + async def _security_headers(request, call_next): + """ + Defence in depth behind the escaping fixes for H2. This UI is unauthenticated + on loopback, so script execution here equals full control of the node admin API. + + Note what this does and does not do: the page relies on inline diff --git a/packages/meshbay-hub/src/meshbay_hub/static/app.js b/packages/meshbay-hub/src/meshbay_hub/static/app.js index 94bf09e..300059d 100644 --- a/packages/meshbay-hub/src/meshbay_hub/static/app.js +++ b/packages/meshbay-hub/src/meshbay_hub/static/app.js @@ -144,24 +144,24 @@ function passwordBits(pw) { const PASSWORD_MIN_BITS = 60; // refuse below this const PASSWORD_MIN_LEN = 12; -// Whether this account backs its encrypted keys up to the nodes it joins. -// -// On: any browser recovers the same identity with the password — the ordinary -// multi-device expectation. Off: the keys exist only where they were generated, -// nothing is left on anyone's disk, and losing this browser's storage loses the -// account's content for good. That is a real choice, so it is the user's. -const KEY_BACKUP_PREFIX = 'mb_key_backup_'; - -function keyBackupEnabled(username) { - try { - return localStorage.getItem(KEY_BACKUP_PREFIX + username) !== '0'; - } catch { return true; } -} - -function setKeyBackupEnabled(username, on) { +/** + * Re-encrypt a bundle written under the old KDF before it is stored again. + * + * PBKDF2 bundles are still readable, but leaving one on a node keeps the weak + * protection alive for as long as it sits there. Any backup is an opportunity to + * replace it with the Argon2id form, and it costs nothing the user notices. + */ +async function _upgradedBundle(bundleEnc) { try { - localStorage.setItem(KEY_BACKUP_PREFIX + username, on ? '1' : '0'); - } catch {} + if (!window.MeshBayKeys || !_sessionKeys || !_bundleKey) return bundleEnc; + if (window.MeshBayKeys.bundleVersion(bundleEnc) === 2) return bundleEnc; + const b64 = (s) => Uint8Array.from(atob(s), c => c.charCodeAt(0)); + return await window.MeshBayKeys.encryptBundleWithKey( + b64(_sessionKeys.skEdB64), b64(_sessionKeys.skXB64), _bundleKey.v2); + } catch (e) { + console.warn('[MeshBay] bundle upgrade skipped:', e.message); + return bundleEnc; + } } function _restoreSessionKeys() { @@ -979,26 +979,18 @@ function GroupPage({ groupId, group, token, username, userId, onRefreshAuth }) { } } - // Back the encrypted keys up to the node, or withdraw them — whichever - // this account asked for. The local copy is only dropped once the node - // holds one, so turning backup off never strands anybody. - if (transport.connected) { - if (keyBackupEnabled(username)) { - if (_pendingBundlePush) { - try { - await transport.storeKeypairBundle(_pendingBundlePush); - try { localStorage.removeItem(`meshbay_kp_${username}`); } catch {} - _pendingBundlePush = null; - } catch (e) { - console.warn('[MeshBay] Bundle push to node deferred:', e.message); - } - } - } else { - try { - await transport.deleteKeypairBundle(); - } catch (e) { - console.warn('[MeshBay] Could not withdraw key backup:', e.message); - } + // Back the encrypted keys up to the node. This is what lets any other + // browser recover them with the passphrase, which is the ordinary + // expectation; the protection that matters is the KDF guarding the + // bundle, not withholding the bundle. + if (transport.connected && _pendingBundlePush) { + try { + await transport.storeKeypairBundle( + await _upgradedBundle(_pendingBundlePush)); + try { localStorage.removeItem(`meshbay_kp_${username}`); } catch {} + _pendingBundlePush = null; + } catch (e) { + console.warn('[MeshBay] Bundle push to node deferred:', e.message); } } @@ -2206,15 +2198,6 @@ function SettingsPage({ user, theme, onThemeChange, groups }) { const [nodeKeyLoading, setNodeKeyLoading] = useState(false); const [pinCount, setPinCount] = useState( () => (window.MeshBayTransport?.pinnedNodeCount?.() ?? 0)); - const [backup, setBackup] = useState(() => keyBackupEnabled(user.username)); - - // Takes effect on the next connection to each node: enabling uploads the - // encrypted bundle, disabling withdraws whatever that node already holds. - const toggleBackup = useCallback(() => { - const next = !backup; - setKeyBackupEnabled(user.username, next); - setBackup(next); - }, [backup, user.username]); // 11.5.8: node identity pins are refused strictly on change, so users need a // deliberate way to accept a legitimate rotation (operator reinstalled a node). @@ -2312,22 +2295,6 @@ function SettingsPage({ user, theme, onThemeChange, groups }) { `} -
-

${t('settings.key_backup')}

-

${t('settings.key_backup_hint')}

-
- - ${backup ? t('settings.key_backup_on') : t('settings.key_backup_off')} - - -
- ${!backup && html` -

${t('settings.key_backup_warning')}

- `} -
-

${t('settings.node_pins')}

${t('settings.node_pins_hint')}

diff --git a/packages/meshbay-hub/src/meshbay_hub/static/i18n.js b/packages/meshbay-hub/src/meshbay_hub/static/i18n.js index 702da0b..f0c5cef 100644 --- a/packages/meshbay-hub/src/meshbay_hub/static/i18n.js +++ b/packages/meshbay-hub/src/meshbay_hub/static/i18n.js @@ -124,19 +124,6 @@ const en = { 'settings.coming_soon': 'Coming soon.', 'settings.profile': 'Profile', 'settings.username': 'Username', - 'settings.key_backup': 'Use this account on other devices', - 'settings.key_backup_hint': 'Your keys can be kept — encrypted with your ' - + 'passphrase — on the nodes whose groups you join, so another browser can ' - + 'recover them. Turn this off and your keys stay only where they were ' - + 'created: nothing of yours sits on anyone else\'s disk, and only that ' - + 'browser can open your groups.', - 'settings.key_backup_on': 'Enabled — other browsers can recover your keys', - 'settings.key_backup_off': 'Disabled — keys stay in this browser only', - 'settings.key_backup_enable': 'Enable', - 'settings.key_backup_disable': 'Disable', - 'settings.key_backup_warning': 'With this off, clearing this browser\'s data ' - + 'loses access to everything encrypted for you. There is no recovery — that ' - + 'is the point. Copies already on nodes are withdrawn at the next connection.', 'settings.node_pins': 'Node identities', 'settings.node_pins_hint': "Each node's identity key is remembered the first time you connect. If it changes, the connection is refused — that is expected only when an operator reinstalls a node. Verify with them before clearing.", 'settings.node_pins_count': '{n} pinned', diff --git a/packages/meshbay-hub/src/meshbay_hub/static/keyderive.js b/packages/meshbay-hub/src/meshbay_hub/static/keyderive.js index 3d9c3c6..afa5d27 100644 --- a/packages/meshbay-hub/src/meshbay_hub/static/keyderive.js +++ b/packages/meshbay-hub/src/meshbay_hub/static/keyderive.js @@ -67,11 +67,34 @@ async function generateKeypairs() { // ── Password → AES key ──────────────────────────────────────────────────────── -/** - * Derive an AES-256 key from password + username using PBKDF2-SHA512. - * Used for encrypting the keypair bundle. - */ -async function deriveEncryptionKey(password, username) { +// Argon2id parameters for the keypair bundle. +// +// This is the one KDF in the browser that guards something an adversary can take +// away and attack at leisure: the bundle is stored on every node whose group its +// owner joins (finding C4). PBKDF2 was the wrong tool — it is compute-only, which +// is exactly what a GPU is good at, so 600k iterations bought far less than the +// wall-clock time suggested. +// +// 64 MB / t=3 / p=1 measured at ~320 ms through this WASM build on a desktop, so +// roughly a second on a modest phone — the most that belongs in a login. Memory +// is what matters here: at 64 MB per guess, a 24 GB card holds a few hundred in +// parallel instead of the effectively unbounded number PBKDF2 allows. +const ARGON2_MEM_KIB = 65536; // 64 MB +const ARGON2_TIME = 3; +const ARGON2_LANES = 1; + +// Bundles written before this carry no marker and are read with the old KDF. +// They are re-encrypted the first time their owner signs in (see upgradeBundle). +const BUNDLE_V2_MAGIC = 'MBK2'; + +function _argon2() { + const a = (typeof window !== 'undefined' && window.argon2) || globalThis.argon2; + if (!a) throw new Error('Argon2 unavailable — vendor/argon2.min.js did not load'); + return a; +} + +/** Legacy: PBKDF2-SHA512. Kept to read bundles written before the change. */ +async function deriveEncryptionKeyV1(password, username) { const enc = new TextEncoder(); const km = await crypto.subtle.importKey( 'raw', enc.encode(password), 'PBKDF2', false, ['deriveKey']); @@ -86,6 +109,27 @@ async function deriveEncryptionKey(password, username) { ); } +/** + * Derive the bundle key with Argon2id. + * + * The salt stays deterministic and domain-separated per user, as before: it is + * what lets the key be derived once at sign-in and kept, instead of holding the + * passphrase in memory to re-derive it whenever a bundle turns up. It is unique + * per account, so it does what a salt is for — no shared precomputation. + */ +async function deriveEncryptionKey(password, username) { + const enc = new TextEncoder(); + const salt = new Uint8Array(await crypto.subtle.digest( + 'SHA-256', enc.encode(`meshbay:bundle:v2:${username}`))).slice(0, 16); + const out = await _argon2().hash({ + pass: password, salt, + time: ARGON2_TIME, mem: ARGON2_MEM_KIB, parallelism: ARGON2_LANES, + hashLen: 32, type: _argon2().ArgonType.Argon2id, + }); + return crypto.subtle.importKey( + 'raw', out.hash, { name: 'AES-GCM' }, false, ['encrypt', 'decrypt']); +} + // ── Bundle encryption ───────────────────────────────────────────────────────── /** @@ -94,29 +138,42 @@ async function deriveEncryptionKey(password, username) { */ async function encryptBundle(skEdRaw, skXRaw, password, username) { const aesKey = await deriveEncryptionKey(password, username); + return encryptBundleWithKey(skEdRaw, skXRaw, aesKey); +} + +/** Same, when the key was already derived at sign-in. Always writes v2. */ +async function encryptBundleWithKey(skEdRaw, skXRaw, aesKey) { const nonce = crypto.getRandomValues(new Uint8Array(12)); const data = new TextEncoder().encode(JSON.stringify({ skEd: btoa(String.fromCharCode(...new Uint8Array(skEdRaw))), skX: btoa(String.fromCharCode(...new Uint8Array(skXRaw))), })); const ct = await crypto.subtle.encrypt({ name: 'AES-GCM', iv: nonce }, aesKey, data); - // Return base64(nonce || ciphertext) - const out = new Uint8Array(nonce.length + ct.byteLength); - out.set(nonce); - out.set(new Uint8Array(ct), nonce.length); + // base64( "MBK2" || nonce || ciphertext ). The marker is what tells a reader + // which KDF produced the key, so old bundles stay readable and new ones are + // never fed to the old derivation. + const magic = new TextEncoder().encode(BUNDLE_V2_MAGIC); + const out = new Uint8Array(magic.length + nonce.length + ct.byteLength); + out.set(magic); + out.set(nonce, magic.length); + out.set(new Uint8Array(ct), magic.length + nonce.length); return btoa(String.fromCharCode(...out)); } +function bundleVersion(bundleB64) { + try { + return atob(bundleB64).startsWith(BUNDLE_V2_MAGIC) ? 2 : 1; + } catch { return 1; } +} + /** * Decrypt a keypair bundle. Throws if password is wrong. */ async function decryptBundle(bundleB64, password, username) { - const aesKey = await deriveEncryptionKey(password, username); - const raw = Uint8Array.from(atob(bundleB64), c => c.charCodeAt(0)); - const nonce = raw.slice(0, 12); - const ct = raw.slice(12); - const plain = await crypto.subtle.decrypt({ name: 'AES-GCM', iv: nonce }, aesKey, ct); - return JSON.parse(new TextDecoder().decode(plain)); + const key = bundleVersion(bundleB64) === 2 + ? await deriveEncryptionKey(password, username) + : await deriveEncryptionKeyV1(password, username); + return decryptBundleWithKey(bundleB64, key); } // ── Registration ────────────────────────────────────────────────────────────── @@ -165,11 +222,19 @@ async function registerUser(username, email, password) { * Decrypt a keypair bundle using a pre-derived AES-256 CryptoKey. * Used when the bundle is fetched from the node (bundleKey was derived at login). */ -async function decryptBundleWithKey(bundleB64, aesKey) { +async function decryptBundleWithKey(bundleB64, aesKeyOrPair) { + const v2 = bundleVersion(bundleB64) === 2; + // Callers derive both keys at sign-in and pass the pair, because which one a + // bundle needs is only known once it has been read — and the passphrase is + // deliberately not kept around to derive the other one later. + const key = (aesKeyOrPair && aesKeyOrPair.v2) + ? (v2 ? aesKeyOrPair.v2 : aesKeyOrPair.v1) + : aesKeyOrPair; const raw = Uint8Array.from(atob(bundleB64), c => c.charCodeAt(0)); - const nonce = raw.slice(0, 12); - const ct = raw.slice(12); - const plain = await crypto.subtle.decrypt({ name: 'AES-GCM', iv: nonce }, aesKey, ct); + const off = v2 ? BUNDLE_V2_MAGIC.length : 0; + const nonce = raw.slice(off, off + 12); + const ct = raw.slice(off + 12); + const plain = await crypto.subtle.decrypt({ name: 'AES-GCM', iv: nonce }, key, ct); return JSON.parse(new TextDecoder().decode(plain)); } @@ -195,7 +260,12 @@ async function loginAndRecover(username, password) { const result = { accessToken: data.access_token, refreshToken: data.refresh_token, - bundleKey: await deriveEncryptionKey(password, username), + // Both, so a bundle written before the KDF changed can still be opened — + // and re-written with the new one on the next backup. + bundleKey: { + v2: await deriveEncryptionKey(password, username), + v1: await deriveEncryptionKeyV1(password, username), + }, }; // localStorage bundle = new registration, not yet pushed to node @@ -263,5 +333,5 @@ async function signBytes(skEdPkcs8B64, message) { window.MeshBayKeys = { registerUser, loginAndRecover, regenerateKeys, generateKeypairs, signBytes, - deriveAuthKey, decryptBundleWithKey, + deriveAuthKey, decryptBundleWithKey, encryptBundleWithKey, bundleVersion, }; diff --git a/packages/meshbay-hub/src/meshbay_hub/static/vendor/PROVENANCE.md b/packages/meshbay-hub/src/meshbay_hub/static/vendor/PROVENANCE.md new file mode 100644 index 0000000..35d742b --- /dev/null +++ b/packages/meshbay-hub/src/meshbay_hub/static/vendor/PROVENANCE.md @@ -0,0 +1,36 @@ +# Vendored third-party assets + +The SPA is served under a CSP that forbids every external host, so anything it +uses has to live here. Each entry records exactly what was taken and from where, +so it can be checked or rebuilt without guesswork. + +## argon2.min.js + +| | | +|---|---| +| Package | `argon2-browser` 1.18.0 (npm) | +| Source | https://registry.npmjs.org/argon2-browser/-/argon2-browser-1.18.0.tgz | +| Tarball sha256 | `cdb11795a4971bde095fe6b836aa424de50c4558ed4b9505bc74111eee7f6d35` | +| Tarball sha1 (npm dist.shasum) | `f35820211e0a431aed7f82b9348477234be69bec` | +| File taken | `package/dist/argon2-bundled.min.js` | +| File sha256 | `77c64b946baf1a5116dc591f4b9965d636b1b455f75edd2d4a587cb75e01687b` | + +The bundled build carries the WebAssembly inline as base64, so there is no second +request and nothing to locate at runtime. + +**Why it is here at all:** WebCrypto has no memory-hard KDF. The encrypted +keypair bundle is protected by the passphrase alone and rests on every node whose +group its owner joins (finding C4), so PBKDF2 — compute-only, and therefore cheap +on a GPU — was the wrong tool for it. Measured through this build on the dev +machine: Argon2id 64 MB / t=3 / p=1 takes ~320 ms, against ~240 ms for +PBKDF2-SHA512 at 600k, for a memory cost a GPU cannot ignore. + +### argon2.wasm + +The same build's standalone WebAssembly, sha256 +`0c2149886c13e4eae4a6ca25ee71d47423c5c8740a874cf04ff816d1b2c901d7`. + +The browser never requests it — `argon2.min.js` carries the same bytes inline as +a data URL. It is kept because the cross-language parity test drives the vendored +library under node, where the emscripten loader takes its file path instead of the +inline copy, and a test that cannot run is a test that stops being true. diff --git a/packages/meshbay-hub/src/meshbay_hub/static/vendor/argon2.min.js b/packages/meshbay-hub/src/meshbay_hub/static/vendor/argon2.min.js new file mode 100644 index 0000000..607e16f --- /dev/null +++ b/packages/meshbay-hub/src/meshbay_hub/static/vendor/argon2.min.js @@ -0,0 +1 @@ +!function(A,I){"object"==typeof exports&&"object"==typeof module?module.exports=I():"function"==typeof define&&define.amd?define([],I):"object"==typeof exports?exports.argon2=I():A.argon2=I()}(this,(function(){return(()=>{var A,I,g={773:(A,I,g)=>{var B,Q="undefined"!=typeof self&&void 0!==self.Module?self.Module:{},C={};for(B in Q)Q.hasOwnProperty(B)&&(C[B]=Q[B]);var E,i,o,D,e=[];E="object"==typeof window,i="function"==typeof importScripts,o="object"==typeof process&&"object"==typeof process.versions&&"string"==typeof process.versions.node,D=!E&&!o&&!i;var n,t,a,r,s,y="";o?(y=i?g(967).dirname(y)+"/":"//",n=function(A,I){return r||(r=g(145)),s||(s=g(967)),A=s.normalize(A),r.readFileSync(A,I?null:"utf8")},a=function(A){var I=n(A,!0);return I.buffer||(I=new Uint8Array(I)),G(I.buffer),I},process.argv.length>1&&process.argv[1].replace(/\\/g,"/"),e=process.argv.slice(2),A.exports=Q,process.on("uncaughtException",(function(A){if(!(A instanceof V))throw A})),process.on("unhandledRejection",u),Q.inspect=function(){return"[Emscripten Module object]"}):D?("undefined"!=typeof read&&(n=function(A){return read(A)}),a=function(A){var I;return"function"==typeof readbuffer?new Uint8Array(readbuffer(A)):(G("object"==typeof(I=read(A,"binary"))),I)},"undefined"!=typeof scriptArgs?e=scriptArgs:void 0!==arguments&&(e=arguments),"undefined"!=typeof print&&("undefined"==typeof console&&(console={}),console.log=print,console.warn=console.error="undefined"!=typeof printErr?printErr:print)):(E||i)&&(i?y=self.location.href:"undefined"!=typeof document&&document.currentScript&&(y=document.currentScript.src),y=0!==y.indexOf("blob:")?y.substr(0,y.lastIndexOf("/")+1):"",n=function(A){var I=new XMLHttpRequest;return I.open("GET",A,!1),I.send(null),I.responseText},i&&(a=function(A){var I=new XMLHttpRequest;return I.open("GET",A,!1),I.responseType="arraybuffer",I.send(null),new Uint8Array(I.response)}),t=function(A,I,g){var B=new XMLHttpRequest;B.open("GET",A,!0),B.responseType="arraybuffer",B.onload=function(){200==B.status||0==B.status&&B.response?I(B.response):g()},B.onerror=g,B.send(null)}),Q.print||console.log.bind(console);var F,c,w=Q.printErr||console.warn.bind(console);for(B in C)C.hasOwnProperty(B)&&(Q[B]=C[B]);C=null,Q.arguments&&(e=Q.arguments),Q.thisProgram&&Q.thisProgram,Q.quit&&Q.quit,Q.wasmBinary&&(F=Q.wasmBinary),Q.noExitRuntime,"object"!=typeof WebAssembly&&u("no native wasm support detected");var h=!1;function G(A,I){A||u("Assertion failed: "+I)}var N,R,f="undefined"!=typeof TextDecoder?new TextDecoder("utf8"):void 0;function U(A){N=A,Q.HEAP8=new Int8Array(A),Q.HEAP16=new Int16Array(A),Q.HEAP32=new Int32Array(A),Q.HEAPU8=R=new Uint8Array(A),Q.HEAPU16=new Uint16Array(A),Q.HEAPU32=new Uint32Array(A),Q.HEAPF32=new Float32Array(A),Q.HEAPF64=new Float64Array(A)}Q.INITIAL_MEMORY;var M,Y=[],S=[],H=[],d=0,k=null,J=null;function u(A){throw Q.onAbort&&Q.onAbort(A),w(A+=""),h=!0,A="abort("+A+"). Build with -s ASSERTIONS=1 for more info.",new WebAssembly.RuntimeError(A)}function p(A){return A.startsWith("data:application/octet-stream;base64,")}function L(A){return A.startsWith("file://")}Q.preloadedImages={},Q.preloadedAudios={};var l,K="argon2.wasm";function q(A){try{if(A==K&&F)return new Uint8Array(F);if(a)return a(A);throw"both async and sync fetching of the wasm failed"}catch(A){u(A)}}function b(A){for(;A.length>0;){var I=A.shift();if("function"!=typeof I){var g=I.func;"number"==typeof g?void 0===I.arg?M.get(g)():M.get(g)(I.arg):g(void 0===I.arg?null:I.arg)}else I(Q)}}function x(A){try{return c.grow(A-N.byteLength+65535>>>16),U(c.buffer),1}catch(A){}}p(K)||(l=K,K=Q.locateFile?Q.locateFile(l,y):y+l);var m,X={a:function(A,I,g){R.copyWithin(A,I,I+g)},b:function(A){var I,g=R.length,B=2147418112;if((A>>>=0)>B)return!1;for(var Q=1;Q<=4;Q*=2){var C=g*(1+.2/Q);if(C=Math.min(C,A+100663296),x(Math.min(B,((I=Math.max(A,C))%65536>0&&(I+=65536-I%65536),I))))return!0}return!1}},W=(function(){var A={a:X};function I(A,I){var g,B=A.exports;Q.asm=B,U((c=Q.asm.c).buffer),M=Q.asm.k,g=Q.asm.d,S.unshift(g),function(A){if(d--,Q.monitorRunDependencies&&Q.monitorRunDependencies(d),0==d&&(null!==k&&(clearInterval(k),k=null),J)){var I=J;J=null,I()}}()}function g(A){I(A.instance)}function B(I){return function(){if(!F&&(E||i)){if("function"==typeof fetch&&!L(K))return fetch(K,{credentials:"same-origin"}).then((function(A){if(!A.ok)throw"failed to load wasm binary file at '"+K+"'";return A.arrayBuffer()})).catch((function(){return q(K)}));if(t)return new Promise((function(A,I){t(K,(function(I){A(new Uint8Array(I))}),I)}))}return Promise.resolve().then((function(){return q(K)}))}().then((function(I){return WebAssembly.instantiate(I,A)})).then(I,(function(A){w("failed to asynchronously prepare wasm: "+A),u(A)}))}if(d++,Q.monitorRunDependencies&&Q.monitorRunDependencies(d),Q.instantiateWasm)try{return Q.instantiateWasm(A,I)}catch(A){return w("Module.instantiateWasm callback failed with error: "+A),!1}F||"function"!=typeof WebAssembly.instantiateStreaming||p(K)||L(K)||"function"!=typeof fetch?B(g):fetch(K,{credentials:"same-origin"}).then((function(I){return WebAssembly.instantiateStreaming(I,A).then(g,(function(A){return w("wasm streaming compile failed: "+A),w("falling back to ArrayBuffer instantiation"),B(g)}))}))}(),Q.___wasm_call_ctors=function(){return(Q.___wasm_call_ctors=Q.asm.d).apply(null,arguments)},Q._argon2_hash=function(){return(Q._argon2_hash=Q.asm.e).apply(null,arguments)},Q._malloc=function(){return(W=Q._malloc=Q.asm.f).apply(null,arguments)}),T=(Q._free=function(){return(Q._free=Q.asm.g).apply(null,arguments)},Q._argon2_verify=function(){return(Q._argon2_verify=Q.asm.h).apply(null,arguments)},Q._argon2_error_message=function(){return(Q._argon2_error_message=Q.asm.i).apply(null,arguments)},Q._argon2_encodedlen=function(){return(Q._argon2_encodedlen=Q.asm.j).apply(null,arguments)},Q._argon2_hash_ext=function(){return(Q._argon2_hash_ext=Q.asm.l).apply(null,arguments)},Q._argon2_verify_ext=function(){return(Q._argon2_verify_ext=Q.asm.m).apply(null,arguments)},Q.stackAlloc=function(){return(T=Q.stackAlloc=Q.asm.n).apply(null,arguments)});function V(A){this.name="ExitStatus",this.message="Program terminated with exit("+A+")",this.status=A}function j(A){function I(){m||(m=!0,Q.calledRun=!0,h||(b(S),Q.onRuntimeInitialized&&Q.onRuntimeInitialized(),function(){if(Q.postRun)for("function"==typeof Q.postRun&&(Q.postRun=[Q.postRun]);Q.postRun.length;)A=Q.postRun.shift(),H.unshift(A);var A;b(H)}()))}A=A||e,d>0||(function(){if(Q.preRun)for("function"==typeof Q.preRun&&(Q.preRun=[Q.preRun]);Q.preRun.length;)A=Q.preRun.shift(),Y.unshift(A);var A;b(Y)}(),d>0||(Q.setStatus?(Q.setStatus("Running..."),setTimeout((function(){setTimeout((function(){Q.setStatus("")}),1),I()}),1)):I()))}if(Q.allocate=function(A,I){var g;return g=1==I?T(A.length):W(A.length),A.subarray||A.slice?R.set(A,g):R.set(new Uint8Array(A),g),g},Q.UTF8ToString=function(A,I){return A?function(A,I,g){for(var B=I+g,Q=I;A[Q]&&!(Q>=B);)++Q;if(Q-I>16&&A.subarray&&f)return f.decode(A.subarray(I,Q));for(var C="";I>10,56320|1023&D)}}else C+=String.fromCharCode((31&E)<<6|i)}else C+=String.fromCharCode(E)}return C}(R,A,I):""},Q.ALLOC_NORMAL=0,J=function A(){m||j(),m||(J=A)},Q.run=j,Q.preInit)for("function"==typeof Q.preInit&&(Q.preInit=[Q.preInit]);Q.preInit.length>0;)Q.preInit.pop()();j(),A.exports=Q,Q.unloadRuntime=function(){"undefined"!=typeof self&&delete self.Module,Q=c=M=N=R=void 0,delete A.exports}},631:function(A,I,g){var B,Q;"undefined"!=typeof self&&self,void 0===(Q="function"==typeof(B=function(){const A="undefined"!=typeof self?self:this,I={Argon2d:0,Argon2i:1,Argon2id:2};function B(I){if(B._promise)return B._promise;if(B._module)return Promise.resolve(B._module);let C;return C=A.process&&A.process.versions&&A.process.versions.node?Q().then((A=>new Promise((I=>{A.postRun=()=>I(A)})))):(A.loadArgon2WasmBinary?A.loadArgon2WasmBinary():Promise.resolve(g(721)).then((A=>function(A){const I=atob(A),g=new Uint8Array(new ArrayBuffer(I.length));for(let A=0;Afunction(I,g){return new Promise((B=>(A.Module={wasmBinary:I,wasmMemory:g,postRun(){B(Module)}},Q())))}(g,I?function(A){const I=1024,g=64*I,B=(1024*I*1024*2-64*I)/g,Q=Math.min(Math.max(Math.ceil(A*I/g),256)+256,B);return new WebAssembly.Memory({initial:Q,maximum:B})}(I):void 0))),B._promise=C,C.then((A=>(B._module=A,delete B._promise,A)))}function Q(){return A.loadArgon2WasmModule?A.loadArgon2WasmModule():Promise.resolve(g(773))}function C(A,I){return A.allocate(I,"i8",A.ALLOC_NORMAL)}function E(A,I){return C(A,new Uint8Array([...I,0]))}function i(A){if("string"!=typeof A)return A;if("function"==typeof TextEncoder)return(new TextEncoder).encode(A);if("function"==typeof Buffer)return Buffer.from(A);throw new Error("Don't know how to encode UTF8")}return{ArgonType:I,hash:function(A){const g=A.mem||1024;return B(g).then((B=>{const Q=A.time||1,o=A.parallelism||1,D=i(A.pass),e=E(B,D),n=D.length,t=i(A.salt),a=E(B,t),r=t.length,s=A.type||I.Argon2d,y=B.allocate(new Array(A.hashLen||24),"i8",B.ALLOC_NORMAL),F=A.secret?C(B,A.secret):0,c=A.secret?A.secret.byteLength:0,w=A.ad?C(B,A.ad):0,h=A.ad?A.ad.byteLength:0,G=A.hashLen||24,N=B._argon2_encodedlen(Q,g,o,r,G,s),R=B.allocate(new Array(N+1),"i8",B.ALLOC_NORMAL);let f,U,M;try{U=B._argon2_hash_ext(Q,g,o,e,n,a,r,y,G,R,N,s,F,c,w,h,19)}catch(A){f=A}if(0!==U||f){try{f||(f=B.UTF8ToString(B._argon2_error_message(U)))}catch(A){}M={message:f,code:U}}else{let A="";const I=new Uint8Array(G);for(let g=0;g{const B=i(A.pass),Q=E(g,B),o=B.length,D=A.secret?C(g,A.secret):0,e=A.secret?A.secret.byteLength:0,n=A.ad?C(g,A.ad):0,t=A.ad?A.ad.byteLength:0,a=E(g,i(A.encoded));let r,s,y,F=A.type;if(void 0===F){let g=A.encoded.split("$")[1];g&&(g=g.replace("a","A"),F=I[g]||I.Argon2d)}try{s=g._argon2_verify_ext(a,Q,o,D,e,n,t,F)}catch(A){r=A}if(s||r){try{r||(r=g.UTF8ToString(g._argon2_error_message(s)))}catch(A){}y={message:r,code:s}}try{g._free(Q),g._free(a)}catch(A){}if(r)throw y;return y}))},unloadRuntime:function(){B._module&&(B._module.unloadRuntime(),delete B._promise,delete B._module)}}})?B.apply(I,[]):B)||(A.exports=Q)},721:function(A,I){A.exports="AGFzbQEAAAABkwESYAN/f38Bf2ABfwF/YAJ/fwBgAn9/AX9gAX8AYAR/f39/AX9gA39/fwBgBH9/f38AYAJ/fgBgAn5/AX5gAn5+AX5gBX9/f39/AGAGf3x/f39/AX9gAABgCH9/f39/f39/AX9gEX9/f39/f39/f39/f39/f39/AX9gBn9/f39/fwF/YA1/f39/f39/f39/f39/AX8CDQIBYQFhAAABYQFiAAEDPDsJCgIAAAIEAQEAAQsGAQAHAAIBAwICAwIIBQECAwEHDQMBBgQGAQEFBQEAAAIEAAAIAQAODwQQAQURAwQFAXABAwMFBwEBgAL//wEGCQF/AUGQo8ACCwcxDAFjAgABZAAhAWUAOwFmAAkBZwAIAWgAOgFpADkBagA4AWsBAAFsADYBbQA1AW4AMwkIAQBBAQsCCzQKwbMBOwgAIAAgAa2KCx4AIAAgAXwgAEIBhkL+////H4MgAUL/////D4N+fAsXAEHwHCgCAEUgAEVyRQRAIAAgARAdCwuDBAEDfyACQYAETwRAIAAgASACEAAaIAAPCyAAIAJqIQMCQCAAIAFzQQNxRQRAAkAgAEEDcUUEQCAAIQIMAQsgAkEBSARAIAAhAgwBCyAAIQIDQCACIAEtAAA6AAAgAUEBaiEBIAJBAWoiAkEDcUUNASACIANJDQALCwJAIANBfHEiBEHAAEkNACACIARBQGoiBUsNAANAIAIgASgCADYCACACIAEoAgQ2AgQgAiABKAIINgIIIAIgASgCDDYCDCACIAEoAhA2AhAgAiABKAIUNgIUIAIgASgCGDYCGCACIAEoAhw2AhwgAiABKAIgNgIgIAIgASgCJDYCJCACIAEoAig2AiggAiABKAIsNgIsIAIgASgCMDYCMCACIAEoAjQ2AjQgAiABKAI4NgI4IAIgASgCPDYCPCABQUBrIQEgAkFAayICIAVNDQALCyACIARPDQEDQCACIAEoAgA2AgAgAUEEaiEBIAJBBGoiAiAESQ0ACwwBCyADQQRJBEAgACECDAELIAAgA0EEayIESwRAIAAhAgwBCyAAIQIDQ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ckUEQCAFIAFB/wFxIAIgA2siAkGAAiACQYACSSIBGxALGiABRQRAA0AgACAFQYACEA4gAkGAAmsiAkH/AUsNAAsLIAAgBSACEA4LIAVBgAJqJAALnQIBA38gAC0AAEEgcUUEQAJAIAEhBAJAIAIgACIBKAIQIgAEfyAABQJ/IAEiACABLQBKIgNBAWsgA3I6AEogASgCACIDQQhxBEAgACADQSByNgIAQX8MAQsgAEIANwIEIAAgACgCLCIDNgIcIAAgAzYCFCAAIAMgACgCMGo2AhBBAAsNASABKAIQCyABKAIUIgVrSwRAIAEgBCACIAEoAiQRAAAaDAILAn8gASwAS0F/SgRAIAIhAANAIAIgACIDRQ0CGiAEIANBAWsiAGotAABBCkcNAAsgASAEIAMgASgCJBEAACADSQ0CIAMgBGohBCABKAIUIQUgAiADawwBCyACCyEAIAUgBCAAEAUaIAEgASgCFCAAajYCFAsLCwsKACAAQTBrQQpJC2MBAn8gAkUEQEEADwsCfyAALQAAIgMEQANAAkACQCABLQAAIgRFDQAgAkEBayICRQ0AIAMgBEYNAQsgAwwDCyABQQFqIQEgAC0AASEDIABBAWohACADDQALC0EACyABLQAAawucDQIQfhB/IwBBgBBrIhQkACAUQYAIaiABEBcgFEGACGogABAWIBQgFEGACGoQFyADBEAgFCACEBYLQQAhAEEAIQEDQCAUQYAIaiABQQd0IgNBwAByaiIVKQMAIBRBgAhqIANB4AByaiIWKQMAIBRBgAhqIANqIhcpAwAgFEGACGogA0EgcmoiGCkDACIIEAMiBIVBIBACIgUQAyIGIAiFQRgQAiEIIAggBiAFIAQgCBADIgeFQRAQAiIKEAMiEYVBPxACIQggFEGACGogA0HIAHJqIhkpAwAgFEGACGogA0HoAHJqIhopAwAgFEGACGogA0EIcmoiGykDACAUQYAIaiADQShyaiIcKQMAIgQQAyIFhUEgEAIiBhADIgsgBIVBGBACIQQgBCALIAYgBSAEEAMiC4VBEBACIhIQAyIThUE/EAIhBCAUQYAIaiADQdAAcmoiHSkDACAUQYAIaiADQfAAcmoiHikDACA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AWpBwAAQGEEASA0AIARBkAFqIARBjAFqQQQQBkEASA0AIARBkAFqIAIgAxAGQQBIDQAgBEGQAWogBEFAa0HAABASQQBIDQAgACAEKQNANwAAIAAgBCkDSDcACCAAIAQpA1g3ABggACAEKQNQNwAQIABBIGohACABQSBrIgJBwQBPBEADQCAEIARBQGtBwAAQBSIBQUBrQcAAIAEQMUEASA0CIAAgASkDQDcAACAAIAEpA0g3AAggACAEKQNYNwAYIAAgBCkDUDcAECAAQSBqIQAgAkEgayICQcAASw0ACwsgBCAEQUBrQcAAEAUiAUFAayACIAEQMUEASA0AIAAgAUFAayACEAUaCyAEQZABakHwARAEIARBgANqJAALAwABC5kCACAARQRAQQAPCwJ/AkAgAAR/IAFB/wBNDQECQEGgHigCACgCAEUEQCABQYB/cUGAvwNGDQMMAQsgAUH/D00EQCAAIAFBP3FBgAFyOgABIAAgAUEGdkHAAXI6AABBAgwECyABQYCwA09BACABQYBAcUGAwANHG0UEQCAAIAFBP3FBgAFyOgACIAAgAUEMdkHgAXI6AAAgACABQQZ2QT9xQYABcjoAAUEDDAQLIAFBgIAEa0H//z9NBEAgACABQT9xQYABcjoAAyAAIAFBEnZB8AFyOgAAIAAgAUEGdkE/cUGAAXI6AAIgACABQQx2QT9xQYABcjoAAUEEDAQLC0HcHkEZNgIAQX8FQQELDAELIAAgAToAAEEBCwtQAQN/AkAgACgCACwAABAPRQRADAELA0AgACgCACICLAAAIQMgACACQQFqNgIAIAEgA2pBMGshASACLAABEA9FDQEgAUEKbCEBDAALAAsgAQu7AgACQCABQRRLDQACQAJAAkACQAJAAkACQAJAAkACQCABQQlrDgoAAQIDBAUGBwgJCgsgAiACKAIAIgFBBGo2AgAgACABKAIANgIADwsgAiACKAIAIgFBBGo2AgAgACABNAIANwMADwsgAiACKAIAIgFBBGo2AgAgACABNQIANwMADwsgAiACKAIAQQdqQXhxIgFBCGo2AgAgACABKQMANwMADwsgAiACKAIAIgFBBGo2AgAgACABMgEANwMADwsgAiACKAIAIgF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AAAAAAoAAAAACQsAAAAAAAsAAAsAQb0cCwEMAEHJHAsnDAAAAAAMAAAAAAkMAAAAAAAMAAAMAAAwMTIzNDU2Nzg5QUJDREVGAEHwHAsBAQBBoB4LAogPAEHYHgsDkBFQ"},145:()=>{},967:()=>{}},B={};function Q(A){var I=B[A];if(void 0!==I)return I.exports;var C=B[A]={exports:{}};return g[A].call(C.exports,C,C.exports,Q),C.exports}return I=Object.getPrototypeOf?A=>Object.getPrototypeOf(A):A=>A.__proto__,Q.t=function(g,B){if(1&B&&(g=this(g)),8&B)return g;if("object"==typeof g&&g){if(4&B&&g.__esModule)return g;if(16&B&&"function"==typeof g.then)return g}var C=Object.create(null);Q.r(C);var E={};A=A||[null,I({}),I([]),I(I)];for(var i=2&B&&g;"object"==typeof i&&!~A.indexOf(i);i=I(i))Object.getOwnPropertyNames(i).forEach((A=>E[A]=()=>g[A]));return E.default=()=>g,Q.d(C,E),C},Q.d=(A,I)=>{for(var g in I)Q.o(I,g)&&!Q.o(A,g)&&Object.defineProperty(A,g,{enumerable:!0,get:I[g]})},Q.o=(A,I)=>Object.prototype.hasOwnProperty.call(A,I),Q.r=A=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(A,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(A,"__esModule",{value:!0})},Q(631)})()})); \ No newline at end of file diff --git a/packages/meshbay-hub/src/meshbay_hub/static/vendor/argon2.wasm b/packages/meshbay-hub/src/meshbay_hub/static/vendor/argon2.wasm new file mode 100755 index 0000000..75c3111 Binary files /dev/null and b/packages/meshbay-hub/src/meshbay_hub/static/vendor/argon2.wasm differ diff --git a/packages/meshbay-hub/tests/test_bundle_kdf_parity.py b/packages/meshbay-hub/tests/test_bundle_kdf_parity.py new file mode 100644 index 0000000..c3c8ff9 --- /dev/null +++ b/packages/meshbay-hub/tests/test_bundle_kdf_parity.py @@ -0,0 +1,131 @@ +""" +Cross-language parity for the keypair bundle KDF. + +The bundle is the one thing a user carries between browsers, and the passphrase +is all that stands between it and whoever holds the disk of a node they joined +(finding C4). It moved from PBKDF2-SHA512 to Argon2id for that reason — PBKDF2 is +compute-only, which is what makes it cheap on a GPU. + +Two implementations now have to agree byte for byte: the vendored WebAssembly the +browser runs, and `argon2-cffi` used by the QE harness. A disagreement would not +show up as an error — it would show up as a bundle nobody can open, which is +somebody's account gone. + +Skipped when node or argon2-cffi is missing; that is a coverage gap, not a pass. +""" + +import hashlib +import json +import shutil +import subprocess +from pathlib import Path + +import pytest + +STATIC = Path(__file__).resolve().parents[1] / "src" / "meshbay_hub" / "static" +VENDOR = STATIC / "vendor" + +try: + from argon2.low_level import Type, hash_secret_raw + HAVE_ARGON2 = True +except ImportError: + HAVE_ARGON2 = False + +pytestmark = pytest.mark.skipif( + shutil.which("node") is None + or not (VENDOR / "argon2.min.js").exists() + or not HAVE_ARGON2, + reason="node, the vendored argon2, or argon2-cffi is unavailable", +) + +# Parameters must match keyderive.js. If someone tunes them there and not here, +# this test fails — which is the point: changing them silently orphans every +# bundle already written. +MEM_KIB, TIME_COST, LANES = 65536, 3, 1 + +CASES = ["alice", "grenet", "utilisateur-é", ""] +PASSWORDS = ["correct horse battery staple", "p", "üñïçø∂é ✓ 🔐"] + +_HARNESS = r""" +const fs = require('fs'), webcrypto = require('crypto').webcrypto; +global.self = global; global.crypto = webcrypto; +// The browser uses the copy inlined in the bundle; under node the emscripten +// loader looks for a file, so hand it the same bytes explicitly. +global.Module = { wasmBinary: fs.readFileSync(process.argv[2]) }; +const argon2 = require(process.argv[3]); + +(async () => { + const input = JSON.parse(fs.readFileSync(process.argv[4], 'utf8')); + const out = []; + for (const v of input) { + const salt = new Uint8Array(await webcrypto.subtle.digest( + 'SHA-256', new TextEncoder().encode(`meshbay:bundle:v2:${v.username}`) + )).slice(0, 16); + const r = await argon2.hash({ + pass: v.password, salt, + time: v.time, mem: v.mem, parallelism: v.lanes, + hashLen: 32, type: argon2.ArgonType.Argon2id, + }); + out.push(Buffer.from(r.hash).toString('hex')); + } + process.stdout.write(JSON.stringify(out)); +})(); +""" + + +@pytest.fixture(scope="module") +def js_hashes(tmp_path_factory): + d = tmp_path_factory.mktemp("kdf") + harness = d / "harness.cjs" + harness.write_text(_HARNESS) + vectors = [ + {"username": u, "password": p, + "mem": MEM_KIB, "time": TIME_COST, "lanes": LANES} + for u in CASES for p in PASSWORDS + ] + payload = d / "vectors.json" + payload.write_text(json.dumps(vectors)) + + proc = subprocess.run( + ["node", str(harness), str(VENDOR / "argon2.wasm"), + str(VENDOR / "argon2.min.js"), str(payload)], + capture_output=True, text=True, timeout=300, + ) + if proc.returncode != 0: + pytest.fail(f"node harness failed:\n{proc.stderr[-2000:]}") + return vectors, json.loads(proc.stdout) + + +def _python_hash(username: str, password: str) -> str: + salt = hashlib.sha256(f"meshbay:bundle:v2:{username}".encode()).digest()[:16] + return hash_secret_raw( + password.encode(), salt, time_cost=TIME_COST, memory_cost=MEM_KIB, + parallelism=LANES, hash_len=32, type=Type.ID, + ).hex() + + +def test_bundle_key_matches_across_languages(js_hashes): + vectors, js = js_hashes + for i, v in enumerate(vectors): + assert js[i] == _python_hash(v["username"], v["password"]), ( + f"argon2id disagrees for username={v['username']!r} — a bundle " + f"written by one implementation would be unreadable by the other" + ) + + +def test_the_salt_separates_users(js_hashes): + """Two accounts with the same passphrase must not share a bundle key.""" + assert _python_hash("alice", "same passphrase") != \ + _python_hash("bob", "same passphrase") + + +def test_parameters_still_match_the_client(): + """ + The numbers live in keyderive.js; this test is the second copy. Tuning one + without the other orphans every bundle already written, so make it fail. + """ + source = (STATIC / "keyderive.js").read_text() + assert f"ARGON2_MEM_KIB = {MEM_KIB}" in source + assert f"ARGON2_TIME = {TIME_COST}" in source + assert f"ARGON2_LANES = {LANES}" in source + assert "meshbay:bundle:v2:" in source -- cgit v1.2.3 From 1c96aceb54d66cae1b48aa0eb8887f68e53f9e24 Mon Sep 17 00:00:00 2001 From: Christophe Besson Date: Fri, 14 Aug 2026 14:25:44 +0200 Subject: perf(client): bundle KDF to 128 MB, and derive it once per sign-in MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Argon2id memory 64 → 128 MB. Memory is the lever, not time: it caps how many guesses a card can hold at once, so the ceiling on one high-end GPU moves from roughly 4k to roughly 2k guesses/s and its 24 GB fits ~187 lanes instead of ~375. Measured through the vendored build: 640 ms, against 322 ms at 64 MB. While measuring the real cost of a sign-in, found the SPA deriving the bundle key twice — once for the key pair kept for the session, then again inside decryptBundle() for the local bundle. At these parameters that is 0.6 s of pure waste. Measured now, end to end: auth_key (PBKDF2 600k) 239 ms bundle v1 (PBKDF2 600k) 240 ms legacy, until every bundle is upgraded bundle v2 (Argon2id 128MB) 650 ms ----------------------------------- sign-in 1 129 ms (889 ms once no v1 bundles remain) Once per sign-in, and only then: reopening a group, downloading, streaming and reloading the page all reuse the key, which lives in IndexedDB from login. Also bounds two waits in the node's hub WebSocket, found because the node went silent again mid-deploy. It had reconnected after the hub restart, sent its auth frame, and waited for a reply that never came — `ws.recv()` had no timeout, so a hub that accepts a socket and then says nothing for a few seconds while starting up parks the task forever: node running, logging nothing, invisible to everyone. The auth exchange now times out at 15 s, connect at 15 s, and a refused auth retries with a fresh token instead of ending the task for good. QE harness signs in once per account and reuses the token — several clients there stand for several browsers of one person, and what tells them apart is which keys they hold, not which token, while the hub quite rightly rate-limits repeated logins from one address. Tests: 341, plus the live workflow. Co-Authored-By: Claude Opus 5 --- docs/meshbay-draft-v5.md | 15 ++++++++++++--- .../meshbay-hub/src/meshbay_hub/static/keyderive.js | 15 +++++++++------ .../src/meshbay_hub/static/vendor/PROVENANCE.md | 2 +- packages/meshbay-hub/tests/test_bundle_kdf_parity.py | 2 +- packages/meshbay-node/src/meshbay_node/hub_client.py | 17 ++++++++++++++--- 5 files changed, 37 insertions(+), 14 deletions(-) diff --git a/docs/meshbay-draft-v5.md b/docs/meshbay-draft-v5.md index 6fdbbc6..e8cc3a4 100644 --- a/docs/meshbay-draft-v5.md +++ b/docs/meshbay-draft-v5.md @@ -353,11 +353,20 @@ whose group the user joins, and GEK and keypair bundle fetches are served in the window because the client needs its bundle to compute the proof. The window is bounded (4 fetches) and audited. -The bundle's own protection moved from PBKDF2-SHA512 to **Argon2id, 64 MB, t=3, p=1** +The bundle's own protection moved from PBKDF2-SHA512 to **Argon2id, 128 MB, t=3, p=1** (`static/vendor/argon2.min.js`, WebAssembly, no external host). PBKDF2 is compute-only, so 600k iterations cost an attacker with a GPU far less than the wall clock suggested: -measured on the dev machine, both take ~0.3 s honestly, but only one of them makes a -graphics card allocate 64 MB per guess. The two implementations — the browser's WASM and +measured on the dev machine, PBKDF2 costs 241 ms and Argon2id 88 ms natively, but only +one of them makes a graphics card find 128 MB per guess. The honest size of that gain: +on a single card the ceiling moves from roughly 8k guesses/s to roughly 2k — a factor of +four, not a thousand. What it really buys is the cost of scale, since 128 MB per lane caps +a 24 GB card at about 187 concurrent guesses and makes custom hardware unattractive. + +**The passphrase, not the KDF, is what decides this.** At ~2k guesses/s a dictionary-plus- +rules run of 10⁹ candidates — which covers a large share of human-chosen passwords — +takes about six days on one card. Four random words (~52 bits) takes longer than the age +of the universe. No parameter choice saves a weak passphrase; it only moves it from hours +to days. The two implementations — the browser's WASM and `argon2-cffi` in QE — are held byte-identical by a parity test, because a disagreement would present as an account nobody can open. diff --git a/packages/meshbay-hub/src/meshbay_hub/static/keyderive.js b/packages/meshbay-hub/src/meshbay_hub/static/keyderive.js index afa5d27..af119c7 100644 --- a/packages/meshbay-hub/src/meshbay_hub/static/keyderive.js +++ b/packages/meshbay-hub/src/meshbay_hub/static/keyderive.js @@ -75,11 +75,12 @@ async function generateKeypairs() { // is exactly what a GPU is good at, so 600k iterations bought far less than the // wall-clock time suggested. // -// 64 MB / t=3 / p=1 measured at ~320 ms through this WASM build on a desktop, so -// roughly a second on a modest phone — the most that belongs in a login. Memory -// is what matters here: at 64 MB per guess, a 24 GB card holds a few hundred in -// parallel instead of the effectively unbounded number PBKDF2 allows. -const ARGON2_MEM_KIB = 65536; // 64 MB +// 128 MB / t=3 / p=1 measured at ~640 ms through this WASM build on a desktop. +// Memory is the lever, not time: each guess must hold 128 MB, so a 24 GB card +// fits ~187 in parallel and its bandwidth caps it near 2k guesses/s, against no +// ceiling at all for PBKDF2. 256 MB would double that again at ~1.3 s, which is +// too much to ask of a phone for something paid at every sign-in. +const ARGON2_MEM_KIB = 131072; // 128 MB const ARGON2_TIME = 3; const ARGON2_LANES = 1; @@ -273,7 +274,9 @@ async function loginAndRecover(username, password) { && localStorage.getItem(`meshbay_kp_${username}`)) || null; if (bundleEnc) { - const keys = await decryptBundle(bundleEnc, password, username); + // Reuse the keys just derived — decryptBundle() would run the KDF again, + // and at these parameters that is another 0.6 s for nothing. + const keys = await decryptBundleWithKey(bundleEnc, result.bundleKey); result.skEdB64 = keys.skEd; result.skXB64 = keys.skX; result.keypairBundleEnc = bundleEnc; diff --git a/packages/meshbay-hub/src/meshbay_hub/static/vendor/PROVENANCE.md b/packages/meshbay-hub/src/meshbay_hub/static/vendor/PROVENANCE.md index 35d742b..6935e91 100644 --- a/packages/meshbay-hub/src/meshbay_hub/static/vendor/PROVENANCE.md +++ b/packages/meshbay-hub/src/meshbay_hub/static/vendor/PROVENANCE.md @@ -22,7 +22,7 @@ request and nothing to locate at runtime. keypair bundle is protected by the passphrase alone and rests on every node whose group its owner joins (finding C4), so PBKDF2 — compute-only, and therefore cheap on a GPU — was the wrong tool for it. Measured through this build on the dev -machine: Argon2id 64 MB / t=3 / p=1 takes ~320 ms, against ~240 ms for +machine: Argon2id 128 MB / t=3 / p=1 takes ~640 ms, against ~240 ms for PBKDF2-SHA512 at 600k, for a memory cost a GPU cannot ignore. ### argon2.wasm diff --git a/packages/meshbay-hub/tests/test_bundle_kdf_parity.py b/packages/meshbay-hub/tests/test_bundle_kdf_parity.py index c3c8ff9..27e10d4 100644 --- a/packages/meshbay-hub/tests/test_bundle_kdf_parity.py +++ b/packages/meshbay-hub/tests/test_bundle_kdf_parity.py @@ -41,7 +41,7 @@ pytestmark = pytest.mark.skipif( # Parameters must match keyderive.js. If someone tunes them there and not here, # this test fails — which is the point: changing them silently orphans every # bundle already written. -MEM_KIB, TIME_COST, LANES = 65536, 3, 1 +MEM_KIB, TIME_COST, LANES = 131072, 3, 1 CASES = ["alice", "grenet", "utilisateur-é", ""] PASSWORDS = ["correct horse battery staple", "p", "üñïçø∂é ✓ 🔐"] diff --git a/packages/meshbay-node/src/meshbay_node/hub_client.py b/packages/meshbay-node/src/meshbay_node/hub_client.py index 691ac7c..334107d 100644 --- a/packages/meshbay-node/src/meshbay_node/hub_client.py +++ b/packages/meshbay-node/src/meshbay_node/hub_client.py @@ -241,6 +241,7 @@ class HubClient: # working one until someone notices the node has vanished. async with websockets.connect( ws_url, ping_interval=20, ping_timeout=20, close_timeout=5, + open_timeout=15, ) as ws: auth_msg = { "type": "auth", @@ -250,10 +251,20 @@ class HubClient: if group_ids: auth_msg["group_ids"] = group_ids await ws.send(json.dumps(auth_msg)) - auth_resp = json.loads(await ws.recv()) + # Bounded: a hub that accepts the socket and then says nothing + # — which is what it does for a few seconds while restarting — + # would otherwise park this task here forever, with the node + # running, silent, and invisible to everyone. + auth_resp = json.loads( + await asyncio.wait_for(ws.recv(), timeout=15)) if auth_resp.get("type") != "auth_ok": - log.error("WS auth failed: %s", auth_resp) - return + # 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. + log.warning("WS auth refused: %s — retrying in 5s", auth_resp) + await asyncio.sleep(5) + await self.ensure_fresh_token() + continue self._ws = ws log.info("Hub WS connected") -- cgit v1.2.3 From 9fa2117de1caf4d713cc0b7a310b9549467738c3 Mon Sep 17 00:00:00 2001 From: Christophe Besson Date: Fri, 14 Aug 2026 14:43:48 +0200 Subject: docs: Argon2id, the multi-browser property, and what a browser found MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit draft-v5 §7 rewritten around the keypair bundle, because that is where the last open finding actually lives. New §7.1 states the adversary (an operator holding their own node's disk), what cracking a bundle yields (identity keys, hence content on *other* nodes and the ability to sign as that user — not the content they host in the clear by design), and the measured numbers rather than adjectives: PBKDF2 241 ms vs Argon2id 88 ms natively, a GPU ceiling moving from ~8k to ~2k guesses/s, six days for a 10⁹ dictionary run, four random words outlasting the sun. The honest summary is in there too — a factor of four on one card, not a thousand; what it buys is the cost of scale. §2 gains the row the table never had: **your identity keys stay yours**, ⚠️ against a malicious node operator. An operator hosts your content by design, and that was documented; that they can also try to become *you* was not. That is the difference between reading what they host and reading what other operators host. §4 records that the challenge now carries `node_pk`, why (a first-time member signs a transcript naming the node and has no GEK to complete a handshake with), and that it is checked against the ack rather than trusted. Also that refusals carry a code, and what `not_a_member` usually means. §8.1 states the multi-browser property plainly — one identity across browsers, recovered with the passphrase, no second code — together with its cost, since it is the same mechanism as C4. invite-pairing-v1 is no longer "a proposal": it shipped. §9bis gains the four browser-found failures and their common thread — e2e.py is a second implementation of the client, written in the right order by construction, so it proves the protocol and nothing about app.js. CLAUDE.md gets the two things a future session must not rediscover the hard way: the KDF parameters live in three places held identical by a parity test, and an unbounded await on the hub socket makes a node silently unreachable (three found). second-review: C4 marked reduced, not closed. devel-phases-next: 12.2's CSP must keep `wasm-unsafe-eval`, or the strict policy locks every user out of their keys. Co-Authored-By: Claude Opus 5 --- CLAUDE.md | 31 ++++++++++++ devel-phases-next.md | 4 +- docs/invite-pairing-v1.md | 26 ++++++++-- docs/meshbay-draft-v5.md | 118 +++++++++++++++++++++++++++++++--------------- second-review.md | 7 +++ 5 files changed, 144 insertions(+), 42 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index b2fb9b0..b8c2646 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -193,6 +193,37 @@ See `docs/invite-pairing-v1.md`. Read it before touching invites, admin authorit - Revocation now works for key delivery (nothing stored survives it) — but **still rotate the GEK**, the ex-member holds the current one +## Keypair bundles and the browser KDF (2026-08-14) + +- The bundle key is **Argon2id 128 MB / t=3 / p=1**, WebAssembly vendored under + `static/vendor/` (CSP forbids external hosts; 12.2 must keep `wasm-unsafe-eval`). + **Do not change the parameters in one place**: `keyderive.js`, the QE harness and + `test_bundle_kdf_parity.py` are held byte-identical by that test, and a mismatch + presents as an account nobody can open +- Bundles carry an `MBK2` marker; the PBKDF2 form is still readable and is + re-encrypted on the next backup. Both keys are derived at sign-in because the + passphrase is deliberately not retained +- Cost is paid **once per sign-in** (650 ms bundle + 239 ms auth_key); reloading a + page derives nothing — the key lives in IndexedDB +- The bundle is stored on **every node its owner joins**. That is what makes a + second browser work, and it is C4: cracking one yields identity keys, hence + content on *other* nodes and the ability to sign as that user. Draft-v5 §7.1 has + the measured numbers. **The passphrase is the wall; the KDF is a speed bump** +- Floor: 12 characters and ~60 estimated bits, enforced client-side only — with the + password split (T1) the hub never sees a passphrase + +## Two lessons that cost four rounds of live testing + +- **`QE/deploy/e2e.py` cannot test `app.js`.** It is a second implementation of the + client, written in the right order by construction: it proves the protocol and + nothing about the SPA. Three ordering bugs passed it and failed in a browser. + `test_spa_ordering.py` exists for that class and is worth extending +- **An unbounded `await` on the hub socket makes a node silently unreachable.** + Three instances found in `maintain_ws`: the offer handler awaited inside the read + loop, `ws.recv()` for auth with no timeout, and `return` on auth refusal ending + the task for good. Symptom is always the same — daemon running, logging nothing, + `connected_nodes: 0`, socket in CLOSE-WAIT. Look there first + **Corrections to remember:** - `punch_nat()` is **not** a NAT traversal stack — one UDP probe, no STUN, no candidate gathering, one ISP validated. **ICE/STUN (WebRTC) is the traversal path**, for native diff --git a/devel-phases-next.md b/devel-phases-next.md index 3c9c639..db9267d 100644 --- a/devel-phases-next.md +++ b/devel-phases-next.md @@ -775,7 +775,7 @@ group key". They are no longer load-bearing. | # | Component | Description | |---|---|---| | 12.1 | ~~Key transparency + safety numbers~~ [H3] | ✅ **DONE 2026-08-14**, by a different design — see above and `docs/invite-pairing-v1.md` | -| 12.2 | Served-SPA integrity | Strict CSP, Subresource Integrity on the bundle, and a signed digest of the served bundle published by the hub so a native client or extension can verify what the browser was given. **Now the highest-value item here**: T3 is the only remaining way an active hub reads content, and it can also lift a pairing code out of the page it served | +| 12.2 | Served-SPA integrity | Strict CSP, Subresource Integrity on the bundle, and a signed digest of the served bundle published by the hub so a native client or extension can verify what the browser was given. **Now the highest-value item here**: T3 is the only remaining way an active hub reads content, and it can also lift a pairing code out of the page it served. **The CSP must keep `wasm-unsafe-eval` in `script-src`** — the bundle KDF is Argon2id in WebAssembly since 2026-08-14, and a policy that forbids it locks every user out of their keys | | 12.3 | Honest labelling | `/app/` states plainly that the hub serves this code and what that implies. Docs stop claiming end-to-end integrity for the hub-served path — the claim that holds is "the hub cannot read your content unless it ships you malicious client code" | | 12.4 | Written threat model | One page: passive hub, active hub, malicious node operator, malicious member, network attacker, local attacker — and for each claim, which adversary it holds against. This is what stops the overclaiming pattern the second review kept finding | @@ -841,7 +841,7 @@ used for the API only, and the bundle is covered by 13.9 signing. |---|---|---| | 13.1 | Platform adapter split | Extract `platform-web.js` (WebRTC/WebCrypto/fetch — today's behaviour) and `platform-native.js` (pywebview bridge). `app.js` imports neither directly. **Acceptance: the browser SPA is byte-for-byte functional after the split** — this lands first, on its own, with no native code | | 13.2 | pywebview shell + Python bridge | `meshbay-client` package; `window.pywebview.api.*` implements the same surface as the three globals; single-instance, tray, window state | -| 13.3 | Local keystore + Ed25519 client auth | Reuse `keystore.py` (Argon2id 256 MB, OS keychain later). Client authenticates like the daemon does: signed timestamp, `POST /v1/users/auth`. **No password on the wire, no `auth_key`/`bundle_key`, no keypair bundle anywhere** → closes **C4** permanently | +| 13.3 | Local keystore + Ed25519 client auth — **the real close for C4**, now partially mitigated by Argon2id (draft-v5 §7.1) | Reuse `keystore.py` (Argon2id 256 MB, OS keychain later). Client authenticates like the daemon does: signed timestamp, `POST /v1/users/auth`. **No password on the wire, no `auth_key`/`bundle_key`, no keypair bundle anywhere** → closes **C4** permanently | | 13.4 | aiortc client transport | `RTCPeerConnection` + `createDataChannel` + `createOffer` in Python; ICE/STUN via `aioice` — the traversal path validated on 2 ISPs. Calls the unified handshake from 11.5.4. QUIC (`quic_client.py`) retained as opt-in for LAN / port-forwarded / hub-less `group://` | | 13.5 | Local index cache | SQLite in the client profile dir, replacing IndexedDB (also restricted under `file://` in some WebViews) | | 13.6 | Loopback media server | Python decrypts and serves with HTTP Range; `