- 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>
Block notifications from bypassing the user blocking feature on iOS.
Vulnerabilities fixed:
1. Nostr public messages: checkForMentions() was called regardless of
blocking status, allowing blocked users to trigger mention notifications
2. Noise-encrypted DMs: didReceiveNoisePayload() didn't check blocking
before calling handlePrivateMessage(), allowing DM notifications
Changes:
- ChatViewModel+Nostr.swift: Add blocking check before checkForMentions()
and sendHapticFeedback() in subscribeNostrEvent
- ChatViewModel.swift: Add isPeerBlocked() check in didReceiveNoisePayload
before processing private messages
- Add NotificationBlockingTests.swift with 5 tests for blocking behavior
Security: Blocked users can no longer trigger notifications through any
message path (Nostr public, Nostr DM, or BLE Noise DM).
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
Update lastAnnounceTime to 'now' when rate-limiting subscription attempts.
This ensures each blocked attempt extends the suppression window, preventing
attackers from waiting out the backoff while continuously spamming attempts.
Previously, the backoff timer was only based on the last successful announce,
allowing attackers to receive an announce as soon as the initial backoff
expired regardless of how many blocked attempts occurred in between.
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
P1: Wire didReceivePendingFileTransfer into ChatViewModel
- Add implementation that creates system message for pending files
- Route to appropriate chat (public/private)
- Send local notification for incoming files
- Auto-decline files from blocked users
P2: Keep pending files in queue if save fails
- Only remove file from pendingFiles after successful save
- Allows user to retry accept if initial save failed
Also adds test for save failure scenario.
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
Add proper error classification to distinguish expected states (item not
found) from critical failures (access denied, storage full) and
recoverable errors (device locked, auth failed).
Changes:
- Add KeychainReadResult and KeychainSaveResult enums with error types
- Add getIdentityKeyWithResult/saveIdentityKeyWithResult protocol methods
- Implement retry logic with exponential backoff for transient errors
- Add consistent SecureLogger logging for all keychain operations
- Update NoiseEncryptionService identity loading to handle errors gracefully
- Update MockKeychain and TrackingMockKeychain with error simulation
- Add comprehensive KeychainErrorHandlingTests (18 new tests)
Security: Applications can now properly detect and respond to critical
keychain failures, improving resilience during device lock states and
providing actionable diagnostics for access issues.
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
BCH-01-011: Reduces replay attack window from ±1 hour to ±5 minutes.
The previous 1-hour window allowed extended replay attacks. A 5-minute
window is industry standard for replay protection while accommodating
reasonable clock drift.
- Updated InputValidator.validateTimestamp to use 300-second window
- Updated tests to verify new boundary conditions
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
Adds rate-limiting to prevent device enumeration attacks via rapid
subscription/disconnect cycles. Without this fix, an attacker could
enumerate ~120 bitchat devices per minute by connecting, subscribing,
capturing the announce packet, then disconnecting and moving to the next.
Key changes:
- Add per-central rate-limit tracking with exponential backoff
- Minimum 2-second interval between announces per central
- Exponential backoff (2x) up to 30 seconds for rapid reconnects
- After 5 rapid attempts, suppress announces entirely (likely attack)
- Clean up stale rate-limit entries after 60-second window
- Clear rate-limit state during panic mode
Configuration:
- bleSubscriptionRateLimitMinSeconds: 2.0
- bleSubscriptionRateLimitBackoffFactor: 2.0
- bleSubscriptionRateLimitMaxBackoffSeconds: 30.0
- bleSubscriptionRateLimitWindowSeconds: 60.0
- bleSubscriptionRateLimitMaxAttempts: 5
Security audit reference: Cure53 BCH-01-004 (Medium severity)
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
Incoming files are now held in memory via PendingFileManager instead of
being auto-saved to disk. Users must explicitly accept files before they
are written. This prevents attackers from exhausting device storage.
Key changes:
- Add PendingFileManager with configurable limits (max 10 files, 5MB total)
- Files auto-expire after 5 minutes if not accepted
- LRU eviction when limits are exceeded
- Pending files cleared during panic mode (emergencyDisconnectAll)
- Add didReceivePendingFileTransfer delegate method
- Add acceptPendingFile/declinePendingFile to Transport protocol
Security audit reference: Cure53 BCH-01-002 (Medium severity)
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>