97 lines
4.2 KiB
Swift
97 lines
4.2 KiB
Swift
import Foundation
|
|
import Security
|
|
|
|
/// Keeps the backend's HttpOnly session and refresh cookies available when Xcode
|
|
/// replaces a SwiftUI preview process. Cookie values stay in the Keychain.
|
|
enum AuthCookiePersistence {
|
|
private static let service = "dk.lucasskt.MusicApp.auth-cookies"
|
|
private static let account = "music.lucasskt.dk"
|
|
|
|
static func restore(into storage: HTTPCookieStorage, for url: URL) {
|
|
guard let data = read() else {
|
|
debug("restore: no Keychain record for host=\(url.host ?? "?")")
|
|
return
|
|
}
|
|
guard let properties = try? PropertyListSerialization.propertyList(
|
|
from: data, options: [], format: nil) as? [[HTTPCookiePropertyKey: Any]] else {
|
|
debug("restore: Keychain data could not be decoded (\(data.count) bytes)")
|
|
return
|
|
}
|
|
|
|
let cookies = properties.compactMap(HTTPCookie.init(properties:))
|
|
.filter { $0.domain.hasSuffix("music.lucasskt.dk") && $0.expiresDate.map { $0 > Date() } ?? true }
|
|
storage.setCookies(cookies, for: url, mainDocumentURL: nil)
|
|
debug("restore: loaded \(cookies.count) cookies [\(cookieNames(cookies))] for host=\(url.host ?? "?")")
|
|
}
|
|
|
|
static func save(from storage: HTTPCookieStorage, for url: URL) {
|
|
let properties = storage.cookies(for: url)?
|
|
.filter { $0.domain.hasSuffix("music.lucasskt.dk") }
|
|
.compactMap(\.properties) ?? []
|
|
guard let data = try? PropertyListSerialization.data(
|
|
fromPropertyList: properties, format: .binary, options: 0)
|
|
else {
|
|
debug("save: cookie properties could not be encoded [\(cookieNames(storage.cookies(for: url) ?? []))]")
|
|
return
|
|
}
|
|
|
|
let query: [String: Any] = [
|
|
kSecClass as String: kSecClassGenericPassword,
|
|
kSecAttrService as String: service,
|
|
kSecAttrAccount as String: account,
|
|
]
|
|
let update: [String: Any] = [kSecValueData as String: data]
|
|
let status = SecItemUpdate(query as CFDictionary, update as CFDictionary)
|
|
if status == errSecItemNotFound {
|
|
var insert = query
|
|
insert[kSecValueData as String] = data
|
|
insert[kSecAttrAccessible as String] = kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly
|
|
let addStatus = SecItemAdd(insert as CFDictionary, nil)
|
|
debug("save: insert status=\(addStatus), cookies=\(properties.count) [\(cookieNames(storage.cookies(for: url) ?? []))]")
|
|
} else {
|
|
debug("save: update status=\(status), cookies=\(properties.count) [\(cookieNames(storage.cookies(for: url) ?? []))]")
|
|
}
|
|
}
|
|
|
|
static func logRequestCookies(from storage: HTTPCookieStorage, for url: URL, phase: String) {
|
|
debug("\(phase): request cookie names [\(cookieNames(storage.cookies(for: url) ?? []))] host=\(url.host ?? "?")")
|
|
}
|
|
|
|
static func clear() {
|
|
SecItemDelete([
|
|
kSecClass as String: kSecClassGenericPassword,
|
|
kSecAttrService as String: service,
|
|
kSecAttrAccount as String: account,
|
|
] as CFDictionary)
|
|
}
|
|
|
|
private static func read() -> Data? {
|
|
var query: [String: Any] = [
|
|
kSecClass as String: kSecClassGenericPassword,
|
|
kSecAttrService as String: service,
|
|
kSecAttrAccount as String: account,
|
|
kSecReturnData as String: true,
|
|
kSecMatchLimit as String: kSecMatchLimitOne,
|
|
]
|
|
query[kSecUseAuthenticationUI as String] = kSecUseAuthenticationUIFail
|
|
var result: CFTypeRef?
|
|
let status = SecItemCopyMatching(query as CFDictionary, &result)
|
|
guard status == errSecSuccess else {
|
|
debug("read: Keychain status=\(status)")
|
|
return nil
|
|
}
|
|
debug("read: Keychain success")
|
|
return result as? Data
|
|
}
|
|
|
|
private static func cookieNames(_ cookies: [HTTPCookie]) -> String {
|
|
cookies.map(\.name).sorted().joined(separator: ",")
|
|
}
|
|
|
|
private static func debug(_ message: String) {
|
|
#if DEBUG
|
|
print("[AuthCookiePersistence] pid=\(ProcessInfo.processInfo.processIdentifier) bundle=\(Bundle.main.bundleIdentifier ?? "?") \(message)")
|
|
#endif
|
|
}
|
|
}
|