Mesh Network
v1.5.0WebSocket-based peer-to-peer mesh infrastructure
The YAKMESH mesh network provides the communication backbone for all peer-to-peer operations. Built on WebSockets with quantum-resistant cryptography, gossip protocols, and onion routing.
"Your packets travel like yak caravans through hidden mountain paths"
The mesh network is designed for resilience, privacy, and decentralization. No central servers, no single points of failure — just nodes cooperating through cryptographic trust.
Quick Start
Create and start a mesh network node:
import { MeshNetwork, MessageTypes } from './mesh/network.js';
// Create mesh network with your node identity
const mesh = new MeshNetwork(identity, {
wsPort: 9001, // WebSocket port (auto-fallback if in use)
maxPeers: 10, // Maximum concurrent peer connections
pingInterval: 30000, // Keep-alive ping interval (ms)
portRetries: 10, // Try up to 10 sequential ports
networkId: 'yakmesh', // Network identifier
networkFingerprint: fingerprint, // Code proof verification
});
// Start listening for connections
await mesh.start();
// Connect to a peer
await mesh.connect('ws://peer-node:9001');
// Broadcast to all peers (gossip)
mesh.broadcast({ type: 'custom', data: 'hello mesh!' });
// Send to specific peer
mesh.sendTo(nodeId, { action: 'sync', payload: data });
// Listen for messages
mesh.on(MessageTypes.GOSSIP, (msg, ws, nodeId) => {
console.log(`Gossip from ${nodeId}:`, msg.payload);
});
// Get connected peers
const peers = mesh.getPeers();
console.log(`Connected to ${peers.length} peers`);
// Stop mesh server
await mesh.stop();
Message Types
The mesh protocol uses these message types for peer communication:
| Type | Constant | Description |
|---|---|---|
hello |
MessageTypes.HELLO |
Initial connection handshake with identity and network fingerprint |
welcome |
MessageTypes.WELCOME |
Response to hello with peer list |
ping |
MessageTypes.PING |
Keep-alive ping |
pong |
MessageTypes.PONG |
Keep-alive response |
peers |
MessageTypes.PEERS |
Share known peer endpoints |
sync_request |
MessageTypes.SYNC_REQUEST |
Request data synchronization |
sync_response |
MessageTypes.SYNC_RESPONSE |
Data sync response |
replicate |
MessageTypes.REPLICATE |
Push new data to peers |
gossip |
MessageTypes.GOSSIP |
Broadcast message with deduplication |
Mesh Modules
The mesh subsystem is composed of specialized modules, each handling a critical aspect of network communication.
MeshNetwork
network.jsCore mesh network manager handling peer connections, message routing, and WebSocket server. Features automatic port fallback, code proof verification, and gossip with deduplication.
import { MeshNetwork, MessageTypes } from './mesh/network.js';
const mesh = new MeshNetwork(identity, { wsPort: 9001 });
await mesh.start();
mesh.broadcast({ type: 'announce', data: myData });
ANNEX
annex.js — Autonomous Network Negotiated Encrypted eXchangeEnd-to-end encrypted point-to-point channels using ML-KEM768 (Kyber) for quantum-resistant key exchange and AES-256-GCM for authenticated encryption. Perfect forward secrecy via ephemeral keys.
import { AnnexChannel } from './mesh/annex.js';
const channel = new AnnexChannel(myIdentity, peerId);
await channel.establish(meshNetwork);
await channel.send({ secret: 'data' }); // E2E encrypted
Beacon Broadcast
beacon-broadcast.js — Broadcast Emergency Alert Channel Over NetworkPriority message propagation with guaranteed delivery. Flood-based protocol with intelligent deduplication, proof-of-receipt, and emergency priority levels (ROUTINE → CRITICAL).
import { BeaconBroadcaster, Priority } from './mesh/beacon-broadcast.js';
const beacon = new BeaconBroadcaster(mesh);
await beacon.broadcast(payload, {
priority: Priority.IMMEDIATE,
ttl: 10, // hop count
});
SHERPA Discovery
sherpa-discovery.js — Secure Hidden Endpoint Resolution Path Architecture
Decentralized peer discovery using public web endpoints as a DHT. Nodes expose
/.well-known/yakmesh/beacon for self-organizing peer registry.
No central bootstrap nodes required.
import { SherpaDiscovery } from './mesh/sherpa-discovery.js';
const sherpa = new SherpaDiscovery(identity, {
maxCrawlDepth: 3,
crawlInterval: 300000, // 5 minutes
});
const peers = await sherpa.discover(seedEndpoints);
NAKPAK Routing
nakpak-routing.js — Nested Anonymous Kernel for Private Authenticated KommsPost-quantum secure onion routing with ML-DSA-65 signatures at every layer and ML-KEM key encapsulation. Multi-layer encryption with timing attack resistance through temporal padding.
import { NakpakRouter } from './mesh/nakpak-routing.js';
const router = new NakpakRouter(identity, mesh);
const circuit = await router.buildCircuit(3); // 3 hops
await router.sendAnonymous(circuit, payload);
Pulse Sync
pulse-sync.js — Precision Universal Latency Sync EngineThe heartbeat of the mesh network. Distributed liveness detection with temporal proofs, cryptographic heartbeat chains, and partition detection through gap analysis.
import { PulseSync } from './mesh/pulse-sync.js';
const pulse = new PulseSync(identity, mesh, {
heartbeatIntervalMs: 1000,
missedBeatsThreshold: 5,
});
pulse.on('partition', (nodes) => handlePartition(nodes));
Echo Ranging
echo-ranging.js — Encrypted Coordinate Heuristic OraclePrivacy-preserving network cartography. Maps mesh topology using encrypted timing probes without exposing node positions. Builds virtual coordinate space from RTT measurements.
import { EchoRanging } from './mesh/echo-ranging.js';
const echo = new EchoRanging(identity, mesh);
const rtt = await echo.measureLatency(peerId);
const coords = echo.getVirtualCoordinates();
Temporal Encoder
temporal-encoder.js — Temporal Mesh EncodingNovel packet resilience through temporal encoding. Instead of erasure coding across space, TME encodes data across TIME using synchronized clocks as the redundancy dimension.
import { TemporalEncoder } from './mesh/temporal-encoder.js';
const encoder = new TemporalEncoder({
sliceIntervalNs: 50_000_000, // 50ms slices
minSlicesForReconstruction: 0.6,
});
const slices = encoder.encode(data);
Security Modules
Defense-in-depth protection against network attacks:
Rate Limiter
rate-limiter.jsSliding window rate limiter protecting against connection floods, handshake spam, and gossip storms. Per-IP and per-node tracking with automatic banning.
import { ConnectionRateLimiter } from './mesh/rate-limiter.js';
const limiter = new ConnectionRateLimiter({
maxConnectionsPerMinute: 10,
maxMessagesPerSecond: 50,
maxHandshakesPerMinute: 5,
banThreshold: 5,
banDuration: 300000, // 5 minutes
});
if (!limiter.checkConnection(ip).allowed) {
ws.close(1008, 'Rate limited');
}
Message Validator
message-validator.jsValidates message size and structure to prevent amplification attacks. Enforces payload limits by type: gossip (64KB), handshake (8KB), listing (128KB), data (512KB).
import { MessageValidator, SafeJsonParser } from './mesh/message-validator.js';
const validator = new MessageValidator();
const parser = new SafeJsonParser();
const sizeCheck = validator.validateRaw(rawMessage, 'gossip');
if (!sizeCheck.valid) reject(sizeCheck.reason);
const parsed = parser.parse(rawMessage);
if (!parsed.success) reject(parsed.error);
const structCheck = validator.validateStructure(parsed.data, 'gossip');
if (!structCheck.valid) reject(structCheck.reason);
Replay Defense
replay-defense.jsMulti-layer replay attack protection with nonce registry, timestamp validation, and sequence tracking. Automatically detects and rejects duplicate or out-of-window messages.
import { NonceRegistry, TimestampValidator, SequenceTracker }
from './mesh/replay-defense.js';
const nonces = new NonceRegistry({ maxAge: 3600000 });
const timestamps = new TimestampValidator({ maxAge: 600000 });
const sequences = new SequenceTracker();
// Generate nonce for outgoing message
const nonce = nonces.generate();
// Validate incoming message
const nonceOk = nonces.validate(msg.nonce);
const timeOk = timestamps.validate(msg.timestamp);
const seqOk = sequences.validate(msg.senderId, msg.sequence);
Sybil Defense
sybil-defense.jsProtection against Sybil attacks through NAVR (proof-of-work challenges), reputation tracking, and subnet diversity enforcement.
import { NAVR, ReputationTracker, SubnetDiversity }
from './mesh/sybil-defense.js';
const navr = new NAVR({ difficulty: 16 });
const reputation = new ReputationTracker();
const subnets = new SubnetDiversity({ maxPerSubnet: 3 });
// Challenge new peer
const challenge = navr.createChallenge(peerId);
// Peer solves and returns solution
const verified = navr.verify(challenge, solution);
// Track reputation
reputation.registerNode(peerId, solution);
reputation.reportGoodBehavior(peerId);
const trust = reputation.getTrustLevel(peerId); // 'trusted'|'normal'|'suspicious'|'banned'
// Check subnet diversity
if (!subnets.allowConnection(peerIp).allowed) {
reject('Too many connections from this subnet');
}
Key Features
Automatic Port Fallback
If the configured WebSocket port is in use, automatically tries sequential ports
up to portRetries times.
Code Proof Verification
Network fingerprint exchanged during handshake. Nodes running different codebases are automatically rejected.
Gossip Deduplication
Messages include unique IDs tracked in seenMessages
set. Prevents infinite broadcast loops.
Signed Messages
All outgoing messages are signed with the node's identity using ML-DSA-65. Receivers verify authenticity.
Configuration
MeshNetwork constructor options:
| Option | Default | Description |
|---|---|---|
wsPort |
9001 |
WebSocket server port |
maxPeers |
10 |
Maximum concurrent peer connections |
pingInterval |
30000 |
Keep-alive ping interval (ms) |
portRetries |
10 |
Number of sequential ports to try if base port is in use |
networkId |
null |
Network identifier for code proof |
networkFingerprint |
null |
Codebase hash for peer verification |
publicHost |
null |
Public hostname for endpoint advertisement |
rateLimiter |
{} |
Rate limiter configuration object |
MeshNetwork API
| Method | Description |
|---|---|
start() |
Start WebSocket server with automatic port fallback |
connect(endpoint) |
Connect to a peer node, returns identity on WELCOME |
broadcast(message) |
Send gossip message to all connected peers |
sendTo(nodeId, message) |
Send direct message to specific peer |
on(type, handler) |
Register message handler for type |
off(type, handler) |
Remove message handler |
emit(type, ...args) |
Emit event to registered handlers |
isConnectedTo(nodeId) |
Check if connected to a specific node |
getPeers() |
Get list of connected peers with metadata |
getPublicEndpoint() |
Get this node's public WebSocket endpoint |
stop() |
Stop server and close all connections |