Phase 5: in-app update check with SHA-256 verification
Browse files12345678910111213141516171819202122232425262728293031323334353637package io.github.abrarul.modularai.update
import io.github.abrarul.modularai.BuildConfigimport kotlinx.coroutines.Dispatchersimport kotlinx.coroutines.withContextimport org.json.JSONObjectimport java.io.Fileimport java.net.URLimport java.security.MessageDigest
/** * Manifest (JSON) hosted next to releases: * {"versionCode":2,"versionName":"0.2.0","apk":"https://.../app.apk","sha256":"..."} * Android itself refuses to install an update signed with a different key, which is the * real signature check; SHA-256 guards against corrupt or tampered downloads. */data class UpdateInfo(val versionCode: Int, val versionName: String, val apkUrl: String, val sha256: String)
class Updater(private val manifestUrl: String, private val cacheDir: File) {
suspend fun check(): UpdateInfo? = withContext(Dispatchers.IO) { val j = JSONObject(URL(manifestUrl).readText()) val info = UpdateInfo(j.getInt("versionCode"), j.getString("versionName"), j.getString("apk"), j.getString("sha256")) if (info.versionCode > BuildConfig.VERSION_CODE) info else null }
suspend fun download(info: UpdateInfo): File = withContext(Dispatchers.IO) { val f = File(cacheDir, "update-${info.versionCode}.apk") URL(info.apkUrl).openStream().use { i -> f.outputStream().use { o -> i.copyTo(o) } } val md = MessageDigest.getInstance("SHA-256") f.inputStream().use { i -> val b = ByteArray(1 shl 20); while (true) { val n = i.read(b); if (n < 0) break; md.update(b, 0, n) } } val actual = md.digest().joinToString("") { "%02x".format(it) } if (!actual.equals(info.sha256, ignoreCase = true)) { f.delete(); error("Update checksum mismatch") } f } // Install hand-off (PackageInstaller / FileProvider) is the next task.}app/src/main/java/io/github/abrarul/modularai/update/Updater.ktAdded+37