diff --git a/bitchat/App/AppRuntime.swift b/bitchat/App/AppRuntime.swift index 14c0abb7..2726ad17 100644 --- a/bitchat/App/AppRuntime.swift +++ b/bitchat/App/AppRuntime.swift @@ -108,7 +108,7 @@ final class AppRuntime: ObservableObject { let resolvedSharedContentStore: SharedContentStore? if let sharedContentStore { resolvedSharedContentStore = sharedContentStore - } else if let sharedDefaults = UserDefaults(suiteName: BitchatApp.groupID) { + } else if let sharedDefaults = BitchatApp.sharedUserDefaults() { resolvedSharedContentStore = SharedContentStore(defaults: sharedDefaults) } else { resolvedSharedContentStore = nil diff --git a/bitchat/BitchatApp.swift b/bitchat/BitchatApp.swift index 5c909448..152faec6 100644 --- a/bitchat/BitchatApp.swift +++ b/bitchat/BitchatApp.swift @@ -12,7 +12,39 @@ import UserNotifications @main struct BitchatApp: App { static let bundleID = Bundle.main.bundleIdentifier ?? "chat.bitchat" - static let groupID = "group.\(bundleID)" + static let groupID = resolvedGroupID( + infoDictionary: Bundle.main.infoDictionary, + bundleIdentifier: Bundle.main.bundleIdentifier + ) + + static func resolvedGroupID( + infoDictionary: [String: Any]?, + bundleIdentifier: String? + ) -> String { + if let configured = (infoDictionary?["AppGroupID"] as? String)? + .trimmingCharacters(in: .whitespacesAndNewlines), + !configured.isEmpty, + !configured.contains("$(") { + return configured + } + let resolvedBundleID = bundleIdentifier ?? "chat.bitchat" + return "group.\(resolvedBundleID)" + } + + /// Returns shared `UserDefaults` for the configured App Group only when the + /// running binary is entitled to that container. Calling + /// `UserDefaults(suiteName:)` for an unprovisioned App Group detaches from + /// `cfprefsd` and logs `Container: (null)` on every launch. + static func sharedUserDefaults( + groupID: String = BitchatApp.groupID, + containerURLProvider: (String) -> URL? = { + FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: $0) + }, + defaultsProvider: (String) -> UserDefaults? = { UserDefaults(suiteName: $0) } + ) -> UserDefaults? { + guard containerURLProvider(groupID) != nil else { return nil } + return defaultsProvider(groupID) + } @StateObject private var runtime: AppRuntime @AppStorage(AppTheme.storageKey) private var appThemeRawValue = AppTheme.matrix.rawValue diff --git a/bitchat/Services/BLE/BLEService+LinkLayerPeripheralRole.swift b/bitchat/Services/BLE/BLEService+LinkLayerPeripheralRole.swift index ffe6831d..5db46071 100644 --- a/bitchat/Services/BLE/BLEService+LinkLayerPeripheralRole.swift +++ b/bitchat/Services/BLE/BLEService+LinkLayerPeripheralRole.swift @@ -30,24 +30,53 @@ extension BLEService: CBPeripheralManagerDelegate { characteristic = nil return } - // Remove all services first to ensure clean state - peripheral.removeAllServices() - // Create characteristic - characteristic = CBMutableCharacteristic( - type: BLEService.characteristicUUID, - properties: [.notify, .write, .writeWithoutResponse, .read], - value: nil, - permissions: [.readable, .writeable] - ) + switch BLEService.peripheralPoweredOnAction( + hasPublishedCharacteristic: characteristic != nil, + isAdvertising: peripheral.isAdvertising, + subscribedCentralCount: linkStateStore.subscribedCentralCount + ) { + case let .reusePublishedService(shouldStartAdvertising, shouldAnnounceToSubscribedCentrals): + // CoreBluetooth already restored (or previously published) our + // matching BitChat GATT service. Reusing it avoids tearing down + // the GATT database and firing redundant Service Changed + // indications to already-connected peers. + if shouldStartAdvertising { + peripheral.startAdvertising(BLERadioController.advertisementData()) + } + SecureLogger.debug( + "♻️ Reusing published BLE service (startedAdvertising=\(shouldStartAdvertising), subscribedCentrals=\(linkStateStore.subscribedCentralCount), ID: \(myPeerID.id.prefix(8))…)", + category: .session + ) + if shouldAnnounceToSubscribedCentrals { + wakeMaintenanceCadenceIfNeeded() + engineScheduler.schedule(after: TransportConfig.blePostSubscribeAnnounceDelaySeconds) { [weak self] in + self?.sendAnnounce(forceSend: true) + self?.flushDirectedSpool() + } + } - // Create service - let service = CBMutableService(type: BLEService.serviceUUID, primary: true) - service.characteristics = [characteristic!] + case .rebuildAndAddService: + // Remove any stale services first to ensure a clean GATT database + peripheral.removeAllServices() - // Add service (advertising will start in didAdd delegate) - SecureLogger.debug("🔧 Adding BLE service...", category: .session) - peripheral.add(service) + // Create characteristic + let newCharacteristic = CBMutableCharacteristic( + type: BLEService.characteristicUUID, + properties: BLEService.peripheralCharacteristicProperties, + value: nil, + permissions: BLEService.peripheralCharacteristicPermissions + ) + characteristic = newCharacteristic + + // Create service + let service = CBMutableService(type: BLEService.serviceUUID, primary: true) + service.characteristics = [newCharacteristic] + + // Add service (advertising will start in didAdd delegate) + SecureLogger.debug("🔧 Adding BLE service...", category: .session) + peripheral.add(service) + } case .poweredOff: // Bluetooth was turned off - clean up peripheral state @@ -74,8 +103,16 @@ extension BLEService: CBPeripheralManagerDelegate { SecureLogger.error("❌ Bluetooth LE peripheral role not supported", category: .session) case .resetting: - // Bluetooth stack is resetting + // CoreBluetooth drops all published GATT services on stack reset; + // clear local state so the subsequent poweredOn rebuilds cleanly. SecureLogger.info("🔄 Bluetooth peripheral stack resetting...", category: .session) + let centralIDs = linkStateStore.subscribedCentrals.map { $0.identifier.uuidString } + pendingNotifications.removeAll() + pendingWriteBuffers.removeAll() + linkStateStore.clearCentrals() + subscriptionAnnounceLimiter.removeAll() + characteristic = nil + emitLinkEvent(.allCentralLinksEnded(centralUUIDs: centralIDs, retireProofsAndNotify: true)) case .unknown: SecureLogger.debug("❓ Peripheral Bluetooth state unknown (initializing)", category: .session) @@ -101,18 +138,23 @@ extension BLEService: CBPeripheralManagerDelegate { category: .session ) - // Attempt to recover characteristic from restored services - if characteristic == nil { - if let service = restoredServices.first(where: { $0.uuid == BLEService.serviceUUID }), - let restoredCharacteristic = service.characteristics?.first(where: { $0.uuid == BLEService.characteristicUUID }) as? CBMutableCharacteristic { - characteristic = restoredCharacteristic + // Recover our published characteristic when the restored GATT database + // already matches what poweredOn would publish, along with any centrals + // still subscribed to it. Otherwise leave `characteristic` nil so + // poweredOn rebuilds the service cleanly. + if let restoredCharacteristic = BLEService.restoredBitChatCharacteristic(from: restoredServices) { + characteristic = restoredCharacteristic + for central in restoredCharacteristic.subscribedCentrals ?? [] { + linkStateStore.addSubscribedCentral(central) } + } else { + characteristic = nil } // Via the sampler for a fresh background budget (see central-restore). logBluetoothStatus("peripheral-restore") - if peripheral.state == .poweredOn && !peripheral.isAdvertising { + if characteristic != nil && peripheral.state == .poweredOn && !peripheral.isAdvertising { peripheral.startAdvertising(BLERadioController.advertisementData()) } } @@ -124,6 +166,7 @@ extension BLEService: CBPeripheralManagerDelegate { return } if let error = error { + characteristic = nil SecureLogger.error("❌ Failed to add service: \(error.localizedDescription)", category: .session) return } @@ -326,3 +369,55 @@ extension BLEService: CBPeripheralManagerDelegate { )) } } + +enum BLEPeripheralPoweredOnAction: Equatable { + case reusePublishedService( + shouldStartAdvertising: Bool, + shouldAnnounceToSubscribedCentrals: Bool + ) + case rebuildAndAddService +} + +extension BLEService { + static let peripheralCharacteristicProperties: CBCharacteristicProperties = [ + .notify, .write, .writeWithoutResponse, .read + ] + static let peripheralCharacteristicPermissions: CBAttributePermissions = [ + .readable, .writeable + ] + + /// Returns the restored BitChat characteristic only when the restored GATT + /// database already matches what `peripheralManagerDidUpdateState(.poweredOn)` + /// would publish. Returning `nil` falls back to `removeAllServices()` + `add(service)`. + static func restoredBitChatCharacteristic( + from restoredServices: [CBMutableService] + ) -> CBMutableCharacteristic? { + guard restoredServices.count == 1, + let service = restoredServices.first, + service.uuid == BLEService.serviceUUID, + service.isPrimary, + let characteristics = service.characteristics, + characteristics.count == 1, + let restored = characteristics.first as? CBMutableCharacteristic, + restored.uuid == BLEService.characteristicUUID, + restored.properties.contains(peripheralCharacteristicProperties), + restored.permissions.contains(peripheralCharacteristicPermissions) else { + return nil + } + return restored + } + + static func peripheralPoweredOnAction( + hasPublishedCharacteristic: Bool, + isAdvertising: Bool, + subscribedCentralCount: Int + ) -> BLEPeripheralPoweredOnAction { + guard hasPublishedCharacteristic else { + return .rebuildAndAddService + } + return .reusePublishedService( + shouldStartAdvertising: !isAdvertising, + shouldAnnounceToSubscribedCentrals: subscribedCentralCount > 0 + ) + } +} diff --git a/bitchat/ViewModels/ChatViewModel.swift b/bitchat/ViewModels/ChatViewModel.swift index d3833184..5e94425f 100644 --- a/bitchat/ViewModels/ChatViewModel.swift +++ b/bitchat/ViewModels/ChatViewModel.swift @@ -1774,7 +1774,7 @@ final class ChatViewModel: ObservableObject, SynchronousMessageTransportEventDel // crash-recovery replay calls this method directly and would otherwise // let a staged envelope survive the wipe. Clearing here is idempotent // (it only removes the app-group key), so the double-clear is harmless. - if let sharedDefaults = UserDefaults(suiteName: BitchatApp.groupID) { + if let sharedDefaults = BitchatApp.sharedUserDefaults() { SharedContentStore(defaults: sharedDefaults).discardAll() } diff --git a/bitchatShareExtension/ShareViewController.swift b/bitchatShareExtension/ShareViewController.swift index d46f1c1f..ac8a0f66 100644 --- a/bitchatShareExtension/ShareViewController.swift +++ b/bitchatShareExtension/ShareViewController.swift @@ -13,7 +13,15 @@ import UniformTypeIdentifiers /// Avoids deprecated Social framework and SLComposeServiceViewController. final class ShareViewController: UIViewController { // Bundle.main.bundleIdentifier would get the extension's bundleID - private static let groupID = Bundle.main.object(forInfoDictionaryKey: "AppGroupID") as? String ?? "group.chat.bitchat" + private static let groupID: String = { + if let configured = (Bundle.main.object(forInfoDictionaryKey: "AppGroupID") as? String)? + .trimmingCharacters(in: .whitespacesAndNewlines), + !configured.isEmpty, + !configured.contains("$(") { + return configured + } + return "group.chat.bitchat" + }() private enum Strings { static let nothingToShare = String(localized: "share.status.nothing_to_share", comment: "Shown when the share extension receives no content") @@ -161,7 +169,8 @@ final class ShareViewController: UIViewController { } private func stageAndFinish(_ payload: SharedContentPayload) { - guard let defaults = UserDefaults(suiteName: Self.groupID) else { + guard FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: Self.groupID) != nil, + let defaults = UserDefaults(suiteName: Self.groupID) else { finishWithMessage(Strings.failedToSave) return } diff --git a/bitchatTests/BLEServiceCoreTests.swift b/bitchatTests/BLEServiceCoreTests.swift index e7a667fd..547bfb8f 100644 --- a/bitchatTests/BLEServiceCoreTests.swift +++ b/bitchatTests/BLEServiceCoreTests.swift @@ -1354,6 +1354,94 @@ struct BLEServiceCoreTests { )) } + @Test + func restoredPeripheralService_reusesExactBitChatServiceAndCharacteristic() { + let characteristic = CBMutableCharacteristic( + type: BLEService.characteristicUUID, + properties: BLEService.peripheralCharacteristicProperties, + value: nil, + permissions: BLEService.peripheralCharacteristicPermissions + ) + let service = CBMutableService(type: BLEService.serviceUUID, primary: true) + service.characteristics = [characteristic] + + let restored = BLEService.restoredBitChatCharacteristic(from: [service]) + #expect(restored === characteristic) + } + + @Test + func restoredPeripheralService_rejectsMismatchedSecondaryOrExtraServices() { + let validCharacteristic = CBMutableCharacteristic( + type: BLEService.characteristicUUID, + properties: BLEService.peripheralCharacteristicProperties, + value: nil, + permissions: BLEService.peripheralCharacteristicPermissions + ) + + // Secondary service instead of primary + let secondaryService = CBMutableService(type: BLEService.serviceUUID, primary: false) + secondaryService.characteristics = [validCharacteristic] + #expect(BLEService.restoredBitChatCharacteristic(from: [secondaryService]) == nil) + + // Missing required characteristic properties + let notifyOnly = CBMutableCharacteristic( + type: BLEService.characteristicUUID, + properties: [.notify], + value: nil, + permissions: BLEService.peripheralCharacteristicPermissions + ) + let partialPropsService = CBMutableService(type: BLEService.serviceUUID, primary: true) + partialPropsService.characteristics = [notifyOnly] + #expect(BLEService.restoredBitChatCharacteristic(from: [partialPropsService]) == nil) + + // Missing writeable permission + let readOnly = CBMutableCharacteristic( + type: BLEService.characteristicUUID, + properties: BLEService.peripheralCharacteristicProperties, + value: nil, + permissions: [.readable] + ) + let readOnlyService = CBMutableService(type: BLEService.serviceUUID, primary: true) + readOnlyService.characteristics = [readOnly] + #expect(BLEService.restoredBitChatCharacteristic(from: [readOnlyService]) == nil) + + // Extra stale service alongside the BitChat service + let validService = CBMutableService(type: BLEService.serviceUUID, primary: true) + validService.characteristics = [validCharacteristic] + let extraService = CBMutableService( + type: CBUUID(string: "0000180F-0000-1000-8000-00805F9B34FB"), + primary: true + ) + #expect(BLEService.restoredBitChatCharacteristic(from: [validService, extraService]) == nil) + } + + @Test + func peripheralPoweredOnAction_reusesRestoredServiceOrRebuildsWhenMissing() { + #expect(BLEService.peripheralPoweredOnAction( + hasPublishedCharacteristic: false, + isAdvertising: false, + subscribedCentralCount: 0 + ) == .rebuildAndAddService) + + #expect(BLEService.peripheralPoweredOnAction( + hasPublishedCharacteristic: true, + isAdvertising: true, + subscribedCentralCount: 0 + ) == .reusePublishedService( + shouldStartAdvertising: false, + shouldAnnounceToSubscribedCentrals: false + )) + + #expect(BLEService.peripheralPoweredOnAction( + hasPublishedCharacteristic: true, + isAdvertising: false, + subscribedCentralCount: 2 + ) == .reusePublishedService( + shouldStartAdvertising: true, + shouldAnnounceToSubscribedCentrals: true + )) + } + /// Pings are unsigned, so their claimed sender is attacker-controlled. /// The pong budget must be keyed on the ingress link (the directly /// connected peer that delivered the packet): rotating forged sender IDs diff --git a/bitchatTests/SharedContentHandoffTests.swift b/bitchatTests/SharedContentHandoffTests.swift index ff205ad6..b2abc33d 100644 --- a/bitchatTests/SharedContentHandoffTests.swift +++ b/bitchatTests/SharedContentHandoffTests.swift @@ -170,4 +170,56 @@ struct SharedContentHandoffTests { #expect(model.offer?.payload == newer) #expect(context.store.pending(now: now) == newer) } + + @Test("App group ID prefers configured Info.plist AppGroupID and ignores unexpanded placeholders") + func appGroupIDResolutionPrefersConfiguredValue() { + #expect(BitchatApp.resolvedGroupID( + infoDictionary: ["AppGroupID": "group.chat.bitchat.TEAM123"], + bundleIdentifier: "chat.bitchat" + ) == "group.chat.bitchat.TEAM123") + + #expect(BitchatApp.resolvedGroupID( + infoDictionary: ["AppGroupID": " group.custom.bitchat "], + bundleIdentifier: "chat.bitchat" + ) == "group.custom.bitchat") + + #expect(BitchatApp.resolvedGroupID( + infoDictionary: ["AppGroupID": "$(APP_GROUP_ID)"], + bundleIdentifier: "chat.bitchat.local" + ) == "group.chat.bitchat.local") + + #expect(BitchatApp.resolvedGroupID( + infoDictionary: ["AppGroupID": " "], + bundleIdentifier: nil + ) == "group.chat.bitchat") + } + + @Test("Shared defaults are skipped when the App Group container is unavailable") + func sharedUserDefaultsRequiresAvailableContainer() { + var defaultsRequested = false + let missing = BitchatApp.sharedUserDefaults( + groupID: "group.chat.bitchat", + containerURLProvider: { _ in nil }, + defaultsProvider: { _ in + defaultsRequested = true + return UserDefaults(suiteName: "should-not-be-called") + } + ) + #expect(missing == nil) + #expect(!defaultsRequested) + + let context = makeStore() + defer { context.defaults.removePersistentDomain(forName: context.suite) } + var requestedGroupID: String? + let available = BitchatApp.sharedUserDefaults( + groupID: "group.chat.bitchat", + containerURLProvider: { id in + requestedGroupID = id + return URL(fileURLWithPath: "/tmp/mock-app-group") + }, + defaultsProvider: { _ in context.defaults } + ) + #expect(requestedGroupID == "group.chat.bitchat") + #expect(available === context.defaults) + } }