Sources/OrgApp/CryptPassphrases.swift

06941b2cf25c6ccc1629723cd7951910ce15e67a
orgstar/Sources/OrgApp/CryptPassphrases.swift history · blame · raw

44 lines · 1929 bytes

 1import Foundation
 2import LocalAuthentication
 3import Security
 4
 5/// Passphrases for encrypted entries, kept in the Keychain by file when asked, and given back
 6/// only after Touch ID, Face ID or the device's password.
 7public enum CryptPassphrases {
 8    static let service = "sh.krz.orgstar.crypt"
 9
10    static func query(_ path: String) -> [String: Any] {
11        [kSecClass as String: kSecClassGenericPassword, kSecAttrService as String: service, kSecAttrAccount as String: path]
12    }
13
14    public static func store(_ passphrase: String, for path: String) {
15        forget(path)
16        var item = query(path)
17        item[kSecValueData as String] = Data(passphrase.utf8)
18        item[kSecAttrLabel as String] = "orgstar: encrypted entries in " + (path as NSString).lastPathComponent
19        SecItemAdd(item as CFDictionary, nil)
20    }
21
22    public static func forget(_ path: String) {
23        SecItemDelete(query(path) as CFDictionary)
24    }
25
26    public static func hasStored(_ path: String) -> Bool {
27        var q = query(path)
28        q[kSecReturnAttributes as String] = true
29        return SecItemCopyMatching(q as CFDictionary, nil) == errSecSuccess
30    }
31
32    /// The stored passphrase, once the person has proved who they are; nil otherwise.
33    public static func stored(for path: String) async -> String? {
34        guard hasStored(path) else { return nil }
35        let context = LAContext()
36        let reason = "unlock the passphrase for encrypted entries in " + (path as NSString).lastPathComponent
37        guard (try? await context.evaluatePolicy(.deviceOwnerAuthentication, localizedReason: reason)) == true else { return nil }
38        var q = query(path)
39        q[kSecReturnData as String] = true
40        var result: AnyObject?
41        guard SecItemCopyMatching(q as CFDictionary, &result) == errSecSuccess, let data = result as? Data else { return nil }
42        return String(decoding: data, as: UTF8.self)
43    }
44}