From 2ff8aa523f8510a7748fa09f1be32a6e3f42c9ed Mon Sep 17 00:00:00 2001 From: jack <212554440+jackjackbits@users.noreply.github.com> Date: Thu, 26 Nov 2026 17:35:03 -1000 Subject: [PATCH] fix(security,media,tor): close panic-wipe races, high-res photo rejection, live-voice sweep, and TorManager lifecycle bugs (#1902) * fix(security,media,tor): close panic-wipe races, high-res photo rejection, live-voice sweep, and TorManager lifecycle bugs * test(ptt): tolerate 3s idle-timer promotion during async startup sweep test --------- Co-authored-by: jack --- bitchat/Features/media/ImageDownsampler.swift | 48 +++- bitchat/Features/media/ImageUtils.swift | 12 +- .../Identity/SecureIdentityStateManager.swift | 21 +- bitchat/Nostr/GeoRelayDirectory.swift | 54 ++++- bitchat/Nostr/NostrIdentityBridge.swift | 84 +++++-- .../Services/BLE/BLEFileTransferPolicy.swift | 7 +- bitchat/Services/BLE/BLEService.swift | 32 +++ bitchat/Services/CashuTokenDecoder.swift | 35 ++- bitchat/Services/NostrTransport.swift | 25 +- bitchat/Services/NotificationService.swift | 40 ++++ bitchat/Utils/Color+Peer.swift | 46 +++- .../ViewModels/ChatLiveVoiceCoordinator.swift | 41 +++- .../ViewModels/ChatOutgoingCoordinator.swift | 16 +- bitchat/ViewModels/ChatViewModel.swift | 68 ++++-- .../ChatViewModelBootstrapper.swift | 4 +- .../ViewModels/PublicMessagePipeline.swift | 10 + .../ChatLiveVoiceCoordinatorTests.swift | 45 ++++ bitchatTests/Features/ImageUtilsTests.swift | 37 +++ .../Nostr/GeoRelayDirectoryTests.swift | 81 +++++++ .../Services/NotificationServiceTests.swift | 43 ++++ .../Services/PanicWipeCoverageTests.swift | 213 ++++++++++++++++++ localPackages/Arti/Sources/TorManager.swift | 136 ++++++----- 22 files changed, 964 insertions(+), 134 deletions(-) diff --git a/bitchat/Features/media/ImageDownsampler.swift b/bitchat/Features/media/ImageDownsampler.swift index 4bf28bc6..3c9203e1 100644 --- a/bitchat/Features/media/ImageDownsampler.swift +++ b/bitchat/Features/media/ImageDownsampler.swift @@ -20,12 +20,38 @@ enum ImageDownsampler { typealias PlatformImage = NSImage #endif - private static let cache: NSCache = { - let cache = NSCache() - cache.countLimit = 48 - cache.totalCostLimit = 32 * 1024 * 1024 - return cache - }() + private final class DownsampledCache: @unchecked Sendable { + private let lock = NSLock() + private var wipeGeneration: UInt64 = 0 + private let storage: NSCache = { + let cache = NSCache() + cache.countLimit = 48 + cache.totalCostLimit = 32 * 1024 * 1024 + return cache + }() + + func lookup(_ key: NSString) -> (image: PlatformImage?, generation: UInt64) { + lock.lock() + defer { lock.unlock() } + return (storage.object(forKey: key), wipeGeneration) + } + + func store(_ image: PlatformImage, for key: NSString, cost: Int, expectedGeneration: UInt64) { + lock.lock() + defer { lock.unlock() } + guard wipeGeneration == expectedGeneration else { return } + storage.setObject(image, forKey: key, cost: cost) + } + + func reset() { + lock.lock() + defer { lock.unlock() } + wipeGeneration &+= 1 + storage.removeAllObjects() + } + } + + private static let cache = DownsampledCache() private static func cacheKey(for url: URL, maxPixelSize: Int) -> NSString { "\(url.path)#\(maxPixelSize)" as NSString @@ -33,19 +59,21 @@ enum ImageDownsampler { static func cachedImage(for url: URL, maxPixelSize: Int) -> PlatformImage? { guard maxPixelSize > 0 else { return nil } - return cache.object(forKey: cacheKey(for: url, maxPixelSize: maxPixelSize)) + return cache.lookup(cacheKey(for: url, maxPixelSize: maxPixelSize)).image } static func resetForPanic() { - cache.removeAllObjects() + cache.reset() } static func loadDownsampledImage(from url: URL, maxPixelSize: Int) -> PlatformImage? { guard maxPixelSize > 0 else { return nil } let key = cacheKey(for: url, maxPixelSize: maxPixelSize) - if let cached = cache.object(forKey: key) { + let initial = cache.lookup(key) + if let cached = initial.image { return cached } + let generation = initial.generation let sourceOptions: CFDictionary = [ kCGImageSourceShouldCache: false ] as CFDictionary @@ -74,7 +102,7 @@ enum ImageDownsampler { image = NSImage(cgImage: cgImage, size: NSSize(width: cgImage.width, height: cgImage.height)) #endif let cost = max(1, cgImage.width * cgImage.height * 4) - cache.setObject(image, forKey: key, cost: cost) + cache.store(image, for: key, cost: cost, expectedGeneration: generation) return image } } diff --git a/bitchat/Features/media/ImageUtils.swift b/bitchat/Features/media/ImageUtils.swift index 678840fa..d3923772 100644 --- a/bitchat/Features/media/ImageUtils.swift +++ b/bitchat/Features/media/ImageUtils.swift @@ -16,6 +16,12 @@ enum ImageUtils { private static let compressionQuality: CGFloat = 0.82 private static let targetImageBytes: Int = 45_000 private static let maxSourceImageBytes: Int = 10 * 1024 * 1024 + /// Generous local-source bounds for outgoing photos before ImageIO + /// downsamples them to `maxDimension` (448 px). Supports 12–48 MP iPhone + /// photos, panoramas, and 5K screenshots while still blocking absurd + /// crafted local image headers. + static let maxSourceDimensionPixels: Int = 16_384 + static let maxSourceTotalPixels: Int = 100_000_000 private static let timestampFormatterLock = NSLock() private static let timestampFormatter: DateFormatter = { @@ -31,7 +37,11 @@ enum ImageUtils { return try autoreleasepool { let sourceOptions = [kCGImageSourceShouldCache: false] as CFDictionary guard let source = CGImageSourceCreateWithURL(url as CFURL, sourceOptions), - ImageContainerValidator.validateDimensions(of: source) == nil else { + ImageContainerValidator.validateDimensions( + of: source, + maxDimensionPixels: maxSourceDimensionPixels, + maxTotalPixels: maxSourceTotalPixels + ) == nil else { throw ImageUtilsError.invalidImage } diff --git a/bitchat/Identity/SecureIdentityStateManager.swift b/bitchat/Identity/SecureIdentityStateManager.swift index 29e02011..77f8df85 100644 --- a/bitchat/Identity/SecureIdentityStateManager.swift +++ b/bitchat/Identity/SecureIdentityStateManager.swift @@ -187,12 +187,12 @@ final class SecureIdentityStateManager: SecureIdentityStateManagerProtocol { private var pendingSave = false // Encryption key - private let encryptionKey: SymmetricKey + private var encryptionKey: SymmetricKey /// True when `encryptionKey` is a throwaway generated this session because the /// persisted key could not be read (device locked / access denied). In that /// state we must NOT persist (it would overwrite the real cache with data the /// next launch can't decrypt) and must NOT delete the existing cache. - private let encryptionKeyIsEphemeral: Bool + private var encryptionKeyIsEphemeral: Bool init(_ keychain: KeychainManagerProtocol) { self.keychain = keychain @@ -689,9 +689,20 @@ final class SecureIdentityStateManager: SecureIdentityStateManagerProtocol { self.ephemeralSessions.removeAll() self.pendingSave = false - // Delete from keychain - let deleted = self.keychain.deleteIdentityKey(forKey: self.cacheKey) - SecureLogger.logKeyOperation(.delete, keyType: "identity cache", success: deleted) + // Delete the encrypted cache and previous cache encryption key from + // keychain, then generate and persist a fresh encryption key so + // post-panic blocks, verifications, and pins remain readable across + // the next cold launch instead of being sealed under a deleted key. + let deletedCache = self.keychain.deleteIdentityKey(forKey: self.cacheKey) + SecureLogger.logKeyOperation(.delete, keyType: "identity cache", success: deletedCache) + _ = self.keychain.deleteIdentityKey(forKey: self.encryptionKeyName) + + let freshKey = SymmetricKey(size: .bits256) + let keyData = freshKey.withUnsafeBytes { Data($0) } + let saved = self.keychain.saveIdentityKey(keyData, forKey: self.encryptionKeyName) + self.encryptionKey = freshKey + self.encryptionKeyIsEphemeral = !saved + SecureLogger.logKeyOperation(.generate, keyType: "identity cache encryption key", success: saved) } } diff --git a/bitchat/Nostr/GeoRelayDirectory.swift b/bitchat/Nostr/GeoRelayDirectory.swift index 29fbe3a3..1a44828b 100644 --- a/bitchat/Nostr/GeoRelayDirectory.swift +++ b/bitchat/Nostr/GeoRelayDirectory.swift @@ -150,6 +150,7 @@ final class GeoRelayDirectory { var observers: [NSObjectProtocol] = [] var refreshTimer: Timer? var retryTask: Task? + var fetchTask: Task? var localLoadTask: Task? init(notificationCenter: NotificationCenter) { @@ -160,6 +161,7 @@ final class GeoRelayDirectory { observers.forEach { notificationCenter.removeObserver($0) } refreshTimer?.invalidate() retryTask?.cancel() + fetchTask?.cancel() localLoadTask?.cancel() } } @@ -175,6 +177,7 @@ final class GeoRelayDirectory { case torNotReady case invalidData case network(String) + case cancelled } static let shared = GeoRelayDirectory() @@ -206,6 +209,10 @@ final class GeoRelayDirectory { private var didCompleteLocalLoad = false private var retryAttempt: Int = 0 private var isFetching: Bool = false + /// Incremented on panic wipe so any in-flight remote fetch cannot write + /// `georelays_cache_v2.csv`, `georelay.lastFetchAt`, or re-arm `retryTask` + /// after `resetForPanic()` runs. + private var panicGeneration: UInt64 = 0 private init() { self.dependencies = .live() @@ -336,6 +343,7 @@ final class GeoRelayDirectory { private func fetchRemote() { guard !isFetching else { return } isFetching = true + let generation = panicGeneration let request = URLRequest( url: dependencies.remoteURL, @@ -343,21 +351,33 @@ final class GeoRelayDirectory { timeoutInterval: 15 ) let awaitTorReady = dependencies.awaitTorReady + let isNetworkActivationAllowed = dependencies.isNetworkActivationAllowed let makeFetchData = dependencies.makeFetchData let validationPolicy = dependencies.validationPolicy let baselineEntries = Set(entries) - Task { [weak self] in + cleanupState.fetchTask?.cancel() + cleanupState.fetchTask = Task { [weak self] in guard let self else { return } let outcome = await Self.fetchRemoteOutcome( request: request, awaitTorReady: awaitTorReady, + isNetworkActivationAllowed: isNetworkActivationAllowed, makeFetchData: makeFetchData, validationPolicy: validationPolicy, baselineEntries: baselineEntries ) + guard !Task.isCancelled, self.panicGeneration == generation else { + if self.panicGeneration == generation { + self.isFetching = false + self.cleanupState.fetchTask = nil + } + return + } + self.cleanupState.fetchTask = nil + switch outcome { case .success(let parsed, let csv): self.handleFetchSuccess(entries: parsed, csv: csv) @@ -367,6 +387,8 @@ final class GeoRelayDirectory { self.handleFetchFailure(.invalidData) case .network(let description): self.handleFetchFailure(.network(description)) + case .cancelled: + self.isFetching = false } } } @@ -374,21 +396,32 @@ final class GeoRelayDirectory { nonisolated private static func fetchRemoteOutcome( request: URLRequest, awaitTorReady: @escaping @Sendable () async -> Bool, + isNetworkActivationAllowed: @escaping @MainActor () -> Bool, makeFetchData: @escaping @MainActor @Sendable () -> (@Sendable (URLRequest) async throws -> Data), validationPolicy: GeoRelayDirectoryValidationPolicy, baselineEntries: Set ) async -> DetachedFetchOutcome { - await Task.detached(priority: .utility) { - let ready = await awaitTorReady() - guard ready else { return .torNotReady } + let ready = await awaitTorReady() + guard !Task.isCancelled else { return .cancelled } + guard ready else { return .torNotReady } - // Resolve the URLSession after Tor readiness completes so a proxy - // transition or Tor bootstrap while awaiting cannot leave us on a - // stale pre-wait session. - let fetchData = await makeFetchData() + // Re-check activation gate after Tor readiness completes so a panic + // wipe or offline transition during the wait cannot fire an outbound + // request. + let allowed = await isNetworkActivationAllowed() + guard !Task.isCancelled, allowed else { return .cancelled } + // Resolve the URLSession after Tor readiness completes so a proxy + // transition or Tor bootstrap while awaiting cannot leave us on a + // stale pre-wait session. + let fetchData = await makeFetchData() + guard !Task.isCancelled else { return .cancelled } + + return await Task.detached(priority: .utility) { + guard !Task.isCancelled else { return DetachedFetchOutcome.cancelled } do { let data = try await fetchData(request) + guard !Task.isCancelled else { return .cancelled } guard let parsed = Self.validatedEntries( from: data, policy: validationPolicy, @@ -400,6 +433,7 @@ final class GeoRelayDirectory { return .success(entries: parsed, csv: data) } catch { + if Task.isCancelled { return .cancelled } return .network(error.localizedDescription) } }.value @@ -751,9 +785,13 @@ final class GeoRelayDirectory { /// drop cached geohash lookups from memory, and remove the cached relay CSV /// from Application Support. func resetForPanic() { + panicGeneration &+= 1 cancelRetry() + cleanupState.fetchTask?.cancel() + cleanupState.fetchTask = nil cleanupState.localLoadTask?.cancel() cleanupState.localLoadTask = nil + isFetching = false retryAttempt = 0 closestRelaysCache.removeAll(keepingCapacity: false) dependencies.userDefaults.removeObject(forKey: lastFetchKey) diff --git a/bitchat/Nostr/NostrIdentityBridge.swift b/bitchat/Nostr/NostrIdentityBridge.swift index ba528570..5c7407ca 100644 --- a/bitchat/Nostr/NostrIdentityBridge.swift +++ b/bitchat/Nostr/NostrIdentityBridge.swift @@ -14,7 +14,15 @@ final class NostrIdentityBridge { private var deviceSeedCache: Data? // Cache derived identities to avoid repeated crypto during view rendering private var derivedIdentityCache: [String: NostrIdentity] = [:] + // Incremented on every cache clear/panic wipe so a concurrent cold-start + // Keychain load or HMAC derivation that started before a wipe can never + // repopulate the shared cache with pre-wipe private keys. + private var cacheGeneration: UInt64 = 0 private let cacheLock = NSLock() + // Serializes cold-start Keychain read/create so two concurrent callers + // hitting `.itemNotFound` cannot generate and persist divergent identities + // or seeds. Lock ordering: always acquire `keyCreationLock` before `cacheLock`. + private let keyCreationLock = NSLock() private let keychain: KeychainManagerProtocol @@ -31,13 +39,26 @@ final class NostrIdentityBridge { } cacheLock.unlock() + keyCreationLock.lock() + defer { keyCreationLock.unlock() } + + cacheLock.lock() + if let cached = currentIdentityCache { + cacheLock.unlock() + return cached + } + let generation = cacheGeneration + cacheLock.unlock() + // Distinguish missing vs transiently unavailable Keychain so a locked-device // read neither overwrites an existing identity nor caches a throwaway key. switch keychain.loadWithResult(key: currentIdentityKey, service: keychainService) { case .success(let existingData): if let identity = try? JSONDecoder().decode(NostrIdentity.self, from: existingData) { cacheLock.lock() - currentIdentityCache = identity + if cacheGeneration == generation { + currentIdentityCache = identity + } cacheLock.unlock() return identity } @@ -57,7 +78,9 @@ final class NostrIdentityBridge { if case .success(let stored) = keychain.loadWithResult(key: currentIdentityKey, service: keychainService), stored == data { cacheLock.lock() - currentIdentityCache = nostrIdentity + if cacheGeneration == generation { + currentIdentityCache = nostrIdentity + } cacheLock.unlock() } @@ -79,6 +102,7 @@ final class NostrIdentityBridge { /// cannot keep signing with pre-panic keys cached in memory. func clearInMemoryCaches() { cacheLock.lock() + cacheGeneration &+= 1 currentIdentityCache = nil deviceSeedCache = nil derivedIdentityCache.removeAll() @@ -87,15 +111,14 @@ final class NostrIdentityBridge { /// Clear all Nostr identity associations and current identity func clearAllAssociations() { + // Bump generation and drop in-memory keys before and after deleting + // Keychain items so concurrent callers spanning the wipe cannot + // repopulate the cache with pre-wipe private keys. + clearInMemoryCaches() // Must go through the injected keychain, not raw SecItem calls: // under test that keychain is in-memory, and a direct delete here // would wipe the developer's real Nostr identity on every test run. keychain.deleteAll(service: keychainService) - - // Also drop the in-memory derived per-geohash identities and seed. These - // hold actual secp256k1 private keys; if left cached, post-panic geohash - // messages would still be signed with pre-panic keys (linkable across the - // wipe) until the app is force-quit. clearInMemoryCaches() } @@ -103,26 +126,42 @@ final class NostrIdentityBridge { /// Returns a stable device seed used to derive unlinkable per-geohash identities, /// along with whether the seed is durably backed by Keychain and safe to cache. - private func getOrCreateDeviceSeed() -> (seed: Data, durable: Bool) { + private func getOrCreateDeviceSeed() -> (seed: Data, durable: Bool, generation: UInt64) { cacheLock.lock() if let cached = deviceSeedCache { + let generation = cacheGeneration cacheLock.unlock() - return (cached, true) + return (cached, true, generation) } cacheLock.unlock() + keyCreationLock.lock() + defer { keyCreationLock.unlock() } + + cacheLock.lock() + if let cached = deviceSeedCache { + let generation = cacheGeneration + cacheLock.unlock() + return (cached, true, generation) + } + let generation = cacheGeneration + cacheLock.unlock() + switch keychain.loadWithResult(key: deviceSeedKey, service: keychainService) { case .success(let existing): cacheLock.lock() - deviceSeedCache = existing + let currentGen = cacheGeneration + if currentGen == generation { + deviceSeedCache = existing + } cacheLock.unlock() - return (existing, true) + return (existing, currentGen == generation, generation) case .itemNotFound: break case .deviceLocked, .accessDenied, .authenticationFailed, .otherError: // Preserve the retry path without overwriting or caching a temporary seed. let ephemeralSeed = SymmetricKey(size: .bits256).withUnsafeBytes { Data($0) } - return (ephemeralSeed, false) + return (ephemeralSeed, false, generation) } // CryptoKit key generation cannot fail, unlike SecRandomCopyBytes — @@ -134,13 +173,18 @@ final class NostrIdentityBridge { if case .success(let stored) = keychain.loadWithResult(key: deviceSeedKey, service: keychainService), stored == seed { cacheLock.lock() - deviceSeedCache = seed + let currentGen = cacheGeneration + if currentGen == generation { + deviceSeedCache = seed + persisted = true + } else { + persisted = false + } cacheLock.unlock() - persisted = true } else { persisted = false } - return (seed, persisted) + return (seed, persisted, generation) } /// Derive a deterministic, unlinkable Nostr identity for a mesh-bridge @@ -162,7 +206,7 @@ final class NostrIdentityBridge { } cacheLock.unlock() - let (seed, durable) = getOrCreateDeviceSeed() + let (seed, durable, generation) = getOrCreateDeviceSeed() guard let msg = geohash.data(using: .utf8) else { throw NSError(domain: "NostrIdentity", code: -1, userInfo: [NSLocalizedDescriptionKey: "Invalid geohash string"]) } @@ -183,7 +227,9 @@ final class NostrIdentityBridge { if let identity = try? NostrIdentity(privateKeyData: keyData) { if durable { cacheLock.lock() - derivedIdentityCache[geohash] = identity + if cacheGeneration == generation { + derivedIdentityCache[geohash] = identity + } cacheLock.unlock() } return identity @@ -195,7 +241,9 @@ final class NostrIdentityBridge { if durable { cacheLock.lock() - derivedIdentityCache[geohash] = identity + if cacheGeneration == generation { + derivedIdentityCache[geohash] = identity + } cacheLock.unlock() } diff --git a/bitchat/Services/BLE/BLEFileTransferPolicy.swift b/bitchat/Services/BLE/BLEFileTransferPolicy.swift index 59fab8b9..7ad077b4 100644 --- a/bitchat/Services/BLE/BLEFileTransferPolicy.swift +++ b/bitchat/Services/BLE/BLEFileTransferPolicy.swift @@ -123,7 +123,12 @@ enum ImageContainerValidator { return validateDimensions(of: source) } - static func validateDimensions(of source: CGImageSource) -> String? { + static func validateDimensions( + of source: CGImageSource, + maxDimensionPixels: Int = ImageContainerValidator.maxDimensionPixels, + maxTotalPixels: Int = ImageContainerValidator.maxTotalPixels, + maxFrameCount: Int = ImageContainerValidator.maxFrameCount + ) -> String? { let frameCount = CGImageSourceGetCount(source) guard frameCount >= 1 else { return "image contains no frames" diff --git a/bitchat/Services/BLE/BLEService.swift b/bitchat/Services/BLE/BLEService.swift index 7d65fc1d..10f9f6dd 100644 --- a/bitchat/Services/BLE/BLEService.swift +++ b/bitchat/Services/BLE/BLEService.swift @@ -1037,6 +1037,12 @@ final class BLEService: NSObject { options: [CBCentralManagerScanOptionAllowDuplicatesKey: false] ) } + // Restart peripheral advertising if Bluetooth is already powered on + // (e.g. after stopServicesImmediatelyForPanic() stopped advertising + // without tearing down the CBPeripheralManager). + if let pm = peripheralManager, pm.state == .poweredOn, !pm.isAdvertising { + pm.startAdvertising(BLERadioController.advertisementData()) + } // Send initial announce after services are ready // Use longer delay to avoid conflicts with other announces @@ -1498,10 +1504,21 @@ final class BLEService: NSObject { noiseService.verifySignature(signature, for: data, publicKey: publicKey) } + private let externalNoiseCallbacksLock = NSLock() + private var externalPeerAuthenticatedHandlers: [(PeerID, String) -> Void] = [] + private var externalHandshakeRequiredHandler: ((PeerID) -> Void)? + func installNoiseSessionCallbacks( onPeerAuthenticated: @escaping (PeerID, String) -> Void, onHandshakeRequired: @escaping (PeerID) -> Void ) { + // Persist externally installed callbacks so `resetIdentityForPanic()` + // re-attaches them when it creates a fresh `NoiseEncryptionService`. + externalNoiseCallbacksLock.lock() + externalPeerAuthenticatedHandlers.append(onPeerAuthenticated) + externalHandshakeRequiredHandler = onHandshakeRequired + externalNoiseCallbacksLock.unlock() + // `onPeerAuthenticated` is additive (the encryption service keeps an // array of handlers); `onHandshakeRequired` is a single slot. noiseService.onPeerAuthenticated = onPeerAuthenticated @@ -3043,6 +3060,9 @@ final class BLEService: NSObject { } func addPeerAuthenticatedObserver(_ handler: @escaping (PeerID, String) -> Void) { + externalNoiseCallbacksLock.lock() + externalPeerAuthenticatedHandlers.append(handler) + externalNoiseCallbacksLock.unlock() // Appends to the encryption service's handler array, so this never // displaces the callbacks installed by installNoiseSessionCallbacks. noiseService.addOnPeerAuthenticatedHandler(handler) @@ -4135,6 +4155,18 @@ extension BLEService { } private func configureNoiseServiceCallbacks(for service: NoiseEncryptionService) { + let (peerAuthHandlers, handshakeRequiredHandler): ([(PeerID, String) -> Void], ((PeerID) -> Void)?) = { + externalNoiseCallbacksLock.lock() + defer { externalNoiseCallbacksLock.unlock() } + return (externalPeerAuthenticatedHandlers, externalHandshakeRequiredHandler) + }() + for handler in peerAuthHandlers { + service.addOnPeerAuthenticatedHandler(handler) + } + if let handshakeRequiredHandler { + service.onHandshakeRequired = handshakeRequiredHandler + } + service.onPeerAuthenticatedWithGeneration = { [weak self] peerID, fingerprint, generation in SecureLogger.debug("🔐 Noise session authenticated with \(peerID.id.prefix(8))…, fingerprint: \(fingerprint.prefix(16))…") // Authentication can be reported while an initiator is still diff --git a/bitchat/Services/CashuTokenDecoder.swift b/bitchat/Services/CashuTokenDecoder.swift index 06b9a95e..0f528551 100644 --- a/bitchat/Services/CashuTokenDecoder.swift +++ b/bitchat/Services/CashuTokenDecoder.swift @@ -84,30 +84,57 @@ enum CashuTokenDecoder { } private final class PermissiveDecodeCache: @unchecked Sendable { + private let lock = NSLock() + private var generation: UInt64 = 0 private let cache: NSCache = { let c = NSCache() c.countLimit = 256 return c }() - func entry(for key: String) -> DecodeCacheEntry? { - cache.object(forKey: key as NSString) + func currentGeneration() -> UInt64 { + lock.lock() + defer { lock.unlock() } + return generation } - func store(_ info: TokenInfo?, for key: String) { + func entry(for key: String) -> DecodeCacheEntry? { + lock.lock() + defer { lock.unlock() } + return cache.object(forKey: key as NSString) + } + + func store(_ info: TokenInfo?, for key: String, expectedGeneration: UInt64) { + lock.lock() + defer { lock.unlock() } + guard generation == expectedGeneration else { return } cache.setObject(DecodeCacheEntry(info), forKey: key as NSString) } + + func reset() { + lock.lock() + defer { lock.unlock() } + generation &+= 1 + cache.removeAllObjects() + } } private static let permissiveCache = PermissiveDecodeCache() + /// Panic-wipe hook: evicts cached bearer ecash token strings and decoded + /// mint/memo metadata from process memory, and fences any in-flight decode. + static func resetForPanic() { + permissiveCache.reset() + } + static func decode(_ raw: String, strict: Bool = false) -> TokenInfo? { + let generation = strict ? 0 : permissiveCache.currentGeneration() if !strict, let cached = permissiveCache.entry(for: raw) { return cached.info } let decoded = decodeUncached(raw, strict: strict) if !strict { - permissiveCache.store(decoded, for: raw) + permissiveCache.store(decoded, for: raw, expectedGeneration: generation) } return decoded } diff --git a/bitchat/Services/NostrTransport.swift b/bitchat/Services/NostrTransport.swift index c65c8376..bbc630e5 100644 --- a/bitchat/Services/NostrTransport.swift +++ b/bitchat/Services/NostrTransport.swift @@ -69,7 +69,18 @@ final class NostrTransport: Transport, @unchecked Sendable { // BLE short peer ID embedded in favorites (recipient-addressed) envelopes. // Geohash envelopes never carry it (see NostrEmbeddedBitChat). - var senderPeerID = PeerID(str: "") + // When `senderPeerIDProvider` is wired (production bootstrap), this reads + // the live mesh peer ID at send time so a panic-wipe identity rotation + // never embeds the pre-wipe peer ID in subsequent Nostr envelopes. + private var storedSenderPeerID = PeerID(str: "") + var senderPeerIDProvider: (() -> PeerID)? + var senderPeerID: PeerID { + get { senderPeerIDProvider?() ?? storedSenderPeerID } + set { + senderPeerIDProvider = nil + storedSenderPeerID = newValue + } + } // Throttle outbound acks — READ receipts and DELIVERED acks, direct and // geohash — to avoid relay rate limits. Reconnect redelivery produces a @@ -280,7 +291,9 @@ final class NostrTransport: Transport, @unchecked Sendable { func sendMessage(_ content: String, mentions: [String]) { /* no-op */ } func sendPrivateMessage(_ content: String, to peerID: PeerID, recipientNickname: String, messageID: String) { + let generation = dependencies.ackPacer.currentGeneration() Task { @MainActor in + guard dependencies.ackPacer.currentGeneration() == generation else { return } guard let recipientNpub = resolveRecipientNpub(for: peerID), let recipientHex = npubToHex(recipientNpub), let senderIdentity = try? dependencies.currentIdentity() else { return } @@ -289,7 +302,7 @@ final class NostrTransport: Transport, @unchecked Sendable { SecureLogger.error("NostrTransport: failed to embed PM packet", category: .session) return } - sendWrappedMessage(content: embedded, recipientHex: recipientHex, senderIdentity: senderIdentity) + sendWrappedMessage(content: embedded, recipientHex: recipientHex, senderIdentity: senderIdentity, expectedGeneration: generation) } } @@ -306,7 +319,9 @@ final class NostrTransport: Transport, @unchecked Sendable { } func sendFavoriteNotification(to peerID: PeerID, isFavorite: Bool) { + let generation = dependencies.ackPacer.currentGeneration() Task { @MainActor in + guard dependencies.ackPacer.currentGeneration() == generation else { return } guard let recipientNpub = resolveRecipientNpub(for: peerID), let recipientHex = npubToHex(recipientNpub), let senderIdentity = try? dependencies.currentIdentity() else { return } @@ -316,7 +331,7 @@ final class NostrTransport: Transport, @unchecked Sendable { SecureLogger.error("NostrTransport: failed to embed favorite notification", category: .session) return } - sendWrappedMessage(content: embedded, recipientHex: recipientHex, senderIdentity: senderIdentity) + sendWrappedMessage(content: embedded, recipientHex: recipientHex, senderIdentity: senderIdentity, expectedGeneration: generation) } } @@ -341,14 +356,16 @@ extension NostrTransport { // MARK: Geohash DMs (per-geohash identity) func sendPrivateMessageGeohash(content: String, toRecipientHex recipientHex: String, from identity: NostrIdentity, messageID: String) { + let generation = dependencies.ackPacer.currentGeneration() Task { @MainActor in + guard dependencies.ackPacer.currentGeneration() == generation else { return } guard !recipientHex.isEmpty else { return } SecureLogger.debug("GeoDM: send PM mid=\(messageID.prefix(8))…", category: .session) guard let embedded = NostrEmbeddedBitChat.encodePMForNostrNoRecipient(content: content, messageID: messageID) else { SecureLogger.error("NostrTransport: failed to embed geohash PM packet", category: .session) return } - sendWrappedMessage(content: embedded, recipientHex: recipientHex, senderIdentity: identity, registerPending: true) + sendWrappedMessage(content: embedded, recipientHex: recipientHex, senderIdentity: identity, registerPending: true, expectedGeneration: generation) } } } diff --git a/bitchat/Services/NotificationService.swift b/bitchat/Services/NotificationService.swift index e50d4da5..c371bd8b 100644 --- a/bitchat/Services/NotificationService.swift +++ b/bitchat/Services/NotificationService.swift @@ -30,6 +30,11 @@ protocol NotificationCategoryRegistering { func setCategories(_ categories: Set) } +protocol NotificationClearing { + func removeAllDeliveredNotifications() + func removeAllPendingNotificationRequests() +} + private final class NotificationCenterAuthorizerAdapter: NotificationAuthorizing { private let center: UNUserNotificationCenter @@ -71,6 +76,22 @@ private final class NotificationCenterCategoryRegistrarAdapter: NotificationCate } } +private final class NotificationCenterClearerAdapter: NotificationClearing { + private let center: UNUserNotificationCenter + + init(center: UNUserNotificationCenter) { + self.center = center + } + + func removeAllDeliveredNotifications() { + center.removeAllDeliveredNotifications() + } + + func removeAllPendingNotificationRequests() { + center.removeAllPendingNotificationRequests() + } +} + private struct NoopNotificationAuthorizer: NotificationAuthorizing { func requestAuthorization( options: UNAuthorizationOptions, @@ -88,6 +109,11 @@ private struct NoopNotificationCategoryRegistrar: NotificationCategoryRegisterin func setCategories(_ categories: Set) {} } +private struct NoopNotificationClearer: NotificationClearing { + func removeAllDeliveredNotifications() {} + func removeAllPendingNotificationRequests() {} +} + final class NotificationService { static let shared = NotificationService() @@ -128,6 +154,7 @@ final class NotificationService { private let authorizer: NotificationAuthorizing private let requestDeliverer: NotificationRequestDelivering private let categoryRegistrar: NotificationCategoryRegistering + private let notificationClearer: NotificationClearing /// Returns true if running in test environment (XCTest, Swift Testing, or CI) private var isRunningTests: Bool { @@ -148,11 +175,13 @@ final class NotificationService { self.authorizer = NoopNotificationAuthorizer() self.requestDeliverer = NoopNotificationRequestDeliverer() self.categoryRegistrar = NoopNotificationCategoryRegistrar() + self.notificationClearer = NoopNotificationClearer() } else { let center = UNUserNotificationCenter.current() self.authorizer = NotificationCenterAuthorizerAdapter(center: center) self.requestDeliverer = NotificationCenterRequestDelivererAdapter(center: center) self.categoryRegistrar = NotificationCenterCategoryRegistrarAdapter(center: center) + self.notificationClearer = NotificationCenterClearerAdapter(center: center) } } @@ -161,15 +190,26 @@ final class NotificationService { authorizer: NotificationAuthorizing, requestDeliverer: NotificationRequestDelivering, categoryRegistrar: NotificationCategoryRegistering = NoopNotificationCategoryRegistrar(), + notificationClearer: NotificationClearing = NoopNotificationClearer(), hidePreviewsProvider: @escaping () -> Bool = { NotificationPrivacySettings.hideMessagePreviews } ) { self.isRunningTestsProvider = isRunningTestsProvider self.authorizer = authorizer self.requestDeliverer = requestDeliverer self.categoryRegistrar = categoryRegistrar + self.notificationClearer = notificationClearer self.hidePreviewsProvider = hidePreviewsProvider } + /// Panic-wipe hook: removes all delivered and pending local notifications + /// from Notification Center so sender names, previews, and routing metadata + /// cannot linger on a seized device after a wipe. + func clearAllNotificationsForPanic() { + guard !isRunningTests else { return } + notificationClearer.removeAllPendingNotificationRequests() + notificationClearer.removeAllDeliveredNotifications() + } + func requestAuthorization() { guard !isRunningTests else { return } registerCategories() diff --git a/bitchat/Utils/Color+Peer.swift b/bitchat/Utils/Color+Peer.swift index ad77ee45..bb5ae528 100644 --- a/bitchat/Utils/Color+Peer.swift +++ b/bitchat/Utils/Color+Peer.swift @@ -10,11 +10,48 @@ import SwiftUI extension Color { private static let maxPeerColorCacheEntries = 512 - private static var peerColorCache: [String: Color] = [:] + + private final class PeerColorCache: @unchecked Sendable { + private let lock = NSLock() + private var entries: [String: Color] = [:] + private var generation: UInt64 = 0 + + func lookup(_ key: String) -> (color: Color?, generation: UInt64) { + lock.lock() + defer { lock.unlock() } + return (entries[key], generation) + } + + func store(_ color: Color, for key: String, expectedGeneration: UInt64) { + lock.lock() + defer { lock.unlock() } + guard generation == expectedGeneration else { return } + if entries.count >= Color.maxPeerColorCacheEntries { + entries.removeAll(keepingCapacity: true) + } + entries[key] = color + } + + func reset() { + lock.lock() + defer { lock.unlock() } + generation &+= 1 + entries.removeAll(keepingCapacity: false) + } + } + + private static let peerColorCache = PeerColorCache() + + /// Panic-wipe hook: drops cached peer color seeds (nicknames, Noise keys, + /// Nostr pubkeys) from memory and fences any concurrent lookup. + static func clearPeerColorCache() { + peerColorCache.reset() + } init(peerSeed: String, isDark: Bool) { let cacheKey = peerSeed + (isDark ? "|dark" : "|light") - if let cached = Self.peerColorCache[cacheKey] { + let lookup = Self.peerColorCache.lookup(cacheKey) + if let cached = lookup.color { self = cached return } @@ -33,10 +70,7 @@ extension Color { let saturation = min(1.0, max(0.50, sBase + (sRand - 0.5) * sRange)) let brightness = min(1.0, max(0.35, bBase + (bRand - 0.5) * bRange)) let c = Color(hue: hue, saturation: saturation, brightness: brightness) - if Self.peerColorCache.count >= Self.maxPeerColorCacheEntries { - Self.peerColorCache.removeAll(keepingCapacity: true) - } - Self.peerColorCache[cacheKey] = c + Self.peerColorCache.store(c, for: cacheKey, expectedGeneration: lookup.generation) self = c } } diff --git a/bitchat/ViewModels/ChatLiveVoiceCoordinator.swift b/bitchat/ViewModels/ChatLiveVoiceCoordinator.swift index 66d9d30a..9b1e0e71 100644 --- a/bitchat/ViewModels/ChatLiveVoiceCoordinator.swift +++ b/bitchat/ViewModels/ChatLiveVoiceCoordinator.swift @@ -195,6 +195,11 @@ final class ChatLiveVoiceCoordinator { private var fileManager: FileManager { fileStore.fileManager } private var assemblies: [AssemblyKey: Assembly] = [:] private var finishedBursts: [AssemblyKey: FinishedBurst] = [:] + /// Live capture filenames created by *this* coordinator instance so an + /// asynchronous startup sweep launched during lazy initialization can never + /// unlink an in-flight capture that started immediately after `init()`. + private var createdCaptureFileNames: Set = [] + private var startupSweepTask: Task? /// Players still draining after their assembly — the sole strong owner — /// was discarded on burst END. Without this hold the player deallocates /// mid-tail (or mid session-acquire, killing the whole burst's audio) @@ -225,8 +230,14 @@ final class ChatLiveVoiceCoordinator { if sweepsOnInit { if asyncStartupSweep { let store = fileStore - Task.detached(priority: .utility) { - Self.sweepStaleLiveCaptures(in: store) + startupSweepTask = Task.detached(priority: .utility) { [weak self] in + let candidates = Self.discoverStaleLiveCaptures(in: store) + guard !candidates.isEmpty, !Task.isCancelled else { return } + let excluded: Set = await MainActor.run { [weak self] in + self?.createdCaptureFileNames ?? [] + } + guard !Task.isCancelled else { return } + Self.removeLiveCaptures(candidates, excludingFileNames: excluded, in: store) } } else { Self.sweepStaleLiveCaptures(in: fileStore) @@ -310,6 +321,9 @@ final class ChatLiveVoiceCoordinator { } drainingPlayers.removeAll(keepingCapacity: false) finishedBursts.removeAll(keepingCapacity: false) + createdCaptureFileNames.removeAll(keepingCapacity: false) + startupSweepTask?.cancel() + startupSweepTask = nil updatePublicTalkerIndicator() } @@ -425,6 +439,7 @@ final class ChatLiveVoiceCoordinator { } else { fileStore.enforceQuota(reservingBytes: TransportConfig.pttMaxBurstBytes) } + createdCaptureFileNames.insert(fileURL.lastPathComponent) fileManager.createFile( atPath: fileURL.path, contents: nil, @@ -784,7 +799,7 @@ final class ChatLiveVoiceCoordinator { /// only (ConversationStore never persists; the gossip archive replays /// `MessageType.message` packets only), so no row from a previous /// process can reference the file. - nonisolated private static func sweepStaleLiveCaptures(in fileStore: BLEIncomingFileStore) { + nonisolated private static func discoverStaleLiveCaptures(in fileStore: BLEIncomingFileStore) -> [URL] { let fileManager = fileStore.fileManager guard let directory = try? fileStore.incomingDirectory(subdirectory: Self.incomingSubdirectory), let contents = try? fileManager.contentsOfDirectory( @@ -792,9 +807,25 @@ final class ChatLiveVoiceCoordinator { includingPropertiesForKeys: nil, options: [.skipsHiddenFiles] ) - else { return } - for url in contents where url.lastPathComponent.hasPrefix(BLEIncomingFileStore.liveCapturePrefix) && url.pathExtension == "aac" { + else { return [] } + return contents.filter { + $0.lastPathComponent.hasPrefix(BLEIncomingFileStore.liveCapturePrefix) && $0.pathExtension == "aac" + } + } + + nonisolated private static func removeLiveCaptures( + _ urls: [URL], + excludingFileNames: Set, + in fileStore: BLEIncomingFileStore + ) { + let fileManager = fileStore.fileManager + for url in urls where !excludingFileNames.contains(url.lastPathComponent) { try? fileManager.removeItem(at: url) } } + + nonisolated private static func sweepStaleLiveCaptures(in fileStore: BLEIncomingFileStore) { + let candidates = discoverStaleLiveCaptures(in: fileStore) + removeLiveCaptures(candidates, excludingFileNames: [], in: fileStore) + } } diff --git a/bitchat/ViewModels/ChatOutgoingCoordinator.swift b/bitchat/ViewModels/ChatOutgoingCoordinator.swift index 1bb3e213..246e2998 100644 --- a/bitchat/ViewModels/ChatOutgoingCoordinator.swift +++ b/bitchat/ViewModels/ChatOutgoingCoordinator.swift @@ -83,11 +83,20 @@ final class ChatOutgoingCoordinator { /// the message still goes out at the difficulty already reached. /// (Read access is internal so tests can await the send's completion.) private(set) var geohashMiningTask: Task? + /// Incremented on panic wipe so any in-flight PoW mining task drops its + /// pre-wipe event instead of appending or publishing after the wipe. + private var panicGeneration: UInt64 = 0 init(context: any ChatOutgoingContext) { self.context = context } + func resetForPanic() { + panicGeneration &+= 1 + geohashMiningTask?.cancel() + geohashMiningTask = nil + } + /// Finish any in-flight geohash PoW mining early (the pending message /// still sends, at whatever committed difficulty it reached). func expeditePendingGeohashMining() { @@ -182,10 +191,12 @@ private extension ChatOutgoingCoordinator { // NIP-13 target is polled, not aborted), so it still finishes and // sends — and it finishes fast, so awaiting it never stacks mining // delays or blocks a send beyond `NostrPoW.miningTimeCap`. + let generation = panicGeneration let previousSend = geohashMiningTask previousSend?.cancel() - geohashMiningTask = Task { @MainActor [weak context = self.context] in + geohashMiningTask = Task { @MainActor [weak self, weak context = self.context] in await previousSend?.value + guard let self, self.panicGeneration == generation else { return } let event: NostrEvent do { @@ -197,13 +208,14 @@ private extension ChatOutgoingCoordinator { teleported: teleported ) } catch { + guard self.panicGeneration == generation else { return } SecureLogger.error("❌ Failed to prepare geohash message: \(error)", category: .session) context?.addSystemMessage( String(localized: "system.location.send_failed", comment: "System message when a location channel send fails") ) return } - guard let context else { return } + guard self.panicGeneration == generation, let context else { return } let message = BitchatMessage( id: event.id, diff --git a/bitchat/ViewModels/ChatViewModel.swift b/bitchat/ViewModels/ChatViewModel.swift index c92ff2c2..41e919a9 100644 --- a/bitchat/ViewModels/ChatViewModel.swift +++ b/bitchat/ViewModels/ChatViewModel.swift @@ -481,8 +481,40 @@ final class ChatViewModel: ObservableObject, BitchatDelegate, SynchronousMessage // Track sent read receipts to avoid duplicates (persisted across launches). // Mutations coalesce into a debounced off-main encode/write so rapid bursts // (opening a chat, reconnecting) do not re-encode the whole set on MainActor. + private final class ReadReceiptPersistGate: @unchecked Sendable { + private let lock = NSLock() + private var generation: UInt64 = 0 + + func nextGeneration() -> UInt64 { + lock.lock() + defer { lock.unlock() } + generation &+= 1 + return generation + } + + func commitIfCurrent(data: Data, expectedGeneration: UInt64, defaults: UserDefaults) { + lock.lock() + defer { lock.unlock() } + guard generation == expectedGeneration else { return } + defaults.set(data, forKey: "sentReadReceipts") + } + + func flushSynchronously(receipts: [String], defaults: UserDefaults) { + lock.lock() + defer { lock.unlock() } + generation &+= 1 + if receipts.isEmpty { + defaults.removeObject(forKey: "sentReadReceipts") + } else if let data = try? JSONEncoder().encode(receipts) { + defaults.set(data, forKey: "sentReadReceipts") + } else { + SecureLogger.error("❌ Failed to encode read receipts for persistence", category: .session) + } + } + } + private var readReceiptPersistTask: Task? - private var readReceiptPersistGeneration: UInt64 = 0 + private let readReceiptPersistGate = ReadReceiptPersistGate() var sentReadReceipts: Set = [] { // messageID set didSet { @@ -493,21 +525,23 @@ final class ChatViewModel: ObservableObject, BitchatDelegate, SynchronousMessage private func schedulePersistSentReadReceipts() { readReceiptPersistTask?.cancel() - readReceiptPersistGeneration &+= 1 - let generation = readReceiptPersistGeneration + let gate = readReceiptPersistGate + let generation = gate.nextGeneration() let snapshot = Array(sentReadReceipts) let defaults = readReceiptsDefaults readReceiptPersistTask = Task.detached(priority: .utility) { [weak self] in try? await Task.sleep(nanoseconds: 250_000_000) guard !Task.isCancelled else { return } if let data = try? JSONEncoder().encode(snapshot) { - defaults.set(data, forKey: "sentReadReceipts") + gate.commitIfCurrent(data: data, expectedGeneration: generation, defaults: defaults) } else { SecureLogger.error("❌ Failed to encode read receipts for persistence", category: .session) } await MainActor.run { [weak self] in - guard let self, self.readReceiptPersistGeneration == generation else { return } - self.readReceiptPersistTask = nil + guard let self else { return } + if self.readReceiptPersistTask?.isCancelled == false { + self.readReceiptPersistTask = nil + } } } } @@ -517,14 +551,10 @@ final class ChatViewModel: ObservableObject, BitchatDelegate, SynchronousMessage func flushPersistedReadReceiptsSynchronously() { readReceiptPersistTask?.cancel() readReceiptPersistTask = nil - readReceiptPersistGeneration &+= 1 - if sentReadReceipts.isEmpty { - readReceiptsDefaults.removeObject(forKey: "sentReadReceipts") - } else if let data = try? JSONEncoder().encode(Array(sentReadReceipts)) { - readReceiptsDefaults.set(data, forKey: "sentReadReceipts") - } else { - SecureLogger.error("❌ Failed to encode read receipts for persistence", category: .session) - } + readReceiptPersistGate.flushSynchronously( + receipts: Array(sentReadReceipts), + defaults: readReceiptsDefaults + ) } // Track which GeoDM messages we've already sent a delivery ACK for (by messageID) @@ -1631,14 +1661,20 @@ final class ChatViewModel: ObservableObject, BitchatDelegate, SynchronousMessage meshService.emergencyDisconnectAll() } - // Invalidate detached media preparation and close live capture file + // Invalidate detached media preparation, in-flight geohash PoW mining, + // uncommitted public timeline batches, and close live capture file // handles before clearing state or removing the media directory. + outgoingCoordinator.resetForPanic() + publicMessagePipeline.reset() mediaTransferCoordinator.resetForPanic() liveVoiceCoordinator.resetForPanic() privateChatClearGeneration &+= 1 queuedPrivateChatClears.removeAll(keepingCapacity: false) privateChatClearInFlight = false + // Remove delivered and pending local notifications from Notification Center. + NotificationService.shared.clearAllNotificationsForPanic() + // Deny and release any clear-media confirmations before identities, // message state, and local files are wiped. cancelAllLegacyPrivateMediaConsents() @@ -1710,6 +1746,8 @@ final class ChatViewModel: ObservableObject, BitchatDelegate, SynchronousMessage LocationNotesDependencies.clearCachedIdentitiesForPanic() WaveformCache.shared.resetForPanic() ImageDownsampler.resetForPanic() + CashuTokenDecoder.resetForPanic() + Color.clearPeerColorCache() // Drop private group keys and rosters (keychain + disk) groupStore.wipe() diff --git a/bitchat/ViewModels/ChatViewModelBootstrapper.swift b/bitchat/ViewModels/ChatViewModelBootstrapper.swift index 0f5d9593..739e2714 100644 --- a/bitchat/ViewModels/ChatViewModelBootstrapper.swift +++ b/bitchat/ViewModels/ChatViewModelBootstrapper.swift @@ -29,7 +29,9 @@ struct ChatViewModelServiceBundle { identityManager: identityManager ) let nostrTransport = NostrTransport(keychain: keychain, idBridge: idBridge) - nostrTransport.senderPeerID = meshService.myPeerID + nostrTransport.senderPeerIDProvider = { [weak meshService] in + meshService?.myPeerID ?? PeerID(str: "") + } let messageRouter = MessageRouter( transports: [meshService, nostrTransport], outboxStore: outboxStore, diff --git a/bitchat/ViewModels/PublicMessagePipeline.swift b/bitchat/ViewModels/PublicMessagePipeline.swift index 92dd0412..1fee21df 100644 --- a/bitchat/ViewModels/PublicMessagePipeline.swift +++ b/bitchat/ViewModels/PublicMessagePipeline.swift @@ -77,6 +77,16 @@ final class PublicMessagePipeline { func flushIfNeeded() { flushBuffer() } + + /// Panic-wipe hook: cancels any scheduled batch flush and drops all + /// uncommitted public messages so pre-wipe traffic cannot resurface. + func reset() { + timer?.invalidate() + timer = nil + buffer.removeAll(keepingCapacity: false) + recentBatchSizes.removeAll(keepingCapacity: false) + dynamicFlushInterval = baseFlushInterval + } } private extension PublicMessagePipeline { diff --git a/bitchatTests/ChatLiveVoiceCoordinatorTests.swift b/bitchatTests/ChatLiveVoiceCoordinatorTests.swift index 5931370a..97cd3bfe 100644 --- a/bitchatTests/ChatLiveVoiceCoordinatorTests.swift +++ b/bitchatTests/ChatLiveVoiceCoordinatorTests.swift @@ -630,6 +630,51 @@ struct ChatLiveVoiceCoordinatorTests { #expect(FileManager.default.fileExists(atPath: finalized.path)) } + @Test func asyncStartupSweepDoesNotDeleteActiveCaptureStartedImmediatelyAfterInit() async throws { + let (store, incoming, cleanup) = try makeTempStore() + defer { cleanup() } + + let stale = incoming.appendingPathComponent("voice_live_0000000000000000_peer_dm.aac") + try Data([0x01]).write(to: stale) + + let context = MockChatLiveVoiceContext() + let coordinator = ChatLiveVoiceCoordinator( + context: context, + fileStore: store, + sweepsOnInit: true, + asyncStartupSweep: true + ) + + // Immediately start a live burst before the detached startup sweep runs. + let burstID = makeBurstID(0x88) + let frame = Data(repeating: 0x0E, count: 60) + send(try #require(VoiceBurstPacket(burstID: burstID, seq: 1, kind: .frames([frame]))), to: coordinator, from: peer) + + let liveCapture = incoming.appendingPathComponent( + "voice_live_\(burstID.hexEncodedString())_\(peer.id)_dm.aac" + ) + let fallbackURL = incoming.appendingPathComponent(fallbackName(burstID: burstID, peerID: peer)) + #expect(FileManager.default.fileExists(atPath: liveCapture.path)) + + let swept = await TestHelpers.waitUntil( + { !FileManager.default.fileExists(atPath: stale.path) }, + timeout: TestConstants.settleTimeout + ) + #expect(swept) + // Under heavy parallel CI load the 3s idle timer may already have + // promoted the active capture to its fallback name while waiting on the + // `.utility` sweep; either way, the sweep must never have deleted it. + #expect( + FileManager.default.fileExists(atPath: liveCapture.path) + || FileManager.default.fileExists(atPath: fallbackURL.path) + ) + + // Finalizing the burst (no-op if idle timer already finalized) must + // leave the full audio intact at the promoted fallback path. + send(try #require(VoiceBurstPacket(burstID: burstID, seq: 2, kind: .end(totalDataPackets: 1, durationMs: 64))), to: coordinator, from: peer) + #expect(try Data(contentsOf: fallbackURL) == ADTSFramer.frame(frame)) + } + @Test func finalizedFallbackSurvivesNextStartupSweep() throws { let (store, incoming, cleanup) = try makeTempStore() defer { cleanup() } diff --git a/bitchatTests/Features/ImageUtilsTests.swift b/bitchatTests/Features/ImageUtilsTests.swift index 8c872bff..1d784eb0 100644 --- a/bitchatTests/Features/ImageUtilsTests.swift +++ b/bitchatTests/Features/ImageUtilsTests.swift @@ -120,4 +120,41 @@ struct ImageUtilsTests { ImageDownsampler.resetForPanic() #expect(ImageDownsampler.cachedImage(for: fileURL, maxPixelSize: 64) == nil) } + + @Test + func processImageAtURL_acceptsHighResolution24MPPhotoAndDownsamples() throws { + // 5712 x 4284 (~24.5 MP) exceeds the incoming BLE 4096 px / 16.7 MP cap + // (ImageContainerValidator.maxDimensionPixels), matching modern iPhone + // default photos. Outgoing ImageUtils must still accept and downsample it. + let dir = makeTemporaryDirectoryURL("image-24mp-\(UUID().uuidString)") + let outputDir = makeTemporaryDirectoryURL("image-24mp-out-\(UUID().uuidString)") + defer { + try? FileManager.default.removeItem(at: dir) + try? FileManager.default.removeItem(at: outputDir) + } + try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true) + + let sourceURL = dir.appendingPathComponent("iphone-24mp.png") + try TestImageFixtures.makePNG(width: 5_712, height: 4_284).write(to: sourceURL) + + let downsampledURL = try ImageUtils.processImage(at: sourceURL, maxDimension: 448, outputDirectory: outputDir) + let data = try Data(contentsOf: downsampledURL) + #expect(data.starts(with: Data([0xFF, 0xD8]))) + let loaded = try #require(ImageDownsampler.loadDownsampledImage(from: downsampledURL, maxPixelSize: 1024)) + #expect(max(loaded.size.width, loaded.size.height) <= 448.5) + } + + @Test + func processImageAtURL_stillRejectsExtremeDecompressionBomb() throws { + let dir = makeTemporaryDirectoryURL("image-bomb-\(UUID().uuidString)") + defer { try? FileManager.default.removeItem(at: dir) } + try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true) + + let bombURL = dir.appendingPathComponent("bomb.png") + try TestImageFixtures.makePNGBomb(width: 20_000, height: 20_000).write(to: bombURL) + + #expect(throws: ImageUtilsError.self) { + try ImageUtils.processImage(at: bombURL) + } + } } diff --git a/bitchatTests/Nostr/GeoRelayDirectoryTests.swift b/bitchatTests/Nostr/GeoRelayDirectoryTests.swift index 8b0f81e2..fab7b627 100644 --- a/bitchatTests/Nostr/GeoRelayDirectoryTests.swift +++ b/bitchatTests/Nostr/GeoRelayDirectoryTests.swift @@ -561,6 +561,87 @@ final class GeoRelayDirectoryTests: XCTestCase { XCTAssertEqual(directory.debugClosestRelaysCacheCount, 0) } + func test_resetForPanic_cancelsInFlightFetchWithoutWritingCacheOrSchedulingRetry() async { + final class Gate: @unchecked Sendable { + private let lock = NSLock() + private var startedContinuation: CheckedContinuation? + private var releaseContinuation: CheckedContinuation? + private var didStart = false + private var pendingRelease: Bool? + + func awaitStart() async { + await withCheckedContinuation { cont in + lock.lock() + if didStart { + lock.unlock() + cont.resume() + } else { + startedContinuation = cont + lock.unlock() + } + } + } + + func waitForTor() async -> Bool { + await withCheckedContinuation { cont in + lock.lock() + didStart = true + let start = startedContinuation + startedContinuation = nil + if let result = pendingRelease { + pendingRelease = nil + lock.unlock() + start?.resume() + cont.resume(returning: result) + } else { + releaseContinuation = cont + lock.unlock() + start?.resume() + } + } + } + + func release(_ result: Bool) { + lock.lock() + if let cont = releaseContinuation { + releaseContinuation = nil + lock.unlock() + cont.resume(returning: result) + } else { + pendingRelease = result + lock.unlock() + } + } + } + + let gate = Gate() + let harness = makeHarness( + bundleCSV: """ + relay url,lat,lon + bundle.example,37.77,-122.41 + """, + fetchCSV: """ + relay url,lat,lon + remote.example,37.77,-122.41 + """, + awaitTorReady: { await gate.waitForTor() } + ) + let directory = GeoRelayDirectory(dependencies: harness.dependencies) + + directory.prefetchIfNeeded(force: true) + await gate.awaitStart() + + // Panic runs while the remote fetch is awaiting Tor readiness. + directory.resetForPanic() + gate.release(false) + await Task.yield() + try? await Task.sleep(nanoseconds: 50_000_000) + + XCTAssertFalse(directory.debugHasRetryTask, "Stale pre-panic fetch must not re-arm retryTask") + XCTAssertNil(harness.fileStore.dataByURL[harness.cacheURL]) + XCTAssertNil(harness.dependencies.userDefaults.object(forKey: "georelay.lastFetchAt")) + } + private func makeHarness( cacheCSV: String? = nil, bundleCSV: String? = nil, diff --git a/bitchatTests/Services/NotificationServiceTests.swift b/bitchatTests/Services/NotificationServiceTests.swift index 384f0075..0e5fadfb 100644 --- a/bitchatTests/Services/NotificationServiceTests.swift +++ b/bitchatTests/Services/NotificationServiceTests.swift @@ -116,6 +116,49 @@ final class NotificationServiceTests: XCTestCase { XCTAssertEqual(deliverer.requests[1].content.interruptionLevel, .timeSensitive) XCTAssertEqual(deliverer.requests[1].content.body, "2 people around") } + + func test_clearAllNotificationsForPanic_clearsPendingAndDelivered() { + let clearer = RecordingNotificationClearer() + let service = NotificationService( + isRunningTestsProvider: { false }, + authorizer: RecordingNotificationAuthorizer(), + requestDeliverer: RecordingNotificationRequestDeliverer(), + notificationClearer: clearer + ) + + service.clearAllNotificationsForPanic() + + XCTAssertEqual(clearer.removePendingCalls, 1) + XCTAssertEqual(clearer.removeDeliveredCalls, 1) + } + + func test_clearAllNotificationsForPanic_skipsWhenRunningTests() { + let clearer = RecordingNotificationClearer() + let service = NotificationService( + isRunningTestsProvider: { true }, + authorizer: RecordingNotificationAuthorizer(), + requestDeliverer: RecordingNotificationRequestDeliverer(), + notificationClearer: clearer + ) + + service.clearAllNotificationsForPanic() + + XCTAssertEqual(clearer.removePendingCalls, 0) + XCTAssertEqual(clearer.removeDeliveredCalls, 0) + } +} + +private final class RecordingNotificationClearer: NotificationClearing { + private(set) var removePendingCalls = 0 + private(set) var removeDeliveredCalls = 0 + + func removeAllPendingNotificationRequests() { + removePendingCalls += 1 + } + + func removeAllDeliveredNotifications() { + removeDeliveredCalls += 1 + } } private final class RecordingNotificationAuthorizer: NotificationAuthorizing { diff --git a/bitchatTests/Services/PanicWipeCoverageTests.swift b/bitchatTests/Services/PanicWipeCoverageTests.swift index 2d9108bb..89e618c4 100644 --- a/bitchatTests/Services/PanicWipeCoverageTests.swift +++ b/bitchatTests/Services/PanicWipeCoverageTests.swift @@ -1,6 +1,7 @@ import BitFoundation import Combine import Foundation +import SwiftUI import XCTest @testable import bitchat @@ -276,4 +277,216 @@ final class PanicWipeCoverageTests: XCTestCase { XCTAssertEqual(counter.noteCount, 0) XCTAssertGreaterThanOrEqual(released, 0) } + + func test_secureIdentityStateManager_postPanicStateSurvivesReinitAfterKeychainWipe() { + let keychain = PreviewKeychainManager() + let manager = SecureIdentityStateManager(keychain) + + // Pre-panic block + manager.setBlocked("aaaa1111aaaa1111aaaa1111aaaa1111aaaa1111aaaa1111aaaa1111aaaa1111", isBlocked: true) + + // Simulate panic wipe sequence from ChatViewModel.panicClearAllData(): + // keychain.deleteAllKeychainData() followed by identityManager.clearAllIdentityData(). + XCTAssertTrue(keychain.deleteAllKeychainData()) + manager.clearAllIdentityData() + + // Record post-panic block & verification on the same live manager instance. + let postPanicBlocked = "bbbb2222bbbb2222bbbb2222bbbb2222bbbb2222bbbb2222bbbb2222bbbb2222" + let postPanicVerified = "cccc3333cccc3333cccc3333cccc3333cccc3333cccc3333cccc3333cccc3333" + manager.setBlocked(postPanicBlocked, isBlocked: true) + manager.setVerified(fingerprint: postPanicVerified, verified: true) + + // Simulate next cold launch with a fresh manager reading the same keychain. + let relaunched = SecureIdentityStateManager(keychain) + XCTAssertTrue(relaunched.isBlocked(fingerprint: postPanicBlocked)) + XCTAssertTrue(relaunched.isVerified(fingerprint: postPanicVerified)) + XCTAssertFalse(relaunched.isBlocked(fingerprint: "aaaa1111aaaa1111aaaa1111aaaa1111aaaa1111aaaa1111aaaa1111aaaa1111")) + } + + func test_publicMessagePipeline_resetDropsBufferedMessages() { + final class RecordingDelegate: PublicMessagePipelineDelegate { + var committed: [BitchatMessage] = [] + func pipeline(_: PublicMessagePipeline, normalizeContent content: String) -> String { content } + func pipeline(_: PublicMessagePipeline, contentTimestampForKey _: String) -> Date? { nil } + func pipeline(_: PublicMessagePipeline, recordContentKey _: String, timestamp _: Date) {} + func pipeline(_: PublicMessagePipeline, commit message: BitchatMessage, to _: ConversationID) -> Bool { + committed.append(message) + return true + } + func pipelinePrewarmMessage(_: PublicMessagePipeline, message _: BitchatMessage) {} + } + + let pipeline = PublicMessagePipeline(baseFlushInterval: 60) + let delegate = RecordingDelegate() + pipeline.delegate = delegate + + let message = BitchatMessage( + id: "pre-panic-public", + sender: "alice", + content: "buffered before wipe", + timestamp: Date(), + isRelay: false + ) + pipeline.enqueue(message, to: .mesh) + XCTAssertTrue(pipeline.containsMessage(withID: "pre-panic-public")) + + pipeline.reset() + pipeline.flushIfNeeded() + + XCTAssertFalse(pipeline.containsMessage(withID: "pre-panic-public")) + XCTAssertTrue(delegate.committed.isEmpty) + } + + func test_nostrTransport_senderPeerIDProvider_tracksRotatedIdentityAfterPanic() { + var currentPeerID = PeerID(str: "0123456789abcdef") + let transport = NostrTransport( + keychain: PreviewKeychainManager(), + idBridge: NostrIdentityBridge(keychain: PreviewKeychainManager()) + ) + transport.senderPeerIDProvider = { currentPeerID } + XCTAssertEqual(transport.senderPeerID, PeerID(str: "0123456789abcdef")) + + currentPeerID = PeerID(str: "fedcba9876543210") + XCTAssertEqual(transport.senderPeerID, PeerID(str: "fedcba9876543210")) + } + + func test_cashuAndPeerColorCaches_resetForPanicWithoutCrash() { + _ = CashuTokenDecoder.decode("cashuAeyJ0b2tlbiI6W3sibWludCI6Imh0dHBzOi8vbWludC5leGFtcGxlLmNvbSIsInByb29mcyI6W3siYW1vdW50IjoxMH1dfV19") + CashuTokenDecoder.resetForPanic() + + let before = Color(peerSeed: "panic-peer-seed", isDark: true) + Color.clearPeerColorCache() + let after = Color(peerSeed: "panic-peer-seed", isDark: true) + XCTAssertEqual(before, after) + } + + func test_bleService_resetIdentityForPanic_preservesInstalledNoiseCallbacks() { + let mesh = SimulatedMesh() + let alice = mesh.addNode(nickname: "alice") + let bob = mesh.addNode(nickname: "bob") + mesh.connect(0, 1) + mesh.announceAll() + + let callbackLock = NSLock() + var installedAuthPeers: [PeerID] = [] + var observerAuthPeers: [PeerID] = [] + + bob.service.installNoiseSessionCallbacks( + onPeerAuthenticated: { peerID, _ in + callbackLock.lock() + installedAuthPeers.append(peerID) + callbackLock.unlock() + }, + onHandshakeRequired: { _ in } + ) + bob.service.addPeerAuthenticatedObserver { peerID, _ in + callbackLock.lock() + observerAuthPeers.append(peerID) + callbackLock.unlock() + } + + // Replace bob's NoiseEncryptionService via panic reset. + bob.service.suspendForPanicReset() + bob.service.resetIdentityForPanic(currentNickname: "anon1234", restartServices: false) + bob.service.completePanicReset(restartServices: false) + mesh.pump() + + // Re-announce so both nodes discover bob's fresh post-panic identity. + mesh.forceAnnounce(from: 1) + mesh.forceAnnounce(from: 0) + let newBobID = bob.service.myPeerID + mesh.settleUntil { alice.service.getConnectedPeers().contains(newBobID) } + + // Initiate a real Noise handshake from alice to bob's post-panic identity. + alice.service.sendPrivateMessage( + "hello after panic", + to: newBobID, + recipientNickname: "anon1234", + messageID: UUID().uuidString + ) + mesh.settleUntil { + callbackLock.lock() + defer { callbackLock.unlock() } + return installedAuthPeers.contains(alice.service.myPeerID) + && observerAuthPeers.contains(alice.service.myPeerID) + } + + callbackLock.lock() + let installedCount = installedAuthPeers.filter { $0 == alice.service.myPeerID }.count + let observerCount = observerAuthPeers.filter { $0 == alice.service.myPeerID }.count + callbackLock.unlock() + + XCTAssertGreaterThanOrEqual(installedCount, 1) + XCTAssertGreaterThanOrEqual(observerCount, 1) + } + + func test_chatOutgoingCoordinator_resetForPanic_cancelsInFlightGeohashSend() async throws { + @MainActor + final class PanicOutgoingContext: ChatOutgoingContext { + var nickname = "alice" + var myPeerID = PeerID(str: "0123456789abcdef") + var activeChannel: ChannelID = .location(GeohashChannel(level: .neighborhood, geohash: "u4pruy")) + var selectedPrivateChatPeer: PeerID? + var isTeleported = false + var appendedMessages: [BitchatMessage] = [] + var sentGeohashCount = 0 + private let identity: NostrIdentity + + init(identity: NostrIdentity) { + self.identity = identity + } + + func handleCommand(_: String) {} + func updatePrivateChatPeerIfNeeded() {} + func sendPrivateMessage(_: String, to _: PeerID) {} + func parseMentions(from _: String) -> [String] { [] } + @discardableResult + func appendPublicMessage(_ message: BitchatMessage, to _: ConversationID) -> Bool { + appendedMessages.append(message) + return true + } + func addSystemMessage(_: String) {} + func normalizedContentKey(_ content: String) -> String { content } + func recordContentKey(_: String, timestamp _: Date) {} + func recordPublicActivity(forChannelKey _: String) {} + func sendMeshMessage(_: String, mentions _: [String], messageID _: String, timestamp _: Date) {} + func sendGeohash(context _: ChatViewModel.GeoOutgoingContext) { sentGeohashCount += 1 } + func bridgeOutgoingPublicMessage(_: String, senderPeerID _: PeerID, timestamp _: Date) {} + func deriveNostrIdentity(forGeohash _: String) throws -> NostrIdentity { identity } + } + + let context = PanicOutgoingContext(identity: try NostrIdentity.generate()) + let coordinator = ChatOutgoingCoordinator(context: context) + + coordinator.sendMessage("pre-panic geo message") + let miningTask = coordinator.geohashMiningTask + coordinator.resetForPanic() + await miningTask?.value + + XCTAssertTrue(context.appendedMessages.isEmpty) + XCTAssertEqual(context.sentGeohashCount, 0) + } + + func test_nostrIdentityBridge_concurrentColdStartReturnsConsistentIdentity() async throws { + let keychain = PreviewKeychainManager() + let bridge = NostrIdentityBridge(keychain: keychain) + + let results: [String] = try await withThrowingTaskGroup(of: String.self) { group in + for _ in 0..<8 { + group.addTask { + guard let id = try bridge.getCurrentNostrIdentity() else { + throw NSError(domain: "Test", code: 1) + } + return id.publicKeyHex + } + } + var pubkeys: [String] = [] + for try await pubkey in group { + pubkeys.append(pubkey) + } + return pubkeys + } + + XCTAssertEqual(Set(results).count, 1) + } } diff --git a/localPackages/Arti/Sources/TorManager.swift b/localPackages/Arti/Sources/TorManager.swift index e0e9f8a0..73dbe2d4 100644 --- a/localPackages/Arti/Sources/TorManager.swift +++ b/localPackages/Arti/Sources/TorManager.swift @@ -95,6 +95,8 @@ public final class TorManager: ObservableObject { private var startedAt: Date? = nil // Tracks initial startup time for grace period private(set) var allowAutoStart: Bool = false + private let artiExecutor = ArtiLifecycleExecutor() + private struct ReadyWaiter { let continuation: CheckedContinuation let timeoutTask: Task @@ -150,7 +152,11 @@ public final class TorManager: ObservableObject { return await withTaskCancellationHandler { await withCheckedContinuation { continuation in - Task { @MainActor in + Task { @MainActor [weak self] in + guard let self else { + continuation.resume(returning: false) + return + } if cancellationFlag.isSet { continuation.resume(returning: false) return @@ -174,8 +180,8 @@ public final class TorManager: ObservableObject { } } onCancel: { _ = cancellationFlag.trySet() - Task { @MainActor in - self.cancelReadyWaiter(id: waiterID) + Task { @MainActor [weak self] in + self?.cancelReadyWaiter(id: waiterID) } } } @@ -213,14 +219,6 @@ public final class TorManager: ObservableObject { } } - nonisolated private static func ensureFilesystemLayout(at dir: URL) { - do { - try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true) - } catch { - // Non-fatal; Arti will surface errors during start if paths are missing - } - } - // MARK: - Arti Integration private func startArti(generation: Int) { @@ -231,28 +229,27 @@ public final class TorManager: ObservableObject { } let host = socksHost let port = socksPort + let executor = artiExecutor - // Run directory creation and Arti FFI startup off the main actor so - // launch/foreground recovery never stalls UI rendering. + // Run directory creation and Arti FFI startup off the main actor on + // the serialized lifecycle executor so launch/foreground recovery never + // stalls UI rendering and cannot race shutdown or panic wipe. Task.detached(priority: .userInitiated) { [weak self] in guard let self else { return } - Self.ensureFilesystemLayout(at: dirURL) - - let alreadyRunning = arti_is_running() != 0 - if alreadyRunning { - SecureLogger.info("TorManager: Arti already running", category: .session) - await MainActor.run { - guard generation == self.bootstrapGeneration else { return } - self.startBootstrapMonitor(generation: generation) + let outcome = await executor.start( + dirURL: dirURL, + socksPort: UInt16(port), + isStillCurrent: { + await MainActor.run { + self.bootstrapGeneration == generation + } } + ) + + switch outcome { + case .superseded: return - } - - let result = dirURL.path.withCString { dptr in - arti_start(dptr, UInt16(port)) - } - - if result != 0 { + case .failed(let result): SecureLogger.error("TorManager: arti_start failed rc=\(result)", category: .session) await MainActor.run { guard generation == self.bootstrapGeneration else { return } @@ -260,16 +257,23 @@ public final class TorManager: ObservableObject { self.lastError = NSError(domain: "TorManager", code: Int(result), userInfo: [NSLocalizedDescriptionKey: "Arti start failed"]) } return + case .alreadyRunning: + SecureLogger.info("TorManager: Arti already running", category: .session) + case .started: + SecureLogger.info("TorManager: arti_start OK (SOCKS \(host):\(port))", category: .session) } - SecureLogger.info("TorManager: arti_start OK (SOCKS \(host):\(port))", category: .session) - await MainActor.run { - guard generation == self.bootstrapGeneration else { return } + let stillCurrent: Bool = await MainActor.run { + guard generation == self.bootstrapGeneration else { return false } self.startBootstrapMonitor(generation: generation) + return true } + guard stillCurrent else { return } - // Probe SOCKS readiness off-main, fenced to this bootstrap generation - // so an in-flight probe cannot mark Tor ready after shutdown/restart. + // Probe SOCKS readiness off-main for BOTH newly started and + // already-running Arti instances (fenced to this bootstrap + // generation) so `socksReady` cannot remain stuck at `false` + // after dormancy or an overlapping restart. let ready = await self.waitForSocksReady(port: port, timeout: 60.0) await MainActor.run { guard generation == self.bootstrapGeneration else { return } @@ -476,16 +480,10 @@ public final class TorManager: ObservableObject { bootstrapSummary = "" isStarting = false shutdownsInFlight += 1 + let executor = artiExecutor Task.detached { [weak self] in guard let self = self else { return } - _ = arti_stop() - - // Wait for shutdown - var waited = 0 - while arti_is_running() != 0 && waited < 50 { - try? await Task.sleep(nanoseconds: 100_000_000) - waited += 1 - } + await executor.stop(maxPolls: 50) await MainActor.run { self.isReady = false @@ -513,11 +511,11 @@ public final class TorManager: ObservableObject { } /// Panic-wipe hook: removes `Application Support/bitchat/arti` (guard - /// nodes, state, consensus cache). If Arti is currently shutting down, - /// defers removal until `arti_stop()` finishes so SQLite/state files are - /// deleted cleanly before any post-panic restart. + /// nodes, state, consensus cache). If Arti is starting, running, or + /// shutting down, defers removal until serialized `arti_stop()` finishes so + /// SQLite/state files are deleted cleanly before any post-panic restart. public func wipeStateDirectoryForPanic() { - if shutdownsInFlight > 0 || arti_is_running() != 0 { + if shutdownsInFlight > 0 || isStarting || didStart || arti_is_running() != 0 { wipeDataDirectoryOnShutdown = true if shutdownsInFlight == 0 { shutdownCompletely() @@ -534,7 +532,7 @@ public final class TorManager: ObservableObject { nonisolated private func restartArti() async { SecureLogger.debug("TorManager: restartArti() starting", category: .session) - await MainActor.run { + let executor = await MainActor.run { () -> ArtiLifecycleExecutor in NotificationCenter.default.post(name: .TorWillRestart, object: nil) self.bootstrapGeneration += 1 self.isReady = false @@ -544,16 +542,10 @@ public final class TorManager: ObservableObject { self.isStarting = true self.bootstrapDidStall = false self.lastRestartAt = Date() + return self.artiExecutor } - _ = arti_stop() - - // Wait for stop off the main actor. - var waited = 0 - while arti_is_running() != 0 && waited < 40 { - try? await Task.sleep(nanoseconds: 100_000_000) - waited += 1 - } + await executor.stop(maxPolls: 40) await MainActor.run { self.bootstrapMonitorStarted = false @@ -615,6 +607,42 @@ public final class TorManager: ObservableObject { } } +private actor ArtiLifecycleExecutor { + enum StartOutcome: Sendable { + case started + case alreadyRunning + case superseded + case failed(Int32) + } + + func start( + dirURL: URL, + socksPort: UInt16, + isStillCurrent: @Sendable () async -> Bool + ) async -> StartOutcome { + guard await isStillCurrent() else { + return .superseded + } + if arti_is_running() != 0 { + return .alreadyRunning + } + try? FileManager.default.createDirectory(at: dirURL, withIntermediateDirectories: true) + let rc = dirURL.path.withCString { dptr in + arti_start(dptr, socksPort) + } + return rc == 0 ? .started : .failed(rc) + } + + func stop(maxPolls: Int) async { + _ = arti_stop() + var waited = 0 + while arti_is_running() != 0 && waited < maxPolls { + try? await Task.sleep(nanoseconds: 100_000_000) + waited += 1 + } + } +} + private final class AtomicOnceFlag: @unchecked Sendable { private let lock = NSLock() private var flag = false