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
6 changes: 6 additions & 0 deletions core/cloudtts/build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,12 @@ dependencies {
// CloudApiKeyStore.kt) — serialized to JSON before hardware-key wrapping.
implementation(libs.kotlinx.serialization.json)

// Vendor TTS HTTP adapters — play flavour only, scoped the same way
// billing-ktx is scoped in core:billing, so OkHttp never reaches the
// F-Droid runtime classpath.
"playImplementation"(libs.okhttp)

testImplementation(libs.bundles.testing.jvm)
testRuntimeOnly(libs.junit5.engine)
"testPlayImplementation"(libs.okhttp.mockwebserver3)
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
package xyz.libravault.core.cloudtts

import xyz.libravault.core.cloudtts.vendor.AmazonPollyAdapter
import xyz.libravault.core.cloudtts.vendor.AzureSpeechAdapter
import xyz.libravault.core.cloudtts.vendor.ElevenLabsAdapter
import xyz.libravault.core.cloudtts.vendor.GoogleCloudTtsAdapter
import xyz.libravault.core.cloudtts.vendor.OpenAiAdapter
import xyz.libravault.core.cloudtts.vendor.VendorTtsAdapter
import javax.inject.Inject
import javax.inject.Singleton

/**
* Fans out to one of the five vendor HTTP adapters by [CloudProviderId].
* F-Droid's counterpart is [NoOpCloudTtsProvider] — this class only exists
* in the `play` flavor's compilation.
*
* Not `internal`: this class's own primary constructor is `internal`
* (Hilt uses the public `@Inject` secondary one — same pattern as
* [xyz.libravault.core.cloudtts.RealCloudApiKeyStore]), but the class
* itself, [xyz.libravault.core.cloudtts.vendor.VendorTtsAdapter], and the
* five vendor adapter classes all need Kotlin-public visibility — a public
* class can't have a constructor exposing `internal` parameter types.
* Nothing outside this module references any of them directly regardless;
* only [CloudTtsProvider] (bound to this class in
* `di.CloudTtsPlayModule`) is the real public surface.
*/
@Singleton
class RealCloudTtsProvider @Inject constructor(
private val elevenLabsAdapter: ElevenLabsAdapter,
private val openAiAdapter: OpenAiAdapter,
private val googleCloudTtsAdapter: GoogleCloudTtsAdapter,
private val azureSpeechAdapter: AzureSpeechAdapter,
private val amazonPollyAdapter: AmazonPollyAdapter,
) : CloudTtsProvider {

override suspend fun synthesize(
provider: CloudProviderId,
text: String,
voiceId: String,
credentials: Map<String, String>,
): Result<ByteArray> = adapterFor(provider).synthesize(text, voiceId, credentials)

override suspend fun validateKey(provider: CloudProviderId, credentials: Map<String, String>): Result<Unit> =
adapterFor(provider).validateKey(credentials)

private fun adapterFor(provider: CloudProviderId): VendorTtsAdapter = when (provider) {
CloudProviderId.ELEVENLABS -> elevenLabsAdapter
CloudProviderId.OPENAI -> openAiAdapter
CloudProviderId.GOOGLE_CLOUD_TTS -> googleCloudTtsAdapter
CloudProviderId.AZURE_SPEECH -> azureSpeechAdapter
CloudProviderId.AMAZON_POLLY -> amazonPollyAdapter
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
package xyz.libravault.core.cloudtts.di

import dagger.Binds
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.components.SingletonComponent
import okhttp3.OkHttpClient
import xyz.libravault.core.cloudtts.CloudTtsProvider
import xyz.libravault.core.cloudtts.RealCloudTtsProvider
import java.util.concurrent.TimeUnit
import javax.inject.Singleton

@Module
@InstallIn(SingletonComponent::class)
abstract class CloudTtsPlayModule {

@Binds
@Singleton
abstract fun bindCloudTtsProvider(impl: RealCloudTtsProvider): CloudTtsProvider

companion object {
/** One shared client for all five vendor adapters — connection
* pooling, one place to tune timeouts. Synthesis calls can be slow
* (real vendor TTS latency), so a generous read timeout; connect/write
* stay short so a genuinely unreachable host fails fast instead of
* hanging the fallback-to-on-device path (engine-wiring follow-up). */
@Provides
@Singleton
fun provideOkHttpClient(): OkHttpClient = OkHttpClient.Builder()
.connectTimeout(10, TimeUnit.SECONDS)
.writeTimeout(10, TimeUnit.SECONDS)
.readTimeout(30, TimeUnit.SECONDS)
.build()
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
package xyz.libravault.core.cloudtts.vendor

import kotlinx.serialization.json.buildJsonObject
import kotlinx.serialization.json.put
import okhttp3.HttpUrl
import okhttp3.HttpUrl.Companion.toHttpUrl
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.RequestBody.Companion.toRequestBody
import xyz.libravault.core.cloudtts.CloudCredentialFields
import javax.inject.Inject

/**
* Amazon Polly text-to-speech — verified against AWS's SynthesizeSpeech API
* docs. The one vendor here that isn't a bearer-token REST call: AWS
* Signature Version 4 (SigV4), region-specific host
* (`polly.{region}.amazonaws.com`), JSON body. See [AwsSigV4Signer]'s class
* doc for the residual-verification caveat on the signing implementation
* itself.
*/
class AmazonPollyAdapter internal constructor(
private val httpClient: OkHttpClient,
private val testBaseUrl: HttpUrl? = null,
) : VendorTtsAdapter {

@Inject constructor(httpClient: OkHttpClient) : this(httpClient, testBaseUrl = null)

private fun baseUrl(region: String): HttpUrl =
testBaseUrl ?: "https://${CloudTtsFixedHosts.pollyHost(region)}".toHttpUrl()

override suspend fun synthesize(text: String, voiceId: String, credentials: Map<String, String>): Result<ByteArray> =
runCatching {
val accessKeyId = credentials.field(CloudCredentialFields.ACCESS_KEY_ID)
val secretAccessKey = credentials.field(CloudCredentialFields.SECRET_ACCESS_KEY)
val region = credentials.field(CloudCredentialFields.REGION)

val payload = buildJsonObject {
put("Text", text)
put("VoiceId", voiceId)
put("OutputFormat", "mp3")
put("Engine", "neural")
}.toString()

val url = baseUrl(region).newBuilder().addPathSegments("v1/speech").build()
val signed = AwsSigV4Signer.sign(
method = "POST",
host = url.host,
canonicalUri = "/v1/speech",
payload = payload,
region = region,
accessKeyId = accessKeyId,
secretAccessKey = secretAccessKey,
extraSignedHeaders = mapOf("content-type" to "application/json"),
)
val request = Request.Builder()
.url(url)
.addHeader("Content-Type", "application/json")
.addHeader("X-Amz-Date", signed.amzDate)
.addHeader("Authorization", signed.authorizationHeader)
.post(payload.toRequestBody("application/json".toMediaType()))
.build()

httpClient.executeOrFail(request, "Amazon Polly").use { response ->
response.body?.bytes() ?: error("Amazon Polly returned an empty body")
}
}

override suspend fun validateKey(credentials: Map<String, String>): Result<Unit> = runCatching {
val accessKeyId = credentials.field(CloudCredentialFields.ACCESS_KEY_ID)
val secretAccessKey = credentials.field(CloudCredentialFields.SECRET_ACCESS_KEY)
val region = credentials.field(CloudCredentialFields.REGION)

val url = baseUrl(region).newBuilder().addPathSegments("v1/voices").build()
val signed = AwsSigV4Signer.sign(
method = "GET",
host = url.host,
canonicalUri = "/v1/voices",
payload = "",
region = region,
accessKeyId = accessKeyId,
secretAccessKey = secretAccessKey,
)
val request = Request.Builder()
.url(url)
.addHeader("X-Amz-Date", signed.amzDate)
.addHeader("Authorization", signed.authorizationHeader)
.get()
.build()

httpClient.executeOrFail(request, "Amazon Polly key validation").close()
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,118 @@
package xyz.libravault.core.cloudtts.vendor

import java.security.MessageDigest
import java.time.Instant
import java.time.ZoneOffset
import java.time.format.DateTimeFormatter
import javax.crypto.Mac
import javax.crypto.spec.SecretKeySpec

/**
* AWS Signature Version 4 request signing, for Amazon Polly (the one vendor
* here whose real API isn't a bearer-token REST call — verified against
* AWS's own SigV4 documentation, not assumed). Deliberately scoped to
* exactly what this module's two Polly calls (`POST /v1/speech`,
* `GET /v1/voices`) need — a small, focused signer, not a general-purpose
* AWS SDK reimplementation.
*
* RESIDUAL RISK, called out explicitly rather than papered over: this was
* implemented directly from AWS's published algorithm
* (https://docs.aws.amazon.com/general/latest/gr/sigv4-calculate-signature.html)
* and covered by structural/differential unit tests (correct format,
* deterministic for a fixed input, sensitive to every input changing), but
* has NOT been verified against a real AWS request/response or an official
* AWS test-vector fixture — no trustworthy verbatim copy of one was
* available in this environment. Tracked as a required manual/live
* verification step before Polly support ships to users — see the filed
* follow-up issue referenced from the vendor-adapters PR description.
*/
internal object AwsSigV4Signer {

private const val ALGORITHM = "AWS4-HMAC-SHA256"
private val AMZ_DATE_FORMAT = DateTimeFormatter.ofPattern("yyyyMMdd'T'HHmmss'Z'").withZone(ZoneOffset.UTC)
private val DATE_STAMP_FORMAT = DateTimeFormatter.ofPattern("yyyyMMdd").withZone(ZoneOffset.UTC)

data class SignedRequest(
val amzDate: String,
val authorizationHeader: String,
)

/**
* @param canonicalUri absolute path, e.g. "/v1/speech" — must already be
* URI-encoded per AWS's rules (none of this module's paths need
* encoding, so that step is deliberately not implemented here).
* @param extraSignedHeaders additional headers (beyond `host`) to
* include in both the canonical request and the actual outgoing
* request — lowercase names, e.g. "content-type" to "application/json".
* Must be exactly the set of non-host, non-x-amz-date headers the
* caller will actually send.
*/
fun sign(
method: String,
host: String,
canonicalUri: String,
payload: String,
region: String,
accessKeyId: String,
secretAccessKey: String,
extraSignedHeaders: Map<String, String> = emptyMap(),
now: Instant = Instant.now(),
): SignedRequest {
val amzDate = AMZ_DATE_FORMAT.format(now)
val dateStamp = DATE_STAMP_FORMAT.format(now)

val allHeaders = (extraSignedHeaders + mapOf("host" to host, "x-amz-date" to amzDate))
.toSortedMap()
val canonicalHeaders = allHeaders.entries.joinToString("") { (name, value) -> "${name}:${value.trim()}\n" }
val signedHeaders = allHeaders.keys.joinToString(";")
val hashedPayload = sha256Hex(payload)

val canonicalRequest = listOf(
method,
canonicalUri,
"", // no query string for either call this module makes
canonicalHeaders,
signedHeaders,
hashedPayload,
).joinToString("\n")

val credentialScope = "$dateStamp/$region/polly/aws4_request"
val stringToSign = listOf(
ALGORITHM,
amzDate,
credentialScope,
sha256Hex(canonicalRequest),
).joinToString("\n")

val signingKey = deriveSigningKey(secretAccessKey, dateStamp, region, "polly")
val signature = hmacSha256Hex(signingKey, stringToSign)

val authorizationHeader = "$ALGORITHM " +
"Credential=$accessKeyId/$credentialScope, " +
"SignedHeaders=$signedHeaders, " +
"Signature=$signature"

return SignedRequest(amzDate = amzDate, authorizationHeader = authorizationHeader)
}

private fun deriveSigningKey(secretAccessKey: String, dateStamp: String, region: String, service: String): ByteArray {
val kSecret = "AWS4$secretAccessKey".toByteArray(Charsets.UTF_8)
val kDate = hmacSha256(kSecret, dateStamp)
val kRegion = hmacSha256(kDate, region)
val kService = hmacSha256(kRegion, service)
return hmacSha256(kService, "aws4_request")
}

private fun hmacSha256(key: ByteArray, data: String): ByteArray {
val mac = Mac.getInstance("HmacSHA256")
mac.init(SecretKeySpec(key, "HmacSHA256"))
return mac.doFinal(data.toByteArray(Charsets.UTF_8))
}

private fun hmacSha256Hex(key: ByteArray, data: String): String = hmacSha256(key, data).toHex()

private fun sha256Hex(data: String): String =
MessageDigest.getInstance("SHA-256").digest(data.toByteArray(Charsets.UTF_8)).toHex()

private fun ByteArray.toHex(): String = joinToString("") { "%02x".format(it) }
}
Loading
Loading