interplane.Get Omega
Read in your language

hop

Hop: a small native macOS launcher. Clipboard history, find, on-device dictation and your coding agent behind one key.

Brought by drakestapleton

branch main Branches Tags History

hop / Sources / Vault.swift

206 lines · 11667 bytes Raw Blame History
1import Foundation
2import Security
3import CryptoKit
4import LocalAuthentication
5
6/// Saved subscriptions, API keys and logins, kept in the macOS login Keychain.
7/// Hop's own files never contain these values.
8struct VaultEntry: Identifiable, Hashable {
9 var id: String { account }
10 var account: String // unique name, e.g. "openrouter"
11 var kind: String // "API key", "Subscription", "Login", ...
12 var note: String // free text: what it is for, which factory service uses it
13}
14
15enum Vault {
16 static let service = "com.aienos.hop.vault"
17 static let internalService = "com.aienos.hop.internal"
18 private static let interactionLock = NSLock()
19
20 static func list() -> [VaultEntry] {
21 interactionLock.lock(); defer { interactionLock.unlock() }
22 let q: [String: Any] = [kSecClass as String: kSecClassGenericPassword,
23 kSecAttrService as String: service,
24 kSecMatchLimit as String: kSecMatchLimitAll,
25 kSecReturnAttributes as String: true]
26 var out: CFTypeRef?
27 guard SecItemCopyMatching(q as CFDictionary, &out) == errSecSuccess,
28 let items = out as? [[String: Any]] else { return [] }
29 return items.map {
30 VaultEntry(account: $0[kSecAttrAccount as String] as? String ?? "?",
31 kind: $0[kSecAttrDescription as String] as? String ?? "",
32 note: $0[kSecAttrComment as String] as? String ?? "")
33 }.sorted { $0.account.lowercased() < $1.account.lowercased() }
34 }
35
36 @discardableResult
37 static func save(account: String, secret: String, kind: String, note: String, svc: String = service) -> Bool {
38 interactionLock.lock(); defer { interactionLock.unlock() }
39 let base: [String: Any] = [kSecClass as String: kSecClassGenericPassword,
40 kSecAttrService as String: svc,
41 kSecAttrAccount as String: account]
42 SecItemDelete(base as CFDictionary)
43 var add = base
44 add[kSecValueData as String] = Data(secret.utf8)
45 add[kSecAttrDescription as String] = kind
46 add[kSecAttrComment as String] = note
47 add[kSecAttrAccessible as String] = kSecAttrAccessibleWhenUnlockedThisDeviceOnly
48 return SecItemAdd(add as CFDictionary, nil) == errSecSuccess
49 }
50
51 static func secret(_ account: String, svc: String = service) -> String? {
52 interactionLock.lock(); defer { interactionLock.unlock() }
53 let q: [String: Any] = [kSecClass as String: kSecClassGenericPassword,
54 kSecAttrService as String: svc,
55 kSecAttrAccount as String: account,
56 kSecReturnData as String: true,
57 kSecMatchLimit as String: kSecMatchLimitOne]
58 var out: CFTypeRef?
59 guard SecItemCopyMatching(q as CFDictionary, &out) == errSecSuccess, let d = out as? Data else { return nil }
60 return String(data: d, encoding: .utf8)
61 }
62
63 static func delete(_ account: String) {
64 interactionLock.lock(); defer { interactionLock.unlock() }
65 let q: [String: Any] = [kSecClass as String: kSecClassGenericPassword,
66 kSecAttrService as String: service,
67 kSecAttrAccount as String: account]
68 SecItemDelete(q as CFDictionary)
69 }
70
71 enum StorageError: LocalizedError {
72 case keychain(OSStatus), malformed, missingHistoricalKey
73 var errorDescription: String? {
74 switch self {
75 case .keychain(let code): return "Clipboard key is unavailable (Keychain status \(code)). Existing history has not been changed."
76 case .malformed: return "The stored clipboard key is invalid. It has not been replaced."
77 case .missingHistoricalKey: return "Encrypted clipboard history exists but its key is missing. Restore that key before continuing."
78 }
79 }
80 }
81
82 // MARK: Clipboard key
83 /// The clipboard key lives in a Keychain item owned by Apple's `security` tool and is read through that tool.
84 /// macOS ties a Keychain approval to the exact build of an app that has no Apple team ID, so a key owned by
85 /// Hop itself locked again after every update, whatever the user clicked. Access through the system tool
86 /// never prompts and does not change when Hop is rebuilt.
87 static let toolService = "com.aienos.hop.clipboard"
88 private static let toolAccount = "storage-key-v2"
89 private static let tool = "/usr/bin/security"
90
91 private static func runTool(_ args: [String], stdin: String? = nil) -> (code: Int32, out: String) {
92 let p = Process(); p.executableURL = URL(fileURLWithPath: tool); p.arguments = args
93 let inp = Pipe(), out = Pipe()
94 p.standardInput = inp; p.standardOutput = out; p.standardError = FileHandle.nullDevice
95 do { try p.run() } catch { return (127, "") }
96 if let stdin { inp.fileHandleForWriting.write(Data(stdin.utf8)) }
97 inp.fileHandleForWriting.closeFile()
98 let d = out.fileHandleForReading.readDataToEndOfFile()
99 p.waitUntilExit()
100 return (p.terminationStatus, String(decoding: d, as: UTF8.self).trimmingCharacters(in: .whitespacesAndNewlines))
101 }
102
103 /// nil = no key stored yet. Any other failure throws, so a locked Keychain is never mistaken for "no key".
104 private static func toolKey() throws -> SymmetricKey? {
105 let r = runTool(["find-generic-password", "-s", toolService, "-a", toolAccount, "-w"])
106 if r.code == 44 { return nil }
107 guard r.code == 0 else { throw StorageError.keychain(OSStatus(r.code)) }
108 guard let bytes = Data(base64Encoded: r.out), bytes.count == 32 else { throw StorageError.malformed }
109 return SymmetricKey(data: bytes)
110 }
111
112 /// The clipboard key, for reading only (`hop clip`): nil when none is stored. Nothing is created, moved or
113 /// replaced, and a denied or malformed read throws as it does for Hop itself.
114 static func readStorageKey() throws -> SymmetricKey? {
115 interactionLock.lock(); defer { interactionLock.unlock() }
116 return try toolKey()
117 }
118
119 private static func storeToolKey(_ key: SymmetricKey) throws {
120 let encoded = key.withUnsafeBytes { Data($0).base64EncodedString() }
121 // Sent on stdin so the key never appears in a process list. No -U: an existing key is never overwritten.
122 _ = runTool(["-i"], stdin: "add-generic-password -s \(toolService) -a \(toolAccount) -w \(encoded) -T \(tool) -D internal -j \"Hop clipboard encryption\"\n")
123 guard let back = try toolKey(), back.withUnsafeBytes({ Data($0) }) == key.withUnsafeBytes({ Data($0) }) else {
124 throw StorageError.keychain(errSecIO)
125 }
126 }
127
128 static func storageKey(allowInteraction: Bool = false) throws -> SymmetricKey {
129 interactionLock.lock()
130 let existing: SymmetricKey?
131 do { existing = try toolKey() } catch { interactionLock.unlock(); throw error }
132 interactionLock.unlock()
133 if let existing { return existing }
134 // First run with the new store. Bring the old key over if macOS lets Hop read it without a prompt.
135 let dir = HopConfig.dir, fm = FileManager.default
136 let old = dir.appendingPathComponent("clipboard.bin")
137 var key: SymmetricKey?
138 if fm.fileExists(atPath: old.path) {
139 key = try? legacyStorageKey(allowInteraction: allowInteraction)
140 if key == nil {
141 // It can't be read without a prompt. Set the old history aside, untouched, and start fresh;
142 // "Recover older clipboard history…" in the menu brings it back with one approval.
143 let stamp = Int(Date().timeIntervalSince1970)
144 try fm.moveItem(at: old, to: dir.appendingPathComponent("clipboard-legacy-\(stamp).bin"))
145 let images = dir.appendingPathComponent("clip-images")
146 if fm.fileExists(atPath: images.path) { try? fm.moveItem(at: images, to: dir.appendingPathComponent("clip-images-legacy-\(stamp)")) }
147 }
148 }
149 let fresh = key ?? SymmetricKey(size: .bits256)
150 interactionLock.lock(); defer { interactionLock.unlock() }
151 try storeToolKey(fresh)
152 return fresh
153 }
154
155 /// The first design: a key owned by Hop itself in the login Keychain. Read only to migrate or recover old history.
156 /// A denied/locked read is never treated as a missing key. New keys use add-only, never delete.
157 static func legacyStorageKey(allowInteraction: Bool = false) throws -> SymmetricKey {
158 interactionLock.lock(); defer { interactionLock.unlock() }
159 // The login Keychain's legacy ACL dialog ignores per-query suppression on this Mac.
160 // This process-local suppression fails closed; it grants no access and is restored.
161 var previous: DarwinBoolean = false
162 if !allowInteraction {
163 let readState = SecKeychainGetUserInteractionAllowed(&previous)
164 guard readState == errSecSuccess else { throw StorageError.keychain(readState) }
165 let setState = SecKeychainSetUserInteractionAllowed(false)
166 guard setState == errSecSuccess else { throw StorageError.keychain(setState) }
167 }
168 defer { if !allowInteraction { _ = SecKeychainSetUserInteractionAllowed(previous.boolValue) } }
169 let context = LAContext()
170 context.interactionNotAllowed = !allowInteraction
171 let query: [String: Any] = [
172 kSecClass as String: kSecClassGenericPassword,
173 kSecAttrService as String: internalService,
174 kSecAttrAccount as String: "storage-key",
175 kSecReturnData as String: true,
176 kSecMatchLimit as String: kSecMatchLimitOne,
177 kSecUseAuthenticationContext as String: context
178 ]
179 var result: CFTypeRef?
180 let status = SecItemCopyMatching(query as CFDictionary, &result)
181 if status == errSecSuccess {
182 guard let raw = result as? Data, let encoded = String(data: raw, encoding: .utf8),
183 let bytes = Data(base64Encoded: encoded), bytes.count == 32 else { throw StorageError.malformed }
184 return SymmetricKey(data: bytes)
185 }
186 guard status == errSecItemNotFound else { throw StorageError.keychain(status) }
187 let directory = HopConfig.dir
188 if FileManager.default.fileExists(atPath: directory.appendingPathComponent("clipboard.bin").path) {
189 throw StorageError.missingHistoricalKey
190 }
191 let images = directory.appendingPathComponent("clip-images")
192 if FileManager.default.fileExists(atPath: images.path),
193 !(try FileManager.default.contentsOfDirectory(atPath: images.path)).isEmpty { throw StorageError.missingHistoricalKey }
194 let key = SymmetricKey(size: .bits256)
195 let encoded = key.withUnsafeBytes { Data($0).base64EncodedString() }
196 let add: [String: Any] = [
197 kSecClass as String: kSecClassGenericPassword, kSecAttrService as String: internalService,
198 kSecAttrAccount as String: "storage-key", kSecValueData as String: Data(encoded.utf8),
199 kSecAttrDescription as String: "internal", kSecAttrComment as String: "Hop clipboard encryption",
200 kSecAttrAccessible as String: kSecAttrAccessibleWhenUnlockedThisDeviceOnly
201 ]
202 let added = SecItemAdd(add as CFDictionary, nil)
203 guard added == errSecSuccess else { throw StorageError.keychain(added) }
204 return key
205 }
206}