diff --git a/LoopFollow/Helpers/APNsCredentialValidator.swift b/LoopFollow/Helpers/APNsCredentialValidator.swift index 6eae74f81..0c3454158 100644 --- a/LoopFollow/Helpers/APNsCredentialValidator.swift +++ b/LoopFollow/Helpers/APNsCredentialValidator.swift @@ -29,4 +29,9 @@ enum APNsCredentialValidator { static func isFullyConfigured(keyId: String, apnsKey: String) -> Bool { isValidKeyId(keyId) && isValidApnsKey(apnsKey) } + + /// LoopFollow's own key under Settings → APN is valid. + static var hasValidLoopFollowKey: Bool { + isFullyConfigured(keyId: Storage.shared.lfKeyId.value, apnsKey: Storage.shared.lfApnsKey.value) + } } diff --git a/LoopFollow/Hub/HubClient.swift b/LoopFollow/Hub/HubClient.swift index 6a2231449..b44cc9830 100644 --- a/LoopFollow/Hub/HubClient.swift +++ b/LoopFollow/Hub/HubClient.swift @@ -338,13 +338,19 @@ final class HubClient { isConnected && hubInfo.value?.features.contains(feature) == true } - /// This app holds an APN key of its own under Settings → APN. - static var hasOwnApnKey: Bool { - !Storage.shared.lfKeyId.value.isEmpty && !Storage.shared.lfApnsKey.value.isEmpty + /// In Hub mode this phone registers with the hub for the key an admin shares: it + /// joined with an invite or has no key of its own, and the hub shares keys. Until + /// the hub's status says the key is shared, the hub checklist tells why it is not. + var expectsSharedApnKey: Bool { + guard isHubMode else { return false } + return Self.apnsKeyUse(keyId: Storage.shared.lfKeyId.value, key: Storage.shared.lfApnsKey.value, + sentFingerprint: "", hubSharesKeys: offers("sharedApnsKey"), + ownKeyAllowed: !joinedWithInvite.value) == .shared } - /// The hub can push to this phone with a key: this app's own or one an admin shares. - var hasApnKey: Bool { Self.hasOwnApnKey || (isConnected && apnsKeyShared.value) } + /// The hub updates and renews the Live Activity with the key an admin shares, and + /// the app starts one only while it is open. + var liveActivityUsesSharedKey: Bool { expectsSharedApnKey && apnsKeyShared.value } /// LF Hub needs iOS 26: its alarms ring through silent mode as AlarmKit alarms. static var isSupported: Bool { @@ -1322,7 +1328,13 @@ final class HubClient { @MainActor private func record(_ status: Status) { if hubInfo.value != status.hub { hubInfo.value = status.hub } role.value = Self.role(reported: status.device.role, joinedWithInvite: joinedWithInvite.value) + let keyBecameShared = !apnsKeyShared.value && status.device.apnsKeyShared == true apnsKeyShared.value = status.device.apnsKeyShared == true + #if !targetEnvironment(macCatalyst) + if keyBecameShared, liveActivityUsesSharedKey { + LiveActivityManager.shared.startFromCurrentState() + } + #endif patientName.value = status.patient.name guard isHubMode else { setConfirmed(false, problems: []) diff --git a/LoopFollow/Hub/HubManagedSettings.swift b/LoopFollow/Hub/HubManagedSettings.swift index cb252207b..8fd5b9b20 100644 --- a/LoopFollow/Hub/HubManagedSettings.swift +++ b/LoopFollow/Hub/HubManagedSettings.swift @@ -105,6 +105,7 @@ extension HubSourceSync.State { } /// The APN settings while LF Hub pushes to this phone with the APN key an admin added. +/// The key here stays this phone's own: remote control signs with it. struct HubManagedApnKey: View { @ViewBuilder let content: Content @@ -112,19 +113,18 @@ struct HubManagedApnKey: View { @ObservedObject private var apnsKeyShared = HubClient.shared.apnsKeyShared private var shared: Bool { - HubClient.shared.isConnected && apnsKeyShared.value && !HubClient.hasOwnApnKey + HubClient.shared.isConnected && apnsKeyShared.value } var body: some View { if shared { Section { - Label("Managed by LF Hub", systemImage: "lock.fill") - Text("LF Hub notifies this phone with the APN key an admin added.") + Label("Shared by LF Hub", systemImage: "person.2.fill") + Text("LF Hub notifies this phone with the APN key an admin added. Remote Control needs a key here as well.") .font(.footnote) .foregroundColor(.secondary) } } - Group { content } - .disabled(shared) + content } } diff --git a/LoopFollow/LiveActivity/LiveActivityManager.swift b/LoopFollow/LiveActivity/LiveActivityManager.swift index 6e2433887..eab84fdd2 100644 --- a/LoopFollow/LiveActivity/LiveActivityManager.swift +++ b/LoopFollow/LiveActivity/LiveActivityManager.swift @@ -231,7 +231,7 @@ final class LiveActivityManager { await activity.update(content) LogManager.shared.log(category: .general, message: "[LA] resign-active flush sent seq=\(nextSeq)", isDebug: true) // Also send APNs so the extension receives the latest token-based update. - if let token = pushToken { + if let token = pushToken, APNsCredentialValidator.hasValidLoopFollowKey { await APNSClient.shared.sendLiveActivityUpdate(pushToken: token, state: state) } } @@ -714,8 +714,9 @@ final class LiveActivityManager { /// deadline has passed, working around Apple's 8-hour maximum LA lifetime. /// Returns true if renewal was performed (caller should return early). private func renewIfNeeded(snapshot: GlucoseSnapshot) -> Bool { - // LF Hub renews through push-to-start when it drives the activity. - guard !HubClient.shared.drivesLiveActivity, let oldActivity = current else { return false } + // LF Hub renews through push-to-start when it drives the activity or pushes with the key an admin shares. + guard !HubClient.shared.drivesLiveActivity, !HubClient.shared.expectsSharedApnKey, + let oldActivity = current else { return false } let renewBy = Storage.shared.laRenewBy.value guard renewBy > 0, Date().timeIntervalSince1970 >= renewBy else { return false } @@ -772,17 +773,16 @@ final class LiveActivityManager { /// Foreground-only local creation via Activity.request(pushType: .token). /// Returns false when creation is not possible; the caller decides whether - /// to fall back to push-to-start. APNs credentials stay a hard prerequisite - /// even here — background renewal and updates depend on them. + /// to fall back to push-to-start. APNs credentials, this app's own or the key + /// LF Hub holds, stay a hard prerequisite even here — background renewal and + /// updates depend on them. @MainActor private func attemptLocalCreate( reason: String, oldActivity: Activity?, snapshot: GlucoseSnapshot? = nil ) -> Bool { - let keyId = Storage.shared.lfKeyId.value - let apnsKey = Storage.shared.lfApnsKey.value - guard APNsCredentialValidator.isFullyConfigured(keyId: keyId, apnsKey: apnsKey) else { + guard APNsCredentialValidator.hasValidLoopFollowKey || HubClient.shared.liveActivityUsesSharedKey else { LogManager.shared.log( category: .general, message: "[LA] local create (\(reason)) blocked — APNs credentials missing" @@ -876,11 +876,21 @@ final class LiveActivityManager { oldActivity: Activity?, snapshot: GlucoseSnapshot? = nil ) { + // The app cannot sign a push-to-start with the key LF Hub holds; the hub renews + // the activity, and the app starts one locally the next time it is open. + if HubClient.shared.expectsSharedApnKey { + LogManager.shared.log( + category: .general, + message: "[LA] push-to-start (\(reason)) skipped — LF Hub pushes with the key an admin shares (shared=\(HubClient.shared.apnsKeyShared.value))" + ) + return + } + // Validate APNs credentials up-front — push-to-start is the only // transport, so missing/invalid creds mean the LA will never display. let keyId = Storage.shared.lfKeyId.value let apnsKey = Storage.shared.lfApnsKey.value - guard APNsCredentialValidator.isFullyConfigured(keyId: keyId, apnsKey: apnsKey) else { + guard APNsCredentialValidator.hasValidLoopFollowKey else { LogManager.shared.log( category: .general, message: "[LA] push-to-start (\(reason)) blocked — APNs credentials missing or invalid (keyId valid=\(APNsCredentialValidator.isValidKeyId(keyId)), apnsKey valid=\(APNsCredentialValidator.isValidApnsKey(apnsKey)))" @@ -1229,7 +1239,13 @@ final class LiveActivityManager { lastUpdateTime = Date() LogManager.shared.log(category: .general, message: "[LA] updated id=\(activityID) seq=\(nextSeq) reason=\(reason)", isDebug: true) - if let token = pushToken { + if !APNsCredentialValidator.hasValidLoopFollowKey { + LogManager.shared.log( + category: .general, + message: "[LA] update seq=\(nextSeq) reason=\(reason) — no APN key of this app's own, APNs skipped", + isDebug: true + ) + } else if let token = pushToken { await APNSClient.shared.sendLiveActivityUpdate(pushToken: token, state: state) } else { LogManager.shared.log( @@ -1367,7 +1383,9 @@ final class LiveActivityManager { private func scheduleApnsCredentialsMissingNotification() { let content = UNMutableNotificationContent() content.title = "Live Activity Setup Needed" - content.body = "APNs credentials are missing or invalid. Configure them in Settings → APN." + content.body = HubClient.shared.isConnected && HubClient.shared.apnsKeyShared.value + ? "LF Hub updates the Live Activity only while Background Refresh uses LF Hub. Choose LF Hub there, or add an APN key in Settings → APN." + : "APNs credentials are missing or invalid. Configure them in Settings → APN." content.sound = .default let request = UNNotificationRequest( identifier: LiveActivityManager.apnsCredentialsNotificationID, diff --git a/LoopFollow/LiveActivity/RestartLiveActivityIntent.swift b/LoopFollow/LiveActivity/RestartLiveActivityIntent.swift index 5a25afdae..8e3ccec50 100644 --- a/LoopFollow/LiveActivity/RestartLiveActivityIntent.swift +++ b/LoopFollow/LiveActivity/RestartLiveActivityIntent.swift @@ -12,10 +12,7 @@ func perform() async throws -> some IntentResult & ProvidesDialog { Storage.shared.laEnabled.value = true - let keyId = Storage.shared.lfKeyId.value - let apnsKey = Storage.shared.lfApnsKey.value - - if keyId.isEmpty || apnsKey.isEmpty { + if !APNsCredentialValidator.hasValidLoopFollowKey, !HubClient.shared.liveActivityUsesSharedKey { if let url = URL(string: "loopfollow://settings/live-activity") { await MainActor.run { UIApplication.shared.open(url) } } diff --git a/LoopFollow/LiveActivitySettingsView.swift b/LoopFollow/LiveActivitySettingsView.swift index a835dd613..1b0f436ba 100644 --- a/LoopFollow/LiveActivitySettingsView.swift +++ b/LoopFollow/LiveActivitySettingsView.swift @@ -19,7 +19,7 @@ /// with which the hub updates the Live Activity. private var apnsConfigured: Bool { APNsCredentialValidator.isFullyConfigured(keyId: keyId, apnsKey: apnsKey) - || (HubClient.shared.isHubMode && HubClient.shared.apnsKeyShared.value) + || HubClient.shared.liveActivityUsesSharedKey } var body: some View { diff --git a/LoopFollow/Settings/ImportExport/ExportableSettings.swift b/LoopFollow/Settings/ImportExport/ExportableSettings.swift index 1150a6831..a804680a9 100644 --- a/LoopFollow/Settings/ImportExport/ExportableSettings.swift +++ b/LoopFollow/Settings/ImportExport/ExportableSettings.swift @@ -245,15 +245,23 @@ struct RemoteSettingsExport: Codable { let loopMaxFutureCarbHours: Int? let device: String + /// The key fields carry the key that signs commands, so a phone of the same team + /// gets LoopFollow's own key from them; without one, the remote key as stored. static func fromCurrentStorage() -> RemoteSettingsExport { let storage = Storage.shared + let signing = RemoteSigningKey.resolve( + lfTeamID: BuildDetails.default.teamID ?? "", + remoteTeamID: storage.teamId.value ?? "", + lfKey: (storage.lfApnsKey.value, storage.lfKeyId.value), + remoteKey: (storage.remoteApnsKey.value, storage.remoteKeyId.value) + ) return RemoteSettingsExport( version: AppVersionManager().version(), remoteType: storage.remoteType.value, user: storage.user.value, sharedSecret: storage.sharedSecret.value, - remoteApnsKey: storage.remoteApnsKey.value, - remoteKeyId: storage.remoteKeyId.value, + remoteApnsKey: signing.key.isEmpty ? storage.remoteApnsKey.value : signing.key, + remoteKeyId: signing.key.isEmpty ? storage.remoteKeyId.value : signing.keyID, teamId: storage.teamId.value, maxBolus: storage.maxBolus.value.doubleValue(for: .internationalUnit()), maxCarbs: storage.maxCarbs.value.doubleValue(for: .gram()), @@ -277,6 +285,7 @@ struct RemoteSettingsExport: Codable { storage.remoteApnsKey.value = remoteApnsKey storage.remoteKeyId.value = remoteKeyId storage.teamId.value = teamId + storage.adoptRemoteKeyAsLoopFollowKey() storage.maxBolus.value = HKQuantity(unit: .internationalUnit(), doubleValue: maxBolus) storage.maxCarbs.value = HKQuantity(unit: .gram(), doubleValue: maxCarbs) storage.maxProtein.value = HKQuantity(unit: .gram(), doubleValue: maxProtein) @@ -400,16 +409,24 @@ struct APNSSettingsExport: Codable { let version: String let keyId: String let apnsKey: String + /// The exporting LoopFollow's team; nil from versions that did not send it. + let teamId: String? static func fromCurrentStorage() -> APNSSettingsExport { let storage = Storage.shared return APNSSettingsExport( version: AppVersionManager().version(), keyId: storage.lfKeyId.value, - apnsKey: storage.lfApnsKey.value + apnsKey: storage.lfApnsKey.value, + teamId: BuildDetails.default.teamID ) } + /// The key belongs to this LoopFollow's team, or one of the teams is not known. + var matchesThisBuild: Bool { + !RemoteSigningKey.otherTeam(lfTeamID: BuildDetails.default.teamID ?? "", remoteTeamID: teamId ?? "") + } + func applyToStorage() { let storage = Storage.shared storage.lfKeyId.value = keyId diff --git a/LoopFollow/Settings/ImportExport/ImportExportSettingsViewModel.swift b/LoopFollow/Settings/ImportExport/ImportExportSettingsViewModel.swift index 0550e609e..f5aad830f 100644 --- a/LoopFollow/Settings/ImportExport/ImportExportSettingsViewModel.swift +++ b/LoopFollow/Settings/ImportExport/ImportExportSettingsViewModel.swift @@ -177,7 +177,16 @@ class ImportExportSettingsViewModel: ObservableObject { } if let apns = settings.apns { - if apns.hasValidSettings() { + if !apns.matchesThisBuild { + // A Remote Settings export of another team carries its LoopFollow key too. + guard settings.remote != nil else { + throw NSError(domain: "SettingsImport", code: 4, userInfo: [NSLocalizedDescriptionKey: "The APNS settings in \(source) belong to a LoopFollow built with another Apple Developer account"]) + } + LogManager.shared.log(category: .general, message: "APNS settings from \(source) skipped: team \(apns.teamId ?? "") is not this build's") + } else if settings.remote != nil, APNsCredentialValidator.hasValidLoopFollowKey { + // The key that goes along with Remote Settings never replaces this phone's own. + LogManager.shared.log(category: .general, message: "APNS settings from \(source) skipped: this phone has its own key") + } else if apns.hasValidSettings() { apns.applyToStorage() importedComponents.append("APNS settings") LogManager.shared.log(category: .general, message: "APNS settings imported from \(source) (version: \(apns.version), keyId: \(apns.keyId))") @@ -218,8 +227,14 @@ class ImportExportSettingsViewModel: ObservableObject { } return nil } + // Commands to an app of another team are signed with the remote key, so + // LoopFollow's own key, which confirmations need, goes along. + let apnsSettings = APNSSettingsExport.fromCurrentStorage() + let otherTeam = RemoteSigningKey.otherTeam(lfTeamID: BuildDetails.default.teamID ?? "", + remoteTeamID: remoteSettings.teamId ?? "") settings = CombinedSettingsExport( remote: remoteSettings, + apns: otherTeam && apnsSettings.hasValidSettings() ? apnsSettings : nil, exportType: exportType.rawValue ) case .alarms: diff --git a/LoopFollow/Storage/Storage+Migrate.swift b/LoopFollow/Storage/Storage+Migrate.swift index 93d9bc0f5..5b14f4e6c 100644 --- a/LoopFollow/Storage/Storage+Migrate.swift +++ b/LoopFollow/Storage/Storage+Migrate.swift @@ -106,6 +106,25 @@ extension Storage { debugLogLevel.value = true } + /// Commands to a Loop or Trio app of LoopFollow's own team are signed with LoopFollow's + /// key: without a valid one, the remote key becomes it when the remote team is known + /// and is this build's team. + func adoptRemoteKeyAsLoopFollowKey() { + let lfTeamId = BuildDetails.default.teamID ?? "" + guard RemoteSigningKey.sameTeam(lfTeamID: lfTeamId, remoteTeamID: teamId.value ?? ""), + !APNsCredentialValidator.hasValidLoopFollowKey, + APNsCredentialValidator.isFullyConfigured(keyId: remoteKeyId.value, apnsKey: remoteApnsKey.value) + else { return } + LogManager.shared.log(category: .general, message: "Remote APN key of team \(lfTeamId) taken as LoopFollow's own key") + lfKeyId.value = remoteKeyId.value + lfApnsKey.value = LoopAPNSService().validateAndFixAPNSKey(remoteApnsKey.value) + } + + func migrateStep11() { + LogManager.shared.log(category: .general, message: "Running migrateStep11 — LoopFollow APN key from a same-team remote key") + adoptRemoteKeyAsLoopFollowKey() + } + func migrateStep6() { // APNs credential separation LogManager.shared.log(category: .general, message: "Running migrateStep6 — APNs credential separation") diff --git a/LoopFollow/Storage/Storage.swift b/LoopFollow/Storage/Storage.swift index 641c5d583..5dd92b44d 100644 --- a/LoopFollow/Storage/Storage.swift +++ b/LoopFollow/Storage/Storage.swift @@ -246,7 +246,7 @@ class Storage { // When adding a new migration step in `runMigrationsIfNeeded()`, bump this default // to the new latest step number so fresh installs skip all migrations. Other defaults // in this file must reflect the post-migration final state for a fresh install. - var migrationStep = StorageValue(key: "migrationStep", defaultValue: 10) + var migrationStep = StorageValue(key: "migrationStep", defaultValue: 11) var persistentNotification = StorageValue(key: "persistentNotification", defaultValue: false) var persistentNotificationLastBGTime = StorageValue(key: "persistentNotificationLastBGTime", defaultValue: .distantPast) diff --git a/LoopFollow/ViewControllers/MainViewController.swift b/LoopFollow/ViewControllers/MainViewController.swift index c5fb0f523..22115acc2 100644 --- a/LoopFollow/ViewControllers/MainViewController.swift +++ b/LoopFollow/ViewControllers/MainViewController.swift @@ -737,6 +737,12 @@ class MainViewController: UIViewController, UNUserNotificationCenterDelegate { Storage.shared.migrateStep10() Storage.shared.migrationStep.value = 10 } + + // Step 11: Added in dev 8.0.8 (2026-11-19). Can be removed after 2027-11-19. + if Storage.shared.migrationStep.value < 11 { + Storage.shared.migrateStep11() + Storage.shared.migrationStep.value = 11 + } } @objc func appDidBecomeActive() { diff --git a/RemoteShared/WatchCredentials.swift b/RemoteShared/WatchCredentials.swift index 2830e858a..fc8377c9f 100644 --- a/RemoteShared/WatchCredentials.swift +++ b/RemoteShared/WatchCredentials.swift @@ -59,10 +59,19 @@ enum RemoteSigningKey { lfKey: (key: String, keyID: String), remoteKey: (key: String, keyID: String) ) -> (key: String, keyID: String, teamID: String) { - let sameTeam = !lfTeamID.isEmpty && !remoteTeamID.isEmpty && lfTeamID == remoteTeamID - if sameTeam || remoteTeamID.isEmpty { + if sameTeam(lfTeamID: lfTeamID, remoteTeamID: remoteTeamID) || remoteTeamID.isEmpty { return (lfKey.key, lfKey.keyID, lfTeamID) } return (remoteKey.key, remoteKey.keyID, remoteTeamID) } + + /// Both teams are known and the same. + static func sameTeam(lfTeamID: String, remoteTeamID: String) -> Bool { + !lfTeamID.isEmpty && !remoteTeamID.isEmpty && lfTeamID == remoteTeamID + } + + /// Both teams are known and differ. + static func otherTeam(lfTeamID: String, remoteTeamID: String) -> Bool { + !lfTeamID.isEmpty && !remoteTeamID.isEmpty && lfTeamID != remoteTeamID + } }