diff --git a/Sources/PushNotifications/PushNotificationCipher.swift b/Sources/PushNotifications/PushNotificationCipher.swift index 0587435..54fca4e 100644 --- a/Sources/PushNotifications/PushNotificationCipher.swift +++ b/Sources/PushNotifications/PushNotificationCipher.swift @@ -13,9 +13,7 @@ import Common class PushNotificationCipher { static func decrypt(payload: String, iv: String) -> PushNotification? { - // Decode PrivateKey from base64 to String - guard let privateKey = UserSessionFactory.shared.getCurrentNotificationDeviceConfiguration()?.notificationsEncryptionKey, - let privateKeyAsData = Data(base64Encoded: privateKey) else { + guard let privateKey = UserSessionFactory.shared.getCurrentNotificationEncryptionKey() else { return nil } @@ -24,7 +22,7 @@ class PushNotificationCipher { return nil } - let uint8Key = [UInt8](privateKeyAsData) + let uint8Key = [UInt8](privateKey) let uint8Iv = [UInt8](ivAsData) guard let payloadAsData = Data(base64Encoded: payload) else { diff --git a/Sources/UserStore/UserSession.swift b/Sources/UserStore/UserSession.swift index fff77f3..f4e93ba 100644 --- a/Sources/UserStore/UserSession.swift +++ b/Sources/UserStore/UserSession.swift @@ -120,6 +120,21 @@ public class UserSession: ObservableObject { notificationDeviceConfigurations.first(where: { $0.institutionIdentifier == institution && $0.username == username }) } + /// Gets the currently active key for decrypting notifications. + /// This force-loads the latest keychain data because the notification extension can outlive the app, + /// thus the key may have changed while the UserSession is still in memory + public func getCurrentNotificationEncryptionKey() -> Data? { + setupLoginData() + setupInstitutionSelection() + setupNotificationData() + guard let config = getCurrentNotificationDeviceConfiguration(), + let key = config.notificationsEncryptionKey, + let keyAsData = Data(base64Encoded: key) else { + return nil + } + return keyAsData + } + public func saveInstitution(identifier: InstitutionIdentifier?) { self.institution = identifier