# 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 creates an account and nothing else: a username, an email, and a value derived from your passphrase that lets the hub check it without ever seeing it. **No keys are generated here.** An identity keypair belongs to a *node*, not to the hub: one is created the first time you join a given node, encrypted under your passphrase, and left with that node. So an operator who takes their own disk holds a key that is worthless on anyone else's, and the hub has no key directory to publish — which is what finding H3 read. **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", "email": "string", "auth_key": "base64 (PBKDF2-SHA512 of your passphrase — the hub never sees the passphrase itself)" } → 201 {"user_id": "uuid"} → 409 if username is taken ``` 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, } ``` Le trousseau ne vient pas d'ici : chaque nœud conserve celui qui lui est propre, chiffré par votre phrase de passe, et un nouveau navigateur le récupère auprès du nœud auquel il se connecte. ```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 node holds a Group Encryption Key (GEK) — a random 32-byte key that is never sent over the wire in cleartext. Each member receives a copy wrapped for their own X25519 public key (ECIES: X25519 + HKDF + AEAD). **The node does the wrapping, and it never asks the hub for anybody's key.** That matters: the hub is the account directory, so a hub that answered a key lookup with its own key would be handed the group key by an honest member following the protocol exactly (finding H3). Instead the recipient presents their own public keys over the authenticated P2P channel, signed by their identity key, and the node wraps for what it just verified. ### Add a member to a private group The node operator issues a one-time code, from the server or from their browser: ```bash # On the node, over SSH — no browser needed meshbay-node member invite bob INVITATION CODE R3H8-TB6V valid until 2026-08-21T12:00:00+00:00 ``` Send the code to Bob however you already talk to him — it never passes through the hub, which is what stops the hub from claiming to be Bob. He enters it the first time he opens the group, and the node then wraps the group key for the key he proved he holds. After that first time the pin is his credential: he is recognised on every later connection, and asked for nothing. You do not need to be online when he joins. | | | |---|---| | Code lifetime | 7 days (`[node] invite_ttl_hours`) | | Reuse | Single use; re-inviting supersedes the previous code | | If it expires | Issue another one — nothing else is affected | | Wrong code, repeatedly | Bounded per connection and node-wide, and logged in the node's audit log | The same operation is available in the web app: the group's **Members** tab, if your browser is paired with the node (`meshbay-node operator pair`). ### Removing a member ```bash meshbay-node member revoke bob meshbay-node gek-init # rotate: Bob still holds the old key ``` Revoking stops the node serving Bob the key from his next connection onward — there is no stored bundle left behind that could outlive the decision. It does **not** take back the key he already has, which is why the second command exists. ### What revocation does and does not do Rotating the GEK (`meshbay-node gek-init`) makes the node encrypt new content with a new key, which every remaining member picks up automatically on their next connection — nothing has to be re-uploaded or re-wrapped by hand. A former member can still decrypt content they already received: there is no retroactive re-encryption, and there is no way to reach into someone's disk. Revocation controls what happens next, not what already happened. --- ## 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 `