* Fix iOS BLE mesh authentication bypass chain in BLEService
- Bind sender IDs to BLE connection UUIDs for peripherals and centrals to prevent spoofing
- Enforce explicit RSR request/response validation and remove legacy TTL==0 RSR path
- Remove TTL==0 unconditional acceptance for messages and file transfers
- Ensure gossip sync caching only occurs after a packet is accepted
- Preserve self‑sync TTL==0 dedup exception without weakening authentication
* fix: toctou in boundPeerID identified by codex
* fix: Remove unused variable and bump version to 1.5.1
- Remove unused messageType variable (compiler warning fix)
- Bump marketing version to 1.5.1
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
---------
Co-authored-by: jack <212554440+jackjackbits@users.noreply.github.com>
Co-authored-by: jack <jackjackbits@users.noreply.github.com>
Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
* feat: Implement Request Sync Manager (V2 Sync)
- Add RequestSyncManager to track and attribute sync requests
- Update BitchatPacket and BinaryProtocol to support IS_RSR flag (0x10)
- Update RequestSyncPacket with new TLV fields (sinceTimestamp, fragmentIdFilter)
- Update GossipSyncManager to use unicast sync requests and mark responses as RSR
- Update BLEService to enforce timestamp validation for normal packets and exempt valid RSRs
- Add documentation for the new sync manager mechanism
* fix: Resolve compilation errors in V2 Sync implementation
- Remove duplicate restartGossipManager in BLEService
- Add missing TransportConfig constants for sync
- Add 'sync' log category to BitLogger
- Add missing BitLogger import in GossipSyncManager
* fix: Update tests for V2 Sync changes
- Add requestSyncManager parameter to GossipSyncManager init in tests
- Implement getConnectedPeers stub in RecordingDelegate
- Remove unused variable warning in SubscriptionRateLimitTests
---------
Co-authored-by: a1denvalu3 <>
Co-authored-by: jack <212554440+jackjackbits@users.noreply.github.com>
* Improve BLE mesh reliability for large transfers
Major reliability improvements for fragment-based transfers (photos, files):
**Notification Queue Fixes**
- Fix silent packet loss when notification queue is full - now queues for retry
- Fix retry queue bug where remaining items were lost when one retry failed
- Add periodic drain mechanism as backup (every 5 seconds)
**Write Queue Fixes**
- Fix drainPendingWrites to use atomic take-send-requeue pattern
- Add logging when peripheral is ready for more writes
- Add periodic drain for pending writes as backup
**Fragment Pacing**
- Increase fragment spacing from 4-5ms to 25-30ms to prevent buffer overflow
- Conservative pacing prevents packet loss on congested BLE connections
**Thread Safety**
- Fix race conditions in stopServices() and emergencyDisconnectAll()
- Synchronize access to peripherals/centrals dictionaries during cleanup
- Clear pending message queues in emergencyDisconnectAll()
**Error Recovery**
- Add handlers for all BLE state transitions (poweredOff, unauthorized, etc.)
- Clear Noise session and re-initiate handshake on decryption failure
- Queue ACKs/receipts for delivery after handshake instead of dropping
- Re-queue failed pending messages for retry
**Other Improvements**
- Add route freshness validation in MeshTopologyTracker (60s threshold)
- Add TTL (24h) and size limits (100 per peer) for MessageRouter outbox
- Fix connection timeout to check peripheral.state before canceling
- Add NoiseEncryptionService.clearSession(for:) method
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
* Fix race condition and increase test timeouts
- Fix race in sendNoisePayload: use sync barrier instead of async
to ensure payload is queued before initiating handshake
(addresses Codex review feedback)
- Increase BLEServiceTests sleep from 0.5s to 1.0s for CI reliability
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
---------
Co-authored-by: jack <jackjackbits@users.noreply.github.com>
Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
* Add comprehensive test coverage for ChatViewModel and BLEService
This commit adds 14 new tests to improve the safety net for future
refactoring of ChatViewModel and BLEService:
New test files:
- ChatViewModelTorTests: Tor lifecycle notification handlers (8 tests)
- ChatViewModelDeliveryStatusTests: Delivery status state machine (6 tests)
- ChatViewModelRefactoringTests: Command routing and message handling (4 tests)
- BLEServiceCoreTests: Packet deduplication and stale broadcast filtering (2 tests)
- PublicMessagePipelineTests: Message ordering and deduplication (4 tests)
- MessageRouterTests: Transport selection and outbox behavior (4 tests)
- PrivateChatManagerTests: Chat selection and read receipts (2 tests)
- UnifiedPeerServiceTests: Fingerprint resolution and blocking (2 tests)
- RelayControllerTests: TTL, handshake, and fragment relay logic (4 tests)
Modified files:
- MockTransport: Added peer snapshot publishing on connect/disconnect
- TestHelpers: Added waitUntil polling helper for async tests
- MockIdentityManager: Extended for new test scenarios
Total: 454 tests across 64 suites (was 440)
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
* Fix flaky test by using waitUntil instead of fixed sleep
Replace fixed 200ms sleep with waitUntil helper for more reliable
async assertion in routing tests. This prevents timing issues on CI.
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
---------
Co-authored-by: jack <jackjackbits@users.noreply.github.com>
Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
Arti's dormant/wake FFI functions are no-op stubs that don't actually
implement dormant mode. The app was wasting 2.5-12 seconds trying to
wake from a dormant state that doesn't exist before falling back to
a full restart.
This change:
- Removes wakeFromDormant() call and function
- Simplifies goDormantOnBackground() to just mark state as not ready
- Goes straight to restartArti() on foreground, eliminating the delay
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
BitchatMessage is a class, so modifying its properties through an array
reference doesn't mutate the array itself. Changed var to let binding.
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
Update root Package.swift to reference localPackages/Arti instead of
the removed localPackages/Tor directory.
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
- Replace C Tor (0.4.8.21) with Rust Arti (1.9.0/arti-client 0.38)
- 70% smaller binary: 21MB xcframework vs 67MB (6.9MB vs 14MB per slice)
- Memory-safe Rust implementation with modern async (tokio)
- Same SOCKS5 proxy interface at 127.0.0.1:39050 for drop-in compatibility
- FFI wrapper (arti-bitchat crate) with C-compatible exports
- Swift TorManager maintains identical public API
- Aggressive size optimization: opt-level=z, lto=fat, panic=abort, strip
- Supports iOS device, iOS simulator (Apple Silicon), and macOS
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
This change reverts the nonce size increase introduced in f41a390 ('BCH-01-010: Noise Protocol spec compliance improvements').
While 8-byte nonces are recommended by the Noise specification, increasing the size from 4 bytes broke wire compatibility with existing clients. This caused all encrypted DMs to fail between updated and non-updated clients.
Changes:
- Revert NONCE_SIZE_BYTES to 4.
- Restore 4-byte nonce extraction logic in extractNonceFromCiphertextPayload.
- Restore 4-byte nonce serialization in nonceToBytes.
- Restore UInt32.max overflow check in encrypt.
Note: Other improvements from BCH-01-010 (constant-time comparisons, safe arithmetic in replay window, sensitive data clearing) are preserved.
Include the build-minimal.sh script alongside BITCHAT_TOR.md so future
rebuilds can be done directly from the bitchat repo.
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
Move updateNeighbors call to after signature verification passes,
preventing spoofed or stale announces from injecting bad routing data.
Also reset isNewPeer/isReconnectedPeer flags on verification failure
to prevent spurious peer connection notifications.
Addresses review feedback from PR #938.
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
- Add findMessageIndex helper to handle peer ID format mismatch
(short 16-hex vs long 64-hex noise key)
- Prevent DELIVERED acks from downgrading .read status back to .delivered
(fixes race condition where late-arriving delivery acks overwrote read status)
- Use incoming peerID for READ receipts instead of creating new ID from noise key
- Explicitly re-assign messages array to trigger @Published setter
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
When selectedPrivateChatPeer was migrated to a 64-hex stable Noise key
after session establishment, file transfers would silently fail because:
1. Sender used raw 64-hex key, truncated to first 8 bytes by BinaryProtocol
2. Receiver's myPeerID is SHA256-fingerprint-derived (different value)
3. Recipient check failed, causing silent packet drop
The fix normalizes peerID to short form (SHA256-derived 16-hex) in
sendFilePrivate before constructing recipientData, ensuring the wire
format matches what receivers expect.
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
Add `nonisolated` to the static method since it only performs
thread-safe FileManager operations and is called from Task.detached.
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
The original PR introduced a PendingFileManager that held incoming files
in memory until user acceptance. However, this approach had issues:
1. No UI was implemented for users to accept/decline files
2. Files would expire after 5 minutes, losing legitimate transfers
3. The app only allows specific media types (photos, audio) that users
explicitly choose to send, so manual acceptance adds friction
This commit replaces the pending file system with disk quota management:
- Auto-save files immediately (preserving original UX)
- Enforce 100 MB storage quota for incoming files
- Auto-delete oldest files when quota is exceeded
- Logs cleanup activity for visibility
This directly addresses the DoS vulnerability (disk exhaustion from
file spam) while maintaining good UX for legitimate transfers.
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
Addresses Codex review feedback on PR #948: the getTransportCiphers()
method now returns the handshake hash as part of its return tuple,
capturing it BEFORE split() calls clearSensitiveData().
Previously, calling getHandshakeHash() after getTransportCiphers()
would return an all-zero value since split() clears the symmetric
state. This broke channel binding functionality.
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
This addresses the Cure53 audit finding BCH-01-010 which identified several
implementation deviations from the Noise Protocol Framework specification.
Changes:
- Expand nonce from 4-byte to 8-byte transmission per spec guidance
This provides 2^64 nonce space instead of the limited 2^32 space
- Fix integer overflow in replay window check using safe arithmetic
- Add constant-time comparison functions for key validation to prevent
timing side-channel attacks
- Add clearSensitiveData() method to NoiseSymmetricState that clears
chaining key and hash after split() operation
- Document atomic nonce state updates in decryption
Security improvements:
- Constant-time operations prevent information leakage via timing analysis
- Proper cleanup of symmetric state after handshake completion
- Safer arithmetic prevents potential integer overflow issues
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
Add code to clear iOS app switcher snapshot cache during panic mode.
iOS automatically captures screenshots for the app switcher, which could
reveal sensitive message content visible at the time.
Changes:
- Add clearAppSwitcherSnapshots() helper function (iOS only)
- Call it from panicClearAllData() during file cleanup phase
- Clears all files in Library/Caches/Snapshots/ directory
Security: Sensitive information visible in the app when it entered
background will no longer be recoverable from snapshot cache after
panic reset.
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>