Commit Graph
658 Commits
Author SHA1 Message Date
jack ca9748ede0 Complete all translations to 100% and fix auto-extraction
- Mark non-localizable strings with Text(verbatim:) to prevent extraction
- Update UI strings to lowercase per style guide (open, save, close, recording)
- Add complete translations for all 29 languages (194/194 strings at 100%)
- Remove empty/duplicate entries (@, bitchat/, Open, Recording %@)
- Add proper localization comments for all user-facing strings
2025-10-14 22:29:38 +02:00
jack 946abce1b2 Fix infinite render loop and apply all security fixes
CRITICAL BUG FIX - Infinite Render Loop:

Root Cause: Duplicate view identity in ContentView.swift:368
  ForEach(messageItems) { item in  // Already uses item.id via Identifiable
      messageRow(...)
          .id(item.id)  //  REDUNDANT modifier caused identity re-evaluation loop
  }

When @Published properties updated, SwiftUI re-evaluated .id() → appeared as
'new' identity → triggered re-render → infinite loop. Caused UI freezes,
keyboard failures, and 100% CPU usage.

Fix: Remove redundant .id() modifier - ForEach already has stable identity.

PERFORMANCE FIXES:

1. Waveform Cache Deadlock (Waveform.swift)
   - Removed nested queue.async(barrier) on cache hits
   - Was causing task saturation and potential deadlocks

2. Async Send Pattern (ContentView.swift)
   - Clear input immediately, defer actual send to next runloop
   - Prevents blocking current event handler

3. Proper Swift Concurrency (VoiceNoteView.swift)
   - Switch from .onAppear + DispatchQueue to .task
   - Cleaner async/await pattern for loading

4. Remove Redundant objectWillChange (ChatViewModel.swift)
   - @Published already triggers updates automatically
   - Explicit send() was causing double update cycles

SECURITY FIXES (C1-C5, H1-H2):

C1. Path Traversal Protection (BLEService.swift)
    - Unicode normalization, null byte removal
    - Replace ALL path separators, reject dotfiles
    - Validate paths don't escape directory

C2. Integer Overflow (BitchatFilePacket.swift)
    - Use UInt64 for TLV parsing, safe Int conversion

C3. MIME Validation (BLEService.swift)
    - Whitelist: JPEG, PNG, GIF, WebP, M4A, MP3, WAV, OGG, PDF
    - Magic byte validation for all types
    - Lenient on M4A (platform variations)

C4. Compression Bomb (BinaryProtocol.swift)
    - Ratio validation <= 50,000:1
    - Defense-in-depth with 1MB size cap

C5. TOCTOU Race (ChatViewModel.swift)
    - Direct removeItem without fileExists check

H1. File Size Validation (ChatViewModel, ImageUtils)
    - Check attributes BEFORE Data(contentsOf:)
    - Prevents memory exhaustion

H2. Metadata Stripping (ImageUtils.swift)
    - Remove ALL metadata keys from JPEG encoding
    - Only compression quality set
    - Protects GPS/EXIF/device info privacy

RESULT:
 No render loops
 Works with Xcode debugger
 Voice notes display properly
 All security vulnerabilities fixed
 164 tests passing

Production ready.
2025-10-14 22:29:38 +02:00
jack 326ff628f7 Ensure /clear and panic triple-tap delete media files
Fix: /clear command and panicClearAllData() now properly delete media files

1. /clear (triple-tap on chat):
   - Deletes outgoing media (voice notes, images, files)
   - Conservative: only our sent media, preserves received media
   - Runs in background to avoid UI freeze

2. panicClearAllData() (triple-tap on bitchat/ header):
   - Deletes ALL media files (incoming + outgoing)
   - Removes entire files directory and recreates structure
   - Ensures complete data wipe for emergency scenarios

Both operations run async on .utility queue to prevent blocking UI.
2025-10-14 22:29:38 +02:00
jack 2040e94b83 Make voice note loading completely lazy with deferred initialization
Aggressive performance optimization to prevent UI freezes:

Problem: Even with async loading, creating 10+ VoiceNotePlaybackController
instances simultaneously (when scrolling past multiple voice notes) spawned
20+ concurrent background tasks, potentially starving main thread.

Solution - Ultra-lazy loading:
1. VoiceNotePlaybackController.init() now does ZERO work
   - No duration loading
   - No player creation
   - Instant initialization

2. Duration loaded on-demand via public loadDuration() method
   - Called from VoiceNoteView.onAppear after 150ms delay
   - Reduced priority: .utility instead of .userInitiated
   - Guard prevents duplicate loading

3. Waveform loading also deferred 150ms
   - Gives UI time to settle after message appears
   - Prevents task storms when multiple voice notes appear

This spreads the work over time instead of all at once.
2025-10-14 22:29:38 +02:00
jack 8f62dd1776 Cache geohash identity in ChatViewModel to prevent crypto during rendering
Additional optimization for location channels (voice notes are mesh-only,
but this helps with text message rendering in geohash channels):

- Add cachedGeohashIdentity to avoid deriveIdentity calls during rendering
- Check cache before falling back to crypto derivation
- Reduces main thread crypto work in location channels
2025-10-14 22:29:38 +02:00
jack 7722009f11 Cache Nostr identity derivation to prevent crypto during view rendering
Critical performance fix:

Problem: formatMessageHeader() called deriveIdentity(forGeohash:) during
every SwiftUI render for every media message. Each call performed:
- Keychain I/O (getOrCreateDeviceSeed)
- HMAC-SHA256 computation
- Up to 10 secp256k1 key validations (elliptic curve crypto)

With multiple media messages, this resulted in 100s of milliseconds of
blocking crypto on main thread per render cycle.

Solution: Add thread-safe cache for derived identities
- Check cache before expensive crypto operations
- NSLock protects concurrent access
- Identity is deterministic per geohash, so caching is safe

This eliminates crypto from the hot rendering path.
2025-10-14 22:28:46 +02:00
jack da0474680c Eliminate disk I/O from SwiftUI view rendering path
Critical performance fix for UI freezes when receiving media:

Problem: mediaAttachment(for:) was called during every SwiftUI render,
performing synchronous disk I/O on main thread:
- FileManager.fileExists() called 2-6x per message (checking subdirs)
- applicationFilesDirectory() creating directories on every call
- With multiple media messages, this meant 20-100+ disk ops per render

Solution:
1. Remove fileExists checks - construct URLs directly
   - Files are validated during playback/display (fail gracefully if missing)
   - Sender determines subdirectory (outgoing vs incoming)

2. Cache applicationFilesDirectory() result
   - Static cache prevents repeated FileManager.url() calls
   - Directory created only once

3. Remove redundant playback.replaceURL() in VoiceNoteView.onAppear
   - Controller already initialized with correct URL

This eliminates ALL disk I/O from the view rendering hot path.
2025-10-14 22:26:03 +02:00
jack 0a525be57a Fix memory leaks and post-playback freeze
Fixes:
1. Post-playback freeze: audioPlayerDidFinishPlaying now dispatches to main
   thread before updating @Published properties (Swift concurrency violation)

2. Unbounded waveform cache: Implement LRU eviction with 20-entry limit
   - Track last access time for each cached waveform
   - Evict oldest entry when cache is full
   - Prevents unlimited memory growth as voice notes accumulate

3. Audio buffer memory leaks: Wrap computeWaveform in autoreleasepool
   - AVAudioPCMBuffer allocations are autoreleased
   - Pool ensures buffers are freed promptly

4. Image processing memory: Add autoreleasepool around compression loops
   - Each jpegData() call creates temporary objects
   - Inner pool per iteration prevents memory spikes during quality search

Memory should now remain stable during extended use.
2025-10-14 22:26:03 +02:00
jack 16e9271570 Fix UI freeze when receiving voice notes
Problem: AVAudioPlayer initialization in VoiceNotePlaybackController.init()
was running synchronously on main thread during view creation, blocking
UI for 50-200ms per voice note.

Solution:
- Remove eager preparePlayer() call from init
- Load duration asynchronously on background queue
- Player is only prepared when playback is actually requested via ensurePlayerReady()

This prevents UI freezes when voice notes appear in the chat.
2025-10-14 22:26:03 +02:00
jack 747551f35a Fix critical issues from PR #681 review
Critical fixes:
- BinaryProtocol: Return nil for unknown versions (prevents buffer underflows)
- Add BinaryProtocol.Offsets struct to centralize magic numbers
- Replace magic offset calculations with named constants

Security/Privacy:
- FileAttachmentView: Use url.lastPathComponent instead of url.path
  (prevents exposing full system paths)

Documentation:
- Fix compression algorithm documentation (zlib, not LZ4)

All tests passing.
2025-10-14 22:26:03 +02:00
jack 367addf138 Fix binary protocol test fixtures 2025-10-14 22:25:29 +02:00
jack aa35200c6f Reset BLE assembler on stalled fragment trains 2025-10-14 22:25:29 +02:00
jack e09de446fc Drop attachment ceilings to 1 MiB and bump release version 2025-10-14 22:25:29 +02:00
jack 0714b09a89 Guard peer map reads on BLE message path 2025-10-14 22:25:29 +02:00
jack adb2626898 Restore BLE broadcasts when notify buffer is saturated 2025-10-14 22:23:12 +02:00
jack 20435d55e8 Fix cleanupLocalFile lookup 2025-10-14 22:23:12 +02:00
jack a0187fb430 Resolve image/voice path handling 2025-10-14 22:23:12 +02:00
jack 9c55a2e1fd Hide absolute paths in media messages 2025-10-14 22:23:12 +02:00
jack eb37aa8046 Stub file transfer methods in mock 2025-10-14 22:23:12 +02:00
jack 2edf29033f Stub file transfer methods in mock 2025-10-14 22:22:16 +02:00
jack b6cb287991 Use unique transfer identifiers 2025-10-14 22:22:16 +02:00
jack c9be273750 Preserve packet version when signing 2025-10-14 22:21:17 +02:00
jack c7280284ea Fix CFMutableData handling 2025-10-14 22:21:17 +02:00
jack 24cc307a0e Target image byte size across platforms 2025-10-14 22:21:17 +02:00
jack 177642ac4d Normalize mac JPEG color space 2025-10-14 22:21:17 +02:00
jack ef6309c08f Strip metadata in mac image encoding 2025-10-14 22:21:17 +02:00
jack 7ab7fbfd1b Revert unsupported JPEG option 2025-10-14 22:21:17 +02:00
jack 2b5505a20d Align mac image JPEG encoding 2025-10-14 22:21:17 +02:00
jack ccce384a90 Allow user-selected write access 2025-10-14 22:21:17 +02:00
jack e2da5e2ef9 Fix image attachment detection 2025-10-14 22:21:17 +02:00
jack a71b8cd545 Use save panel for mac image export 2025-10-14 22:21:17 +02:00
jack 1d4bf96f7a Keep processed images for outgoing messages 2025-10-14 22:21:17 +02:00
jack c55c19e738 Lowercase image preview buttons 2025-10-14 22:21:17 +02:00
jack 5cafa4d5b4 Reblur images via swipe 2025-10-14 22:21:17 +02:00
jack 567e1dbbbf Allow long-press reblur on images 2025-10-14 22:21:17 +02:00
jack 9e0542df73 Use Photos picker on mac 2025-10-14 22:21:17 +02:00
jack 32a8e558ed Restore mac photo picker access 2025-10-14 22:21:17 +02:00
jack 5209a6cfcf Display recording milliseconds 2025-10-14 22:21:17 +02:00
jack d290fd4670 Harden attachment transfer bookkeeping 2025-10-14 22:21:17 +02:00
jack cb53a3b48e Describe microphone usage 2025-10-14 22:21:17 +02:00
jack 8001486a2b Permit mac media library access 2025-10-14 22:21:17 +02:00
jack 0d6c1a0b44 Allow mac microphone access 2025-10-14 22:21:17 +02:00
jack d8e8703a5f Enable mac attachment importers 2025-10-14 22:21:17 +02:00
jack c75f32da2c Fix compressed BLE file transfers 2025-10-14 22:21:17 +02:00
jack dcd26c19d7 Stop dropping partial BLE frames while assembling notifications 2025-10-14 22:21:17 +02:00
jack eccec2f27d Log incomplete BLE frames for debugging 2025-10-14 22:21:17 +02:00
jack de7a496af9 Add detailed logging for BLE fragment assembly 2025-10-14 22:21:17 +02:00
jack ee19d9c948 Let BLE assembler accept large frames up to hard cap 2025-10-14 22:21:17 +02:00
jack 74414c369a Add guard to drop oversized BLE notification assemblies 2025-10-14 22:21:17 +02:00
jack 7935857dae Revert "Raise BLE notification buffer cap for large file transfers"
This reverts commit b624523af843475db84e4a846db8dcbe824ae408.
2025-10-14 22:21:17 +02:00