LoopAPNSService.swift 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766
  1. // LoopFollow
  2. // LoopAPNSService.swift
  3. import CryptoKit
  4. import Foundation
  5. import HealthKit
  6. import SwiftJWT
  7. class LoopAPNSService {
  8. private let storage = Storage.shared
  9. enum LoopAPNSError: Error, LocalizedError {
  10. case invalidConfiguration
  11. case jwtError
  12. case networkError
  13. case invalidResponse
  14. case noDeviceToken
  15. case noBundleIdentifier
  16. case unauthorized
  17. case deviceTokenNotConfigured
  18. case bundleIdentifierNotConfigured
  19. case rateLimited
  20. var errorDescription: String? {
  21. switch self {
  22. case .invalidConfiguration:
  23. return "Loop APNS Configuration not valid"
  24. case .jwtError:
  25. return "Failed generating JWT token, check APNS Key ID, APNS Key and Team ID"
  26. case .networkError:
  27. return "Network error occurred"
  28. case .invalidResponse:
  29. return "Invalid response from server"
  30. case .noDeviceToken:
  31. return "No device token found in profile"
  32. case .noBundleIdentifier:
  33. return "No bundle identifier found in profile"
  34. case .unauthorized:
  35. return "Unauthorized - check your API secret"
  36. case .deviceTokenNotConfigured:
  37. return "Device token not configured"
  38. case .bundleIdentifierNotConfigured:
  39. return "Bundle identifier not configured"
  40. case .rateLimited:
  41. return "Too many requests - please wait a few minutes before trying again"
  42. }
  43. }
  44. }
  45. private func createReturnNotificationInfo() -> ReturnNotificationInfo? {
  46. let loopFollowDeviceToken = Observable.shared.loopFollowDeviceToken.value
  47. guard !loopFollowDeviceToken.isEmpty else { return nil }
  48. // Get LoopFollow's own Team ID from BuildDetails.
  49. guard let loopFollowTeamID = BuildDetails.default.teamID, !loopFollowTeamID.isEmpty else {
  50. LogManager.shared.log(category: .apns, message: "LoopFollow Team ID not found in BuildDetails.plist. Cannot create return notification info.")
  51. return nil
  52. }
  53. // Get the target Loop app's Team ID from storage.
  54. let targetTeamId = storage.teamId.value ?? ""
  55. let teamIdsAreDifferent = loopFollowTeamID != targetTeamId
  56. let keyIdForReturn: String
  57. let apnsKeyForReturn: String
  58. if teamIdsAreDifferent {
  59. // Team IDs differ, use the separate return credentials.
  60. keyIdForReturn = storage.returnKeyId.value
  61. apnsKeyForReturn = storage.returnApnsKey.value
  62. } else {
  63. // Team IDs are the same, use the primary credentials.
  64. keyIdForReturn = storage.keyId.value
  65. apnsKeyForReturn = storage.apnsKey.value
  66. }
  67. // Ensure we have the necessary credentials.
  68. guard !keyIdForReturn.isEmpty, !apnsKeyForReturn.isEmpty else {
  69. LogManager.shared.log(category: .apns, message: "Missing required return APNS credentials. Check Remote Settings.")
  70. return nil
  71. }
  72. return ReturnNotificationInfo(
  73. productionEnvironment: BuildDetails.default.isTestFlightBuild(),
  74. deviceToken: loopFollowDeviceToken,
  75. bundleId: Bundle.main.bundleIdentifier ?? "",
  76. teamId: loopFollowTeamID,
  77. keyId: keyIdForReturn,
  78. apnsKey: apnsKeyForReturn
  79. )
  80. }
  81. /// Encrypts return notification info using OTP code
  82. private func encryptReturnNotificationInfo(returnInfo: ReturnNotificationInfo, otpCode: String) -> String? {
  83. guard let messenger = OTPSecureMessenger(otpCode: otpCode) else {
  84. LogManager.shared.log(category: .apns, message: "Failed to create OTP secure messenger")
  85. return nil
  86. }
  87. do {
  88. return try messenger.encrypt(returnInfo)
  89. } catch {
  90. LogManager.shared.log(category: .apns, message: "Failed to encrypt return notification info: \(error.localizedDescription)")
  91. return nil
  92. }
  93. }
  94. /// Validates the Loop APNS setup by checking all required fields
  95. /// - Returns: True if setup is valid, false otherwise
  96. func validateSetup() -> Bool {
  97. let hasKeyId = !storage.keyId.value.isEmpty
  98. let hasAPNSKey = !storage.apnsKey.value.isEmpty
  99. let hasQrCode = !storage.loopAPNSQrCodeURL.value.isEmpty
  100. let hasDeviceToken = !Storage.shared.deviceToken.value.isEmpty
  101. let hasBundleIdentifier = !Storage.shared.bundleId.value.isEmpty
  102. // For initial setup, we don't require device token and bundle identifier
  103. // These will be fetched when the user clicks "Refresh Device Token"
  104. let hasBasicSetup = hasKeyId && hasAPNSKey && hasQrCode
  105. // For full validation (after device token is fetched), check everything
  106. let hasFullSetup = hasBasicSetup && hasDeviceToken && hasBundleIdentifier
  107. return hasFullSetup
  108. }
  109. /// Sends carbs via APNS push notification
  110. /// - Parameters:
  111. /// - payload: The carbs payload to send
  112. /// - completion: Completion handler with success status and error message
  113. func sendCarbsViaAPNS(payload: LoopAPNSPayload, completion: @escaping (Bool, String?) -> Void) {
  114. guard validateSetup() else {
  115. let errorMessage = "Loop APNS Configuration not valid"
  116. LogManager.shared.log(category: .apns, message: errorMessage)
  117. completion(false, errorMessage)
  118. return
  119. }
  120. let deviceToken = Storage.shared.deviceToken.value
  121. let bundleIdentifier = Storage.shared.bundleId.value
  122. let keyId = storage.keyId.value
  123. let apnsKey = storage.apnsKey.value
  124. // Create APNS notification payload (matching Loop's expected format)
  125. let now = Date()
  126. let expiration = Date(timeIntervalSinceNow: 5 * 60) // 5 minutes from now
  127. // Create the complete notification payload (matching Nightscout's exact format)
  128. // Based on Nightscout's loop.js implementation
  129. let carbsAmount = payload.carbsAmount ?? 0.0
  130. let absorptionTime = payload.absorptionTime ?? 3.0
  131. let startTime = payload.consumedDate ?? now
  132. var finalPayload = [
  133. "carbs-entry": carbsAmount,
  134. "absorption-time": absorptionTime,
  135. "otp": String(payload.otp),
  136. "remote-address": "LoopFollow",
  137. "notes": "Sent via LoopFollow APNS",
  138. "entered-by": "LoopFollow",
  139. "sent-at": formatDateForAPNS(now),
  140. "expiration": formatDateForAPNS(expiration),
  141. "start-time": formatDateForAPNS(startTime),
  142. "alert": "Remote Carbs Entry: \(String(format: "%.1f", carbsAmount)) grams\nAbsorption Time: \(String(format: "%.1f", absorptionTime)) hours",
  143. ] as [String: Any]
  144. // Encrypt and include return notification info using OTP
  145. if let returnInfo = createReturnNotificationInfo() {
  146. LogManager.shared.log(category: .apns, message: "Created return notification info for carbs - deviceToken: \(returnInfo.deviceToken.prefix(8))..., bundleId: \(returnInfo.bundleId)")
  147. if let encryptedReturnInfo = encryptReturnNotificationInfo(returnInfo: returnInfo, otpCode: String(payload.otp)) {
  148. finalPayload["encrypted_return_notification"] = encryptedReturnInfo
  149. LogManager.shared.log(category: .apns, message: "Added encrypted_return_notification to carbs payload, length: \(encryptedReturnInfo.count)")
  150. } else {
  151. LogManager.shared.log(category: .apns, message: "Failed to encrypt return notification info for carbs command")
  152. }
  153. } else {
  154. LogManager.shared.log(category: .apns, message: "Failed to create return notification info for carbs command")
  155. }
  156. // Log the exact carbs amount for debugging precision issues
  157. LogManager.shared.log(category: .apns, message: "Carbs amount - Raw: \(payload.carbsAmount ?? 0.0), Formatted: \(String(format: "%.1f", carbsAmount)), JSON: \(carbsAmount)")
  158. LogManager.shared.log(category: .apns, message: "Absorption time - Raw: \(payload.absorptionTime ?? 3.0), Formatted: \(String(format: "%.1f", absorptionTime)), JSON: \(absorptionTime)")
  159. // Log carbs entry attempt
  160. LogManager.shared.log(category: .apns, message: "Sending carbs: \(String(format: "%.1f", carbsAmount))g, absorption: \(String(format: "%.1f", absorptionTime))h")
  161. sendAPNSNotification(
  162. deviceToken: deviceToken,
  163. bundleIdentifier: bundleIdentifier,
  164. keyId: keyId,
  165. apnsKey: apnsKey,
  166. payload: finalPayload,
  167. completion: completion
  168. )
  169. }
  170. /// Sends bolus via APNS push notification
  171. /// - Parameters:
  172. /// - payload: The bolus payload to send
  173. /// - completion: Completion handler with success status and error message
  174. func sendBolusViaAPNS(payload: LoopAPNSPayload, completion: @escaping (Bool, String?) -> Void) {
  175. guard validateSetup() else {
  176. let errorMessage = "Loop APNS Configuration not valid"
  177. LogManager.shared.log(category: .apns, message: errorMessage)
  178. completion(false, errorMessage)
  179. return
  180. }
  181. let deviceToken = Storage.shared.deviceToken.value
  182. let bundleIdentifier = Storage.shared.bundleId.value
  183. let keyId = storage.keyId.value
  184. let apnsKey = storage.apnsKey.value
  185. // Create APNS notification payload (matching Loop's expected format)
  186. let now = Date()
  187. let expiration = Date(timeIntervalSinceNow: 5 * 60) // 5 minutes from now
  188. // Create the complete notification payload (matching Nightscout's exact format)
  189. // Based on Nightscout's loop.js implementation
  190. let bolusAmount = payload.bolusAmount ?? 0.0
  191. var finalPayload = [
  192. "bolus-entry": bolusAmount,
  193. "otp": String(payload.otp),
  194. "remote-address": "LoopFollow",
  195. "notes": "Sent via LoopFollow APNS",
  196. "entered-by": "LoopFollow",
  197. "sent-at": formatDateForAPNS(now),
  198. "expiration": formatDateForAPNS(expiration),
  199. "alert": "Remote Bolus Entry: \(String(format: "%.2f", bolusAmount)) U",
  200. ] as [String: Any]
  201. // Encrypt and include return notification info using OTP
  202. if let returnInfo = createReturnNotificationInfo() {
  203. LogManager.shared.log(category: .apns, message: "Created return notification info for carbs - deviceToken: \(returnInfo.deviceToken.prefix(8))..., bundleId: \(returnInfo.bundleId)")
  204. if let encryptedReturnInfo = encryptReturnNotificationInfo(returnInfo: returnInfo, otpCode: String(payload.otp)) {
  205. finalPayload["encrypted_return_notification"] = encryptedReturnInfo
  206. LogManager.shared.log(category: .apns, message: "Added encrypted_return_notification to carbs payload, length: \(encryptedReturnInfo.count)")
  207. } else {
  208. LogManager.shared.log(category: .apns, message: "Failed to encrypt return notification info for carbs command")
  209. }
  210. } else {
  211. LogManager.shared.log(category: .apns, message: "Failed to create return notification info for carbs command")
  212. }
  213. // Log the exact bolus amount for debugging precision issues
  214. LogManager.shared.log(category: .apns, message: "Bolus amount - Raw: \(payload.bolusAmount ?? 0.0), Formatted: \(String(format: "%.2f", bolusAmount)), JSON: \(bolusAmount)")
  215. // Log bolus entry attempt
  216. LogManager.shared.log(category: .apns, message: "Sending bolus: \(String(format: "%.2f", bolusAmount))U")
  217. sendAPNSNotification(
  218. deviceToken: deviceToken,
  219. bundleIdentifier: bundleIdentifier,
  220. keyId: keyId,
  221. apnsKey: apnsKey,
  222. payload: finalPayload,
  223. completion: completion
  224. )
  225. }
  226. /// Validates APNS credentials similar to PushNotificationManager
  227. /// - Returns: Array of validation error messages, or nil if valid
  228. private func validateCredentials() -> [String]? {
  229. var errors = [String]()
  230. let keyId = storage.keyId.value
  231. let teamId = Storage.shared.teamId.value ?? ""
  232. let apnsKey = storage.apnsKey.value
  233. // Validate keyId (should be 10 alphanumeric characters)
  234. let keyIdPattern = "^[A-Z0-9]{10}$"
  235. if !matchesRegex(keyId, pattern: keyIdPattern) {
  236. errors.append("APNS Key ID (\(keyId)) must be 10 uppercase alphanumeric characters.")
  237. }
  238. // Validate teamId (should be 10 alphanumeric characters)
  239. let teamIdPattern = "^[A-Z0-9]{10}$"
  240. if !matchesRegex(teamId, pattern: teamIdPattern) {
  241. errors.append("Team ID (\(teamId)) must be 10 uppercase alphanumeric characters.")
  242. }
  243. // Validate apnsKey (should contain the BEGIN and END PRIVATE KEY markers)
  244. if !apnsKey.contains("-----BEGIN PRIVATE KEY-----") || !apnsKey.contains("-----END PRIVATE KEY-----") {
  245. errors.append("APNS Key must be a valid PEM-formatted private key.")
  246. } else {
  247. // Validate that the key data between the markers is valid Base64
  248. if let keyData = extractKeyData(from: apnsKey) {
  249. if Data(base64Encoded: keyData) == nil {
  250. errors.append("APNS Key contains invalid Base64 key data.")
  251. }
  252. } else {
  253. errors.append("APNS Key has invalid formatting.")
  254. }
  255. }
  256. return errors.isEmpty ? nil : errors
  257. }
  258. /// Helper method to match regex patterns
  259. /// - Parameters:
  260. /// - text: Text to match
  261. /// - pattern: Regex pattern
  262. /// - Returns: True if pattern matches
  263. private func matchesRegex(_ text: String, pattern: String) -> Bool {
  264. let regex = try? NSRegularExpression(pattern: pattern)
  265. let range = NSRange(location: 0, length: text.utf16.count)
  266. return regex?.firstMatch(in: text, options: [], range: range) != nil
  267. }
  268. /// Provides simple environment guidance for APNS configuration
  269. /// - Returns: String with simple guidance to try opposite setting
  270. private func getEnvironmentGuidance() -> String {
  271. let currentSetting = storage.productionEnvironment.value ? "ON" : "OFF"
  272. let trySetting = storage.productionEnvironment.value ? "OFF" : "ON"
  273. return "Try changing Production Environment from \(currentSetting) to \(trySetting) in your Loop APNS settings."
  274. }
  275. /// Sends an APNS notification
  276. /// - Parameters:
  277. /// - deviceToken: The device token to send to
  278. /// - bundleIdentifier: The bundle identifier
  279. /// - keyId: The APNS key ID
  280. /// - apnsKey: The APNS key
  281. /// - payload: The notification payload
  282. /// - completion: Completion handler with success status and error message
  283. private func sendAPNSNotification(
  284. deviceToken: String,
  285. bundleIdentifier: String,
  286. keyId: String,
  287. apnsKey: String,
  288. payload: [String: Any],
  289. completion: @escaping (Bool, String?) -> Void
  290. ) {
  291. // Validate credentials first
  292. if let validationErrors = validateCredentials() {
  293. let errorMessage = "Credential validation failed: \(validationErrors.joined(separator: ", "))"
  294. LogManager.shared.log(category: .apns, message: errorMessage)
  295. completion(false, errorMessage)
  296. return
  297. }
  298. // Create JWT token for APNS authentication
  299. guard let jwt = JWTManager.shared.getOrGenerateJWT(keyId: keyId, teamId: Storage.shared.teamId.value ?? "", apnsKey: apnsKey) else {
  300. let errorMessage = "Failed to generate JWT, please check that the APNS Key ID, APNS Key and Team ID are correct."
  301. LogManager.shared.log(category: .apns, message: errorMessage)
  302. completion(false, errorMessage)
  303. return
  304. }
  305. // Determine APNS environment
  306. let isProduction = storage.productionEnvironment.value
  307. let apnsURL = isProduction ? "https://api.push.apple.com" : "https://api.sandbox.push.apple.com"
  308. guard let requestURL = URL(string: "\(apnsURL)/3/device/\(deviceToken)") else {
  309. let errorMessage = "Failed to construct APNs URL"
  310. LogManager.shared.log(category: .apns, message: errorMessage)
  311. completion(false, errorMessage)
  312. return
  313. }
  314. var request = URLRequest(url: requestURL)
  315. request.httpMethod = "POST"
  316. request.setValue("application/json", forHTTPHeaderField: "content-type")
  317. request.setValue("bearer \(jwt)", forHTTPHeaderField: "authorization")
  318. request.setValue(bundleIdentifier, forHTTPHeaderField: "apns-topic")
  319. request.setValue("alert", forHTTPHeaderField: "apns-push-type")
  320. request.setValue("10", forHTTPHeaderField: "apns-priority") // High priority
  321. // Validate bundle identifier format
  322. if !bundleIdentifier.contains(".") {
  323. LogManager.shared.log(category: .apns, message: "Warning: Bundle identifier may be in wrong format: \(bundleIdentifier)")
  324. }
  325. // Create the proper APNS payload structure (matching @parse/node-apn format)
  326. var apnsPayload: [String: Any] = [
  327. "aps": [
  328. "alert": payload["alert"] as? String ?? "",
  329. "content-available": 1,
  330. "interruption-level": "time-sensitive",
  331. ],
  332. ]
  333. // Add all the custom payload fields (excluding APNS-specific fields)
  334. for (key, value) in payload {
  335. if key != "alert", key != "content-available", key != "interruption-level" {
  336. apnsPayload[key] = value
  337. }
  338. }
  339. // Remove nil values to clean up the payload
  340. let cleanPayload = apnsPayload.compactMapValues { $0 }
  341. // Log if encrypted_return_notification is in the payload
  342. if cleanPayload["encrypted_return_notification"] != nil {
  343. LogManager.shared.log(category: .apns, message: "encrypted_return_notification is present in final APNS payload")
  344. } else {
  345. LogManager.shared.log(category: .apns, message: "WARNING: encrypted_return_notification is NOT in final APNS payload. Available keys: \(Array(cleanPayload.keys).joined(separator: ", "))")
  346. }
  347. do {
  348. let jsonData = try JSONSerialization.data(withJSONObject: cleanPayload)
  349. request.httpBody = jsonData
  350. let task = URLSession.shared.dataTask(with: request) { data, response, error in
  351. if let error = error {
  352. let errorMessage = "Failed to send push notification: \(error.localizedDescription)"
  353. LogManager.shared.log(category: .apns, message: errorMessage)
  354. completion(false, errorMessage)
  355. return
  356. }
  357. if let httpResponse = response as? HTTPURLResponse {
  358. var responseBodyMessage = ""
  359. if let data = data, let responseBody = String(data: data, encoding: .utf8) {
  360. if let json = try? JSONSerialization.jsonObject(with: data, options: []) as? [String: Any],
  361. let reason = json["reason"] as? String
  362. {
  363. responseBodyMessage = reason
  364. }
  365. }
  366. switch httpResponse.statusCode {
  367. case 200:
  368. LogManager.shared.log(category: .apns, message: "APNS notification sent successfully")
  369. completion(true, nil)
  370. case 400:
  371. let environmentGuidance = self.getEnvironmentGuidance()
  372. let errorMessage = "Bad request. The request was invalid or malformed. \(responseBodyMessage)\n\n\(environmentGuidance)"
  373. LogManager.shared.log(category: .apns, message: "APNS error 400: \(responseBodyMessage) - Check device token and environment settings")
  374. completion(false, errorMessage)
  375. case 403:
  376. let errorMessage = "Authentication error. Check your certificate or authentication token. \(responseBodyMessage)"
  377. LogManager.shared.log(category: .apns, message: "APNS error 403: \(responseBodyMessage) - Check APNS key permissions for bundle ID")
  378. completion(false, errorMessage)
  379. case 404:
  380. let errorMessage = "Invalid request: The :path value was incorrect. \(responseBodyMessage)"
  381. LogManager.shared.log(category: .apns, message: "APNS error 404: \(responseBodyMessage)")
  382. completion(false, errorMessage)
  383. case 405:
  384. let errorMessage = "Invalid request: Only POST requests are supported. \(responseBodyMessage)"
  385. LogManager.shared.log(category: .apns, message: "APNS error 405: \(responseBodyMessage)")
  386. completion(false, errorMessage)
  387. case 410:
  388. let errorMessage = "The device token is no longer active for the topic. \(responseBodyMessage)"
  389. LogManager.shared.log(category: .apns, message: "APNS error 410: Device token is invalid or expired")
  390. completion(false, errorMessage)
  391. case 413:
  392. let errorMessage = "Payload too large. The notification payload exceeded the size limit. \(responseBodyMessage)"
  393. LogManager.shared.log(category: .apns, message: "APNS error 413: \(responseBodyMessage)")
  394. completion(false, errorMessage)
  395. case 429:
  396. let errorMessage = "Too many requests. \(responseBodyMessage)"
  397. LogManager.shared.log(category: .apns, message: "APNS error 429: Rate limited - wait before retrying")
  398. completion(false, errorMessage)
  399. case 500:
  400. let errorMessage = "Internal server error at APNs. \(responseBodyMessage)"
  401. LogManager.shared.log(category: .apns, message: "APNS error 500: \(responseBodyMessage)")
  402. completion(false, errorMessage)
  403. case 503:
  404. let errorMessage = "Service unavailable. The server is temporarily unavailable. Try again later. \(responseBodyMessage)"
  405. LogManager.shared.log(category: .apns, message: "APNS error 503: \(responseBodyMessage)")
  406. completion(false, errorMessage)
  407. default:
  408. let errorMessage = "Unexpected status code: \(httpResponse.statusCode). \(responseBodyMessage)"
  409. LogManager.shared.log(category: .apns, message: "APNS error \(httpResponse.statusCode): \(responseBodyMessage)")
  410. completion(false, errorMessage)
  411. }
  412. } else {
  413. let errorMessage = "Failed to get a valid HTTP response."
  414. LogManager.shared.log(category: .apns, message: errorMessage)
  415. completion(false, errorMessage)
  416. }
  417. }
  418. task.resume()
  419. } catch {
  420. let errorMessage = "Failed to serialize APNS payload: \(error.localizedDescription)"
  421. LogManager.shared.log(category: .apns, message: errorMessage)
  422. completion(false, errorMessage)
  423. }
  424. }
  425. /// Validates and fixes APNS key format if needed
  426. /// - Parameter key: The APNS key to validate and fix
  427. /// - Returns: The fixed APNS key
  428. func validateAndFixAPNSKey(_ key: String) -> String {
  429. // Normalize: replace all literal \n with real newlines
  430. var fixedKey = key.replacingOccurrences(of: "\\n", with: "\n")
  431. // Strip leading/trailing quotes
  432. fixedKey = fixedKey.trimmingCharacters(in: CharacterSet(charactersIn: "\"'"))
  433. // Check if the key has proper line breaks
  434. if !fixedKey.contains("\n") {
  435. LogManager.shared.log(category: .apns, message: "APNS Key missing line breaks, attempting to fix format")
  436. // Try to add line breaks if the key is all on one line
  437. if fixedKey.contains("-----BEGIN PRIVATE KEY-----") && fixedKey.contains("-----END PRIVATE KEY-----") {
  438. // Find the positions of the headers
  439. if let beginRange = fixedKey.range(of: "-----BEGIN PRIVATE KEY-----"),
  440. let endRange = fixedKey.range(of: "-----END PRIVATE KEY-----")
  441. {
  442. let beginIndex = fixedKey.index(beginRange.upperBound, offsetBy: 0)
  443. let endIndex = endRange.lowerBound
  444. if beginIndex < endIndex {
  445. let header = String(fixedKey[..<beginIndex])
  446. let keyData = String(fixedKey[beginIndex ..< endIndex])
  447. let footer = String(fixedKey[endIndex...])
  448. // Clean up the key data - remove any whitespace and split into 64-character lines
  449. let cleanKeyData = keyData.replacingOccurrences(of: " ", with: "")
  450. .replacingOccurrences(of: "\t", with: "")
  451. .replacingOccurrences(of: "\n", with: "")
  452. .replacingOccurrences(of: "\r", with: "")
  453. // Validate the key data length (should be 44 characters for P-256)
  454. LogManager.shared.log(category: .apns, message: "Key data validation - Length: \(cleanKeyData.count) characters")
  455. if cleanKeyData.count != 44 {
  456. LogManager.shared.log(category: .apns, message: "WARNING: Key data length is \(cleanKeyData.count), expected 44 for P-256 private key")
  457. }
  458. // Validate base64 format
  459. if Data(base64Encoded: cleanKeyData) == nil {
  460. LogManager.shared.log(category: .apns, message: "WARNING: Key data is not valid base64")
  461. }
  462. // Split into 64-character lines (standard PEM format)
  463. var formattedKeyData = ""
  464. var currentLine = ""
  465. for char in cleanKeyData {
  466. currentLine.append(char)
  467. if currentLine.count == 64 {
  468. formattedKeyData += currentLine + "\n"
  469. currentLine = ""
  470. }
  471. }
  472. // Add any remaining characters
  473. if !currentLine.isEmpty {
  474. formattedKeyData += currentLine
  475. }
  476. fixedKey = "\(header)\n\(formattedKeyData)\n\(footer)"
  477. LogManager.shared.log(category: .apns, message: "APNS Key format fixed - added proper line breaks")
  478. LogManager.shared.log(category: .apns, message: "Key data length: \(cleanKeyData.count) characters")
  479. LogManager.shared.log(category: .apns, message: "Formatted key lines: \(formattedKeyData.components(separatedBy: "\n").count)")
  480. }
  481. }
  482. }
  483. } else {
  484. // Key already has line breaks, but let's ensure proper formatting
  485. let lines = fixedKey.components(separatedBy: .newlines)
  486. var cleanedLines: [String] = []
  487. for line in lines {
  488. let cleanedLine = line.trimmingCharacters(in: .whitespacesAndNewlines)
  489. if !cleanedLine.isEmpty {
  490. cleanedLines.append(cleanedLine)
  491. }
  492. }
  493. // Reconstruct with proper formatting
  494. if cleanedLines.count > 2 {
  495. let header = cleanedLines[0]
  496. let footer = cleanedLines[cleanedLines.count - 1]
  497. let keyLines = Array(cleanedLines[1 ..< (cleanedLines.count - 1)])
  498. // Combine all key data lines and validate
  499. let combinedKeyData = keyLines.joined()
  500. LogManager.shared.log(category: .apns, message: "Combined key data length: \(combinedKeyData.count) characters")
  501. // Validate the key data length (should be 44 characters for P-256)
  502. if combinedKeyData.count != 44 {
  503. LogManager.shared.log(category: .apns, message: "WARNING: Combined key data length is \(combinedKeyData.count), expected 44 for P-256 private key")
  504. }
  505. // Validate base64 format
  506. if Data(base64Encoded: combinedKeyData) == nil {
  507. LogManager.shared.log(category: .apns, message: "WARNING: Combined key data is not valid base64")
  508. }
  509. // Ensure key lines are properly formatted (64 characters each)
  510. var formattedKeyLines: [String] = []
  511. var currentLine = ""
  512. for line in keyLines {
  513. let cleanLine = line.replacingOccurrences(of: " ", with: "")
  514. .replacingOccurrences(of: "\t", with: "")
  515. for char in cleanLine {
  516. currentLine.append(char)
  517. if currentLine.count == 64 {
  518. formattedKeyLines.append(currentLine)
  519. currentLine = ""
  520. }
  521. }
  522. }
  523. // Add any remaining characters
  524. if !currentLine.isEmpty {
  525. formattedKeyLines.append(currentLine)
  526. }
  527. fixedKey = "\(header)\n\(formattedKeyLines.joined(separator: "\n"))\n\(footer)"
  528. LogManager.shared.log(category: .apns, message: "APNS Key reformatted - cleaned up existing line breaks")
  529. }
  530. }
  531. return fixedKey
  532. }
  533. /// Extracts key data from PEM format
  534. /// - Parameter pemString: The PEM formatted private key
  535. /// - Returns: The extracted key data string
  536. private func extractKeyData(from pemString: String) -> String? {
  537. let lines = pemString.components(separatedBy: "\n")
  538. guard let startIndex = lines.firstIndex(of: "-----BEGIN PRIVATE KEY-----"),
  539. let endIndex = lines.firstIndex(of: "-----END PRIVATE KEY-----"),
  540. startIndex < endIndex
  541. else {
  542. return nil
  543. }
  544. let keyLines = lines[(startIndex + 1) ..< endIndex]
  545. return keyLines.joined()
  546. }
  547. // MARK: - Date Formatting Helper
  548. /// Creates a properly formatted ISO8601 date string with milliseconds (matching Nightscout's format)
  549. /// - Parameter date: The date to format
  550. /// - Returns: Formatted date string like "2022-12-24T21:34:02.090Z"
  551. private func formatDateForAPNS(_ date: Date) -> String {
  552. let dateFormatter = ISO8601DateFormatter()
  553. dateFormatter.formatOptions = [.withInternetDateTime, .withFractionalSeconds]
  554. return dateFormatter.string(from: date)
  555. }
  556. // MARK: - Override Methods
  557. func sendOverrideNotification(presetName: String, duration: TimeInterval? = nil, completion: @escaping (Bool, String?) -> Void) {
  558. let deviceToken = Storage.shared.deviceToken.value
  559. guard !deviceToken.isEmpty else {
  560. let errorMessage = "Device token not configured"
  561. LogManager.shared.log(category: .apns, message: errorMessage)
  562. completion(false, errorMessage)
  563. return
  564. }
  565. let bundleIdentifier = Storage.shared.bundleId.value
  566. guard !bundleIdentifier.isEmpty else {
  567. let errorMessage = "Bundle identifier not configured"
  568. LogManager.shared.log(category: .apns, message: errorMessage)
  569. completion(false, errorMessage)
  570. return
  571. }
  572. // Create APNS notification payload (matching Loop's expected format)
  573. let now = Date()
  574. let expiration = Date(timeIntervalSinceNow: 5 * 60) // 5 minutes from now
  575. // Create alert text (matching Nightscout's format)
  576. var alertText = "\(presetName) Temporary Override"
  577. if let duration = duration, duration > 0 {
  578. let hours = Int(duration / 3600)
  579. let minutes = Int((duration.truncatingRemainder(dividingBy: 3600)) / 60)
  580. if hours > 0 {
  581. alertText += " (\(hours)h \(minutes)m)"
  582. } else {
  583. alertText += " (\(minutes)m)"
  584. }
  585. }
  586. var payload: [String: Any] = [
  587. "override-name": presetName,
  588. "remote-address": "LoopFollow",
  589. "entered-by": "LoopFollow",
  590. "sent-at": formatDateForAPNS(now),
  591. "expiration": formatDateForAPNS(expiration),
  592. "alert": alertText,
  593. ]
  594. if let duration = duration, duration > 0 {
  595. payload["override-duration-minutes"] = Int(duration / 60)
  596. }
  597. // For override commands, we can include return notification info unencrypted
  598. // since override commands don't require OTP validation in Loop
  599. if let returnInfo = createReturnNotificationInfo() {
  600. payload["return_notification"] = [
  601. "production_environment": returnInfo.productionEnvironment,
  602. "device_token": returnInfo.deviceToken,
  603. "bundle_id": returnInfo.bundleId,
  604. "team_id": returnInfo.teamId,
  605. "key_id": returnInfo.keyId,
  606. "apns_key": returnInfo.apnsKey,
  607. ]
  608. }
  609. // Send the notification using the existing APNS infrastructure
  610. sendAPNSNotification(
  611. deviceToken: deviceToken,
  612. bundleIdentifier: bundleIdentifier,
  613. keyId: storage.keyId.value,
  614. apnsKey: storage.apnsKey.value,
  615. payload: payload,
  616. completion: completion
  617. )
  618. }
  619. func sendCancelOverrideNotification(completion: @escaping (Bool, String?) -> Void) {
  620. let deviceToken = Storage.shared.deviceToken.value
  621. guard !deviceToken.isEmpty else {
  622. let errorMessage = "Device token not configured"
  623. LogManager.shared.log(category: .apns, message: errorMessage)
  624. completion(false, errorMessage)
  625. return
  626. }
  627. let bundleIdentifier = Storage.shared.bundleId.value
  628. guard !bundleIdentifier.isEmpty else {
  629. let errorMessage = "Bundle identifier not configured"
  630. LogManager.shared.log(category: .apns, message: errorMessage)
  631. completion(false, errorMessage)
  632. return
  633. }
  634. // Create APNS notification payload (matching Loop's expected format)
  635. let now = Date()
  636. let expiration = Date(timeIntervalSinceNow: 5 * 60) // 5 minutes from now
  637. var payload: [String: Any] = [
  638. "cancel-temporary-override": "true",
  639. "remote-address": "LoopFollow",
  640. "entered-by": "LoopFollow",
  641. "sent-at": formatDateForAPNS(now),
  642. "expiration": formatDateForAPNS(expiration),
  643. "alert": "Cancel Temporary Override",
  644. ]
  645. // For override commands, we can include return notification info unencrypted
  646. // since override commands don't require OTP validation in Loop
  647. if let returnInfo = createReturnNotificationInfo() {
  648. payload["return_notification"] = [
  649. "production_environment": returnInfo.productionEnvironment,
  650. "device_token": returnInfo.deviceToken,
  651. "bundle_id": returnInfo.bundleId,
  652. "team_id": returnInfo.teamId,
  653. "key_id": returnInfo.keyId,
  654. "apns_key": returnInfo.apnsKey,
  655. ]
  656. }
  657. // Send the notification using the existing APNS infrastructure
  658. sendAPNSNotification(
  659. deviceToken: deviceToken,
  660. bundleIdentifier: bundleIdentifier,
  661. keyId: storage.keyId.value,
  662. apnsKey: storage.apnsKey.value,
  663. payload: payload,
  664. completion: completion
  665. )
  666. }
  667. }