Version 3

This commit is contained in:
2025-08-17 20:28:17 +03:00
parent 55ec6cedb4
commit e0af36f9a6
10 changed files with 376 additions and 293 deletions

View File

@@ -1,13 +1,9 @@
import Foundation
/// A protocol that defines a type-safe interface for storing and retrieving values
/// in the system keychain.
/// A type that provides access to data stored in the keychain.
///
/// This protocol provides generic support for `Data`, `String`, `UUID`, and `Codable` types.
/// It allows configuring the associated account and service context for each operation.
///
/// Types conforming to this protocol must specify concrete types for `Account`
/// and `Service`, which describe keychain item identity and service grouping.
/// Conforming types define how items are encoded, saved, and accessed securely, using account and
/// service descriptors to identify individual entries.
///
/// ## Topics
///
@@ -20,205 +16,170 @@ import Foundation
///
/// - ``service``
///
/// ### Retrieving Values
/// ### Retrieving Items
///
/// - ``get(_:)-2gcee``
/// - ``get(_:)-23z7h``
/// - ``get(_:)-4xbe6``
/// - ``get(_:decoder:)``
/// - ``get(by:)->Data?``
/// - ``get(by:)->String?``
/// - ``get(by:)->UUID?``
/// - ``get(by:decoder:)``
///
/// ### Storing Values
/// ### Inserting Items
///
/// - ``set(_:for:)-21dla``
/// - ``set(_:for:)-6nzkf``
/// - ``set(_:for:)-2smpc``
/// - ``set(_:for:encoder:)``
/// - ``insert(_:by:)-(Data,_)``
/// - ``insert(_:by:)-(String,_)``
/// - ``insert(_:by:)-(UUID,_)``
/// - ``insert(_:by:encoder:)``
///
/// ### Deleting Values
/// ### Deleting Items
///
/// - ``delete(_:)``
public protocol KeychainStorageProtocol {
/// A type that describes a keychain account and its security configuration.
/// - ``delete(by:)``
///
/// ### Checking Existence
///
/// - ``exists(by:)``
public protocol KeychainStorageProtocol: Sendable {
// MARK: - Types
/// A type that describes a keychain account used to identify stored items.
associatedtype Account: KeychainAccountProtocol
/// A type that identifies a keychain service context (e.g., app or subsystem).
/// A type that describes a keychain service used to group stored items.
associatedtype Service: KeychainServiceProtocol
/// The service associated with this keychain storage instance.
///
/// This value is used as the `kSecAttrService` when interacting with the keychain.
/// If `nil`, the default service behavior is used.
// MARK: - Properties
/// The keychain service associated with this storage instance.
var service: Service? { get }
/// Retrieves the value stored in the keychain for the specified account as raw `Data`.
///
/// - Parameter account: The keychain account whose value should be retrieved.
/// - Returns: The data associated with the given account.
/// - Throws: An error if the item is not found, access is denied, or another keychain error occurs.
func get(_ account: Account) throws(KeychainError) -> Data
// MARK: - Methods
/// Retrieves the value stored in the keychain for the specified account as a UTF-8 string.
/// Retrieves raw data for the given account.
///
/// - Parameter account: The keychain account whose value should be retrieved.
/// - Returns: A string decoded from the stored data using UTF-8 encoding.
/// - Throws: An error if the item is not found, the data is not valid UTF-8,
/// or a keychain access error occurs.
func get(_ account: Account) throws(KeychainError) -> String
/// - Parameter account: The account descriptor identifying the stored item.
/// - Returns: The stored data, or `nil` if no item exists.
/// - Throws: ``KeychainError`` if the operation fails.
func get(by account: Account) throws(KeychainError) -> Data?
/// Retrieves the value stored in the keychain for the specified account as a `UUID`.
///
/// - Parameter account: The keychain account whose value should be retrieved.
/// - Returns: A UUID decoded from a 16-byte binary representation stored in the keychain.
/// - Throws: An error if the item is not found, the data is not exactly 16 bytes,
/// or a keychain access error occurs.
func get(_ account: Account) throws(KeychainError) -> UUID
/// Retrieves and decodes a value of type `T` stored in the keychain for the specified account.
/// Inserts raw data for the given account.
///
/// - Parameters:
/// - account: The keychain account whose value should be retrieved.
/// - decoder: The `JSONDecoder` instance used to decode the stored data.
/// - Returns: A decoded instance of type `T`.
/// - Throws: An error if the item is not found, decoding fails, or a keychain access error occurs.
func get<T: Decodable>(_ account: Account, decoder: JSONDecoder) throws(KeychainError) -> T
/// - value: The data to store.
/// - account: The account descriptor identifying the target item.
/// - Throws: ``KeychainError`` if the operation fails.
func insert(_ value: Data, by account: Account) throws(KeychainError)
/// Stores raw `Data` in the keychain for the specified account.
/// Deletes the item for the given account.
///
/// - Parameters:
/// - value: The data to store in the keychain.
/// - account: The keychain account under which the data will be saved.
/// - Throws: An error if storing the data fails.
func set(_ value: Data, for account: Account) throws(KeychainError)
/// - Parameter account: The account descriptor identifying the item to remove.
/// - Throws: ``KeychainError`` if the operation fails.
func delete(by account: Account) throws(KeychainError)
/// Stores a UTF-8 encoded `String` in the keychain for the specified account.
/// Checks whether an item exists for the given account.
///
/// - Parameters:
/// - value: The string to store in the keychain.
/// - account: The keychain account under which the string will be saved.
/// - Throws: An error if storing the string fails.
func set(_ value: String, for account: Account) throws(KeychainError)
/// Stores a `UUID` in the keychain for the specified account.
///
/// - Parameters:
/// - value: The UUID to store in the keychain (stored in 16-byte binary format).
/// - account: The keychain account under which the UUID will be saved.
/// - Throws: An error if storing the UUID fails.
func set(_ value: UUID, for account: Account) throws(KeychainError)
/// Encodes and stores a value of type `T` in the keychain for the specified account.
///
/// - Parameters:
/// - value: The value to encode and store.
/// - account: The keychain account under which the encoded data will be saved.
/// - encoder: The `JSONEncoder` used to encode the value.
/// - Throws: An error if encoding or storing the value fails.
func set<T: Encodable>(_ value: T, for account: Account, encoder: JSONEncoder) throws(KeychainError)
/// Deletes the keychain item associated with the specified account.
///
/// - Parameter account: The keychain account whose stored value should be deleted.
/// - Note: If the item does not exist, the method completes silently without error.
/// - Throws: An error only if the item exists but removal fails.
func delete(_ account: Account) throws(KeychainError)
/// - Parameter account: The account descriptor identifying the stored item.
/// - Returns: `true` if the item exists; otherwise, `false`.
/// - Throws: ``KeychainError`` if the check fails.
func exists(by account: Account) throws(KeychainError) -> Bool
}
// MARK: - Get Extension
public extension KeychainStorageProtocol {
/// Retrieves a UTF-8 encoded string stored in the keychain for the specified account.
/// Retrieves a UTF-8 string for the given account.
///
/// - Parameter account: The account identifier used to locate the stored value.
/// - Returns: A string decoded from the keychain data using UTF-8 encoding.
/// - Throws: ``KeychainError/unexpectedData`` if the data cannot be decoded as UTF-8.
/// - Throws: Any error thrown by ``KeychainStorageProtocol/get(_:)-2gcee``
/// if reading the raw data fails.
func get(_ account: Account) throws(KeychainError) -> String {
guard let value = String(data: try get(account), encoding: .utf8) else {
throw KeychainError.unexpectedData
/// - Parameter account: The account descriptor identifying the stored item.
/// - Returns: The decoded string, or `nil` if no item exists.
/// - Throws: ``KeychainError`` if retrieval fails.
/// - Throws: ``KeychainError/invalidData`` if the stored data cannot be decoded as UTF-8.
func get(by account: Account) throws(KeychainError) -> String? {
guard let data = try get(by: account) else { return nil }
guard let string = String(data: data, encoding: .utf8) else {
throw .invalidData
}
return value
return string
}
/// Retrieves a `UUID` stored in the keychain for the specified account.
/// Retrieves a UUID for the given account.
///
/// - Parameter account: The account identifier used to locate the stored value.
/// - Returns: A UUID decoded from the keychain string.
/// - Throws: ``KeychainError/unexpectedData`` if the stored string is missing or invalid.
/// - Throws: Any error thrown by ``KeychainStorageProtocol/get(_:)-23z7h``
/// if reading the string from the keychain fails.
func get(_ account: Account) throws(KeychainError) -> UUID {
guard let value = UUID(uuidString: try get(account)) else {
throw KeychainError.unexpectedData
/// - Parameter account: The account descriptor identifying the stored item.
/// - Returns: The decoded UUID, or `nil` if no item exists.
/// - Throws: ``KeychainError`` if retrieval fails.
/// - Throws: ``KeychainError/invalidData`` if the stored value is not a valid UUID string.
func get(by account: Account) throws(KeychainError) -> UUID? {
guard let string: String = try get(by: account) else { return nil }
guard let uuid = UUID(uuidString: string) else {
throw .invalidData
}
return value
return uuid
}
/// Retrieves a value of type `T` stored in the keychain and decodes it from JSON using the given decoder.
/// Retrieves and decodes a `Decodable` value for the given account.
///
/// - Parameters:
/// - account: The account identifier used to locate the stored value.
/// - decoder: The `JSONDecoder` to use for decoding. Defaults to a new instance.
/// - Returns: A decoded instance of type `T`.
/// - Throws: ``KeychainError/unexpectedError(_:)`` if the data cannot be decoded into the specified type.
/// - Throws: Any error thrown by ``KeychainStorageProtocol/get(_:)-2gcee`` if reading the raw data fails.
/// - account: The account descriptor identifying the stored item.
/// - decoder: The JSON decoder used to decode the stored data.
/// - Returns: The decoded value, or `nil` if no item exists.
/// - Throws: ``KeychainError`` if retrieval fails.
/// - Throws: ``KeychainError/underlying(_:)`` if JSON decoding fails.
func get<T: Decodable>(
_ account: Account,
by account: Account,
decoder: JSONDecoder = .init()
) throws(KeychainError) -> T {
let value: Data = try get(account)
) throws(KeychainError) -> T? {
guard let data = try get(by: account) else { return nil }
do {
return try decoder.decode(T.self, from: value)
return try decoder.decode(T.self, from: data)
} catch {
throw KeychainError.unexpectedError(error)
throw .underlying(error as NSError)
}
}
/// Stores a UTF-8 encoded string in the keychain for the specified account.
}
// MARK: - Set Extension
public extension KeychainStorageProtocol {
/// Inserts a UTF-8 string for the given account.
///
/// - Parameters:
/// - value: The string to store.
/// - account: The account identifier used as the key for storing the value.
/// - Throws: ``KeychainError/unexpectedData`` if the string cannot be encoded as UTF-8.
/// - Throws: Any error thrown by ``KeychainStorageProtocol/set(_:for:)-21dla``
/// if saving the data fails.
func set(_ value: String, for account: Account) throws(KeychainError) {
/// - account: The account descriptor identifying the target item.
/// - Throws: ``KeychainError`` if the operation fails.
/// - Throws: ``KeychainError/invalidData`` if the string cannot be encoded as UTF-8.
func insert(_ value: String, by account: Account) throws(KeychainError) {
guard let data = value.data(using: .utf8) else {
throw KeychainError.unexpectedData
throw .invalidData
}
try set(data, for: account)
try insert(data, by: account)
}
/// Stores a `UUID` value as a UTF-8 encoded string in the keychain for the specified account.
/// Inserts a UUID for the given account.
///
/// - Parameters:
/// - value: The UUID to store.
/// - account: The account identifier used as the key for storing the value.
/// - Throws: Any error thrown by ``KeychainStorageProtocol/set(_:for:)-6nzkf``
/// if saving the data fails.
func set(_ value: UUID, for account: Account) throws(KeychainError) {
try set(value.uuidString, for: account)
/// - account: The account descriptor identifying the target item.
/// - Throws: ``KeychainError`` if the operation fails.
func insert(_ value: UUID, by account: Account) throws(KeychainError) {
try insert(value.uuidString, by: account)
}
/// Stores an `Encodable` value in the keychain as JSON-encoded data for the specified account.
/// Encodes and inserts an `Encodable` value for the given account.
///
/// - Parameters:
/// - value: The value to encode and store.
/// - account: The account identifier used as the key for storing the value.
/// - encoder: The JSON encoder to use (default is a new instance).
/// - Throws: ``KeychainError/unexpectedError(_:)`` if encoding the value fails.
/// - Throws: Any error thrown by ``KeychainStorageProtocol/set(_:for:)-21dla``
/// if saving the data fails.
func set<T: Encodable>(
/// - account: The account descriptor identifying the target item.
/// - encoder: The JSON encoder used to encode the value.
/// - Throws: ``KeychainError`` if the operation fails.
/// - Throws: ``KeychainError/underlying(_:)`` if JSON encoding fails.
func insert<T: Encodable>(
_ value: T,
for account: Account,
by account: Account,
encoder: JSONEncoder = .init()
) throws(KeychainError) {
let data: Data
do {
let data = try encoder.encode(value)
try set(data, for: account)
} catch let error as KeychainError {
throw error
data = try encoder.encode(value)
} catch {
throw KeychainError.unexpectedError(error)
throw .underlying(error as NSError)
}
try insert(data, by: account)
}
}