Modern Apps git

← Modern-Apps.git

new metadata generation method

Commit
4d640fc7654ac7e22a28a65a4bdbdfec7ea59284
Author
Vayun Mathur <[email protected]>
When
2026-08-01 19:56 UTC (4 months ago)
Parents
db0c859

Diff

.gitignore
diff --git a/.gitignore b/.gitignoreindex 1ab0f4b2aa..c858c3aff4 100644--- a/.gitignore+++ b/.gitignore@@ -43,3 +43,16 @@ target/  # Small100 quantized binaries > 100MB — do not commit, fetch via quantize_small100.sh or R2 scripts/translate/quantized/++# Nutrition database asset — large binary, regenerate with scripts/generate_food_db.py+health/src/main/assets/food.bin+health/src/main/assets/food.bin.br+health/src/main/assets/food.bin.meta.json+health/src/main/assets/staging.db++# Compose preview screenshot rendering (common-conventions-preview-metadata). These PNGs+# are an intermediate: the `metadata` task copies them into metadata_data/photos/<module>,+# which is what is committed and what release.sh reads. Committing them too would store+# every listing image twice. Remove this ignore if you ever want+# `validate<Variant>ScreenshotTest` to act as UI regression testing.+**/src/screenshotTest*/reference/
SUPPLY_CHAIN_RISKS.md
diff --git a/SUPPLY_CHAIN_RISKS.md b/SUPPLY_CHAIN_RISKS.mdindex 2c9f1cd69f..4596c4331b 100644--- a/SUPPLY_CHAIN_RISKS.md+++ b/SUPPLY_CHAIN_RISKS.md@@ -4,7 +4,7 @@ This document enumerates critical external dependencies for the Modern-Apps mono  ## Assumptions -- **Self-hosted infrastructure is assumed indefinite**: `api.vayunmathur.com`, `data.vayunmathur.com`, `findfamily.cc` and any subdomains are excluded from the risk list. These services host self-owned data (e.g. the `health` food/nutrition DB behind `/api/food`, the `openassistant`/`photos` ML models permanently hosted at `data.vayunmathur.com/models`, map pmtiles/zone downloads on `data.vayunmathur.com`, E2EE relays) and proxy a few third-party secrets (Duffel, Google Places/Ratings) to keep F-Droid builds reproducible. Only the *transitive third-party* upstreams (Duffel, Google Maps Platform) are listed — the proxy/DB itself is not a supply-chain risk.+- **Self-hosted infrastructure is assumed indefinite**: `api.vayunmathur.com`, `data.vayunmathur.com`, `findfamily.cc` and any subdomains are excluded from the risk list. These services host self-owned data (e.g. the `openassistant`/`photos` ML models permanently hosted at `data.vayunmathur.com/models`, map pmtiles/zone downloads on `data.vayunmathur.com`, E2EE relays) and proxy a few third-party secrets (Duffel, Google Places/Ratings) to keep F-Droid builds reproducible. Only the *transitive third-party* upstreams (Duffel, Google Maps Platform) are listed — the proxy/DB itself is not a supply-chain risk. - Offline apps require only Maven Central / Google Maven at build time.  ---@@ -42,9 +42,9 @@ These servers provide data/functionality that is NOT intrinsically tied to a sin | `youpipe` extras | **SponsorBlock / DeArrow (community)** — data APIs now self-hosted | Segment + branding data served from `https://api.vayunmathur.com/api/skipSegments` and `/api/branding` (a local mirror of the SponsorBlock DB, no runtime call to ajay.app). DeArrow now self-hosted renderer `GET /api/dearrow/thumbnail?videoID=&time=` (`handlers/dearrow.rs`, own yt-dlp + ffmpeg impl inspired by `ajayyy/DeArrowThumbnailCache`) | Crowdsourced, best-effort extras, not core YouTube | Sponsor skips + DeArrow titles/branding + thumbnail frames now continue from local even if ajay.app is down | ✅ **Fully self-hosted** — SponsorBlock DB mirrored into `sponsorblock.db` (`sb_build.sh` rsyncs public dumps; served by `handlers/sponsorblock.rs`). DeArrow thumbnail proxy + render at `/api/dearrow/thumbnail` (`dearrow.rs`), clients rewired in `Extractor.kt:167` `DEARROW_THUMB_MIRROR` and `Wikidata.kt:10` `BASE_URL`. Wikidata proxy `GET /api/wikidata/items/:id` (`wikidata.rs`) — 73 server tests green | | `maps` / `travel` / `photos` / `weather` | **MapLibre rendering + Wikidata enrichment** | `org.maplibre.compose:maplibre-compose:0.13.0` → `libmaplibre.so`, self-hosted Wikidata `https://api.vayunmathur.com/api/wikidata/items/{id}` (`Wikidata.kt:10`) | Map renderer is FOSS community project (vs Mapbox), Wikidata is enrichment only (now also proxied/self-cached at `wikidata_cache/`) | Map rendering would need fork/mirror if MapLibre artifacts gone; Wikidata fail is graceful null | Vendor MapLibre AAR, or switch to OpenGL self-render; Wikidata proxy keeps attribution | -`health` food search hits `api.vayunmathur.com/api/food` — a **self-hosted nutrition DB** (not a third-party proxy), so it is excluded from the risk list per Assumptions.+`health` **no longer requests `android.permission.INTERNET` at all** — it is the first app here with no network access whatsoever. Its nutrition database ships inside the APK as a brotli-compressed columnar asset (`scripts/generate_food_db.py` → `health/src/main/assets/food.bin.br`, 10.9 MB for 465,000 products), which `FoodDatabase.kt` turns into a SQLite/FTS5 database on first launch. Upstream is the **Open Food Facts** daily CSV export (ODbL v1.0, attributed in-app) — a build-host dependency, not a runtime one: if it vanished the shipped database keeps working and only stops being refreshable. The older `/api/food/search` and `/api/food/data/:id` endpoints remain up for previously-shipped builds. -Notably **offline after first launch**: `astronomy`, `calendar`, `clock`, `contacts` (only `libphonenumber` locally), `files`, `notes` (Room + Ink), `things`, `camera` (on-device `tasks-vision:0.10.14` BlazeFace), `pdf` (Rust `libpdf_render.so`), `music` (Media3 ExoPlayer + local scan), `games/*`, `passwords` (biometric + KeePass), `library/*`, `health` core.+Notably **offline after first launch**: `astronomy`, `calendar`, `clock`, `contacts` (only `libphonenumber` locally), `files`, `notes` (Room + Ink), `things`, `camera` (on-device `tasks-vision:0.10.14` BlazeFace), `pdf` (Rust `libpdf_render.so`), `music` (Media3 ExoPlayer + local scan), `games/*`, `passwords` (biometric + KeePass), `library/*`, `health` (including food search, which ships its database in the APK).  --- 
appstore/build.gradle.kts
diff --git a/appstore/build.gradle.kts b/appstore/build.gradle.ktsindex fc179f3492..66e6369880 100644--- a/appstore/build.gradle.kts+++ b/appstore/build.gradle.kts@@ -1,6 +1,8 @@ plugins {     id("common-conventions-app")-    id("common-conventions-metadata")+    // Listing screenshots come from Compose previews (src/screenshotTest), not from an+    // instrumented test on a device. Same `:appstore:metadata` task name either way.+    id("common-conventions-preview-metadata")     alias(libs.plugins.ksp) } @@ -22,6 +24,10 @@ dependencies {     implementation(libs.androidx.datastore.preferences)     implementation(project(":library:image"))     implementation(libs.jsoup)+    // APK source-stamp verification. The stamp is a second signing identity that+    // survives Play App Signing re-signing, so it can be pinned per package where the+    // APK signing key (held by Google) cannot be.+    implementation(libs.apksig)     // HttpURLConnection-based PlayHttpClient/AnonymousAuthRepository/PlayDownloader – no okhttp     implementation(libs.kotlinx.serialization.json)     implementation(libs.auroraoss.gplayapi)
appstore/src/main/AndroidManifest.xml
diff --git a/appstore/src/main/AndroidManifest.xml b/appstore/src/main/AndroidManifest.xmlindex 355fcb1ecb..6a51c6ed23 100644--- a/appstore/src/main/AndroidManifest.xml+++ b/appstore/src/main/AndroidManifest.xml@@ -40,13 +40,25 @@                 <action android:name="android.intent.action.MAIN" />                 <category android:name="android.intent.category.LAUNCHER" />             </intent-filter>+            <!-- market:// links are ours to claim outright. The https ones are path-scoped:+                 handleIntentUrl only knows how to turn an app-listing URL into a package+                 name, so claiming the whole host would put this app in the chooser for+                 every unrelated play.google.com / f-droid.org link and then drop the user+                 on an empty screen. -->             <intent-filter>                 <action android:name="android.intent.action.VIEW" />                 <category android:name="android.intent.category.DEFAULT" />                 <category android:name="android.intent.category.BROWSABLE" />                 <data android:scheme="market" />-                <data android:scheme="https" android:host="play.google.com" />-                <data android:scheme="https" android:host="f-droid.org" />+            </intent-filter>+            <intent-filter>+                <action android:name="android.intent.action.VIEW" />+                <category android:name="android.intent.category.DEFAULT" />+                <category android:name="android.intent.category.BROWSABLE" />+                <data android:scheme="https" android:host="play.google.com" android:pathPrefix="/store/apps/details" />+                <data android:scheme="https" android:host="f-droid.org" android:pathPrefix="/packages/" />+                <!-- f-droid.org also serves localised listing URLs (/en/packages/...). -->+                <data android:scheme="https" android:host="f-droid.org" android:pathPattern="/.*/packages/.*" />             </intent-filter>         </activity> 
appstore/src/main/java/com/vayunmathur/appstore/MainActivity.kt
diff --git a/appstore/src/main/java/com/vayunmathur/appstore/MainActivity.kt b/appstore/src/main/java/com/vayunmathur/appstore/MainActivity.ktindex 539299654f..8e4e4afdd0 100644--- a/appstore/src/main/java/com/vayunmathur/appstore/MainActivity.kt+++ b/appstore/src/main/java/com/vayunmathur/appstore/MainActivity.kt@@ -14,6 +14,7 @@ import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier+import androidx.compose.ui.res.stringResource import androidx.lifecycle.lifecycleScope import androidx.lifecycle.viewmodel.compose.viewModel import com.vayunmathur.appstore.data.AppDatabase@@ -25,6 +26,8 @@ import com.vayunmathur.appstore.ui.ReposPage import com.vayunmathur.appstore.ui.UpdatesPage import com.vayunmathur.appstore.util.AppStoreViewModel import com.vayunmathur.appstore.util.AppStoreViewModelFactory+import com.vayunmathur.library.network.NetworkClient+import com.vayunmathur.library.network.TrustBundle import com.vayunmathur.library.room.buildDatabase import com.vayunmathur.library.ui.DynamicTheme import com.vayunmathur.library.ui.IconDownload@@ -50,6 +53,9 @@ class MainActivity : ComponentActivity() {      override fun onCreate(savedInstanceState: Bundle?) {         super.onCreate(savedInstanceState)+        // STANDARD includes GTS R1-R4 (needed for Play Store -> play.google.com / android.clients.google.com)+        // + ISRG X1/X2 (F-Droid) + DigiCert G2/G3 (GitHub). Covers all appstore hosts without full system ~140 roots.+        NetworkClient.init(this, TrustBundle.STANDARD)         enableEdgeToEdge()          lifecycleScope.launch(Dispatchers.IO) {@@ -128,6 +134,7 @@ sealed interface Route : NavKey {     @Serializable data object Updates : Route     @Serializable data object Repos : Route     @Serializable data object Detail : Route+    @Serializable data object SecurityTiers : Route }  @Composable@@ -149,14 +156,14 @@ private fun AppRoot(     MainNavigation(         backStack,         bottomBar = {-            if (current !is Route.Detail) {+            if (current !is Route.Detail && current !is Route.SecurityTiers) {                 BottomNavBar(                     backStack,                     listOf(-                        BottomBarItem("Browse", Route.Browse) { IconHome() },-                        BottomBarItem("Installed", Route.Installed) { IconPackage() },-                        BottomBarItem("Updates", Route.Updates) { IconDownload() },-                        BottomBarItem("Repos", Route.Repos) { IconSettings() },+                        BottomBarItem(stringResource(R.string.nav_browse), Route.Browse) { IconHome() },+                        BottomBarItem(stringResource(R.string.nav_installed), Route.Installed) { IconPackage() },+                        BottomBarItem(stringResource(R.string.nav_updates), Route.Updates) { IconDownload() },+                        BottomBarItem(stringResource(R.string.nav_sources), Route.Repos) { IconSettings() },                     ),                     current                 )@@ -182,10 +189,20 @@ private fun AppRoot(             })         }         entry<Route.Repos> {-            ReposPage(viewModel = viewModel)+            ReposPage(viewModel = viewModel, onOpenTiers = { backStack.add(Route.SecurityTiers) })         }         entry<Route.Detail> {-            AppDetailPage(viewModel = viewModel, onBack = { backStack.pop() })+            AppDetailPage(+                viewModel = viewModel,+                onBack = { backStack.pop() },+                onOpenTiers = { backStack.add(Route.SecurityTiers) },+            )+        }+        entry<Route.SecurityTiers> {+            com.vayunmathur.appstore.ui.SecurityTiersPage(+                ownSigningCertificates = viewModel.ownSigningCertificates,+                onBack = { backStack.pop() },+            )         }     } }
appstore/src/main/java/com/vayunmathur/appstore/data/AppDatabase.kt
diff --git a/appstore/src/main/java/com/vayunmathur/appstore/data/AppDatabase.kt b/appstore/src/main/java/com/vayunmathur/appstore/data/AppDatabase.ktindex 4c1fcdf3ed..62292b179c 100644--- a/appstore/src/main/java/com/vayunmathur/appstore/data/AppDatabase.kt+++ b/appstore/src/main/java/com/vayunmathur/appstore/data/AppDatabase.kt@@ -19,6 +19,7 @@ data class RepoEntity(     @PrimaryKey val url: String,     val name: String,     val enabled: Boolean = true,+    /** SHA-256 of the certificate the repo's index JAR must be signed with. */     val fingerprint: String? = null,     val lastSync: Long = 0L )@@ -26,7 +27,7 @@ data class RepoEntity( @Entity data class CachedAppEntity(     @PrimaryKey val packageName: String,-    val source: String, // FDROID, PLAYSTORE+    val source: String, // MODERN_APPS, FDROID, PLAYSTORE     val name: String,     val summary: String,     val description: String,@@ -39,9 +40,90 @@ data class CachedAppEntity(     val apkUrl: String?,     val targetSdk: Int?,     val repoUrl: String?,-    val lastUpdated: Long+    val lastUpdated: Long,+    /** Comma-joined SHA-256 signing-certificate fingerprints from an authenticated index. */+    val expectedSigners: String? = null,+    /** SHA-256 of the APK itself, from an authenticated index. */+    val apkSha256: String? = null,+    val license: String? = null,+    val website: String? = null,+    val sourceCode: String? = null+)++fun UnifiedApp.toEntity(): CachedAppEntity = CachedAppEntity(+    packageName = packageName,+    source = source.name,+    name = name,+    summary = summary,+    description = description,+    iconUrl = iconUrl,+    author = author,+    categories = categories.joinToString(","),+    versionName = versionName,+    versionCode = versionCode,+    sizeBytes = sizeBytes,+    apkUrl = apkUrl,+    targetSdk = targetSdk,+    repoUrl = repoUrl?.removeSuffix("/") ?: DefaultRepos.FDROID_MAIN,+    lastUpdated = lastUpdated,+    expectedSigners = expectedSigners.joinToString(",").ifBlank { null },+    apkSha256 = apkSha256,+    license = license,+    website = website,+    sourceCode = sourceCode,+)++fun CachedAppEntity.toUnifiedApp(): UnifiedApp = UnifiedApp(+    packageName = packageName,+    source = try { AppSource.valueOf(source) } catch (_: Exception) { AppSource.FDROID },+    name = name,+    summary = summary,+    description = description,+    iconUrl = iconUrl,+    author = author,+    categories = categories.split(",").filter { it.isNotBlank() },+    versionName = versionName,+    versionCode = versionCode,+    sizeBytes = sizeBytes,+    apkUrl = apkUrl,+    targetSdk = targetSdk,+    repoUrl = repoUrl,+    lastUpdated = lastUpdated,+    expectedSigners = expectedSigners?.split(",")?.filter { it.isNotBlank() } ?: emptyList(),+    apkSha256 = apkSha256,+    license = license,+    website = website,+    sourceCode = sourceCode,+)++/**+ * Trust-on-first-use pin of a package's APK source-stamp certificate.+ *+ * Only meaningful for Play, where the APK signing key belongs to Google and so cannot+ * identify the publisher. The stamp survives Play's re-signing, so pinning it detects a+ * change of publisher identity across updates. See+ * [com.vayunmathur.appstore.data.security.SourceStamp] for what this does and does not+ * prove.+ */+@Entity+data class PinnedStampEntity(+    @PrimaryKey val packageName: String,+    val stampSha256: String,+    val firstSeen: Long, ) +@Dao+interface PinnedStampDao {+    @Query("SELECT * FROM PinnedStampEntity WHERE packageName = :pkg LIMIT 1")+    suspend fun byPackage(pkg: String): PinnedStampEntity?++    @Upsert+    suspend fun upsert(pin: PinnedStampEntity)++    @Query("DELETE FROM PinnedStampEntity WHERE packageName = :pkg")+    suspend fun deleteByPackage(pkg: String)+}+ @Dao interface RepoDao {     @Query("SELECT * FROM RepoEntity ORDER BY name ASC")@@ -68,9 +150,19 @@ interface CachedAppDao {     @Query("SELECT * FROM CachedAppEntity WHERE packageName LIKE '%' || :q || '%' OR name LIKE '%' || :q || '%' ORDER BY name ASC")     fun searchFlow(q: String): Flow<List<CachedAppEntity>> +    @Query("SELECT * FROM CachedAppEntity")+    suspend fun all(): List<CachedAppEntity>+     @Query("SELECT * FROM CachedAppEntity WHERE packageName = :pkg LIMIT 1")     suspend fun byPackage(pkg: String): CachedAppEntity? +    @Query(+        "SELECT * FROM CachedAppEntity WHERE source = :source AND (" ++            "packageName LIKE '%' || :q || '%' OR name LIKE '%' || :q || '%' " ++            "OR summary LIKE '%' || :q || '%') ORDER BY name ASC LIMIT 40"+    )+    suspend fun search(source: String, q: String): List<CachedAppEntity>+     @Upsert     suspend fun upsertAll(apps: List<CachedAppEntity>) @@ -85,13 +177,14 @@ interface CachedAppDao { }  @Database(-    entities = [RepoEntity::class, CachedAppEntity::class],-    version = 3,+    entities = [RepoEntity::class, CachedAppEntity::class, PinnedStampEntity::class],+    version = 4,     exportSchema = false ) abstract class AppDatabase : RoomDatabase() {     abstract fun repoDao(): RepoDao     abstract fun cachedAppDao(): CachedAppDao+    abstract fun pinnedStampDao(): PinnedStampDao      companion object {         val migrations = listOf(@@ -104,6 +197,26 @@ abstract class AppDatabase : RoomDatabase() {                 override fun migrate(db: SupportSQLiteDatabase) {                     db.execSQL("ALTER TABLE CachedAppEntity ADD COLUMN targetSdk INTEGER")                 }+            },+            object : Migration(3, 4) {+                override fun migrate(db: SupportSQLiteDatabase) {+                    db.execSQL("ALTER TABLE CachedAppEntity ADD COLUMN expectedSigners TEXT")+                    db.execSQL("ALTER TABLE CachedAppEntity ADD COLUMN apkSha256 TEXT")+                    db.execSQL("ALTER TABLE CachedAppEntity ADD COLUMN license TEXT")+                    db.execSQL("ALTER TABLE CachedAppEntity ADD COLUMN website TEXT")+                    db.execSQL("ALTER TABLE CachedAppEntity ADD COLUMN sourceCode TEXT")+                    // Rows cached before this version carry no signer or hash, and the+                    // reproducible-only filter had not run yet. Drop them so nothing+                    // unverifiable survives the upgrade; the next sync repopulates.+                    db.execSQL("DELETE FROM CachedAppEntity")+                    db.execSQL("DELETE FROM RepoEntity")+                    db.execSQL(+                        "CREATE TABLE IF NOT EXISTS PinnedStampEntity (" ++                            "packageName TEXT NOT NULL PRIMARY KEY, " ++                            "stampSha256 TEXT NOT NULL, " ++                            "firstSeen INTEGER NOT NULL)"+                    )+                }             }         )     }
appstore/src/main/java/com/vayunmathur/appstore/data/AppModels.kt
diff --git a/appstore/src/main/java/com/vayunmathur/appstore/data/AppModels.kt b/appstore/src/main/java/com/vayunmathur/appstore/data/AppModels.ktindex 4310b3e7ac..c52a54a31e 100644--- a/appstore/src/main/java/com/vayunmathur/appstore/data/AppModels.kt+++ b/appstore/src/main/java/com/vayunmathur/appstore/data/AppModels.kt@@ -1,6 +1,8 @@ package com.vayunmathur.appstore.data  enum class AppSource {+    /** This monorepo's own GitHub releases, signed with the same key as this app. */+    MODERN_APPS,     FDROID,     PLAYSTORE }@@ -30,7 +32,15 @@ data class UnifiedApp(     val offerType: Int = 0,     val rating: Float? = null,     val containsSplit: Boolean = false,-    val isFree: Boolean = true+    val isFree: Boolean = true,+    /**+     * Lowercase-hex SHA-256 fingerprints of the certificates the publisher says this+     * APK is signed with, from a source we authenticated (a JAR-signed F-Droid index).+     * Empty when the source can't tell us — notably Play, where Google holds the key.+     */+    val expectedSigners: List<String> = emptyList(),+    /** Lowercase-hex SHA-256 of the APK itself, when the source publishes one. */+    val apkSha256: String? = null, )  data class InstalledInfo(@@ -41,8 +51,37 @@ data class InstalledInfo(     val enabled: Boolean = true ) +/**+ * The one and only F-Droid repository this store will talk to.+ *+ * Third-party F-Droid-format repos (IzzyOnDroid and friends) are deliberately not+ * supported and cannot be added: they republish binaries built by the upstream developer+ * rather than building from source, so an app from one carries the developer's release+ * pipeline *and* the mirror operator in its trusted set, with no published source to+ * check the binary against. The f-droid.org archive is excluded for a different reason —+ * it exists to serve superseded versions, which is the opposite of what we want.+ */ object DefaultRepos {     const val FDROID_MAIN = "https://f-droid.org/repo"-    const val FDROID_ARCHIVE = "https://f-droid.org/archive"-    const val IZVYZID = "https://apt.izzysoft.de/fdroid/repo"+}++/** The Modern-Apps monorepo's own GitHub release channel. */+object ModernAppsRepo {+    const val OWNER_REPO = "vayun-mathur/Modern-Apps"+    const val PROJECT_URL = "https://github.com/$OWNER_REPO"+    const val LATEST_RELEASE_API = "https://api.github.com/repos/$OWNER_REPO/releases/latest"++    /** Asset published by `release.sh` alongside the APKs; see [ModernAppsProvider]. */+    const val INDEX_ASSET = "index.json"++    /** File listing for a tag, used to recover package names on pre-index releases. */+    fun treeApi(tag: String) =+        "https://api.github.com/repos/$OWNER_REPO/git/trees/$tag?recursive=1"++    /** Two lines: versionCode, versionName. Injected into every module by `release.sh`. */+    fun versionTxt(tag: String) =+        "https://raw.githubusercontent.com/$OWNER_REPO/$tag/version.txt"++    /** Pseudo repo URL, used as the `repoUrl` key for cached rows. */+    const val REPO_KEY = PROJECT_URL }
appstore/src/main/java/com/vayunmathur/appstore/data/FDroidAppProvider.kt
diff --git a/appstore/src/main/java/com/vayunmathur/appstore/data/FDroidAppProvider.kt b/appstore/src/main/java/com/vayunmathur/appstore/data/FDroidAppProvider.ktindex 274bf78066..178ac873f4 100644--- a/appstore/src/main/java/com/vayunmathur/appstore/data/FDroidAppProvider.kt+++ b/appstore/src/main/java/com/vayunmathur/appstore/data/FDroidAppProvider.kt@@ -4,6 +4,19 @@ import android.content.Context import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext +/**+ * F-Droid, restricted twice over:+ *+ * 1. **One repository only** — [DefaultRepos.FDROID_MAIN], with its index signing+ *    certificate hard-pinned. Third-party F-Droid-format repos are not supported and+ *    cannot be added, because they ship binaries the upstream developer built.+ * 2. **Reproduced builds only** — a version is offered only if F-Droid's verification+ *    server independently rebuilt it and got identical bytes (see [ReproducibleBuilds]).+ *+ * Both gates fail closed: if the signed index or the verification feed can't be+ * fetched and checked, the sync throws and the previous catalogue is left untouched+ * rather than being replaced with unverified entries.+ */ class FDroidAppProvider(     private val db: AppDatabase,     private val appContext: Context@@ -14,36 +27,32 @@ class FDroidAppProvider(      @Volatile var cachedPackageNames: Set<String> = emptySet() +    /** Number of packages dropped by the reproducibility gate on the last sync. */+    @Volatile var lastFilteredOut: Int = 0+        private set+     override suspend fun fetchAll(): List<UnifiedApp> = withContext(Dispatchers.IO) {-        val repos = db.repoDao().all().filter { it.enabled }-        val all = mutableListOf<UnifiedApp>()-        for (repo in repos) {-            try { all += FDroidRepository.fetchRepoIndex(appContext, repo.url) } catch (_: Exception) { }-        }-        val filtered = AppProvider.filterTargetSdk(all).distinctBy { it.packageName }-        cachedPackageNames = filtered.map { it.packageName }.toSet()-        filtered+        val result = fetchVerifiedIndex()+        cachedPackageNames = result.apps.map { it.packageName }.toSet()+        result.apps     }      override suspend fun search(query: String): List<UnifiedApp> = withContext(Dispatchers.IO) {         if (query.isBlank()) return@withContext emptyList()-        val q = query.lowercase()-        val live = mutableListOf<UnifiedApp>()-        for (url in listOf(DefaultRepos.FDROID_MAIN, DefaultRepos.IZVYZID)) {-            try {-                live += FDroidRepository.fetchRepoIndex(appContext, url).filter {-                    it.name.lowercase().contains(q) || it.packageName.lowercase().contains(q) || it.summary.lowercase().contains(q)-                }-            } catch (_: Exception) {}-        }-        AppProvider.filterTargetSdk(live).take(40)+        // Search the synced cache; re-downloading a 54 MB index per keystroke is not an option.+        try {+            db.cachedAppDao().search(AppSource.FDROID.name, query).map { it.toUnifiedApp() }+        } catch (_: Exception) { emptyList() }     }      override suspend fun isPresent(packageName: String): Boolean = withContext(Dispatchers.IO) {         if (cachedPackageNames.contains(packageName)) return@withContext true         try {             val entity = db.cachedAppDao().byPackage(packageName) ?: return@withContext false-            if (entity.targetSdk != null && entity.targetSdk < AppProvider.MIN_TARGET_SDK) return@withContext false+            if (entity.source != AppSource.FDROID.name) return@withContext false+            if (entity.targetSdk != null && entity.targetSdk < AppProvider.MIN_TARGET_SDK) {+                return@withContext false+            }             true         } catch (_: Exception) { false }     }@@ -51,62 +60,52 @@ class FDroidAppProvider(     override suspend fun getDetails(packageName: String): UnifiedApp? = withContext(Dispatchers.IO) {         try {             val entity = db.cachedAppDao().byPackage(packageName) ?: return@withContext null-            if (entity.targetSdk != null && entity.targetSdk < AppProvider.MIN_TARGET_SDK) return@withContext null+            if (entity.source != AppSource.FDROID.name) return@withContext null+            if (entity.targetSdk != null && entity.targetSdk < AppProvider.MIN_TARGET_SDK) {+                return@withContext null+            }             entity.toUnifiedApp()         } catch (_: Exception) { null }     } -    suspend fun syncIntoDb(context: Context? = null): Int = withContext(Dispatchers.IO) {-        val ctx = context ?: appContext-        val repos = db.repoDao().all().filter { it.enabled }-        var total = 0-        for (repo in repos) {-            try {-                val apps = FDroidRepository.fetchRepoIndex(ctx, repo.url)-                val filtered = AppProvider.filterTargetSdk(apps)-                val entities = filtered.map { it.toEntity() }-                db.cachedAppDao().deleteByRepo(repo.url.trimEnd('/'))-                db.cachedAppDao().upsertAll(entities)-                db.repoDao().upsert(repo.copy(lastSync = System.currentTimeMillis()))-                total += entities.size-            } catch (_: Exception) { }-        }-        total+    /**+     * Refresh from f-droid.org and replace this source's rows. Throws if either the index+     * signature or the reproducibility feed can't be obtained — the caller surfaces that+     * instead of silently serving a stale or unverified catalogue.+     */+    suspend fun syncIntoDb(): Int = withContext(Dispatchers.IO) {+        val result = fetchVerifiedIndex()+        val repo = db.repoDao().all().find { it.url == DefaultRepos.FDROID_MAIN }+        db.cachedAppDao().deleteByRepo(DefaultRepos.FDROID_MAIN)+        db.cachedAppDao().upsertAll(result.apps.map { it.toEntity() })+        db.repoDao().upsert(+            (repo ?: RepoEntity(DefaultRepos.FDROID_MAIN, "F-Droid", true)).copy(+                fingerprint = result.signerSha256,+                lastSync = System.currentTimeMillis(),+            )+        )+        cachedPackageNames = result.apps.map { it.packageName }.toSet()+        result.apps.size     } -    private fun UnifiedApp.toEntity(): CachedAppEntity = CachedAppEntity(-        packageName = packageName,-        source = source.name,-        name = name,-        summary = summary,-        description = description,-        iconUrl = iconUrl,-        author = author,-        categories = categories.joinToString(","),-        versionName = versionName,-        versionCode = versionCode,-        sizeBytes = sizeBytes,-        apkUrl = apkUrl,-        targetSdk = targetSdk,-        repoUrl = repoUrl?.removeSuffix("/") ?: DefaultRepos.FDROID_MAIN,-        lastUpdated = lastUpdated-    )--    private fun CachedAppEntity.toUnifiedApp(): UnifiedApp = UnifiedApp(-        packageName = packageName,-        source = try { AppSource.valueOf(source) } catch (_: Exception) { AppSource.FDROID },-        name = name,-        summary = summary,-        description = description,-        iconUrl = iconUrl,-        author = author,-        categories = categories.split(",").filter { it.isNotBlank() },-        versionName = versionName,-        versionCode = versionCode,-        sizeBytes = sizeBytes,-        apkUrl = apkUrl,-        targetSdk = targetSdk,-        repoUrl = repoUrl,-        lastUpdated = lastUpdated-    )+    private suspend fun fetchVerifiedIndex(): FDroidRepository.IndexResult {+        // Fetch the reproducibility verdicts first: no verdicts means no catalogue, and+        // there is no point pulling 54 MB of index we would then throw away.+        val verified = ReproducibleBuilds.fetch(appContext)+        if (verified.size == 0) {+            throw java.io.IOException("F-Droid verification feed listed no reproduced builds")+        }+        var rejected = 0+        val result = FDroidRepository.fetchRepoIndex(+            context = appContext,+            repoUrl = DefaultRepos.FDROID_MAIN,+            pinnedFingerprint = FDroidRepository.FDROID_SIGNING_CERT_SHA256,+        ) { pkg, versionCode ->+            val ok = verified.contains(pkg, versionCode)+            if (!ok) rejected+++            ok+        }+        lastFilteredOut = rejected+        return result+    } }
appstore/src/main/java/com/vayunmathur/appstore/data/FDroidRepository.kt
diff --git a/appstore/src/main/java/com/vayunmathur/appstore/data/FDroidRepository.kt b/appstore/src/main/java/com/vayunmathur/appstore/data/FDroidRepository.ktindex 10fe01b8d0..829878eb78 100644--- a/appstore/src/main/java/com/vayunmathur/appstore/data/FDroidRepository.kt+++ b/appstore/src/main/java/com/vayunmathur/appstore/data/FDroidRepository.kt@@ -3,62 +3,128 @@ package com.vayunmathur.appstore.data import android.content.Context import android.util.JsonReader import android.util.JsonToken+import com.vayunmathur.appstore.data.security.ApkCertificates+import com.vayunmathur.appstore.data.security.SignedJarIndex import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext+import org.json.JSONObject import java.io.File import java.net.HttpURLConnection import java.net.URL  /**- * Fixed F-Droid repo client — avoids OOM on 99MB index-v2.json.- * Downloads to file first (buffered), then streaming-parses with android.util.JsonReader- * so we never hold the full String + JsonObject tree in memory.+ * F-Droid repo client. Avoids OOM on the ~100MB index by downloading to a file and+ * streaming-parsing with android.util.JsonReader rather than holding a whole object tree.  * Filters targetSdk < AppProvider.MIN_TARGET_SDK.+ *+ * **The index is always taken from the repo's signed JAR** (`entry.jar` for index-v2,+ * `index-v1.jar` for the legacy format) and the signing certificate is pinned per repo.+ * The plain `index-v2.json` endpoint is deliberately *not* used as a fallback: without a+ * signature the per-APK `sha256` and `signer` values this parser extracts would be+ * attacker-controlled, and pinning them would be security theatre.  */ object FDroidRepository { -    suspend fun fetchRepoIndex(context: Context, repoUrl: String): List<UnifiedApp> = withContext(Dispatchers.IO) {+    /**+     * SHA-256 of the certificate f-droid.org signs its index with (CN=Ciaran Gultnieks).+     * Hard-pinned rather than trust-on-first-use because there is exactly one supported+     * repository, so there is no reason to ever accept an unknown key for it.+     */+    const val FDROID_SIGNING_CERT_SHA256 =+        "43238d512c1e5eb2d6569f4a3afbf5523418b82e0a3ed1552770abb9a9c9ccab"++    /** Parsed index plus the repo signing certificate it was authenticated with. */+    data class IndexResult(val apps: List<UnifiedApp>, val signerSha256: String)++    /**+     * Fetch and verify [repoUrl]'s index.+     *+     * [pinnedFingerprint] null means trust-on-first-use, and the caller must persist+     * [IndexResult.signerSha256]. [acceptVersion] decides which versions of a package may+     * be offered at all — the newest *accepted* version wins, so a package whose latest+     * build has not yet been reproduced falls back to its newest reproduced one rather+     * than disappearing.+     */+    suspend fun fetchRepoIndex(+        context: Context,+        repoUrl: String,+        pinnedFingerprint: String?,+        acceptVersion: (packageName: String, versionCode: Long) -> Boolean,+    ): IndexResult = withContext(Dispatchers.IO) {         val base = repoUrl.trimEnd('/')-        val cacheFile = File(context.cacheDir, "fdroid_${base.hashCode()}_index.json")-        val candidates = listOf("$base/index-v2.json", "$base/index-v1.json")-        var lastErr: Exception? = null-        for (url in candidates) {+        val work = File(context.cacheDir, "fdroid-index/${base.hashCode()}").apply { mkdirs() }+        try {+            val errors = mutableListOf<String>()+            try {+                return@withContext fetchV2(base, pinnedFingerprint, work, acceptVersion)+            } catch (e: Exception) {+                errors += "index-v2: ${e.message}"+            }             try {-                downloadToFile(url, cacheFile)-                val apps = if (url.endsWith("v2.json")) parseV2Streaming(cacheFile, base) else parseV1Streaming(cacheFile, base)-                val filtered = AppProvider.filterTargetSdk(apps)-                cacheFile.delete()-                return@withContext filtered+                return@withContext fetchV1(base, pinnedFingerprint, work, acceptVersion)             } catch (e: Exception) {-                lastErr = e+                errors += "index-v1: ${e.message}"             }+            throw java.io.IOException("Could not load a signed index from $base (${errors.joinToString("; ")})")+        } finally {+            work.deleteRecursively()         }-        cacheFile.delete()-        throw lastErr ?: RuntimeException("Failed to fetch $repoUrl")     } -    suspend fun fetchRepoIndex(repoUrl: String): List<UnifiedApp> = withContext(Dispatchers.IO) {-        val base = repoUrl.trimEnd('/')-        val temp = File.createTempFile("fdroid_index_", ".json")-        try {-            val candidates = listOf("$base/index-v2.json", "$base/index-v1.json")-            var lastErr: Exception? = null-            for (url in candidates) {-                try {-                    downloadToFile(url, temp)-                    val apps = if (url.endsWith("v2.json")) parseV2Streaming(temp, base) else parseV1Streaming(temp, base)-                    return@withContext AppProvider.filterTargetSdk(apps)-                } catch (e: Exception) {-                    lastErr = e-                }-            }-            throw lastErr ?: RuntimeException("Failed to fetch $repoUrl")-        } finally {-            temp.delete()+    /**+     * index-v2: `entry.jar` is the signed root. It names the real index file and pins its+     * SHA-256, so the large index itself needs no separate signature — the hash chains+     * back to the certificate we just verified.+     */+    private fun fetchV2(+        base: String,+        pinnedFingerprint: String?,+        work: File,+        acceptVersion: (String, Long) -> Boolean,+    ): IndexResult {+        val entryJar = File(work, "entry.jar")+        downloadToFile("$base/entry.jar", entryJar)+        val verified = SignedJarIndex.readVerified(entryJar, "entry.json", pinnedFingerprint)++        val entry = JSONObject(String(verified.content, Charsets.UTF_8))+        val index = entry.optJSONObject("index")+            ?: throw java.io.IOException("entry.json has no index section")+        val name = index.optString("name").takeIf { it.isNotBlank() }+            ?: throw java.io.IOException("entry.json index has no name")+        val expectedSha = index.optString("sha256").takeIf { it.isNotBlank() }+            ?: throw java.io.IOException("entry.json index has no sha256")++        val indexFile = File(work, "index-v2.json")+        downloadToFile(base + "/" + name.trimStart('/'), indexFile)+        val actualSha = ApkCertificates.sha256(indexFile)+        if (!actualSha.equals(expectedSha, ignoreCase = true)) {+            throw java.io.IOException("index-v2.json hash does not match the signed entry.json")         }++        return IndexResult(+            apps = AppProvider.filterTargetSdk(parseV2Streaming(indexFile, base, acceptVersion)),+            signerSha256 = verified.signerSha256,+        )+    }++    /** Legacy format: the whole index is inside the signed JAR. */+    private fun fetchV1(+        base: String,+        pinnedFingerprint: String?,+        work: File,+        acceptVersion: (String, Long) -> Boolean,+    ): IndexResult {+        val jar = File(work, "index-v1.jar")+        downloadToFile("$base/index-v1.jar", jar)+        val indexFile = File(work, "index-v1.json")+        val signer = SignedJarIndex.extractVerified(jar, "index-v1.json", pinnedFingerprint, indexFile)+        return IndexResult(+            apps = AppProvider.filterTargetSdk(parseV1Streaming(indexFile, base, acceptVersion)),+            signerSha256 = signer,+        )     } -    private fun downloadToFile(url: String, outFile: File) {+    internal fun downloadToFile(url: String, outFile: File) {         val conn = (URL(url).openConnection() as HttpURLConnection).apply {             connectTimeout = 30000             readTimeout = 120000@@ -78,7 +144,11 @@ object FDroidRepository {      // ---- Streaming V2 parser ---- -    private fun parseV2Streaming(file: File, repoBase: String): List<UnifiedApp> {+    private fun parseV2Streaming(+        file: File,+        repoBase: String,+        acceptVersion: (String, Long) -> Boolean,+    ): List<UnifiedApp> {         val result = mutableListOf<UnifiedApp>()         JsonReader(file.reader()).use { r ->             r.isLenient = true@@ -90,7 +160,7 @@ object FDroidRepository {                         while (r.hasNext()) {                             val pkg = r.nextName()                             try {-                                val app = parsePackageV2(r, pkg, repoBase)+                                val app = parsePackageV2(r, pkg, repoBase, acceptVersion)                                 if (app != null) result.add(app)                             } catch (_: Exception) {                                 try { r.skipValue() } catch (_: Exception) {}@@ -106,7 +176,12 @@ object FDroidRepository {         return result     } -    private fun parsePackageV2(reader: JsonReader, packageName: String, repoBase: String): UnifiedApp? {+    private fun parsePackageV2(+        reader: JsonReader,+        packageName: String,+        repoBase: String,+        acceptVersion: (String, Long) -> Boolean,+    ): UnifiedApp? {         // reader at BEGIN_OBJECT of package         var metaName: String? = null         var metaSummary: String? = null@@ -122,6 +197,8 @@ object FDroidRepository {         var latestAdded: Long = -1L         var latestFileName: String? = null         var latestSize: Long = 0L+        var latestSha256: String? = null+        var latestSigners: List<String> = emptyList()         var latestVersionName: String? = null         var latestVersionCode: Long = 0L         var latestTargetSdk: Int? = null@@ -145,8 +222,10 @@ object FDroidRepository {                             "added" -> added = nextLongOrNull(reader) ?: 0L                             "lastUpdated" -> lastUpdated = nextLongOrNull(reader) ?: 0L                             "icon" -> {+                                // index-v2 icon names are repo-absolute ("/icons/foo.png");+                                // don't prepend /icons/ again as the v1 branch has to.                                 val iconName = readIconName(reader)-                                if (iconName != null) iconUrl = "$repoBase/icons/$iconName"+                                if (iconName != null) iconUrl = repoBase + "/" + iconName.trimStart('/')                             }                             else -> reader.skipValue()                         }@@ -162,6 +241,8 @@ object FDroidRepository {                             var vAdded: Long = 0L                             var vFileName: String? = null                             var vFileSize: Long = 0L+                            var vFileSha256: String? = null+                            var vSigners: List<String> = emptyList()                             var vVersionName: String? = null                             var vVersionCode: Long = 0L                             var vTargetSdk: Int? = null@@ -175,6 +256,7 @@ object FDroidRepository {                                             when (reader.nextName()) {                                                 "name" -> vFileName = nextStringOrNull(reader)                                                 "size" -> vFileSize = nextLongOrNull(reader) ?: 0L+                                                "sha256" -> vFileSha256 = nextStringOrNull(reader)                                                 else -> reader.skipValue()                                             }                                         }@@ -196,6 +278,18 @@ object FDroidRepository {                                                     }                                                     reader.endObject()                                                 }+                                                // signer.sha256 is the list of signing-certificate+                                                // fingerprints this APK is expected to carry.+                                                "signer" -> {+                                                    reader.beginObject()+                                                    while (reader.hasNext()) {+                                                        when (reader.nextName()) {+                                                            "sha256" -> vSigners = readStringArray(reader)+                                                            else -> reader.skipValue()+                                                        }+                                                    }+                                                    reader.endObject()+                                                }                                                 else -> reader.skipValue()                                             }                                         }@@ -206,10 +300,15 @@ object FDroidRepository {                                 }                             }                             reader.endObject()-                            if (vAdded >= latestAdded) {+                            // Newest *acceptable* version wins: a package whose latest build+                            // hasn't been reproduced yet falls back to its newest reproduced+                            // one instead of vanishing from the catalogue.+                            if (vAdded >= latestAdded && acceptVersion(packageName, vVersionCode)) {                                 latestAdded = vAdded                                 latestFileName = vFileName                                 latestSize = vFileSize+                                latestSha256 = vFileSha256+                                latestSigners = vSigners                                 latestVersionName = vVersionName                                 latestVersionCode = vVersionCode                                 latestTargetSdk = vTargetSdk@@ -226,10 +325,17 @@ object FDroidRepository {         }         reader.endObject() -        val apkUrl = latestFileName?.let { "$repoBase/$it" }+        // No version passed acceptVersion — drop the package entirely rather than+        // advertising an entry that has no installable APK behind it.+        if (latestAdded < 0L || latestFileName == null) return null++        // index-v2 file names are repo-absolute ("/com.example_12.apk").+        val apkUrl = latestFileName.let { repoBase + "/" + it.trimStart('/') }         return UnifiedApp(             packageName = packageName,             source = AppSource.FDROID,+            expectedSigners = latestSigners,+            apkSha256 = latestSha256,             name = metaName ?: packageName.substringAfterLast('.'),             summary = metaSummary ?: "",             description = metaDesc ?: "",@@ -253,7 +359,11 @@ object FDroidRepository {      // ---- Streaming V1 parser (apps[] + packages{ pkg:[...] }) ---- -    private fun parseV1Streaming(file: File, repoBase: String): List<UnifiedApp> {+    private fun parseV1Streaming(+        file: File,+        repoBase: String,+        acceptVersion: (String, Long) -> Boolean,+    ): List<UnifiedApp> {         val appsMeta = mutableMapOf<String, V1AppMeta>()         val packagesMap = mutableMapOf<String, V1PackageLatest>()         JsonReader(file.reader()).use { r ->@@ -278,7 +388,7 @@ object FDroidRepository {                         while (r.hasNext()) {                             val pkgName = r.nextName()                             try {-                                val latest = parseV1PackagesArray(r)+                                val latest = parseV1PackagesArray(r, pkgName, acceptVersion)                                 if (latest != null) packagesMap[pkgName] = latest                             } catch (_: Exception) {                                 try { r.skipValue() } catch (_: Exception) {}@@ -294,7 +404,8 @@ object FDroidRepository {          val result = mutableListOf<UnifiedApp>()         for ((pkg, meta) in appsMeta) {-            val latest = packagesMap[pkg]+            // Same rule as v2: no acceptable version means no catalogue entry.+            val latest = packagesMap[pkg] ?: continue             result.add(                 UnifiedApp(                     packageName = pkg,@@ -308,8 +419,11 @@ object FDroidRepository {                     versionName = latest?.versionName,                     versionCode = latest?.versionCode ?: 0L,                     sizeBytes = latest?.size ?: 0L,-                    apkUrl = latest?.apkName?.let { "$repoBase/$it" },+                    apkUrl = latest?.apkName?.let { repoBase + "/" + it.trimStart('/') },                     targetSdk = latest?.targetSdk,+                    expectedSigners = listOfNotNull(latest?.signer),+                    // v1 states the hash algorithm; only pin it when it really is SHA-256.+                    apkSha256 = latest?.hash?.takeIf { latest?.hashType.equals("sha256", true) },                     website = meta.webSite,                     sourceCode = meta.sourceCode,                     license = meta.license,@@ -342,7 +456,10 @@ object FDroidRepository {         val versionName: String?,         val versionCode: Long,         val size: Long,-        val targetSdk: Int?+        val targetSdk: Int?,+        val hash: String?,+        val hashType: String?,+        val signer: String?     )      private fun parseV1AppMeta(reader: JsonReader): V1AppMeta? {@@ -382,8 +499,12 @@ object FDroidRepository {         return V1AppMeta(pkg, name, summary, description, icon, authorName, categories, webSite, sourceCode, license, added, lastUpdated)     } -    private fun parseV1PackagesArray(reader: JsonReader): V1PackageLatest? {-        // array of package versions, take last+    private fun parseV1PackagesArray(+        reader: JsonReader,+        packageName: String,+        acceptVersion: (String, Long) -> Boolean,+    ): V1PackageLatest? {+        // array of package versions, take the last acceptable one         var last: V1PackageLatest? = null         reader.beginArray()         while (reader.hasNext()) {@@ -394,6 +515,9 @@ object FDroidRepository {                 var versionCode: Long = 0L                 var size: Long = 0L                 var targetSdk: Int? = null+                var hash: String? = null+                var hashType: String? = null+                var signer: String? = null                 while (reader.hasNext()) {                     when (reader.nextName()) {                         "apkName" -> apkName = nextStringOrNull(reader)@@ -401,11 +525,18 @@ object FDroidRepository {                         "versionCode" -> versionCode = nextLongOrNull(reader) ?: 0L                         "size" -> size = nextLongOrNull(reader) ?: 0L                         "targetSdkVersion" -> targetSdk = nextIntOrNull(reader)+                        "hash" -> hash = nextStringOrNull(reader)+                        "hashType" -> hashType = nextStringOrNull(reader)+                        "signer" -> signer = nextStringOrNull(reader)                         else -> reader.skipValue()                     }                 }                 reader.endObject()-                last = V1PackageLatest(apkName, versionName, versionCode, size, targetSdk)+                if (acceptVersion(packageName, versionCode)) {+                    last = V1PackageLatest(+                        apkName, versionName, versionCode, size, targetSdk, hash, hashType, signer+                    )+                }             } catch (_: Exception) {                 try { reader.endObject() } catch (_: Exception) {}                 try { reader.skipValue() } catch (_: Exception) {}
appstore/src/main/java/com/vayunmathur/appstore/data/FDroidVerification.kt
diff --git a/appstore/src/main/java/com/vayunmathur/appstore/data/FDroidVerification.kt b/appstore/src/main/java/com/vayunmathur/appstore/data/FDroidVerification.ktnew file mode 100644index 0000000000..b0d4f2ada9--- /dev/null+++ b/appstore/src/main/java/com/vayunmathur/appstore/data/FDroidVerification.kt@@ -0,0 +1,134 @@+package com.vayunmathur.appstore.data++import android.content.Context+import android.util.JsonReader+import android.util.JsonToken+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.withContext+import java.io.File++/**+ * The set of F-Droid builds that have been **reproduced**.+ *+ * F-Droid's verification server (<https://verification.f-droid.org>) rebuilds apps that+ * f-droid.org already built, on separate infrastructure, and records whether the two+ * outputs are bit-identical. Its `verified.json` is the only machine-readable statement+ * of that: `index-v2.json` carries no reproducibility field whatsoever, so the index+ * alone cannot tell you whether a version was independently reproduced.+ *+ * Shape (~24 MB, ~31k build records):+ * ```+ * { "packages": { "<packageName>": [ {+ *       "verified": true,+ *       "local":  { "packageName": ..., "versionCode": 110002, ... },+ *       "remote": { ... }, "diffoscope": ..., "url": ...+ * } ] } }+ * ```+ * `versionCode` is a JSON number for some records and a string for others, so it is read+ * leniently. The `local`/`remote` SHA-256s are of the *unsigned* build artefacts and+ * never match the published APK's hash — `verified` is the field that carries the+ * verdict, not a hash comparison.+ *+ * This is a hard gate: [ReproducibleBuilds.fetch] throwing means the F-Droid sync fails+ * rather than falling back to importing unreproduced apps.+ */+object ReproducibleBuilds {++    const val VERIFIED_JSON_URL = "https://verification.f-droid.org/verified.json"++    /** Keys are `"$packageName:$versionCode"`. */+    @JvmInline+    value class Verified(private val keys: Set<String>) {+        val size: Int get() = keys.size+        fun contains(packageName: String, versionCode: Long): Boolean =+            keys.contains("$packageName:$versionCode")+    }++    suspend fun fetch(context: Context): Verified = withContext(Dispatchers.IO) {+        val file = File(context.cacheDir, "fdroid-verified.json")+        try {+            FDroidRepository.downloadToFile(VERIFIED_JSON_URL, file)+            parse(file)+        } finally {+            file.delete()+        }+    }++    private fun parse(file: File): Verified {+        val keys = HashSet<String>(24_000)+        JsonReader(file.reader()).use { r ->+            r.isLenient = true+            r.beginObject()+            while (r.hasNext()) {+                if (r.nextName() != "packages") {+                    r.skipValue()+                    continue+                }+                r.beginObject()+                while (r.hasNext()) {+                    val pkg = r.nextName()+                    try {+                        readBuilds(r, pkg, keys)+                    } catch (_: Exception) {+                        runCatching { r.skipValue() }+                    }+                }+                r.endObject()+            }+            r.endObject()+        }+        return Verified(keys)+    }++    private fun readBuilds(r: JsonReader, pkg: String, into: MutableSet<String>) {+        if (r.peek() != JsonToken.BEGIN_ARRAY) {+            r.skipValue()+            return+        }+        r.beginArray()+        while (r.hasNext()) {+            var verified = false+            var versionCode: Long? = null+            r.beginObject()+            while (r.hasNext()) {+                when (r.nextName()) {+                    "verified" -> verified = readBooleanLenient(r)+                    // The build's identity lives in the `local` block; `remote` repeats it.+                    "local" -> versionCode = readVersionCode(r) ?: versionCode+                    else -> r.skipValue()+                }+            }+            r.endObject()+            if (verified && versionCode != null) into.add("$pkg:$versionCode")+        }+        r.endArray()+    }++    private fun readVersionCode(r: JsonReader): Long? {+        if (r.peek() != JsonToken.BEGIN_OBJECT) {+            r.skipValue()+            return null+        }+        var code: Long? = null+        r.beginObject()+        while (r.hasNext()) {+            if (r.nextName() == "versionCode") {+                code = when (r.peek()) {+                    JsonToken.NUMBER -> r.nextLong()+                    JsonToken.STRING -> r.nextString().toLongOrNull()+                    else -> { r.skipValue(); null }+                }+            } else {+                r.skipValue()+            }+        }+        r.endObject()+        return code+    }++    private fun readBooleanLenient(r: JsonReader): Boolean = when (r.peek()) {+        JsonToken.BOOLEAN -> r.nextBoolean()+        JsonToken.STRING -> r.nextString().equals("true", ignoreCase = true)+        else -> { r.skipValue(); false }+    }+}
appstore/src/main/java/com/vayunmathur/appstore/data/ModernAppsProvider.kt
diff --git a/appstore/src/main/java/com/vayunmathur/appstore/data/ModernAppsProvider.kt b/appstore/src/main/java/com/vayunmathur/appstore/data/ModernAppsProvider.ktnew file mode 100644index 0000000000..c50649052f--- /dev/null+++ b/appstore/src/main/java/com/vayunmathur/appstore/data/ModernAppsProvider.kt@@ -0,0 +1,296 @@+package com.vayunmathur.appstore.data++import android.content.Context+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.withContext+import kotlinx.serialization.SerialName+import kotlinx.serialization.Serializable+import kotlinx.serialization.json.Json+import java.net.HttpURLConnection+import java.net.URL++/**+ * The monorepo's own apps, sourced straight from its GitHub releases.+ *+ * `release.sh` attaches every module's release APK to the tagged GitHub release, together+ * with an `index.json` describing them — the APK filenames alone can't be mapped back to+ * package names, since `:games:chess` builds `chess-release.apk` but installs as+ * `com.vayunmathur.games.chess`.+ *+ * Releases cut before `index.json` existed are still usable: [fetchFromGitTree] derives+ * the same information from the tag itself, by listing the repo tree for that tag and+ * turning each module path into its applicationId (`games/chess` →+ * `com.vayunmathur.games.chess`, which holds for every module in the repo). Version comes+ * from `version.txt` at the tag and per-asset SHA-256 from GitHub's own `digest` field, so+ * the fallback is exact rather than a guess.+ *+ * **Neither path is signed, and neither needs to be.** Every APK from this source is+ * checked at install time against the certificate *this store app itself* is signed with+ * (see [com.vayunmathur.appstore.data.security.ApkCertificates.selfSigners]). A tampered+ * index, a compromised GitHub account, or a hostile CDN can change which bytes are+ * offered, but cannot produce bytes that will install: that needs the release signing+ * key, which is the sole trust root here.+ */+class ModernAppsProvider(private val appContext: Context) : AppProvider {++    override val id = "modern-apps"+    override val name = "Modern Apps"+    override val source = AppSource.MODERN_APPS++    @Volatile+    var cachedPackageNames: Set<String> = emptySet()+        private set++    @Volatile+    private var cached: List<UnifiedApp> = emptyList()++    private val json = Json { ignoreUnknownKeys = true; isLenient = true }++    override suspend fun fetchAll(): List<UnifiedApp> = withContext(Dispatchers.IO) {+        val release = json.decodeFromString(+            GithubRelease.serializer(),+            httpGetString(ModernAppsRepo.LATEST_RELEASE_API, accept = GITHUB_ACCEPT),+        )+        val indexAsset = release.assets.firstOrNull { it.name == ModernAppsRepo.INDEX_ASSET }+        val apps = if (indexAsset != null) {+            fetchFromIndex(release, indexAsset)+        } else {+            fetchFromGitTree(release)+        }+        val filtered = AppProvider.filterTargetSdk(apps).distinctBy { it.packageName }+        cached = filtered+        cachedPackageNames = filtered.map { it.packageName }.toSet()+        filtered+    }++    /** Preferred path: the release states its own contents. */+    private fun fetchFromIndex(release: GithubRelease, indexAsset: GithubAsset): List<UnifiedApp> {+        val index = json.decodeFromString(+            ModernAppsIndex.serializer(),+            httpGetString(indexAsset.downloadUrl, accept = "application/json"),+        )+        val assets = release.assets.associateBy { it.name }+        return index.apps.mapNotNull { entry ->+            val asset = assets[entry.apk] ?: return@mapNotNull null+            entryToApp(+                packageName = entry.packageName,+                label = entry.label,+                asset = asset,+                versionCode = entry.versionCode ?: index.versionCode,+                versionName = entry.versionName ?: index.versionName ?: release.tagName,+                targetSdk = entry.targetSdk,+                sha256 = entry.sha256 ?: asset.sha256(),+                summary = entry.summary.orEmpty(),+                description = entry.description.orEmpty(),+                publishedAt = release.publishedAtMillis(),+            )+        }+    }++    /**+     * Fallback for releases published before `index.json` existed.+     *+     * Every module in the repo has `applicationId = "com.vayunmathur." + <module path with+     * dots>`, and each builds `<leaf>-release.apk`, so the tag's file listing is enough to+     * recover the mapping exactly. Where a leaf name is ambiguous (`openassistant` is both+     * an app and an `sdk/` library) the shallowest path wins, which is the app; a wrong+     * guess could not install anything anyway, because [InstallVerifier] rejects an APK+     * whose declared package differs from the one requested.+     */+    private fun fetchFromGitTree(release: GithubRelease): List<UnifiedApp> {+        val tag = release.tagName.ifBlank { throw java.io.IOException("Release has no tag") }+        val tree = json.decodeFromString(+            GitTree.serializer(),+            httpGetString(ModernAppsRepo.treeApi(tag), accept = GITHUB_ACCEPT),+        )+        val modules = tree.tree.asSequence()+            .map { it.path }+            .filter { it.endsWith("/build.gradle.kts") && !it.startsWith("build-logic") }+            .map { it.removeSuffix("/build.gradle.kts") }+            .toList()++        // leaf -> shallowest module path with that leaf+        val byLeaf = HashMap<String, String>()+        for (module in modules.sortedBy { it.count { c -> c == '/' } }) {+            byLeaf.putIfAbsent(module.substringAfterLast('/'), module)+        }++        // release.sh injects one version across every module; version.txt at the tag+        // records it, and GitHub's asset list carries no versionCode of its own.+        val (versionCode, versionName) = readVersionTxt(tag) ?: (0L to tag)++        return release.assets.mapNotNull { asset ->+            if (!asset.name.endsWith(APK_SUFFIX)) return@mapNotNull null+            val leaf = asset.name.removeSuffix(APK_SUFFIX)+            val module = byLeaf[leaf] ?: return@mapNotNull null+            entryToApp(+                packageName = "com.vayunmathur." + module.replace('/', '.'),+                label = leaf.replaceFirstChar { it.uppercase() },+                asset = asset,+                versionCode = versionCode,+                versionName = versionName,+                // Unknown without reading the APK; null passes filterTargetSdk, and the+                // whole repo targets well above the floor anyway.+                targetSdk = null,+                sha256 = asset.sha256(),+                summary = "",+                description = "",+                publishedAt = release.publishedAtMillis(),+            )+        }+    }++    /** `version.txt` is two lines: versionCode, then versionName. */+    private fun readVersionTxt(tag: String): Pair<Long, String>? = try {+        val lines = httpGetString(ModernAppsRepo.versionTxt(tag), accept = "text/plain")+            .lineSequence().map { it.trim() }.filter { it.isNotEmpty() }.toList()+        val code = lines.getOrNull(0)?.toLongOrNull()+        val name = lines.getOrNull(1)+        if (code != null && name != null) code to name else null+    } catch (_: Exception) {+        null+    }++    private fun entryToApp(+        packageName: String,+        label: String,+        asset: GithubAsset,+        versionCode: Long,+        versionName: String,+        targetSdk: Int?,+        sha256: String?,+        summary: String,+        description: String,+        publishedAt: Long,+    ) = UnifiedApp(+        packageName = packageName,+        source = AppSource.MODERN_APPS,+        name = label,+        summary = summary,+        description = description,+        author = AUTHOR,+        versionName = versionName,+        versionCode = versionCode,+        sizeBytes = asset.size,+        apkUrl = asset.downloadUrl,+        targetSdk = targetSdk,+        license = LICENSE,+        website = ModernAppsRepo.PROJECT_URL,+        sourceCode = ModernAppsRepo.PROJECT_URL,+        repoUrl = ModernAppsRepo.REPO_KEY,+        apkSha256 = sha256,+        lastUpdated = publishedAt,+    )++    override suspend fun search(query: String): List<UnifiedApp> {+        if (query.isBlank()) return emptyList()+        val q = query.lowercase()+        return cached.filter {+            it.name.lowercase().contains(q) ||+                it.packageName.lowercase().contains(q) ||+                it.summary.lowercase().contains(q)+        }+    }++    override suspend fun isPresent(packageName: String): Boolean =+        cachedPackageNames.contains(packageName)++    override suspend fun getDetails(packageName: String): UnifiedApp? =+        cached.find { it.packageName == packageName }++    /** Refresh from GitHub and replace this source's rows in the shared cache table. */+    suspend fun syncIntoDb(db: AppDatabase): Int = withContext(Dispatchers.IO) {+        val apps = fetchAll()+        db.cachedAppDao().deleteByRepo(ModernAppsRepo.REPO_KEY)+        db.cachedAppDao().upsertAll(apps.map { it.toEntity() })+        apps.size+    }++    /** Seed the in-memory view from previously cached rows so browse works offline. */+    fun primeFrom(entities: List<CachedAppEntity>) {+        val apps = entities+            .filter { it.source == AppSource.MODERN_APPS.name }+            .map { it.toUnifiedApp() }+        cached = apps+        cachedPackageNames = apps.map { it.packageName }.toSet()+    }++    private fun httpGetString(url: String, accept: String): String {+        val conn = (URL(url).openConnection() as HttpURLConnection).apply {+            connectTimeout = 20_000+            readTimeout = 60_000+            instanceFollowRedirects = true+            setRequestProperty("Accept", accept)+            setRequestProperty("User-Agent", USER_AGENT)+        }+        try {+            if (conn.responseCode !in 200..299) {+                throw java.io.IOException("HTTP ${conn.responseCode} for $url")+            }+            return conn.inputStream.use { it.readBytes().toString(Charsets.UTF_8) }+        } finally {+            conn.disconnect()+        }+    }++    companion object {+        private const val GITHUB_ACCEPT = "application/vnd.github+json"+        private const val USER_AGENT = "ModernAppStore/1.0"+        private const val AUTHOR = "Vayun Mathur"+        private const val LICENSE = "GPL-3.0-only"+        private const val APK_SUFFIX = "-release.apk"+    }+}++// --- Wire formats -------------------------------------------------------------------++@Serializable+private data class GithubRelease(+    @SerialName("tag_name") val tagName: String = "",+    @SerialName("published_at") val publishedAt: String? = null,+    val assets: List<GithubAsset> = emptyList(),+) {+    /** GitHub returns ISO-8601 UTC ("2026-08-01T12:00:00Z"); 0 if absent or unparseable. */+    fun publishedAtMillis(): Long = publishedAt?.let {+        runCatching { java.time.Instant.parse(it).toEpochMilli() }.getOrNull()+    } ?: 0L+}++@Serializable+private data class GithubAsset(+    val name: String = "",+    @SerialName("browser_download_url") val downloadUrl: String = "",+    val size: Long = 0L,+    /** GitHub returns `"sha256:<hex>"`; absent on older releases. */+    val digest: String? = null,+) {+    fun sha256(): String? = digest?.removePrefix("sha256:")?.takeIf { it.length == 64 }+}++@Serializable+private data class GitTree(val tree: List<GitTreeEntry> = emptyList())++@Serializable+private data class GitTreeEntry(val path: String = "")++@Serializable+private data class ModernAppsIndex(+    val versionCode: Long = 0L,+    val versionName: String? = null,+    val apps: List<ModernAppEntry> = emptyList(),+)++@Serializable+private data class ModernAppEntry(+    val packageName: String,+    val label: String,+    /** Release asset filename, e.g. `chess-release.apk`. */+    val apk: String,+    val sha256: String? = null,+    val size: Long = 0L,+    val versionCode: Long? = null,+    val versionName: String? = null,+    val targetSdk: Int? = null,+    val summary: String? = null,+    val description: String? = null,+)
appstore/src/main/java/com/vayunmathur/appstore/data/installer/PlayDownloader.kt
diff --git a/appstore/src/main/java/com/vayunmathur/appstore/data/installer/PlayDownloader.kt b/appstore/src/main/java/com/vayunmathur/appstore/data/installer/PlayDownloader.ktindex 51f969e042..9ca3ada654 100644--- a/appstore/src/main/java/com/vayunmathur/appstore/data/installer/PlayDownloader.kt+++ b/appstore/src/main/java/com/vayunmathur/appstore/data/installer/PlayDownloader.kt@@ -8,8 +8,14 @@ import java.net.HttpURLConnection import java.net.URL  /**- * Downloads Play Store split APKs with resume + SHA verification,- * then delegates to SessionInstaller — now using HttpURLConnection.+ * Downloads Play Store split APKs with resume support.+ *+ * There is deliberately no publisher-key check here and there cannot be one: Play App+ * Signing means Google holds the key, so nothing Play returns can be pinned to a+ * publisher. What integrity checking is possible happens in+ * [com.vayunmathur.appstore.data.security.InstallVerifier] just before install — package+ * identity, a single consistent signer across all splits, and continuity with the copy+ * already on the device.  */ class PlayDownloader(     private val context: Context@@ -148,22 +154,4 @@ class PlayDownloader(         }     } -    /**-     * Full pipeline: download + install-     */-    suspend fun downloadAndInstall(-        packageName: String,-        versionCode: Long,-        gplayFiles: List<PlayFile>,-        installer: SessionInstaller,-        progressCallback: (Float) -> Unit = {}-    ): Result<Boolean> {-        val downloadResult = downloadFiles(packageName, versionCode, gplayFiles, progressCallback)-        if (downloadResult.isFailure) return Result.failure(downloadResult.exceptionOrNull()!!)--        val files = downloadResult.getOrNull()!!-        val totalSize = files.sumOf { it.length() }-        val installed = installer.installSplits(packageName, files, totalSize)-        return if (installed) Result.success(true) else Result.failure(Exception("Installer failed"))-    } }
appstore/src/main/java/com/vayunmathur/appstore/data/installer/SessionInstaller.kt
diff --git a/appstore/src/main/java/com/vayunmathur/appstore/data/installer/SessionInstaller.kt b/appstore/src/main/java/com/vayunmathur/appstore/data/installer/SessionInstaller.ktindex 273388cfff..1bd967dc4d 100644--- a/appstore/src/main/java/com/vayunmathur/appstore/data/installer/SessionInstaller.kt+++ b/appstore/src/main/java/com/vayunmathur/appstore/data/installer/SessionInstaller.kt@@ -7,10 +7,18 @@ import android.content.pm.PackageInstaller import android.os.Build import android.os.Process import android.util.Log+import com.vayunmathur.appstore.data.security.InstallRequirement+import com.vayunmathur.appstore.data.security.InstallVerifier+import com.vayunmathur.appstore.data.security.VerificationResult import java.io.File  /**- * Simplified installer supporting single + split APKs via PackageInstaller.+ * Installer for single + split APKs via PackageInstaller.+ *+ * [requirement] is mandatory rather than defaulted: every install path has to state what+ * it expects of the bytes, so a new caller cannot accidentally inherit "check nothing".+ * Verification runs before the session is created, so rejected bytes are never written+ * into a PackageInstaller session at all.  */ class SessionInstaller(private val context: Context) { @@ -18,15 +26,32 @@ class SessionInstaller(private val context: Context) {         private const val TAG = "SessionInstaller"     } +    /** Outcome of an install attempt, including why it was refused. */+    data class Outcome(val started: Boolean, val verification: VerificationResult)+     suspend fun installSplits(         packageName: String,         files: List<File>,+        requirement: InstallRequirement,         totalSize: Long = -1L-    ): Boolean {+    ): Outcome {         if (files.isEmpty()) {             Log.w(TAG, "No files to install for $packageName")-            return false+            return Outcome(false, VerificationResult.Rejected("nothing was downloaded"))+        }++        val verification = InstallVerifier.verify(context, files, requirement)+        if (verification is VerificationResult.Rejected) {+            Log.e(TAG, "Refusing to install $packageName: ${verification.reason}")+            files.forEach { runCatching { it.delete() } }+            return Outcome(false, verification)         }++        val started = commit(packageName, files, totalSize)+        return Outcome(started, verification)+    }++    private fun commit(packageName: String, files: List<File>, totalSize: Long): Boolean {         val computedSize = if (totalSize > 0) totalSize else files.sumOf { it.length() }         return try {             val pm = context.packageManager@@ -91,9 +116,4 @@ class SessionInstaller(private val context: Context) {         }     } -    fun installSingleApkBlocking(packageName: String, file: File): Boolean {-        return kotlinx.coroutines.runBlocking {-            installSplits(packageName, listOf(file), file.length())-        }-    } }
appstore/src/main/java/com/vayunmathur/appstore/data/play/PlayHttpClient.kt
diff --git a/appstore/src/main/java/com/vayunmathur/appstore/data/play/PlayHttpClient.kt b/appstore/src/main/java/com/vayunmathur/appstore/data/play/PlayHttpClient.ktindex f4165a51ae..1e5ccf36de 100644--- a/appstore/src/main/java/com/vayunmathur/appstore/data/play/PlayHttpClient.kt+++ b/appstore/src/main/java/com/vayunmathur/appstore/data/play/PlayHttpClient.kt@@ -178,7 +178,13 @@ class PlayHttpClient : IHttpClient {         bodyBytes: ByteArray?,         contentType: String?,     ): HttpURLConnection {-        val conn = (URL(urlString).openConnection() as HttpURLConnection).apply {+        val rawConn = URL(urlString).openConnection()+        // Play Store auth uses Google GTS — pin via app-wide STANDARD bundle (contains GTS R1-R4).+        val factory = com.vayunmathur.library.network.NetworkClient.defaultSslSocketFactory+        if (factory != null && rawConn is javax.net.ssl.HttpsURLConnection) {+            rawConn.sslSocketFactory = factory+        }+        val conn = (rawConn as HttpURLConnection).apply {             connectTimeout = CONNECT_TIMEOUT             readTimeout = READ_TIMEOUT             instanceFollowRedirects = false
appstore/src/main/java/com/vayunmathur/appstore/data/play/PlayStoreApi.kt
diff --git a/appstore/src/main/java/com/vayunmathur/appstore/data/play/PlayStoreApi.kt b/appstore/src/main/java/com/vayunmathur/appstore/data/play/PlayStoreApi.ktindex 0016341d4a..c6e6af96c7 100644--- a/appstore/src/main/java/com/vayunmathur/appstore/data/play/PlayStoreApi.kt+++ b/appstore/src/main/java/com/vayunmathur/appstore/data/play/PlayStoreApi.kt@@ -8,6 +8,7 @@ import com.aurora.gplayapi.helpers.PurchaseHelper import com.aurora.gplayapi.helpers.SearchHelper import com.vayunmathur.appstore.data.AppSource import com.vayunmathur.appstore.data.UnifiedApp+import com.vayunmathur.appstore.data.security.ApkCertificates import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext @@ -41,7 +42,15 @@ class PlayStoreApi(                 offerType = app.offerType,                 isFree = app.isFree,                 whatsNew = app.changes.takeIf { it.isNotBlank() },-                targetSdk = app.targetSdk+                targetSdk = app.targetSdk,+                // AppDetails.certificateSet[].sha256 is the signing certificate Google+                // says this package should carry — the same expectation the Play client+                // stores on its library entry and compares against PackageManager. It+                // pins the bytes against a swapped CDN response, but note that Google+                // supplies both this value and the APK, so it is not a publisher key.+                expectedSigners = app.certificateSetList+                    .mapNotNull { it.sha256?.let(ApkCertificates::normalizeFingerprint) }+                    .distinct(),             )         } catch (e: Exception) {             null
appstore/src/main/java/com/vayunmathur/appstore/data/security/ApkCertificates.kt
diff --git a/appstore/src/main/java/com/vayunmathur/appstore/data/security/ApkCertificates.kt b/appstore/src/main/java/com/vayunmathur/appstore/data/security/ApkCertificates.ktnew file mode 100644index 0000000000..93c32f8efe--- /dev/null+++ b/appstore/src/main/java/com/vayunmathur/appstore/data/security/ApkCertificates.kt@@ -0,0 +1,122 @@+package com.vayunmathur.appstore.data.security++import android.content.Context+import android.content.pm.PackageInfo+import android.content.pm.PackageManager+import android.content.pm.Signature+import java.io.File+import java.security.MessageDigest++/**+ * Reads signing certificates out of APK files and installed packages.+ *+ * A "fingerprint" here is always the lowercase-hex SHA-256 of the DER-encoded X.509+ * signing certificate. That is the same value `apksigner verify --print-certs` prints+ * as *Signer #1 certificate SHA-256 digest*, and the same value F-Droid publishes as a+ * package's `signer` in its index — so index-supplied and locally-computed values are+ * directly comparable with no conversion.+ *+ * [PackageManager.getPackageArchiveInfo] performs a real APK signature verification+ * (v3/v2 block, falling back to v1) while parsing, so a certificate coming back from+ * [apkSigners] means the file genuinely carries a valid signature by that certificate —+ * not merely that a certificate is embedded somewhere in it.+ */+object ApkCertificates {++    /** Fingerprints of the certificates that actually signed [apk]. Empty if unparseable. */+    fun apkSigners(context: Context, apk: File): Set<String> =+        fingerprints(signaturesOf(archiveInfo(context, apk), contentsOnly = true))++    /**+     * Fingerprints currently trusted for an installed [packageName]. Includes rotated+     * ancestors (`signingCertificateHistory`) so an app that has legitimately rotated its+     * key still matches an APK signed by either the old or the new certificate.+     */+    fun installedSigners(context: Context, packageName: String): Set<String> = try {+        val info = context.packageManager+            .getPackageInfo(packageName, PackageManager.GET_SIGNING_CERTIFICATES)+        fingerprints(signaturesOf(info, contentsOnly = false))+    } catch (_: Exception) {+        emptySet()+    }++    /**+     * Fingerprints of the certificate **this app** is signed with.+     *+     * Read back out of PackageManager at runtime rather than compared against a constant+     * compiled into the source, so there is no fingerprint in the codebase that could+     * drift from — or be edited independently of — the key that actually ships.+     */+    fun selfSigners(context: Context): Set<String> = installedSigners(context, context.packageName)++    /** Parsed manifest of an APK on disk, or null if it isn't a readable, validly-signed APK. */+    fun archiveInfo(context: Context, apk: File): PackageInfo? = try {+        @Suppress("DEPRECATION")+        context.packageManager+            .getPackageArchiveInfo(apk.absolutePath, PackageManager.GET_SIGNING_CERTIFICATES)+    } catch (_: Exception) {+        null+    }++    fun sha256(file: File): String {+        val digest = MessageDigest.getInstance("SHA-256")+        file.inputStream().use { input ->+            val buf = ByteArray(64 * 1024)+            var n: Int+            while (input.read(buf).also { n = it } != -1) digest.update(buf, 0, n)+        }+        return digest.digest().toHex()+    }++    fun sha256(bytes: ByteArray): String =+        MessageDigest.getInstance("SHA-256").digest(bytes).toHex()++    /** Short form for UI: first 8 hex bytes, colon separated. */+    fun abbreviate(fingerprint: String): String =+        fingerprint.chunked(2).take(8).joinToString(":").uppercase()++    /**+     * Normalise a certificate fingerprint to lowercase hex.+     *+     * F-Droid publishes hex; Play's `CertificateSet.sha256` is base64url of the raw+     * 32 bytes (its sibling `certificateHash` uses the same encoding for SHA-1 — see the+     * `08wXWKFU633Z_75SlQFnM8loIWE` style values hardcoded in the Play Store binary).+     * Returns null for anything that decodes to neither.+     */+    fun normalizeFingerprint(value: String): String? {+        val trimmed = value.trim()+        if (trimmed.length == 64 && trimmed.all { it.isDigit() || it.lowercaseChar() in 'a'..'f' }) {+            return trimmed.lowercase()+        }+        return try {+            val flags = android.util.Base64.NO_WRAP or android.util.Base64.NO_PADDING or+                android.util.Base64.URL_SAFE+            val bytes = android.util.Base64.decode(trimmed, flags)+            if (bytes.size == 32) bytes.toHex() else null+        } catch (_: Exception) {+            null+        }+    }++    /**+     * [contentsOnly] true asks "what signed these bytes" (`apkContentsSigners`); false asks+     * "what may sign for this identity" and therefore also accepts rotated ancestors.+     */+    private fun signaturesOf(info: PackageInfo?, contentsOnly: Boolean): Array<Signature> {+        val signing = info?.signingInfo ?: return emptyArray()+        val contents = signing.apkContentsSigners ?: emptyArray()+        if (contentsOnly || signing.hasMultipleSigners()) return contents+        return contents + (signing.signingCertificateHistory ?: emptyArray())+    }++    private fun fingerprints(signatures: Array<Signature>): Set<String> =+        signatures.mapNotNull { sig ->+            try {+                MessageDigest.getInstance("SHA-256").digest(sig.toByteArray()).toHex()+            } catch (_: Exception) {+                null+            }+        }.toSet()++    private fun ByteArray.toHex(): String = joinToString("") { "%02x".format(it) }+}
appstore/src/main/java/com/vayunmathur/appstore/data/security/InstallVerifier.kt
diff --git a/appstore/src/main/java/com/vayunmathur/appstore/data/security/InstallVerifier.kt b/appstore/src/main/java/com/vayunmathur/appstore/data/security/InstallVerifier.ktnew file mode 100644index 0000000000..b7712dd334--- /dev/null+++ b/appstore/src/main/java/com/vayunmathur/appstore/data/security/InstallVerifier.kt@@ -0,0 +1,213 @@+package com.vayunmathur.appstore.data.security++import android.content.Context+import com.vayunmathur.appstore.data.AppProvider+import java.io.File++/**+ * What must hold for a downloaded set of APK files before they may be handed to+ * PackageInstaller. Built per install by the caller from whatever the source could+ * authenticate; see [InstallVerifier.verify] for how each field is enforced.+ */+data class InstallRequirement(+    val expectedPackage: String,+    /**+     * Certificate fingerprints the APK must be signed by. Non-empty means authoritative:+     * a mismatch is a hard failure. Empty means the source could not tell us.+     */+    val requiredSigners: Set<String> = emptySet(),+    /**+     * Expected SHA-256 per downloaded file, keyed by file name. A file present here must+     * match; files absent from the map are not hash-checked. Play supplies one entry per+     * split via `PlayFile.sha256`; F-Droid supplies one for the single APK.+     */+    val expectedSha256: Map<String, String> = emptyMap(),+    /** Human-readable origin of [requiredSigners], for the failure message. */+    val signerOrigin: String = "",+    /**+     * Previously pinned source-stamp fingerprint for this package, if any. The APK's+     * stamp (or its rotation lineage) must include it. Only used for Play, where the+     * APK signing key belongs to Google and cannot identify the publisher.+     */+    val pinnedStamp: String? = null,+    /** Refuse to install if the APK carries no verifiable source stamp at all. */+    val requireStamp: Boolean = false,+)++sealed class VerificationResult {+    /** Every check that could be run, passed. */+    data class Verified(+        val detail: String,+        /** Stamp fingerprint to persist as this package's pin, if newly observed. */+        val stampToPin: String? = null,+    ) : VerificationResult()++    /** Nothing contradicted, but no publisher key or hash was available to check against. */+    data class Unverified(val reason: String, val stampToPin: String? = null) : VerificationResult()++    /** A check actively failed. The install must not proceed. */+    data class Rejected(val reason: String) : VerificationResult()++    val allowsInstall: Boolean get() = this !is Rejected++    val stamp: String?+        get() = when (this) {+            is Verified -> stampToPin+            is Unverified -> stampToPin+            is Rejected -> null+        }+}++/**+ * Runs the certificate and hash checks on downloaded files before install.+ *+ * Policy (chosen deliberately: block on contradiction, warn on absence):+ * - the archive must parse and declare [InstallRequirement.expectedPackage] — blocks a+ *   swapped APK being installed under a name the user thought they were getting;+ * - if the package is already installed, the new APK's signers must intersect the+ *   installed app's signer history. Android would refuse this anyway, but failing here+ *   turns a cryptic `INSTALL_FAILED_UPDATE_INCOMPATIBLE` into a stated key mismatch, and+ *   catches it before the bytes reach the system installer;+ * - a published SHA-256 must match;+ * - a published signer set must intersect the APK's actual signers;+ * - with none of the above available, the result is [VerificationResult.Unverified] and+ *   the caller may proceed with a visible warning.+ */+object InstallVerifier {++    fun verify(+        context: Context,+        files: List<File>,+        requirement: InstallRequirement,+    ): VerificationResult {+        if (files.isEmpty()) return VerificationResult.Rejected("nothing was downloaded")++        // Parse every file. Splits legitimately parse to the same package as the base.+        val parsed = files.map { file -> file to ApkCertificates.archiveInfo(context, file) }+        val unreadable = parsed.filter { (_, info) -> info == null }+        if (unreadable.size == files.size) {+            return VerificationResult.Rejected("the download is not a valid signed app file")+        }++        val declared = parsed.mapNotNull { (_, info) -> info?.packageName }.toSet()+        if (declared.isNotEmpty() && requirement.expectedPackage !in declared) {+            return VerificationResult.Rejected(+                "the download is ${declared.joinToString()}, not ${requirement.expectedPackage}"+            )+        }++        // The catalogue filters on the target SDK each source *claims*, which a source+        // may not state at all. Re-check it against the manifest we now hold, so the+        // floor holds for every install regardless of what the listing said.+        parsed.firstNotNullOfOrNull { (_, info) -> info?.applicationInfo?.targetSdkVersion }+            ?.let { target ->+                if (target < AppProvider.MIN_TARGET_SDK) {+                    return VerificationResult.Rejected(+                        "it is built for Android API $target, and this store needs " ++                            "${AppProvider.MIN_TARGET_SDK} or newer"+                    )+                }+            }++        // Signers of the bytes we actually hold. Every readable file must agree, or the+        // set is mixed and something has been substituted.+        val perFileSigners = parsed+            .filter { (_, info) -> info != null }+            .map { (file, _) -> file to ApkCertificates.apkSigners(context, file) }+        val emptySigner = perFileSigners.firstOrNull { (_, signers) -> signers.isEmpty() }+        if (emptySigner != null) {+            return VerificationResult.Rejected("${emptySigner.first.name} is not signed")+        }+        val signerSets = perFileSigners.map { (_, signers) -> signers }.toSet()+        if (signerSets.size > 1) {+            return VerificationResult.Rejected("the app's files are not all signed by the same key")+        }+        val actualSigners = signerSets.first()++        val checks = mutableListOf<String>()++        val installed = ApkCertificates.installedSigners(context, requirement.expectedPackage)+        if (installed.isNotEmpty()) {+            if (actualSigners.none { it in installed }) {+                return VerificationResult.Rejected(+                    "it is signed with a different key than the copy you have installed"+                )+            }+            checks += "same key as the installed copy"+        }++        if (requirement.expectedSha256.isNotEmpty()) {+            var hashed = 0+            for (file in files) {+                val expected = requirement.expectedSha256[file.name] ?: continue+                val actual = ApkCertificates.sha256(file)+                if (!actual.equals(expected, ignoreCase = true)) {+                    return VerificationResult.Rejected(+                        "${file.name} does not match the hash the source published"+                    )+                }+                hashed+++            }+            // A published hash set that matches nothing we downloaded means the file+            // names moved under us; treat that as a failure rather than a silent skip.+            if (hashed == 0) {+                return VerificationResult.Rejected(+                    "the published hashes do not cover any of the files that downloaded"+                )+            }+            checks += "hash matches for $hashed of ${files.size} file(s)"+        }++        if (requirement.requiredSigners.isNotEmpty()) {+            val required = requirement.requiredSigners.map { it.lowercase() }.toSet()+            if (actualSigners.none { it in required }) {+                val origin = requirement.signerOrigin.ifBlank { "the source" }+                return VerificationResult.Rejected("it is not signed by the key $origin expects")+            }+            checks += "signed by the key ${requirement.signerOrigin.ifBlank { "the source" }} expects"+        }++        // Source stamp: a second identity that survives Play App Signing re-signing.+        // Checked on the base APK — splits do not carry their own stamp.+        var stampToPin: String? = null+        if (requirement.requireStamp || requirement.pinnedStamp != null) {+            val base = baseApk(parsed, requirement.expectedPackage) ?: files.first()+            val stamp = SourceStamp.of(base)+            if (stamp == null) {+                if (requirement.requireStamp) {+                    return VerificationResult.Rejected("it carries no publisher stamp to check")+                }+                if (requirement.pinnedStamp != null) {+                    return VerificationResult.Rejected(+                        "the publisher stamp is gone, and this app had one last time"+                    )+                }+            } else {+                val pinned = requirement.pinnedStamp+                if (pinned != null && stamp.lineage.none { it.equals(pinned, true) }) {+                    return VerificationResult.Rejected(+                        "the publisher stamp changed since you installed this app"+                    )+                }+                stampToPin = stamp.current+                checks += if (pinned != null) "same publisher stamp as before" else "publisher stamp saved"+            }+        }++        if (checks.isEmpty()) {+            return VerificationResult.Unverified(+                "the source published no key or hash to check this download against",+                stampToPin,+            )+        }+        return VerificationResult.Verified(checks.joinToString("; "), stampToPin)+    }++    /** The file whose manifest declares [packageName] without a split name. */+    private fun baseApk(+        parsed: List<Pair<File, android.content.pm.PackageInfo?>>,+        packageName: String,+    ): File? = parsed.firstOrNull { (_, info) ->+        info?.packageName == packageName && info.splitNames.isNullOrEmpty()+    }?.first+}
appstore/src/main/java/com/vayunmathur/appstore/data/security/SecurityTier.kt
diff --git a/appstore/src/main/java/com/vayunmathur/appstore/data/security/SecurityTier.kt b/appstore/src/main/java/com/vayunmathur/appstore/data/security/SecurityTier.ktnew file mode 100644index 0000000000..0280fb8eab--- /dev/null+++ b/appstore/src/main/java/com/vayunmathur/appstore/data/security/SecurityTier.kt@@ -0,0 +1,142 @@+package com.vayunmathur.appstore.data.security++import androidx.annotation.StringRes+import com.vayunmathur.appstore.R+import com.vayunmathur.appstore.data.AppProvider+import com.vayunmathur.appstore.data.AppSource++/**+ * A rule the store applies to every app, whatever its source.+ *+ * Everything user-visible here is a string resource rather than a literal, because this is+ * the text that explains the store's security model and it has to be readable in the user's+ * own language to be worth anything.+ */+data class StoreRule(+    @param:StringRes val title: Int,+    @param:StringRes val detail: Int,+    /** Format arguments for [detail], when it takes any. */+    val detailArgs: List<Any> = emptyList(),+)++/**+ * Guarantees that hold for **every** install, from every source.+ *+ * These live here rather than being repeated on each tier so that a tier card only ever+ * describes what is *distinctive* about that tier. If something is true of all three, it+ * belongs in this list.+ */+object StoreGuarantees {++    val rules: List<StoreRule> = listOf(+        StoreRule(+            R.string.store_rule_modern_android_title,+            R.string.store_rule_modern_android_detail,+            listOf(AppProvider.MIN_TARGET_SDK),+        ),+        StoreRule(R.string.store_rule_signed_title, R.string.store_rule_signed_detail),+        StoreRule(R.string.store_rule_identity_title, R.string.store_rule_identity_detail),+        StoreRule(R.string.store_rule_same_key_title, R.string.store_rule_same_key_detail),+        StoreRule(R.string.store_rule_split_key_title, R.string.store_rule_split_key_detail),+        StoreRule(R.string.store_rule_precheck_title, R.string.store_rule_precheck_detail),+        StoreRule(R.string.store_rule_fail_blocks_title, R.string.store_rule_fail_blocks_detail),+        StoreRule(R.string.store_rule_updates_stay_title, R.string.store_rule_updates_stay_detail),+        StoreRule(R.string.store_rule_fixed_sources_title, R.string.store_rule_fixed_sources_detail),+    )+}++/**+ * How much a successful install can be verified, ranked by how feasible a supply-chain+ * attack against it is.+ *+ * The ranking is about **who is able to produce bytes this device will accept as an+ * update**, because that is the question that survives contact with reality once an app+ * is installed: review, scanning and store policy reduce the odds of a bad app arriving,+ * while the signing key decides who can replace a good one.+ *+ * Everything in [StoreGuarantees] applies here too and is deliberately not repeated.+ */+enum class SecurityTier {++    /**+     * Signed with the same key as this store app, checked against our own signing+     * certificate as read back from PackageManager at install time.+     */+    FIRST_PARTY,++    /**+     * F-Droid, restricted to builds F-Droid's verification server independently+     * reproduced bit-for-bit.+     */+    REPRODUCIBLE,++    /** Play, where Google holds the signing key and no publisher key exists to pin. */+    GOOGLE_PLAY;++    val rank: Int get() = ordinal + 1++    @get:StringRes+    val title: Int+        get() = when (this) {+            FIRST_PARTY -> R.string.tier_first_party_title+            REPRODUCIBLE -> R.string.tier_reproducible_title+            GOOGLE_PLAY -> R.string.tier_play_title+        }++    /** One line, shown under the badge on the app's page. */+    @get:StringRes+    val summary: Int+        get() = when (this) {+            FIRST_PARTY -> R.string.tier_first_party_summary+            REPRODUCIBLE -> R.string.tier_reproducible_summary+            GOOGLE_PLAY -> R.string.tier_play_summary+        }++    /** Who has to be compromised to push you malicious code. */+    @get:StringRes+    val threatModel: Int+        get() = when (this) {+            FIRST_PARTY -> R.string.tier_first_party_threat+            REPRODUCIBLE -> R.string.tier_reproducible_threat+            GOOGLE_PLAY -> R.string.tier_play_threat+        }++    /** Checks specific to this tier, on top of [StoreGuarantees.rules]. */+    val additionalChecks: List<Int>+        get() = when (this) {+            FIRST_PARTY -> listOf(+                R.string.tier_first_party_check_key,+                R.string.tier_first_party_check_hash,+            )+            REPRODUCIBLE -> listOf(+                R.string.tier_reproducible_check_index_signed,+                R.string.tier_reproducible_check_chained,+                R.string.tier_reproducible_check_rebuilt,+                R.string.tier_reproducible_check_hash_and_key,+            )+            GOOGLE_PLAY -> listOf(+                R.string.tier_play_check_hash,+                R.string.tier_play_check_key,+                R.string.tier_play_check_stamp,+            )+        }++    /** The honest downside of this tier. */+    @get:StringRes+    val caveat: Int+        get() = when (this) {+            FIRST_PARTY -> R.string.tier_first_party_caveat+            REPRODUCIBLE -> R.string.tier_reproducible_caveat+            GOOGLE_PLAY -> R.string.tier_play_caveat+        }++    companion object {+        fun of(source: AppSource): SecurityTier = when (source) {+            AppSource.MODERN_APPS -> FIRST_PARTY+            // Non-reproduced F-Droid packages are dropped during sync and never reach the+            // UI, so anything surviving from FDROID is tier 2 by construction.+            AppSource.FDROID -> REPRODUCIBLE+            AppSource.PLAYSTORE -> GOOGLE_PLAY+        }+    }+}
appstore/src/main/java/com/vayunmathur/appstore/data/security/SignedJarIndex.kt
diff --git a/appstore/src/main/java/com/vayunmathur/appstore/data/security/SignedJarIndex.kt b/appstore/src/main/java/com/vayunmathur/appstore/data/security/SignedJarIndex.ktnew file mode 100644index 0000000000..67b0721294--- /dev/null+++ b/appstore/src/main/java/com/vayunmathur/appstore/data/security/SignedJarIndex.kt@@ -0,0 +1,99 @@+package com.vayunmathur.appstore.data.security++import java.io.File+import java.security.cert.X509Certificate+import java.util.jar.JarFile++/**+ * Verifies an F-Droid repository index, which ships as a JAR signed with the repo's key+ * (`entry.jar` for index-v2, `index-v1.jar` for the legacy format).+ *+ * This is the check that makes everything downstream mean anything: the per-APK SHA-256+ * and `signer` fingerprints only bind the APK to the index, so an index we haven't+ * authenticated could simply state a hostile APK's own hash and key. Pinning the index+ * signing certificate is what stops a malicious mirror from rewriting both sides.+ *+ * [JarFile] with verification enabled checks the PKCS#7 signature block against the+ * per-entry digests in `META-INF/MANIFEST.MF` as entries are read — but only for entries+ * that are actually consumed, and an unsigned entry simply reports no certificates. Hence+ * [readVerified] reads the entry to completion first and treats a missing certificate as+ * a failure rather than as "unsigned but fine".+ */+object SignedJarIndex {++    class VerificationException(message: String) : Exception(message)++    data class Verified(+        val content: ByteArray,+        /** Lowercase-hex SHA-256 of the signing certificate. */+        val signerSha256: String,+    )++    /**+     * Read [entryName] out of the signed [jar], enforcing that it is covered by the JAR+     * signature. When [pinnedFingerprint] is non-null the signing certificate must match+     * it; when null the caller is doing trust-on-first-use and should persist the+     * returned [Verified.signerSha256].+     */+    fun readVerified(jar: File, entryName: String, pinnedFingerprint: String?): Verified {+        var content = ByteArray(0)+        val fingerprint = consumeVerified(jar, entryName, pinnedFingerprint) { input ->+            content = input.readBytes()+        }+        return Verified(content, fingerprint)+    }++    /**+     * Streaming form of [readVerified] for entries too large to hold in memory — the+     * full F-Droid `index-v1.json` runs to hundreds of megabytes. Writes the entry to+     * [dest] and returns the signing certificate fingerprint. [dest] is deleted if+     * verification fails, so a rejected index is never left behind to be parsed.+     */+    fun extractVerified(+        jar: File,+        entryName: String,+        pinnedFingerprint: String?,+        dest: File,+    ): String = try {+        consumeVerified(jar, entryName, pinnedFingerprint) { input ->+            dest.outputStream().use { input.copyTo(it) }+        }+    } catch (t: Throwable) {+        dest.delete()+        throw t+    }++    private fun consumeVerified(+        jar: File,+        entryName: String,+        pinnedFingerprint: String?,+        consume: (java.io.InputStream) -> Unit,+    ): String {+        JarFile(jar, true).use { jarFile ->+            if (jarFile.manifest == null) {+                throw VerificationException("Index JAR has no manifest — it is not signed")+            }+            val entry = jarFile.getJarEntry(entryName)+                ?: throw VerificationException("Index JAR does not contain $entryName")++            // Certificates are only attached once the entry has been read to completion+            // and its digest checked, so this read *is* the verification step, not just IO.+            jarFile.getInputStream(entry).use(consume)++            val certificates = entry.certificates+                ?: throw VerificationException("$entryName is not covered by the JAR signature")+            val signer = certificates.filterIsInstance<X509Certificate>().firstOrNull()+                ?: throw VerificationException("$entryName has no X.509 signer")++            val fingerprint = ApkCertificates.sha256(signer.encoded)+            if (pinnedFingerprint != null && !fingerprint.equals(pinnedFingerprint, true)) {+                throw VerificationException(+                    "Repository signing key changed: pinned " ++                        "${ApkCertificates.abbreviate(pinnedFingerprint)}, " ++                        "got ${ApkCertificates.abbreviate(fingerprint)}"+                )+            }+            return fingerprint+        }+    }+}
appstore/src/main/java/com/vayunmathur/appstore/data/security/SourceStamp.kt
diff --git a/appstore/src/main/java/com/vayunmathur/appstore/data/security/SourceStamp.kt b/appstore/src/main/java/com/vayunmathur/appstore/data/security/SourceStamp.ktnew file mode 100644index 0000000000..6e8ff4741c--- /dev/null+++ b/appstore/src/main/java/com/vayunmathur/appstore/data/security/SourceStamp.kt@@ -0,0 +1,66 @@+package com.vayunmathur.appstore.data.security++import android.util.Log+import com.android.apksig.SourceStampVerifier+import java.io.File+import java.security.cert.X509Certificate++/**+ * Reads an APK's **source stamp**.+ *+ * A source stamp is a signature block distinct from the APK signing block, carrying its+ * own certificate (`META-INF/stamp-cert-sha256` plus a v1/v2 stamp block). It matters+ * here because it **survives Play App Signing re-signing**: Google replaces the APK+ * signing key with its own, but the stamp identity persists across updates.+ *+ * That makes the stamp the only stable per-package identity available for Play apps.+ * It is worth being precise about what pinning it buys: it gives **continuity, not+ * provenance**. A change of stamp is detectable; who holds the stamp key for any given+ * Play-App-Signing app is not something the device can determine. For F-Droid and Modern+ * Apps the APK signing key itself is pinned, so the stamp is redundant there.+ *+ * Verified empirically against the Play Store's own APK, which reports+ * `Verified for SourceStamp: true` with a stamp certificate distinct from its signer.+ */+object SourceStamp {++    /**+     * @param current fingerprint of the stamp certificate this APK carries+     * @param lineage every fingerprint in the stamp's rotation lineage, including+     *   [current]. A stamp key may be rotated legitimately, and the lineage is what+     *   proves the new key descends from the pinned one.+     */+    data class Stamp(val current: String, val lineage: Set<String>)++    /** Verified source stamp of [apk], or null if it carries none. */+    fun of(apk: File): Stamp? = try {+        val result = SourceStampVerifier.Builder(apk)+            // Match the platform's own verification range. Below 24 the stamp uses the+            // v1 scheme, which apksig handles through the same entry point.+            .setMinCheckedPlatformVersion(24)+            .build()+            .verifySourceStamp()++        val info = result.sourceStampInfo+        if (!result.isVerified || info == null) {+            null+        } else {+            val current = fingerprint(info.certificate)+            val lineage = info.certificatesInLineage.orEmpty()+                .mapNotNull(::fingerprint)+                .toMutableSet()+            if (current != null) lineage += current+            if (current == null) null else Stamp(current, lineage)+        }+    } catch (t: Throwable) {+        // An absent stamp is normal and not an error; a malformed one is treated the+        // same as absent, and the caller decides whether absence is acceptable.+        Log.d(TAG, "No verifiable source stamp on ${apk.name}: ${t.message}")+        null+    }++    private fun fingerprint(cert: X509Certificate?): String? =+        cert?.let { runCatching { ApkCertificates.sha256(it.encoded) }.getOrNull() }++    private const val TAG = "SourceStamp"+}
appstore/src/main/java/com/vayunmathur/appstore/ui/AppDetailPage.kt
diff --git a/appstore/src/main/java/com/vayunmathur/appstore/ui/AppDetailPage.kt b/appstore/src/main/java/com/vayunmathur/appstore/ui/AppDetailPage.ktindex aea5e68617..20133d05e5 100644--- a/appstore/src/main/java/com/vayunmathur/appstore/ui/AppDetailPage.kt+++ b/appstore/src/main/java/com/vayunmathur/appstore/ui/AppDetailPage.kt@@ -31,9 +31,14 @@ import androidx.compose.ui.unit.dp import androidx.core.graphics.drawable.toBitmap import com.vayunmathur.library.image.compose.AsyncImage import com.vayunmathur.appstore.data.AppSource+import com.vayunmathur.appstore.data.security.SecurityTier+import com.vayunmathur.appstore.data.security.VerificationResult+import com.vayunmathur.appstore.util.AppDetailActions+import com.vayunmathur.appstore.util.AppDetailUiState import com.vayunmathur.appstore.util.AppStoreViewModel import com.vayunmathur.library.ui.AlertDialog import com.vayunmathur.library.ui.Button+import com.vayunmathur.library.ui.Card import com.vayunmathur.library.ui.CenterAlignedTopAppBar import com.vayunmathur.library.ui.FilledTonalButton import com.vayunmathur.library.ui.HorizontalDivider@@ -52,23 +57,59 @@ import com.vayunmathur.library.ui.TextButton import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.setValue +/** Binds [AppStoreViewModel] to the stateless [AppDetailScreen]. */ @Composable fun AppDetailPage(     viewModel: AppStoreViewModel,-    onBack: () -> Unit+    onBack: () -> Unit,+    onOpenTiers: () -> Unit = {}, ) {     val app by viewModel.selectedApp.collectAsState()-    val current = app ?: return+    val verificationMap by viewModel.verification.collectAsState()     val installed by viewModel.installedApps.collectAsState()-    val isInstalled = installed.any { it.packageName == current.packageName }-    val installedInfo = installed.find { it.packageName == current.packageName }     val progressMap by viewModel.downloadProgress.collectAsState()-    val progress = progressMap[current.packageName]     val icons by viewModel.installedIcons.collectAsState()-    val installedIcon = icons[current.packageName]     val syncMessage by viewModel.syncMessage.collectAsState()+    // "" can never be a real package name, so the lookups below miss harmlessly while+    // nothing is selected and the screen bails out.+    val pkg = app?.packageName.orEmpty() -    var showUninstallConfirm by remember { androidx.compose.runtime.mutableStateOf(false) }+    AppDetailScreen(+        state = AppDetailUiState(+            app = app,+            installedInfo = installed.find { it.packageName == pkg },+            verification = verificationMap[pkg],+            progress = progressMap[pkg],+            installedIcon = icons[pkg],+            syncMessage = syncMessage,+        ),+        actions = viewModel,+        onBack = onBack,+        onOpenTiers = onOpenTiers,+    )+}++/**+ * The app detail screen, with no dependency on the ViewModel so it can be rendered from a+ * `@Preview` — see `src/screenshotTest`, which is where the store listing images come from.+ */+@Composable+fun AppDetailScreen(+    state: AppDetailUiState,+    actions: AppDetailActions,+    onBack: () -> Unit = {},+    onOpenTiers: () -> Unit = {},+) {+    val current = state.app ?: return+    val tier = SecurityTier.of(current.source)+    val lastVerification = state.verification+    val installedInfo = state.installedInfo+    val isInstalled = installedInfo != null+    val progress = state.progress+    val installedIcon = state.installedIcon+    val syncMessage = state.syncMessage++    var showUninstallConfirm by remember { mutableStateOf(false) }      Scaffold(         topBar = {@@ -115,6 +156,8 @@ fun AppDetailPage(                     Text(current.name, style = MaterialTheme.typography.headlineSmall, fontWeight = FontWeight.Bold)                     current.author?.let { Text(it, style = MaterialTheme.typography.bodySmall) }                     Row(verticalAlignment = Alignment.CenterVertically) {+                        SecurityTierBadge(tier, onClick = onOpenTiers)+                        Spacer(Modifier.width(6.dp))                         SourceBadge(current.source)                         Spacer(Modifier.width(8.dp))                         if (isInstalled) {@@ -132,22 +175,63 @@ fun AppDetailPage(                 Text(stringResource(R.string.downloading, (progress * 100).toInt()), style = MaterialTheme.typography.labelSmall)             } +            // What this tier claims, and what the last install attempt actually proved.+            Card(+                onClick = onOpenTiers,+                modifier = Modifier.fillMaxWidth(),+            ) {+                Column(Modifier.padding(12.dp), verticalArrangement = Arrangement.spacedBy(4.dp)) {+                    Row(verticalAlignment = Alignment.CenterVertically) {+                        SecurityTierBadge(tier, onClick = onOpenTiers)+                        Spacer(Modifier.width(8.dp))+                        Text(+                            stringResource(tier.title),+                            style = MaterialTheme.typography.titleSmall,+                            fontWeight = FontWeight.SemiBold,+                        )+                    }+                    Text(stringResource(tier.summary), style = MaterialTheme.typography.bodySmall)+                    when (val v = lastVerification) {+                        is VerificationResult.Rejected -> Text(+                            stringResource(R.string.detail_install_blocked, v.reason),+                            style = MaterialTheme.typography.labelSmall,+                            color = MaterialTheme.colorScheme.error,+                        )+                        is VerificationResult.Verified -> Text(+                            stringResource(R.string.detail_checked_on_install, v.detail),+                            style = MaterialTheme.typography.labelSmall,+                            color = MaterialTheme.colorScheme.primary,+                        )+                        is VerificationResult.Unverified -> Text(+                            stringResource(R.string.detail_installed_unverified, v.reason),+                            style = MaterialTheme.typography.labelSmall,+                            color = MaterialTheme.colorScheme.error,+                        )+                        null -> Text(+                            stringResource(R.string.detail_tap_for_tier),+                            style = MaterialTheme.typography.labelSmall,+                            color = MaterialTheme.colorScheme.onSurfaceVariant,+                        )+                    }+                }+            }+             // Action row redesigned per plan: Open + Uninstall for installed, Install/Update for others             Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {                 when {                     isInstalled && current.versionCode > (installedInfo?.versionCode ?: 0L) -> {-                        Button(onClick = { viewModel.downloadAndInstall(current) }, modifier = Modifier.weight(1f), enabled = progress == null) {+                        Button(onClick = { actions.downloadAndInstall(current) }, modifier = Modifier.weight(1f), enabled = progress == null) {                             IconDownload()                             Spacer(Modifier.width(6.dp))                             Text(if (progress != null) "Downloading ${(progress * 100).toInt()}%" else "Update")                         }-                        FilledTonalButton(onClick = { viewModel.openApp(current.packageName) }, modifier = Modifier.weight(1f)) {+                        FilledTonalButton(onClick = { actions.openApp(current.packageName) }, modifier = Modifier.weight(1f)) {                             Text(stringResource(R.string.open))                         }                         OutlinedButton(onClick = { showUninstallConfirm = true }) { IconDelete() }                     }                     isInstalled -> {-                        FilledTonalButton(onClick = { viewModel.openApp(current.packageName) }, modifier = Modifier.weight(1f)) {+                        FilledTonalButton(onClick = { actions.openApp(current.packageName) }, modifier = Modifier.weight(1f)) {                             Text(stringResource(R.string.open))                         }                         OutlinedButton(onClick = { showUninstallConfirm = true }, modifier = Modifier.weight(1f)) {@@ -158,7 +242,7 @@ fun AppDetailPage(                     }                     current.source == AppSource.PLAYSTORE -> {                         Button(-                            onClick = { viewModel.downloadAndInstall(current) },+                            onClick = { actions.downloadAndInstall(current) },                             modifier = Modifier.weight(1f),                             enabled = progress == null                         ) {@@ -166,13 +250,13 @@ fun AppDetailPage(                             Spacer(Modifier.width(6.dp))                             Text(if (progress != null) "Downloading ${(progress * 100).toInt()}%" else "Install")                         }-                        OutlinedButton(onClick = { viewModel.openInPlayStore(current.packageName) }) {+                        OutlinedButton(onClick = { actions.openInPlayStore(current.packageName) }) {                             IconShoppingCart()                         }                     }                     else -> {                         Button(-                            onClick = { viewModel.downloadAndInstall(current) },+                            onClick = { actions.downloadAndInstall(current) },                             modifier = Modifier.weight(1f),                             enabled = progress == null                         ) {@@ -185,7 +269,7 @@ fun AppDetailPage(                 // Globe button remains for website/source when not already handling installed actions                 if (!isInstalled && (current.source == AppSource.FDROID || current.website != null)) {                     OutlinedButton(onClick = {-                        viewModel.openInBrowser(current.website ?: current.sourceCode ?: "")+                        actions.openInBrowser(current.website ?: current.sourceCode ?: "")                     }) { IconGlobe() }                 }             }@@ -193,14 +277,14 @@ fun AppDetailPage(             // For Play installed, also show View in Play Store as secondary             if (isInstalled && current.source == AppSource.PLAYSTORE) {                 Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {-                    OutlinedButton(onClick = { viewModel.openInPlayStore(current.packageName) }, modifier = Modifier.weight(1f)) {+                    OutlinedButton(onClick = { actions.openInPlayStore(current.packageName) }, modifier = Modifier.weight(1f)) {                         IconShoppingCart()                         Spacer(Modifier.width(6.dp))                         Text(stringResource(R.string.view_in_play_store))                     }                     if (current.website != null || current.sourceCode != null) {                         OutlinedButton(onClick = {-                            viewModel.openInBrowser(current.website ?: current.sourceCode ?: "")+                            actions.openInBrowser(current.website ?: current.sourceCode ?: "")                         }) { IconGlobe() }                     }                 }@@ -224,8 +308,8 @@ fun AppDetailPage(                 if (current.categories.isNotEmpty()) DetailRow("Categories", current.categories.joinToString(", "))                 current.sourceCode?.let { DetailRow("Source", it) }                 current.website?.let { DetailRow("Website", it) }-                if (current.antiFeatures.isNotEmpty()) DetailRow("Anti-Features", current.antiFeatures.joinToString(", "))-                current.whatsNew?.let { if (it.isNotBlank()) DetailRow("What's New", it) }+                if (current.antiFeatures.isNotEmpty()) DetailRow("Anti-features", current.antiFeatures.joinToString(", "))+                current.whatsNew?.let { if (it.isNotBlank()) DetailRow("What's new", it) }             }         }     }@@ -238,7 +322,7 @@ fun AppDetailPage(             confirmButton = {                 Button(onClick = {                     showUninstallConfirm = false-                    viewModel.uninstallApp(current.packageName)+                    actions.uninstallApp(current.packageName)                 }) { Text(stringResource(R.string.uninstall)) }             },             dismissButton = {
appstore/src/main/java/com/vayunmathur/appstore/ui/BrowsePage.kt
diff --git a/appstore/src/main/java/com/vayunmathur/appstore/ui/BrowsePage.kt b/appstore/src/main/java/com/vayunmathur/appstore/ui/BrowsePage.ktindex a0e1408fc9..b829ab0640 100644--- a/appstore/src/main/java/com/vayunmathur/appstore/ui/BrowsePage.kt+++ b/appstore/src/main/java/com/vayunmathur/appstore/ui/BrowsePage.kt@@ -28,6 +28,7 @@ import androidx.core.graphics.drawable.toBitmap import com.vayunmathur.library.image.compose.AsyncImage import com.vayunmathur.appstore.data.AppSource import com.vayunmathur.appstore.data.UnifiedApp+import com.vayunmathur.appstore.data.security.SecurityTier import com.vayunmathur.library.ui.Card import com.vayunmathur.library.ui.CardDefaults import com.vayunmathur.library.ui.LinearProgressIndicator@@ -89,6 +90,8 @@ fun AppRow(                             modifier = Modifier.weight(1f, fill = false)                         )                         Spacer(Modifier.width(6.dp))+                        SecurityTierBadge(SecurityTier.of(app.source))+                        Spacer(Modifier.width(4.dp))                         SourceBadge(app.source)                     }                     if (app.summary.isNotBlank()) {@@ -121,10 +124,12 @@ fun AppRow( @Composable fun SourceBadge(source: AppSource) {     val label = when (source) {+        AppSource.MODERN_APPS -> "Modern Apps"         AppSource.FDROID -> "F-Droid"         AppSource.PLAYSTORE -> "Play Store"     }     val color = when (source) {+        AppSource.MODERN_APPS -> MaterialTheme.colorScheme.tertiaryContainer         AppSource.FDROID -> MaterialTheme.colorScheme.primaryContainer         AppSource.PLAYSTORE -> MaterialTheme.colorScheme.secondaryContainer     }@@ -132,3 +137,39 @@ fun SourceBadge(source: AppSource) {         Text(label, style = MaterialTheme.typography.labelSmall, modifier = Modifier.padding(horizontal = 6.dp, vertical = 2.dp))     } }++/**+ * "Tier 1" / "Tier 2" / "Tier 3" next to the source badge. Tapping opens+ * [SecurityTiersPage], which explains what each tier is actually claiming.+ */+@Composable+fun SecurityTierBadge(tier: SecurityTier, onClick: (() -> Unit)? = null) {+    // Tier 3 is neutral, not red: a Play install still passes every check the platform+    // makes possible, so an alarm colour would overstate the difference.+    val container = when (tier) {+        SecurityTier.FIRST_PARTY -> MaterialTheme.colorScheme.tertiary+        SecurityTier.REPRODUCIBLE -> MaterialTheme.colorScheme.primary+        SecurityTier.GOOGLE_PLAY -> MaterialTheme.colorScheme.surfaceVariant+    }+    val content = when (tier) {+        SecurityTier.FIRST_PARTY -> MaterialTheme.colorScheme.onTertiary+        SecurityTier.REPRODUCIBLE -> MaterialTheme.colorScheme.onPrimary+        SecurityTier.GOOGLE_PLAY -> MaterialTheme.colorScheme.onSurfaceVariant+    }+    val colors = CardDefaults.cardColors(containerColor = container, contentColor = content)+    if (onClick != null) {+        Card(onClick = onClick, colors = colors) { TierLabel(tier) }+    } else {+        Card(colors = colors) { TierLabel(tier) }+    }+}++@Composable+private fun TierLabel(tier: SecurityTier) {+    Text(+        stringResource(R.string.tier_badge_label, tier.rank),+        style = MaterialTheme.typography.labelSmall,+        fontWeight = FontWeight.Bold,+        modifier = Modifier.padding(horizontal = 6.dp, vertical = 2.dp),+    )+}
appstore/src/main/java/com/vayunmathur/appstore/ui/InstalledPage.kt
diff --git a/appstore/src/main/java/com/vayunmathur/appstore/ui/InstalledPage.kt b/appstore/src/main/java/com/vayunmathur/appstore/ui/InstalledPage.ktindex 67ed77aef1..dc5effe42d 100644--- a/appstore/src/main/java/com/vayunmathur/appstore/ui/InstalledPage.kt+++ b/appstore/src/main/java/com/vayunmathur/appstore/ui/InstalledPage.kt@@ -7,37 +7,26 @@ import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.Row-import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth-import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding-import androidx.compose.foundation.layout.width import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.LazyRow import androidx.compose.foundation.lazy.items import androidx.compose.runtime.Composable import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue-import androidx.compose.runtime.mutableStateOf-import androidx.compose.runtime.remember-import androidx.compose.runtime.setValue-import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.unit.dp import com.vayunmathur.appstore.data.AppSource import com.vayunmathur.appstore.data.UnifiedApp import com.vayunmathur.appstore.util.AppStoreViewModel import com.vayunmathur.appstore.util.InstalledFilter-import com.vayunmathur.library.ui.AlertDialog import com.vayunmathur.library.ui.Button import com.vayunmathur.library.ui.FilterChip-import com.vayunmathur.library.ui.IconDelete-import com.vayunmathur.library.ui.IconButton import com.vayunmathur.library.ui.MaterialTheme import com.vayunmathur.library.ui.Scaffold import com.vayunmathur.library.ui.Text-import com.vayunmathur.library.ui.TextButton import com.vayunmathur.library.ui.TopAppBar  @Composable@@ -50,9 +39,9 @@ fun InstalledPage(     val srcMap by viewModel.installedSourceMap.collectAsState()     val filteredInstalled by viewModel.filteredInstalled.collectAsState()     val filter by viewModel.installedFilter.collectAsState()-    var confirmPkg by remember { mutableStateOf<String?>(null) }      val allCount = srcMap.size+    val modernCount = srcMap.values.count { it == AppSource.MODERN_APPS }     val fdroidCount = srcMap.values.count { it == AppSource.FDROID }     val playCount = srcMap.values.count { it == AppSource.PLAYSTORE } @@ -91,6 +80,13 @@ fun InstalledPage(                         label = { Text(stringResource(R.string.all, allCount)) }                     )                 }+                item {+                    FilterChip(+                        selected = filter == InstalledFilter.MODERN_APPS,+                        onClick = { viewModel.setInstalledFilter(InstalledFilter.MODERN_APPS) },+                        label = { Text(stringResource(R.string.modern_apps, modernCount)) }+                    )+                }                 item {                     FilterChip(                         selected = filter == InstalledFilter.FDROID,@@ -115,49 +111,28 @@ fun InstalledPage(                 if (apps.isEmpty()) {                     item {                         Text(-                            if (allCount == 0) "No installed apps found in F-Droid or Play Store. Sync repos to populate F-Droid."-                            else "No apps match this filter",+                            if (allCount == 0) "None of your apps were found in these sources yet. Try syncing in Sources."+                            else "Nothing matches this filter",                             style = MaterialTheme.typography.bodyMedium,                             modifier = Modifier.padding(16.dp)                         )                     }                 } else {+                    // Uninstall lives only on the app's own page — a delete button next to+                    // every row in a long list is too easy to hit by accident.                     items(apps, key = { it.packageName }) { app ->-                        Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) {-                            androidx.compose.foundation.layout.Box(Modifier.weight(1f)) {-                                AppRow(-                                    app = app,-                                    isInstalled = true,-                                    progress = null,-                                    installedIcon = icons[app.packageName],-                                    onClick = { onAppClick(app) }-                                )-                            }-                            Spacer(Modifier.width(4.dp))-                            IconButton(onClick = { confirmPkg = app.packageName }) { IconDelete() }-                        }+                        AppRow(+                            app = app,+                            isInstalled = true,+                            progress = null,+                            installedIcon = icons[app.packageName],+                            onClick = { onAppClick(app) }+                        )                     }                 }             }         }     }--    confirmPkg?.let { pkg ->-        AlertDialog(-            onDismissRequest = { confirmPkg = null },-            title = { Text(stringResource(R.string.uninstall_2)) },-            text = { Text(stringResource(R.string.uninstall_you_can_reinstall_from_the_sto, pkg)) },-            confirmButton = {-                Button(onClick = {-                    confirmPkg = null-                    viewModel.uninstallApp(pkg)-                }) { Text(stringResource(R.string.uninstall)) }-            },-            dismissButton = {-                TextButton(onClick = { confirmPkg = null }) { Text(stringResource(R.string.cancel)) }-            }-        )-    } }  @Composable
appstore/src/main/java/com/vayunmathur/appstore/ui/ReposPage.kt
diff --git a/appstore/src/main/java/com/vayunmathur/appstore/ui/ReposPage.kt b/appstore/src/main/java/com/vayunmathur/appstore/ui/ReposPage.ktindex 6eac1ae9f4..d3391a325d 100644--- a/appstore/src/main/java/com/vayunmathur/appstore/ui/ReposPage.kt+++ b/appstore/src/main/java/com/vayunmathur/appstore/ui/ReposPage.kt@@ -11,47 +11,42 @@ import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.layout.width import androidx.compose.foundation.lazy.LazyColumn-import androidx.compose.foundation.lazy.items import androidx.compose.runtime.Composable import androidx.compose.runtime.collectAsState import androidx.compose.runtime.get

Diff truncated.