Skip to content

Fastest and only macOS Dictation app with on-device STT and custom trained AI enhancement model. Windows, iOS testflight! Android, Linux waitlist open! A local Wispr Flow alternative. Follow https://x.com/fluidvoiceapp for more

Request keychain access while entering

grohith327860c3f9ffba2
diff --git a/README.md b/README.md
index 6feabef0..b58b4d30 100644
--- a/README.md
+++ b/README.md
@@ -60,7 +60,7 @@ https://github.com/user-attachments/assets/c57ef6d5-f0a1-4a3f-a121-637533442c24
2. Move to Applications folder
3. Grant microphone and accessibility permissions when prompted
4. Set your preferred hotkey in settings
-5. Optionally add an AI provider API key for enhanced transcription (keys are stored securely in your macOS Keychain)
+5. Optionally add an AI provider API key for enhanced transcription, keys are stored securely in your macOS Keychain. Make sure select "Always allow" for permissions
## Requirements
diff --git a/Sources/Fluid/ContentView.swift b/Sources/Fluid/ContentView.swift
index 23f8fb00..6f823017 100644
--- a/Sources/Fluid/ContentView.swift
+++ b/Sources/Fluid/ContentView.swift
@@ -11,6 +11,7 @@ import AVFoundation
import Combine
import CoreAudio
import CoreGraphics
+import Security
// MARK: - Sidebar Item Enum
@@ -132,6 +133,8 @@ struct ContentView: View {
@State private var newProviderBaseURL: String = ""
@State private var keyJustSaved: Bool = false
@State private var showAPIKeysGuide: Bool = false
+ @State private var showKeychainPermissionAlert: Bool = false
+ @State private var keychainPermissionMessage: String = ""
// Feedback State
@State private var feedbackText: String = ""
@@ -468,6 +471,16 @@ struct ContentView: View {
}
.overlay(alignment: .center) {
}
+ .alert("Keychain Access Required", isPresented: $showKeychainPermissionAlert) {
+ Button("Open Keychain Access") {
+ openKeychainAccessApp()
+ }
+ Button("OK", role: .cancel) { }
+ } message: {
+ Text(keychainPermissionMessage.isEmpty
+ ? "FluidVoice stores provider API keys securely in your macOS Keychain. Please grant access by choosing \"Always Allow\" when prompted."
+ : keychainPermissionMessage)
+ }
.onReceive(audioObserver.changePublisher) { _ in
// Hardware change detected → refresh lists and apply preferences if available
refreshDevices()
@@ -1400,8 +1413,7 @@ struct ContentView: View {
Divider()
Button(action: {
- newProviderApiKey = providerAPIKeys[currentProvider] ?? ""
- showAPIKeyEditor = true
+ handleAPIKeyButtonTapped()
}) {
Label("Add or Modify API Key", systemImage: "key.fill")
.labelStyle(.titleAndIcon)
@@ -1586,7 +1598,7 @@ struct ContentView: View {
Color.clear.frame(height: 0)
.sheet(isPresented: $showAPIKeyEditor) {
VStack(spacing: 14) {
- Text("Enter \(currentProvider.capitalized) API Key")
+ Text("Enter \(providerDisplayName(for: selectedProviderID)) API Key")
.font(.headline)
SecureField("API Key (optional for local endpoints)", text: $newProviderApiKey)
@@ -2084,6 +2096,16 @@ struct ContentView: View {
// Saved providers use their stable id
return providerID.isEmpty ? currentProvider : "custom:\(providerID)"
}
+
+ private func providerDisplayName(for providerID: String) -> String {
+ switch providerID {
+ case "openai": return "OpenAI"
+ case "groq": return "Groq"
+ case "apple-intelligence": return "Apple Intelligence"
+ default:
+ return savedProviders.first(where: { $0.id == providerID })?.name ?? providerID.capitalized
+ }
+ }
private func defaultModels(for providerKey: String) -> [String] {
switch providerKey {
@@ -2097,6 +2119,81 @@ struct ContentView: View {
SettingsStore.shared.providerAPIKeys = providerAPIKeys
}
+ // MARK: - Keychain Access Helpers
+ private enum KeychainAccessCheckResult {
+ case granted
+ case denied(OSStatus)
+ }
+
+ private func handleAPIKeyButtonTapped() {
+ switch probeKeychainAccess() {
+ case .granted:
+ newProviderApiKey = providerAPIKeys[currentProvider] ?? ""
+ showAPIKeyEditor = true
+ case .denied(let status):
+ keychainPermissionMessage = keychainPermissionExplanation(for: status)
+ showKeychainPermissionAlert = true
+ }
+ }
+
+ private func probeKeychainAccess() -> KeychainAccessCheckResult {
+ let service = "com.fluidvoice.provider-api-keys"
+ let account = "fluidApiKeys"
+
+ var query: [String: Any] = [
+ kSecClass as String: kSecClassGenericPassword,
+ kSecAttrService as String: service,
+ kSecAttrAccount as String: account
+ ]
+
+ var readQuery = query
+ readQuery[kSecReturnData as String] = kCFBooleanTrue
+ readQuery[kSecMatchLimit as String] = kSecMatchLimitOne
+
+ let readStatus = SecItemCopyMatching(readQuery as CFDictionary, nil)
+ switch readStatus {
+ case errSecSuccess:
+ return .granted
+ case errSecItemNotFound:
+ var addQuery = query
+ addQuery[kSecAttrAccessible as String] = kSecAttrAccessibleAfterFirstUnlock
+ addQuery[kSecValueData as String] = (try? JSONEncoder().encode([String: String]())) ?? Data()
+
+ let addStatus = SecItemAdd(addQuery as CFDictionary, nil)
+ if addStatus == errSecSuccess {
+ SecItemDelete(query as CFDictionary)
+ }
+
+ switch addStatus {
+ case errSecSuccess, errSecDuplicateItem:
+ return .granted
+ case errSecAuthFailed, errSecInteractionNotAllowed, errSecUserCanceled:
+ return .denied(addStatus)
+ default:
+ DebugLogger.shared.warning("Keychain access probe failed with status \(addStatus)", source: "ContentView")
+ return .denied(addStatus)
+ }
+ case errSecAuthFailed, errSecInteractionNotAllowed, errSecUserCanceled:
+ return .denied(readStatus)
+ default:
+ DebugLogger.shared.warning("Keychain access probe failed with status \(readStatus)", source: "ContentView")
+ return .denied(readStatus)
+ }
+ }
+
+ private func keychainPermissionExplanation(for status: OSStatus) -> String {
+ var message = "FluidVoice stores provider API keys securely in your macOS Keychain but does not currently have permission to access it."
+ if let detail = SecCopyErrorMessageString(status, nil) as String? {
+ message += "\n\nmacOS reported: \(detail) (\(status))"
+ }
+ message += "\n\nClick \"Always Allow\" when the Keychain prompt appears, or open Keychain Access > login > Passwords, locate the FluidVoice entry, and grant access."
+ return message
+ }
+
+ private func openKeychainAccessApp() {
+ NSWorkspace.shared.launchApplication("Keychain Access")
+ }
+
private func updateCurrentProvider() {
// Map baseURL to canonical key for built-ins; else keep existing
let url = openAIBaseURL.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
diff --git a/Sources/Fluid/Persistence/KeychainService.swift b/Sources/Fluid/Persistence/KeychainService.swift
index bc5f20a3..5e07eb82 100644
--- a/Sources/Fluid/Persistence/KeychainService.swift
+++ b/Sources/Fluid/Persistence/KeychainService.swift
@@ -24,37 +24,100 @@ final class KeychainService {
static let shared = KeychainService()
private let service = "com.fluidvoice.provider-api-keys"
+ private let account = "fluidApiKeys"
private init() {}
+ // MARK: - Public API
+
func storeKey(_ key: String, for providerID: String) throws {
let trimmed = key.trimmingCharacters(in: .whitespacesAndNewlines)
- guard let data = trimmed.data(using: .utf8) else {
- throw KeychainServiceError.invalidData
- }
+ var keys = try loadStoredKeys()
+ keys[providerID] = trimmed
+ try saveStoredKeys(keys)
+ }
- var attributes = baseQuery(for: providerID)
- attributes[kSecAttrAccessible as String] = kSecAttrAccessibleAfterFirstUnlock
- attributes[kSecValueData as String] = data
+ func fetchKey(for providerID: String) throws -> String? {
+ let keys = try loadStoredKeys()
+ return keys[providerID]
+ }
- let status = SecItemAdd(attributes as CFDictionary, nil)
+ func deleteKey(for providerID: String) throws {
+ var keys = try loadStoredKeys()
+ guard keys.removeValue(forKey: providerID) != nil else { return }
+ try saveStoredKeys(keys)
+ }
+
+ func containsKey(for providerID: String) -> Bool {
+ guard let keys = try? loadStoredKeys() else { return false }
+ return keys[providerID] != nil
+ }
+
+ func allProviderIDs() throws -> [String] {
+ return try loadStoredKeys().keys.sorted()
+ }
+
+ func fetchAllKeys() throws -> [String: String] {
+ try loadStoredKeys()
+ }
+
+ func storeAllKeys(_ values: [String: String]) throws {
+ try saveStoredKeys(values)
+ }
+
+ func legacyProviderEntries() throws -> [String: String] {
+ var result: [String: String] = [:]
+ let query: [String: Any] = [
+ kSecClass as String: kSecClassGenericPassword,
+ kSecAttrService as String: service,
+ kSecReturnAttributes as String: true,
+ kSecReturnData as String: true,
+ kSecMatchLimit as String: kSecMatchLimitAll
+ ]
+
+ var items: CFTypeRef?
+ let status = SecItemCopyMatching(query as CFDictionary, &items)
switch status {
case errSecSuccess:
- return
- case errSecDuplicateItem:
- let updateStatus = SecItemUpdate(baseQuery(for: providerID) as CFDictionary,
- [kSecValueData as String: data] as CFDictionary)
- guard updateStatus == errSecSuccess else {
- throw KeychainServiceError.unhandled(updateStatus)
+ guard let attributesArray = items as? [[String: Any]] else { return [:] }
+ for attributes in attributesArray {
+ guard let providerID = attributes[kSecAttrAccount as String] as? String,
+ providerID != account,
+ let data = attributes[kSecValueData as String] as? Data,
+ let key = String(data: data, encoding: .utf8) else {
+ continue
+ }
+ result[providerID] = key
}
+ return result
+ case errSecItemNotFound:
+ return [:]
default:
throw KeychainServiceError.unhandled(status)
}
}
- func fetchKey(for providerID: String) throws -> String? {
- var query = baseQuery(for: providerID)
+ func removeLegacyEntries(providerIDs: [String]? = nil) throws {
+ let targets: [String]
+ if let providerIDs {
+ targets = providerIDs
+ } else {
+ targets = Array((try legacyProviderEntries()).keys)
+ }
+
+ for providerID in targets {
+ let status = SecItemDelete(legacyQuery(for: providerID) as CFDictionary)
+ guard status == errSecSuccess || status == errSecItemNotFound else {
+ throw KeychainServiceError.unhandled(status)
+ }
+ }
+ }
+
+ // MARK: - Private helpers
+
+ private func loadStoredKeys() throws -> [String: String] {
+ var query = aggregatedQuery()
query[kSecReturnData as String] = kCFBooleanTrue
query[kSecMatchLimit as String] = kSecMatchLimitOne
@@ -63,56 +126,58 @@ final class KeychainService {
switch status {
case errSecSuccess:
- guard let data = item as? Data,
- let key = String(data: data, encoding: .utf8) else {
+ guard let data = item as? Data else {
+ throw KeychainServiceError.invalidData
+ }
+ if data.isEmpty {
+ return [:]
+ }
+ do {
+ return try JSONDecoder().decode([String: String].self, from: data)
+ } catch {
throw KeychainServiceError.invalidData
}
- return key
case errSecItemNotFound:
- return nil
+ return [:]
default:
throw KeychainServiceError.unhandled(status)
}
}
- func deleteKey(for providerID: String) throws {
- let status = SecItemDelete(baseQuery(for: providerID) as CFDictionary)
- guard status == errSecSuccess || status == errSecItemNotFound else {
- throw KeychainServiceError.unhandled(status)
- }
- }
-
- func containsKey(for providerID: String) -> Bool {
- var query = baseQuery(for: providerID)
- query[kSecReturnData as String] = kCFBooleanFalse
- query[kSecMatchLimit as String] = kSecMatchLimitOne
- let status = SecItemCopyMatching(query as CFDictionary, nil)
- return status == errSecSuccess
- }
+ private func saveStoredKeys(_ keys: [String: String]) throws {
+ let data = try JSONEncoder().encode(keys)
- func allProviderIDs() throws -> [String] {
- let query: [String: Any] = [
- kSecClass as String: kSecClassGenericPassword,
- kSecAttrService as String: service,
- kSecReturnAttributes as String: true,
- kSecMatchLimit as String: kSecMatchLimitAll
- ]
+ var attributes = aggregatedQuery()
+ attributes[kSecAttrAccessible as String] = kSecAttrAccessibleAfterFirstUnlock
+ attributes[kSecValueData as String] = data
- var items: CFTypeRef?
- let status = SecItemCopyMatching(query as CFDictionary, &items)
+ let status = SecItemAdd(attributes as CFDictionary, nil)
switch status {
case errSecSuccess:
- guard let attributesArray = items as? [[String: Any]] else { return [] }
- return attributesArray.compactMap { $0[kSecAttrAccount as String] as? String }
- case errSecItemNotFound:
- return []
+ try removeLegacyEntries()
+ return
+ case errSecDuplicateItem:
+ let updateStatus = SecItemUpdate(aggregatedQuery() as CFDictionary,
+ [kSecValueData as String: data] as CFDictionary)
+ guard updateStatus == errSecSuccess else {
+ throw KeychainServiceError.unhandled(updateStatus)
+ }
+ try removeLegacyEntries()
default:
throw KeychainServiceError.unhandled(status)
}
}
- private func baseQuery(for providerID: String) -> [String: Any] {
+ private func aggregatedQuery() -> [String: Any] {
+ [
+ kSecClass as String: kSecClassGenericPassword,
+ kSecAttrService as String: service,
+ kSecAttrAccount as String: account
+ ]
+ }
+
+ private func legacyQuery(for providerID: String) -> [String: Any] {
[
kSecClass as String: kSecClassGenericPassword,
kSecAttrService as String: service,
diff --git a/Sources/Fluid/Persistence/SettingsStore.swift b/Sources/Fluid/Persistence/SettingsStore.swift
index 3706a00e..fa254023 100644
--- a/Sources/Fluid/Persistence/SettingsStore.swift
+++ b/Sources/Fluid/Persistence/SettingsStore.swift
@@ -132,16 +132,7 @@ final class SettingsStore: ObservableObject
}
var providerAPIKeys: [String: String] {
- get {
- var result: [String: String] = [:]
- for providerID in storedProviderKeyIDs {
- if let value = try? keychain.fetchKey(for: providerID),
- value.isEmpty == false {
- result[providerID] = value
- }
- }
- return result
- }
+ get { (try? keychain.fetchAllKeys()) ?? [:] }
set {
objectWillChange.send()
persistProviderAPIKeys(newValue)
@@ -476,52 +467,37 @@ final class SettingsStore: ObservableObject
// MARK: - Private Methods
- private var storedProviderKeyIDs: [String] {
- get { defaults.stringArray(forKey: Keys.providerAPIKeyIdentifiers) ?? [] }
- set {
- let unique = Array(Set(newValue)).sorted()
- defaults.set(unique, forKey: Keys.providerAPIKeyIdentifiers)
+ private func persistProviderAPIKeys(_ values: [String: String]) {
+ let trimmed = sanitizeAPIKeys(values)
+ do {
+ try keychain.storeAllKeys(trimmed)
+ } catch {
+ DebugLogger.shared.error("Failed to persist provider API keys: \(error.localizedDescription)", source: "SettingsStore")
}
}
- private func persistProviderAPIKeys(_ values: [String: String]) {
- let trimmed = values.reduce(into: [String: String]()) { partialResult, pair in
- let sanitizedValue = pair.value.trimmingCharacters(in: .whitespacesAndNewlines)
- guard sanitizedValue.isEmpty == false else { return }
- partialResult[pair.key] = sanitizedValue
- }
+ private func migrateProviderAPIKeysIfNeeded() {
+ defaults.removeObject(forKey: Keys.providerAPIKeyIdentifiers)
- let existingIDs = Set(storedProviderKeyIDs)
- let incomingIDs = Set(trimmed.keys)
+ var merged = (try? keychain.fetchAllKeys()) ?? [:]
+ var didMutate = false
- for (providerID, apiKey) in trimmed {
- do {
- try keychain.storeKey(apiKey, for: providerID)
- } catch {
- DebugLogger.shared.error("Failed to store API key for \(providerID): \(error.localizedDescription)", source: "SettingsStore")
- }
+ if let legacyDefaults = defaults.dictionary(forKey: Keys.providerAPIKeys) as? [String: String],
+ legacyDefaults.isEmpty == false {
+ merged.merge(sanitizeAPIKeys(legacyDefaults)) { _, new in new }
+ didMutate = true
}
+ defaults.removeObject(forKey: Keys.providerAPIKeys)
- for providerID in existingIDs.subtracting(incomingIDs) {
- do {
- try keychain.deleteKey(for: providerID)
- } catch {
- DebugLogger.shared.error("Failed to delete API key for \(providerID): \(error.localizedDescription)", source: "SettingsStore")
- }
+ if let legacyKeychain = try? keychain.legacyProviderEntries(),
+ legacyKeychain.isEmpty == false {
+ merged.merge(sanitizeAPIKeys(legacyKeychain)) { _, new in new }
+ didMutate = true
+ try? keychain.removeLegacyEntries(providerIDs: Array(legacyKeychain.keys))
}
- storedProviderKeyIDs = Array(incomingIDs)
- }
-
- private func migrateProviderAPIKeysIfNeeded() {
- if let legacy = defaults.dictionary(forKey: Keys.providerAPIKeys) as? [String: String],
- legacy.isEmpty == false {
- persistProviderAPIKeys(legacy)
- defaults.removeObject(forKey: Keys.providerAPIKeys)
- } else if storedProviderKeyIDs.isEmpty,
- let existing = try? keychain.allProviderIDs(),
- existing.isEmpty == false {
- storedProviderKeyIDs = existing
+ if didMutate {
+ persistProviderAPIKeys(merged)
}
}
@@ -530,7 +506,6 @@ final class SettingsStore: ObservableObject
var decoded = try? JSONDecoder().decode([SavedProvider].self, from: data) else { return }
var didModify = false
- var migratedIDs: [String] = []
for index in decoded.indices {
let provider = decoded[index]
let trimmed = provider.apiKey.trimmingCharacters(in: .whitespacesAndNewlines)
@@ -539,7 +514,6 @@ final class SettingsStore: ObservableObject
let keyID = canonicalProviderKey(for: provider.id)
do {
try keychain.storeKey(trimmed, for: keyID)
- migratedIDs.append(keyID)
didModify = true
} catch {
DebugLogger.shared.error("Failed to migrate API key for \(provider.name): \(error.localizedDescription)", source: "SettingsStore")
@@ -557,9 +531,7 @@ final class SettingsStore: ObservableObject
defaults.set(encoded, forKey: Keys.savedProviders)
}
- if didModify {
- storedProviderKeyIDs = storedProviderKeyIDs + migratedIDs
- }
+ // No need to track migrated IDs; consolidated storage keeps them together.
}
private func canonicalProviderKey(for providerID: String) -> String {
@@ -572,6 +544,14 @@ final class SettingsStore: ObservableObject
return "custom:\(providerID)"
}
+ private func sanitizeAPIKeys(_ values: [String: String]) -> [String: String] {
+ values.reduce(into: [String: String]()) { partialResult, pair in
+ let sanitizedValue = pair.value.trimmingCharacters(in: .whitespacesAndNewlines)
+ guard sanitizedValue.isEmpty == false else { return }
+ partialResult[pair.key] = sanitizedValue
+ }
+ }
+
private func updateLaunchAtStartup(_ enabled: Bool) {
#if os(macOS)
// Note: SMAppService.mainApp requires the app to be signed with Developer ID