UpdateManifest.kt

14.1 KB · raw

1package com.peachpasswords.updates23import org.bouncycastle.crypto.digests.Blake3Digest4import org.json.JSONArray5import org.json.JSONObject6import java.io.File7import java.io.InputStream8import java.security.MessageDigest910/**11 * Kepr's generic release manifest, as returned by12 * `GET https://kepr.uk/api/<repo>/releases/latest`, flattened to the single13 * platform this app can install.14 *15 * ```json16 * { "version": "2.3.68",17 *   "notes": "...",18 *   "platforms": { "android-arm64": { "url": "...", "checksum": "blake3:<64 hex>" } } }19 * ```20 */21data class ReleaseManifest(22    val version: String,23    val url: String,24    val checksum: String,25    /** Absent — not empty, not "null" — when the release carries no notes. */26    val notes: String?,27    /** Kepr platform key represented by this flattened manifest. */28    val platformKey: String = ANDROID_PLATFORM_KEY,29) {30    fun toJson(): String = JSONObject().apply {31        put("version", version)32        if (notes != null) put("notes", notes)33        put("platforms", JSONObject().put(platformKey, JSONObject().apply {34            put("url", url)35            put(checksum.substringBefore(':'), checksum.substringAfter(':'))36        }))37    }.toString()3839    companion object {40        /** Cached and network manifests share the same strict parser. */41        fun fromCachedJson(json: String): ReleaseManifest? = runCatching {42            parseReleaseManifest(json)43        }.getOrNull()44    }45}4647class ManifestFormatException(message: String) : Exception(message)4849/** Thrown when the APK on disk is not the package/version the updater was told to install. */50class ApkIdentityException(message: String) : Exception(message)5152/** Thrown when the download would exceed [MAX_APK_BYTES] or advertise a larger Content-Length. */53class DownloadSizeException(message: String) : Exception(message)5455/**56 * Kepr platform keys for the two APK splits Peach publishes. `android-x86`57 * carries the x86_64 APK; the shorter public key matches Kepr's platform58 * vocabulary while Android's ABI name remains `x86_64` inside the archive.59 */60const val ANDROID_PLATFORM_KEY = "android-arm64"61const val ANDROID_X86_PLATFORM_KEY = "android-x86"6263fun androidPlatformKey(supportedAbis: Array<String>): String? = when {64    "arm64-v8a" in supportedAbis -> ANDROID_PLATFORM_KEY65    "x86_64" in supportedAbis -> ANDROID_X86_PLATFORM_KEY66    else -> null67}6869sealed interface UpdateCheckResult {70    data class Accepted(val manifest: ReleaseManifest) : UpdateCheckResult71    data class NoUpdate(val version: String) : UpdateCheckResult72    data class RollbackSuppressed(val servedVersion: String, val highWaterVersion: String) : UpdateCheckResult73}74/**75 * Hard ceiling on a downloaded APK. Kepr publishes ~24 MB today; 50 MB leaves76 * headroom for growth without letting a hostile manifest exhaust cache or disk.77 */78const val MAX_APK_BYTES = 50L * 1024 * 10247980/**81 * Strict SemVer core: exactly three non-empty, non-leading-zero decimal82 * components, each small enough to fit in an Int. Anything else (NaN segments,83 * extra components, negatives, overflow) is refused — the manifest's version84 * is later used to derive the cache filename, so a permissive parser here would85 * let `..` or `/` reach the filesystem.86 */87private val STRICT_SEMVER = Regex("""^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$""")8889internal fun validateSemver(version: String) {90    if (!STRICT_SEMVER.matches(version)) {91        throw ManifestFormatException("version '$version' is not strict SemVer major.minor.patch")92    }93    version.split('.').forEach { seg ->94        // STRICT_SEMVER already excludes non-digits and leading zeros, so this95        // overflow check is the only thing left standing between "9999999999"96        // and a silently-wrapped compareVersions result.97        if (seg.length > 9 || seg.toLong() > Int.MAX_VALUE) {98            throw ManifestFormatException("version '$version' has an out-of-range segment")99        }100    }101}102103/**104 * True when a parsed APK archive is the package and version this updater105 * belongs to. Pure: takes the values PackageManager already extracted so the106 * Android side stays at the call site and this stays unit-testable.107 *108 * The package must be an exact match. In particular, a production build must109 * never hand a separately-installable `.debug` package to Android's installer.110 * Debug builds still work in their own process because the caller supplies111 * that process's exact `Context.packageName` as [expectedPackage].112 */113fun isExpectedApk(114    packageName: String?,115    versionName: String?,116    versionCode: Long,117    expectedPackage: String,118    expectedVersionName: String,119    currentVersionCode: Long,120): Boolean {121    if (packageName != expectedPackage) return false122    if (versionName != expectedVersionName) return false123    // Kepr's release manifest carries the semantic version but not the Android124    // versionCode.  The enforceable contract is therefore exact SemVer plus a125    // strictly monotonic code, which blocks equal-version replays and downgrades126    // while still allowing Gradle to choose the next code independently.127    return versionCode > currentVersionCode128}129130/**131 * Select the PackageInfo version-code field without loading the API-28-only132 * property on Oreo.  Keeping the branch as a pure helper lets JVM tests cover133 * both sides even though the unit-test runner is not a real API-26 device.134 */135internal fun packageVersionCodeForSdk(136    sdkInt: Int,137    legacyVersionCode: Int,138    modernVersionCode: Long,139): Long = if (sdkInt >= 28) modernVersionCode else legacyVersionCode.toLong()140141/**142 * Select the signing-info flag set for the minimum supported API.  The flag143 * values are supplied by the Android caller so this helper remains a plain144 * integer decision that can be tested without an SDK emulator.145 */146internal fun packageSigningInfoFlagsForSdk(147    sdkInt: Int,148    legacyFlags: Int,149    modernFlags: Int,150): Int = if (sdkInt >= 28) modernFlags else legacyFlags151152/**153 * Check the direction of an APK signing-key rotation against the installed154 * package's current signer set.155 *156 * A normal update has the same current signer set. A forward v3 rotation has157 * the installed current signer in the archive's proof-of-rotation history and158 * a new current signer. The reverse direction (an old key with a higher159 * versionCode) is deliberately rejected: an archive must prove that it is a160 * descendant of the key currently protecting the installed app, not merely161 * share any historical certificate with it. Equal signer-set cardinality also162 * prevents a multi-signer package from being reduced to a subset.163 *164 * API 26/27 callers pass an empty [archiveHistory], making this an exact165 * signature-set comparison on platforms without [android.content.pm.SigningInfo].166 */167internal fun isSigningLineageCompatible(168    archiveCurrent: Set<String>,169    archiveHistory: Set<String>,170    installedCurrent: Set<String>,171): Boolean {172    if (archiveCurrent.isEmpty() || installedCurrent.isEmpty()) return false173    if (archiveCurrent.size != installedCurrent.size) return false174    return installedCurrent.all { it in archiveCurrent || it in archiveHistory }175}176177/**178 * Parse a Kepr release manifest.179 *180 * Two contract wrinkles are handled deliberately:181 * - The notes key is `notes` canonically, but the published Guidelines still show182 *   the retired `release_notes`. Both are accepted, `notes` winning.183 * - `optString` on a JSON null yields the literal string "null" in org.json, which184 *   would render as changelog text. [optTextOrNull] rejects that class of value185 *   outright rather than trusting the caller to notice.186 *187 * Security note: the canonical platform key is required and the sole-artifact188 * fallback is gone. A Kepr build that only published, say, `android-x86` would189 * otherwise point an Android phone at the wrong binary.190 */191fun parseReleaseManifest(body: String, platformKey: String = ANDROID_PLATFORM_KEY): ReleaseManifest {192    val root = runCatching { JSONObject(body) }193        .getOrElse { throw ManifestFormatException("manifest is not JSON") }194195    val version = root.optTextOrNull("version")196        ?: throw ManifestFormatException("manifest has no version")197    validateSemver(version)198199    val platforms = root.optJSONObject("platforms")200        ?: throw ManifestFormatException("manifest has no platforms")201202    val platform = platforms.optJSONObject(platformKey)203        ?: throw ManifestFormatException("manifest has no '$platformKey' artifact")204205    val url = platform.optTextOrNull("url")206        ?: throw ManifestFormatException("artifact has no url")207    if (!url.startsWith("https://")) {208        throw ManifestFormatException("artifact url must use https")209    }210    val checksum = parseArtifactChecksum(platform)211        ?: throw ManifestFormatException("artifact has no usable checksum (blake3, sha256, or legacy 'checksum')")212213    return ReleaseManifest(214        version = version,215        url = url,216        checksum = checksum,217        notes = root.optTextOrNull("notes") ?: root.optTextOrNull("release_notes"),218    )219}220221/**222 * Extract a `blake3:<hex>` (preferred) or `sha256:<hex>` checksum from a Kepr223 * artifact object. Three shapes are accepted:224 * - Modern: separate `blake3` and/or `sha256` top-level fields on the artifact.225 *   blake3 wins when both are present.226 * - Legacy: a single `checksum` field shaped as `<algorithm>:<64 hex>`. Older227 *   Kepr builds used this and the existing tests still pin it.228 * The string is normalized to `<algorithm>:<64 lowercase hex>` so229 * [parseChecksum] downstream can validate it.230 */231internal fun parseArtifactChecksum(artifact: org.json.JSONObject): String? {232    val blake3 = artifact.optTextOrNull("blake3")?.takeIf(::isHex64)233    if (blake3 != null) return "blake3:$blake3"234    val sha256 = artifact.optTextOrNull("sha256")?.takeIf(::isHex64)235    if (sha256 != null) return "sha256:$sha256"236    return artifact.optTextOrNull("checksum")237}238239private fun isHex64(value: String): Boolean =240    value.length == 64 && value.all { it in '0'..'9' || it in 'a'..'f' }241242/** Non-blank string value, or null — never JSON null surfaced as the text "null". */243internal fun JSONObject.optTextOrNull(key: String): String? {244    if (!has(key) || isNull(key)) return null245    return optString(key).trim().takeIf { it.isNotEmpty() }246}247248/** One published release from Kepr's `releases/history` endpoint. */249data class ReleaseNote(val version: String, val notes: String?)250251/**252 * Parse Kepr's `GET /api/<repo>/releases/history` response: a JSON array of253 * `{version, notes}` objects, newest first. Notes stay null when a release254 * shipped none, so the UI decides what to show for it.255 */256fun parseReleaseHistory(json: String): List<ReleaseNote> {257    val arr = JSONArray(json)258    return (0 until arr.length()).map { i ->259        val obj = arr.getJSONObject(i)260        ReleaseNote(obj.getString("version"), obj.optTextOrNull("notes"))261    }262}263264/* ─────────────────────────────  version compare  ───────────────────────────── */265266/**267 * Strip everything that isn't the numeric release, so a debug build268 * ("2.3.67-debug", from the `versionNameSuffix`) compares as the release it was269 * built from rather than as an unrelated string.270 */271fun normalizeVersion(version: String): String =272    version.trim().removePrefix("v").substringBefore('-').substringBefore('+')273274/**275 * Numeric-segment comparison — "2.3.67" < "2.3.100", which a string compare gets wrong.276 *277 * Tolerant on purpose, and only safely so: both untrusted entry points278 * ([parseReleaseManifest] and [ReleaseManifest.fromCachedJson]) run279 * [validateSemver] first, so the `?: 0` fallback is only ever reachable for the280 * locally built `BuildConfig.VERSION_NAME`. Throwing here instead would turn a281 * malformed local version string into a crash on every update check.282 */283fun compareVersions(a: String, b: String): Int {284    val left = normalizeVersion(a).split('.')285    val right = normalizeVersion(b).split('.')286    for (i in 0 until maxOf(left.size, right.size)) {287        val x = left.getOrNull(i)?.toIntOrNull() ?: 0288        val y = right.getOrNull(i)?.toIntOrNull() ?: 0289        if (x != y) return x.compareTo(y)290    }291    return 0292}293294fun isNewerVersion(candidate: String, current: String): Boolean = compareVersions(candidate, current) > 0295296/* ──────────────────────────────────  checksum  ─────────────────────────────── */297298data class ExpectedChecksum(val algorithm: String, val hex: String)299300class ChecksumMismatchException(message: String) : Exception(message)301302private val SUPPORTED_CHECKSUMS = setOf("blake3", "sha256")303304/** `blake3:<64 hex>` (Kepr's default) or `sha256:<64 hex>`. Anything else is refused. */305fun parseChecksum(raw: String): ExpectedChecksum? {306    val separator = raw.indexOf(':')307    if (separator <= 0) return null308    val algorithm = raw.substring(0, separator).trim().lowercase()309    val hex = raw.substring(separator + 1).trim().lowercase()310    if (algorithm !in SUPPORTED_CHECKSUMS) return null311    if (hex.length != 64 || hex.any { it !in "0123456789abcdef" }) return null312    return ExpectedChecksum(algorithm, hex)313}314315fun hashStream(input: InputStream, algorithm: String): String = when (algorithm) {316    "blake3" -> {317        val digest = Blake3Digest(32)318        val buffer = ByteArray(64 * 1024)319        while (true) {320            val read = input.read(buffer)321            if (read <= 0) break322            digest.update(buffer, 0, read)323        }324        val out = ByteArray(digest.digestSize)325        digest.doFinal(out, 0)326        out.toHex()327    }328    "sha256" -> {329        val digest = MessageDigest.getInstance("SHA-256")330        val buffer = ByteArray(64 * 1024)331        while (true) {332            val read = input.read(buffer)333            if (read <= 0) break334            digest.update(buffer, 0, read)335        }336        digest.digest().toHex()337    }338    else -> throw ChecksumMismatchException("unsupported checksum algorithm '$algorithm'")339}340341fun hashFile(file: File, algorithm: String): String =342    file.inputStream().use { hashStream(it, algorithm) }343344private fun ByteArray.toHex(): String = joinToString("") { "%02x".format(it) }