Fix App Group defaults lookup and preserve restored BLE GATT service (#1919)

Co-authored-by: jack <jackjackbits@users.noreply.github.com>
This commit is contained in:
jackandjack authored and GitHub committed 2026-11-27 10:49:45 -10:00
1 parent 87ae09c316
commit cc37cb0946
7 files changed
+303 -27

No files matched your search

+1 -1
View File
@@ -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
+33 -1
View File
@@ -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
@@ -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
)
}
}
+1 -1
View File
@@ -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()
}
@@ -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
}
+88
View File
@@ -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
@@ -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)
}
}