forked from BasedHardware/omi
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAPIKeyService.swift
More file actions
384 lines (334 loc) · 14 KB
/
Copy pathAPIKeyService.swift
File metadata and controls
384 lines (334 loc) · 14 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
import CryptoKit
import Foundation
/// Fetches API keys from the backend at runtime instead of bundling them in the app.
/// Developer overrides (set in Settings) take precedence over backend-provided keys.
///
/// Also hosts the Bring-Your-Own-Key (BYOK) free-plan flow: when the user supplies
/// their own OpenAI, Anthropic, Gemini, and Deepgram keys, the app sends them along
/// with every request and the backend skips subscription billing. Keys live in
/// UserDefaults (reusing the existing dev-override AppStorage pattern); the backend
/// only ever sees SHA-256 fingerprints for state tracking.
///
/// NOTE: Deepgram, Gemini, Anthropic keys are NO LONGER fetched from the backend —
/// they are proxied server-side (issues #5861, #6594).
/// Firebase and Calendar keys are still served via /v1/config/api-keys.
/// Keys that participate in the BYOK free-plan flow.
enum BYOKProvider: String, CaseIterable {
case openrouter
case openai
case anthropic
case gemini
case deepgram
var storageKey: String {
switch self {
case .openrouter: return "dev_openrouter_api_key"
case .openai: return "dev_openai_api_key"
case .anthropic: return "dev_anthropic_api_key"
case .gemini: return "dev_gemini_api_key"
case .deepgram: return "dev_deepgram_api_key"
}
}
var headerName: String {
switch self {
case .openrouter: return "X-BYOK-OpenRouter"
case .openai: return "X-BYOK-OpenAI"
case .anthropic: return "X-BYOK-Anthropic"
case .gemini: return "X-BYOK-Gemini"
case .deepgram: return "X-BYOK-Deepgram"
}
}
var displayName: String {
switch self {
case .openrouter: return "OpenRouter"
case .openai: return "OpenAI"
case .anthropic: return "Anthropic"
case .gemini: return "Gemini"
case .deepgram: return "Deepgram"
}
}
}
enum BYOKLLMProvider: String, CaseIterable, Identifiable {
case openrouter
case openai
case gemini
case anthropic
var id: String { rawValue }
var displayName: String {
switch self {
case .openrouter: return "OpenRouter"
case .openai: return "OpenAI Direct"
case .gemini: return "Gemini"
case .anthropic: return "Anthropic"
}
}
var provider: BYOKProvider {
switch self {
case .openrouter: return .openrouter
case .openai: return .openai
case .gemini: return .gemini
case .anthropic: return .anthropic
}
}
}
@MainActor
final class APIKeyService: ObservableObject {
static let shared = APIKeyService()
// Backend-provided keys (in-memory only, never persisted to disk)
@Published private(set) var geminiApiKey: String?
@Published private(set) var firebaseApiKey: String?
@Published private(set) var googleCalendarApiKey: String?
@Published private(set) var isLoaded: Bool = false
@Published private(set) var loadError: String?
/// The in-flight fetch task, so callers can await it instead of polling.
private var fetchTask: Task<Void, Never>?
/// Start fetching keys in the background. Callers can await via waitForKeys().
func startFetchingKeys() {
guard !isLoaded else { return }
guard fetchTask == nil else { return }
fetchTask = Task { await self.fetchKeys() }
}
/// Wait for keys to be loaded. Returns immediately if already loaded.
/// If no fetch is in-flight, starts one (handles app-restart-while-signed-in case).
/// A previously failed fetch clears fetchTask, so Calendar/Chat callers can retry without restarting.
func waitForKeys() async {
if isLoaded { return }
if fetchTask == nil {
log("APIKeyService: waitForKeys called but no fetch in-flight, starting one")
fetchTask = Task { await fetchKeys() }
}
await fetchTask?.value
if isLoaded { return }
if fetchTask == nil {
log("APIKeyService: key fetch completed without loaded keys, retrying once")
fetchTask = Task { await fetchKeys() }
await fetchTask?.value
}
}
var effectiveGeminiKey: String? {
nonEmpty(UserDefaults.standard.string(forKey: "dev_gemini_api_key")) ?? geminiApiKey
}
var effectiveFirebaseApiKey: String? {
firebaseApiKey
}
var effectiveGoogleCalendarApiKey: String? {
googleCalendarApiKey
}
/// Fetch keys from the backend. Call after Firebase auth is ready.
func fetchKeys() async {
loadError = nil
// Retry up to 3 times with backoff
for attempt in 1...3 {
do {
let keys = try await APIClient.shared.fetchApiKeys()
self.geminiApiKey = keys.geminiApiKey
self.firebaseApiKey = keys.firebaseApiKey
self.googleCalendarApiKey = keys.googleCalendarApiKey
self.isLoaded = true
// Set env vars so existing getenv() consumers keep working during transition
applyToEnvironment()
// Clear the completed task on the success path too (not just on the
// all-attempts-failed path below). Otherwise a stale finished task
// lingers; after sign-out (clear() sets isLoaded=false) the fetchTask
// == nil guards in startFetchingKeys()/waitForKeys() never fire, so a
// re-login can never refetch keys until the app is relaunched.
fetchTask = nil
log(
"APIKeyService: Fetched keys from backend (gemini=\(keys.geminiApiKey != nil), firebase=\(keys.firebaseApiKey != nil), calendar=\(keys.googleCalendarApiKey != nil))"
)
return
} catch {
let delay = pow(2.0, Double(attempt - 1))
log("APIKeyService: Fetch attempt \(attempt)/3 failed: \(error.localizedDescription), retrying in \(delay)s")
if attempt < 3 {
try? await Task.sleep(nanoseconds: UInt64(delay * 1_000_000_000))
}
}
}
loadError = "Failed to fetch API keys from backend"
log("APIKeyService: All fetch attempts failed — features requiring API keys will be unavailable")
fetchTask = nil
// Still apply env vars from developer overrides if set
applyToEnvironment()
}
/// Clear all keys (e.g. on sign-out)
func clear() {
geminiApiKey = nil
firebaseApiKey = nil
googleCalendarApiKey = nil
isLoaded = false
loadError = nil
// Drop any completed/in-flight fetch task so the next sign-in can start a
// fresh fetch — the fetchTask == nil guards would otherwise block it.
fetchTask?.cancel()
fetchTask = nil
unsetenv("GEMINI_API_KEY")
// NOTE: Do NOT unset FIREBASE_API_KEY — it's needed for the next sign-in
// (auth bootstrap requires Firebase key before backend is reachable)
unsetenv("GOOGLE_CALENDAR_API_KEY")
}
/// Push effective keys into the process environment for backward compatibility.
private func applyToEnvironment() {
if let key = effectiveGeminiKey {
setenv("GEMINI_API_KEY", key, 1)
}
if let key = effectiveFirebaseApiKey {
setenv("FIREBASE_API_KEY", key, 1)
}
if let key = effectiveGoogleCalendarApiKey {
setenv("GOOGLE_CALENDAR_API_KEY", key, 1)
}
}
private func nonEmpty(_ s: String?) -> String? {
guard let s, !s.trimmingCharacters(in: .whitespaces).isEmpty else { return nil }
return s
}
// MARK: - Thread-safe key access (for non-MainActor contexts)
// These read from UserDefaults (thread-safe) and getenv() (set by applyToEnvironment).
// Use these from actors, nonisolated inits, and background threads.
nonisolated static var currentGeminiKey: String? {
nonEmptyStatic(UserDefaults.standard.string(forKey: "dev_gemini_api_key"))
?? (getenv("GEMINI_API_KEY").flatMap { String(validatingCString: $0) })
}
/// True when the app has enough configuration to start transcription and screen analysis.
/// In proxy mode (OMI_DESKTOP_API_URL set), no client-side Deepgram/Gemini keys are needed.
nonisolated static var keysAvailable: Bool {
getenv("GEMINI_API_KEY") != nil || getenv("OMI_DESKTOP_API_URL") != nil
}
private nonisolated static func nonEmptyStatic(_ s: String?) -> String? {
guard let s, !s.trimmingCharacters(in: .whitespaces).isEmpty else { return nil }
return s
}
// MARK: - BYOK (Bring Your Own Keys) — free plan
/// Read a BYOK key from UserDefaults. Returns nil if empty/whitespace.
nonisolated static func byokKey(_ provider: BYOKProvider) -> String? {
nonEmptyStatic(UserDefaults.standard.string(forKey: provider.storageKey))
}
/// True when the user has supplied a selected LLM key.
/// The subscription-bypass gate: when this is true, the user is on the free
/// plan and we attach their selected LLM key to every backend request.
nonisolated static var isByokActive: Bool {
guard let provider = selectedBYOKLLMProvider, let key = byokKey(provider) else { return false }
return enrolledFingerprints()[provider.rawValue] == byokFingerprint(key)
}
nonisolated static var hasTranscriptionBYOK: Bool {
guard selectedBYOKLLMProvider != nil, let key = byokKey(.deepgram) else { return false }
return enrolledFingerprints()["deepgram"] == byokFingerprint(key)
}
/// Persist fingerprints that passed BYOKValidator and were sent to activateBYOK.
nonisolated static func clearPersistedBYOKKeys() {
let defaults = UserDefaults.standard
for provider in BYOKProvider.allCases {
defaults.removeObject(forKey: provider.storageKey)
}
defaults.removeObject(forKey: DefaultsKey.byokLLMProvider.rawValue)
persistEnrolledFingerprints([:])
}
nonisolated static func bindBYOKOwner(_ uid: String?) {
guard let uid, !uid.isEmpty else { return }
let last = UserDefaults.standard.string(forKey: DefaultsKey.byokOwnerUid.rawValue)
if last != uid {
// Unowned pre-upgrade keys (last == nil) are unsafe to inherit: the next
// signed-in account would otherwise enroll someone else's credentials.
clearPersistedBYOKKeys()
UserDefaults.standard.set(uid, forKey: DefaultsKey.byokOwnerUid.rawValue)
}
}
nonisolated static func persistEnrolledFingerprints(_ fingerprints: [String: String]) {
if fingerprints.isEmpty {
UserDefaults.standard.removeObject(forKey: DefaultsKey.byokEnrolledFingerprints.rawValue)
} else {
UserDefaults.standard.set(fingerprints, forKey: DefaultsKey.byokEnrolledFingerprints.rawValue)
}
}
nonisolated static func enrolledFingerprints() -> [String: String] {
UserDefaults.standard.dictionary(forKey: DefaultsKey.byokEnrolledFingerprints.rawValue) as? [String: String]
?? [:]
}
/// Voice/realtime may use a leftover OpenAI/Gemini key only when that provider is selected.
nonisolated static func selectedRealtimeBYOKKey(for provider: BYOKProvider) -> String? {
guard selectedBYOKLLMProvider == provider else { return nil }
return byokKey(provider)
}
nonisolated static var selectedBYOKLLMProvider: BYOKProvider? {
let requested: BYOKLLMProvider
if let stored = UserDefaults.standard.string(forKey: .byokLLMProvider),
let selected = BYOKLLMProvider(rawValue: stored)
{
requested = selected
} else if let legacy = BYOKLLMProvider.allCases.first(where: { byokKey($0.provider) != nil }) {
requested = legacy
} else {
requested = .openrouter
}
return byokKey(requested.provider) == nil ? nil : requested.provider
}
/// SHA-256 fingerprint of a key, used by the backend to detect when the
/// user rotated their keys without us ever storing the key itself.
nonisolated static func byokFingerprint(_ key: String) -> String {
let digest = SHA256.hash(data: Data(key.utf8))
return digest.map { String(format: "%02x", $0) }.joined()
}
/// Map of provider → (key, fingerprint) for every provider the user has configured.
nonisolated static var byokSnapshot: [BYOKProvider: (key: String, fingerprint: String)] {
var out: [BYOKProvider: (String, String)] = [:]
for provider in BYOKProvider.allCases {
if let key = byokKey(provider) {
out[provider] = (key, byokFingerprint(key))
}
}
return out
}
nonisolated static var activeBYOKSnapshot: [BYOKProvider: (key: String, fingerprint: String)] {
var snapshot: [BYOKProvider: (String, String)] = [:]
if let provider = selectedBYOKLLMProvider, let key = byokKey(provider) {
snapshot[provider] = (key, byokFingerprint(key))
}
if let key = byokKey(.deepgram) {
snapshot[.deepgram] = (key, byokFingerprint(key))
}
return snapshot
}
private static let reconcileLock = NSLock()
private static var reconcileGeneration: UInt64 = 0
private static func nextReconciliationGeneration() -> UInt64 {
reconcileLock.lock()
defer { reconcileLock.unlock() }
reconcileGeneration += 1
return reconcileGeneration
}
private static func isCurrentReconciliation(_ generation: UInt64) -> Bool {
reconcileLock.lock()
defer { reconcileLock.unlock() }
return reconcileGeneration == generation
}
func reconcileBYOKActivation() async {
Self.bindBYOKOwner(UserDefaults.standard.string(forKey: .authUserId))
guard let selectedProvider = Self.selectedBYOKLLMProvider, Self.byokKey(selectedProvider) != nil else { return }
let generation = Self.nextReconciliationGeneration()
let snapshot = Self.activeBYOKSnapshot.reduce(into: [BYOKProvider: String]()) { result, entry in
result[entry.key] = entry.value.key
}
let statuses = await BYOKValidator.validateAll(snapshot)
guard Self.isCurrentReconciliation(generation) else { return }
guard statuses[selectedProvider] == .ok else {
try? await APIClient.shared.deactivateBYOK()
guard Self.isCurrentReconciliation(generation) else { return }
Self.persistEnrolledFingerprints([:])
return
}
// Fingerprints must come from the captured snapshot, not a later UserDefaults
// edit that raced the provider check.
let fingerprints = snapshot.reduce(into: [String: String]()) { result, entry in
if statuses[entry.key] == .ok {
result[entry.key.rawValue] = Self.byokFingerprint(entry.value)
}
}
do {
try await APIClient.shared.activateBYOK(fingerprints: fingerprints)
guard Self.isCurrentReconciliation(generation) else { return }
Self.persistEnrolledFingerprints(fingerprints)
} catch {
// Leave local capability inactive when the backend never enrolled.
}
}
}