CRITICAL BUG FIX: Spam filter was blocking Bluetooth mesh messages
PROBLEM
=======
SpamFilterService was being applied to ALL public messages including
local Bluetooth mesh messages. This caused legitimate back-and-forth
chat to be rate-limited and dropped.
Logs showed:
Rate limited message from mesh:... (sender:false content:true)
The sender token bucket (capacity: 5, refill: 1/sec) was exhausted
during normal conversation, blocking messages.
ROOT CAUSE
==========
When extracting SpamFilterService, the spam filter was applied to both:
- Geohash/Nostr messages (from internet - spam risk HIGH)
- Mesh/Bluetooth messages (local trusted peers - spam risk LOW)
Mesh messages should NOT be aggressively rate-limited since they come
from local trusted peers over Bluetooth.
SOLUTION
========
Changed spam filter to ONLY apply to geohash messages:
Before:
if !spamFilter.shouldAllow(message) { return }
After:
if isGeo && !spamFilter.shouldAllow(message) { return }
Now mesh messages bypass spam filter entirely, while geohash messages
from internet still get rate-limited protection.
IMPACT
======
✅ Mesh messages now flow freely (no artificial rate limiting)
✅ Geohash messages still protected from spam
✅ Normal back-and-forth chat works correctly
✅ Tests still passing
This fix is critical for usability - mesh chat is the core feature.
Continues god object decomposition by extracting peer color assignment logic.
WHAT WAS EXTRACTED
==================
Removed from ChatViewModel (248 net lines):
- Peer palette dictionaries and state (6 dictionaries)
- peerColor() function (20 lines)
- getPeerPaletteColor() function (17 lines)
- getNostrPaletteColor() function (20 lines)
- rebuildPeerPaletteIfNeeded() function (69 lines)
- rebuildNostrPaletteIfNeeded() function (96 lines)
- meshSeed() helper (6 lines)
- Minimal-distance color assignment algorithm (140 lines)
NEW SERVICE
===========
bitchat/Services/ColorPaletteService.swift (330 lines)
Features:
- Minimal-distance hue assignment algorithm
- Separate palettes for mesh/Nostr peers
- Light/dark mode support
- Deterministic color assignment with stability
- Fallback to seed-based colors
API:
- colorForMeshPeer() - Get color for mesh peer
- colorForNostrPubkey() - Get color for Nostr participant
- peerColor() - Auto-detect type and assign color
- reset() - Clear state for testing
INTEGRATION
===========
Updated ChatViewModel wrapper functions:
- colorForNostrPubkey() - now delegates to ColorPaletteService
- colorForMeshPeer() - now delegates to ColorPaletteService
- formatMessageAsText() - uses colorPalette.peerColor()
Removed duplicate Color(peerSeed:isDark:) extension from
ColorPaletteService (already exists in Utils/Color+Peer.swift with caching).
IMPACT
======
ChatViewModel: 6,111 → 5,863 lines (-4.1% this commit, -5.4% cumulative)
New service: +330 lines (focused, testable)
Tests: ✅ All 23 passing
Build: ✅ Clean (5.96s)
Cumulative god object reduction: -384 lines (6.2% total)
Services extracted: 2 (SpamFilterService, ColorPaletteService)
* Location notes: fix performance and UI issues
Performance fixes:
- Add Set-based duplicate detection (O(1) vs O(n) lookup)
- Eliminates lag when receiving 200+ notes during EOSE
Correctness fixes:
- Fix optimistic echo timestamp to match signed event timestamp
- Add echo IDs to noteIDs set for consistency
UI improvements:
- Remove duplicate "loading recent notes" text in header
- Simplify toolbar icon color logic for immediate green indication
- Icon now reliably turns green when notes exist in geohash
Tests: All 3 LocationNotes tests passing
* Location notes: add remaining robustness fixes
Additional improvements:
- Align counter/manager limits to 200 (prevents showing count higher than displayable)
- Set loading state before clearing notes to eliminate UI flicker on geohash change
- Add geohash validation for building-level precision (8 valid base32 chars)
- Add defensive 500-note memory cap with automatic trimming
- Clear stale notesGeohash state on sheet dismiss
Tests:
- Fix test geohashes to use valid base32 characters
- All 3 LocationNotes tests passing
---------
Co-authored-by: jack <jackjackbits@users.noreply.github.com>
The camera scanner was continuously detecting the same QR code (10-30+ times/second), causing multiple verification notifications to be sent. This happened because:
1. AVCaptureMetadataOutput fires repeatedly while QR is visible
2. Each detection triggered a new verification flow
3. After receiving response, pendingQRVerifications was cleared, allowing duplicate scans
Changes:
- Add deduplication using lastValid state to ignore re-scans of same QR code
- Only set lastValid after successful verification initiation
- Add onSuccess callback to close scanner after successful scan
- Automatically return to "My QR" view after verification starts
- Apply same logic to both iOS camera and macOS manual input paths
This ensures exactly one verification request per scan session.
Co-authored-by: jack <jackjackbits@users.noreply.github.com>
Problem:
- Ghost peers from yesterday appeared on app restart
- Old messages resurfaced after restarting
- Peers running 24+ hours synced stale data to restarting peers
Root causes:
1. GossipSyncManager stored packets indefinitely (no time limit)
2. handleAnnounce/handleMessage had no timestamp validation
3. Relayed announces from other peers could be arbitrarily old
Solution (defense in depth):
- Added 15-minute age window to GossipSyncManager config
- Gossip storage rejects expired packets at ingestion
- Gossip sync responses filter out expired packets
- GCS payload building excludes expired packets
- Periodic cleanup removes expired announcements/messages
- handleAnnounce rejects stale announces before processing
- handleMessage rejects stale broadcast messages before processing
This prevents ghost peers from appearing on restart and ensures
only recent mesh state is synchronized between peers.
Co-authored-by: jack <jackjackbits@users.noreply.github.com>
* enabled drag gesture to close the sidebar view
* removed extraneous onChanged block
* Fix sidebar swipe gestures to work with ScrollView
Improvements:
- Use simultaneousGesture() instead of gesture() to work alongside ScrollView
- Add horizontal-only detection (width > height * 1.5) to prevent interfering with vertical scrolling
- Add visual feedback during drag with sidebarDragOffset updates
- Add 20pt right edge zone for easier swipe-to-open activation (iOS-native behavior)
- Lower threshold for edge swipe (-50pt instead of -100pt)
Both swipe-to-open and swipe-to-close now work reliably:
- Swipe left from anywhere (or from right edge) to open sidebar
- Swipe right on sidebar to close it
- Vertical scrolling unaffected
* Fix sidebar drag offset direction
Changed offset calculation from:
showSidebar ? -dragOffset : width - dragOffset
To:
showSidebar ? dragOffset : width + dragOffset
This fixes the issue where dragging right to close the sidebar would
make it fly to the left side of the screen before closing.
Now the sidebar correctly follows the finger during drag:
- When closing: moves right (toward off-screen)
- When opening: moves left (toward on-screen)
* Optimize sidebar drag performance for smooth 60fps
Performance improvements:
- Remove .animation() modifier that was conflicting with drag updates
- Use Transaction with disablesAnimations during drag for instant updates
- Throttle state updates to only fire when offset changes >2pt
- Always render sidebar (avoid conditional view creation overhead)
- Only animate on gesture end, not during drag
This eliminates the lag/jank during swipe by ensuring:
1. No animation conflicts during manual drag
2. Direct offset updates follow finger immediately
3. Stable view hierarchy (no conditional rendering)
4. Reduced state update frequency
The sidebar now feels buttery smooth at 60fps.
---------
Co-authored-by: jack <jackjackbits@users.noreply.github.com>
* Fix test suite peer ID collisions
Use unique peer IDs for each test suite to prevent global registry
collisions when Swift Testing runs suites in parallel.
- PrivateChatE2ETests: PRIV_* prefix
- PublicChatE2ETests: PUB_* prefix
- Update all peer ID references to use actual instance IDs
This fixes the race condition where simplePublicMessage() was receiving
duplicate deliveries due to registry contamination.
* Add Bluetooth permission & state alerts on launch and foreground
Wire up existing Bluetooth alert infrastructure to show notifications
when Bluetooth is off, unauthorized, or unsupported.
Changes:
- Add didUpdateBluetoothState() to BitchatDelegate protocol
- BLEService now notifies delegate when Bluetooth state changes
- ChatViewModel implements delegate method to show alerts
- Check Bluetooth state on app launch (after 100ms delay)
- Check Bluetooth state when app comes to foreground
- Add getCurrentBluetoothState() method to BLEService
The UI alert already existed but wasn't wired up. Now users will see
appropriate alerts for:
- Bluetooth turned off
- Bluetooth permission denied
- Bluetooth unsupported on device
Alert includes a button to open Settings on iOS.
---------
Co-authored-by: jack <jackjackbits@users.noreply.github.com>
Use unique peer IDs for each test suite to prevent global registry
collisions when Swift Testing runs suites in parallel.
- PrivateChatE2ETests: PRIV_* prefix
- PublicChatE2ETests: PUB_* prefix
- Update all peer ID references to use actual instance IDs
This fixes the race condition where simplePublicMessage() was receiving
duplicate deliveries due to registry contamination.
Co-authored-by: jack <jackjackbits@users.noreply.github.com>
* Swift Testing: `PrivateChatE2ETests` + minor refactor
* Swift Testing: `PublicChatE2ETests`
* Swift Testing: `FragmentationTests`
* Fix MockBLEService init to accept PeerID and remove _testRegister call
* Add peerID property to MockBLEService and fix ttlDecrement test
* Remove duplicate peerID property and fix type comparisons
---------
Co-authored-by: jack <jackjackbits@users.noreply.github.com>
* Rearrange `Transport`’s properties and functions
* `NostrTransport`: group Transport-related code together
* `BLEService`: group Transport-related code together
* Extract `NotificationStreamAssembler` into a file
* Move private functions to a dedicated extension
* PeerID 14/n: `Transport` and its dependents
* Noise types use PeerID
* Fix tests
* Extract `NoiseSessionManager` into a separate file
* Extract `NoiseSessionState` into a separate file
* Remove `failed` state from `NoiseSessionState`
* Extract `NoiseSessionError` into a separate file
* PeerID 12/n: `GossipSyncManager`
* Noise types use PeerID
* Fix tests
* Extract `NoiseSessionManager` into a separate file
* Extract `NoiseSessionState` into a separate file
* Remove `failed` state from `NoiseSessionState`
* Extract `NoiseSessionError` into a separate file
* Extract Tor into a separate module
* Add Tor package as a dependency for iOS & macOS targets
* Move `tor-nolzma.xcframework` inside Tor
* Remove `libz` from Frameworks as its linked in Tor
* Remove stray `.gitkeep` from macOS target membership
* Fix missing import and access control for modularized Tor
- Add import Tor to NetworkActivationService
- Make TorManager.shutdownCompletely() public for external access
* Fix tor-nolzma.xcframework structure for Xcode builds
- Add missing Info.plist files to all framework slices
- Restructure macOS framework to use deep bundle format (Versions/)
- Keep iOS frameworks as shallow bundles (standard for iOS)
This fixes the Xcode build errors while maintaining SPM compatibility.
* Remove stale xcframework references from Xcode project
Xcode cleaned up old direct references to tor-nolzma.xcframework
since it's now managed internally by the Tor Swift package.
---------
Co-authored-by: jack <jackjackbits@users.noreply.github.com>
* Update .gitignore to not ignored shared settings
`xcshareddata/` should be added to the repo to sync the scheme settings (like running parallel tests or turning on code coverage…)
* Add `bitchat (iOS)` shared scheme
* Parallelized and randomized test execution
* Gather code coverage for `bitchat_iOS` target
* Move LocalizationCatalogTests out of Localization/
SPM is treating all the files under Localization as a resource as per the Package.swift, hence it’s not even building it
* Use a class object vs struct to fix build issue
* Explicitly check that the output is not a l10n key
* Remove skipped test