# MeshBay User Guide This guide covers MeshBay in depth — architecture, configuration, security, and the full API. Read the [Quickstart](QUICKSTART.md) first if you have not set up a node yet. --- ## Table of Contents 1. [Architecture overview](#1-architecture-overview) 2. [Account management](#2-account-management) 3. [Groups](#3-groups) 4. [Setting up a node](#4-setting-up-a-node) 5. [Sharing files](#5-sharing-files) 6. [Accessing files](#6-accessing-files) 7. [Video streaming](#7-video-streaming) 8. [Security model](#8-security-model) 9. [Moderation and legal](#9-moderation-and-legal) 10. [Troubleshooting](#10-troubleshooting) 11. [API reference](#11-api-reference) --- ## 1. Architecture Overview MeshBay has three components. Understanding which role each plays avoids a lot of confusion. ``` ┌─────────────────────────────────────────────┐ │ Mesh Hub (meshbay.org) │ │ │ │ • User accounts and public keys │ │ • Group registry (name, membership) │ │ • Encrypted GEK bundles (opaque blobs) │ │ • JWT issuance and verification key │ │ • Connection logs (legal compliance) │ │ • No file content, no indexes, no GEKs │ └──────────────┬──────────────────────────────┘ │ HTTPS (identity + routing only) │ ┌──────────┴──────────┐ │ │ ┌───▼────────┐ ┌──────▼───────┐ │ Mesh Node │ │ Mesh Client │ │ │ │ │ │ Your files │ MNP │ Browser or │ │ Your keys │◄───►│ Android app │ │ TCP+TLS │ │ │ └────────────┘ └──────────────┘ ``` **Mesh Hub** — a lightweight registrar. Its job is to vouch for identities, track group membership, and store encrypted GEK bundles. After login, clients talk directly to nodes. The hub is never in the data path for file transfers. **Mesh Node** — the program you run on your server or home machine. It watches a directory, maintains a group index, handles connections from clients, encrypts files at read time, and holds your private keys. You are the legal host of everything in your shared directory. **Mesh Client** — a web browser or Android app. It authenticates with the hub, fetches the encrypted GEK bundle, and connects directly to nodes for file browsing and download. **Protocol versioning:** MNP (Mesh Node Protocol) is currently at v0.1 over TCP+TLS 1.3. QUIC transport is planned for v2 with no protocol changes. Every wire message carries a `v` field; N-2 minor version backward compatibility is guaranteed. --- ## 2. Account Management ### Register Registration submits your Ed25519 (signing) and X25519 (key agreement) public keys. These let other members wrap GEK bundles for you and let nodes verify your JWT offline. **Deux modes de génération de clés :** **Mode CLI / native node** (`setup_demo.py`, `meshbay-node`) : Les clés sont *dérivées* de votre username + password via Argon2id — pas besoin de fichier de clés séparé. Même identifiants → mêmes clés sur n'importe quelle machine. Implémenté dans `meshbay_common.keyderive.derive_keys_from_password()`. ```python from meshbay_common.keyderive import derive_keys_from_password sk_ed, sk_x = derive_keys_from_password("alice", "MonMotDePasse!") ``` **Mode navigateur** (interface web) : Le navigateur génère des clés aléatoires via WebCrypto, les chiffre avec une clé dérivée du mot de passe (PBKDF2-SHA512), et envoie le bundle chiffré au hub. À la prochaine connexion, le hub retourne le bundle et le navigateur le déchiffre localement. Le hub stocke le bundle mais ne peut pas le lire. Implémenté dans `static/keyderive.js`. ``` POST /v1/users/register { "username": "string", "password": "string (min 8 chars)", "pk_user_ed25519": "base64 raw 32-byte Ed25519 public key", "pk_user_x25519": "base64 raw 32-byte X25519 public key", "keypair_bundle": "base64 AES-256-GCM encrypted bundle (web clients only, optional)" } → 201 {"user_id": "uuid"} → 409 if username is taken ``` Passwords are hashed with Argon2id (iterations=3, memory=64 MB in dev; target 256 MB / ~500ms in production). Intentionally slow to resist offline attacks. ### Login ``` POST /v1/users/login {"username": "yourname", "password": "yourpassword"} → { "access_token": "JWT (Ed25519, 1 hour validity)", "refresh_token": "opaque 256-bit token (30 days)", "token_type": "bearer", "expires_in": 3600, "keypair_bundle": "base64 AES-GCM blob (présent uniquement si enregistré via web)" } ``` Les clients web utilisent `keypair_bundle` pour récupérer leurs clés privées sur un nouvel appareil : déchiffrement local avec le mot de passe via `keyderive.js`. ```bash curl -s -X POST https://meshbay.org/v1/users/login \ -H "Content-Type: application/json" \ -d '{"username":"alice_test","password":"AliceTest2026!"}' ``` ### Token refresh Access tokens are valid for 1 hour. When one expires, use the refresh token to get a new one without re-entering your password: ``` POST /v1/users/token/refresh {"refresh_token": "your-refresh-token"} → {"access_token": "new JWT", "token_type": "bearer", "expires_in": 3600} ``` ```bash curl -s -X POST https://meshbay.org/v1/users/token/refresh \ -H "Content-Type: application/json" \ -d '{"refresh_token":"YOUR_REFRESH_TOKEN"}' ``` Refresh tokens are valid for 30 days and can be immediately invalidated by the hub on account compromise. Revoking the refresh token means the next access token renewal will fail; any active access token expires within 1 hour at most. ### Access token structure The JWT payload contains: | Claim | Value | |---|---| | `iss` | Hub ID (`meshbay.org`) | | `sub` | Your `user_id` (UUID4) | | `pk_user` | Your Ed25519 public key (base64) | | `hub_id` | `meshbay.org` | | `jti` | UUID4 — unique per token, enables revocation, prevents replay | | `iat` | Issued at (Unix timestamp) | | `exp` | Expires at (Unix timestamp, 1 hour from issue) | Nodes verify this JWT locally using the hub's cached Ed25519 public key. No hub roundtrip is needed — verified at 884µs in testing. This means your files remain accessible even if the hub is temporarily unreachable. --- ## 3. Groups Groups are the primary unit of organization. Every file on a node belongs to a group. ### Create a group ```bash TOKEN="your-access-token" curl -s -X POST https://meshbay.org/v1/groups \ -H "Content-Type: application/json" \ -H "Authorization: Bearer $TOKEN" \ -d '{"name": "my-group"}' ``` Response: ```json {"group_id": "uuid", "name": "my-group"} ``` Save `group_id` — you will need it in your `node.toml` and when adding members. ### Public vs. private groups | | Public | Private | |---|---|---| | File index | Plaintext + Ed25519 signed | GEK-encrypted, members only | | Content | TLS transport only (no application-layer encryption) | GEK-encrypted per chunk | | Join | Open / approval-gated | By invitation only | | GEK | Not applicable | Required | For private groups, the group admin generates a Group Encryption Key (GEK) — a random 32-byte ChaCha20-Poly1305 key. The GEK is never sent over the wire in cleartext. Instead, the admin wraps a copy of it for each member using that member's X25519 public key and stores the opaque bundle on the hub. ### Add a member to a private group The group admin fetches the new member's X25519 public key from the hub, wraps the GEK for them, and uploads the bundle: ```python import base64, httpx from cryptography.hazmat.primitives.asymmetric.x25519 import X25519PrivateKey, X25519PublicKey from cryptography.hazmat.primitives.ciphers.aead import ChaCha20Poly1305 from cryptography.hazmat.primitives.kdf.hkdf import HKDF from cryptography.hazmat.primitives import hashes, serialization import os HUB = "https://meshbay.org" GROUP_ID = "10484cb7-e45a-4cdc-8b06-f8ccdacc04d2" TOKEN = "alice_test-access-token" GEK_RAW = bytes.fromhex("your-32-byte-gek-in-hex") # load from keystore headers = {"Authorization": f"Bearer {TOKEN}"} # 1. Fetch new member's X25519 public key r = httpx.get(f"{HUB}/v1/users/bob_test/pubkeys", headers=headers) r.raise_for_status() pk_member_raw = base64.b64decode(r.json()["pk_x25519"]) # 2. Wrap GEK for them (ECIES-like) sk_eph = X25519PrivateKey.generate() pk_eph_raw = sk_eph.public_key().public_bytes( serialization.Encoding.Raw, serialization.PublicFormat.Raw) shared = sk_eph.exchange(X25519PublicKey.from_public_bytes(pk_member_raw)) wrap_key = HKDF(algorithm=hashes.SHA256(), length=32, salt=pk_eph_raw, info=b"meshbay:gek_wrap:v1").derive(shared) nonce = os.urandom(12) wrapped = ChaCha20Poly1305(wrap_key).encrypt(nonce, GEK_RAW, pk_member_raw) # 3. Upload the opaque bundle to the hub bundle = { "pk_eph_b64": base64.b64encode(pk_eph_raw).decode(), "nonce_b64": base64.b64encode(nonce).decode(), "wrapped_b64": base64.b64encode(wrapped).decode(), } r = httpx.post(f"{HUB}/v1/groups/{GROUP_ID}/members/bob_test/gek", json=bundle, headers=headers) r.raise_for_status() print("Bundle stored. bob_test can now access the group.") ``` The hub stores the bundle as an opaque blob. It cannot decrypt it — it stores `pk_eph`, `nonce`, and `wrapped` as separate columns but has no key to derive `wrap_key`. ### Member revocation To revoke a member: generate a new GEK, re-encrypt it for all remaining members, and upload the new bundles. The node begins encrypting new content with the new GEK from that point. Former members can still decrypt previously received content (no retroactive re-encryption). --- ## 4. Setting up a Node ### Configuration file Full `~/.config/meshbay/node.toml` reference: ```toml [hub] url = "https://meshbay.org" [auth] username = "yourname" password = "YourPassword123!" # Each group this node hosts gets its own [[groups]] block [[groups]] group_id = "uuid-of-your-group" shared_dir = "/srv/meshbay/my-group" [[groups]] group_id = "uuid-of-second-group" shared_dir = "/srv/meshbay/second-group" [node] # MNP listener port (must be internet-reachable) listen_port = 19001 # Local web UI port (loopback only, not exposed externally) ui_port = 18000 # Announce this address to the hub (auto-detected via STUN if not set) # endpoint_hint = "203.0.113.42:19001" [keystore] # "secure" — password prompt at each startup # "lazy_file" — password read from ~/.config/meshbay/unlock.key (chmod 600) # "service" — password read from MESHBAY_UNLOCK_KEY env var unlock_mode = "secure" path = "~/.config/meshbay/keystore.enc" [crypto] # Argon2id parameters for keystore password derivation. # Run `meshbay-node --calibrate-argon2` to tune for your hardware. # Target: ~500ms on your machine. argon2_iterations = 4 argon2_memory_cost = 262144 # 256 MB argon2_parallelism = 1 ``` ### Environment variables (alternative to node.toml) | Variable | Equivalent config | |---|---| | `MESHBAY_HUB_URL` | `[hub] url` | | `MESHBAY_USERNAME` | `[auth] username` | | `MESHBAY_PASSWORD` | `[auth] password` | | `MESHBAY_UNLOCK_KEY` | keystore unlock key (for `service` mode) | | `MESHBAY_LISTEN_PORT` | `[node] listen_port` | ### Keystore unlock modes The keystore is an Argon2id-derived AES-256-GCM encrypted file holding your Ed25519 and X25519 private keys plus GEK copies. **secure (default):** prompts for a password at startup. Suitable for interactive use. The password is not stored anywhere. **lazy_file:** reads the password from `~/.config/meshbay/unlock.key` (must be `chmod 600`). Use on a physically secure home server where you want unattended restarts. ```bash echo -n "YourKeystorePassword" > ~/.config/meshbay/unlock.key chmod 600 ~/.config/meshbay/unlock.key ``` **service:** reads the unlock key from the `MESHBAY_UNLOCK_KEY` environment variable. Standard practice for systemd deployments: ```ini # /etc/systemd/system/meshbay-node.service [Unit] Description=MeshBay Node After=network.target [Service] User=meshbay EnvironmentFile=/etc/meshbay/unlock.env # chmod 600, owned by meshbay ExecStart=/usr/bin/meshbay-node --config /etc/meshbay/node.toml Restart=on-failure [Install] WantedBy=multi-user.target ``` ```bash # /etc/meshbay/unlock.env (chmod 600, owned by meshbay user) MESHBAY_UNLOCK_KEY=YourKeystorePassword ``` ### Argon2id calibration The keystore password derivation is intentionally slow. Tune it to your hardware: ```bash meshbay-node --calibrate-argon2 ``` This prints the derivation time for several parameter combinations. Choose the set that gives ~500ms. The default (iterations=4, memory=256MB) is calibrated for a modern home server. ### Hardware sizing (upload bandwidth is the constraint) | Scenario | Simultaneous users | Upload needed | RAM | |---|---|---|---| | Files + chat, no streaming | 10 | 20–50 Mbps | 512 MB | | 1080p streaming, 5–6 streams | 10 | 50–80 Mbps | 1 GB | | Mixed, light streaming | 50 | 200–300 Mbps | 2 GB | | Heavy streaming | 50 | 400 Mbps | 2–4 GB | A standard home fiber line (100–500 Mbps symmetric) handles 10–30 concurrent users. Beyond that, a dedicated server is needed. --- ## 5. Sharing Files ### How indexing works The node watches `shared_dir` for file changes using filesystem events (`watchdog` library). When a file is added, modified, or removed: 1. The node computes `blake3(file)` as the file identifier 2. It builds or updates a Mesh Group Index entry for that file 3. The index entry is serialized as msgpack, compressed with zstd, then encrypted with the GEK (for private groups) or signed with the node's Ed25519 key (for public groups) 4. Connected members receive an index delta push; new connections receive the full index ### Index entry structure ```python { "version": 1, "id": "", # file identity and chunk key input "name": "filename.mkv", "path": "Movies/2024/", # relative path within shared_dir "size": 4294967296, # bytes "type": "video", # video | audio | image | document | archive | other "duration": 7245, # seconds (media files only) "thumb_hash": "", # thumbnail, also GEK-encrypted "added_at": 1720000000 # Unix timestamp } ``` ### Supported file types The node detects type by file extension and MIME sniffing: | Type | Extensions | |---|---| | `video` | mp4, mkv, avi, mov, webm | | `audio` | mp3, flac, ogg, opus, m4a | | `image` | jpg, jpeg, png, gif, webp, avif | | `document` | pdf, txt, md, epub, doc, docx, odt | | `archive` | zip, tar, gz, bz2, xz, 7z | | `other` | everything else | ### Files are stored in plaintext on disk The node holds your files in plaintext. Encryption happens at read time — the node encrypts each 1 MB chunk using a per-chunk key derived from the GEK before sending it over the wire. This means: - Disk-level encryption (LUKS, etc.) is your responsibility if you need at-rest protection - Backups of the shared directory are plaintext - Node compromise exposes all files in plaintext --- ## 6. Accessing Files ### Browse the index ``` GET /index Authorization: Bearer → [ {"id": "blake3hash", "name": "filename", "size": 1234, "type": "video"}, ... ] ``` ```bash curl -s -H "Authorization: Bearer $TOKEN" http://meshbay.org:19001/index | python3 -m json.tool ``` ### Download a full file ``` GET /file/{file_id} Authorization: Bearer → raw file bytes (Content-Type set by file type) ``` ```bash curl -s -H "Authorization: Bearer $TOKEN" \ http://meshbay.org:19001/file/ \ -o output.txt ``` For private groups, the returned bytes are the concatenated encrypted chunks. You must decrypt them client-side using the GEK (see the Quickstart download script for the full decryption flow). ### Download an encrypted chunk ``` GET /file/{file_id}/{chunk_index} Authorization: Bearer → { "ct_b64": "base64 ChaCha20-Poly1305 ciphertext", "nonce_b64": "base64 12-byte nonce", "file_hash_b64": "base64 blake3 of full file (HKDF salt input)", "chunk_index": 0, "plaintext_size": 1048576 } ``` Chunks are 1 MB. Chunk 0 is the first megabyte. For a 5 MB file, request chunks 0–4. **Per-chunk key derivation:** ```python chunk_key = HKDF( algorithm=hashes.SHA256(), length=32, salt=None, info=b"file:" + file_hash_bytes + b":chunk:" + chunk_index.to_bytes(4, "big") ).derive(gek) plaintext = ChaCha20Poly1305(chunk_key).decrypt(nonce, ciphertext, None) ``` Each chunk has an independent key derived from the GEK and the chunk's position. This enables seeking in media files without decrypting from the start. ### Node info endpoint ``` GET / → { "file_count": 2, "pk_node": "base64 Ed25519 public key", "group_id": "uuid" } ``` The node's Ed25519 public key (`pk_node`) is also what nodes use for TLS certificate pinning. Clients retrieve it from the hub via `GET /v1/nodes/{node_id}` and validate the node's self-signed TLS cert against it. --- ## 7. Video Streaming The node generates HLS (HTTP Live Streaming) segments on the fly for video files. ### HLS endpoint ``` GET /stream/{file_id}/index.m3u8 Authorization: Bearer → M3U8 playlist with segment URLs ``` Each segment is a GEK-encrypted 1 MB chunk served as `application/octet-stream`. The browser-side player must decrypt segments before handing them to the media element. ### Play in a browser Because segments are encrypted, a standard `