RadrootsAppLocalStateReset.swift (2892B)
1 import Foundation 2 import Security 3 4 public struct RadrootsAppLocalStateResetRequest: Sendable, Equatable { 5 public let appIdentifier: String 6 public let keychainServiceNames: [String] 7 8 public init(appIdentifier: String, keychainServiceNames: [String] = []) { 9 self.appIdentifier = appIdentifier 10 self.keychainServiceNames = keychainServiceNames 11 } 12 } 13 14 public enum RadrootsAppLocalStateReset { 15 public static func reset(_ request: RadrootsAppLocalStateResetRequest) throws { 16 try clearApplicationSupport(appIdentifier: request.appIdentifier) 17 for serviceName in request.keychainServiceNames { 18 try clearKeychainService(serviceName) 19 } 20 } 21 22 public static func clearApplicationSupport( 23 appIdentifier: String, 24 fileManager: FileManager = .default 25 ) throws { 26 let normalizedAppIdentifier: String 27 do { 28 normalizedAppIdentifier = try RadrootsAppleFileRoots.normalizedAppIdentifier( 29 appIdentifier) 30 } catch { 31 throw RadrootsAppLocalStateResetError.invalidRequest 32 } 33 do { 34 let root = try fileManager.url( 35 for: .applicationSupportDirectory, 36 in: .userDomainMask, 37 appropriateFor: nil, 38 create: true 39 ).appendingPathComponent(normalizedAppIdentifier, isDirectory: true) 40 if fileManager.fileExists(atPath: root.path) { 41 try fileManager.removeItem(at: root) 42 } 43 } catch let error as RadrootsAppLocalStateResetError { 44 throw error 45 } catch { 46 throw RadrootsAppLocalStateResetError.fileSystemFailure 47 } 48 } 49 50 public static func clearKeychainService(_ serviceName: String) throws { 51 let trimmed = serviceName.trimmingCharacters(in: .whitespacesAndNewlines) 52 guard !trimmed.isEmpty else { 53 throw RadrootsAppLocalStateResetError.invalidRequest 54 } 55 let query: [String: Any] = [ 56 kSecClass as String: kSecClassGenericPassword, 57 kSecAttrService as String: trimmed, 58 ] 59 let status = SecItemDelete(query as CFDictionary) 60 guard status == errSecSuccess || status == errSecItemNotFound else { 61 throw RadrootsAppLocalStateResetError.keychainFailure 62 } 63 } 64 } 65 66 public enum RadrootsAppLocalStateResetError: Error, Equatable, Sendable { 67 case invalidRequest 68 case fileSystemFailure 69 case keychainFailure 70 } 71 72 extension RadrootsAppLocalStateResetError: LocalizedError { 73 public var errorDescription: String? { 74 switch self { 75 case .invalidRequest: "The local-state reset request is invalid." 76 case .fileSystemFailure: "The local application state could not be reset." 77 case .keychainFailure: "The secure local state could not be reset." 78 } 79 } 80 }