Skip to content
addyPublic

About

Decentralized chat

Resources

Stars

3 stars

Watchers

0 watching

Forks

Latest commit

 

History

38 Commits

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

mesh-node

A self-healing peer-to-peer mesh network with forward-secret end-to-end encrypted chat and P2P file transfer, built in Rust.

Nodes form a degree-constrained graph (2–3 connections each), propagate authenticated membership state via signed Scuttlebutt anti-entropy gossip, disseminate group messages via Plumtree epidemic broadcast trees, and auto-discover peers on LAN (mDNS) or connect across NATs over iroh 1.0 QUIC with automatic hole-punching and relay fallback.

The encrypted chat & file layer provides:

  • Forward-secret E2EE: pairwise X3DH + Double Ratchet for direct messages (with post-compromise security) and Epoch-Ratcheted Sender Keys for O(1) broadcast & #room messaging with automatic epoch rotation on key revocation
  • E2EE P2P file transfer (mesh-node/file/1): chunked 64 KiB ChaCha20-Poly1305 encrypted transfers over secondary QUIC streams (zero head-of-line blocking), constant-time SHA-256 verification, strict filename sanitization, and DM/group sender authorization
  • Zero-friction onboarding: one-step mesh-invite://v1/... invite bundles (carrying seed, founder key, optional custom relay/discovery, and bounded-use join token) plus live host Knock-to-Join approval (F5 / /approve)
  • Delegated trust & key lifecycle: Founder → Admin → Member signed delegation chains persisted in a durable TrustStore, active mesh-wide revocation eviction, and dual-signed planned KeyRotation
  • Rich messaging & presence: #rooms, dedicated @peer DM panes, threaded /reply, /react, sender-verified /edit & /delete, DM delivery ACKs (✓ → ✓✓), ephemeral typing indicators, /status presence, /search (Ctrl+F), and out-of-band SAS safety-number verification (/verify)
  • Encrypted at rest: MKS1 passphrase-encrypted identity backups (PBKDF2-HMAC-SHA256 + ChaCha20-Poly1305), MCH2 encrypted local history (0600), multi-profile isolation (--profile), and strict zero-retention ephemeral_mode
  • Live diagnostics: 5-stage mesh-node doctor / --diagnose preflight check, per-peer direct/relayed path & RTT telemetry ([D 12ms] / [R 72ms]), and live /diag (F6) popup

Quick Start

Prerequisites

  • Rust 1.91+ (iroh 1.0 MSRV — install via rustup)
  • No VPN required for remote chat — iroh handles NAT traversal (hole-punching) and relay fallback in-process

Build

git clone <repo-url> && cd mesh-node
cargo build --release

This produces three binaries:

  • target/release/mesh-chat-tui — Full interactive terminal UI (recommended)
  • target/release/mesh-chat — Scriptable CLI & headless --json NDJSON bot client
  • target/release/mesh-node — Headless mesh node / bootstrap daemon & doctor preflight tool

Zero-Friction Onboarding

Option A: One-Step Invite Bundle (Recommended)

1. Alice starts a new mesh:

mesh-chat-tui

On first launch, the setup wizard creates Alice's Ed25519 identity (0600), pins her public key as Founder, asks for her nickname, leaves seed empty, and starts the node in the background (so the TUI renders immediately and Ctrl+C always exits cleanly).

Alice mints a single-use (or bounded-use) invite link:

/invite-link
# or with custom uses/expiry or omitting a custom relay token:
/invite-link 3 60 --no-relay-token

(Or press F3 → i or F4 → i to copy the link via OSC 52.)

2. Bob joins in one command:

mesh-chat-tui --nick bob --join "mesh-invite://v1/..."
# or in the CLI client:
mesh-chat --nick bob --join "mesh-invite://v1/..."

Or Bob simply launches mesh-chat-tui and pastes the mesh-invite://v1/... link at Step 1 of the setup wizard. The bundle configures seed, pinned founder key, custom relay/discovery (if any), and the single-use join token (kept in RAM only, never saved to disk) — Bob connects and is admitted immediately.

Option B: Host Knock-to-Join (Ticket / LAN mDNS)

  1. Alice shares her node ticket (F3 → t, or /ticket). On a LAN, Bob needs no ticket at all — mDNS discovers Alice automatically.
  2. Bob pastes Alice's ticket in Step 1 of the setup wizard (if Alice uses a custom relay not in Bob's config, the wizard detects the mismatch and prefills Step 2 with Alice's relay URL).
  3. Bob's node connects and knocks in invite-only mode; Bob sees a status banner (Waiting for invite/approval from host...).
  4. Alice's status bar flashes F5 knocks(1). Alice presses F5 (or runs /approve bob / /deny bob), approves Bob, and her node immediately gossips the signed invitation and dials Bob back for instant admission.

Preflight Diagnostics (doctor / --diagnose)

Before or during troubleshooting connectivity, run the 5-stage self-check:

mesh-node doctor --seed <ticket>
# or on any binary:
mesh-node --diagnose --relay https://relay.example.com
mesh-chat --diagnose --seed <ticket>
mesh-chat-tui --diagnose --profile work

doctor checks:

  1. UDP socket bind (IPv4/IPv6 ephemeral or pinned port)
  2. Relay reachability & authentication (with fast early detection of token/auth denials)
  3. QUIC Address Discovery (QAD) / public IP & NAT observation
  4. Address lookup (n0/pkarr) & LAN mDNS status
  5. Optional seed probe (relay mismatch warning, path type direct vs relayed, and live RTT)

Inside a running TUI, press F6 (or Alt+D, /diag) for live bound sockets, relay health, seed backoff state, and per-peer [D 12ms] / [R 72ms] path telemetry.


TUI Keybindings & Slash Commands (mesh-chat-tui)

Keybindings

Key Action
F1 / Alt+H Help popup
F2 / Alt+M Scrollable Members popup (live [D/R/mesh] path badges, verified ✓, /status)
F3 / Alt+E Your Identity popup (unbroken 64-char pubkey, ticket, [i] invite link, [t] copy ticket, [k] copy key)
F4 / Alt+I Invite popup (64-hex counter, [i] mint one-step invite link)
F5 / Alt+K Pending Knock-to-Join requests popup (y/Enter approve, n/d deny)
F6 / Alt+D Live Network Diagnostics popup (r refresh, Up/Down/PgUp/PgDn scroll)
Alt+1..9 Switch conversation pane by index
Ctrl+N / Ctrl+P (Alt+Left/Right) Cycle next / previous conversation pane (#general, #rooms, @peer DMs)
Ctrl+F Search messages popup (Enter jumps to pane & highlights message)
Alt+S Toggle members sidebar (also auto-hides on narrow terminals < 70 cols)
Tab Autocomplete /commands, #rooms, @nick mentions, and member arguments
Up / Down Cycle sent input history (50-entry ring buffer)
PgUp / PgDn (Alt+Up/Down) Scroll history by page / 1 line (Ctrl+Home/End top/bottom; unread badge when scrolled up)
Ctrl+W / Ctrl+U / Esc Delete previous word / clear line / clear input or dismiss banner/popup
Ctrl+C Quit gracefully (works immediately even during startup)

Slash Commands

Command Description
/join <#room> / /part Open/switch to a #room pane, or close the current non-general pane
/dm <nick|hex> [msg] Open a dedicated @peer DM pane, optionally sending a DM immediately
/reply <id> <text> Reply to a message by its #4-hex ID prefix
/react <id> <emoji> Add or toggle an emoji reaction on a message
/edit <id> <new_text> Edit your own message (sender-verified across peers)
/delete <id> Delete/tombstone your own message (sender-verified across peers)
/search [query] Search local messages across panes (Ctrl+F)
/verify <nick|hex> Open SAS safety-number & 4-emoji verification popup (v toggles persisted ✓)
/status [text] Set or clear your Scuttlebutt presence status
/send [nick|hex] <path> Offer an E2EE file transfer to the active pane, or DM a specific member
/accept <id_prefix> [dest_dir] Accept & download a pending file asynchronously (status bar progress bar)
/decline <id_prefix> Decline a pending file offer and zeroize its transfer key
/transfers List active downloads and pending file offers
/invite-link [uses] [ttl_min] [--no-relay-token] Mint & copy a mesh-invite://v1/... bundle
/invite [64-char-hex] Open invite popup or invite a peer directly by public key
/approve <nick|hex> / /deny <nick|hex> Approve or deny (10m mute) a pending knock-to-join request
/knocks Open the pending join requests popup (F5)
/seed add <ticket> | list | remove <n> Manage bootstrap seed peers at runtime (persisted to config.toml)
/reconnect Reset seed/LAN backoffs and redial immediately
/diag Open live network & path diagnostics (F6)
/export-key <path> Export an MKS1 passphrase-encrypted identity backup (masked prompt or MESH_KEY_PASSPHRASE)
/nick <new_nick> Change your display nickname at runtime (persisted & gossiped)
/revoke <nick|hex> Permanently revoke a peer's key (with [y/N] confirmation popup)
/members / /me / /ticket Open members / identity popup, or copy node ticket
/clear / /help / /quit Clear view / open help / quit (prefix with // to send a literal /... message)

CLI Reference & Headless Bot Mode

mesh-chat-tui Flags

mesh-chat-tui --profile work --nick alice --wan
mesh-chat-tui --profile test2 --join "mesh-invite://v1/..." --nick bob
mesh-chat-tui --no-invite-only --no-relay --discovery none
mesh-chat-tui --reset-config             # deletes config.toml only (never identity.key)
mesh-chat-tui --diagnose                 # 5-stage preflight check without entering TUI

# Encrypted identity backup & restore (passphrase read ONLY from MESH_KEY_PASSPHRASE, never argv):
MESH_KEY_PASSPHRASE='...' mesh-chat-tui --profile work --export-identity backup.mks1
MESH_KEY_PASSPHRASE='...' mesh-chat-tui --profile work --import-identity backup.mks1

Key flags: --profile <NAME>, --config-dir <PATH>, --nick <NICK>, --seed <TICKET> (repeatable), --join <INVITE_BUNDLE>, --wan, --no-invite-only, --reset-config, --diagnose, --export-identity <OUT>, --import-identity <IN>, plus shared network flags (--relay, --no-relay, --relay-quic-port, --discovery, --pkarr-relay, --dns-origin, --no-mdns).

mesh-chat CLI & --json Headless Bot Mode

# Persistent identity (raw 32-byte seed or MKS1 encrypted keystore unlocked via MESH_KEY_PASSPHRASE)
mesh-chat --nick alice --identity-file ~/.config/mesh-chat/identity.key --invite-only

# Join via invite bundle
mesh-chat --nick bob --join "mesh-invite://v1/..."

# Headless NDJSON bot mode (newline-delimited JSON events on stdout, JSON commands on stdin)
mesh-chat --nick bot --identity-file ./bot.key --seed <ticket> --json

Interactive commands include /dm, /room, /send, /accept, /decline, /transfers, /status, /verify, /invite-link, /invite, /approve, /deny, /knocks, /revoke, /seed, /reconnect, /members, /diag, /me, /quit, and //<literal>.

In --json mode, mesh-chat emits single-line JSON events (ready, chat, delivered, typing, file_offer, file_progress, file_complete, file_failed, join, leave, died, revoked, key_rotated, rejected, knock, members, diag, verify, invite_link, ok, error) and accepts NDJSON commands on stdin:

{"cmd":"broadcast","text":"hello mesh"}
{"cmd":"room","room":"ops","text":"deploying v2"}
{"cmd":"dm","to":"bob","text":"secret"}
{"cmd":"reply","channel":"room","room":"ops","reply_to":"<32-hex>","text":"ack"}
{"cmd":"react","channel":"broadcast","target":"<32-hex>","emoji":"👍"}
{"cmd":"edit","channel":"broadcast","target":"<32-hex>","text":"corrected"}
{"cmd":"delete","channel":"broadcast","target":"<32-hex>"}
{"cmd":"typing","channel":"direct","to":"bob"}
{"cmd":"send_file","to":"bob","path":"/path/to/archive.tar.gz"}
{"cmd":"accept_file","transfer_id":"<hex-prefix>","dest_dir":"/tmp/downloads"}
{"cmd":"decline_file","transfer_id":"<hex-prefix>"}
{"cmd":"status","status":"away: lunch"}
{"cmd":"verify","peer":"bob"}
{"cmd":"invite_link","uses":1,"ttl_mins":15}
{"cmd":"approve","peer":"carol"}
{"cmd":"members"}
{"cmd":"diag"}
{"cmd":"quit"}

mesh-node Headless Daemon & doctor

# 5-stage preflight diagnostics
mesh-node doctor --timeout 5 --seed <ticket>
mesh-node --diagnose --relay https://relay.example.com

# Stable headless bootstrap node with identity backup/restore
mesh-node --identity-file /var/lib/mesh-node/identity.key --port 9000 --wan --require-invitation
MESH_KEY_PASSPHRASE='...' mesh-node --identity-file /var/lib/mesh-node/identity.key --export-identity node.mks1
MESH_KEY_PASSPHRASE='...' mesh-node --identity-file /var/lib/mesh-node/identity.key --import-identity node.mks1

Configuration & Storage

Profile Directory & Files

mesh-chat-tui stores files under the platform-native config directory (dirs::config_dir()/mesh-chat/profiles/<profile>/, with automatic backward compatibility for legacy ~/.config/mesh-chat/ files on the default profile):

File Permissions Purpose
identity.key 0600 32-byte Ed25519 seed (or MKS1 encrypted keystore unlocked via MESH_KEY_PASSPHRASE). Back this up. Never overwritten if unreadable or malformed
config.toml 0600 Nickname, require_invitation, founder_pub_key, seed_peers, verified_peers, notifications, [relay], [discovery]
history.bin 0600 Append-only MCH2 ChaCha20-Poly1305 encrypted chat history (auto-migrates legacy plaintext history; auto-compacts at cap)
trust.bin 0600 Atomic durable TrustStore persisting verified invitations, revocations, and key rotations
known_peers.toml 0600 Up to 8 recently seen peers cached as fallback bootstrap seeds
mesh-chat.log 0600 Profile-scoped diagnostic log file

config.toml Example

nick = "alice"
wan_mode = false
require_invitation = true
notifications = true
founder_pub_key = "a1b2c3..."
seed_peers = [
    "endpointbob1234laptop...",
]
verified_peers = [
    "d4e5f6...",
]

[relay]
mode = "custom"                   # default | disabled | custom
urls = ["https://relay.example.com"]
auth_token = "…"                  # optional; env MESH_RELAY_TOKEN overrides
quic_port = 7842                  # optional (QUIC address discovery)

[discovery]
mode = "n0"                       # n0 | custom | none
# pkarr_relay = "https://dns.example.com/pkarr"   # required for custom
# dns_origin = "dns.example.com"                  # optional, needs NS delegation
mdns = true

Custom Relay & Address Lookup

By default nodes use n0's public relays and DNS/pkarr address lookup. You can point a mesh at your own iroh-relay (optionally token-gated via MESH_RELAY_TOKEN) and/or self-hosted iroh-dns-server. Relay mode and address lookup are independent (--no-relay still uses n0 DNS unless --discovery none is also set). Invalid combinations fail loudly at startup rather than silently falling back to n0.

Tickets don't carry tokens (whereas mesh-invite://v1/... bundles optionally include the relay token unless --no-relay-token is passed). Every node using a token-gated relay must configure that relay URL and token.

MeshConfig (Library)

Field Default Description
bind_addr None Optional fixed UDP socket (None = ephemeral; port-only binds both IPv4 & IPv6 with fallback)
relay_mode RelayMode::Default Default, Disabled, or Custom(RelayMap)
address_lookup AddressLookupMode::N0 N0, Custom { pkarr_relay, dns_origin }, or None
relay_ca_tls None Custom TLS roots for relays / pkarr
enable_mdns true LAN mDNS auto-discovery
seed_peers [] Bootstrap peers (Vec<EndpointTicket>)
min_degree / max_degree 2 / 3 Target direct connection degree bounds
keypair_seed None Deterministic 32-byte Ed25519 seed (zeroized immediately after derivation)
require_invitation false Require signed invitation (or valid join token) on incoming links
founder_pub_key None Optional pinned Founder public key (mesh_id root of trust)
trust_store_path None Optional path for durable 0600 TrustStore persistence
initial_nick None Initial display nickname sent in ConnectRequest knock hints
join_token None Optional 32-byte single/bounded-use join token (RAM-only, zeroized after use)
ephemeral_mode false Strict zero-retention forward secrecy (no in-memory history, refuses SyncRequest)
max_file_size_bytes 50 MiB Maximum offered or accepted file transfer size
gossip_interval / heartbeat_interval 1s / 500ms Scuttlebutt digest round & heartbeat intervals
phi_threshold / ghost_timeout 8.0 / None Phi accrual failure detection threshold & < MIN_SAMPLES ghost expiry
rebalance_interval / ihave_timeout 5s / 500ms Topology rebalance & Plumtree IHave graft timeout
connect_timeout / startup_readiness_timeout 10s / 8s Outbound connect & startup readiness bounds

Library API

use std::path::Path;
use mesh_node::chat::message::Channel;
use mesh_node::{ChatContent, MeshConfig, MeshEvent, MeshNode};

let node = MeshNode::start(MeshConfig {
    keypair_seed: Some(seed),
    require_invitation: true,
    founder_pub_key: Some(founder_pk),
    ..Default::default()
}).await?;

// Identity — NodeId == iroh EndpointId == Ed25519 public key
node.set_nick("alice").await?;
node.set_status("online").await?;
let ticket = node.ticket();

// Forward-secret E2EE chat (Double Ratchet DMs, Epoch Sender Keys Broadcast/Rooms)
node.send_chat(b"hello everyone").await?;
node.send_room_chat("ops", b"release ready").await?;
node.send_direct_chat(peer_id, b"private message").await?;

// Structured rich messaging inside E2EE ciphertext
let reply = ChatContent::Text { body: "agreed!".into(), reply_to: Some(target_msg_id) }.encode()?;
node.send_chat(&reply).await?;

// E2EE P2P file transfer over secondary mesh-node/file/1 QUIC streams
let offer = node.offer_file(Channel::Direct(peer_id), Path::new("report.pdf")).await?;
let pending = node.pending_file_offers().await;
let saved_path = node.accept_file(offer.transfer_id, Path::new("./downloads")).await?;

// Onboarding, trust, key rotation, and live diagnostics
let invite_uri = node.create_invite_bundle(1, std::time::Duration::from_secs(900), None, None, Some("alice".into())).await?;
node.approve_join(knocking_peer).await?;
node.revoke(compromised_pk).await?;
let diag = node.diagnostics().await;

// Events
let (mut events, initial_members) = node.subscribe_with_members().await;
while let Ok(event) = events.recv().await {
    match event {
        MeshEvent::ChatMessageReceived { sender_pub_key, channel, plaintext, .. } => { /* ... */ }
        MeshEvent::FileOfferReceived { transfer_id, filename, size, .. } => { /* ... */ }
        MeshEvent::FileTransferCompleted { path, bytes, .. } => { /* ... */ }
        MeshEvent::JoinRequested { peer, nick } => { /* ... */ }
        MeshEvent::MessageDelivered { peer, msg_id } => { /* ... */ }
        _ => {}
    }
}

node.shutdown().await?;

Architecture & Wire Protocol

MeshNode (orchestrates lifecycle, public API, FileTransferManager)
  │
  ├─ IrohTransport (iroh 1.0 QUIC Endpoint + multi-ALPN Router)
  │    ├─ ALPN "mesh-node/2"       ──► per-peer framed bi-stream ──► MessageRouter
  │    │                                                              ├─► MembershipActor (signed Scuttlebutt + TrustStore + phi)
  │    │                                                              ├─► PlumtreeActor (epidemic broadcast tree + Message::Direct)
  │    │                                                              └─► TopologyActor (graph + rebalance + admission + knocks)
  │    └─ ALPN "mesh-node/file/1"  ──► FileProto (admitted + Semaphore(4)) ──► FileTransferManager (64 KiB AEAD chunked streams)
  ├─ ChatActor (X3DH + Double Ratchet DMs, Epoch Sender Keys Broadcast/Rooms, authentic paginated sync, FileOffer registration)
  ├─ DiscoveryActor (mDNS LAN + seed-ticket dial + dynamic runtime seeds + exponential backoff)
  └─ Event Bus (broadcast channel) ◄── all actors emit/subscribe

Wire Protocols

ALPN Category Messages / Framing
mesh-node/2 Scuttlebutt ScuttlebuttDigest, ScuttlebuttDelta (Ed25519-signed KV entries & TrustRecords)
mesh-node/2 Plumtree Gossip, IHave, Graft, Prune, Direct (authenticated point-to-point)
mesh-node/2 Topology / Lifecycle ConnectRequest (nick hint + optional join token), ConnectAccept, ConnectReject(RejectReason), Leave
mesh-node/2 Chat (0xC4 magic) RatchetDirect (X3DH + Double Ratchet), SenderKeyDist, SenderKeyChat, SenderKeyRequest, Chat (hybrid-DEK ECIES v2 fallback), SyncRequest, SyncResponse, DeliveryAck, Typing
mesh-node/file/1 File Transfer [u32 len][FileStreamRequest] → [u8 status] → [u32 ct_len][u8 is_final][ChaCha20-Poly1305(chunk, nonce(idx), AAD)]*

Security Model

  • Identity & Encrypted Keystore (MKS1): Each node has a single Ed25519 identity (NodeId == iroh EndpointId == chat/trust pubkey). identity.key is created 0600 and supports both raw 32-byte seeds and versioned MKS1 passphrase-encrypted keystores (PBKDF2-HMAC-SHA256 600k iterations + random 16-byte salt + ChaCha20-Poly1305, unlocked via MESH_KEY_PASSPHRASE, never via CLI argv). All key material is zeroized on drop (zeroize).
  • Forward-Secret Direct Messages (X3DH + Double Ratchet): Nodes publish Ed25519-signed rotatable X25519 prekey bundles via Scuttlebutt (prekey, max 2 secrets in RAM). Pairwise DMs use X3DH + Double Ratchet with contributory DH checks, HKDF/HMAC KDF chains, bounded skipped-key buffers (100 keys, max skip 64, 24h TTL), simultaneous-initiation tie-breaking, replay rejection, and graceful ECIES v2 fallback before prekeys converge.
  • Forward-Secret Broadcast & Rooms (Epoch-Ratcheted Sender Keys): Group messages use O(1) symmetric chain-ratcheted ChaCha20-Poly1305 AEAD + dual Ed25519 author_sig & envelope_sig, with Sender Key distribution encrypted pairwise over Double Ratchet (or ECIES v2 fallback) and automatic epoch rotation on peer revocation, 500 messages, or 24h (zeroizing old chain keys so revoked members cannot decrypt future messages).
  • Delegated Trust, Active Revocation & Key Rotation: TrustStore (trust.bin, 0600) evaluates signed Invitation, Revocation, and dual-signed KeyRotation records with revocation-first fixed-point semantics over a Founder → Admin → Member hierarchy (when founder_pub_key is pinned). Revocations immediately evict active peers across topology, Plumtree, chat, and file transfers. Planned KeyRotation transfers authority to a new key and retires the old key while preserving the historical invitation DAG.
  • Authenticated Gossip & Sync: Every Scuttlebutt entry is Ed25519-signed and version-monotonic. Paginated history sync serves only Broadcast/Room messages (never private DMs), verifies original author_sig on every synced record, and is completely disabled in ephemeral_mode.
  • E2EE File Transfer (mesh-node/file/1): Per-transfer random 32-byte ChaCha20-Poly1305 keys travel end-to-end inside the Double Ratchet / Sender Key ChatContent::FileOffer ciphertext. Secondary QUIC streams enforce peer admission, non-revocation, DM recipient-only authorization, a 4-stream concurrency semaphore, configurable size caps (50 MiB default), per-chunk AAD (mesh-file-v1: + transfer_id + idx + is_final), constant-time SHA-256 verification, cross-platform filename sanitization, 0600 .part staging with immediate cleanup on tamper/error, and non-overwriting atomic rename.
  • Encrypted Local History (MCH2) & DoS Hardening: TUI history is encrypted at rest (MCH2, per-record AEAD, 0600). Wire framing enforces a 256 KiB frame cap, admission gates block unadmitted gossip/direct/file traffic, transport sends are mutex-free with bounded timeouts, sync/typing/knock queues are rate-limited and bounded, and remote strings are stripped of ANSI escape sequences and control characters before terminal rendering.

Testing

# All tests (hermetic, parallel, 100% offline)
cargo test --offline --locked

# Individual suites
cargo test --lib
cargo test --test integration
cargo test --test relay
cargo test --bin mesh-chat-tui
cargo test --bin mesh-chat

Integration tests are hermetic (loopback bind, relays + mDNS + address lookup disabled, seed-ticket bootstrap) and run cleanly in parallel. Relay tests spin up in-process token-gated iroh-relay and pkarr servers (dev-dependencies only).

Test Coverage (296 passed, 0 failed, 1 ignored, 0 warnings)

  • 188 library unit tests (src/lib.rs): Ed25519/X25519/HKDF/PBKDF2/ECIES/SAS crypto, MKS1 keystore, X3DH + Double Ratchet + Epoch Sender Keys, ChatContent rich payloads & FileOffer, file_transfer filename sanitization / non-overwrite / chunk AEAD & tamper rejection, TrustStore delegation/revocation/KeyRotation, signed Scuttlebutt anti-entropy, phi accrual + ghost expiry, Plumtree state machine, mesh-node/2 codec bounds, MessageRouter spoofing/admission gates, lock-free transport, netcfg / mesh-invite://v1 bundles, and 5-stage doctor diagnostics
  • 54 mesh-chat-tui unit & TestBackend tests: UTF-8/emoji TextInput, wrapped-row scroll, setup wizard + relay mismatch + invite bundle parsing, multi-profile isolation, MCH2 encrypted history & legacy migration, multi-pane routing, rich messaging mutations, /search, /verify, /knocks, /diag, /send//accept//decline//transfers, and live file progress bar rendering
  • 5 mesh-chat CLI/JSON unit tests: ANSI sanitization, member disambiguation, --join/--diagnose CLI parsing, and full NDJSON command & event round-trips (including file transfer commands & events)
  • 1 mesh-node CLI unit test: doctor subcommand & --diagnose flag parsing
  • 42 integration tests (tests/integration.rs) (+1 #[ignore]d n0 relay smoke test needing internet): lifecycle, bootstrap, cluster formation, Plumtree broadcast, graceful leave & restart recovery, dual-stack --port bind, unadmitted injection & spoofing rejection, active revocation eviction, Chat v2 & #rooms, DM privacy & delivery ACKs, typing & /status presence, one-step mesh-invite://v1 bundles, knock-to-join approve/deny, live diagnostics(), multi-turn Double Ratchet DMs, post-revocation Epoch Sender Key exclusion, ephemeral FS mode, dual-signed KeyRotation, multi-chunk E2EE DM file transfer round-trip, and 3-node file transfer authorization & size-cap security
  • 6 in-process relay tests (tests/relay.rs): token-gated relay auth success/refusal, relay-map token isolation, custom pkarr address lookup, and doctor Stage 2 relay auth pass/fail

Project Structure

mesh-node/
├── Cargo.toml
├── src/
│   ├── lib.rs                      # Public library API re-exports
│   ├── main.rs                     # mesh-node CLI binary & `doctor` subcommand
│   ├── config.rs                   # MeshConfig, AddressLookupMode
│   ├── netcfg.rs                   # Seeds, RelaySettings, DiscoverySettings, InviteBundleV1, NetArgs
│   ├── diag.rs                     # 5-stage run_doctor, NodeDiagnostics, PeerLinkDiag, RelayDiag
│   ├── node.rs                     # MeshNode orchestrator & public async API
│   ├── identity.rs                 # NodeId (= iroh EndpointId), NodeInfo
│   ├── event.rs                    # MeshEvent enum
│   ├── error.rs                    # MeshError & Result
│   ├── crypto.rs                   # Ed25519, X25519, HKDF-SHA256, PBKDF2-HMAC-SHA256, ECIES, SAS
│   ├── keystore.rs                 # MKS1 authenticated passphrase-encrypted identity keystore
│   ├── ratchet.rs                  # SignedPreKeyBundle, X3DH + DoubleRatchet, Epoch Sender Keys
│   ├── file_transfer.rs            # mesh-node/file/1 E2EE chunked P2P file transfer engine
│   ├── invitation.rs               # Invitation, Revocation, KeyRotation, Role, TrustRecord
│   ├── router.rs                   # Admission-gated stateless iroh message demuxer
│   ├── protocol/
│   │   ├── codec.rs                # Bounded length-prefixed bincode framing (256 KiB cap)
│   │   └── messages.rs             # Wire Message enum, RejectReason, SignedScuttlebuttEntry
│   ├── chat/
│   │   ├── actor.rs                # ChatActor: Double Ratchet, Sender Keys, sync, typing, FileOffer
│   │   ├── content.rs              # Versioned in-ciphertext ChatContent (Text/Reaction/Edit/Delete/FileOffer)
│   │   ├── message.rs              # Channel, wire envelopes, canonical AAD & signing bytes
│   │   └── history.rs              # Bounded deduplicated paginated in-memory chat history
│   ├── membership/
│   │   ├── actor.rs                # Signed Scuttlebutt gossip, TrustStore, JoinTokenStore, MembershipQuery
│   │   ├── state.rs                # Signed per-node ScuttlebuttState KV namespaces
│   │   ├── trust.rs                # Durable Founder/Admin/Member TrustStore & KeyRotation evaluation
│   │   └── phi.rs                  # Phi accrual failure detector + ghost expiry
│   ├── plumtree/
│   │   ├── actor.rs                # Plumtree epidemic broadcast + authenticated Message::Direct
│   │   └── state.rs                # Eager/lazy peer sets, IHave timers, bounded message cache
│   ├── topology/
│   │   ├── actor.rs                # Connect/leave/rebalance, invitation/token gate, knock-to-join queue
│   │   ├── departed.rs             # Bounded recently-departed peer tracking
│   │   └── graph.rs                # Degree-constrained adjacency graph
│   ├── discovery/
│   │   └── actor.rs                # mDNS LAN discovery, seed-ticket dial, runtime seed management
│   ├── transport/
│   │   └── iroh.rs                 # iroh 1.0 Endpoint + multi-ALPN Router (mesh-node/2 & mesh-node/file/1)
│   ├── model/                      # Optional Stateright formal model-checking suite (--features model-check)
│   └── bin/
│       ├── mesh_chat.rs            # Interactive CLI & --json headless NDJSON bot client
│       ├── model_check.rs          # Stateright model checker binary
│       └── mesh_chat_tui/          # Full interactive TUI client (ratatui)
│           ├── main.rs             # clap TuiArgs, --profile, --diagnose, --export/import-identity
│           ├── app.rs              # Non-blocking App state, panes, commands, transfers, events
│           ├── config.rs           # Profile dirs, config.toml, MCH2 encrypted history, known_peers
│           └── ui/
│               ├── chat.rs         # Tab bar, wrapped messages, progress bar, responsive sidebar
│               ├── input.rs        # UTF-8/emoji-safe scrolling TextInput widget
│               ├── popup.rs        # Invite, Members, Knocks, Diag, Search, Verify, ExportKey, Help, Identity
│               ├── setup.rs        # First-run wizard (invite bundles, relay mismatch, masked token)
│               └── theme.rs        # Color palette & deterministic nick colors
└── tests/
    ├── integration.rs              # 42 hermetic multi-node integration tests (+1 ignored n0 smoke test)
    └── relay.rs                    # 6 in-process custom relay, token, pkarr & doctor tests

About

Decentralized chat

Resources

Stars

3 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages