Skip to content

feat(ios): Cloud TTS foundation — Keychain store, consent, pure gate - #472

Merged
libravault-xyz merged 1 commit into
devfrom
feature/cloudtts-ios-foundation
Aug 23, 2026
Merged

libravault-xyz merged 1 commit into
devfrom
feature/cloudtts-ios-foundation

Conversation

@libravault-xyz

Copy link
Copy Markdown
Collaborator

What

PR 1 of 4 for iOS's half of Premium Cloud TTS Voices (BYOK) — progress toward #452. Mirrors Android's core:cloudtts foundation (#462), adapted where iOS's own conventions genuinely differ rather than ported literally — see the implementation plan's "Secure key storage" and "Consent toggle" sections for the reasoning already written down before this was built.

New: Sources/Features/CloudTTS/

  • CloudProviderId — the PRD's closed 5-vendor list (§3).
  • CloudCredentialFields — per-provider required-field sets: Amazon Polly's SigV4 needs 3 fields (access key id/secret/region), Azure needs 2 (key + region-scoped host), the rest need 1 bearer key. Same reasoning as Android's identical Map<String, String> credential shape — kept in sync by hand across the two files, not shared code.
  • CloudApiKeyStore protocol + KeychainCloudApiKeyStore — one kSecClassGenericPassword item per provider, kSecAttrAccessibleWhenUnlockedThisDeviceOnly. Deliberately does NOT additionally wrap 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 has no OS-level encryption-at-rest of its own. The Keychain already provides that here, and a BYOK vendor key isn't LibraVault's root of trust the way the vault master key is — see the file's own doc comment for the full reasoning.
  • CloudVoicePreferences — consent/selected-provider/selected-voice-id, mirrors SupporterStatusPersistence's exact shape (not bolted onto UserPreferencesPersistence, whose existing boolean keys use the opposite "true by default" polarity — wrong default for a feature PRD §4 requires off by default).
  • CloudTtsGate — a pure function, 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). Keeping the actual AND logic in a function of two Bools means CloudTtsGateTests covers all four quadrants with zero StoreKit dependency.
  • CloudTtsProvider protocol — shared shape for the 5 vendor adapters (next PR).

Testing

  • CloudTtsGateTests — 4-quadrant coverage plus an explicit "subscription alone never opens the gate" regression guard (the single most safety-critical assertion here, PRD §4).
  • CloudVoicePreferencesTests — round trip + default-false-when-absent.
  • CloudCredentialFieldsTests — pins each provider's required-field set, including a dedicated regression guard for Polly's 3-field SigV4 shape.
  • CloudApiKeyStoreTests — round trip against the real Keychain (Simulator-safe, unlike Secure Enclave persistence). Guarded with the same errSecMissingEntitlement → XCTSkip pattern SecureEnclaveHardwareKeyWrapTests already uses for this CI job's CODE_SIGNING_ALLOWED=NO environment (confirmed necessary there 2026-08-19) — generic-password persistence isn't guaranteed exempt from the same restriction, so this suite degrades the same way rather than failing CI outright if that turns out to be true here too.
  • FakeCloudApiKeyStore — in-memory test double for downstream test targets (engine/UI PRs).

Known limitation of this PR

No Xcode/macOS is available in the environment this was written in — verified by careful manual review against this codebase's existing conventions (matched HardwareKeyWrap/SecureEnclaveHardwareKeyWrapFactory's Keychain query style, SupporterStatusPersistence's UserDefaults shape, and the skipIfKeychainKeyPersistenceUnavailable CI gotcha) rather than a local build. Real verification is this PR's own CI run (ios-app-build.yml) — flagging explicitly per the implementation plan's "Known gaps" section rather than silently asserting local test-green.

Part of #452. Governance: #449.

…gate

PR 1 of 4 for iOS's half of Premium Cloud TTS Voices (BYOK), issue #452.
Mirrors Android's core:cloudtts foundation (#462), adapted where iOS's
own conventions genuinely differ rather than ported literally.

New Sources/Features/CloudTTS/:
- CloudProviderId — the PRD's closed 5-vendor list (§3).
- CloudCredentialFields — per-provider required-field sets (Amazon
  Polly's SigV4 needs 3 fields, Azure needs 2, the rest need 1 bearer
  key) — same reasoning as Android's identical Map<String,String>
  credential shape, kept in sync by hand.
- CloudApiKeyStore protocol + KeychainCloudApiKeyStore — one
  kSecClassGenericPassword item per provider, kSecAttrAccessibleWhen
  UnlockedThisDeviceOnly. Deliberately does NOT additionally wrap
  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 has no OS-level encryption-at-rest of its own; the
  Keychain already provides that here, and a BYOK vendor key isn't
  LibraVault's root of trust the way the vault master key is.
- CloudVoicePreferences — consent/selected-provider/selected-voice-id,
  mirrors SupporterStatusPersistence's shape (not bolted onto
  UserPreferencesPersistence, whose existing keys use the opposite
  "true by default" polarity).
- CloudTtsGate — pure function, not a class wrapping live
  StoreKitBillingManager/CloudVoicePreferences: StoreKitBillingManager
  needs a live SKTestSession to test for real (documented Xcode 26.5
  CLI gap), so the actual AND logic lives in a function of two Bools
  instead, letting CloudTtsGateTests cover all four quadrants with no
  StoreKit dependency at all.
- CloudTtsProvider protocol — shared shape for the 5 vendor adapters
  (next PR).

Tests: CloudTtsGateTests (4-quadrant + explicit "subscription alone
never opens the gate" regression guard), CloudVoicePreferencesTests,
CloudCredentialFieldsTests, CloudApiKeyStoreTests (real Keychain
round-trip — guarded with the same errSecMissingEntitlement XCTSkip
pattern SecureEnclaveHardwareKeyWrapTests already uses for this CI
job's CODE_SIGNING_ALLOWED=NO environment), FakeCloudApiKeyStore for
downstream test targets (engine/UI PRs).

No Xcode/macOS available in this environment — verified by careful
manual review against this codebase's existing conventions (matched
HardwareKeyWrap/SecureEnclaveHardwareKeyWrapFactory's Keychain query
style, SupporterStatusPersistence's UserDefaults shape, and the
skipIfKeychainKeyPersistenceUnavailable CI gotcha) rather than a local
build; real verification is this PR's CI run (ios-app-build.yml).

Closes nothing yet — first of 4 iOS PRs for #452.
@github-actions github-actions Bot added the risk:high Touches a sensitive path or exceeds diff-size threshold — always human merge label Aug 23, 2026
@libravault-pipeline-bot libravault-pipeline-bot Bot added the status:needs-review QA passed, awaiting principal-review-agent label Aug 23, 2026
@github-actions

Copy link
Copy Markdown
Contributor

This PR was opened outside the automated pipeline (author isn't libravault-pipeline-bot[bot]) and doesn't link an issue (no Closes #N-style line in its body), so there's no acceptance criteria for qa-agent.yml to verify against — it would otherwise sit with no risk/status label and nothing downstream would pick it up (see issue #223's actual history, and issue #343 for this issue-less case specifically). This deterministic backstop (pr-intake.yml) classified its risk and applied status:needs-review to route it straight to principal review.

@github-actions

Copy link
Copy Markdown
Contributor

📱 iOS Build Status: PASSED

✅ iOS Simulator Build & Unit Tests - success
⏭️ Android Core Modules - skipped

iOS UI tests run in a separate, informational job and are not reflected above — check "iOS UI Tests (informational)" for those.

View run details

@github-actions

Copy link
Copy Markdown
Contributor

Principal review — verdict: human-merge

Risk label: risk:high — correctly applied. Confirmed independently: git diff --numstat against the merge-base with dev is 636 changed lines (all additions), over the 400-line max_auto_mergeable_diff_lines threshold in .github/agent-policy.yml. No changed file matches a sensitive_paths glob (the new ios/.../Sources/Features/CloudTTS/** files aren't listed; they're distinct from the gated Sources/VaultCrypto/**/Sources/VaultStore/** paths). So this is risk:high on diff size alone — the label wasn't stale (label was applied on the only commit).

This means outcome is human-merge regardless of finding severity, per policy. Reviewed to full depth anyway since a human still has to act on this.

What I verified (not just read)

  • Every "mirrors Android's X" / "matches existing convention Y" claim in the PR body checked against the actual referenced file — all confirmed accurate, including some fairly specific ones:
    • core/cloudtts/CloudApiKeyStore.kt's CloudCredentialFields object matches the iOS port field-for-field (Polly's 3-field SigV4 shape, Azure's 2-field, others' 1-field).
    • SecureEnclaveHardwareKeyWrapTests.swift's errSecMissingEntitlement/CODE_SIGNING_ALLOWED=NO skip pattern and the "confirmed against a real CI run (2026-08-19)" claim — present verbatim in that file.
    • StoreKitBillingManagerTests.skipIfStoreKitConfigUnavailableViaCLI and the Xcode 26.5 CLI gap — present.
    • UserPreferencesPersistence.loadMiniPlayerAutoHideEnabled's as? Bool ?? true-shaped default — present, confirms the stated reason for not reusing that file for consent storage (wrong default polarity).
    • TTSEngineBridge.voice(for:) auto-detecting language rather than being user-selectable — present in DomainBridge.swift, supports the claim that there's no stale-voice-carryover risk to guard against on iOS the way Android's CloudVoicesSection does.
  • Ran the PR's actual CI (Build & Test iOS (Simulator), run 32653630464) to completion rather than trusting the PR body's "known limitation: no Xcode locally, verified by manual review" framing — it now shows pass (6m31s). Pulled the job log directly: all four new test suites ran and passed; the CloudApiKeyStoreTests real-Keychain cases skipped exactly as documented (errSecMissingEntitlement under this job's CODE_SIGNING_ALLOWED=NO), not silently passed or excluded. This is exactly the "confirm CI actually ran" bar the review persona sets, and the PR's own honesty about not having a local build made it worth the extra minutes to wait on.
  • Networking sign-off check: this PR's foundation includes a CloudTtsProvider protocol whose conformers will make real HTTP calls to five third-party vendors in a later PR. Checked for prior human sign-off per policy — found it: issue Sign-off: Premium Cloud TTS Voices reverses "no Pro tier" (#172) and narrows on #400's networking scope #449 ("Sign-off: Premium Cloud TTS Voices reverses 'no Pro tier' (chore: delete core:licensing — no Pro/paid tier for now, docs cleanup #172) and narrows on PR #398/#397 reintroduce real networking (StoreKit 2 / Play Billing) with no documented human sign-off reversing the explicit "zero network calls" decision from #163 #400's networking scope"), closed, explicit product-owner approval dated 2026-08-22 for exactly this: five named BYOK vendor endpoints, subscription-gated, plus a second independent consent toggle. This PR's CloudTtsGate (isSubscribed && consentEnabled) and CloudProviderId's closed 5-vendor enum match that sign-off's scope exactly. No actual network call ships in this PR (protocol only, no URLSession implementation) — consistent with "PR 1 of 4."
  • Sensitive-path / pipeline-bypass check: this PR was opened directly by libravault-xyz, not the pipeline bot, and never went through dev-agent/qa-agent — confirmed via the pr-intake.yml bot comment on the PR, which is the documented, deterministic backstop for exactly this case (issue iOS: no way to delete a Vault (Manage Vaults screen is a static mock) #223/[ci] pr-intake.yml leaves manually-opened PRs with no linked issue completely unlabeled #343 precedent). Nothing in .github/agent-policy.yml's sensitive_paths or sensitive_issue_labels gates apply differently here since no autonomous dev-agent triage occurred — but worth flagging for the human merger: the originating issue Premium Cloud TTS Voices — iOS implementation (BYOK, 5 presets) #452 itself carries the security label, so this is exactly the kind of change that label exists to slow down, even though the fast-path here is a diff-size trigger rather than a security-content one.

Findings

No CONFIRMED-severity findings — nothing rising to the bar that requires a gh issue create per the persona's "documenting real findings" section.

Two PLAUSIBLE/minor notes for the human merger to weigh, neither blocking:

  1. CloudApiKeyStoreError.keychainError(status: 0) (KeychainCloudApiKeyStore.swift:346) reuses the keychainError case with a synthetic OSStatus of 0 for a JSONEncoder failure on [String: String] — 0 is errSecSuccess, so a caller pattern-matching on .keychainError(status:) and logging the raw status would see a nonsensical "success" status attached to a thrown error. The PR's own comment acknowledges this is meant to be practically unreachable (encoding a flat string dictionary essentially can't fail), so this is cosmetic, not a functional bug.
  2. AGENTS.md's "prove a new test can fail" rule (deliberately breaking each new assertion once, pre-commit, per the "Test conventions" section) isn't addressed in the PR body the way it is for, e.g., prior iOS Keychain-test PRs. Given the author had no local Xcode available this run, they couldn't have easily done this themselves before pushing; the tests here are simple enough (direct equality/boolean assertions, no mocking-that-could-silently-no-op) that the failure mode this rule guards against seems unlikely, but it's worth a human's second look rather than my asserting it's fine.

Everything else checked clean

  • CloudTtsGate is a pure function of two Bools with all 4 quadrants tested plus an explicit "subscription alone never opens the gate" regression test — correctly implements the PRD §4 requirement verified in Sign-off: Premium Cloud TTS Voices reverses "no Pro tier" (#172) and narrows on #400's networking scope #449.
  • CloudVoicePreferences defaults to consent-false-when-absent (verified via UserDefaults.bool(forKey:)'s documented absent-read behavior, and by the passing testLoadConsentEnabledDefaultsToFalseWhenNothingSaved test).
  • Keychain round-trip logic (JSON-encode a [String: String]-remapped dict rather than [CloudCredentialField: String] directly) is correct and matches genuine Codable/Dictionary behavior — a RawRepresentable-keyed dictionary without CodingKeyRepresentable conformance does not encode as a JSON object under JSONEncoder, so the remapping is a real fix, not defensive over-engineering.
  • Field-mismatch validation (Set(credentials.keys) == requiredFields) correctly rejects both missing and extra fields, with tests for both directions.
  • No new networking dependency actually lands in this PR despite the eventual scope; CloudTtsProvider is a protocol only.

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Principal review — verdict: human-merge

Risk label: risk:high — correctly applied. Confirmed independently: git diff --numstat against the merge-base with dev is 636 changed lines (all additions), over the 400-line max_auto_mergeable_diff_lines threshold in .github/agent-policy.yml. No changed file matches a sensitive_paths glob (the new ios/.../Sources/Features/CloudTTS/** files aren't listed; they're distinct from the gated Sources/VaultCrypto/**/Sources/VaultStore/** paths). So this is risk:high on diff size alone — the label wasn't stale (label was applied on the only commit).

This means outcome is human-merge regardless of finding severity, per policy. Reviewed to full depth anyway since a human still has to act on this.

What I verified (not just read)

  • Every "mirrors Android's X" / "matches existing convention Y" claim in the PR body checked against the actual referenced file — all confirmed accurate, including some fairly specific ones:
    • core/cloudtts/CloudApiKeyStore.kt's CloudCredentialFields object matches the iOS port field-for-field (Polly's 3-field SigV4 shape, Azure's 2-field, others' 1-field).
    • SecureEnclaveHardwareKeyWrapTests.swift's errSecMissingEntitlement/CODE_SIGNING_ALLOWED=NO skip pattern and the "confirmed against a real CI run (2026-08-19)" claim — present verbatim in that file.
    • StoreKitBillingManagerTests.skipIfStoreKitConfigUnavailableViaCLI and the Xcode 26.5 CLI gap — present.
    • UserPreferencesPersistence.loadMiniPlayerAutoHideEnabled's as? Bool ?? true-shaped default — present, confirms the stated reason for not reusing that file for consent storage (wrong default polarity).
    • TTSEngineBridge.voice(for:) auto-detecting language rather than being user-selectable — present in DomainBridge.swift, supports the claim that there's no stale-voice-carryover risk to guard against on iOS the way Android's CloudVoicesSection does.
  • Ran the PR's actual CI (Build & Test iOS (Simulator), run 32653630464) to completion rather than trusting the PR body's "known limitation: no Xcode locally, verified by manual review" framing — it now shows pass (6m31s). Pulled the job log directly: all four new test suites ran and passed; the CloudApiKeyStoreTests real-Keychain cases skipped exactly as documented (errSecMissingEntitlement under this job's CODE_SIGNING_ALLOWED=NO), not silently passed or excluded. This is exactly the "confirm CI actually ran" bar the review persona sets, and the PR's own honesty about not having a local build made it worth the extra minutes to wait on.
  • Networking sign-off check: this PR's foundation includes a CloudTtsProvider protocol whose conformers will make real HTTP calls to five third-party vendors in a later PR. Checked for prior human sign-off per policy — found it: issue #449 ("Sign-off: Premium Cloud TTS Voices reverses 'no Pro tier' (#172) and narrows on #400's networking scope"), closed, explicit product-owner approval dated 2026-08-22 for exactly this: five named BYOK vendor endpoints, subscription-gated, plus a second independent consent toggle. This PR's CloudTtsGate (isSubscribed && consentEnabled) and CloudProviderId's closed 5-vendor enum match that sign-off's scope exactly. No actual network call ships in this PR (protocol only, no URLSession implementation) — consistent with "PR 1 of 4."
  • Sensitive-path / pipeline-bypass check: this PR was opened directly by libravault-xyz, not the pipeline bot, and never went through dev-agent/qa-agent — confirmed via the pr-intake.yml bot comment on the PR, which is the documented, deterministic backstop for exactly this case (issue #223/#343 precedent). Nothing in .github/agent-policy.yml's sensitive_paths or sensitive_issue_labels gates apply differently here since no autonomous dev-agent triage occurred — but worth flagging for the human merger: the originating issue #452 itself carries the security label, so this is exactly the kind of change that label exists to slow down, even though the fast-path here is a diff-size trigger rather than a security-content one.

Findings

No CONFIRMED-severity findings — nothing rising to the bar that requires a gh issue create per the persona's "documenting real findings" section.

Two PLAUSIBLE/minor notes for the human merger to weigh, neither blocking:

  1. CloudApiKeyStoreError.keychainError(status: 0) (KeychainCloudApiKeyStore.swift:346) reuses the keychainError case with a synthetic OSStatus of 0 for a JSONEncoder failure on [String: String] — 0 is errSecSuccess, so a caller pattern-matching on .keychainError(status:) and logging the raw status would see a nonsensical "success" status attached to a thrown error. The PR's own comment acknowledges this is meant to be practically unreachable (encoding a flat string dictionary essentially can't fail), so this is cosmetic, not a functional bug.
  2. AGENTS.md's "prove a new test can fail" rule (deliberately breaking each new assertion once, pre-commit, per the "Test conventions" section) isn't addressed in the PR body the way it is for, e.g., prior iOS Keychain-test PRs. Given the author had no local Xcode available this run, they couldn't have easily done this themselves before pushing; the tests here are simple enough (direct equality/boolean assertions, no mocking-that-could-silently-no-op) that the failure mode this rule guards against seems unlikely, but it's worth a human's second look rather than my asserting it's fine.

Everything else checked clean

  • CloudTtsGate is a pure function of two Bools with all 4 quadrants tested plus an explicit "subscription alone never opens the gate" regression test — correctly implements the PRD §4 requirement verified in #449.
  • CloudVoicePreferences defaults to consent-false-when-absent (verified via UserDefaults.bool(forKey:)'s documented absent-read behavior, and by the passing testLoadConsentEnabledDefaultsToFalseWhenNothingSaved test).
  • Keychain round-trip logic (JSON-encode a [String: String]-remapped dict rather than [CloudCredentialField: String] directly) is correct and matches genuine Codable/Dictionary behavior — a RawRepresentable-keyed dictionary without CodingKeyRepresentable conformance does not encode as a JSON object under JSONEncoder, so the remapping is a real fix, not defensive over-engineering.
  • Field-mismatch validation (Set(credentials.keys) == requiredFields) correctly rejects both missing and extra fields, with tests for both directions.
  • No new networking dependency actually lands in this PR despite the eventual scope; CloudTtsProvider is a protocol only.

@github-actions github-actions Bot added status:needs-human-merge Principal review done, requires human merge decision and removed status:needs-review QA passed, awaiting principal-review-agent labels Aug 23, 2026
@libravault-xyz
libravault-xyz merged commit 01b9a2f into dev Aug 23, 2026
16 checks passed
@libravault-xyz
libravault-xyz deleted the feature/cloudtts-ios-foundation branch August 23, 2026 17:20
libravault-xyz added a commit that referenced this pull request Aug 23, 2026
…476)

* feat(ios): core Cloud TTS foundation — Keychain store, consent, pure gate

PR 1 of 4 for iOS's half of Premium Cloud TTS Voices (BYOK), issue #452.
Mirrors Android's core:cloudtts foundation (#462), adapted where iOS's
own conventions genuinely differ rather than ported literally.

New Sources/Features/CloudTTS/:
- CloudProviderId — the PRD's closed 5-vendor list (§3).
- CloudCredentialFields — per-provider required-field sets (Amazon
  Polly's SigV4 needs 3 fields, Azure needs 2, the rest need 1 bearer
  key) — same reasoning as Android's identical Map<String,String>
  credential shape, kept in sync by hand.
- CloudApiKeyStore protocol + KeychainCloudApiKeyStore — one
  kSecClassGenericPassword item per provider, kSecAttrAccessibleWhen
  UnlockedThisDeviceOnly. Deliberately does NOT additionally wrap
  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 has no OS-level encryption-at-rest of its own; the
  Keychain already provides that here, and a BYOK vendor key isn't
  LibraVault's root of trust the way the vault master key is.
- CloudVoicePreferences — consent/selected-provider/selected-voice-id,
  mirrors SupporterStatusPersistence's shape (not bolted onto
  UserPreferencesPersistence, whose existing keys use the opposite
  "true by default" polarity).
- CloudTtsGate — pure function, not a class wrapping live
  StoreKitBillingManager/CloudVoicePreferences: StoreKitBillingManager
  needs a live SKTestSession to test for real (documented Xcode 26.5
  CLI gap), so the actual AND logic lives in a function of two Bools
  instead, letting CloudTtsGateTests cover all four quadrants with no
  StoreKit dependency at all.
- CloudTtsProvider protocol — shared shape for the 5 vendor adapters
  (next PR).

Tests: CloudTtsGateTests (4-quadrant + explicit "subscription alone
never opens the gate" regression guard), CloudVoicePreferencesTests,
CloudCredentialFieldsTests, CloudApiKeyStoreTests (real Keychain
round-trip — guarded with the same errSecMissingEntitlement XCTSkip
pattern SecureEnclaveHardwareKeyWrapTests already uses for this CI
job's CODE_SIGNING_ALLOWED=NO environment), FakeCloudApiKeyStore for
downstream test targets (engine/UI PRs).

No Xcode/macOS available in this environment — verified by careful
manual review against this codebase's existing conventions (matched
HardwareKeyWrap/SecureEnclaveHardwareKeyWrapFactory's Keychain query
style, SupporterStatusPersistence's UserDefaults shape, and the
skipIfKeychainKeyPersistenceUnavailable CI gotcha) rather than a local
build; real verification is this PR's CI run (ios-app-build.yml).

Closes nothing yet — first of 4 iOS PRs for #452.

* feat(ios): Cloud TTS vendor adapters — 5 vendors + AWS SigV4 signer

PR 2 of 4 for iOS's half of Premium Cloud TTS Voices (BYOK), progress
toward #452. Builds on the (as-yet-unmerged) foundation PR (#472).
Direct Swift port of Android's 5 vendor adapters (#465) + AwsSigV4Signer
(#467/#466) — same verified real API shapes, same algorithm, ported
rather than re-researched from scratch so both platforms stay provably
aligned.

New Sources/Features/CloudTTS/Vendors/:
- CloudTtsFixedHosts — the fixed, closed set of hosts (PRD §7); Azure/
  Polly pin the host *pattern* (region-scoped), not a literal.
- VendorTtsAdapter protocol + shared executeOrFail/localeFromVoiceID/
  jsonBody helpers. Deliberately NOT guarded by the isRunningUnderXCTest
  check TTSEngineBridge/PocketTTSEngine/StoreKitBillingManager use —
  that guard exists specifically for audio-hardware activation hangs
  in the CI Simulator, which a plain URLSession HTTP call has no
  dependency on; applying it here would also silently no-op every
  adapter test against MockURLProtocol. The engine PR's AVAudioPlayer-
  based playback is where that guard actually belongs, matching the
  precedent's real scope.
- ElevenLabsAdapter/OpenAIAdapter/GoogleCloudTtsAdapter/AzureSpeechAdapter/
  AmazonPollyAdapter — same per-vendor auth/body/host shapes as their
  Kotlin counterparts (xi-api-key header, bearer token, API-key query
  param + base64 JSON response, region-scoped SSML + Ocp-Apim key,
  SigV4).
- AwsSigV4Signer — direct port of the Kotlin signer, using CryptoKit
  (already a dependency here) instead of javax.crypto. Reuses the SAME
  known-answer test vectors already cross-checked against botocore for
  Android (#466), rather than re-deriving a second independent check —
  if both platforms' signers match the same pinned values, they're
  provably computing the same algorithm.
- RealCloudTtsProvider — dispatches to the right vendor adapter by
  CloudProviderId. No fdroid-equivalent NoOp needed (iOS has one
  distribution channel).

Testing: MockURLProtocol (hand-rolled URLProtocol mock — this repo has
no network-test dependency, matching the "no new deps" constraint) +
per-vendor test suites mirroring the Kotlin MockWebServer tests'
coverage (auth header/body shape, non-2xx fails closed, missing-
credential fails closed, path-traversal/XML-injection regression
guards for the two adapters with caller-controlled path/SSML content),
AwsSigV4SignerTests (structural + the reused known-answer vectors),
CloudTtsFixedHostsRegressionTests, RealCloudTtsProviderTests (dispatch
correctness via which real host each provider's request lands on).

No Xcode/macOS available in this environment — verified by careful
manual review and direct comparison against the already-reviewed,
already-merged Kotlin implementation, not a local build. Real
verification is this PR's own CI run.

Part of #452. Depends on #472 (not yet merged) — this branch merges
that branch's commits in directly so it builds/tests standalone;
retarget to dev once #472 merges.

* fix(cloudtts-ios): ElevenLabs voiceID path segment wasn't actually percent-encoded

Real CI failure, not caught locally (no Xcode available when this was
first written): URL.appendingPathComponent(_:) does NOT percent-encode
"/" in its argument the way Kotlin's addPathSegment (singular) does —
it treats "/" as a literal path separator (that's the whole point of
the method: appendingPathComponent("a/b/c") is the same as three
separate appends). A voiceID containing a slash was therefore NOT
percent-encoded as one opaque segment as the code's own comment
claimed — CI's testSlashInVoiceIDIsPercentEncodedNotSplitIntoExtra
PathSegments failed for real against
api.elevenlabs.io/v1/text-to-speech/abc/../admin, the exact path-
traversal shape that test exists to catch.

Fixed by percent-encoding voiceID myself first (CharacterSet
.urlPathAllowed minus "/", so "/" becomes "%2F") and assigning it via
URLComponents.percentEncodedPath, which stores/uses already-encoded
content as-is rather than re-interpreting it. No other adapter has
this bug: ElevenLabs is the only one that puts voiceID into a URL
path segment — the other four put it in a JSON body or XML-escaped
SSML, neither of which goes through appendingPathComponent.

Verified: this is exactly what the existing regression test already
asserted (abc%2F..%2Fadmin) — no test change needed, only the
production code was wrong.
libravault-xyz added a commit that referenced this pull request Aug 24, 2026
* feat(ios): core Cloud TTS foundation — Keychain store, consent, pure gate

PR 1 of 4 for iOS's half of Premium Cloud TTS Voices (BYOK), issue #452.
Mirrors Android's core:cloudtts foundation (#462), adapted where iOS's
own conventions genuinely differ rather than ported literally.

New Sources/Features/CloudTTS/:
- CloudProviderId — the PRD's closed 5-vendor list (§3).
- CloudCredentialFields — per-provider required-field sets (Amazon
  Polly's SigV4 needs 3 fields, Azure needs 2, the rest need 1 bearer
  key) — same reasoning as Android's identical Map<String,String>
  credential shape, kept in sync by hand.
- CloudApiKeyStore protocol + KeychainCloudApiKeyStore — one
  kSecClassGenericPassword item per provider, kSecAttrAccessibleWhen
  UnlockedThisDeviceOnly. Deliberately does NOT additionally wrap
  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 has no OS-level encryption-at-rest of its own; the
  Keychain already provides that here, and a BYOK vendor key isn't
  LibraVault's root of trust the way the vault master key is.
- CloudVoicePreferences — consent/selected-provider/selected-voice-id,
  mirrors SupporterStatusPersistence's shape (not bolted onto
  UserPreferencesPersistence, whose existing keys use the opposite
  "true by default" polarity).
- CloudTtsGate — pure function, not a class wrapping live
  StoreKitBillingManager/CloudVoicePreferences: StoreKitBillingManager
  needs a live SKTestSession to test for real (documented Xcode 26.5
  CLI gap), so the actual AND logic lives in a function of two Bools
  instead, letting CloudTtsGateTests cover all four quadrants with no
  StoreKit dependency at all.
- CloudTtsProvider protocol — shared shape for the 5 vendor adapters
  (next PR).

Tests: CloudTtsGateTests (4-quadrant + explicit "subscription alone
never opens the gate" regression guard), CloudVoicePreferencesTests,
CloudCredentialFieldsTests, CloudApiKeyStoreTests (real Keychain
round-trip — guarded with the same errSecMissingEntitlement XCTSkip
pattern SecureEnclaveHardwareKeyWrapTests already uses for this CI
job's CODE_SIGNING_ALLOWED=NO environment), FakeCloudApiKeyStore for
downstream test targets (engine/UI PRs).

No Xcode/macOS available in this environment — verified by careful
manual review against this codebase's existing conventions (matched
HardwareKeyWrap/SecureEnclaveHardwareKeyWrapFactory's Keychain query
style, SupporterStatusPersistence's UserDefaults shape, and the
skipIfKeychainKeyPersistenceUnavailable CI gotcha) rather than a local
build; real verification is this PR's CI run (ios-app-build.yml).

Closes nothing yet — first of 4 iOS PRs for #452.

* feat(ios): Cloud TTS vendor adapters — 5 vendors + AWS SigV4 signer

PR 2 of 4 for iOS's half of Premium Cloud TTS Voices (BYOK), progress
toward #452. Builds on the (as-yet-unmerged) foundation PR (#472).
Direct Swift port of Android's 5 vendor adapters (#465) + AwsSigV4Signer
(#467/#466) — same verified real API shapes, same algorithm, ported
rather than re-researched from scratch so both platforms stay provably
aligned.

New Sources/Features/CloudTTS/Vendors/:
- CloudTtsFixedHosts — the fixed, closed set of hosts (PRD §7); Azure/
  Polly pin the host *pattern* (region-scoped), not a literal.
- VendorTtsAdapter protocol + shared executeOrFail/localeFromVoiceID/
  jsonBody helpers. Deliberately NOT guarded by the isRunningUnderXCTest
  check TTSEngineBridge/PocketTTSEngine/StoreKitBillingManager use —
  that guard exists specifically for audio-hardware activation hangs
  in the CI Simulator, which a plain URLSession HTTP call has no
  dependency on; applying it here would also silently no-op every
  adapter test against MockURLProtocol. The engine PR's AVAudioPlayer-
  based playback is where that guard actually belongs, matching the
  precedent's real scope.
- ElevenLabsAdapter/OpenAIAdapter/GoogleCloudTtsAdapter/AzureSpeechAdapter/
  AmazonPollyAdapter — same per-vendor auth/body/host shapes as their
  Kotlin counterparts (xi-api-key header, bearer token, API-key query
  param + base64 JSON response, region-scoped SSML + Ocp-Apim key,
  SigV4).
- AwsSigV4Signer — direct port of the Kotlin signer, using CryptoKit
  (already a dependency here) instead of javax.crypto. Reuses the SAME
  known-answer test vectors already cross-checked against botocore for
  Android (#466), rather than re-deriving a second independent check —
  if both platforms' signers match the same pinned values, they're
  provably computing the same algorithm.
- RealCloudTtsProvider — dispatches to the right vendor adapter by
  CloudProviderId. No fdroid-equivalent NoOp needed (iOS has one
  distribution channel).

Testing: MockURLProtocol (hand-rolled URLProtocol mock — this repo has
no network-test dependency, matching the "no new deps" constraint) +
per-vendor test suites mirroring the Kotlin MockWebServer tests'
coverage (auth header/body shape, non-2xx fails closed, missing-
credential fails closed, path-traversal/XML-injection regression
guards for the two adapters with caller-controlled path/SSML content),
AwsSigV4SignerTests (structural + the reused known-answer vectors),
CloudTtsFixedHostsRegressionTests, RealCloudTtsProviderTests (dispatch
correctness via which real host each provider's request lands on).

No Xcode/macOS available in this environment — verified by careful
manual review and direct comparison against the already-reviewed,
already-merged Kotlin implementation, not a local build. Real
verification is this PR's own CI run.

Part of #452. Depends on #472 (not yet merged) — this branch merges
that branch's commits in directly so it builds/tests standalone;
retarget to dev once #472 merges.

* feat(ios): Cloud TTS engine wiring — makes Cloud TTS reachable

PR 3 of 4 for iOS's half of Premium Cloud TTS Voices (BYOK), progress
toward #452. Builds on the (as-yet-unmerged) vendors PR (#476). First
PR where CloudTtsEngine is actually reachable via TTSEngineType.cloud
— mirrors Android's engine-wiring PR (#468).

- TTSEngineType gains `.cloud`; LibravaultDomainBridge.switchTTSEngine
  (to:)'s ternary becomes a switch with a new .cloud branch.
- New configureCloudTts(billingManager:) on the bridge singleton — its
  only path to a live StoreKitBillingManager, called once from
  AppState.init before ttsEngineType's own didSet can ever request
  .cloud (ordering documented at both call sites).
- CloudTtsEngine (@mainactor, TTSEngineProtocol): re-checks
  CloudTtsGate on every speak() call, not just once at engine
  selection — subscribed+consent+configured-provider+voice-id all
  required, matching Android's engine. Falls back to the on-device
  engine (TTSEngineBridge) on gate-closed, not-configured, vendor
  failure, or playback failure — never a silent stall.
- Explicitly does NOT fall back on cancellation: catches both
  CancellationError (Task cancellation) AND URLError(.cancelled)
  (URLSession's own cancellation surfacing, a real Foundation nuance
  distinct from CancellationError) and returns without falling back —
  the Swift equivalent of Android's runCatchingCancellable fix.
  Covered by a dedicated regression test using a hangUntilCancelled
  fake provider, mirroring Android's SuspendingCloudTtsProvider/
  awaitCancellation() test.
- isSubscribedProvider is an injected @mainactor closure, not a direct
  StoreKitBillingManager dependency — keeps CloudTtsEngine's own unit
  tests fully StoreKit-free (only a thin wiring test would ever need
  real StoreKit, per the implementation plan's "Known gaps" section).
- CloudPlayback / AVAudioPlayerCloudPlayback: AVAudioPlayer-backed,
  always hints .mp3 (every vendor adapter explicitly requests MP3 —
  no per-format sniffing needed here, unlike VaultAudioPlaybackEngine's
  arbitrary-import case). Reuses that same file's already-proven-
  necessary "always pass an explicit fileTypeHint" fix (omitting it
  silently reports duration 0 instead of throwing — a real CI-caught
  bug there, not re-discovered here). Split into load()/play() the
  same way, so decode failures are testable without touching audio
  hardware. NSLock-guarded continuation resolution: stop() (main
  actor) and the AVAudioPlayerDelegate finish callback (AVAudioPlayer's
  own thread) can race to resolve the same continuation, which is a
  fatal double-resume, not just a logic bug — proactively applying the
  same fix Android's MediaPlayerCloudPlayback needed after review found
  the identical race there.

Testing: CloudTtsEngineTests (gate/config fallback paths, happy path,
vendor/playback failure fallback, the cancellation-doesn't-fall-back
regression test, pause/resume routing, initialize()) with fully
scripted fakes (FakeCloudTtsProvider/FakeCloudPlayback/FakeTTSEngine —
no real network/audio in any test); AVAudioPlayerCloudPlaybackTests
(load() decode-failure cases only, mirroring
VaultAudioPlaybackEngineTests' isRunningUnderXCTest-safe scope —
flagged explicitly: no "successfully decodes real MP3" test, since
hand-writing a valid MP3 fixture wasn't done here, unlike that file's
hand-written WAV).

No Xcode/macOS available in this environment — verified by careful
manual review, matching this codebase's established conventions
(VaultAudioPlaybackEngine's fileTypeHint/isRunningUnderXCTest split,
AppState's @MainActor-default-argument-initialization-order gotcha,
Android's runCatchingCancellable precedent). Real verification is this
PR's own CI run.

Part of #452. Depends on #476.

* fix(cloudtts-ios): ElevenLabs voiceID path segment wasn't actually percent-encoded

Real CI failure, not caught locally (no Xcode available when this was
first written): URL.appendingPathComponent(_:) does NOT percent-encode
"/" in its argument the way Kotlin's addPathSegment (singular) does —
it treats "/" as a literal path separator (that's the whole point of
the method: appendingPathComponent("a/b/c") is the same as three
separate appends). A voiceID containing a slash was therefore NOT
percent-encoded as one opaque segment as the code's own comment
claimed — CI's testSlashInVoiceIDIsPercentEncodedNotSplitIntoExtra
PathSegments failed for real against
api.elevenlabs.io/v1/text-to-speech/abc/../admin, the exact path-
traversal shape that test exists to catch.

Fixed by percent-encoding voiceID myself first (CharacterSet
.urlPathAllowed minus "/", so "/" becomes "%2F") and assigning it via
URLComponents.percentEncodedPath, which stores/uses already-encoded
content as-is rather than re-interpreting it. No other adapter has
this bug: ElevenLabs is the only one that puts voiceID into a URL
path segment — the other four put it in a JSON body or XML-escaped
SSML, neither of which goes through appendingPathComponent.

Verified: this is exactly what the existing regression test already
asserted (abc%2F..%2Fadmin) — no test change needed, only the
production code was wrong.

* fix(ios): resolve Task<Void, Never> type mismatch in CloudTtsEngine.speak()

self?.performSpeak(...) inside the weak-self Task closure inferred
Task<()?, Never> (optional chaining on an async call returning Void
still returns Void?), which doesn't match the declared
activeTask: Task<Void, Never>?. Unwrap self with guard let first so
the closure's return type is plain Void.

Fixes the Swift compile error blocking PR #478's CI (Build & Test iOS
(Simulator)).
github-actions Bot pushed a commit that referenced this pull request Aug 24, 2026
…re picker (#492)

Fixes #491, found while reviewing the current state of dev: PR #482
(a parallel, independently-authorized dev-agent run on issue #452 that
merged while this session's own from-scratch Settings UI PR for the
same scope was still in progress — genuine duplicate work, discarded
in favor of this small targeted fix instead of a competing rewrite)
implemented provider/key/voice-id configuration but never wired
activation: `CloudVoicesSection.swift` never referenced `ttsEngineType`
anywhere, and `ttsSection`'s segmented Picker listed `TTSEngineType
.allCases` unfiltered, making ".cloud" directly selectable there with
nothing configured — CloudTtsEngine's own gate would just silently
fall back to on-device every time, a confusing dead end disconnected
from the Cloud Voices section below it.

- `ttsSection`'s Picker now filters out `.cloud` — mirrors Android's
  `TtsSettingsSection` never listing CLOUD as a bare radio option.
  Footer copy fixed too (still claimed "no network access").
- New "Use Cloud Voices for Read Aloud" toggle inside `CloudVoicesSection`,
  shown once a provider is merely *selected* — not gated on already
  being configured, which is exactly the gating bug Android's own PR
  #470 hit and fixed (hiding it until configured leaves no discovery
  path at all). Disabled + explained until the selected provider
  actually has credentials saved and a non-blank voice id is set.
  Re-checks `CloudTtsGate.canUseCloudTts` before actually activating,
  not just relying on the toggle's own `.disabled` affordance.
  Disabling always reverts to `.system`, gate irrelevant.
- Extracted the enable/disable decision as a pure `static func
  canActivateCloudEngine`, matching this file's own established
  `isSaveEnabled`/`nextVoiceID` precedent for testability without
  ViewInspector/snapshot infrastructure (which this repo doesn't have).
- `#Preview` needed the two new `@EnvironmentObject`s added.

Testing: 6 new `CloudVoicesSectionTests` cases covering
`canActivateCloudEngine`'s every branch (no provider selected, wrong
provider configured, empty/whitespace voice id, the happy path). The
gate re-check itself already has full coverage via `CloudTtsGateTests`
(#472) — nothing new to test there.

No Xcode/macOS available in this environment — verified by careful
manual review against the actual merged file content on dev (`git
show origin/dev:...`, not a stale local assumption) and this file's
own established static-helper testing convention. Real verification is
this PR's own CI run.

Closes #491. Part of #452.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

risk:high Touches a sensitive path or exceeds diff-size threshold — always human merge status:needs-human-merge Principal review done, requires human merge decision

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant