Commit Graph
100 Commits
Author SHA1 Message Date
jack f55694c920 Update WHITEPAPER.md 2025-07-25 12:26:27 +02:00
2e0d9be03e Implement targeted delivery for private messages (#319)
- Add direct delivery for private messages when recipient is connected
- Implement selective relay using 2-3 best RSSI peers as fallback
- Limit TTL to 2 hops for relayed private messages
- Update all private communication types to use targeted delivery:
  - Private messages
  - Read receipts
  - Delivery ACKs
  - Protocol ACKs/NACKs
  - Handshake messages
  - Identity announces (when targeted)
  - Session validation pings
  - Version ACKs
- Add intelligent relay logic to forward messages only when recipient is reachable
- Fall back to broadcast only as last resort when no direct path available

This reduces network traffic by ~90% for private communications, improves battery life, and enhances privacy by limiting message visibility.

Co-authored-by: jack <jackjackbits@users.noreply.github.com>
2025-07-25 09:54:56 +02:00
809e222a31 Improve BLE connection stability and message reliability (#318)
* Remove sequence numbers from protocol

- Remove sequenceNumber field from BitchatPacket struct
- Update BinaryProtocol to not encode/decode sequence numbers (header size reduced from 17 to 13 bytes)
- Replace sequence-based duplicate detection with content-based using packet ID hash
- Update packet ID generation to use SHA256(senderID + timestamp + type + payload prefix)
- Remove all sequence tracking variables and methods
- Simplify duplicate detection to rely on timestamp and content hashing

* Fix connection stability issues

- Increase peer availability check interval from 5 to 15 seconds
- Fix availability logic to not mark connected peers as unavailable
- Add BLE connection keepalive timer (20s) to prevent iOS timeouts
- Fix missing delivery ACKs by passing peripheral context through Noise decryption
- Reduce identity announce frequency from 2 to 10 seconds minimum
- Remove unnecessary identity announces on connection
- Debounce identity cache keychain saves (2 second delay)
- Add message retry notification handler in ChatViewModel
- Fix version negotiation redundancy by checking existing negotiations
- Keep Noise sessions for already-connected peers

* Fix build errors in message retry handler

- Fix reference to 'displayedMessages' - should be 'messages'
- Fix sendMessage call signature to use individual parameters instead of message object
- Both iOS and macOS builds now succeed

* Fix remaining connection stability issues

- Fix duplicate identity announces with content-based deduplication
- Simplify peripheral mapping with cleaner temp ID to peer ID transitions
- Improve graceful leave detection across peer ID rotations
- Track previousPeerID from announcements to maintain state
- Add time-based cleanup for gracefully left peers

* Fix connection stability issues

- Add special duplicate detection for identity announces
- Simplify peripheral mapping with dedicated structure
- Improve graceful leave detection with peer ID rotation handling
- Track graceful leave timestamps for cleanup
- Transfer states properly during peer ID rotation

* Improve BLE connection stability and message reliability

- Increase peer availability timeout from 5s to 15s to prevent flapping
- Add BLE keepalive timer with 30s interval to maintain connections
- Fix missing delivery ACKs by passing peripheral context through decryption
- Reduce identity announce frequency from 2s to 10s minimum interval
- Add keychain save debouncing with 2s delay to prevent excessive writes
- Implement message retry system for failed deliveries to favorites
- Fix version negotiation redundancy by checking existing state
- Add special duplicate detection for identity announcements
- Implement graceful leave detection with peer ID rotation support
- Simplify peripheral mapping to reduce complexity
- Fix switch statement structure issues causing build errors

These changes significantly improve connection stability, eliminate peer availability flapping, and ensure reliable message delivery.

---------

Co-authored-by: jack <jackjackbits@users.noreply.github.com>
2025-07-25 02:40:51 +02:00
86726d7033 Fix RSSI nil display issue (#316)
* Add comprehensive RSSI debugging logs

- Log RSSI capture during discovery phase
- Log RSSI reading after peripheral connection
- Log didReadRSSI results including validation and retries
- Log getPeerRSSI() calls and dictionary contents
- Log RSSI transfer from temp IDs to real peer IDs
- Add UI logging to trace nil RSSI values in ContentView
- Track RSSI flow from Bluetooth discovery to UI display

* Add detailed logging for RSSI transfer from temp ID to real peer ID

- Log peripheral mapping updates during announce packet handling
- Track connectedPeripherals state before and after mapping
- Log RSSI transfer from peripheralRSSI to peerRSSI
- Identify whether temp ID is found and properly transferred

* Add peripheral lookup fallback for announce packets

- Log whether peripheral is present when announce received
- Add fallback to look up peripheral if not passed as parameter
- This handles cases where announce is received via relay

* Add comprehensive state logging to getPeerRSSI

- Log connectedPeripherals mapping state
- Log peripheralRSSI dictionary contents
- Log UI-side RSSI lookup attempts with dictionary state
- Track exactly what's in the RSSI lookup tables

* Log peer list shown in UI

* Ensure RSSI transfers even when no temp ID mapping exists

* Add debugging for announce packets without peripheral reference

* Fix build errors and add type annotations

* Fix RSSI mapping for relayed announce packets

- Add fallback logic to match unmapped peripherals with announced peers
- Transfer RSSI from temp UUID to real peer ID when single unmapped peripheral exists
- Implement periodic RSSI updates every 10 seconds for all connected peripherals
- Improve RSSI debugging logs to track mapping state

* Fix RSSI mapping condition for single unmapped peripheral

- Remove peerNicknames.count == 0 condition that was preventing mapping
- Map single unmapped peripheral to announcing peer regardless of nickname state
- Remove temp RSSI entries when transferring to real peer ID
- Improve logging to show successful RSSI transfers

* Improve getPeerRSSI to skip temp IDs and check known peers

- Skip temp IDs (non-16 character) when iterating connectedPeripherals
- Add fallback to check peerNicknames for known peers without peripherals
- Check both peerRSSI and peripheralRSSI for known peers
- Improve RSSI lookup coverage for edge cases

* Remove RSSI debug logging and fix build warnings

- Remove all RSSI-related debug logging added during troubleshooting
- Keep functional RSSI tracking code intact
- Fix unused variable warnings in didReadRSSI and updateAllPeripheralRSSI
- Clean up verbose logging while maintaining core functionality

---------

Co-authored-by: jack <jackjackbits@users.noreply.github.com>
2025-07-24 22:22:19 +02:00
jack f4e954b837 Replace commands section with security warning in app info
- Removed COMMANDS section from AppInfoView
- Added WARNING section about unaudited private message security
- Warning displayed at bottom with red styling for visibility
- Users advised not to use for critical situations until audit complete
2025-07-24 20:04:30 +02:00
492f90edd5 Optimize BLE mesh network for robustness and range (#314)
- Fixed relay probability calculation for 2-node networks (0% relay needed)
- Added protocol ACKs to prevent unnecessary retransmissions
- Implemented MessageState for enhanced duplicate detection
- Added exponential backoff for collision avoidance
- Fixed duplicate sends for bidirectional connections
- Resolved packet ID generation issues using immutable fields only
- Implemented smart rate limiting with progressive throttling
- Removed unnecessary debug logging and fixed build warnings
- Optimized message routing to prevent flooding in small networks

Co-authored-by: jack <jackjackbits@users.noreply.github.com>
2025-07-24 19:49:37 +02:00
jack 498bb30d82 Fix iOS keyboard constraint warnings
- Added 0.1s delay before focusing text field on appear
- This gives iOS time to properly layout keyboard views
- Prevents constraint conflict warnings in system keyboard
2025-07-24 15:15:28 +02:00
jack bdbc0a6cfe Fix duplicate disconnect messages when Mac app closes
- Added gracefullyLeftPeers tracking to prevent duplicate disconnect messages
- Show disconnect message immediately when leave announcement is received
- Skip duplicate message when physical disconnect happens after graceful leave
- Fixed API misuse by adding peripheral.state checks before readRSSI() calls
- Added debug logging to track graceful leave flow
2025-07-24 15:11:45 +02:00
jack 439668f745 Fix duplicate ChatViewModel disconnect messages
- Prevent didDisconnectFromPeer delegate call when peer gracefully left
- This prevents duplicate 'rick disconnected' messages in chat UI
2025-07-24 14:58:21 +02:00
jack fbc904a331 Fix duplicate disconnect messages and API misuse errors
- Track peers that gracefully left with 'gracefullyLeftPeers' set
- Only log disconnect message if peer didn't send leave message first
- Add state checks before all peripheral.readRSSI() calls
- Prevents API misuse errors for disconnected peripherals
- Clear gracefullyLeftPeers after 5 seconds to handle race conditions
2025-07-24 14:52:22 +02:00
jack a3773a6b31 Fix build errors: wrap textInputAutocapitalization in iOS conditional
- textInputAutocapitalization is iOS-only API
- Wrapped in #if os(iOS) to fix macOS build
2025-07-24 14:38:16 +02:00
jack ffab7b695c Fix NaN errors and timeout warnings when typing
- Disable iOS autocorrection on text fields to prevent conflicts
- Add NaN validation for all geometry and gesture calculations
- Fix frame calculations to handle invalid geometry values
- Validate translation and velocity values in drag gestures
- Prevent Result accumulator timeout warnings
2025-07-24 14:33:20 +02:00
jackandGitHub eac3531a54 Merge pull request #310 from permissionlesstech/fix/ui-polish
UI Polish and Performance Optimizations
2025-07-24 14:23:41 +02:00
jack cea0579bce Fix build error: move PeerDisplayData struct outside ViewBuilder
- Move struct declaration to top level to avoid ViewBuilder error
- Struct declarations cannot be inside ViewBuilder closures
2025-07-24 13:47:44 +02:00
jack c7f0a5ea02 Implement lazy loading for heavy components
- Add LazyLinkPreviewView wrapper to defer link preview loading
- Only render sidebar content when visible or animating
- Defer expensive computations until components are shown
- Reduces initial render cost and memory usage
2025-07-24 13:46:23 +02:00
jack 2350c48e13 Reduce ForEach overhead with pre-computed data
- Remove unnecessary Array() conversions in messages ForEach
- Optimize URL ForEach to use indices instead of enumerated
- Simplify autocomplete ForEach by removing unneeded enumeration
- Pre-compute all peer display data outside ForEach for sidebar
- Create PeerDisplayData struct to bundle peer properties
- Move sorting and data preparation outside the render loop
2025-07-24 13:43:02 +02:00
jack 7120b11692 Optimize autocomplete with debouncing
- Add 150ms debounce to text field onChange handler
- Prevents excessive autocomplete calculations during rapid typing
- Add timer cleanup in onDisappear
- Works for both main chat and private chat inputs
2025-07-24 13:40:34 +02:00
jack bb6552f4a6 Add more spacing between chat messages
- Increased vertical padding from 1px to 2px per message
- Total spacing between messages now 4px (was 2px)
- Improves readability and visual separation
2025-07-24 13:34:21 +02:00
jack 354d3ff6ce Optimization 5: Fix animation overhead
- Removed redundant animation modifiers (multiple animations on same view)
- Replaced spring animations with simpler easeInOut/easeOut curves
- Spring animations are computationally expensive, now using 0.2s easeInOut
- Added scroll throttling to prevent excessive animations on message updates
- Scroll animations limited to once per 0.5 seconds
- Removed withAnimation wrapper from scrollTo calls
- Simplified drag gesture animations from spring to easeOut

This reduces CPU usage during UI transitions and message updates
2025-07-24 13:30:56 +02:00
jack 8d64920f8e Optimization 4: Batch message updates for better performance
- Added message batching system with 100ms window
- Created pendingMessages array for public messages
- Created pendingPrivateMessages dictionary for private messages
- Added scheduleBatchFlush() to consolidate updates
- Batch all incoming messages from didReceiveMessage
- Batch system messages (connect/disconnect/screenshot)
- Keep immediate updates for user's own sent messages
- Single UI update per batch instead of per message
- Flush pending messages on app background/terminate
- Clear timer on deinit

This reduces UI updates when multiple messages arrive quickly
2025-07-24 13:23:31 +02:00
jack 58876704c3 Bold user's own nickname in chat messages
- Added font weight logic to formatMessageAsText and formatMessage
- User's own @nickname appears bold (weight: .bold)
- Other nicknames remain medium weight
- Helps visually distinguish own messages from others
2025-07-24 13:18:12 +02:00
jack b51000939b Remove RSSI-based sender name coloring in chat messages
- Simplified getSenderColor to always return primary color
- Removed RSSI color calculation logic from formatMessageAsText
- Removed RSSI color calculation logic from formatMessage
- All sender names now use consistent green color
- RSSI information remains visible only in peer list
2025-07-24 13:16:47 +02:00
jack e13380fe27 Set message limit to 1337 and auto-trim oldest messages
- Added maxMessages constant set to 1337
- Added trimMessagesIfNeeded() to remove oldest messages when limit exceeded
- Added trimPrivateChatMessagesIfNeeded() for private chat limits
- Applied trimming after all message append operations:
  - Regular chat messages (sent and received)
  - Private messages (sent and received)
  - System messages (connect/disconnect/screenshot)
  - Message migrations between peer IDs
- Ensures chat history doesn't grow unbounded
2025-07-24 13:14:37 +02:00
jack f9d5a07542 Optimization 3: Add caching for expensive view computations
- Cache getRSSIColor results with key format: "\(rssi)_\(isDark)"
- Cache getEncryptionStatus results with peerID as key
- Add cache invalidation methods for both caches
- Invalidate encryption cache when:
  - Encryption status is updated
  - Fingerprints are verified
  - Peer authentication callbacks trigger
- Invalidate RSSI cache when peer list updates
- Clear all caches in panicClearAllData

This reduces redundant calculations during view updates and improves performance
2025-07-24 13:09:18 +02:00
jack 5d3512dfbc Add 1pt more padding around link preview box
- Increased padding from 9pt to 10pt for better visual spacing
- Improves readability and touch target size
2025-07-24 13:04:43 +02:00
jack 5a0c8f0a26 Add 1pt more padding around link preview box
- Increase top padding from 2pt to 3pt
- Add 1pt horizontal padding for better visual balance
2025-07-24 12:59:46 +02:00
jack c08fe38c72 Fix URL detection and message spacing
- Add URL detection to message formatting with blue color and underline
- Replace List with ScrollView for precise spacing control
- Use minimal vertical padding (1px) between messages
- Remove LazyLinkPreviewView, use LinkPreviewView directly
- URLs now appear highlighted in message text AND show preview below
2025-07-24 12:53:55 +02:00
jack b480a4836c Fix message spacing and remove markdown link support
- Reduce VStack spacing from 4 to 2 and nested VStack from 2 to 0
- Set list row insets top/bottom to 0 to minimize spacing on iPhone
- Remove all markdown link parsing and formatting
- Share plain URLs instead of markdown when using share extension
- Keep only plain text URL detection and preview functionality
2025-07-24 12:47:49 +02:00
jack f45c52e9d3 Optimize UI performance with message caching and List view
- Convert BitchatMessage from struct to class for efficient caching
- Cache formatted AttributedStrings to avoid expensive regex on every render
- Replace ScrollView+LazyVStack with native List for better cell reuse
- Implement message windowing (show last 100 messages for performance)
- Add LazyLinkPreviewView that defers loading for 0.5s to improve scroll performance

These optimizations significantly improve scroll performance, especially with large message lists.
2025-07-24 12:38:31 +02:00
jack a338008511 Remove nickname label from chat input box
- Remove <@nickname> label to simplify UI
- Add placeholder text "type a message..." for clarity
- Maintain consistent padding for input field
2025-07-24 12:22:50 +02:00
jack cc3a094205 Add nickname validation to prevent empty names
- Validate nickname only when field loses focus or on submit
- Replace empty nicknames with anon+random 4 digits (e.g. anon3847)
- Remove auto-save timer to prevent validation while typing
- Add FocusState to detect when user exits the field
2025-07-24 12:16:23 +02:00
jack c4ca38654d Improve private message notification behavior
- Don't show PM notifications when the private chat is already open
- Store peer ID in notification userInfo for reliable chat opening
- Tap notification to open the correct private chat using peer ID
- Check both in ChatViewModel (when receiving) and NotificationDelegate (when presenting)
2025-07-24 12:00:01 +02:00
jack b0204afa75 Add message action sheet for user interactions
- Tap any message to show action sheet with user options
- Actions include: private message, hug, slap, and block
- Only appears for messages from other users (not system or self)
- Integrates with existing chat commands (/hug, /slap, /block)
2025-07-24 11:54:09 +02:00
jack 0beee2fb27 Improve peer list UI polish
- Make entire peer list row tappable for starting private chats
- Fix separator bar visibility when private chat is fully open (offset by -1px)
- Keep favorite star as separate tap target
- Preserve double-tap gesture for showing fingerprints
2025-07-24 11:47:20 +02:00
jackandGitHub ad5ee7eb4c Merge pull request #308 from permissionlesstech/bluetooth-efficiency-optimization
Fix Bluetooth disconnect messages and blank chat rows
2025-07-23 21:36:53 +02:00
jack 1ec4b7fe50 Fix missing disconnect/connect messages when peers walk away
- Update peripheral ID to peer ID mapping for all message types including handshakes
- Ensure disconnect messages appear even if peer disconnects right after handshake
- Add detailed logging for peripheral mapping to help debug connection issues
- Fix blank message rows by ensuring display names are never empty
2025-07-23 21:35:22 +02:00
jack 391c80ef14 Fix blank message row and API misuse warnings
- Fix blank row appearing when peer disconnects by ensuring display names are never empty
- Add validation to prevent system messages with empty content from being displayed
- Fix API MISUSE warnings by adding connection state checks before writing to peripherals
- Improve write queue processing with additional safety checks
- Update activity tracking when processing queued writes

These fixes address UI glitches and improve Bluetooth reliability.
2025-07-23 21:02:51 +02:00
jack a33ba1678b Implement Bluetooth efficiency optimizations
- Add in-memory cache for peer public keys with TTL to reduce keychain I/O
- Implement write queue for disconnected peripherals with backpressure handling
- Add connection pooling limits with LRU eviction when pool is full
- Track peripheral activity for intelligent connection management
- Replace all direct peripheral.writeValue calls with new writeToPeripheral method
- Add automatic cleanup of expired cache entries and write queues

These optimizations reduce battery consumption and improve performance by:
- Minimizing expensive keychain operations
- Queueing writes instead of dropping them when peripherals disconnect
- Limiting concurrent connections to prevent resource exhaustion
- Implementing intelligent connection management based on usage patterns
2025-07-23 20:29:41 +02:00
jackandGitHub 169a25bb62 Merge pull request #305 from permissionlesstech/robust-connection-state
Fix handshake deadlock and improve connection reliability
2025-07-23 19:05:28 +02:00
jack 2759202616 Fix NoiseSessionManager to always accept handshake initiations
Previously, NoiseSessionManager would reject handshake initiations if it had an existing established session. This caused deadlocks when one peer cleared their session (e.g., after decryption failure) but the other peer rejected the new handshake.

Changes:
- NoiseSessionManager now always accepts handshake initiations, clearing any existing session
- Added comprehensive tests for handshake recovery scenarios
- Tests verify proper re-establishment after decryption failures and nonce desynchronization
2025-07-23 19:03:41 +02:00
jack a84d6f22ef Fix handshake deadlock after decryption failure
Always accept handshake initiations even with valid sessions, as the peer must have cleared their session for a good reason (e.g., decryption failure). This prevents deadlock where one peer has no session while the other maintains an invalid one.
2025-07-23 18:22:39 +02:00
jackandGitHub d1d4434b66 Merge pull request #304 from permissionlesstech/noise-handshake-improvements
Fix Noise handshake stability and session synchronization
2025-07-23 15:13:57 +02:00
jack 557d5b915e Fix unused variable warning in integration tests
Replace unused 'decrypted' binding with underscore to suppress warning
2025-07-23 15:10:29 +02:00
jack 558bc52881 Add comprehensive tests for Noise handshake stability improvements
- Add test for peer restart detection and session recovery
- Add test for nonce desynchronization detection
- Add test for concurrent encryption thread safety
- Add test for session stale detection
- Add test for handshake after decryption failure
- Add integration test for peer presence tracking and reconnection
- Add integration test for encrypted messages after peer restart

These tests ensure:
- Sessions properly recover when a peer restarts
- Nonce desynchronization is detected correctly
- Encryption operations are thread-safe under concurrent load
- Identity announcements are sent on reconnection after silence
- Encrypted messages work after session re-establishment
2025-07-23 15:04:42 +02:00
jack d912da5898 Fix Noise handshake stability and session synchronization issues
- Add peer presence tracking with lastHeardFromPeer to detect reconnections
- Automatically send identity announcement when detecting peer reconnection after 30s
- Clear stale sessions when receiving handshake from recently-seen peer (likely restart)
- Add peers to activePeers when successfully decrypting their messages
- Fix thread safety in handshake coordinator with concurrent collections
- Extend message delivery timeouts (30s→120s private, 60s→180s room, 300s→600s favorite)
- Add per-peer encryption queues to prevent nonce desynchronization
- Make NoiseSession encrypt/decrypt operations thread-safe with barrier flag
- Initialize lastSuccessfulMessageTime when handshake completes
- Send identity announcement when decryption fails to prompt session reset
- Improve handshake state logging and debugging

This fixes:
- Peers stuck in "establishing encryption" after restart
- Nonce desynchronization causing "Decryption failed at nonce N"
- Asymmetric peer visibility (one peer sees the other but not vice versa)
- Thread safety issues causing crashes with pendingPrivateMessages
- Sessions marked as stale immediately after establishment
2025-07-23 14:57:15 +02:00
jack 9cf59651bb Clear handshake coordinator state during panic mode
When panic mode is triggered (triple tap on logo), it now properly clears:
- All handshake coordinator states
- Handshake attempt times
- Notifies UI that all peers are disconnected

This fixes the issue where handshake states would persist after clearing identity, causing confusion when the device showed "zero peers connected" but still had established handshake states in logs.

Also ensures UI is properly notified to update the peer list to empty.
2025-07-23 11:16:13 +02:00
jack 1e67bb4fd1 Improve UI update triggers for encryption status
Added multiple UI update triggers to ensure the lock icon updates:
1. In onPeerAuthenticated callback when handshake completes
2. When detecting an already established session on reconnect

This ensures the encryption status is reflected in the UI immediately after:
- Initial handshake completion
- Reconnection with existing session
- Peer authentication events
2025-07-23 10:59:21 +02:00
jack 61d267db5e Fix UI not updating lock icon after handshake completion
The handshake was completing successfully but the UI wasn't being notified to update the encryption status icon. Added a delegate notification after handshake completion to trigger updateEncryptionStatusForPeers() in the UI.

This ensures the lock icon changes from empty to filled when encryption is established.
2025-07-23 10:54:47 +02:00
jack fb35d59dc9 Fix session migration state mismatch after peer restart
When a peer restarts and gets a new peer ID, the session migration was only happening on one side, causing a state mismatch where one peer had an encrypted session but the other didn't.

Changed approach to clear the old session instead of migrating it, ensuring both peers establish a fresh handshake after ID rotation. This fixes the issue where one peer shows empty lock (no encryption) while the other shows lock with circle (encryption established).
2025-07-23 10:35:13 +02:00
jack 0243397ba2 Fix Noise handshake failures and implement binary protocol migration
## Summary
- Added timestamps to SecureLogger for precise timing analysis
- Implemented NoiseHandshakeCoordinator to prevent race conditions
- Added deterministic role selection based on peer ID comparison
- Implemented proper handshake state machine with retry logic
- Added duplicate message detection for handshake messages
- Improved logging and diagnostics for handshake debugging

## Details
The coordinator ensures only one peer initiates handshakes by using deterministic role selection (lower peer ID initiates). This prevents the simultaneous handshake attempts that were causing failures. The state machine tracks handshake progress and handles retries with exponential backoff.

## Testing
Successfully builds with no errors or warnings. The implementation should resolve the "establishing encryption" stuck state issue by ensuring proper handshake coordination between peers.
2025-07-23 10:19:45 +02:00
jackandGitHub b461399743 Update BRING_THE_NOISE.md 2025-07-23 09:33:07 +02:00
jackandGitHub 6be5d2587f Merge pull request #303 from permissionlesstech/feature/comprehensive-test-suite
Add comprehensive test suite
2025-07-23 09:29:01 +02:00
jack 847d333366 Fix all compilation errors and warnings in test suite
- Fixed mock service property overrides to match base class properties
- Added missing CryptoKit imports where needed
- Fixed immutable property assignments by creating new instances
- Replaced XCTAssertThrows with XCTAssertThrowsError
- Fixed DeliveryAck serialization method names (serialize -> encode)
- Fixed unused variable warnings
- Ensured all BitchatPacket modifications create new instances
- Fixed BitchatMessage property mutations by creating new instances

All test targets now build successfully for both iOS and macOS platforms.
2025-07-23 09:25:57 +02:00
jack 96136ec364 Add comprehensive test suite for bitchat
- Created test utilities and helpers for common test operations
- Implemented Binary Protocol tests covering encoding/decoding, compression, and padding
- Added Noise Protocol tests for handshake, encryption, and session management
- Created Public Chat E2E tests for broadcasting, routing, TTL, and mesh topologies
- Implemented Private Chat E2E tests for direct messaging, delivery ACKs, and retry logic
- Added Integration tests for multi-peer scenarios, network resilience, and mixed traffic patterns
- Created mock implementations for BluetoothMeshService and NoiseSession

Test coverage includes:
- Protocol layer (binary encoding, message serialization)
- Security layer (Noise handshake, encryption/decryption)
- Application layer (public/private messaging, delivery tracking)
- Network scenarios (mesh topology, partitions, churn)
- Performance and stress testing
2025-07-23 08:56:13 +02:00
jackandGitHub fd0ef35487 Merge pull request #302 from permissionlesstech/remove-private-channels
Remove all channel functionality and clean up test suite
2025-07-23 01:35:31 +02:00
jack f53e163d25 Remove all channel functionality and clean up test suite
- Remove channel UI elements from ContentView
- Remove channel data structures and methods from ChatViewModel
- Remove channel commands (/j, /leave, /channels)
- Remove channel field from BitchatMessage protocol
- Remove channel message types and handling
- Remove NoiseChannelEncryption.swift entirely
- Clean up all channel references across the codebase
- Fix compilation warnings (var to let conversions)
- Remove all outdated test files that used incorrect APIs
- Simplify app to only support public broadcast and 1:1 private messages
2025-07-23 01:33:54 +02:00
jackandGitHub c8088f785c Update README.md 2025-07-23 00:50:43 +02:00
jackandGitHub 1ecf8f1709 Update README.md 2025-07-23 00:49:11 +02:00
jackandGitHub 36bda0821f Merge pull request #301 from permissionlesstech/convert-to-secure-logger
Convert all print statements to SecureLogger
2025-07-22 21:08:39 +02:00
jackandClaude 70d8c78a76 Convert all print statements to SecureLogger
- Replaced all print() calls with appropriate SecureLogger.log() calls
- Used proper categories: noise, encryption, session, security
- Applied appropriate log levels: debug, info, warning, error
- Converted 25 prints in BluetoothMeshService.swift
- Converted 1 print in ChatViewModel.swift
- Converted 8 prints in DeliveryTracker.swift
- Test files kept as-is for debugging purposes
- Verified successful build on iOS

This improves security by using structured logging that can filter sensitive data.

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-07-22 20:59:11 +02:00
jackandGitHub 2e46421dcb Merge pull request #297 from permissionlesstech/delete-BinaryMessageHandler
(chore) remove unused file BinaryMessageHandler.swift
2025-07-22 20:18:22 +02:00
jackandGitHub 22449ff20b Merge pull request #295 from permissionlesstech/network-notifications
Add network availability notifications
2025-07-22 17:47:32 +02:00
jack b849cfbad3 Remove debug logging from notification system
- Clean up all temporary logging statements
- Production-ready notification implementation
- Network notifications trigger when peers become available
2025-07-22 17:42:53 +02:00
jack 79243c8fca Reduce notification timing for better UX
- Network empty reset delay: 5 min → 1 min
- Notification cooldown: 10 min → 5 min
- More responsive when peers drop and rejoin
- Still prevents spam from flaky connections
2025-07-22 16:53:33 +02:00
jack f7b4fb815b Fix compilation error and add peer tracking logs
- Remove reference to undefined wasInserted variable
- Add proper logging after wasInserted is defined
- Track when peers are added vs already present
2025-07-22 16:50:25 +02:00
jack 3d3c711885 Remove app state checks to fix thread issues
- Completely remove UIApplication/NSApplication state checks
- Let NotificationDelegate handle foreground presentation
- All notifications now sent regardless of app state
- Fixes all thread checker warnings
2025-07-22 16:47:04 +02:00
jack 29c0fdca21 Fix macOS thread checker warning
- Move all app state checks inside DispatchQueue.main.async
- Ensures NSApplication.isActive is only accessed from main thread
- Prevents thread checker warnings on macOS
2025-07-22 16:46:03 +02:00
jack 7b81dd4c0d Fix remaining thread safety issues in notifications
- Favorite notifications now bypass sendLocalNotification to avoid thread issues
- All notification code properly wrapped in DispatchQueue.main.async
- Added logging for favorite notifications
- Network and favorite notifications now work independently
2025-07-22 16:44:34 +02:00
jack 9f42d91903 Fix thread safety issue for notifications
- Wrap UIApplication.applicationState access in DispatchQueue.main.async
- Network notifications bypass app state check entirely
- Added more detailed logging for debugging
- Notifications now handled properly from background threads
2025-07-22 16:41:43 +02:00
jack 537d489daa Fix network notifications and add debugging
- Network notifications now show even when app is in foreground
- Added unique identifiers to prevent iOS deduplication
- Set interruptionLevel to timeSensitive for prominence
- Added comprehensive logging throughout notification flow
- Improved error handling for notification permissions
2025-07-22 16:39:56 +02:00
jack 3194da8f85 Add anti-spam protection for network availability notifications
- 10 minute cooldown between notifications
- 5 minute hysteresis before resetting notification flag after network becomes empty
- Prevents spam when peers briefly disconnect/reconnect
- Emergency disconnect immediately resets all notification state
2025-07-22 16:35:28 +02:00
jack 79d9f8ee88 Add network availability notifications when bitchatters are nearby
- Show notification when network transitions from empty to having peers
- Single notification per session, resets when network becomes empty
- Background Bluetooth modes enabled for iOS
- Generic message: 'bitchatters nearby\! 1 person around' or 'X people around'
2025-07-22 16:32:07 +02:00
jackandGitHub cdaa3dadc2 Merge pull request #294 from permissionlesstech/ui-improvements
UI improvements and performance optimizations
2025-07-22 16:20:35 +02:00
jack 8f9df5beb3 UI improvements and performance optimizations
- Changed toolbar text from "bitchat*" to "bitchat/" with tighter spacing
- Removed blue intro message when no peers are connected
- Changed RSSI indicator back to simple dot instead of radiowaves icon
- Added triple-tap gesture on chat area to clear current context
- Improved LinkPreviewView performance with metadata caching
- Moved link previews closer to messages for better visual connection
- Fixed AppInfoView duplication by consolidating strings into single location
- Better error handling for link preview ATS errors
2025-07-22 16:19:40 +02:00
jackandGitHub 849da32947 Merge pull request #293 from permissionlesstech/enhance-logging-framework
Enhance logging framework and fix build issues
2025-07-22 15:41:25 +02:00
jack aaa7e2bf28 Enhance logging framework and fix build issues
- Rename SecurityLogger to SecureLogger for better clarity
- Add file:line:function tracking to all log entries
- Optimize logging with pre-compiled regex patterns and NSCache
- Add comprehensive logging for critical protocol flow points
- Fix iOS entitlements to include Bluetooth permission
- Fix VersionHello field name and optional chaining issues
- Fix Package.swift resource warnings
- Fix test compilation errors with proper type annotations
2025-07-22 15:40:13 +02:00
jackandGitHub 49daa995cc Delete .github/workflows directory 2025-07-22 15:23:15 +02:00
jackandGitHub 960d47336a Merge pull request #292 from permissionlesstech/binary-protocol-migration
Fix Noise handshake failures and implement binary protocol migration
2025-07-22 14:53:14 +02:00
jack 5e726f993e Fix Noise handshake failures and implement binary protocol migration
- Fix asymmetric handshake state causing message delivery failures
- Prevent duplicate handshake init messages from disrupting ongoing handshakes
- Add defensive copying to all binary decoders to prevent thread safety issues
- Implement binary encoding for all 9 message types (60-80% bandwidth reduction)
- Fix delivery ACK decoding for Noise encrypted messages
- Add comprehensive logging for debugging handshake and message flow
- Fix race condition in delivery status updates
- Add relay logic for handshake packets to ensure mesh delivery
- Maintain backward compatibility with JSON fallback
2025-07-22 14:52:33 +02:00
jack 7579612c61 Migrate protocol from JSON to binary encoding
This change introduces a comprehensive binary protocol to replace JSON encoding
for all network messages, resulting in ~70% bandwidth reduction and 10-20x
faster parsing.

Key changes:
- Add BinaryEncodingUtils with common binary encoding/decoding operations
- Implement toBinaryData/fromBinaryData for all 9 message types
- Maintain backward compatibility with JSON fallback
- Add safety checks including minimum size validation and data copying
- Fix thread safety issues with concurrent data access
- Update all message handlers to try binary first, then JSON

Benefits:
- Reduced bandwidth usage (critical for Bluetooth)
- Faster message parsing
- Better MTU efficiency
- Eliminates JSON injection vulnerabilities
- Consistent binary format throughout the protocol

The implementation maintains full backward compatibility - new messages are
sent as binary while the app can still receive and process JSON messages
from older clients.
2025-07-22 14:12:39 +02:00
jackandGitHub 8ee3f306e7 Merge pull request #271 from ryannair05/patch-1
Fix Crash when receiving notification from the background
2025-07-22 11:46:34 +02:00
jackandGitHub 327869cbdc Merge pull request #281 from zeugmaster/reduce-fragment-size
Reduce fragment size
2025-07-22 11:45:47 +02:00
jackandGitHub 06a7003924 Merge pull request #291 from permissionlesstech/cleanup-dead-code
Remove dead code and fix warnings
2025-07-22 11:44:46 +02:00
jack a09c5f6461 Remove CONSOLE_WARNINGS.md 2025-07-22 11:43:43 +02:00
jack b3d1d8e4e1 Document benign console warnings
Add documentation explaining the harmless system-level warnings:
- CFPrefsPlistSource warning from UserDefaults with app groups
- "Failed to get or decode unavailable reasons" from CoreBluetooth

These are Apple framework issues that don't affect functionality
and appear in many production iOS apps.
2025-07-22 11:42:34 +02:00
jack 128b19496d Fix remaining Swift 6 warnings about unused results
- Add explicit discarding of Set.remove results in sync blocks
- Add explicit discarding of Dictionary.removeValue results
- Ensures completely clean builds with no warnings

All instances of remove/removeValue inside sync blocks now
explicitly discard their return values to satisfy Swift 6.
2025-07-22 11:40:28 +02:00
jack 9e035c9c14 Fix Swift 6 warning about unused result
- Add explicit discarding of removeValue results in NoiseSession
- Remove unnecessary _ = from BluetoothMeshService sync block
- Ensures clean builds with no warnings (except AppIntents metadata)

The warning was caused by Swift 6 being stricter about unused
results from methods that return values inside sync blocks.
2025-07-22 11:38:20 +02:00
jack d804b93488 Fix compilation errors and warnings
- Fix redundant underscore warnings in NoiseSession.swift
- Replace non-existent handlePeerDisconnection with proper cleanup code
- Remove invalid showSystemMessage call, use didDisconnectFromPeer instead
- Clean up peer state when version negotiation fails

The project now builds successfully for iOS with only minor warnings
about metadata extraction for app intents (which can be ignored).
2025-07-22 11:33:51 +02:00
jack 673f6a76dd Remove more dead code
- Remove unused loggedCryptoErrors property from BluetoothMeshService
- Remove unused error cases from NoiseEncryptionError:
  - invalidMessage (never thrown)
  - handshakeFailed(Error) (never thrown)

These were identified during deeper code analysis and are
confirmed to be unused throughout the codebase.
2025-07-22 11:26:18 +02:00
jack ce6e90701c Remove dead code and placeholders
- Remove NoisePostQuantum.swift entirely (placeholder with no implementation)
- Remove Double Ratchet placeholder code from NoiseChannelKeyRotation.swift
- Remove NoisePostQuantumTests that tested mock implementations
- Handle TODO for version negotiation rejection (now properly disconnects)
- Remove legacy comment about removed message type 0x02
- Keep deprecated ownerID field as it's still used for compatibility

This cleanup removes ~400 lines of placeholder code that was not
being used and unlikely to be implemented in the near future.
2025-07-22 11:20:07 +02:00
jackandGitHub 9fef19a595 Merge pull request #289 from permissionlesstech/implement-ed25519-signatures
Implement Ed25519 signatures and fix session management
2025-07-22 11:10:43 +02:00
jack 8fccbe69b9 Fix session destruction race condition causing handshake delays
Root cause: When receiving a handshake initiation (32 bytes) from a peer
with whom we already had an established session, the code would destroy
the existing session to "help" the other side. This created a cascade:
- Peer A completes handshake with Peer B
- Peer A sends message, realizes no session, initiates handshake
- Peer B destroys its working session to "help"
- Peer B now has no session, initiates handshake
- Both peers keep destroying each other's sessions

Fix:
- Never destroy an established session when receiving new handshake attempts
- Add early check in handshake initiation to skip if session exists
- Clear handshake rate limit timers when session already established

This eliminates the delays and repeated handshakes seen in the logs.
2025-07-22 11:06:57 +02:00
jack 0be35a5378 Fix Noise session persistence during peer ID rotation
- Add session migration when peer IDs rotate
- Sessions now follow peers across ID changes via fingerprint
- Add migratePeerSession to NoiseEncryptionService
- Add migrateSession to NoiseSessionManager
- Integrate migration in BluetoothMeshService updatePeerBinding

This fixes the issue where established Noise sessions were lost
when peer IDs rotated, causing "No Noise session" errors and
requiring re-handshake.
2025-07-22 11:01:24 +02:00
jack 83a808fce6 Implement Ed25519 signatures for identity announcements
- Add Ed25519 signing key pair to NoiseEncryptionService
- Update NoiseIdentityAnnouncement to include signingPublicKey
- Replace HMAC signatures with proper Ed25519 signatures
- Fix timestamp synchronization between signing and verification
- Add signature verification in PeerIdentityBinding
- Persist signing keys in keychain alongside Noise static keys

This provides cryptographic non-repudiation for peer identity claims
and strengthens the security of the identity rotation mechanism.
2025-07-22 10:50:47 +02:00
jackandGitHub 079f36664c Merge pull request #254 from permissionlesstech/remove-message-retention-and-save
Remove message retention and /save command
2025-07-16 16:00:08 +02:00
jack b61904bee9 Remove message retention and /save command
- Delete MessageRetentionService.swift
- Remove retentionEnabledChannels from ChatViewModel
- Remove /save command handling
- Remove retention UI elements from ContentView
- Remove channelRetention message type from protocol
- Update documentation and tests
2025-07-16 15:59:38 +02:00
jackandGitHub fcc0735928 Merge pull request #253 from permissionlesstech/ui/move-verified-badge-position
Move encryption status icons and implement slide-over navigation
2025-07-16 15:39:32 +02:00
jack ee2c7550d1 Move encryption status icons after peer names and implement slide-over navigation
- Moved encryption/handshake status icons to appear after peer names in sidebar and private message headers
- Converted private messages and channels to slide-over views with smooth transitions
- Added swipe-right gesture to dismiss private chats and channels
- Added vertical separator bars to slide-over views for visual consistency
2025-07-16 15:38:20 +02:00
jack 17e96e9993 Replace RSSI dot with radio wave icon in sidebar 2025-07-16 00:49:06 +02:00
jackandGitHub 92a8bab411 Merge pull request #246 from permissionlesstech/feat/protocol-version-negotiation
Add protocol version negotiation
2025-07-15 14:37:30 +02:00