Modern Apps git

← Modern-Apps.git

uniflix: make platform backup restore the SQLCipher DB safely

Commit
dec505c084789cb15c738e2133b053f626dc3640
Author
Vayun Mathur <[email protected]>
When
2026-12-04 21:52 UTC (1 day ago)
Parents
09a686f
Uniflix carried its raw SQLCipher database in platform backup
rules. That file cannot survive a device change: its passphrase
is wrapped by the old device's non-exportable AndroidKeyStore
key in secure_prefs, so a restored copy cannot be opened and
the app would fail on first launch instead of starting clean.

The database is real user data, not cache - watchlist,
continue-watching positions, user lists, title notes and
installed addons including JS plugin source - so excluding it
outright would lose the library on every device migration.
Follow the weather pattern instead:

- Declare platform/AppBackupAgent in the manifest. It extends
  BaseBackupAgent with SqlCipherDbCodec, so the DB is exported
  to plaintext inside the backup payload and re-encrypted
  under the new device's key on restore, and it carries the
  uniflix_addons DataStore (default addon id) as a plain file.
  Add UNIFLIX_DB_NAME and uniflixDbConfigs() in data/, shared
  by the repository and the agent.
- Exclude uniflix-db plus its -wal/-shm/-journal sidecars and
  secure_prefs.xml from both cloud-backup and device-transfer
  in data_extraction_rules.xml, with the audit and scope
  documented in the file. Everything else backs up as before.

Host verification is the strongest available without a device:
AppBackupAgentTest pins the agent wiring and codec, parses
the compiled extraction rules for the excludes in both
sections, checks the manifest backup agent, exercises a full
BackupHelper backup/restore round-trip with a fake codec,
and asserts the SqlCipherDbCodec pre-native contract for
uniflix-db (missing export writes nothing, failed import
leaves the live DB untouched). The native sqlcipher_export
round-trip itself is device-provable only and is not claimed
here.

Verified: ./gradlew :uniflix:lint :uniflix:lintVitalRelease
:uniflix:testDevUnitTest (219 tests, 0 failures).

Diff

uniflix/AGENTS.md
diff --git a/uniflix/AGENTS.md b/uniflix/AGENTS.mdindex fa64b32cad..95cde30179 100644--- a/uniflix/AGENTS.md+++ b/uniflix/AGENTS.md@@ -27,6 +27,7 @@ Watch/Detail link to the addon manager. - URL addons enforce HTTPS except loopback/private (dev); remote `http://` is rejected as `InsecureUrl` - `UniflixDatabase` is v3, with `Migration(1,2)` adding `AddonEntity` and `Migration(2,3)` adding `kind`/`jsSource`; default addon id lives in DataStore, ordering in Room priority - Private `personal/uniflix_strem/` keeps the native Strem provider + hardcoded TMDB key — never copy those into `uniflix/`+- Backup: `platform/AppBackupAgent` (declared in the manifest) carries the DB via `SqlCipherDbCodec` (plaintext in the payload, re-encrypted on restore) + the `uniflix_addons` DataStore; the raw `uniflix-db` file and `secure_prefs.xml` are excluded in `data_extraction_rules.xml` — the wrapped passphrase is device-bound, so a raw restored DB cannot be opened  ## Key files ### Root — entry + navigation@@ -51,6 +52,7 @@ Watch/Detail link to the addon manager. ### platform/ — ViewModels - com/vayunmathur/uniflix/platform/DetailViewModel.kt — registry injection + RegistryFactory - com/vayunmathur/uniflix/platform/AddonsViewModel.kt — manager state+- com/vayunmathur/uniflix/platform/AppBackupAgent.kt — platform backup via SqlCipherDbCodec + uniflix_addons DataStore ### ui/ — catalog + manager - com/vayunmathur/uniflix/ui/AddonsScreen.kt — manager list host (pushes `Route.AddAddonDialog`) - com/vayunmathur/uniflix/ui/AddonDetailScreen.kt — per-addon settings host
uniflix/src/main/AndroidManifest.xml
diff --git a/uniflix/src/main/AndroidManifest.xml b/uniflix/src/main/AndroidManifest.xmlindex 6433c321b9..7021af92e9 100644--- a/uniflix/src/main/AndroidManifest.xml+++ b/uniflix/src/main/AndroidManifest.xml@@ -21,6 +21,7 @@      <application         android:allowBackup="true"+        android:backupAgent=".platform.AppBackupAgent"         android:banner="@drawable/tv_banner"         android:dataExtractionRules="@xml/data_extraction_rules"         android:icon="@mipmap/ic_launcher"
uniflix/src/main/java/com/vayunmathur/uniflix/data/UniflixDatabase.kt
diff --git a/uniflix/src/main/java/com/vayunmathur/uniflix/data/UniflixDatabase.kt b/uniflix/src/main/java/com/vayunmathur/uniflix/data/UniflixDatabase.ktindex c6f722ec30..ef59fbe9e5 100644--- a/uniflix/src/main/java/com/vayunmathur/uniflix/data/UniflixDatabase.kt+++ b/uniflix/src/main/java/com/vayunmathur/uniflix/data/UniflixDatabase.kt@@ -12,6 +12,8 @@ import androidx.room3.Upsert import androidx.room3.migration.Migration import androidx.sqlite.SQLiteConnection import androidx.sqlite.execSQL+import android.content.Context+import com.vayunmathur.library.util.DatabaseHelper import com.vayunmathur.library.util.DefaultConverters import kotlinx.coroutines.flow.Flow @@ -135,6 +137,13 @@ interface UserListDao {     suspend fun deleteNote(value: TitleNote) } +/** On-device database file name for the Uniflix Room database. */+const val UNIFLIX_DB_NAME = "uniflix-db"++/** Backup config shared by [com.vayunmathur.uniflix.platform.AppBackupAgent]. */+fun uniflixDbConfigs(context: Context): List<Pair<String, String>> =+    listOf(UNIFLIX_DB_NAME to DatabaseHelper(context).getPassphrase())+ /** Local-only watch state: watchlist, resume positions, lists, notes. No server sync. */ @ColumnTypeConverters(DefaultConverters::class) @Database(
uniflix/src/main/java/com/vayunmathur/uniflix/data/UniflixRepository.kt
diff --git a/uniflix/src/main/java/com/vayunmathur/uniflix/data/UniflixRepository.kt b/uniflix/src/main/java/com/vayunmathur/uniflix/data/UniflixRepository.ktindex 60d91a7adc..751297a3fa 100644--- a/uniflix/src/main/java/com/vayunmathur/uniflix/data/UniflixRepository.kt+++ b/uniflix/src/main/java/com/vayunmathur/uniflix/data/UniflixRepository.kt@@ -14,7 +14,7 @@ class UniflixRepository private constructor(context: Context) :     RoomRepository<UniflixDatabase>(         context,         UniflixDatabase::class,-        "uniflix-db",+        UNIFLIX_DB_NAME,         migrations = UniflixDatabase.migrations,     ) { 
uniflix/src/main/java/com/vayunmathur/uniflix/platform/AppBackupAgent.kt
diff --git a/uniflix/src/main/java/com/vayunmathur/uniflix/platform/AppBackupAgent.kt b/uniflix/src/main/java/com/vayunmathur/uniflix/platform/AppBackupAgent.ktnew file mode 100644index 0000000000..22473ce201--- /dev/null+++ b/uniflix/src/main/java/com/vayunmathur/uniflix/platform/AppBackupAgent.kt@@ -0,0 +1,29 @@+package com.vayunmathur.uniflix.platform++import com.vayunmathur.library.room.SqlCipherDbCodec+import com.vayunmathur.library.util.BaseBackupAgent+import com.vayunmathur.uniflix.data.uniflixDbConfigs++/**+ * Backup agent for Uniflix user data.+ *+ * The Room database holds real user data — watchlist, continue-watching+ * positions, user lists, title notes and installed addons (including JS+ * plugin source) — so it must survive a device change, but its raw+ * SQLCipher file cannot: its passphrase is wrapped by the old device's+ * non-exportable AndroidKeyStore key. [SqlCipherDbCodec] exports the DB+ * to plaintext inside the backup payload and re-encrypts it under the new+ * device's key on restore. The `uniflix_addons` DataStore (default addon+ * id) rides along as a plain file. `secure_prefs` is deliberately not+ * listed: it holds only the wrapped passphrase, which is useless and+ * device-bound on any other device.+ */+class AppBackupAgent : BaseBackupAgent() {+    override val dbCodec = SqlCipherDbCodec++    override val dbConfigs: List<Pair<String, String>>+        get() = uniflixDbConfigs(this)++    override val datastoreNames: List<String>+        get() = listOf("uniflix_addons")+}
uniflix/src/main/res/xml/data_extraction_rules.xml
diff --git a/uniflix/src/main/res/xml/data_extraction_rules.xml b/uniflix/src/main/res/xml/data_extraction_rules.xmlindex 81a97e0f26..49891c9943 100644--- a/uniflix/src/main/res/xml/data_extraction_rules.xml+++ b/uniflix/src/main/res/xml/data_extraction_rules.xml@@ -1,17 +1,56 @@ <?xml version="1.0" encoding="utf-8"?>+<!--+  Uniflix. Audited state:+    * databases/uniflix-db — Room DB holding real user data: watchlist,+      continue-watching positions, user lists, title notes and installed+      addons (including JS plugin source). Not regenerable cache.+    * secure_prefs.xml — SQLCipher passphrase wrapped by a non-exportable+      AndroidKeyStore key.+    * files/datastore/uniflix_addons.preferences_pb — default addon id.++  The raw uniflix-db file is excluded from both sections: it is+  SQLCipher-encrypted under a passphrase wrapped by a key that never leaves+  the old device, so a restored copy cannot be opened and would crash on+  first launch instead of starting clean. secure_prefs.xml is excluded+  for the same reason — it is only that wrapped passphrase.++  The user data still migrates: Uniflix declares its own BackupAgent+  (platform/AppBackupAgent), which uses SqlCipherDbCodec to export the DB+  to plaintext inside the backup payload and re-encrypt it under the new+  device's key on restore, plus the uniflix_addons DataStore file. That+  path is the one that works; the raw file copy would only get in its way.++  SCOPE: Uniflix declares android:backupAgent=".platform.AppBackupAgent"+  and does NOT set android:fullBackupOnly, so Android uses key/value+  backup here and the <cloud-backup> section below is NOT consulted.+  Cloud content is exactly AppBackupAgent's uniflixDbConfigs(this) plus+  the uniflix_addons DataStore. The rules below govern <device-transfer>,+  and are the correct control if the backupAgent is ever removed.+--> <data-extraction-rules>+    <!-- Not consulted while android:backupAgent is declared; see SCOPE above. -->     <cloud-backup>         <include domain="root" path="." />         <include domain="file" path="." />         <include domain="database" path="." />+        <exclude domain="database" path="uniflix-db" />+        <exclude domain="database" path="uniflix-db-wal" />+        <exclude domain="database" path="uniflix-db-shm" />+        <exclude domain="database" path="uniflix-db-journal" />         <include domain="sharedpref" path="." />+        <exclude domain="sharedpref" path="secure_prefs.xml" />         <include domain="external" path="." />     </cloud-backup>     <device-transfer>         <include domain="root" path="." />         <include domain="file" path="." />         <include domain="database" path="." />+        <exclude domain="database" path="uniflix-db" />+        <exclude domain="database" path="uniflix-db-wal" />+        <exclude domain="database" path="uniflix-db-shm" />+        <exclude domain="database" path="uniflix-db-journal" />         <include domain="sharedpref" path="." />+        <exclude domain="sharedpref" path="secure_prefs.xml" />         <include domain="external" path="." />     </device-transfer> </data-extraction-rules>
uniflix/src/test/java/com/vayunmathur/uniflix/platform/AppBackupAgentTest.kt
diff --git a/uniflix/src/test/java/com/vayunmathur/uniflix/platform/AppBackupAgentTest.kt b/uniflix/src/test/java/com/vayunmathur/uniflix/platform/AppBackupAgentTest.ktnew file mode 100644index 0000000000..40432d4849--- /dev/null+++ b/uniflix/src/test/java/com/vayunmathur/uniflix/platform/AppBackupAgentTest.kt@@ -0,0 +1,159 @@+package com.vayunmathur.uniflix.platform++import android.content.Context+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.library.room.SqlCipherDbCodec+import com.vayunmathur.library.util.BackupHelper+import com.vayunmathur.library.util.DbBackupCodec+import com.vayunmathur.uniflix.data.UNIFLIX_DB_NAME+import java.io.ByteArrayInputStream+import java.io.ByteArrayOutputStream+import java.io.File+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertNotNull+import kotlin.test.assertSame+import kotlin.test.assertTrue+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.xmlpull.v1.XmlPullParser++/**+ * Host-strongest backup tests for Uniflix. The SQLCipher native library+ * cannot load on a host JVM, so the actual `sqlcipher_export` round-trip+ * is device-provable only; here we prove everything around it: the agent+ * wiring, the extraction rules that keep the raw encrypted DB and the+ * wrapped passphrase out of platform backup, the pre-native codec+ * contract for `uniflix-db`, and a full BackupHelper backup/restore+ * round-trip with a fake codec standing in for the native export.+ */+@RunWith(RobolectricTestRunner::class)+class AppBackupAgentTest {++    private val ctx: Context get() = ApplicationProvider.getApplicationContext()++    /** Copies the live DB bytes verbatim, standing in for the native export. */+    private object FakeCodec : DbBackupCodec {+        override fun exportDatabase(context: Context, dbName: String, password: String, outputFile: File) {+            val src = context.getDatabasePath(dbName)+            if (!src.exists()) return+            outputFile.parentFile?.mkdirs()+            src.copyTo(outputFile, overwrite = true)+        }++        override fun importDatabase(context: Context, dbName: String, password: String, inputFile: File) {+            val dst = context.getDatabasePath(dbName)+            dst.parentFile?.mkdirs()+            inputFile.copyTo(dst, overwrite = true)+        }+    }++    @Test fun agentWiringUsesSqlCipherCodecAndUniflixStores() {+        val agent = AppBackupAgent()+        assertSame(SqlCipherDbCodec, agent.dbCodec)+        assertEquals(listOf("uniflix_addons"), agent.datastoreNames)+        assertTrue(agent.prefNames.isEmpty(), "secure_prefs must not be restored on a new device")+        assertTrue(agent.extraFiles.isEmpty())+        // dbConfigs is not read here: resolving it needs the AndroidKeyStore+        // passphrase, which Robolectric cannot provide. Its name is pinned+        // by UNIFLIX_DB_NAME below and by uniflixDbConfigs in data/.+        assertEquals("uniflix-db", UNIFLIX_DB_NAME)+    }++    @Test fun manifestDeclaresBackupAgent() {+        val info = ctx.packageManager.getApplicationInfo(ctx.packageName, 0)+        assertEquals(+            "com.vayunmathur.uniflix.platform.AppBackupAgent",+            info.backupAgentName,+        )+        assertTrue(ctx.resources.getIdentifier("data_extraction_rules", "xml", ctx.packageName) != 0)+    }++    @Test fun extractionRulesExcludeRawDbAndSecurePrefsInBothSections() {+        val resId = ctx.resources.getIdentifier("data_extraction_rules", "xml", ctx.packageName)+        assertTrue(resId != 0)+        val parser = ctx.resources.getXml(resId)+        val excludes = mutableListOf<Triple<String, String, String>>()+        var section = ""+        var event = parser.eventType+        while (event != XmlPullParser.END_DOCUMENT) {+            if (event == XmlPullParser.START_TAG) {+                when (parser.name) {+                    "cloud-backup", "device-transfer" -> section = parser.name+                    "exclude" -> excludes += Triple(+                        section,+                        parser.getAttributeValue(null, "domain") ?: "",+                        parser.getAttributeValue(null, "path") ?: "",+                    )+                }+            }+            event = parser.next()+        }+        for (sec in listOf("cloud-backup", "device-transfer")) {+            assertTrue(Triple(sec, "database", "uniflix-db") in excludes, "$sec must exclude uniflix-db")+            assertTrue(Triple(sec, "database", "uniflix-db-wal") in excludes, "$sec must exclude wal")+            assertTrue(Triple(sec, "database", "uniflix-db-shm") in excludes, "$sec must exclude shm")+            assertTrue(Triple(sec, "database", "uniflix-db-journal") in excludes, "$sec must exclude journal")+            assertTrue(+                Triple(sec, "sharedpref", "secure_prefs.xml") in excludes,+                "$sec must exclude secure_prefs.xml",+            )+        }+    }++    @Test fun backupHelperRoundTripsDbAndDatastoreWithFakeCodec() {+        val dbFile = ctx.getDatabasePath(UNIFLIX_DB_NAME)+        dbFile.parentFile?.mkdirs()+        dbFile.writeBytes(byteArrayOf(1, 2, 3, 4))+        val dsFile = File(ctx.filesDir, "datastore/uniflix_addons.preferences_pb")+        dsFile.parentFile?.mkdirs()+        dsFile.writeBytes(byteArrayOf(9, 8, 7))++        val out = ByteArrayOutputStream()+        BackupHelper.performFullBackup(+            ctx, listOf(UNIFLIX_DB_NAME to "pw"), listOf("uniflix_addons"),+            emptyList(), emptyList(), out, FakeCodec,+        )+        assertTrue(out.size() > 0)++        dbFile.delete(); dsFile.delete()+        assertFalse(dbFile.exists()); assertFalse(dsFile.exists())++        BackupHelper.performFullRestore(+            ctx, listOf(UNIFLIX_DB_NAME to "pw"), listOf("uniflix_addons"),+            emptyList(), emptyMap(), ByteArrayInputStream(out.toByteArray()), FakeCodec,+        )+        assertTrue(byteArrayOf(1, 2, 3, 4).contentEquals(dbFile.readBytes()))+        assertTrue(byteArrayOf(9, 8, 7).contentEquals(dsFile.readBytes()))+        dbFile.delete(); dsFile.delete()+    }++    @Test fun sqlCipherCodecPreNativeContractForUniflixDb() {+        // Exporting a missing DB writes nothing (returns before native load).+        val output = File(ctx.cacheDir, "uniflix-export-missing.db")+        if (output.exists()) output.delete()+        SqlCipherDbCodec.exportDatabase(ctx, UNIFLIX_DB_NAME, "pw", output)+        assertFalse(output.exists())++        // A failed import (native unavailable on host; corrupt on device)+        // must leave the live DB and sidecars byte-for-byte untouched.+        val dbFile = ctx.getDatabasePath(UNIFLIX_DB_NAME)+        dbFile.parentFile?.mkdirs()+        dbFile.writeBytes(byteArrayOf(1))+        val wal = File("${dbFile.path}-wal").apply { writeBytes(byteArrayOf(2)) }+        val input = File(ctx.cacheDir, "uniflix-import-plain.db")+        input.writeBytes(ByteArray(32) { 5 })+        try {+            runCatching { SqlCipherDbCodec.importDatabase(ctx, UNIFLIX_DB_NAME, "pw", input) }+            assertTrue(byteArrayOf(1).contentEquals(dbFile.readBytes()))+            assertTrue(byteArrayOf(2).contentEquals(wal.readBytes()))+            val leftovers = dbFile.parentFile?.listFiles()+                ?.filter { it.name.contains(".import-") || it.name.contains(".bak-") }.orEmpty()+            assertTrue(leftovers.isEmpty(), "leftover swap files: $leftovers")+            assertNotNull(dbFile)+        } finally {+            dbFile.delete(); wal.delete(); input.delete()+        }+    }+}