react-native-ble-mesh 1.1.0 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (66) hide show
  1. package/README.md +439 -556
  2. package/docs/IOS-BACKGROUND-BLE.md +231 -0
  3. package/docs/OPTIMIZATION.md +70 -0
  4. package/docs/SPEC-v2.1.md +308 -0
  5. package/docs/prompt-instructions.md +528 -0
  6. package/package.json +2 -2
  7. package/src/MeshNetwork.js +659 -465
  8. package/src/constants/index.js +1 -0
  9. package/src/crypto/AutoCrypto.js +79 -0
  10. package/src/crypto/CryptoProvider.js +99 -0
  11. package/src/crypto/index.js +15 -63
  12. package/src/crypto/providers/ExpoCryptoProvider.js +125 -0
  13. package/src/crypto/providers/QuickCryptoProvider.js +134 -0
  14. package/src/crypto/providers/TweetNaClProvider.js +124 -0
  15. package/src/crypto/providers/index.js +11 -0
  16. package/src/errors/MeshError.js +2 -1
  17. package/src/expo/withBLEMesh.js +102 -0
  18. package/src/hooks/useMesh.js +30 -9
  19. package/src/hooks/useMessages.js +2 -0
  20. package/src/index.js +23 -8
  21. package/src/mesh/dedup/DedupManager.js +36 -10
  22. package/src/mesh/fragment/Assembler.js +5 -0
  23. package/src/mesh/index.js +1 -1
  24. package/src/mesh/monitor/ConnectionQuality.js +408 -0
  25. package/src/mesh/monitor/NetworkMonitor.js +327 -316
  26. package/src/mesh/monitor/index.js +7 -3
  27. package/src/mesh/peer/PeerManager.js +6 -1
  28. package/src/mesh/router/MessageRouter.js +26 -15
  29. package/src/mesh/router/RouteTable.js +7 -1
  30. package/src/mesh/store/StoreAndForwardManager.js +295 -297
  31. package/src/mesh/store/index.js +1 -1
  32. package/src/service/BatteryOptimizer.js +282 -278
  33. package/src/service/EmergencyManager.js +224 -214
  34. package/src/service/HandshakeManager.js +167 -13
  35. package/src/service/MeshService.js +72 -6
  36. package/src/service/SessionManager.js +77 -2
  37. package/src/service/audio/AudioManager.js +8 -2
  38. package/src/service/file/FileAssembler.js +106 -0
  39. package/src/service/file/FileChunker.js +79 -0
  40. package/src/service/file/FileManager.js +307 -0
  41. package/src/service/file/FileMessage.js +122 -0
  42. package/src/service/file/index.js +15 -0
  43. package/src/service/text/broadcast/BroadcastManager.js +16 -0
  44. package/src/transport/BLETransport.js +131 -9
  45. package/src/transport/MockTransport.js +1 -1
  46. package/src/transport/MultiTransport.js +305 -0
  47. package/src/transport/WiFiDirectTransport.js +295 -0
  48. package/src/transport/adapters/NodeBLEAdapter.js +34 -0
  49. package/src/transport/adapters/RNBLEAdapter.js +56 -1
  50. package/src/transport/index.js +6 -0
  51. package/src/utils/compression.js +291 -291
  52. package/src/crypto/aead.js +0 -189
  53. package/src/crypto/chacha20.js +0 -181
  54. package/src/crypto/hkdf.js +0 -187
  55. package/src/crypto/hmac.js +0 -143
  56. package/src/crypto/keys/KeyManager.js +0 -271
  57. package/src/crypto/keys/KeyPair.js +0 -216
  58. package/src/crypto/keys/SecureStorage.js +0 -219
  59. package/src/crypto/keys/index.js +0 -32
  60. package/src/crypto/noise/handshake.js +0 -410
  61. package/src/crypto/noise/index.js +0 -27
  62. package/src/crypto/noise/session.js +0 -253
  63. package/src/crypto/noise/state.js +0 -268
  64. package/src/crypto/poly1305.js +0 -113
  65. package/src/crypto/sha256.js +0 -240
  66. package/src/crypto/x25519.js +0 -154
@@ -0,0 +1,528 @@
1
+ # AI Agent Instructions: react-native-ble-mesh
2
+
3
+ > This document provides instructions for AI agents to understand and help users with the `react-native-ble-mesh` npm module.
4
+
5
+ ## Overview
6
+
7
+ `react-native-ble-mesh` is a Bluetooth Low Energy (BLE) mesh networking library for React Native that enables:
8
+ - Peer-to-peer communication without internet
9
+ - End-to-end encryption using Noise Protocol
10
+ - Offline messaging with store-and-forward
11
+ - Multi-hop message routing
12
+ - Battery-optimized operation
13
+
14
+ **Primary use case**: Building decentralized chat apps, emergency communication tools, or any app requiring offline P2P messaging.
15
+
16
+ ---
17
+
18
+ ## Installation
19
+
20
+ ```bash
21
+ npm install react-native-ble-mesh
22
+ ```
23
+
24
+ ### Peer Dependencies (React Native)
25
+ ```bash
26
+ npm install react-native-ble-plx react-native-get-random-values
27
+ ```
28
+
29
+ ### iOS Setup
30
+ ```bash
31
+ cd ios && pod install
32
+ ```
33
+
34
+ Add to `Info.plist`:
35
+ ```xml
36
+ <key>NSBluetoothAlwaysUsageDescription</key>
37
+ <string>App uses Bluetooth to communicate with nearby devices</string>
38
+ <key>NSBluetoothPeripheralUsageDescription</key>
39
+ <string>App uses Bluetooth to communicate with nearby devices</string>
40
+ <key>UIBackgroundModes</key>
41
+ <array>
42
+ <string>bluetooth-central</string>
43
+ <string>bluetooth-peripheral</string>
44
+ </array>
45
+ ```
46
+
47
+ ### Android Setup
48
+ Add to `AndroidManifest.xml`:
49
+ ```xml
50
+ <uses-permission android:name="android.permission.BLUETOOTH" />
51
+ <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
52
+ <uses-permission android:name="android.permission.BLUETOOTH_SCAN" />
53
+ <uses-permission android:name="android.permission.BLUETOOTH_ADVERTISE" />
54
+ <uses-permission android:name="android.permission.BLUETOOTH_CONNECT" />
55
+ <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
56
+ ```
57
+
58
+ ---
59
+
60
+ ## Quick Start
61
+
62
+ ### Basic Usage (High-Level API)
63
+
64
+ ```javascript
65
+ import { MeshNetwork } from 'react-native-ble-mesh';
66
+
67
+ // Create mesh instance
68
+ const mesh = new MeshNetwork({
69
+ nickname: 'Alice',
70
+ batteryMode: MeshNetwork.BatteryMode.BALANCED,
71
+ });
72
+
73
+ // Set up event listeners
74
+ mesh.on('messageReceived', ({ from, text, channel }) => {
75
+ console.log(`${from}: ${text}`);
76
+ });
77
+
78
+ mesh.on('peerConnected', ({ peerId, displayName }) => {
79
+ console.log(`${displayName} joined the network`);
80
+ });
81
+
82
+ // Start the mesh network
83
+ await mesh.start();
84
+
85
+ // Send messages
86
+ await mesh.broadcast('Hello everyone!');
87
+ await mesh.sendDirect('peer-id-here', 'Private message');
88
+
89
+ // Join channels
90
+ await mesh.joinChannel('#general');
91
+ await mesh.sendToChannel('#general', 'Hello channel!');
92
+
93
+ // Clean up
94
+ await mesh.destroy();
95
+ ```
96
+
97
+ ### Using React Hooks
98
+
99
+ ```javascript
100
+ import { useMesh, useMessages, usePeers } from 'react-native-ble-mesh/hooks';
101
+
102
+ function ChatScreen() {
103
+ const { mesh, isConnected, start, stop } = useMesh({ nickname: 'User' });
104
+ const { messages, sendMessage, sendBroadcast } = useMessages(mesh);
105
+ const { peers, connectedPeers } = usePeers(mesh);
106
+
107
+ useEffect(() => {
108
+ start();
109
+ return () => stop();
110
+ }, []);
111
+
112
+ return (
113
+ <View>
114
+ <Text>Connected peers: {connectedPeers.length}</Text>
115
+ {messages.map(msg => (
116
+ <Text key={msg.id}>{msg.from}: {msg.text}</Text>
117
+ ))}
118
+ </View>
119
+ );
120
+ }
121
+ ```
122
+
123
+ ---
124
+
125
+ ## Core Concepts
126
+
127
+ ### 1. MeshNetwork (High-Level API)
128
+ The main entry point. Handles all mesh operations including peer discovery, messaging, encryption, and battery optimization.
129
+
130
+ ```javascript
131
+ const mesh = new MeshNetwork({
132
+ nickname: 'DisplayName', // User's display name
133
+ batteryMode: 'balanced', // 'high' | 'balanced' | 'low' | 'auto'
134
+ compression: { enabled: true }, // Enable LZ4 compression
135
+ storeAndForward: { enabled: true }, // Cache messages for offline peers
136
+ });
137
+ ```
138
+
139
+ ### 2. Message Types
140
+ - **Broadcast**: Unencrypted, reaches all peers in range
141
+ - **Direct/Private**: End-to-end encrypted, point-to-point
142
+ - **Channel**: Group messages to subscribed peers
143
+
144
+ ### 3. Peer States
145
+ - `discovered`: Peer found via BLE scan
146
+ - `connecting`: Handshake in progress
147
+ - `connected`: Secure session established
148
+ - `disconnected`: Connection lost
149
+
150
+ ### 4. Battery Modes
151
+ ```javascript
152
+ MeshNetwork.BatteryMode.HIGH_PERFORMANCE // Max range, frequent scans
153
+ MeshNetwork.BatteryMode.BALANCED // Default, balanced power
154
+ MeshNetwork.BatteryMode.LOW_POWER // Minimal power usage
155
+ MeshNetwork.BatteryMode.AUTO // Adapts to battery level
156
+ ```
157
+
158
+ ### 5. Health Status
159
+ ```javascript
160
+ MeshNetwork.HealthStatus.GOOD // < 100ms latency, < 5% packet loss
161
+ MeshNetwork.HealthStatus.FAIR // < 300ms latency, < 15% packet loss
162
+ MeshNetwork.HealthStatus.POOR // High latency or packet loss
163
+ ```
164
+
165
+ ---
166
+
167
+ ## API Reference
168
+
169
+ ### MeshNetwork Methods
170
+
171
+ | Method | Description |
172
+ |--------|-------------|
173
+ | `start(transport?)` | Start mesh network (optional custom transport) |
174
+ | `stop()` | Stop mesh network |
175
+ | `destroy()` | Clean up all resources |
176
+ | `broadcast(text)` | Send message to all peers |
177
+ | `sendDirect(peerId, text)` | Send encrypted message to peer |
178
+ | `sendToChannel(channel, text)` | Send to channel subscribers |
179
+ | `joinChannel(channel)` | Subscribe to channel |
180
+ | `leaveChannel(channel)` | Unsubscribe from channel |
181
+ | `getStatus()` | Get network status object |
182
+ | `getPeers()` | Get list of known peers |
183
+ | `getIdentity()` | Get own identity info |
184
+ | `setNickname(name)` | Update display name |
185
+ | `setBatteryMode(mode)` | Change battery mode |
186
+ | `getBatteryMode()` | Get current battery mode |
187
+ | `getNetworkHealth()` | Get health metrics |
188
+ | `blockPeer(peerId)` | Block a peer |
189
+ | `unblockPeer(peerId)` | Unblock a peer |
190
+ | `enablePanicMode(options?)` | Enable emergency data wipe |
191
+ | `disablePanicMode()` | Disable panic mode |
192
+ | `wipeAllData()` | Execute immediate data wipe |
193
+
194
+ ### Events
195
+
196
+ | Event | Payload | Description |
197
+ |-------|---------|-------------|
198
+ | `started` | `{}` | Network started |
199
+ | `stopped` | `{}` | Network stopped |
200
+ | `messageReceived` | `{ from, text, channel?, encrypted }` | Message received |
201
+ | `messageSent` | `{ id, to?, channel? }` | Message sent |
202
+ | `peerDiscovered` | `{ peerId, rssi }` | New peer found |
203
+ | `peerConnected` | `{ peerId, displayName }` | Peer connected |
204
+ | `peerDisconnected` | `{ peerId, reason }` | Peer disconnected |
205
+ | `channelJoined` | `{ channel }` | Joined channel |
206
+ | `channelLeft` | `{ channel }` | Left channel |
207
+ | `networkHealthChanged` | `{ health, status }` | Health status changed |
208
+ | `batteryModeChanged` | `{ mode, previous }` | Battery mode changed |
209
+ | `error` | `{ code, message }` | Error occurred |
210
+
211
+ ---
212
+
213
+ ## Common Patterns
214
+
215
+ ### 1. Handling Offline Peers (Store & Forward)
216
+
217
+ ```javascript
218
+ const mesh = new MeshNetwork({
219
+ storeAndForward: {
220
+ enabled: true,
221
+ retentionHours: 24, // Keep messages for 24 hours
222
+ maxCachedMessages: 500, // Max messages to cache
223
+ },
224
+ });
225
+
226
+ // Messages to offline peers are automatically cached
227
+ await mesh.sendDirect('offline-peer', 'Will deliver when online');
228
+
229
+ // Listen for cached message delivery
230
+ mesh.on('messageCached', ({ messageId, recipientId }) => {
231
+ console.log(`Message cached for ${recipientId}`);
232
+ });
233
+
234
+ mesh.on('cachedMessageDelivered', ({ messageId, recipientId }) => {
235
+ console.log(`Cached message delivered to ${recipientId}`);
236
+ });
237
+ ```
238
+
239
+ ### 2. Battery-Aware Operation
240
+
241
+ ```javascript
242
+ import { DeviceEventEmitter } from 'react-native';
243
+
244
+ const mesh = new MeshNetwork({
245
+ batteryMode: MeshNetwork.BatteryMode.AUTO,
246
+ });
247
+
248
+ // Update mesh with battery info
249
+ DeviceEventEmitter.addListener('batteryLevelChanged', (level) => {
250
+ mesh.updateBatteryLevel(level, level < 20);
251
+ });
252
+
253
+ // Listen for mode changes
254
+ mesh.on('batteryModeChanged', ({ mode }) => {
255
+ console.log(`Switched to ${mode} mode`);
256
+ });
257
+ ```
258
+
259
+ ### 3. Emergency Data Wipe (Panic Mode)
260
+
261
+ ```javascript
262
+ const mesh = new MeshNetwork();
263
+ await mesh.start();
264
+
265
+ // Enable panic mode with triple-tap trigger
266
+ mesh.enablePanicMode({
267
+ trigger: MeshNetwork.PanicTrigger.TRIPLE_TAP,
268
+ wipeTarget: 200, // Target wipe time in ms
269
+ });
270
+
271
+ // Register taps from UI
272
+ onTripleTap(() => {
273
+ mesh.registerPanicTap();
274
+ });
275
+
276
+ // Or trigger manually
277
+ await mesh.wipeAllData();
278
+ ```
279
+
280
+ ### 4. Network Health Monitoring
281
+
282
+ ```javascript
283
+ mesh.on('networkHealthChanged', ({ status, health }) => {
284
+ if (status === MeshNetwork.HealthStatus.POOR) {
285
+ // Show warning to user
286
+ showNetworkWarning();
287
+ }
288
+
289
+ console.log(`Latency: ${health.averageLatencyMs}ms`);
290
+ console.log(`Packet loss: ${health.packetLossRate}%`);
291
+ });
292
+
293
+ // Get current health
294
+ const health = mesh.getNetworkHealth();
295
+ ```
296
+
297
+ ### 5. Using Compression
298
+
299
+ ```javascript
300
+ import { MessageCompressor } from 'react-native-ble-mesh/utils';
301
+
302
+ // Automatic compression in MeshNetwork
303
+ const mesh = new MeshNetwork({
304
+ compression: {
305
+ enabled: true,
306
+ threshold: 100, // Compress payloads > 100 bytes
307
+ },
308
+ });
309
+
310
+ // Manual compression
311
+ const compressor = new MessageCompressor({ threshold: 50 });
312
+ const { data, compressed } = compressor.compress(payload);
313
+ const original = compressor.decompress(data, compressed);
314
+ ```
315
+
316
+ ---
317
+
318
+ ## Low-Level API (Advanced)
319
+
320
+ For advanced use cases, access individual components:
321
+
322
+ ```javascript
323
+ import {
324
+ // Core service
325
+ MeshService,
326
+
327
+ // Crypto
328
+ NoiseHandshake,
329
+ KeyManager,
330
+ AEAD,
331
+
332
+ // Mesh components
333
+ PeerManager,
334
+ MessageRouter,
335
+ BloomFilter,
336
+
337
+ // Transport
338
+ BLETransport,
339
+ MockTransport,
340
+
341
+ // Protocol
342
+ MessageSerializer,
343
+ MessageDeserializer,
344
+
345
+ // Storage
346
+ MessageStore,
347
+ MemoryStorage,
348
+ } from 'react-native-ble-mesh';
349
+ ```
350
+
351
+ ### Custom Transport
352
+
353
+ ```javascript
354
+ import { Transport, MeshService } from 'react-native-ble-mesh';
355
+
356
+ class MyCustomTransport extends Transport {
357
+ async start() { /* ... */ }
358
+ async stop() { /* ... */ }
359
+ async send(peerId, data) { /* ... */ }
360
+ async broadcast(data) { /* ... */ }
361
+ }
362
+
363
+ const service = new MeshService();
364
+ await service.initialize(new MyCustomTransport());
365
+ ```
366
+
367
+ ---
368
+
369
+ ## Testing
370
+
371
+ ### Mock Transport for Tests
372
+
373
+ ```javascript
374
+ import { MeshNetwork, MockTransport } from 'react-native-ble-mesh';
375
+
376
+ describe('Chat Feature', () => {
377
+ let mesh1, mesh2;
378
+
379
+ beforeEach(async () => {
380
+ const transport1 = new MockTransport();
381
+ const transport2 = new MockTransport();
382
+
383
+ // Link transports for peer-to-peer simulation
384
+ transport1.linkTo(transport2);
385
+ transport2.linkTo(transport1);
386
+
387
+ mesh1 = new MeshNetwork({ nickname: 'Alice' });
388
+ mesh2 = new MeshNetwork({ nickname: 'Bob' });
389
+
390
+ await mesh1.start(transport1);
391
+ await mesh2.start(transport2);
392
+ });
393
+
394
+ afterEach(async () => {
395
+ await mesh1.destroy();
396
+ await mesh2.destroy();
397
+ });
398
+
399
+ it('sends messages between peers', async () => {
400
+ const received = jest.fn();
401
+ mesh2.on('messageReceived', received);
402
+
403
+ await mesh1.broadcast('Hello!');
404
+
405
+ expect(received).toHaveBeenCalledWith(
406
+ expect.objectContaining({ text: 'Hello!' })
407
+ );
408
+ });
409
+ });
410
+ ```
411
+
412
+ ---
413
+
414
+ ## Error Handling
415
+
416
+ ```javascript
417
+ import { ValidationError, MeshError, ConnectionError } from 'react-native-ble-mesh';
418
+
419
+ try {
420
+ await mesh.sendDirect('', 'message'); // Invalid peer ID
421
+ } catch (error) {
422
+ if (error instanceof ValidationError) {
423
+ console.log('Invalid input:', error.message);
424
+ } else if (error instanceof ConnectionError) {
425
+ console.log('Connection failed:', error.message);
426
+ } else if (error instanceof MeshError) {
427
+ console.log('Mesh error:', error.code, error.message);
428
+ }
429
+ }
430
+
431
+ // Global error handling
432
+ mesh.on('error', ({ code, message, details }) => {
433
+ console.error(`Error ${code}: ${message}`, details);
434
+ });
435
+ ```
436
+
437
+ ---
438
+
439
+ ## TypeScript Support
440
+
441
+ Full TypeScript support with exported types:
442
+
443
+ ```typescript
444
+ import {
445
+ MeshNetwork,
446
+ MeshNetworkConfig,
447
+ MeshNetworkStatus,
448
+ Peer,
449
+ Message,
450
+ BATTERY_MODE,
451
+ PANIC_TRIGGER,
452
+ HEALTH_STATUS,
453
+ NetworkHealthReport,
454
+ StoreAndForwardStats,
455
+ } from 'react-native-ble-mesh';
456
+
457
+ const config: MeshNetworkConfig = {
458
+ nickname: 'TypedUser',
459
+ batteryMode: BATTERY_MODE.BALANCED,
460
+ };
461
+
462
+ const mesh = new MeshNetwork(config);
463
+
464
+ mesh.on('messageReceived', (message: Message) => {
465
+ console.log(message.text);
466
+ });
467
+ ```
468
+
469
+ ---
470
+
471
+ ## Troubleshooting
472
+
473
+ ### Common Issues
474
+
475
+ 1. **BLE not working on Android**
476
+ - Ensure location permissions are granted (required for BLE scanning)
477
+ - Check if Bluetooth is enabled
478
+
479
+ 2. **Peers not discovering each other**
480
+ - Devices must be within BLE range (~10-30 meters)
481
+ - Check battery mode isn't set to LOW_POWER (reduces scan frequency)
482
+
483
+ 3. **Messages not delivering**
484
+ - Verify peer is connected (not just discovered)
485
+ - Check if peer is blocked
486
+ - For encrypted messages, ensure handshake completed
487
+
488
+ 4. **High battery drain**
489
+ - Switch to `LOW_POWER` or `AUTO` battery mode
490
+ - Reduce scan frequency in config
491
+
492
+ ### Debug Mode
493
+
494
+ ```javascript
495
+ const mesh = new MeshNetwork({
496
+ debug: true, // Enable verbose logging
497
+ });
498
+ ```
499
+
500
+ ---
501
+
502
+ ## Security Notes
503
+
504
+ - All private messages use **Noise Protocol XX** handshake
505
+ - Encryption: **ChaCha20-Poly1305** AEAD
506
+ - Key exchange: **X25519** ECDH
507
+ - Messages have **forward secrecy** via ephemeral keys
508
+ - Panic mode wipes all keys and message history in <200ms
509
+
510
+ ---
511
+
512
+ ## Version Compatibility
513
+
514
+ | Library Version | React Native | react-native-ble-plx |
515
+ |-----------------|--------------|----------------------|
516
+ | 1.1.x | >= 0.60.0 | >= 2.0.0 |
517
+ | 1.0.x | >= 0.60.0 | >= 2.0.0 |
518
+
519
+ ---
520
+
521
+ ## Resources
522
+
523
+ - [Full API Documentation](./API.md)
524
+ - [Protocol Specification](./PROTOCOL.md)
525
+ - [Security Documentation](./SECURITY.md)
526
+ - [React Native Guide](./REACT_NATIVE.md)
527
+ - [GitHub Repository](https://github.com/suhailtajshaik/react-native-ble-mesh)
528
+ - [npm Package](https://www.npmjs.com/package/react-native-ble-mesh)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "react-native-ble-mesh",
3
- "version": "1.1.0",
3
+ "version": "2.0.0",
4
4
  "description": "React Native Bluetooth Low Energy (BLE) mesh networking library with end-to-end encryption, offline messaging, peer-to-peer communication, and Noise Protocol security for iOS and Android",
5
5
  "main": "src/index.js",
6
6
  "types": "src/index.d.ts",
@@ -102,4 +102,4 @@
102
102
  "url": "https://github.com/suhailtajshaik/react-native-ble-mesh/issues"
103
103
  },
104
104
  "homepage": "https://github.com/suhailtajshaik/react-native-ble-mesh#readme"
105
- }
105
+ }