Repository Public
1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Core/Security/Keychain.swift3// Description: Session credential and its stores (Keychain in release builds, memory and file stores for tests).4import Foundation5import Security67/// What the app must remember to stay signed in. Stored as one Keychain item; never written to a file or a log.8public struct Credential: Codable, Sendable, Equatable {9 public var serverURL: URL10 public var sessionToken: String11 public var csrfToken: String12 public var account: Account13 public var expiresAt: Date?14 public init(serverURL: URL, sessionToken: String, csrfToken: String, account: Account, expiresAt: Date?) { self.serverURL = serverURL; self.sessionToken = sessionToken; self.csrfToken = csrfToken; self.account = account; self.expiresAt = expiresAt }15}1617public protocol CredentialStore: Sendable {18 func load() -> Credential?19 func save(_ c: Credential) throws20 func clear()21}2223public struct KeychainError: Error, Sendable { public let status: OSStatus }2425/// Generic-password item in the login keychain, readable by this app only (code-signing identity).26public struct KeychainCredentialStore: CredentialStore {27 let service: String28 let account: String29 public init(service: String = "ai.spboucher.spmusic.session", account: String = "default") { self.service = service; self.account = account }3031 private var base: [String: Any] { [kSecClass as String: kSecClassGenericPassword, kSecAttrService as String: service, kSecAttrAccount as String: account] }3233 public func load() -> Credential? {34 var q = base; q[kSecReturnData as String] = true; q[kSecMatchLimit as String] = kSecMatchLimitOne35 var out: CFTypeRef?36 guard SecItemCopyMatching(q as CFDictionary, &out) == errSecSuccess, let data = out as? Data else { return nil }37 return try? JSONDecoder().decode(Credential.self, from: data)38 }39 public func save(_ c: Credential) throws {40 let data = try JSONEncoder().encode(c)41 SecItemDelete(base as CFDictionary)42 var q = base43 q[kSecValueData as String] = data44 q[kSecAttrAccessible as String] = kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly45 q[kSecAttrLabel as String] = "SP Music"46 let status = SecItemAdd(q as CFDictionary, nil)47 guard status == errSecSuccess else { throw KeychainError(status: status) }48 }49 public func clear() { SecItemDelete(base as CFDictionary) }50}5152/// For tests and command-line tools: nothing leaves the process.53public final class MemoryCredentialStore: CredentialStore, @unchecked Sendable {54 private let lock = NSLock()55 private var value: Credential?56 public init(_ initial: Credential? = nil) { value = initial }57 public func load() -> Credential? { lock.withLock { value } }58 public func save(_ c: Credential) throws { lock.withLock { value = c } }59 public func clear() { lock.withLock { value = nil } }60}6162/// Development builds only: the session of a TEST backend kept in a file (mode 0600) inside the test data folder, so63/// that functional tests can relaunch the app without the server. Release builds always use the Keychain.64public struct FileCredentialStore: CredentialStore {65 let url: URL66 public init(url: URL) { self.url = url }67 public func load() -> Credential? { (try? Data(contentsOf: url)).flatMap { try? JSONDecoder().decode(Credential.self, from: $0) } }68 public func save(_ c: Credential) throws {69 try FileManager.default.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true)70 try JSONEncoder().encode(c).write(to: url, options: .atomic)71 try FileManager.default.setAttributes([.posixPermissions: 0o600], ofItemAtPath: url.path)72 }73 public func clear() { try? FileManager.default.removeItem(at: url) }74}75