Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions LoopFollow/Helpers/APNsCredentialValidator.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
}
22 changes: 17 additions & 5 deletions LoopFollow/Hub/HubClient.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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: [])
Expand Down
10 changes: 5 additions & 5 deletions LoopFollow/Hub/HubManagedSettings.swift
Original file line number Diff line number Diff line change
Expand Up @@ -105,26 +105,26 @@ 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<Content: View>: View {
@ViewBuilder let content: Content

@ObservedObject private var deviceKey = HubClient.shared.deviceKey
@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
}
}
40 changes: 29 additions & 11 deletions LoopFollow/LiveActivity/LiveActivityManager.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
}
Expand Down Expand Up @@ -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 }
Expand Down Expand Up @@ -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<GlucoseLiveActivityAttributes>?,
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"
Expand Down Expand Up @@ -876,11 +876,21 @@ final class LiveActivityManager {
oldActivity: Activity<GlucoseLiveActivityAttributes>?,
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)))"
Expand Down Expand Up @@ -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(
Expand Down Expand Up @@ -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,
Expand Down
5 changes: 1 addition & 4 deletions LoopFollow/LiveActivity/RestartLiveActivityIntent.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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) }
}
Expand Down
2 changes: 1 addition & 1 deletion LoopFollow/LiveActivitySettingsView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
23 changes: 20 additions & 3 deletions LoopFollow/Settings/ImportExport/ExportableSettings.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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()),
Expand All @@ -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)
Expand Down Expand Up @@ -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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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))")
Expand Down Expand Up @@ -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:
Expand Down
19 changes: 19 additions & 0 deletions LoopFollow/Storage/Storage+Migrate.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand Down
2 changes: 1 addition & 1 deletion LoopFollow/Storage/Storage.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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<Int>(key: "migrationStep", defaultValue: 10)
var migrationStep = StorageValue<Int>(key: "migrationStep", defaultValue: 11)

var persistentNotification = StorageValue<Bool>(key: "persistentNotification", defaultValue: false)
var persistentNotificationLastBGTime = StorageValue<Date>(key: "persistentNotificationLastBGTime", defaultValue: .distantPast)
Expand Down
6 changes: 6 additions & 0 deletions LoopFollow/ViewControllers/MainViewController.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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() {
Expand Down
13 changes: 11 additions & 2 deletions RemoteShared/WatchCredentials.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
}