Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import Foundation

/// iOS counterpart to Android's `CloudApiKeyStore` interface (core/cloudtts/CloudApiKeyStore.kt)
/// — a protocol, not a direct Keychain call at every call site, for the same reason
/// `HardwareKeyWrap` is one (see that file's doc comment): fakeable in plain unit tests
/// without touching the real Keychain. Credentials are a `[CloudCredentialField: String]`
/// map, not a single `apiKey: String`, matching Android's identical shape (see
/// `CloudCredentialFields`'s doc comment for why).
protocol CloudApiKeyStore {
/// Overwrites any existing credentials for `provider`. Callers (see
/// `CloudApiKeyStoreError`) are expected to have already validated the credentials
/// against the real vendor API (PRD §6: "validated with a single cheap test call,
/// then stored") — this method itself does no validation, only storage.
func save(provider: CloudProviderId, credentials: [CloudCredentialField: String]) throws

/// `nil` if nothing has been saved for `provider` yet.
func load(provider: CloudProviderId) -> [CloudCredentialField: String]?

/// No-op if nothing was saved for `provider`.
func clear(provider: CloudProviderId)
}

/// Errors `CloudApiKeyStore` conformers can throw.
enum CloudApiKeyStoreError: LocalizedError, Equatable {
/// `credentials`' keys didn't exactly match `CloudCredentialFields.requiredFields`
/// for the given provider — mirrors Android's `RealCloudApiKeyStore.saveCredentials`
/// `require()` check, catching a caller bug (a missing/extra field) before it's
/// silently stored in a shape a vendor adapter can't actually use.
case fieldMismatch(provider: CloudProviderId)

/// A Keychain operation (`SecItemAdd`/`SecItemUpdate`/`SecItemDelete`) failed for a
/// reason other than "item not found."
case keychainError(status: OSStatus)

var errorDescription: String? {
switch self {
case .fieldMismatch(let provider):
return "Credentials for \(provider.displayName) don't match its required fields"
case .keychainError(let status):
return "Keychain operation failed (OSStatus \(status))"
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import Foundation

/// Mirrors Android's `CloudCredentialFields` object (core/cloudtts/CloudApiKeyStore.kt)
/// field-by-field — kept in sync by hand, like `StoreKitBillingManager`'s product ids,
/// since Kotlin and Swift can't share a constant here. A single `apiKey: String` couldn't
/// express Amazon Polly's real (SigV4, multi-field) auth — same reasoning as Android's
/// identical `Map<String, String>`-shaped credentials.
enum CloudCredentialField: String, Codable, CaseIterable, Hashable {
case apiKey
case region
case accessKeyID
case secretAccessKey

var label: String {
switch self {
case .apiKey: return "API Key"
case .region: return "Region"
case .accessKeyID: return "Access Key ID"
case .secretAccessKey: return "Secret Access Key"
}
}
}

enum CloudCredentialFields {
/// Which fields each vendor's real auth scheme actually needs. Mirrors Android's
/// `CloudCredentialFields.requiredFields` exactly:
/// - ElevenLabs (`xi-api-key` header), OpenAI, Google Cloud TTS (bearer header) —
/// a single API key.
/// - Azure AI Speech — API key plus a region (its host is region-scoped:
/// `{region}.tts.speech.microsoft.com`).
/// - Amazon Polly — SigV4 request signing needs an access key id, secret access
/// key, AND region; there's no single bearer token.
static func requiredFields(for provider: CloudProviderId) -> Set<CloudCredentialField> {
switch provider {
case .elevenLabs, .openAI, .googleCloudTTS:
return [.apiKey]
case .azureSpeech:
return [.apiKey, .region]
case .amazonPolly:
return [.accessKeyID, .secretAccessKey, .region]
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import Foundation

/// Mirrors Android's `CloudProviderId` (core/cloudtts/CloudProviderId.kt) — the PRD's
/// closed list of five vendor presets (docs/cloud-tts-premium-prd.md §3). `String`-backed
/// and `Codable` so it round-trips directly through `UserDefaults`/Keychain storage
/// (see `CloudVoicePreferences`/`KeychainCloudApiKeyStore`) without a separate raw-value
/// mapping layer. Raw values are camelCase (Swift convention), NOT the same strings as
/// Android's `CloudProviderId.name` (SCREAMING_SNAKE_CASE, e.g. `"GOOGLE_CLOUD_TTS"`) —
/// the two platforms never share persisted state, so there's no cross-platform format to
/// keep in sync here, unlike `StoreKitBillingManager`'s product ids.
enum CloudProviderId: String, CaseIterable, Codable {
case elevenLabs
case openAI
case googleCloudTTS
case azureSpeech
case amazonPolly

var displayName: String {
switch self {
case .elevenLabs: return "ElevenLabs"
case .openAI: return "OpenAI"
case .googleCloudTTS: return "Google Cloud TTS"
case .azureSpeech: return "Azure AI Speech"
case .amazonPolly: return "Amazon Polly"
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import Foundation

/// The four-quadrant gate (PRD §4): a real subscription AND explicit consent are BOTH
/// required before any cloud TTS call is allowed. A pure function taking two plain
/// `Bool`s, not a class wrapping live `StoreKitBillingManager`/`CloudVoicePreferences`
/// instances — `StoreKitBillingManager.isSubscribed` needs a live `SKTestSession`/
/// `.storekit` config to exercise for real, a documented Xcode 26.5 `xcodebuild test`
/// CLI gap (see `StoreKitBillingManagerTests.skipIfStoreKitConfigUnavailableViaCLI`'s doc
/// comment). Extracting the actual AND logic into a function of two `Bool`s means
/// `CloudTtsGateTests` can exercise all four quadrants with neither a live StoreKit
/// session nor a real UserDefaults-backed `CloudVoicePreferences` — mirrors Android's
/// `CloudTtsGate` combining `SupportBillingClient.observeSubscriptionActive()` and
/// `TtsPreferences.consentFlow`, minus the `Flow`/reactive plumbing iOS doesn't need
/// here (both inputs are already synchronously readable: `isSubscribed` is a `@Published`
/// property already resolved by billing-manager init, `consentEnabled` is a plain
/// `UserDefaults` read).
enum CloudTtsGate {
/// Explicitly `isSubscribed`, NOT `isSupporter` — a one-time tip alone (no active
/// subscription) must never open this gate, matching the PRD-mandated distinction
/// `StoreKitBillingManager.isSubscribed`'s own doc comment draws from `isSupporter`.
static func canUseCloudTts(isSubscribed: Bool, consentEnabled: Bool) -> Bool {
isSubscribed && consentEnabled
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
import Foundation

/// One HTTP call shape shared by all five vendor adapters (`Vendors/*Adapter.swift`) —
/// iOS counterpart to Android's `CloudTtsProvider` interface (core/cloudtts/CloudTtsProvider.kt).
/// A protocol, not a direct `URLSession` call at every call site, both for fakeability in
/// tests and so `CloudTtsEngine` can dispatch to whichever vendor is actually selected
/// without a hardcoded `switch` of its own — `RealCloudTtsProvider` (added in the
/// vendors PR) is the dispatcher; this is just the shared contract.
///
/// Every conformer/caller MUST check `CloudTtsGate.canUseCloudTts` immediately before
/// calling either method below — this protocol has no way to enforce that itself, since
/// enforcing it here would require this protocol to depend on `StoreKitBillingManager`/
/// `CloudVoicePreferences`, which would invert the dependency direction this feature is
/// built on (see the implementation plan's "Engine integration seam"). `CloudTtsEngine`
/// (added in the engine PR) is the actual enforcement point.
protocol CloudTtsProvider {
/// Synthesizes `text` as speech using `voiceID` and `credentials`, returning the raw
/// audio bytes. Format is vendor-specific (MP3 for most) — handled generically by
/// `AVAudioPlayer` on the `CloudTtsEngine` side, the same "don't care about the
/// container format, just play the bytes" approach Android's `MediaPlayer`-based
/// `CloudPlayback` takes.
func synthesize(
provider: CloudProviderId,
text: String,
voiceID: String,
credentials: [CloudCredentialField: String]
) async throws -> Data

/// A single cheap validation call (PRD §6: "validated with a single cheap test
/// call, then stored") — never persists anything itself. The caller only saves
/// credentials (via `CloudApiKeyStore`) once this succeeds.
func validateKey(
provider: CloudProviderId,
credentials: [CloudCredentialField: String]
) async throws
}

/// Errors this protocol's conformers throw — deliberately generic (not
/// per-vendor-specific HTTP status parsing) since callers only need to know "did it
/// work," not why, to decide whether to fall back to the on-device engine. Mirrors
/// Android's `CloudTtsProvider`'s `Result<...>` failure shape, adapted to Swift's
/// `throws` convention.
enum CloudTtsProviderError: LocalizedError, Equatable {
case missingCredentials(field: CloudCredentialField)
case httpError(statusCode: Int, body: String)
case invalidResponse

var errorDescription: String? {
switch self {
case .missingCredentials(let field):
return "Missing required field: \(field.label)"
case .httpError(let statusCode, let body):
return "HTTP \(statusCode): \(body.prefix(200))"
case .invalidResponse:
return "Unexpected response from the TTS vendor"
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
import Foundation

/// Consent + selection state for Premium Cloud TTS Voices (PRD §4/§6). Mirrors
/// `SupporterStatusPersistence`'s exact shape (plain, non-`ObservableObject` struct,
/// injectable `UserDefaults` for test isolation, namespaced `"xyz.libravault.*"` keys) —
/// deliberately NOT bolted onto `UserPreferencesPersistence`, whose existing boolean
/// keys (e.g. `loadMiniPlayerAutoHideEnabled`) use `object(forKey:) as? Bool` specifically
/// to default to `true`/enabled when absent. Consent here needs the opposite default
/// (PRD §4: off until explicitly accepted), which `UserDefaults.bool(forKey:)`'s
/// absent-reads-false behavior already gives for free — reusing the wrong-polarity
/// pattern would risk a future refactor accidentally flipping the default.
struct CloudVoicePreferences {
private let defaults: UserDefaults

private enum Key {
static let consentEnabled = "xyz.libravault.cloudtts.consentEnabled"
static let selectedProvider = "xyz.libravault.cloudtts.selectedProvider"
static let selectedVoiceID = "xyz.libravault.cloudtts.selectedVoiceID"
}

init(defaults: UserDefaults = .standard) {
self.defaults = defaults
}

/// Absent key correctly reads as `false` via `bool(forKey:)` — a never-configured
/// install must default to consent OFF (PRD §4: "off by default — enabling it sends
/// text to a vendor's servers"), the same "do not silently opt in" reasoning as
/// Android's `CLOUD_VOICES_CONSENT_KEY` default.
func loadConsentEnabled() -> Bool {
defaults.bool(forKey: Key.consentEnabled)
}

func save(consentEnabled: Bool) {
defaults.set(consentEnabled, forKey: Key.consentEnabled)
}

func loadSelectedProvider() -> CloudProviderId? {
guard let raw = defaults.string(forKey: Key.selectedProvider) else { return nil }
return CloudProviderId(rawValue: raw)
}

func save(selectedProvider: CloudProviderId?) {
defaults.set(selectedProvider?.rawValue, forKey: Key.selectedProvider)
}

/// Scoped to Cloud TTS only — deliberately a SEPARATE key from
/// `UserPreferencesPersistence`'s TTS engine type, not shared the way Android's
/// `TtsPreferences.selectedVoiceFlow` is shared across all three engine types
/// there. iOS's on-device engines (`TTSEngineBridge`/`PocketTTSEngine`) don't have
/// a "selected voice id" concept of their own to collide with (see
/// `TTSEngineBridge.voice(for:)` — the system voice is auto-detected from text
/// language, never user-picked), so there's no equivalent stale-carryover risk to
/// guard against here the way `CloudVoicesSection`'s Android counterpart does.
func loadSelectedVoiceID() -> String? {
defaults.string(forKey: Key.selectedVoiceID)
}

func save(selectedVoiceID: String?) {
defaults.set(selectedVoiceID, forKey: Key.selectedVoiceID)
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
import Foundation
import Security

/// Real, Keychain-backed `CloudApiKeyStore`. One `kSecClassGenericPassword` item per
/// provider, keyed by `kSecAttrAccount` = the provider's raw value under a fixed
/// `kSecAttrService` — a different shape from `SecureEnclaveHardwareKeyWrapFactory`'s
/// `kSecClassKey` items (that class stores an actual EC keypair; this stores an
/// arbitrary opaque secret, which `kSecClassGenericPassword` is Apple's documented class
/// for).
///
/// Deliberately does NOT additionally wrap the value through `HardwareKeyWrap`/the
/// Secure Enclave the way Android's `RealCloudApiKeyStore` wraps through
/// `HardwareKeyWrapFactory` before writing to DataStore — that extra layer exists on
/// Android because a DataStore file is plain app-private storage with no OS-level
/// encryption-at-rest of its own. The iOS Keychain already provides encryption-at-rest
/// itself (backed by the Secure Enclave-derived class keys, the same hierarchy
/// `SecureEnclaveHardwareKeyWrap` sits on top of for the vault master key), and
/// `kSecAttrAccessibleWhenUnlockedThisDeviceOnly` below is the standard, sufficient
/// pattern for a secret like a BYOK vendor API key — unlike the vault master key, this
/// isn't LibraVault's root of trust, so no extra ECIES wrapping layer is warranted here.
///
/// Credentials are JSON-encoded as `[String: String]` (not `[CloudCredentialField:
/// String]` directly) before being handed to `JSONEncoder` — dictionaries keyed by a
/// custom `RawRepresentable` enum aren't guaranteed to encode as a JSON object across
/// Codable's synthesized behavior, so the field/value pairs are converted to plain
/// `String` keys first, matching a pattern already proven safe rather than relying on
/// an implementation detail.
final class KeychainCloudApiKeyStore: CloudApiKeyStore {

private static let service = "xyz.libravault.cloudtts.apikey"

func save(provider: CloudProviderId, credentials: [CloudCredentialField: String]) throws {
let requiredFields = CloudCredentialFields.requiredFields(for: provider)
guard Set(credentials.keys) == requiredFields else {
throw CloudApiKeyStoreError.fieldMismatch(provider: provider)
}

let plainKeyed = Dictionary(uniqueKeysWithValues: credentials.map { ($0.key.rawValue, $0.value) })
let data: Data
do {
data = try JSONEncoder().encode(plainKeyed)
} catch {
// JSONEncoder failing on a [String: String] would mean something is
// fundamentally broken about the runtime, not a real recoverable case —
// there's no vendor-specific reason this should ever throw, so it's
// surfaced as the same keychainError case with status 0 rather than adding
// a third error case nothing else in this type could ever produce.
throw CloudApiKeyStoreError.keychainError(status: 0)
}

// Delete-then-add, not SecItemUpdate: mirrors
// SecureEnclaveHardwareKeyWrapFactory.createNew's "any existing item under this
// identity is replaced" contract — simpler than branching on whether an item
// already exists, and this is a cheap, infrequent (user-initiated) operation.
deleteItem(provider: provider)

var query = keychainQuery(provider: provider)
query[kSecValueData as String] = data
query[kSecAttrAccessible as String] = kSecAttrAccessibleWhenUnlockedThisDeviceOnly

let status = SecItemAdd(query as CFDictionary, nil)
guard status == errSecSuccess else {
throw CloudApiKeyStoreError.keychainError(status: status)
}
}

func load(provider: CloudProviderId) -> [CloudCredentialField: String]? {
var query = keychainQuery(provider: provider)
query[kSecReturnData as String] = true
query[kSecMatchLimit as String] = kSecMatchLimitOne

var item: CFTypeRef?
let status = SecItemCopyMatching(query as CFDictionary, &item)
guard status == errSecSuccess, let data = item as? Data else { return nil }

guard let plainKeyed = try? JSONDecoder().decode([String: String].self, from: data) else {
return nil
}
// A field name that no longer maps to a known CloudCredentialField (e.g. a
// stale Keychain item from a since-removed field) is dropped rather than
// failing the whole load — the caller's own required-fields check downstream
// (CloudTtsEngine/onValidateAndSaveCloudKey-equivalent) is what should reject a
// now-incomplete credential set, not this layer silently returning nil for an
// otherwise-readable item.
return Dictionary(uniqueKeysWithValues: plainKeyed.compactMap { key, value in
CloudCredentialField(rawValue: key).map { ($0, value) }
})
}

func clear(provider: CloudProviderId) {
deleteItem(provider: provider)
}

private func deleteItem(provider: CloudProviderId) {
SecItemDelete(keychainQuery(provider: provider) as CFDictionary)
}

private func keychainQuery(provider: CloudProviderId) -> [String: Any] {
[
kSecClass as String: kSecClassGenericPassword,
kSecAttrService as String: Self.service,
kSecAttrAccount as String: provider.rawValue,
]
}
}
Loading
Loading