|
| 1 | +/* |
| 2 | + Modified MIT License |
| 3 | + |
| 4 | + Copyright 2026 OneSignal |
| 5 | + |
| 6 | + Permission is hereby granted, free of charge, to any person obtaining a copy |
| 7 | + of this software and associated documentation files (the "Software"), to deal |
| 8 | + in the Software without restriction, including without limitation the rights |
| 9 | + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell |
| 10 | + copies of the Software, and to permit persons to whom the Software is |
| 11 | + furnished to do so, subject to the following conditions: |
| 12 | + |
| 13 | + 1. The above copyright notice and this permission notice shall be included in |
| 14 | + all copies or substantial portions of the Software. |
| 15 | + |
| 16 | + 2. All copies of substantial portions of the Software may only be used in connection |
| 17 | + with services provided by OneSignal. |
| 18 | + |
| 19 | + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR |
| 20 | + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, |
| 21 | + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE |
| 22 | + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER |
| 23 | + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, |
| 24 | + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN |
| 25 | + THE SOFTWARE. |
| 26 | + */ |
| 27 | + |
| 28 | +import Foundation |
| 29 | +import OneSignalCore |
| 30 | + |
| 31 | +/// File-backed mirror of OneSignal SDK identifiers, written with `NSFileProtectionNone` |
| 32 | +/// so it's readable before first unlock, when shared `UserDefaults` reads silently return nil. |
| 33 | +/// |
| 34 | +/// Stored in the App Group container, so it's shared across any targets (main app, NSE, etc.) |
| 35 | +/// configured with the same App Group entitlement. Opaque identifiers only: no PII or credentials. |
| 36 | +@objc(OSResilientStorage) |
| 37 | +public final class OSResilientStorage: NSObject { |
| 38 | + |
| 39 | + // MARK: - Public key constants |
| 40 | + |
| 41 | + @objc public static let keyAppId = "app_id" |
| 42 | + @objc public static let keySubscriptionId = "subscription_id" |
| 43 | + @objc public static let keyOneSignalId = "onesignal_id" |
| 44 | + /// Needed because the NSE reads this flag from shared UserDefaults while the device may be locked |
| 45 | + /// and the read silently returns the default (NO). Stored as "1" / "0". |
| 46 | + @objc public static let keyReceiveReceiptsEnabled = "receive_receipts_enabled" |
| 47 | + |
| 48 | + // MARK: - Internal |
| 49 | + |
| 50 | + private static let fileName = "onesignal_identity.json" |
| 51 | + |
| 52 | + /// Serial queue used to serialize all file reads/writes. |
| 53 | + private static let queue = DispatchQueue(label: "com.onesignal.resilient-storage") |
| 54 | + |
| 55 | + /// Resolve a writable container URL. App Group container is preferred so |
| 56 | + /// the NSE can read the same file. Falls back to the app's private |
| 57 | + /// Application Support directory when no App Group is entitled. |
| 58 | + private static func fileURL() -> URL? { |
| 59 | + let fm = FileManager.default |
| 60 | + |
| 61 | + let groupName = OneSignalUserDefaults.appGroupName() |
| 62 | + if let container = fm.containerURL(forSecurityApplicationGroupIdentifier: groupName) { |
| 63 | + return container.appendingPathComponent(fileName) |
| 64 | + } |
| 65 | + |
| 66 | + do { |
| 67 | + let support = try fm.url( |
| 68 | + for: .applicationSupportDirectory, |
| 69 | + in: .userDomainMask, |
| 70 | + appropriateFor: nil, |
| 71 | + create: true |
| 72 | + ) |
| 73 | + return support.appendingPathComponent(fileName) |
| 74 | + } catch { |
| 75 | + OneSignalLog.onesignalLog(.LL_ERROR, message: "OSResilientStorage could not resolve a container URL: \(error)") |
| 76 | + return nil |
| 77 | + } |
| 78 | + } |
| 79 | + |
| 80 | + /// Reads the cache file. Caller is responsible for queue-serialization. |
| 81 | + /// Returns an empty dict if the file is missing or unreadable. |
| 82 | + private static func loadUnsafe() -> [String: String] { |
| 83 | + guard let url = fileURL() else { return [:] } |
| 84 | + guard FileManager.default.fileExists(atPath: url.path) else { return [:] } |
| 85 | + |
| 86 | + do { |
| 87 | + let data = try Data(contentsOf: url) |
| 88 | + if data.isEmpty { return [:] } |
| 89 | + let object = try JSONSerialization.jsonObject(with: data, options: []) |
| 90 | + return (object as? [String: String]) ?? [:] |
| 91 | + } catch { |
| 92 | + OneSignalLog.onesignalLog(.LL_WARN, message: "OSResilientStorage could not read file: \(error)") |
| 93 | + return [:] |
| 94 | + } |
| 95 | + } |
| 96 | + |
| 97 | + /// Writes the cache file atomically with `.none` file protection. |
| 98 | + /// Caller is responsible for queue-serialization. |
| 99 | + private static func writeUnsafe(_ contents: [String: String]) { |
| 100 | + guard let url = fileURL() else { return } |
| 101 | + |
| 102 | + do { |
| 103 | + let data = try JSONSerialization.data(withJSONObject: contents, options: []) |
| 104 | + try data.write(to: url, options: [.atomic, .noFileProtection]) |
| 105 | + |
| 106 | + // Explicitly re-apply protection class. The atomic write performs a rename which |
| 107 | + // has been observed to reset attributes on some iOS versions. |
| 108 | + try FileManager.default.setAttributes( |
| 109 | + [.protectionKey: FileProtectionType.none], |
| 110 | + ofItemAtPath: url.path |
| 111 | + ) |
| 112 | + } catch { |
| 113 | + OneSignalLog.onesignalLog(.LL_ERROR, message: "OSResilientStorage write failed: \(error)") |
| 114 | + } |
| 115 | + } |
| 116 | + |
| 117 | + // MARK: - Public API |
| 118 | + |
| 119 | + /// Returns the full current contents of the cache. Empty dict if absent. |
| 120 | + @objc public static func snapshot() -> [String: String] { |
| 121 | + return queue.sync { loadUnsafe() } |
| 122 | + } |
| 123 | + |
| 124 | + /// Reads a single value. Returns nil when missing or unreadable. |
| 125 | + @objc public static func string(forKey key: String) -> String? { |
| 126 | + let dict = snapshot() |
| 127 | + guard let value = dict[key], !value.isEmpty else { return nil } |
| 128 | + return value |
| 129 | + } |
| 130 | + |
| 131 | + /// Atomically updates a single value. Passing nil or an empty string removes the key. |
| 132 | + @objc public static func setString(_ value: String?, forKey key: String) { |
| 133 | + queue.async { |
| 134 | + var current = loadUnsafe() |
| 135 | + if let value = value, !value.isEmpty { |
| 136 | + current[key] = value |
| 137 | + } else { |
| 138 | + current.removeValue(forKey: key) |
| 139 | + } |
| 140 | + writeUnsafe(current) |
| 141 | + } |
| 142 | + } |
| 143 | + |
| 144 | + /// Atomically updates multiple values, preserving keys not in `values`. |
| 145 | + /// An empty-string value removes the corresponding key. |
| 146 | + @objc public static func setStrings(_ values: [String: String]) { |
| 147 | + guard !values.isEmpty else { return } |
| 148 | + queue.async { |
| 149 | + var current = loadUnsafe() |
| 150 | + for (key, value) in values { |
| 151 | + if value.isEmpty { |
| 152 | + current.removeValue(forKey: key) |
| 153 | + } else { |
| 154 | + current[key] = value |
| 155 | + } |
| 156 | + } |
| 157 | + writeUnsafe(current) |
| 158 | + } |
| 159 | + } |
| 160 | +} |
0 commit comments