SPB Git

Repository Public

KeychainTokenStore.swift 2.4 KB 42 lines swift

1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Core/Security/KeychainTokenStore.swift3// Description: The device session token in the data-protection keychain, in an access group shared by the app and its File Provider extension. Readable after first unlock so that sync resumes after a restart.4import Foundation5import Security67public struct KeychainTokenStore: TokenStore {8    public let service: String9    public let account: String10    /// Keychain access group (TEAMID.group) shared with the extensions; nil = the app's own default group.11    public let accessGroup: String?12    public init(service: String, account: String = "device-session", accessGroup: String?) { self.service = service; self.account = account; self.accessGroup = accessGroup }1314    private var base: [String: Any] {15        var q: [String: Any] = [kSecClass as String: kSecClassGenericPassword, kSecAttrService as String: service, kSecAttrAccount as String: account, kSecUseDataProtectionKeychain as String: true]16        if let accessGroup { q[kSecAttrAccessGroup as String] = accessGroup }17        return q18    }19    public func readToken() throws -> String? {20        var q = base; q[kSecReturnData as String] = true; q[kSecMatchLimit as String] = kSecMatchLimitOne21        var out: CFTypeRef?22        let s = SecItemCopyMatching(q as CFDictionary, &out)23        if s == errSecItemNotFound { return nil }24        guard s == errSecSuccess, let d = out as? Data else { throw DriveError.local("trousseau : lecture impossible (\(s))") }25        return String(data: d, encoding: .utf8)26    }27    public func writeToken(_ token: String) throws {28        let data = Data(token.utf8)29        var s = SecItemUpdate(base as CFDictionary, [kSecValueData as String: data] as CFDictionary)30        if s == errSecItemNotFound {31            var q = base; q[kSecValueData as String] = data32            q[kSecAttrAccessible as String] = kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly // never synced to iCloud Keychain, never restored on another device33            s = SecItemAdd(q as CFDictionary, nil)34        }35        guard s == errSecSuccess else { throw DriveError.local("trousseau : écriture impossible (\(s))") }36    }37    public func deleteToken() throws {38        let s = SecItemDelete(base as CFDictionary)39        guard s == errSecSuccess || s == errSecItemNotFound else { throw DriveError.local("trousseau : suppression impossible (\(s))") }40    }41}42
Files main
Menu

Theme