mirror of
https://github.com/permissionlesstech/bitchat.git
synced 2026-07-25 17:45:19 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f0c8b4e2ea | ||
|
|
5ba6f32f61 | ||
|
|
43c7fc52ba |
+3
-3
@@ -17,8 +17,8 @@ bitchat is designed for private, account-free communication. This policy describ
|
||||
|
||||
1. **Identity and cryptographic keys**
|
||||
- Noise, signing, group, prekey, and optional Nostr identity material is generated locally.
|
||||
- Secret keys are stored in the system keychain. Public keys are shared when required for messaging, verification, groups, or Nostr events.
|
||||
- Keys remain until they are rotated, removed by the relevant feature, erased with panic wipe, or removed with the app.
|
||||
- Secret keys are stored in the system keychain as device-only items. Public keys are shared when required for messaging, verification, groups, or Nostr events.
|
||||
- Keys remain until they are rotated, removed by the relevant feature, or erased with panic wipe. Because operating-system keychains can outlive an uninstall, bitchat records a non-secret install marker and deletes surviving app keys before use after a later reinstall.
|
||||
|
||||
2. **Nickname, preferences, and relationships**
|
||||
- Your nickname, settings, favorites, petnames, read-receipt identifiers, and bounded operational metadata are stored locally.
|
||||
@@ -121,7 +121,7 @@ No cryptographic system can protect content after a recipient reads, copies, scr
|
||||
|
||||
## Your Controls
|
||||
|
||||
- **Panic wipe:** Triple-tap the logo to clear local keys, sessions, preferences, groups, queues, carried mail, public archives, board data, and media managed by the app.
|
||||
- **Panic wipe:** Triple-tap the logo to synchronously cancel in-flight media work and clear local keys, sessions, preferences, groups, queues, carried mail, public archives, board data, and media managed by the app.
|
||||
- **Feature controls:** Location channels, mesh bridge, internet gateway, and related internet behaviors can be disabled in the app. Some already-published relay data cannot be recalled.
|
||||
- **System permissions:** Bluetooth, location, microphone, camera, and photo-library access can be revoked in system settings.
|
||||
- **No account:** The project operates no account record for you to request or export.
|
||||
|
||||
@@ -21,6 +21,9 @@ final class AppChromeModel: ObservableObject {
|
||||
|
||||
private let chatViewModel: ChatViewModel
|
||||
private var cancellables = Set<AnyCancellable>()
|
||||
/// The composer owns capture state above ChatViewModel. ContentView
|
||||
/// installs this hook so both panic entry points synchronously stop it.
|
||||
private var prepareForPanic: (@MainActor () -> Void)?
|
||||
|
||||
/// Bulletin-board coordinator, created on first use of the board sheet.
|
||||
private(set) lazy var boardManager = BoardManager(transport: chatViewModel.meshService)
|
||||
@@ -97,7 +100,12 @@ final class AppChromeModel: ObservableObject {
|
||||
showScreenshotPrivacyWarning = true
|
||||
}
|
||||
|
||||
func setPanicPreparation(_ preparation: (@MainActor () -> Void)?) {
|
||||
prepareForPanic = preparation
|
||||
}
|
||||
|
||||
func panicClearAllData() {
|
||||
prepareForPanic?()
|
||||
chatViewModel.panicClearAllData()
|
||||
}
|
||||
|
||||
|
||||
@@ -107,12 +107,15 @@ final class AppRuntime: ObservableObject {
|
||||
)
|
||||
)
|
||||
|
||||
if chatViewModel.networkActivationAllowed {
|
||||
GeoRelayDirectory.shared.prefetchIfNeeded()
|
||||
}
|
||||
bindRuntimeObservers()
|
||||
NotificationDelegate.shared.runtime = self
|
||||
}
|
||||
|
||||
func start() {
|
||||
guard chatViewModel.networkActivationAllowed else { return }
|
||||
guard !started else {
|
||||
checkForSharedContent()
|
||||
return
|
||||
@@ -151,12 +154,14 @@ final class AppRuntime: ObservableObject {
|
||||
}
|
||||
|
||||
func handleDidBecomeActiveNotification() {
|
||||
guard chatViewModel.networkActivationAllowed else { return }
|
||||
chatViewModel.handleDidBecomeActive()
|
||||
checkForSharedContent()
|
||||
}
|
||||
|
||||
#if os(macOS)
|
||||
func handleMacDidBecomeActiveNotification() {
|
||||
guard chatViewModel.networkActivationAllowed else { return }
|
||||
record(.scenePhaseChanged(.active))
|
||||
chatViewModel.handleDidBecomeActive()
|
||||
checkForSharedContent()
|
||||
@@ -175,6 +180,7 @@ final class AppRuntime: ObservableObject {
|
||||
didEnterBackground = true
|
||||
|
||||
case .active:
|
||||
guard chatViewModel.networkActivationAllowed else { return }
|
||||
record(.scenePhaseChanged(.active))
|
||||
chatViewModel.meshService.startServices()
|
||||
TorManager.shared.setAppForeground(true)
|
||||
@@ -222,6 +228,7 @@ final class AppRuntime: ObservableObject {
|
||||
actionIdentifier: String = UNNotificationDefaultActionIdentifier,
|
||||
userInfo: [AnyHashable: Any]
|
||||
) {
|
||||
guard chatViewModel.networkActivationAllowed else { return }
|
||||
if actionIdentifier == NotificationService.waveActionID {
|
||||
chatViewModel.sendMeshWave()
|
||||
return
|
||||
@@ -273,6 +280,8 @@ private extension AppRuntime {
|
||||
NotificationCenter.default.publisher(for: .TorWillRestart)
|
||||
.receive(on: DispatchQueue.main)
|
||||
.sink { [weak self] _ in
|
||||
guard self?.chatViewModel.networkActivationAllowed == true
|
||||
else { return }
|
||||
self?.record(.torLifecycleChanged(.willRestart))
|
||||
self?.chatViewModel.handleTorWillRestart()
|
||||
}
|
||||
@@ -281,6 +290,8 @@ private extension AppRuntime {
|
||||
NotificationCenter.default.publisher(for: .TorDidBecomeReady)
|
||||
.receive(on: DispatchQueue.main)
|
||||
.sink { [weak self] _ in
|
||||
guard self?.chatViewModel.networkActivationAllowed == true
|
||||
else { return }
|
||||
self?.record(.torLifecycleChanged(.didBecomeReady))
|
||||
self?.chatViewModel.handleTorDidBecomeReady()
|
||||
}
|
||||
@@ -289,6 +300,8 @@ private extension AppRuntime {
|
||||
NotificationCenter.default.publisher(for: .TorWillStart)
|
||||
.receive(on: DispatchQueue.main)
|
||||
.sink { [weak self] _ in
|
||||
guard self?.chatViewModel.networkActivationAllowed == true
|
||||
else { return }
|
||||
self?.record(.torLifecycleChanged(.willStart))
|
||||
self?.chatViewModel.handleTorWillStart()
|
||||
}
|
||||
@@ -297,6 +310,8 @@ private extension AppRuntime {
|
||||
NotificationCenter.default.publisher(for: .TorUserPreferenceChanged)
|
||||
.receive(on: DispatchQueue.main)
|
||||
.sink { [weak self] notification in
|
||||
guard self?.chatViewModel.networkActivationAllowed == true
|
||||
else { return }
|
||||
self?.record(.torLifecycleChanged(.preferenceChanged))
|
||||
self?.chatViewModel.handleTorPreferenceChanged(notification)
|
||||
}
|
||||
@@ -313,6 +328,7 @@ private extension AppRuntime {
|
||||
}
|
||||
|
||||
func checkForSharedContent() {
|
||||
guard chatViewModel.networkActivationAllowed else { return }
|
||||
guard let userDefaults = UserDefaults(suiteName: BitchatApp.groupID) else { return }
|
||||
let clearSharedContent = {
|
||||
userDefaults.removeObject(forKey: "sharedContent")
|
||||
@@ -359,7 +375,9 @@ private extension AppRuntime {
|
||||
let becameConnected = isConnected && !lastNostrRelayConnectedState
|
||||
lastNostrRelayConnectedState = isConnected
|
||||
|
||||
guard started, becameConnected else { return }
|
||||
guard chatViewModel.networkActivationAllowed,
|
||||
started,
|
||||
becameConnected else { return }
|
||||
|
||||
let isInitialConnection = !didHandleInitialNostrConnection
|
||||
didHandleInitialNostrConnection = true
|
||||
|
||||
@@ -26,6 +26,8 @@ protocol VoiceCaptureSession: AnyObject {
|
||||
/// nothing valid was captured.
|
||||
func finish() async -> URL?
|
||||
func cancel() async
|
||||
/// Stops capture and suppresses every later send before returning.
|
||||
func panicCancelSynchronously()
|
||||
}
|
||||
|
||||
/// The classic record-then-send backend, wrapping the shared `VoiceRecorder`.
|
||||
@@ -55,6 +57,10 @@ final class VoiceNoteCaptureSession: VoiceCaptureSession {
|
||||
func cancel() async {
|
||||
await recorder.cancelRecording(owner: owner)
|
||||
}
|
||||
|
||||
func panicCancelSynchronously() {
|
||||
recorder.panicCancelSynchronously(owner: owner)
|
||||
}
|
||||
}
|
||||
|
||||
/// Testable surface of the live capture engine. Production uses
|
||||
@@ -216,6 +222,13 @@ final class PTTLiveVoiceSession: VoiceCaptureSession {
|
||||
}
|
||||
}
|
||||
|
||||
func panicCancelSynchronously() {
|
||||
// Do not emit a canceled packet: it would itself be pre-panic
|
||||
// conversation data racing the emergency transport reset.
|
||||
completed = true
|
||||
capture.cancel()
|
||||
}
|
||||
|
||||
private func sendControlPacket(_ kind: VoiceBurstPacket.Kind) {
|
||||
guard let packet = VoiceBurstPacket(burstID: burstID, seq: stream.packetizer.nextSeq, kind: kind) else { return }
|
||||
sendPacket(packet.encode())
|
||||
|
||||
@@ -246,6 +246,21 @@ actor VoiceRecorder {
|
||||
currentURL = nil
|
||||
}
|
||||
|
||||
/// Panic is a synchronous security boundary: the caller must know the
|
||||
/// microphone, audio-session lease, and partial file are gone before it
|
||||
/// rotates identities or deletes the media tree. VoiceRecorder is an
|
||||
/// independent actor and this cleanup path never hops to MainActor, so a
|
||||
/// short semaphore join is safe even when invoked by the UI actor.
|
||||
nonisolated
|
||||
func panicCancelSynchronously(owner: RecordingOwner) {
|
||||
let finished = DispatchSemaphore(value: 0)
|
||||
Task {
|
||||
await cancelRecording(owner: owner)
|
||||
finished.signal()
|
||||
}
|
||||
finished.wait()
|
||||
}
|
||||
|
||||
/// The audio session was interrupted (call, Siri) or reconfigured: stop
|
||||
/// the recorder but keep `recorder`/`currentURL` so the caller's pending
|
||||
/// `stopRecording()` still returns the partial note.
|
||||
|
||||
@@ -15,9 +15,6 @@ enum NoiseSecurityConstants {
|
||||
// Maximum handshake message size
|
||||
static let maxHandshakeMessageSize = 2048 // 2KB to accommodate XX pattern
|
||||
|
||||
// Noise XX message 1 contains only the initiator's 32-byte ephemeral key.
|
||||
static let xxInitialMessageSize = 32
|
||||
|
||||
// Session timeout - sessions older than this should be renegotiated
|
||||
static let sessionTimeout: TimeInterval = 86400 // 24 hours
|
||||
|
||||
|
||||
@@ -11,5 +11,4 @@ enum NoiseSessionError: Error, Equatable {
|
||||
case notEstablished
|
||||
case sessionNotFound
|
||||
case alreadyEstablished
|
||||
case peerIdentityMismatch
|
||||
}
|
||||
|
||||
@@ -13,11 +13,6 @@ import BitFoundation
|
||||
|
||||
final class NoiseSessionManager {
|
||||
private var sessions: [PeerID: NoiseSession] = [:]
|
||||
/// A responder rehandshake must not evict a working transport session
|
||||
/// before the candidate proves that its authenticated static key belongs
|
||||
/// to the claimed wire ID. Candidates therefore live outside `sessions`
|
||||
/// until the XX handshake completes and the binding is validated.
|
||||
private var responderCandidates: [PeerID: NoiseSession] = [:]
|
||||
private let sessionFactory: (PeerID, NoiseRole) -> NoiseSession
|
||||
private let managerQueue = DispatchQueue(label: "chat.bitchat.noise.manager", attributes: .concurrent)
|
||||
|
||||
@@ -59,9 +54,6 @@ final class NoiseSessionManager {
|
||||
if let session = sessions.removeValue(forKey: peerID) {
|
||||
session.reset() // Clear sensitive data before removing
|
||||
}
|
||||
if let candidate = responderCandidates.removeValue(forKey: peerID) {
|
||||
candidate.reset()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -70,11 +62,7 @@ final class NoiseSessionManager {
|
||||
for (_, session) in sessions {
|
||||
session.reset()
|
||||
}
|
||||
for (_, candidate) in responderCandidates {
|
||||
candidate.reset()
|
||||
}
|
||||
sessions.removeAll()
|
||||
responderCandidates.removeAll()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -91,7 +79,6 @@ final class NoiseSessionManager {
|
||||
// Remove any existing non-established session
|
||||
if let existingSession = sessions[peerID], !existingSession.isEstablished() {
|
||||
_ = sessions.removeValue(forKey: peerID)
|
||||
existingSession.reset()
|
||||
}
|
||||
|
||||
// Create new initiator session
|
||||
@@ -104,7 +91,6 @@ final class NoiseSessionManager {
|
||||
} catch {
|
||||
// Clean up failed session
|
||||
_ = sessions.removeValue(forKey: peerID)
|
||||
session.reset()
|
||||
SecureLogger.error(.handshakeFailed(peerID: peerID.id, error: error.localizedDescription))
|
||||
throw error
|
||||
}
|
||||
@@ -114,50 +100,39 @@ final class NoiseSessionManager {
|
||||
func handleIncomingHandshake(from peerID: PeerID, message: Data) throws -> Data? {
|
||||
// Process everything within the synchronized block to prevent race conditions
|
||||
return try managerQueue.sync(flags: .barrier) {
|
||||
let session: NoiseSession
|
||||
let isReplacementCandidate: Bool
|
||||
var shouldCreateNew = false
|
||||
var existingSession: NoiseSession? = nil
|
||||
|
||||
if let candidate = responderCandidates[peerID] {
|
||||
// A fresh XX message 1 supersedes an incomplete candidate,
|
||||
// but never the established session it is trying to replace.
|
||||
if message.count == NoiseSecurityConstants.xxInitialMessageSize {
|
||||
candidate.reset()
|
||||
let replacement = sessionFactory(peerID, .responder)
|
||||
responderCandidates[peerID] = replacement
|
||||
session = replacement
|
||||
} else {
|
||||
session = candidate
|
||||
}
|
||||
isReplacementCandidate = true
|
||||
} else if let existing = sessions[peerID] {
|
||||
if let existing = sessions[peerID] {
|
||||
// If we have an established session, the peer must have cleared their session
|
||||
// for a good reason (e.g., decryption failure, restart, etc.)
|
||||
// We should accept the new handshake to re-establish encryption
|
||||
if existing.isEstablished() {
|
||||
SecureLogger.info(
|
||||
"Validating replacement handshake from \(peerID) while preserving the established session",
|
||||
category: .session
|
||||
)
|
||||
let candidate = sessionFactory(peerID, .responder)
|
||||
responderCandidates[peerID] = candidate
|
||||
session = candidate
|
||||
isReplacementCandidate = true
|
||||
} else if existing.getState() == .handshaking,
|
||||
message.count == NoiseSecurityConstants.xxInitialMessageSize {
|
||||
// No established transport state exists to preserve. A
|
||||
// fresh initiation replaces the incomplete handshake.
|
||||
SecureLogger.info("Accepting handshake from \(peerID) despite existing session - peer likely cleared their session", category: .session)
|
||||
_ = sessions.removeValue(forKey: peerID)
|
||||
existing.reset()
|
||||
let replacement = sessionFactory(peerID, .responder)
|
||||
sessions[peerID] = replacement
|
||||
session = replacement
|
||||
isReplacementCandidate = false
|
||||
shouldCreateNew = true
|
||||
} else {
|
||||
session = existing
|
||||
isReplacementCandidate = false
|
||||
// If we're in the middle of a handshake and receive a new initiation,
|
||||
// reset and start fresh (the other side may have restarted)
|
||||
if existing.getState() == .handshaking && message.count == 32 {
|
||||
_ = sessions.removeValue(forKey: peerID)
|
||||
shouldCreateNew = true
|
||||
} else {
|
||||
existingSession = existing
|
||||
}
|
||||
}
|
||||
} else {
|
||||
shouldCreateNew = true
|
||||
}
|
||||
|
||||
// Get or create session
|
||||
let session: NoiseSession
|
||||
if shouldCreateNew {
|
||||
let newSession = sessionFactory(peerID, .responder)
|
||||
sessions[peerID] = newSession
|
||||
session = newSession
|
||||
isReplacementCandidate = false
|
||||
} else {
|
||||
session = existingSession!
|
||||
}
|
||||
|
||||
// Process the handshake message within the synchronized block
|
||||
@@ -166,40 +141,18 @@ final class NoiseSessionManager {
|
||||
|
||||
// Check if session is established after processing
|
||||
if session.isEstablished() {
|
||||
guard let remoteKey = session.getRemoteStaticPublicKey(),
|
||||
authenticatedRemoteKey(remoteKey, matches: peerID) else {
|
||||
throw NoiseSessionError.peerIdentityMismatch
|
||||
}
|
||||
|
||||
if isReplacementCandidate {
|
||||
_ = responderCandidates.removeValue(forKey: peerID)
|
||||
let previous = sessions.updateValue(session, forKey: peerID)
|
||||
if let previous, previous !== session {
|
||||
previous.reset()
|
||||
}
|
||||
}
|
||||
|
||||
if let remoteKey = session.getRemoteStaticPublicKey() {
|
||||
// Schedule callback outside the synchronized block to prevent deadlock
|
||||
DispatchQueue.global().async { [weak self] in
|
||||
self?.onSessionEstablished?(peerID, remoteKey)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return response
|
||||
} catch {
|
||||
// A failed candidate is discarded without touching the
|
||||
// established session. Ordinary failed handshakes retain the
|
||||
// historical cleanup behavior.
|
||||
if isReplacementCandidate {
|
||||
if let storedCandidate = responderCandidates[peerID],
|
||||
storedCandidate === session {
|
||||
_ = responderCandidates.removeValue(forKey: peerID)
|
||||
}
|
||||
} else if let storedSession = sessions[peerID],
|
||||
storedSession === session {
|
||||
// Reset the session on handshake failure so next attempt can start fresh
|
||||
_ = sessions.removeValue(forKey: peerID)
|
||||
}
|
||||
session.reset()
|
||||
|
||||
// Schedule callback outside the synchronized block to prevent deadlock
|
||||
DispatchQueue.global().async { [weak self] in
|
||||
@@ -212,24 +165,6 @@ final class NoiseSessionManager {
|
||||
}
|
||||
}
|
||||
|
||||
/// Mesh handshakes normally use a 16-hex wire ID. Full Noise-key IDs are
|
||||
/// also accepted by internal callers when they exactly match the static
|
||||
/// key. Non-wire identifiers remain available to protocol test harnesses;
|
||||
/// BLE packet ingress always supplies a short hexadecimal ID.
|
||||
private func authenticatedRemoteKey(
|
||||
_ remoteKey: Curve25519.KeyAgreement.PublicKey,
|
||||
matches claimedPeerID: PeerID
|
||||
) -> Bool {
|
||||
let rawKey = remoteKey.rawRepresentation
|
||||
if claimedPeerID.isShort {
|
||||
return PeerID(publicKey: rawKey) == claimedPeerID
|
||||
}
|
||||
if let claimedNoiseKey = claimedPeerID.noiseKey {
|
||||
return claimedNoiseKey == rawKey
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// MARK: - Encryption/Decryption
|
||||
|
||||
func encrypt(_ plaintext: Data, for peerID: PeerID) throws -> Data {
|
||||
|
||||
@@ -2,8 +2,124 @@ import BitLogger
|
||||
import BitFoundation
|
||||
import Foundation
|
||||
|
||||
struct PanicRecoveryIntent {
|
||||
let fileMarkerEstablished: Bool
|
||||
let externalMarkerEstablished: Bool
|
||||
|
||||
var hasDurableMarker: Bool {
|
||||
fileMarkerEstablished || externalMarkerEstablished
|
||||
}
|
||||
}
|
||||
|
||||
/// Small, dependency-injectable transaction surface used by ChatViewModel.
|
||||
/// Production persists the same intent in two independent locations before
|
||||
/// any application state is erased. Tests can inject an ephemeral operation
|
||||
/// set without touching the developer's Application Support directory.
|
||||
struct PanicRecoveryOperations {
|
||||
let isPending: () throws -> Bool
|
||||
let begin: () -> PanicRecoveryIntent
|
||||
let wipeMedia: (PanicRecoveryIntent) throws -> Void
|
||||
let complete: () throws -> Void
|
||||
|
||||
static func ephemeral(
|
||||
wipeMedia: @escaping () throws -> Void = {}
|
||||
) -> PanicRecoveryOperations {
|
||||
PanicRecoveryOperations(
|
||||
isPending: { false },
|
||||
begin: {
|
||||
PanicRecoveryIntent(
|
||||
fileMarkerEstablished: false,
|
||||
externalMarkerEstablished: false
|
||||
)
|
||||
},
|
||||
wipeMedia: { _ in try wipeMedia() },
|
||||
complete: {}
|
||||
)
|
||||
}
|
||||
|
||||
static func live(
|
||||
fileStore: BLEIncomingFileStore = BLEIncomingFileStore(),
|
||||
defaults: UserDefaults = .standard
|
||||
) -> PanicRecoveryOperations {
|
||||
let defaultsKey = "bitchat.panicResetPending"
|
||||
return PanicRecoveryOperations(
|
||||
isPending: {
|
||||
if defaults.bool(forKey: defaultsKey) {
|
||||
return true
|
||||
}
|
||||
return try fileStore.isPanicRecoveryPending()
|
||||
},
|
||||
begin: {
|
||||
defaults.set(true, forKey: defaultsKey)
|
||||
let externalMarkerEstablished =
|
||||
defaults.synchronize()
|
||||
&& defaults.bool(forKey: defaultsKey)
|
||||
|
||||
let fileMarkerEstablished: Bool
|
||||
do {
|
||||
try fileStore.markPanicRecoveryPending()
|
||||
fileMarkerEstablished = true
|
||||
} catch {
|
||||
fileMarkerEstablished = false
|
||||
SecureLogger.error(
|
||||
"Failed to persist file panic-recovery marker: \(error)",
|
||||
category: .security
|
||||
)
|
||||
}
|
||||
|
||||
return PanicRecoveryIntent(
|
||||
fileMarkerEstablished: fileMarkerEstablished,
|
||||
externalMarkerEstablished: externalMarkerEstablished
|
||||
)
|
||||
},
|
||||
wipeMedia: { intent in
|
||||
try fileStore.panicWipe(
|
||||
hasDurablePendingMarker: intent.hasDurableMarker
|
||||
)
|
||||
},
|
||||
complete: {
|
||||
// Keep the independent defaults latch until the file marker
|
||||
// has definitely cleared. Any failure therefore remains
|
||||
// visible to the next launch.
|
||||
try fileStore.completePanicRecovery()
|
||||
defaults.removeObject(forKey: defaultsKey)
|
||||
guard defaults.synchronize(),
|
||||
!defaults.bool(forKey: defaultsKey) else {
|
||||
throw BLEIncomingFileStore.PanicRecoveryError
|
||||
.externalMarkerCommitFailed
|
||||
}
|
||||
}
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
struct BLEIncomingFileStore {
|
||||
enum PanicRecoveryError: Error {
|
||||
case externalMarkerCommitFailed
|
||||
case markerWriteFailed(Error)
|
||||
case markerWriteAndMediaWipeFailed(
|
||||
markerError: Error,
|
||||
mediaError: Error
|
||||
)
|
||||
}
|
||||
|
||||
private static let quotaBytes: Int64 = 100 * 1024 * 1024
|
||||
/// 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 mediaSubdirectories = [
|
||||
"voicenotes/incoming",
|
||||
"voicenotes/outgoing",
|
||||
"images/incoming",
|
||||
"images/outgoing",
|
||||
"files/incoming",
|
||||
"files/outgoing"
|
||||
]
|
||||
|
||||
/// Name prefix of in-flight live voice captures (progressively written by
|
||||
/// `ChatLiveVoiceCoordinator`). Quota eviction skips them by pattern —
|
||||
@@ -17,11 +133,96 @@ struct BLEIncomingFileStore {
|
||||
let fileManager: FileManager
|
||||
private let baseDirectory: URL?
|
||||
private let dateProvider: () -> Date
|
||||
private let panicMarkerWriter: (Data, URL) throws -> Void
|
||||
|
||||
init(fileManager: FileManager = .default, baseDirectory: URL? = nil, dateProvider: @escaping () -> Date = Date.init) {
|
||||
init(
|
||||
fileManager: FileManager = .default,
|
||||
baseDirectory: URL? = nil,
|
||||
dateProvider: @escaping () -> Date = Date.init,
|
||||
panicMarkerWriter: @escaping (Data, URL) throws -> Void = {
|
||||
try $0.write(to: $1, options: .atomic)
|
||||
}
|
||||
) {
|
||||
self.fileManager = fileManager
|
||||
self.baseDirectory = baseDirectory
|
||||
self.dateProvider = dateProvider
|
||||
self.panicMarkerWriter = panicMarkerWriter
|
||||
}
|
||||
|
||||
/// 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 {
|
||||
let markerError: Error?
|
||||
do {
|
||||
try markPanicRecoveryPending()
|
||||
markerError = nil
|
||||
} catch {
|
||||
markerError = error
|
||||
SecureLogger.error(
|
||||
"Could not persist file panic-recovery marker; attempting media deletion anyway: \(error)",
|
||||
category: .security
|
||||
)
|
||||
}
|
||||
|
||||
do {
|
||||
let filesDirectory = try rootDirectory()
|
||||
.appendingPathComponent("files", isDirectory: true)
|
||||
if fileManager.fileExists(atPath: filesDirectory.path) {
|
||||
try fileManager.removeItem(at: filesDirectory)
|
||||
}
|
||||
for subdirectory in Self.mediaSubdirectories {
|
||||
try fileManager.createDirectory(
|
||||
at: filesDirectory.appendingPathComponent(
|
||||
subdirectory,
|
||||
isDirectory: true
|
||||
),
|
||||
withIntermediateDirectories: true,
|
||||
attributes: nil
|
||||
)
|
||||
}
|
||||
} catch {
|
||||
if let markerError {
|
||||
throw PanicRecoveryError.markerWriteAndMediaWipeFailed(
|
||||
markerError: markerError,
|
||||
mediaError: error
|
||||
)
|
||||
}
|
||||
throw error
|
||||
}
|
||||
|
||||
if let markerError, !hasDurablePendingMarker {
|
||||
throw PanicRecoveryError.markerWriteFailed(markerError)
|
||||
}
|
||||
}
|
||||
|
||||
func markPanicRecoveryPending() throws {
|
||||
let markerURL = try panicRecoveryPendingMarkerURL()
|
||||
try fileManager.createDirectory(
|
||||
at: markerURL.deletingLastPathComponent(),
|
||||
withIntermediateDirectories: true,
|
||||
attributes: nil
|
||||
)
|
||||
try panicMarkerWriter(Data([1]), markerURL)
|
||||
}
|
||||
|
||||
func isPanicRecoveryPending() throws -> Bool {
|
||||
try panicRecoveryMarkerURLs().contains {
|
||||
fileManager.fileExists(atPath: $0.path)
|
||||
}
|
||||
}
|
||||
|
||||
func completePanicRecovery() throws {
|
||||
for markerURL in try panicRecoveryMarkerURLs()
|
||||
where fileManager.fileExists(atPath: markerURL.path) {
|
||||
try fileManager.removeItem(at: markerURL)
|
||||
}
|
||||
}
|
||||
|
||||
/// Resolves (and creates) an incoming-media directory for callers that
|
||||
@@ -113,15 +314,39 @@ struct BLEIncomingFileStore {
|
||||
}
|
||||
|
||||
private func filesDirectory() throws -> URL {
|
||||
let root = try baseDirectory ?? fileManager.url(
|
||||
let filesDir = try rootDirectory().appendingPathComponent("files", isDirectory: true)
|
||||
try fileManager.createDirectory(at: filesDir, withIntermediateDirectories: true, attributes: nil)
|
||||
return filesDir
|
||||
}
|
||||
|
||||
private func rootDirectory() throws -> URL {
|
||||
try baseDirectory ?? fileManager.url(
|
||||
for: .applicationSupportDirectory,
|
||||
in: .userDomainMask,
|
||||
appropriateFor: nil,
|
||||
create: true
|
||||
)
|
||||
let filesDir = root.appendingPathComponent("files", isDirectory: true)
|
||||
try fileManager.createDirectory(at: filesDir, withIntermediateDirectories: true, attributes: nil)
|
||||
return filesDir
|
||||
}
|
||||
|
||||
private func panicRecoveryPendingMarkerURL() throws -> URL {
|
||||
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
|
||||
)
|
||||
]
|
||||
}
|
||||
|
||||
private func sanitizedFileName(_ name: String?, defaultName: String, fallbackExtension: String?) -> String {
|
||||
|
||||
@@ -49,11 +49,7 @@ final class BLENoisePacketHandler {
|
||||
self.environment = environment
|
||||
}
|
||||
|
||||
/// Returns true when the handshake message was processed successfully.
|
||||
/// Callers use this to distinguish an authenticated replacement completion
|
||||
/// from a rejected candidate while an older session remains established.
|
||||
@discardableResult
|
||||
func handleHandshake(_ packet: BitchatPacket, from peerID: PeerID) -> Bool {
|
||||
func handleHandshake(_ packet: BitchatPacket, from peerID: PeerID) {
|
||||
let env = environment
|
||||
// Use NoiseEncryptionService for handshake processing
|
||||
if PeerID(hexData: packet.recipientID) == env.localPeerID() {
|
||||
@@ -76,26 +72,14 @@ final class BLENoisePacketHandler {
|
||||
|
||||
// Session establishment will trigger onPeerAuthenticated callback
|
||||
// which will send any pending messages at the right time
|
||||
return true
|
||||
} catch NoiseSessionError.peerIdentityMismatch {
|
||||
// The candidate was already discarded by the session manager.
|
||||
// Do not let a spoofed claimed ID trigger a fresh outbound
|
||||
// handshake or recreate state for the attacker-selected ID.
|
||||
SecureLogger.warning(
|
||||
"Rejected Noise handshake whose static key does not match \(peerID.id.prefix(8))…",
|
||||
category: .security
|
||||
)
|
||||
return false
|
||||
} catch {
|
||||
SecureLogger.error("Failed to process handshake: \(error)")
|
||||
// Try initiating a new handshake
|
||||
if !env.hasNoiseSession(peerID) {
|
||||
env.initiateHandshake(peerID)
|
||||
}
|
||||
return false
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func handleEncrypted(_ packet: BitchatPacket, from peerID: PeerID) {
|
||||
|
||||
@@ -155,6 +155,10 @@ final class BLEService: NSObject {
|
||||
private var centralManager: CBCentralManager?
|
||||
private var peripheralManager: CBPeripheralManager?
|
||||
private var characteristic: CBMutableCharacteristic?
|
||||
private let shouldInitializeBluetoothManagers: Bool
|
||||
private let panicLifecycleLock = NSLock()
|
||||
private var _isPanicSuspended: Bool
|
||||
private var panicLifecycleGeneration: UInt64 = 0
|
||||
|
||||
// MARK: - Identity
|
||||
|
||||
@@ -275,10 +279,13 @@ final class BLEService: NSObject {
|
||||
keychain: KeychainManagerProtocol,
|
||||
idBridge: NostrIdentityBridge,
|
||||
identityManager: SecureIdentityStateManagerProtocol,
|
||||
initializeBluetoothManagers: Bool = true
|
||||
initializeBluetoothManagers: Bool = true,
|
||||
startSuspendedForPanicRecovery: Bool = false
|
||||
) {
|
||||
self.keychain = keychain
|
||||
self.idBridge = idBridge
|
||||
self.shouldInitializeBluetoothManagers = initializeBluetoothManagers
|
||||
self._isPanicSuspended = startSuspendedForPanicRecovery
|
||||
noiseService = NoiseEncryptionService(keychain: keychain)
|
||||
self.identityManager = identityManager
|
||||
super.init()
|
||||
@@ -327,37 +334,90 @@ final class BLEService: NSObject {
|
||||
// any access from another queue (cross-queue reads use readLinkState).
|
||||
linkStateStore.assumeOwnership(of: bleQueue)
|
||||
|
||||
if initializeBluetoothManagers {
|
||||
// Initialize BLE on background queue to prevent main thread blocking.
|
||||
if !startSuspendedForPanicRecovery {
|
||||
initializeBluetoothManagersIfNeeded()
|
||||
}
|
||||
|
||||
// Single maintenance timer for all periodic tasks (dispatch-based for
|
||||
// determinism). Only run it when real Bluetooth managers exist.
|
||||
meshBackgroundEnabled = initializeBluetoothManagers
|
||||
if !startSuspendedForPanicRecovery {
|
||||
startMaintenanceTimer()
|
||||
}
|
||||
|
||||
// Publish initial empty state
|
||||
requestPeerDataPublish()
|
||||
|
||||
// Initialize gossip sync manager
|
||||
if !startSuspendedForPanicRecovery {
|
||||
restartGossipManager()
|
||||
}
|
||||
}
|
||||
|
||||
private var isPanicSuspended: Bool {
|
||||
panicLifecycleLock.lock()
|
||||
defer { panicLifecycleLock.unlock() }
|
||||
return _isPanicSuspended
|
||||
}
|
||||
|
||||
private func setPanicSuspended(_ suspended: Bool) {
|
||||
panicLifecycleLock.lock()
|
||||
if suspended {
|
||||
panicLifecycleGeneration &+= 1
|
||||
}
|
||||
_isPanicSuspended = suspended
|
||||
panicLifecycleLock.unlock()
|
||||
}
|
||||
|
||||
private func capturePanicLifecycleGeneration() -> UInt64? {
|
||||
panicLifecycleLock.lock()
|
||||
defer { panicLifecycleLock.unlock() }
|
||||
return _isPanicSuspended ? nil : panicLifecycleGeneration
|
||||
}
|
||||
|
||||
private func isCurrentPanicLifecycleGeneration(_ generation: UInt64) -> Bool {
|
||||
panicLifecycleLock.lock()
|
||||
defer { panicLifecycleLock.unlock() }
|
||||
return !_isPanicSuspended && panicLifecycleGeneration == generation
|
||||
}
|
||||
|
||||
private func initializeBluetoothManagersIfNeeded() {
|
||||
guard shouldInitializeBluetoothManagers,
|
||||
centralManager == nil,
|
||||
peripheralManager == nil,
|
||||
!isPanicSuspended else { return }
|
||||
|
||||
// Initialize BLE on its dedicated delegate queue. On iOS, retain the
|
||||
// restoration identifiers even when construction was deferred by a
|
||||
// pending panic-recovery latch.
|
||||
#if os(iOS)
|
||||
let centralOptions: [String: Any] = [
|
||||
CBCentralManagerOptionRestoreIdentifierKey: BLEService.centralRestorationID
|
||||
CBCentralManagerOptionRestoreIdentifierKey:
|
||||
BLEService.centralRestorationID
|
||||
]
|
||||
centralManager = CBCentralManager(delegate: self, queue: bleQueue, options: centralOptions)
|
||||
centralManager = CBCentralManager(
|
||||
delegate: self,
|
||||
queue: bleQueue,
|
||||
options: centralOptions
|
||||
)
|
||||
|
||||
let peripheralOptions: [String: Any] = [
|
||||
CBPeripheralManagerOptionRestoreIdentifierKey: BLEService.peripheralRestorationID
|
||||
CBPeripheralManagerOptionRestoreIdentifierKey:
|
||||
BLEService.peripheralRestorationID
|
||||
]
|
||||
peripheralManager = CBPeripheralManager(delegate: self, queue: bleQueue, options: peripheralOptions)
|
||||
peripheralManager = CBPeripheralManager(
|
||||
delegate: self,
|
||||
queue: bleQueue,
|
||||
options: peripheralOptions
|
||||
)
|
||||
#else
|
||||
centralManager = CBCentralManager(delegate: self, queue: bleQueue)
|
||||
peripheralManager = CBPeripheralManager(delegate: self, queue: bleQueue)
|
||||
#endif
|
||||
}
|
||||
|
||||
// Single maintenance timer for all periodic tasks (dispatch-based for
|
||||
// determinism). Only run it when real Bluetooth managers exist.
|
||||
meshBackgroundEnabled = initializeBluetoothManagers
|
||||
startMaintenanceTimer()
|
||||
|
||||
// Publish initial empty state
|
||||
requestPeerDataPublish()
|
||||
|
||||
// Initialize gossip sync manager
|
||||
restartGossipManager()
|
||||
}
|
||||
|
||||
private func restartGossipManager() {
|
||||
guard !isPanicSuspended else { return }
|
||||
// Stop existing
|
||||
gossipSyncManager?.stop()
|
||||
|
||||
@@ -416,7 +476,35 @@ final class BLEService: NSObject {
|
||||
#endif
|
||||
}
|
||||
|
||||
func resetIdentityForPanic(currentNickname: String) {
|
||||
/// Close radio admission before application state starts disappearing.
|
||||
/// CoreBluetooth callbacks consult the same gate and cannot restart scan
|
||||
/// or advertising while the full panic transaction is incomplete.
|
||||
func suspendForPanicReset() {
|
||||
setPanicSuspended(true)
|
||||
gossipSyncManager?.stop()
|
||||
gossipSyncManager = nil
|
||||
// Wait out sends that passed admission before the gate closed. Work
|
||||
// queued behind this barrier observes `isPanicSuspended` and exits,
|
||||
// so the radio stop below is a true synchronous boundary.
|
||||
messageQueue.sync(flags: .barrier) {}
|
||||
stopServicesImmediatelyForPanic()
|
||||
clearEmergencySessionState()
|
||||
}
|
||||
|
||||
/// Reopen the radio only after media deletion and recovery-marker commit.
|
||||
func completePanicReset(restartServices: Bool) {
|
||||
setPanicSuspended(false)
|
||||
guard restartServices else { return }
|
||||
startServices()
|
||||
sendAnnounce(forceSend: true)
|
||||
}
|
||||
|
||||
func resetIdentityForPanic(
|
||||
currentNickname: String,
|
||||
restartServices: Bool = true
|
||||
) {
|
||||
gossipSyncManager?.stop()
|
||||
gossipSyncManager = nil
|
||||
messageQueue.sync(flags: .barrier) {
|
||||
pendingNoiseSessionQueues.removeAll()
|
||||
}
|
||||
@@ -460,16 +548,19 @@ final class BLEService: NSObject {
|
||||
configureNoiseServiceCallbacks(for: newNoise)
|
||||
refreshPeerIdentity()
|
||||
}
|
||||
restartGossipManager()
|
||||
|
||||
setNickname(currentNickname)
|
||||
|
||||
// Keep the transport silent until the application-level transaction
|
||||
// has also removed its media and committed both recovery markers.
|
||||
myNickname = currentNickname
|
||||
messageDeduplicator.reset()
|
||||
messageQueue.async(flags: .barrier) { [weak self] in
|
||||
self?.selfBroadcastTracker.removeAll()
|
||||
}
|
||||
requestPeerDataPublish()
|
||||
if restartServices {
|
||||
restartGossipManager()
|
||||
startServices()
|
||||
sendAnnounce(forceSend: true)
|
||||
}
|
||||
}
|
||||
|
||||
// Ensure this runs on message queue to avoid main thread blocking
|
||||
@@ -481,6 +572,7 @@ final class BLEService: NSObject {
|
||||
}
|
||||
return
|
||||
}
|
||||
guard !isPanicSuspended else { return }
|
||||
|
||||
guard content.count <= maxMessageLength else {
|
||||
SecureLogger.error("Message too long: \(content.count) chars", category: .session)
|
||||
@@ -562,7 +654,9 @@ final class BLEService: NSObject {
|
||||
/// `startServices()` — the latter matters after a panic reset, where
|
||||
/// `stopServices()` cancels and nils the timer.
|
||||
private func startMaintenanceTimer() {
|
||||
guard meshBackgroundEnabled, maintenanceTimer == nil else { return }
|
||||
guard !isPanicSuspended,
|
||||
meshBackgroundEnabled,
|
||||
maintenanceTimer == nil else { return }
|
||||
let timer = DispatchSource.makeTimerSource(queue: bleQueue)
|
||||
timer.schedule(deadline: .now() + TransportConfig.bleMaintenanceInterval,
|
||||
repeating: TransportConfig.bleMaintenanceInterval,
|
||||
@@ -575,6 +669,12 @@ final class BLEService: NSObject {
|
||||
}
|
||||
|
||||
func startServices() {
|
||||
guard let lifecycleGeneration =
|
||||
capturePanicLifecycleGeneration() else { return }
|
||||
initializeBluetoothManagersIfNeeded()
|
||||
if gossipSyncManager == nil {
|
||||
restartGossipManager()
|
||||
}
|
||||
// Restart the maintenance timer if a prior stopServices() cancelled it
|
||||
// (e.g. the panic flow), otherwise periodic announces, peer reconciliation
|
||||
// and cache cleanup would never resume until app restart.
|
||||
@@ -591,7 +691,11 @@ final class BLEService: NSObject {
|
||||
// Send initial announce after services are ready
|
||||
// Use longer delay to avoid conflicts with other announces
|
||||
messageQueue.asyncAfter(deadline: .now() + TransportConfig.bleInitialAnnounceDelaySeconds) { [weak self] in
|
||||
self?.sendAnnounce(forceSend: true)
|
||||
guard let self,
|
||||
self.isCurrentPanicLifecycleGeneration(
|
||||
lifecycleGeneration
|
||||
) else { return }
|
||||
self.sendAnnounce(forceSend: true)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -660,9 +764,36 @@ final class BLEService: NSObject {
|
||||
}
|
||||
}
|
||||
|
||||
/// Panic cannot spend its security boundary sending a signed LEAVE or
|
||||
/// pumping the main run loop. Close the radio and timers immediately;
|
||||
/// the identity/session cleanup follows synchronously.
|
||||
private func stopServicesImmediatelyForPanic() {
|
||||
collectionsQueue.sync(flags: .barrier) {
|
||||
pendingNotifications.removeAll()
|
||||
}
|
||||
|
||||
maintenanceTimer?.cancel()
|
||||
maintenanceTimer = nil
|
||||
scanDutyTimer?.cancel()
|
||||
scanDutyTimer = nil
|
||||
|
||||
centralManager?.stopScan()
|
||||
peripheralManager?.stopAdvertising()
|
||||
|
||||
let peripheralsToDisconnect = bleQueue.sync {
|
||||
linkStateStore.peripheralStates
|
||||
}
|
||||
for state in peripheralsToDisconnect {
|
||||
centralManager?.cancelPeripheralConnection(state.peripheral)
|
||||
}
|
||||
}
|
||||
|
||||
func emergencyDisconnectAll() {
|
||||
stopServices()
|
||||
clearEmergencySessionState()
|
||||
}
|
||||
|
||||
private func clearEmergencySessionState() {
|
||||
// Clear all sessions and peers
|
||||
let cancelledTransfers: [(id: String, items: [DispatchWorkItem])] = collectionsQueue.sync(flags: .barrier) {
|
||||
let entries = outboundFragmentTransfers.removeAll().map { ($0.id, $0.workItems) }
|
||||
@@ -899,6 +1030,7 @@ final class BLEService: NSObject {
|
||||
func sendFileBroadcast(_ filePacket: BitchatFilePacket, transferId: String) {
|
||||
messageQueue.async { [weak self] in
|
||||
guard let self = self else { return }
|
||||
guard !self.isPanicSuspended else { return }
|
||||
guard let payload = filePacket.encode() else {
|
||||
SecureLogger.error("❌ Failed to encode file packet for broadcast", category: .session)
|
||||
return
|
||||
@@ -935,6 +1067,7 @@ final class BLEService: NSObject {
|
||||
func sendFilePrivate(_ filePacket: BitchatFilePacket, to peerID: PeerID, transferId: String) {
|
||||
messageQueue.async { [weak self] in
|
||||
guard let self = self else { return }
|
||||
guard !self.isPanicSuspended else { return }
|
||||
guard let payload = filePacket.encode() else {
|
||||
SecureLogger.error("❌ Failed to encode file packet for private send", category: .session)
|
||||
return
|
||||
@@ -1088,6 +1221,7 @@ final class BLEService: NSObject {
|
||||
// MARK: - Packet Broadcasting
|
||||
|
||||
private func broadcastPacket(_ packet: BitchatPacket, transferId: String? = nil) {
|
||||
guard !isPanicSuspended else { return }
|
||||
// Apply route if recipient exists (centralized route application)
|
||||
let packetToSend: BitchatPacket
|
||||
if let recipientPeerID = PeerID(hexData: packet.recipientID) {
|
||||
@@ -1169,8 +1303,10 @@ final class BLEService: NSObject {
|
||||
}
|
||||
|
||||
private func enqueuePendingNotification(data: Data, centrals: [CBCentral]?, context: String, attempt: Int = 0) {
|
||||
guard !isPanicSuspended else { return }
|
||||
collectionsQueue.async(flags: .barrier) { [weak self] in
|
||||
guard let self = self else { return }
|
||||
guard !self.isPanicSuspended else { return }
|
||||
let result = self.pendingNotifications.enqueue(
|
||||
data: data,
|
||||
targets: centrals,
|
||||
@@ -1271,6 +1407,7 @@ final class BLEService: NSObject {
|
||||
requireDirectPeerLink: Bool = false,
|
||||
requireNoiseAuthenticatedPeerLink: Bool = false
|
||||
) -> Bool {
|
||||
guard !isPanicSuspended else { return false }
|
||||
let ingressRecord = collectionsQueue.sync { ingressLinks.record(for: packet) }
|
||||
var excludedPeerLinks = links(to: ingressRecord?.peerID)
|
||||
if requireNoiseAuthenticatedPeerLink {
|
||||
@@ -1421,6 +1558,7 @@ final class BLEService: NSObject {
|
||||
}
|
||||
|
||||
private func flushDirectedSpool() {
|
||||
guard !isPanicSuspended else { return }
|
||||
// Move items out and attempt broadcast; if still no links, they'll be re-spooled
|
||||
let toSend = collectionsQueue.sync(flags: .barrier) {
|
||||
pendingDirectedRelays.drainUnexpired(
|
||||
@@ -1618,44 +1756,7 @@ final class BLEService: NSObject {
|
||||
}
|
||||
}
|
||||
|
||||
/// Accept a leave only when the claimed sender proves possession of the
|
||||
/// signing key bound by a verified announce. The persisted identity cache
|
||||
/// keeps delayed/relayed leaves verifiable after the live registry entry
|
||||
/// has aged out.
|
||||
private func handleLeave(_ packet: BitchatPacket, from peerID: PeerID) -> Bool {
|
||||
let registrySigningKey = collectionsQueue.sync {
|
||||
peerRegistry.info(for: peerID)?.signingPublicKey
|
||||
}
|
||||
let verifiedViaRegistry = registrySigningKey.map {
|
||||
noiseService.verifyPacketSignature(packet, publicKey: $0)
|
||||
} ?? false
|
||||
let verifiedViaPersistedIdentity = !verifiedViaRegistry
|
||||
&& identityManager.getCryptoIdentitiesByPeerIDPrefix(peerID).contains { identity in
|
||||
PeerID(publicKey: identity.publicKey) == peerID
|
||||
&& identity.signingPublicKey.map {
|
||||
noiseService.verifyPacketSignature(packet, publicKey: $0)
|
||||
} == true
|
||||
}
|
||||
|
||||
guard verifiedViaRegistry || verifiedViaPersistedIdentity else {
|
||||
SecureLogger.warning(
|
||||
"🚫 Dropping leave with missing/invalid signature for claimed sender \(peerID.id.prefix(8))…",
|
||||
category: .security
|
||||
)
|
||||
return false
|
||||
}
|
||||
|
||||
// A valid departure retires transport state too; otherwise
|
||||
// canDeliverSecurely could remain true for a peer we just removed.
|
||||
noiseService.clearSession(for: peerID)
|
||||
readLinkState { _ in
|
||||
let departedLinks = noiseAuthenticatedLinkOwners.compactMap { link, owner in
|
||||
owner == peerID ? link : nil
|
||||
}
|
||||
for link in departedLinks {
|
||||
noiseAuthenticatedLinkOwners.removeValue(forKey: link)
|
||||
}
|
||||
}
|
||||
private func handleLeave(_: BitchatPacket, from peerID: PeerID) {
|
||||
_ = collectionsQueue.sync(flags: .barrier) {
|
||||
// Remove the peer when they leave
|
||||
peerRegistry.remove(peerID)
|
||||
@@ -1672,9 +1773,9 @@ final class BLEService: NSObject {
|
||||
self.deliverTransportEvent(.peerDisconnected(peerID))
|
||||
self.deliverTransportEvent(.peerListUpdated(currentPeerIDs))
|
||||
}
|
||||
return true
|
||||
}
|
||||
private func sendAnnounce(forceSend: Bool = false) {
|
||||
guard !isPanicSuspended else { return }
|
||||
// Throttle announces to prevent flooding
|
||||
if !announceThrottle.shouldSend(force: forceSend, now: Date()) {
|
||||
return
|
||||
@@ -1884,6 +1985,13 @@ extension BLEService: CBCentralManagerDelegate {
|
||||
#if os(iOS)
|
||||
func centralManager(_ central: CBCentralManager, willRestoreState dict: [String: Any]) {
|
||||
let restoredPeripherals = (dict[CBCentralManagerRestoredStatePeripheralsKey] as? [CBPeripheral]) ?? []
|
||||
guard !isPanicSuspended else {
|
||||
central.stopScan()
|
||||
restoredPeripherals.forEach {
|
||||
central.cancelPeripheralConnection($0)
|
||||
}
|
||||
return
|
||||
}
|
||||
let restoredServices = (dict[CBCentralManagerRestoredStateScanServicesKey] as? [CBUUID]) ?? []
|
||||
let restoredOptions = (dict[CBCentralManagerRestoredStateScanOptionsKey] as? [String: Any]) ?? [:]
|
||||
let allowDuplicates = restoredOptions[CBCentralManagerScanOptionAllowDuplicatesKey] as? Bool
|
||||
@@ -1939,6 +2047,10 @@ extension BLEService: CBCentralManagerDelegate {
|
||||
|
||||
switch central.state {
|
||||
case .poweredOn:
|
||||
guard !isPanicSuspended else {
|
||||
central.stopScan()
|
||||
return
|
||||
}
|
||||
// Links restored as connected have no characteristic in the new
|
||||
// process; without rediscovery they sit connected-but-unusable
|
||||
// until the peer disconnects. Runs here (not willRestoreState)
|
||||
@@ -1995,7 +2107,8 @@ extension BLEService: CBCentralManagerDelegate {
|
||||
}
|
||||
|
||||
private func startScanning() {
|
||||
guard let central = centralManager,
|
||||
guard !isPanicSuspended,
|
||||
let central = centralManager,
|
||||
central.state == .poweredOn,
|
||||
!central.isScanning else { return }
|
||||
|
||||
@@ -2016,6 +2129,7 @@ extension BLEService: CBCentralManagerDelegate {
|
||||
}
|
||||
|
||||
func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String: Any], rssi RSSI: NSNumber) {
|
||||
guard !isPanicSuspended else { return }
|
||||
let peripheralID = peripheral.identifier.uuidString
|
||||
let advertisedName = advertisementData[CBAdvertisementDataLocalNameKey] as? String ?? (peripheralID.prefix(6) + "…")
|
||||
let isConnectable = (advertisementData[CBAdvertisementDataIsConnectable] as? NSNumber)?.boolValue ?? true
|
||||
@@ -2057,6 +2171,10 @@ extension BLEService: CBCentralManagerDelegate {
|
||||
}
|
||||
|
||||
func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral) {
|
||||
guard !isPanicSuspended else {
|
||||
central.cancelPeripheralConnection(peripheral)
|
||||
return
|
||||
}
|
||||
let peripheralID = peripheral.identifier.uuidString
|
||||
|
||||
#if os(iOS)
|
||||
@@ -2207,7 +2325,9 @@ private extension CBPeripheralState {
|
||||
|
||||
extension BLEService {
|
||||
private func tryConnectFromQueue() {
|
||||
guard let central = centralManager, central.state == .poweredOn else { return }
|
||||
guard !isPanicSuspended,
|
||||
let central = centralManager,
|
||||
central.state == .poweredOn else { return }
|
||||
|
||||
let decision = connectionScheduler.nextCandidate(
|
||||
connectedOrConnectingCount: linkStateStore.connectedOrConnectingPeripheralCount,
|
||||
@@ -2233,6 +2353,7 @@ extension BLEService {
|
||||
using central: CBCentralManager,
|
||||
logPrefix: String
|
||||
) {
|
||||
guard !isPanicSuspended else { return }
|
||||
let peripheral = candidate.peripheral
|
||||
let peripheralID = candidate.peripheralID
|
||||
linkStateStore.beginConnecting(to: peripheral, at: Date())
|
||||
@@ -2374,12 +2495,6 @@ extension BLEService {
|
||||
}
|
||||
}
|
||||
|
||||
func _test_isNoiseAuthenticatedCentral(_ centralUUID: String, for peerID: PeerID) -> Bool {
|
||||
bleQueue.sync {
|
||||
noiseAuthenticatedLinkOwners[.central(centralUUID)] == peerID
|
||||
}
|
||||
}
|
||||
|
||||
func _test_seedConnectedPeer(_ peerID: PeerID, nickname: String) {
|
||||
collectionsQueue.sync(flags: .barrier) {
|
||||
peerRegistry.upsert(BLEPeerInfo(
|
||||
@@ -2420,6 +2535,7 @@ extension BLEService {
|
||||
|
||||
extension BLEService: CBPeripheralDelegate {
|
||||
func peripheral(_ peripheral: CBPeripheral, didDiscoverServices error: Error?) {
|
||||
guard !isPanicSuspended else { return }
|
||||
if let error = error {
|
||||
SecureLogger.error("❌ Error discovering services for \(peripheral.name ?? "Unknown"): \(error.localizedDescription)", category: .session)
|
||||
// Retry service discovery after a delay
|
||||
@@ -2446,6 +2562,7 @@ extension BLEService: CBPeripheralDelegate {
|
||||
}
|
||||
|
||||
func peripheral(_ peripheral: CBPeripheral, didDiscoverCharacteristicsFor service: CBService, error: Error?) {
|
||||
guard !isPanicSuspended else { return }
|
||||
if let error = error {
|
||||
SecureLogger.error("❌ Error discovering characteristics for \(peripheral.name ?? "Unknown"): \(error.localizedDescription)", category: .session)
|
||||
return
|
||||
@@ -2493,6 +2610,7 @@ extension BLEService: CBPeripheralDelegate {
|
||||
}
|
||||
|
||||
func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?) {
|
||||
guard !isPanicSuspended else { return }
|
||||
if let error = error {
|
||||
SecureLogger.error("❌ Error receiving notification: \(error.localizedDescription)", category: .session)
|
||||
return
|
||||
@@ -2610,6 +2728,7 @@ extension BLEService: CBPeripheralDelegate {
|
||||
}
|
||||
|
||||
func peripheralIsReady(toSendWriteWithoutResponse peripheral: CBPeripheral) {
|
||||
guard !isPanicSuspended else { return }
|
||||
// Resume queued writes for this peripheral - called when canSendWriteWithoutResponse becomes true again
|
||||
if logRateLimiter.shouldLog(key: "peripheral-ready:\(peripheral.identifier.uuidString)") {
|
||||
SecureLogger.debug("📤 Peripheral \(peripheral.name ?? peripheral.identifier.uuidString.prefix(8).description) ready for more writes", category: .session)
|
||||
@@ -2618,6 +2737,7 @@ extension BLEService: CBPeripheralDelegate {
|
||||
}
|
||||
|
||||
func peripheral(_ peripheral: CBPeripheral, didModifyServices invalidatedServices: [CBService]) {
|
||||
guard !isPanicSuspended else { return }
|
||||
SecureLogger.warning("⚠️ Services modified for \(peripheral.name ?? peripheral.identifier.uuidString)", category: .session)
|
||||
|
||||
let shouldRediscover = BLEService.shouldRediscoverBitChatService(
|
||||
@@ -2638,6 +2758,7 @@ extension BLEService: CBPeripheralDelegate {
|
||||
}
|
||||
|
||||
func peripheral(_ peripheral: CBPeripheral, didUpdateNotificationStateFor characteristic: CBCharacteristic, error: Error?) {
|
||||
guard !isPanicSuspended else { return }
|
||||
if let error = error {
|
||||
SecureLogger.error("❌ Error updating notification state: \(error.localizedDescription)", category: .session)
|
||||
} else {
|
||||
@@ -2661,6 +2782,12 @@ extension BLEService: CBPeripheralManagerDelegate {
|
||||
|
||||
switch peripheral.state {
|
||||
case .poweredOn:
|
||||
guard !isPanicSuspended else {
|
||||
peripheral.stopAdvertising()
|
||||
peripheral.removeAllServices()
|
||||
characteristic = nil
|
||||
return
|
||||
}
|
||||
// Remove all services first to ensure clean state
|
||||
peripheral.removeAllServices()
|
||||
|
||||
@@ -2721,6 +2848,12 @@ extension BLEService: CBPeripheralManagerDelegate {
|
||||
|
||||
#if os(iOS)
|
||||
func peripheralManager(_ peripheral: CBPeripheralManager, willRestoreState dict: [String: Any]) {
|
||||
guard !isPanicSuspended else {
|
||||
peripheral.stopAdvertising()
|
||||
peripheral.removeAllServices()
|
||||
characteristic = nil
|
||||
return
|
||||
}
|
||||
let restoredServices = (dict[CBPeripheralManagerRestoredStateServicesKey] as? [CBMutableService]) ?? []
|
||||
let restoredAdvertisement = (dict[CBPeripheralManagerRestoredStateAdvertisementDataKey] as? [String: Any]) ?? [:]
|
||||
|
||||
@@ -2747,6 +2880,10 @@ extension BLEService: CBPeripheralManagerDelegate {
|
||||
#endif
|
||||
|
||||
func peripheralManager(_ peripheral: CBPeripheralManager, didAdd service: CBService, error: Error?) {
|
||||
guard !isPanicSuspended else {
|
||||
peripheral.stopAdvertising()
|
||||
return
|
||||
}
|
||||
if let error = error {
|
||||
SecureLogger.error("❌ Failed to add service: \(error.localizedDescription)", category: .session)
|
||||
return
|
||||
@@ -2762,6 +2899,7 @@ extension BLEService: CBPeripheralManagerDelegate {
|
||||
}
|
||||
|
||||
func peripheralManager(_ peripheral: CBPeripheralManager, central: CBCentral, didSubscribeTo characteristic: CBCharacteristic) {
|
||||
guard !isPanicSuspended else { return }
|
||||
let centralUUID = central.identifier.uuidString
|
||||
SecureLogger.debug("📥 Central subscribed: \(centralUUID.prefix(8))…", category: .session)
|
||||
linkStateStore.addSubscribedCentral(central)
|
||||
@@ -2803,7 +2941,7 @@ extension BLEService: CBPeripheralManagerDelegate {
|
||||
let removedPeerID = linkStateStore.removeSubscribedCentral(central)
|
||||
|
||||
// Ensure we're still advertising for other devices to find us
|
||||
if peripheral.isAdvertising == false {
|
||||
if !isPanicSuspended, peripheral.isAdvertising == false {
|
||||
SecureLogger.debug("📡 Restarting advertising after central unsubscribed", category: .session)
|
||||
peripheral.startAdvertising(buildAdvertisementData())
|
||||
}
|
||||
@@ -2840,6 +2978,7 @@ extension BLEService: CBPeripheralManagerDelegate {
|
||||
}
|
||||
|
||||
func peripheralManagerIsReady(toUpdateSubscribers peripheral: CBPeripheralManager) {
|
||||
guard !isPanicSuspended else { return }
|
||||
drainPendingNotifications(logPrefix: "✅ Sent")
|
||||
}
|
||||
|
||||
@@ -2900,6 +3039,7 @@ extension BLEService: CBPeripheralManagerDelegate {
|
||||
for request in requests {
|
||||
peripheral.respond(to: request, withResult: .success)
|
||||
}
|
||||
guard !isPanicSuspended else { return }
|
||||
|
||||
// Process writes. For long writes, CoreBluetooth may deliver multiple CBATTRequest values with offsets.
|
||||
// Combine per-central request values by offset before decoding.
|
||||
@@ -4182,6 +4322,7 @@ extension BLEService {
|
||||
let uuid = peripheral.identifier.uuidString
|
||||
bleQueue.async { [weak self] in
|
||||
guard let self = self else { return }
|
||||
guard !self.isPanicSuspended else { return }
|
||||
guard let state = self.linkStateStore.state(forPeripheralID: uuid), let ch = state.characteristic else { return }
|
||||
|
||||
// Atomically take all pending items from the queue to avoid race conditions
|
||||
@@ -4272,7 +4413,10 @@ extension BLEService {
|
||||
slotReserve: Int = TransportConfig.bleBackgroundPendingConnectSlotReserve
|
||||
) {
|
||||
bleQueue.async { [weak self] in
|
||||
guard let self, let central = self.centralManager, central.state == .poweredOn else { return }
|
||||
guard let self,
|
||||
!self.isPanicSuspended,
|
||||
let central = self.centralManager,
|
||||
central.state == .poweredOn else { return }
|
||||
let budget = TransportConfig.bleMaxCentralLinks
|
||||
- slotReserve
|
||||
- self.linkStateStore.connectedOrConnectingPeripheralCount
|
||||
@@ -4829,9 +4973,7 @@ extension BLEService {
|
||||
handleMeshPong(packet, from: senderID)
|
||||
|
||||
case .leave:
|
||||
// A forged leave must neither evict the claimed peer nor spread
|
||||
// to downstream nodes.
|
||||
guard handleLeave(packet, from: senderID) else { return }
|
||||
handleLeave(packet, from: senderID)
|
||||
|
||||
case .none:
|
||||
SecureLogger.warning("⚠️ Unknown message type: \(packet.type)", category: .session)
|
||||
@@ -5472,14 +5614,8 @@ extension BLEService {
|
||||
|
||||
private func handleNoiseHandshake(_ packet: BitchatPacket, from peerID: PeerID) {
|
||||
let wasEstablished = noiseService.hasEstablishedSession(with: peerID)
|
||||
let processed = noisePacketHandler.handleHandshake(packet, from: peerID)
|
||||
let isEstablished = noiseService.hasEstablishedSession(with: peerID)
|
||||
// XX message 1 is exactly the unauthenticated 32-byte ephemeral key.
|
||||
// While replacing an existing session, do not authenticate its ingress
|
||||
// link until a later message completes and validates the candidate.
|
||||
let completedAuthenticatedHandshake = !wasEstablished
|
||||
|| packet.payload.count != NoiseSecurityConstants.xxInitialMessageSize
|
||||
if processed, isEstablished, completedAuthenticatedHandshake {
|
||||
noisePacketHandler.handleHandshake(packet, from: peerID)
|
||||
if !wasEstablished, noiseService.hasEstablishedSession(with: peerID) {
|
||||
markNoiseAuthenticatedIngressLink(for: packet, peerID: peerID)
|
||||
}
|
||||
}
|
||||
@@ -5587,6 +5723,7 @@ extension BLEService {
|
||||
// MARK: Consolidated Maintenance
|
||||
|
||||
private func performMaintenance() {
|
||||
guard !isPanicSuspended else { return }
|
||||
maintenanceCounter += 1
|
||||
lastMaintenanceAt = Date()
|
||||
|
||||
|
||||
@@ -45,6 +45,9 @@ final class GeohashPresenceService: ObservableObject {
|
||||
|
||||
private var subscriptions = Set<AnyCancellable>()
|
||||
private var heartbeatTimer: GeohashPresenceTimerProtocol?
|
||||
private var pendingBroadcastTasks: [UUID: Task<Void, Never>] = [:]
|
||||
private var heartbeatGeneration: UInt64 = 0
|
||||
private var started = false
|
||||
private let availableChannelsProvider: () -> [GeohashChannel]
|
||||
private let locationChanges: AnyPublisher<[GeohashChannel], Never>
|
||||
private let torReadyPublisher: AnyPublisher<Void, Never>
|
||||
@@ -147,10 +150,25 @@ final class GeohashPresenceService: ObservableObject {
|
||||
|
||||
/// Start the service (safe to call multiple times)
|
||||
func start() {
|
||||
guard !started else { return }
|
||||
started = true
|
||||
heartbeatGeneration &+= 1
|
||||
SecureLogger.info("Presence: service starting...", category: .session)
|
||||
scheduleNextHeartbeat()
|
||||
}
|
||||
|
||||
/// Stops the timer and every decorrelation task synchronously at the panic
|
||||
/// boundary. Generation checks also protect against custom sleepers that
|
||||
/// ignore task cancellation and return later.
|
||||
func stopForPanic() {
|
||||
started = false
|
||||
heartbeatGeneration &+= 1
|
||||
heartbeatTimer?.invalidate()
|
||||
heartbeatTimer = nil
|
||||
pendingBroadcastTasks.values.forEach { $0.cancel() }
|
||||
pendingBroadcastTasks.removeAll(keepingCapacity: false)
|
||||
}
|
||||
|
||||
private func setupObservers() {
|
||||
// Monitor location channel changes
|
||||
locationChanges
|
||||
@@ -169,20 +187,26 @@ final class GeohashPresenceService: ObservableObject {
|
||||
}
|
||||
|
||||
func handleLocationChange() {
|
||||
guard started else { return }
|
||||
// When location changes, we trigger an immediate (but slightly delayed) heartbeat
|
||||
// to announce presence in the new zone, then reset the loop.
|
||||
SecureLogger.debug("Presence: location changed, scheduling update", category: .session)
|
||||
heartbeatTimer?.invalidate()
|
||||
|
||||
// Small delay to allow location state to settle
|
||||
let generation = heartbeatGeneration
|
||||
heartbeatTimer = scheduleTimer(5.0) { [weak self] in
|
||||
Task { @MainActor [weak self] in
|
||||
self?.performHeartbeat()
|
||||
guard let self,
|
||||
self.started,
|
||||
self.heartbeatGeneration == generation else { return }
|
||||
self.performHeartbeat()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func handleConnectivityChange() {
|
||||
guard started else { return }
|
||||
SecureLogger.debug("Presence: connectivity restored, triggering heartbeat", category: .session)
|
||||
// If we were waiting for network, do it now
|
||||
if heartbeatTimer == nil || !heartbeatTimer!.isValid {
|
||||
@@ -191,18 +215,29 @@ final class GeohashPresenceService: ObservableObject {
|
||||
}
|
||||
|
||||
func scheduleNextHeartbeat() {
|
||||
guard started else { return }
|
||||
heartbeatTimer?.invalidate()
|
||||
let interval = TimeInterval.random(in: loopMinInterval...loopMaxInterval)
|
||||
let generation = heartbeatGeneration
|
||||
heartbeatTimer = scheduleTimer(interval) { [weak self] in
|
||||
Task { @MainActor [weak self] in
|
||||
self?.performHeartbeat()
|
||||
guard let self,
|
||||
self.started,
|
||||
self.heartbeatGeneration == generation else { return }
|
||||
self.performHeartbeat()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func performHeartbeat() {
|
||||
guard started else { return }
|
||||
let generation = heartbeatGeneration
|
||||
// Always schedule next loop first ensures continuity even if this one fails/skips
|
||||
defer { scheduleNextHeartbeat() }
|
||||
defer {
|
||||
if started, heartbeatGeneration == generation {
|
||||
scheduleNextHeartbeat()
|
||||
}
|
||||
}
|
||||
|
||||
// 1. Check preconditions
|
||||
guard torIsReady() else {
|
||||
@@ -228,14 +263,27 @@ final class GeohashPresenceService: ObservableObject {
|
||||
}
|
||||
|
||||
// Launch independent task for each channel's delay
|
||||
Task { @MainActor in
|
||||
// Random delay for decorrelation
|
||||
let delay = TimeInterval.random(in: self.burstMinDelay...self.burstMaxDelay)
|
||||
let taskID = UUID()
|
||||
let sleeper = self.sleeper
|
||||
let delay = TimeInterval.random(
|
||||
in: burstMinDelay...burstMaxDelay
|
||||
)
|
||||
let nanoseconds = UInt64(delay * 1_000_000_000)
|
||||
await self.sleeper(nanoseconds)
|
||||
let task = Task { @MainActor [weak self] in
|
||||
// Random delay for decorrelation
|
||||
await sleeper(nanoseconds)
|
||||
|
||||
guard let self else { return }
|
||||
guard !Task.isCancelled,
|
||||
self.started,
|
||||
self.heartbeatGeneration == generation else {
|
||||
self.pendingBroadcastTasks.removeValue(forKey: taskID)
|
||||
return
|
||||
}
|
||||
self.pendingBroadcastTasks.removeValue(forKey: taskID)
|
||||
self.broadcastPresence(for: channel.geohash)
|
||||
}
|
||||
pendingBroadcastTasks[taskID] = task
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -11,6 +11,13 @@ import BitFoundation
|
||||
import Foundation
|
||||
import Security
|
||||
|
||||
enum KeychainInstallLifecycleAction: Equatable {
|
||||
case markerPresent
|
||||
case bootstrapMarker
|
||||
case clearStaleKeys
|
||||
case retryLater
|
||||
}
|
||||
|
||||
final class KeychainManager: KeychainManagerProtocol {
|
||||
/// Default keychain for components that construct their own rather than
|
||||
/// having one injected. Under test this is an in-memory keychain: the
|
||||
@@ -41,27 +48,80 @@ final class KeychainManager: KeychainManagerProtocol {
|
||||
// Use consistent service name for all keychain items
|
||||
private let service = BitchatApp.bundleID
|
||||
private let appGroup = "group.\(BitchatApp.bundleID)"
|
||||
|
||||
// AfterFirstUnlock, not WhenUnlocked: the mesh keeps running with the
|
||||
// device locked (identity-cache saves failed with -25308 throughout
|
||||
// locked-phone testing), and a wake-on-proximity relaunch via BLE state
|
||||
// restoration must be able to read the noise keys before the user
|
||||
// unlocks. Backup/sync semantics are unchanged (not ThisDeviceOnly).
|
||||
private static let itemAccessibility = kSecAttrAccessibleAfterFirstUnlock
|
||||
// unlocks. ThisDeviceOnly prevents private identities and group keys from
|
||||
// migrating through device backups onto a second device.
|
||||
private static let itemAccessibility = kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly
|
||||
|
||||
init() {
|
||||
#if os(iOS)
|
||||
reconcileInstallLifecycle()
|
||||
migrateAccessibilityIfNeeded()
|
||||
#endif
|
||||
}
|
||||
|
||||
static func installLifecycleAction(
|
||||
containerKnowsMarker: Bool,
|
||||
markerRead: KeychainReadResult
|
||||
) -> KeychainInstallLifecycleAction {
|
||||
switch markerRead {
|
||||
case .success:
|
||||
return containerKnowsMarker ? .markerPresent : .clearStaleKeys
|
||||
case .itemNotFound:
|
||||
return .bootstrapMarker
|
||||
case .accessDenied, .deviceLocked, .authenticationFailed, .otherError:
|
||||
return .retryLater
|
||||
}
|
||||
}
|
||||
|
||||
#if os(iOS)
|
||||
|
||||
private static let installMarkerAccount = "install_lifecycle_marker"
|
||||
private static let installMarkerDefaultsKey = "keychain.installLifecycleMarker.present"
|
||||
|
||||
/// Keychain items can survive app removal while the app container and its
|
||||
/// UserDefaults do not. The first version carrying this marker bootstraps
|
||||
/// without deleting existing users' identities. On a later reinstall, a
|
||||
/// surviving keychain marker plus a missing defaults marker proves the app
|
||||
/// container was replaced, so stale secrets are removed before use.
|
||||
private func reconcileInstallLifecycle() {
|
||||
let defaults = UserDefaults.standard
|
||||
let containerKnowsMarker = defaults.bool(forKey: Self.installMarkerDefaultsKey)
|
||||
|
||||
let markerRead = retrieveDataWithResult(forKey: Self.installMarkerAccount)
|
||||
switch Self.installLifecycleAction(
|
||||
containerKnowsMarker: containerKnowsMarker,
|
||||
markerRead: markerRead
|
||||
) {
|
||||
case .markerPresent:
|
||||
defaults.set(true, forKey: Self.installMarkerDefaultsKey)
|
||||
|
||||
case .bootstrapMarker:
|
||||
if case .success = saveDataWithResult(Data([1]), forKey: Self.installMarkerAccount) {
|
||||
defaults.set(true, forKey: Self.installMarkerDefaultsKey)
|
||||
}
|
||||
|
||||
case .clearStaleKeys:
|
||||
_ = deleteAllKeychainData()
|
||||
defaults.set(true, forKey: Self.installMarkerDefaultsKey)
|
||||
|
||||
case .retryLater:
|
||||
// Do not guess that a temporarily unreadable marker is absent.
|
||||
// Leaving the defaults flag unchanged lets a later construction
|
||||
// retry once protected keychain data is available.
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
/// One-time upgrade of items created under WhenUnlocked. New saves get
|
||||
/// the right class on their own (saves are delete-then-add), but the
|
||||
/// long-lived identity keys are written once and would otherwise stay
|
||||
/// unreadable while the device is locked.
|
||||
private func migrateAccessibilityIfNeeded() {
|
||||
let flag = "keychain.accessibility.afterFirstUnlock.migrated"
|
||||
let flag = "keychain.accessibility.afterFirstUnlockThisDeviceOnly.migrated"
|
||||
guard !UserDefaults.standard.bool(forKey: flag) else { return }
|
||||
|
||||
let query: [String: Any] = [
|
||||
@@ -76,7 +136,7 @@ final class KeychainManager: KeychainManagerProtocol {
|
||||
case errSecSuccess, errSecItemNotFound:
|
||||
// Nothing to migrate on a fresh install; both are terminal.
|
||||
UserDefaults.standard.set(true, forKey: flag)
|
||||
SecureLogger.info("Keychain accessibility migrated to AfterFirstUnlock (status \(status))", category: .keychain)
|
||||
SecureLogger.info("Keychain accessibility migrated to AfterFirstUnlockThisDeviceOnly (status \(status))", category: .keychain)
|
||||
default:
|
||||
// Likely errSecInteractionNotAllowed (relaunched while locked) —
|
||||
// leave the flag unset so the next launch retries.
|
||||
@@ -492,6 +552,15 @@ final class KeychainManager: KeychainManagerProtocol {
|
||||
|
||||
SecureLogger.warning("Panic mode cleanup completed. Total items deleted: \(totalDeleted)", category: .keychain)
|
||||
|
||||
#if os(iOS)
|
||||
// The non-secret marker is intentionally recreated after a panic so a
|
||||
// later uninstall/reinstall can still be distinguished from an in-place
|
||||
// upgrade. It never restores any wiped identity or relationship data.
|
||||
if case .success = saveDataWithResult(Data([1]), forKey: Self.installMarkerAccount) {
|
||||
UserDefaults.standard.set(true, forKey: Self.installMarkerDefaultsKey)
|
||||
}
|
||||
#endif
|
||||
|
||||
return totalDeleted > 0
|
||||
}
|
||||
|
||||
@@ -526,18 +595,39 @@ final class KeychainManager: KeychainManagerProtocol {
|
||||
|
||||
/// Save data with a custom service name
|
||||
func save(key: String, data: Data, service customService: String, accessible: CFString?) {
|
||||
var query: [String: Any] = [
|
||||
let primaryKeyQuery: [String: Any] = [
|
||||
kSecClass as String: kSecClassGenericPassword,
|
||||
kSecAttrService as String: customService,
|
||||
kSecAttrAccount as String: key,
|
||||
kSecValueData as String: data
|
||||
kSecAttrAccount as String: key
|
||||
]
|
||||
if let accessible = accessible {
|
||||
query[kSecAttrAccessible as String] = accessible
|
||||
}
|
||||
var addQuery = primaryKeyQuery
|
||||
addQuery.merge([
|
||||
kSecValueData as String: data,
|
||||
kSecAttrAccessible as String: accessible ?? Self.itemAccessibility,
|
||||
kSecAttrSynchronizable as String: false
|
||||
]) { _, new in new }
|
||||
|
||||
SecItemDelete(query as CFDictionary)
|
||||
SecItemAdd(query as CFDictionary, nil)
|
||||
// Delete by the item's primary key only. Value/accessibility fields
|
||||
// are add attributes, not valid selectors for replacing an existing
|
||||
// item; including them can leave the old item in place and make the
|
||||
// subsequent add fail as a duplicate.
|
||||
let deleteStatus = SecItemDelete(primaryKeyQuery as CFDictionary)
|
||||
guard deleteStatus == errSecSuccess || deleteStatus == errSecItemNotFound else {
|
||||
SecureLogger.error(
|
||||
NSError(domain: "Keychain", code: Int(deleteStatus)),
|
||||
context: "Unable to replace custom-service keychain item",
|
||||
category: .keychain
|
||||
)
|
||||
return
|
||||
}
|
||||
let addStatus = SecItemAdd(addQuery as CFDictionary, nil)
|
||||
if addStatus != errSecSuccess {
|
||||
SecureLogger.error(
|
||||
NSError(domain: "Keychain", code: Int(addStatus)),
|
||||
context: "Unable to save custom-service keychain item",
|
||||
category: .keychain
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/// Load data from a custom service
|
||||
|
||||
@@ -154,6 +154,19 @@ final class NetworkActivationService: ObservableObject {
|
||||
.store(in: &cancellables)
|
||||
}
|
||||
|
||||
/// Stops all internet-facing work at the synchronous panic boundary.
|
||||
/// `start()` may be called again only after the full wipe commits.
|
||||
func stopForPanic() {
|
||||
cancellables.removeAll()
|
||||
started = false
|
||||
reachabilityMonitor.stop()
|
||||
activationAllowed = false
|
||||
torAutoStartDesired = false
|
||||
relayController.disconnect()
|
||||
torController.setAutoStartAllowed(false)
|
||||
applyTorState(torDesired: false)
|
||||
}
|
||||
|
||||
func setUserTorEnabled(_ enabled: Bool) {
|
||||
guard enabled != userTorEnabled else { return }
|
||||
userTorEnabled = enabled
|
||||
@@ -167,6 +180,7 @@ final class NetworkActivationService: ObservableObject {
|
||||
}
|
||||
|
||||
private func reevaluate() {
|
||||
guard started else { return }
|
||||
let allowed = effectiveAllowed()
|
||||
let torDesired = allowed && userTorEnabled
|
||||
let statusChanged = allowed != activationAllowed
|
||||
|
||||
@@ -27,6 +27,8 @@ protocol NetworkReachabilityMonitoring: AnyObject {
|
||||
var reachabilityPublisher: AnyPublisher<Bool, Never> { get }
|
||||
/// Begin monitoring. Idempotent.
|
||||
func start()
|
||||
/// Stop monitoring and discard pending debounce work. Idempotent.
|
||||
func stop()
|
||||
}
|
||||
|
||||
/// Pure debounce/decision logic for reachability, split out so it can be
|
||||
@@ -98,6 +100,7 @@ final class AlwaysReachableMonitor: NetworkReachabilityMonitoring {
|
||||
Empty(completeImmediately: false).eraseToAnyPublisher()
|
||||
}
|
||||
func start() {}
|
||||
func stop() {}
|
||||
}
|
||||
|
||||
/// `NWPathMonitor`-backed reachability. All state lives on the main actor; the
|
||||
@@ -146,6 +149,18 @@ final class NWPathReachabilityMonitor: NetworkReachabilityMonitoring {
|
||||
#endif
|
||||
}
|
||||
|
||||
func stop() {
|
||||
guard started else { return }
|
||||
started = false
|
||||
flushWorkItem?.cancel()
|
||||
flushWorkItem = nil
|
||||
#if canImport(Network)
|
||||
monitor?.pathUpdateHandler = nil
|
||||
monitor?.cancel()
|
||||
monitor = nil
|
||||
#endif
|
||||
}
|
||||
|
||||
/// Feed an observation into the debounce and publish committed changes.
|
||||
/// Exposed internally so higher layers/tests could drive it if needed.
|
||||
func ingest(reachable: Bool) {
|
||||
|
||||
@@ -226,6 +226,21 @@ final class ChatLiveVoiceCoordinator {
|
||||
assemblies.values.contains { $0.messageID == message.id }
|
||||
}
|
||||
|
||||
/// Stop every live file handle/player before the panic media directory is
|
||||
/// removed. This prevents an in-flight assembly from continuing to write
|
||||
/// through an unlinked file after the wipe returns.
|
||||
func resetForPanic() {
|
||||
for assembly in Array(assemblies.values) {
|
||||
cancelAssembly(assembly)
|
||||
}
|
||||
for player in drainingPlayers.values {
|
||||
player.stop()
|
||||
}
|
||||
drainingPlayers.removeAll(keepingCapacity: false)
|
||||
finishedBursts.removeAll(keepingCapacity: false)
|
||||
updatePublicTalkerIndicator()
|
||||
}
|
||||
|
||||
/// Called for every inbound private message: when it is the finalized
|
||||
/// voice note of a burst we assembled (matched by burst ID in the file
|
||||
/// name), swap it into the existing live bubble and report `true` so the
|
||||
|
||||
@@ -78,6 +78,7 @@ final class ChatMediaTransferCoordinator {
|
||||
|
||||
private(set) var transferIdToMessageIDs: [String: [String]] = [:]
|
||||
private(set) var messageIDToTransferId: [String: String] = [:]
|
||||
private var preparationGeneration: UInt64 = 0
|
||||
|
||||
init(context: any ChatMediaTransferContext) {
|
||||
self.context = context
|
||||
@@ -98,13 +99,14 @@ final class ChatMediaTransferCoordinator {
|
||||
)
|
||||
let messageID = message.id
|
||||
let transferId = makeTransferID(messageID: messageID)
|
||||
let generation = preparationGeneration
|
||||
|
||||
Task.detached(priority: .userInitiated) { [weak self] in
|
||||
do {
|
||||
let packet = try ChatMediaPreparation.prepareVoiceNotePacket(at: url)
|
||||
|
||||
await MainActor.run { [weak self] in
|
||||
guard let self else { return }
|
||||
guard let self, self.preparationGeneration == generation else { return }
|
||||
self.registerTransfer(transferId: transferId, messageID: messageID)
|
||||
if let peerID = targetPeer {
|
||||
self.context.sendFilePrivate(packet, to: peerID, transferId: transferId)
|
||||
@@ -116,13 +118,13 @@ final class ChatMediaTransferCoordinator {
|
||||
SecureLogger.warning("Voice note exceeds size limit (\(size) bytes)", category: .session)
|
||||
try? FileManager.default.removeItem(at: url)
|
||||
await MainActor.run { [weak self] in
|
||||
guard let self else { return }
|
||||
guard let self, self.preparationGeneration == generation else { return }
|
||||
self.handleMediaSendFailure(messageID: messageID, reason: String(localized: "content.delivery.reason.voice_too_large", comment: "Failure reason shown when a voice note exceeds the size limit"))
|
||||
}
|
||||
} catch {
|
||||
SecureLogger.error("Voice note send failed: \(error)", category: .session)
|
||||
await MainActor.run { [weak self] in
|
||||
guard let self else { return }
|
||||
guard let self, self.preparationGeneration == generation else { return }
|
||||
self.handleMediaSendFailure(messageID: messageID, reason: String(localized: "content.delivery.reason.voice_send_failed", comment: "Failure reason shown when a voice note could not be sent"))
|
||||
}
|
||||
}
|
||||
@@ -132,11 +134,15 @@ final class ChatMediaTransferCoordinator {
|
||||
#if os(iOS)
|
||||
func processThenSendImage(_ image: UIImage?) {
|
||||
guard let image else { return }
|
||||
let generation = preparationGeneration
|
||||
Task.detached { [weak self] in
|
||||
do {
|
||||
let processedURL = try ImageUtils.processImage(image)
|
||||
await MainActor.run { [weak self] in
|
||||
guard let self else { return }
|
||||
guard let self, self.preparationGeneration == generation else {
|
||||
try? FileManager.default.removeItem(at: processedURL)
|
||||
return
|
||||
}
|
||||
self.sendImage(from: processedURL)
|
||||
}
|
||||
} catch {
|
||||
@@ -147,11 +153,15 @@ final class ChatMediaTransferCoordinator {
|
||||
#elseif os(macOS)
|
||||
func processThenSendImage(from url: URL?) {
|
||||
guard let url else { return }
|
||||
let generation = preparationGeneration
|
||||
Task.detached { [weak self] in
|
||||
do {
|
||||
let processedURL = try ImageUtils.processImage(at: url)
|
||||
await MainActor.run { [weak self] in
|
||||
guard let self else { return }
|
||||
guard let self, self.preparationGeneration == generation else {
|
||||
try? FileManager.default.removeItem(at: processedURL)
|
||||
return
|
||||
}
|
||||
self.sendImage(from: processedURL)
|
||||
}
|
||||
} catch {
|
||||
@@ -170,6 +180,7 @@ final class ChatMediaTransferCoordinator {
|
||||
}
|
||||
|
||||
let targetPeer = context.selectedPrivateChatPeer
|
||||
let generation = preparationGeneration
|
||||
|
||||
do {
|
||||
try ImageUtils.validateImageSource(at: sourceURL)
|
||||
@@ -184,7 +195,10 @@ final class ChatMediaTransferCoordinator {
|
||||
let prepared = try ChatMediaPreparation.prepareImagePacket(from: sourceURL)
|
||||
|
||||
await MainActor.run { [weak self] in
|
||||
guard let self else { return }
|
||||
guard let self, self.preparationGeneration == generation else {
|
||||
try? FileManager.default.removeItem(at: prepared.outputURL)
|
||||
return
|
||||
}
|
||||
let message = self.enqueueMediaMessage(
|
||||
content: "\(MimeType.Category.image.messagePrefix)\(prepared.outputURL.lastPathComponent)",
|
||||
targetPeer: targetPeer
|
||||
@@ -201,13 +215,13 @@ final class ChatMediaTransferCoordinator {
|
||||
} catch ChatMediaPreparationError.imageTooLarge(let size) {
|
||||
SecureLogger.warning("Processed image exceeds size limit (\(size) bytes)", category: .session)
|
||||
await MainActor.run { [weak self] in
|
||||
guard let self else { return }
|
||||
guard let self, self.preparationGeneration == generation else { return }
|
||||
self.context.addSystemMessage("Image is too large to send.")
|
||||
}
|
||||
} catch {
|
||||
SecureLogger.error("Image send preparation failed: \(error)", category: .session)
|
||||
await MainActor.run { [weak self] in
|
||||
guard let self else { return }
|
||||
guard let self, self.preparationGeneration == generation else { return }
|
||||
self.context.addSystemMessage("Failed to prepare image for sending.")
|
||||
}
|
||||
}
|
||||
@@ -341,6 +355,19 @@ final class ChatMediaTransferCoordinator {
|
||||
clearTransferMapping(for: messageID)
|
||||
context.removeMessage(withID: messageID, cleanupFile: true)
|
||||
}
|
||||
|
||||
/// Invalidates detached preparation work and cancels every transfer that
|
||||
/// reached the transport. Stale tasks check the generation before they
|
||||
/// can recreate a message or send after a panic wipe.
|
||||
func resetForPanic() {
|
||||
preparationGeneration &+= 1
|
||||
let transferIDs = Set(transferIdToMessageIDs.keys)
|
||||
transferIdToMessageIDs.removeAll(keepingCapacity: false)
|
||||
messageIDToTransferId.removeAll(keepingCapacity: false)
|
||||
for transferID in transferIDs {
|
||||
context.cancelTransfer(transferID)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private extension ChatMediaTransferCoordinator {
|
||||
|
||||
@@ -89,6 +89,26 @@ import UIKit
|
||||
#endif
|
||||
import UniformTypeIdentifiers
|
||||
|
||||
struct PanicNetworkLifecycle {
|
||||
let stop: @MainActor () -> Void
|
||||
let restart: @MainActor () -> Void
|
||||
|
||||
static let noop = PanicNetworkLifecycle(stop: {}, restart: {})
|
||||
|
||||
static var live: PanicNetworkLifecycle {
|
||||
PanicNetworkLifecycle(
|
||||
stop: {
|
||||
GeohashPresenceService.shared.stopForPanic()
|
||||
NetworkActivationService.shared.stopForPanic()
|
||||
},
|
||||
restart: {
|
||||
NetworkActivationService.shared.start()
|
||||
GeohashPresenceService.shared.start()
|
||||
}
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/// Manages the application state and business logic for BitChat.
|
||||
/// Acts as the primary coordinator between UI components and backend services,
|
||||
/// implementing the BitchatDelegate protocol to handle network events.
|
||||
@@ -142,6 +162,8 @@ final class ChatViewModel: ObservableObject, BitchatDelegate, TransportEventDele
|
||||
@Published var currentColorScheme: ColorScheme = .light
|
||||
@Published var currentTheme: AppTheme = .matrix
|
||||
@Published var isConnected = false
|
||||
@Published private(set) var panicRecoveryBlocked = false
|
||||
var networkActivationAllowed: Bool { !panicRecoveryBlocked }
|
||||
@Published var nickname: String = "" {
|
||||
didSet {
|
||||
// Trim whitespace whenever nickname is set; whitespace-only becomes ""
|
||||
@@ -151,7 +173,7 @@ final class ChatViewModel: ObservableObject, BitchatDelegate, TransportEventDele
|
||||
return
|
||||
}
|
||||
// Update mesh service nickname if it's initialized
|
||||
if !meshService.myPeerID.isEmpty {
|
||||
if !isPanicResetting, !meshService.myPeerID.isEmpty {
|
||||
meshService.setNickname(nickname)
|
||||
}
|
||||
}
|
||||
@@ -177,7 +199,10 @@ final class ChatViewModel: ObservableObject, BitchatDelegate, TransportEventDele
|
||||
lazy var privateConversationCoordinator = ChatPrivateConversationCoordinator(context: self)
|
||||
lazy var nostrCoordinator = ChatNostrCoordinator(context: self)
|
||||
lazy var mediaTransferCoordinator = ChatMediaTransferCoordinator(context: self)
|
||||
lazy var liveVoiceCoordinator = ChatLiveVoiceCoordinator(context: self)
|
||||
lazy var liveVoiceCoordinator = ChatLiveVoiceCoordinator(
|
||||
context: self,
|
||||
sweepsOnInit: !TestEnvironment.isRunningTests
|
||||
)
|
||||
lazy var verificationCoordinator = ChatVerificationCoordinator(context: self)
|
||||
lazy var groupCoordinator = ChatGroupCoordinator(context: self)
|
||||
lazy var vouchCoordinator = ChatVouchCoordinator(context: self)
|
||||
@@ -292,6 +317,9 @@ final class ChatViewModel: ObservableObject, BitchatDelegate, TransportEventDele
|
||||
var nostrRelayManager: NostrRelayManager?
|
||||
private let userDefaults = UserDefaults.standard
|
||||
let keychain: KeychainManagerProtocol
|
||||
private let panicRecoveryOperations: PanicRecoveryOperations
|
||||
private let panicNetworkLifecycle: PanicNetworkLifecycle
|
||||
private var isPanicResetting = false
|
||||
/// Private group membership: keys in the keychain, metadata on disk.
|
||||
let groupStore: GroupStore
|
||||
private let nicknameKey = "bitchat.nickname"
|
||||
@@ -769,7 +797,34 @@ final class ChatViewModel: ObservableObject, BitchatDelegate, TransportEventDele
|
||||
locationPresenceStore: LocationPresenceStore? = nil,
|
||||
locationManager: LocationChannelManager = .shared
|
||||
) {
|
||||
let meshService = BLEService(keychain: keychain, idBridge: idBridge, identityManager: identityManager)
|
||||
let livePanicRecoveryOperations = PanicRecoveryOperations.live()
|
||||
let startSuspendedForRecovery: Bool
|
||||
do {
|
||||
startSuspendedForRecovery =
|
||||
try livePanicRecoveryOperations.isPending()
|
||||
} catch {
|
||||
startSuspendedForRecovery = true
|
||||
}
|
||||
// Preserve the preflight decision used to defer CoreBluetooth. A
|
||||
// transiently successful second read must not skip recovery and leave
|
||||
// the service permanently suspended without running the wipe.
|
||||
let panicRecoveryOperations = PanicRecoveryOperations(
|
||||
isPending: {
|
||||
if startSuspendedForRecovery {
|
||||
return true
|
||||
}
|
||||
return try livePanicRecoveryOperations.isPending()
|
||||
},
|
||||
begin: livePanicRecoveryOperations.begin,
|
||||
wipeMedia: livePanicRecoveryOperations.wipeMedia,
|
||||
complete: livePanicRecoveryOperations.complete
|
||||
)
|
||||
let meshService = BLEService(
|
||||
keychain: keychain,
|
||||
idBridge: idBridge,
|
||||
identityManager: identityManager,
|
||||
startSuspendedForPanicRecovery: startSuspendedForRecovery
|
||||
)
|
||||
meshService.sfMetrics = .shared
|
||||
self.init(
|
||||
keychain: keychain,
|
||||
@@ -781,7 +836,9 @@ final class ChatViewModel: ObservableObject, BitchatDelegate, TransportEventDele
|
||||
locationPresenceStore: locationPresenceStore ?? LocationPresenceStore(),
|
||||
locationManager: locationManager,
|
||||
outboxStore: MessageOutboxStore(keychain: keychain),
|
||||
sfMetrics: .shared
|
||||
sfMetrics: .shared,
|
||||
panicRecoveryOperations: panicRecoveryOperations,
|
||||
panicNetworkLifecycle: .live
|
||||
)
|
||||
}
|
||||
|
||||
@@ -799,7 +856,10 @@ final class ChatViewModel: ObservableObject, BitchatDelegate, TransportEventDele
|
||||
locationManager: LocationChannelManager = .shared,
|
||||
readReceiptsDefaults: UserDefaults? = nil,
|
||||
outboxStore: MessageOutboxStore? = nil,
|
||||
sfMetrics: StoreAndForwardMetrics? = nil
|
||||
sfMetrics: StoreAndForwardMetrics? = nil,
|
||||
panicMediaWipe: (() throws -> Void)? = nil,
|
||||
panicRecoveryOperations: PanicRecoveryOperations? = nil,
|
||||
panicNetworkLifecycle: PanicNetworkLifecycle = .noop
|
||||
) {
|
||||
let conversations = conversations ?? ConversationStore()
|
||||
let peerIdentityStore = peerIdentityStore ?? PeerIdentityStore()
|
||||
@@ -814,6 +874,9 @@ final class ChatViewModel: ObservableObject, BitchatDelegate, TransportEventDele
|
||||
)
|
||||
|
||||
self.keychain = keychain
|
||||
self.panicRecoveryOperations = panicRecoveryOperations
|
||||
?? .ephemeral(wipeMedia: panicMediaWipe ?? {})
|
||||
self.panicNetworkLifecycle = panicNetworkLifecycle
|
||||
self.groupStore = GroupStore(keychain: keychain)
|
||||
self.idBridge = idBridge
|
||||
self.identityManager = identityManager
|
||||
@@ -849,8 +912,32 @@ final class ChatViewModel: ObservableObject, BitchatDelegate, TransportEventDele
|
||||
}
|
||||
.store(in: &cancellables)
|
||||
|
||||
let recoveryRequired: Bool
|
||||
do {
|
||||
recoveryRequired = try self.panicRecoveryOperations.isPending()
|
||||
} catch {
|
||||
// Failure to read the latch cannot fail open. Re-run the complete
|
||||
// transaction; a persistent storage failure leaves services
|
||||
// blocked below.
|
||||
recoveryRequired = true
|
||||
SecureLogger.error(
|
||||
"Could not read panic-recovery state; retrying the full wipe before startup: \(error)",
|
||||
category: .security
|
||||
)
|
||||
}
|
||||
|
||||
if recoveryRequired {
|
||||
SecureLogger.warning(
|
||||
"Pending panic recovery detected; wiping before runtime services start",
|
||||
category: .security
|
||||
)
|
||||
_ = panicClearAllData(restartServices: false)
|
||||
}
|
||||
|
||||
if networkActivationAllowed {
|
||||
ChatViewModelBootstrapper(viewModel: self).configure()
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Deinitialization
|
||||
|
||||
@@ -1153,8 +1240,33 @@ final class ChatViewModel: ObservableObject, BitchatDelegate, TransportEventDele
|
||||
|
||||
// PANIC: Emergency data clearing for activist safety
|
||||
@MainActor
|
||||
func panicClearAllData() {
|
||||
// Messages are processed immediately - nothing to flush
|
||||
@discardableResult
|
||||
func panicClearAllData(restartServices: Bool = true) -> Bool {
|
||||
panicRecoveryBlocked = true
|
||||
isPanicResetting = true
|
||||
defer { isPanicResetting = false }
|
||||
|
||||
// Stop internet and location-presence work before clearing identity or
|
||||
// state. These services cancel their subscriptions and delayed tasks,
|
||||
// so old callbacks cannot reconnect during the transaction.
|
||||
panicNetworkLifecycle.stop()
|
||||
|
||||
// Establish both independent durable intents before erasing anything.
|
||||
// `wipeMedia` will still attempt deletion if neither write succeeds.
|
||||
let recoveryIntent = panicRecoveryOperations.begin()
|
||||
|
||||
// Quiesce the mesh before clearing stores. Identity replacement below
|
||||
// deliberately stays stopped until media deletion and marker commit.
|
||||
if let bleService = meshService as? BLEService {
|
||||
bleService.suspendForPanicReset()
|
||||
} else {
|
||||
meshService.emergencyDisconnectAll()
|
||||
}
|
||||
|
||||
// Invalidate detached media preparation and close live capture file
|
||||
// handles before clearing state or removing the media directory.
|
||||
mediaTransferCoordinator.resetForPanic()
|
||||
liveVoiceCoordinator.resetForPanic()
|
||||
|
||||
// Clear all messages (public timelines and private chats live in the
|
||||
// single-writer ConversationStore; the derived `messages` view and
|
||||
@@ -1176,7 +1288,7 @@ final class ChatViewModel: ObservableObject, BitchatDelegate, TransportEventDele
|
||||
|
||||
// Reset nickname to anonymous
|
||||
nickname = "anon\(Int.random(in: 1000...9999))"
|
||||
saveNickname()
|
||||
userDefaults.set(nickname, forKey: nicknameKey)
|
||||
|
||||
// Clear favorites and peer mappings
|
||||
// Clear through SecureIdentityStateManager instead of directly
|
||||
@@ -1248,78 +1360,68 @@ final class ChatViewModel: ObservableObject, BitchatDelegate, TransportEventDele
|
||||
// Clear Nostr identity associations
|
||||
idBridge.clearAllAssociations()
|
||||
|
||||
// Disconnect from all peers and clear persistent identity
|
||||
// This will force creation of a new identity (new fingerprint) on next launch
|
||||
meshService.emergencyDisconnectAll()
|
||||
// Replace the BLE identity while keeping the radio stopped. It may
|
||||
// reopen only after the durable panic transaction commits.
|
||||
if let bleService = meshService as? BLEService {
|
||||
bleService.resetIdentityForPanic(currentNickname: nickname)
|
||||
bleService.resetIdentityForPanic(
|
||||
currentNickname: nickname,
|
||||
restartServices: false
|
||||
)
|
||||
} else {
|
||||
meshService.setNickname(nickname)
|
||||
}
|
||||
|
||||
// No need to force UserDefaults synchronization
|
||||
// The wipe must finish before this security action returns. A detached
|
||||
// task could otherwise lose a race with a new capture or app exit and
|
||||
// leave pre-panic media behind.
|
||||
let panicCompleted: Bool
|
||||
do {
|
||||
try panicRecoveryOperations.wipeMedia(recoveryIntent)
|
||||
try panicRecoveryOperations.complete()
|
||||
panicCompleted = true
|
||||
SecureLogger.info("🗑️ Deleted all media files during panic clear", category: .session)
|
||||
} catch {
|
||||
panicCompleted = false
|
||||
SecureLogger.error(
|
||||
"Panic transaction did not commit; services remain stopped: \(error)",
|
||||
category: .security
|
||||
)
|
||||
}
|
||||
panicRecoveryBlocked = !panicCompleted
|
||||
|
||||
// Reinitialize Nostr with new identity
|
||||
// This will generate new Nostr keys derived from new Noise keys.
|
||||
// Skipped under tests: connecting the shared relay singleton starts
|
||||
// real network/reconnect work that never completes and would keep the
|
||||
// test process alive (the singleton, unlike a discardable instance, is
|
||||
// never deallocated to cancel it).
|
||||
// BCH-01-013: Clear iOS app switcher snapshots. Keep tests away from
|
||||
// the host user's real cache tree just as the default media wipe does.
|
||||
#if os(iOS)
|
||||
if !TestEnvironment.isRunningTests {
|
||||
Task { @MainActor in
|
||||
// Small delay to ensure cleanup completes
|
||||
try? await Task.sleep(nanoseconds: TransportConfig.uiAsyncShortSleepNs) // 0.1 seconds
|
||||
Self.clearAppSwitcherSnapshots()
|
||||
}
|
||||
#endif
|
||||
|
||||
// Reinitialize Nostr relay manager with new identity. Reuse the
|
||||
// shared singleton — every other component (NostrTransport, geohash
|
||||
// subscriptions, AppRuntime observers) is bound to `.shared`, so
|
||||
// creating a fresh instance here would split relay state and leave
|
||||
// sends running against a disconnected manager.
|
||||
guard panicCompleted else { return false }
|
||||
|
||||
if let bleService = meshService as? BLEService {
|
||||
// Startup recovery reopens admission but leaves actual service
|
||||
// start to the bootstrapper immediately after this method.
|
||||
bleService.completePanicReset(
|
||||
restartServices: restartServices
|
||||
)
|
||||
}
|
||||
|
||||
if restartServices {
|
||||
// All persistent state and media are gone. Bring each service back
|
||||
// only now, under the new identity.
|
||||
if !(meshService is BLEService) {
|
||||
meshService.startServices()
|
||||
}
|
||||
|
||||
if !TestEnvironment.isRunningTests {
|
||||
nostrRelayManager = NostrRelayManager.shared
|
||||
setupNostrMessageHandling()
|
||||
nostrRelayManager?.connect()
|
||||
}
|
||||
panicNetworkLifecycle.restart()
|
||||
}
|
||||
|
||||
// Delete ALL media files (incoming and outgoing) in background
|
||||
Task.detached(priority: .utility) {
|
||||
// Skipped under tests: the test process shares the user's real
|
||||
// ~/Library/Application Support/files tree, and this detached
|
||||
// utility-priority wipe fires at a nondeterministic time —
|
||||
// deleting media that concurrently running tests (e.g. the
|
||||
// sendImage flow) just wrote there, and the developer's real
|
||||
// app data with it.
|
||||
guard !TestEnvironment.isRunningTests else { return }
|
||||
do {
|
||||
let base = try FileManager.default.url(for: .applicationSupportDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
|
||||
let filesDir = base.appendingPathComponent("files", isDirectory: true)
|
||||
|
||||
// Delete the entire files directory and recreate it
|
||||
if FileManager.default.fileExists(atPath: filesDir.path) {
|
||||
try FileManager.default.removeItem(at: filesDir)
|
||||
SecureLogger.info("🗑️ Deleted all media files during panic clear", category: .session)
|
||||
}
|
||||
|
||||
// Recreate empty directory structure
|
||||
try FileManager.default.createDirectory(at: filesDir, withIntermediateDirectories: true, attributes: nil)
|
||||
try FileManager.default.createDirectory(at: filesDir.appendingPathComponent("voicenotes/incoming", isDirectory: true), withIntermediateDirectories: true, attributes: nil)
|
||||
try FileManager.default.createDirectory(at: filesDir.appendingPathComponent("voicenotes/outgoing", isDirectory: true), withIntermediateDirectories: true, attributes: nil)
|
||||
try FileManager.default.createDirectory(at: filesDir.appendingPathComponent("images/incoming", isDirectory: true), withIntermediateDirectories: true, attributes: nil)
|
||||
try FileManager.default.createDirectory(at: filesDir.appendingPathComponent("images/outgoing", isDirectory: true), withIntermediateDirectories: true, attributes: nil)
|
||||
try FileManager.default.createDirectory(at: filesDir.appendingPathComponent("files/incoming", isDirectory: true), withIntermediateDirectories: true, attributes: nil)
|
||||
try FileManager.default.createDirectory(at: filesDir.appendingPathComponent("files/outgoing", isDirectory: true), withIntermediateDirectories: true, attributes: nil)
|
||||
} catch {
|
||||
SecureLogger.error("Failed to clear media files during panic: \(error)", category: .session)
|
||||
}
|
||||
|
||||
// BCH-01-013: Clear iOS app switcher snapshots
|
||||
// These are stored in Library/Caches/Snapshots/<bundle_id>/
|
||||
#if os(iOS)
|
||||
Self.clearAppSwitcherSnapshots()
|
||||
#endif
|
||||
}
|
||||
|
||||
// Force immediate UI update for panic mode
|
||||
// UI updates immediately - no flushing needed
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
/// BCH-01-013: Clear iOS app switcher snapshots during panic mode
|
||||
|
||||
@@ -188,8 +188,25 @@ final class VoiceRecordingViewModel: ObservableObject {
|
||||
|
||||
Task {
|
||||
let finalDuration = Date().timeIntervalSince(startDate)
|
||||
if let url = await session.finish(),
|
||||
isValidRecording(at: url, duration: finalDuration) {
|
||||
if let url = await session.finish() {
|
||||
// Panic and a newer hold both invalidate this completion.
|
||||
// Never route an old recording using a post-panic target.
|
||||
guard generation == holdGeneration else {
|
||||
try? FileManager.default.removeItem(at: url)
|
||||
return
|
||||
}
|
||||
guard isValidRecording(
|
||||
at: url,
|
||||
duration: finalDuration
|
||||
) else {
|
||||
guard state == .idle else { return }
|
||||
state = .error(
|
||||
message: finalDuration < VoiceRecorder.minRecordingDuration
|
||||
? "Recording is too short."
|
||||
: "Recording failed to save."
|
||||
)
|
||||
return
|
||||
}
|
||||
completion(url)
|
||||
} else {
|
||||
guard generation == holdGeneration, state == .idle else { return }
|
||||
@@ -206,6 +223,17 @@ final class VoiceRecordingViewModel: ObservableObject {
|
||||
finish(completion: nil)
|
||||
}
|
||||
|
||||
/// Invalidates in-flight permission/start/finalize callbacks and tears
|
||||
/// down an active microphone before the panic transaction continues.
|
||||
func panicWipe() {
|
||||
holdGeneration &+= 1
|
||||
let session = activeSession
|
||||
activeSession = nil
|
||||
state = .idle
|
||||
isLiveStreaming = false
|
||||
session?.panicCancelSynchronously()
|
||||
}
|
||||
|
||||
private func isValidRecording(at url: URL, duration: TimeInterval) -> Bool {
|
||||
if let attributes = try? FileManager.default.attributesOfItem(atPath: url.path),
|
||||
let fileSize = attributes[.size] as? NSNumber,
|
||||
|
||||
@@ -79,6 +79,9 @@ struct ContentView: View {
|
||||
voiceRecordingVM.sessionProvider = { [weak conversationUIModel] in
|
||||
conversationUIModel?.makeVoiceCaptureSession() ?? VoiceNoteCaptureSession()
|
||||
}
|
||||
appChromeModel.setPanicPreparation { [weak voiceRecordingVM] in
|
||||
voiceRecordingVM?.panicWipe()
|
||||
}
|
||||
#if os(macOS)
|
||||
DispatchQueue.main.async {
|
||||
isNicknameFieldFocused = false
|
||||
@@ -229,6 +232,7 @@ struct ContentView: View {
|
||||
}
|
||||
.onDisappear {
|
||||
autocompleteDebounceTimer?.invalidate()
|
||||
appChromeModel.setPanicPreparation(nil)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -99,95 +99,6 @@ struct BLEServiceCoreTests {
|
||||
#expect(ble.currentPeerSnapshots().isEmpty)
|
||||
}
|
||||
|
||||
@Test
|
||||
func unsignedAndBadSignatureLeaveDoNotEvictOrRelayClaimedPeer() async throws {
|
||||
let ble = makeService()
|
||||
let alice = NoiseEncryptionService(keychain: MockKeychain())
|
||||
let mallory = NoiseEncryptionService(keychain: MockKeychain())
|
||||
let alicePeerID = PeerID(publicKey: alice.getStaticPublicKeyData())
|
||||
let outbound = OutboundPacketTap()
|
||||
ble._test_onOutboundPacket = outbound.record
|
||||
|
||||
let unsigned = makeLeavePacket(sender: alicePeerID, marker: "unsigned")
|
||||
ble._test_handlePacket(
|
||||
unsigned,
|
||||
fromPeerID: alicePeerID,
|
||||
signingPublicKey: alice.getSigningPublicKeyData()
|
||||
)
|
||||
|
||||
let unsignedRelayed = await TestHelpers.waitUntil(
|
||||
{ outbound.count(ofType: .leave) > 0 },
|
||||
timeout: TestConstants.shortTimeout
|
||||
)
|
||||
#expect(!unsignedRelayed)
|
||||
#expect(ble.currentPeerSnapshots().contains { $0.peerID == alicePeerID })
|
||||
|
||||
let badSignature = try #require(
|
||||
mallory.signPacket(makeLeavePacket(sender: alicePeerID, marker: "bad-signature"))
|
||||
)
|
||||
ble._test_handlePacket(
|
||||
badSignature,
|
||||
fromPeerID: alicePeerID,
|
||||
signingPublicKey: alice.getSigningPublicKeyData()
|
||||
)
|
||||
|
||||
let badSignatureRelayed = await TestHelpers.waitUntil(
|
||||
{ outbound.count(ofType: .leave) > 0 },
|
||||
timeout: TestConstants.shortTimeout
|
||||
)
|
||||
#expect(!badSignatureRelayed)
|
||||
#expect(ble.currentPeerSnapshots().contains { $0.peerID == alicePeerID })
|
||||
}
|
||||
|
||||
@Test
|
||||
func validSignedLeaveEvictsSessionAndRelays() async throws {
|
||||
let ble = makeService()
|
||||
let alice = NoiseEncryptionService(keychain: MockKeychain())
|
||||
let alicePeerID = PeerID(publicKey: alice.getStaticPublicKeyData())
|
||||
|
||||
// Establish a real session so the leave regression also verifies that
|
||||
// stale secure-delivery state is retired, not just the peer-list row.
|
||||
let message1 = try ble._test_noiseInitiateHandshake(with: alicePeerID)
|
||||
let message2 = try #require(
|
||||
try alice.processHandshakeMessage(from: ble.myPeerID, message: message1)
|
||||
)
|
||||
let message3 = try #require(
|
||||
try ble._test_noiseProcessHandshakeMessage(from: alicePeerID, message: message2)
|
||||
)
|
||||
_ = try alice.processHandshakeMessage(from: ble.myPeerID, message: message3)
|
||||
#expect(ble.canDeliverSecurely(to: alicePeerID))
|
||||
let centralUUID = "central-valid-leave"
|
||||
ble._test_bindCentral(centralUUID, to: alicePeerID)
|
||||
ble._test_markNoiseAuthenticatedCentral(centralUUID, to: alicePeerID)
|
||||
#expect(ble._test_isNoiseAuthenticatedCentral(centralUUID, for: alicePeerID))
|
||||
|
||||
let outbound = OutboundPacketTap()
|
||||
ble._test_onOutboundPacket = outbound.record
|
||||
let signedLeave = try #require(
|
||||
alice.signPacket(makeLeavePacket(sender: alicePeerID, marker: "valid"))
|
||||
)
|
||||
ble._test_handlePacket(
|
||||
signedLeave,
|
||||
fromPeerID: alicePeerID,
|
||||
signingPublicKey: alice.getSigningPublicKeyData()
|
||||
)
|
||||
|
||||
let evicted = await TestHelpers.waitUntil(
|
||||
{
|
||||
!ble.currentPeerSnapshots().contains { $0.peerID == alicePeerID }
|
||||
&& !ble.canDeliverSecurely(to: alicePeerID)
|
||||
&& !ble._test_isNoiseAuthenticatedCentral(centralUUID, for: alicePeerID)
|
||||
},
|
||||
timeout: TestConstants.longTimeout
|
||||
)
|
||||
#expect(evicted)
|
||||
let relayed = await TestHelpers.waitUntil(
|
||||
{ outbound.count(ofType: .leave) == 1 },
|
||||
timeout: TestConstants.longTimeout
|
||||
)
|
||||
#expect(relayed)
|
||||
}
|
||||
|
||||
@Test
|
||||
func ingressAllowsRelayedSenderOnBoundLink() async throws {
|
||||
let ble = makeService()
|
||||
@@ -661,6 +572,26 @@ struct BLEServiceCoreTests {
|
||||
#expect(ble.myPeerID == PeerID(str: newFingerprint.prefix(16)))
|
||||
}
|
||||
|
||||
@Test
|
||||
func panicSuspension_dropsLateOutboundWorkUntilCommit() async {
|
||||
let ble = makeService()
|
||||
let outbound = OutboundPacketTap()
|
||||
ble._test_onOutboundPacket = outbound.record
|
||||
let packet = makePublicPacket(
|
||||
content: "late callback",
|
||||
sender: ble.myPeerID,
|
||||
timestamp: UInt64(Date().timeIntervalSince1970 * 1000)
|
||||
)
|
||||
|
||||
ble.suspendForPanicReset()
|
||||
ble.sendPacket(packet)
|
||||
#expect(outbound.count(ofType: .message) == 0)
|
||||
|
||||
ble.completePanicReset(restartServices: false)
|
||||
ble.sendPacket(packet)
|
||||
#expect(outbound.count(ofType: .message) == 1)
|
||||
}
|
||||
|
||||
@Test
|
||||
func modifiedServices_rediscoverWhenBitChatServiceIsInvalidated() async throws {
|
||||
let otherService = CBUUID(string: "0000180F-0000-1000-8000-00805F9B34FB")
|
||||
@@ -779,18 +710,6 @@ private func makePublicPacket(content: String, sender: PeerID, timestamp: UInt64
|
||||
)
|
||||
}
|
||||
|
||||
private func makeLeavePacket(sender: PeerID, marker: String) -> BitchatPacket {
|
||||
BitchatPacket(
|
||||
type: MessageType.leave.rawValue,
|
||||
senderID: Data(hexString: sender.id) ?? Data(),
|
||||
recipientID: nil,
|
||||
timestamp: UInt64(Date().timeIntervalSince1970 * 1000),
|
||||
payload: Data(marker.utf8),
|
||||
signature: nil,
|
||||
ttl: TransportConfig.messageTTLDefault
|
||||
)
|
||||
}
|
||||
|
||||
private final class PublicCaptureDelegate: BitchatDelegate {
|
||||
private let lock = NSLock()
|
||||
private(set) var publicMessages: [BitchatMessage] = []
|
||||
|
||||
@@ -188,6 +188,21 @@ struct ChatMediaTransferCoordinatorContextTests {
|
||||
#expect(coordinator.messageIDToTransferId.isEmpty)
|
||||
}
|
||||
|
||||
@Test @MainActor
|
||||
func resetForPanic_cancelsEveryTransportTransferAndClearsMappings() {
|
||||
let context = MockChatMediaTransferContext()
|
||||
let coordinator = ChatMediaTransferCoordinator(context: context)
|
||||
coordinator.registerTransfer(transferId: "t1", messageID: "m1")
|
||||
coordinator.registerTransfer(transferId: "t1", messageID: "m2")
|
||||
coordinator.registerTransfer(transferId: "t2", messageID: "m3")
|
||||
|
||||
coordinator.resetForPanic()
|
||||
|
||||
#expect(Set(context.cancelledTransfers) == Set(["t1", "t2"]))
|
||||
#expect(coordinator.transferIdToMessageIDs.isEmpty)
|
||||
#expect(coordinator.messageIDToTransferId.isEmpty)
|
||||
}
|
||||
|
||||
@Test @MainActor
|
||||
func sendVoiceNote_blockedContextRemovesFileAndExplains() async throws {
|
||||
let context = MockChatMediaTransferContext()
|
||||
|
||||
@@ -15,7 +15,11 @@ import BitFoundation
|
||||
|
||||
/// Creates a ChatViewModel with mock dependencies for testing
|
||||
@MainActor
|
||||
private func makeTestableViewModel() -> (viewModel: ChatViewModel, transport: MockTransport) {
|
||||
private func makeTestableViewModel(
|
||||
panicMediaWipe: (() throws -> Void)? = nil,
|
||||
panicRecoveryOperations: PanicRecoveryOperations? = nil,
|
||||
panicNetworkLifecycle: PanicNetworkLifecycle = .noop
|
||||
) -> (viewModel: ChatViewModel, transport: MockTransport) {
|
||||
let keychain = MockKeychain()
|
||||
let keychainHelper = MockKeychainHelper()
|
||||
let idBridge = NostrIdentityBridge(keychain: keychainHelper)
|
||||
@@ -26,7 +30,10 @@ private func makeTestableViewModel() -> (viewModel: ChatViewModel, transport: Mo
|
||||
keychain: keychain,
|
||||
idBridge: idBridge,
|
||||
identityManager: identityManager,
|
||||
transport: transport
|
||||
transport: transport,
|
||||
panicMediaWipe: panicMediaWipe,
|
||||
panicRecoveryOperations: panicRecoveryOperations,
|
||||
panicNetworkLifecycle: panicNetworkLifecycle
|
||||
)
|
||||
|
||||
return (viewModel, transport)
|
||||
@@ -1116,6 +1123,92 @@ struct ChatViewModelBluetoothTests {
|
||||
|
||||
struct ChatViewModelPanicTests {
|
||||
|
||||
@Test @MainActor
|
||||
func panicClearAllData_finishesMediaWipeBeforeReturning() {
|
||||
var wipeFinished = false
|
||||
let (viewModel, _) = makeTestableViewModel(panicMediaWipe: {
|
||||
wipeFinished = true
|
||||
})
|
||||
|
||||
viewModel.panicClearAllData()
|
||||
|
||||
#expect(wipeFinished)
|
||||
}
|
||||
|
||||
@Test @MainActor
|
||||
func panicClearAllData_stopsNetworkBeforeWipeAndRestartsAfterCommit() {
|
||||
var events: [String] = []
|
||||
let lifecycle = PanicNetworkLifecycle(
|
||||
stop: { events.append("stop") },
|
||||
restart: { events.append("restart") }
|
||||
)
|
||||
let (viewModel, _) = makeTestableViewModel(
|
||||
panicMediaWipe: { events.append("wipe") },
|
||||
panicNetworkLifecycle: lifecycle
|
||||
)
|
||||
|
||||
let completed = viewModel.panicClearAllData()
|
||||
|
||||
#expect(completed)
|
||||
#expect(events == ["stop", "wipe", "restart"])
|
||||
#expect(viewModel.networkActivationAllowed)
|
||||
}
|
||||
|
||||
@Test @MainActor
|
||||
func pendingPanicRecoveryCompletesBeforeTransportBootstrap() {
|
||||
var events: [String] = []
|
||||
let operations = PanicRecoveryOperations(
|
||||
isPending: {
|
||||
events.append("read")
|
||||
return true
|
||||
},
|
||||
begin: {
|
||||
events.append("begin")
|
||||
return PanicRecoveryIntent(
|
||||
fileMarkerEstablished: true,
|
||||
externalMarkerEstablished: false
|
||||
)
|
||||
},
|
||||
wipeMedia: { _ in events.append("wipe") },
|
||||
complete: { events.append("complete") }
|
||||
)
|
||||
|
||||
let (viewModel, transport) = makeTestableViewModel(
|
||||
panicRecoveryOperations: operations
|
||||
)
|
||||
|
||||
#expect(events == ["read", "begin", "wipe", "complete"])
|
||||
#expect(transport.emergencyDisconnectCallCount == 1)
|
||||
#expect(transport.startServicesCallCount == 1)
|
||||
#expect(viewModel.networkActivationAllowed)
|
||||
}
|
||||
|
||||
@Test @MainActor
|
||||
func failedStartupRecoveryLeavesTransportAndNetworkBlocked() {
|
||||
enum WipeFailure: Error { case failed }
|
||||
var completedMarker = false
|
||||
let operations = PanicRecoveryOperations(
|
||||
isPending: { true },
|
||||
begin: {
|
||||
PanicRecoveryIntent(
|
||||
fileMarkerEstablished: true,
|
||||
externalMarkerEstablished: false
|
||||
)
|
||||
},
|
||||
wipeMedia: { _ in throw WipeFailure.failed },
|
||||
complete: { completedMarker = true }
|
||||
)
|
||||
|
||||
let (viewModel, transport) = makeTestableViewModel(
|
||||
panicRecoveryOperations: operations
|
||||
)
|
||||
|
||||
#expect(!completedMarker)
|
||||
#expect(transport.emergencyDisconnectCallCount == 1)
|
||||
#expect(transport.startServicesCallCount == 0)
|
||||
#expect(!viewModel.networkActivationAllowed)
|
||||
}
|
||||
|
||||
@Test @MainActor
|
||||
func panicClearAllData_delegatesToTransport() async {
|
||||
let (viewModel, transport) = makeTestableViewModel()
|
||||
|
||||
@@ -12,15 +12,8 @@ struct NoiseCoverageTests {
|
||||
private let bobStaticKey = Curve25519.KeyAgreement.PrivateKey()
|
||||
private let charlieStaticKey = Curve25519.KeyAgreement.PrivateKey()
|
||||
|
||||
// Manager test dictionaries are keyed by the remote peer. Keep the
|
||||
// historical names, but derive each wire ID from the static key that the
|
||||
// corresponding manager authenticates during the handshake.
|
||||
private var alicePeerID: PeerID {
|
||||
PeerID(publicKey: bobStaticKey.publicKey.rawRepresentation)
|
||||
}
|
||||
private var bobPeerID: PeerID {
|
||||
PeerID(publicKey: aliceStaticKey.publicKey.rawRepresentation)
|
||||
}
|
||||
private let alicePeerID = PeerID(str: "0011223344556677")
|
||||
private let bobPeerID = PeerID(str: "8899aabbccddeeff")
|
||||
private let charliePeerID = PeerID(str: "fedcba9876543210")
|
||||
|
||||
@Test("Protocol metadata and handshake patterns expose expected values")
|
||||
|
||||
@@ -1,10 +1,31 @@
|
||||
import Foundation
|
||||
import Testing
|
||||
import BitFoundation
|
||||
@testable import bitchat
|
||||
|
||||
@Suite("PreviewKeychainManager Tests")
|
||||
struct PreviewKeychainManagerTests {
|
||||
|
||||
@Test("Install lifecycle distinguishes upgrade, reinstall, bootstrap, and unreadable keychain")
|
||||
func installLifecycleDecision() {
|
||||
#expect(KeychainManager.installLifecycleAction(
|
||||
containerKnowsMarker: true,
|
||||
markerRead: .success(Data([1]))
|
||||
) == .markerPresent)
|
||||
#expect(KeychainManager.installLifecycleAction(
|
||||
containerKnowsMarker: false,
|
||||
markerRead: .success(Data([1]))
|
||||
) == .clearStaleKeys)
|
||||
#expect(KeychainManager.installLifecycleAction(
|
||||
containerKnowsMarker: false,
|
||||
markerRead: .itemNotFound
|
||||
) == .bootstrapMarker)
|
||||
#expect(KeychainManager.installLifecycleAction(
|
||||
containerKnowsMarker: false,
|
||||
markerRead: .deviceLocked
|
||||
) == .retryLater)
|
||||
}
|
||||
|
||||
@Test("Preview keychain manager stores identity and service-scoped data in memory")
|
||||
func previewKeychainManagerRoundTripsData() {
|
||||
let manager = PreviewKeychainManager()
|
||||
|
||||
@@ -370,6 +370,132 @@ struct BLEFileTransferHandlerTests {
|
||||
#expect(!FileManager.default.fileExists(atPath: evictable.path))
|
||||
}
|
||||
|
||||
@Test
|
||||
func panicWipeDeletesEveryManagedMediaFileAndRecreatesEmptyDirectories() throws {
|
||||
let base = FileManager.default.temporaryDirectory
|
||||
.appendingPathComponent("panic-media-wipe-\(UUID().uuidString)", isDirectory: true)
|
||||
defer { try? FileManager.default.removeItem(at: base) }
|
||||
let store = BLEIncomingFileStore(baseDirectory: base)
|
||||
let subdirectories = [
|
||||
"voicenotes/incoming",
|
||||
"voicenotes/outgoing",
|
||||
"images/incoming",
|
||||
"images/outgoing",
|
||||
"files/incoming",
|
||||
"files/outgoing"
|
||||
]
|
||||
|
||||
for subdirectory in subdirectories {
|
||||
let directory = base
|
||||
.appendingPathComponent("files", isDirectory: true)
|
||||
.appendingPathComponent(subdirectory, isDirectory: true)
|
||||
try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)
|
||||
try Data("secret".utf8).write(to: directory.appendingPathComponent("artifact.bin"))
|
||||
}
|
||||
let unmanaged = base.appendingPathComponent("files/legacy/secret.bin")
|
||||
try FileManager.default.createDirectory(at: unmanaged.deletingLastPathComponent(), withIntermediateDirectories: true)
|
||||
try Data("legacy".utf8).write(to: unmanaged)
|
||||
|
||||
try store.panicWipe()
|
||||
|
||||
#expect(!FileManager.default.fileExists(atPath: unmanaged.path))
|
||||
for subdirectory in subdirectories {
|
||||
let directory = base
|
||||
.appendingPathComponent("files", isDirectory: true)
|
||||
.appendingPathComponent(subdirectory, isDirectory: true)
|
||||
var isDirectory: ObjCBool = false
|
||||
#expect(FileManager.default.fileExists(atPath: directory.path, isDirectory: &isDirectory))
|
||||
#expect(isDirectory.boolValue)
|
||||
#expect(try FileManager.default.contentsOfDirectory(atPath: directory.path).isEmpty)
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
func panicWipeAttemptsDeletionWhenMarkerPersistenceFails() throws {
|
||||
enum MarkerFailure: Error { case unavailable }
|
||||
|
||||
let base = FileManager.default.temporaryDirectory
|
||||
.appendingPathComponent(
|
||||
"panic-marker-failure-\(UUID().uuidString)",
|
||||
isDirectory: true
|
||||
)
|
||||
defer { try? FileManager.default.removeItem(at: base) }
|
||||
let secret = base
|
||||
.appendingPathComponent("files/images/outgoing", isDirectory: true)
|
||||
.appendingPathComponent("secret.jpg")
|
||||
try FileManager.default.createDirectory(
|
||||
at: secret.deletingLastPathComponent(),
|
||||
withIntermediateDirectories: true
|
||||
)
|
||||
try Data("secret".utf8).write(to: secret)
|
||||
let store = BLEIncomingFileStore(
|
||||
baseDirectory: base,
|
||||
panicMarkerWriter: { _, _ in throw MarkerFailure.unavailable }
|
||||
)
|
||||
|
||||
do {
|
||||
try store.panicWipe(hasDurablePendingMarker: false)
|
||||
Issue.record("Expected the missing durable marker to fail closed")
|
||||
} catch {
|
||||
// The marker error is reported only after the deletion attempt.
|
||||
}
|
||||
|
||||
#expect(!FileManager.default.fileExists(atPath: secret.path))
|
||||
#expect(
|
||||
FileManager.default.fileExists(
|
||||
atPath: secret.deletingLastPathComponent().path
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
@Test
|
||||
func externalMarkerAllowsDeletionToCommitWhenFileMarkerFails() throws {
|
||||
enum MarkerFailure: Error { case unavailable }
|
||||
|
||||
let base = FileManager.default.temporaryDirectory
|
||||
.appendingPathComponent(
|
||||
"panic-external-marker-\(UUID().uuidString)",
|
||||
isDirectory: true
|
||||
)
|
||||
defer { try? FileManager.default.removeItem(at: base) }
|
||||
let secret = base
|
||||
.appendingPathComponent("files/voicenotes/incoming", isDirectory: true)
|
||||
.appendingPathComponent("secret.m4a")
|
||||
try FileManager.default.createDirectory(
|
||||
at: secret.deletingLastPathComponent(),
|
||||
withIntermediateDirectories: true
|
||||
)
|
||||
try Data("secret".utf8).write(to: secret)
|
||||
let store = BLEIncomingFileStore(
|
||||
baseDirectory: base,
|
||||
panicMarkerWriter: { _, _ in throw MarkerFailure.unavailable }
|
||||
)
|
||||
|
||||
try store.panicWipe(hasDurablePendingMarker: true)
|
||||
|
||||
#expect(!FileManager.default.fileExists(atPath: secret.path))
|
||||
}
|
||||
|
||||
@Test
|
||||
func panicRecoveryMarkerPersistsUntilExplicitCommit() throws {
|
||||
let base = FileManager.default.temporaryDirectory
|
||||
.appendingPathComponent(
|
||||
"panic-recovery-marker-\(UUID().uuidString)",
|
||||
isDirectory: true
|
||||
)
|
||||
defer { try? FileManager.default.removeItem(at: base) }
|
||||
let store = BLEIncomingFileStore(baseDirectory: base)
|
||||
|
||||
try store.markPanicRecoveryPending()
|
||||
#expect(try store.isPanicRecoveryPending())
|
||||
try store.panicWipe(hasDurablePendingMarker: true)
|
||||
#expect(try store.isPanicRecoveryPending())
|
||||
|
||||
try store.completePanicRecovery()
|
||||
|
||||
#expect(try !store.isPanicRecoveryPending())
|
||||
}
|
||||
|
||||
private func expectNoSideEffects(_ recorder: Recorder) {
|
||||
#expect(recorder.signedNameQueries.isEmpty)
|
||||
#expect(recorder.trackedPackets.isEmpty)
|
||||
|
||||
@@ -152,21 +152,6 @@ struct BLENoisePacketHandlerTests {
|
||||
#expect(recorder.initiatedHandshakes.isEmpty)
|
||||
}
|
||||
|
||||
@Test
|
||||
func peerIdentityMismatchDoesNotRecreateHandshakeState() {
|
||||
let recorder = Recorder()
|
||||
recorder.handshakeResult = .failure(NoiseSessionError.peerIdentityMismatch)
|
||||
recorder.hasSession = false
|
||||
let handler = makeHandler(recorder: recorder)
|
||||
let packet = makeHandshakePacket(recipientID: Data(hexString: localPeerID.id))
|
||||
|
||||
#expect(!handler.handleHandshake(packet, from: remotePeerID))
|
||||
|
||||
#expect(recorder.hasSessionQueries.isEmpty)
|
||||
#expect(recorder.initiatedHandshakes.isEmpty)
|
||||
#expect(recorder.broadcastPackets.isEmpty)
|
||||
}
|
||||
|
||||
// MARK: Encrypted
|
||||
|
||||
@Test
|
||||
|
||||
@@ -76,6 +76,7 @@ final class GeohashPresenceServiceTests: XCTestCase {
|
||||
burstMaxDelay: 0
|
||||
)
|
||||
|
||||
service.start()
|
||||
service.performHeartbeat()
|
||||
|
||||
let sentAllAllowedChannels = await waitUntil { sentGeohashes.count == 3 }
|
||||
@@ -83,7 +84,7 @@ final class GeohashPresenceServiceTests: XCTestCase {
|
||||
XCTAssertEqual(Set(sentGeohashes), Set(["9q", "9q8y", "9q8yy"]))
|
||||
XCTAssertEqual(Set(lookedUpGeohashes), Set(["9q", "9q8y", "9q8yy"]))
|
||||
XCTAssertEqual(sleptNanoseconds.count, 3)
|
||||
XCTAssertEqual(scheduler.intervals, [17])
|
||||
XCTAssertEqual(scheduler.intervals, [17, 17])
|
||||
}
|
||||
|
||||
func test_performHeartbeat_skipsBroadcastWhenTorIsNotReady() async {
|
||||
@@ -97,11 +98,12 @@ final class GeohashPresenceServiceTests: XCTestCase {
|
||||
loopMaxInterval: 21
|
||||
)
|
||||
|
||||
service.start()
|
||||
service.performHeartbeat()
|
||||
try? await Task.sleep(nanoseconds: 20_000_000)
|
||||
|
||||
XCTAssertEqual(sendCount, 0)
|
||||
XCTAssertEqual(scheduler.intervals, [21])
|
||||
XCTAssertEqual(scheduler.intervals, [21, 21])
|
||||
}
|
||||
|
||||
func test_performHeartbeat_skipsBroadcastWhenAppIsBackgrounded() async {
|
||||
@@ -115,11 +117,45 @@ final class GeohashPresenceServiceTests: XCTestCase {
|
||||
loopMaxInterval: 22
|
||||
)
|
||||
|
||||
service.start()
|
||||
service.performHeartbeat()
|
||||
try? await Task.sleep(nanoseconds: 20_000_000)
|
||||
|
||||
XCTAssertEqual(sendCount, 0)
|
||||
XCTAssertEqual(scheduler.intervals, [22])
|
||||
XCTAssertEqual(scheduler.intervals, [22, 22])
|
||||
}
|
||||
|
||||
func test_stopForPanic_cancelsTimerAndSuppressesDelayedBroadcast() async throws {
|
||||
let identity = try NostrIdentity.generate()
|
||||
let scheduler = MockGeohashPresenceScheduler()
|
||||
var sleeperContinuation: CheckedContinuation<Void, Never>?
|
||||
var sendCount = 0
|
||||
let service = makeService(
|
||||
scheduler: scheduler,
|
||||
deriveIdentity: { _ in identity },
|
||||
relaySender: { _, _ in sendCount += 1 },
|
||||
sleeper: { _ in
|
||||
await withCheckedContinuation { continuation in
|
||||
sleeperContinuation = continuation
|
||||
}
|
||||
},
|
||||
burstMinDelay: 1,
|
||||
burstMaxDelay: 1
|
||||
)
|
||||
|
||||
service.start()
|
||||
service.performHeartbeat()
|
||||
let delayStarted = await waitUntil {
|
||||
sleeperContinuation != nil
|
||||
}
|
||||
XCTAssertTrue(delayStarted)
|
||||
|
||||
service.stopForPanic()
|
||||
sleeperContinuation?.resume()
|
||||
try? await Task.sleep(nanoseconds: 20_000_000)
|
||||
|
||||
XCTAssertEqual(sendCount, 0)
|
||||
XCTAssertEqual(scheduler.timers.first?.invalidateCallCount, 1)
|
||||
}
|
||||
|
||||
func test_broadcastPresence_skipsSendWhenNoRelaysAreAvailable() async throws {
|
||||
|
||||
@@ -91,6 +91,53 @@ final class NetworkActivationServiceTests: XCTestCase {
|
||||
XCTAssertGreaterThanOrEqual(context.relayController.connectCallCount, 1)
|
||||
}
|
||||
|
||||
func test_stopForPanic_synchronouslyStopsAndIgnoresPublisherUpdates() async {
|
||||
let context = makeService(permission: .authorized, favorites: [])
|
||||
|
||||
context.service.start()
|
||||
context.service.stopForPanic()
|
||||
let connectCountAfterStop = context.relayController.connectCallCount
|
||||
let startCountAfterStop = context.torController.startIfNeededCallCount
|
||||
|
||||
context.favoritesSubject.send([Data([0x01])])
|
||||
context.reachability.set(false)
|
||||
context.reachability.set(true)
|
||||
try? await Task.sleep(nanoseconds: 30_000_000)
|
||||
|
||||
XCTAssertFalse(context.service.activationAllowed)
|
||||
XCTAssertEqual(context.reachability.stopCallCount, 1)
|
||||
XCTAssertEqual(context.torController.autoStartAllowedValues.last, false)
|
||||
XCTAssertEqual(context.proxyController.proxyModes.last, false)
|
||||
XCTAssertGreaterThanOrEqual(
|
||||
context.torController.shutdownCompletelyCallCount,
|
||||
1
|
||||
)
|
||||
XCTAssertGreaterThanOrEqual(
|
||||
context.relayController.disconnectCallCount,
|
||||
1
|
||||
)
|
||||
XCTAssertEqual(
|
||||
context.relayController.connectCallCount,
|
||||
connectCountAfterStop
|
||||
)
|
||||
XCTAssertEqual(
|
||||
context.torController.startIfNeededCallCount,
|
||||
startCountAfterStop
|
||||
)
|
||||
}
|
||||
|
||||
func test_start_afterPanicStop_reestablishesSubscriptions() {
|
||||
let context = makeService(permission: .authorized, favorites: [])
|
||||
|
||||
context.service.start()
|
||||
context.service.stopForPanic()
|
||||
context.service.start()
|
||||
|
||||
XCTAssertTrue(context.service.activationAllowed)
|
||||
XCTAssertEqual(context.reachability.startCallCount, 2)
|
||||
XCTAssertEqual(context.relayController.connectCallCount, 2)
|
||||
}
|
||||
|
||||
private func makeService(
|
||||
permission: LocationChannelManager.PermissionState,
|
||||
favorites: Set<Data>
|
||||
@@ -104,6 +151,7 @@ final class NetworkActivationServiceTests: XCTestCase {
|
||||
let torController = MockNetworkActivationTorController()
|
||||
let relayController = MockNetworkActivationRelayController()
|
||||
let proxyController = MockNetworkActivationProxyController()
|
||||
let reachability = MockNetworkActivationReachability()
|
||||
let notificationCenter = NotificationCenter()
|
||||
let service = NetworkActivationService(
|
||||
storage: storage,
|
||||
@@ -111,7 +159,7 @@ final class NetworkActivationServiceTests: XCTestCase {
|
||||
mutualFavoritesPublisher: favoritesSubject.eraseToAnyPublisher(),
|
||||
permissionProvider: { permissionSubject.value },
|
||||
mutualFavoritesProvider: { favoritesSubject.value },
|
||||
reachabilityMonitor: AlwaysReachableMonitor(),
|
||||
reachabilityMonitor: reachability,
|
||||
torController: torController,
|
||||
relayController: relayController,
|
||||
proxyController: proxyController,
|
||||
@@ -121,6 +169,7 @@ final class NetworkActivationServiceTests: XCTestCase {
|
||||
service: service,
|
||||
storage: storage,
|
||||
favoritesSubject: favoritesSubject,
|
||||
reachability: reachability,
|
||||
torController: torController,
|
||||
relayController: relayController,
|
||||
proxyController: proxyController,
|
||||
@@ -148,12 +197,38 @@ private struct NetworkActivationTestContext {
|
||||
let service: NetworkActivationService
|
||||
let storage: UserDefaults
|
||||
let favoritesSubject: CurrentValueSubject<Set<Data>, Never>
|
||||
let reachability: MockNetworkActivationReachability
|
||||
let torController: MockNetworkActivationTorController
|
||||
let relayController: MockNetworkActivationRelayController
|
||||
let proxyController: MockNetworkActivationProxyController
|
||||
let notificationCenter: NotificationCenter
|
||||
}
|
||||
|
||||
@MainActor
|
||||
private final class MockNetworkActivationReachability:
|
||||
NetworkReachabilityMonitoring {
|
||||
private let subject = CurrentValueSubject<Bool, Never>(true)
|
||||
private(set) var startCallCount = 0
|
||||
private(set) var stopCallCount = 0
|
||||
|
||||
var isReachable: Bool { subject.value }
|
||||
var reachabilityPublisher: AnyPublisher<Bool, Never> {
|
||||
subject.removeDuplicates().dropFirst().eraseToAnyPublisher()
|
||||
}
|
||||
|
||||
func start() {
|
||||
startCallCount += 1
|
||||
}
|
||||
|
||||
func stop() {
|
||||
stopCallCount += 1
|
||||
}
|
||||
|
||||
func set(_ reachable: Bool) {
|
||||
subject.send(reachable)
|
||||
}
|
||||
}
|
||||
|
||||
@MainActor
|
||||
private final class MockNetworkActivationTorController: NetworkActivationTorControlling {
|
||||
private(set) var autoStartAllowedValues: [Bool] = []
|
||||
|
||||
@@ -213,6 +213,7 @@ private final class ControllableReachabilityMonitor: NetworkReachabilityMonitori
|
||||
subject.removeDuplicates().dropFirst().eraseToAnyPublisher()
|
||||
}
|
||||
func start() { startCalled = true }
|
||||
func stop() { startCalled = false }
|
||||
func set(_ reachable: Bool) { subject.send(reachable) }
|
||||
}
|
||||
|
||||
|
||||
@@ -91,150 +91,39 @@ struct NoiseEncryptionServiceTests {
|
||||
func handshakeEncryptionAndFingerprintLifecycle() async throws {
|
||||
let alice = NoiseEncryptionService(keychain: MockKeychain())
|
||||
let bob = NoiseEncryptionService(keychain: MockKeychain())
|
||||
let alicePeerID = PeerID(publicKey: alice.getStaticPublicKeyData())
|
||||
let bobPeerID = PeerID(publicKey: bob.getStaticPublicKeyData())
|
||||
let alicePeerID = PeerID(str: "0011223344556677")
|
||||
let bobPeerID = PeerID(str: "8899aabbccddeeff")
|
||||
let recorder = AuthenticationRecorder()
|
||||
|
||||
#expect(alice.onPeerAuthenticated == nil)
|
||||
alice.addOnPeerAuthenticatedHandler(recorder.record(peerID:fingerprint:))
|
||||
bob.onPeerAuthenticated = recorder.record(peerID:fingerprint:)
|
||||
|
||||
try establishSessions(alice: alice, bob: bob)
|
||||
try establishSessions(alice: alice, bob: bob, alicePeerID: alicePeerID, bobPeerID: bobPeerID)
|
||||
|
||||
let authenticated = await TestHelpers.waitUntil({ recorder.count >= 2 }, timeout: 5.0)
|
||||
#expect(authenticated)
|
||||
#expect(alice.hasEstablishedSession(with: bobPeerID))
|
||||
#expect(bob.hasEstablishedSession(with: alicePeerID))
|
||||
#expect(alice.hasSession(with: bobPeerID))
|
||||
#expect(bob.hasSession(with: alicePeerID))
|
||||
#expect(alice.getPeerPublicKeyData(bobPeerID)?.count == 32)
|
||||
#expect(bob.getPeerPublicKeyData(alicePeerID)?.count == 32)
|
||||
#expect(alice.getPeerFingerprint(bobPeerID) != nil)
|
||||
#expect(bob.getPeerFingerprint(alicePeerID) != nil)
|
||||
#expect(alice.hasEstablishedSession(with: alicePeerID))
|
||||
#expect(bob.hasEstablishedSession(with: bobPeerID))
|
||||
#expect(alice.hasSession(with: alicePeerID))
|
||||
#expect(bob.hasSession(with: bobPeerID))
|
||||
#expect(alice.getPeerPublicKeyData(alicePeerID)?.count == 32)
|
||||
#expect(bob.getPeerPublicKeyData(bobPeerID)?.count == 32)
|
||||
#expect(alice.getPeerFingerprint(alicePeerID) != nil)
|
||||
#expect(bob.getPeerFingerprint(bobPeerID) != nil)
|
||||
|
||||
let plaintext = Data("secret payload".utf8)
|
||||
let ciphertext = try alice.encrypt(plaintext, for: bobPeerID)
|
||||
let decrypted = try bob.decrypt(ciphertext, from: alicePeerID)
|
||||
let ciphertext = try alice.encrypt(plaintext, for: alicePeerID)
|
||||
let decrypted = try bob.decrypt(ciphertext, from: bobPeerID)
|
||||
#expect(decrypted == plaintext)
|
||||
|
||||
alice.clearSession(for: bobPeerID)
|
||||
#expect(!alice.hasSession(with: bobPeerID))
|
||||
#expect(alice.getPeerFingerprint(bobPeerID) == nil)
|
||||
alice.clearSession(for: alicePeerID)
|
||||
#expect(!alice.hasSession(with: alicePeerID))
|
||||
#expect(alice.getPeerFingerprint(alicePeerID) == nil)
|
||||
|
||||
bob.clearEphemeralStateForPanic()
|
||||
#expect(!bob.hasSession(with: alicePeerID))
|
||||
#expect(bob.getPeerFingerprint(alicePeerID) == nil)
|
||||
}
|
||||
|
||||
@Test("Handshake rejects a claimed peer ID that does not match the authenticated static key")
|
||||
func handshakeRejectsClaimedPeerIDStaticKeyMismatch() async throws {
|
||||
let receiver = NoiseEncryptionService(keychain: MockKeychain())
|
||||
let claimedAlice = NoiseEncryptionService(keychain: MockKeychain())
|
||||
let mallory = NoiseEncryptionService(keychain: MockKeychain())
|
||||
let receiverPeerID = PeerID(publicKey: receiver.getStaticPublicKeyData())
|
||||
let claimedAlicePeerID = PeerID(publicKey: claimedAlice.getStaticPublicKeyData())
|
||||
let recorder = AuthenticationRecorder()
|
||||
receiver.addOnPeerAuthenticatedHandler(recorder.record(peerID:fingerprint:))
|
||||
|
||||
let message1 = try mallory.initiateHandshake(with: receiverPeerID)
|
||||
let message2 = try #require(
|
||||
try receiver.processHandshakeMessage(from: claimedAlicePeerID, message: message1)
|
||||
)
|
||||
let message3 = try #require(
|
||||
try mallory.processHandshakeMessage(from: receiverPeerID, message: message2)
|
||||
)
|
||||
|
||||
do {
|
||||
_ = try receiver.processHandshakeMessage(from: claimedAlicePeerID, message: message3)
|
||||
Issue.record("Expected the authenticated Mallory key to be rejected for Alice's peer ID")
|
||||
} catch let error as NoiseSessionError {
|
||||
#expect(error == .peerIdentityMismatch)
|
||||
} catch {
|
||||
Issue.record("Unexpected mismatch error: \(error)")
|
||||
}
|
||||
|
||||
#expect(!receiver.hasSession(with: claimedAlicePeerID))
|
||||
let emittedAuthentication = await TestHelpers.waitUntil(
|
||||
{ recorder.count > 0 },
|
||||
timeout: TestConstants.shortTimeout
|
||||
)
|
||||
#expect(!emittedAuthentication)
|
||||
}
|
||||
|
||||
@Test("Failed forged replacement preserves the established peer session")
|
||||
func forgedReplacementPreservesEstablishedSession() async throws {
|
||||
let alice = NoiseEncryptionService(keychain: MockKeychain())
|
||||
let receiver = NoiseEncryptionService(keychain: MockKeychain())
|
||||
let mallory = NoiseEncryptionService(keychain: MockKeychain())
|
||||
let alicePeerID = PeerID(publicKey: alice.getStaticPublicKeyData())
|
||||
let receiverPeerID = PeerID(publicKey: receiver.getStaticPublicKeyData())
|
||||
let recorder = AuthenticationRecorder()
|
||||
receiver.addOnPeerAuthenticatedHandler(recorder.record(peerID:fingerprint:))
|
||||
|
||||
try establishSessions(alice: alice, bob: receiver)
|
||||
let initialAuthentication = await TestHelpers.waitUntil(
|
||||
{ recorder.count == 1 },
|
||||
timeout: TestConstants.longTimeout
|
||||
)
|
||||
#expect(initialAuthentication)
|
||||
|
||||
let before = try alice.encrypt(Data("before".utf8), for: receiverPeerID)
|
||||
#expect(try receiver.decrypt(before, from: alicePeerID) == Data("before".utf8))
|
||||
|
||||
let forgedMessage1 = try mallory.initiateHandshake(with: receiverPeerID)
|
||||
let forgedMessage2 = try #require(
|
||||
try receiver.processHandshakeMessage(from: alicePeerID, message: forgedMessage1)
|
||||
)
|
||||
// The replacement has not authenticated yet; the working Alice
|
||||
// transport session must remain available throughout the candidate.
|
||||
#expect(receiver.hasEstablishedSession(with: alicePeerID))
|
||||
let forgedMessage3 = try #require(
|
||||
try mallory.processHandshakeMessage(from: receiverPeerID, message: forgedMessage2)
|
||||
)
|
||||
|
||||
do {
|
||||
_ = try receiver.processHandshakeMessage(from: alicePeerID, message: forgedMessage3)
|
||||
Issue.record("Expected forged replacement to fail peer binding")
|
||||
} catch let error as NoiseSessionError {
|
||||
#expect(error == .peerIdentityMismatch)
|
||||
} catch {
|
||||
Issue.record("Unexpected replacement error: \(error)")
|
||||
}
|
||||
|
||||
#expect(receiver.hasEstablishedSession(with: alicePeerID))
|
||||
let after = try alice.encrypt(Data("after".utf8), for: receiverPeerID)
|
||||
#expect(try receiver.decrypt(after, from: alicePeerID) == Data("after".utf8))
|
||||
let emittedReplacementAuthentication = await TestHelpers.waitUntil(
|
||||
{ recorder.count > 1 },
|
||||
timeout: TestConstants.shortTimeout
|
||||
)
|
||||
#expect(!emittedReplacementAuthentication)
|
||||
}
|
||||
|
||||
@Test("Valid rehandshake atomically replaces the established session")
|
||||
func validRehandshakeReplacesEstablishedSession() throws {
|
||||
let alice = NoiseEncryptionService(keychain: MockKeychain())
|
||||
let receiver = NoiseEncryptionService(keychain: MockKeychain())
|
||||
let alicePeerID = PeerID(publicKey: alice.getStaticPublicKeyData())
|
||||
let receiverPeerID = PeerID(publicKey: receiver.getStaticPublicKeyData())
|
||||
|
||||
try establishSessions(alice: alice, bob: receiver)
|
||||
alice.clearSession(for: receiverPeerID)
|
||||
|
||||
let message1 = try alice.initiateHandshake(with: receiverPeerID)
|
||||
let message2 = try #require(
|
||||
try receiver.processHandshakeMessage(from: alicePeerID, message: message1)
|
||||
)
|
||||
#expect(receiver.hasEstablishedSession(with: alicePeerID))
|
||||
let message3 = try #require(
|
||||
try alice.processHandshakeMessage(from: receiverPeerID, message: message2)
|
||||
)
|
||||
_ = try receiver.processHandshakeMessage(from: alicePeerID, message: message3)
|
||||
|
||||
#expect(alice.hasEstablishedSession(with: receiverPeerID))
|
||||
#expect(receiver.hasEstablishedSession(with: alicePeerID))
|
||||
let ciphertext = try alice.encrypt(Data("new session".utf8), for: receiverPeerID)
|
||||
#expect(try receiver.decrypt(ciphertext, from: alicePeerID) == Data("new session".utf8))
|
||||
#expect(!bob.hasSession(with: bobPeerID))
|
||||
#expect(bob.getPeerFingerprint(bobPeerID) == nil)
|
||||
}
|
||||
|
||||
@Test("Encrypt without a session requests handshake and decrypt without session fails")
|
||||
@@ -311,16 +200,16 @@ struct NoiseEncryptionServiceTests {
|
||||
|
||||
private func establishSessions(
|
||||
alice: NoiseEncryptionService,
|
||||
bob: NoiseEncryptionService
|
||||
bob: NoiseEncryptionService,
|
||||
alicePeerID: PeerID,
|
||||
bobPeerID: PeerID
|
||||
) throws {
|
||||
let alicePeerID = PeerID(publicKey: alice.getStaticPublicKeyData())
|
||||
let bobPeerID = PeerID(publicKey: bob.getStaticPublicKeyData())
|
||||
let message1 = try alice.initiateHandshake(with: bobPeerID)
|
||||
let response = try bob.processHandshakeMessage(from: alicePeerID, message: message1)
|
||||
let message1 = try alice.initiateHandshake(with: alicePeerID)
|
||||
let response = try bob.processHandshakeMessage(from: bobPeerID, message: message1)
|
||||
let message2 = try #require(response, "Expected handshake response")
|
||||
let final = try alice.processHandshakeMessage(from: bobPeerID, message: message2)
|
||||
let final = try alice.processHandshakeMessage(from: alicePeerID, message: message2)
|
||||
let message3 = try #require(final, "Expected handshake final")
|
||||
let finalMessage = try bob.processHandshakeMessage(from: alicePeerID, message: message3)
|
||||
let finalMessage = try bob.processHandshakeMessage(from: bobPeerID, message: message3)
|
||||
#expect(finalMessage == nil)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -61,6 +61,7 @@ private final class GatedVoiceCaptureSession: VoiceCaptureSession {
|
||||
private let startError: Error?
|
||||
private(set) var finishStarted = false
|
||||
private(set) var cancelCount = 0
|
||||
private(set) var panicCancelCount = 0
|
||||
private var finishContinuation: CheckedContinuation<URL?, Never>?
|
||||
|
||||
init(startError: Error? = nil) {
|
||||
@@ -83,6 +84,10 @@ private final class GatedVoiceCaptureSession: VoiceCaptureSession {
|
||||
cancelCount += 1
|
||||
}
|
||||
|
||||
func panicCancelSynchronously() {
|
||||
panicCancelCount += 1
|
||||
}
|
||||
|
||||
func resolveFinish(with url: URL?) {
|
||||
let continuation = finishContinuation
|
||||
finishContinuation = nil
|
||||
@@ -204,4 +209,57 @@ struct VoiceCaptureSessionTests {
|
||||
}
|
||||
#expect(viewModel.state == .idle)
|
||||
}
|
||||
|
||||
@Test func panicSynchronouslyCancelsActiveCaptureAndResetsUI() async {
|
||||
let session = GatedVoiceCaptureSession()
|
||||
let viewModel = VoiceRecordingViewModel()
|
||||
viewModel.sessionProvider = { session }
|
||||
|
||||
viewModel.start(shouldShow: true)
|
||||
await waitUntil { self.isRecording(viewModel.state) }
|
||||
|
||||
viewModel.panicWipe()
|
||||
|
||||
#expect(session.panicCancelCount == 1)
|
||||
#expect(viewModel.state == .idle)
|
||||
#expect(!viewModel.isLiveStreaming)
|
||||
}
|
||||
|
||||
@Test func panicInvalidatesARecordingAlreadyFinalizing() async throws {
|
||||
let session = GatedVoiceCaptureSession()
|
||||
let viewModel = VoiceRecordingViewModel()
|
||||
viewModel.sessionProvider = { session }
|
||||
let url = FileManager.default.temporaryDirectory
|
||||
.appendingPathComponent("voice-panic-\(UUID().uuidString).m4a")
|
||||
try Data([0x01]).write(to: url)
|
||||
var delivered = false
|
||||
|
||||
viewModel.start(shouldShow: true)
|
||||
await waitUntil { self.isRecording(viewModel.state) }
|
||||
viewModel.finish { _ in delivered = true }
|
||||
await waitUntil { session.finishStarted }
|
||||
|
||||
viewModel.panicWipe()
|
||||
session.resolveFinish(with: url)
|
||||
await waitUntil {
|
||||
!FileManager.default.fileExists(atPath: url.path)
|
||||
}
|
||||
|
||||
#expect(!delivered)
|
||||
#expect(viewModel.state == .idle)
|
||||
}
|
||||
|
||||
@Test func liveSessionPanicStopsCaptureWithoutSendingControl() {
|
||||
let capture = StubPTTCapture(stopResult: (nil, 0))
|
||||
var sentPackets: [Data] = []
|
||||
let session = PTTLiveVoiceSession(
|
||||
sendPacket: { sentPackets.append($0) },
|
||||
capture: capture
|
||||
)
|
||||
|
||||
session.panicCancelSynchronously()
|
||||
|
||||
#expect(capture.cancelCount == 1)
|
||||
#expect(sentPackets.isEmpty)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -360,6 +360,35 @@ struct VoiceRecorderTests {
|
||||
#expect(FileManager.default.fileExists(atPath: secondURL.path))
|
||||
}
|
||||
|
||||
@Test func classicSessionPanicStopsRecorderAndDeletesFileBeforeReturning() async throws {
|
||||
let directory = try makeTemporaryDirectory()
|
||||
defer { try? FileManager.default.removeItem(at: directory) }
|
||||
|
||||
let rawSession = VoiceRecorderTestSession()
|
||||
let coordinator = AudioSessionCoordinator(session: rawSession)
|
||||
let factory = TestVoiceAudioRecorderFactory(plans: [.success])
|
||||
let voiceRecorder = VoiceRecorder(
|
||||
sessionCoordinator: coordinator,
|
||||
recorderFactory: factory,
|
||||
permissionGranted: { true },
|
||||
paddingInterval: 0,
|
||||
outputDirectory: directory
|
||||
)
|
||||
let capture = VoiceNoteCaptureSession(recorder: voiceRecorder)
|
||||
|
||||
try await capture.start()
|
||||
let url = try #require(factory.urls.first)
|
||||
let recorder = try #require(factory.recorders.first)
|
||||
|
||||
capture.panicCancelSynchronously()
|
||||
|
||||
#expect(recorder.stopCallCount == 1)
|
||||
#expect(!recorder.isRecording)
|
||||
#expect(!FileManager.default.fileExists(atPath: url.path))
|
||||
await coordinator.drain()
|
||||
#expect(rawSession.activationCalls == [true, false])
|
||||
}
|
||||
|
||||
private func verifyFailedStart(
|
||||
firstPlan: TestVoiceAudioRecorderFactory.Plan,
|
||||
expectedPrepareCalls: Int,
|
||||
|
||||
@@ -48,7 +48,7 @@ Residual risk: private-message metadata such as timing, radio adjacency, ciphert
|
||||
- Recent signed public mesh messages are archived in Application Support for up to 15 minutes so gossip sync survives a relaunch and can cross mesh partitions.
|
||||
- Signed public board posts and tombstones persist until author-selected expiry, at most seven days. Stores are bounded by global and per-author quotas.
|
||||
- Group metadata (name, roster, creator, epoch) persists as protected JSON; group keys live in the keychain until leave/removal/wipe.
|
||||
- Voice notes and images are stored in Application Support. Incoming media has a 100 MB oldest-first quota; outgoing media does not have an equivalent automatic lifetime and remains until cleanup, panic wipe, or app removal.
|
||||
- Voice notes and images are stored in Application Support. Incoming media has a 100 MB oldest-first quota; outgoing media does not have an equivalent automatic lifetime and remains until cleanup, panic wipe, or app removal. Panic wipe invalidates detached preparation work, cancels active transfers, closes live capture files, and removes the managed media tree before returning.
|
||||
|
||||
Public archives contain content already intended for public mesh/board distribution, but a seized unlocked device can reveal it. Group metadata and media can reveal relationships or content even when the in-memory chat timeline has gone away.
|
||||
|
||||
@@ -88,7 +88,7 @@ Residual risk: Nostr relay retention and logging are outside project control. Pu
|
||||
|
||||
## Panic Wipe Coverage
|
||||
|
||||
The panic action clears identity/session state, preferences, location state, groups, prekeys, outbox mail, courier mail, bridge dedup state, gossip archive, board data, managed media, and active subscriptions/transports. New persistent stores must add an explicit wipe hook and a regression test.
|
||||
The panic action clears identity/session state, preferences, location state, groups, prekeys, outbox mail, courier mail, bridge dedup state, gossip archive, board data, managed media, and active subscriptions/transports. Managed media deletion completes synchronously, after active media work has been invalidated. Keychain secrets use device-only accessibility, and an install marker detects and clears app keys that survive uninstall before a later reinstall can use them. New persistent stores must add an explicit wipe hook and a regression test.
|
||||
|
||||
## Release Review Checklist
|
||||
|
||||
|
||||
Reference in New Issue
Block a user