diff --git a/bitchat/App/AppChromeModel.swift b/bitchat/App/AppChromeModel.swift index ea23d28e..9df535a3 100644 --- a/bitchat/App/AppChromeModel.swift +++ b/bitchat/App/AppChromeModel.swift @@ -163,63 +163,25 @@ final class AppChromeModel: ObservableObject { } .store(in: &cancellables) - chatViewModel.$nickname - .removeDuplicates() - .dropFirst() - .receive(on: DispatchQueue.main) - .sink { [weak self] nickname in - guard let self, self.nickname != nickname else { return } - self.nickname = nickname - } - .store(in: &cancellables) + mirror(chatViewModel.$nickname, to: \.nickname) + mirror(chatViewModel.$showBluetoothAlert, to: \.showBluetoothAlert) + mirror(chatViewModel.$bluetoothAlertMessage, to: \.bluetoothAlertMessage) + mirror(chatViewModel.$bluetoothState, to: \.bluetoothState) + mirror(chatViewModel.$torBlocked, to: \.torBlocked) + mirror(chatViewModel.$panicRecoveryBlocked, to: \.panicWipeBlocked) + } - chatViewModel.$showBluetoothAlert + private func mirror( + _ publisher: Published.Publisher, + to keyPath: ReferenceWritableKeyPath + ) { + publisher .removeDuplicates() .dropFirst() .receive(on: DispatchQueue.main) - .sink { [weak self] showAlert in - guard let self, self.showBluetoothAlert != showAlert else { return } - self.showBluetoothAlert = showAlert - } - .store(in: &cancellables) - - chatViewModel.$bluetoothAlertMessage - .removeDuplicates() - .dropFirst() - .receive(on: DispatchQueue.main) - .sink { [weak self] message in - guard let self, self.bluetoothAlertMessage != message else { return } - self.bluetoothAlertMessage = message - } - .store(in: &cancellables) - - chatViewModel.$bluetoothState - .removeDuplicates() - .dropFirst() - .receive(on: DispatchQueue.main) - .sink { [weak self] state in - guard let self, self.bluetoothState != state else { return } - self.bluetoothState = state - } - .store(in: &cancellables) - - chatViewModel.$torBlocked - .removeDuplicates() - .dropFirst() - .receive(on: DispatchQueue.main) - .sink { [weak self] blocked in - guard let self, self.torBlocked != blocked else { return } - self.torBlocked = blocked - } - .store(in: &cancellables) - - chatViewModel.$panicRecoveryBlocked - .removeDuplicates() - .dropFirst() - .receive(on: DispatchQueue.main) - .sink { [weak self] blocked in - guard let self, self.panicWipeBlocked != blocked else { return } - self.panicWipeBlocked = blocked + .sink { [weak self] value in + guard let self, self[keyPath: keyPath] != value else { return } + self[keyPath: keyPath] = value } .store(in: &cancellables) } diff --git a/bitchat/App/AppRuntime.swift b/bitchat/App/AppRuntime.swift index 5093d86c..2222b8ba 100644 --- a/bitchat/App/AppRuntime.swift +++ b/bitchat/App/AppRuntime.swift @@ -182,7 +182,7 @@ final class AppRuntime: ObservableObject { /// best-effort, nothing at launch depends on their results. private func performMediaMaintenance() { Task.detached(priority: .utility) { - let store = BLEIncomingFileStore() + let store = BLEIncomingFileStore.shared store.expireAgedMedia() store.migrateFileProtectionIfNeeded() } diff --git a/bitchat/App/ComposerDraftModel.swift b/bitchat/App/ComposerDraftModel.swift index 245e203f..945fd535 100644 --- a/bitchat/App/ComposerDraftModel.swift +++ b/bitchat/App/ComposerDraftModel.swift @@ -155,22 +155,19 @@ final class ComposerAutocompleteModel: ObservableObject { } private func bind() { - chatViewModel.$showAutocomplete - .removeDuplicates() - .dropFirst() - .receive(on: DispatchQueue.main) - .assign(to: &$showAutocomplete) + mirror(chatViewModel.$showAutocomplete, to: &$showAutocomplete) + mirror(chatViewModel.$autocompleteSuggestions, to: &$autocompleteSuggestions) + mirror(chatViewModel.$selectedAutocompleteIndex, to: &$selectedAutocompleteIndex) + } - chatViewModel.$autocompleteSuggestions + private func mirror( + _ publisher: Published.Publisher, + to target: inout Published.Publisher + ) { + publisher .removeDuplicates() .dropFirst() .receive(on: DispatchQueue.main) - .assign(to: &$autocompleteSuggestions) - - chatViewModel.$selectedAutocompleteIndex - .removeDuplicates() - .dropFirst() - .receive(on: DispatchQueue.main) - .assign(to: &$selectedAutocompleteIndex) + .assign(to: &target) } } diff --git a/bitchat/Features/voice/VoiceCaptureSession.swift b/bitchat/Features/voice/VoiceCaptureSession.swift index 75451552..7b7f4d6c 100644 --- a/bitchat/Features/voice/VoiceCaptureSession.swift +++ b/bitchat/Features/voice/VoiceCaptureSession.swift @@ -235,16 +235,8 @@ final class PTTLiveVoiceSession: VoiceCaptureSession { } private static func makeOutputURL(burstID: Data) throws -> URL { - let base = try FileManager.default.url( - for: .applicationSupportDirectory, - in: .userDomainMask, - appropriateFor: nil, - create: true + try VoiceRecorder.makeOutgoingVoiceNoteURL( + fileName: "voice_\(burstID.hexEncodedString()).m4a" ) - let directory = base - .appendingPathComponent("files", isDirectory: true) - .appendingPathComponent("voicenotes/outgoing", isDirectory: true) - try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true, attributes: BLEIncomingFileStore.mediaProtectionAttributes) - return directory.appendingPathComponent("voice_\(burstID.hexEncodedString()).m4a") } } diff --git a/bitchat/Features/voice/VoiceRecorder.swift b/bitchat/Features/voice/VoiceRecorder.swift index 3d64bcbd..acc883ee 100644 --- a/bitchat/Features/voice/VoiceRecorder.swift +++ b/bitchat/Features/voice/VoiceRecorder.swift @@ -291,20 +291,41 @@ actor VoiceRecorder { #endif } - private func makeOutputURL() throws -> URL { + private static let fileNameDateFormatter: DateFormatter = { let formatter = DateFormatter() formatter.dateFormat = "yyyyMMdd_HHmmss" - let fileName = "voice_\(formatter.string(from: Date()))_\(UUID().uuidString).m4a" + return formatter + }() - let baseDirectory = try outputDirectory - ?? applicationFilesDirectory().appendingPathComponent("voicenotes/outgoing", isDirectory: true) - try FileManager.default.createDirectory(at: baseDirectory, withIntermediateDirectories: true, attributes: BLEIncomingFileStore.mediaProtectionAttributes) + nonisolated static func makeOutgoingVoiceNoteURL( + fileName: String, + outputDirectory: URL? = nil + ) throws -> URL { + let baseDirectory: URL + if let outputDirectory { + baseDirectory = outputDirectory + } else { + let appSupport = try FileManager.default.url( + for: .applicationSupportDirectory, + in: .userDomainMask, + appropriateFor: nil, + create: true + ) + baseDirectory = appSupport + .appendingPathComponent("files", isDirectory: true) + .appendingPathComponent("voicenotes/outgoing", isDirectory: true) + } + try FileManager.default.createDirectory( + at: baseDirectory, + withIntermediateDirectories: true, + attributes: BLEIncomingFileStore.mediaProtectionAttributes + ) return baseDirectory.appendingPathComponent(fileName) } - private func applicationFilesDirectory() throws -> URL { - try FileManager.default.url(for: .applicationSupportDirectory, in: .userDomainMask, appropriateFor: nil, create: true) - .appendingPathComponent("files", isDirectory: true) + private func makeOutputURL() throws -> URL { + let fileName = "voice_\(Self.fileNameDateFormatter.string(from: Date()))_\(UUID().uuidString).m4a" + return try Self.makeOutgoingVoiceNoteURL(fileName: fileName, outputDirectory: outputDirectory) } /// Fire-and-forget: the coordinator hops the blocking deactivation IPC diff --git a/bitchat/Noise/NoiseSession.swift b/bitchat/Noise/NoiseSession.swift index fe5edd6c..effe069e 100644 --- a/bitchat/Noise/NoiseSession.swift +++ b/bitchat/Noise/NoiseSession.swift @@ -39,14 +39,19 @@ class NoiseSession { private var handshakeState: NoiseHandshakeState? private var sendCipher: NoiseCipherState? private var receiveCipher: NoiseCipherState? - + + // Lifecycle & security limits (confined to sessionQueue) + private var messageCount: UInt64 = 0 + private var sessionStartTime = Date() + private var lastActivityTime = Date() + // Keys private let localStaticKey: Curve25519.KeyAgreement.PrivateKey private var remoteStaticPublicKey: Curve25519.KeyAgreement.PublicKey? // Thread safety private let sessionQueue = DispatchQueue(label: "chat.bitchat.noise.session", attributes: .concurrent) - + init( peerID: PeerID, role: NoiseRole, @@ -60,15 +65,15 @@ class NoiseSession { self.localStaticKey = localStaticKey self.remoteStaticPublicKey = remoteStaticKey } - + // MARK: - Handshake - + func startHandshake() throws -> Data { return try sessionQueue.sync(flags: .barrier) { guard case .uninitialized = state else { throw NoiseSessionError.invalidState } - + // For XX pattern, we don't need remote static key upfront handshakeState = NoiseHandshakeState( role: role, @@ -77,9 +82,9 @@ class NoiseSession { localStaticKey: localStaticKey, remoteStaticKey: nil ) - + state = .handshaking - + // Only initiator writes the first message if role == .initiator { guard let handshake = handshakeState else { @@ -93,11 +98,11 @@ class NoiseSession { } } } - + func processHandshakeMessage(_ message: Data) throws -> Data? { return try sessionQueue.sync(flags: .barrier) { SecureLogger.debug("NoiseSession[\(peerID)]: Processing handshake message, current state: \(state), role: \(role)") - + // Initialize handshake state if needed (for responders) if state == .uninitialized && role == .responder { handshakeState = NoiseHandshakeState( @@ -110,15 +115,15 @@ class NoiseSession { state = .handshaking SecureLogger.debug("NoiseSession[\(peerID)]: Initialized handshake state for responder") } - + guard case .handshaking = state, let handshake = handshakeState else { throw NoiseSessionError.invalidState } - + // Process incoming message _ = try handshake.readMessage(message) SecureLogger.debug("NoiseSession[\(peerID)]: Read handshake message, checking if complete") - + // Check if handshake is complete if handshake.isHandshakeComplete() { try completeHandshake(handshake) @@ -127,12 +132,12 @@ class NoiseSession { // Generate response let response = try handshake.writeMessage() SecureLogger.debug("NoiseSession[\(peerID)]: Generated handshake response of size \(response.count)") - + // Check if handshake is complete after writing if handshake.isHandshakeComplete() { try completeHandshake(handshake) } - + return response } } @@ -148,37 +153,96 @@ class NoiseSession { SecureLogger.debug("NoiseSession[\(peerID)]: Handshake complete, transitioning to established") SecureLogger.info(.handshakeCompleted(peerID: peerID.id)) } - + // MARK: - Transport - + func encrypt(_ plaintext: Data) throws -> Data { return try sessionQueue.sync(flags: .barrier) { + let now = Date() + if now.timeIntervalSince(sessionStartTime) > NoiseSecurityConstants.sessionTimeout { + throw NoiseSecurityError.sessionExpired + } + if messageCount >= NoiseSecurityConstants.maxMessagesPerSession { + throw NoiseSecurityError.sessionExhausted + } + + // Ordinary Noise messages keep the protocol ceiling. Finalized media + // is the sole typed-payload extension and remains under the framed-file + // cap enforced again at the service and file-decoder layers. + let isPrivateFile = NoisePayloadType.isPrivateFile(rawValue: plaintext.first) + && NoiseSecurityValidator.validatePrivateFileMessageSize(plaintext) + guard NoiseSecurityValidator.validateMessageSize(plaintext) || isPrivateFile else { + throw NoiseSecurityError.messageTooLarge + } + guard case .established = state, let cipher = sendCipher else { throw NoiseSessionError.notEstablished } - - return try cipher.encrypt(plaintext: plaintext) + + let encrypted = try cipher.encrypt(plaintext: plaintext) + messageCount += 1 + lastActivityTime = now + return encrypted } } - + func decrypt(_ ciphertext: Data) throws -> Data { return try sessionQueue.sync(flags: .barrier) { + let now = Date() + if now.timeIntervalSince(sessionStartTime) > NoiseSecurityConstants.sessionTimeout { + throw NoiseSecurityError.sessionExpired + } + + // The payload type is encrypted, so a large candidate can only be + // bounded here; `NoiseEncryptionService.decrypt` authenticates it and + // then requires the resulting type to be `.privateFile`. + guard NoiseSecurityValidator.validateCiphertextSize(ciphertext) + || NoiseSecurityValidator.validatePrivateFileCiphertextSize(ciphertext) else { + throw NoiseSecurityError.messageTooLarge + } + guard case .established = state, let cipher = receiveCipher else { throw NoiseSessionError.notEstablished } - - return try cipher.decrypt(ciphertext: ciphertext) + + let decrypted = try cipher.decrypt(ciphertext: ciphertext) + lastActivityTime = now + return decrypted } } - + + func needsRenegotiation() -> Bool { + sessionQueue.sync { + let messageThreshold = UInt64(Double(NoiseSecurityConstants.maxMessagesPerSession) * 0.9) + if messageCount >= messageThreshold { + return true + } + + let now = Date() + if now.timeIntervalSince(lastActivityTime) > NoiseSecurityConstants.sessionTimeout { + return true + } + + // A session that never goes idle keeps refreshing lastActivityTime forever, + // so check sessionStartTime at 90% of sessionTimeout to give the periodic + // rekey check room to rotate keys before encrypt/decrypt start throwing + // sessionExpired. + if now.timeIntervalSince(sessionStartTime) > NoiseSecurityConstants.sessionTimeout * 0.9 { + return true + } + + return false + } + } + // MARK: - State Management - + func getState() -> NoiseSessionState { return sessionQueue.sync { return state } } - + func isEstablished() -> Bool { return sessionQueue.sync { if case .established = state { @@ -187,19 +251,23 @@ class NoiseSession { return false } } - + func getRemoteStaticPublicKey() -> Curve25519.KeyAgreement.PublicKey? { return sessionQueue.sync { return remoteStaticPublicKey } } - + func reset() { sessionQueue.sync(flags: .barrier) { let wasEstablished = state == .established state = .uninitialized handshakeState = nil - + messageCount = 0 + let now = Date() + sessionStartTime = now + lastActivityTime = now + // Clear sensitive cipher states sendCipher?.clearSensitiveData() receiveCipher?.clearSensitiveData() @@ -211,4 +279,25 @@ class NoiseSession { } } } + + // MARK: - Testing Support + #if DEBUG + func setLastActivityTimeForTesting(_ date: Date) { + sessionQueue.sync(flags: .barrier) { + lastActivityTime = date + } + } + + func setMessageCountForTesting(_ count: UInt64) { + sessionQueue.sync(flags: .barrier) { + messageCount = count + } + } + + func setSessionStartTimeForTesting(_ date: Date) { + sessionQueue.sync(flags: .barrier) { + sessionStartTime = date + } + } + #endif } diff --git a/bitchat/Noise/NoiseSessionManager.swift b/bitchat/Noise/NoiseSessionManager.swift index 80b3cc42..6ac8a7e5 100644 --- a/bitchat/Noise/NoiseSessionManager.swift +++ b/bitchat/Noise/NoiseSessionManager.swift @@ -46,21 +46,6 @@ enum NoiseSessionRestoreReason: Equatable, Sendable { } final class NoiseSessionManager { - private var sessions: [PeerID: NoiseSession] = [:] - /// Opaque identity for each exact entry in `sessions`. The generation is - /// created and removed under the same barrier as the session itself, so a - /// caller can never authenticate data with one session and lease another. - private var sessionGenerations: [PeerID: UUID] = [:] - /// One-time handoff tokens prevent a prepared XX message 1 from leaving - /// after an inbound collision has already changed this peer's role. - private var ordinaryInitiationIDs: [PeerID: UUID] = [:] - private var ordinaryInitiatorTimeouts: [PeerID: DispatchWorkItem] = [:] - private var ordinaryInitiatorRetryNotifications: [PeerID: Bool] = [:] - private var ordinaryResponderTimeouts: [PeerID: DispatchWorkItem] = [:] - private var ordinaryResponderDeadlines: [PeerID: DispatchTime] = [:] - private var ordinaryResponderRetryNotifications: [PeerID: Bool] = [:] - private var ordinaryRespondersCreatedByYield: Set = [] - private var recentOrdinaryInitiatorCompletions: [PeerID: Date] = [:] private struct QuarantinedTransport { let session: NoiseSession let generation: UUID @@ -68,17 +53,94 @@ final class NoiseSessionManager { /// never extend the original rollback window indefinitely. let rollbackDeadline: DispatchTime } - /// An unauthenticated inbound message 1 cannot keep old sending keys live, - /// but it also must not permanently destroy a victim session. The old - /// transport remains receive-only while the ordinary responder proves the - /// claimed static identity, then is discarded on success or restored on - /// bounded failure. - private var quarantinedTransports: [PeerID: QuarantinedTransport] = [:] - private var quarantineRollbackCooldownUntil: [PeerID: Date] = [:] - private var suppressedInitiationRecoveryTimeouts: [PeerID: DispatchWorkItem] = [:] - private var delayedHandshakeRecoveryWorkItems: [PeerID: DispatchWorkItem] = [:] - private var handshakeRecoveryCallbackIDs: [PeerID: UUID] = [:] - private var pendingHandshakeRecoveryIDs: [PeerID: UUID] = [:] + + /// All per-peer session, timer, quarantine, and handshake-recovery state + /// consolidated into one value so cleanup and teardown never leave + /// orphaned entries across parallel tables. + private struct PeerSessionSlot { + var session: NoiseSession? + /// Opaque identity for `session`, created and cleared under the same + /// manager barrier so callers never authenticate data with one session + /// and lease another. + var generation: UUID? + /// One-time handoff token preventing a prepared XX message 1 from + /// leaving after an inbound collision changed this peer's role. + var ordinaryInitiationID: UUID? + var ordinaryInitiatorTimeout: DispatchWorkItem? + var ordinaryInitiatorRetryNotification = false + var ordinaryResponderTimeout: DispatchWorkItem? + var ordinaryResponderDeadline: DispatchTime? + var ordinaryResponderRetryNotification = false + var ordinaryResponderCreatedByYield = false + var recentOrdinaryInitiatorCompletion: Date? + /// Receive-only rollback state while an unauthenticated inbound + /// message 1 proves the claimed static identity. + var quarantinedTransport: QuarantinedTransport? + var quarantineRollbackCooldownUntil: Date? + var suppressedInitiationRecoveryTimeout: DispatchWorkItem? + var delayedHandshakeRecoveryWorkItem: DispatchWorkItem? + var handshakeRecoveryCallbackID: UUID? + var pendingHandshakeRecoveryID: UUID? + + var isEmpty: Bool { + session == nil + && generation == nil + && ordinaryInitiationID == nil + && ordinaryInitiatorTimeout == nil + && !ordinaryInitiatorRetryNotification + && ordinaryResponderTimeout == nil + && ordinaryResponderDeadline == nil + && !ordinaryResponderRetryNotification + && !ordinaryResponderCreatedByYield + && recentOrdinaryInitiatorCompletion == nil + && quarantinedTransport == nil + && quarantineRollbackCooldownUntil == nil + && suppressedInitiationRecoveryTimeout == nil + && delayedHandshakeRecoveryWorkItem == nil + && handshakeRecoveryCallbackID == nil + && pendingHandshakeRecoveryID == nil + } + + mutating func cancelOrdinaryInitiatorTimeout() { + ordinaryInitiatorTimeout?.cancel() + ordinaryInitiatorTimeout = nil + ordinaryInitiatorRetryNotification = false + } + + mutating func cancelOrdinaryResponderTimeout(preserveDeadline: Bool = false) { + ordinaryResponderTimeout?.cancel() + ordinaryResponderTimeout = nil + if !preserveDeadline { + ordinaryResponderDeadline = nil + } + ordinaryResponderRetryNotification = false + ordinaryResponderCreatedByYield = false + } + + mutating func cancelSuppressedInitiationRecovery() { + suppressedInitiationRecoveryTimeout?.cancel() + suppressedInitiationRecoveryTimeout = nil + } + + mutating func cancelDelayedHandshakeRecovery() { + delayedHandshakeRecoveryWorkItem?.cancel() + delayedHandshakeRecoveryWorkItem = nil + handshakeRecoveryCallbackID = nil + pendingHandshakeRecoveryID = nil + } + + mutating func resetAll() { + session?.reset() + quarantinedTransport?.session.reset() + cancelOrdinaryInitiatorTimeout() + cancelOrdinaryResponderTimeout() + cancelSuppressedInitiationRecovery() + cancelDelayedHandshakeRecovery() + self = PeerSessionSlot() + } + } + + private var slots: [PeerID: PeerSessionSlot] = [:] private let sessionFactory: (PeerID, NoiseRole) -> NoiseSession private let localPeerID: PeerID private let ordinaryHandshakeTimeout: TimeInterval @@ -86,13 +148,13 @@ final class NoiseSessionManager { private let recentInitiatorCompletionGracePeriod: TimeInterval private let ordinaryReconnectRollbackCooldown: TimeInterval private let managerQueue = DispatchQueue(label: "chat.bitchat.noise.manager", attributes: .concurrent) - + // Callbacks var onSessionEstablished: ((PeerID, Curve25519.KeyAgreement.PublicKey, UUID) -> Void)? var onSessionRestored: ((PeerID, UUID, NoiseSessionRestoreReason) -> Void)? var onSessionFailed: ((PeerID, Error) -> Void)? var onHandshakeRecoveryRequired: ((NoiseHandshakeRecoveryRequest) -> Void)? - + init( localStaticKey: Curve25519.KeyAgreement.PrivateKey, keychain: KeychainManagerProtocol, @@ -113,7 +175,7 @@ final class NoiseSessionManager { self.ordinaryReconnectRollbackCooldown = ordinaryReconnectRollbackCooldown self.sessionFactory = { peerID, role in - SecureNoiseSession( + NoiseSession( peerID: peerID, role: role, keychain: keychain, @@ -146,12 +208,26 @@ final class NoiseSessionManager { self.sessionFactory = sessionFactory } #endif - + + // MARK: - Slot Helpers (must hold managerQueue barrier) + + @discardableResult + private func mutateSlot(for peerID: PeerID, _ body: (inout PeerSessionSlot) -> T) -> T { + var slot = slots[peerID] ?? PeerSessionSlot() + let result = body(&slot) + if slot.isEmpty { + slots.removeValue(forKey: peerID) + } else { + slots[peerID] = slot + } + return result + } + // MARK: - Session Management - + func getSession(for peerID: PeerID) -> NoiseSession? { return managerQueue.sync { - return sessions[peerID] + return slots[peerID]?.session } } @@ -159,7 +235,7 @@ final class NoiseSessionManager { /// needs message 3 before its receive keys can become authoritative. func isAwaitingResponderHandshakeCompletion(for peerID: PeerID) -> Bool { managerQueue.sync { - guard let session = sessions[peerID] else { return false } + guard let session = slots[peerID]?.session else { return false } return session.role == .responder && session.getState() == .handshaking } @@ -175,11 +251,11 @@ final class NoiseSessionManager { ) throws -> NoiseHandshakeRecoveryPreparation? { try managerQueue.sync(flags: .barrier) { let peerID = request.peerID - guard pendingHandshakeRecoveryIDs[peerID] == request.recoveryID else { + guard slots[peerID]?.pendingHandshakeRecoveryID == request.recoveryID else { return nil } - if let current = sessions[peerID], + if let current = slots[peerID]?.session, current.getState() == .handshaking { if current.role == .initiator { scheduleOrdinaryInitiatorTimeoutLocked( @@ -197,7 +273,7 @@ final class NoiseSessionManager { for: peerID, notifyOnTimeout: true, createdByYield: true, - rearmDeadline: quarantinedTransports[peerID] == nil + rearmDeadline: slots[peerID]?.quarantinedTransport == nil ) } return .transferred @@ -226,26 +302,22 @@ final class NoiseSessionManager { throw error } + let attemptID = UUID() // Start before retiring a working transport. If preparation fails, // the established session and its generation are untouched. - if let current = sessions.removeValue(forKey: peerID) { - current.reset() + mutateSlot(for: peerID) { slot in + slot.session?.reset() + slot.quarantinedTransport?.session.reset() + slot.quarantinedTransport = nil + slot.cancelOrdinaryInitiatorTimeout() + slot.cancelOrdinaryResponderTimeout() + slot.cancelSuppressedInitiationRecovery() + slot.recentOrdinaryInitiatorCompletion = nil + slot.quarantineRollbackCooldownUntil = nil + slot.session = next + slot.generation = UUID() + slot.ordinaryInitiationID = attemptID } - if let quarantined = quarantinedTransports.removeValue(forKey: peerID) { - quarantined.session.reset() - } - sessionGenerations.removeValue(forKey: peerID) - ordinaryInitiationIDs.removeValue(forKey: peerID) - cancelOrdinaryInitiatorTimeoutLocked(for: peerID) - cancelOrdinaryResponderTimeoutLocked(for: peerID) - cancelSuppressedInitiationRecoveryLocked(for: peerID) - recentOrdinaryInitiatorCompletions.removeValue(forKey: peerID) - quarantineRollbackCooldownUntil.removeValue(forKey: peerID) - - let attemptID = UUID() - sessions[peerID] = next - sessionGenerations[peerID] = UUID() - ordinaryInitiationIDs[peerID] = attemptID // This is the one retry owned by `request`; it may time out but // must not recursively mint another generation. scheduleOrdinaryInitiatorTimeoutLocked( @@ -268,7 +340,7 @@ final class NoiseSessionManager { consumeHandshakeRecoveryLocked(request) } } - + func removeSession(for peerID: PeerID) { managerQueue.sync(flags: .barrier) { removeSessionLocked(for: peerID) @@ -276,82 +348,43 @@ final class NoiseSessionManager { } private func removeSessionLocked(for peerID: PeerID) { - if let session = sessions.removeValue(forKey: peerID) { - session.reset() // Clear sensitive data before removing + if var slot = slots.removeValue(forKey: peerID) { + slot.resetAll() } - if let quarantined = quarantinedTransports.removeValue(forKey: peerID) { - quarantined.session.reset() - } - sessionGenerations.removeValue(forKey: peerID) - ordinaryInitiationIDs.removeValue(forKey: peerID) - cancelOrdinaryInitiatorTimeoutLocked(for: peerID) - cancelOrdinaryResponderTimeoutLocked(for: peerID) - recentOrdinaryInitiatorCompletions.removeValue(forKey: peerID) - quarantineRollbackCooldownUntil.removeValue(forKey: peerID) - cancelSuppressedInitiationRecoveryLocked(for: peerID) - cancelDelayedHandshakeRecoveryLocked(for: peerID) } func removeAllSessions() { managerQueue.sync(flags: .barrier) { - for (_, session) in sessions { - session.reset() + for var slot in slots.values { + slot.resetAll() } - for (_, quarantined) in quarantinedTransports { - quarantined.session.reset() - } - for (_, timeout) in ordinaryInitiatorTimeouts { - timeout.cancel() - } - for (_, timeout) in ordinaryResponderTimeouts { - timeout.cancel() - } - for (_, timeout) in suppressedInitiationRecoveryTimeouts { - timeout.cancel() - } - for (_, timeout) in delayedHandshakeRecoveryWorkItems { - timeout.cancel() - } - sessions.removeAll() - sessionGenerations.removeAll() - ordinaryInitiationIDs.removeAll() - ordinaryInitiatorTimeouts.removeAll() - ordinaryInitiatorRetryNotifications.removeAll() - ordinaryResponderTimeouts.removeAll() - ordinaryResponderDeadlines.removeAll() - ordinaryResponderRetryNotifications.removeAll() - ordinaryRespondersCreatedByYield.removeAll() - recentOrdinaryInitiatorCompletions.removeAll() - quarantinedTransports.removeAll() - quarantineRollbackCooldownUntil.removeAll() - suppressedInitiationRecoveryTimeouts.removeAll() - delayedHandshakeRecoveryWorkItems.removeAll() - handshakeRecoveryCallbackIDs.removeAll() - pendingHandshakeRecoveryIDs.removeAll() + slots.removeAll() } } - + // MARK: - Handshake Helpers - + func initiateHandshake(with peerID: PeerID) throws -> Data { return try managerQueue.sync(flags: .barrier) { // Check if we already have an established session - if let existingSession = sessions[peerID], existingSession.isEstablished() { + if let existingSession = slots[peerID]?.session, existingSession.isEstablished() { // Session already established, don't recreate throw NoiseSessionError.alreadyEstablished } - + // Remove any existing non-established session - if let existingSession = sessions[peerID], !existingSession.isEstablished() { + if let existingSession = slots[peerID]?.session, !existingSession.isEstablished() { removeSessionLocked(for: peerID) } - recentOrdinaryInitiatorCompletions.removeValue(forKey: peerID) - + // Create new initiator session let session = sessionFactory(peerID, .initiator) - sessions[peerID] = session - sessionGenerations[peerID] = UUID() - + mutateSlot(for: peerID) { slot in + slot.recentOrdinaryInitiatorCompletion = nil + slot.session = session + slot.generation = UUID() + } + do { let handshakeData = try session.startHandshake() scheduleOrdinaryInitiatorTimeoutLocked( @@ -359,14 +392,16 @@ final class NoiseSessionManager { for: peerID, notifyOnTimeout: false ) - cancelDelayedHandshakeRecoveryLocked(for: peerID) + mutateSlot(for: peerID) { $0.cancelDelayedHandshakeRecovery() } return handshakeData } catch { // Clean up failed session - _ = sessions.removeValue(forKey: peerID) - sessionGenerations.removeValue(forKey: peerID) - ordinaryInitiationIDs.removeValue(forKey: peerID) - cancelOrdinaryInitiatorTimeoutLocked(for: peerID) + mutateSlot(for: peerID) { slot in + slot.session = nil + slot.generation = nil + slot.ordinaryInitiationID = nil + slot.cancelOrdinaryInitiatorTimeout() + } session.reset() SecureLogger.error(.handshakeFailed(peerID: peerID.id, error: error.localizedDescription)) throw error @@ -384,8 +419,8 @@ final class NoiseSessionManager { authorize: () throws -> Void ) throws -> NoiseHandshakeInitiation? { try managerQueue.sync(flags: .barrier) { - guard sessions[peerID] == nil, - quarantinedTransports[peerID] == nil else { + guard slots[peerID]?.session == nil, + slots[peerID]?.quarantinedTransport == nil else { return nil } try authorize() @@ -394,17 +429,19 @@ final class NoiseSessionManager { do { let payload = try session.startHandshake() let attemptID = UUID() - sessions[peerID] = session - sessionGenerations[peerID] = UUID() - ordinaryInitiationIDs[peerID] = attemptID - recentOrdinaryInitiatorCompletions.removeValue(forKey: peerID) - quarantineRollbackCooldownUntil.removeValue(forKey: peerID) + mutateSlot(for: peerID) { slot in + slot.session = session + slot.generation = UUID() + slot.ordinaryInitiationID = attemptID + slot.recentOrdinaryInitiatorCompletion = nil + slot.quarantineRollbackCooldownUntil = nil + slot.cancelDelayedHandshakeRecovery() + } scheduleOrdinaryInitiatorTimeoutLocked( session, for: peerID, notifyOnTimeout: notifyOnTimeout ) - cancelDelayedHandshakeRecoveryLocked(for: peerID) return NoiseHandshakeInitiation( payload: payload, attemptID: attemptID @@ -432,7 +469,7 @@ final class NoiseSessionManager { authorize: () throws -> Void ) throws -> NoiseHandshakeInitiation { try managerQueue.sync(flags: .barrier) { - guard let established = sessions[peerID], + guard let established = slots[peerID]?.session, established.isEstablished() else { throw NoiseSessionError.notEstablished } @@ -453,24 +490,22 @@ final class NoiseSessionManager { throw error } + let attemptID = UUID() // Retire only after the replacement initiator has successfully // produced message 1. Do not use the broad removal helper here: // this transition owns the exact new session installed below. - _ = sessions.removeValue(forKey: peerID) - sessionGenerations.removeValue(forKey: peerID) - ordinaryInitiationIDs.removeValue(forKey: peerID) - cancelOrdinaryInitiatorTimeoutLocked(for: peerID) - cancelOrdinaryResponderTimeoutLocked(for: peerID) - cancelSuppressedInitiationRecoveryLocked(for: peerID) - cancelDelayedHandshakeRecoveryLocked(for: peerID) - recentOrdinaryInitiatorCompletions.removeValue(forKey: peerID) - quarantineRollbackCooldownUntil.removeValue(forKey: peerID) + mutateSlot(for: peerID) { slot in + slot.cancelOrdinaryInitiatorTimeout() + slot.cancelOrdinaryResponderTimeout() + slot.cancelSuppressedInitiationRecovery() + slot.cancelDelayedHandshakeRecovery() + slot.recentOrdinaryInitiatorCompletion = nil + slot.quarantineRollbackCooldownUntil = nil + slot.session = next + slot.generation = UUID() + slot.ordinaryInitiationID = attemptID + } established.reset() - - let attemptID = UUID() - sessions[peerID] = next - sessionGenerations[peerID] = UUID() - ordinaryInitiationIDs[peerID] = attemptID scheduleOrdinaryInitiatorTimeoutLocked( next, for: peerID, @@ -490,15 +525,15 @@ final class NoiseSessionManager { for peerID: PeerID ) -> Data? { managerQueue.sync(flags: .barrier) { - guard ordinaryInitiationIDs[peerID] == initiation.attemptID, - let session = sessions[peerID], + guard let slot = slots[peerID], + slot.ordinaryInitiationID == initiation.attemptID, + let session = slot.session, session.role == .initiator, session.getState() == .handshaking else { return nil } - ordinaryInitiationIDs.removeValue(forKey: peerID) - let notifyOnTimeout = - ordinaryInitiatorRetryNotifications[peerID] ?? false + let notifyOnTimeout = slot.ordinaryInitiatorRetryNotification + mutateSlot(for: peerID) { $0.ordinaryInitiationID = nil } // Preparation and on-wire exchange have independent bounds. Once // BLE owns these exact bytes, give the peer the full response // window without changing retry ownership. @@ -510,7 +545,7 @@ final class NoiseSessionManager { return initiation.payload } } - + func handleIncomingHandshake(from peerID: PeerID, message: Data) throws -> Data? { try handleIncomingHandshakeWithResult( from: peerID, @@ -542,7 +577,7 @@ final class NoiseSessionManager { var didYieldLocalInitiator = false var inheritedResponderShouldRetry = false var inheritedResponderWasCreatedByYield = false - let existingAtIngress = sessions[peerID] + let existingAtIngress = slots[peerID]?.session let isFreshInitiation = message.count == NoiseSecurityConstants.xxInitialMessageSize || existingAtIngress == nil @@ -553,21 +588,21 @@ final class NoiseSessionManager { ) if isFreshInitiation { - if let cooldownUntil = quarantineRollbackCooldownUntil[peerID] { + if let cooldownUntil = slots[peerID]?.quarantineRollbackCooldownUntil { if cooldownUntil > Date(), - sessions[peerID]?.isEstablished() == true { + slots[peerID]?.session?.isEstablished() == true { SecureLogger.debug( "Ignoring unauthenticated reconnect initiation during rollback cooldown for \(peerID)", category: .session ) return (nil, nil) } - quarantineRollbackCooldownUntil.removeValue(forKey: peerID) + mutateSlot(for: peerID) { $0.quarantineRollbackCooldownUntil = nil } } - if suppressedInitiationRecoveryTimeouts[peerID] != nil, + if slots[peerID]?.suppressedInitiationRecoveryTimeout != nil, localPeerID < peerID.toShort(), - sessions[peerID]?.isEstablished() == true { + slots[peerID]?.session?.isEstablished() == true { SecureLogger.debug( "Coalescing duplicate initiation while convergence recovery is pending for \(peerID)", category: .session @@ -575,14 +610,14 @@ final class NoiseSessionManager { return (nil, nil) } - if let completedAt = recentOrdinaryInitiatorCompletions[peerID] { + if let completedAt = slots[peerID]?.recentOrdinaryInitiatorCompletion { let stillInGrace = Date().timeIntervalSince(completedAt) < recentInitiatorCompletionGracePeriod if stillInGrace, localPeerID < peerID.toShort(), - let established = sessions[peerID], + let established = slots[peerID]?.session, established.isEstablished() { - recentOrdinaryInitiatorCompletions.removeValue(forKey: peerID) + mutateSlot(for: peerID) { $0.recentOrdinaryInitiatorCompletion = nil } scheduleSuppressedInitiationRecoveryLocked( established, completedAt: completedAt, @@ -594,10 +629,10 @@ final class NoiseSessionManager { ) return (nil, nil) } - recentOrdinaryInitiatorCompletions.removeValue(forKey: peerID) + mutateSlot(for: peerID) { $0.recentOrdinaryInitiatorCompletion = nil } } - if let ordinaryInitiator = sessions[peerID], + if let ordinaryInitiator = slots[peerID]?.session, ordinaryInitiator.role == .initiator, ordinaryInitiator.getState() == .handshaking { if localPeerID < peerID.toShort() { @@ -608,20 +643,22 @@ final class NoiseSessionManager { return (nil, nil) } yieldedInitiatorShouldRetry = - ordinaryInitiatorRetryNotifications[peerID] ?? false + slots[peerID]?.ordinaryInitiatorRetryNotification ?? false didYieldLocalInitiator = true - _ = sessions.removeValue(forKey: peerID) - sessionGenerations.removeValue(forKey: peerID) - ordinaryInitiationIDs.removeValue(forKey: peerID) - cancelOrdinaryInitiatorTimeoutLocked(for: peerID) - cancelOrdinaryResponderTimeoutLocked(for: peerID) + mutateSlot(for: peerID) { slot in + slot.session = nil + slot.generation = nil + slot.ordinaryInitiationID = nil + slot.cancelOrdinaryInitiatorTimeout() + slot.cancelOrdinaryResponderTimeout() + } ordinaryInitiator.reset() } } let session: NoiseSession - if let existing = sessions[peerID] { + if let existing = slots[peerID]?.session { if existing.isEstablished(), !isFreshInitiation { // An established ordinary XX transport has no remaining @@ -634,56 +671,54 @@ final class NoiseSessionManager { return (nil, nil) } if isFreshInitiation { + let replacement = sessionFactory(peerID, .responder) if existing.isEstablished(), - let generation = sessionGenerations[peerID] { + let generation = slots[peerID]?.generation { // Message 1 is unauthenticated. Remove the old // transport from every outbound/generation API now, // retaining it only as receive-only rollback state. - _ = sessions.removeValue(forKey: peerID) - sessionGenerations.removeValue(forKey: peerID) - ordinaryInitiationIDs.removeValue(forKey: peerID) - cancelOrdinaryInitiatorTimeoutLocked(for: peerID) - cancelOrdinaryResponderTimeoutLocked(for: peerID) - if let prior = quarantinedTransports.updateValue( - QuarantinedTransport( + let priorQuarantined = mutateSlot(for: peerID) { slot -> QuarantinedTransport? in + slot.ordinaryInitiationID = nil + slot.cancelOrdinaryInitiatorTimeout() + slot.cancelOrdinaryResponderTimeout() + let prior = slot.quarantinedTransport + slot.quarantinedTransport = QuarantinedTransport( session: existing, generation: generation, rollbackDeadline: .now() + ordinaryResponderHandshakeTimeout - ), - forKey: peerID - ) { - prior.session.reset() + ) + slot.session = replacement + slot.generation = UUID() + return prior } + priorQuarantined?.session.reset() } else { inheritedResponderShouldRetry = - ordinaryResponderRetryNotifications[peerID] ?? false + slots[peerID]?.ordinaryResponderRetryNotification ?? false inheritedResponderWasCreatedByYield = - ordinaryRespondersCreatedByYield.contains(peerID) - _ = sessions.removeValue(forKey: peerID) - sessionGenerations.removeValue(forKey: peerID) - ordinaryInitiationIDs.removeValue(forKey: peerID) - // Keep the first responder/quarantine deadline. A - // repeated message 1 may refresh message 2, but never - // refreshes the attacker's outbound-pause budget. - cancelOrdinaryResponderTimeoutLocked( - for: peerID, - preserveDeadline: true - ) + slots[peerID]?.ordinaryResponderCreatedByYield ?? false + mutateSlot(for: peerID) { slot in + slot.ordinaryInitiationID = nil + // Keep the first responder/quarantine deadline. A + // repeated message 1 may refresh message 2, but never + // refreshes the attacker's outbound-pause budget. + slot.cancelOrdinaryResponderTimeout(preserveDeadline: true) + slot.session = replacement + slot.generation = UUID() + } existing.reset() } - - let replacement = sessionFactory(peerID, .responder) - sessions[peerID] = replacement - sessionGenerations[peerID] = UUID() session = replacement } else { session = existing } } else { let newSession = sessionFactory(peerID, .responder) - sessions[peerID] = newSession - sessionGenerations[peerID] = UUID() + mutateSlot(for: peerID) { slot in + slot.session = newSession + slot.generation = UUID() + } session = newSession } @@ -703,7 +738,7 @@ final class NoiseSessionManager { } let response = try session.processHandshakeMessage(message) - + // Check the exact session that processed this message. A // preserved peer-level session can remain established while a // replacement candidate is still unauthenticated. @@ -717,68 +752,79 @@ final class NoiseSessionManager { throw NoiseSessionError.peerIdentityMismatch } - if let quarantined = quarantinedTransports.removeValue( - forKey: peerID - ) { - quarantined.session.reset() + let (quarantined, generation) = mutateSlot(for: peerID) { slot -> (QuarantinedTransport?, UUID?) in + let quarantined = slot.quarantinedTransport + slot.quarantinedTransport = nil + slot.ordinaryInitiationID = nil + slot.cancelOrdinaryInitiatorTimeout() + slot.cancelOrdinaryResponderTimeout() + slot.quarantineRollbackCooldownUntil = nil + slot.recentOrdinaryInitiatorCompletion = + session.role == .initiator ? Date() : nil + slot.cancelSuppressedInitiationRecovery() + slot.cancelDelayedHandshakeRecovery() + return (quarantined, slot.generation) } - ordinaryInitiationIDs.removeValue(forKey: peerID) - cancelOrdinaryInitiatorTimeoutLocked(for: peerID) - cancelOrdinaryResponderTimeoutLocked(for: peerID) - quarantineRollbackCooldownUntil.removeValue(forKey: peerID) - if session.role == .initiator { - recentOrdinaryInitiatorCompletions[peerID] = Date() - } else { - recentOrdinaryInitiatorCompletions.removeValue( - forKey: peerID - ) - } - cancelSuppressedInitiationRecoveryLocked(for: peerID) - cancelDelayedHandshakeRecoveryLocked(for: peerID) - guard let generation = sessionGenerations[peerID] else { + quarantined?.session.reset() + guard let generation else { throw NoiseEncryptionError.sessionNotEstablished } establishedSession = (remoteKey, generation) } - + return (response, establishedSession) } catch { - var shouldRequestRecovery = false - var shouldSuppressImmediateHandlerRestart = false - if session.role == .initiator { - shouldRequestRecovery = - ordinaryInitiatorRetryNotifications[peerID] ?? false - shouldSuppressImmediateHandlerRestart = true - } else { - shouldRequestRecovery = - ordinaryResponderRetryNotifications[peerID] ?? false - shouldSuppressImmediateHandlerRestart = - ordinaryRespondersCreatedByYield.contains(peerID) - } - - if let storedSession = sessions[peerID], - storedSession === session { - _ = sessions.removeValue(forKey: peerID) - sessionGenerations.removeValue(forKey: peerID) - } - ordinaryInitiationIDs.removeValue(forKey: peerID) - cancelOrdinaryInitiatorTimeoutLocked(for: peerID) - cancelOrdinaryResponderTimeoutLocked(for: peerID) - recentOrdinaryInitiatorCompletions.removeValue(forKey: peerID) - session.reset() - let isIdentityMismatch = (error as? NoiseSessionError) == .peerIdentityMismatch - let restoredGeneration: UUID? - if let quarantined = quarantinedTransports.removeValue(forKey: peerID) { - sessions[peerID] = quarantined.session - sessionGenerations[peerID] = quarantined.generation - restoredGeneration = quarantined.generation - markRollbackCooldownLocked(for: peerID) - } else { - restoredGeneration = nil + let ( + shouldRequestRecovery, + initialSuppressRestart, + restoredGeneration, + pendingRecoveryID + ) = mutateSlot(for: peerID) { slot -> (Bool, Bool, UUID?, UUID?) in + let shouldRetry: Bool + let suppressRestart: Bool + if session.role == .initiator { + shouldRetry = slot.ordinaryInitiatorRetryNotification + suppressRestart = true + } else { + shouldRetry = slot.ordinaryResponderRetryNotification + suppressRestart = slot.ordinaryResponderCreatedByYield + } + + if let storedSession = slot.session, + storedSession === session { + slot.session = nil + slot.generation = nil + } + slot.ordinaryInitiationID = nil + slot.cancelOrdinaryInitiatorTimeout() + slot.cancelOrdinaryResponderTimeout() + slot.recentOrdinaryInitiatorCompletion = nil + + let restoredGen: UUID? + if let quarantined = slot.quarantinedTransport { + slot.quarantinedTransport = nil + slot.session = quarantined.session + slot.generation = quarantined.generation + slot.quarantineRollbackCooldownUntil = + Date().addingTimeInterval(ordinaryReconnectRollbackCooldown) + restoredGen = quarantined.generation + } else { + restoredGen = nil + } + return ( + shouldRetry, + suppressRestart, + restoredGen, + slot.pendingHandshakeRecoveryID + ) } + session.reset() + + let shouldSuppressImmediateHandlerRestart = + initialSuppressRestart || pendingRecoveryID != nil // An identity mismatch is terminal: the counterpart failed to // prove the claimed static key, so it never finished keys that @@ -788,8 +834,7 @@ final class NoiseSessionManager { // may already have discarded the restored sending keys. let restoreReason: NoiseSessionRestoreReason = !isIdentityMismatch - && (shouldRequestRecovery - || pendingHandshakeRecoveryIDs[peerID] != nil) + && (shouldRequestRecovery || pendingRecoveryID != nil) ? .pendingConvergence : .terminal @@ -800,9 +845,6 @@ final class NoiseSessionManager { } self?.onSessionFailed?(peerID, error) } - if pendingHandshakeRecoveryIDs[peerID] != nil { - shouldSuppressImmediateHandlerRestart = true - } if shouldRequestRecovery, !isIdentityMismatch { requestHandshakeRecovery( for: peerID, @@ -810,7 +852,7 @@ final class NoiseSessionManager { .handshakeCollisionRecoveryDelay ) } else if isIdentityMismatch, - let recoveryID = pendingHandshakeRecoveryIDs[peerID] { + let recoveryID = pendingRecoveryID { redispatchHandshakeRecoveryLocked( NoiseHandshakeRecoveryRequest( peerID: peerID, @@ -820,7 +862,7 @@ final class NoiseSessionManager { .handshakeCollisionRecoveryDelay ) } - + SecureLogger.error(.handshakeFailed(peerID: peerID.id, error: error.localizedDescription)) if shouldSuppressImmediateHandlerRestart, !isIdentityMismatch { throw NoiseManagedHandshakeFailure(underlying: error) @@ -843,24 +885,24 @@ final class NoiseSessionManager { for peerID: PeerID, notifyOnTimeout: Bool ) { - cancelOrdinaryInitiatorTimeoutLocked(for: peerID) - ordinaryInitiatorRetryNotifications[peerID] = notifyOnTimeout let timeout = DispatchWorkItem(flags: .barrier) { [weak self, weak session] in guard let self, let session, - let current = self.sessions[peerID], + let current = self.slots[peerID]?.session, current === session, current.role == .initiator, current.getState() == .handshaking else { return } - _ = self.sessions.removeValue(forKey: peerID) - self.sessionGenerations.removeValue(forKey: peerID) - self.ordinaryInitiationIDs.removeValue(forKey: peerID) - self.ordinaryInitiatorTimeouts.removeValue(forKey: peerID) - self.ordinaryInitiatorRetryNotifications.removeValue(forKey: peerID) - self.recentOrdinaryInitiatorCompletions.removeValue(forKey: peerID) + self.mutateSlot(for: peerID) { slot in + slot.session = nil + slot.generation = nil + slot.ordinaryInitiationID = nil + slot.ordinaryInitiatorTimeout = nil + slot.ordinaryInitiatorRetryNotification = false + slot.recentOrdinaryInitiatorCompletion = nil + } session.reset() SecureLogger.debug( "Ordinary initiator handshake with \(peerID) timed out", @@ -871,18 +913,17 @@ final class NoiseSessionManager { self.requestHandshakeRecovery(for: peerID) } } - ordinaryInitiatorTimeouts[peerID] = timeout + mutateSlot(for: peerID) { slot in + slot.cancelOrdinaryInitiatorTimeout() + slot.ordinaryInitiatorRetryNotification = notifyOnTimeout + slot.ordinaryInitiatorTimeout = timeout + } managerQueue.asyncAfter( deadline: .now() + ordinaryHandshakeTimeout, execute: timeout ) } - private func cancelOrdinaryInitiatorTimeoutLocked(for peerID: PeerID) { - ordinaryInitiatorTimeouts.removeValue(forKey: peerID)?.cancel() - ordinaryInitiatorRetryNotifications.removeValue(forKey: peerID) - } - private func scheduleOrdinaryResponderTimeoutLocked( _ session: NoiseSession, for peerID: PeerID, @@ -890,57 +931,46 @@ final class NoiseSessionManager { createdByYield: Bool, rearmDeadline: Bool = false ) { - let previousDeadline = ordinaryResponderDeadlines[peerID] - cancelOrdinaryResponderTimeoutLocked( - for: peerID, - preserveDeadline: true - ) - ordinaryResponderRetryNotifications[peerID] = notifyOnTimeout - if createdByYield { - ordinaryRespondersCreatedByYield.insert(peerID) - } - let deadline: DispatchTime - if let rollbackDeadline = - quarantinedTransports[peerID]?.rollbackDeadline { + if let rollbackDeadline = slots[peerID]?.quarantinedTransport?.rollbackDeadline { deadline = rollbackDeadline - } else if !rearmDeadline, let previousDeadline { + } else if !rearmDeadline, let previousDeadline = slots[peerID]?.ordinaryResponderDeadline { deadline = previousDeadline } else { deadline = .now() + ordinaryResponderHandshakeTimeout } - ordinaryResponderDeadlines[peerID] = deadline let timeout = DispatchWorkItem(flags: .barrier) { [weak self, weak session] in guard let self, let session, - let current = self.sessions[peerID], + let current = self.slots[peerID]?.session, current === session, current.role == .responder, current.getState() == .handshaking else { return } - _ = self.sessions.removeValue(forKey: peerID) - self.sessionGenerations.removeValue(forKey: peerID) - self.ordinaryInitiationIDs.removeValue(forKey: peerID) - self.ordinaryResponderTimeouts.removeValue(forKey: peerID) - self.ordinaryResponderDeadlines.removeValue(forKey: peerID) - self.ordinaryResponderRetryNotifications.removeValue(forKey: peerID) - self.ordinaryRespondersCreatedByYield.remove(peerID) - self.recentOrdinaryInitiatorCompletions.removeValue(forKey: peerID) - session.reset() + let restored: QuarantinedTransport? = self.mutateSlot(for: peerID) { slot in + slot.session = nil + slot.generation = nil + slot.ordinaryInitiationID = nil + slot.ordinaryResponderTimeout = nil + slot.ordinaryResponderDeadline = nil + slot.ordinaryResponderRetryNotification = false + slot.ordinaryResponderCreatedByYield = false + slot.recentOrdinaryInitiatorCompletion = nil - let restored: QuarantinedTransport? - if let quarantined = - self.quarantinedTransports.removeValue(forKey: peerID) { - self.sessions[peerID] = quarantined.session - self.sessionGenerations[peerID] = quarantined.generation - self.markRollbackCooldownLocked(for: peerID) - restored = quarantined - } else { - restored = nil + if let quarantined = slot.quarantinedTransport { + slot.quarantinedTransport = nil + slot.session = quarantined.session + slot.generation = quarantined.generation + slot.quarantineRollbackCooldownUntil = + Date().addingTimeInterval(self.ordinaryReconnectRollbackCooldown) + return quarantined + } + return nil } + session.reset() SecureLogger.debug( restored == nil @@ -969,25 +999,14 @@ final class NoiseSessionManager { self.requestHandshakeRecovery(for: peerID) } } - ordinaryResponderTimeouts[peerID] = timeout - managerQueue.asyncAfter(deadline: deadline, execute: timeout) - } - - private func cancelOrdinaryResponderTimeoutLocked( - for peerID: PeerID, - preserveDeadline: Bool = false - ) { - ordinaryResponderTimeouts.removeValue(forKey: peerID)?.cancel() - if !preserveDeadline { - ordinaryResponderDeadlines.removeValue(forKey: peerID) + mutateSlot(for: peerID) { slot in + slot.cancelOrdinaryResponderTimeout(preserveDeadline: true) + slot.ordinaryResponderRetryNotification = notifyOnTimeout + slot.ordinaryResponderCreatedByYield = createdByYield + slot.ordinaryResponderDeadline = deadline + slot.ordinaryResponderTimeout = timeout } - ordinaryResponderRetryNotifications.removeValue(forKey: peerID) - ordinaryRespondersCreatedByYield.remove(peerID) - } - - private func markRollbackCooldownLocked(for peerID: PeerID) { - quarantineRollbackCooldownUntil[peerID] = - Date().addingTimeInterval(ordinaryReconnectRollbackCooldown) + managerQueue.asyncAfter(deadline: deadline, execute: timeout) } private func scheduleSuppressedInitiationRecoveryLocked( @@ -995,7 +1014,6 @@ final class NoiseSessionManager { completedAt: Date, for peerID: PeerID ) { - cancelSuppressedInitiationRecoveryLocked(for: peerID) let elapsed = max(0, Date().timeIntervalSince(completedAt)) let remainingGrace = max( 0, @@ -1004,29 +1022,25 @@ final class NoiseSessionManager { let timeout = DispatchWorkItem(flags: .barrier) { [weak self, weak establishedSession] in guard let self, let establishedSession, - let current = self.sessions[peerID], + let current = self.slots[peerID]?.session, current === establishedSession, current.isEstablished() else { return } - self.suppressedInitiationRecoveryTimeouts.removeValue( - forKey: peerID - ) + self.mutateSlot(for: peerID) { $0.suppressedInitiationRecoveryTimeout = nil } self.requestHandshakeRecovery(for: peerID) } - suppressedInitiationRecoveryTimeouts[peerID] = timeout + mutateSlot(for: peerID) { slot in + slot.cancelSuppressedInitiationRecovery() + slot.suppressedInitiationRecoveryTimeout = timeout + } managerQueue.asyncAfter( deadline: .now() + remainingGrace, execute: timeout ) } - private func cancelSuppressedInitiationRecoveryLocked(for peerID: PeerID) { - suppressedInitiationRecoveryTimeouts.removeValue(forKey: peerID)? - .cancel() - } - #if DEBUG /// Fires a pending suppressed-initiation recovery immediately instead of /// waiting out the completion-grace timer, so tests can inject a grace @@ -1034,12 +1048,14 @@ final class NoiseSessionManager { /// the recovery path deterministically. func _test_fireSuppressedInitiationRecovery(for peerID: PeerID) { managerQueue.sync(flags: .barrier) { - guard let pending = suppressedInitiationRecoveryTimeouts - .removeValue(forKey: peerID) else { - return + let pending = mutateSlot(for: peerID) { slot -> DispatchWorkItem? in + let work = slot.suppressedInitiationRecoveryTimeout + slot.suppressedInitiationRecoveryTimeout = nil + return work } + guard let pending else { return } pending.cancel() - guard let current = sessions[peerID], + guard let current = slots[peerID]?.session, current.isEstablished() else { return } @@ -1052,12 +1068,14 @@ final class NoiseSessionManager { for peerID: PeerID, after delay: TimeInterval = 0 ) { - cancelDelayedHandshakeRecoveryLocked(for: peerID) let request = NoiseHandshakeRecoveryRequest( peerID: peerID, recoveryID: UUID() ) - pendingHandshakeRecoveryIDs[peerID] = request.recoveryID + mutateSlot(for: peerID) { slot in + slot.cancelDelayedHandshakeRecovery() + slot.pendingHandshakeRecoveryID = request.recoveryID + } scheduleHandshakeRecoveryCallbackLocked(request, after: delay) } @@ -1065,7 +1083,7 @@ final class NoiseSessionManager { _ request: NoiseHandshakeRecoveryRequest, after delay: TimeInterval ) { - guard pendingHandshakeRecoveryIDs[request.peerID] + guard slots[request.peerID]?.pendingHandshakeRecoveryID == request.recoveryID else { return } @@ -1077,28 +1095,31 @@ final class NoiseSessionManager { after delay: TimeInterval ) { let peerID = request.peerID - guard pendingHandshakeRecoveryIDs[peerID] == request.recoveryID else { + guard slots[peerID]?.pendingHandshakeRecoveryID == request.recoveryID else { return } - delayedHandshakeRecoveryWorkItems.removeValue(forKey: peerID)?.cancel() let callbackID = UUID() - handshakeRecoveryCallbackIDs[peerID] = callbackID let callback = DispatchWorkItem(flags: .barrier) { [weak self] in guard let self, - self.pendingHandshakeRecoveryIDs[peerID] - == request.recoveryID, - self.handshakeRecoveryCallbackIDs[peerID] == callbackID else { + self.slots[peerID]?.pendingHandshakeRecoveryID == request.recoveryID, + self.slots[peerID]?.handshakeRecoveryCallbackID == callbackID else { return } - self.delayedHandshakeRecoveryWorkItems.removeValue(forKey: peerID) - self.handshakeRecoveryCallbackIDs.removeValue(forKey: peerID) + self.mutateSlot(for: peerID) { slot in + slot.delayedHandshakeRecoveryWorkItem = nil + slot.handshakeRecoveryCallbackID = nil + } let handler = self.onHandshakeRecoveryRequired DispatchQueue.global().async { handler?(request) } } - delayedHandshakeRecoveryWorkItems[peerID] = callback + mutateSlot(for: peerID) { slot in + slot.delayedHandshakeRecoveryWorkItem?.cancel() + slot.handshakeRecoveryCallbackID = callbackID + slot.delayedHandshakeRecoveryWorkItem = callback + } managerQueue.asyncAfter( deadline: .now() + max(0, delay), execute: callback @@ -1109,18 +1130,10 @@ final class NoiseSessionManager { _ request: NoiseHandshakeRecoveryRequest ) { let peerID = request.peerID - guard pendingHandshakeRecoveryIDs[peerID] == request.recoveryID else { + guard slots[peerID]?.pendingHandshakeRecoveryID == request.recoveryID else { return } - delayedHandshakeRecoveryWorkItems.removeValue(forKey: peerID)?.cancel() - handshakeRecoveryCallbackIDs.removeValue(forKey: peerID) - pendingHandshakeRecoveryIDs.removeValue(forKey: peerID) - } - - private func cancelDelayedHandshakeRecoveryLocked(for peerID: PeerID) { - delayedHandshakeRecoveryWorkItems.removeValue(forKey: peerID)?.cancel() - handshakeRecoveryCallbackIDs.removeValue(forKey: peerID) - pendingHandshakeRecoveryIDs.removeValue(forKey: peerID) + mutateSlot(for: peerID) { $0.cancelDelayedHandshakeRecovery() } } /// Mesh handshakes normally use a 16-hex wire ID. Full Noise-key IDs are @@ -1140,12 +1153,12 @@ final class NoiseSessionManager { } return false } - + // MARK: - Encryption/Decryption - + func encrypt(_ plaintext: Data, for peerID: PeerID) throws -> Data { try managerQueue.sync { - guard let session = sessions[peerID] else { + guard let session = slots[peerID]?.session else { throw NoiseSessionError.sessionNotFound } return try session.encrypt(plaintext) @@ -1161,23 +1174,25 @@ final class NoiseSessionManager { expectedSessionGeneration expected: UUID ) throws -> Data { try managerQueue.sync { - guard let session = sessions[peerID], + guard let slot = slots[peerID], + let session = slot.session, session.isEstablished(), - sessionGenerations[peerID] == expected else { + slot.generation == expected else { throw NoiseEncryptionError.sessionNotEstablished } return try session.encrypt(plaintext) } } - + func decrypt(_ ciphertext: Data, from peerID: PeerID) throws -> Data { try decryptWithSessionGeneration(ciphertext, from: peerID).plaintext } func sessionGeneration(for peerID: PeerID) -> UUID? { managerQueue.sync { - guard sessions[peerID]?.isEstablished() == true else { return nil } - return sessionGenerations[peerID] + guard let slot = slots[peerID], + slot.session?.isEstablished() == true else { return nil } + return slot.generation } } @@ -1191,9 +1206,10 @@ final class NoiseSessionManager { authorizeDecrypt: () throws -> Void = {} ) throws -> (plaintext: Data, sessionGeneration: UUID) { try managerQueue.sync { - if let session = sessions[peerID], + let slot = slots[peerID] + if let session = slot?.session, session.isEstablished(), - let generation = sessionGenerations[peerID] { + let generation = slot?.generation { // Keep the generation lease across the transport-readiness // check and decrypt. Promotion/restoration needs this queue's // barrier, so no new receive nonce can be consumed before BLE @@ -1209,10 +1225,10 @@ final class NoiseSessionManager { // an established generation, or authorize outbound state, but // legitimate in-flight ciphertext from the retained peer may // still advance and later resume on rollback. - if let responder = sessions[peerID], + if let responder = slot?.session, responder.role == .responder, responder.getState() == .handshaking, - let quarantined = quarantinedTransports[peerID] { + let quarantined = slot?.quarantinedTransport { try authorizeDecrypt() return ( try quarantined.session.decrypt(ciphertext), @@ -1220,7 +1236,7 @@ final class NoiseSessionManager { ) } - if sessions[peerID] == nil, quarantinedTransports[peerID] == nil { + if slot?.session == nil, slot?.quarantinedTransport == nil { throw NoiseSessionError.sessionNotFound } throw NoiseEncryptionError.sessionNotEstablished @@ -1229,15 +1245,16 @@ final class NoiseSessionManager { func hasReceiveSession(for peerID: PeerID) -> Bool { managerQueue.sync { - if sessions[peerID]?.isEstablished() == true { + guard let slot = slots[peerID] else { return false } + if slot.session?.isEstablished() == true { return true } - guard let responder = sessions[peerID], + guard let responder = slot.session, responder.role == .responder, responder.getState() == .handshaking else { return false } - return quarantinedTransports[peerID]?.session.isEstablished() == true + return slot.quarantinedTransport?.session.isEstablished() == true } } @@ -1249,36 +1266,37 @@ final class NoiseSessionManager { _ body: () -> Result ) -> Result? { managerQueue.sync { - guard sessions[peerID]?.isEstablished() == true, - sessionGenerations[peerID] == expected else { return nil } + guard let slot = slots[peerID], + slot.session?.isEstablished() == true, + slot.generation == expected else { return nil } return body() } } - + // MARK: - Key Management - + func getRemoteStaticKey(for peerID: PeerID) -> Curve25519.KeyAgreement.PublicKey? { return getSession(for: peerID)?.getRemoteStaticPublicKey() } - + // MARK: - Session Rekeying - + func getSessionsNeedingRekey() -> [(peerID: PeerID, needsRekey: Bool)] { return managerQueue.sync { var needingRekey: [(peerID: PeerID, needsRekey: Bool)] = [] - - for (peerID, session) in sessions { - if let secureSession = session as? SecureNoiseSession, - secureSession.isEstablished(), - secureSession.needsRenegotiation() { + + for (peerID, slot) in slots { + if let session = slot.session, + session.isEstablished(), + session.needsRenegotiation() { needingRekey.append((peerID: peerID, needsRekey: true)) } } - + return needingRekey } } - + func initiateRekey(for peerID: PeerID) throws -> NoiseHandshakeInitiation { try initiateReconnectHandshake( with: peerID, diff --git a/bitchat/Noise/SecureNoiseSession.swift b/bitchat/Noise/SecureNoiseSession.swift deleted file mode 100644 index a6f53f11..00000000 --- a/bitchat/Noise/SecureNoiseSession.swift +++ /dev/null @@ -1,133 +0,0 @@ -// -// SecureNoiseSession.swift -// bitchat -// -// This is free and unencumbered software released into the public domain. -// For more information, see -// - -import Foundation - -final class SecureNoiseSession: NoiseSession { - private let stateLock = NSLock() - private var _messageCount: UInt64 = 0 - private var _sessionStartTime = Date() - private var _lastActivityTime = Date() - - override func encrypt(_ plaintext: Data) throws -> Data { - let now = Date() - stateLock.lock() - let startTime = _sessionStartTime - let count = _messageCount - stateLock.unlock() - - // Check session age - if now.timeIntervalSince(startTime) > NoiseSecurityConstants.sessionTimeout { - throw NoiseSecurityError.sessionExpired - } - - // Check message count - if count >= NoiseSecurityConstants.maxMessagesPerSession { - throw NoiseSecurityError.sessionExhausted - } - - // Ordinary Noise messages keep the protocol ceiling. Finalized media - // is the sole typed-payload extension and remains under the framed-file - // cap enforced again at the service and file-decoder layers. - let isPrivateFile = NoisePayloadType.isPrivateFile(rawValue: plaintext.first) - && NoiseSecurityValidator.validatePrivateFileMessageSize(plaintext) - guard NoiseSecurityValidator.validateMessageSize(plaintext) || isPrivateFile else { - throw NoiseSecurityError.messageTooLarge - } - - let encrypted = try super.encrypt(plaintext) - stateLock.lock() - _messageCount += 1 - _lastActivityTime = Date() - stateLock.unlock() - - return encrypted - } - - override func decrypt(_ ciphertext: Data) throws -> Data { - let now = Date() - stateLock.lock() - let startTime = _sessionStartTime - stateLock.unlock() - - // Check session age - if now.timeIntervalSince(startTime) > NoiseSecurityConstants.sessionTimeout { - throw NoiseSecurityError.sessionExpired - } - - // The payload type is encrypted, so a large candidate can only be - // bounded here; `NoiseEncryptionService.decrypt` authenticates it and - // then requires the resulting type to be `.privateFile`. - guard NoiseSecurityValidator.validateCiphertextSize(ciphertext) - || NoiseSecurityValidator.validatePrivateFileCiphertextSize(ciphertext) else { - throw NoiseSecurityError.messageTooLarge - } - - let decrypted = try super.decrypt(ciphertext) - stateLock.lock() - _lastActivityTime = Date() - stateLock.unlock() - - return decrypted - } - - func needsRenegotiation() -> Bool { - let now = Date() - stateLock.lock() - let count = _messageCount - let lastActivity = _lastActivityTime - let startTime = _sessionStartTime - stateLock.unlock() - - // Check if we've used more than 90% of message limit - let messageThreshold = UInt64(Double(NoiseSecurityConstants.maxMessagesPerSession) * 0.9) - if count >= messageThreshold { - return true - } - - // Check if last activity exceeded sessionTimeout - if now.timeIntervalSince(lastActivity) > NoiseSecurityConstants.sessionTimeout { - return true - } - - // A session that never goes idle (a long-lived conversation with - // steady traffic) keeps refreshing lastActivityTime forever, so the - // check above never fires -- only sessionStartTime tracks how close - // encrypt/decrypt are to the hard sessionExpired cutoff above. Firing - // at 90% of sessionTimeout leaves the rekey timer's polling interval - // (checked every 60s, see NoiseEncryptionService.rekeyCheckInterval) - // room to complete a full handshake well before the old session - // starts throwing sessionExpired on every call. - if now.timeIntervalSince(startTime) > NoiseSecurityConstants.sessionTimeout * 0.9 { - return true - } - - return false - } - - // MARK: - Testing Support - #if DEBUG - func setLastActivityTimeForTesting(_ date: Date) { - stateLock.lock() - _lastActivityTime = date - stateLock.unlock() - } - - func setMessageCountForTesting(_ count: UInt64) { - stateLock.lock() - _messageCount = count - stateLock.unlock() - } - - func setSessionStartTimeForTesting(_ date: Date) { - stateLock.lock() - _sessionStartTime = date - stateLock.unlock() - } - #endif -} diff --git a/bitchat/Nostr/NostrRelayConnection.swift b/bitchat/Nostr/NostrRelayConnection.swift new file mode 100644 index 00000000..a1f2870e --- /dev/null +++ b/bitchat/Nostr/NostrRelayConnection.swift @@ -0,0 +1,125 @@ +import Combine +import Foundation +import Tor + +protocol NostrRelayConnectionProtocol: AnyObject { + func resume() + func cancel(with closeCode: URLSessionWebSocketTask.CloseCode, reason: Data?) + func send(_ message: URLSessionWebSocketTask.Message, completionHandler: @escaping (Error?) -> Void) + func receive(completionHandler: @escaping (Result) -> Void) + func sendPing(pongReceiveHandler: @escaping (Error?) -> Void) +} + +protocol NostrRelaySessionProtocol { + func webSocketTask(with url: URL) -> NostrRelayConnectionProtocol +} + +private final class URLSessionWebSocketTaskAdapter: NostrRelayConnectionProtocol { + private let base: URLSessionWebSocketTask + + init(base: URLSessionWebSocketTask) { + self.base = base + } + + func resume() { + base.resume() + } + + func cancel(with closeCode: URLSessionWebSocketTask.CloseCode, reason: Data?) { + base.cancel(with: closeCode, reason: reason) + } + + func send(_ message: URLSessionWebSocketTask.Message, completionHandler: @escaping (Error?) -> Void) { + base.send(message, completionHandler: completionHandler) + } + + func receive(completionHandler: @escaping (Result) -> Void) { + base.receive(completionHandler: completionHandler) + } + + func sendPing(pongReceiveHandler: @escaping (Error?) -> Void) { + base.sendPing(pongReceiveHandler: pongReceiveHandler) + } +} + +private struct URLSessionAdapter: NostrRelaySessionProtocol { + let base: URLSession + + func webSocketTask(with url: URL) -> NostrRelayConnectionProtocol { + let task = base.webSocketTask(with: url) + // Byte bound per inbound frame; without it the per-relay buffer cap + // (nostrInboundPerRelayBufferCap) bounds FRAMES but not BYTES, and a + // hostile relay could pile up cap × 1 MiB (URLSession default) per + // connection. See TransportConfig.nostrInboundMaxFrameBytes for the + // sizing rationale. Oversized frames fail the receive with an error. + task.maximumMessageSize = TransportConfig.nostrInboundMaxFrameBytes + return URLSessionWebSocketTaskAdapter(base: task) + } +} + +struct NostrRelayManagerDependencies { + var activationAllowed: () -> Bool + var userTorEnabled: () -> Bool + var hasMutualFavorites: () -> Bool + var hasLocationPermission: () -> Bool + var mutualFavoritesPublisher: AnyPublisher, Never> + var locationPermissionPublisher: AnyPublisher + var torEnforced: () -> Bool + var torIsReady: () -> Bool + var torIsForeground: () -> Bool + var awaitTorReady: (@escaping (Bool) -> Void) -> Void + var makeSession: () -> NostrRelaySessionProtocol + var scheduleAfter: @Sendable (TimeInterval, @escaping @Sendable () -> Void) -> Void + var now: () -> Date + /// Uniform random value in [0, 1) used to jitter reconnect backoff. + /// Injectable so tests can pin or sweep the jitter deterministically. + var jitterUnit: () -> Double + /// Where relay-settings changes are observed. Injectable so a test can use + /// its own center instead of racing the process-wide one. + var notificationCenter: NotificationCenter = .default + /// Relays added by hand, merged with the built-in set. Injectable so tests + /// do not have to write to shared preferences. + var customRelays: () -> [String] = { NostrRelaySettings.customRelays() } + /// Whether a location channel is currently open. Mirrors the third arm of + /// `NetworkActivationService`'s gate: teleporting into a geohash needs no + /// location permission, and without this the relays would stay filtered out + /// for someone who denied location and has no mutual favorites. + var isInLocationChannel: () -> Bool = { false } + var selectedChannelPublisher: AnyPublisher = Empty().eraseToAnyPublisher() +} + +extension NostrRelayManagerDependencies { + @MainActor + static func live() -> Self { + Self( + activationAllowed: { NetworkActivationService.shared.activationAllowed }, + userTorEnabled: { NetworkActivationService.shared.userTorEnabled }, + hasMutualFavorites: { !FavoritesPersistenceService.shared.mutualFavorites.isEmpty }, + hasLocationPermission: { LocationChannelManager.shared.permissionState == .authorized }, + mutualFavoritesPublisher: FavoritesPersistenceService.shared.$mutualFavorites.eraseToAnyPublisher(), + locationPermissionPublisher: LocationChannelManager.shared.$permissionState.eraseToAnyPublisher(), + torEnforced: { TorManager.shared.torEnforced }, + torIsReady: { TorManager.shared.isReady }, + torIsForeground: { TorManager.shared.isForeground() }, + awaitTorReady: { completion in + Task.detached { + let ready = await TorManager.shared.awaitReady() + await MainActor.run { + completion(ready) + } + } + }, + makeSession: { URLSessionAdapter(base: TorURLSession.shared.session) }, + scheduleAfter: { delay, action in + DispatchQueue.main.asyncAfter(deadline: .now() + delay, execute: action) + }, + now: Date.init, + jitterUnit: { Double.random(in: 0..<1) }, + isInLocationChannel: { + if case .location = LocationChannelManager.shared.selectedChannel { return true } + return false + }, + selectedChannelPublisher: LocationChannelManager.shared.$selectedChannel.eraseToAnyPublisher() + ) + } +} diff --git a/bitchat/Nostr/NostrRelayInboundRouter.swift b/bitchat/Nostr/NostrRelayInboundRouter.swift new file mode 100644 index 00000000..7511cedb --- /dev/null +++ b/bitchat/Nostr/NostrRelayInboundRouter.swift @@ -0,0 +1,228 @@ +import Foundation + +/// A single raw socket frame awaiting off-main parse + Schnorr verification. +struct InboundFrame: Sendable { + let message: URLSessionWebSocketTask.Message +} + +/// Lock-guarded registry of per-relay inbound streams. +/// +/// The raw WebSocket receive callback is not main-actor isolated, so it needs a +/// `Sendable` path to route a frame to the correct relay's stream without a +/// per-frame hop onto the main actor. Pipeline lifecycle (start/finish) is +/// driven from the main actor; frame delivery (`yield`) can come from any +/// thread. All access is serialized by a single lock — contention is negligible +/// because the guarded critical section is only a dictionary lookup + yield. +final class InboundFrameRouter: @unchecked Sendable { + /// Full cryptographic identity of a Nostr event being verified. + /// Including every field covered by the NIP-01 event ID + signature ensures + /// a forged/tampered copy can never coalesce onto — or poison — a genuine copy. + private struct VerificationFingerprint: Hashable { + let id: String + let pubkey: String + let createdAt: Int + let kind: Int + let tags: [[String]] + let content: String + let sig: String? + + init(event: NostrEvent) { + self.id = event.id + self.pubkey = event.pubkey + self.createdAt = event.created_at + self.kind = event.kind + self.tags = event.tags + self.content = event.content + self.sig = event.sig + } + + static func == (lhs: VerificationFingerprint, rhs: VerificationFingerprint) -> Bool { + lhs.id == rhs.id && + lhs.pubkey == rhs.pubkey && + lhs.createdAt == rhs.createdAt && + lhs.kind == rhs.kind && + lhs.sig == rhs.sig && + lhs.content == rhs.content && + lhs.tags == rhs.tags + } + + func hash(into hasher: inout Hasher) { + hasher.combine(id) + hasher.combine(pubkey) + hasher.combine(createdAt) + hasher.combine(kind) + hasher.combine(sig) + hasher.combine(content) + hasher.combine(tags) + } + } + + private let lock = NSLock() + private var continuations: [String: AsyncStream.Continuation] = [:] + private var tasks: [String: Task] = [:] + private var activeConnections: [String: ObjectIdentifier] = [:] + private var inFlightVerifications: [VerificationFingerprint: [CheckedContinuation]] = [:] + + /// Start a relay's stream + consumer if one does not already exist. + /// Returns true when a new pipeline was created. The bounded + /// `.bufferingNewest` policy makes a single relay shed its OWN oldest + /// frames under a flood, never other relays' frames. Buffered memory per + /// relay is bounded (not eliminated) at the frame cap times the per-frame + /// byte cap (`maximumMessageSize`) — see TransportConfig. + func startPipeline( + for relayUrl: String, + connectionID: ObjectIdentifier, + makeConsumer: (AsyncStream) -> Task + ) -> Bool { + lock.lock() + defer { lock.unlock() } + activeConnections[relayUrl] = connectionID + if continuations[relayUrl] != nil { return false } + let (stream, continuation) = AsyncStream.makeStream( + bufferingPolicy: .bufferingNewest(TransportConfig.nostrInboundPerRelayBufferCap) + ) + continuations[relayUrl] = continuation + tasks[relayUrl] = makeConsumer(stream) + return true + } + + /// Route a frame to a relay's stream if `connectionID` is still the active + /// socket for `relayUrl`. Returns whether the caller should re-arm receive. + @discardableResult + func yield(_ frame: InboundFrame, to relayUrl: String, from connectionID: ObjectIdentifier) -> Bool { + lock.lock() + guard activeConnections[relayUrl] == connectionID, + let continuation = continuations[relayUrl] else { + lock.unlock() + return false + } + lock.unlock() + continuation.yield(frame) + return true + } + + /// Verifies `event.isValidSignature()` while coalescing simultaneous fan-in + /// deliveries of byte-identical events across multiple relay pipelines. + func verifySignatureCoalesced(_ event: NostrEvent) async -> Bool { + let fingerprint = VerificationFingerprint(event: event) + let isOwner: Bool = { + lock.lock() + defer { lock.unlock() } + if inFlightVerifications[fingerprint] != nil { + return false + } + inFlightVerifications[fingerprint] = [] + return true + }() + + if isOwner { + let valid = event.isValidSignature() + let waiters: [CheckedContinuation] = { + lock.lock() + defer { lock.unlock() } + return inFlightVerifications.removeValue(forKey: fingerprint) ?? [] + }() + for waiter in waiters { + waiter.resume(returning: valid) + } + return valid + } + + return await withCheckedContinuation { continuation in + lock.lock() + if var waiters = inFlightVerifications[fingerprint] { + waiters.append(continuation) + inFlightVerifications[fingerprint] = waiters + lock.unlock() + } else { + lock.unlock() + continuation.resume(returning: event.isValidSignature()) + } + } + } + + /// Finish a relay's stream. The consumer drains any already-buffered frames + /// before exiting, so in-flight verified events are still delivered. + func finishPipeline(for relayUrl: String) { + lock.lock() + activeConnections.removeValue(forKey: relayUrl) + let continuation = continuations.removeValue(forKey: relayUrl) + tasks.removeValue(forKey: relayUrl) + lock.unlock() + continuation?.finish() + } + + func finishAll() { + lock.lock() + let allContinuations = continuations + activeConnections.removeAll() + continuations.removeAll() + tasks.removeAll() + lock.unlock() + for continuation in allContinuations.values { + continuation.finish() + } + } +} + +enum ParsedInbound { + case event(subId: String, event: NostrEvent) + case ok(eventId: String, success: Bool, reason: String) + case eose(subscriptionId: String) + + init?(_ message: URLSessionWebSocketTask.Message) { + guard let data = message.dataWithinInboundLimit, + let array = try? JSONSerialization.jsonObject(with: data) as? [Any], + array.count >= 2, + let type = array[0] as? String else { + return nil + } + + switch type { + case "EVENT": + if array.count >= 3, + let subId = array[1] as? String, + let eventDict = array[2] as? [String: Any], + let event = try? NostrEvent(from: eventDict) { + self = .event(subId: subId, event: event) + return + } + return nil + case "EOSE": + if let subId = array[1] as? String { + self = .eose(subscriptionId: subId) + return + } + return nil + case "OK": + if array.count >= 3, + let eventId = array[1] as? String, + let success = array[2] as? Bool { + let reason = array.count >= 4 ? (array[3] as? String ?? "no reason given") : "no reason given" + self = .ok(eventId: eventId, success: success, reason: reason) + return + } + return nil + default: + return nil + } + } +} + +private extension URLSessionWebSocketTask.Message { + /// Prefer rejecting oversized frames before UTF-8/Data materialization + /// where we can (string length), and always before JSON parse. + var dataWithinInboundLimit: Data? { + let maxBytes = TransportConfig.nostrMaxInboundMessageBytes + switch self { + case .string(let text): + guard text.utf8.count <= maxBytes else { return nil } + return text.data(using: .utf8) + case .data(let data): + guard data.count <= maxBytes else { return nil } + return data + @unknown default: + return nil + } + } +} diff --git a/bitchat/Nostr/NostrRelayManager.swift b/bitchat/Nostr/NostrRelayManager.swift index 1512a41a..c5507225 100644 --- a/bitchat/Nostr/NostrRelayManager.swift +++ b/bitchat/Nostr/NostrRelayManager.swift @@ -1,130 +1,6 @@ import BitLogger import Foundation -import Network import Combine -import Tor - -protocol NostrRelayConnectionProtocol: AnyObject { - func resume() - func cancel(with closeCode: URLSessionWebSocketTask.CloseCode, reason: Data?) - func send(_ message: URLSessionWebSocketTask.Message, completionHandler: @escaping (Error?) -> Void) - func receive(completionHandler: @escaping (Result) -> Void) - func sendPing(pongReceiveHandler: @escaping (Error?) -> Void) -} - -protocol NostrRelaySessionProtocol { - func webSocketTask(with url: URL) -> NostrRelayConnectionProtocol -} - -private final class URLSessionWebSocketTaskAdapter: NostrRelayConnectionProtocol { - private let base: URLSessionWebSocketTask - - init(base: URLSessionWebSocketTask) { - self.base = base - } - - func resume() { - base.resume() - } - - func cancel(with closeCode: URLSessionWebSocketTask.CloseCode, reason: Data?) { - base.cancel(with: closeCode, reason: reason) - } - - func send(_ message: URLSessionWebSocketTask.Message, completionHandler: @escaping (Error?) -> Void) { - base.send(message, completionHandler: completionHandler) - } - - func receive(completionHandler: @escaping (Result) -> Void) { - base.receive(completionHandler: completionHandler) - } - - func sendPing(pongReceiveHandler: @escaping (Error?) -> Void) { - base.sendPing(pongReceiveHandler: pongReceiveHandler) - } -} - -private struct URLSessionAdapter: NostrRelaySessionProtocol { - let base: URLSession - - func webSocketTask(with url: URL) -> NostrRelayConnectionProtocol { - let task = base.webSocketTask(with: url) - // Byte bound per inbound frame; without it the per-relay buffer cap - // (nostrInboundPerRelayBufferCap) bounds FRAMES but not BYTES, and a - // hostile relay could pile up cap × 1 MiB (URLSession default) per - // connection. See TransportConfig.nostrInboundMaxFrameBytes for the - // sizing rationale. Oversized frames fail the receive with an error. - task.maximumMessageSize = TransportConfig.nostrInboundMaxFrameBytes - return URLSessionWebSocketTaskAdapter(base: task) - } -} - -struct NostrRelayManagerDependencies { - var activationAllowed: () -> Bool - var userTorEnabled: () -> Bool - var hasMutualFavorites: () -> Bool - var hasLocationPermission: () -> Bool - var mutualFavoritesPublisher: AnyPublisher, Never> - var locationPermissionPublisher: AnyPublisher - var torEnforced: () -> Bool - var torIsReady: () -> Bool - var torIsForeground: () -> Bool - var awaitTorReady: (@escaping (Bool) -> Void) -> Void - var makeSession: () -> NostrRelaySessionProtocol - var scheduleAfter: @Sendable (TimeInterval, @escaping @Sendable () -> Void) -> Void - var now: () -> Date - /// Uniform random value in [0, 1) used to jitter reconnect backoff. - /// Injectable so tests can pin or sweep the jitter deterministically. - var jitterUnit: () -> Double - /// Where relay-settings changes are observed. Injectable so a test can use - /// its own center instead of racing the process-wide one. - var notificationCenter: NotificationCenter = .default - /// Relays added by hand, merged with the built-in set. Injectable so tests - /// do not have to write to shared preferences. - var customRelays: () -> [String] = { NostrRelaySettings.customRelays() } - /// Whether a location channel is currently open. Mirrors the third arm of - /// `NetworkActivationService`'s gate: teleporting into a geohash needs no - /// location permission, and without this the relays would stay filtered out - /// for someone who denied location and has no mutual favorites. - var isInLocationChannel: () -> Bool = { false } - var selectedChannelPublisher: AnyPublisher = Empty().eraseToAnyPublisher() -} - -private extension NostrRelayManagerDependencies { - @MainActor - static func live() -> Self { - Self( - activationAllowed: { NetworkActivationService.shared.activationAllowed }, - userTorEnabled: { NetworkActivationService.shared.userTorEnabled }, - hasMutualFavorites: { !FavoritesPersistenceService.shared.mutualFavorites.isEmpty }, - hasLocationPermission: { LocationChannelManager.shared.permissionState == .authorized }, - mutualFavoritesPublisher: FavoritesPersistenceService.shared.$mutualFavorites.eraseToAnyPublisher(), - locationPermissionPublisher: LocationChannelManager.shared.$permissionState.eraseToAnyPublisher(), - torEnforced: { TorManager.shared.torEnforced }, - torIsReady: { TorManager.shared.isReady }, - torIsForeground: { TorManager.shared.isForeground() }, - awaitTorReady: { completion in - Task.detached { - let ready = await TorManager.shared.awaitReady() - await MainActor.run { - completion(ready) - } - } - }, - makeSession: { URLSessionAdapter(base: TorURLSession.shared.session) }, - scheduleAfter: { delay, action in - DispatchQueue.main.asyncAfter(deadline: .now() + delay, execute: action) - }, - now: Date.init, - jitterUnit: { Double.random(in: 0..<1) }, - isInLocationChannel: { - if case .location = LocationChannelManager.shared.selectedChannel { return true } - return false - }, - selectedChannelPublisher: LocationChannelManager.shared.$selectedChannel.eraseToAnyPublisher() - ) - } -} /// Manages WebSocket connections to Nostr relays @MainActor @@ -1744,369 +1620,3 @@ final class NostrRelayManager: ObservableObject { return false } } - -// MARK: - Off-main inbound parsing helpers (file scope, non-isolated) - -/// A single raw socket frame awaiting off-main parse + Schnorr verification. -private struct InboundFrame: Sendable { - let message: URLSessionWebSocketTask.Message -} - -/// Lock-guarded registry of per-relay inbound streams. -/// -/// The raw WebSocket receive callback is not main-actor isolated, so it needs a -/// `Sendable` path to route a frame to the correct relay's stream without a -/// per-frame hop onto the main actor. Pipeline lifecycle (start/finish) is -/// driven from the main actor; frame delivery (`yield`) can come from any -/// thread. All access is serialized by a single lock — contention is negligible -/// because the guarded critical section is only a dictionary lookup + yield. -private final class InboundFrameRouter: @unchecked Sendable { - /// Full cryptographic identity of a Nostr event being verified. - /// Including every field covered by the NIP-01 event ID + signature ensures - /// a forged/tampered copy can never coalesce onto — or poison — a genuine copy. - private struct VerificationFingerprint: Hashable { - let id: String - let pubkey: String - let createdAt: Int - let kind: Int - let tags: [[String]] - let content: String - let sig: String? - - init(event: NostrEvent) { - self.id = event.id - self.pubkey = event.pubkey - self.createdAt = event.created_at - self.kind = event.kind - self.tags = event.tags - self.content = event.content - self.sig = event.sig - } - - static func == (lhs: VerificationFingerprint, rhs: VerificationFingerprint) -> Bool { - lhs.id == rhs.id && - lhs.pubkey == rhs.pubkey && - lhs.createdAt == rhs.createdAt && - lhs.kind == rhs.kind && - lhs.sig == rhs.sig && - lhs.content == rhs.content && - lhs.tags == rhs.tags - } - - func hash(into hasher: inout Hasher) { - hasher.combine(id) - hasher.combine(pubkey) - hasher.combine(createdAt) - hasher.combine(kind) - hasher.combine(sig) - hasher.combine(content) - hasher.combine(tags) - } - } - - private let lock = NSLock() - private var continuations: [String: AsyncStream.Continuation] = [:] - private var tasks: [String: Task] = [:] - private var activeConnections: [String: ObjectIdentifier] = [:] - private var inFlightVerifications: [VerificationFingerprint: [CheckedContinuation]] = [:] - - /// Start a relay's stream + consumer if one does not already exist. - /// Returns true when a new pipeline was created. The bounded - /// `.bufferingNewest` policy makes a single relay shed its OWN oldest - /// frames under a flood, never other relays' frames. Buffered memory per - /// relay is bounded (not eliminated) at the frame cap times the per-frame - /// byte cap (`maximumMessageSize`) — see TransportConfig. - func startPipeline( - for relayUrl: String, - connectionID: ObjectIdentifier, - makeConsumer: (AsyncStream) -> Task - ) -> Bool { - lock.lock() - defer { lock.unlock() } - activeConnections[relayUrl] = connectionID - if continuations[relayUrl] != nil { return false } - let (stream, continuation) = AsyncStream.makeStream( - bufferingPolicy: .bufferingNewest(TransportConfig.nostrInboundPerRelayBufferCap) - ) - continuations[relayUrl] = continuation - tasks[relayUrl] = makeConsumer(stream) - return true - } - - /// Route a frame to a relay's stream if `connectionID` is still the active - /// socket for `relayUrl`. Returns whether the caller should re-arm receive. - @discardableResult - func yield(_ frame: InboundFrame, to relayUrl: String, from connectionID: ObjectIdentifier) -> Bool { - lock.lock() - guard activeConnections[relayUrl] == connectionID, - let continuation = continuations[relayUrl] else { - lock.unlock() - return false - } - lock.unlock() - continuation.yield(frame) - return true - } - - /// Verifies `event.isValidSignature()` while coalescing simultaneous fan-in - /// deliveries of byte-identical events across multiple relay pipelines. - func verifySignatureCoalesced(_ event: NostrEvent) async -> Bool { - let fingerprint = VerificationFingerprint(event: event) - let isOwner: Bool = { - lock.lock() - defer { lock.unlock() } - if inFlightVerifications[fingerprint] != nil { - return false - } - inFlightVerifications[fingerprint] = [] - return true - }() - - if isOwner { - let valid = event.isValidSignature() - let waiters: [CheckedContinuation] = { - lock.lock() - defer { lock.unlock() } - return inFlightVerifications.removeValue(forKey: fingerprint) ?? [] - }() - for waiter in waiters { - waiter.resume(returning: valid) - } - return valid - } - - return await withCheckedContinuation { continuation in - lock.lock() - if var waiters = inFlightVerifications[fingerprint] { - waiters.append(continuation) - inFlightVerifications[fingerprint] = waiters - lock.unlock() - } else { - lock.unlock() - continuation.resume(returning: event.isValidSignature()) - } - } - } - - /// Finish a relay's stream. The consumer drains any already-buffered frames - /// before exiting, so in-flight verified events are still delivered. - func finishPipeline(for relayUrl: String) { - lock.lock() - activeConnections.removeValue(forKey: relayUrl) - let continuation = continuations.removeValue(forKey: relayUrl) - tasks.removeValue(forKey: relayUrl) - lock.unlock() - continuation?.finish() - } - - func finishAll() { - lock.lock() - let allContinuations = continuations - activeConnections.removeAll() - continuations.removeAll() - tasks.removeAll() - lock.unlock() - for continuation in allContinuations.values { - continuation.finish() - } - } -} - -private enum ParsedInbound { - case event(subId: String, event: NostrEvent) - case ok(eventId: String, success: Bool, reason: String) - case eose(subscriptionId: String) - - init?(_ message: URLSessionWebSocketTask.Message) { - guard let data = message.dataWithinInboundLimit, - let array = try? JSONSerialization.jsonObject(with: data) as? [Any], - array.count >= 2, - let type = array[0] as? String else { - return nil - } - - switch type { - case "EVENT": - if array.count >= 3, - let subId = array[1] as? String, - let eventDict = array[2] as? [String: Any], - let event = try? NostrEvent(from: eventDict) { - self = .event(subId: subId, event: event) - return - } - return nil - case "EOSE": - if let subId = array[1] as? String { - self = .eose(subscriptionId: subId) - return - } - return nil - case "OK": - if array.count >= 3, - let eventId = array[1] as? String, - let success = array[2] as? Bool { - let reason = array.count >= 4 ? (array[3] as? String ?? "no reason given") : "no reason given" - self = .ok(eventId: eventId, success: success, reason: reason) - return - } - return nil - default: - return nil - } - } -} - -private extension URLSessionWebSocketTask.Message { - /// Prefer rejecting oversized frames before UTF-8/Data materialization - /// where we can (string length), and always before JSON parse. - var dataWithinInboundLimit: Data? { - let maxBytes = TransportConfig.nostrMaxInboundMessageBytes - switch self { - case .string(let text): - guard text.utf8.count <= maxBytes else { return nil } - return text.data(using: .utf8) - case .data(let data): - guard data.count <= maxBytes else { return nil } - return data - @unknown default: - return nil - } - } -} - -// MARK: - Nostr Protocol Types - -enum NostrRequest: Encodable { - case event(NostrEvent) - case subscribe(id: String, filters: [NostrFilter]) - case close(id: String) - - func encode(to encoder: Encoder) throws { - var container = encoder.unkeyedContainer() - - switch self { - case .event(let event): - try container.encode("EVENT") - try container.encode(event) - - case .subscribe(let id, let filters): - try container.encode("REQ") - try container.encode(id) - for filter in filters { - try container.encode(filter) - } - - case .close(let id): - try container.encode("CLOSE") - try container.encode(id) - } - } -} - -struct NostrFilter: Encodable { - var ids: [String]? - var authors: [String]? - var kinds: [Int]? - var since: Int? - var until: Int? - var limit: Int? - - // Tag filters - stored internally but encoded specially - fileprivate var tagFilters: [String: [String]]? - - init() { - // Default initializer - } - - func encode(to encoder: Encoder) throws { - var container = encoder.container(keyedBy: DynamicCodingKey.self) - - // Encode standard fields - if let ids = ids { try container.encode(ids, forKey: DynamicCodingKey(stringValue: "ids")) } - if let authors = authors { try container.encode(authors, forKey: DynamicCodingKey(stringValue: "authors")) } - if let kinds = kinds { try container.encode(kinds, forKey: DynamicCodingKey(stringValue: "kinds")) } - if let since = since { try container.encode(since, forKey: DynamicCodingKey(stringValue: "since")) } - if let until = until { try container.encode(until, forKey: DynamicCodingKey(stringValue: "until")) } - if let limit = limit { try container.encode(limit, forKey: DynamicCodingKey(stringValue: "limit")) } - - // Encode tag filters with # prefix - if let tagFilters = tagFilters { - for (tag, values) in tagFilters { - try container.encode(values, forKey: DynamicCodingKey(stringValue: "#\(tag)")) - } - } - } - - // For NIP-17 gift wraps - static func giftWrapsFor(pubkey: String, since: Date? = nil) -> NostrFilter { - var filter = NostrFilter() - filter.kinds = [1059] // Gift wrap kind - filter.since = since?.timeIntervalSince1970.toInt() - filter.tagFilters = ["p": [pubkey]] - filter.limit = TransportConfig.nostrRelayDefaultFetchLimit // reasonable limit - return filter - } - - // For location channels: geohash-scoped ephemeral events (kind 20000) and presence (kind 20001) - static func geohashEphemeral(_ geohash: String, since: Date? = nil, limit: Int = 1000) -> NostrFilter { - var filter = NostrFilter() - filter.kinds = [20000, 20001] - filter.since = since?.timeIntervalSince1970.toInt() - filter.tagFilters = ["g": [geohash]] - filter.limit = limit - return filter - } - - // For location notes with neighbors: subscribe to multiple geohashes (center + neighbors) - static func geohashNotes(_ geohashes: [String], since: Date? = nil, limit: Int = 200) -> NostrFilter { - var filter = NostrFilter() - filter.kinds = [1] - filter.since = since?.timeIntervalSince1970.toInt() - filter.tagFilters = ["g": geohashes] - filter.limit = limit - return filter - } - - // For the mesh bridge: rendezvous messages (kind 20000) and presence - // (kind 20001) tagged `#r` with one or more cells (own + neighbors). - static func bridgeRendezvous(_ cells: [String], since: Date? = nil, limit: Int = 200) -> NostrFilter { - var filter = NostrFilter() - filter.kinds = [20000, 20001] - filter.since = since?.timeIntervalSince1970.toInt() - filter.tagFilters = ["r": cells] - filter.limit = limit - return filter - } - - // For courier drops: sealed envelopes (kind 1401) parked under rotating - // recipient tags (`#x`, hex). Callers pass every candidate tag (adjacent - // UTC days x recipients) in one filter. - static func courierDrops(recipientTagsHex: [String], since: Date? = nil, limit: Int = 100) -> NostrFilter { - var filter = NostrFilter() - filter.kinds = [NostrProtocol.EventKind.courierDrop.rawValue] - filter.since = since?.timeIntervalSince1970.toInt() - filter.tagFilters = ["x": recipientTagsHex] - filter.limit = limit - return filter - } -} - -// Dynamic coding key for tag filters -private struct DynamicCodingKey: CodingKey { - var stringValue: String - var intValue: Int? { nil } - - init(stringValue: String) { - self.stringValue = stringValue - } - - init?(intValue: Int) { - return nil - } -} - -private extension TimeInterval { - func toInt() -> Int { - return Int(self) - } -} diff --git a/bitchat/Nostr/NostrWireTypes.swift b/bitchat/Nostr/NostrWireTypes.swift new file mode 100644 index 00000000..6e21ca66 --- /dev/null +++ b/bitchat/Nostr/NostrWireTypes.swift @@ -0,0 +1,136 @@ +import Foundation + +enum NostrRequest: Encodable { + case event(NostrEvent) + case subscribe(id: String, filters: [NostrFilter]) + case close(id: String) + + func encode(to encoder: Encoder) throws { + var container = encoder.unkeyedContainer() + + switch self { + case .event(let event): + try container.encode("EVENT") + try container.encode(event) + + case .subscribe(let id, let filters): + try container.encode("REQ") + try container.encode(id) + for filter in filters { + try container.encode(filter) + } + + case .close(let id): + try container.encode("CLOSE") + try container.encode(id) + } + } +} + +struct NostrFilter: Encodable { + var ids: [String]? + var authors: [String]? + var kinds: [Int]? + var since: Int? + var until: Int? + var limit: Int? + + // Tag filters - stored internally but encoded specially + fileprivate var tagFilters: [String: [String]]? + + init() { + // Default initializer + } + + func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: DynamicCodingKey.self) + + // Encode standard fields + if let ids = ids { try container.encode(ids, forKey: DynamicCodingKey(stringValue: "ids")) } + if let authors = authors { try container.encode(authors, forKey: DynamicCodingKey(stringValue: "authors")) } + if let kinds = kinds { try container.encode(kinds, forKey: DynamicCodingKey(stringValue: "kinds")) } + if let since = since { try container.encode(since, forKey: DynamicCodingKey(stringValue: "since")) } + if let until = until { try container.encode(until, forKey: DynamicCodingKey(stringValue: "until")) } + if let limit = limit { try container.encode(limit, forKey: DynamicCodingKey(stringValue: "limit")) } + + // Encode tag filters with # prefix + if let tagFilters = tagFilters { + for (tag, values) in tagFilters { + try container.encode(values, forKey: DynamicCodingKey(stringValue: "#\(tag)")) + } + } + } + + // For NIP-17 gift wraps + static func giftWrapsFor(pubkey: String, since: Date? = nil) -> NostrFilter { + var filter = NostrFilter() + filter.kinds = [1059] // Gift wrap kind + filter.since = since?.timeIntervalSince1970.toInt() + filter.tagFilters = ["p": [pubkey]] + filter.limit = TransportConfig.nostrRelayDefaultFetchLimit // reasonable limit + return filter + } + + // For location channels: geohash-scoped ephemeral events (kind 20000) and presence (kind 20001) + static func geohashEphemeral(_ geohash: String, since: Date? = nil, limit: Int = 1000) -> NostrFilter { + var filter = NostrFilter() + filter.kinds = [20000, 20001] + filter.since = since?.timeIntervalSince1970.toInt() + filter.tagFilters = ["g": [geohash]] + filter.limit = limit + return filter + } + + // For location notes with neighbors: subscribe to multiple geohashes (center + neighbors) + static func geohashNotes(_ geohashes: [String], since: Date? = nil, limit: Int = 200) -> NostrFilter { + var filter = NostrFilter() + filter.kinds = [1] + filter.since = since?.timeIntervalSince1970.toInt() + filter.tagFilters = ["g": geohashes] + filter.limit = limit + return filter + } + + // For the mesh bridge: rendezvous messages (kind 20000) and presence + // (kind 20001) tagged `#r` with one or more cells (own + neighbors). + static func bridgeRendezvous(_ cells: [String], since: Date? = nil, limit: Int = 200) -> NostrFilter { + var filter = NostrFilter() + filter.kinds = [20000, 20001] + filter.since = since?.timeIntervalSince1970.toInt() + filter.tagFilters = ["r": cells] + filter.limit = limit + return filter + } + + // For courier drops: sealed envelopes (kind 1401) parked under rotating + // recipient tags (`#x`, hex). Callers pass every candidate tag (adjacent + // UTC days x recipients) in one filter. + static func courierDrops(recipientTagsHex: [String], since: Date? = nil, limit: Int = 100) -> NostrFilter { + var filter = NostrFilter() + filter.kinds = [NostrProtocol.EventKind.courierDrop.rawValue] + filter.since = since?.timeIntervalSince1970.toInt() + filter.tagFilters = ["x": recipientTagsHex] + filter.limit = limit + return filter + } +} + +// Dynamic coding key for tag filters +private struct DynamicCodingKey: CodingKey { + var stringValue: String + var intValue: Int? { nil } + + init(stringValue: String) { + self.stringValue = stringValue + } + + init?(intValue: Int) { + return nil + } +} + +private extension TimeInterval { + func toInt() -> Int { + return Int(self) + } +} diff --git a/bitchat/Services/BLE/BLEFileTransferHandler.swift b/bitchat/Services/BLE/BLEFileTransferHandler.swift index f2c68d67..42c2110f 100644 --- a/bitchat/Services/BLE/BLEFileTransferHandler.swift +++ b/bitchat/Services/BLE/BLEFileTransferHandler.swift @@ -40,9 +40,10 @@ struct BLEFileTransferHandlerEnvironment { let commitPrivateMediaFile: (_ messageID: String, _ storedURL: URL) -> Bool /// Rolls back a saved payload when its durable receipt commit fails. let removeIncomingFile: (_ storedURL: URL) -> Void - /// Releases the allocator's save-to-UI ownership guard after synchronous - /// conversation insertion has completed. - let finishIncomingFileDelivery: (_ storedURL: URL) -> Void + /// Protects an incoming file from quota eviction while UI delivery is pending. + let beginPendingDelivery: (_ storedURL: URL) -> Void + /// Releases quota-eviction protection once UI delivery finalizes. + let finishPendingDelivery: (_ storedURL: URL) -> Void /// Checks the authenticated sender before any private-media disk work. let isPrivateMediaSenderBlocked: (PeerID) -> Bool /// Updates the registry last-seen timestamp for the peer (async barrier write). @@ -298,6 +299,7 @@ final class BLEFileTransferHandler { "📁 Restored durable private media duplicate id=\(messageID.prefix(12))… from \(peerID.id.prefix(8))… -> \(existingFile.lastPathComponent)", category: .session ) + env.beginPendingDelivery(existingFile) deliverStableMessage( message, messageID: messageID, @@ -346,10 +348,15 @@ final class BLEFileTransferHandler { return false } + // Protect the saved payload from quota eviction until its async UI + // delivery finalizes (or commit rollback removes it). + env.beginPendingDelivery(destination) + if let messageID, !env.commitPrivateMediaFile(messageID, destination) { // A payload without its durable ID mapping cannot safely suppress // a retry after relaunch. Roll it back and withhold UI/ACK. + env.finishPendingDelivery(destination) env.removeIncomingFile(destination) return false } @@ -385,16 +392,11 @@ final class BLEFileTransferHandler { { true }, {}, { outcome in + env.finishPendingDelivery(destination) if outcome == .rejected { // Raw media has no durable receipt that can redeliver - // it later. Do not leave a newly saved, UI-unowned file - // available for a stale fallback path to misidentify. + // it later; roll back the unowned file on disk. env.removeIncomingFile(destination) - } else { - // Plain delegates are invoked without synchronous - // insertion confirmation. Preserve the payload for - // that supported delivery path. - env.finishIncomingFileDelivery(destination) } } ) @@ -423,7 +425,7 @@ final class BLEFileTransferHandler { env.acknowledgePrivateMedia(messageID, peerID) }, { _ in - env.finishIncomingFileDelivery(expectedURL) + env.finishPendingDelivery(expectedURL) } ) } diff --git a/bitchat/Services/BLE/BLEIncomingFileStore.swift b/bitchat/Services/BLE/BLEIncomingFileStore.swift index 915de27d..cd16fa28 100644 --- a/bitchat/Services/BLE/BLEIncomingFileStore.swift +++ b/bitchat/Services/BLE/BLEIncomingFileStore.swift @@ -38,7 +38,7 @@ struct PanicRecoveryOperations { } static func live( - fileStore: BLEIncomingFileStore = BLEIncomingFileStore(), + fileStore: BLEIncomingFileStore = .shared, defaults: UserDefaults = .standard ) -> PanicRecoveryOperations { let defaultsKey = "bitchat.panicResetPending" @@ -94,6 +94,11 @@ struct PanicRecoveryOperations { } struct BLEIncomingFileStore: @unchecked Sendable { + /// Shared production store so `BLEService`, `PanicRecoveryOperations`, + /// `ChatLiveVoiceCoordinator`, and startup maintenance operate on a single + /// receipt cache and directory cache. + static let shared = BLEIncomingFileStore() + enum PanicRecoveryError: Error { case externalMarkerCommitFailed case markerWriteFailed(Error) @@ -103,32 +108,45 @@ struct BLEIncomingFileStore: @unchecked Sendable { ) } - struct PrivateMediaDeletionReservation: Sendable { - fileprivate let id: UUID - } - - private final class PayloadCoordination: @unchecked Sendable { - let lock = NSLock() - var pendingDeliveryPaths: Set = [] - var deletionReservations: [UUID: Set] = [:] - } - - /// Separate leaf lock for resolved media directory caching so callers - /// holding or not holding `payloadCoordination.lock` can both query - /// `filesDirectory()` without lock ordering cycles. private final class DirectoryCache: @unchecked Sendable { let lock = NSLock() var filesRoot: URL? var incomingDirectoryPaths: Set = [] var createdSubdirectories: Set = [] + var pendingDeliveryCounts: [String: Int] = [:] func invalidate() { lock.lock() filesRoot = nil incomingDirectoryPaths.removeAll(keepingCapacity: false) createdSubdirectories.removeAll(keepingCapacity: false) + pendingDeliveryCounts.removeAll(keepingCapacity: false) lock.unlock() } + + func beginPendingDelivery(path: String) { + lock.lock() + pendingDeliveryCounts[path, default: 0] += 1 + lock.unlock() + } + + func finishPendingDelivery(path: String) { + lock.lock() + if let count = pendingDeliveryCounts[path] { + if count <= 1 { + pendingDeliveryCounts.removeValue(forKey: path) + } else { + pendingDeliveryCounts[path] = count - 1 + } + } + lock.unlock() + } + + func pendingDeliveryPathsSnapshot() -> Set { + lock.lock() + defer { lock.unlock() } + return Set(pendingDeliveryCounts.keys) + } } private static let defaultQuotaBytes: Int64 = 100 * 1024 * 1024 @@ -137,12 +155,8 @@ struct BLEIncomingFileStore: @unchecked Sendable { static let defaultMediaRetention: TimeInterval = 7 * 24 * 60 * 60 /// Kept outside `files/` so deleting the media tree cannot erase the /// fail-closed startup decision before the full panic has committed. - private static let panicRecoveryPendingMarkerFileName = - ".panic-recovery-pending" - /// Compatibility with a short-lived development build that used the - /// media-specific name for the same full-transaction latch. - private static let legacyPanicRecoveryPendingMarkerFileName = - ".panic-media-wipe-pending" + private static let panicRecoveryPendingMarkerFileName = ".panic-recovery-pending" + private static let legacyPanicRecoveryPendingMarkerFileName = ".panic-media-wipe-pending" private static let mediaSubdirectories = [ "voicenotes/incoming", "voicenotes/outgoing", @@ -171,12 +185,6 @@ struct BLEIncomingFileStore: @unchecked Sendable { /// orphans a previous session left behind. static let liveCapturePrefix = "voice_live_" - /// Media payloads follow the same at-rest posture as the app's other - /// persistence layers (courier, outbox, receipt index): protected until - /// first unlock, so the launch-time retention sweep can still run after - /// a reboot. Applied to the media directories so recordings that save - /// as they go (live captures, `AVAudioRecorder`) inherit it, and stated - /// explicitly at the payload write site like every other store. static var mediaProtectionAttributes: [FileAttributeKey: Any]? { #if os(iOS) return [.protectionKey: FileProtectionType.completeUntilFirstUserAuthentication] @@ -193,7 +201,6 @@ struct BLEIncomingFileStore: @unchecked Sendable { private let panicMarkerWriter: (Data, URL) throws -> Void private let quotaBytes: Int64 private let privateMediaReceipts: BLEPrivateMediaReceiptStore - private let payloadCoordination: PayloadCoordination private let directoryCache: DirectoryCache init( @@ -215,35 +222,16 @@ struct BLEIncomingFileStore: @unchecked Sendable { baseDirectory: baseDirectory, now: dateProvider ) - self.payloadCoordination = PayloadCoordination() self.directoryCache = DirectoryCache() } /// Panic-wipe every managed incoming and outgoing media artifact before /// returning. Recreating the directory tree keeps later capture/receive /// paths usable without allowing a detached cleanup task to race them. - /// - /// Marker persistence and deletion are deliberately separate error - /// domains: even when both durable marker channels fail, deletion is - /// still attempted before this method reports the marker failure. - func panicWipe( - hasDurablePendingMarker: Bool = false - ) throws { - // The receipt index caches tombstones as well as accepted payloads, - // while payload coordination retains save/delete reservations. Always - // invalidate both on return, including partial-failure paths, so no - // pre-panic receiver decision survives after identity reset. + func panicWipe(hasDurablePendingMarker: Bool = false) throws { defer { privateMediaReceipts.resetForPanic() directoryCache.invalidate() - payloadCoordination.lock.lock() - payloadCoordination.pendingDeliveryPaths.removeAll( - keepingCapacity: false - ) - payloadCoordination.deletionReservations.removeAll( - keepingCapacity: false - ) - payloadCoordination.lock.unlock() } let markerError: Error? @@ -266,10 +254,7 @@ struct BLEIncomingFileStore: @unchecked Sendable { } for subdirectory in Self.mediaSubdirectories { try fileManager.createDirectory( - at: filesDirectory.appendingPathComponent( - subdirectory, - isDirectory: true - ), + at: filesDirectory.appendingPathComponent(subdirectory, isDirectory: true), withIntermediateDirectories: true, attributes: Self.mediaProtectionAttributes ) @@ -318,6 +303,9 @@ struct BLEIncomingFileStore: @unchecked Sendable { try ensureSubdirectory(subdirectory) } + /// Writes an incoming payload to a globally unique `_` + /// file so distinct transfers, retries, and post-eviction arrivals never + /// collide on a shared basename. func save( data: Data, preferredName: String?, @@ -325,9 +313,6 @@ struct BLEIncomingFileStore: @unchecked Sendable { fallbackExtension: String?, defaultPrefix: String ) -> URL? { - payloadCoordination.lock.lock() - defer { payloadCoordination.lock.unlock() } - do { let base = try ensureSubdirectory(subdirectory) let sanitized = sanitizedFileName( @@ -335,30 +320,12 @@ struct BLEIncomingFileStore: @unchecked Sendable { defaultName: "\(defaultPrefix)_\(Self.timestampString(from: dateProvider()))", fallbackExtension: fallbackExtension ) - let reservedPaths = privateMediaReceipts.reservedPayloadPaths() - let deletionPaths = payloadCoordination - .deletionReservations.values.reduce(into: Set()) { - $0.formUnion($1) - } - let allocationReservations = deletionPaths.union( - payloadCoordination.pendingDeliveryPaths - ) - let destination = uniqueFileURL( - in: base, - fileName: sanitized, - reservedPaths: (reservedPaths ?? []).union( - allocationReservations - ), - forceRandomizedName: reservedPaths == nil - ) + let destination = uniqueFileURL(in: base, sanitizedName: sanitized) var options: Data.WritingOptions = [.atomic] #if os(iOS) options.insert(.completeFileProtectionUntilFirstUserAuthentication) #endif try data.write(to: destination, options: options) - payloadCoordination.pendingDeliveryPaths.insert( - destination.standardizedFileURL.path - ) return destination } catch { SecureLogger.error("❌ Failed to persist incoming media: \(error)", category: .session) @@ -366,119 +333,50 @@ struct BLEIncomingFileStore: @unchecked Sendable { } } - /// Drops THIS instance's in-memory receipt index after a panic wipe. - /// - /// `panicWipe` already resets the receipt store it runs on, but the - /// production wipe runs on the `PanicRecoveryOperations.live()` file - /// store while receipt lookups are served by `BLEService`'s own - /// `incomingFileStore`. The service's panic path must invalidate its own - /// cache explicitly or pre-panic decisions survive in memory. func resetPrivateMediaReceiptsForPanic() { privateMediaReceipts.resetForPanic() } - func privateMediaReceiptState( - messageID: String - ) -> BLEPrivateMediaReceiptState { + /// Marks an incoming file as awaiting asynchronous UI delivery so quota + /// eviction and age-based retention cannot unlink it before the UI receives + /// the message. Ref-counted per standardized path. + func beginPendingDelivery(at url: URL) { + directoryCache.beginPendingDelivery(path: url.standardizedFileURL.path) + } + + func finishPendingDelivery(at url: URL) { + directoryCache.finishPendingDelivery(path: url.standardizedFileURL.path) + } + + func privateMediaReceiptState(messageID: String) -> BLEPrivateMediaReceiptState { privateMediaReceipts.state(for: messageID) } - func commitPrivateMediaFile( - messageID: String, - storedURL: URL - ) -> Bool { - privateMediaReceipts.commitAccepted( - messageID: messageID, - storedURL: storedURL - ) - } - - /// Reserves every receipt/UI path before the asynchronous deletion - /// barrier. Allocation and reservation share one lock, so either an - /// in-flight raw arrival is observed and deletion fails closed, or the - /// arrival is forced onto a different filename. - func reservePrivateMediaDeletion( - messageIDs: [String], - payloadRelativePaths: [String: String] - ) -> PrivateMediaDeletionReservation? { - payloadCoordination.lock.lock() - defer { payloadCoordination.lock.unlock() } - - guard let paths = privateMediaReceipts - .prospectiveDeletionPayloadPaths( - messageIDs: messageIDs, - payloadRelativePaths: payloadRelativePaths - ), - paths.isDisjoint( - with: payloadCoordination.pendingDeliveryPaths - ) else { - return nil - } - - let reservation = PrivateMediaDeletionReservation(id: UUID()) - payloadCoordination.deletionReservations[reservation.id] = paths - return reservation + func commitPrivateMediaFile(messageID: String, storedURL: URL) -> Bool { + privateMediaReceipts.commitAccepted(messageID: messageID, storedURL: storedURL) } func commitPrivateMediaDeletion( - reservation: PrivateMediaDeletionReservation, messageIDs: [String], - payloadRelativePaths: [String: String], - protectedPayloadRelativePaths: Set + payloadRelativePaths: [String: String] ) -> Bool { - payloadCoordination.lock.lock() - defer { - payloadCoordination.deletionReservations.removeValue( - forKey: reservation.id - ) - payloadCoordination.lock.unlock() - } - guard payloadCoordination.deletionReservations[reservation.id] != nil - else { - return false - } - return privateMediaReceipts.recordDeleted( + privateMediaReceipts.recordDeleted( messageIDs: messageIDs, - payloadRelativePaths: payloadRelativePaths, - protectedPayloadRelativePaths: protectedPayloadRelativePaths + payloadRelativePaths: payloadRelativePaths ) } - /// Explicit deletion of a LEGACY (non-stable-ID) incoming payload. - /// - /// Legacy media has no durable receipt, so the only safe unlink is one - /// that can prove no other owner may hold the basename: the path must - /// not be pending delivery, must not belong to an in-flight deletion - /// reservation, and must not be owned by a stable receipt or journal - /// entry. When any of those hold — or receipt state cannot be read — - /// the file stays for bounded quota cleanup (the fail-safe fallback). - /// Returns true only when the payload was verifiably unlinked. + /// Explicit deletion of a legacy (non-stable-ID) incoming payload. + /// Deletes only regular files directly inside an incoming media directory + /// that are not owned by any stable receipt. @discardableResult func removeLegacyIncomingFile(relativePath: String) -> Bool { - payloadCoordination.lock.lock() - defer { payloadCoordination.lock.unlock() } - - guard let payload = incomingPayloadURL( - relativePath: relativePath - ) else { - return false - } - let standardizedPath = payload.standardizedFileURL.path - let reservedByDeletion = payloadCoordination.deletionReservations - .values.contains { $0.contains(standardizedPath) } - guard !reservedByDeletion, - !payloadCoordination.pendingDeliveryPaths.contains( - standardizedPath - ), - let receiptOwnedPaths = - privateMediaReceipts.reservedPayloadPaths(), - !receiptOwnedPaths.contains(standardizedPath) else { + guard let payload = incomingPayloadURL(relativePath: relativePath), + privateMediaReceipts.isPayloadOwned(relativePath: relativePath) == false else { return false } guard fileManager.fileExists(atPath: payload.path), - (try? payload.resourceValues( - forKeys: [.isRegularFileKey] - ).isRegularFile) == true else { + (try? payload.resourceValues(forKeys: [.isRegularFileKey]).isRegularFile) == true else { return false } do { @@ -493,42 +391,9 @@ struct BLEIncomingFileStore: @unchecked Sendable { } } - /// Resolves a `files/`-relative path iff it lands directly inside one of - /// the incoming media directories. Anything else is not a deletable - /// incoming payload. - private func incomingPayloadURL(relativePath: String) -> URL? { - guard !relativePath.isEmpty, - let resolved = try? resolvedFilesRootAndIncomingPaths() else { - return nil - } - let candidate = resolved.filesRoot - .appendingPathComponent(relativePath, isDirectory: false) - .standardizedFileURL - let parentPath = candidate.deletingLastPathComponent().path - guard resolved.incomingPaths.contains(parentPath) else { - return nil - } - return candidate - } - - /// Releases the short window between disk save and synchronous - /// conversation insertion. Before this callback, a deletion transaction - /// may not infer ownership from a stale bubble that names the same path. - func finishIncomingFileDelivery(at storedURL: URL) { - payloadCoordination.lock.lock() - defer { payloadCoordination.lock.unlock() } - payloadCoordination.pendingDeliveryPaths.remove( - storedURL.standardizedFileURL.path - ) - } - - /// Best-effort rollback for a payload whose durable receipt commit failed. + /// Best-effort rollback for a payload whose durable receipt commit failed + /// or whose raw delivery was rejected. func removeIncomingFile(at storedURL: URL) { - payloadCoordination.lock.lock() - defer { payloadCoordination.lock.unlock() } - payloadCoordination.pendingDeliveryPaths.remove( - storedURL.standardizedFileURL.path - ) guard isURLInsideFilesDirectory(storedURL) else { return } do { try fileManager.removeItem(at: storedURL) @@ -541,29 +406,21 @@ struct BLEIncomingFileStore: @unchecked Sendable { } /// Frees least-recently-modified incoming files until `reservingBytes` - /// fits under the quota. Files named `voice_live_*` (in-flight live - /// captures) are never evicted regardless of who triggers enforcement — - /// a finalized transfer can arrive at quota while a burst is still - /// streaming — but they still count toward usage. + /// fits under the quota. In-flight `voice_live_*` captures are never evicted + /// but still count toward usage. func enforceQuota(reservingBytes: Int) { - payloadCoordination.lock.lock() - defer { payloadCoordination.lock.unlock() } - do { let base = try filesDirectory() - let incomingDirs = [ - base.appendingPathComponent("voicenotes/incoming", isDirectory: true), - base.appendingPathComponent("images/incoming", isDirectory: true), - base.appendingPathComponent("files/incoming", isDirectory: true) - ] var allFiles: [(url: URL, size: Int64, modified: Date)] = [] - for dir in incomingDirs where fileManager.fileExists(atPath: dir.path) { - guard let contents = try? fileManager.contentsOfDirectory( - at: dir, - includingPropertiesForKeys: [.fileSizeKey, .contentModificationDateKey], - options: [.skipsHiddenFiles] - ) else { continue } + for subdirectory in Self.incomingSubdirectories { + let dir = base.appendingPathComponent(subdirectory, isDirectory: true) + guard fileManager.fileExists(atPath: dir.path), + let contents = try? fileManager.contentsOfDirectory( + at: dir, + includingPropertiesForKeys: [.fileSizeKey, .contentModificationDateKey], + options: [.skipsHiddenFiles] + ) else { continue } for fileURL in contents { guard let attrs = try? fileURL.resourceValues(forKeys: [.fileSizeKey, .contentModificationDateKey]), @@ -578,22 +435,12 @@ struct BLEIncomingFileStore: @unchecked Sendable { guard currentUsage > targetUsage else { return } let needToFree = currentUsage - targetUsage - let activeDeletionPaths = payloadCoordination - .deletionReservations.values.reduce(into: Set()) { - $0.formUnion($1) - } - let protectedPaths = activeDeletionPaths.union( - payloadCoordination.pendingDeliveryPaths - ) + let protectedPaths = directoryCache.pendingDeliveryPathsSnapshot() var freedSpace: Int64 = 0 for file in allFiles.sorted(by: { $0.modified < $1.modified }) { guard freedSpace < needToFree else { break } - guard !file.url.lastPathComponent.hasPrefix(Self.liveCapturePrefix) else { continue } - guard !protectedPaths.contains( - file.url.standardizedFileURL.path - ) else { - continue - } + guard !file.url.lastPathComponent.hasPrefix(Self.liveCapturePrefix), + !protectedPaths.contains(file.url.standardizedFileURL.path) else { continue } do { try fileManager.removeItem(at: file.url) freedSpace += file.size @@ -612,54 +459,34 @@ struct BLEIncomingFileStore: @unchecked Sendable { } /// Deletes managed media older than `retention`, across both incoming and - /// outgoing directories, and reports how many files went away. - /// - /// The quota sweep above only bounds *size*, and only for incoming files, - /// so a received photo or a sent voice note could sit on disk unbounded in - /// time — long outliving the conversation it belonged to, which is what a - /// seized device gives up. This bounds media by age instead, on the same - /// principle as the courier envelope and gossip archive lifetimes. - /// - /// Honors the same exclusions as quota eviction: in-flight live captures - /// and files reserved by an in-progress delivery or deletion are left - /// alone regardless of age. + /// outgoing directories, skipping in-flight live captures. @discardableResult func expireAgedMedia(retention: TimeInterval = Self.defaultMediaRetention) -> Int { guard retention > 0 else { return 0 } - payloadCoordination.lock.lock() - defer { payloadCoordination.lock.unlock() } - let cutoff = dateProvider().addingTimeInterval(-retention) - let activeDeletionPaths = payloadCoordination - .deletionReservations.values.reduce(into: Set()) { - $0.formUnion($1) - } - let protectedPaths = activeDeletionPaths.union( - payloadCoordination.pendingDeliveryPaths - ) - + let protectedPaths = directoryCache.pendingDeliveryPathsSnapshot() var removed = 0 do { let base = try filesDirectory() for subdirectory in Self.mediaSubdirectories { let dir = base.appendingPathComponent(subdirectory, isDirectory: true) - guard fileManager.fileExists(atPath: dir.path) else { continue } - guard let contents = try? fileManager.contentsOfDirectory( - at: dir, - includingPropertiesForKeys: [.contentModificationDateKey], - options: [.skipsHiddenFiles] - ) else { continue } + guard fileManager.fileExists(atPath: dir.path), + let contents = try? fileManager.contentsOfDirectory( + at: dir, + includingPropertiesForKeys: [.contentModificationDateKey], + options: [.skipsHiddenFiles] + ) else { continue } for fileURL in contents { guard let modified = try? fileURL.resourceValues( forKeys: [.contentModificationDateKey] - ).contentModificationDate else { continue } - guard modified < cutoff else { continue } - guard !fileURL.lastPathComponent.hasPrefix(Self.liveCapturePrefix) else { continue } - guard !protectedPaths.contains( - fileURL.standardizedFileURL.path - ) else { continue } + ).contentModificationDate, + modified < cutoff, + !fileURL.lastPathComponent.hasPrefix(Self.liveCapturePrefix), + !protectedPaths.contains(fileURL.standardizedFileURL.path) else { + continue + } do { try fileManager.removeItem(at: fileURL) @@ -673,10 +500,7 @@ struct BLEIncomingFileStore: @unchecked Sendable { } } } catch { - SecureLogger.warning( - "⚠️ Could not expire aged media: \(error)", - category: .security - ) + SecureLogger.warning("⚠️ Could not expire aged media: \(error)", category: .security) return removed } @@ -689,17 +513,8 @@ struct BLEIncomingFileStore: @unchecked Sendable { return removed } - /// Stamps the media directories and any resident payloads with the - /// explicit protection class, covering files written by builds that - /// relied on the container default. Runs every launch: re-stamping an - /// equal class is a metadata no-op, and anything carrying a stronger - /// class is left alone, so repetition is cheap and can never downgrade. - /// In-flight live captures are skipped for symmetry with the retention - /// sweep; they receive the class at creation and need no repair. - /// Best-effort like the sweep it runs alongside; a file that cannot be - /// stamped is logged, not fatal, and the migration moves on to the next - /// item. Returns the number of items stamped so the launch path and - /// tests can observe coverage. + /// Stamps media directories and resident payloads with the explicit + /// protection class, leaving stronger classes untouched. @discardableResult func migrateFileProtectionIfNeeded() -> Int { #if os(iOS) @@ -727,13 +542,6 @@ struct BLEIncomingFileStore: @unchecked Sendable { } #if os(iOS) - /// Applies the class to one item, but only when the item currently sits - /// at the container default or weaker. The list names the classes that - /// are safe to replace; anything else, including classes added in later - /// iOS versions, is left alone. Only regular files are stamped when - /// `requireRegularFile` is set (and only real directories otherwise), - /// matching the caution the legacy-file removal path applies; symlinks - /// and other non-regular files are left untouched. private func stampProtectionIfWeaker( _ itemURL: URL, requireRegularFile: Bool, @@ -756,20 +564,31 @@ struct BLEIncomingFileStore: @unchecked Sendable { try fileManager.setAttributes(attributes, ofItemAtPath: itemURL.path) return 1 } catch let error as CocoaError where error.code == .fileNoSuchFile { - // Quota eviction or a deletion commit on another store instance - // can delete an item out from under this migration; that is not - // a failure. return 0 } catch { - SecureLogger.warning( - "⚠️ Failed to migrate media file protection: \(error)", - category: .security - ) + SecureLogger.warning("⚠️ Failed to migrate media file protection: \(error)", category: .security) return 0 } } #endif + // MARK: - Helpers + + private func incomingPayloadURL(relativePath: String) -> URL? { + guard !relativePath.isEmpty, + let resolved = try? resolvedFilesRootAndIncomingPaths() else { + return nil + } + let candidate = resolved.filesRoot + .appendingPathComponent(relativePath, isDirectory: false) + .standardizedFileURL + let parentPath = candidate.deletingLastPathComponent().path + guard resolved.incomingPaths.contains(parentPath) else { + return nil + } + return candidate + } + private func resolvedFilesRootAndIncomingPaths() throws -> (filesRoot: URL, incomingPaths: Set) { directoryCache.lock.lock() if let cachedRoot = directoryCache.filesRoot { @@ -823,23 +642,14 @@ struct BLEIncomingFileStore: @unchecked Sendable { } private func panicRecoveryPendingMarkerURL() throws -> URL { - try rootDirectory().appendingPathComponent( - Self.panicRecoveryPendingMarkerFileName, - isDirectory: false - ) + try rootDirectory().appendingPathComponent(Self.panicRecoveryPendingMarkerFileName, isDirectory: false) } private func panicRecoveryMarkerURLs() throws -> [URL] { let root = try rootDirectory() return [ - root.appendingPathComponent( - Self.panicRecoveryPendingMarkerFileName, - isDirectory: false - ), - root.appendingPathComponent( - Self.legacyPanicRecoveryPendingMarkerFileName, - isDirectory: false - ) + root.appendingPathComponent(Self.panicRecoveryPendingMarkerFileName, isDirectory: false), + root.appendingPathComponent(Self.legacyPanicRecoveryPendingMarkerFileName, isDirectory: false) ] } @@ -861,12 +671,14 @@ struct BLEIncomingFileStore: @unchecked Sendable { if candidate.isEmpty { candidate = defaultName } if candidate.hasPrefix(".") { candidate = "_" + candidate } - if candidate.count > 120 { + // Reserve room for the 37-character "_" prefix within a 120-char cap. + let maxSanitizedLength = 80 + if candidate.count > maxSanitizedLength { let ext = (candidate as NSString).pathExtension let base = (candidate as NSString).deletingPathExtension candidate = ext.isEmpty - ? String(candidate.prefix(120)) - : String(base.prefix(max(10, 120 - ext.count - 1))) + "." + ext + ? String(candidate.prefix(maxSanitizedLength)) + : String(base.prefix(max(10, maxSanitizedLength - ext.count - 1))) + "." + ext } if let fallbackExtension, (candidate as NSString).pathExtension.isEmpty { @@ -876,53 +688,15 @@ struct BLEIncomingFileStore: @unchecked Sendable { return candidate.isEmpty ? defaultName : candidate } - private func uniqueFileURL( - in directory: URL, - fileName: String, - reservedPaths: Set, - forceRandomizedName: Bool - ) -> URL { + private func uniqueFileURL(in directory: URL, sanitizedName: String) -> URL { let directoryPath = directory.standardizedFileURL.path - func isInsideDirectory(_ url: URL) -> Bool { - url.standardizedFileURL.path.hasPrefix(directoryPath + "/") + let uniqueName = "\(UUID().uuidString)_\(sanitizedName)" + let candidate = directory.appendingPathComponent(uniqueName, isDirectory: false) + guard candidate.standardizedFileURL.path.hasPrefix(directoryPath + "/") else { + SecureLogger.warning("⚠️ Path traversal blocked: \(sanitizedName)", category: .security) + return directory.appendingPathComponent("blocked_\(UUID().uuidString)", isDirectory: false) } - func isAvailable(_ url: URL) -> Bool { - !reservedPaths.contains(url.standardizedFileURL.path) - && !fileManager.fileExists(atPath: url.path) - } - - var candidate = directory.appendingPathComponent(fileName) - guard isInsideDirectory(candidate) else { - SecureLogger.warning("⚠️ Path traversal blocked: \(fileName)", category: .security) - return directory.appendingPathComponent("blocked_\(UUID().uuidString)") - } - - let baseName = (fileName as NSString).deletingPathExtension - let ext = (fileName as NSString).pathExtension - if forceRandomizedName { - let suffix = UUID().uuidString - let randomizedName = ext.isEmpty - ? "\(baseName)_\(suffix)" - : "\(baseName)_\(suffix).\(ext)" - return directory.appendingPathComponent(randomizedName) - } - - if isAvailable(candidate) { - return candidate - } - - for counter in 1..<100 { - let newName = ext.isEmpty ? "\(baseName) (\(counter))" : "\(baseName) (\(counter)).\(ext)" - candidate = directory.appendingPathComponent(newName) - guard isInsideDirectory(candidate) else { - return directory.appendingPathComponent("blocked_\(UUID().uuidString)") - } - if isAvailable(candidate) { - return candidate - } - } - - return directory.appendingPathComponent("\(baseName)_\(UUID().uuidString).\(ext.isEmpty ? "dat" : ext)") + return candidate } private static func timestampString(from date: Date) -> String { diff --git a/bitchat/Services/BLE/BLEIngressLinkRegistry.swift b/bitchat/Services/BLE/BLEIngressLinkRegistry.swift index 9ea63c8d..a831feb2 100644 --- a/bitchat/Services/BLE/BLEIngressLinkRegistry.swift +++ b/bitchat/Services/BLE/BLEIngressLinkRegistry.swift @@ -143,3 +143,83 @@ struct BLEIngressLinkRegistry { packet.isRSR && packet.ttl == 0 } } + + +// MARK: - Ingress Packet Guard + +enum BLEIngressPacketGuard { + enum Rejection: Error, Equatable { + case selfLoopback(packetType: UInt8) + case directSenderMismatch(boundPeerID: PeerID, claimedSenderID: PeerID) + case invalidRSR(peerID: PeerID) + case timestampSkew(peerID: PeerID, skewMs: UInt64, maxSkewMs: UInt64) + } + + static func evaluate( + packet: BitchatPacket, + claimedSenderID: PeerID, + boundPeerID: PeerID?, + localPeerID: PeerID, + directAnnounceTTL: UInt8, + nowMs: UInt64 = UInt64(Date().timeIntervalSince1970 * 1000), + maxTimestampSkewMs: UInt64 = TransportConfig.bleMaxTimestampSkewMs, + isValidSyncResponse: (PeerID) -> Bool + ) -> Result { + let contextResult = BLEIngressLinkRegistry.packetContext( + for: packet, + claimedSenderID: claimedSenderID, + boundPeerID: boundPeerID, + localPeerID: localPeerID, + directAnnounceTTL: directAnnounceTTL + ) + + let context: BLEIngressPacketContext + switch contextResult { + case .success(let acceptedContext): + context = acceptedContext + case .failure(.selfLoopback(let packetType)): + return .failure(.selfLoopback(packetType: packetType)) + case .failure(.directSenderMismatch(let boundPeerID, let claimedSenderID)): + return .failure(.directSenderMismatch(boundPeerID: boundPeerID, claimedSenderID: claimedSenderID)) + } + + switch validatePayload( + packet, + from: context.validationPeerID, + nowMs: nowMs, + maxTimestampSkewMs: maxTimestampSkewMs, + isValidSyncResponse: isValidSyncResponse + ) { + case .success: + return .success(context) + case .failure(let rejection): + return .failure(rejection) + } + } + + static func validatePayload( + _ packet: BitchatPacket, + from peerID: PeerID, + nowMs: UInt64 = UInt64(Date().timeIntervalSince1970 * 1000), + maxTimestampSkewMs: UInt64 = TransportConfig.bleMaxTimestampSkewMs, + isValidSyncResponse: (PeerID) -> Bool + ) -> Result { + let packetTime = packet.timestamp + if packet.isRSR { + guard isValidSyncResponse(peerID) else { + return .failure(.invalidRSR(peerID: peerID)) + } + guard packetTime <= nowMs || packetTime - nowMs <= maxTimestampSkewMs else { + return .failure(.timestampSkew(peerID: peerID, skewMs: packetTime - nowMs, maxSkewMs: maxTimestampSkewMs)) + } + return .success(()) + } + + let skew = packetTime > nowMs ? packetTime - nowMs : nowMs - packetTime + guard skew <= maxTimestampSkewMs else { + return .failure(.timestampSkew(peerID: peerID, skewMs: skew, maxSkewMs: maxTimestampSkewMs)) + } + + return .success(()) + } +} diff --git a/bitchat/Services/BLE/BLEIngressPacketGuard.swift b/bitchat/Services/BLE/BLEIngressPacketGuard.swift deleted file mode 100644 index 3081a5b3..00000000 --- a/bitchat/Services/BLE/BLEIngressPacketGuard.swift +++ /dev/null @@ -1,84 +0,0 @@ -import BitFoundation -import Foundation - -enum BLEIngressPacketGuard { - enum Rejection: Error, Equatable { - case selfLoopback(packetType: UInt8) - case directSenderMismatch(boundPeerID: PeerID, claimedSenderID: PeerID) - case invalidRSR(peerID: PeerID) - case timestampSkew(peerID: PeerID, skewMs: UInt64, maxSkewMs: UInt64) - } - - static func evaluate( - packet: BitchatPacket, - claimedSenderID: PeerID, - boundPeerID: PeerID?, - localPeerID: PeerID, - directAnnounceTTL: UInt8, - nowMs: UInt64 = UInt64(Date().timeIntervalSince1970 * 1000), - maxTimestampSkewMs: UInt64 = TransportConfig.bleMaxTimestampSkewMs, - isValidSyncResponse: (PeerID) -> Bool - ) -> Result { - let contextResult = BLEIngressLinkRegistry.packetContext( - for: packet, - claimedSenderID: claimedSenderID, - boundPeerID: boundPeerID, - localPeerID: localPeerID, - directAnnounceTTL: directAnnounceTTL - ) - - let context: BLEIngressPacketContext - switch contextResult { - case .success(let acceptedContext): - context = acceptedContext - case .failure(.selfLoopback(let packetType)): - return .failure(.selfLoopback(packetType: packetType)) - case .failure(.directSenderMismatch(let boundPeerID, let claimedSenderID)): - return .failure(.directSenderMismatch(boundPeerID: boundPeerID, claimedSenderID: claimedSenderID)) - } - - switch validatePayload( - packet, - from: context.validationPeerID, - nowMs: nowMs, - maxTimestampSkewMs: maxTimestampSkewMs, - isValidSyncResponse: isValidSyncResponse - ) { - case .success: - return .success(context) - case .failure(let rejection): - return .failure(rejection) - } - } - - static func validatePayload( - _ packet: BitchatPacket, - from peerID: PeerID, - nowMs: UInt64 = UInt64(Date().timeIntervalSince1970 * 1000), - maxTimestampSkewMs: UInt64 = TransportConfig.bleMaxTimestampSkewMs, - isValidSyncResponse: (PeerID) -> Bool - ) -> Result { - let packetTime = packet.timestamp - if packet.isRSR { - guard isValidSyncResponse(peerID) else { - return .failure(.invalidRSR(peerID: peerID)) - } - // Sync replies legitimately replay old packets, so only the past - // bound is waived. A far-future packet is never legitimate: it - // would outlive every gossip freshness window, drag requesters' - // since-cursors past all real history, and pin itself below live - // chat. - guard packetTime <= nowMs || packetTime - nowMs <= maxTimestampSkewMs else { - return .failure(.timestampSkew(peerID: peerID, skewMs: packetTime - nowMs, maxSkewMs: maxTimestampSkewMs)) - } - return .success(()) - } - - let skew = packetTime > nowMs ? packetTime - nowMs : nowMs - packetTime - guard skew <= maxTimestampSkewMs else { - return .failure(.timestampSkew(peerID: peerID, skewMs: skew, maxSkewMs: maxTimestampSkewMs)) - } - - return .success(()) - } -} diff --git a/bitchat/Services/BLE/BLELinkAuthState.swift b/bitchat/Services/BLE/BLELinkAuthState.swift index 3989c3c4..42ea9579 100644 --- a/bitchat/Services/BLE/BLELinkAuthState.swift +++ b/bitchat/Services/BLE/BLELinkAuthState.swift @@ -113,3 +113,45 @@ struct BLELinkAuthState { return true } } + + +// MARK: - Reconnect Revalidation Policy + +/// Bounds ordinary Noise revalidation to one attempt per physical-link epoch. +/// A live epoch may retry after the cooldown so a lost handshake cannot leave +/// the link permanently unauthenticated. +struct BLENoiseReconnectPolicy { + static let minimumRetryInterval: TimeInterval = 60 + + private var lastAttemptAt: [BLEIngressLinkID: Date] = [:] + + mutating func shouldRevalidate( + on link: BLEIngressLinkID, + hasEstablishedSession: Bool, + isNoiseAuthenticatedLink: Bool, + hasAuthenticatedPeerLink: Bool, + now: Date + ) -> Bool { + guard hasEstablishedSession, + !isNoiseAuthenticatedLink, + !hasAuthenticatedPeerLink else { + return false + } + if let previous = lastAttemptAt[link], + now.timeIntervalSince(previous) < Self.minimumRetryInterval { + return false + } + lastAttemptAt[link] = now + return true + } + + /// Link identifiers can be stable across CoreBluetooth reconnects, so a + /// disconnect explicitly starts a new epoch and permits one fresh attempt. + mutating func endLinkEpoch(_ link: BLEIngressLinkID) { + lastAttemptAt.removeValue(forKey: link) + } + + mutating func removeAll() { + lastAttemptAt.removeAll() + } +} diff --git a/bitchat/Services/BLE/BLENoiseReconnectPolicy.swift b/bitchat/Services/BLE/BLENoiseReconnectPolicy.swift deleted file mode 100644 index 99b748fb..00000000 --- a/bitchat/Services/BLE/BLENoiseReconnectPolicy.swift +++ /dev/null @@ -1,40 +0,0 @@ -import Foundation - -/// Bounds ordinary Noise revalidation to one attempt per physical-link epoch. -/// A live epoch may retry after the cooldown so a lost handshake cannot leave -/// the link permanently unauthenticated. -struct BLENoiseReconnectPolicy { - static let minimumRetryInterval: TimeInterval = 60 - - private var lastAttemptAt: [BLEIngressLinkID: Date] = [:] - - mutating func shouldRevalidate( - on link: BLEIngressLinkID, - hasEstablishedSession: Bool, - isNoiseAuthenticatedLink: Bool, - hasAuthenticatedPeerLink: Bool, - now: Date - ) -> Bool { - guard hasEstablishedSession, - !isNoiseAuthenticatedLink, - !hasAuthenticatedPeerLink else { - return false - } - if let previous = lastAttemptAt[link], - now.timeIntervalSince(previous) < Self.minimumRetryInterval { - return false - } - lastAttemptAt[link] = now - return true - } - - /// Link identifiers can be stable across CoreBluetooth reconnects, so a - /// disconnect explicitly starts a new epoch and permits one fresh attempt. - mutating func endLinkEpoch(_ link: BLEIngressLinkID) { - lastAttemptAt.removeValue(forKey: link) - } - - mutating func removeAll() { - lastAttemptAt.removeAll() - } -} diff --git a/bitchat/Services/BLE/BLEPacketFreshnessPolicy.swift b/bitchat/Services/BLE/BLEPacketFreshnessPolicy.swift deleted file mode 100644 index 2559d855..00000000 --- a/bitchat/Services/BLE/BLEPacketFreshnessPolicy.swift +++ /dev/null @@ -1,27 +0,0 @@ -import Foundation - -enum BLEPacketFreshnessPolicy { - static let defaultMaxAgeSeconds: TimeInterval = 900 - - static func isBroadcastRecipient(_ recipientID: Data?) -> Bool { - guard let recipientID else { return true } - return recipientID.count == 8 && recipientID.allSatisfy { $0 == 0xFF } - } - - static func isStale( - timestampMilliseconds: UInt64, - now: Date, - maxAgeSeconds: TimeInterval = defaultMaxAgeSeconds - ) -> Bool { - let nowMilliseconds = UInt64(now.timeIntervalSince1970 * 1000) - let maxAgeMilliseconds = UInt64(maxAgeSeconds * 1000) - guard nowMilliseconds >= maxAgeMilliseconds else { return false } - return timestampMilliseconds < nowMilliseconds - maxAgeMilliseconds - } - - static func ageSeconds(timestampMilliseconds: UInt64, now: Date) -> Double { - let nowMilliseconds = UInt64(now.timeIntervalSince1970 * 1000) - guard nowMilliseconds >= timestampMilliseconds else { return 0 } - return Double(nowMilliseconds - timestampMilliseconds) / 1000.0 - } -} diff --git a/bitchat/Services/BLE/BLEPeerRegistry.swift b/bitchat/Services/BLE/BLEPeerRegistry.swift index ee718726..5b6f7c0b 100644 --- a/bitchat/Services/BLE/BLEPeerRegistry.swift +++ b/bitchat/Services/BLE/BLEPeerRegistry.swift @@ -270,3 +270,72 @@ struct BLEPeerRegistry { return changes } } + + +// MARK: - Lock-Backed Shared Registry Store + +/// Lock-backed shared ownership of the peer registry, readable from any +/// queue or the main actor without hopping onto a transport queue. +final class BLEPeerRegistryStore: @unchecked Sendable { + private let lock = NSLock() + private var registry = BLEPeerRegistry() + + func read(_ body: (BLEPeerRegistry) -> T) -> T { + lock.withLock { body(registry) } + } + + func mutate(_ body: (inout BLEPeerRegistry) -> T) -> T { + lock.withLock { body(®istry) } + } + + // MARK: - Single-question reads + + var peerIDs: [PeerID] { read { $0.peerIDs } } + var connectedCount: Int { read { $0.connectedCount } } + var connectedPeerIDs: [PeerID] { read { $0.connectedPeerIDs } } + var connectedRoutingData: [Data] { read { $0.connectedRoutingData } } + var snapshotByID: [PeerID: BLEPeerInfo] { read { $0.snapshotByID } } + + func info(for peerID: PeerID) -> BLEPeerInfo? { + read { $0.info(for: peerID) } + } + + func isConnected(_ peerID: PeerID) -> Bool { + read { $0.isConnected(peerID) } + } + + func isReachable(_ peerID: PeerID, now: Date) -> Bool { + read { $0.isReachable(peerID, now: now) } + } + + func nickname(for peerID: PeerID, connectedOnly: Bool) -> String? { + read { $0.nickname(for: peerID, connectedOnly: connectedOnly) } + } + + func fingerprint(for peerID: PeerID) -> String? { + read { $0.fingerprint(for: peerID) } + } + + func capabilities(for peerID: PeerID) -> PeerCapabilities { + read { $0.capabilities(for: peerID) } + } + + func advertisedBridgeGeohash() -> String? { + read { $0.advertisedBridgeGeohash() } + } + + func displayNicknames(selfNickname: String) -> [PeerID: String] { + read { $0.displayNicknames(selfNickname: selfNickname) } + } + + func transportSnapshots(selfNickname: String) -> [TransportPeerSnapshot] { + read { $0.transportSnapshots(selfNickname: selfNickname) } + } + + func reachablePeers(advertising capability: PeerCapabilities, now: Date) -> [PeerID] { + read { registry in + registry.peers(advertising: capability) + .filter { registry.isReachable($0, now: now) } + } + } +} diff --git a/bitchat/Services/BLE/BLEPeerRegistryStore.swift b/bitchat/Services/BLE/BLEPeerRegistryStore.swift deleted file mode 100644 index 89463062..00000000 --- a/bitchat/Services/BLE/BLEPeerRegistryStore.swift +++ /dev/null @@ -1,83 +0,0 @@ -import BitFoundation -import Foundation - -/// Lock-backed shared ownership of the peer registry, readable from any -/// queue or the main actor without hopping onto a transport queue. -/// -/// Mutations come only from the transport's own serial queues — the -/// engine, plus the bleQueue link-drop paths that mark a peer -/// disconnected — and the lock serializes them against each other and -/// against readers, so the main actor answers questions like -/// `isPeerConnected` without blocking behind in-flight transport work. -/// Every `BLEPeerRegistry` mutation is a single whole-transition method, -/// so a reader between two mutations always observes a valid pre- or -/// post-state, never a torn one. -/// -/// Closures passed to `read`/`mutate` run under the (non-recursive) lock -/// and must not call back into the store. -final class BLEPeerRegistryStore: @unchecked Sendable { - private let lock = NSLock() - private var registry = BLEPeerRegistry() - - /// One consistent view across multiple registry reads. - func read(_ body: (BLEPeerRegistry) -> T) -> T { - lock.withLock { body(registry) } - } - - func mutate(_ body: (inout BLEPeerRegistry) -> T) -> T { - lock.withLock { body(®istry) } - } - - // MARK: - Single-question reads - - var peerIDs: [PeerID] { read { $0.peerIDs } } - var connectedCount: Int { read { $0.connectedCount } } - var connectedPeerIDs: [PeerID] { read { $0.connectedPeerIDs } } - var connectedRoutingData: [Data] { read { $0.connectedRoutingData } } - var snapshotByID: [PeerID: BLEPeerInfo] { read { $0.snapshotByID } } - - func info(for peerID: PeerID) -> BLEPeerInfo? { - read { $0.info(for: peerID) } - } - - func isConnected(_ peerID: PeerID) -> Bool { - read { $0.isConnected(peerID) } - } - - func isReachable(_ peerID: PeerID, now: Date) -> Bool { - read { $0.isReachable(peerID, now: now) } - } - - func nickname(for peerID: PeerID, connectedOnly: Bool) -> String? { - read { $0.nickname(for: peerID, connectedOnly: connectedOnly) } - } - - func fingerprint(for peerID: PeerID) -> String? { - read { $0.fingerprint(for: peerID) } - } - - func capabilities(for peerID: PeerID) -> PeerCapabilities { - read { $0.capabilities(for: peerID) } - } - - func advertisedBridgeGeohash() -> String? { - read { $0.advertisedBridgeGeohash() } - } - - func displayNicknames(selfNickname: String) -> [PeerID: String] { - read { $0.displayNicknames(selfNickname: selfNickname) } - } - - func transportSnapshots(selfNickname: String) -> [TransportPeerSnapshot] { - read { $0.transportSnapshots(selfNickname: selfNickname) } - } - - /// Peers advertising `capability` that are reachable now, in one - /// consistent view. - func reachablePeers(advertising capability: PeerCapabilities, now: Date) -> [PeerID] { - read { registry in - registry.peers(advertising: capability) - .filter { registry.isReachable($0, now: now) } - } - } -} diff --git a/bitchat/Services/BLE/BLEPrivateMediaReceiptStore.swift b/bitchat/Services/BLE/BLEPrivateMediaReceiptStore.swift index d8108861..4f71c23b 100644 --- a/bitchat/Services/BLE/BLEPrivateMediaReceiptStore.swift +++ b/bitchat/Services/BLE/BLEPrivateMediaReceiptStore.swift @@ -13,19 +13,14 @@ enum BLEPrivateMediaReceiptState: Equatable { case unavailable } -/// Durable, per-message receiver decisions for stable private media. +/// Durable receiver ledger for stable private-media message IDs. /// -/// Each ID has its own atomic record so one hot lookup never rewrites or -/// decodes the entire ledger. The process-lifetime index is installed only -/// after a complete directory scan. A structural failure of the directory -/// itself (create/enumerate) — or of the single batch deletion journal — -/// remains globally fail-closed and retryable. An individual record that -/// cannot be read, decoded, or validated is quarantined instead: the file is -/// moved aside with a `.corrupt` suffix, excluded from future scans, and only -/// that ID stays fail-closed — the rest of the ledger keeps working, so one -/// damaged record can never make every inbound private media payload vanish. +/// Stored as a single atomic JSON snapshot (`files/.private-media-ledger.json`), +/// making both single-ID accepts and multi-ID explicit deletions atomic in one +/// write without per-ID files or a separate deletion journal. On first load, +/// any legacy `files/.private-media-receipts/` directory is migrated once into +/// the snapshot and removed. final class BLEPrivateMediaReceiptStore: @unchecked Sendable { - typealias DirectoryReader = (_ directory: URL) throws -> [URL] typealias DataReader = (_ url: URL) throws -> Data typealias DataWriter = ( _ data: Data, @@ -33,9 +28,12 @@ final class BLEPrivateMediaReceiptStore: @unchecked Sendable { _ options: Data.WritingOptions ) throws -> Void typealias PayloadRemover = (_ url: URL) throws -> Void - private static let receiptDirectoryName = ".private-media-receipts" - private static let quarantinePathExtension = "corrupt" - private static let deletionJournalFileName = ".deletion-journal.json" + + static let ledgerFileName = ".private-media-ledger.json" + private static let legacyReceiptDirectoryName = ".private-media-receipts" + private static let legacyDeletionJournalFileName = ".deletion-journal.json" + private static let legacyQuarantinePathExtension = "corrupt" + private static let currentVersion = 2 private static let maximumDeletionPathsPerMessage = 2 private struct ReceiptRecord: Codable, Equatable { @@ -45,36 +43,41 @@ final class BLEPrivateMediaReceiptStore: @unchecked Sendable { } let kind: Kind - /// Path below the app's `files/` root. Absolute application-container - /// prefixes are not stable across updates, restores, or reinstalls. + /// Path below `files/` for `.accepted` records. Tombstones keep this `nil`. + var relativePath: String? + /// Incoming payload paths awaiting unlink retry after an atomic tombstone commit. + var pendingUnlinkPaths: [String]? + let recordedAt: Date + } + + private struct LedgerSnapshot: Codable, Equatable { + var version: Int = BLEPrivateMediaReceiptStore.currentVersion + var records: [String: ReceiptRecord] = [:] + var quarantined: Set = [] + } + + // Legacy on-disk migration fixtures. + private struct LegacyReceiptRecord: Codable { + let kind: ReceiptRecord.Kind let relativePath: String? let recordedAt: Date } - /// One atomic write of this journal is the commit point for an entire - /// explicit-deletion batch. Per-ID records and payload unlinks are - /// idempotent materialization performed only after that commit. - private struct DeletionJournalEntry: Codable, Equatable { + private struct LegacyDeletionJournalEntry: Codable { let relativePaths: [String] let recordedAt: Date } - private struct DeletionJournal: Codable { + private struct LegacyDeletionJournal: Codable { let version: Int - let entries: [String: DeletionJournalEntry] + let entries: [String: LegacyDeletionJournalEntry] } private final class Runtime: @unchecked Sendable { let lock = NSLock() - var records: [String: ReceiptRecord]? - /// IDs whose durable record was quarantined as unreadable. Installed - /// together with `records`; these IDs stay fail-closed while every - /// other record keeps serving. - var quarantined: Set = [] - var deletionJournal: [String: DeletionJournalEntry]? + var snapshot: LedgerSnapshot? var cachedFilesRoot: URL? var cachedIncomingDirectoryPaths: Set = [] - var cachedReservedPayloadPaths: Set? } private let fileManager: FileManager @@ -82,7 +85,6 @@ final class BLEPrivateMediaReceiptStore: @unchecked Sendable { private let capacity: Int private let ttl: TimeInterval private let now: () -> Date - private let directoryReader: DirectoryReader? private let dataReader: DataReader? private let dataWriter: DataWriter private let payloadRemover: PayloadRemover @@ -94,11 +96,8 @@ final class BLEPrivateMediaReceiptStore: @unchecked Sendable { capacity: Int = TransportConfig.privateMediaReceivedLedgerCapacity, ttl: TimeInterval = TransportConfig.privateMediaReceivedLedgerTTLSeconds, now: @escaping () -> Date = Date.init, - directoryReader: DirectoryReader? = nil, dataReader: DataReader? = nil, - dataWriter: @escaping DataWriter = { - try $0.write(to: $1, options: $2) - }, + dataWriter: @escaping DataWriter = { try $0.write(to: $1, options: $2) }, payloadRemover: PayloadRemover? = nil ) { self.fileManager = fileManager @@ -106,26 +105,18 @@ final class BLEPrivateMediaReceiptStore: @unchecked Sendable { self.capacity = max(1, capacity) self.ttl = max(0, ttl) self.now = now - self.directoryReader = directoryReader self.dataReader = dataReader self.dataWriter = dataWriter - self.payloadRemover = payloadRemover ?? { - try fileManager.removeItem(at: $0) - } + self.payloadRemover = payloadRemover ?? { try fileManager.removeItem(at: $0) } } - /// Drops process-lifetime decisions after the enclosing media directory - /// has been panic-wiped. A later lookup must rebuild from the durable - /// ledger instead of retaining an accepted receipt or tombstone whose - /// backing files no longer exist. + /// Drops cached decisions after the enclosing media directory has been + /// panic-wiped so subsequent lookups rebuild from disk. func resetForPanic() { runtime.lock.lock() - runtime.records = nil - runtime.quarantined.removeAll(keepingCapacity: false) - runtime.deletionJournal = nil + runtime.snapshot = nil runtime.cachedFilesRoot = nil runtime.cachedIncomingDirectoryPaths.removeAll(keepingCapacity: false) - runtime.cachedReservedPayloadPaths = nil runtime.lock.unlock() } @@ -138,87 +129,57 @@ final class BLEPrivateMediaReceiptStore: @unchecked Sendable { defer { runtime.lock.unlock() } let date = now() - guard let directory = resolvedReceiptDirectory(), - loadDurableStateIfNeeded(from: directory, at: date) else { + guard let ledgerURL = resolvedLedgerURL(), + loadSnapshotIfNeeded(ledgerURL: ledgerURL, at: date), + var snapshot = runtime.snapshot else { return .unavailable } - _ = recoverDeletionJournal(in: directory) - // Committed deletion intent outranks quarantine: a pending journal - // entry proves the payload must stay deleted no matter what state - // the per-ID record file is in. - if runtime.deletionJournal?[messageID] != nil { - return .tombstoned - } - // A quarantined record could have been an acceptance or a tombstone; - // only this ID fails closed, so a retry can neither resurrect deleted - // media nor double-deliver, while every other payload keeps working. - if runtime.quarantined.contains(messageID) { - return .unavailable - } - guard var records = runtime.records else { return .unavailable } - guard var record = records[messageID] else { return .absent } - if record.kind == .tombstone, record.relativePath != nil { - guard scrubLegacyTombstone( - record, - messageID: messageID, - in: directory, - records: &records - ) else { - return .tombstoned - } - guard let scrubbed = records[messageID] else { - return .unavailable - } - record = scrubbed + retryPendingUnlinks(in: &snapshot, ledgerURL: ledgerURL) + if snapshot.quarantined.contains(messageID) { + return .unavailable + } + guard let record = snapshot.records[messageID] else { + return .absent } let retainsAcceptedPath = record.kind == .accepted && record.relativePath.flatMap(existingPayload) != nil + let hasPendingUnlinks = !(record.pendingUnlinkPaths ?? []).isEmpty if isExpired(record.recordedAt, at: date), - !retainsAcceptedPath { - guard removeRecord( - messageID: messageID, - from: directory - ) else { - return record.kind == .tombstone - ? .tombstoned - : .unavailable + !retainsAcceptedPath, + !hasPendingUnlinks { + var updated = snapshot + updated.records.removeValue(forKey: messageID) + guard persist(updated, to: ledgerURL) else { + return record.kind == .tombstone ? .tombstoned : .unavailable } - records.removeValue(forKey: messageID) - runtime.records = records - runtime.cachedReservedPayloadPaths = nil + runtime.snapshot = updated return .absent } switch record.kind { case .tombstone: return .tombstoned - case .accepted: guard let relativePath = record.relativePath, let existingURL = existingPayload(relativePath: relativePath) else { - // Quota cleanup is not explicit deletion. Remove the stale - // receipt so a sender retry can restore the payload and bubble. - guard removeRecord( - messageID: messageID, - from: directory - ) else { + // Quota eviction is not explicit deletion; prune the stale + // receipt so a sender retry can restore the payload. + var updated = snapshot + updated.records.removeValue(forKey: messageID) + guard persist(updated, to: ledgerURL) else { return .unavailable } - records.removeValue(forKey: messageID) - runtime.records = records - runtime.cachedReservedPayloadPaths = nil + runtime.snapshot = updated return .absent } return .accepted(existingURL) } } - /// Records an accepted ID only after the payload is on disk. Callers must - /// roll the payload back and withhold UI delivery/ACK when this returns - /// false. + /// Records an accepted ID only after the payload is on disk. func commitAccepted(messageID: String, storedURL: URL) -> Bool { guard PrivateMediaMessageIdentity.isStableID(messageID) else { return false @@ -233,64 +194,55 @@ final class BLEPrivateMediaReceiptStore: @unchecked Sendable { } let date = now() - guard let directory = resolvedReceiptDirectory(), - loadDurableStateIfNeeded(from: directory, at: date) else { + guard let ledgerURL = resolvedLedgerURL(), + loadSnapshotIfNeeded(ledgerURL: ledgerURL, at: date), + var snapshot = runtime.snapshot else { return false } - _ = recoverDeletionJournal(in: directory) - guard runtime.deletionJournal?[messageID] == nil, - !runtime.quarantined.contains(messageID), - var records = runtime.records else { + + retryPendingUnlinks(in: &snapshot, ledgerURL: ledgerURL) + guard !snapshot.quarantined.contains(messageID) else { return false } - if runtime.deletionJournal?.values.contains(where: { - $0.relativePaths.contains(relativePath) - }) == true { - return false - } - if records.contains(where: { existingMessageID, record in - existingMessageID != messageID - && record.relativePath == relativePath + // Reject cross-ID path reuse or pending-unlink path collision. + if snapshot.records.contains(where: { otherID, record in + if record.pendingUnlinkPaths?.contains(relativePath) == true { + return true + } + return otherID != messageID && record.relativePath == relativePath }) { return false } - if let existing = records[messageID], + if let existing = snapshot.records[messageID], existing.kind == .tombstone, - !isExpired(existing.recordedAt, at: date) { + (!isExpired(existing.recordedAt, at: date) + || !(existing.pendingUnlinkPaths ?? []).isEmpty) { + return false + } + if snapshot.records[messageID]?.kind != .accepted, + snapshot.records.values.lazy.filter({ $0.kind == .accepted }).count >= capacity { return false } - if records[messageID]?.kind != .accepted, - records.values.lazy.filter({ $0.kind == .accepted }).count >= capacity { - return false - } - - let record = ReceiptRecord( + var updated = snapshot + updated.records[messageID] = ReceiptRecord( kind: .accepted, relativePath: relativePath, + pendingUnlinkPaths: nil, recordedAt: date ) - guard persist(record, messageID: messageID, to: directory) else { + guard persist(updated, to: ledgerURL) else { return false } - - records[messageID] = record - runtime.records = records - runtime.cachedReservedPayloadPaths = nil + runtime.snapshot = updated return true } - /// Atomically commits explicit deletion for every stable ID in `messageIDs`. - /// - /// The journal is the single batch commit point: a failed write changes - /// neither durable nor in-memory receiver state, so callers must preserve - /// their bubbles. Once the write succeeds, every entry is tombstoned even - /// if the process exits before per-ID materialization or payload unlink. - /// Recovery retries both operations on the next lookup or launch. + /// Atomically commits explicit deletion for every stable ID in `messageIDs` + /// in a single snapshot write, then unlinks the associated payloads. func recordDeleted( messageIDs: [String], - payloadRelativePaths: [String: String] = [:], - protectedPayloadRelativePaths: Set = [] + payloadRelativePaths: [String: String] = [:] ) -> Bool { let stableIDs = Array( Set(messageIDs.filter(PrivateMediaMessageIdentity.isStableID)) @@ -302,93 +254,62 @@ final class BLEPrivateMediaReceiptStore: @unchecked Sendable { defer { runtime.lock.unlock() } let date = now() - guard let directory = resolvedReceiptDirectory(), - loadDurableStateIfNeeded(from: directory, at: date) else { - return false - } - _ = recoverDeletionJournal(in: directory) - guard let records = runtime.records, - var journal = runtime.deletionJournal else { + guard let ledgerURL = resolvedLedgerURL(), + loadSnapshotIfNeeded(ledgerURL: ledgerURL, at: date), + var snapshot = runtime.snapshot else { return false } - // Quarantined IDs need no special case here: their record is never - // indexed, so deleting one requires a caller-supplied payload path - // (the general pathless-deletion refusal below rejects it otherwise), - // and materialization never rewrites a quarantined ID's record. - let pendingIDs = Set(journal.keys) + retryPendingUnlinks(in: &snapshot, ledgerURL: ledgerURL) + let newIDs = stableIDs.filter { messageID in - if pendingIDs.contains(messageID) { return false } - if let current = records[messageID], + if let current = snapshot.records[messageID], current.kind == .tombstone, - !isExpired(current.recordedAt, at: date) { + (!isExpired(current.recordedAt, at: date) + || !(current.pendingUnlinkPaths ?? []).isEmpty) { return false } return true } - guard !newIDs.isEmpty else { - return true - } - guard Set(journal.keys).union(newIDs).count <= capacity else { - return false - } + guard !newIDs.isEmpty else { return true } - var newEntries: [String: DeletionJournalEntry] = [:] + let stableIDSet = Set(stableIDs) + var updated = snapshot for messageID in newIDs { - // Accepted receipts normally supply the exact stored path. The UI - // fallback is required when that receipt aged or was capacity - // evicted while its bubble and payload remain. They may differ - // after a retry selected a suffixed filename, so journal both. - // Never commit a new pathless tombstone: it could retire - // successfully while leaving an untracked payload behind. let relativePaths = Array(Set([ - records[messageID]?.relativePath, + snapshot.records[messageID]?.relativePath, payloadRelativePaths[messageID] ].compactMap { $0 })).sorted() + guard !relativePaths.isEmpty, - relativePaths.count <= - Self.maximumDeletionPathsPerMessage, - relativePaths.allSatisfy({ - isSafeDeletionTarget(relativePath: $0) - }), - protectedPayloadRelativePaths.isDisjoint( - with: relativePaths - ), - !records.contains(where: { otherMessageID, record in - otherMessageID != messageID - && !stableIDs.contains(otherMessageID) - && record.relativePath.map( - relativePaths.contains - ) == true - }), - !journal.contains(where: { otherMessageID, entry in - otherMessageID != messageID - && !stableIDs.contains(otherMessageID) - && !Set(entry.relativePaths).isDisjoint( - with: relativePaths - ) + relativePaths.count <= Self.maximumDeletionPathsPerMessage, + relativePaths.allSatisfy({ isSafeDeletionTarget(relativePath: $0) }), + !snapshot.records.contains(where: { otherID, record in + otherID != messageID + && !stableIDSet.contains(otherID) + && (record.relativePath.map(relativePaths.contains) == true + || !(Set(record.pendingUnlinkPaths ?? []).isDisjoint(with: relativePaths))) }) else { return false } - newEntries[messageID] = DeletionJournalEntry( - // The journal retains every owned path so payload deletion - // remains recoverable across a crash or unlink failure. - relativePaths: relativePaths, + + updated.records[messageID] = ReceiptRecord( + kind: .tombstone, + relativePath: nil, + pendingUnlinkPaths: relativePaths, recordedAt: date ) } - journal.merge(newEntries) { _, new in new } - // Do not install any process-local tombstone before this succeeds. - // A failed delete must continue to resolve to its prior accepted - // state, otherwise a retry could be falsely ACKed while UI remains. - guard persistDeletionJournal(journal, in: directory) else { + // Enforce tombstone capacity by evicting oldest tombstones outside this batch. + enforceTombstoneCapacity(in: &updated, preserving: stableIDSet) + + // Single atomic write commits the entire deletion batch. + guard persist(updated, to: ledgerURL) else { return false } - - runtime.deletionJournal = journal - runtime.cachedReservedPayloadPaths = nil - _ = recoverDeletionJournal(in: directory) + runtime.snapshot = updated + retryPendingUnlinks(in: &updated, ledgerURL: ledgerURL) return true } @@ -399,633 +320,323 @@ final class BLEPrivateMediaReceiptStore: @unchecked Sendable { return recordDeleted(messageIDs: [messageID]) } - /// Resolves every path a deletion transaction may target. The incoming - /// allocator reserves this set at the journal barrier so a concurrent raw - /// arrival cannot reuse a missing UI fallback. - func prospectiveDeletionPayloadPaths( - messageIDs: [String], - payloadRelativePaths: [String: String] - ) -> Set? { - let stableIDs = Set( - messageIDs.filter(PrivateMediaMessageIdentity.isStableID) - ) - guard !stableIDs.isEmpty else { return [] } - + /// Returns whether `relativePath` is owned by an accepted receipt or a + /// pending tombstone unlink, or `nil` when the ledger cannot be read. + func isPayloadOwned(relativePath: String) -> Bool? { runtime.lock.lock() defer { runtime.lock.unlock() } let date = now() - guard let directory = resolvedReceiptDirectory(), - loadDurableStateIfNeeded(from: directory, at: date) else { - return nil - } - _ = recoverDeletionJournal(in: directory) - guard let journal = runtime.deletionJournal, - let records = runtime.records else { + guard let ledgerURL = resolvedLedgerURL(), + loadSnapshotIfNeeded(ledgerURL: ledgerURL, at: date), + var snapshot = runtime.snapshot else { return nil } - var paths: Set = [] - for messageID in stableIDs { - if let entry = journal[messageID] { - paths.formUnion(entry.relativePaths) - continue - } - if let relativePath = records[messageID]?.relativePath { - paths.insert(relativePath) - } - if let relativePath = payloadRelativePaths[messageID] { - paths.insert(relativePath) - } + retryPendingUnlinks(in: &snapshot, ledgerURL: ledgerURL) + return snapshot.records.values.contains { record in + record.relativePath == relativePath + || (record.pendingUnlinkPaths?.contains(relativePath) == true) } - guard paths.allSatisfy({ - candidatePayload(relativePath: $0) != nil - }) else { - return nil - } - return Set(paths.compactMap { - candidatePayload(relativePath: $0)? - .standardizedFileURL.path - }) } - /// Paths owned by accepted receipts, legacy pathful tombstones, or the - /// deletion journal. Incoming allocation must not reuse any of them for a - /// different ID. Quarantined records are unreadable, so any path they may - /// have owned cannot be reserved; their bytes remain preserved in the - /// `.corrupt` file for offline inspection. - func reservedPayloadPaths() -> Set? { - runtime.lock.lock() - defer { runtime.lock.unlock() } + // MARK: - Loading & Legacy Migration - let date = now() - guard let directory = resolvedReceiptDirectory(), - loadDurableStateIfNeeded(from: directory, at: date) else { - return nil - } - _ = recoverDeletionJournal(in: directory) - guard let journal = runtime.deletionJournal, - let records = runtime.records else { - return nil - } - if let cached = runtime.cachedReservedPayloadPaths { - return cached - } - var reserved: Set = [] - reserved.reserveCapacity(records.count + journal.count) - for record in records.values { - if let relativePath = record.relativePath, - let path = candidatePayload(relativePath: relativePath)?.standardizedFileURL.path { - reserved.insert(path) - } - } - for entry in journal.values { - for relativePath in entry.relativePaths { - if let path = candidatePayload(relativePath: relativePath)?.standardizedFileURL.path { - reserved.insert(path) + private func loadSnapshotIfNeeded(ledgerURL: URL, at date: Date) -> Bool { + if runtime.snapshot != nil { return true } + + var snapshot: LedgerSnapshot + var needsPersist = false + + if fileManager.fileExists(atPath: ledgerURL.path) { + do { + let data = try dataReader?(ledgerURL) ?? Data(contentsOf: ledgerURL) + let decoded = try JSONDecoder().decode(LedgerSnapshot.self, from: data) + guard isStructurallyValid(decoded) else { + SecureLogger.error("❌ Invalid private-media receipt ledger", category: .session) + return false } + snapshot = decoded + } catch { + SecureLogger.error("❌ Failed to read private-media receipt ledger: \(error)", category: .session) + return false + } + } else if let legacyDirectory = resolvedLegacyReceiptDirectory(), + fileManager.fileExists(atPath: legacyDirectory.path) { + guard let migrated = migrateLegacyDirectory(legacyDirectory) else { + return false + } + snapshot = migrated + needsPersist = true + } else { + snapshot = LedgerSnapshot() + } + + if pruneExpiredAndOverflow(in: &snapshot, at: date) { + needsPersist = true + } + + if needsPersist { + guard persist(snapshot, to: ledgerURL) else { + return false + } + if let legacyDirectory = resolvedLegacyReceiptDirectory(), + fileManager.fileExists(atPath: legacyDirectory.path) { + try? fileManager.removeItem(at: legacyDirectory) } } - runtime.cachedReservedPayloadPaths = reserved - return reserved - } - private func scrubLegacyTombstone( - _ tombstone: ReceiptRecord, - messageID: String, - in directory: URL, - records: inout [String: ReceiptRecord] - ) -> Bool { - guard tombstone.kind == .tombstone, - tombstone.relativePath != nil else { - return true - } - // Pre-journal tombstones cannot prove that the current file is still - // the payload they originally described. Older allocators did not - // reserve these paths, so a raw/public arrival may have reused the - // basename. Shed the ambiguous path without unlinking anything. - let pathless = ReceiptRecord( - kind: .tombstone, - relativePath: nil, - recordedAt: tombstone.recordedAt - ) - guard persist( - pathless, - messageID: messageID, - to: directory - ) else { - return false - } - records[messageID] = pathless - runtime.records = records - runtime.cachedReservedPayloadPaths = nil + runtime.snapshot = snapshot + retryPendingUnlinks(in: &snapshot, ledgerURL: ledgerURL) return true } - private func loadDurableStateIfNeeded( - from directory: URL, - at date: Date - ) -> Bool { - if runtime.records != nil, runtime.deletionJournal != nil { - return true - } - - do { - try fileManager.createDirectory( - at: directory, - withIntermediateDirectories: true, - attributes: nil - ) - } catch { - SecureLogger.error( - "❌ Failed to create private-media receipt directory: \(error)", - category: .session - ) - return false - } - + /// One-time migration from the pre-consolidation per-ID receipt directory + /// and `.deletion-journal.json` into a single `LedgerSnapshot`. + private func migrateLegacyDirectory(_ directory: URL) -> LedgerSnapshot? { let urls: [URL] do { - if let directoryReader { - urls = try directoryReader(directory) - } else { - urls = try fileManager.contentsOfDirectory( - at: directory, - includingPropertiesForKeys: nil, - options: [] - ) - } - } catch { - SecureLogger.error( - "❌ Failed to enumerate private-media receipts: \(error)", - category: .session + urls = try fileManager.contentsOfDirectory( + at: directory, + includingPropertiesForKeys: nil, + options: [] ) - return false + } catch { + SecureLogger.error("❌ Failed to enumerate legacy private-media receipts: \(error)", category: .session) + return nil } - var records: [String: ReceiptRecord] = [:] - var scannedRecords: [String: ReceiptRecord] = [:] - var quarantined: Set = [] - var expired: [String] = [] - var tombstones: [(messageID: String, record: ReceiptRecord)] = [] + var snapshot = LedgerSnapshot() + for url in urls { - // Records quarantined by an earlier scan stay fail-closed on - // every launch without being re-read: only their ID matters. - if url.pathExtension == Self.quarantinePathExtension { + if url.pathExtension == Self.legacyQuarantinePathExtension { let messageID = url .deletingPathExtension() .deletingPathExtension() .lastPathComponent if PrivateMediaMessageIdentity.isStableID(messageID) { - quarantined.insert(messageID) + snapshot.quarantined.insert(messageID) } continue } - guard url.pathExtension == "json" else { continue } + guard url.pathExtension == "json", + url.lastPathComponent != Self.legacyDeletionJournalFileName else { + continue + } let messageID = url.deletingPathExtension().lastPathComponent guard PrivateMediaMessageIdentity.isStableID(messageID) else { continue } - - let record: ReceiptRecord do { let data = try dataReader?(url) ?? Data(contentsOf: url) - record = try JSONDecoder().decode(ReceiptRecord.self, from: data) - } catch { - // Never delete or silently skip an unreadable stable-ID - // record: treating it as absent could resurrect accepted or - // deleted media. But never let it poison the whole ledger - // either — quarantine the file and fail only this ID closed. - quarantine(url, messageID: messageID, reason: "\(error)") - quarantined.insert(messageID) - continue - } - - guard isStructurallyValid(record) else { - quarantine( - url, - messageID: messageID, - reason: "structurally invalid" - ) - quarantined.insert(messageID) - continue - } - scannedRecords[messageID] = record - if record.kind == .tombstone { - tombstones.append((messageID, record)) - } - let retainsAcceptedPath = - record.kind == .accepted - && record.relativePath.flatMap(existingPayload) != nil - if isExpired(record.recordedAt, at: date), - !retainsAcceptedPath { - expired.append(messageID) - continue - } - records[messageID] = record - } - - // A readable duplicate of a quarantined ID must not override the - // fail-closed decision, not even through the failed-prune restore - // or legacy-tombstone scrub paths below. - for messageID in quarantined { - records.removeValue(forKey: messageID) - scannedRecords.removeValue(forKey: messageID) - } - tombstones.removeAll { quarantined.contains($0.messageID) } - - let overflow = overflowVictims(in: records) - for messageID in overflow { - records.removeValue(forKey: messageID) - } - - let journal: [String: DeletionJournalEntry] - let journalURL = deletionJournalURL(in: directory) - if fileManager.fileExists(atPath: journalURL.path) { - do { - let data = try dataReader?(journalURL) - ?? Data(contentsOf: journalURL) - let snapshot = try JSONDecoder().decode( - DeletionJournal.self, - from: data - ) - guard snapshot.version == 1, - snapshot.entries.count <= capacity, - snapshot.entries.allSatisfy({ messageID, entry in - PrivateMediaMessageIdentity.isStableID(messageID) - && !entry.relativePaths.isEmpty - && entry.relativePaths.count <= - Self.maximumDeletionPathsPerMessage - && Set(entry.relativePaths).count - == entry.relativePaths.count - && entry.relativePaths.allSatisfy { - candidatePayload(relativePath: $0) != nil - } - }) else { - // The journal is a single batch commit file: like a - // directory-level failure it stays globally fail-closed - // and retryable, never quarantined per-ID. - SecureLogger.error( - "❌ Invalid private-media deletion journal", - category: .session - ) - return false - } - journal = snapshot.entries - } catch { - // The journal is the all-ID commit record. It may never be - // skipped or treated as empty when unreadable. - SecureLogger.error( - "❌ Failed to read private-media deletion journal: \(error)", - category: .session - ) - return false - } - } else { - journal = [:] - } - - var protectedFromPruning: Set = [] - - // Old per-ID tombstones may still carry a payload path from before the - // deletion journal existed. That path is inherently ambiguous because - // old allocators did not reserve it. Convert it to a pathless - // tombstone without unlinking any current file. - for (messageID, tombstone) in tombstones - where journal[messageID] == nil - && tombstone.relativePath != nil { - let pathless = ReceiptRecord( - kind: .tombstone, - relativePath: nil, - recordedAt: tombstone.recordedAt - ) - guard persist( - pathless, - messageID: messageID, - to: directory - ) else { - records[messageID] = tombstone - protectedFromPruning.insert(messageID) - continue - } - scannedRecords[messageID] = pathless - if records[messageID] != nil { - records[messageID] = pathless - } - } - - for messageID in expired + overflow { - guard !protectedFromPruning.contains(messageID) else { continue } - if !removeRecord(messageID: messageID, from: directory), - let record = scannedRecords[messageID] { - records[messageID] = record - } - } - - // Install caches only after every per-ID record and the batch journal - // have been read and validated. Failed legacy cleanup remains indexed - // and path-reserved instead of blocking unrelated media. - runtime.records = records - runtime.quarantined = quarantined - runtime.deletionJournal = journal - runtime.cachedReservedPayloadPaths = nil - return true - } - - /// Idempotently materializes the write-ahead journal. An entry leaves the - /// journal only after its per-ID tombstone is durable and every recorded - /// payload is absent. Any failure keeps the journal authoritative for a - /// later lookup or process restart. - @discardableResult - private func recoverDeletionJournal(in directory: URL) -> Bool { - guard let journal = runtime.deletionJournal, - !journal.isEmpty, - var records = runtime.records else { - return true - } - - let preservedMessageIDs = Set(journal.keys) - var remaining = journal - let orderedEntries = journal.sorted { lhs, rhs in - if lhs.value.recordedAt == rhs.value.recordedAt { - return lhs.key < rhs.key - } - return lhs.value.recordedAt < rhs.value.recordedAt - } - - for (messageID, journalEntry) in orderedEntries { - // Never materialize a per-ID record for a quarantined ID: the - // scanner ignores readable duplicates of a quarantined record, - // and quarantine is already permanently fail-closed - // (state == .unavailable, commitAccepted refuses it), which - // subsumes the tombstone's no-resurrection guarantee. Only the - // payload unlinks below still need to run before the entry can - // retire. - if !runtime.quarantined.contains(messageID) { - let pathlessTombstone = ReceiptRecord( - kind: .tombstone, - relativePath: nil, - recordedAt: journalEntry.recordedAt - ) - if records[messageID] != pathlessTombstone { - let victim = capacityVictim( - for: .tombstone, - replacing: messageID, - in: records, - preserving: preservedMessageIDs - ) - if records[messageID]?.kind != .tombstone, - records.values.lazy.filter({ - $0.kind == .tombstone - }).count >= capacity, - victim == nil { + let legacy = try JSONDecoder().decode(LegacyReceiptRecord.self, from: data) + let migrated: ReceiptRecord + switch legacy.kind { + case .accepted: + guard let path = legacy.relativePath, + candidatePayload(relativePath: path) != nil else { + snapshot.quarantined.insert(messageID) continue } - guard persist( - pathlessTombstone, - messageID: messageID, - to: directory - ) else { + migrated = ReceiptRecord( + kind: .accepted, + relativePath: path, + pendingUnlinkPaths: nil, + recordedAt: legacy.recordedAt + ) + case .tombstone: + if let path = legacy.relativePath, + candidatePayload(relativePath: path) == nil { + snapshot.quarantined.insert(messageID) continue } - records[messageID] = pathlessTombstone - if let victim, victim != messageID { - records.removeValue(forKey: victim) - removeRecord(messageID: victim, from: directory) - } + // Pre-journal pathful tombstones carried ambiguous basenames; + // drop the path without unlinking any current file. + migrated = ReceiptRecord( + kind: .tombstone, + relativePath: nil, + pendingUnlinkPaths: nil, + recordedAt: legacy.recordedAt + ) } - } - - // Only the journal retains the paths. Once every unlink succeeds, - // the durable per-ID tombstone is pathless and cannot later - // delete a different payload that reused the basename. - let removedEveryPayload = journalEntry.relativePaths.allSatisfy { - removePayload(atRelativePath: $0) - } - guard removedEveryPayload else { - continue - } - remaining.removeValue(forKey: messageID) - } - - runtime.records = records - runtime.cachedReservedPayloadPaths = nil - guard remaining != journal else { return false } - - if remaining.isEmpty { - guard removeDeletionJournal(in: directory) else { return false } - } else { - guard persistDeletionJournal(remaining, in: directory) else { - return false + snapshot.records[messageID] = migrated + } catch { + snapshot.quarantined.insert(messageID) } } - runtime.deletionJournal = remaining - runtime.cachedReservedPayloadPaths = nil - return remaining.isEmpty - } - private func persistDeletionJournal( - _ entries: [String: DeletionJournalEntry], - in directory: URL - ) -> Bool { - do { - try fileManager.createDirectory( - at: directory, - withIntermediateDirectories: true, - attributes: nil - ) - let data = try JSONEncoder().encode( - DeletionJournal(version: 1, entries: entries) - ) - var options: Data.WritingOptions = [.atomic] - #if os(iOS) - options.insert( - .completeFileProtectionUntilFirstUserAuthentication - ) - #endif - try dataWriter(data, deletionJournalURL(in: directory), options) - return true - } catch { - SecureLogger.error( - "❌ Failed to persist private-media deletion journal: \(error)", - category: .session - ) - return false - } - } - - private func removeDeletionJournal(in directory: URL) -> Bool { - let url = deletionJournalURL(in: directory) - guard fileManager.fileExists(atPath: url.path) else { return true } - do { - try fileManager.removeItem(at: url) - return true - } catch { - SecureLogger.warning( - "⚠️ Failed to retire private-media deletion journal: \(error)", - category: .session - ) - return false - } - } - - private func deletionJournalURL(in directory: URL) -> URL { - directory.appendingPathComponent( - Self.deletionJournalFileName, + let journalURL = directory.appendingPathComponent( + Self.legacyDeletionJournalFileName, isDirectory: false ) - } - - /// Moves an unreadable record aside so future scans skip it while its ID - /// stays fail-closed. The bytes are preserved for offline inspection — - /// quarantine never deletes receiver decisions. - private func quarantine(_ url: URL, messageID: String, reason: String) { - SecureLogger.error( - "❌ Quarantining unreadable private-media receipt \(messageID.prefix(12))…: \(reason)", - category: .session - ) - let destination = url.appendingPathExtension( - Self.quarantinePathExtension - ) - do { - if fileManager.fileExists(atPath: destination.path) { - // Same ID, already fail-closed; keep the earlier evidence. - try fileManager.removeItem(at: url) - } else { - try fileManager.moveItem(at: url, to: destination) + if fileManager.fileExists(atPath: journalURL.path) { + do { + let data = try dataReader?(journalURL) ?? Data(contentsOf: journalURL) + let journal = try JSONDecoder().decode(LegacyDeletionJournal.self, from: data) + guard journal.version == 1, + journal.entries.count <= capacity, + journal.entries.allSatisfy({ id, entry in + PrivateMediaMessageIdentity.isStableID(id) + && !entry.relativePaths.isEmpty + && entry.relativePaths.count <= Self.maximumDeletionPathsPerMessage + && Set(entry.relativePaths).count == entry.relativePaths.count + && entry.relativePaths.allSatisfy { candidatePayload(relativePath: $0) != nil } + }) else { + SecureLogger.error("❌ Invalid legacy private-media deletion journal", category: .session) + return nil + } + for (messageID, entry) in journal.entries { + // Committed journal deletion outranks quarantine. + snapshot.quarantined.remove(messageID) + snapshot.records[messageID] = ReceiptRecord( + kind: .tombstone, + relativePath: nil, + pendingUnlinkPaths: entry.relativePaths, + recordedAt: entry.recordedAt + ) + } + } catch { + SecureLogger.error("❌ Failed to read legacy private-media deletion journal: \(error)", category: .session) + return nil } - } catch { - // The record stays where it is and will be re-quarantined (in - // memory at minimum) by the next scan. Still fail-closed. - SecureLogger.warning( - "⚠️ Failed to move corrupt private-media receipt aside: \(error)", - category: .session - ) + } + + for id in snapshot.quarantined { + snapshot.records.removeValue(forKey: id) + } + return snapshot + } + + // MARK: - Maintenance & Persistence + + private func retryPendingUnlinks(in snapshot: inout LedgerSnapshot, ledgerURL: URL) { + var changed = false + for (messageID, var record) in snapshot.records { + guard record.kind == .tombstone, + let paths = record.pendingUnlinkPaths, + !paths.isEmpty else { + continue + } + let remaining = paths.filter { !removePayload(atRelativePath: $0) } + if remaining != paths { + record.pendingUnlinkPaths = remaining.isEmpty ? nil : remaining + snapshot.records[messageID] = record + changed = true + } + } + if changed, persist(snapshot, to: ledgerURL) { + runtime.snapshot = snapshot } } - private func isStructurallyValid(_ record: ReceiptRecord) -> Bool { - switch record.kind { - case .tombstone: - guard let relativePath = record.relativePath else { return true } - return candidatePayload(relativePath: relativePath) != nil - case .accepted: - guard let relativePath = record.relativePath else { return false } - return candidatePayload(relativePath: relativePath) != nil + private func pruneExpiredAndOverflow(in snapshot: inout LedgerSnapshot, at date: Date) -> Bool { + var changed = false + for (messageID, record) in snapshot.records { + let retainsAccepted = record.kind == .accepted + && record.relativePath.flatMap(existingPayload) != nil + let hasPendingUnlinks = !(record.pendingUnlinkPaths ?? []).isEmpty + if isExpired(record.recordedAt, at: date), !retainsAccepted, !hasPendingUnlinks { + snapshot.records.removeValue(forKey: messageID) + changed = true + } } + + for kind in [ReceiptRecord.Kind.accepted, .tombstone] { + let allMatching = snapshot.records.filter { $0.value.kind == kind } + let overflow = allMatching.count - capacity + guard overflow > 0 else { continue } + let eligible = allMatching.filter { _, record in + if kind == .accepted { + return record.relativePath.flatMap(existingPayload) == nil + } + return (record.pendingUnlinkPaths ?? []).isEmpty + } + let victims = eligible.sorted { lhs, rhs in + lhs.value.recordedAt == rhs.value.recordedAt + ? lhs.key < rhs.key + : lhs.value.recordedAt < rhs.value.recordedAt + }.prefix(overflow).map(\.key) + for victim in victims { + snapshot.records.removeValue(forKey: victim) + changed = true + } + } + return changed + } + + private func enforceTombstoneCapacity( + in snapshot: inout LedgerSnapshot, + preserving preservedIDs: Set + ) { + let tombstones = snapshot.records.filter { $0.value.kind == .tombstone } + let overflow = tombstones.count - capacity + guard overflow > 0 else { return } + let victims = tombstones + .filter { !preservedIDs.contains($0.key) && ($0.value.pendingUnlinkPaths ?? []).isEmpty } + .sorted { lhs, rhs in + lhs.value.recordedAt == rhs.value.recordedAt + ? lhs.key < rhs.key + : lhs.value.recordedAt < rhs.value.recordedAt + } + .prefix(overflow) + .map(\.key) + for victim in victims { + snapshot.records.removeValue(forKey: victim) + } + } + + private func isStructurallyValid(_ snapshot: LedgerSnapshot) -> Bool { + guard snapshot.version == Self.currentVersion else { return false } + for id in snapshot.quarantined where !PrivateMediaMessageIdentity.isStableID(id) { + return false + } + for (id, record) in snapshot.records { + guard PrivateMediaMessageIdentity.isStableID(id) else { return false } + switch record.kind { + case .accepted: + guard let path = record.relativePath, + candidatePayload(relativePath: path) != nil, + record.pendingUnlinkPaths == nil else { + return false + } + case .tombstone: + guard record.relativePath == nil else { return false } + if let pending = record.pendingUnlinkPaths { + guard pending.count <= Self.maximumDeletionPathsPerMessage, + pending.allSatisfy({ candidatePayload(relativePath: $0) != nil }) else { + return false + } + } + } + } + return true } private func isExpired(_ recordedAt: Date, at date: Date) -> Bool { date.timeIntervalSince(recordedAt) > ttl } - private func overflowVictims( - in records: [String: ReceiptRecord] - ) -> [String] { - var victims: [String] = [] - for kind in [ReceiptRecord.Kind.accepted, .tombstone] { - let allMatching = records.filter { $0.value.kind == kind } - let overflow = allMatching.count - capacity - guard overflow > 0 else { continue } - let eligible = allMatching.filter { _, record in - guard kind == .accepted else { return true } - return record.relativePath.flatMap(existingPayload) == nil - } - victims.append(contentsOf: eligible.sorted { lhs, rhs in - if lhs.value.recordedAt == rhs.value.recordedAt { - return lhs.key < rhs.key - } - return lhs.value.recordedAt < rhs.value.recordedAt - } - .prefix(overflow) - .map(\.key)) - } - return victims - } - - /// Accepted receipts and tombstones have independent capacity. High media - /// volume cannot evict explicit deletion intent, and vice versa. - private func capacityVictim( - for incomingKind: ReceiptRecord.Kind, - replacing messageID: String, - in records: [String: ReceiptRecord], - preserving preservedMessageIDs: Set = [] - ) -> String? { - guard records[messageID]?.kind != incomingKind else { return nil } - // During a live session an accepted receipt is the only durable owner - // of its filename, even after quota removes the payload. Evicting it - // here could let another ID reuse the path while the old bubble still - // exists. The large capacity therefore acts as admission control. - guard incomingKind != .accepted else { return nil } - let matching = records.filter { - $0.key != messageID - && !preservedMessageIDs.contains($0.key) - && $0.value.kind == incomingKind - } - let currentCount = records.values.lazy.filter { - $0.kind == incomingKind - }.count - guard currentCount >= capacity else { return nil } - return matching.min { lhs, rhs in - if lhs.value.recordedAt == rhs.value.recordedAt { - return lhs.key < rhs.key - } - return lhs.value.recordedAt < rhs.value.recordedAt - }?.key - } - - private func persist( - _ record: ReceiptRecord, - messageID: String, - to directory: URL - ) -> Bool { + private func persist(_ snapshot: LedgerSnapshot, to ledgerURL: URL) -> Bool { do { try fileManager.createDirectory( - at: directory, + at: ledgerURL.deletingLastPathComponent(), withIntermediateDirectories: true, attributes: nil ) - let data = try JSONEncoder().encode(record) + let data = try JSONEncoder().encode(snapshot) var options: Data.WritingOptions = [.atomic] #if os(iOS) options.insert(.completeFileProtectionUntilFirstUserAuthentication) #endif - let url = recordURL(messageID: messageID, in: directory) - try dataWriter(data, url, options) + try dataWriter(data, ledgerURL, options) return true } catch { - SecureLogger.error( - "❌ Failed to persist private-media receipt \(messageID.prefix(12))…: \(error)", - category: .session - ) + SecureLogger.error("❌ Failed to persist private-media receipt ledger: \(error)", category: .session) return false } } - @discardableResult - private func removeRecord( - messageID: String, - from directory: URL - ) -> Bool { - let url = recordURL(messageID: messageID, in: directory) - guard fileManager.fileExists(atPath: url.path) else { return true } - do { - try fileManager.removeItem(at: url) - return true - } catch { - SecureLogger.warning( - "⚠️ Failed to prune private-media receipt \(messageID.prefix(12))…: \(error)", - category: .session - ) - return false - } - } - - private func recordURL(messageID: String, in directory: URL) -> URL { - directory - .appendingPathComponent(messageID, isDirectory: false) - .appendingPathExtension("json") - } + // MARK: - Path Validation & Payload Unlink @discardableResult private func removePayload(atRelativePath relativePath: String) -> Bool { @@ -1033,24 +644,15 @@ final class BLEPrivateMediaReceiptStore: @unchecked Sendable { fileManager.fileExists(atPath: payload.path) else { return true } - guard let values = try? payload.resourceValues( - forKeys: [.isRegularFileKey] - ), - values.isRegularFile == true else { - SecureLogger.warning( - "⚠️ Refusing to remove non-file private-media payload", - category: .session - ) + guard (try? payload.resourceValues(forKeys: [.isRegularFileKey]).isRegularFile) == true else { + SecureLogger.warning("⚠️ Refusing to remove non-file private-media payload", category: .session) return false } do { try payloadRemover(payload) return !fileManager.fileExists(atPath: payload.path) } catch { - SecureLogger.warning( - "⚠️ Failed to remove explicitly deleted private media: \(error)", - category: .session - ) + SecureLogger.warning("⚠️ Failed to remove explicitly deleted private media: \(error)", category: .session) return false } } @@ -1062,9 +664,7 @@ final class BLEPrivateMediaReceiptStore: @unchecked Sendable { guard fileManager.fileExists(atPath: payload.path) else { return true } - return (try? payload.resourceValues( - forKeys: [.isRegularFileKey] - ).isRegularFile) == true + return (try? payload.resourceValues(forKeys: [.isRegularFileKey]).isRegularFile) == true } private func validExistingPayload(_ url: URL) -> URL? { @@ -1073,10 +673,8 @@ final class BLEPrivateMediaReceiptStore: @unchecked Sendable { return nil } var isDirectory: ObjCBool = false - guard fileManager.fileExists( - atPath: standardized.path, - isDirectory: &isDirectory - ), !isDirectory.boolValue else { + guard fileManager.fileExists(atPath: standardized.path, isDirectory: &isDirectory), + !isDirectory.boolValue else { return nil } return standardized @@ -1116,16 +714,16 @@ final class BLEPrivateMediaReceiptStore: @unchecked Sendable { guard (try? filesDirectory()) != nil else { return false } - let parentPath = url.standardizedFileURL - .deletingLastPathComponent().path + let parentPath = url.standardizedFileURL.deletingLastPathComponent().path return runtime.cachedIncomingDirectoryPaths.contains(parentPath) } - private func resolvedReceiptDirectory() -> URL? { - return try? filesDirectory().appendingPathComponent( - Self.receiptDirectoryName, - isDirectory: true - ) + private func resolvedLedgerURL() -> URL? { + try? filesDirectory().appendingPathComponent(Self.ledgerFileName, isDirectory: false) + } + + private func resolvedLegacyReceiptDirectory() -> URL? { + try? filesDirectory().appendingPathComponent(Self.legacyReceiptDirectoryName, isDirectory: true) } private func filesDirectory() throws -> URL { @@ -1139,11 +737,7 @@ final class BLEPrivateMediaReceiptStore: @unchecked Sendable { create: true ) let files = root.appendingPathComponent("files", isDirectory: true) - try fileManager.createDirectory( - at: files, - withIntermediateDirectories: true, - attributes: nil - ) + try fileManager.createDirectory(at: files, withIntermediateDirectories: true, attributes: nil) let standardizedFiles = files.standardizedFileURL runtime.cachedFilesRoot = standardizedFiles runtime.cachedIncomingDirectoryPaths = Set([ @@ -1151,9 +745,7 @@ final class BLEPrivateMediaReceiptStore: @unchecked Sendable { "images/incoming", "files/incoming" ].map { - standardizedFiles - .appendingPathComponent($0, isDirectory: true) - .standardizedFileURL.path + standardizedFiles.appendingPathComponent($0, isDirectory: true).standardizedFileURL.path }) return standardizedFiles } diff --git a/bitchat/Services/BLE/BLEPublicMessageHandler.swift b/bitchat/Services/BLE/BLEPublicMessageHandler.swift index 7c95bf72..fede06d8 100644 --- a/bitchat/Services/BLE/BLEPublicMessageHandler.swift +++ b/bitchat/Services/BLE/BLEPublicMessageHandler.swift @@ -144,3 +144,50 @@ final class BLEPublicMessageHandler { return true } } + + +// MARK: - Public Message Acceptance Policy + +struct BLEPublicMessageAcceptance: Equatable { + let shouldTrackForSync: Bool +} + +enum BLEPublicMessageRejection: Equatable { + case selfEcho + case staleBroadcast(ageSeconds: Double) +} + +enum BLEPublicMessageDecision: Equatable { + case accept(BLEPublicMessageAcceptance) + case reject(BLEPublicMessageRejection) +} + +enum BLEPublicMessagePolicy { + static func evaluate( + packet: BitchatPacket, + from peerID: PeerID, + localPeerID: PeerID, + now: Date + ) -> BLEPublicMessageDecision { + if peerID == localPeerID && packet.ttl != 0 { + return .reject(.selfEcho) + } + + let isBroadcast = BLEPacketFreshnessPolicy.isBroadcastRecipient(packet.recipientID) + if isBroadcast, + BLEPacketFreshnessPolicy.isStale( + timestampMilliseconds: packet.timestamp, + now: now, + maxAgeSeconds: TransportConfig.syncPublicMessageMaxAgeSeconds + ) { + return .reject(.staleBroadcast(ageSeconds: BLEPacketFreshnessPolicy.ageSeconds( + timestampMilliseconds: packet.timestamp, + now: now + ))) + } + + return .accept(BLEPublicMessageAcceptance( + shouldTrackForSync: isBroadcast && packet.type == MessageType.message.rawValue + )) + } +} diff --git a/bitchat/Services/BLE/BLEPublicMessagePolicy.swift b/bitchat/Services/BLE/BLEPublicMessagePolicy.swift deleted file mode 100644 index 9a0bc965..00000000 --- a/bitchat/Services/BLE/BLEPublicMessagePolicy.swift +++ /dev/null @@ -1,49 +0,0 @@ -import BitFoundation -import Foundation - -struct BLEPublicMessageAcceptance: Equatable { - let shouldTrackForSync: Bool -} - -enum BLEPublicMessageRejection: Equatable { - case selfEcho - case staleBroadcast(ageSeconds: Double) -} - -enum BLEPublicMessageDecision: Equatable { - case accept(BLEPublicMessageAcceptance) - case reject(BLEPublicMessageRejection) -} - -enum BLEPublicMessagePolicy { - static func evaluate( - packet: BitchatPacket, - from peerID: PeerID, - localPeerID: PeerID, - now: Date - ) -> BLEPublicMessageDecision { - if peerID == localPeerID && packet.ttl != 0 { - return .reject(.selfEcho) - } - - let isBroadcast = BLEPacketFreshnessPolicy.isBroadcastRecipient(packet.recipientID) - // Acceptance window matches the gossip-sync serving window: a peer - // walking between partitions carries hours of public history, so the - // receive side must not drop what sync legitimately serves. - if isBroadcast, - BLEPacketFreshnessPolicy.isStale( - timestampMilliseconds: packet.timestamp, - now: now, - maxAgeSeconds: TransportConfig.syncPublicMessageMaxAgeSeconds - ) { - return .reject(.staleBroadcast(ageSeconds: BLEPacketFreshnessPolicy.ageSeconds( - timestampMilliseconds: packet.timestamp, - now: now - ))) - } - - return .accept(BLEPublicMessageAcceptance( - shouldTrackForSync: isBroadcast && packet.type == MessageType.message.rawValue - )) - } -} diff --git a/bitchat/Services/BLE/BLERadioController.swift b/bitchat/Services/BLE/BLERadioController.swift index eb89338b..9f3418cf 100644 --- a/bitchat/Services/BLE/BLERadioController.swift +++ b/bitchat/Services/BLE/BLERadioController.swift @@ -473,3 +473,98 @@ private extension CBPeripheralState { } } } + + +// MARK: - Scan Duty Policy + +enum BLEScanDutyPlan: Equatable { + case continuous + case dutyCycle(onDuration: TimeInterval, offDuration: TimeInterval) +} + +enum BLEScanDutyPolicy { + static func plan( + appIsActive: Bool, + connectedCount: Int, + hasRecentTraffic: Bool, + highDegreeThreshold: Int = TransportConfig.bleHighDegreeThreshold, + lowPowerMode: Bool = false + ) -> BLEScanDutyPlan { + if lowPowerMode && appIsActive && !hasRecentTraffic { + if connectedCount >= highDegreeThreshold { + return .dutyCycle(onDuration: 2.0, offDuration: 20.0) + } + return .dutyCycle( + onDuration: TransportConfig.bleDutyOnDurationDense, + offDuration: TransportConfig.bleDutyOffDurationDense + ) + } + + let forceContinuousScan = connectedCount <= 2 || hasRecentTraffic + let shouldDutyCycle = appIsActive && connectedCount > 0 && !forceContinuousScan + + guard shouldDutyCycle else { + return .continuous + } + + if connectedCount >= highDegreeThreshold { + return .dutyCycle( + onDuration: TransportConfig.bleDutyOnDurationDense, + offDuration: TransportConfig.bleDutyOffDurationDense + ) + } + + return .dutyCycle( + onDuration: TransportConfig.bleDutyOnDuration, + offDuration: TransportConfig.bleDutyOffDuration + ) + } +} + +// MARK: - Recent Peripheral Cache + +/// Remembers recently seen bitchat peripherals so pending background connects +/// can be armed when the app leaves the foreground. +final class BLERecentPeripheralCache { + private struct Entry { + let peripheral: Peripheral + var lastSeen: Date + } + + private var entries: [String: Entry] = [:] + private let capacity: Int + private let maxAge: TimeInterval + + init( + capacity: Int = TransportConfig.bleRecentPeripheralCacheCap, + maxAge: TimeInterval = TransportConfig.bleRecentPeripheralMaxAgeSeconds + ) { + self.capacity = capacity + self.maxAge = maxAge + } + + var count: Int { entries.count } + + func record(_ peripheral: Peripheral, peripheralID: String, at now: Date) { + entries[peripheralID] = Entry(peripheral: peripheral, lastSeen: now) + guard entries.count > capacity else { return } + if let stalest = entries.min(by: { $0.value.lastSeen < $1.value.lastSeen }) { + entries.removeValue(forKey: stalest.key) + } + } + + func reconnectTargets( + now: Date, + limit: Int, + excluding: (String) -> Bool + ) -> [(peripheralID: String, peripheral: Peripheral)] { + let cutoff = now.addingTimeInterval(-maxAge) + entries = entries.filter { $0.value.lastSeen >= cutoff } + guard limit > 0 else { return [] } + return entries + .filter { !excluding($0.key) } + .sorted { $0.value.lastSeen > $1.value.lastSeen } + .prefix(limit) + .map { (peripheralID: $0.key, peripheral: $0.value.peripheral) } + } +} diff --git a/bitchat/Services/BLE/BLEReceivePipeline.swift b/bitchat/Services/BLE/BLEReceivePipeline.swift index 1b175d49..9b6c8fd9 100644 --- a/bitchat/Services/BLE/BLEReceivePipeline.swift +++ b/bitchat/Services/BLE/BLEReceivePipeline.swift @@ -155,3 +155,32 @@ struct BLERecentTrafficTracker: Equatable { lhs.packetTimestamps[lhs.head...].elementsEqual(rhs.packetTimestamps[rhs.head...]) } } + + +// MARK: - Packet Freshness Policy + +enum BLEPacketFreshnessPolicy { + static let defaultMaxAgeSeconds: TimeInterval = 900 + + static func isBroadcastRecipient(_ recipientID: Data?) -> Bool { + guard let recipientID else { return true } + return recipientID.count == 8 && recipientID.allSatisfy { $0 == 0xFF } + } + + static func isStale( + timestampMilliseconds: UInt64, + now: Date, + maxAgeSeconds: TimeInterval = defaultMaxAgeSeconds + ) -> Bool { + let nowMilliseconds = UInt64(now.timeIntervalSince1970 * 1000) + let maxAgeMilliseconds = UInt64(maxAgeSeconds * 1000) + guard nowMilliseconds >= maxAgeMilliseconds else { return false } + return timestampMilliseconds < nowMilliseconds - maxAgeMilliseconds + } + + static func ageSeconds(timestampMilliseconds: UInt64, now: Date) -> Double { + let nowMilliseconds = UInt64(now.timeIntervalSince1970 * 1000) + guard nowMilliseconds >= timestampMilliseconds else { return 0 } + return Double(nowMilliseconds - timestampMilliseconds) / 1000.0 + } +} diff --git a/bitchat/Services/BLE/BLERecentPeripheralCache.swift b/bitchat/Services/BLE/BLERecentPeripheralCache.swift deleted file mode 100644 index 1f7819fd..00000000 --- a/bitchat/Services/BLE/BLERecentPeripheralCache.swift +++ /dev/null @@ -1,53 +0,0 @@ -import Foundation - -/// Remembers recently seen bitchat peripherals (fresh discoveries and dropped -/// links) so the service can arm pending background connections against them -/// when the app leaves the foreground. Generic over the peripheral type so -/// the eviction/expiry logic is testable without CoreBluetooth. -final class BLERecentPeripheralCache { - private struct Entry { - let peripheral: Peripheral - var lastSeen: Date - } - - private var entries: [String: Entry] = [:] - private let capacity: Int - private let maxAge: TimeInterval - - init( - capacity: Int = TransportConfig.bleRecentPeripheralCacheCap, - maxAge: TimeInterval = TransportConfig.bleRecentPeripheralMaxAgeSeconds - ) { - self.capacity = capacity - self.maxAge = maxAge - } - - var count: Int { entries.count } - - func record(_ peripheral: Peripheral, peripheralID: String, at now: Date) { - entries[peripheralID] = Entry(peripheral: peripheral, lastSeen: now) - guard entries.count > capacity else { return } - // Inserts overshoot capacity by at most one; evict the stalest entry - if let stalest = entries.min(by: { $0.value.lastSeen < $1.value.lastSeen }) { - entries.removeValue(forKey: stalest.key) - } - } - - /// Most-recently-seen peripherals eligible for a pending background - /// connect, freshest first, capped at `limit`. Expired entries are - /// pruned as a side effect. - func reconnectTargets( - now: Date, - limit: Int, - excluding: (String) -> Bool - ) -> [(peripheralID: String, peripheral: Peripheral)] { - let cutoff = now.addingTimeInterval(-maxAge) - entries = entries.filter { $0.value.lastSeen >= cutoff } - guard limit > 0 else { return [] } - return entries - .filter { !excluding($0.key) } - .sorted { $0.value.lastSeen > $1.value.lastSeen } - .prefix(limit) - .map { (peripheralID: $0.key, peripheral: $0.value.peripheral) } - } -} diff --git a/bitchat/Services/BLE/BLERouteForwardingPolicy.swift b/bitchat/Services/BLE/BLERouteForwardingPolicy.swift deleted file mode 100644 index aa12f7e0..00000000 --- a/bitchat/Services/BLE/BLERouteForwardingPolicy.swift +++ /dev/null @@ -1,101 +0,0 @@ -import BitFoundation -import Foundation - -struct BLERouteForwardingPlan { - let shouldSuppressFloodRelay: Bool - let forwardPacket: BitchatPacket? - let nextHop: PeerID? - - static let allowFloodRelay = BLERouteForwardingPlan( - shouldSuppressFloodRelay: false, - forwardPacket: nil, - nextHop: nil - ) - - static let suppressFloodRelay = BLERouteForwardingPlan( - shouldSuppressFloodRelay: true, - forwardPacket: nil, - nextHop: nil - ) - - static func forward(_ packet: BitchatPacket, to nextHop: PeerID) -> BLERouteForwardingPlan { - BLERouteForwardingPlan( - shouldSuppressFloodRelay: true, - forwardPacket: packet, - nextHop: nextHop - ) - } -} - -struct BLERouteForwardingPolicy { - static func plan( - for packet: BitchatPacket, - localPeerID: PeerID, - localRoutingData: Data?, - routingPeer: (Data) -> PeerID?, - isPeerConnected: (PeerID) -> Bool - ) -> BLERouteForwardingPlan { - // REQUEST_SYNC is link-local: never forward it, on the flood path or - // the source-routed path. A crafted request with a route and TTL - // headroom must not be able to fan a full-store replay out to the next - // hop. Suppressing here also short-circuits the flood relay. - if packet.type == MessageType.requestSync.rawValue { - return .suppressFloodRelay - } - - if PeerID(hexData: packet.recipientID) == localPeerID { - return .suppressFloodRelay - } - - guard let route = packet.route, !route.isEmpty else { - return .allowFloodRelay - } - - guard packet.ttl > 1 else { - return .suppressFloodRelay - } - - guard let localRoutingData else { - return .allowFloodRelay - } - - guard let localIndex = route.firstIndex(of: localRoutingData) else { - return forward(packet, toRouteData: route[0], routingPeer: routingPeer, isPeerConnected: isPeerConnected) - } - - if localIndex == route.count - 1 { - guard let destinationPeer = PeerID(hexData: packet.recipientID), - isPeerConnected(destinationPeer) else { - return .allowFloodRelay - } - return .forward(relayed(packet), to: destinationPeer) - } - - return forward( - packet, - toRouteData: route[localIndex + 1], - routingPeer: routingPeer, - isPeerConnected: isPeerConnected - ) - } - - private static func forward( - _ packet: BitchatPacket, - toRouteData routeData: Data, - routingPeer: (Data) -> PeerID?, - isPeerConnected: (PeerID) -> Bool - ) -> BLERouteForwardingPlan { - guard let nextPeer = routingPeer(routeData), - isPeerConnected(nextPeer) else { - return .allowFloodRelay - } - - return .forward(relayed(packet), to: nextPeer) - } - - private static func relayed(_ packet: BitchatPacket) -> BitchatPacket { - var relayPacket = packet - relayPacket.ttl = packet.ttl - 1 - return relayPacket - } -} diff --git a/bitchat/Services/BLE/BLEScanDutyPolicy.swift b/bitchat/Services/BLE/BLEScanDutyPolicy.swift deleted file mode 100644 index 4aacac74..00000000 --- a/bitchat/Services/BLE/BLEScanDutyPolicy.swift +++ /dev/null @@ -1,50 +0,0 @@ -import Foundation - -enum BLEScanDutyPlan: Equatable { - case continuous - case dutyCycle(onDuration: TimeInterval, offDuration: TimeInterval) -} - -enum BLEScanDutyPolicy { - static func plan( - appIsActive: Bool, - connectedCount: Int, - hasRecentTraffic: Bool, - highDegreeThreshold: Int = TransportConfig.bleHighDegreeThreshold, - lowPowerMode: Bool = false - ) -> BLEScanDutyPlan { - // Under Low Power Mode, duty-cycle aggressively even with 0-2 peers - // whenever there is no active traffic burst so the BLE radio sleeps ~85-90% of the time. - if lowPowerMode && appIsActive && !hasRecentTraffic { - if connectedCount >= highDegreeThreshold { - return .dutyCycle( - onDuration: 2.0, - offDuration: 20.0 - ) - } - return .dutyCycle( - onDuration: TransportConfig.bleDutyOnDurationDense, - offDuration: TransportConfig.bleDutyOffDurationDense - ) - } - - let forceContinuousScan = connectedCount <= 2 || hasRecentTraffic - let shouldDutyCycle = appIsActive && connectedCount > 0 && !forceContinuousScan - - guard shouldDutyCycle else { - return .continuous - } - - if connectedCount >= highDegreeThreshold { - return .dutyCycle( - onDuration: TransportConfig.bleDutyOnDurationDense, - offDuration: TransportConfig.bleDutyOffDurationDense - ) - } - - return .dutyCycle( - onDuration: TransportConfig.bleDutyOnDuration, - offDuration: TransportConfig.bleDutyOffDuration - ) - } -} diff --git a/bitchat/Services/BLE/BLEService+Courier.swift b/bitchat/Services/BLE/BLEService+Courier.swift new file mode 100644 index 00000000..e0ba31a3 --- /dev/null +++ b/bitchat/Services/BLE/BLEService+Courier.swift @@ -0,0 +1,571 @@ +import BitFoundation +import BitLogger +import Foundation + +// MARK: - Courier Store-and-Forward, Prekey Bundles & Gateway Carrier + +extension BLEService { + // MARK: Courier Store-and-Forward + + /// Seal `content` for the recipient and hand the envelope to the given + /// couriers for physical delivery. When a verified one-time prekey bundle + /// is cached for the recipient, sealing targets one of its prekeys + /// (forward secret, envelope v2); otherwise it falls back to their static + /// key (one-way Noise X, v1) exactly as before. Returns false when no + /// courier is connected, the payload cannot be built, or sealing fails; + /// link writes are queued asynchronously after the envelope is ready. + private func sealCourierEnvelope( + _ content: String, + messageID: String, + recipientNoiseKey: Data, + copies: UInt8 + ) -> CourierEnvelope? { + guard let typedPayload = BLENoisePayloadFactory.privateMessage(content: content, messageID: messageID) else { + return nil + } + do { + let now = Date() + let sealed: Data + let prekeyID: UInt32? + if let prekey = assignRecipientPrekey(messageID: messageID, recipientNoiseKey: recipientNoiseKey) { + sealed = try noiseService.sealPrekeyPayload(typedPayload, recipientPrekey: prekey) + prekeyID = prekey.id + } else { + sealed = try noiseService.sealCourierPayload(typedPayload, recipientStaticKey: recipientNoiseKey) + prekeyID = nil + } + return CourierEnvelope( + recipientTag: CourierEnvelope.recipientTag( + noiseStaticKey: recipientNoiseKey, + epochDay: CourierEnvelope.epochDay(for: now) + ), + expiry: UInt64((now.timeIntervalSince1970 + CourierEnvelope.maxLifetimeSeconds) * 1000), + ciphertext: sealed, + copies: copies, + prekeyID: prekeyID + ) + } catch { + SecureLogger.error("Failed to seal courier envelope: \(error)", category: .encryption) + return nil + } + } + + func sendCourierMessage(_ content: String, messageID: String, recipientNoiseKey: Data, via couriers: [PeerID]) -> Bool { + let connected = couriers.filter { isPeerConnected($0) } + guard !connected.isEmpty, + let envelope = sealCourierEnvelope( + content, + messageID: messageID, + recipientNoiseKey: recipientNoiseKey, + copies: TransportConfig.courierInitialCopies + ), + let payload = envelope.encode() else { + return false + } + + messageQueue.async { [weak self] in + guard let self else { return } + for courier in connected { + SecureLogger.debug("📦 Depositing courier envelope with \(courier.id.prefix(8))… id=\(messageID.prefix(8))…", category: .session) + self.sendPacketDirected(self.makeCourierPacket(payload, to: courier), to: courier) + } + } + return true + } + + // MARK: Courier over the bridge + + /// Seals `content` into a courier envelope for relay parking (a bridge + /// courier drop). Same sealing rules as `sendCourierMessage` — prekey + /// (v2) when a verified bundle is cached, static Noise X (v1) otherwise — + /// but carry-only: a relay copy never sprays. + func sealBridgeCourierEnvelope(_ content: String, messageID: String, recipientNoiseKey: Data) -> CourierEnvelope? { + sealCourierEnvelope(content, messageID: messageID, recipientNoiseKey: recipientNoiseKey, copies: 1) + } + + /// Opens a courier envelope that arrived as a bridge drop (relay fetch, + /// not a directed mesh packet). Returns false when the rotating tag does + /// not match our static key — a drop for someone else, or a stale tag. + /// The inner Noise X seal authenticates the sender; there is no packet + /// signature to check on this path. + @discardableResult + func openBridgedCourierEnvelope(_ envelope: CourierEnvelope) -> Bool { + guard !envelope.isExpired else { return false } + let myKey = noiseService.getStaticPublicKeyData() + guard CourierEnvelope.candidateTags(noiseStaticKey: myKey, around: Date()).contains(envelope.recipientTag) else { + return false + } + return openCourierEnvelope(envelope) + } + + /// Hands a bridge-fetched envelope directly to the matching local peer + /// as a directed courier packet. Delivery-only by design: the recipient's + /// tag matched, so this never lands in a stranger's carry quota. + /// Returns true only if a current Noise-authenticated physical link + /// accepted the packet; a stale peer-level session, reachability record, + /// replay-rebound link, or process-local spool is not delivery. + @discardableResult + func deliverBridgedEnvelope(_ envelope: CourierEnvelope, to peerID: PeerID) -> Bool { + guard let payload = envelope.encode() else { return false } + let packet = makeCourierPacket(payload, to: peerID) + return onEngine { + // Engine slot: the auth-link check and the directed send see one + // consistent view of the identity domain. + guard hasCurrentNoiseAuthenticatedLink(to: peerID) else { return false } + return sendPacketDirected( + packet, + to: peerID, + requireDirectPeerLink: true, + requireNoiseAuthenticatedPeerLink: true + ) + } + } + + /// Verified reachable peers with known Noise keys — the set a bridge + /// gateway watches courier drops for. + func verifiedPeersWithNoiseKeys() -> [(peerID: PeerID, noiseKey: Data)] { + let now = Date() + return onEngine { + peerRegistry.snapshotByID.values.compactMap { info in + guard info.isVerifiedNickname, + let key = info.noisePublicKey, + peerRegistry.isReachable(info.peerID, now: now) else { return nil } + return (info.peerID, key) + } + } + } + + /// The prekey to seal a courier message with, or nil to fall back to + /// static sealing. The real signal is a verified, unexpired bundle with a + /// spare prekey; the advertised `.prekeys` capability only acts as a veto + /// for peers we currently see on the mesh (a cached bundle can outlive a + /// peer's downgrade to a build that no longer holds the privates). + /// Re-deposits of the same message reuse its assigned prekey, so one + /// message consumes exactly one prekey ID regardless of courier count. + private func assignRecipientPrekey(messageID: String, recipientNoiseKey: Data) -> PrekeyBundle.Prekey? { + let shortID = PeerID(publicKey: recipientNoiseKey) + let knownOnMesh = peerRegistry.info(for: shortID) != nil + if knownOnMesh, !peerCapabilities(shortID).contains(.prekeys) { + return nil + } + return prekeyBundleStore.assignPrekey(messageID: messageID, recipientNoiseKey: recipientNoiseKey) + } + + private func makeCourierPacket(_ payload: Data, to peerID: PeerID) -> BitchatPacket { + let packet = BitchatPacket( + type: MessageType.courierEnvelope.rawValue, + senderID: myPeerIDData, + recipientID: Data(hexString: peerID.id), + timestamp: UInt64(Date().timeIntervalSince1970 * 1000), + payload: payload, + signature: nil, + ttl: messageTTL + ) + // Signed so a courier can authenticate the depositor before carrying + // mail under their quota. Handover to the recipient doesn't need the + // packet signature — the inner Noise X seal authenticates the sender. + return noiseService.signPacket(packet) ?? packet + } + + /// Handles both courier roles for an incoming envelope addressed to us: + /// recipient (the rotating tag matches our static key → open and deliver) + /// or courier (a trusted peer is depositing mail for someone else → store). + func handleCourierEnvelope(_ packet: BitchatPacket, from peerID: PeerID) { + // Directed packets only; envelopes addressed elsewhere ride the + // generic relay path untouched. + guard packet.recipientID == myPeerIDData else { return } + guard let envelope = CourierEnvelope.decode(packet.payload), !envelope.isExpired else { return } + + let myKey = noiseService.getStaticPublicKeyData() + if CourierEnvelope.candidateTags(noiseStaticKey: myKey, around: Date()).contains(envelope.recipientTag) { + openCourierEnvelope(envelope) + } else { + acceptCourierDeposit(envelope, from: peerID, packet: packet) + } + } + + @discardableResult + private func openCourierEnvelope(_ envelope: CourierEnvelope) -> Bool { + do { + let typedPayload: Data + let senderStaticKey: Data + if let prekeyID = envelope.prekeyID { + // Envelope v2: sealed to one of our one-time prekeys. Opening + // consumes the prekey (48h redelivery grace), which shrinks our + // published bundle under a strictly newer generatedAt. Re-gossip + // so peers replace their cached copy and stop assigning the + // consumed ID before the grace lapses; force the broadcast when + // the batch also topped back up (low-water), otherwise let the + // rebroadcast throttle coalesce bursts. + let opened = try noiseService.openPrekeyPayload(envelope.ciphertext, prekeyID: prekeyID) + (typedPayload, senderStaticKey) = (opened.payload, opened.senderStaticKey) + if opened.consumedPrekey { + let replenished = noiseService.replenishPrekeysIfNeeded() + sendPrekeyBundle(force: replenished) + } + } else { + (typedPayload, senderStaticKey) = try noiseService.openCourierPayload(envelope.ciphertext) + } + guard let typeRaw = typedPayload.first, + let payloadType = NoisePayloadType(rawValue: typeRaw), + payloadType == .privateMessage else { + SecureLogger.warning("⚠️ Courier envelope carried unsupported payload type", category: .session) + return true // decrypted but deterministically unsupported + } + let payload = Data(typedPayload.dropFirst()) + guard let innerMessageID = PrivateMessagePacket.decode(from: payload)?.messageID else { + SecureLogger.warning("⚠️ Courier envelope carried undecodable private message", category: .session) + return true // decrypted but deterministically malformed + } + // Redundant copies of one message arrive as distinct envelopes + // (fresh seal each: mesh couriers, bridge drops across relays), + // so dedup here on the inner message ID — before delivery, ack, + // and handshake work. A duplicate costs only the decrypt above + // and at most one ack ever goes out per message ID. + let firstOpen = onEngine { + openedCourierMessageIDs.insert(innerMessageID) + } + guard firstOpen else { + SecureLogger.debug("📦 Dropping duplicate courier envelope for message \(innerMessageID.prefix(8))…", category: .session) + return true + } + // Couriered mail arrives while the sender is absent, so the UI's + // block check can't resolve their fingerprint from a live session. + // Gate here, where the full static key is in hand. + guard !identityManager.isBlocked(fingerprint: senderStaticKey.sha256Fingerprint()) else { + SecureLogger.debug("🚫 Dropping courier envelope from blocked sender", category: .security) + return true + } + // A present sender resolves to their live mesh thread via the + // derived short ID. An absent sender — the usual courier case — + // uses the full noise-key ID so the message lands on the stable + // favorite conversation instead of an unresolvable short-ID + // thread labeled "Unknown". + let shortID = PeerID(publicKey: senderStaticKey) + let isKnownOnMesh = peerRegistry.info(for: shortID) != nil + let senderPeerID = isKnownOnMesh ? shortID : PeerID(hexData: senderStaticKey) + SecureLogger.debug("📦 Opened courier envelope from \(senderPeerID.id.prefix(8))…", category: .session) + notifyUI { [weak self] in + self?.deliverTransportEvent(.noisePayloadReceived( + peerID: senderPeerID, + type: payloadType, + payload: payload, + timestamp: Date() + )) + } + return true + } catch { + // Tag collision or stale key: not addressed to us after all. + SecureLogger.debug("📦 Courier envelope failed to open: \(error)", category: .encryption) + return false + } + } + + private func acceptCourierDeposit(_ envelope: CourierEnvelope, from peerID: PeerID, packet: BitchatPacket) { + // A deposit must come from its depositor over the direct link: the + // claimed sender has to be the ingress peer, and the packet signature + // has to verify against that peer's announced signing key. Otherwise + // an untrusted sender could route an envelope through any trusted + // neighbor and have us carry it under the neighbor's quota. + guard PeerID(hexData: packet.senderID) == peerID else { + SecureLogger.debug("📦 Courier deposit rejected: relayed envelope claims sender \(PeerID(hexData: packet.senderID).id.prefix(8))… but arrived from \(peerID.id.prefix(8))…", category: .security) + return + } + let depositorInfo = peerRegistry.info(for: peerID) + guard let depositorKey = depositorInfo?.noisePublicKey else { + SecureLogger.debug("📦 Courier deposit from unknown peer \(peerID.id.prefix(8))… rejected", category: .session) + return + } + guard let signingKey = depositorInfo?.signingPublicKey, + noiseService.verifyPacketSignature(packet, publicKey: signingKey) else { + SecureLogger.debug("📦 Courier deposit from \(peerID.id.prefix(8))… rejected (missing/invalid signature)", category: .security) + return + } + let isVerifiedPeer = depositorInfo?.isVerifiedNickname ?? false + let store = courierStore + let policy = courierDepositPolicy + notifyUI { [weak self] in + guard let self else { return } + guard let tier = policy(depositorKey, isVerifiedPeer) else { + SecureLogger.debug("📦 Courier deposit from \(peerID.id.prefix(8))… rejected (neither favorite nor verified)", category: .session) + return + } + self.messageQueue.async { + if store.deposit(envelope, from: depositorKey, tier: tier) { + SecureLogger.debug("📦 Carrying courier envelope deposited by \(peerID.id.prefix(8))… (\(tier.rawValue))", category: .session) + } + } + } + } + + /// Hand over any carried envelopes addressed to a peer we just heard from. + func deliverCourierMail(to peerID: PeerID, noiseKey: Data) { + let accepted = courierStore.handoverEnvelopes(for: noiseKey) { [weak self] envelope in + guard let self, + let payload = envelope.encode(), + self.sendPacketDirected( + self.makeCourierPacket(payload, to: peerID), + to: peerID, + requireDirectPeerLink: true, + requireNoiseAuthenticatedPeerLink: true + ) else { + return false + } + return true + } + if accepted > 0 { + SecureLogger.debug("📦 Handed over \(accepted) courier envelope(s) to \(peerID.id.prefix(8))…", category: .session) + } + } + + /// Speculative handover toward a recipient heard only via a relayed + /// announce: the envelope floods the mesh as a directed packet (relays + /// treat it like a directed DM). Non-destructive — the carried copy stays + /// until a direct handover or expiry, throttled per envelope so repeated + /// announces don't re-flood. + func deliverCourierMailRemotely(to peerID: PeerID, noiseKey: Data) { + let envelopes = courierStore.envelopesForRemoteHandover( + recipientNoiseKey: noiseKey, + cooldown: TransportConfig.courierRemoteHandoverCooldownSeconds + ) + guard !envelopes.isEmpty else { return } + SecureLogger.debug("📦 Remote handover: flooding \(envelopes.count) envelope(s) toward \(peerID.id.prefix(8))…", category: .session) + for envelope in envelopes { + guard let payload = envelope.encode() else { continue } + broadcastPacket(makeCourierPacket(payload, to: peerID)) + } + } + + /// Spray-and-wait: split copy budgets with another courier we just + /// encountered, so carried mail diffuses through a moving crowd instead + /// of riding a single carrier. Only favorites and verified peers qualify, + /// mirroring the deposit policy they would apply to us. + func sprayCourierMail(to peerID: PeerID, noiseKey: Data, isVerifiedPeer: Bool) { + let store = courierStore + let sendSpray: () -> Void = { [weak self] in + guard let self else { return } + let accepted = store.transferSprayCopies(to: noiseKey) { envelope in + guard let payload = envelope.encode(), + self.sendPacketDirected( + self.makeCourierPacket(payload, to: peerID), + to: peerID, + requireDirectPeerLink: true, + requireNoiseAuthenticatedPeerLink: true + ) else { + return false + } + return true + } + if accepted > 0 { + SecureLogger.debug("📦 Sprayed \(accepted) envelope copy(ies) to courier \(peerID.id.prefix(8))…", category: .session) + } + } + let policy = courierDepositPolicy + notifyUI { [weak self] in + guard let self else { return } + // Same trust gate as deposits: don't hand mail to a peer who + // would reject it from us. + guard policy(noiseKey, isVerifiedPeer) != nil else { return } + self.messageQueue.async { + sendSpray() + } + } + } + + // MARK: One-Time Prekey Bundles + + /// Broadcasts our signed prekey bundle and tracks it for gossip sync. + /// Unforced sends (piggybacked on announces) are throttled — gossip does + /// the spreading, the broadcast just keeps our own gossip entry fresh. + /// Forced sends (bundle changed after consumption) go immediately. + func sendPrekeyBundle(force: Bool = false) { + let now = Date() + let shouldSend: Bool = onEngine { + if !force, + let last = lastPrekeyBundleSentAt, + now.timeIntervalSince(last) < TransportConfig.prekeyBundleRebroadcastSeconds { + return false + } + lastPrekeyBundleSentAt = now + return true + } + guard shouldSend else { return } + guard let bundle = noiseService.currentPrekeyBundle(), + let payload = bundle.encode() else { + SecureLogger.error("❌ Failed to build prekey bundle", category: .security) + return + } + guard let signedPacket = buildSignedBroadcastPacket( + type: .prekeyBundle, + payload: payload, + timestamp: now, + logLabel: "prekey bundle packet" + ) else { return } + if DispatchQueue.getSpecific(key: messageQueueKey) != nil { + broadcastPacket(signedPacket) + } else { + messageQueue.async { [weak self] in + self?.broadcastPacket(signedPacket) + } + } + gossipSyncManager?.onPublicPacketSeen(signedPacket) + } + + /// Ingests a gossiped prekey bundle. Attribution is layered: the outer + /// packet must originate from the bundle owner (fabricated sender IDs, used + /// to multiply cache/gossip entries, are rejected), and BOTH the inner + /// bundle signature and the outer packet signature must verify against the + /// owner's announce-bound signing key. Verifying the outer packet — whose + /// signed bytes cover senderID and timestamp — stops a valid bundle from + /// being replayed under a fresh timestamp or spoofed sender to pass + /// freshness or poison attribution. Only after that does the packet enter + /// our own gossip store, so we never help spread a bundle we couldn't + /// attribute. + @discardableResult + func handlePrekeyBundle(_ packet: BitchatPacket, from peerID: PeerID) -> Bool { + guard let bundle = PrekeyBundle.decode(packet.payload) else { + SecureLogger.debug("🔑 Ignoring malformed prekey bundle from \(peerID.id.prefix(8))…", category: .security) + return false + } + // Our own bundle is tracked at send time; a copy echoing back adds nothing. + guard bundle.noiseStaticPublicKey != noiseService.getStaticPublicKeyData() else { return false } + let owner = PeerID(publicKey: bundle.noiseStaticPublicKey) + // The owner's genuine bundle (direct or relayed) always carries the + // owner's senderID + outer signature; gossip resends preserve both. A + // packet whose senderID isn't the owner can't be authenticated here. + guard PeerID(hexData: packet.senderID) == owner else { + SecureLogger.debug("🔑 Ignoring prekey bundle whose sender ≠ owner \(owner.id.prefix(8))…", category: .security) + return false + } + guard let signingKey = announceBoundSigningKey(forNoiseKey: bundle.noiseStaticPublicKey, owner: owner) else { + // No binding yet: retain the latest bundle per owner, bounded, and + // retry once the verified announce lands (engine-confined on messageQueue). + if pendingPrekeyBundles[owner] != nil + || pendingPrekeyBundles.count < Self.pendingPrekeyBundleCap { + pendingPrekeyBundles[owner] = packet + } + SecureLogger.debug("🔑 Deferring prekey bundle without a bound signing key (owner \(owner.id.prefix(8))…)", category: .security) + return false + } + return ingestVerifiedPrekeyBundle(bundle, packet: packet, owner: owner, signingKey: signingKey) + } + + /// Verify a bundle's inner + outer signatures against the owner's bound + /// signing key and, on success, cache it and let it enter our gossip store. + @discardableResult + private func ingestVerifiedPrekeyBundle(_ bundle: PrekeyBundle, packet: BitchatPacket, owner: PeerID, signingKey: Data) -> Bool { + guard noiseService.verifyPrekeyBundleSignature(bundle, signingPublicKey: signingKey), + noiseService.verifyPacketSignature(packet, publicKey: signingKey) else { + SecureLogger.debug("🔑 Ignoring prekey bundle without verifiable signature (owner \(owner.id.prefix(8))…)", category: .security) + return false + } + if prekeyBundleStore.ingest(bundle) { + SecureLogger.debug("🔑 Cached prekey bundle for \(owner.id.prefix(8))… (\(bundle.prekeys.count) prekeys)", category: .security) + } + gossipSyncManager?.onPublicPacketSeen(packet) + return true + } + + /// Re-attempt any prekey bundle that arrived before this owner's announce + /// bound a signing key. Called from handleAnnounce on messageQueue. + func drainPendingPrekeyBundles(for owner: PeerID) { + guard let packet = pendingPrekeyBundles.removeValue(forKey: owner), + let bundle = PrekeyBundle.decode(packet.payload), + let signingKey = announceBoundSigningKey(forNoiseKey: bundle.noiseStaticPublicKey, owner: owner) else { return } + ingestVerifiedPrekeyBundle(bundle, packet: packet, owner: owner, signingKey: signingKey) + } + + /// Ed25519 signing key bound to a Noise static key by a verified + /// announce: from the live registry when the owner is on the mesh, else + /// from identities persisted for offline verification. + private func announceBoundSigningKey(forNoiseKey noiseKey: Data, owner: PeerID? = nil) -> Data? { + let shortID = owner ?? PeerID(publicKey: noiseKey) + if let info = peerRegistry.info(for: shortID), + info.noisePublicKey == noiseKey, + let signingKey = info.signingPublicKey { + return signingKey + } + for candidate in identityManager.getCryptoIdentitiesByPeerIDPrefix(shortID) + where candidate.publicKey == noiseKey { + if let signingKey = candidate.signingPublicKey { + return signingKey + } + } + return nil + } + + // MARK: Gateway carrier (nostrCarrier) + + /// Sign and send an encoded `toGateway` carrier payload directed at a + /// gateway peer. The packet is signed so the gateway can key its uplink + /// quotas to an authenticated depositor; the carried Nostr event has its + /// own Schnorr signature for content authenticity. Returns false when + /// the gateway is not reachable or signing fails. + func sendNostrCarrier(_ payload: Data, to gatewayPeer: PeerID) -> Bool { + guard isPeerReachable(gatewayPeer) else { return false } + let packet = BitchatPacket( + type: MessageType.nostrCarrier.rawValue, + senderID: myPeerIDData, + recipientID: Data(hexString: gatewayPeer.id), + timestamp: UInt64(Date().timeIntervalSince1970 * 1000), + payload: payload, + signature: nil, + ttl: messageTTL + ) + guard let signed = noiseService.signPacket(packet) else { return false } + messageQueue.async { [weak self] in + // broadcastPacket applies a known route when one exists and + // otherwise floods the directed packet like a DM, so a gateway + // that is reachable but multi-hop still gets the deposit. + self?.broadcastPacket(signed) + } + return true + } + + /// Broadcast an encoded `fromGateway` carrier payload on the mesh with + /// the default TTL. Unsigned at the packet layer — receivers verify the + /// carried event's own Schnorr signature. + func broadcastNostrCarrier(_ payload: Data) { + let packet = BitchatPacket( + type: MessageType.nostrCarrier.rawValue, + senderID: myPeerIDData, + recipientID: nil, + timestamp: UInt64(Date().timeIntervalSince1970 * 1000), + payload: payload, + signature: nil, + ttl: messageTTL + ) + messageQueue.async { [weak self] in + self?.broadcastPacket(packet) + } + } + + /// Transport-level handling for a received nostrCarrier packet; policy + /// (verification of the carried event, quotas, loop prevention) lives in + /// `GatewayService` behind `onNostrCarrierPacket`. + func handleNostrCarrier(_ packet: BitchatPacket, from _: PeerID) { + let senderID = PeerID(hexData: packet.senderID) + let directedToUs: Bool + if let recipientID = packet.recipientID { + // Carriers addressed elsewhere ride the generic relay path untouched. + guard recipientID == myPeerIDData else { return } + // Uplink deposit: quotas are keyed by the depositor, so the + // packet signature must verify against the sender's announced + // signing key. Unlike courier deposits the depositor may be + // multi-hop away, so ingress-link identity is not required. + let signingKey = peerRegistry.info(for: senderID)?.signingPublicKey + guard let signingKey, + noiseService.verifyPacketSignature(packet, publicKey: signingKey) else { + SecureLogger.debug("🌐 nostrCarrier uplink from \(senderID.id.prefix(8))… rejected (missing/invalid packet signature)", category: .security) + return + } + directedToUs = true + } else { + directedToUs = false + } + let payload = packet.payload + notifyUI { [weak self] in + self?.onNostrCarrierPacket?(payload, senderID, directedToUs) + } + } +} diff --git a/bitchat/Services/BLE/BLEService+Diagnostics.swift b/bitchat/Services/BLE/BLEService+Diagnostics.swift new file mode 100644 index 00000000..b72619bc --- /dev/null +++ b/bitchat/Services/BLE/BLEService+Diagnostics.swift @@ -0,0 +1,195 @@ +import BitFoundation +import BitLogger +import Foundation + +// MARK: - Mesh Diagnostics (/ping, /trace, topology map) + +extension BLEService { + /// Sends a directed unencrypted ping probe (8-byte nonce + origin TTL). + /// The completion fires exactly once on the main actor: with RTT/hops + /// when the matching pong returns, or nil after the timeout window. + func sendMeshPing(to peerID: PeerID, completion: @escaping @MainActor (MeshPingResult?) -> Void) { + guard let generation = capturePanicLifecycleGeneration() else { + return + } + messageQueue.async { [weak self] in + guard let self, + self.isCurrentPanicLifecycleGeneration(generation), + let recipientData = peerID.toShort().routingData, + let payload = MeshPingPayload( + nonce: Data((0.. [PeerID]? { + refreshLocalTopology() + if let route = computeRoute(to: peerID) { + return route.compactMap { PeerID(routingData: $0) } + } + // Confirmed claims can lag a brand-new link (the peer's next announce + // hasn't arrived yet); a live direct connection is still a known path. + return isPeerConnected(peerID) ? [] : nil + } + + /// Mesh graph for the topology map. Edges are advisory: announces cap + /// neighbor lists at 10, so an edge claimed by either endpoint counts. + func currentMeshTopology() -> MeshTopologySnapshot? { + refreshLocalTopology() + let claims = meshTopology.adjacencySnapshot() + var nodes = Set() + var edges = Set() + for (source, neighbors) in claims { + guard let sourcePeer = PeerID(routingData: source) else { continue } + nodes.insert(sourcePeer) + for neighborData in neighbors { + guard let neighborPeer = PeerID(routingData: neighborData), + neighborPeer != sourcePeer else { continue } + nodes.insert(neighborPeer) + edges.insert(MeshTopologyEdge(sourcePeer, neighborPeer)) + } + } + nodes.insert(myPeerID) + return MeshTopologySnapshot( + localPeerID: myPeerID, + nodes: nodes.sorted(), + edges: edges.sorted { ($0.a, $0.b) < ($1.a, $1.b) } + ) + } + + func forwardAlongRouteIfNeeded(_ packet: BitchatPacket) -> Bool { + let myRoutingData = routingData(for: myPeerID) ?? (myPeerIDData.isEmpty ? nil : myPeerIDData) + let plan = BLERouteForwardingPolicy.plan( + for: packet, + localPeerID: myPeerID, + localRoutingData: myRoutingData, + routingPeer: routingPeer(from:), + isPeerConnected: isPeerConnected(_:) + ) + + if let forwardPacket = plan.forwardPacket, let nextHop = plan.nextHop { + sendPacketDirected(forwardPacket, to: nextHop) + } + + return plan.shouldSuppressFloodRelay + } +} diff --git a/bitchat/Services/BLE/BLEService+NoiseSession.swift b/bitchat/Services/BLE/BLEService+NoiseSession.swift new file mode 100644 index 00000000..67cb2e24 --- /dev/null +++ b/bitchat/Services/BLE/BLEService+NoiseSession.swift @@ -0,0 +1,500 @@ +import BitFoundation +import BitLogger +import Foundation + +// MARK: - Link Auth & Noise Session Coordination + +extension BLEService { + func links(to peerID: PeerID?) -> Set { + linkBindings.links(to: peerID) + } + + /// Marks the exact physical ingress link that completed a fresh Noise + /// handshake. An old session keyed only by peer ID is insufficient: a + /// replayed announce can rebind an attacker's link to that ID. + /// Engine-confined. + func markNoiseAuthenticatedIngressLink(for packet: BitchatPacket, peerID: PeerID) { + guard let link = ingressLinks.link(for: packet) else { return } + guard linkBindings.boundPeer(for: link) == peerID else { return } + linkAuth.markAuthenticated(link, owner: peerID) + } + + func isNoiseAuthenticatedIngressLink(for packet: BitchatPacket, peerID: PeerID) -> Bool { + guard let link = ingressLinks.link(for: packet) else { return false } + return linkAuth.isAuthenticated(link, for: peerID) && linkBindings.boundPeer(for: link) == peerID + } + + func hasCurrentNoiseAuthenticatedLink(to peerID: PeerID) -> Bool { + !currentNoiseAuthenticatedLinks(to: peerID).isEmpty + } + + func currentNoiseAuthenticatedLinks(to peerID: PeerID) -> Set { + Set(linkAuth.links(ownedBy: peerID).filter { link in + linkBindings.boundPeer(for: link) == peerID + }) + } + + /// A peer-level session can outlive the physical link that established it. + /// Revalidate a fresh direct link with an ordinary XX exchange, retiring + /// cached sending keys atomically before message 1 can leave. + /// + /// Takes the already-resolved ingress link. Engine-confined: it runs + /// inside the rebind's engine slot, so no observer can see the new + /// binding while a cached peer-level sender is still considered + /// established. + func refreshNoiseSessionForVerifiedDirectLink( + link: BLEIngressLinkID, + peerID: PeerID + ) { + let hasEstablishedSession = noiseService.hasEstablishedSession(with: peerID) + let authenticatedPeerLinks = currentNoiseAuthenticatedLinks(to: peerID) + let shouldRevalidate: Bool + if linkBindings.boundPeer(for: link) == peerID { + shouldRevalidate = linkAuth.shouldRevalidate( + on: link, + for: peerID, + hasEstablishedSession: hasEstablishedSession, + hasAuthenticatedPeerLink: !authenticatedPeerLinks.isEmpty, + now: Date() + ) + } else { + shouldRevalidate = false + } + guard shouldRevalidate else { return } + + SecureLogger.info( + "🔄 Revalidating cached Noise session on fresh direct link to \(peerID.id.prefix(8))…", + category: .session + ) + initiateNoiseReconnectHandshake(with: peerID) + } + + 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 + // returning XX message 3. Serialize generation-bound state and + // every post-handshake drain behind the handshake packet handler. + self?.messageQueue.async { [weak self] in + self?.handleNoisePeerAuthenticated( + peerID: peerID, + fingerprint: fingerprint, + sessionGeneration: generation + ) + } + } + service.onRekeyHandshakeReady = { [weak self, weak service] peerID, initiation in + self?.messageQueue.async { [weak self, weak service] in + guard let self, + let service, + self.noiseService === service else { + return + } + self.noteNoiseSessionCleared(for: peerID) + guard let message = service.claimHandshakeInitiation( + initiation, + for: peerID + ) else { + return + } + self.broadcastNoiseHandshake(message, to: peerID) + } + } + service.onHandshakeRecoveryRequired = { [weak self, weak service] request in + guard let self, let service else { return } + #if DEBUG + self._test_beforeHandshakeRecoveryEnqueued?(request.peerID) + #endif + self.messageQueue.async { [weak self, weak service] in + guard let self, + let service, + self.noiseService === service else { + return + } + let peerID = request.peerID + guard self.isPeerReachable(peerID) else { + service.cancelHandshakeRecovery(request) + return + } + + do { + guard let preparation = + try service.prepareHandshakeRecovery(request) else { + return + } + switch preparation { + case .ordinary(let initiation): + self.noteNoiseSessionCleared(for: peerID) + guard let handshakeData = + service.claimHandshakeInitiation( + initiation, + for: peerID + ) else { + return + } + self.broadcastNoiseHandshake( + handshakeData, + to: peerID + ) + case .transferred: + return + } + } catch { + SecureLogger.error( + "Failed to prepare handshake recovery with \(peerID.id.prefix(8))…: \(error)", + category: .session + ) + } + } + } + service.onSessionRestoredWithGeneration = { [weak self, weak service] peerID, generation, reason in + guard let self, let service else { return } + // The manager makes restored keys visible atomically. Reconcile + // transport state and queued sends as the next serialized phase. + self.messageQueue.async { [weak self, weak service] in + guard let self, + let service, + self.noiseService === service, + let fingerprint = service.getPeerFingerprint(peerID) else { + return + } + SecureLogger.debug( + "🔐 Restored quarantined Noise session with \(peerID.id.prefix(8))…", + category: .session + ) + // Re-enter the same generation-bound transition used after a + // successful handshake to restore authenticated protocol + // state. Only a terminal restore may also drain the PM and + // typed-payload queues: after a responder timeout the + // counterpart may have completed the replacement handshake + // and discarded the restored keys, so encrypting the queues + // under them would lose every message silently. The mandatory + // convergence retry that accompanies the restore drains them + // under the new session instead (any establishment does). + self.handleNoisePeerAuthenticated( + peerID: peerID, + fingerprint: fingerprint, + sessionGeneration: generation, + deferOutboundUntilConvergence: reason == .pendingConvergence + ) + } + } + } + + func handleNoisePeerAuthenticated( + peerID: PeerID, + fingerprint: String, + sessionGeneration generation: UUID, + deferOutboundUntilConvergence: Bool = false + ) { + // Engine-only: the store transition below runs inside the noise + // manager's critical section while this engine slot stays blocked. + // The store is a leaf lock, so that nesting is safe — but nothing in + // that closure may sync-re-enter the engine (self-deadlock). + #if DEBUG + dispatchPrecondition(condition: .onQueue(messageQueue)) + #endif + let normalizedPeerID = peerID.toShort() + // The generation lease serializes this transition against session + // replacement; nil-inside-nil distinguishes a lost lease (outer) + // from the same-generation reconciliation path (inner). + guard let leased = noiseService.withCurrentSessionGeneration( + for: normalizedPeerID, + expected: generation, + { + privateMediaSessions.beginAuthenticatedGeneration( + for: normalizedPeerID, + fingerprint: fingerprint, + generation: generation + ) + } + ) else { return } + + guard let fresh = leased else { + // A quarantined transport restored the same cryptographic + // generation. Its capability proof and announce state never + // became stale; only work queued while outbound keys were paused + // needs one idempotent ready transition. Retrying the bounded + // early-ciphertext queue is receive-side and therefore always + // safe under the restored keys. + noisePacketHandler.handleSessionAuthenticated(normalizedPeerID) + finalizeNoisePeerAuthentication( + for: normalizedPeerID, + deferOutboundUntilConvergence: deferOutboundUntilConvergence, + sendInitialStateAndAnnounce: false + ) + return + } + + completePrivateMediaPolicyResolution(fresh.rejected, with: .blockedDowngrade) + schedulePrivateMediaProofTimeout( + for: normalizedPeerID, + fingerprint: fingerprint, + sessionGeneration: generation, + nonce: fresh.watchdogNonce + ) + // Cross-link delivery can put ciphertext sent immediately after + // message 3 ahead of message 3 itself. Retry the bounded queue only + // after this generation's transport state has been fully installed. + noisePacketHandler.handleSessionAuthenticated(normalizedPeerID) + finalizeNoisePeerAuthentication( + for: normalizedPeerID, + deferOutboundUntilConvergence: deferOutboundUntilConvergence, + sendInitialStateAndAnnounce: true + ) + } + + private func finalizeNoisePeerAuthentication( + for peerID: PeerID, + deferOutboundUntilConvergence: Bool, + sendInitialStateAndAnnounce: Bool + ) { + if deferOutboundUntilConvergence { + // Timeout-restore: the counterpart may have completed the + // replacement handshake and discarded these keys, so encrypting + // the parked queues here would lose them silently. The restore's + // mandatory convergence retry — or any later handshake — re-enters + // with a fresh generation and drains them under keys both sides hold. + privateMediaSessions.setOutboundDeferredUntilConvergence(peerID) + #if DEBUG + _test_onPrivateMediaSessionReconciled?(peerID) + #endif + return + } + privateMediaSessions.clearOutboundDeferredUntilConvergence(peerID) + if sendInitialStateAndAnnounce { + sendAuthenticatedPeerState(to: peerID, echo: false) + } + #if DEBUG + _test_onPrivateMediaSessionReconciled?(peerID) + #endif + sendPendingMessagesAfterHandshake(for: peerID) + sendPendingNoisePayloadsAfterHandshake(for: peerID) + if sendInitialStateAndAnnounce { + sendAnnounce(forceSend: true) + } + } + + private func sendAuthenticatedPeerState(to peerID: PeerID, echo: Bool) { + let normalizedPeerID = peerID.toShort() + guard privateMediaSessions.markPeerStateSend(for: normalizedPeerID, echo: echo) else { return } + + let capabilities = localIdentityState.snapshot().advertisedCapabilities + let state = AuthenticatedPeerStatePacket( + capabilities: capabilities, + signingPublicKey: noiseService.getSigningPublicKeyData() + ) + guard let payload = BLENoisePayloadFactory.authenticatedPeerState(state) else { + SecureLogger.error("Failed to encode authenticated peer state", category: .security) + return + } + sendNoisePayload(payload, to: normalizedPeerID) + } + + func handleAuthenticatedPeerState( + _ payload: Data, + from peerID: PeerID, + sessionGeneration generation: UUID + ) { + // Engine-only, like handleNoisePeerAuthenticated: the closure below + // runs on the noise manager's queue while this engine slot stays + // blocked, so it accesses engine-owned state directly instead of + // sync-re-entering the engine (self-deadlock). + #if DEBUG + dispatchPrecondition(condition: .onQueue(messageQueue)) + #endif + let normalizedPeerID = peerID.toShort() + guard let state = AuthenticatedPeerStatePacket.decode(from: payload) else { + SecureLogger.warning( + "Ignoring malformed authenticated peer state from \(normalizedPeerID.id.prefix(8))…", + category: .security + ) + return + } + guard let fingerprint = noiseService.getPeerFingerprint(normalizedPeerID), + let publicKey = noiseService.getPeerPublicKeyData(normalizedPeerID), + publicKey.sha256Fingerprint().caseInsensitiveCompare(fingerprint) == .orderedSame else { + SecureLogger.warning( + "Ignoring peer state without a matching authenticated Noise identity", + category: .security + ) + return + } + guard let application = noiseService.withCurrentSessionGeneration( + for: normalizedPeerID, + expected: generation, + { + () -> (accepted: Bool, completions: [@MainActor (PrivateMediaSendPolicy) -> Void]) in + guard privateMediaSessions.currentGeneration(for: normalizedPeerID) == generation else { + return (false, []) + } + + // The generation lease (plus the engine slot this section + // holds) prevents rekey/session promotion from interleaving + // between validation and these durable mutations. + identityManager.bindAuthenticatedSigningPublicKey( + state.signingPublicKey, + fingerprint: fingerprint + ) + identityManager.upsertCryptographicIdentity( + fingerprint: fingerprint, + noisePublicKey: publicKey, + signingPublicKey: state.signingPublicKey, + claimedNickname: nil + ) + if state.capabilities.contains(.privateMedia) { + identityManager.markPrivateMediaCapable(fingerprint: fingerprint) + } + + peerRegistry.mutate { + $0.bindAuthenticatedSigningPublicKey( + state.signingPublicKey, + for: normalizedPeerID + ) + } + guard let completions = privateMediaSessions.applyAuthenticatedPeerState( + for: normalizedPeerID, + fingerprint: fingerprint, + generation: generation, + capabilities: state.capabilities + ) else { + return (false, []) + } + return (true, completions) + } + ), application.accepted else { return } + + // One bounded echo makes initiator/responder proof ordering converge + // even when message 3 and the first proof take different mesh links. + sendAuthenticatedPeerState(to: normalizedPeerID, echo: true) + let policy = privateMediaSendPolicy(to: normalizedPeerID) + sendPendingNoisePayloadsAfterHandshake(for: normalizedPeerID) + completePrivateMediaPolicyResolution(application.completions, with: policy) + } + + func noteNoiseSessionCleared(for peerID: PeerID) { + let normalizedPeerID = peerID.toShort() + let reset = privateMediaSessions.clearSession(for: normalizedPeerID) + if let reset { + schedulePrivateMediaProofTimeout( + for: normalizedPeerID, + fingerprint: reset.fingerprint, + sessionGeneration: nil, + nonce: reset.nonce + ) + } + } + + func clearNoiseSession(for peerID: PeerID) { + noiseService.clearSession(for: peerID) + noteNoiseSessionCleared(for: peerID) + } + + /// Swaps `myPeerID`/`myPeerIDData` to match the current Noise identity. + /// The swap runs as a `messageQueue` barrier so in-flight work items that + /// read the identity (e.g. `sendMessage` building packets) complete + /// against the old value and everything after sees the new one atomically. + /// Callers (init, panic reset on the main thread) are never on + /// `messageQueue`; the re-entrancy check keeps any future on-queue caller + /// from deadlocking. + func refreshPeerIdentity() { + onEngine { + let fingerprint = noiseService.getIdentityFingerprint() + localIdentityState.replacePeerIdentity( + with: PeerID(str: fingerprint.prefix(16)) + ) + meshTopology.reset() + } + } + + func sendNoisePayload(_ typedPayload: Data, to peerID: PeerID) { + sendOrQueueNoisePayload( + typedPayload, + to: peerID, + initiateOnlyIfReachable: false, + logLabel: "noise payload" + ) + } + + func sendOrQueueNoisePayload( + _ typedPayload: Data, + to peerID: PeerID, + initiateOnlyIfReachable: Bool, + logLabel: String + ) { + // Hop like sendMessage: callers are often on the main actor, and the + // send path sync-waits on bleQueue for link state. + if DispatchQueue.getSpecific(key: messageQueueKey) == nil { + messageQueue.async { [weak self] in + self?.sendOrQueueNoisePayload( + typedPayload, + to: peerID, + initiateOnlyIfReachable: initiateOnlyIfReachable, + logLabel: logLabel + ) + } + return + } + guard noiseService.hasEstablishedSession(with: peerID) else { + pendingNoiseSessionQueues.appendTypedPayload(typedPayload, for: peerID) + SecureLogger.debug("📥 Queued \(logLabel) for \(peerID.id.prefix(8))… pending handshake", category: .session) + if !initiateOnlyIfReachable || (!noiseService.hasSession(with: peerID) && isPeerReachable(peerID)) { + initiateNoiseHandshake(with: peerID) + } + return + } + do { + broadcastPacket(try makeEncryptedNoisePacket(typedPayload, to: peerID)) + } catch { + SecureLogger.error("Failed to send \(logLabel): \(error)") + } + } + + func makeEncryptedNoisePacket( + _ typedPayload: Data, + to peerID: PeerID, + requiresAuthenticatedPrivateMediaReceipts: Bool = false + ) throws -> BitchatPacket { + let encrypted: Data + let isPrivateFile = NoisePayloadType.isPrivateFile(rawValue: typedPayload.first) + if isPrivateFile { + let provenGeneration = privateMediaSessions.provenGeneration( + for: peerID, + requireReceipts: requiresAuthenticatedPrivateMediaReceipts + ) + guard let provenGeneration else { + throw NoiseEncryptionError.sessionNotEstablished + } + encrypted = try noiseService.encryptPrivateFilePayload( + typedPayload, + for: peerID, + sessionGeneration: provenGeneration + ) + } else { + encrypted = try noiseService.encrypt(typedPayload, for: peerID) + } + return BitchatPacket( + type: MessageType.noiseEncrypted.rawValue, + senderID: myPeerIDData, + recipientID: Data(hexString: peerID.id), + timestamp: UInt64(Date().timeIntervalSince1970 * 1000), + payload: encrypted, + signature: nil, + ttl: messageTTL, + // v1 has a 16-bit payload length; finalized media can exceed it. + version: isPrivateFile ? 2 : 1 + ) + } +} diff --git a/bitchat/Services/BLE/BLEService+Testing.swift b/bitchat/Services/BLE/BLEService+Testing.swift new file mode 100644 index 00000000..a889d828 --- /dev/null +++ b/bitchat/Services/BLE/BLEService+Testing.swift @@ -0,0 +1,363 @@ +#if DEBUG +import BitFoundation +import CoreBluetooth +import Foundation + +// Test-only helper to inject packets into the receive pipeline +extension BLEService { + /// Queues an event through the same MainActor hop as production receive + /// handlers so panic-boundary tests can deterministically invalidate it. + func _test_emitTransportEvent(_ event: TransportEvent) { + emitTransportEvent(event) + } + + var _test_isPanicIngressOpen: Bool { + capturePanicLifecycleGeneration() != nil + } + + /// Queries the receipt store of the service's OWN incoming-file store — + /// the instance production lookups run against — so panic tests exercise + /// the real wiring instead of a same-instance shortcut. + func _test_privateMediaReceiptState( + messageID: String + ) -> BLEPrivateMediaReceiptState { + incomingFileStore.privateMediaReceiptState(messageID: messageID) + } + + /// Models a CoreBluetooth delegate callback without requiring a physical + /// peripheral. The callback itself runs on `bleQueue`, exactly where the + /// panic radio-stop barrier must linearize it. + func _test_handlePacketFromBLEQueue( + _ packet: BitchatPacket, + fromPeerID: PeerID + ) { + bleQueue.async { [weak self] in + self?.handleReceivedPacket(packet, from: fromPeerID) + } + } + + /// Simulated-link ingress: the full production attribution path — + /// binding lookup, spoof rejection, raw-announce binding, ingress + /// recording — for a frame arriving on a synthetic link. The + /// SimulatedMesh harness feeds every node through this, so multi-node + /// tests exercise the same engine code as CoreBluetooth ingress. + func _test_ingestFrame(_ packet: BitchatPacket, link: BLEIngressLinkID) { + emitLinkEvent(.frameDecoded(packet, link: link, linkDescription: "Simulated \(link)")) + } + + /// Sends an unthrottled announce, exactly like the maintenance forced + /// path. SimulatedMesh uses this as the deterministic discovery step. + func _test_forceAnnounce() { + onEngine { sendAnnounceNow(forceSend: true) } + } + + /// Clears the announce throttle's wall-clock debt — the simulator's + /// stand-in for "enough real time has passed", since scheduler time + /// cannot move the throttle's Date-based window. Deliberately NOT + /// part of `_test_forceAnnounce`: the panic-rotation mesh test relies + /// on the production panic path performing its own reset, and a + /// blanket reset here would mask that regression. + func _test_resetAnnounceThrottle() { + announceThrottle.reset() + } + + /// Blocks until every engine slot enqueued so far has run — the + /// deterministic settling fence for simulated-mesh pumping. + func _test_fenceEngine() { + onEngine {} + } + + func _test_emitTransportEvent( + _ event: TransportEvent, + completion: @escaping () -> Void, + finalization: @escaping (TransportEventDeliveryOutcome) -> Void + ) { + emitTransportEvent( + event, + completion: completion, + finalization: finalization + ) + } + + func _test_handlePacket(_ packet: BitchatPacket, fromPeerID: PeerID, preseedPeer: Bool = true, signingPublicKey: Data? = nil) { + if preseedPeer { + // Ensure the synthetic peer is known and marked verified for public-message tests + let normalizedID = PeerID(hexData: packet.senderID) + peerRegistry.mutate { registry in + if var existing = registry.info(for: normalizedID) { + existing.isConnected = true + existing.isVerifiedNickname = true + if let signingPublicKey { existing.signingPublicKey = signingPublicKey } + existing.lastSeen = Date() + registry.upsert(existing) + } else { + registry.upsert(BLEPeerInfo( + peerID: normalizedID, + nickname: "TestPeer_\(fromPeerID.id.prefix(4))", + isConnected: true, + noisePublicKey: packet.senderID, + signingPublicKey: signingPublicKey, + isVerifiedNickname: true, + lastSeen: Date() + )) + } + } + } + handleReceivedPacket(packet, from: fromPeerID) + } + + /// Waits until fragment ingress already submitted by a test has finished + /// reassembly/reinjection and any resulting transport event has crossed + /// the MainActor delivery hop. This is a deterministic pipeline fence, + /// avoiding wall-clock sleeps that become flaky under a parallel suite. + func _test_drainFragmentPipeline() async { + await withCheckedContinuation { continuation in + messageQueue.async { + // Reassembled packets are reinjected synchronously on + // `messageQueue`; their UI delivery task is therefore already + // enqueued before this later MainActor marker. + Task { @MainActor in + continuation.resume() + } + } + } + } + + func _test_hasGossipPrekeyBundle(for peerID: PeerID) -> Bool { + gossipSyncManager?._hasPrekeyBundle(for: peerID) ?? false + } + + func _test_acceptsIngress(packet: BitchatPacket, boundPeerID: PeerID?) -> Bool { + let claimedSenderID = PeerID(hexData: packet.senderID) + guard case .success = BLEIngressLinkRegistry.packetContext( + for: packet, + claimedSenderID: claimedSenderID, + boundPeerID: boundPeerID, + localPeerID: myPeerID, + directAnnounceTTL: messageTTL + ) else { + return false + } + return true + } + + func _test_recordIngressIfNew(packet: BitchatPacket, linkID: String) -> Bool { + recordIngressIfNew( + messageID: BLEIngressLinkRegistry.messageID(for: packet), + link: .central(linkID), + peerID: PeerID(hexData: packet.senderID) + ) + } + + func _test_bindCentral(_ centralUUID: String, to peerID: PeerID) { + onEngine { linkBindings.bindCentral(centralUUID, to: peerID) } + } + + func _test_centralBinding(_ centralUUID: String) -> PeerID? { + onEngine { linkBindings.peer(forCentralUUID: centralUUID) } + } + + func _test_linkBinding(_ link: BLEIngressLinkID) -> PeerID? { + onEngine { linkBindings.boundPeer(for: link) } + } + + func _test_knownPeerIDs() -> [PeerID] { + peerRegistry.peerIDs + } + + func _test_markNoiseAuthenticatedCentral(_ centralUUID: String, to peerID: PeerID) { + onEngine { + guard linkBindings.peer(forCentralUUID: centralUUID) == peerID else { return } + linkAuth.markAuthenticated(.central(centralUUID), owner: peerID) + } + } + + func _test_isNoiseAuthenticatedCentral(_ centralUUID: String, for peerID: PeerID) -> Bool { + onEngine { + linkAuth.isAuthenticated(.central(centralUUID), for: peerID) + } + } + + func _test_seedConnectedPeer( + _ peerID: PeerID, + nickname: String, + capabilities: PeerCapabilities? = nil, + noisePublicKey: Data? = nil + ) { + peerRegistry.mutate { + $0.upsert(BLEPeerInfo( + peerID: peerID, + nickname: nickname, + isConnected: true, + noisePublicKey: noisePublicKey, + signingPublicKey: nil, + isVerifiedNickname: true, + lastSeen: Date(), + capabilities: capabilities ?? [] + )) + } + } + + /// Handshake plumbing for tests that need a real established Noise + /// session (e.g. canDeliverSecurely) without Bluetooth in the loop. + func _test_noiseInitiateHandshake(with peerID: PeerID) throws -> Data { + try noiseService.initiateHandshake(with: peerID) + } + + func _test_noiseProcessHandshakeMessage(from peerID: PeerID, message: Data) throws -> Data? { + try noiseService.processHandshakeMessage(from: peerID, message: message) + } + + func _test_enqueuePendingPrivateMessage( + content: String, + messageID: String, + for peerID: PeerID + ) { + onEngine { + pendingNoiseSessionQueues.appendPrivateMessage( + content: content, + messageID: messageID, + for: peerID + ) + } + } + + func _test_enqueuePendingNoisePayload( + _ payload: Data, + transferId: String, + for peerID: PeerID + ) { + guard privateMediaTransferAdmissions.begin(transferId) == .admitted else { return } + onEngine { + pendingNoiseSessionQueues.appendTypedPayload( + payload, + transferId: transferId, + for: peerID + ) + } + } + + func _test_sendPendingNoisePayloadsAfterHandshake(for peerID: PeerID) { + sendPendingNoisePayloadsAfterHandshake(for: peerID) + } + + func _test_hasPendingPrivateMediaPolicyResolution(for peerID: PeerID) -> Bool { + privateMediaSessions.hasPendingPolicyResolution(for: peerID.toShort()) + } + + func _test_forcePrivateMediaProofTimeout(for peerID: PeerID) { + let normalizedPeerID = peerID.toShort() + let target = privateMediaSessions.proofTimeoutTarget(for: normalizedPeerID) + guard let target else { return } + handlePrivateMediaProofTimeout( + for: normalizedPeerID, + fingerprint: target.fingerprint, + sessionGeneration: target.generation, + nonce: target.nonce + ) + } + + func _test_privateMediaTransferState( + transferId: String + ) -> (admissionActive: Bool, pendingNoise: Bool, activeScheduler: Int, pendingScheduler: Int) { + let scheduler = onEngine { + ( + pendingNoiseSessionQueues.containsTypedPayload(transferId: transferId), + outboundFragmentTransfers.activeCount, + outboundFragmentTransfers.pendingCount + ) + } + return ( + privateMediaTransferAdmissions.isActive(transferId), + scheduler.0, + scheduler.1, + scheduler.2 + ) + } + + func _test_privateMediaAdmissionEntryCount() -> Int { + privateMediaTransferAdmissions.count + } + + @discardableResult + func _test_beginPrivateMediaAdmission(_ transferId: String, now: Date) -> Bool { + privateMediaTransferAdmissions.begin(transferId, now: now) == .admitted + } + + func _test_isPrivateMediaAdmissionActive(_ transferId: String, now: Date) -> Bool { + privateMediaTransferAdmissions.isActive(transferId, now: now) + } + + func _test_finishPrivateMediaAdmission(_ transferId: String) { + privateMediaTransferAdmissions.finish(transferId) + } + + func _test_drainPrivateMediaSendPipeline() async { + // Capture only the (Sendable) queue, not self, so the @Sendable + // dispatch closures carry no non-Sendable state. + let queue = messageQueue + await withCheckedContinuation { continuation in + queue.async { + queue.async { + continuation.resume() + } + } + } + } + + func _test_broadcastPrivateMediaPacket( + _ packet: BitchatPacket, + transferId: String + ) { + broadcastPacket( + packet, + transferId: transferId, + requiresPrivateMediaAdmission: true + ) + } + + func _test_drainNoiseMessagePipeline() async { + await _test_drainPrivateMediaSendPipeline() + } + + /// Replays the current generation's ready callback. Restore tests use + /// this to prove same-generation reconciliation is idempotent. + func _test_reconcileCurrentNoiseSession(for peerID: PeerID) { + let normalizedPeerID = peerID.toShort() + messageQueue.async { [weak self] in + guard let self, + let generation = self.noiseService.sessionGeneration( + for: normalizedPeerID + ), + let fingerprint = self.noiseService.getPeerFingerprint( + normalizedPeerID + ) else { + return + } + self.handleNoisePeerAuthenticated( + peerID: normalizedPeerID, + fingerprint: fingerprint, + sessionGeneration: generation + ) + } + } + + /// Builds an authenticated-session packet from an exact typed plaintext. + /// Compatibility tests use this to model Android's deployed 0x20 file + /// payload and the short-lived 0x09 prerelease payload without exposing a + /// production API that can emit the old value. + func _test_makeEncryptedNoisePacket(_ typedPayload: Data, to peerID: PeerID) throws -> BitchatPacket { + try makeEncryptedNoisePacket(typedPayload, to: peerID) + } + + static func _test_shouldRediscoverBitChatService( + invalidatedServiceUUIDs: [CBUUID], + cachedServiceUUIDs: [CBUUID]? + ) -> Bool { + shouldRediscoverBitChatService( + invalidatedServiceUUIDs: invalidatedServiceUUIDs, + cachedServiceUUIDs: cachedServiceUUIDs + ) + } +} +#endif diff --git a/bitchat/Services/BLE/BLEService.swift b/bitchat/Services/BLE/BLEService.swift index 58473808..00526858 100644 --- a/bitchat/Services/BLE/BLEService.swift +++ b/bitchat/Services/BLE/BLEService.swift @@ -16,7 +16,7 @@ import UIKit /// bounds. Tombstones may age out or evict older tombstones; active entries /// are never evicted under pressure. A one-hour active timeout is reported as /// an explicit transfer failure and removes any handshake-queued payload. -private final class BLEPrivateMediaTransferAdmissionRegistry { +final class BLEPrivateMediaTransferAdmissionRegistry { enum BeginResult: Equatable { case admitted case alreadyKnown @@ -196,7 +196,7 @@ final class BLEService: NSObject { private let defaultFragmentSize = TransportConfig.bleDefaultFragmentSize private let bleMaxMTU = 512 private let maxMessageLength = TransportConfig.maxMessageLength - private let messageTTL: UInt8 = TransportConfig.messageTTLDefault + let messageTTL: UInt8 = TransportConfig.messageTTLDefault // Flood/battery controls private let maxInFlightAssemblies = TransportConfig.bleMaxInFlightAssemblies // cap concurrent fragment assemblies private let highDegreeThreshold = TransportConfig.bleHighDegreeThreshold // for adaptive TTL/probabilistic relays @@ -220,11 +220,11 @@ final class BLEService: NSObject { // which the engine may sync-read via `readLinkState`. private var _linkAuth = BLELinkAuthState() private var _linkBindings = BLELinkBindings() - private var linkAuth: BLELinkAuthState { + var linkAuth: BLELinkAuthState { get { assertLinkIdentityEngineOwned(); return _linkAuth } set { assertLinkIdentityEngineOwned(); _linkAuth = newValue } } - private var linkBindings: BLELinkBindings { + var linkBindings: BLELinkBindings { get { assertLinkIdentityEngineOwned(); return _linkBindings } set { assertLinkIdentityEngineOwned(); _linkBindings = newValue } } @@ -245,7 +245,7 @@ final class BLEService: NSObject { // engine, plus the two bleQueue link-drop paths (didDisconnectPeripheral // / didUnsubscribeFrom) that mark a peer disconnected the moment its // last physical link goes; the store's lock serializes them. - private let peerRegistry = BLEPeerRegistryStore() + let peerRegistry = BLEPeerRegistryStore() // 4. Efficient Message Deduplication private let messageDeduplicator = MessageDeduplicator() @@ -268,14 +268,14 @@ final class BLEService: NSObject { var prekeyBundleStore: PrekeyBundleStore = .shared // Throttle for re-broadcasting our own (unchanged) bundle // (engine-confined). - private var lastPrekeyBundleSentAt: Date? + var lastPrekeyBundleSentAt: Date? // Prekey bundles that arrived before their owner's verified announce bound // a signing key. Over the air a bundle can still arrive before the // announce it depends on; we retain the latest such bundle per owner // (bounded) and re-attempt attribution when the announce lands. // Engine-confined. - private var pendingPrekeyBundles: [PeerID: BitchatPacket] = [:] - private static let pendingPrekeyBundleCap = 64 + var pendingPrekeyBundles: [PeerID: BitchatPacket] = [:] + static let pendingPrekeyBundleCap = 64 // Gateway mode: sink for received nostrCarrier packets (set by app // wiring, called on the main actor after transport-level checks) and the // runtime-toggled capability bits ORed into `PeerCapabilities.localSupported` @@ -304,31 +304,31 @@ final class BLEService: NSObject { var _test_beforeHandshakeRecoveryEnqueued: ((PeerID) -> Void)? #endif private var selfBroadcastTracker = BLESelfBroadcastTracker() - private let meshTopology = MeshTopologyTracker() + let meshTopology = MeshTopologyTracker() // Route health for originated source routes (engine-confined). private var sourceRouteFailures = BLESourceRouteFailureCache() // Mesh diagnostics (/ping): engine-confined probe and budget state. - private var meshPings = BLEMeshPingTracker() + var meshPings = BLEMeshPingTracker() // 5. Fragment Reassembly (necessary for messages > MTU) private var fragmentAssemblyBuffer = BLEFragmentAssemblyBuffer() - private var outboundFragmentTransfers = BLEOutboundFragmentTransferScheduler() + var outboundFragmentTransfers = BLEOutboundFragmentTransferScheduler() /// bleQueue-confined tokens holding scanning paused while outbound /// fragment trains are active, preventing overlapping transfers from /// prematurely restarting scanning. private var fragmentScanPauseTokens = Set() - private lazy var privateMediaTransferAdmissions = BLEPrivateMediaTransferAdmissionRegistry { [weak self] transferId in + lazy var privateMediaTransferAdmissions = BLEPrivateMediaTransferAdmissionRegistry { [weak self] transferId in self?.handlePrivateMediaAdmissionExpiry(transferId) } // Generation-bound private-media session state (lock-backed store: the // main actor answers the send policy from it synchronously, and noise // critical sections mutate it without re-entering the engine). - private let privateMediaSessions = BLEPrivateMediaSessionStore() - private let incomingFileStore: BLEIncomingFileStore + let privateMediaSessions = BLEPrivateMediaSessionStore() + let incomingFileStore: BLEIncomingFileStore // Simple announce throttling - private let announceThrottle = BLEAnnounceThrottle() + let announceThrottle = BLEAnnounceThrottle() // Application state tracking (thread-safe) #if os(iOS) @@ -358,14 +358,14 @@ final class BLEService: NSObject { // MARK: - Identity - private var noiseService: NoiseEncryptionService + var noiseService: NoiseEncryptionService /// Injected so tests can compress the quarantine/rollback window; /// production always passes the security-constant default. private let noiseResponderHandshakeTimeout: TimeInterval - private let identityManager: SecureIdentityStateManagerProtocol + let identityManager: SecureIdentityStateManagerProtocol private let keychain: KeychainManagerProtocol private let idBridge: NostrIdentityBridge - private let localIdentityState = BLELocalIdentityStateStore() + let localIdentityState = BLELocalIdentityStateStore() // MARK: - Advertising Privacy // No Local Name by default for maximum privacy. No rotating alias. @@ -377,8 +377,8 @@ final class BLEService: NSObject { /// collections queue it guarded state with). BLE throughput is far below /// what one queue serializes comfortably, and a single writer makes the /// old per-field ownership comments and barrier discipline structural. - private let messageQueue = DispatchQueue(label: "mesh.message") - private let messageQueueKey = DispatchSpecificKey() + let messageQueue = DispatchQueue(label: "mesh.message") + let messageQueueKey = DispatchSpecificKey() /// The only source of deferred engine work (see BLEEngineScheduling); /// injectable so tests drive protocol deadlines with a manual clock. let engineScheduler: BLEEngineScheduling @@ -401,7 +401,7 @@ final class BLEService: NSObject { /// `messageQueue.async` instead, and debug builds trap any violation /// here. (The engine only ever async-dispatches into mesh.sync; its /// queue.sync helpers are DEBUG test entry points on test threads.) - private func onEngine(_ body: () -> T) -> T { + func onEngine(_ body: () -> T) -> T { #if DEBUG dispatchPrecondition(condition: .notOnQueue(bleQueue)) #endif @@ -414,7 +414,7 @@ final class BLEService: NSObject { } // Noise messages and typed payloads pending handshake completion. - private var pendingNoiseSessionQueues = BLENoiseSessionQueues() + var pendingNoiseSessionQueues = BLENoiseSessionQueues() // Queue for notifications that failed due to full queue (bleQueue-owned, // like the link state store: every producer and drain runs there). var pendingNotifications = BLEOutboundNotificationBuffer() @@ -435,14 +435,14 @@ final class BLEService: NSObject { // Ingress link tracking for duplicate and last-hop suppression // (lock-backed: recorded on bleQueue the moment a frame decodes, read // by engine relay/routing decisions) - private var ingressLinks = BLEIngressLinkRegistry() + var ingressLinks = BLEIngressLinkRegistry() // Inner message IDs of recently opened courier envelopes. Redundant // copies of one message ride different envelopes (each seal uses a fresh // ephemeral key, and bridge drops multiply across relays/couriers), so // envelope-level dedup can't catch them; dedup on the inner ID before // delivery so a duplicate costs one decrypt instead of a delivery + ack // + handshake each. Engine-confined. - private var openedCourierMessageIDs = BoundedIDSet(capacity: TransportConfig.courierOpenedMessageIDCap) + var openedCourierMessageIDs = BoundedIDSet(capacity: TransportConfig.courierOpenedMessageIDCap) let logRateLimiter = BLELogRateLimiter(defaultMinimumInterval: 5) // Per-peripheral write backpressure (bleQueue-owned) @@ -458,14 +458,14 @@ final class BLEService: NSObject { // Public-message orchestration (queue hops stay in the environment closures) private lazy var publicMessageHandler = BLEPublicMessageHandler(environment: makePublicMessageHandlerEnvironment()) // Noise handshake/encrypted orchestration (queue hops and crypto stay in the environment closures) - private lazy var noisePacketHandler = BLENoisePacketHandler(environment: makeNoisePacketHandlerEnvironment()) + lazy var noisePacketHandler = BLENoisePacketHandler(environment: makeNoisePacketHandlerEnvironment()) // Fragment-assembly orchestration (queue hops stay in the environment closures) private lazy var fragmentHandler = BLEFragmentHandler(environment: makeFragmentHandlerEnvironment()) // File-transfer orchestration (queue hops stay in the environment closures) private lazy var fileTransferHandler = BLEFileTransferHandler(environment: makeFileTransferHandlerEnvironment()) // MARK: - Gossip Sync - private var gossipSyncManager: GossipSyncManager? + var gossipSyncManager: GossipSyncManager? private let requestSyncManager = RequestSyncManager() // MARK: - Maintenance Timer @@ -521,7 +521,7 @@ final class BLEService: NSObject { idBridge: NostrIdentityBridge, identityManager: SecureIdentityStateManagerProtocol, initializeBluetoothManagers: Bool = true, - incomingFileStore: BLEIncomingFileStore = BLEIncomingFileStore(), + incomingFileStore: BLEIncomingFileStore = .shared, startSuspendedForPanicRecovery: Bool = false, noiseResponderHandshakeTimeout: TimeInterval = NoiseSecurityConstants.ordinaryResponderHandshakeTimeout, @@ -639,13 +639,13 @@ final class BLEService: NSObject { panicLifecycleLock.unlock() } - private func capturePanicLifecycleGeneration() -> UInt64? { + func capturePanicLifecycleGeneration() -> UInt64? { panicLifecycleLock.lock() defer { panicLifecycleLock.unlock() } return _isPanicSuspended ? nil : panicLifecycleGeneration } - private func isCurrentPanicLifecycleGeneration(_ generation: UInt64) -> Bool { + func isCurrentPanicLifecycleGeneration(_ generation: UInt64) -> Bool { panicLifecycleLock.lock() defer { panicLifecycleLock.unlock() } return !_isPanicSuspended && panicLifecycleGeneration == generation @@ -884,7 +884,7 @@ final class BLEService: NSObject { gossipSyncManager?.onPublicPacketSeen(signedPacket) } - private func buildSignedBroadcastPacket( + func buildSignedBroadcastPacket( type: MessageType, payload: Data, timestamp: Date = Date(), @@ -930,7 +930,7 @@ final class BLEService: NSObject { /// so all three local identity fields live in one lock-backed snapshot. var myPeerID: PeerID { localIdentityState.snapshot().peerID } var myNickname: String { localIdentityState.snapshot().nickname } - private var myPeerIDData: Data { localIdentityState.snapshot().peerIDData } + var myPeerIDData: Data { localIdentityState.snapshot().peerIDData } /// Sole mutator for `myNickname`: updates the stored value and force-sends /// an announce so peers learn the new name. @@ -1368,7 +1368,7 @@ final class BLEService: NSObject { } } - private func completePrivateMediaPolicyResolution( + func completePrivateMediaPolicyResolution( _ completions: [@MainActor (PrivateMediaSendPolicy) -> Void], with policy: PrivateMediaSendPolicy ) { @@ -1378,7 +1378,7 @@ final class BLEService: NSObject { } } - private func schedulePrivateMediaProofTimeout( + func schedulePrivateMediaProofTimeout( for peerID: PeerID, fingerprint: String, sessionGeneration: UUID?, @@ -1394,7 +1394,7 @@ final class BLEService: NSObject { } } - private func handlePrivateMediaProofTimeout( + func handlePrivateMediaProofTimeout( for peerID: PeerID, fingerprint: String, sessionGeneration: UUID?, @@ -1499,9 +1499,9 @@ 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)? + let externalNoiseCallbacksLock = NSLock() + var externalPeerAuthenticatedHandlers: [(PeerID, String) -> Void] = [] + var externalHandshakeRequiredHandler: ((PeerID) -> Void)? func installNoiseSessionCallbacks( onPeerAuthenticated: @escaping (PeerID, String) -> Void, @@ -2002,7 +2002,7 @@ final class BLEService: NSObject { SecureLogger.debug("↩️ Dropping BLE self-loopback packet type \(packetType) from \(linkDescription)", category: .session) } - private func recordIngressIfNew( + func recordIngressIfNew( messageID: String, link: BLEIngressLinkID, peerID: PeerID @@ -2017,7 +2017,7 @@ final class BLEService: NSObject { // MARK: - Packet Broadcasting - private func broadcastPacket( + func broadcastPacket( _ packet: BitchatPacket, transferId: String? = nil, requiresPrivateMediaAdmission: Bool = false, @@ -2505,7 +2505,7 @@ final class BLEService: NSObject { // Directed send helper (unicast to a specific peerID) without altering packet contents @discardableResult - private func sendPacketDirected( + func sendPacketDirected( _ packet: BitchatPacket, to peerID: PeerID, requireDirectPeerLink: Bool = false, @@ -2715,17 +2715,11 @@ final class BLEService: NSObject { removeIncomingFile: { [weak self] storedURL in self?.incomingFileStore.removeIncomingFile(at: storedURL) }, - finishIncomingFileDelivery: { [weak self] storedURL in - // Serialize pending-owner release behind deletion barriers. - // If /clear snapshots before this UI insertion, its already - // queued barrier must still observe the path as pending. If - // insertion wins first, the next MainActor snapshot sees the - // new bubble and protects the path explicitly. - self?.messageQueue.async { - self?.incomingFileStore.finishIncomingFileDelivery( - at: storedURL - ) - } + beginPendingDelivery: { [weak self] storedURL in + self?.incomingFileStore.beginPendingDelivery(at: storedURL) + }, + finishPendingDelivery: { [weak self] storedURL in + self?.incomingFileStore.finishPendingDelivery(at: storedURL) }, isPrivateMediaSenderBlocked: { [weak self] peerID in guard let self else { return false } @@ -2855,7 +2849,7 @@ final class BLEService: NSObject { } } - private func sendAnnounceNow(forceSend: Bool) { + func sendAnnounceNow(forceSend: Bool) { // Re-check on the serialized queue: a panic suspend may have started // after this announce was scheduled but before it runs. guard !isPanicSuspended else { return } @@ -3132,367 +3126,6 @@ extension BLEService: BLERadioControllerDelegate { } -#if DEBUG -// Test-only helper to inject packets into the receive pipeline -extension BLEService { - /// Queues an event through the same MainActor hop as production receive - /// handlers so panic-boundary tests can deterministically invalidate it. - func _test_emitTransportEvent(_ event: TransportEvent) { - emitTransportEvent(event) - } - - var _test_isPanicIngressOpen: Bool { - capturePanicLifecycleGeneration() != nil - } - - /// Queries the receipt store of the service's OWN incoming-file store — - /// the instance production lookups run against — so panic tests exercise - /// the real wiring instead of a same-instance shortcut. - func _test_privateMediaReceiptState( - messageID: String - ) -> BLEPrivateMediaReceiptState { - incomingFileStore.privateMediaReceiptState(messageID: messageID) - } - - /// Models a CoreBluetooth delegate callback without requiring a physical - /// peripheral. The callback itself runs on `bleQueue`, exactly where the - /// panic radio-stop barrier must linearize it. - func _test_handlePacketFromBLEQueue( - _ packet: BitchatPacket, - fromPeerID: PeerID - ) { - bleQueue.async { [weak self] in - self?.handleReceivedPacket(packet, from: fromPeerID) - } - } - - /// Simulated-link ingress: the full production attribution path — - /// binding lookup, spoof rejection, raw-announce binding, ingress - /// recording — for a frame arriving on a synthetic link. The - /// SimulatedMesh harness feeds every node through this, so multi-node - /// tests exercise the same engine code as CoreBluetooth ingress. - func _test_ingestFrame(_ packet: BitchatPacket, link: BLEIngressLinkID) { - emitLinkEvent(.frameDecoded(packet, link: link, linkDescription: "Simulated \(link)")) - } - - /// Sends an unthrottled announce, exactly like the maintenance forced - /// path. SimulatedMesh uses this as the deterministic discovery step. - func _test_forceAnnounce() { - onEngine { sendAnnounceNow(forceSend: true) } - } - - /// Clears the announce throttle's wall-clock debt — the simulator's - /// stand-in for "enough real time has passed", since scheduler time - /// cannot move the throttle's Date-based window. Deliberately NOT - /// part of `_test_forceAnnounce`: the panic-rotation mesh test relies - /// on the production panic path performing its own reset, and a - /// blanket reset here would mask that regression. - func _test_resetAnnounceThrottle() { - announceThrottle.reset() - } - - /// Blocks until every engine slot enqueued so far has run — the - /// deterministic settling fence for simulated-mesh pumping. - func _test_fenceEngine() { - onEngine {} - } - - func _test_emitTransportEvent( - _ event: TransportEvent, - completion: @escaping () -> Void, - finalization: @escaping (TransportEventDeliveryOutcome) -> Void - ) { - emitTransportEvent( - event, - completion: completion, - finalization: finalization - ) - } - - func _test_handlePacket(_ packet: BitchatPacket, fromPeerID: PeerID, preseedPeer: Bool = true, signingPublicKey: Data? = nil) { - if preseedPeer { - // Ensure the synthetic peer is known and marked verified for public-message tests - let normalizedID = PeerID(hexData: packet.senderID) - peerRegistry.mutate { registry in - if var existing = registry.info(for: normalizedID) { - existing.isConnected = true - existing.isVerifiedNickname = true - if let signingPublicKey { existing.signingPublicKey = signingPublicKey } - existing.lastSeen = Date() - registry.upsert(existing) - } else { - registry.upsert(BLEPeerInfo( - peerID: normalizedID, - nickname: "TestPeer_\(fromPeerID.id.prefix(4))", - isConnected: true, - noisePublicKey: packet.senderID, - signingPublicKey: signingPublicKey, - isVerifiedNickname: true, - lastSeen: Date() - )) - } - } - } - handleReceivedPacket(packet, from: fromPeerID) - } - - /// Waits until fragment ingress already submitted by a test has finished - /// reassembly/reinjection and any resulting transport event has crossed - /// the MainActor delivery hop. This is a deterministic pipeline fence, - /// avoiding wall-clock sleeps that become flaky under a parallel suite. - func _test_drainFragmentPipeline() async { - await withCheckedContinuation { continuation in - messageQueue.async { - // Reassembled packets are reinjected synchronously on - // `messageQueue`; their UI delivery task is therefore already - // enqueued before this later MainActor marker. - Task { @MainActor in - continuation.resume() - } - } - } - } - - func _test_hasGossipPrekeyBundle(for peerID: PeerID) -> Bool { - gossipSyncManager?._hasPrekeyBundle(for: peerID) ?? false - } - - func _test_acceptsIngress(packet: BitchatPacket, boundPeerID: PeerID?) -> Bool { - let claimedSenderID = PeerID(hexData: packet.senderID) - guard case .success = BLEIngressLinkRegistry.packetContext( - for: packet, - claimedSenderID: claimedSenderID, - boundPeerID: boundPeerID, - localPeerID: myPeerID, - directAnnounceTTL: messageTTL - ) else { - return false - } - return true - } - - func _test_recordIngressIfNew(packet: BitchatPacket, linkID: String) -> Bool { - recordIngressIfNew( - messageID: BLEIngressLinkRegistry.messageID(for: packet), - link: .central(linkID), - peerID: PeerID(hexData: packet.senderID) - ) - } - - func _test_bindCentral(_ centralUUID: String, to peerID: PeerID) { - onEngine { linkBindings.bindCentral(centralUUID, to: peerID) } - } - - func _test_centralBinding(_ centralUUID: String) -> PeerID? { - onEngine { linkBindings.peer(forCentralUUID: centralUUID) } - } - - func _test_linkBinding(_ link: BLEIngressLinkID) -> PeerID? { - onEngine { linkBindings.boundPeer(for: link) } - } - - func _test_knownPeerIDs() -> [PeerID] { - peerRegistry.peerIDs - } - - func _test_markNoiseAuthenticatedCentral(_ centralUUID: String, to peerID: PeerID) { - onEngine { - guard linkBindings.peer(forCentralUUID: centralUUID) == peerID else { return } - linkAuth.markAuthenticated(.central(centralUUID), owner: peerID) - } - } - - func _test_isNoiseAuthenticatedCentral(_ centralUUID: String, for peerID: PeerID) -> Bool { - onEngine { - linkAuth.isAuthenticated(.central(centralUUID), for: peerID) - } - } - - func _test_seedConnectedPeer( - _ peerID: PeerID, - nickname: String, - capabilities: PeerCapabilities? = nil, - noisePublicKey: Data? = nil - ) { - peerRegistry.mutate { - $0.upsert(BLEPeerInfo( - peerID: peerID, - nickname: nickname, - isConnected: true, - noisePublicKey: noisePublicKey, - signingPublicKey: nil, - isVerifiedNickname: true, - lastSeen: Date(), - capabilities: capabilities ?? [] - )) - } - } - - /// Handshake plumbing for tests that need a real established Noise - /// session (e.g. canDeliverSecurely) without Bluetooth in the loop. - func _test_noiseInitiateHandshake(with peerID: PeerID) throws -> Data { - try noiseService.initiateHandshake(with: peerID) - } - - func _test_noiseProcessHandshakeMessage(from peerID: PeerID, message: Data) throws -> Data? { - try noiseService.processHandshakeMessage(from: peerID, message: message) - } - - func _test_enqueuePendingPrivateMessage( - content: String, - messageID: String, - for peerID: PeerID - ) { - onEngine { - pendingNoiseSessionQueues.appendPrivateMessage( - content: content, - messageID: messageID, - for: peerID - ) - } - } - - func _test_enqueuePendingNoisePayload( - _ payload: Data, - transferId: String, - for peerID: PeerID - ) { - guard privateMediaTransferAdmissions.begin(transferId) == .admitted else { return } - onEngine { - pendingNoiseSessionQueues.appendTypedPayload( - payload, - transferId: transferId, - for: peerID - ) - } - } - - func _test_sendPendingNoisePayloadsAfterHandshake(for peerID: PeerID) { - sendPendingNoisePayloadsAfterHandshake(for: peerID) - } - - func _test_hasPendingPrivateMediaPolicyResolution(for peerID: PeerID) -> Bool { - privateMediaSessions.hasPendingPolicyResolution(for: peerID.toShort()) - } - - func _test_forcePrivateMediaProofTimeout(for peerID: PeerID) { - let normalizedPeerID = peerID.toShort() - let target = privateMediaSessions.proofTimeoutTarget(for: normalizedPeerID) - guard let target else { return } - handlePrivateMediaProofTimeout( - for: normalizedPeerID, - fingerprint: target.fingerprint, - sessionGeneration: target.generation, - nonce: target.nonce - ) - } - - func _test_privateMediaTransferState( - transferId: String - ) -> (admissionActive: Bool, pendingNoise: Bool, activeScheduler: Int, pendingScheduler: Int) { - let scheduler = onEngine { - ( - pendingNoiseSessionQueues.containsTypedPayload(transferId: transferId), - outboundFragmentTransfers.activeCount, - outboundFragmentTransfers.pendingCount - ) - } - return ( - privateMediaTransferAdmissions.isActive(transferId), - scheduler.0, - scheduler.1, - scheduler.2 - ) - } - - func _test_privateMediaAdmissionEntryCount() -> Int { - privateMediaTransferAdmissions.count - } - - @discardableResult - func _test_beginPrivateMediaAdmission(_ transferId: String, now: Date) -> Bool { - privateMediaTransferAdmissions.begin(transferId, now: now) == .admitted - } - - func _test_isPrivateMediaAdmissionActive(_ transferId: String, now: Date) -> Bool { - privateMediaTransferAdmissions.isActive(transferId, now: now) - } - - func _test_finishPrivateMediaAdmission(_ transferId: String) { - privateMediaTransferAdmissions.finish(transferId) - } - - func _test_drainPrivateMediaSendPipeline() async { - // Capture only the (Sendable) queue, not self, so the @Sendable - // dispatch closures carry no non-Sendable state. - let queue = messageQueue - await withCheckedContinuation { continuation in - queue.async { - queue.async { - continuation.resume() - } - } - } - } - - func _test_broadcastPrivateMediaPacket( - _ packet: BitchatPacket, - transferId: String - ) { - broadcastPacket( - packet, - transferId: transferId, - requiresPrivateMediaAdmission: true - ) - } - - func _test_drainNoiseMessagePipeline() async { - await _test_drainPrivateMediaSendPipeline() - } - - /// Replays the current generation's ready callback. Restore tests use - /// this to prove same-generation reconciliation is idempotent. - func _test_reconcileCurrentNoiseSession(for peerID: PeerID) { - let normalizedPeerID = peerID.toShort() - messageQueue.async { [weak self] in - guard let self, - let generation = self.noiseService.sessionGeneration( - for: normalizedPeerID - ), - let fingerprint = self.noiseService.getPeerFingerprint( - normalizedPeerID - ) else { - return - } - self.handleNoisePeerAuthenticated( - peerID: normalizedPeerID, - fingerprint: fingerprint, - sessionGeneration: generation - ) - } - } - - /// Builds an authenticated-session packet from an exact typed plaintext. - /// Compatibility tests use this to model Android's deployed 0x20 file - /// payload and the short-lived 0x09 prerelease payload without exposing a - /// production API that can emit the old value. - func _test_makeEncryptedNoisePacket(_ typedPayload: Data, to peerID: PeerID) throws -> BitchatPacket { - try makeEncryptedNoisePacket(typedPayload, to: peerID) - } - - static func _test_shouldRediscoverBitChatService( - invalidatedServiceUUIDs: [CBUUID], - cachedServiceUUIDs: [CBUUID]? - ) -> Bool { - shouldRediscoverBitChatService( - invalidatedServiceUUIDs: invalidatedServiceUUIDs, - cachedServiceUUIDs: cachedServiceUUIDs - ) - } -} -#endif - - // MARK: - Private Media Deletion extension BLEService: PrivateMediaDeletionPersisting { @@ -3500,29 +3133,14 @@ extension BLEService: PrivateMediaDeletionPersisting { func persistDeletedPrivateMedia( messageIDs: [String], payloadRelativePaths: [String: String], - protectedPayloadRelativePaths: Set, completion: @escaping @MainActor (Bool) -> Void ) { let fileStore = incomingFileStore messageQueue.async { - guard let reservation = fileStore - .reservePrivateMediaDeletion( - messageIDs: messageIDs, - payloadRelativePaths: payloadRelativePaths - ) else { - Task { @MainActor in - completion(false) - } - return - } - let persisted = fileStore - .commitPrivateMediaDeletion( - reservation: reservation, - messageIDs: messageIDs, - payloadRelativePaths: payloadRelativePaths, - protectedPayloadRelativePaths: - protectedPayloadRelativePaths - ) + let persisted = fileStore.commitPrivateMediaDeletion( + messageIDs: messageIDs, + payloadRelativePaths: payloadRelativePaths + ) Task { @MainActor in completion(persisted) } @@ -3550,42 +3168,10 @@ enum TransportEventDeliveryOutcome: Equatable { case rejected } -enum TransportEventDeliveryGate { - /// Runs finalization exactly once for every attempted main-actor delivery, - /// including pre-insertion rejection, a missing/rejecting sink, and - /// post-insertion revalidation failure. Only a fully accepted delivery - /// runs `completion` (for example, a stable-media ACK). - @MainActor - static func attempt( - shouldDeliver: () -> Bool, - deliver: () -> TransportEventDeliveryOutcome, - completion: () -> Void, - finalization: (TransportEventDeliveryOutcome) -> Void - ) { - var outcome = TransportEventDeliveryOutcome.rejected - defer { finalization(outcome) } - guard shouldDeliver() else { - return - } - switch deliver() { - case .rejected: - return - case .invokedUnconfirmed: - outcome = .invokedUnconfirmed - return - case .accepted: - break - } - guard shouldDeliver() else { return } - outcome = .accepted - completion() - } -} - extension BLEService { /// Notify UI on the MainActor to satisfy Swift concurrency isolation - private func notifyUI(_ block: @escaping @MainActor () -> Void) { + func notifyUI(_ block: @escaping @MainActor () -> Void) { // Capture the panic lifecycle before queueing the MainActor hop. A // receive callback can enqueue UI delivery immediately before panic // clears application state; rechecking here prevents that stale work @@ -3615,22 +3201,28 @@ extension BLEService { return } Task { @MainActor [weak self] in + var outcome = TransportEventDeliveryOutcome.rejected + defer { finalization?(outcome) } guard let self, - self.isCurrentPanicLifecycleGeneration(generation) else { - finalization?(.rejected) + self.isCurrentPanicLifecycleGeneration(generation), + shouldDeliver?() ?? true else { return } - TransportEventDeliveryGate.attempt( - shouldDeliver: { - self.isCurrentPanicLifecycleGeneration(generation) - && (shouldDeliver?() ?? true) - }, - deliver: { - return self.deliverTransportEvent(event) - }, - completion: { completion?() }, - finalization: { finalization?($0) } - ) + switch self.deliverTransportEvent(event) { + case .rejected: + return + case .invokedUnconfirmed: + outcome = .invokedUnconfirmed + return + case .accepted: + break + } + guard self.isCurrentPanicLifecycleGeneration(generation), + shouldDeliver?() ?? true else { + return + } + outcome = .accepted + completion?() } } @@ -3650,7 +3242,7 @@ extension BLEService { /// event and `false` when no delegate is installed. @MainActor @discardableResult - private func deliverTransportEvent( + func deliverTransportEvent( _ event: TransportEvent ) -> TransportEventDeliveryOutcome { guard let eventDelegate else { return .rejected } @@ -3750,15 +3342,15 @@ extension BLEService { } #endif - private func routingData(for peerID: PeerID) -> Data? { + func routingData(for peerID: PeerID) -> Data? { peerID.toShort().routingData } - private func refreshLocalTopology() { + func refreshLocalTopology() { meshTopology.updateNeighbors(for: myPeerIDData, neighbors: peerRegistry.connectedRoutingData) } - private func computeRoute(to peerID: PeerID) -> [Data]? { + func computeRoute(to peerID: PeerID) -> [Data]? { // Version-gated: every hop and the recipient must have been observed // speaking v2, since a v1-only node drops v2 frames on decode. meshTopology.computeRoute( @@ -3807,1261 +3399,10 @@ extension BLEService { return signedPacket } - private func routingPeer(from data: Data) -> PeerID? { + func routingPeer(from data: Data) -> PeerID? { PeerID(routingData: data) } - // MARK: - Mesh Diagnostics (/ping, /trace, topology map) - - /// Sends a directed unencrypted ping probe (8-byte nonce + origin TTL). - /// The completion fires exactly once on the main actor: with RTT/hops - /// when the matching pong returns, or nil after the timeout window. - func sendMeshPing(to peerID: PeerID, completion: @escaping @MainActor (MeshPingResult?) -> Void) { - guard let generation = capturePanicLifecycleGeneration() else { - return - } - messageQueue.async { [weak self] in - guard let self, - self.isCurrentPanicLifecycleGeneration(generation), - let recipientData = peerID.toShort().routingData, - let payload = MeshPingPayload( - nonce: Data((0.. [PeerID]? { - refreshLocalTopology() - if let route = computeRoute(to: peerID) { - return route.compactMap { PeerID(routingData: $0) } - } - // Confirmed claims can lag a brand-new link (the peer's next announce - // hasn't arrived yet); a live direct connection is still a known path. - return isPeerConnected(peerID) ? [] : nil - } - - /// Mesh graph for the topology map. Edges are advisory: announces cap - /// neighbor lists at 10, so an edge claimed by either endpoint counts. - func currentMeshTopology() -> MeshTopologySnapshot? { - refreshLocalTopology() - let claims = meshTopology.adjacencySnapshot() - var nodes = Set() - var edges = Set() - for (source, neighbors) in claims { - guard let sourcePeer = PeerID(routingData: source) else { continue } - nodes.insert(sourcePeer) - for neighborData in neighbors { - guard let neighborPeer = PeerID(routingData: neighborData), - neighborPeer != sourcePeer else { continue } - nodes.insert(neighborPeer) - edges.insert(MeshTopologyEdge(sourcePeer, neighborPeer)) - } - } - nodes.insert(myPeerID) - return MeshTopologySnapshot( - localPeerID: myPeerID, - nodes: nodes.sorted(), - edges: edges.sorted { ($0.a, $0.b) < ($1.a, $1.b) } - ) - } - - private func forwardAlongRouteIfNeeded(_ packet: BitchatPacket) -> Bool { - let myRoutingData = routingData(for: myPeerID) ?? (myPeerIDData.isEmpty ? nil : myPeerIDData) - let plan = BLERouteForwardingPolicy.plan( - for: packet, - localPeerID: myPeerID, - localRoutingData: myRoutingData, - routingPeer: routingPeer(from:), - isPeerConnected: isPeerConnected(_:) - ) - - if let forwardPacket = plan.forwardPacket, let nextHop = plan.nextHop { - sendPacketDirected(forwardPacket, to: nextHop) - } - - return plan.shouldSuppressFloodRelay - } - - private func links(to peerID: PeerID?) -> Set { - linkBindings.links(to: peerID) - } - - - - /// Marks the exact physical ingress link that completed a fresh Noise - /// handshake. An old session keyed only by peer ID is insufficient: a - /// replayed announce can rebind an attacker's link to that ID. - /// Engine-confined. - private func markNoiseAuthenticatedIngressLink(for packet: BitchatPacket, peerID: PeerID) { - guard let link = ingressLinks.link(for: packet) else { return } - guard linkBindings.boundPeer(for: link) == peerID else { return } - linkAuth.markAuthenticated(link, owner: peerID) - } - - private func isNoiseAuthenticatedIngressLink(for packet: BitchatPacket, peerID: PeerID) -> Bool { - guard let link = ingressLinks.link(for: packet) else { return false } - return linkAuth.isAuthenticated(link, for: peerID) && linkBindings.boundPeer(for: link) == peerID - } - - private func hasCurrentNoiseAuthenticatedLink(to peerID: PeerID) -> Bool { - !currentNoiseAuthenticatedLinks(to: peerID).isEmpty - } - - private func currentNoiseAuthenticatedLinks(to peerID: PeerID) -> Set { - Set(linkAuth.links(ownedBy: peerID).filter { link in - linkBindings.boundPeer(for: link) == peerID - }) - } - - /// A peer-level session can outlive the physical link that established it. - /// Revalidate a fresh direct link with an ordinary XX exchange, retiring - /// cached sending keys atomically before message 1 can leave. - /// - /// Takes the already-resolved ingress link. Engine-confined: it runs - /// inside the rebind's engine slot, so no observer can see the new - /// binding while a cached peer-level sender is still considered - /// established. - private func refreshNoiseSessionForVerifiedDirectLink( - link: BLEIngressLinkID, - peerID: PeerID - ) { - let hasEstablishedSession = noiseService.hasEstablishedSession(with: peerID) - let authenticatedPeerLinks = currentNoiseAuthenticatedLinks(to: peerID) - let shouldRevalidate: Bool - if linkBindings.boundPeer(for: link) == peerID { - shouldRevalidate = linkAuth.shouldRevalidate( - on: link, - for: peerID, - hasEstablishedSession: hasEstablishedSession, - hasAuthenticatedPeerLink: !authenticatedPeerLinks.isEmpty, - now: Date() - ) - } else { - shouldRevalidate = false - } - guard shouldRevalidate else { return } - - SecureLogger.info( - "🔄 Revalidating cached Noise session on fresh direct link to \(peerID.id.prefix(8))…", - category: .session - ) - initiateNoiseReconnectHandshake(with: peerID) - } - - 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 - // returning XX message 3. Serialize generation-bound state and - // every post-handshake drain behind the handshake packet handler. - self?.messageQueue.async { [weak self] in - self?.handleNoisePeerAuthenticated( - peerID: peerID, - fingerprint: fingerprint, - sessionGeneration: generation - ) - } - } - service.onRekeyHandshakeReady = { [weak self, weak service] peerID, initiation in - self?.messageQueue.async { [weak self, weak service] in - guard let self, - let service, - self.noiseService === service else { - return - } - self.noteNoiseSessionCleared(for: peerID) - guard let message = service.claimHandshakeInitiation( - initiation, - for: peerID - ) else { - return - } - self.broadcastNoiseHandshake(message, to: peerID) - } - } - service.onHandshakeRecoveryRequired = { [weak self, weak service] request in - guard let self, let service else { return } - #if DEBUG - self._test_beforeHandshakeRecoveryEnqueued?(request.peerID) - #endif - self.messageQueue.async { [weak self, weak service] in - guard let self, - let service, - self.noiseService === service else { - return - } - let peerID = request.peerID - guard self.isPeerReachable(peerID) else { - service.cancelHandshakeRecovery(request) - return - } - - do { - guard let preparation = - try service.prepareHandshakeRecovery(request) else { - return - } - switch preparation { - case .ordinary(let initiation): - self.noteNoiseSessionCleared(for: peerID) - guard let handshakeData = - service.claimHandshakeInitiation( - initiation, - for: peerID - ) else { - return - } - self.broadcastNoiseHandshake( - handshakeData, - to: peerID - ) - case .transferred: - return - } - } catch { - SecureLogger.error( - "Failed to prepare handshake recovery with \(peerID.id.prefix(8))…: \(error)", - category: .session - ) - } - } - } - service.onSessionRestoredWithGeneration = { [weak self, weak service] peerID, generation, reason in - guard let self, let service else { return } - // The manager makes restored keys visible atomically. Reconcile - // transport state and queued sends as the next serialized phase. - self.messageQueue.async { [weak self, weak service] in - guard let self, - let service, - self.noiseService === service, - let fingerprint = service.getPeerFingerprint(peerID) else { - return - } - SecureLogger.debug( - "🔐 Restored quarantined Noise session with \(peerID.id.prefix(8))…", - category: .session - ) - // Re-enter the same generation-bound transition used after a - // successful handshake to restore authenticated protocol - // state. Only a terminal restore may also drain the PM and - // typed-payload queues: after a responder timeout the - // counterpart may have completed the replacement handshake - // and discarded the restored keys, so encrypting the queues - // under them would lose every message silently. The mandatory - // convergence retry that accompanies the restore drains them - // under the new session instead (any establishment does). - self.handleNoisePeerAuthenticated( - peerID: peerID, - fingerprint: fingerprint, - sessionGeneration: generation, - deferOutboundUntilConvergence: reason == .pendingConvergence - ) - } - } - } - - private func handleNoisePeerAuthenticated( - peerID: PeerID, - fingerprint: String, - sessionGeneration generation: UUID, - deferOutboundUntilConvergence: Bool = false - ) { - // Engine-only: the store transition below runs inside the noise - // manager's critical section while this engine slot stays blocked. - // The store is a leaf lock, so that nesting is safe — but nothing in - // that closure may sync-re-enter the engine (self-deadlock). - #if DEBUG - dispatchPrecondition(condition: .onQueue(messageQueue)) - #endif - let normalizedPeerID = peerID.toShort() - // The generation lease serializes this transition against session - // replacement; nil-inside-nil distinguishes a lost lease (outer) - // from the same-generation reconciliation path (inner). - guard let leased = noiseService.withCurrentSessionGeneration( - for: normalizedPeerID, - expected: generation, - { - privateMediaSessions.beginAuthenticatedGeneration( - for: normalizedPeerID, - fingerprint: fingerprint, - generation: generation - ) - } - ) else { return } - - guard let fresh = leased else { - // A quarantined transport restored the same cryptographic - // generation. Its capability proof and announce state never - // became stale; only work queued while outbound keys were paused - // needs one idempotent ready transition. Retrying the bounded - // early-ciphertext queue is receive-side and therefore always - // safe under the restored keys. - noisePacketHandler.handleSessionAuthenticated(normalizedPeerID) - finalizeNoisePeerAuthentication( - for: normalizedPeerID, - deferOutboundUntilConvergence: deferOutboundUntilConvergence, - sendInitialStateAndAnnounce: false - ) - return - } - - completePrivateMediaPolicyResolution(fresh.rejected, with: .blockedDowngrade) - schedulePrivateMediaProofTimeout( - for: normalizedPeerID, - fingerprint: fingerprint, - sessionGeneration: generation, - nonce: fresh.watchdogNonce - ) - // Cross-link delivery can put ciphertext sent immediately after - // message 3 ahead of message 3 itself. Retry the bounded queue only - // after this generation's transport state has been fully installed. - noisePacketHandler.handleSessionAuthenticated(normalizedPeerID) - finalizeNoisePeerAuthentication( - for: normalizedPeerID, - deferOutboundUntilConvergence: deferOutboundUntilConvergence, - sendInitialStateAndAnnounce: true - ) - } - - private func finalizeNoisePeerAuthentication( - for peerID: PeerID, - deferOutboundUntilConvergence: Bool, - sendInitialStateAndAnnounce: Bool - ) { - if deferOutboundUntilConvergence { - // Timeout-restore: the counterpart may have completed the - // replacement handshake and discarded these keys, so encrypting - // the parked queues here would lose them silently. The restore's - // mandatory convergence retry — or any later handshake — re-enters - // with a fresh generation and drains them under keys both sides hold. - privateMediaSessions.setOutboundDeferredUntilConvergence(peerID) - #if DEBUG - _test_onPrivateMediaSessionReconciled?(peerID) - #endif - return - } - privateMediaSessions.clearOutboundDeferredUntilConvergence(peerID) - if sendInitialStateAndAnnounce { - sendAuthenticatedPeerState(to: peerID, echo: false) - } - #if DEBUG - _test_onPrivateMediaSessionReconciled?(peerID) - #endif - sendPendingMessagesAfterHandshake(for: peerID) - sendPendingNoisePayloadsAfterHandshake(for: peerID) - if sendInitialStateAndAnnounce { - sendAnnounce(forceSend: true) - } - } - - private func sendAuthenticatedPeerState(to peerID: PeerID, echo: Bool) { - let normalizedPeerID = peerID.toShort() - guard privateMediaSessions.markPeerStateSend(for: normalizedPeerID, echo: echo) else { return } - - let capabilities = localIdentityState.snapshot().advertisedCapabilities - let state = AuthenticatedPeerStatePacket( - capabilities: capabilities, - signingPublicKey: noiseService.getSigningPublicKeyData() - ) - guard let payload = BLENoisePayloadFactory.authenticatedPeerState(state) else { - SecureLogger.error("Failed to encode authenticated peer state", category: .security) - return - } - sendNoisePayload(payload, to: normalizedPeerID) - } - - private func handleAuthenticatedPeerState( - _ payload: Data, - from peerID: PeerID, - sessionGeneration generation: UUID - ) { - // Engine-only, like handleNoisePeerAuthenticated: the closure below - // runs on the noise manager's queue while this engine slot stays - // blocked, so it accesses engine-owned state directly instead of - // sync-re-entering the engine (self-deadlock). - #if DEBUG - dispatchPrecondition(condition: .onQueue(messageQueue)) - #endif - let normalizedPeerID = peerID.toShort() - guard let state = AuthenticatedPeerStatePacket.decode(from: payload) else { - SecureLogger.warning( - "Ignoring malformed authenticated peer state from \(normalizedPeerID.id.prefix(8))…", - category: .security - ) - return - } - guard let fingerprint = noiseService.getPeerFingerprint(normalizedPeerID), - let publicKey = noiseService.getPeerPublicKeyData(normalizedPeerID), - publicKey.sha256Fingerprint().caseInsensitiveCompare(fingerprint) == .orderedSame else { - SecureLogger.warning( - "Ignoring peer state without a matching authenticated Noise identity", - category: .security - ) - return - } - guard let application = noiseService.withCurrentSessionGeneration( - for: normalizedPeerID, - expected: generation, - { - () -> (accepted: Bool, completions: [@MainActor (PrivateMediaSendPolicy) -> Void]) in - guard privateMediaSessions.currentGeneration(for: normalizedPeerID) == generation else { - return (false, []) - } - - // The generation lease (plus the engine slot this section - // holds) prevents rekey/session promotion from interleaving - // between validation and these durable mutations. - identityManager.bindAuthenticatedSigningPublicKey( - state.signingPublicKey, - fingerprint: fingerprint - ) - identityManager.upsertCryptographicIdentity( - fingerprint: fingerprint, - noisePublicKey: publicKey, - signingPublicKey: state.signingPublicKey, - claimedNickname: nil - ) - if state.capabilities.contains(.privateMedia) { - identityManager.markPrivateMediaCapable(fingerprint: fingerprint) - } - - peerRegistry.mutate { - $0.bindAuthenticatedSigningPublicKey( - state.signingPublicKey, - for: normalizedPeerID - ) - } - guard let completions = privateMediaSessions.applyAuthenticatedPeerState( - for: normalizedPeerID, - fingerprint: fingerprint, - generation: generation, - capabilities: state.capabilities - ) else { - return (false, []) - } - return (true, completions) - } - ), application.accepted else { return } - - // One bounded echo makes initiator/responder proof ordering converge - // even when message 3 and the first proof take different mesh links. - sendAuthenticatedPeerState(to: normalizedPeerID, echo: true) - let policy = privateMediaSendPolicy(to: normalizedPeerID) - sendPendingNoisePayloadsAfterHandshake(for: normalizedPeerID) - completePrivateMediaPolicyResolution(application.completions, with: policy) - } - - private func noteNoiseSessionCleared(for peerID: PeerID) { - let normalizedPeerID = peerID.toShort() - let reset = privateMediaSessions.clearSession(for: normalizedPeerID) - if let reset { - schedulePrivateMediaProofTimeout( - for: normalizedPeerID, - fingerprint: reset.fingerprint, - sessionGeneration: nil, - nonce: reset.nonce - ) - } - } - - private func clearNoiseSession(for peerID: PeerID) { - noiseService.clearSession(for: peerID) - noteNoiseSessionCleared(for: peerID) - } - - /// Swaps `myPeerID`/`myPeerIDData` to match the current Noise identity. - /// The swap runs as a `messageQueue` barrier so in-flight work items that - /// read the identity (e.g. `sendMessage` building packets) complete - /// against the old value and everything after sees the new one atomically. - /// Callers (init, panic reset on the main thread) are never on - /// `messageQueue`; the re-entrancy check keeps any future on-queue caller - /// from deadlocking. - private func refreshPeerIdentity() { - onEngine { - let fingerprint = noiseService.getIdentityFingerprint() - localIdentityState.replacePeerIdentity( - with: PeerID(str: fingerprint.prefix(16)) - ) - meshTopology.reset() - } - } - - - - private func sendNoisePayload(_ typedPayload: Data, to peerID: PeerID) { - sendOrQueueNoisePayload( - typedPayload, - to: peerID, - initiateOnlyIfReachable: false, - logLabel: "noise payload" - ) - } - - private func sendOrQueueNoisePayload( - _ typedPayload: Data, - to peerID: PeerID, - initiateOnlyIfReachable: Bool, - logLabel: String - ) { - // Hop like sendMessage: callers are often on the main actor, and the - // send path sync-waits on bleQueue for link state. - if DispatchQueue.getSpecific(key: messageQueueKey) == nil { - messageQueue.async { [weak self] in - self?.sendOrQueueNoisePayload( - typedPayload, - to: peerID, - initiateOnlyIfReachable: initiateOnlyIfReachable, - logLabel: logLabel - ) - } - return - } - guard noiseService.hasEstablishedSession(with: peerID) else { - pendingNoiseSessionQueues.appendTypedPayload(typedPayload, for: peerID) - SecureLogger.debug("📥 Queued \(logLabel) for \(peerID.id.prefix(8))… pending handshake", category: .session) - if !initiateOnlyIfReachable || (!noiseService.hasSession(with: peerID) && isPeerReachable(peerID)) { - initiateNoiseHandshake(with: peerID) - } - return - } - do { - broadcastPacket(try makeEncryptedNoisePacket(typedPayload, to: peerID)) - } catch { - SecureLogger.error("Failed to send \(logLabel): \(error)") - } - } - - private func makeEncryptedNoisePacket( - _ typedPayload: Data, - to peerID: PeerID, - requiresAuthenticatedPrivateMediaReceipts: Bool = false - ) throws -> BitchatPacket { - let encrypted: Data - let isPrivateFile = NoisePayloadType.isPrivateFile(rawValue: typedPayload.first) - if isPrivateFile { - let provenGeneration = privateMediaSessions.provenGeneration( - for: peerID, - requireReceipts: requiresAuthenticatedPrivateMediaReceipts - ) - guard let provenGeneration else { - throw NoiseEncryptionError.sessionNotEstablished - } - encrypted = try noiseService.encryptPrivateFilePayload( - typedPayload, - for: peerID, - sessionGeneration: provenGeneration - ) - } else { - encrypted = try noiseService.encrypt(typedPayload, for: peerID) - } - return BitchatPacket( - type: MessageType.noiseEncrypted.rawValue, - senderID: myPeerIDData, - recipientID: Data(hexString: peerID.id), - timestamp: UInt64(Date().timeIntervalSince1970 * 1000), - payload: encrypted, - signature: nil, - ttl: messageTTL, - // v1 has a 16-bit payload length; finalized media can exceed it. - version: isPrivateFile ? 2 : 1 - ) - } - - // MARK: Courier Store-and-Forward - - /// Seal `content` for the recipient and hand the envelope to the given - /// couriers for physical delivery. When a verified one-time prekey bundle - /// is cached for the recipient, sealing targets one of its prekeys - /// (forward secret, envelope v2); otherwise it falls back to their static - /// key (one-way Noise X, v1) exactly as before. Returns false when no - /// courier is connected, the payload cannot be built, or sealing fails; - /// link writes are queued asynchronously after the envelope is ready. - private func sealCourierEnvelope( - _ content: String, - messageID: String, - recipientNoiseKey: Data, - copies: UInt8 - ) -> CourierEnvelope? { - guard let typedPayload = BLENoisePayloadFactory.privateMessage(content: content, messageID: messageID) else { - return nil - } - do { - let now = Date() - let sealed: Data - let prekeyID: UInt32? - if let prekey = assignRecipientPrekey(messageID: messageID, recipientNoiseKey: recipientNoiseKey) { - sealed = try noiseService.sealPrekeyPayload(typedPayload, recipientPrekey: prekey) - prekeyID = prekey.id - } else { - sealed = try noiseService.sealCourierPayload(typedPayload, recipientStaticKey: recipientNoiseKey) - prekeyID = nil - } - return CourierEnvelope( - recipientTag: CourierEnvelope.recipientTag( - noiseStaticKey: recipientNoiseKey, - epochDay: CourierEnvelope.epochDay(for: now) - ), - expiry: UInt64((now.timeIntervalSince1970 + CourierEnvelope.maxLifetimeSeconds) * 1000), - ciphertext: sealed, - copies: copies, - prekeyID: prekeyID - ) - } catch { - SecureLogger.error("Failed to seal courier envelope: \(error)", category: .encryption) - return nil - } - } - - func sendCourierMessage(_ content: String, messageID: String, recipientNoiseKey: Data, via couriers: [PeerID]) -> Bool { - let connected = couriers.filter { isPeerConnected($0) } - guard !connected.isEmpty, - let envelope = sealCourierEnvelope( - content, - messageID: messageID, - recipientNoiseKey: recipientNoiseKey, - copies: TransportConfig.courierInitialCopies - ), - let payload = envelope.encode() else { - return false - } - - messageQueue.async { [weak self] in - guard let self else { return } - for courier in connected { - SecureLogger.debug("📦 Depositing courier envelope with \(courier.id.prefix(8))… id=\(messageID.prefix(8))…", category: .session) - self.sendPacketDirected(self.makeCourierPacket(payload, to: courier), to: courier) - } - } - return true - } - - // MARK: Courier over the bridge - - /// Seals `content` into a courier envelope for relay parking (a bridge - /// courier drop). Same sealing rules as `sendCourierMessage` — prekey - /// (v2) when a verified bundle is cached, static Noise X (v1) otherwise — - /// but carry-only: a relay copy never sprays. - func sealBridgeCourierEnvelope(_ content: String, messageID: String, recipientNoiseKey: Data) -> CourierEnvelope? { - sealCourierEnvelope(content, messageID: messageID, recipientNoiseKey: recipientNoiseKey, copies: 1) - } - - /// Opens a courier envelope that arrived as a bridge drop (relay fetch, - /// not a directed mesh packet). Returns false when the rotating tag does - /// not match our static key — a drop for someone else, or a stale tag. - /// The inner Noise X seal authenticates the sender; there is no packet - /// signature to check on this path. - @discardableResult - func openBridgedCourierEnvelope(_ envelope: CourierEnvelope) -> Bool { - guard !envelope.isExpired else { return false } - let myKey = noiseService.getStaticPublicKeyData() - guard CourierEnvelope.candidateTags(noiseStaticKey: myKey, around: Date()).contains(envelope.recipientTag) else { - return false - } - return openCourierEnvelope(envelope) - } - - /// Hands a bridge-fetched envelope directly to the matching local peer - /// as a directed courier packet. Delivery-only by design: the recipient's - /// tag matched, so this never lands in a stranger's carry quota. - /// Returns true only if a current Noise-authenticated physical link - /// accepted the packet; a stale peer-level session, reachability record, - /// replay-rebound link, or process-local spool is not delivery. - @discardableResult - func deliverBridgedEnvelope(_ envelope: CourierEnvelope, to peerID: PeerID) -> Bool { - guard let payload = envelope.encode() else { return false } - let packet = makeCourierPacket(payload, to: peerID) - return onEngine { - // Engine slot: the auth-link check and the directed send see one - // consistent view of the identity domain. - guard hasCurrentNoiseAuthenticatedLink(to: peerID) else { return false } - return sendPacketDirected( - packet, - to: peerID, - requireDirectPeerLink: true, - requireNoiseAuthenticatedPeerLink: true - ) - } - } - - /// Verified reachable peers with known Noise keys — the set a bridge - /// gateway watches courier drops for. - func verifiedPeersWithNoiseKeys() -> [(peerID: PeerID, noiseKey: Data)] { - let now = Date() - return onEngine { - peerRegistry.snapshotByID.values.compactMap { info in - guard info.isVerifiedNickname, - let key = info.noisePublicKey, - peerRegistry.isReachable(info.peerID, now: now) else { return nil } - return (info.peerID, key) - } - } - } - - /// The prekey to seal a courier message with, or nil to fall back to - /// static sealing. The real signal is a verified, unexpired bundle with a - /// spare prekey; the advertised `.prekeys` capability only acts as a veto - /// for peers we currently see on the mesh (a cached bundle can outlive a - /// peer's downgrade to a build that no longer holds the privates). - /// Re-deposits of the same message reuse its assigned prekey, so one - /// message consumes exactly one prekey ID regardless of courier count. - private func assignRecipientPrekey(messageID: String, recipientNoiseKey: Data) -> PrekeyBundle.Prekey? { - let shortID = PeerID(publicKey: recipientNoiseKey) - let knownOnMesh = peerRegistry.info(for: shortID) != nil - if knownOnMesh, !peerCapabilities(shortID).contains(.prekeys) { - return nil - } - return prekeyBundleStore.assignPrekey(messageID: messageID, recipientNoiseKey: recipientNoiseKey) - } - - private func makeCourierPacket(_ payload: Data, to peerID: PeerID) -> BitchatPacket { - let packet = BitchatPacket( - type: MessageType.courierEnvelope.rawValue, - senderID: myPeerIDData, - recipientID: Data(hexString: peerID.id), - timestamp: UInt64(Date().timeIntervalSince1970 * 1000), - payload: payload, - signature: nil, - ttl: messageTTL - ) - // Signed so a courier can authenticate the depositor before carrying - // mail under their quota. Handover to the recipient doesn't need the - // packet signature — the inner Noise X seal authenticates the sender. - return noiseService.signPacket(packet) ?? packet - } - - /// Handles both courier roles for an incoming envelope addressed to us: - /// recipient (the rotating tag matches our static key → open and deliver) - /// or courier (a trusted peer is depositing mail for someone else → store). - private func handleCourierEnvelope(_ packet: BitchatPacket, from peerID: PeerID) { - // Directed packets only; envelopes addressed elsewhere ride the - // generic relay path untouched. - guard packet.recipientID == myPeerIDData else { return } - guard let envelope = CourierEnvelope.decode(packet.payload), !envelope.isExpired else { return } - - let myKey = noiseService.getStaticPublicKeyData() - if CourierEnvelope.candidateTags(noiseStaticKey: myKey, around: Date()).contains(envelope.recipientTag) { - openCourierEnvelope(envelope) - } else { - acceptCourierDeposit(envelope, from: peerID, packet: packet) - } - } - - @discardableResult - private func openCourierEnvelope(_ envelope: CourierEnvelope) -> Bool { - do { - let typedPayload: Data - let senderStaticKey: Data - if let prekeyID = envelope.prekeyID { - // Envelope v2: sealed to one of our one-time prekeys. Opening - // consumes the prekey (48h redelivery grace), which shrinks our - // published bundle under a strictly newer generatedAt. Re-gossip - // so peers replace their cached copy and stop assigning the - // consumed ID before the grace lapses; force the broadcast when - // the batch also topped back up (low-water), otherwise let the - // rebroadcast throttle coalesce bursts. - let opened = try noiseService.openPrekeyPayload(envelope.ciphertext, prekeyID: prekeyID) - (typedPayload, senderStaticKey) = (opened.payload, opened.senderStaticKey) - if opened.consumedPrekey { - let replenished = noiseService.replenishPrekeysIfNeeded() - sendPrekeyBundle(force: replenished) - } - } else { - (typedPayload, senderStaticKey) = try noiseService.openCourierPayload(envelope.ciphertext) - } - guard let typeRaw = typedPayload.first, - let payloadType = NoisePayloadType(rawValue: typeRaw), - payloadType == .privateMessage else { - SecureLogger.warning("⚠️ Courier envelope carried unsupported payload type", category: .session) - return true // decrypted but deterministically unsupported - } - let payload = Data(typedPayload.dropFirst()) - guard let innerMessageID = PrivateMessagePacket.decode(from: payload)?.messageID else { - SecureLogger.warning("⚠️ Courier envelope carried undecodable private message", category: .session) - return true // decrypted but deterministically malformed - } - // Redundant copies of one message arrive as distinct envelopes - // (fresh seal each: mesh couriers, bridge drops across relays), - // so dedup here on the inner message ID — before delivery, ack, - // and handshake work. A duplicate costs only the decrypt above - // and at most one ack ever goes out per message ID. - let firstOpen = onEngine { - openedCourierMessageIDs.insert(innerMessageID) - } - guard firstOpen else { - SecureLogger.debug("📦 Dropping duplicate courier envelope for message \(innerMessageID.prefix(8))…", category: .session) - return true - } - // Couriered mail arrives while the sender is absent, so the UI's - // block check can't resolve their fingerprint from a live session. - // Gate here, where the full static key is in hand. - guard !identityManager.isBlocked(fingerprint: senderStaticKey.sha256Fingerprint()) else { - SecureLogger.debug("🚫 Dropping courier envelope from blocked sender", category: .security) - return true - } - // A present sender resolves to their live mesh thread via the - // derived short ID. An absent sender — the usual courier case — - // uses the full noise-key ID so the message lands on the stable - // favorite conversation instead of an unresolvable short-ID - // thread labeled "Unknown". - let shortID = PeerID(publicKey: senderStaticKey) - let isKnownOnMesh = peerRegistry.info(for: shortID) != nil - let senderPeerID = isKnownOnMesh ? shortID : PeerID(hexData: senderStaticKey) - SecureLogger.debug("📦 Opened courier envelope from \(senderPeerID.id.prefix(8))…", category: .session) - notifyUI { [weak self] in - self?.deliverTransportEvent(.noisePayloadReceived( - peerID: senderPeerID, - type: payloadType, - payload: payload, - timestamp: Date() - )) - } - return true - } catch { - // Tag collision or stale key: not addressed to us after all. - SecureLogger.debug("📦 Courier envelope failed to open: \(error)", category: .encryption) - return false - } - } - - private func acceptCourierDeposit(_ envelope: CourierEnvelope, from peerID: PeerID, packet: BitchatPacket) { - // A deposit must come from its depositor over the direct link: the - // claimed sender has to be the ingress peer, and the packet signature - // has to verify against that peer's announced signing key. Otherwise - // an untrusted sender could route an envelope through any trusted - // neighbor and have us carry it under the neighbor's quota. - guard PeerID(hexData: packet.senderID) == peerID else { - SecureLogger.debug("📦 Courier deposit rejected: relayed envelope claims sender \(PeerID(hexData: packet.senderID).id.prefix(8))… but arrived from \(peerID.id.prefix(8))…", category: .security) - return - } - let depositorInfo = peerRegistry.info(for: peerID) - guard let depositorKey = depositorInfo?.noisePublicKey else { - SecureLogger.debug("📦 Courier deposit from unknown peer \(peerID.id.prefix(8))… rejected", category: .session) - return - } - guard let signingKey = depositorInfo?.signingPublicKey, - noiseService.verifyPacketSignature(packet, publicKey: signingKey) else { - SecureLogger.debug("📦 Courier deposit from \(peerID.id.prefix(8))… rejected (missing/invalid signature)", category: .security) - return - } - let isVerifiedPeer = depositorInfo?.isVerifiedNickname ?? false - let store = courierStore - let policy = courierDepositPolicy - notifyUI { [weak self] in - guard let self else { return } - guard let tier = policy(depositorKey, isVerifiedPeer) else { - SecureLogger.debug("📦 Courier deposit from \(peerID.id.prefix(8))… rejected (neither favorite nor verified)", category: .session) - return - } - self.messageQueue.async { - if store.deposit(envelope, from: depositorKey, tier: tier) { - SecureLogger.debug("📦 Carrying courier envelope deposited by \(peerID.id.prefix(8))… (\(tier.rawValue))", category: .session) - } - } - } - } - - /// Hand over any carried envelopes addressed to a peer we just heard from. - private func deliverCourierMail(to peerID: PeerID, noiseKey: Data) { - let accepted = courierStore.handoverEnvelopes(for: noiseKey) { [weak self] envelope in - guard let self, - let payload = envelope.encode(), - self.sendPacketDirected( - self.makeCourierPacket(payload, to: peerID), - to: peerID, - requireDirectPeerLink: true, - requireNoiseAuthenticatedPeerLink: true - ) else { - return false - } - return true - } - if accepted > 0 { - SecureLogger.debug("📦 Handed over \(accepted) courier envelope(s) to \(peerID.id.prefix(8))…", category: .session) - } - } - - /// Speculative handover toward a recipient heard only via a relayed - /// announce: the envelope floods the mesh as a directed packet (relays - /// treat it like a directed DM). Non-destructive — the carried copy stays - /// until a direct handover or expiry, throttled per envelope so repeated - /// announces don't re-flood. - private func deliverCourierMailRemotely(to peerID: PeerID, noiseKey: Data) { - let envelopes = courierStore.envelopesForRemoteHandover( - recipientNoiseKey: noiseKey, - cooldown: TransportConfig.courierRemoteHandoverCooldownSeconds - ) - guard !envelopes.isEmpty else { return } - SecureLogger.debug("📦 Remote handover: flooding \(envelopes.count) envelope(s) toward \(peerID.id.prefix(8))…", category: .session) - for envelope in envelopes { - guard let payload = envelope.encode() else { continue } - broadcastPacket(makeCourierPacket(payload, to: peerID)) - } - } - - /// Spray-and-wait: split copy budgets with another courier we just - /// encountered, so carried mail diffuses through a moving crowd instead - /// of riding a single carrier. Only favorites and verified peers qualify, - /// mirroring the deposit policy they would apply to us. - private func sprayCourierMail(to peerID: PeerID, noiseKey: Data, isVerifiedPeer: Bool) { - let store = courierStore - let sendSpray: () -> Void = { [weak self] in - guard let self else { return } - let accepted = store.transferSprayCopies(to: noiseKey) { envelope in - guard let payload = envelope.encode(), - self.sendPacketDirected( - self.makeCourierPacket(payload, to: peerID), - to: peerID, - requireDirectPeerLink: true, - requireNoiseAuthenticatedPeerLink: true - ) else { - return false - } - return true - } - if accepted > 0 { - SecureLogger.debug("📦 Sprayed \(accepted) envelope copy(ies) to courier \(peerID.id.prefix(8))…", category: .session) - } - } - let policy = courierDepositPolicy - notifyUI { [weak self] in - guard let self else { return } - // Same trust gate as deposits: don't hand mail to a peer who - // would reject it from us. - guard policy(noiseKey, isVerifiedPeer) != nil else { return } - self.messageQueue.async { - sendSpray() - } - } - } - - // MARK: One-Time Prekey Bundles - - /// Broadcasts our signed prekey bundle and tracks it for gossip sync. - /// Unforced sends (piggybacked on announces) are throttled — gossip does - /// the spreading, the broadcast just keeps our own gossip entry fresh. - /// Forced sends (bundle changed after consumption) go immediately. - private func sendPrekeyBundle(force: Bool = false) { - let now = Date() - let shouldSend: Bool = onEngine { - if !force, - let last = lastPrekeyBundleSentAt, - now.timeIntervalSince(last) < TransportConfig.prekeyBundleRebroadcastSeconds { - return false - } - lastPrekeyBundleSentAt = now - return true - } - guard shouldSend else { return } - guard let bundle = noiseService.currentPrekeyBundle(), - let payload = bundle.encode() else { - SecureLogger.error("❌ Failed to build prekey bundle", category: .security) - return - } - guard let signedPacket = buildSignedBroadcastPacket( - type: .prekeyBundle, - payload: payload, - timestamp: now, - logLabel: "prekey bundle packet" - ) else { return } - if DispatchQueue.getSpecific(key: messageQueueKey) != nil { - broadcastPacket(signedPacket) - } else { - messageQueue.async { [weak self] in - self?.broadcastPacket(signedPacket) - } - } - gossipSyncManager?.onPublicPacketSeen(signedPacket) - } - - /// Ingests a gossiped prekey bundle. Attribution is layered: the outer - /// packet must originate from the bundle owner (fabricated sender IDs, used - /// to multiply cache/gossip entries, are rejected), and BOTH the inner - /// bundle signature and the outer packet signature must verify against the - /// owner's announce-bound signing key. Verifying the outer packet — whose - /// signed bytes cover senderID and timestamp — stops a valid bundle from - /// being replayed under a fresh timestamp or spoofed sender to pass - /// freshness or poison attribution. Only after that does the packet enter - /// our own gossip store, so we never help spread a bundle we couldn't - /// attribute. - @discardableResult - private func handlePrekeyBundle(_ packet: BitchatPacket, from peerID: PeerID) -> Bool { - guard let bundle = PrekeyBundle.decode(packet.payload) else { - SecureLogger.debug("🔑 Ignoring malformed prekey bundle from \(peerID.id.prefix(8))…", category: .security) - return false - } - // Our own bundle is tracked at send time; a copy echoing back adds nothing. - guard bundle.noiseStaticPublicKey != noiseService.getStaticPublicKeyData() else { return false } - let owner = PeerID(publicKey: bundle.noiseStaticPublicKey) - // The owner's genuine bundle (direct or relayed) always carries the - // owner's senderID + outer signature; gossip resends preserve both. A - // packet whose senderID isn't the owner can't be authenticated here. - guard PeerID(hexData: packet.senderID) == owner else { - SecureLogger.debug("🔑 Ignoring prekey bundle whose sender ≠ owner \(owner.id.prefix(8))…", category: .security) - return false - } - guard let signingKey = announceBoundSigningKey(forNoiseKey: bundle.noiseStaticPublicKey, owner: owner) else { - // No binding yet: retain the latest bundle per owner, bounded, and - // retry once the verified announce lands (engine-confined on messageQueue). - if pendingPrekeyBundles[owner] != nil - || pendingPrekeyBundles.count < Self.pendingPrekeyBundleCap { - pendingPrekeyBundles[owner] = packet - } - SecureLogger.debug("🔑 Deferring prekey bundle without a bound signing key (owner \(owner.id.prefix(8))…)", category: .security) - return false - } - return ingestVerifiedPrekeyBundle(bundle, packet: packet, owner: owner, signingKey: signingKey) - } - - /// Verify a bundle's inner + outer signatures against the owner's bound - /// signing key and, on success, cache it and let it enter our gossip store. - @discardableResult - private func ingestVerifiedPrekeyBundle(_ bundle: PrekeyBundle, packet: BitchatPacket, owner: PeerID, signingKey: Data) -> Bool { - guard noiseService.verifyPrekeyBundleSignature(bundle, signingPublicKey: signingKey), - noiseService.verifyPacketSignature(packet, publicKey: signingKey) else { - SecureLogger.debug("🔑 Ignoring prekey bundle without verifiable signature (owner \(owner.id.prefix(8))…)", category: .security) - return false - } - if prekeyBundleStore.ingest(bundle) { - SecureLogger.debug("🔑 Cached prekey bundle for \(owner.id.prefix(8))… (\(bundle.prekeys.count) prekeys)", category: .security) - } - gossipSyncManager?.onPublicPacketSeen(packet) - return true - } - - /// Re-attempt any prekey bundle that arrived before this owner's announce - /// bound a signing key. Called from handleAnnounce on messageQueue. - private func drainPendingPrekeyBundles(for owner: PeerID) { - guard let packet = pendingPrekeyBundles.removeValue(forKey: owner), - let bundle = PrekeyBundle.decode(packet.payload), - let signingKey = announceBoundSigningKey(forNoiseKey: bundle.noiseStaticPublicKey, owner: owner) else { return } - ingestVerifiedPrekeyBundle(bundle, packet: packet, owner: owner, signingKey: signingKey) - } - - /// Ed25519 signing key bound to a Noise static key by a verified - /// announce: from the live registry when the owner is on the mesh, else - /// from identities persisted for offline verification. - private func announceBoundSigningKey(forNoiseKey noiseKey: Data, owner: PeerID? = nil) -> Data? { - let shortID = owner ?? PeerID(publicKey: noiseKey) - if let info = peerRegistry.info(for: shortID), - info.noisePublicKey == noiseKey, - let signingKey = info.signingPublicKey { - return signingKey - } - for candidate in identityManager.getCryptoIdentitiesByPeerIDPrefix(shortID) - where candidate.publicKey == noiseKey { - if let signingKey = candidate.signingPublicKey { - return signingKey - } - } - return nil - } - - // MARK: Gateway carrier (nostrCarrier) - - /// Sign and send an encoded `toGateway` carrier payload directed at a - /// gateway peer. The packet is signed so the gateway can key its uplink - /// quotas to an authenticated depositor; the carried Nostr event has its - /// own Schnorr signature for content authenticity. Returns false when - /// the gateway is not reachable or signing fails. - func sendNostrCarrier(_ payload: Data, to gatewayPeer: PeerID) -> Bool { - guard isPeerReachable(gatewayPeer) else { return false } - let packet = BitchatPacket( - type: MessageType.nostrCarrier.rawValue, - senderID: myPeerIDData, - recipientID: Data(hexString: gatewayPeer.id), - timestamp: UInt64(Date().timeIntervalSince1970 * 1000), - payload: payload, - signature: nil, - ttl: messageTTL - ) - guard let signed = noiseService.signPacket(packet) else { return false } - messageQueue.async { [weak self] in - // broadcastPacket applies a known route when one exists and - // otherwise floods the directed packet like a DM, so a gateway - // that is reachable but multi-hop still gets the deposit. - self?.broadcastPacket(signed) - } - return true - } - - /// Broadcast an encoded `fromGateway` carrier payload on the mesh with - /// the default TTL. Unsigned at the packet layer — receivers verify the - /// carried event's own Schnorr signature. - func broadcastNostrCarrier(_ payload: Data) { - let packet = BitchatPacket( - type: MessageType.nostrCarrier.rawValue, - senderID: myPeerIDData, - recipientID: nil, - timestamp: UInt64(Date().timeIntervalSince1970 * 1000), - payload: payload, - signature: nil, - ttl: messageTTL - ) - messageQueue.async { [weak self] in - self?.broadcastPacket(packet) - } - } - - /// Transport-level handling for a received nostrCarrier packet; policy - /// (verification of the carried event, quotas, loop prevention) lives in - /// `GatewayService` behind `onNostrCarrierPacket`. - private func handleNostrCarrier(_ packet: BitchatPacket, from _: PeerID) { - let senderID = PeerID(hexData: packet.senderID) - let directedToUs: Bool - if let recipientID = packet.recipientID { - // Carriers addressed elsewhere ride the generic relay path untouched. - guard recipientID == myPeerIDData else { return } - // Uplink deposit: quotas are keyed by the depositor, so the - // packet signature must verify against the sender's announced - // signing key. Unlike courier deposits the depositor may be - // multi-hop away, so ingress-link identity is not required. - let signingKey = peerRegistry.info(for: senderID)?.signingPublicKey - guard let signingKey, - noiseService.verifyPacketSignature(packet, publicKey: signingKey) else { - SecureLogger.debug("🌐 nostrCarrier uplink from \(senderID.id.prefix(8))… rejected (missing/invalid packet signature)", category: .security) - return - } - directedToUs = true - } else { - directedToUs = false - } - let payload = packet.payload - notifyUI { [weak self] in - self?.onNostrCarrierPacket?(payload, senderID, directedToUs) - } - } - // MARK: Link capability snapshots // Physical link state is bleQueue-owned; the engine (and main) may // sync-read it here. The bindings half of a combined view comes from @@ -5348,7 +3689,7 @@ extension BLEService { } } - private func initiateNoiseHandshake(with peerID: PeerID) { + func initiateNoiseHandshake(with peerID: PeerID) { let service = noiseService do { guard let initiation = try service.initiateHandshakeIfNeeded( @@ -5374,7 +3715,7 @@ extension BLEService { } } - private func broadcastNoiseHandshake(_ handshakeData: Data, to peerID: PeerID) { + func broadcastNoiseHandshake(_ handshakeData: Data, to peerID: PeerID) { let packet = BitchatPacket( type: MessageType.noiseHandshake.rawValue, senderID: myPeerIDData, @@ -5391,7 +3732,7 @@ extension BLEService { /// the initiator before atomically retiring the cached transport; the /// one-shot claim prevents a crossed inbound message from making a stale /// message 1 leave after this peer has already become responder. - private func initiateNoiseReconnectHandshake(with peerID: PeerID) { + func initiateNoiseReconnectHandshake(with peerID: PeerID) { let service = noiseService do { let initiation = try service.initiateReconnectHandshake( @@ -5423,7 +3764,7 @@ extension BLEService { } } - private func sendPendingMessagesAfterHandshake(for peerID: PeerID) { + func sendPendingMessagesAfterHandshake(for peerID: PeerID) { // Atomically take all pending messages to process (prevents concurrent modification) let pendingMessages = onEngine { () -> [BLEPendingPrivateMessage] in pendingNoiseSessionQueues.takePrivateMessages(for: peerID) @@ -5953,7 +4294,7 @@ extension BLEService { handleReceivedPacket(packet, from: context.receivedFromPeerID, precomputedMessageID: messageID) } - private func handleReceivedPacket( + func handleReceivedPacket( _ packet: BitchatPacket, from peerID: PeerID, precomputedMessageID: String? = nil @@ -6938,7 +5279,7 @@ extension BLEService { // MARK: Helper Functions - private func sendPendingNoisePayloadsAfterHandshake(for peerID: PeerID) { + func sendPendingNoisePayloadsAfterHandshake(for peerID: PeerID) { let payloads = onEngine { () -> [BLEPendingTypedPayload] in pendingNoiseSessionQueues.takeTypedPayloads(for: peerID) } diff --git a/bitchat/Services/BLE/BLESourceRouteFailureCache.swift b/bitchat/Services/BLE/BLESourceRouteFailureCache.swift deleted file mode 100644 index fcf23d2c..00000000 --- a/bitchat/Services/BLE/BLESourceRouteFailureCache.swift +++ /dev/null @@ -1,95 +0,0 @@ -import BitFoundation -import Foundation - -/// Tracks whether source-routed sends to a recipient appear to be working. -/// -/// A routed unicast rides exactly one path, so a broken hop silently loses the -/// packet where a flood would have healed around it. Rather than building a -/// retransmission machine (MessageRouter already retries at a higher layer), -/// this cache degrades: a routed send that sees no inbound traffic from the -/// recipient within the confirmation window marks the route as failed, and -/// subsequent sends fall back to flooding until the suppression TTL lapses. -struct BLESourceRouteFailureCache { - struct Config { - /// How long a routed send may go unconfirmed before it counts as a - /// route failure. - var confirmationWindowSeconds: TimeInterval = TransportConfig.bleSourceRouteConfirmationWindowSeconds - /// How long to flood instead of routing after a failure. - var suppressionSeconds: TimeInterval = TransportConfig.bleSourceRouteSuppressionSeconds - } - - private struct State { - var pendingSince: Date? - var suppressedUntil: Date? - } - - private let config: Config - private var states: [PeerID: State] = [:] - - init(config: Config = Config()) { - self.config = config - } - - /// Whether the next directed send to `recipient` may carry a source - /// route. Flips the recipient into suppression when the last routed send - /// went unconfirmed past the confirmation window. - mutating func shouldAttemptRoute(to recipient: PeerID, now: Date = Date()) -> Bool { - guard var state = states[recipient] else { return true } - - if let until = state.suppressedUntil { - guard now >= until else { return false } - state.suppressedUntil = nil - } - - if let pending = state.pendingSince, - now.timeIntervalSince(pending) > config.confirmationWindowSeconds { - // The routed send was never confirmed: treat the route as broken - // and flood until the suppression window lapses. - state.pendingSince = nil - state.suppressedUntil = now.addingTimeInterval(config.suppressionSeconds) - states[recipient] = state - return false - } - - states[recipient] = state - return true - } - - /// Records that a source-routed packet was sent to `recipient`. Keeps the - /// earliest unconfirmed send so back-to-back packets share one deadline. - mutating func noteRoutedSend(to recipient: PeerID, now: Date = Date()) { - var state = states[recipient] ?? State() - if state.pendingSince == nil { - state.pendingSince = now - } - states[recipient] = state - } - - /// Any inbound packet authored by `peer` confirms the pending routed send - /// (delivery acks and replies arrive this way). Deliberately does not - /// lift an active suppression: that traffic may have arrived via flood. - mutating func noteInboundActivity(from peer: PeerID) { - guard var state = states[peer] else { return } - state.pendingSince = nil - if state.suppressedUntil == nil { - states.removeValue(forKey: peer) - } else { - states[peer] = state - } - } - - /// Drops entries that can no longer influence a routing decision. An - /// expired-but-unconverted pending entry is kept for as long as the - /// suppression it would trigger could still be active. - mutating func prune(now: Date = Date()) { - let pendingRetention = config.confirmationWindowSeconds + config.suppressionSeconds - states = states.filter { _, state in - if let until = state.suppressedUntil, now < until { return true } - if let pending = state.pendingSince, - now.timeIntervalSince(pending) <= pendingRetention { - return true - } - return false - } - } -} diff --git a/bitchat/Services/BLE/BLESourceRouteOriginationPolicy.swift b/bitchat/Services/BLE/BLESourceRouteOriginationPolicy.swift deleted file mode 100644 index a5a02275..00000000 --- a/bitchat/Services/BLE/BLESourceRouteOriginationPolicy.swift +++ /dev/null @@ -1,42 +0,0 @@ -import BitFoundation -import Foundation - -/// Decides whether an outbound directed packet should carry a v2 source -/// route. Pure gating logic so BLEService's hot send path stays a thin wire. -enum BLESourceRouteOriginationPolicy { - /// Returns the intermediate-hop route to attach, or nil to keep the - /// current flood/direct-write behavior unchanged. - /// - /// Routes are only originated when every gate passes: - /// - we authored the packet (relays must not rewrite and re-sign someone - /// else's packet; route-following for in-flight routed packets lives in - /// `BLERouteForwardingPolicy`), - /// - the packet is directed at a single peer (not broadcast), - /// - the packet has TTL headroom to traverse hops (link-local TTL-0 - /// packets like REQUEST_SYNC never route), - /// - the recipient is not directly connected (a direct write already - /// delivers in one hop), - /// - routing to the recipient is not suppressed by a recent unconfirmed - /// routed send, and - /// - the topology yields a complete path. - static func route( - for packet: BitchatPacket, - to recipient: PeerID, - localPeerIDData: Data, - isRecipientConnected: (PeerID) -> Bool, - shouldAttemptRoute: (PeerID) -> Bool, - computeRoute: (PeerID) -> [Data]? - ) -> [Data]? { - guard packet.route == nil, - packet.type != MessageType.fragment.rawValue else { return nil } - guard packet.senderID == localPeerIDData else { return nil } - guard let recipientData = packet.recipientID, - recipientData.count == 8, - !recipientData.allSatisfy({ $0 == 0xFF }) else { return nil } - guard packet.ttl > 1 else { return nil } - guard !isRecipientConnected(recipient) else { return nil } - guard shouldAttemptRoute(recipient) else { return nil } - guard let route = computeRoute(recipient), !route.isEmpty else { return nil } - return route - } -} diff --git a/bitchat/Services/BLE/BLESourceRouting.swift b/bitchat/Services/BLE/BLESourceRouting.swift new file mode 100644 index 00000000..1672563f --- /dev/null +++ b/bitchat/Services/BLE/BLESourceRouting.swift @@ -0,0 +1,198 @@ +import BitFoundation +import Foundation + +// MARK: - Source-Route Origination + +/// Decides whether an outbound directed packet should carry a v2 source route. +enum BLESourceRouteOriginationPolicy { + static func route( + for packet: BitchatPacket, + to recipient: PeerID, + localPeerIDData: Data, + isRecipientConnected: (PeerID) -> Bool, + shouldAttemptRoute: (PeerID) -> Bool, + computeRoute: (PeerID) -> [Data]? + ) -> [Data]? { + guard packet.route == nil, + packet.type != MessageType.fragment.rawValue else { return nil } + guard packet.senderID == localPeerIDData else { return nil } + guard let recipientData = packet.recipientID, + recipientData.count == 8, + !recipientData.allSatisfy({ $0 == 0xFF }) else { return nil } + guard packet.ttl > 1 else { return nil } + guard !isRecipientConnected(recipient) else { return nil } + guard shouldAttemptRoute(recipient) else { return nil } + guard let route = computeRoute(recipient), !route.isEmpty else { return nil } + return route + } +} + +// MARK: - Source-Route Failure Suppression + +/// Tracks whether source-routed sends to a recipient appear to be working, +/// falling back to flooding when a routed send goes unconfirmed. +struct BLESourceRouteFailureCache { + struct Config { + var confirmationWindowSeconds: TimeInterval = TransportConfig.bleSourceRouteConfirmationWindowSeconds + var suppressionSeconds: TimeInterval = TransportConfig.bleSourceRouteSuppressionSeconds + } + + private struct State { + var pendingSince: Date? + var suppressedUntil: Date? + } + + private let config: Config + private var states: [PeerID: State] = [:] + + init(config: Config = Config()) { + self.config = config + } + + mutating func shouldAttemptRoute(to recipient: PeerID, now: Date = Date()) -> Bool { + guard var state = states[recipient] else { return true } + + if let until = state.suppressedUntil { + guard now >= until else { return false } + state.suppressedUntil = nil + } + + if let pending = state.pendingSince, + now.timeIntervalSince(pending) > config.confirmationWindowSeconds { + state.pendingSince = nil + state.suppressedUntil = now.addingTimeInterval(config.suppressionSeconds) + states[recipient] = state + return false + } + + states[recipient] = state + return true + } + + mutating func noteRoutedSend(to recipient: PeerID, now: Date = Date()) { + var state = states[recipient] ?? State() + if state.pendingSince == nil { + state.pendingSince = now + } + states[recipient] = state + } + + mutating func noteInboundActivity(from peer: PeerID) { + guard var state = states[peer] else { return } + state.pendingSince = nil + if state.suppressedUntil == nil { + states.removeValue(forKey: peer) + } else { + states[peer] = state + } + } + + mutating func prune(now: Date = Date()) { + let pendingRetention = config.confirmationWindowSeconds + config.suppressionSeconds + states = states.filter { _, state in + if let until = state.suppressedUntil, now < until { return true } + if let pending = state.pendingSince, + now.timeIntervalSince(pending) <= pendingRetention { + return true + } + return false + } + } +} + +// MARK: - Source-Route Forwarding + +struct BLERouteForwardingPlan { + let shouldSuppressFloodRelay: Bool + let forwardPacket: BitchatPacket? + let nextHop: PeerID? + + static let allowFloodRelay = BLERouteForwardingPlan( + shouldSuppressFloodRelay: false, + forwardPacket: nil, + nextHop: nil + ) + + static let suppressFloodRelay = BLERouteForwardingPlan( + shouldSuppressFloodRelay: true, + forwardPacket: nil, + nextHop: nil + ) + + static func forward(_ packet: BitchatPacket, to nextHop: PeerID) -> BLERouteForwardingPlan { + BLERouteForwardingPlan( + shouldSuppressFloodRelay: true, + forwardPacket: packet, + nextHop: nextHop + ) + } +} + +struct BLERouteForwardingPolicy { + static func plan( + for packet: BitchatPacket, + localPeerID: PeerID, + localRoutingData: Data?, + routingPeer: (Data) -> PeerID?, + isPeerConnected: (PeerID) -> Bool + ) -> BLERouteForwardingPlan { + if packet.type == MessageType.requestSync.rawValue { + return .suppressFloodRelay + } + + if PeerID(hexData: packet.recipientID) == localPeerID { + return .suppressFloodRelay + } + + guard let route = packet.route, !route.isEmpty else { + return .allowFloodRelay + } + + guard packet.ttl > 1 else { + return .suppressFloodRelay + } + + guard let localRoutingData else { + return .allowFloodRelay + } + + guard let localIndex = route.firstIndex(of: localRoutingData) else { + return forward(packet, toRouteData: route[0], routingPeer: routingPeer, isPeerConnected: isPeerConnected) + } + + if localIndex == route.count - 1 { + guard let destinationPeer = PeerID(hexData: packet.recipientID), + isPeerConnected(destinationPeer) else { + return .allowFloodRelay + } + return .forward(relayed(packet), to: destinationPeer) + } + + return forward( + packet, + toRouteData: route[localIndex + 1], + routingPeer: routingPeer, + isPeerConnected: isPeerConnected + ) + } + + private static func forward( + _ packet: BitchatPacket, + toRouteData routeData: Data, + routingPeer: (Data) -> PeerID?, + isPeerConnected: (PeerID) -> Bool + ) -> BLERouteForwardingPlan { + guard let nextPeer = routingPeer(routeData), + isPeerConnected(nextPeer) else { + return .allowFloodRelay + } + + return .forward(relayed(packet), to: nextPeer) + } + + private static func relayed(_ packet: BitchatPacket) -> BitchatPacket { + var relayPacket = packet + relayPacket.ttl = packet.ttl - 1 + return relayPacket + } +} diff --git a/bitchat/Services/Gateway/BridgeService.swift b/bitchat/Services/Gateway/BridgeService.swift index 1acabd0f..85e49a8e 100644 --- a/bitchat/Services/Gateway/BridgeService.swift +++ b/bitchat/Services/Gateway/BridgeService.swift @@ -100,12 +100,6 @@ final class BridgeService: ObservableObject { static let cellPrecision = 6 } - struct QueuedUplink { - let depositor: PeerID - let cell: String - let event: NostrEvent - } - /// A validated rendezvous message ready for the timeline. struct InboundBridgeMessage { let messageID: String @@ -205,12 +199,7 @@ final class BridgeService: ObservableObject { // MARK: State - /// Loop rule 1: event IDs seen in `fromBridge` mesh broadcasts. - private var meshBroadcastEventIDs: BoundedIDSet - /// Loop rule 2: event IDs this device published (own or deposited). - private var publishedEventIDs: BoundedIDSet - /// Loop rule 3: event IDs this device already rebroadcast. - private var rebroadcastEventIDs: BoundedIDSet + private let relayEngine: CarrierRelayEngine /// Timeline message IDs already injected (either arrival path). private var injectedMessageIDs: BoundedIDSet /// Signed relay/carrier events already accepted. Kept separate from the @@ -228,15 +217,10 @@ final class BridgeService: ObservableObject { /// Cells the rendezvous subscription covers (own + neighbor ring). private(set) var subscribedCells: Set = [] - private(set) var queuedUplinks: [QueuedUplink] = [] - private var uplinkDepositTimes: [PeerID: [Date]] = [:] - private var downlinkSendTimes: [Date] = [] private var inboundEventTimes: [Date] = [] private var inboundEventTimesBySigner: [String: [Date]] = [:] private var signatureVerificationTokens = Double(Limits.signatureVerificationAttemptsPerMinute) private var signatureVerificationLastRefillAt: Date? - private var pendingDownlinks: [(event: NostrEvent, cell: String)] = [] - private var downlinkDrainScheduled = false private var presenceTimerArmed = false private var lastPresenceAt = Date.distantPast @@ -248,6 +232,10 @@ final class BridgeService: ObservableObject { private let verifyEventSignature: (NostrEvent) -> Bool private static let enabledKey = "bridge.userEnabled" + var queuedUplinks: [CarrierRelayEngine.QueuedUplink] { + relayEngine.queuedUplinks + } + init( defaults: UserDefaults = .standard, now: @escaping () -> Date = Date.init, @@ -257,9 +245,18 @@ final class BridgeService: ObservableObject { self.now = now self.verifyEventSignature = verifyEventSignature self.isEnabled = defaults.bool(forKey: Self.enabledKey) - self.meshBroadcastEventIDs = BoundedIDSet(capacity: Limits.maxTrackedEventIDs) - self.publishedEventIDs = BoundedIDSet(capacity: Limits.maxTrackedEventIDs) - self.rebroadcastEventIDs = BoundedIDSet(capacity: Limits.maxTrackedEventIDs) + self.relayEngine = CarrierRelayEngine( + config: .init( + maxQueuedUplinks: Limits.maxQueuedUplinks, + maxQueuedUplinksPerDepositor: Limits.maxQueuedUplinksPerDepositor, + uplinkEventsPerMinutePerDepositor: Limits.uplinkEventsPerMinutePerDepositor, + downlinkEventsPerMinute: Limits.downlinkEventsPerMinute, + maxPendingDownlinks: Limits.maxPendingDownlinks, + maxEventAgeSeconds: Limits.maxEventAgeSeconds, + maxTrackedEventIDs: Limits.maxTrackedEventIDs + ), + now: now + ) self.injectedMessageIDs = BoundedIDSet(capacity: Limits.maxTrackedEventIDs) self.receivedEventIDs = BoundedIDSet(capacity: Limits.maxTrackedEventIDs) self.observedRadioMessageIDs = BoundedIDSet(capacity: Limits.maxTrackedEventIDs) @@ -272,9 +269,7 @@ final class BridgeService: ObservableObject { isEnabled = enabled defaults.set(enabled, forKey: Self.enabledKey) if !enabled { - queuedUplinks.removeAll() - pendingDownlinks.removeAll() - uplinkDepositTimes.removeAll() + relayEngine.clearQueuesOnDisable() inboundEventTimes.removeAll() inboundEventTimesBySigner.removeAll() participants.removeAll() @@ -294,16 +289,13 @@ final class BridgeService: ObservableObject { closeSubscription?() } isEnabled = false + nearbyOnly = false defaults.removeObject(forKey: Self.enabledKey) activeCell = nil subscribedCells = [] - queuedUplinks.removeAll(keepingCapacity: false) - pendingDownlinks.removeAll(keepingCapacity: false) - downlinkDrainScheduled = false + relayEngine.resetForPanic() presenceTimerArmed = false lastPresenceAt = .distantPast - uplinkDepositTimes.removeAll(keepingCapacity: false) - downlinkSendTimes.removeAll(keepingCapacity: false) inboundEventTimes.removeAll(keepingCapacity: false) inboundEventTimesBySigner.removeAll(keepingCapacity: false) signatureVerificationTokens = Double(Limits.signatureVerificationAttemptsPerMinute) @@ -311,12 +303,11 @@ final class BridgeService: ObservableObject { participants.removeAll(keepingCapacity: false) bridgedPeerCount = 0 bridgedParticipants = [] - meshBroadcastEventIDs = BoundedIDSet(capacity: Limits.maxTrackedEventIDs) - publishedEventIDs = BoundedIDSet(capacity: Limits.maxTrackedEventIDs) - rebroadcastEventIDs = BoundedIDSet(capacity: Limits.maxTrackedEventIDs) injectedMessageIDs = BoundedIDSet(capacity: Limits.maxTrackedEventIDs) receivedEventIDs = BoundedIDSet(capacity: Limits.maxTrackedEventIDs) observedRadioMessageIDs = BoundedIDSet(capacity: Limits.maxTrackedEventIDs) + injectedRadioAliases.removeAll(keepingCapacity: false) + injectedRadioAliasOrder.removeAll(keepingCapacity: false) onEnabledChanged?(false) } @@ -401,7 +392,7 @@ final class BridgeService: ObservableObject { SecureLogger.error("🌉 Bridge: failed to compose rendezvous event", category: .session) return } - publishedEventIDs.insert(event.id) + relayEngine.publishedEventIDs.insert(event.id) injectedMessageIDs.insert(event.id) // our own timeline already has it if relaysConnected?() ?? false { publishToRelays?(event, cell) @@ -424,7 +415,7 @@ final class BridgeService: ObservableObject { lastPresenceAt = now() guard let identity = try? deriveIdentity?(cell), let event = try? NostrProtocol.createBridgePresenceEvent(cell: cell, senderIdentity: identity) else { return } - publishedEventIDs.insert(event.id) + relayEngine.publishedEventIDs.insert(event.id) publishToRelays?(event, cell) } @@ -478,9 +469,9 @@ final class BridgeService: ObservableObject { // deterministically, so even after a relaunch wipes the cache our // own relay-backfilled events are recognized (field bug: own // pre-restart messages re-rendered as bridged). - guard !publishedEventIDs.contains(event.id) else { return } + guard !relayEngine.publishedEventIDs.contains(event.id) else { return } if isOwnRendezvousEvent(event, cell: cell) { - publishedEventIDs.insert(event.id) // never downlink it either + relayEngine.publishedEventIDs.insert(event.id) // never downlink it either return } guard signatureAlreadyVerified || (allowSignatureVerificationAttempt() && verifyEventSignature(event)) else { return } @@ -506,14 +497,19 @@ final class BridgeService: ObservableObject { // with every online bridger serving, the holdoff lets gateways // hear each other's broadcasts and skip duplicates. if !isLocalRadioCopy, - !meshBroadcastEventIDs.contains(event.id), - !rebroadcastEventIDs.contains(event.id), - !pendingDownlinks.contains(where: { $0.event.id == event.id }) { - pendingDownlinks.append((event, cell)) - if pendingDownlinks.count > Limits.maxPendingDownlinks { - pendingDownlinks.removeFirst(pendingDownlinks.count - Limits.maxPendingDownlinks) - } - scheduleDownlinkDrainIfNeeded(jitter: true) + !relayEngine.meshBroadcastEventIDs.contains(event.id), + !relayEngine.rebroadcastEventIDs.contains(event.id), + !relayEngine.hasPendingDownlink(event.id) { + relayEngine.enqueuePendingDownlink(event: event, scope: cell) + // Multi-gateway suppression window: enough spread for another + // gateway's broadcast to land and mark the event mesh-carried. + relayEngine.scheduleDownlinkDrainIfNeeded( + jitterDelay: Double.random(in: 0.2...1.5), + scheduleTimer: scheduleTimer, + onFire: { [weak self] in + self?.drainPendingDownlinks() + } + ) } } } @@ -539,8 +535,8 @@ final class BridgeService: ObservableObject { // A relay event can already be waiting inside the multi-gateway jitter // window. Remove it now so it cannot consume BLE airtime after the // authenticated radio packet proved this island already has a copy. - pendingDownlinks.removeAll { item in - guard case .message(let message)? = classify(item.event, cell: item.cell) else { return false } + relayEngine.removePendingDownlinks { item in + guard case .message(let message)? = classify(item.event, cell: item.scope) else { return false } return message.radioMessageIDHint == messageID } } @@ -572,12 +568,10 @@ final class BridgeService: ObservableObject { SecureLogger.debug("🌉 Bridge: rejected deposit from \(depositor.id.prefix(8))… (failed validation)", category: .security) return } - guard !meshBroadcastEventIDs.contains(event.id), - !publishedEventIDs.contains(event.id), - !queuedUplinks.contains(where: { $0.event.id == event.id }) else { + guard !relayEngine.isUplinkDuplicate(event.id) else { return } - guard allowUplinkDeposit(from: depositor) else { + guard relayEngine.allowUplinkDeposit(from: depositor) else { SecureLogger.debug("🌉 Bridge: rate-limited deposit from \(depositor.id.prefix(8))…", category: .session) return } @@ -588,7 +582,7 @@ final class BridgeService: ObservableObject { if relaysConnected?() ?? false { publish(event, cell: carrier.geohash) } else { - enqueueUplink(QueuedUplink(depositor: depositor, cell: carrier.geohash, event: event)) + relayEngine.enqueueUplink(depositor: depositor, scope: carrier.geohash, event: event) } // No local injection: the depositor's radio broadcast already carried // the message to this island, including us. @@ -596,47 +590,18 @@ final class BridgeService: ObservableObject { /// Publish everything queued while relays were unreachable. func flushQueuedUplinks() { - guard isEnabled, relaysConnected?() ?? false, !queuedUplinks.isEmpty else { return } - let queued = queuedUplinks - queuedUplinks.removeAll() - for item in queued where !publishedEventIDs.contains(item.event.id) { - publish(item.event, cell: item.cell) + guard isEnabled, relaysConnected?() ?? false else { return } + relayEngine.flushQueuedUplinks { event, cell in + publish(event, cell: cell) } } private func publish(_ event: NostrEvent, cell: String) { - publishedEventIDs.insert(event.id) + relayEngine.publishedEventIDs.insert(event.id) publishToRelays?(event, cell) SecureLogger.info("🌉 Bridge: published carried event \(event.id.prefix(8))… for cell \(cell)", category: .session) } - @discardableResult - private func enqueueUplink(_ item: QueuedUplink) -> Bool { - let fromDepositor = queuedUplinks.filter { $0.depositor == item.depositor }.count - guard fromDepositor < Limits.maxQueuedUplinksPerDepositor else { return false } - if queuedUplinks.count >= Limits.maxQueuedUplinks { - queuedUplinks.removeFirst(queuedUplinks.count - Limits.maxQueuedUplinks + 1) - } - queuedUplinks.append(item) - return true - } - - private func allowUplinkDeposit(from depositor: PeerID) -> Bool { - let cutoff = now().addingTimeInterval(-60) - var times = uplinkDepositTimes[depositor, default: []] - times.removeAll { $0 < cutoff } - guard times.count < Limits.uplinkEventsPerMinutePerDepositor else { - uplinkDepositTimes[depositor] = times - return false - } - times.append(now()) - uplinkDepositTimes[depositor] = times - if uplinkDepositTimes.count > Limits.maxTrackedEventIDs { - uplinkDepositTimes = uplinkDepositTimes.filter { $0.value.contains { $0 >= cutoff } } - } - return true - } - /// Bounds relay/carrier work independently of the downlink airtime budget. /// A valid signature proves control of one key, not that the sender is /// entitled to unbounded main-actor state or CPU. @@ -686,59 +651,33 @@ final class BridgeService: ObservableObject { // MARK: - Downlink (gateway role: internet -> mesh) private func drainPendingDownlinks() { - let cutoff = now().addingTimeInterval(-60) - downlinkSendTimes.removeAll { $0 < cutoff } - while !pendingDownlinks.isEmpty, - downlinkSendTimes.count < Limits.downlinkEventsPerMinute { - let (event, cell) = pendingDownlinks.removeFirst() - guard isFresh(event) else { continue } - // Suppression recheck at send time: another gateway may have - // broadcast this event, or the authenticated radio copy may have - // arrived, during our jitter holdoff. - guard !meshBroadcastEventIDs.contains(event.id), - !rebroadcastEventIDs.contains(event.id) else { continue } - if case .message(let message)? = classify(event, cell: cell), - let radioMessageID = message.radioMessageIDHint, - radioCopyAlreadyPresent(radioMessageID) { - continue + relayEngine.drainPendingDownlinks( + direction: .fromBridge, + shouldSend: { [weak self] event, cell in + guard let self else { return false } + // Suppression recheck at send time: another gateway may have + // broadcast this event, or the authenticated radio copy may have + // arrived, during our jitter holdoff. + guard !self.relayEngine.meshBroadcastEventIDs.contains(event.id), + !self.relayEngine.rebroadcastEventIDs.contains(event.id) else { + return false + } + if case .message(let message)? = self.classify(event, cell: cell), + let radioMessageID = message.radioMessageIDHint, + self.radioCopyAlreadyPresent(radioMessageID) { + return false + } + return true + }, + send: { [weak self] payload, event in + self?.broadcastToMesh?(payload) + SecureLogger.debug("🌉 Bridge: downlinked remote event \(event.id.prefix(8))… onto the mesh", category: .session) + }, + scheduleTimer: scheduleTimer, + onScheduledDrain: { [weak self] in + self?.drainPendingDownlinks() } - guard let carrier = NostrCarrierPacket(direction: .fromBridge, geohash: cell, event: event), - let payload = carrier.encode() else { continue } - broadcastToMesh?(payload) - SecureLogger.debug("🌉 Bridge: downlinked remote event \(event.id.prefix(8))… onto the mesh", category: .session) - // Mark-after-send (loop rule 3): a queue-overflow drop stays - // retryable on relay redelivery. - rebroadcastEventIDs.insert(event.id) - downlinkSendTimes.append(now()) - } - scheduleDownlinkDrainIfNeeded() - } - - private func scheduleDownlinkDrainIfNeeded(jitter: Bool = false) { - guard !pendingDownlinks.isEmpty, !downlinkDrainScheduled else { return } - let delay: TimeInterval - if jitter { - // Multi-gateway suppression window: enough spread for another - // gateway's broadcast to land and mark the event mesh-carried. - delay = Double.random(in: 0.2...1.5) - } else { - let oldest = downlinkSendTimes.min() ?? now() - delay = max(0.05, 60 - now().timeIntervalSince(oldest)) - } - downlinkDrainScheduled = true - let fire: @MainActor () -> Void = { [weak self] in - guard let self else { return } - self.downlinkDrainScheduled = false - self.drainPendingDownlinks() - } - if let scheduleTimer { - scheduleTimer(delay, fire) - } else { - Task { @MainActor in - try? await Task.sleep(nanoseconds: UInt64(delay * 1_000_000_000)) - fire() - } - } + ) } // MARK: - Downlink (receiver role: carried event arrives over radio) @@ -748,7 +687,7 @@ final class BridgeService: ObservableObject { // radio, and two phones side by side should not disagree about what // the channel said. Publishing/subscribing remain opt-in. guard let event = structurallyValidEvent(from: carrier), - !publishedEventIDs.contains(event.id), + !relayEngine.publishedEventIDs.contains(event.id), !isOwnRendezvousEvent(event, cell: carrier.geohash), allowSignatureVerificationAttempt(), verifyEventSignature(event) else { @@ -757,7 +696,7 @@ final class BridgeService: ObservableObject { // Mark after verification (a forged copy must not poison the cache), // even when the relay copy won the injection race: pending gateway // downlinks consult this cache and must stand down. - let firstMeshArrival = meshBroadcastEventIDs.insert(event.id) + let firstMeshArrival = relayEngine.meshBroadcastEventIDs.insert(event.id) guard firstMeshArrival, receivedEventIDs.insert(event.id), allowInboundEvent(from: event.pubkey) else { return } @@ -868,7 +807,7 @@ final class BridgeService: ObservableObject { /// Classifies a structurally acceptable rendezvous event; nil rejects. private func classify(_ event: NostrEvent, cell: String) -> RendezvousKind? { - guard isFresh(event), + guard relayEngine.isFresh(event), event.tags.contains(where: { $0.count >= 2 && $0[0] == "r" && $0[1] == cell }), GatewayService.isValidGeohash(cell) else { return nil @@ -925,10 +864,6 @@ final class BridgeService: ObservableObject { return event } - private func isFresh(_ event: NostrEvent) -> Bool { - abs(now().timeIntervalSince1970 - TimeInterval(event.created_at)) <= Limits.maxEventAgeSeconds - } - /// True when the event was signed by this device's own derived /// rendezvous identity for the cell. Survives relaunches (unlike the /// published-ID cache) because the derivation is deterministic; the diff --git a/bitchat/Services/Gateway/CarrierRelayEngine.swift b/bitchat/Services/Gateway/CarrierRelayEngine.swift new file mode 100644 index 00000000..6a546431 --- /dev/null +++ b/bitchat/Services/Gateway/CarrierRelayEngine.swift @@ -0,0 +1,203 @@ +// +// CarrierRelayEngine.swift +// bitchat +// +// This is free and unencumbered software released into the public domain. +// For more information, see +// + +import BitFoundation +import Foundation + +/// Shared uplink/downlink queueing, rate-limiting, freshness, and loop-prevention +/// state machine used by `GatewayService` and `BridgeService`. +@MainActor +final class CarrierRelayEngine { + struct Config { + let maxQueuedUplinks: Int + let maxQueuedUplinksPerDepositor: Int + let uplinkEventsPerMinutePerDepositor: Int + let downlinkEventsPerMinute: Int + let maxPendingDownlinks: Int + let maxEventAgeSeconds: TimeInterval + let maxTrackedEventIDs: Int + } + + struct QueuedUplink { + let depositor: PeerID + let scope: String + let event: NostrEvent + } + + /// Loop rule 1: event IDs seen in downlink (`fromGateway`/`fromBridge`) mesh broadcasts. + var meshBroadcastEventIDs: BoundedIDSet + /// Loop rule 2: event IDs this device already published to relays. + var publishedEventIDs: BoundedIDSet + /// Loop rule 3: event IDs this device already rebroadcast onto the mesh. + var rebroadcastEventIDs: BoundedIDSet + + private(set) var queuedUplinks: [QueuedUplink] = [] + private(set) var pendingDownlinks: [(event: NostrEvent, scope: String)] = [] + private var uplinkDepositTimes: [PeerID: [Date]] = [:] + private var downlinkSendTimes: [Date] = [] + private var downlinkDrainScheduled = false + + private let config: Config + private let now: () -> Date + + init(config: Config, now: @escaping () -> Date) { + self.config = config + self.now = now + self.meshBroadcastEventIDs = BoundedIDSet(capacity: config.maxTrackedEventIDs) + self.publishedEventIDs = BoundedIDSet(capacity: config.maxTrackedEventIDs) + self.rebroadcastEventIDs = BoundedIDSet(capacity: config.maxTrackedEventIDs) + } + + // MARK: - Lifecycle + + func clearQueuesOnDisable() { + queuedUplinks.removeAll() + pendingDownlinks.removeAll() + uplinkDepositTimes.removeAll() + } + + func resetForPanic() { + queuedUplinks.removeAll(keepingCapacity: false) + pendingDownlinks.removeAll(keepingCapacity: false) + downlinkDrainScheduled = false + uplinkDepositTimes.removeAll(keepingCapacity: false) + downlinkSendTimes.removeAll(keepingCapacity: false) + meshBroadcastEventIDs = BoundedIDSet(capacity: config.maxTrackedEventIDs) + publishedEventIDs = BoundedIDSet(capacity: config.maxTrackedEventIDs) + rebroadcastEventIDs = BoundedIDSet(capacity: config.maxTrackedEventIDs) + } + + // MARK: - Freshness & Dedup + + /// True when `event.created_at` is within the accepted clock skew window. + func isFresh(_ event: NostrEvent) -> Bool { + abs(now().timeIntervalSince1970 - TimeInterval(event.created_at)) <= config.maxEventAgeSeconds + } + + func isUplinkDuplicate(_ eventID: String) -> Bool { + meshBroadcastEventIDs.contains(eventID) + || publishedEventIDs.contains(eventID) + || queuedUplinks.contains(where: { $0.event.id == eventID }) + } + + func hasPendingDownlink(_ eventID: String) -> Bool { + pendingDownlinks.contains(where: { $0.event.id == eventID }) + } + + func removePendingDownlinks(where shouldRemove: ((event: NostrEvent, scope: String)) -> Bool) { + pendingDownlinks.removeAll(where: shouldRemove) + } + + // MARK: - Uplink Queue & Rate Limiting + + @discardableResult + func enqueueUplink(depositor: PeerID, scope: String, event: NostrEvent) -> Bool { + let fromDepositor = queuedUplinks.filter { $0.depositor == depositor }.count + guard fromDepositor < config.maxQueuedUplinksPerDepositor else { + return false + } + if queuedUplinks.count >= config.maxQueuedUplinks { + queuedUplinks.removeFirst(queuedUplinks.count - config.maxQueuedUplinks + 1) + } + queuedUplinks.append(QueuedUplink(depositor: depositor, scope: scope, event: event)) + return true + } + + func flushQueuedUplinks(publish: (NostrEvent, String) -> Void) { + guard !queuedUplinks.isEmpty else { return } + let queued = queuedUplinks + queuedUplinks.removeAll() + for item in queued where !publishedEventIDs.contains(item.event.id) { + publish(item.event, item.scope) + } + } + + func allowUplinkDeposit(from depositor: PeerID) -> Bool { + let currentTime = now() + let cutoff = currentTime.addingTimeInterval(-60) + var times = uplinkDepositTimes[depositor, default: []] + times.removeAll { $0 < cutoff } + guard times.count < config.uplinkEventsPerMinutePerDepositor else { + uplinkDepositTimes[depositor] = times + return false + } + times.append(currentTime) + uplinkDepositTimes[depositor] = times + if uplinkDepositTimes.count > config.maxTrackedEventIDs { + uplinkDepositTimes = uplinkDepositTimes.filter { $0.value.contains { $0 >= cutoff } } + } + return true + } + + // MARK: - Downlink Queue & Paced Drain + + func enqueuePendingDownlink(event: NostrEvent, scope: String) { + pendingDownlinks.append((event, scope)) + if pendingDownlinks.count > config.maxPendingDownlinks { + // Bandwidth guard: drop-oldest — fresher chat is worth more. Dropped + // events are not yet marked in `rebroadcastEventIDs`, so a later + // relay redelivery can still carry them. + pendingDownlinks.removeFirst(pendingDownlinks.count - config.maxPendingDownlinks) + } + } + + func drainPendingDownlinks( + direction: NostrCarrierPacket.Direction, + shouldSend: (NostrEvent, String) -> Bool = { _, _ in true }, + send: (Data, NostrEvent) -> Void, + scheduleTimer: ((TimeInterval, @escaping @MainActor () -> Void) -> Void)?, + onScheduledDrain: @escaping @MainActor () -> Void + ) { + let cutoff = now().addingTimeInterval(-60) + downlinkSendTimes.removeAll { $0 < cutoff } + while !pendingDownlinks.isEmpty, + downlinkSendTimes.count < config.downlinkEventsPerMinute { + let (event, scope) = pendingDownlinks.removeFirst() + guard isFresh(event), shouldSend(event, scope) else { continue } + guard let carrier = NostrCarrierPacket(direction: direction, geohash: scope, event: event), + let payload = carrier.encode() else { continue } + send(payload, event) + rebroadcastEventIDs.insert(event.id) + downlinkSendTimes.append(now()) + } + scheduleDownlinkDrainIfNeeded( + jitterDelay: nil, + scheduleTimer: scheduleTimer, + onFire: onScheduledDrain + ) + } + + func scheduleDownlinkDrainIfNeeded( + jitterDelay: TimeInterval?, + scheduleTimer: ((TimeInterval, @escaping @MainActor () -> Void) -> Void)?, + onFire: @escaping @MainActor () -> Void + ) { + guard !pendingDownlinks.isEmpty, !downlinkDrainScheduled else { return } + let delay: TimeInterval + if let jitterDelay { + delay = jitterDelay + } else { + let oldest = downlinkSendTimes.min() ?? now() + delay = max(0.05, 60 - now().timeIntervalSince(oldest)) + } + downlinkDrainScheduled = true + let fire: @MainActor () -> Void = { [weak self] in + guard let self else { return } + self.downlinkDrainScheduled = false + onFire() + } + if let scheduleTimer { + scheduleTimer(delay, fire) + } else { + Task { @MainActor in + try? await Task.sleep(nanoseconds: UInt64(delay * 1_000_000_000)) + fire() + } + } + } +} diff --git a/bitchat/Services/Gateway/GatewayService.swift b/bitchat/Services/Gateway/GatewayService.swift index 379a47f8..84aaa7a2 100644 --- a/bitchat/Services/Gateway/GatewayService.swift +++ b/bitchat/Services/Gateway/GatewayService.swift @@ -78,12 +78,6 @@ final class GatewayService: ObservableObject { static let maxTrackedEventIDs = 512 } - struct QueuedUplink { - let depositor: PeerID - let geohash: String - let event: NostrEvent - } - static let shared = GatewayService() /// The user toggle. While true this device advertises `.gateway` and @@ -117,31 +111,29 @@ final class GatewayService: ObservableObject { // MARK: State - /// Loop rule 1: event IDs seen in `fromGateway` mesh broadcasts. - private var meshBroadcastEventIDs: BoundedIDSet - /// Loop rule 2 (uplink): event IDs this gateway already published. - private var publishedEventIDs: BoundedIDSet - /// Loop rule 2 (downlink): event IDs this gateway already rebroadcast. - private var rebroadcastEventIDs: BoundedIDSet - - private(set) var queuedUplinks: [QueuedUplink] = [] - private var uplinkDepositTimes: [PeerID: [Date]] = [:] - private var downlinkSendTimes: [Date] = [] - private var pendingDownlinks: [(event: NostrEvent, geohash: String)] = [] - /// True while a drain timer is armed, so a burst schedules at most one. - private var downlinkDrainScheduled = false - + private let relayEngine: CarrierRelayEngine private let defaults: UserDefaults - private let now: () -> Date private static let enabledKey = "gateway.userEnabled" + var queuedUplinks: [CarrierRelayEngine.QueuedUplink] { + relayEngine.queuedUplinks + } + init(defaults: UserDefaults = .standard, now: @escaping () -> Date = Date.init) { self.defaults = defaults - self.now = now self.isEnabled = defaults.bool(forKey: Self.enabledKey) - self.meshBroadcastEventIDs = BoundedIDSet(capacity: Limits.maxTrackedEventIDs) - self.publishedEventIDs = BoundedIDSet(capacity: Limits.maxTrackedEventIDs) - self.rebroadcastEventIDs = BoundedIDSet(capacity: Limits.maxTrackedEventIDs) + self.relayEngine = CarrierRelayEngine( + config: .init( + maxQueuedUplinks: Limits.maxQueuedUplinks, + maxQueuedUplinksPerDepositor: Limits.maxQueuedUplinksPerDepositor, + uplinkEventsPerMinutePerDepositor: Limits.uplinkEventsPerMinutePerDepositor, + downlinkEventsPerMinute: Limits.downlinkEventsPerMinute, + maxPendingDownlinks: Limits.maxPendingDownlinks, + maxEventAgeSeconds: Limits.maxEventAgeSeconds, + maxTrackedEventIDs: Limits.maxTrackedEventIDs + ), + now: now + ) } // MARK: - Toggle @@ -151,9 +143,7 @@ final class GatewayService: ObservableObject { isEnabled = enabled defaults.set(enabled, forKey: Self.enabledKey) if !enabled { - queuedUplinks.removeAll() - pendingDownlinks.removeAll() - uplinkDepositTimes.removeAll() + relayEngine.clearQueuesOnDisable() } SecureLogger.info("🌐 Gateway mode \(enabled ? "enabled" : "disabled")", category: .session) onEnabledChanged?(enabled) @@ -164,14 +154,7 @@ final class GatewayService: ObservableObject { func resetForPanic() { isEnabled = false defaults.removeObject(forKey: Self.enabledKey) - queuedUplinks.removeAll(keepingCapacity: false) - pendingDownlinks.removeAll(keepingCapacity: false) - downlinkDrainScheduled = false - uplinkDepositTimes.removeAll(keepingCapacity: false) - downlinkSendTimes.removeAll(keepingCapacity: false) - meshBroadcastEventIDs = BoundedIDSet(capacity: Limits.maxTrackedEventIDs) - publishedEventIDs = BoundedIDSet(capacity: Limits.maxTrackedEventIDs) - rebroadcastEventIDs = BoundedIDSet(capacity: Limits.maxTrackedEventIDs) + relayEngine.resetForPanic() onEnabledChanged?(false) } @@ -217,15 +200,13 @@ final class GatewayService: ObservableObject { // re-published. Loop rule 2: repeat deposits of an already handled // event are absorbed. A replay of one valid deposit is short-circuited // here without a per-packet signature verify. - guard !meshBroadcastEventIDs.contains(event.id), - !publishedEventIDs.contains(event.id), - !queuedUplinks.contains(where: { $0.event.id == event.id }) else { + guard !relayEngine.isUplinkDuplicate(event.id) else { return } // Consume the per-depositor rate token BEFORE the expensive verify so // a flood of distinct forged/junk deposits is bounded by cheap work, // not by main-actor Schnorr verifications. - guard allowUplinkDeposit(from: depositor) else { + guard relayEngine.allowUplinkDeposit(from: depositor) else { SecureLogger.debug("🌐 Gateway: rate-limited uplink deposit from \(depositor.id.prefix(8))…", category: .session) return } @@ -240,7 +221,10 @@ final class GatewayService: ObservableObject { publish(event, geohash: carrier.geohash) accepted = true } else { - accepted = enqueueUplink(QueuedUplink(depositor: depositor, geohash: carrier.geohash, event: event)) + accepted = relayEngine.enqueueUplink(depositor: depositor, scope: carrier.geohash, event: event) + if !accepted { + SecureLogger.debug("🌐 Gateway: uplink queue quota reached for \(depositor.id.prefix(8))…", category: .session) + } } // Only render on our own timeline what we actually accepted for @@ -255,52 +239,18 @@ final class GatewayService: ObservableObject { /// Publish everything queued while relays were unreachable. Called when /// relay connectivity comes back. func flushQueuedUplinks() { - guard isEnabled, relaysConnected?() ?? false, !queuedUplinks.isEmpty else { return } - let queued = queuedUplinks - queuedUplinks.removeAll() - for item in queued where !publishedEventIDs.contains(item.event.id) { - publish(item.event, geohash: item.geohash) + guard isEnabled, relaysConnected?() ?? false else { return } + relayEngine.flushQueuedUplinks { event, geohash in + publish(event, geohash: geohash) } } private func publish(_ event: NostrEvent, geohash: String) { - publishedEventIDs.insert(event.id) + relayEngine.publishedEventIDs.insert(event.id) publishToRelays?(event, geohash) SecureLogger.info("🌐 Gateway: published carried event \(event.id.prefix(8))… to relays for #\(geohash)", category: .session) } - /// Returns true when the item was actually stored for later publish. - @discardableResult - private func enqueueUplink(_ item: QueuedUplink) -> Bool { - let fromDepositor = queuedUplinks.filter { $0.depositor == item.depositor }.count - guard fromDepositor < Limits.maxQueuedUplinksPerDepositor else { - SecureLogger.debug("🌐 Gateway: uplink queue quota reached for \(item.depositor.id.prefix(8))…", category: .session) - return false - } - if queuedUplinks.count >= Limits.maxQueuedUplinks { - queuedUplinks.removeFirst(queuedUplinks.count - Limits.maxQueuedUplinks + 1) - } - queuedUplinks.append(item) - return true - } - - private func allowUplinkDeposit(from depositor: PeerID) -> Bool { - let cutoff = now().addingTimeInterval(-60) - var times = uplinkDepositTimes[depositor, default: []] - times.removeAll { $0 < cutoff } - guard times.count < Limits.uplinkEventsPerMinutePerDepositor else { - uplinkDepositTimes[depositor] = times - return false - } - times.append(now()) - uplinkDepositTimes[depositor] = times - // Bound the tracker itself against a churn of spoofed depositors. - if uplinkDepositTimes.count > Limits.maxTrackedEventIDs { - uplinkDepositTimes = uplinkDepositTimes.filter { !$0.value.isEmpty && $0.value.contains { $0 >= cutoff } } - } - return true - } - // MARK: - Downlink (gateway role: internet -> mesh) /// Called for every event the gateway's own geohash-channel subscription @@ -315,84 +265,40 @@ final class GatewayService: ObservableObject { // same window — so rebroadcasting backfill would burn the whole // per-minute budget on events no mesh peer accepts. Also require the // event's own `#g` tag to match the carrier geohash. - guard isFresh(event), + guard relayEngine.isFresh(event), event.tags.contains(where: { $0.count >= 2 && $0[0] == "g" && $0[1] == geohash }) else { return } // Loop rule 1: never rebroadcast mesh-carried events back onto the // mesh. Loop rule 2 (self-echo): never rebroadcast an event this - // gateway itself uplinked (`publishedEventIDs`) — it originated on this - // very mesh, so our own relay subscription echoing it back must not - // double the BLE airtime by pushing it out again. Loop rule 2 - // (downlink): rebroadcast each genuine inbound relay event at most once - // — but mark only AFTER it is actually sent (in `drainPendingDownlinks`), - // so an event dropped by the queue overflow stays retryable on relay - // redelivery. Guard against a redelivery re-queueing an event that is - // still waiting to be sent. - guard !meshBroadcastEventIDs.contains(event.id), - !publishedEventIDs.contains(event.id), - !rebroadcastEventIDs.contains(event.id), - !pendingDownlinks.contains(where: { $0.event.id == event.id }) else { + // gateway itself uplinked (`publishedEventIDs`). Loop rule 2 (downlink): + // rebroadcast each genuine inbound relay event at most once — marked + // only AFTER it is actually sent so queue-overflow drops stay retryable. + guard !relayEngine.meshBroadcastEventIDs.contains(event.id), + !relayEngine.publishedEventIDs.contains(event.id), + !relayEngine.rebroadcastEventIDs.contains(event.id), + !relayEngine.hasPendingDownlink(event.id) else { return } // Verify before spending BLE airtime when not already verified by // NostrRelayManager's off-main inbound pipeline; receivers verify again. guard signatureAlreadyVerified || event.isValidSignature() else { return } - pendingDownlinks.append((event, geohash)) - if pendingDownlinks.count > Limits.maxPendingDownlinks { - // Bandwidth guard: drop-oldest — fresher chat is worth more. The - // dropped event is not yet in `rebroadcastEventIDs`, so a later - // relay redelivery can still carry it. - pendingDownlinks.removeFirst(pendingDownlinks.count - Limits.maxPendingDownlinks) - } + relayEngine.enqueuePendingDownlink(event: event, scope: geohash) drainPendingDownlinks() } private func drainPendingDownlinks() { - let cutoff = now().addingTimeInterval(-60) - downlinkSendTimes.removeAll { $0 < cutoff } - while !pendingDownlinks.isEmpty, - downlinkSendTimes.count < Limits.downlinkEventsPerMinute { - let (event, geohash) = pendingDownlinks.removeFirst() - // A queued event may have aged past the window while it waited; - // don't burn airtime on what receivers would now drop. - guard isFresh(event) else { continue } - guard let carrier = NostrCarrierPacket(direction: .fromGateway, geohash: geohash, event: event), - let payload = carrier.encode() else { continue } - broadcastToMesh?(payload) - // Mark-after-send: only now is the relay event definitively - // rebroadcast (loop rule 2). - rebroadcastEventIDs.insert(event.id) - downlinkSendTimes.append(now()) - } - // Budget exhausted with events still queued: arm a timer to drain when - // the window frees, instead of stranding them until the next inbound - // relay event (which may never come on a channel that went quiet). - scheduleDownlinkDrainIfNeeded() - } - - /// Arms a single timer to drain the backlog once the per-minute window - /// frees. No-op when nothing is pending or a drain is already scheduled. - private func scheduleDownlinkDrainIfNeeded() { - guard !pendingDownlinks.isEmpty, !downlinkDrainScheduled else { return } - // The window frees when the oldest recorded send ages out of 60s. - let oldest = downlinkSendTimes.min() ?? now() - let delay = max(0.05, 60 - now().timeIntervalSince(oldest)) - downlinkDrainScheduled = true - let fire: @MainActor () -> Void = { [weak self] in - guard let self else { return } - self.downlinkDrainScheduled = false - self.drainPendingDownlinks() - } - if let scheduleDrainTimer { - scheduleDrainTimer(delay, fire) - } else { - Task { @MainActor in - try? await Task.sleep(nanoseconds: UInt64(delay * 1_000_000_000)) - fire() + relayEngine.drainPendingDownlinks( + direction: .fromGateway, + send: { [weak self] payload, _ in + self?.broadcastToMesh?(payload) + }, + scheduleTimer: scheduleDrainTimer, + onScheduledDrain: { [weak self] in + self?.drainPendingDownlinks() } - } + ) } // MARK: - Downlink (receiver role: carried event arrives over mesh) @@ -404,7 +310,7 @@ final class GatewayService: ObservableObject { // marking as dedup: the same broadcast relayed along several mesh // paths injects once (the pipeline's Nostr event-ID cache additionally // dedups against our own relay subscription). - guard meshBroadcastEventIDs.insert(event.id) else { return } + guard relayEngine.meshBroadcastEventIDs.insert(event.id) else { return } // Only inject events for the channel we're viewing; the inbound // pipeline files public messages under the current geohash. guard currentGeohash?() == carrier.geohash else { return } @@ -425,8 +331,8 @@ final class GatewayService: ObservableObject { /// never reach this path, and the mesh-carried guard below backstops it. func uplinkViaMesh(event: NostrEvent, geohash: String) -> Bool { if relaysConnected?() ?? true { return false } - guard !meshBroadcastEventIDs.contains(event.id), - !publishedEventIDs.contains(event.id) else { + guard !relayEngine.meshBroadcastEventIDs.contains(event.id), + !relayEngine.publishedEventIDs.contains(event.id) else { return false } // A single gateway is enough — relays fan out from there, and BLE @@ -464,19 +370,12 @@ final class GatewayService: ObservableObject { let event = carrier.event(), event.kind == NostrProtocol.EventKind.ephemeralEvent.rawValue, event.tags.contains(where: { $0.count >= 2 && $0[0] == "g" && $0[1] == carrier.geohash }), - isFresh(event) else { + relayEngine.isFresh(event) else { return nil } return event } - /// True when `event.created_at` is within the accepted clock skew — the - /// SAME freshness window receivers enforce, so a gateway never spends - /// airtime on events every receiver would drop as stale. - private func isFresh(_ event: NostrEvent) -> Bool { - abs(now().timeIntervalSince1970 - TimeInterval(event.created_at)) <= Limits.maxEventAgeSeconds - } - private static let validGeohashCharacters: Set = Set("0123456789bcdefghjkmnpqrstuvwxyz") static func isValidGeohash(_ geohash: String) -> Bool { diff --git a/bitchat/Services/NostrTransport.swift b/bitchat/Services/NostrTransport.swift index 31416927..f05d8221 100644 --- a/bitchat/Services/NostrTransport.swift +++ b/bitchat/Services/NostrTransport.swift @@ -240,18 +240,8 @@ final class NostrTransport: Transport, @unchecked Sendable { weak var eventDelegate: TransportEventDelegate? weak var peerEventsDelegate: TransportPeerEventsDelegate? - func currentPeerSnapshots() -> [TransportPeerSnapshot] { [] } - var myPeerID: PeerID { senderPeerID } - var myNickname: String { "" } - func setNickname(_ nickname: String) { /* not used for Nostr */ } - func startServices() { /* no-op */ } - func stopServices() { /* no-op */ } - func emergencyDisconnectAll() { /* no-op */ } - - func isPeerConnected(_ peerID: PeerID) -> Bool { false } - func isPeerReachable(_ peerID: PeerID) -> Bool { // Callers address peers by either the short 16-hex ID or the full // 64-hex noise key (offline favorites), so compare in short form. @@ -276,18 +266,8 @@ final class NostrTransport: Transport, @unchecked Sendable { canDeliverPromptly(to: peerID) } - func peerNickname(peerID: PeerID) -> String? { nil } - func getPeerNicknames() -> [PeerID: String] { [:] } - - func getFingerprint(for peerID: PeerID) -> String? { nil } - func getNoiseSessionState(for peerID: PeerID) -> LazyHandshakeState { .none } - func triggerHandshake(with peerID: PeerID) { /* no-op */ } - - // Nostr does not use Noise sessions here; the inert Transport defaults - // for the noise* identity hooks apply. - - // Public broadcast not supported over Nostr here - func sendMessage(_ content: String, mentions: [String]) { /* no-op */ } + // Mesh-only lifecycle, discovery, Noise, and broadcast Transport hooks use + // the inert defaults defined in `extension Transport`. func sendPrivateMessage(_ content: String, to peerID: PeerID, recipientNickname: String, messageID: String) { let generation = dependencies.ackPacer.currentGeneration() @@ -334,7 +314,6 @@ final class NostrTransport: Transport, @unchecked Sendable { } } - func sendBroadcastAnnounce() { /* no-op for Nostr */ } func sendDeliveryAck(for messageID: String, to peerID: PeerID) { enqueueAck(.deliveredDirect(messageID: messageID, peerID: peerID)) } diff --git a/bitchat/Services/PrivateChatManager.swift b/bitchat/Services/PrivateChatManager.swift index f97437e3..7cf9aed7 100644 --- a/bitchat/Services/PrivateChatManager.swift +++ b/bitchat/Services/PrivateChatManager.swift @@ -8,25 +8,17 @@ import BitLogger import BitFoundation -import Combine import Foundation -import SwiftUI -/// Manages private chat session policy (selection, read receipts, -/// consolidation). Message storage lives in the single-writer -/// `ConversationStore` (docs/CONVERSATION-STORE-DESIGN.md); the -/// `privateChats` / `unreadMessages` properties below are read-only views -/// derived from it. +/// Manages private chat session policy (selection delegation, read receipts, +/// consolidation). Message and selection state live in the single-writer +/// `ConversationStore`. @MainActor -final class PrivateChatManager: ObservableObject { - /// Read-only mirror of `ConversationStore.selectedPrivatePeerID` — the - /// store is the sole owner of conversation selection. Kept `@Published` - /// so existing observers (`objectWillChange` forwarding into - /// `ChatViewModel`) keep firing on selection changes. Mutate via - /// `startChat(with:)` / `endChat()`, which route through the store's - /// `setSelectedPrivatePeer` intent. - @Published private(set) var selectedPeer: PeerID? = nil - private var selectedPeerMirrorCancellable: AnyCancellable? = nil +final class PrivateChatManager { + /// Current direct-conversation selection, read directly from `ConversationStore`. + var selectedPeer: PeerID? { + conversationStore?.selectedPrivatePeerID + } var sentReadReceipts: Set = [] // Made accessible for ChatViewModel @@ -37,34 +29,17 @@ final class PrivateChatManager: ObservableObject { weak var unifiedPeerService: UnifiedPeerService? /// Single source of truth for message and selection state; injected by /// the bootstrapper (`wireServiceGraph`). - var conversationStore: ConversationStore? { - didSet { bindSelectionMirror() } - } + var conversationStore: ConversationStore? init(meshService: Transport? = nil, conversationStore: ConversationStore? = nil) { self.meshService = meshService self.conversationStore = conversationStore - bindSelectionMirror() // didSet does not fire during init } func resetForPanic() { sentReadReceipts.removeAll(keepingCapacity: false) } - /// Keeps `selectedPeer` in lock-step with the store's selection axis - /// (including store-internal handoffs such as conversation migration). - private func bindSelectionMirror() { - guard let store = conversationStore else { - selectedPeerMirrorCancellable = nil - return - } - selectedPeerMirrorCancellable = store.$selectedPrivatePeerID - .sink { [weak self] peerID in - guard let self, self.selectedPeer != peerID else { return } - self.selectedPeer = peerID - } - } - #if DEBUG // MARK: - Derived message state (read-only compat views) diff --git a/bitchat/Services/Transport.swift b/bitchat/Services/Transport.swift index 7e5eb982..b60868a7 100644 --- a/bitchat/Services/Transport.swift +++ b/bitchat/Services/Transport.swift @@ -104,15 +104,11 @@ protocol PrivateMediaDeletionPersisting: AnyObject { func persistDeletedPrivateMedia( messageIDs: [String], payloadRelativePaths: [String: String], - protectedPayloadRelativePaths: Set, completion: @escaping @MainActor (Bool) -> Void ) - /// Gated unlink for a LEGACY (non-stable-ID) incoming payload whose - /// bubble was explicitly removed. Implementations delete the file only - /// when its path is not pending delivery and not reserved by any receipt - /// or in-flight deletion transaction; otherwise the file stays for - /// bounded quota cleanup. + /// Unlinks a legacy (non-stable-ID) incoming payload whose bubble was + /// explicitly removed when no stable receipt owns the path. @MainActor func removeLegacyPrivateMediaPayload(relativePath: String) } @@ -232,6 +228,23 @@ extension BitchatMessage { } extension Transport { + // Inert defaults for transports that only handle a subset of the mesh + // surface (e.g. NostrTransport for offline private messaging). + func currentPeerSnapshots() -> [TransportPeerSnapshot] { [] } + var myNickname: String { "" } + func setNickname(_ nickname: String) {} + func startServices() {} + func stopServices() {} + func emergencyDisconnectAll() {} + func isPeerConnected(_ peerID: PeerID) -> Bool { false } + func peerNickname(peerID: PeerID) -> String? { nil } + func getPeerNicknames() -> [PeerID: String] { [:] } + func getFingerprint(for peerID: PeerID) -> String? { nil } + func getNoiseSessionState(for peerID: PeerID) -> LazyHandshakeState { .none } + func triggerHandshake(with peerID: PeerID) {} + func sendMessage(_ content: String, mentions: [String]) {} + func sendBroadcastAnnounce() {} + // Reachability implies prompt delivery for transports that hand packets // straight to the radio; queue-backed transports override this. func canDeliverPromptly(to peerID: PeerID) -> Bool { isPeerReachable(peerID) } diff --git a/bitchat/ViewModels/ChatComposerCoordinator.swift b/bitchat/ViewModels/ChatComposerCoordinator.swift index d94e8952..5fad3184 100644 --- a/bitchat/ViewModels/ChatComposerCoordinator.swift +++ b/bitchat/ViewModels/ChatComposerCoordinator.swift @@ -9,7 +9,7 @@ import Foundation /// testable (see `ChatComposerCoordinatorContextTests`) and makes its true /// dependencies explicit. @MainActor -protocol ChatComposerContext: AnyObject { +protocol ChatComposerContext: ChatIdentityContext, ChatGeohashIdentityContext { // MARK: Autocomplete UI state var autocompleteSuggestions: [String] { get set } var autocompleteRange: NSRange? { get set } @@ -24,21 +24,12 @@ protocol ChatComposerContext: AnyObject { /// Replaces the matched range in `text` with the chosen suggestion. func applyAutocompleteSuggestion(_ suggestion: String, to text: String, range: NSRange) -> String - // MARK: Identity & channel state - var nickname: String { get } - var myPeerID: PeerID { get } - var activeChannel: ChannelID { get } + // MARK: Peer lookups /// The transport's own nickname (excluded from autocomplete candidates). var meshNickname: String { get } func meshPeerNicknames() -> [PeerID: String] /// True when this mesh nickname belongs to a blocked peer. func isMeshNicknameBlocked(_ nickname: String) -> Bool - /// True when this geohash pubkey is blocked for location chats. - func isNostrBlocked(pubkeyHexLowercased: String) -> Bool - - // MARK: Geohash identity (shared with the other contexts) - var geoNicknames: [String: String] { get } - func deriveNostrIdentity(forGeohash geohash: String) throws -> NostrIdentity } extension ChatViewModel: ChatComposerContext { diff --git a/bitchat/ViewModels/ChatLifecycleCoordinator.swift b/bitchat/ViewModels/ChatLifecycleCoordinator.swift index 3fe87392..dd63105a 100644 --- a/bitchat/ViewModels/ChatLifecycleCoordinator.swift +++ b/bitchat/ViewModels/ChatLifecycleCoordinator.swift @@ -10,22 +10,11 @@ import Foundation /// testable (see `ChatLifecycleCoordinatorContextTests`) and makes its true /// dependencies explicit. @MainActor -protocol ChatLifecycleContext: AnyObject { +protocol ChatLifecycleContext: ChatIdentityContext, ChatDirectMessageStoreContext { // MARK: Chat & receipt state - /// A single private chat's timeline (store-direct lookup on - /// `ChatViewModel`; no `privateChats` dictionary build). - func privateMessages(for peerID: PeerID) -> [BitchatMessage] var unreadPrivateMessages: Set { get } var selectedPrivateChatPeer: PeerID? { get } - /// Appends a private message via the single-writer store intent. - @discardableResult - func appendPrivateMessage(_ message: BitchatMessage, to peerID: PeerID) -> Bool - /// Clears the peer's unread flag (store unread state only). - func markPrivateChatRead(_ peerID: PeerID) var sentReadReceipts: Set { get } - var nickname: String { get } - var myPeerID: PeerID { get } - var activeChannel: ChannelID { get } var nostrKeyMapping: [PeerID: String] { get } /// Records that a read receipt is being sent for `messageID`. /// Returns `false` when one was already recorded — the caller must skip sending. diff --git a/bitchat/ViewModels/ChatLiveVoiceCoordinator.swift b/bitchat/ViewModels/ChatLiveVoiceCoordinator.swift index 4641d537..9aa1d17d 100644 --- a/bitchat/ViewModels/ChatLiveVoiceCoordinator.swift +++ b/bitchat/ViewModels/ChatLiveVoiceCoordinator.swift @@ -219,7 +219,7 @@ final class ChatLiveVoiceCoordinator { /// `ioQueue` in production while keeping synchronous unit tests deterministic. init( context: any ChatLiveVoiceContext, - fileStore: BLEIncomingFileStore = BLEIncomingFileStore(), + fileStore: BLEIncomingFileStore = .shared, sweepsOnInit: Bool = true, asyncStartupSweep: Bool = false, asyncQuotaEnforcement: Bool = false diff --git a/bitchat/ViewModels/ChatMediaTransferCoordinator.swift b/bitchat/ViewModels/ChatMediaTransferCoordinator.swift index 97a80b19..32243037 100644 --- a/bitchat/ViewModels/ChatMediaTransferCoordinator.swift +++ b/bitchat/ViewModels/ChatMediaTransferCoordinator.swift @@ -67,13 +67,10 @@ private struct PrivateMediaReconnectRetryCandidate { /// testable (see `ChatMediaTransferCoordinatorContextTests`) and makes its /// true dependencies explicit. @MainActor -protocol ChatMediaTransferContext: AnyObject { +protocol ChatMediaTransferContext: ChatIdentityContext { // MARK: Composition state var canSendMediaInCurrentContext: Bool { get } var selectedPrivateChatPeer: PeerID? { get } - var nickname: String { get } - var myPeerID: PeerID { get } - var activeChannel: ChannelID { get } func nicknameForPeer(_ peerID: PeerID) -> String func currentPublicSender() -> (name: String, peerID: PeerID) @@ -309,44 +306,17 @@ extension ChatViewModel: ChatMediaTransferContext { return } let requestedIDs = Set(messageIDs) - let incomingPathReferences = Array( - conversations.conversationsByID.values - .lazy - .flatMap(\.messages) - .compactMap { message -> ( - messageID: String, - path: String - )? in - guard self.isIncomingPrivateMessage(message), - let path = self.incomingMediaRelativePath( - for: message - ) else { - return nil - } - return (message.id, path) - } - ) - let ownerIDsByPath = Dictionary( - grouping: incomingPathReferences, - by: { $0.path } - ).mapValues { Set($0.map(\.messageID)) } - let protectedPayloadRelativePaths = Set( - ownerIDsByPath.compactMap { path, ownerIDs in - ownerIDs.isSubset(of: requestedIDs) ? nil : path - } - ) var payloadRelativePaths: [String: String] = [:] - for reference in incomingPathReferences - where requestedIDs.contains(reference.messageID) - && ownerIDsByPath[reference.path, default: []] - .isSubset(of: requestedIDs) { - payloadRelativePaths[reference.messageID] = reference.path + for message in conversations.conversationsByID.values.lazy.flatMap(\.messages) + where requestedIDs.contains(message.id) + && isIncomingPrivateMessage(message) { + if let path = incomingMediaRelativePath(for: message) { + payloadRelativePaths[message.id] = path + } } persistence.persistDeletedPrivateMedia( messageIDs: messageIDs, payloadRelativePaths: payloadRelativePaths, - protectedPayloadRelativePaths: - protectedPayloadRelativePaths, completion: completion ) } diff --git a/bitchat/ViewModels/ChatOutgoingCoordinator.swift b/bitchat/ViewModels/ChatOutgoingCoordinator.swift index 05ee9973..4671a80e 100644 --- a/bitchat/ViewModels/ChatOutgoingCoordinator.swift +++ b/bitchat/ViewModels/ChatOutgoingCoordinator.swift @@ -10,11 +10,8 @@ import Foundation /// testable (see `ChatOutgoingCoordinatorContextTests`) and makes its true /// dependencies explicit. @MainActor -protocol ChatOutgoingContext: AnyObject { - // MARK: Identity & channel state - var nickname: String { get } - var myPeerID: PeerID { get } - var activeChannel: ChannelID { get } +protocol ChatOutgoingContext: ChatIdentityContext { + // MARK: Channel & selection state var selectedPrivateChatPeer: PeerID? { get } var isTeleported: Bool { get } diff --git a/bitchat/ViewModels/ChatPrivateConversationCoordinator.swift b/bitchat/ViewModels/ChatPrivateConversationCoordinator.swift index d82fb961..e8cf2ba9 100644 --- a/bitchat/ViewModels/ChatPrivateConversationCoordinator.swift +++ b/bitchat/ViewModels/ChatPrivateConversationCoordinator.swift @@ -12,25 +12,14 @@ import Foundation /// documents the coordinator's real coupling to private-chat state, peer /// identity, and the routing/ack transports. @MainActor -protocol ChatPrivateConversationContext: AnyObject { +protocol ChatPrivateConversationContext: ChatIdentityContext, ChatDirectMessageStoreContext { // MARK: Conversation state var privateChats: [PeerID: [BitchatMessage]] { get } - /// A single private chat's timeline. Witnessed by the store-direct - /// lookup on `ChatViewModel` (no `privateChats` dictionary build). - func privateMessages(for peerID: PeerID) -> [BitchatMessage] var sentReadReceipts: Set { get } var selectedPrivateChatPeer: PeerID? { get } - var nickname: String { get } - var activeChannel: ChannelID { get } var nostrKeyMapping: [PeerID: String] { get } // MARK: Conversation store intents - // The sole mutation paths for private message state (single-writer - // `ConversationStore` ops; see docs/CONVERSATION-STORE-DESIGN.md). - /// Appends a private message in timestamp order; returns `false` on - /// duplicate message ID. - @discardableResult - func appendPrivateMessage(_ message: BitchatMessage, to peerID: PeerID) -> Bool /// Replace-or-append a private message by ID, keeping its position. func upsertPrivateMessage(_ message: BitchatMessage, in peerID: PeerID) /// Applies a delivery status by message ID; returns `false` when the @@ -38,7 +27,6 @@ protocol ChatPrivateConversationContext: AnyObject { @discardableResult func setPrivateDeliveryStatus(_ status: DeliveryStatus, forMessageID messageID: String, peerID: PeerID) -> Bool func markPrivateChatUnread(_ peerID: PeerID) - func markPrivateChatRead(_ peerID: PeerID) /// Moves all messages from `oldPeerID`'s chat into `newPeerID`'s chat /// (dedup by ID, order preserved, unread carried, old chat removed). func migratePrivateChat(from oldPeerID: PeerID, to newPeerID: PeerID) @@ -60,7 +48,6 @@ protocol ChatPrivateConversationContext: AnyObject { func handOffSelectedPrivateChat(from oldPeerIDs: [PeerID], to newPeerID: PeerID) // MARK: Peers & identity - var myPeerID: PeerID { get } func peerNickname(for peerID: PeerID) -> String? func isPeerConnected(_ peerID: PeerID) -> Bool func isPeerReachable(_ peerID: PeerID) -> Bool diff --git a/bitchat/ViewModels/ChatPublicConversationCoordinator.swift b/bitchat/ViewModels/ChatPublicConversationCoordinator.swift index 724f9b2c..91e2487f 100644 --- a/bitchat/ViewModels/ChatPublicConversationCoordinator.swift +++ b/bitchat/ViewModels/ChatPublicConversationCoordinator.swift @@ -18,12 +18,9 @@ import UIKit /// conversation stores, geohash participants, and the inbound public message /// pipeline. @MainActor -protocol ChatPublicConversationContext: AnyObject { +protocol ChatPublicConversationContext: ChatIdentityContext { // MARK: Channel state - var activeChannel: ChannelID { get } var currentGeohash: String? { get } - var nickname: String { get } - var myPeerID: PeerID { get } // MARK: Public conversation store (single-writer intents) /// Appends a public message in timestamp order. Returns `false` when a diff --git a/bitchat/ViewModels/ChatSharedContexts.swift b/bitchat/ViewModels/ChatSharedContexts.swift new file mode 100644 index 00000000..6ac340de --- /dev/null +++ b/bitchat/ViewModels/ChatSharedContexts.swift @@ -0,0 +1,27 @@ +import BitFoundation +import Foundation + +/// Shared local identity and channel state read by multiple ViewModel coordinators. +@MainActor +protocol ChatIdentityContext: AnyObject { + var nickname: String { get } + var myPeerID: PeerID { get } + var activeChannel: ChannelID { get } +} + +/// Shared single-writer direct-conversation store intents. +@MainActor +protocol ChatDirectMessageStoreContext: AnyObject { + func privateMessages(for peerID: PeerID) -> [BitchatMessage] + @discardableResult + func appendPrivateMessage(_ message: BitchatMessage, to peerID: PeerID) -> Bool + func markPrivateChatRead(_ peerID: PeerID) +} + +/// Shared geohash/Nostr identity lookup and blocking surface. +@MainActor +protocol ChatGeohashIdentityContext: AnyObject { + var geoNicknames: [String: String] { get } + func deriveNostrIdentity(forGeohash geohash: String) throws -> NostrIdentity + func isNostrBlocked(pubkeyHexLowercased: String) -> Bool +} diff --git a/bitchat/ViewModels/ChatViewModelBootstrapper.swift b/bitchat/ViewModels/ChatViewModelBootstrapper.swift index 69cc735d..fc092bc6 100644 --- a/bitchat/ViewModels/ChatViewModelBootstrapper.swift +++ b/bitchat/ViewModels/ChatViewModelBootstrapper.swift @@ -312,6 +312,19 @@ private extension ChatViewModelBootstrapper { ) } + private static func publishToGeoRelays(event: NostrEvent, geohash: String, logPrefix: String) { + let relays = GeoRelayDirectory.shared.closestRelays( + toGeohash: geohash, + count: TransportConfig.nostrGeoRelayCount + ) + // Refuse rather than publish to default relays no geo subscriber reads. + guard !relays.isEmpty else { + SecureLogger.warning("\(logPrefix): no geo relays for #\(geohash); not publishing", category: .session) + return + } + NostrRelayManager.shared.sendEvent(event, to: relays) + } + /// Wires the gateway-mode policy layer (`GatewayService`) to the mesh /// transport, the relay manager, and the inbound Nostr pipeline. All /// dependencies are closures so the service stays unit-testable with @@ -323,19 +336,7 @@ private extension ChatViewModelBootstrapper { let gateway = GatewayService.shared gateway.publishToRelays = { event, geohash in - let relays = GeoRelayDirectory.shared.closestRelays( - toGeohash: geohash, - count: TransportConfig.nostrGeoRelayCount - ) - // Symmetric with the local send path (GeohashSubscriptionManager - // .sendGeohash): with no known geo relay, refuse rather than - // publish to default relays no geo subscriber reads — that would - // be silent dead traffic, not delivery. - guard !relays.isEmpty else { - SecureLogger.warning("🌐 Gateway: no geo relays for #\(geohash); not publishing carried event", category: .session) - return - } - NostrRelayManager.shared.sendEvent(event, to: relays) + Self.publishToGeoRelays(event: event, geohash: geohash, logPrefix: "🌐 Gateway") } gateway.broadcastToMesh = { [weak bleService] payload in bleService?.broadcastNostrCarrier(payload) @@ -403,15 +404,7 @@ private extension ChatViewModelBootstrapper { let idBridge = viewModel.idBridge bridge.publishToRelays = { event, cell in - let relays = GeoRelayDirectory.shared.closestRelays( - toGeohash: cell, - count: TransportConfig.nostrGeoRelayCount - ) - guard !relays.isEmpty else { - SecureLogger.warning("🌉 Bridge: no geo relays for cell \(cell); not publishing", category: .session) - return - } - NostrRelayManager.shared.sendEvent(event, to: relays) + Self.publishToGeoRelays(event: event, geohash: cell, logPrefix: "🌉 Bridge") } bridge.openSubscription = { cells in guard let cell = cells.first else { return } diff --git a/bitchatTests/ChatViewModelTests.swift b/bitchatTests/ChatViewModelTests.swift index 32290200..9f07acc8 100644 --- a/bitchatTests/ChatViewModelTests.swift +++ b/bitchatTests/ChatViewModelTests.swift @@ -1303,7 +1303,7 @@ struct ChatViewModelPrivateMediaDeletionTests { } @Test @MainActor - func stableDeleteProtectsPathSharedWithLegacyBubble() { + func stableDeleteRefusalKeepsBubblesAndSurfacesSystemMessage() { let (viewModel, transport) = makeTestableViewModel() transport.persistDeletedPrivateMediaResult = false let peerID = PeerID(str: String(repeating: "6", count: 64)) @@ -1332,11 +1332,9 @@ struct ChatViewModelPrivateMediaDeletionTests { #expect( transport.deletedPrivateMediaMessageIDBatches == [[stableID]] ) - #expect(transport.deletedPrivateMediaRelativePaths == [[:]]) #expect( - transport.protectedPrivateMediaRelativePaths == [[ - "images/incoming/\(filename)" - ]] + transport.deletedPrivateMediaRelativePaths + == [[stableID: "images/incoming/\(filename)"]] ) let messages = viewModel.privateChats[peerID] ?? [] #expect(messages.prefix(2).map(\.id) == [stableID, legacyID]) diff --git a/bitchatTests/EndToEnd/PrivateMediaEndToEndTests.swift b/bitchatTests/EndToEnd/PrivateMediaEndToEndTests.swift index 7799f04c..a19ad5b7 100644 --- a/bitchatTests/EndToEnd/PrivateMediaEndToEndTests.swift +++ b/bitchatTests/EndToEnd/PrivateMediaEndToEndTests.swift @@ -1544,6 +1544,7 @@ struct PrivateMediaEndToEndTests { guard let url = item as? URL, !url.pathComponents.contains(".private-media-receipts"), url.lastPathComponent != ".private-media-receipts.json", + url.lastPathComponent != BLEPrivateMediaReceiptStore.ledgerFileName, (try? url.resourceValues(forKeys: [.isRegularFileKey]).isRegularFile) == true else { return nil } diff --git a/bitchatTests/Mocks/MockTransport.swift b/bitchatTests/Mocks/MockTransport.swift index f0ba9a43..f7bb89b3 100644 --- a/bitchatTests/Mocks/MockTransport.swift +++ b/bitchatTests/Mocks/MockTransport.swift @@ -44,7 +44,6 @@ final class MockTransport: Transport, PrivateMediaDeletionPersisting, private(set) var deletedPrivateMediaRelativePaths: [ [String: String] ] = [] - private(set) var protectedPrivateMediaRelativePaths: [Set] = [] private(set) var sentVerifyChallenges: [(peerID: PeerID, noiseKeyHex: String, nonceA: Data)] = [] private(set) var sentVerifyResponses: [(peerID: PeerID, noiseKeyHex: String, nonceA: Data)] = [] private(set) var sentCourierMessages: [(content: String, messageID: String, recipientNoiseKey: Data, couriers: [PeerID])] = [] @@ -252,14 +251,10 @@ final class MockTransport: Transport, PrivateMediaDeletionPersisting, func persistDeletedPrivateMedia( messageIDs: [String], payloadRelativePaths: [String: String], - protectedPayloadRelativePaths: Set, completion: @escaping @MainActor (Bool) -> Void ) { deletedPrivateMediaMessageIDBatches.append(messageIDs) deletedPrivateMediaRelativePaths.append(payloadRelativePaths) - protectedPrivateMediaRelativePaths.append( - protectedPayloadRelativePaths - ) if deferDeletedPrivateMediaPersistence { pendingDeletedPrivateMediaCompletions.append(completion) } else { @@ -381,7 +376,6 @@ final class MockTransport: Transport, PrivateMediaDeletionPersisting, cancelledTransfers.removeAll() deletedPrivateMediaMessageIDBatches.removeAll() deletedPrivateMediaRelativePaths.removeAll() - protectedPrivateMediaRelativePaths.removeAll() sentVerifyChallenges.removeAll() sentVerifyResponses.removeAll() startServicesCallCount = 0 diff --git a/bitchatTests/Noise/NoiseCoverageTests.swift b/bitchatTests/Noise/NoiseCoverageTests.swift index c777d63f..4bf35e2a 100644 --- a/bitchatTests/Noise/NoiseCoverageTests.swift +++ b/bitchatTests/Noise/NoiseCoverageTests.swift @@ -669,7 +669,7 @@ struct NoiseCoverageTests { try establishManagerSessions(aliceManager: aliceManager, bobManager: bobManager) let establishedSession = try #require( - aliceManager.getSession(for: alicePeerID) as? SecureNoiseSession + aliceManager.getSession(for: alicePeerID) ) establishedSession.setMessageCountForTesting( UInt64(Double(NoiseSecurityConstants.maxMessagesPerSession) * 0.9) @@ -810,13 +810,13 @@ struct NoiseCoverageTests { @Test("Secure noise sessions enforce limits and renegotiation thresholds") func secureNoiseSessionsEnforceLimitsAndThresholds() throws { - let initiator = SecureNoiseSession( + let initiator = NoiseSession( peerID: alicePeerID, role: .initiator, keychain: keychain, localStaticKey: aliceStaticKey ) - let responder = SecureNoiseSession( + let responder = NoiseSession( peerID: bobPeerID, role: .responder, keychain: keychain, @@ -863,13 +863,13 @@ struct NoiseCoverageTests { @Test("Secure noise sessions expire based on session start time") func secureNoiseSessionsExpireBasedOnSessionStartTime() throws { - let initiator = SecureNoiseSession( + let initiator = NoiseSession( peerID: alicePeerID, role: .initiator, keychain: keychain, localStaticKey: aliceStaticKey ) - let responder = SecureNoiseSession( + let responder = NoiseSession( peerID: bobPeerID, role: .responder, keychain: keychain, @@ -901,13 +901,13 @@ struct NoiseCoverageTests { // sessionExpired on every call. needsRenegotiation() has to notice // the session is old on its own -- it can't rely on the idle check, // because there is no idle time to find. - let session = SecureNoiseSession( + let session = NoiseSession( peerID: alicePeerID, role: .initiator, keychain: keychain, localStaticKey: aliceStaticKey ) - let responder = SecureNoiseSession( + let responder = NoiseSession( peerID: bobPeerID, role: .responder, keychain: keychain, diff --git a/bitchatTests/Noise/NoiseProtocolTests.swift b/bitchatTests/Noise/NoiseProtocolTests.swift index fa6789b1..77077565 100644 --- a/bitchatTests/Noise/NoiseProtocolTests.swift +++ b/bitchatTests/Noise/NoiseProtocolTests.swift @@ -186,14 +186,18 @@ struct NoiseProtocolTests { @Test func largeMessageEncryption() throws { try performHandshake(initiator: aliceSession, responder: bobSession) - // Create a large message - let largeMessage = TestHelpers.generateRandomData(length: 100_000) - - // Encrypt and decrypt - let ciphertext = try aliceSession.encrypt(largeMessage) + // Ordinary Noise payloads are capped at NoiseSecurityConstants.maxMessageSize. + let maxOrdinaryMessage = TestHelpers.generateRandomData(length: NoiseSecurityConstants.maxMessageSize) + let ciphertext = try aliceSession.encrypt(maxOrdinaryMessage) let decrypted = try bobSession.decrypt(ciphertext) - - #expect(decrypted == largeMessage) + #expect(decrypted == maxOrdinaryMessage) + + // Private-file typed payloads may exceed the ordinary cap up to the framed-file limit. + var largePrivateFile = Data([NoisePayloadType.privateFile.rawValue]) + largePrivateFile.append(TestHelpers.generateRandomData(length: 100_000)) + let fileCiphertext = try aliceSession.encrypt(largePrivateFile) + let fileDecrypted = try bobSession.decrypt(fileCiphertext) + #expect(fileDecrypted == largePrivateFile) } @Test func encryptionBeforeHandshake() { diff --git a/bitchatTests/Noise/SecureNoiseSessionConcurrencyTests.swift b/bitchatTests/Noise/SecureNoiseSessionConcurrencyTests.swift index 018cd7d2..e58dc306 100644 --- a/bitchatTests/Noise/SecureNoiseSessionConcurrencyTests.swift +++ b/bitchatTests/Noise/SecureNoiseSessionConcurrencyTests.swift @@ -14,18 +14,18 @@ import BitFoundation struct SecureNoiseSessionConcurrencyTests { - private func makeEstablishedPair() throws -> (initiator: SecureNoiseSession, responder: SecureNoiseSession) { + private func makeEstablishedPair() throws -> (initiator: NoiseSession, responder: NoiseSession) { let aliceKey = Curve25519.KeyAgreement.PrivateKey() let bobKey = Curve25519.KeyAgreement.PrivateKey() let keychain = MockKeychain() - let alice = SecureNoiseSession( + let alice = NoiseSession( peerID: PeerID(publicKey: bobKey.publicKey.rawRepresentation), role: .initiator, keychain: keychain, localStaticKey: aliceKey ) - let bob = SecureNoiseSession( + let bob = NoiseSession( peerID: PeerID(publicKey: aliceKey.publicKey.rawRepresentation), role: .responder, keychain: keychain, diff --git a/bitchatTests/Services/BLEFileTransferHandlerTests.swift b/bitchatTests/Services/BLEFileTransferHandlerTests.swift index 42d4f929..c57e405d 100644 --- a/bitchatTests/Services/BLEFileTransferHandlerTests.swift +++ b/bitchatTests/Services/BLEFileTransferHandlerTests.swift @@ -21,7 +21,8 @@ struct BLEFileTransferHandlerTests { var receiptCommits: [(messageID: String, storedURL: URL)] = [] var receiptCommitSucceeds = true var removedIncomingFiles: [URL] = [] - var finishedIncomingFileDeliveries: [URL] = [] + var beganPendingDeliveries: [URL] = [] + var finishedPendingDeliveries: [URL] = [] var lastSeenUpdates: [PeerID] = [] var deliveryAcks: [(messageID: String, peerID: PeerID)] = [] var deliveredMessages: [BitchatMessage] = [] @@ -37,85 +38,12 @@ struct BLEFileTransferHandlerTests { var receiptStateOverride: ((String) -> BLEPrivateMediaReceiptState)? var receiptCommitOverride: ((String, URL) -> Bool)? var removeIncomingFileOverride: ((URL) -> Void)? - var finishIncomingFileDeliveryOverride: ((URL) -> Void)? } private let localPeerID = PeerID(str: "0102030405060708") private let remotePeerID = PeerID(str: "1122334455667788") private let sampleSigningKey = Data(repeating: 0xAB, count: 32) - @Test @MainActor - func deliveryGateFinalizesInitialRejection() { - var completions = 0 - var finalizations = 0 - - TransportEventDeliveryGate.attempt( - shouldDeliver: { false }, - deliver: { - Issue.record("delivery sink must not run") - return .accepted - }, - completion: { completions += 1 }, - finalization: { _ in finalizations += 1 } - ) - - #expect(completions == 0) - #expect(finalizations == 1) - } - - @Test @MainActor - func deliveryGateFinalizesMissingOrRejectingSink() { - var completions = 0 - var finalizations = 0 - - TransportEventDeliveryGate.attempt( - shouldDeliver: { true }, - deliver: { .rejected }, - completion: { completions += 1 }, - finalization: { _ in finalizations += 1 } - ) - - #expect(completions == 0) - #expect(finalizations == 1) - } - - @Test @MainActor - func deliveryGateFinalizesPostInsertionRejection() { - var deliveryChecks = 0 - var completions = 0 - var finalizations = 0 - - TransportEventDeliveryGate.attempt( - shouldDeliver: { - deliveryChecks += 1 - return deliveryChecks == 1 - }, - deliver: { .accepted }, - completion: { completions += 1 }, - finalization: { _ in finalizations += 1 } - ) - - #expect(deliveryChecks == 2) - #expect(completions == 0) - #expect(finalizations == 1) - } - - @Test @MainActor - func deliveryGatePreservesInvokedUnconfirmedOutcomeWithoutAck() { - var completions = 0 - var outcomes: [TransportEventDeliveryOutcome] = [] - - TransportEventDeliveryGate.attempt( - shouldDeliver: { true }, - deliver: { .invokedUnconfirmed }, - completion: { completions += 1 }, - finalization: { outcomes.append($0) } - ) - - #expect(completions == 0) - #expect(outcomes == [.invokedUnconfirmed]) - } - private func makeHandler(recorder: Recorder) -> BLEFileTransferHandler { let environment = BLEFileTransferHandlerEnvironment( localPeerID: { [localPeerID] in localPeerID }, @@ -162,9 +90,11 @@ struct BLEFileTransferHandlerTests { recorder.removedIncomingFiles.append(storedURL) recorder.removeIncomingFileOverride?(storedURL) }, - finishIncomingFileDelivery: { storedURL in - recorder.finishedIncomingFileDeliveries.append(storedURL) - recorder.finishIncomingFileDeliveryOverride?(storedURL) + beginPendingDelivery: { storedURL in + recorder.beganPendingDeliveries.append(storedURL) + }, + finishPendingDelivery: { storedURL in + recorder.finishedPendingDeliveries.append(storedURL) }, isPrivateMediaSenderBlocked: { peerID in recorder.blockedPeers.contains(peerID) @@ -216,6 +146,8 @@ struct BLEFileTransferHandlerTests { #expect(recorder.saveCalls.first?.defaultPrefix == "file") #expect(recorder.lastSeenUpdates.isEmpty) #expect(recorder.deliveredMessages.count == 1) + #expect(recorder.beganPendingDeliveries == [recorder.saveResult]) + #expect(recorder.finishedPendingDeliveries == [recorder.saveResult]) let message = recorder.deliveredMessages.first #expect(message?.sender == "Alice") #expect(message?.content == "[file] sample.pdf") @@ -289,6 +221,8 @@ struct BLEFileTransferHandlerTests { #expect(recorder.signedNameQueries == [remotePeerID]) #expect(recorder.deliveredMessages.count == 1) + #expect(recorder.beganPendingDeliveries == [recorder.saveResult]) + #expect(recorder.finishedPendingDeliveries == [recorder.saveResult]) #expect(recorder.deliveredMessages.first?.sender == "Bob") } @@ -311,6 +245,8 @@ struct BLEFileTransferHandlerTests { #expect(recorder.signatureVerifyCount == 1) #expect(recorder.signedNameQueries.isEmpty) #expect(recorder.deliveredMessages.count == 1) + #expect(recorder.beganPendingDeliveries == [recorder.saveResult]) + #expect(recorder.finishedPendingDeliveries == [recorder.saveResult]) #expect(recorder.deliveredMessages.first?.sender == "Me") } @@ -327,6 +263,8 @@ struct BLEFileTransferHandlerTests { // signature lookup (mirrors BLEPublicMessageHandler). #expect(recorder.signedNameQueries == [remotePeerID]) #expect(recorder.deliveredMessages.count == 1) + #expect(recorder.beganPendingDeliveries == [recorder.saveResult]) + #expect(recorder.finishedPendingDeliveries == [recorder.saveResult]) #expect(recorder.deliveredMessages.first?.sender == "Carol") } @@ -418,6 +356,8 @@ struct BLEFileTransferHandlerTests { #expect(recorder.trackedPackets.isEmpty) #expect(recorder.lastSeenUpdates == [remotePeerID]) #expect(recorder.deliveredMessages.count == 1) + #expect(recorder.beganPendingDeliveries == [recorder.saveResult]) + #expect(recorder.finishedPendingDeliveries == [recorder.saveResult]) #expect(recorder.deliveredMessages.first?.isPrivate == true) #expect(recorder.deliveredMessages.first?.id.hasPrefix("media-") == false) // Must be explicit: BitchatMessage defaults private messages to @@ -451,6 +391,8 @@ struct BLEFileTransferHandlerTests { #expect(recorder.saveCalls.first?.data == content) #expect(recorder.lastSeenUpdates == [remotePeerID]) #expect(recorder.deliveredMessages.count == 1) + #expect(recorder.beganPendingDeliveries == [recorder.saveResult]) + #expect(recorder.finishedPendingDeliveries == [recorder.saveResult]) #expect(recorder.deliveredMessages.first?.isPrivate == true) #expect(recorder.deliveredMessages.first?.timestamp == timestamp) #expect(recorder.deliveredMessages.first?.id == PrivateMediaMessageIdentity.stableID( @@ -496,9 +438,6 @@ struct BLEFileTransferHandlerTests { recorder.removeIncomingFileOverride = { store.removeIncomingFile(at: $0) } - recorder.finishIncomingFileDeliveryOverride = { - store.finishIncomingFileDelivery(at: $0) - } let content = TestImageFixtures.makeJPEG() let fileName = @@ -523,11 +462,10 @@ struct BLEFileTransferHandlerTests { )) #expect(recorder.deliveredMessages.isEmpty) #expect(recorder.deliveryAcks.isEmpty) - #expect(recorder.finishedIncomingFileDeliveries.count == 1) - #expect(store.reservePrivateMediaDeletion( + #expect(store.commitPrivateMediaDeletion( messageIDs: [stableID], payloadRelativePaths: [:] - ) != nil) + )) } @Test @@ -554,6 +492,8 @@ struct BLEFileTransferHandlerTests { #expect(recorder.receiptCommits.isEmpty) #expect(recorder.deliveryAcks.isEmpty) #expect(recorder.deliveredMessages.count == 1) + #expect(recorder.beganPendingDeliveries == [recorder.saveResult]) + #expect(recorder.finishedPendingDeliveries == [recorder.saveResult]) #expect(recorder.deliveredMessages.first?.id.hasPrefix("media-") == false) } @@ -581,7 +521,6 @@ struct BLEFileTransferHandlerTests { #expect(recorder.deliveredMessages.isEmpty) #expect(recorder.removedIncomingFiles.count == 1) #expect(recorder.removedIncomingFiles.first == recorder.saveResult) - #expect(recorder.finishedIncomingFileDeliveries.isEmpty) } @Test @@ -606,13 +545,10 @@ struct BLEFileTransferHandlerTests { #expect(handler.handle(packet, from: remotePeerID)) #expect(recorder.deliveredMessages.count == 1) + #expect(recorder.beganPendingDeliveries == [recorder.saveResult]) + #expect(recorder.finishedPendingDeliveries == [recorder.saveResult]) #expect(recorder.deliveryAcks.isEmpty) #expect(recorder.removedIncomingFiles.isEmpty) - #expect(recorder.finishedIncomingFileDeliveries.count == 1) - #expect( - recorder.finishedIncomingFileDeliveries.first - == recorder.saveResult - ) } @Test @@ -733,9 +669,6 @@ struct BLEFileTransferHandlerTests { recorder.removeIncomingFileOverride = { store.removeIncomingFile(at: $0) } - recorder.finishIncomingFileDeliveryOverride = { - store.finishIncomingFileDelivery(at: $0) - } } let first = Recorder() @@ -819,6 +752,8 @@ struct BLEFileTransferHandlerTests { #expect(recorder.saveCalls.count == 2) #expect(recorder.deliveryAcks.count == 1) #expect(recorder.deliveredMessages.count == 1) + #expect(recorder.beganPendingDeliveries == [recorder.saveResult]) + #expect(recorder.finishedPendingDeliveries == [recorder.saveResult]) } @Test @@ -926,6 +861,8 @@ struct BLEFileTransferHandlerTests { )) #expect(recorder.saveCalls.count == 1) #expect(recorder.deliveredMessages.count == 1) + #expect(recorder.beganPendingDeliveries == [recorder.saveResult]) + #expect(recorder.finishedPendingDeliveries == [recorder.saveResult]) #expect(recorder.deliveryAcks.count == 1) } @@ -1113,36 +1050,6 @@ struct BLEFileTransferHandlerTests { #expect(FileManager.default.fileExists(atPath: victim.path)) } - @Test - func legacyIncomingDeleteLeavesPendingDeliveryPayload() throws { - let base = FileManager.default.temporaryDirectory - .appendingPathComponent( - "legacy-pending-\(UUID().uuidString)", - isDirectory: true - ) - defer { try? FileManager.default.removeItem(at: base) } - let store = BLEIncomingFileStore(baseDirectory: base) - - // save() marks the stored path pending until delivery finishes; a - // legacy delete naming the same basename must not unlink it. - let stored = try #require(store.save( - data: Data([0xFF, 0xD8, 0xFF, 0xD9]), - preferredName: "pending.jpg", - subdirectory: "images/incoming", - fallbackExtension: "jpg", - defaultPrefix: "img" - )) - let relativePath = "images/incoming/\(stored.lastPathComponent)" - - #expect(!store.removeLegacyIncomingFile(relativePath: relativePath)) - #expect(FileManager.default.fileExists(atPath: stored.path)) - - // Once the delivery window closes the same unlink is allowed. - store.finishIncomingFileDelivery(at: stored) - #expect(store.removeLegacyIncomingFile(relativePath: relativePath)) - #expect(!FileManager.default.fileExists(atPath: stored.path)) - } - @Test func legacyIncomingDeleteLeavesReceiptProtectedPayload() throws { let base = FileManager.default.temporaryDirectory @@ -1277,49 +1184,37 @@ struct BLEFileTransferHandlerTests { } @Test - func panicWipeInvalidatesPayloadCoordinationReservations() throws { + func panicWipeAllowsFreshUniqueSavesAfterReset() throws { let base = FileManager.default.temporaryDirectory .appendingPathComponent( - "panic-payload-coordination-\(UUID().uuidString)", + "panic-unique-saves-\(UUID().uuidString)", isDirectory: true ) defer { try? FileManager.default.removeItem(at: base) } let store = BLEIncomingFileStore(baseDirectory: base) - let pendingName = "pending-before-panic.jpg" - let pendingURL = try #require(store.save( + let preferredName = "image-before-panic.jpg" + let prePanicURL = try #require(store.save( data: Data("old".utf8), - preferredName: pendingName, + preferredName: preferredName, subdirectory: "images/incoming", fallbackExtension: "jpg", defaultPrefix: "image" )) - let messageID = "media-aabbccddeeff00112233445566778899" - let reservation = try #require(store.reservePrivateMediaDeletion( - messageIDs: [messageID], - payloadRelativePaths: [ - messageID: "images/incoming/delete-before-panic.jpg" - ] - )) try store.panicWipe() - #expect(!store.commitPrivateMediaDeletion( - reservation: reservation, - messageIDs: [messageID], - payloadRelativePaths: [ - messageID: "images/incoming/delete-before-panic.jpg" - ], - protectedPayloadRelativePaths: [] - )) let postPanicURL = try #require(store.save( data: Data("new".utf8), - preferredName: pendingName, + preferredName: preferredName, subdirectory: "images/incoming", fallbackExtension: "jpg", defaultPrefix: "image" )) - #expect(pendingURL.lastPathComponent == pendingName) - #expect(postPanicURL.lastPathComponent == pendingName) + #expect(prePanicURL.lastPathComponent.hasSuffix("_\(preferredName)")) + #expect(postPanicURL.lastPathComponent.hasSuffix("_\(preferredName)")) + #expect(prePanicURL != postPanicURL) + #expect(!FileManager.default.fileExists(atPath: prePanicURL.path)) + #expect(FileManager.default.fileExists(atPath: postPanicURL.path)) } @Test diff --git a/bitchatTests/Services/BLEPrivateMediaReceiptStoreTests.swift b/bitchatTests/Services/BLEPrivateMediaReceiptStoreTests.swift index a443b856..c560980b 100644 --- a/bitchatTests/Services/BLEPrivateMediaReceiptStoreTests.swift +++ b/bitchatTests/Services/BLEPrivateMediaReceiptStoreTests.swift @@ -4,18 +4,18 @@ import Testing struct BLEPrivateMediaReceiptStoreTests { private struct TestError: Error {} - private struct ReceiptFixture: Codable { + private struct LegacyReceiptFixture: Codable { let kind: String let relativePath: String? let recordedAt: Date } - private struct JournalEntryFixture: Codable { + private struct LegacyJournalEntryFixture: Codable { let relativePaths: [String] let recordedAt: Date } - private struct JournalFixture: Codable { + private struct LegacyJournalFixture: Codable { let version: Int - let entries: [String: JournalEntryFixture] + let entries: [String: LegacyJournalEntryFixture] } private let messageID = "media-00112233445566778899aabbccddeeff" @@ -40,30 +40,15 @@ struct BLEPrivateMediaReceiptStoreTests { let root = makeRoot("accepted-ownership") defer { try? FileManager.default.removeItem(at: root) } let incoming = try makePayload(in: root) - let outgoingDirectory = root.appendingPathComponent( - "files/images/outgoing", - isDirectory: true - ) - try FileManager.default.createDirectory( - at: outgoingDirectory, - withIntermediateDirectories: true - ) + let outgoingDirectory = root.appendingPathComponent("files/images/outgoing", isDirectory: true) + try FileManager.default.createDirectory(at: outgoingDirectory, withIntermediateDirectories: true) let outgoing = outgoingDirectory.appendingPathComponent("image.jpg") try Data([0x01]).write(to: outgoing) let store = BLEPrivateMediaReceiptStore(baseDirectory: root) - #expect(!store.commitAccepted( - messageID: messageID, - storedURL: outgoing - )) - #expect(store.commitAccepted( - messageID: messageID, - storedURL: incoming - )) - #expect(!store.commitAccepted( - messageID: secondMessageID, - storedURL: incoming - )) + #expect(!store.commitAccepted(messageID: messageID, storedURL: outgoing)) + #expect(store.commitAccepted(messageID: messageID, storedURL: incoming)) + #expect(!store.commitAccepted(messageID: secondMessageID, storedURL: incoming)) #expect(FileManager.default.fileExists(atPath: incoming.path)) #expect(FileManager.default.fileExists(atPath: outgoing.path)) } @@ -81,10 +66,7 @@ struct BLEPrivateMediaReceiptStoreTests { ttl: 1, now: { recordedAt } ) - #expect(seed.commitAccepted( - messageID: messageID, - storedURL: firstPayload - )) + #expect(seed.commitAccepted(messageID: messageID, storedURL: firstPayload)) let relaunched = BLEPrivateMediaReceiptStore( baseDirectory: root, @@ -93,592 +75,166 @@ struct BLEPrivateMediaReceiptStoreTests { now: { recordedAt.addingTimeInterval(2) } ) #expect(relaunched.state(for: messageID) == .accepted(firstPayload)) - #expect(!relaunched.commitAccepted( - messageID: secondMessageID, - storedURL: secondPayload - )) + #expect(!relaunched.commitAccepted(messageID: secondMessageID, storedURL: secondPayload)) #expect(relaunched.state(for: messageID) == .accepted(firstPayload)) } @Test - func incomingAllocationDoesNotReuseReceiptOwnedMissingPath() throws { - let root = makeRoot("accepted-reservation") + func incomingAllocationUsesUniqueUUIDPrefixForEverySave() throws { + let root = makeRoot("uuid-filenames") defer { try? FileManager.default.removeItem(at: root) } - let original = try makePayload(in: root) - #expect(BLEPrivateMediaReceiptStore( - baseDirectory: root - ).commitAccepted( - messageID: messageID, - storedURL: original - )) - try FileManager.default.removeItem(at: original) + let store = BLEIncomingFileStore(baseDirectory: root) - let stored = BLEIncomingFileStore(baseDirectory: root).save( - data: Data([0x03]), - preferredName: "image.jpg", - subdirectory: "images/incoming", - fallbackExtension: "jpg", - defaultPrefix: "image" - ) - - #expect(stored?.lastPathComponent != "image.jpg") - #expect(stored.map { - FileManager.default.fileExists(atPath: $0.path) - } == true) - } - - @Test - func pendingRawArrivalBlocksDeletionFallbackPathReuse() throws { - let root = makeRoot("pending-raw-arrival") - defer { try? FileManager.default.removeItem(at: root) } - let incoming = BLEIncomingFileStore(baseDirectory: root) - - // The old stable bubble names image.jpg, but its receipt and payload - // have already been pruned. A raw arrival saves that basename before - // its main-actor bubble is inserted. - let rawArrival = incoming.save( - data: Data([0x03]), - preferredName: "image.jpg", - subdirectory: "images/incoming", - fallbackExtension: "jpg", - defaultPrefix: "image" - ) - #expect(rawArrival?.lastPathComponent == "image.jpg") - - let reservation = incoming.reservePrivateMediaDeletion( - messageIDs: [messageID], - payloadRelativePaths: [ - messageID: "images/incoming/image.jpg" - ] - ) - #expect(reservation == nil) - #expect(rawArrival.map { - FileManager.default.fileExists(atPath: $0.path) - } == true) - } - - @Test - func quotaDoesNotEvictOrReusePendingDeliveryPath() throws { - let root = makeRoot("pending-quota") - defer { try? FileManager.default.removeItem(at: root) } - let incoming = BLEIncomingFileStore( - baseDirectory: root, - quotaBytes: 1 - ) - let first = try #require(incoming.save( + let first = try #require(store.save( data: Data([0x01, 0x02]), preferredName: "image.jpg", subdirectory: "images/incoming", fallbackExtension: "jpg", defaultPrefix: "image" )) - - incoming.enforceQuota(reservingBytes: 1) - #expect(FileManager.default.fileExists(atPath: first.path)) - - let second = try #require(incoming.save( - data: Data([0x03]), + let second = try #require(store.save( + data: Data([0x03, 0x04]), preferredName: "image.jpg", subdirectory: "images/incoming", fallbackExtension: "jpg", defaultPrefix: "image" )) - #expect(second != first) - #expect(second.lastPathComponent == "image (1).jpg") + + #expect(first != second) + #expect(first.lastPathComponent.hasSuffix("_image.jpg")) + #expect(second.lastPathComponent.hasSuffix("_image.jpg")) + #expect(first.lastPathComponent != "image.jpg") #expect(FileManager.default.fileExists(atPath: first.path)) #expect(FileManager.default.fileExists(atPath: second.path)) } @Test - func invalidReceiptAndJournalCannotTargetOutgoingPayload() throws { - let root = makeRoot("invalid-owned-path") + func missingAcceptedPayloadPrunesStaleReceiptSoRetryCanRestore() throws { + let root = makeRoot("quota-evicted-retry") defer { try? FileManager.default.removeItem(at: root) } - let outgoingDirectory = root.appendingPathComponent( - "files/images/outgoing", - isDirectory: true - ) - try FileManager.default.createDirectory( - at: outgoingDirectory, - withIntermediateDirectories: true - ) - let victim = outgoingDirectory.appendingPathComponent("victim.jpg") - try Data([0x02]).write(to: victim) - let receiptURL = receiptRecord(in: root) - try FileManager.default.createDirectory( - at: receiptURL.deletingLastPathComponent(), - withIntermediateDirectories: true - ) - let fixture = ReceiptFixture( - kind: "tombstone", - relativePath: "images/outgoing/victim.jpg", - recordedAt: Date() - ) - try JSONEncoder().encode(fixture).write( - to: receiptURL, - options: .atomic - ) - - #expect( - BLEPrivateMediaReceiptStore(baseDirectory: root) - .state(for: messageID) == .unavailable - ) - #expect(FileManager.default.fileExists(atPath: victim.path)) - - // The invalid record was quarantined aside, never executed. Clear it - // so the second phase exercises the journal validation on its own. - #expect(!FileManager.default.fileExists(atPath: receiptURL.path)) - try FileManager.default.removeItem(at: quarantinedRecord(in: root)) - let journal = JournalFixture( - version: 1, - entries: [messageID: JournalEntryFixture( - relativePaths: ["images/outgoing/victim.jpg"], - recordedAt: fixture.recordedAt - )] - ) - try JSONEncoder().encode(journal).write( - to: deletionJournal(in: root), - options: .atomic - ) - - #expect( - BLEPrivateMediaReceiptStore(baseDirectory: root) - .state(for: messageID) == .unavailable - ) - #expect(FileManager.default.fileExists(atPath: victim.path)) - } - - @Test - func directoryEnumerationFailureIsUnavailableAndRetriesWithoutCachingEmpty() throws { - let root = makeRoot("list-failure") - defer { try? FileManager.default.removeItem(at: root) } - let payload = try makePayload(in: root) - #expect(BLEPrivateMediaReceiptStore(baseDirectory: root).commitAccepted( - messageID: messageID, - storedURL: payload - )) - let record = receiptRecord(in: root) - #expect(FileManager.default.fileExists(atPath: record.path)) - - var shouldFail = true - let store = BLEPrivateMediaReceiptStore( - baseDirectory: root, - directoryReader: { directory in - if shouldFail { - shouldFail = false - throw TestError() - } - return try FileManager.default.contentsOfDirectory( - at: directory, - includingPropertiesForKeys: nil - ) - } - ) - - #expect(store.state(for: messageID) == .unavailable) - #expect(FileManager.default.fileExists(atPath: record.path)) - #expect(store.state(for: messageID) == .accepted(payload)) - } - - @Test - func recordReadFailureQuarantinesOnlyThatRecord() throws { - let root = makeRoot("read-failure") - defer { try? FileManager.default.removeItem(at: root) } - let payload = try makePayload(in: root) - #expect(BLEPrivateMediaReceiptStore(baseDirectory: root).commitAccepted( - messageID: messageID, - storedURL: payload - )) - let record = receiptRecord(in: root) - let durableBytes = try Data(contentsOf: record) - - let store = BLEPrivateMediaReceiptStore( - baseDirectory: root, - dataReader: { url in - if url.lastPathComponent.hasPrefix(self.messageID) { - throw TestError() - } - return try Data(contentsOf: url) - } - ) - - #expect(store.state(for: messageID) == .unavailable) - // The record was moved aside, bytes intact, not deleted. - #expect(!FileManager.default.fileExists(atPath: record.path)) - let quarantined = quarantinedRecord(in: root) - #expect(FileManager.default.fileExists(atPath: quarantined.path)) - #expect(try Data(contentsOf: quarantined) == durableBytes) - // The quarantine is sticky for this ID; no absent/accepted flapping. - #expect(store.state(for: messageID) == .unavailable) - } - - @Test - func decodeFailureQuarantinesRecordWithoutRetryOrDeletion() throws { - let root = makeRoot("decode-failure") - defer { try? FileManager.default.removeItem(at: root) } - let payload = try makePayload(in: root) - #expect(BLEPrivateMediaReceiptStore(baseDirectory: root).commitAccepted( - messageID: messageID, - storedURL: payload - )) - let record = receiptRecord(in: root) - let corruptBytes = Data("{not-json".utf8) - try corruptBytes.write(to: record, options: .atomic) - + let original = try makePayload(in: root, name: "first.jpg") let store = BLEPrivateMediaReceiptStore(baseDirectory: root) - // Only this ID fails closed; it cannot be re-recorded past the - // quarantine either. - #expect(store.state(for: messageID) == .unavailable) - #expect(!store.commitAccepted(messageID: messageID, storedURL: payload)) - #expect(!store.recordDeleted(messageID: messageID)) - #expect(store.state(for: messageID) == .unavailable) + #expect(store.commitAccepted(messageID: messageID, storedURL: original)) + try FileManager.default.removeItem(at: original) - // The unreadable bytes were preserved at the quarantine name. - let quarantined = quarantinedRecord(in: root) - #expect(!FileManager.default.fileExists(atPath: record.path)) - #expect(FileManager.default.fileExists(atPath: quarantined.path)) - #expect(try Data(contentsOf: quarantined) == corruptBytes) + #expect(store.state(for: messageID) == .absent) - // A relaunch stays fail-closed for this ID without ever re-reading - // the quarantined file. - let readURLs = ReadTracker() - let relaunched = BLEPrivateMediaReceiptStore( - baseDirectory: root, - dataReader: { url in - readURLs.append(url) - return try Data(contentsOf: url) - } - ) - #expect(relaunched.state(for: messageID) == .unavailable) - #expect(!readURLs.urls.contains { - $0.lastPathComponent == quarantined.lastPathComponent - }) + let restored = try makePayload(in: root, name: "second.jpg") + #expect(store.commitAccepted(messageID: messageID, storedURL: restored)) + #expect(store.state(for: messageID) == .accepted(restored)) } @Test - func corruptRecordDoesNotBlockAnotherSendersMedia() throws { - let root = makeRoot("quarantine-isolation") - defer { try? FileManager.default.removeItem(at: root) } - let otherMessageID = "media-ffeeddccbbaa99887766554433221100" - let corruptPayload = try makePayload(in: root, name: "corrupt.jpg") - let healthyPayload = try makePayload(in: root, name: "healthy.jpg") - - let seed = BLEPrivateMediaReceiptStore(baseDirectory: root) - #expect(seed.commitAccepted( - messageID: messageID, - storedURL: corruptPayload - )) - #expect(seed.commitAccepted( - messageID: otherMessageID, - storedURL: healthyPayload - )) - try Data("{not-json".utf8).write( - to: receiptRecord(in: root), - options: .atomic - ) - - let store = BLEPrivateMediaReceiptStore(baseDirectory: root) - // Only the damaged record fails closed; the other sender's ledger - // entry keeps serving and new decisions still commit durably. - #expect(store.state(for: messageID) == .unavailable) - #expect(store.state(for: otherMessageID) == .accepted(healthyPayload)) - - let freshMessageID = "media-0102030405060708090a0b0c0d0e0f10" - let freshPayload = try makePayload(in: root, name: "fresh.jpg") - #expect(store.commitAccepted( - messageID: freshMessageID, - storedURL: freshPayload - )) - #expect(store.state(for: freshMessageID) == .accepted(freshPayload)) - } - - @Test - func unreadableTombstoneNeverBecomesAbsentOrGetsDeleted() throws { - let root = makeRoot("tombstone-decode") + func corruptLedgerFailsClosedWithoutDeletingOrOverwriting() throws { + let root = makeRoot("corrupt-ledger") defer { try? FileManager.default.removeItem(at: root) } let payload = try makePayload(in: root) let seed = BLEPrivateMediaReceiptStore(baseDirectory: root) #expect(seed.commitAccepted(messageID: messageID, storedURL: payload)) - #expect(seed.recordDeleted(messageID: messageID)) - #expect(!FileManager.default.fileExists(atPath: payload.path)) - let record = receiptRecord(in: root) - let corruptBytes = Data([0xFF, 0x00, 0x7B]) - try corruptBytes.write(to: record, options: .atomic) + let ledger = ledgerURL(in: root) + let corruptBytes = Data("{not-json".utf8) + try corruptBytes.write(to: ledger, options: .atomic) let relaunched = BLEPrivateMediaReceiptStore(baseDirectory: root) #expect(relaunched.state(for: messageID) == .unavailable) - // The quarantined tombstone can never flip to absent — a sender retry - // must not resurrect explicitly deleted media even when the payload - // bytes arrive again. - try Data([0xFF, 0xD8, 0xFF, 0xD9]).write(to: payload) - #expect(!relaunched.commitAccepted( - messageID: messageID, - storedURL: payload - )) - let quarantined = quarantinedRecord(in: root) - #expect(FileManager.default.fileExists(atPath: quarantined.path)) - #expect(try Data(contentsOf: quarantined) == corruptBytes) - #expect( - BLEPrivateMediaReceiptStore(baseDirectory: root) - .state(for: messageID) == .unavailable - ) + #expect(!relaunched.commitAccepted(messageID: messageID, storedURL: payload)) + #expect(!relaunched.recordDeleted(messageID: messageID)) + #expect(relaunched.isPayloadOwned(relativePath: "images/incoming/image.jpg") == nil) + #expect(FileManager.default.fileExists(atPath: payload.path)) + #expect(try Data(contentsOf: ledger) == corruptBytes) } @Test - func deletionBatchCommitsEveryIDBeforeRemovingPayloads() throws { + func transientReadFailureRecoversOnSubsequentLookup() throws { + let root = makeRoot("transient-read-failure") + defer { try? FileManager.default.removeItem(at: root) } + let payload = try makePayload(in: root) + #expect(BLEPrivateMediaReceiptStore(baseDirectory: root).commitAccepted( + messageID: messageID, + storedURL: payload + )) + + var shouldFail = true + let store = BLEPrivateMediaReceiptStore( + baseDirectory: root, + dataReader: { url in + if shouldFail { + shouldFail = false + throw TestError() + } + return try Data(contentsOf: url) + } + ) + + #expect(store.state(for: messageID) == .unavailable) + #expect(store.state(for: messageID) == .accepted(payload)) + } + + @Test + func deletionBatchCommitsAtomicallyBeforeRemovingPayloads() throws { let root = makeRoot("batch") defer { try? FileManager.default.removeItem(at: root) } let firstPayload = try makePayload(in: root, name: "first.jpg") let secondPayload = try makePayload(in: root, name: "second.jpg") let store = BLEPrivateMediaReceiptStore(baseDirectory: root) - #expect(store.commitAccepted( - messageID: messageID, - storedURL: firstPayload - )) - #expect(store.commitAccepted( - messageID: secondMessageID, - storedURL: secondPayload - )) + #expect(store.commitAccepted(messageID: messageID, storedURL: firstPayload)) + #expect(store.commitAccepted(messageID: secondMessageID, storedURL: secondPayload)) - #expect(store.recordDeleted( - messageIDs: [secondMessageID, messageID] - )) + #expect(store.recordDeleted(messageIDs: [secondMessageID, messageID])) #expect(store.state(for: messageID) == .tombstoned) #expect(store.state(for: secondMessageID) == .tombstoned) #expect(!FileManager.default.fileExists(atPath: firstPayload.path)) #expect(!FileManager.default.fileExists(atPath: secondPayload.path)) - #expect(!FileManager.default.fileExists( - atPath: deletionJournal(in: root).path - )) - } - - @Test - func failedJournalCommitPreservesAcceptedStateAndPayloads() throws { - let root = makeRoot("journal-failure") - defer { try? FileManager.default.removeItem(at: root) } - let firstPayload = try makePayload(in: root, name: "first.jpg") - let secondPayload = try makePayload(in: root, name: "second.jpg") - let seed = BLEPrivateMediaReceiptStore(baseDirectory: root) - #expect(seed.commitAccepted( - messageID: messageID, - storedURL: firstPayload - )) - #expect(seed.commitAccepted( - messageID: secondMessageID, - storedURL: secondPayload - )) - - let failing = BLEPrivateMediaReceiptStore( - baseDirectory: root, - dataWriter: { _, _, _ in throw TestError() } - ) - #expect(!failing.recordDeleted( - messageIDs: [messageID, secondMessageID] - )) - - // A failed commit must not install a volatile tombstone. Otherwise a - // sender retry could be ACKed although the caller kept both bubbles. - #expect(failing.state(for: messageID) == .accepted(firstPayload)) - #expect( - failing.state(for: secondMessageID) == .accepted(secondPayload) - ) - #expect(FileManager.default.fileExists(atPath: firstPayload.path)) - #expect(FileManager.default.fileExists(atPath: secondPayload.path)) - #expect(!FileManager.default.fileExists( - atPath: deletionJournal(in: root).path - )) - } - - @Test - func journalRecoversBatchAfterCrashDuringMaterialization() throws { - let root = makeRoot("crash-recovery") - defer { try? FileManager.default.removeItem(at: root) } - let firstPayload = try makePayload(in: root, name: "first.jpg") - let secondPayload = try makePayload(in: root, name: "second.jpg") - let seed = BLEPrivateMediaReceiptStore(baseDirectory: root) - #expect(seed.commitAccepted( - messageID: messageID, - storedURL: firstPayload - )) - #expect(seed.commitAccepted( - messageID: secondMessageID, - storedURL: secondPayload - )) - - let interrupted = BLEPrivateMediaReceiptStore( - baseDirectory: root, - dataWriter: { data, url, options in - let isJournal = - url.lastPathComponent == ".deletion-journal.json" - let isFirstRecord = - url.deletingPathExtension().lastPathComponent == messageID - guard isJournal || isFirstRecord else { - throw TestError() - } - try data.write(to: url, options: options) - } - ) - #expect(interrupted.recordDeleted( - messageIDs: [messageID, secondMessageID] - )) - #expect(FileManager.default.fileExists( - atPath: deletionJournal(in: root).path - )) - #expect(!FileManager.default.fileExists(atPath: firstPayload.path)) - #expect(FileManager.default.fileExists(atPath: secondPayload.path)) - #expect(interrupted.state(for: messageID) == .tombstoned) - #expect(interrupted.state(for: secondMessageID) == .tombstoned) let relaunched = BLEPrivateMediaReceiptStore(baseDirectory: root) #expect(relaunched.state(for: messageID) == .tombstoned) #expect(relaunched.state(for: secondMessageID) == .tombstoned) - #expect(!FileManager.default.fileExists(atPath: firstPayload.path)) - #expect(!FileManager.default.fileExists(atPath: secondPayload.path)) - #expect(!FileManager.default.fileExists( - atPath: deletionJournal(in: root).path - )) } @Test - func journalRetriesPayloadUnlinkAfterRelaunch() throws { - let root = makeRoot("unlink-recovery") + func failedLedgerWriteLeavesAcceptedStateAndPayloadIntact() throws { + let root = makeRoot("failed-delete-write") defer { try? FileManager.default.removeItem(at: root) } let payload = try makePayload(in: root) - let seed = BLEPrivateMediaReceiptStore(baseDirectory: root) - #expect(seed.commitAccepted( + #expect(BLEPrivateMediaReceiptStore(baseDirectory: root).commitAccepted( messageID: messageID, storedURL: payload )) - let unlinkFailure = BLEPrivateMediaReceiptStore( + let failingStore = BLEPrivateMediaReceiptStore( + baseDirectory: root, + dataWriter: { _, _, _ in throw TestError() } + ) + + #expect(!failingStore.recordDeleted(messageID: messageID)) + #expect(failingStore.state(for: messageID) == .accepted(payload)) + #expect(FileManager.default.fileExists(atPath: payload.path)) + } + + @Test + func failedPayloadUnlinkCommitsTombstoneAndRetriesOnNextLookup() throws { + let root = makeRoot("unlink-retry") + defer { try? FileManager.default.removeItem(at: root) } + let payload = try makePayload(in: root) + #expect(BLEPrivateMediaReceiptStore(baseDirectory: root).commitAccepted( + messageID: messageID, + storedURL: payload + )) + + let failingUnlink = BLEPrivateMediaReceiptStore( baseDirectory: root, payloadRemover: { _ in throw TestError() } ) - #expect(unlinkFailure.recordDeleted(messageID: messageID)) - #expect(unlinkFailure.state(for: messageID) == .tombstoned) + #expect(failingUnlink.recordDeleted(messageID: messageID)) + #expect(failingUnlink.state(for: messageID) == .tombstoned) #expect(FileManager.default.fileExists(atPath: payload.path)) - #expect(FileManager.default.fileExists( - atPath: deletionJournal(in: root).path - )) - let relaunched = BLEPrivateMediaReceiptStore(baseDirectory: root) - #expect(relaunched.state(for: messageID) == .tombstoned) + // On relaunch with a working remover, pendingUnlinkPaths finishes cleanup. + let recovered = BLEPrivateMediaReceiptStore(baseDirectory: root) + #expect(recovered.state(for: messageID) == .tombstoned) #expect(!FileManager.default.fileExists(atPath: payload.path)) - #expect(!FileManager.default.fileExists( - atPath: deletionJournal(in: root).path - )) - } - - @Test - func expiredReceiptUsesFallbackPathForCrashSafeCleanup() throws { - let root = makeRoot("expired-fallback") - defer { try? FileManager.default.removeItem(at: root) } - let payload = try makePayload(in: root) - let recordedAt = Date(timeIntervalSince1970: 1_000) - let seed = BLEPrivateMediaReceiptStore( - baseDirectory: root, - ttl: 10, - now: { recordedAt } - ) - #expect(seed.commitAccepted( - messageID: messageID, - storedURL: payload - )) - // Simulate a receipt pruned by an older app version while its bubble - // and payload remain. Current code retains live accepted-path owners. - try FileManager.default.removeItem(at: receiptRecord(in: root)) - - let afterExpiry = recordedAt.addingTimeInterval(11) - let interrupted = BLEPrivateMediaReceiptStore( - baseDirectory: root, - ttl: 10, - now: { afterExpiry }, - payloadRemover: { _ in throw TestError() } - ) - #expect(interrupted.recordDeleted( - messageIDs: [messageID], - payloadRelativePaths: [ - messageID: "images/incoming/image.jpg" - ] - )) - #expect(interrupted.state(for: messageID) == .tombstoned) - #expect(FileManager.default.fileExists(atPath: payload.path)) - #expect(FileManager.default.fileExists( - atPath: deletionJournal(in: root).path - )) - - let relaunched = BLEPrivateMediaReceiptStore( - baseDirectory: root, - ttl: 10, - now: { afterExpiry } - ) - #expect(relaunched.state(for: messageID) == .tombstoned) - #expect(!FileManager.default.fileExists(atPath: payload.path)) - #expect(!FileManager.default.fileExists( - atPath: deletionJournal(in: root).path - )) - } - - @Test - func retryAtSuffixedPathDeletesReceiptAndBubblePayloads() throws { - let root = makeRoot("retry-suffix") - defer { try? FileManager.default.removeItem(at: root) } - let original = try makePayload(in: root) - let seed = BLEPrivateMediaReceiptStore(baseDirectory: root) - #expect(seed.commitAccepted( - messageID: messageID, - storedURL: original - )) - - // Simulate an older build pruning only the receipt. A retry must use a - // suffixed filename while the old bubble still references image.jpg. - try FileManager.default.removeItem(at: receiptRecord(in: root)) - let retry = try makePayload(in: root, name: "image (1).jpg") - let retried = BLEPrivateMediaReceiptStore(baseDirectory: root) - #expect(retried.commitAccepted( - messageID: messageID, - storedURL: retry - )) - - #expect(retried.recordDeleted( - messageIDs: [messageID], - payloadRelativePaths: [ - messageID: "images/incoming/image.jpg" - ] - )) - #expect(retried.state(for: messageID) == .tombstoned) - #expect(!FileManager.default.fileExists(atPath: original.path)) - #expect(!FileManager.default.fileExists(atPath: retry.path)) - #expect(!FileManager.default.fileExists( - atPath: deletionJournal(in: root).path - )) - - let relaunched = BLEPrivateMediaReceiptStore(baseDirectory: root) - #expect(relaunched.state(for: messageID) == .tombstoned) - #expect(!FileManager.default.fileExists(atPath: original.path)) - #expect(!FileManager.default.fileExists(atPath: retry.path)) - } - - @Test - func protectedUIPathRejectsAcceptedReceiptDeletion() throws { - let root = makeRoot("protected-ui-owner") - defer { try? FileManager.default.removeItem(at: root) } - let payload = try makePayload(in: root) - let store = BLEPrivateMediaReceiptStore(baseDirectory: root) - #expect(store.commitAccepted( - messageID: messageID, - storedURL: payload - )) - - #expect(!store.recordDeleted( - messageIDs: [messageID], - protectedPayloadRelativePaths: [ - "images/incoming/image.jpg" - ] - )) - #expect(store.state(for: messageID) == .accepted(payload)) - #expect(FileManager.default.fileExists(atPath: payload.path)) } @Test @@ -689,201 +245,126 @@ struct BLEPrivateMediaReceiptStoreTests { #expect(!store.recordDeleted(messageID: messageID)) #expect(store.state(for: messageID) == .absent) - #expect(!FileManager.default.fileExists( - atPath: deletionJournal(in: root).path - )) } @Test - func completedTombstoneNeverDeletesReusedPayloadPath() throws { - let root = makeRoot("path-reuse") + func deletionNeverRemovesDirectoryOrOutgoingTarget() throws { + let root = makeRoot("safe-targets") defer { try? FileManager.default.removeItem(at: root) } - let original = try makePayload(in: root) - let store = BLEPrivateMediaReceiptStore(baseDirectory: root) - #expect(store.commitAccepted( - messageID: messageID, - storedURL: original - )) - #expect(store.recordDeleted(messageID: messageID)) - #expect(!FileManager.default.fileExists(atPath: original.path)) - - let reused = try makePayload(in: root) - #expect(store.commitAccepted( - messageID: secondMessageID, - storedURL: reused - )) - #expect(store.state(for: messageID) == .tombstoned) - #expect(FileManager.default.fileExists(atPath: reused.path)) - - let relaunched = BLEPrivateMediaReceiptStore(baseDirectory: root) - #expect(relaunched.state(for: messageID) == .tombstoned) - #expect(FileManager.default.fileExists(atPath: reused.path)) - #expect( - relaunched.state(for: secondMessageID) == .accepted(reused) - ) - } - - @Test - func expiredLegacyPathfulTombstoneDoesNotDeleteAcceptedOwner() throws { - let root = makeRoot("legacy-path-conflict") - defer { try? FileManager.default.removeItem(at: root) } - let payload = try makePayload(in: root) - let receiptDirectory = receiptRecord(in: root) - .deletingLastPathComponent() - try FileManager.default.createDirectory( - at: receiptDirectory, - withIntermediateDirectories: true - ) - let recordedAt = Date(timeIntervalSince1970: 3_000) - try JSONEncoder().encode(ReceiptFixture( - kind: "tombstone", - relativePath: "images/incoming/image.jpg", - recordedAt: recordedAt - )).write( - to: receiptRecord(in: root), - options: .atomic - ) - try JSONEncoder().encode(ReceiptFixture( - kind: "accepted", - relativePath: "images/incoming/image.jpg", - recordedAt: recordedAt - )).write( - to: receiptRecord( - in: root, - messageID: secondMessageID - ), - options: .atomic - ) - - let store = BLEPrivateMediaReceiptStore( - baseDirectory: root, - ttl: 1, - now: { recordedAt.addingTimeInterval(2) } - ) - #expect(store.state(for: messageID) == .absent) - #expect(FileManager.default.fileExists(atPath: payload.path)) - #expect( - store.state(for: secondMessageID) == .accepted(payload) - ) - #expect(FileManager.default.fileExists(atPath: payload.path)) - } - - @Test - func expiredLegacyPathfulTombstonePreservesAmbiguousPayload() throws { - let root = makeRoot("legacy-expired-cleanup") - defer { try? FileManager.default.removeItem(at: root) } - let payload = try makePayload(in: root) - let receiptURL = receiptRecord(in: root) - try FileManager.default.createDirectory( - at: receiptURL.deletingLastPathComponent(), - withIntermediateDirectories: true - ) - let recordedAt = Date(timeIntervalSince1970: 3_000) - try JSONEncoder().encode(ReceiptFixture( - kind: "tombstone", - relativePath: "images/incoming/image.jpg", - recordedAt: recordedAt - )).write(to: receiptURL, options: .atomic) - - let store = BLEPrivateMediaReceiptStore( - baseDirectory: root, - ttl: 1, - now: { recordedAt.addingTimeInterval(2) } - ) - - #expect(store.state(for: messageID) == .absent) - #expect(FileManager.default.fileExists(atPath: payload.path)) - #expect(!FileManager.default.fileExists(atPath: receiptURL.path)) - } - - @Test - func deletionJournalNeverRecursivelyRemovesDirectoryTarget() throws { - let root = makeRoot("journal-directory") - defer { try? FileManager.default.removeItem(at: root) } - let directory = root.appendingPathComponent( - "files/images/incoming/archive", - isDirectory: true - ) - try FileManager.default.createDirectory( - at: directory, - withIntermediateDirectories: true - ) + let directory = root.appendingPathComponent("files/images/incoming/archive", isDirectory: true) + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) let child = directory.appendingPathComponent("child.jpg") try Data([0x01]).write(to: child) - let receiptDirectory = receiptRecord(in: root) - .deletingLastPathComponent() - try FileManager.default.createDirectory( - at: receiptDirectory, - withIntermediateDirectories: true - ) - #expect(!BLEPrivateMediaReceiptStore( - baseDirectory: root - ).recordDeleted( - messageIDs: [messageID], - payloadRelativePaths: [ - messageID: "images/incoming/archive" - ] - )) - #expect(!FileManager.default.fileExists( - atPath: deletionJournal(in: root).path - )) - try JSONEncoder().encode(JournalFixture( - version: 1, - entries: [messageID: JournalEntryFixture( - relativePaths: ["images/incoming/archive"], - recordedAt: Date() - )] - )).write(to: deletionJournal(in: root), options: .atomic) + + let outgoingDir = root.appendingPathComponent("files/images/outgoing", isDirectory: true) + try FileManager.default.createDirectory(at: outgoingDir, withIntermediateDirectories: true) + let outgoing = outgoingDir.appendingPathComponent("victim.jpg") + try Data([0x02]).write(to: outgoing) let store = BLEPrivateMediaReceiptStore(baseDirectory: root) - #expect(store.state(for: messageID) == .tombstoned) - #expect(FileManager.default.fileExists(atPath: directory.path)) - #expect(FileManager.default.fileExists(atPath: child.path)) - #expect(FileManager.default.fileExists( - atPath: deletionJournal(in: root).path + #expect(!store.recordDeleted( + messageIDs: [messageID], + payloadRelativePaths: [messageID: "images/incoming/archive"] )) + #expect(!store.recordDeleted( + messageIDs: [messageID], + payloadRelativePaths: [messageID: "images/outgoing/victim.jpg"] + )) + #expect(FileManager.default.fileExists(atPath: child.path)) + #expect(FileManager.default.fileExists(atPath: outgoing.path)) } @Test - func corruptDeletionJournalFailsClosedWithoutRemovingPayload() throws { - let root = makeRoot("corrupt-journal") + func migratesLegacyPerIDDirectoryJournalAndQuarantineOnceOnStartup() throws { + let root = makeRoot("legacy-migration") + defer { try? FileManager.default.removeItem(at: root) } + let thirdMessageID = "media-11223344556677889900aabbccddeeff" + let fourthMessageID = "media-aa11bb22cc33dd44ee55ff6600778899" + + let acceptedPayload = try makePayload(in: root, name: "accepted.jpg") + let journalPayload = try makePayload(in: root, name: "journal-delete.jpg") + let legacyPathfulPayload = try makePayload(in: root, name: "ambiguous.jpg") + + let legacyDir = legacyReceiptDirectory(in: root) + try FileManager.default.createDirectory(at: legacyDir, withIntermediateDirectories: true) + let now = Date(timeIntervalSince1970: 5_000) + + // 1. Valid accepted record. + try JSONEncoder().encode(LegacyReceiptFixture( + kind: "accepted", + relativePath: "images/incoming/accepted.jpg", + recordedAt: now + )).write(to: legacyDir.appendingPathComponent("\(messageID).json"), options: .atomic) + + // 2. Legacy pathful tombstone — must scrub path without unlinking ambiguous file. + try JSONEncoder().encode(LegacyReceiptFixture( + kind: "tombstone", + relativePath: "images/incoming/ambiguous.jpg", + recordedAt: now + )).write(to: legacyDir.appendingPathComponent("\(secondMessageID).json"), options: .atomic) + + // 3. Corrupt per-ID file — must be quarantined without breaking other records. + try Data("{corrupt".utf8).write( + to: legacyDir.appendingPathComponent("\(thirdMessageID).json"), + options: .atomic + ) + + // 4. Legacy deletion journal — must commit tombstone and unlink payload. + try JSONEncoder().encode(LegacyJournalFixture( + version: 1, + entries: [ + fourthMessageID: LegacyJournalEntryFixture( + relativePaths: ["images/incoming/journal-delete.jpg"], + recordedAt: now + ) + ] + )).write(to: legacyDir.appendingPathComponent(".deletion-journal.json"), options: .atomic) + + let store = BLEPrivateMediaReceiptStore(baseDirectory: root, now: { now }) + #expect(store.state(for: messageID) == .accepted(acceptedPayload)) + #expect(store.state(for: secondMessageID) == .tombstoned) + #expect(store.state(for: thirdMessageID) == .unavailable) + #expect(store.state(for: fourthMessageID) == .tombstoned) + + #expect(FileManager.default.fileExists(atPath: acceptedPayload.path)) + #expect(FileManager.default.fileExists(atPath: legacyPathfulPayload.path)) + #expect(!FileManager.default.fileExists(atPath: journalPayload.path)) + #expect(FileManager.default.fileExists(atPath: ledgerURL(in: root).path)) + #expect(!FileManager.default.fileExists(atPath: legacyDir.path)) + + // Quarantined ID stays fail-closed across relaunches. + let relaunched = BLEPrivateMediaReceiptStore(baseDirectory: root, now: { now }) + #expect(relaunched.state(for: thirdMessageID) == .unavailable) + #expect(!relaunched.commitAccepted(messageID: thirdMessageID, storedURL: acceptedPayload)) + } + + @Test + func corruptLegacyDeletionJournalFailsClosedWithoutDeletingLegacyDirectory() throws { + let root = makeRoot("corrupt-legacy-journal") defer { try? FileManager.default.removeItem(at: root) } let payload = try makePayload(in: root) - #expect(BLEPrivateMediaReceiptStore( - baseDirectory: root - ).commitAccepted( - messageID: messageID, - storedURL: payload - )) - let journal = deletionJournal(in: root) - try Data("{not-json".utf8).write(to: journal, options: .atomic) + let legacyDir = legacyReceiptDirectory(in: root) + try FileManager.default.createDirectory(at: legacyDir, withIntermediateDirectories: true) + try Data("{not-json".utf8).write( + to: legacyDir.appendingPathComponent(".deletion-journal.json"), + options: .atomic + ) - let relaunched = BLEPrivateMediaReceiptStore(baseDirectory: root) - #expect(relaunched.state(for: messageID) == .unavailable) - #expect(!relaunched.commitAccepted( - messageID: messageID, - storedURL: payload - )) + let store = BLEPrivateMediaReceiptStore(baseDirectory: root) + #expect(store.state(for: messageID) == .unavailable) #expect(FileManager.default.fileExists(atPath: payload.path)) - #expect(try Data(contentsOf: journal) == Data("{not-json".utf8)) + #expect(FileManager.default.fileExists(atPath: legacyDir.path)) } @Test func unreleasedAggregateLedgerIsIgnoredAndLeftUntouched() throws { - let root = makeRoot("no-legacy-migration") + let root = makeRoot("no-unreleased-migration") defer { try? FileManager.default.removeItem(at: root) } let files = root.appendingPathComponent("files", isDirectory: true) - try FileManager.default.createDirectory( - at: files, - withIntermediateDirectories: true - ) - let legacy = files.appendingPathComponent( - ".private-media-receipts.json", - isDirectory: false - ) + try FileManager.default.createDirectory(at: files, withIntermediateDirectories: true) + let legacy = files.appendingPathComponent(".private-media-receipts.json", isDirectory: false) let bytes = Data( - #"{"entries":{"media-00112233445566778899aabbccddeeff":{"relativePath":"images/incoming/old.jpg","acceptedAt":0}}}"# - .utf8 + #"{"entries":{"media-00112233445566778899aabbccddeeff":{"relativePath":"images/incoming/old.jpg","acceptedAt":0}}}"#.utf8 ) try bytes.write(to: legacy, options: .atomic) @@ -892,6 +373,8 @@ struct BLEPrivateMediaReceiptStoreTests { #expect(try Data(contentsOf: legacy) == bytes) } + // MARK: - Helpers + private func makeRoot(_ label: String) -> URL { FileManager.default.temporaryDirectory.appendingPathComponent( "private-media-receipt-\(label)-\(UUID().uuidString)", @@ -899,53 +382,21 @@ struct BLEPrivateMediaReceiptStoreTests { ) } - private func makePayload( - in root: URL, - name: String = "image.jpg" - ) throws -> URL { - let directory = root.appendingPathComponent( - "files/images/incoming", - isDirectory: true - ) - try FileManager.default.createDirectory( - at: directory, - withIntermediateDirectories: true - ) + private func makePayload(in root: URL, name: String = "image.jpg") throws -> URL { + let directory = root.appendingPathComponent("files/images/incoming", isDirectory: true) + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) let payload = directory.appendingPathComponent(name) try Data([0xFF, 0xD8, 0xFF, 0xD9]).write(to: payload) return payload } - private func receiptRecord( - in root: URL, - messageID requestedMessageID: String? = nil - ) -> URL { + private func ledgerURL(in root: URL) -> URL { root - .appendingPathComponent( - "files/.private-media-receipts", - isDirectory: true - ) - .appendingPathComponent(requestedMessageID ?? messageID) - .appendingPathExtension("json") + .appendingPathComponent("files", isDirectory: true) + .appendingPathComponent(BLEPrivateMediaReceiptStore.ledgerFileName, isDirectory: false) } - private func quarantinedRecord(in root: URL) -> URL { - receiptRecord(in: root).appendingPathExtension("corrupt") - } - - private func deletionJournal(in root: URL) -> URL { - root - .appendingPathComponent( - "files/.private-media-receipts", - isDirectory: true - ) - .appendingPathComponent(".deletion-journal.json") + private func legacyReceiptDirectory(in root: URL) -> URL { + root.appendingPathComponent("files/.private-media-receipts", isDirectory: true) } } - -/// Collects the URLs a store's data reader touched. A reference type so the -/// `@Sendable`-shaped reader closure can record without mutating captures. -private final class ReadTracker: @unchecked Sendable { - private(set) var urls: [URL] = [] - func append(_ url: URL) { urls.append(url) } -} diff --git a/bitchatTests/Services/BridgeServiceTests.swift b/bitchatTests/Services/BridgeServiceTests.swift index 24ffb54e..57d93b2a 100644 --- a/bitchatTests/Services/BridgeServiceTests.swift +++ b/bitchatTests/Services/BridgeServiceTests.swift @@ -897,4 +897,36 @@ struct BridgeServiceTests { #expect(fixture.broadcasts.isEmpty) } + + @Test func resetForPanicClearsNearbyOnlyAndRadioAliases() throws { + let fixture = Fixture(enabled: true) + fixture.service.refreshRendezvous() + fixture.service.nearbyOnly = true + + let radioHint = MeshMessageIdentity.stableID( + senderIDHex: "0011223344556677", + timestampMs: 1_700_000_000_000, + content: "bridged message" + ) + let event = try makeRemoteEvent( + content: "bridged message", + meshSenderID: "0011223344556677", + meshTimestampMs: 1_700_000_000_000 + ) + fixture.service.handleRendezvousEvent(event) + #expect(fixture.injected.count == 1) + + var removedIDs: [String] = [] + fixture.service.removeInjectedInbound = { removedIDs.append($0) } + + fixture.service.resetForPanic() + + #expect(!fixture.service.isEnabled) + #expect(!fixture.service.nearbyOnly) + + // Radio alias table was cleared by panic wipe, so a post-panic radio + // message with the old hint must not try to remove pre-panic rows. + fixture.service.handleAuthenticatedRadioMessage(messageID: radioHint) + #expect(removedIDs.isEmpty) + } } diff --git a/bitchatTests/Services/MediaRetentionTests.swift b/bitchatTests/Services/MediaRetentionTests.swift index 6c92af10..2af16abe 100644 --- a/bitchatTests/Services/MediaRetentionTests.swift +++ b/bitchatTests/Services/MediaRetentionTests.swift @@ -115,6 +115,31 @@ struct MediaRetentionTests { #expect(BLEIncomingFileStore.defaultMediaRetention == 7 * 24 * 60 * 60) } + @Test + func quotaEvictionSkipsFilesAwaitingUIDeliveryUntilFinalized() throws { + let root = makeRoot() + defer { try? FileManager.default.removeItem(at: root) } + let store = BLEIncomingFileStore(baseDirectory: root, quotaBytes: 12) + + let pending = try #require(store.save( + data: Data(repeating: 0xAA, count: 10), + preferredName: "first.jpg", + subdirectory: "images/incoming", + fallbackExtension: "jpg", + defaultPrefix: "img" + )) + store.beginPendingDelivery(at: pending) + + // Even under quota pressure from a second arrival, the pending file + // stays protected on disk until UI delivery finishes. + store.enforceQuota(reservingBytes: 10) + #expect(FileManager.default.fileExists(atPath: pending.path)) + + store.finishPendingDelivery(at: pending) + store.enforceQuota(reservingBytes: 10) + #expect(!FileManager.default.fileExists(atPath: pending.path)) + } + #if os(iOS) /// Media was the one persistence layer that never stated a protection /// class at its write site, so payloads inherited the container