Skip to content

phase06/meshlink

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

3 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

MeshLink: Offline-First Disaster Response Network

MeshLink is a peer-to-peer (P2P), delay-tolerant networking application designed for communication in infrastructure-denied environments (e.g., flood zones, war zones, or remote areas without cellular coverage).

It utilizes a Store-and-Forward architecture to persist messages locally and opportunistically sync them with nearby peers, effectively turning every device into a data mule.

πŸ—οΈ Architecture

MeshLink consists of two main components:

1. Server (Development Relay)

A lightweight WebSocket relay server built with Bun that simulates nearby devices for testing. In production, this would be replaced by true peer-to-peer mesh networking, but for development and testing, this relay allows multiple clients to discover and communicate with each other as if they were nearby.

2. Mobile (React Native Client)

A cross-platform mobile application built with React Native and Expo, featuring local-first data persistence using WatermelonDB. The app uses the relay server to simulate mesh network behavior during development.

graph LR
    A[Mobile Client 1] <-->|WebSocket| C[Development Relay Server]
    B[Mobile Client 2] <-->|WebSocket| C
    D[Mobile Client N] <-->|WebSocket| C
    A -.->|Local DB| E[(WatermelonDB)]
    B -.->|Local DB| F[(WatermelonDB)]
    D -.->|Local DB| G[(WatermelonDB)]
Loading

Production Environment (Future):

graph TB
    subgraph "Mesh Network Topology"
        A[Mobile Device 1]
        B[Mobile Device 2]
        C[Mobile Device 3]
        D[Mobile Device 4]
        E[Mobile Device 5]
        
        A <-->|Bluetooth/WiFi Direct| B
        A <-->|Bluetooth/WiFi Direct| C
        B <-->|Bluetooth/WiFi Direct| C
        B <-->|Bluetooth/WiFi Direct| D
        C <-->|Bluetooth/WiFi Direct| E
        D <-->|Bluetooth/WiFi Direct| E
        
        A -.->|Local DB| DB1[(WatermelonDB)]
        B -.->|Local DB| DB2[(WatermelonDB)]
        C -.->|Local DB| DB3[(WatermelonDB)]
        D -.->|Local DB| DB4[(WatermelonDB)]
        E -.->|Local DB| DB5[(WatermelonDB)]
    end
    
    style A fill:#4CAF50
    style B fill:#2196F3
    style C fill:#FF9800
    style D fill:#9C27B0
    style E fill:#F44336
Loading

Note

In production, devices communicate directly via Bluetooth or WiFi Direct (P2P mesh), creating a decentralized network. Each device acts as both a client and a relay, forwarding messages to extend network reach. The development relay server above is only used for testing.

πŸš€ Features

Core Messaging

  • βœ… Real-time peer-to-peer messaging via WebSocket relay
  • βœ… Local-first data persistence with WatermelonDB
  • βœ… Message status tracking (pending, synced)
  • βœ… Automatic reconnection and message queue synchronization
  • βœ… Connection status indicator

Technical Highlights

  • 🎯 Local-First Architecture: Messages are stored locally first, then synchronized
  • πŸ”„ Automatic Sync: Pending messages are automatically sent when connection is restored
  • πŸ”Œ Resilient Connections: Auto-reconnect with exponential backoff
  • πŸ“Š Reactive UI: WatermelonDB observables for real-time UI updates
  • 🎨 Cross-Platform: Runs on iOS, Android, and Web using React Native

πŸ“ Project Structure

meshlink/
β”œβ”€β”€ server/                 # WebSocket relay server
β”‚   β”œβ”€β”€ index.ts           # Main server implementation
β”‚   β”œβ”€β”€ package.json       # Server dependencies
β”‚   └── tsconfig.json      # TypeScript configuration
β”‚
β”œβ”€β”€ mobile/                # React Native client
β”‚   β”œβ”€β”€ src/
β”‚   β”‚   β”œβ”€β”€ core/
β”‚   β”‚   β”‚   β”œβ”€β”€ db/       # WatermelonDB setup and models
β”‚   β”‚   β”‚   β”‚   β”œβ”€β”€ index.ts
β”‚   β”‚   β”‚   β”‚   β”œβ”€β”€ schema.ts
β”‚   β”‚   β”‚   β”‚   └── model/
β”‚   β”‚   β”‚   β”‚       └── Message.ts
β”‚   β”‚   β”‚   └── transport/ # Network layer
β”‚   β”‚   β”‚       β”œβ”€β”€ Transport.interface.ts
β”‚   β”‚   β”‚       └── WebSocketTransport.ts
β”‚   β”‚   β”œβ”€β”€ hooks/
β”‚   β”‚   β”‚   └── useMeshNetwork.ts  # Main networking hook
β”‚   β”‚   └── ui/
β”‚   β”‚       β”œβ”€β”€ MessageBubble.tsx  # Message UI component
β”‚   β”‚       └── ConnectionBanner.tsx
β”‚   β”œβ”€β”€ App.tsx           # Main application
β”‚   β”œβ”€β”€ package.json      # Mobile dependencies
β”‚   └── app.json          # Expo configuration
β”‚
└── README.md             # This file

πŸ› οΈ Getting Started

Prerequisites

  • Bun v1.3.4 or later (for server)
  • Node.js v18+ (for mobile)
  • Expo CLI
  • iOS Simulator, Android Emulator, or physical device

Server Setup

  1. Navigate to the server directory:

    cd server
  2. Install dependencies:

    bun install
  3. Start the relay server:

    bun run index.ts

The server will start on ws://localhost:8080

Server Configuration

By default, the server runs on port 8080. To change this, modify the PORT constant in server/index.ts:

const PORT = 8080; // Change to your desired port

Mobile Setup

  1. Navigate to the mobile directory:

    cd mobile
  2. Install dependencies:

    npm install
  3. Start the development server:

    npm start
  4. Run on your preferred platform:

    • iOS: npm run ios
    • Android: npm run android
    • Web: npm run web

Mobile Configuration

To connect to a different relay server, update the WebSocket URL in mobile/src/core/transport/WebSocketTransport.ts:

// Change the server address/port as needed
private url = 'ws://YOUR_SERVER_IP:8080';

Note: When testing on physical devices, replace localhost with your computer's local IP address.

πŸ’‘ How It Works

Message Flow

  1. Sending a Message:

    User Input β†’ Save to Local DB (pending) β†’ Broadcast via WebSocket β†’ Update to synced
    
  2. Receiving a Message:

    WebSocket receives β†’ Save to Local DB (synced) β†’ UI auto-updates via observable
    
  3. Offline/Reconnect:

    Connection lost β†’ Messages queued as pending β†’ Connection restored β†’ Auto-sync pending messages
    

Key Components

Server (server/index.ts)

  • WebSocket server using Bun's native WebSocket support
  • Simulates nearby device discovery for testing mesh networking
  • Topic-based pub/sub pattern (global-mesh topic)
  • Device ID tracking via headers or auto-generated IDs
  • Connection lifecycle management
  • Lightweight development tool (production would use true P2P mesh)

Mobile App

Database Layer (src/core/db/)

  • WatermelonDB for local-first storage
  • Message model with status tracking
  • Reactive queries for UI updates

Transport Layer (src/core/transport/)

  • Abstract transport interface
  • WebSocket implementation with auto-reconnect
  • Connection status callbacks
  • Message broadcast/receive handling

Hook Layer (src/hooks/useMeshNetwork.ts)

  • React hook for network operations
  • Message synchronization logic
  • Connection state management
  • Database write operations

UI Layer (src/ui/ & App.tsx)

  • Message list with real-time updates
  • Message bubbles with sender differentiation
  • Connection status banner
  • Input field and send functionality

πŸ”§ Development

Server Development

The server is intentionally minimalistic and serves as a testing simulator. Key features:

  • Simulates nearby devices for mesh network testing
  • No external dependencies (uses Bun's built-in WebSocket)
  • Topic-based broadcasting mimics local mesh discovery
  • Device ID tracking for peer identification
  • Simple message relay without persistence

Note

In production, the relay server would be replaced by true peer-to-peer mesh networking (Bluetooth, WiFi Direct, etc.). This relay exists purely to facilitate development and testing.

To add features:

  • Message persistence: Add SQLite or other database
  • Authentication: Validate device IDs or add JWT
  • Message routing: Implement private channels or direct messaging

Mobile Development

The mobile app uses a clean, layered architecture:

  • Core: Database and transport implementations
  • Hooks: Business logic and state management
  • UI: React components

To extend:

  • Add more message types (images, files, etc.)
  • Implement user profiles
  • Add end-to-end encryption
  • Create chat rooms or channels

πŸ§ͺ Testing

Testing the Server

  1. Start the server
  2. Use a WebSocket client (e.g., websocat or browser DevTools):
    websocat ws://localhost:8080
  3. Send test messages in JSON format:
    {"type":"TEXT","payload":"Hello World","senderId":"test-1","timestamp":1234567890}

Testing the Mobile App

  1. Run multiple instances (e.g., iOS + Android simulators)
  2. Send messages from one device
  3. Verify they appear on other devices
  4. Test offline scenarios:
    • Stop the server
    • Send messages (should show as pending)
    • Restart server
    • Verify messages sync automatically

πŸ“š Tech Stack

Server

  • Bun - JavaScript runtime and WebSocket server
  • TypeScript - Type safety

Mobile

  • React Native - Cross-platform mobile framework
  • Expo - Development platform and tooling
  • WatermelonDB - Reactive local database
  • React - UI library
  • TypeScript - Type safety

πŸ” Security Considerations

Warning

This is a development/prototype implementation. For production use, consider:

  • Authentication: Implement proper user authentication (JWT, OAuth, etc.)
  • Encryption: Add TLS/SSL for WebSocket connections
  • Validation: Sanitize and validate all incoming messages
  • Rate Limiting: Prevent spam and abuse
  • Message Encryption: Implement end-to-end encryption for privacy
  • Authorization: Add access control for different message types/channels

πŸ› Troubleshooting

Server Issues

Problem: Server won't start on port 8080

Error: Address already in use

Solution: Change the PORT in server/index.ts or kill the process using port 8080

Mobile Issues

Problem: Cannot connect to server from physical device Solution: Replace localhost with your computer's local IP in the WebSocket URL

Problem: Messages not syncing Solution: Check that both server and client are running, and verify the WebSocket URL is correct

Problem: WatermelonDB errors Solution: Clear the app data or reinstall the app to reset the database

🎯 Roadmap

Phase 1 (Current)

  • Basic relay server
  • WebSocket transport
  • Local database persistence
  • Message status tracking
  • Auto-reconnection
  • Connection status UI

Phase 2 (Planned)

  • User authentication
  • End-to-end encryption
  • Media messages (images, files)
  • Message delivery confirmations
  • Typing indicators
  • Read receipts

Phase 3 (Future)

  • True peer-to-peer mesh networking (Bluetooth/WiFi Direct)
  • Group chats/channels
  • Voice/video calls
  • Push notifications
  • Message search
  • Message reactions
  • User profiles and avatars

Phase 4 (Advanced)

  • HQ Command Center - Centralized monitoring and management dashboard
    • Real-time network topology visualization
    • Message analytics and monitoring
    • Device/peer management
    • Network health metrics
    • Administrative controls

πŸ“„ License

MIT

🀝 Support

For issues or questions, please create an issue in the repository.


Built with ❀️ using Bun, React Native, and WatermelonDB

About

MeshLink is a peer-to-peer (P2P), delay-tolerant networking application designed for communication in infrastructure-denied environments (e.g., flood zones, war zones, or remote areas without cellular coverage).

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors