Modern Apps git

← Modern-Apps.git

appstore: add Accrescent as an app source with signed-allowlist trust and gRPC listings/installs

Commit
5fc54d10a29efcccda4d5a42bbb9bee3a66aa74c
Author
Vayun Mathur <[email protected]>
When
2026-08-11 17:51 UTC (3 months ago)
Parents
cee3c1c

Diff

appstore/build.gradle.kts
diff --git a/appstore/build.gradle.kts b/appstore/build.gradle.ktsindex d826ce45a6..c59a3d688c 100644--- a/appstore/build.gradle.kts+++ b/appstore/build.gradle.kts@@ -4,6 +4,10 @@ plugins {     // instrumented test on a device. Same `:appstore:metadata` task name either way.     id("common-conventions-preview-metadata")     alias(libs.plugins.ksp)+    // gRPC/protobuf codegen for the Accrescent app source (data/accrescent). The .proto+    // schemas are vendored under src/main/proto (see the note there); protoc + the grpc+    // plugins generate the message + coroutine-stub classes at build time.+    alias(libs.plugins.protobuf) }  launcherIcon {@@ -14,6 +18,20 @@ android {     defaultConfig {         applicationId = "com.vayunmathur.appstore"     }+    packaging {+        resources {+            // grpc-okhttp (first okhttp in the repo) and grpc pull in several duplicated+            // license / service-loader descriptors that collide during Java-resource merge.+            excludes += setOf(+                "META-INF/DEPENDENCIES",+                "META-INF/INDEX.LIST",+                "META-INF/io.netty.versions.properties",+                "META-INF/*.kotlin_module",+            )+            // grpc discovers transports via META-INF/services; keep those descriptors.+            merges += setOf("META-INF/services/io.grpc.**")+        }+    } }  dependencies {@@ -30,4 +48,45 @@ dependencies {     // HttpURLConnection-based PlayHttpClient/AnonymousAuthRepository/PlayDownloader – no okhttp     implementation(libs.kotlinx.serialization.json)     implementation(libs.auroraoss.gplayapi)++    // --- Accrescent app source -------------------------------------------------------+    // gRPC (appstore-api.accrescent.app) over grpc-okhttp, with protobuf-lite messages and+    // grpc-kotlin coroutine stubs. This is the first okhttp/grpc/protobuf-full surface in+    // the store, which otherwise uses HttpURLConnection only — accepted deliberately, see+    // the plan. grpc-okhttp transitively pulls okhttp/okio.+    implementation(libs.grpc.okhttp)+    implementation(libs.grpc.protobuf.lite)+    implementation(libs.grpc.stub)+    implementation(libs.grpc.kotlin.stub)+    implementation(libs.protobuf.javalite)+    implementation(libs.protobuf.kotlin.lite)+    // grpc-java generated stubs reference @javax.annotation.Generated, absent on Android.+    compileOnly(libs.javax.annotation.api)+    // ed25519 verification of Accrescent's signify-signed repodata allowlist.+    implementation(libs.bouncycastle.bcprov)+}++protobuf {+    protoc {+        artifact = "com.google.protobuf:protoc:${libs.versions.protobufJavalite.get()}"+    }+    plugins {+        create("grpc") {+            artifact = libs.grpc.protoc.gen.java.get().toString()+        }+        create("grpckt") {+            artifact = "${libs.grpc.protoc.gen.kotlin.get()}:jdk8@jar"+        }+    }+    generateProtoTasks {+        all().forEach { task ->+            task.builtins {+                create("java") { option("lite") }+            }+            task.plugins {+                create("grpc") { option("lite") }+                create("grpckt")+            }+        }+    } }
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 32a518c82b..f632d9803e 100644--- a/appstore/src/main/java/com/vayunmathur/appstore/data/AppDatabase.kt+++ b/appstore/src/main/java/com/vayunmathur/appstore/data/AppDatabase.kt@@ -172,6 +172,48 @@ interface PinnedStampDao {     suspend fun deleteByPackage(pkg: String) } +/**+ * One entry of Accrescent's ed25519-signed allowlist, cached in Room.+ *+ * This is the trust anchor for an Accrescent install: [signingCertHash] is the certificate the+ * app's APK must be signed with (lowercase-hex SHA-256 of the cert DER, the same encoding the+ * rest of the store uses), and [minVersionCode] is the oldest version that may be installed+ * (rollback protection). Populated only from a verified [com.vayunmathur.appstore.data.accrescent.RepoData];+ * see [com.vayunmathur.appstore.data.accrescent.AccrescentTrustStore].+ */+@Entity+data class AccrescentTrustEntity(+    @PrimaryKey val appId: String,+    val signingCertHash: String,+    val minVersionCode: Long,+)++@Dao+interface AccrescentTrustDao {+    @Query("SELECT * FROM AccrescentTrustEntity WHERE appId = :appId LIMIT 1")+    suspend fun byId(appId: String): AccrescentTrustEntity?++    @Query("SELECT appId FROM AccrescentTrustEntity")+    suspend fun allIds(): List<String>++    @Query("DELETE FROM AccrescentTrustEntity")+    suspend fun clearAll()++    @Upsert+    suspend fun upsertAll(entries: List<AccrescentTrustEntity>)++    /**+     * Replace the whole allowlist atomically. The signed repodata is authoritative in full —+     * an app id it no longer lists must stop being trusted — so this clears first, in one+     * transaction, rather than merging.+     */+    @androidx.room.Transaction+    suspend fun replaceAll(entries: List<AccrescentTrustEntity>) {+        clearAll()+        upsertAll(entries)+    }+}+ @Dao interface RepoDao {     @Query("SELECT * FROM RepoEntity ORDER BY name ASC")@@ -268,14 +310,20 @@ interface CachedAppDao { }  @Database(-    entities = [RepoEntity::class, CachedAppEntity::class, PinnedStampEntity::class],-    version = 6,+    entities = [+        RepoEntity::class,+        CachedAppEntity::class,+        PinnedStampEntity::class,+        AccrescentTrustEntity::class,+    ],+    version = 7,     exportSchema = false ) abstract class AppDatabase : RoomDatabase() {     abstract fun repoDao(): RepoDao     abstract fun cachedAppDao(): CachedAppDao     abstract fun pinnedStampDao(): PinnedStampDao+    abstract fun accrescentTrustDao(): AccrescentTrustDao      companion object {         val migrations = listOf(@@ -333,6 +381,19 @@ abstract class AppDatabase : RoomDatabase() {                     // predate the badge; the next sync repopulates it. Default false.                     db.execSQL("ALTER TABLE CachedAppEntity ADD COLUMN reproducible INTEGER NOT NULL DEFAULT 0")                 }+            },+            object : Migration(6, 7) {+                override fun migrate(db: SupportSQLiteDatabase) {+                    // Accrescent's signed allowlist, cached as a trust anchor. Empty until the+                    // first repodata fetch verifies and populates it; nothing installs from+                    // Accrescent until then, which is the intended fail-closed default.+                    db.execSQL(+                        "CREATE TABLE IF NOT EXISTS AccrescentTrustEntity (" ++                            "appId TEXT NOT NULL PRIMARY KEY, " ++                            "signingCertHash TEXT NOT NULL, " ++                            "minVersionCode 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 dd440a783c..5e633f2416 100644--- a/appstore/src/main/java/com/vayunmathur/appstore/data/AppModels.kt+++ b/appstore/src/main/java/com/vayunmathur/appstore/data/AppModels.kt@@ -12,7 +12,17 @@ enum class AppSource {      * download + PackageInstaller path, never Google Play.      */     GRAPHENEOS,-    PLAYSTORE+    PLAYSTORE,++    /**+     * Accrescent (accrescent.app). Listings and per-device split download URLs come from+     * Accrescent's gRPC API (appstore-api.accrescent.app); the trust anchor is a separate+     * ed25519-signed allowlist (repo.accrescent.app/repodata) that records each app's expected+     * signing certificate and minimum version code. Installs go through the store's ordinary+     * verify-then-commit path with those values, plus the new min-version gate. See+     * [com.vayunmathur.appstore.data.accrescent.AccrescentRepository].+     */+    ACCRESCENT }  data class UnifiedApp(
appstore/src/main/java/com/vayunmathur/appstore/data/UpdateCheckWorker.kt
diff --git a/appstore/src/main/java/com/vayunmathur/appstore/data/UpdateCheckWorker.kt b/appstore/src/main/java/com/vayunmathur/appstore/data/UpdateCheckWorker.ktindex f639d4d7a9..cba998f247 100644--- a/appstore/src/main/java/com/vayunmathur/appstore/data/UpdateCheckWorker.kt+++ b/appstore/src/main/java/com/vayunmathur/appstore/data/UpdateCheckWorker.kt@@ -25,6 +25,7 @@ import androidx.work.WorkerParameters import com.vayunmathur.appstore.MainActivity import com.vayunmathur.appstore.R import com.vayunmathur.appstore.data.installer.InstallCoordinator+import com.vayunmathur.appstore.data.accrescent.AccrescentRepository import com.vayunmathur.appstore.data.play.PlayRepository import com.vayunmathur.appstore.data.security.ApkCertificates import com.vayunmathur.library.network.NetworkClient@@ -66,6 +67,7 @@ class UpdateCheckWorker(         val catalog = CatalogRepository(context, db, scope)         val installedRepo = InstalledAppsRepository(context)         val play = PlayRepository(context)+        val accrescent = AccrescentRepository(context, db)          catalog.sync()         installedRepo.refresh()@@ -82,7 +84,26 @@ class UpdateCheckWorker(             remote[inst.packageName]?.takeIf { it.versionCode > inst.versionCode }         } -        val updates = (fromCatalog + fromPlay).distinctBy { it.packageName }+        // Accrescent: refresh its signed allowlist, then ask its API for a newer build of each+        // installed package it vouches for. Auto-install still routes through InstallCoordinator,+        // which re-verifies signer + min-version before committing.+        accrescent.refreshRepoData()+        val accrescentIds = accrescent.appIds()+        val fromAccrescent = installed+            .filter { it.packageName in accrescentIds }+            .mapNotNull { inst ->+                val update = runCatching {+                    accrescent.updateInfo(inst.packageName, inst.versionCode)+                }.getOrNull() ?: return@mapNotNull null+                val details = accrescent.details(inst.packageName) ?: UnifiedApp(+                    packageName = inst.packageName,+                    source = AppSource.ACCRESCENT,+                    name = inst.packageName.substringAfterLast('.'),+                )+                details.copy(versionCode = update.versionCode, versionName = update.versionName)+            }++        val updates = (fromCatalog + fromPlay + fromAccrescent).distinctBy { it.packageName }          val settings = SettingsRepository(context, scope)         val autoInstall = settings.readAutoInstallUpdates()@@ -95,7 +116,7 @@ class UpdateCheckWorker(         if (autoInstall && silentCapable && updates.isNotEmpty()) {             val eligible = updates.filter { canSilentlyUpdate(it.packageName) }             if (eligible.isNotEmpty()) {-                autoInstall(eligible, db, play)+                autoInstall(eligible, db, play, accrescent)                 installedRepo.refresh()             }             // Only nag about the updates we could not apply on our own.@@ -105,6 +126,7 @@ class UpdateCheckWorker(             notifyIfChanged(updates.map { it.packageName }.toSortedSet(), updates.size)         } +        accrescent.shutdown()         scope.cancel()         Result.success()     } catch (e: Exception) {@@ -167,12 +189,18 @@ class UpdateCheckWorker(      * confirmed each package will install without a prompt; the caller only reaches here      * when the user's silent-install toggle is on.      */-    private suspend fun autoInstall(apps: List<UnifiedApp>, db: AppDatabase, play: PlayRepository) {+    private suspend fun autoInstall(+        apps: List<UnifiedApp>,+        db: AppDatabase,+        play: PlayRepository,+        accrescent: AccrescentRepository,+    ) {         runCatching { setForeground(installingForegroundInfo(apps.size)) }         val installer = InstallCoordinator(             context = context,             db = db,             play = play,+            accrescent = accrescent,             ownSigningCertificates = { ApkCertificates.selfSigners(context) },             backgroundUpdateInstall = { true },         )
appstore/src/main/java/com/vayunmathur/appstore/data/accrescent/AccrescentApi.kt
diff --git a/appstore/src/main/java/com/vayunmathur/appstore/data/accrescent/AccrescentApi.kt b/appstore/src/main/java/com/vayunmathur/appstore/data/accrescent/AccrescentApi.ktnew file mode 100644index 0000000000..b47bcdbc28--- /dev/null+++ b/appstore/src/main/java/com/vayunmathur/appstore/data/accrescent/AccrescentApi.kt@@ -0,0 +1,136 @@+package com.vayunmathur.appstore.data.accrescent++import app.accrescent.appstore.v1.AppDownloadInfo+import app.accrescent.appstore.v1.AppListing+import app.accrescent.appstore.v1.AppServiceGrpcKt+import app.accrescent.appstore.v1.AppUpdateInfo+import app.accrescent.appstore.v1.GetAppDownloadInfoRequest+import app.accrescent.appstore.v1.GetAppListingRequest+import app.accrescent.appstore.v1.GetAppPackageInfoRequest+import app.accrescent.appstore.v1.GetAppUpdateInfoRequest+import app.accrescent.appstore.v1.ListAppListingsRequest+import app.accrescent.appstore.v1.ListAppListingsResponse+import app.accrescent.appstore.v1.PackageInfo+import io.grpc.ManagedChannel+import io.grpc.Status+import io.grpc.StatusException+import io.grpc.StatusRuntimeException+import io.grpc.okhttp.OkHttpChannelBuilder+import java.util.concurrent.TimeUnit++/** The device this app runs on cannot install the requested Accrescent app (FAILED_PRECONDITION). */+class IncompatibleDeviceException(message: String) : Exception(message)++/** Accrescent's API does not list the requested app id (NOT_FOUND). */+class AccrescentNotFoundException(message: String) : Exception(message)++/**+ * Thin coroutine wrapper over Accrescent's gRPC `AppService`.+ *+ * The channel talks to [AccrescentRepo.APP_STORE_API_DOMAIN] over TLS on 443. TLS here is not+ * the security boundary — the ed25519-signed repodata and the on-device APK signature ++ * min-version checks are — so it uses system trust via grpc-okhttp rather than a pinned factory.+ * This is the first okhttp/grpc surface in the store; everything else uses HttpURLConnection.+ *+ * gRPC status codes are mapped to intent-revealing exceptions so callers can distinguish+ * "incompatible device" and "no such app" from a generic failure.+ */+class AccrescentApi {++    @Volatile+    private var channelRef: ManagedChannel? = null++    private fun stub(): AppServiceGrpcKt.AppServiceCoroutineStub =+        AppServiceGrpcKt.AppServiceCoroutineStub(channel())++    private fun channel(): ManagedChannel {+        channelRef?.let { if (!it.isShutdown && !it.isTerminated) return it }+        return synchronized(this) {+            channelRef?.let { if (!it.isShutdown && !it.isTerminated) return it }+            OkHttpChannelBuilder+                .forAddress(AccrescentRepo.APP_STORE_API_DOMAIN, 443)+                .useTransportSecurity()+                .build()+                .also { channelRef = it }+        }+    }++    suspend fun listAppListings(+        pageSize: Int,+        pageToken: String,+        preferredLanguages: List<String>,+    ): ListAppListingsResponse = call {+        val request = ListAppListingsRequest.newBuilder()+            .setPageSize(pageSize)+            .addAllPreferredLanguages(preferredLanguages)+        // page_token is a proto3 `optional` field: setting it to "" marks it present, and the+        // server rejects an empty-but-present token ("provided page token is invalid"). Only set+        // it for continuation requests so the initial request omits it entirely.+        if (pageToken.isNotEmpty()) request.pageToken = pageToken+        stub().listAppListings(request.build())+    }++    suspend fun getAppListing(appId: String, preferredLanguages: List<String>): AppListing = call {+        stub().getAppListing(+            GetAppListingRequest.newBuilder()+                .setAppId(appId)+                .addAllPreferredLanguages(preferredLanguages)+                .build()+        ).listing+    }++    suspend fun getAppPackageInfo(appId: String): PackageInfo = call {+        stub().getAppPackageInfo(+            GetAppPackageInfoRequest.newBuilder().setAppId(appId).build()+        ).packageInfo+    }++    suspend fun getAppDownloadInfo(+        appId: String,+        deviceAttributes: app.accrescent.appstore.v1.DeviceAttributes,+    ): AppDownloadInfo = call {+        stub().getAppDownloadInfo(+            GetAppDownloadInfoRequest.newBuilder()+                .setAppId(appId)+                .setDeviceAttributes(deviceAttributes)+                .build()+        ).appDownloadInfo+    }++    /** Null when the app is up to date (the response's update-info field is absent). */+    suspend fun getAppUpdateInfo(+        appId: String,+        deviceAttributes: app.accrescent.appstore.v1.DeviceAttributes,+        baseVersionCode: Long,+    ): AppUpdateInfo? = call {+        val response = stub().getAppUpdateInfo(+            GetAppUpdateInfoRequest.newBuilder()+                .setAppId(appId)+                .setDeviceAttributes(deviceAttributes)+                .setBaseVersionCode(baseVersionCode)+                .build()+        )+        if (response.hasAppUpdateInfo()) response.appUpdateInfo else null+    }++    fun shutdown() {+        runCatching { channelRef?.shutdown()?.awaitTermination(2, TimeUnit.SECONDS) }+        channelRef = null+    }++    private suspend inline fun <T> call(block: () -> T): T = try {+        block()+    } catch (e: StatusException) {+        throw mapStatus(e.status, e)+    } catch (e: StatusRuntimeException) {+        throw mapStatus(e.status, e)+    }++    private fun mapStatus(status: Status, cause: Exception): Exception = when (status.code) {+        Status.Code.FAILED_PRECONDITION ->+            IncompatibleDeviceException(status.description ?: "device is not compatible")+        Status.Code.NOT_FOUND ->+            AccrescentNotFoundException(status.description ?: "app not found")+        else -> cause+    }+}
appstore/src/main/java/com/vayunmathur/appstore/data/accrescent/AccrescentRepo.kt
diff --git a/appstore/src/main/java/com/vayunmathur/appstore/data/accrescent/AccrescentRepo.kt b/appstore/src/main/java/com/vayunmathur/appstore/data/accrescent/AccrescentRepo.ktnew file mode 100644index 0000000000..69c793410d--- /dev/null+++ b/appstore/src/main/java/com/vayunmathur/appstore/data/accrescent/AccrescentRepo.kt@@ -0,0 +1,31 @@+package com.vayunmathur.appstore.data.accrescent++/**+ * Fixed trust anchors for the Accrescent source, mirroring Accrescent's own client+ * (`app/src/main/java/app/accrescent/client/data/Constants.kt`).+ *+ * These are the only values this store takes on faith for Accrescent: the repodata host,+ * the gRPC API host, and — the actual root of trust — the ed25519 public key the signed+ * allowlist ([AccrescentRepoData]) must verify against. Everything else (names, icons,+ * download URLs) comes from the gRPC API and is treated as untrusted metadata; the security+ * decision is made from the signed repodata plus on-device APK signature + min-version checks.+ */+object AccrescentRepo {+    const val REPOSITORY_URL = "https://repo.accrescent.app"+    const val APP_STORE_API_DOMAIN = "appstore-api.accrescent.app"++    /** signify-format ed25519 public key the repodata signature is verified against. */+    const val REPODATA_PUBKEY = "RWT8aZ/NdUmXCPqQ0we7UyCe34q1xRfncBFVK5dI3ok9BkL1bFF3mgh3"++    const val REPODATA_VERSION = 1++    /** repodata.<version>.json / .sig. */+    val REPODATA_JSON_URL = "$REPOSITORY_URL/repodata.$REPODATA_VERSION.json"+    val REPODATA_SIG_URL = "$REPOSITORY_URL/repodata.$REPODATA_VERSION.json.sig"++    /**+     * Anti-rollback floor: the store refuses any repodata whose timestamp is older than this,+     * even on first run when nothing is stored yet. Matches Accrescent's `MIN_TIMESTAMP`.+     */+    const val MIN_TIMESTAMP = 1761251784L+}
appstore/src/main/java/com/vayunmathur/appstore/data/accrescent/AccrescentRepoData.kt
diff --git a/appstore/src/main/java/com/vayunmathur/appstore/data/accrescent/AccrescentRepoData.kt b/appstore/src/main/java/com/vayunmathur/appstore/data/accrescent/AccrescentRepoData.ktnew file mode 100644index 0000000000..0bdd37e6d9--- /dev/null+++ b/appstore/src/main/java/com/vayunmathur/appstore/data/accrescent/AccrescentRepoData.kt@@ -0,0 +1,107 @@+package com.vayunmathur.appstore.data.accrescent++import android.content.Context+import android.util.Log+import androidx.datastore.preferences.core.edit+import androidx.datastore.preferences.core.longPreferencesKey+import androidx.datastore.preferences.preferencesDataStore+import com.vayunmathur.library.network.NetworkClient+import kotlinx.coroutines.flow.first+import kotlinx.serialization.SerialName+import kotlinx.serialization.Serializable+import kotlinx.serialization.json.Json++private val Context.accrescentDataStore by preferencesDataStore(name = "accrescent_repodata")+private val REPODATA_TIMESTAMP_KEY = longPreferencesKey("repodata_timestamp")++/**+ * The signed Accrescent allowlist (`repodata.N.json`).+ *+ * This is a pure trust anchor: for each legitimate app id it states the certificate its APK+ * must be signed with and the minimum version code that may be installed, plus a monotonic+ * [timestamp] for rollback protection. It carries no names, icons, descriptions or download+ * URLs — those come from the (untrusted) gRPC API.+ */+@Serializable+data class RepoData(+    val timestamp: Long,+    val apps: Map<String, RepoApp> = emptyMap(),+)++@Serializable+data class RepoApp(+    @SerialName("min_version_code") val minVersionCode: Long,+    @SerialName("signing_cert_hash") val signingCertHash: String,+)++/**+ * Downloads, verifies and anti-rollback-checks Accrescent's signed repodata.+ *+ * The security model, preserved faithfully from upstream: trust comes entirely from the+ * ed25519 signature over the repodata bytes ([AccrescentSignify]) verified against the pinned+ * [AccrescentRepo.REPODATA_PUBKEY], plus a monotonic timestamp that can never go backwards+ * (floored at [AccrescentRepo.MIN_TIMESTAMP]). Every failure path returns+ * [Result.failure] — fail closed — so a tampered, unsigned or rolled-back document yields no+ * usable allowlist and therefore nothing installable.+ */+class AccrescentRepoDataFetcher(private val context: Context) {++    private val json = Json { ignoreUnknownKeys = true; isLenient = true }++    suspend fun fetch(): Result<RepoData> {+        return try {+            val (jsonStatus, _, jsonBytes) =+                NetworkClient.performRequestBytesFull(AccrescentRepo.REPODATA_JSON_URL)+            if (jsonStatus !in 200..299 || jsonBytes.isEmpty()) {+                return Result.failure(IllegalStateException("repodata fetch failed: HTTP $jsonStatus"))+            }++            val sig = NetworkClient.performRequest(AccrescentRepo.REPODATA_SIG_URL)+            if (!sig.isSuccess || sig.body.isBlank()) {+                return Result.failure(IllegalStateException("repodata signature fetch failed: HTTP ${sig.status}"))+            }++            // Verify the signature over the exact bytes downloaded, before parsing them.+            if (!AccrescentSignify.verify(jsonBytes, sig.body)) {+                return Result.failure(SecurityException("repodata signature did not verify"))+            }++            val repoData = json.decodeFromString(RepoData.serializer(), jsonBytes.toString(Charsets.UTF_8))++            // Anti-rollback: never accept a document older than the newest one already seen,+            // and never older than the pinned floor even on first run.+            val floor = maxOf(readStoredTimestamp(), AccrescentRepo.MIN_TIMESTAMP)+            if (repoData.timestamp < floor) {+                return Result.failure(+                    SecurityException(+                        "repodata timestamp ${repoData.timestamp} is older than $floor (rollback)"+                    )+                )+            }+            persistTimestamp(repoData.timestamp)++            Result.success(repoData)+        } catch (e: Exception) {+            Log.w(TAG, "repodata fetch/verify failed", e)+            Result.failure(e)+        }+    }++    private suspend fun readStoredTimestamp(): Long =+        try {+            context.accrescentDataStore.data.first()[REPODATA_TIMESTAMP_KEY] ?: 0L+        } catch (_: Exception) {+            0L+        }++    private suspend fun persistTimestamp(timestamp: Long) {+        try {+            context.accrescentDataStore.edit { it[REPODATA_TIMESTAMP_KEY] = timestamp }+        } catch (_: Exception) {+        }+    }++    private companion object {+        const val TAG = "AccrescentRepoData"+    }+}
appstore/src/main/java/com/vayunmathur/appstore/data/accrescent/AccrescentRepository.kt
diff --git a/appstore/src/main/java/com/vayunmathur/appstore/data/accrescent/AccrescentRepository.kt b/appstore/src/main/java/com/vayunmathur/appstore/data/accrescent/AccrescentRepository.ktnew file mode 100644index 0000000000..29280ae186--- /dev/null+++ b/appstore/src/main/java/com/vayunmathur/appstore/data/accrescent/AccrescentRepository.kt@@ -0,0 +1,220 @@+package com.vayunmathur.appstore.data.accrescent++import android.content.Context+import android.util.Log+import app.accrescent.appstore.v1.AppListing+import com.vayunmathur.appstore.data.AppDatabase+import com.vayunmathur.appstore.data.AppSource+import com.vayunmathur.appstore.data.UnifiedApp+import kotlinx.coroutines.CancellationException+import kotlinx.coroutines.sync.Mutex+import kotlinx.coroutines.sync.withLock+import java.util.Locale++/** One split (base or config) APK to download for an Accrescent install. */+data class AccrescentSplit(val url: String, val size: Long)++/** An available Accrescent update: the new version and the split APKs that make it up. */+data class AccrescentUpdate(+    val versionCode: Long,+    val versionName: String,+    val splits: List<AccrescentSplit>,+)++/** A page of Accrescent listings plus the token to fetch the next one (blank when done). */+data class AccrescentPage(val apps: List<UnifiedApp>, val nextPageToken: String)++/**+ * Everything the Accrescent source needs, behind one object — the analogue of+ * [com.vayunmathur.appstore.data.play.PlayRepository].+ *+ * Two halves that stay firmly separated:+ * - the **gRPC API** ([AccrescentApi]) supplies browsable listings and per-device split+ *   download URLs. This is untrusted metadata; a bad response can at worst show a wrong name+ *   or a URL that fails verification.+ * - the **signed allowlist** ([AccrescentTrustStore], populated by [AccrescentRepoDataFetcher])+ *   is the trust anchor: the expected signing certificate and minimum version per app id.+ *+ * Reads (list/search/details) fail soft and return empty/null like the Play repository, so a+ * network blip just shows fewer apps rather than an error. The install-critical calls+ * ([refreshRepoData], the trust lookups) surface failure so the installer can fail closed.+ */+class AccrescentRepository(+    context: Context,+    db: AppDatabase,+) {+    private val api = AccrescentApi()+    private val repoDataFetcher = AccrescentRepoDataFetcher(context)+    private val trustStore = AccrescentTrustStore(db.accrescentTrustDao())+    private val deviceAttributes = DeviceAttributesProvider(context)+    private val appContext = context.applicationContext++    /** Listings seen so far, for the client-side [search] (the API has no search RPC). */+    private val listingsCache = LinkedHashMap<String, UnifiedApp>()++    /** Guards [ensureAllListingsLoaded] so concurrent searches paginate the catalogue once. */+    private val listingsMutex = Mutex()++    /** True once the whole catalogue has been paged into [listingsCache] at least once. */+    @Volatile+    private var allListingsLoaded = false++    // --- Trust anchor ---------------------------------------------------------------++    /**+     * Fetch, ed25519-verify and cache the signed allowlist. Fail closed: on any failure the+     * previously cached allowlist is left untouched and the error is returned, so an install+     * never proceeds against unverified trust data.+     */+    suspend fun refreshRepoData(): Result<Unit> =+        repoDataFetcher.fetch().mapCatching { repoData ->+            trustStore.replaceFrom(repoData)+        }++    suspend fun signerFor(appId: String): String? = trustStore.signerFor(appId)+    suspend fun minVersionFor(appId: String): Long? = trustStore.minVersionFor(appId)+    suspend fun entryFor(appId: String) = trustStore.entryFor(appId)+    suspend fun appIds(): Set<String> = trustStore.appIds()++    // --- Browse / search ------------------------------------------------------------++    /** One page of listings. Blank [pageToken] starts from the beginning. */+    suspend fun listApps(pageToken: String = ""): AccrescentPage {+        return try {+            val response = api.listAppListings(PAGE_SIZE, pageToken, preferredLanguages())+            val apps = response.listingsList.map { it.toUnifiedApp() }+            apps.forEach { listingsCache[it.packageName] = it }+            AccrescentPage(apps, response.nextPageToken)+        } catch (e: CancellationException) {+            throw e+        } catch (e: Exception) {+            Log.w(TAG, "listApps failed", e)+            AccrescentPage(emptyList(), "")+        }+    }++    /**+     * Client-side search over the full catalogue. Accrescent's API has no search RPC, so this+     * pages every listing into memory once (mirroring Accrescent's own client) and then matches+     * app id, name and summary. The full load is cached for the session.+     */+    suspend fun search(query: String): List<UnifiedApp> {+        val q = query.trim().lowercase()+        if (q.isEmpty()) return emptyList()+        ensureAllListingsLoaded()+        return listingsCache.values.filter {+            it.packageName.lowercase().contains(q) ||+                it.name.lowercase().contains(q) ||+                it.summary.lowercase().contains(q)+        }+    }++    /** Page the entire listing catalogue into [listingsCache], once per session. */+    private suspend fun ensureAllListingsLoaded() {+        if (allListingsLoaded) return+        listingsMutex.withLock {+            if (allListingsLoaded) return+            var token = ""+            var pages = 0+            var complete = false+            while (pages < MAX_LISTING_PAGES) {+                val response = try {+                    api.listAppListings(PAGE_SIZE, token, preferredLanguages())+                } catch (e: CancellationException) {+                    throw e+                } catch (e: Exception) {+                    Log.w(TAG, "listAppListings page $pages failed", e)+                    break+                }+                response.listingsList.forEach { listingsCache[it.appId] = it.toUnifiedApp() }+                token = response.nextPageToken+                pages+++                if (token.isBlank()) {+                    complete = true+                    break+                }+            }+            // Mark loaded when we reached the end (or the page cap); leave it false on a network+            // failure so the next search retries the full load.+            if (complete || pages >= MAX_LISTING_PAGES) allListingsLoaded = true+        }+    }++    /** Full details for one app: listing + package info, enriched with signer/min-version. */+    suspend fun details(appId: String): UnifiedApp? {+        return try {+            val listing = api.getAppListing(appId, preferredLanguages())+            val packageInfo = runCatching { api.getAppPackageInfo(appId) }.getOrNull()+            val trust = trustStore.entryFor(appId)+            listing.toUnifiedApp().copy(+                versionName = packageInfo?.versionName?.ifBlank { null },+                versionCode = packageInfo?.versionCode ?: 0L,+                expectedSigners = trust?.signingCertHash?.let { listOf(it) } ?: emptyList(),+            ).also { listingsCache[appId] = it }+        } catch (e: CancellationException) {+            throw e+        } catch (e: Exception) {+            Log.w(TAG, "details failed for $appId", e)+            null+        }+    }++    // --- Install / update -----------------------------------------------------------++    /**+     * Per-device split download URLs for a fresh install. Throws+     * [IncompatibleDeviceException] when Accrescent has no build for this device.+     */+    suspend fun downloadInfo(appId: String): List<AccrescentSplit> {+        val info = api.getAppDownloadInfo(appId, deviceAttributes.deviceAttributes())+        return info.splitDownloadInfoList.map { AccrescentSplit(it.url, it.downloadSize.toLong()) }+    }++    /**+     * Split URLs for updating from [currentVersionCode], or null when no newer version is+     * available (the API omits update info when up to date). Throws+     * [IncompatibleDeviceException] when the device is unsupported. The new version code/name+     * come from a follow-up package-info lookup, since the update message carries only splits.+     */+    suspend fun updateInfo(appId: String, currentVersionCode: Long): AccrescentUpdate? {+        val update = api.getAppUpdateInfo(+            appId, deviceAttributes.deviceAttributes(), currentVersionCode+        ) ?: return null+        val packageInfo = runCatching { api.getAppPackageInfo(appId) }.getOrNull()+        return AccrescentUpdate(+            // The presence of update info already means "newer than installed"; fall back to+            // currentVersionCode + 1 so it still surfaces if the package-info lookup fails.+            versionCode = packageInfo?.versionCode?.takeIf { it > currentVersionCode }+                ?: (currentVersionCode + 1),+            versionName = packageInfo?.versionName.orEmpty(),+            splits = update.splitUpdateInfoList.map { AccrescentSplit(it.apkUrl, it.apkDownloadSize.toLong()) },+        )+    }++    fun shutdown() = api.shutdown()++    // --- Internals ------------------------------------------------------------------++    private fun AppListing.toUnifiedApp(): UnifiedApp = UnifiedApp(+        packageName = appId,+        source = AppSource.ACCRESCENT,+        name = name.ifBlank { appId },+        summary = shortDescription,+        iconUrl = if (hasIcon()) icon.url.ifBlank { null } else null,+        repoUrl = AccrescentRepo.REPOSITORY_URL,+        apkSha256 = null,+    )++    private fun preferredLanguages(): List<String> {+        val locales = appContext.resources.configuration.locales+        val tags = (0 until locales.size()).map { locales[it].toLanguageTag() }+        return tags.ifEmpty { listOf(Locale.getDefault().toLanguageTag()) }+    }++    private companion object {+        const val TAG = "AccrescentRepository"+        const val PAGE_SIZE = 50+        /** Safety cap on full-catalogue pagination (50 * 40 = 2000 apps, well above the catalogue). */+        const val MAX_LISTING_PAGES = 40+    }+}
appstore/src/main/java/com/vayunmathur/appstore/data/accrescent/AccrescentSignify.kt
diff --git a/appstore/src/main/java/com/vayunmathur/appstore/data/accrescent/AccrescentSignify.kt b/appstore/src/main/java/com/vayunmathur/appstore/data/accrescent/AccrescentSignify.ktnew file mode 100644index 0000000000..ee36910fba--- /dev/null+++ b/appstore/src/main/java/com/vayunmathur/appstore/data/accrescent/AccrescentSignify.kt@@ -0,0 +1,74 @@+package com.vayunmathur.appstore.data.accrescent++import android.util.Base64+import org.bouncycastle.crypto.params.Ed25519PublicKeyParameters+import org.bouncycastle.crypto.signers.Ed25519Signer++/**+ * ed25519 verification of an OpenBSD-signify signature, replicating Accrescent's+ * `util/RepoDataVerifier.verifySignature`.+ *+ * signify wire format (what this understands):+ * - The **public key** ([AccrescentRepo.REPODATA_PUBKEY]) is a raw base64 blob of+ *   `2-byte algo id || 8-byte key id || 32-byte ed25519 public key`; the key is bytes+ *   `[10, 42)`.+ * - A **`.sig` file** is two lines: an `untrusted comment:` line and a base64 blob of+ *   `2-byte algo id || 8-byte key id || 64-byte ed25519 signature`; the signature is bytes+ *   `[10, 74)`.+ * - The signature is over the **raw bytes of the signed file** (here, `repodata.N.json`).+ *+ * This is the whole trust anchor for the Accrescent source, so it fails closed: any parsing+ * or verification problem returns `false` rather than throwing or assuming success.+ */+object AccrescentSignify {++    private const val PUBKEY_HEADER = 10+    private const val PUBKEY_END = 42+    private const val SIG_HEADER = 10+    private const val SIG_END = 74++    /**+     * @param message the exact bytes that were signed (the repodata JSON as downloaded).+     * @param sigFileContent the full text of the `.sig` file.+     * @param base64PublicKey the signify public key, as a raw base64 string (no comment line).+     * @return true only if [sigFileContent] is a valid ed25519 signature over [message] by+     *   [base64PublicKey].+     */+    fun verify(+        message: ByteArray,+        sigFileContent: String,+        base64PublicKey: String = AccrescentRepo.REPODATA_PUBKEY,+    ): Boolean {+        return try {+            val pubKeyBytes = decodeRange(base64PublicKey, PUBKEY_HEADER, PUBKEY_END) ?: return false++            // A .sig file is a comment line followed by the base64 blob. Take the last+            // non-blank, non-comment line so a stray trailing newline can't select "".+            val sigBase64 = sigFileContent+                .lineSequence()+                .map { it.trim() }+                .lastOrNull { it.isNotEmpty() && !it.startsWith("untrusted comment:") }+                ?: return false+            val sigBytes = decodeRange(sigBase64, SIG_HEADER, SIG_END) ?: return false++            val publicKey = Ed25519PublicKeyParameters(pubKeyBytes, 0)+            Ed25519Signer().apply {+                init(false, publicKey)+                update(message, 0, message.size)+            }.verifySignature(sigBytes)+        } catch (_: Exception) {+            false+        }+    }++    /** base64-decode [value] and return bytes `[start, end)`, or null if it is too short. */+    private fun decodeRange(value: String, start: Int, end: Int): ByteArray? {+        val decoded = try {+            Base64.decode(value.trim(), Base64.DEFAULT)+        } catch (_: Exception) {+            return null+        }+        if (decoded.size < end) return null+        return decoded.copyOfRange(start, end)+    }+}
appstore/src/main/java/com/vayunmathur/appstore/data/accrescent/AccrescentTrustStore.kt
diff --git a/appstore/src/main/java/com/vayunmathur/appstore/data/accrescent/AccrescentTrustStore.kt b/appstore/src/main/java/com/vayunmathur/appstore/data/accrescent/AccrescentTrustStore.ktnew file mode 100644index 0000000000..7b09297d12--- /dev/null+++ b/appstore/src/main/java/com/vayunmathur/appstore/data/accrescent/AccrescentTrustStore.kt@@ -0,0 +1,40 @@+package com.vayunmathur.appstore.data.accrescent++import com.vayunmathur.appstore.data.AccrescentTrustEntity+import com.vayunmathur.appstore.data.AccrescentTrustDao++/**+ * Room-cached view of Accrescent's verified allowlist.+ *+ * Every read here answers a trust question — "what certificate must this app id be signed+ * with?" and "what is the oldest version we may install?" — and the answers only ever come+ * from a [RepoData] that [AccrescentRepoDataFetcher] has already ed25519-verified. Nothing+ * writes to this store except [replaceFrom].+ */+class AccrescentTrustStore(private val dao: AccrescentTrustDao) {++    /** Overwrite the whole allowlist from a freshly verified repodata document. */+    suspend fun replaceFrom(repoData: RepoData) {+        dao.replaceAll(+            repoData.apps.map { (appId, app) ->+                AccrescentTrustEntity(+                    appId = appId,+                    signingCertHash = app.signingCertHash.lowercase(),+                    minVersionCode = app.minVersionCode,+                )+            }+        )+    }++    /** The certificate fingerprint the app's APK must be signed with, or null if not listed. */+    suspend fun signerFor(appId: String): String? = dao.byId(appId)?.signingCertHash++    /** The minimum installable version code for [appId], or null if not listed. */+    suspend fun minVersionFor(appId: String): Long? = dao.byId(appId)?.minVersionCode++    /** Both trust values in one lookup, or null when [appId] is not in the allowlist. */+    suspend fun entryFor(appId: String): AccrescentTrustEntity? = dao.byId(appId)++    /** Every app id Accrescent's signed list vouches for, for attribution + membership checks. */+    suspend fun appIds(): Set<String> = dao.allIds().toSet()+}
appstore/src/main/java/com/vayunmathur/appstore/data/accrescent/DeviceAttributesProvider.kt
diff --git a/appstore/src/main/java/com/vayunmathur/appstore/data/accrescent/DeviceAttributesProvider.kt b/appstore/src/main/java/com/vayunmathur/appstore/data/accrescent/DeviceAttributesProvider.ktnew file mode 100644index 0000000000..20804eb8e2--- /dev/null+++ b/appstore/src/main/java/com/vayunmathur/appstore/data/accrescent/DeviceAttributesProvider.kt@@ -0,0 +1,74 @@+package com.vayunmathur.appstore.data.accrescent++import android.app.ActivityManager+import android.content.Context+import android.os.Build+import android.util.DisplayMetrics+import android.view.WindowManager+import app.accrescent.appstore.v1.DeviceAttributes+import com.android.bundle.DeviceSpec++/**+ * Builds the [DeviceAttributes] / bundletool [DeviceSpec] the Accrescent API uses to pick which+ * split (config) APKs this device needs.+ *+ * Starts minimal — the long-stable DeviceSpec fields that actually drive split selection+ * (ABIs, locales, features, density, SDK) plus best-effort build/SoC identification — and+ * deliberately leaves OpenGL extension enumeration empty to avoid dragging in an EGL context+ * just to browse. If the API rejects requests without more (`INVALID_ARGUMENT` /+ * `FAILED_PRECONDITION`), fill in the remaining fields here.+ */+class DeviceAttributesProvider(private val context: Context) {++    fun deviceAttributes(): DeviceAttributes =+        DeviceAttributes.newBuilder().setSpec(deviceSpec()).build()++    fun deviceSpec(): DeviceSpec {+        val builder = DeviceSpec.newBuilder()+            .addAllSupportedAbis(Build.SUPPORTED_ABIS?.toList().orEmpty())+            .addAllSupportedLocales(supportedLocales())+            .addAllDeviceFeatures(deviceFeatures())+            .setScreenDensity(screenDensity())+            .setSdkVersion(Build.VERSION.SDK_INT)+            .setBuildBrand(Build.BRAND)+            .setBuildDevice(Build.DEVICE)+            .setCodename(Build.VERSION.CODENAME)++        // SoC identification is API 31+, which is this store's minSdk. These are non-null+        // (they read "unknown" when unavailable), which the server can simply ignore.+        builder.socManufacturer = Build.SOC_MANUFACTURER+        builder.socModel = Build.SOC_MODEL++        ramBytes()?.let { builder.ramBytes = it }++        return builder.build()+    }++    private fun supportedLocales(): List<String> {+        val locales = context.resources.configuration.locales+        return (0 until locales.size()).map { locales[it].toLanguageTag() }+    }++    private fun deviceFeatures(): List<String> = try {+        context.packageManager.systemAvailableFeatures.mapNotNull { it.name }+    } catch (_: Exception) {+        emptyList()+    }++    private fun screenDensity(): Int = try {+        val metrics = DisplayMetrics()+        val wm = context.getSystemService(Context.WINDOW_SERVICE) as WindowManager+        @Suppress("DEPRECATION")+        wm.defaultDisplay.getMetrics(metrics)+        metrics.densityDpi+    } catch (_: Exception) {+        context.resources.displayMetrics.densityDpi+    }++    private fun ramBytes(): Long? = try {+        val am = context.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager+        ActivityManager.MemoryInfo().also { am.getMemoryInfo(it) }.totalMem+    } catch (_: Exception) {+        null+    }+}
appstore/src/main/java/com/vayunmathur/appstore/data/installer/InstallCoordinator.kt
diff --git a/appstore/src/main/java/com/vayunmathur/appstore/data/installer/InstallCoordinator.kt b/appstore/src/main/java/com/vayunmathur/appstore/data/installer/InstallCoordinator.ktindex 6b012116d4..2abc1adf86 100644--- a/appstore/src/main/java/com/vayunmathur/appstore/data/installer/InstallCoordinator.kt+++ b/appstore/src/main/java/com/vayunmathur/appstore/data/installer/InstallCoordinator.kt@@ -6,6 +6,8 @@ import com.vayunmathur.appstore.data.AppDatabase import com.vayunmathur.appstore.data.AppSource import com.vayunmathur.appstore.data.PinnedStampEntity import com.vayunmathur.appstore.data.UnifiedApp+import com.vayunmathur.appstore.data.accrescent.AccrescentRepository+import com.vayunmathur.appstore.data.accrescent.IncompatibleDeviceException import com.vayunmathur.appstore.data.play.CertUtil import com.vayunmathur.appstore.data.play.PlayRepository import com.vayunmathur.appstore.data.security.InstallRequirement@@ -51,6 +53,7 @@ class InstallCoordinator(     private val context: Context,     private val db: AppDatabase,     private val play: PlayRepository,+    private val accrescent: AccrescentRepository,     private val ownSigningCertificates: () -> Set<String>,     backgroundUpdateInstall: () -> Boolean = { false }, ) {@@ -82,6 +85,7 @@ class InstallCoordinator(         return try {             when (app.source) {                 AppSource.PLAYSTORE -> installFromPlay(app)+                AppSource.ACCRESCENT -> installFromAccrescent(app)                 else -> installFromUrl(app)             }.also { outcome ->                 if (outcome.started) {@@ -182,6 +186,72 @@ class InstallCoordinator(         }     } +    // --- Accrescent ----------------------------------------------------------------++    /**+     * Install an Accrescent app: verified signed-list trust anchor + per-device split URLs.+     *+     * Fail closed at every step. The signing certificate and minimum version come only from+     * the ed25519-signed allowlist ([AccrescentRepository.refreshRepoData] ++     * [AccrescentRepository.entryFor]); if the list doesn't vouch for this app id, or the+     * refresh fails and nothing is cached, the install is refused before anything downloads.+     * The gRPC API supplies only the split URLs, which are then checked against that anchor by+     * [InstallVerifier] (correct signer + version code >= minimum). Accrescent publishes no+     * per-file hashes, so there is no `expectedSha256` — signature + min-version is the guarantee.+     */+    private suspend fun installFromAccrescent(app: UnifiedApp): SessionInstaller.Outcome =+        withContext(Dispatchers.IO) {+            // Refresh the signed allowlist (best effort — a cached, previously-verified copy is+            // fine), then read this app's trust anchor. No anchor, no install.+            accrescent.refreshRepoData()+            val trust = accrescent.entryFor(app.packageName)+                ?: return@withContext SessionInstaller.Outcome(+                    false,+                    VerificationResult.Rejected("Accrescent's signed app list does not vouch for this app"),+                )++            val splits = try {+                accrescent.downloadInfo(app.packageName)+            } catch (e: IncompatibleDeviceException) {+                return@withContext SessionInstaller.Outcome(+                    false, VerificationResult.Rejected("this app has no build for your device")+                )+            }+            if (splits.isEmpty()) {+                return@withContext SessionInstaller.Outcome(+                    false, VerificationResult.Rejected("Accrescent returned no files to download")+                )+            }++            val totalSize = splits.sumOf { it.size }.takeIf { it > 0 } ?: -1L+            var downloadedBytes = 0L+            val files = splits.mapIndexed { index, split ->+                val file = File(context.cacheDir, "${app.packageName}.split$index.apk")+                val start = downloadedBytes+                download(split.url, file, split.size) { fileFraction ->+                    if (totalSize > 0) {+                        val overall = (start + fileFraction * split.size) / totalSize+                        stage(app.packageName, InstallStage.Downloading(overall.coerceIn(0f, 1f)))+                    }+                }+                downloadedBytes += file.length()+                file+            }++            val requirement = InstallRequirement(+                expectedPackage = app.packageName,+                requiredSigners = setOf(trust.signingCertHash),+                expectedSha256 = emptyMap(),+                minVersionCode = trust.minVersionCode,+                signerOrigin = "Accrescent's signed app list",+            )++            stage(app.packageName, InstallStage.Verifying)+            sessionInstaller.installSplits(+                app.packageName, files, requirement, files.sumOf { it.length() }+            )+        }+     // --- Play ----------------------------------------------------------------------      private suspend fun installFromPlay(app: UnifiedApp): SessionInstaller.Outcome =
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 d1ac6f89d8..706a1f7f82 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@@ -69,6 +69,18 @@ class SessionInstaller(             val pm = context.packageManager             val installer = pm.packageInstaller +            // Abandon any of our own still-pending sessions for this package before opening a+            // new one. A previous attempt the user dismissed at the system prompt (or one that+            // failed after the session was created) leaves a pending session, and committing a+            // second session for the same package makes PackageManager reject it with+            // INSTALL_FAILED_DUPLICATE_PACKAGE ("Duplicate package ... in pending install+            // requests"). Multi-split installs (e.g. Accrescent) hit this most, being slower.+            runCatching {+                installer.mySessions+                    .filter { it.appPackageName == packageName }+                    .forEach { runCatching { installer.abandonSession(it.sessionId) } }+            }+             val params = PackageInstaller.SessionParams(PackageInstaller.SessionParams.MODE_FULL_INSTALL).apply {                 if (computedSize > 0) setSize(computedSize)                 setAppPackageName(packageName)
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.ktindex 440b363ae2..8e5be73406 100644--- a/appstore/src/main/java/com/vayunmathur/appstore/data/security/InstallVerifier.kt+++ b/appstore/src/main/java/com/vayunmathur/appstore/data/security/InstallVerifier.kt@@ -32,6 +32,13 @@ data class InstallRequirement(     val pinnedStamp: String? = null,     /** Refuse to install if the APK carries no verifiable source stamp at all. */     val requireStamp: Boolean = false,+    /**+     * Minimum version code the base APK may declare, below which the install is rejected.+     * Used by Accrescent, whose ed25519-signed repodata carries a per-app minimum version+     * for rollback protection. Null (the default) means no floor, so every other source is+     * unaffected — the gate is additive and defaults to a no-op.+     */+    val minVersionCode: Long? = null, )  sealed class VerificationResult {@@ -132,6 +139,23 @@ object InstallVerifier {          val checks = mutableListOf<String>() +        // Rollback guard (Accrescent): the base APK's version code must be at least the+        // minimum the source's signed allowlist records. Read from the base APK's manifest,+        // like the target-SDK check above. Fail closed — a version we cannot read (0) is below+        // any positive floor and is rejected, since the whole point is to refuse an old build.+        requirement.minVersionCode?.let { minVc ->+            val baseInfo = parsed.firstOrNull { (_, info) ->+                info?.packageName == requirement.expectedPackage && info.splitNames.isNullOrEmpty()+            }?.second+            val versionCode = baseInfo?.longVersionCode ?: 0L+            if (versionCode < minVc) {+                return VerificationResult.Rejected(+                    "it is version $versionCode, older than the minimum $minVc the source allows"+                )+            }+            checks += "version $versionCode is at or above the minimum $minVc"+        }+         val installed = ApkCertificates.installedSigners(context, requirement.expectedPackage)         if (installed.isNotEmpty()) {             if (actualSigners.none { it in installed }) {
appstore/src/main/java/com/vayunmathur/appstore/data/security/TrustProfile.kt
diff --git a/appstore/src/main/java/com/vayunmathur/appstore/data/security/TrustProfile.kt b/appstore/src/main/java/com/vayunmathur/appstore/data/security/TrustProfile.ktindex 5925083df3..ad8a3f42c3 100644--- a/appstore/src/main/java/com/vayunmathur/appstore/data/security/TrustProfile.kt+++ b/appstore/src/main/java/com/vayunmathur/appstore/data/security/TrustProfile.kt@@ -80,7 +80,14 @@ enum class TrustProfile {     FDROID,      /** Google Play, via an anonymous account. */-    PLAY;+    PLAY,++    /**+     * Accrescent, via its ed25519-signed allowlist plus its gRPC listing/download API. Trust+     * is the pinned repo signing key and, per app, the signing certificate and minimum version+     * that key vouches for.+     */+    ACCRESCENT;      @get:StringRes     val title: Int@@ -88,6 +95,7 @@ enum class TrustProfile {             MODERN_APPS -> R.string.trust_modern_apps_title             FDROID -> R.string.trust_fdroid_title             PLAY -> R.string.trust_play_title+            ACCRESCENT -> R.string.trust_accrescent_title         }      /** One line, shown under the heading on the app's page. */@@ -97,6 +105,7 @@ enum class TrustProfile {             MODERN_APPS -> R.string.trust_modern_apps_summary             FDROID -> R.string.trust_fdroid_summary             PLAY -> R.string.trust_play_summary+            ACCRESCENT -> R.string.trust_accrescent_summary         }      /** What the source itself does, beyond anything this app can check. */@@ -117,6 +126,11 @@ enum class TrustProfile {                 R.string.trust_play_practice_hsm,                 R.string.trust_play_practice_takedown,             )+            ACCRESCENT -> listOf(+                R.string.trust_accrescent_practice_developer_key,+                R.string.trust_accrescent_practice_signed_list,+                R.string.trust_accrescent_practice_min_version,+            )         }      /** Checks this app performs on the download, on top of [StoreGuarantees.rules]. */@@ -138,6 +152,11 @@ enum class TrustProfile {                 R.string.trust_play_check_key,                 R.string.trust_play_check_stamp,             )+            ACCRESCENT -> listOf(+                R.string.trust_accrescent_check_list_signed,+                R.string.trust_accrescent_check_key,+                R.string.trust_accrescent_check_min_version,+            )         }      /** Where this source is weaker than the others. Every source has one. */@@ -147,6 +166,7 @@ enum class TrustProfile {             MODERN_APPS -> R.string.trust_modern_apps_limits             FDROID -> R.string.trust_fdroid_limits             PLAY -> R.string.trust_play_limits+            ACCRESCENT -> R.string.trust_accrescent_limits         }      companion object {@@ -160,6 +180,9 @@ enum class TrustProfile {             // F-Droid, so it shares that profile.             AppSource.GRAPHENEOS -> FDROID             AppSource.PLAYSTORE -> PLAY+            // Accrescent apps are signed by their developers, not by Accrescent; trust is the+            // ed25519-signed allowlist that pins each app's signing certificate + min version.+            AppSource.ACCRESCENT -> ACCRESCENT         }     } }
appstore/src/main/java/com/vayunmathur/appstore/ui/AppComponents.kt
diff --git a/appstore/src/main/java/com/vayunmathur/appstore/ui/AppComponents.kt b/appstore/src/main/java/com/vayunmathur/appstore/ui/AppComponents.ktindex fe4d771c6b..da03cfc319 100644--- a/appstore/src/main/java/com/vayunmathur/appstore/ui/AppComponents.kt+++ b/appstore/src/main/java/com/vayunmathur/appstore/ui/AppComponents.kt@@ -107,6 +107,7 @@ fun SourceChip(source: AppSource, modifier: Modifier = Modifier) {             AppSource.FDROID -> R.string.source_chip_fdroid             AppSource.GRAPHENEOS -> R.string.source_chip_grapheneos             AppSource.PLAYSTORE -> R.string.source_chip_play+            AppSource.ACCRESCENT -> R.string.source_chip_accrescent         }     )     Text(
appstore/src/main/java/com/vayunmathur/appstore/ui/SearchPage.kt
diff --git a/appstore/src/main/java/com/vayunmathur/appstore/ui/SearchPage.kt b/appstore/src/main/java/com/vayunmathur/appstore/ui/SearchPage.ktindex 9733a24292..1791bacc90 100644--- a/appstore/src/main/java/com/vayunmathur/appstore/ui/SearchPage.kt+++ b/appstore/src/main/java/com/vayunmathur/appstore/ui/SearchPage.kt@@ -151,4 +151,5 @@ internal fun SourceFilter.labelRes(): Int = when (this) {     SourceFilter.FDROID -> R.string.source_chip_fdroid     SourceFilter.GRAPHENEOS -> R.string.source_chip_grapheneos     SourceFilter.PLAYSTORE -> R.string.source_chip_play+    SourceFilter.ACCRESCENT -> R.string.source_chip_accrescent }
appstore/src/main/java/com/vayunmathur/appstore/ui/SourcesPage.kt
diff --git a/appstore/src/main/java/com/vayunmathur/appstore/ui/SourcesPage.kt b/appstore/src/main/java/com/vayunmathur/appstore/ui/SourcesPage.ktindex 502096a4dc..0eea6caa03 100644--- a/appstore/src/main/java/com/vayunmathur/appstore/ui/SourcesPage.kt+++ b/appstore/src/main/java/com/vayunmathur/appstore/ui/SourcesPage.kt@@ -21,6 +21,7 @@ import androidx.compose.ui.unit.dp import com.vayunmathur.appstore.R import com.vayunmathur.appstore.data.DefaultRepos import com.vayunmathur.appstore.data.ModernAppsRepo+import com.vayunmathur.appstore.data.accrescent.AccrescentRepo import com.vayunmathur.appstore.data.security.ApkCertificates import com.vayunmathur.appstore.util.AppStoreViewModel import com.vayunmathur.library.ui.Button@@ -51,6 +52,7 @@ fun SourcesPage(     val repos by viewModel.repos.collectAsState()     val home by viewModel.home.collectAsState()     val backgroundUpdateInstall by viewModel.backgroundUpdateInstall.collectAsState()+    val autoInstallUpdates by viewModel.autoInstallUpdates.collectAsState()     val fdroid = repos.find { it.url == DefaultRepos.FDROID.url }      Scaffold(@@ -151,6 +153,16 @@ fun SourcesPage(                     lastSync = 0L,                 )             }+            item {+                SourceCard(+                    title = stringResource(R.string.source_accrescent),+                    subtitle = AccrescentRepo.REPOSITORY_URL,+                    pinLabel = stringResource(R.string.source_accrescent_pin),+                    pins = setOf(AccrescentRepo.REPODATA_PUBKEY),+                    lastSync = 0L,+                    abbreviatePins = false,+                )+            }         }     } }@@ -162,6 +174,11 @@ private fun SourceCard(     pinLabel: String,     pins: Set<String>,     lastSync: Long,+    /**+     * Whether [pins] are hex certificate fingerprints to abbreviate for display. Accrescent's+     * pin is a base64 signify ed25519 key, not a hex fingerprint, so it is shown verbatim.+     */+    abbreviatePins: Boolean = true, ) {     val locale = LocalConfiguration.current.locales[0]     Card(Modifier.fillMaxWidth()) {@@ -180,7 +197,7 @@ private fun SourceCard(             )             pins.forEach {                 Text(-                    ApkCertificates.abbreviate(it),+                    if (abbreviatePins) ApkCertificates.abbreviate(it) else it,                     style = MaterialTheme.typography.labelMedium,                     color = MaterialTheme.colorScheme.primary,                 )
appstore/src/main/java/com/vayunmathur/appstore/util/AppStoreUiContract.kt
diff --git a/appstore/src/main/java/com/vayunmathur/appstore/util/AppStoreUiContract.kt b/appstore/src/main/java/com/vayunmathur/appstore/util/AppStoreUiContract.ktindex f2583c7591..9d6c025a00 100644--- a/appstore/src/main/java/com/vayunmathur/appstore/util/AppStoreUiContract.kt+++ b/appstore/src/main/java/com/vayunmathur/appstore/util/AppStoreUiContract.kt@@ -46,6 +46,7 @@ enum class SourceFilter(val source: AppSource?) {     FDROID(AppSource.FDROID),     GRAPHENEOS(AppSource.GRAPHENEOS),     PLAYSTORE(AppSource.PLAYSTORE),+    ACCRESCENT(AppSource.ACCRESCENT), }  /** Everything the home screen draws. */
appstore/src/main/java/com/vayunmathur/appstore/util/AppStoreViewModel.kt
diff --git a/appstore/src/main/java/com/vayunmathur/appstore/util/AppStoreViewModel.kt b/appstore/src/main/java/com/vayunmathur/appstore/util/AppStoreViewModel.ktindex d40ed03251..d4fe4d7418 100644--- a/appstore/src/main/java/com/vayunmathur/appstore/util/AppStoreViewModel.kt+++ b/appstore/src/main/java/com/vayunmathur/appstore/util/AppStoreViewModel.kt@@ -19,6 +19,7 @@ import com.vayunmathur.appstore.data.SandboxedGooglePlay import com.vayunmathur.appstore.data.SettingsRepository import com.vayunmathur.appstore.data.SyncStep import com.vayunmathur.appstore.data.UnifiedApp+import com.vayunmathur.appstore.data.accrescent.AccrescentRepository import com.vayunmathur.appstore.data.installer.InstallCoordinator import com.vayunmathur.appstore.data.installer.InstallStage import com.vayunmathur.appstore.data.play.PlayAuthState@@ -51,9 +52,10 @@ class AppStoreViewModel(      private val catalog = CatalogRepository(context, db, viewModelScope)     private val play = PlayRepository(context)+    private val accrescent = AccrescentRepository(context, db)     private val installedRepo = InstalledAppsRepository(context)     private val settings = SettingsRepository(context, viewModelScope)-    private val installer = InstallCoordinator(context, db, play, { ownSigningCertificates }) {+    private val installer = InstallCoordinator(context, db, play, accrescent, { ownSigningCertificates }) {         settings.backgroundUpdateInstall.value     } @@ -82,6 +84,15 @@ class AppStoreViewModel(     private val _playSections = MutableStateFlow<List<AppSection>>(emptyList())     private val _recentlyUpdated = MutableStateFlow<List<UnifiedApp>>(emptyList()) +    /** Accrescent listings for the home carousel, from the gRPC listing API. */+    private val _accrescentApps = MutableStateFlow<List<UnifiedApp>>(emptyList())++    /**+     * App ids Accrescent's signed allowlist vouches for. Drives library attribution for an+     * installed Accrescent app. Empty until the first repodata refresh populates it.+     */+    private val _accrescentPackages = MutableStateFlow<Set<String>>(emptySet())+     /**      * The Sandboxed Google Play bundle rows. Seeded with stand-ins so the section is on      * screen immediately; [loadHome] swaps in richer catalogue rows when a sync has cached@@ -105,6 +116,7 @@ class AppStoreViewModel(      private val _catalogUpdates = MutableStateFlow<List<UnifiedApp>>(emptyList())     private val _playUpdates = MutableStateFlow<List<UnifiedApp>>(emptyList())+    private val _accrescentUpdates = MutableStateFlow<List<UnifiedApp>>(emptyList())      private val _libraryFilter = MutableStateFlow(SourceFilter.ALL) @@ -135,10 +147,11 @@ class AppStoreViewModel(     val updates: StateFlow<List<UnifiedApp>> = combine(         _catalogUpdates,         _playUpdates,+        _accrescentUpdates,         installedRepo.apps,-    ) { catalogUpdates, playUpdates, installed ->+    ) { catalogUpdates, playUpdates, accrescentUpdates, installed ->         val installedVersions = installed.associate { it.packageName to it.versionCode }-        (catalogUpdates + playUpdates)+        (catalogUpdates + playUpdates + accrescentUpdates)             .distinctBy { it.packageName }             // Re-check against what is on the device rather than trusting the lists.             // _playUpdates is a snapshot from the last network check, so without this a@@ -155,9 +168,13 @@ class AppStoreViewModel(         _playSections,         _recentlyUpdated,         _sandboxedGooglePlay,-        combine(_categoryApps, _selectedCategory) { apps, category -> apps to category },-    ) { modern, playSections, recent, sandboxed, (categoryApps, category) ->-        buildSections(modern, playSections, recent, sandboxed, categoryApps, category)+        combine(+            _categoryApps,+            _selectedCategory,+            _accrescentApps,+        ) { apps, category, accrescent -> Triple(apps, category, accrescent) },+    ) { modern, playSections, recent, sandboxed, (categoryApps, category, accrescentApps) ->+        buildSections(modern, playSections, recent, sandboxed, accrescentApps, categoryApps, category)     }.stateIn(viewModelScope, SharingStarted.Eagerly, emptyList())      val home: StateFlow<HomeUiState> = combine(@@ -248,19 +265,22 @@ class AppStoreViewModel(         chrome,         catalog.packageIndex,         _playInstalledPackages,+        _accrescentPackages,         _libraryFilter,-    ) { rows, index, playPackages, filter ->+    ) { rows, index, playPackages, accrescentPackages, filter ->         // Source attribution, highest priority first:         //  1. GrapheneOS's Sandboxed Google Play components (GSF/GMS/Vending) are Google's         //     APKs re-hosted by GrapheneOS and installed from its release server, so they         //     are attributed to GrapheneOS — never Play — even though Play lists them too.         //  2. Whatever the offline catalogue (F-Droid / Modern Apps) recorded.-        //  3. Play, but only for packages Play confirmed it hosts (see _playInstalledPackages).+        //  3. Accrescent, for packages its signed allowlist vouches for.+        //  4. Play, but only for packages Play confirmed it hosts (see _playInstalledPackages).         // A package no source vouches for — sideloaded, or from a store we don't track — is         // left out entirely rather than mislabelled as Play.         fun sourceOf(pkg: String): AppSource? = when {             pkg in SandboxedGooglePlay.PACKAGES -> AppSource.GRAPHENEOS             else -> index[pkg]?.source?.let { runCatching { AppSource.valueOf(it) }.getOrNull() }+                ?: AppSource.ACCRESCENT.takeIf { pkg in accrescentPackages }                 ?: AppSource.PLAYSTORE.takeIf { pkg in playPackages }         } @@ -286,6 +306,7 @@ class AppStoreViewModel(             loadHome()             refreshPlayInstalledPackages()         }+        viewModelScope.launch { loadAccrescent() }         viewModelScope.launch {             // Recompute catalogue-side updates whenever either half changes. The Play             // half needs a network call and is driven by checkForUpdates() instead.@@ -313,6 +334,12 @@ class AppStoreViewModel(         }     } +    override fun onCleared() {+        // Release the Accrescent gRPC channel (and its okhttp connection pool).+        accrescent.shutdown()+        super.onCleared()+    }+     /**      * Ask Play which installed packages it actually hosts, for library attribution.      *@@ -334,6 +361,35 @@ class AppStoreViewModel(         if (available.isNotEmpty()) _playInstalledPackages.value = available     } +    /**+     * Refresh Accrescent's signed allowlist and its home listings. Both fail soft: a network+     * blip leaves the previous rows and attribution set in place rather than emptying them.+     */+    private suspend fun loadAccrescent() {+        accrescent.refreshRepoData()+        val ids = accrescent.appIds()+        if (ids.isNotEmpty()) _accrescentPackages.value = ids+        val page = accrescent.listApps()+        if (page.apps.isNotEmpty()) _accrescentApps.value = page.apps.take(CAROUSEL_LIMIT)+    }++    /**+     * The available Accrescent update for [packageName] as an installable listing, or null when+     * there is none. The version code is the update's, so the [updates] filter keeps it only+     * while it is genuinely newer than what is installed.+     */+    private suspend fun accrescentUpdate(packageName: String, currentVersionCode: Long): UnifiedApp? {+        val update = runCatching {+            accrescent.updateInfo(packageName, currentVersionCode)+        }.getOrNull() ?: return null+        val details = accrescent.details(packageName) ?: UnifiedApp(+            packageName = packageName,+            source = AppSource.ACCRESCENT,+            name = packageName.substringAfterLast('.'),+        )+        return details.copy(versionCode = update.versionCode, versionName = update.versionName)+    }+     // --- Home ---------------------------------------------------------------------      /**@@ -385,6 +441,7 @@ class AppStoreViewModel(         playSections: List<AppSection>,         recent: List<UnifiedApp>,         sandboxed: List<UnifiedApp>,+        accrescent: List<UnifiedApp>,         categoryApps: List<UnifiedApp>,         category: String?,     ): List<AppSection> = buildList {@@ -424,6 +481,16 @@ class AppStoreViewModel(             )         }         addAll(playSections)+        if (accrescent.isNotEmpty()) {+            add(+                AppSection(+                    id = "accrescent",+                    title = context.getString(R.string.section_accrescent),+                    apps = accrescent,+                    subtitle = context.getString(R.string.section_accrescent_subtitle),+                )+            )+        }         if (recent.isNotEmpty()) {             add(                 AppSection(@@ -476,6 +543,7 @@ class AppStoreViewModel(              _categories.value = catalog.categories()             loadHome()+            loadAccrescent()             installedRepo.refresh()         }     }@@ -500,8 +568,11 @@ class AppStoreViewModel(             val local = catalog.searchLocal(query)             _searchResults.value = rank(local, query) +            // Accrescent search is client-side over the listings already cached from the home+            // carousel (its API has no search RPC), so it adds no network round-trip here.+            val accrescentResults = accrescent.search(query)             val remote = play.search(query)-            _searchResults.value = rank(merge(local, remote), query)+            _searchResults.value = rank(merge(local, remote, accrescentResults), query)             _isSearching.value = false             _hasSearched.value = true         }@@ -520,8 +591,8 @@ class AppStoreViewModel(      * rows carry a publisher key and a hash this app can check the download against,      * which is simply more to show on the detail page than a Play listing has.      */-    private fun merge(local: List<UnifiedApp>, remote: List<UnifiedApp>): List<UnifiedApp> =-        (local + remote).distinctBy { it.packageName }+    private fun merge(vararg lists: List<UnifiedApp>): List<UnifiedApp> =+        lists.asSequence().flatten().distinctBy { it.packageName }.toList()      /** Exact hits first, then name prefixes, then everything else alphabetically. */     private fun rank(apps: List<UnifiedApp>, query: String): List<UnifiedApp> {@@ -556,6 +627,15 @@ class AppStoreViewModel(                 _selectedApp.value = cached                 return@launch             }+            // Accrescent listings from the home carousel are shells (no version code, no signer+            // yet); fetch the full listing + package info + trust anchor before the page settles.+            if (app.source == AppSource.ACCRESCENT) {+                _isLoadingDetails.value = true+                val details = accrescent.details(app.packageName)+                if (details != null) _selectedApp.value = details+                _isLoadingDetails.value = false+                return@launch+            }             // Play listings from a cluster are shells: no description, no             // screenshots, no version code. Fill them in before the page settles.             if (app.source == AppSource.PLAYSTORE && app.screenshots.isEmpty()) {@@ -703,6 +783,15 @@ class AppStoreViewModel(             // the library uses to tell a genuine Play app from a sideloaded one.             if (remote.isNotEmpty()) _playInstalledPackages.value = remote.keys.toSet() +            // Accrescent: refresh the signed allowlist, then ask its API for a newer build of+            // each installed package it vouches for.+            accrescent.refreshRepoData()+            val accrescentIds = accrescent.appIds()+            if (accrescentIds.isNotEmpty()) _accrescentPackages.value = accrescentIds+            _accrescentUpdates.value = installed+                .filter { it.packageName in accrescentIds }+                .mapNotNull { inst -> accrescentUpdate(inst.packageName, inst.versionCode) }+             _lastUpdateCheck.value = System.currentTimeMillis()             _statusMessage.value = ""             _isCheckingUpdates.value = false
appstore/src/main/proto/accrescent/appstore/v1/appstore.proto
diff --git a/appstore/src/main/proto/accrescent/appstore/v1/appstore.proto b/appstore/src/main/proto/accrescent/appstore/v1/appstore.protonew file mode 100644index 0000000000..ce94abfb5d--- /dev/null+++ b/appstore/src/main/proto/accrescent/appstore/v1/appstore.proto@@ -0,0 +1,127 @@+syntax = "proto3";++package accrescent.appstore.v1;++option java_package = "app.accrescent.appstore.v1";+option java_multiple_files = true;++import "android/bundle/devicespec.proto";++// Vendored copy of Accrescent's client-facing appstore API (`accrescent.appstore.v1.AppService`,+// served by appstore-api.accrescent.app over gRPC/HTTP2). Transcribed field-for-field from the+// upstream `accrescent/appstore-api` protos so it is wire-compatible with the live server.+//+// Two upstream concerns are deliberately dropped because they do not affect the wire format:+//   * the `buf.validate` field options (server-side validation only), and+//   * the `google.api` service option (default_host annotation only).+// Each RPC returns a *wrapper* response message (e.g. GetAppListingResponse) — decoding the+// inner message directly is what produced the earlier garbled listings.+//+// The security posture does not depend on this schema: trust comes from the ed25519-signed+// repodata and on-device APK signature + min-version verification; these RPCs only supply+// listings and download URLs.++// Graphical image to be displayed in client UI.+message Image {+  optional string url = 1;+}++// A localized store listing for a given app.+message AppListing {+  optional string app_id = 1;+  optional string language = 2;+  optional string name = 3;+  optional string short_description = 4;+  Image icon = 5;+}++// Package information for a given app.+message PackageInfo {+  optional uint64 version_code = 1;+  optional string version_name = 2;+}++// A client device's hardware and OS attributes.+message DeviceAttributes {+  android.bundle.DeviceSpec spec = 1;+}++// Download info for an individual split APK.+message SplitDownloadInfo {+  optional uint32 download_size = 1;+  optional string url = 2;+}++// App download information for a given app.+message AppDownloadInfo {+  repeated SplitDownloadInfo split_download_info = 1;+}++// Update info for an individual split APK.+message SplitUpdateInfo {+  optional uint32 apk_download_size = 1;+  optional string apk_url = 2;+}++// App update information. Carries only the splits; whether an update exists is signalled by the+// presence of the wrapping GetAppUpdateInfoResponse.app_update_info field.+message AppUpdateInfo {+  repeated SplitUpdateInfo split_update_info = 1;+}++message ListAppListingsRequest {+  optional uint32 page_size = 1;+  optional string page_token = 2;+  optional uint32 skip = 3;+  repeated string preferred_languages = 4;+}++message ListAppListingsResponse {+  repeated AppListing listings = 1;+  optional string next_page_token = 2;+}++message GetAppListingRequest {+  optional string app_id = 1;+  repeated string preferred_languages = 2;+}++message GetAppListingResponse {+  AppListing listing = 1;+}++message GetAppPackageInfoRequest {+  optional string app_id = 1;+}++message GetAppPackageInfoResponse {+  PackageInfo package_info = 1;+}++message GetAppDownloadInfoRequest {+  optional string app_id = 1;+  DeviceAttributes device_attributes = 2;+}++message GetAppDownloadInfoResponse {+  AppDownloadInfo app_download_info = 1;+}++message GetAppUpdateInfoRequest {+  optional string app_id = 1;+  DeviceAttributes device_attributes = 2;+  optional uint64 base_version_code = 3;+}++// The app's update info is present if and only if the app is not up-to-date.+message GetAppUpdateInfoResponse {+  AppUpdateInfo app_update_info = 1;+}++service AppService {+  rpc GetAppListing(GetAppListingRequest) returns (GetAppListingResponse);+  rpc ListAppListings(ListAppListingsRequest) returns (ListAppListingsResponse);+  rpc GetAppPackageInfo(GetAppPackageInfoRequest) returns (GetAppPackageInfoResponse);+  rpc GetAppDownloadInfo(GetAppDownloadInfoRequest) returns (GetAppDownloadInfoResponse);+  rpc GetAppUpdateInfo(GetAppUpdateInfoRequest) returns (GetAppUpdateInfoResponse);+}
appstore/src/main/proto/android/bundle/devicespec.proto
diff --git a/appstore/src/main/proto/android/bundle/devicespec.proto b/appstore/src/main/proto/android/bundle/devicespec.protonew file mode 100644index 0000000000..6963c6c9e1--- /dev/null+++ b/appstore/src/main/proto/android/bundle/devicespec.proto@@ -0,0 +1,33 @@+syntax = "proto3";++package android.bundle;++option java_package = "com.android.bundle";+option java_multiple_files = true;+// Distinct outer-class name: without this, protoc derives the outer class "Devicespec" from+// the file name, whose generated Devicespec.java collides with the DeviceSpec message's+// DeviceSpec.java on case-insensitive filesystems (Windows/macOS), clobbering the message class.+option java_outer_classname = "DeviceSpecProto";++// Vendored subset of Android bundletool's `DeviceSpec` (google/bundletool `devices.proto`),+// with the exact upstream field numbers so it is wire-compatible with the DeviceSpec that+// Accrescent's appstore API consumes for split (config APK) selection.+//+// Only the fields this client actually populates are declared. Fields 8 (device_tier), 9+// (device_groups), 10 (sdk_runtime) and 11 (country_set) are intentionally omitted — they are+// unused here and 8/11 would drag in google/protobuf/wrappers.proto. Omitting a field number+// is wire-safe: it is simply never sent. The remaining numbers match upstream exactly.+message DeviceSpec {+  repeated string supported_abis = 1;+  repeated string supported_locales = 2;+  repeated string device_features = 3;+  repeated string gl_extensions = 4;+  uint32 screen_density = 5;+  uint32 sdk_version = 6;+  string codename = 7;+  int64 ram_bytes = 12;+  string build_brand = 13;+  string build_device = 14;+  string soc_manufacturer = 15;+  string soc_model = 16;+}
appstore/src/main/res/values/strings.xml
diff --git a/appstore/src/main/res/values/strings.xml b/appstore/src/main/res/values/strings.xmlindex fa6d93b407..2321a7b317 100644--- a/appstore/src/main/res/values/strings.xml+++ b/appstore/src/main/res/values/strings.xml@@ -23,6 +23,7 @@     <string name="source_chip_fdroid">F-Droid</string>     <string name="source_chip_grapheneos">GrapheneOS</string>     <string name="source_chip_play">Play Store</string>+    <string name="source_chip_accrescent">Accrescent</string>     <string name="filter_all">All</string>     <string name="filter_with_count">%1$s (%2$d)</string>     <string name="category_all">All</string>@@ -36,6 +37,8 @@     <string name="section_category_subtitle">Apps from the offline catalogue in this category</string>     <string name="section_sandboxed_google_play">Sandboxed Google Play</string>     <string name="section_sandboxed_google_play_subtitle">Google\'s Play components as ordinary, unprivileged apps</string>+    <string name="section_accrescent">On Accrescent</string>+    <string name="section_accrescent_subtitle">Developer-signed apps from Accrescent\'s signed app list</string>     <string name="action_install_all">Install all</string>     <string name="home_empty_title">Nothing here yet</string>     <string name="home_empty_message">Sync your sources to fill this up, or search for an app by name.</string>@@ -191,6 +194,16 @@     <string name="trust_play_check_stamp">The app\'s publisher stamp is saved the first time you install it, and has to stay the same afterwards</string>     <string name="trust_play_limits">No source code and no second build, so nothing proves the app matches any published source. Google supplies both the file and the expectation it is checked against, so these checks catch a tampered download but not a bad update Google signs itself. This store also reaches Play through an anonymous account rather than the official client, so it sees less than the Play app does.</string> +    <string name="trust_accrescent_title">Accrescent</string>+    <string name="trust_accrescent_summary">Apps signed by their own developers, listed on Accrescent\'s ed25519-signed allowlist which pins each app\'s signing key and lowest allowed version.</string>+    <string name="trust_accrescent_practice_developer_key">Each app is signed by its developer\'s own key, not by Accrescent</string>+    <string name="trust_accrescent_practice_signed_list">Which apps are legitimate, and each one\'s expected key, come from a single ed25519-signed list</string>+    <string name="trust_accrescent_practice_min_version">The list records a minimum version per app, so an old build can\'t be pushed back onto you</string>+    <string name="trust_accrescent_check_list_signed">The app list is signed and checked against a key built into this store, with a timestamp that can never go backwards</string>+    <string name="trust_accrescent_check_key">The download is signed by exactly the key the signed list names for this app</string>+    <string name="trust_accrescent_check_min_version">The download\'s version is at or above the minimum the signed list allows</string>+    <string name="trust_accrescent_limits">Accrescent publishes no per-file hashes and no reproducible builds, so the guarantee is the signature and minimum version, not a match against source. Listings and download links come from an ordinary server over gRPC; a bad response can only ever produce a file that fails these signature and version checks. Nobody scans the apps, and there is no way to pull a bad release back off phones.</string>+     <!-- Sources page. -->     <string name="repos_syncing">Syncing…</string>     <string name="repos_sync_sources">Sync sources</string>@@ -200,4 +213,6 @@     <string name="source_fdroid_pin">Pinned to F-Droid\'s app list signing key</string>     <string name="source_play">Play Store (anonymous)</string>     <string name="source_play_pin">Nothing to pin: Google holds the signing key</string>+    <string name="source_accrescent">Accrescent</string>+    <string name="source_accrescent_pin">Pinned to Accrescent\'s repodata signing key (ed25519)</string> </resources>
gradle/libs.versions.toml
diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.tomlindex 64778f55b9..d4648d9147 100644--- a/gradle/libs.versions.toml+++ b/gradle/libs.versions.toml@@ -67,6 +67,16 @@ ink = "1.1.0-alpha04" # Google libraries protobuf = "4.36.0-RC1" protobufJavalite = "4.35.0"+# gRPC for the Accrescent app source (:appstore). grpc-java + grpc-kotlin coroutine stubs+# over grpc-okhttp; the messages are generated as protobuf-lite to match the repo's other+# protobuf module (:networklocation). These versions must stay mutually compatible with+# protobufJavalite above and are the most likely first build-friction point.+grpc = "1.69.0"+grpcKotlin = "1.4.1"+# BouncyCastle: ed25519 verification of Accrescent's signify-signed repodata (:appstore).+bouncycastle = "1.79"+# @javax.annotation.Generated referenced by grpc-java generated stubs.+javaxAnnotation = "1.3.2" jsr305 = "3.0.2" zxing = "3.5.4" libphonenumber = "9.0.34"@@ -221,6 +231,16 @@ androidx-ink-rendering = { group = "androidx.ink", name = "ink-rendering", versi # Google libraries protobuf-java = { module = "com.google.protobuf:protobuf-java", version.ref = "protobuf" } protobuf-javalite = { module = "com.google.protobuf:protobuf-javalite", version.ref = "protobufJavalite" }+protobuf-kotlin-lite = { module = "com.google.protobuf:protobuf-kotlin-lite", version.ref = "protobufJavalite" }+# gRPC runtime + codegen (:appstore Accrescent source)+grpc-okhttp = { module = "io.grpc:grpc-okhttp", version.ref = "grpc" }+grpc-protobuf-lite = { module = "io.grpc:grpc-protobuf-lite", version.ref = "grpc" }+grpc-stub = { module = "io.grpc:grpc-stub", version.ref = "grpc" }+grpc-kotlin-stub = { module = "io.grpc:grpc-kotlin-stub", version.ref = "grpcKotlin" }+grpc-protoc-gen-java = { module = "io.grpc:protoc-gen-grpc-java", version.ref = "grpc" }+grpc-protoc-gen-kotlin = { module = "io.grpc:protoc-gen-grpc-kotlin", version.ref = "grpcKotlin" }+bouncycastle-bcprov = { module = "org.bouncycastle:bcprov-jdk18on", version.ref = "bouncycastle" }+javax-annotation-api = { module = "javax.annotation:javax.annotation-api", version.ref = "javaxAnnotation" } google-jsr305 = { module = "com.google.code.findbugs:jsr305", version.ref = "jsr305" } zxing-core = { module = "com.google.zxing:core", version.ref = "zxing" } libphonenumber = { module = "com.googlecode.libphonenumber:libphonenumber", version.ref = "libphonenumber" }
proguard-rules.pro
diff --git a/proguard-rules.pro b/proguard-rules.proindex ea434a3ea1..98f910275e 100644--- a/proguard-rules.pro+++ b/proguard-rules.pro@@ -94,6 +94,24 @@ -keep class org.bouncycastle.** { *; } -dontwarn org.bouncycastle.** +# gRPC + okhttp + protobuf-lite (:appstore Accrescent source). grpc-okhttp is the first+# okhttp in the repo. grpc looks up its transport/name-resolver providers via reflection and+# META-INF/services; okhttp/okio and grpc reference optional compile-time deps (Conscrypp,+# error-prone, javax.annotation, animal-sniffer) that are absent at runtime on Android.+-keep class io.grpc.** { *; }+-dontwarn io.grpc.**+-keep class okhttp3.** { *; }+-keep interface okhttp3.** { *; }+-dontwarn okhttp3.**+-keep class okio.** { *; }+-dontwarn okio.**+-dontwarn com.google.errorprone.annotations.**+-dontwarn javax.annotation.**+-dontwarn org.codehaus.mojo.animal_sniffer.**+-dontwarn org.conscrypt.**+# Accrescent's generated protobuf-lite messages (app.accrescent.appstore.v1, com.android.bundle)+# are covered by the GeneratedMessageLite keep above; grpc service descriptors are under io.grpc.+ # logback-classic (transitive via KeePassJava2-dom, used by :passwords) is a # server-side SLF4J backend that references the Servlet API. javax.servlet.* # doesn't exist on Android, so R8 flags the dangling reference. logback's