package dev.healkite import android.content.Context import android.content.pm.PackageManager import android.os.Build import org.json.JSONArray import org.json.JSONObject import java.io.File import java.io.IOException import java.net.HttpURLConnection import java.net.URL import java.util.UUID import java.util.concurrent.Executors /** * Healkite native core (Android). Same state machine as HealkiteCore.swift: * installUpdate → pending → trial launch (pendingLaunched) → notifyAppReady → * current. A trial launch that never confirms is rolled back on the next launch. */ class HealkiteCore private constructor(private val context: Context) { companion object { private const val MAX_HANDOFF_CHARS = 256 * 1024 private const val HANDOFF_TTL_MS = 2 * 60_000L @Volatile private var instance: HealkiteCore? = null @JvmStatic fun get(context: Context): HealkiteCore = instance ?: synchronized(this) { instance ?: HealkiteCore(context.applicationContext).also { instance = it } } private val HEX64 = Regex("^[0-9a-f]{64}$") private val PREVIEW_CHANNEL = Regex("^[a-z0-9][a-z0-9-]{2,99}$") fun sha256Hex(bytes: ByteArray): String = Hashing.sha256Hex(bytes) } private data class State( var binaryId: String, var deviceId: String, var current: String? = null, var previous: String? = null, var pending: String? = null, var pendingLaunched: Boolean = false, var failed: MutableList = mutableListOf(), var lastRollback: Pair? = null, var clearOnNextLaunch: Boolean = false, var entries: MutableMap = mutableMapOf(), var lastInstallMethod: String? = null, var lastManifestAt: Double? = null, /** PR preview: channel key used instead of healkite_channel until cleared (reset by a new binary). */ var previewChannel: String? = null, ) private val lock = Any() private val executor = Executors.newSingleThreadExecutor() private val rootDir = File(context.filesDir, "healkite") private val updatesDir = File(rootDir, "updates") private val stateFile = File(rootDir, "state.json") private val eventsFile = File(rootDir, "events.json") private val handoffFile = File(rootDir, "handoff.json") private val maxQueuedEvents = 200 private var resolved = false private var resolvedPath: String? = null private var running = "embedded" private var reresolve = false init { updatesDir.mkdirs() } // ---- Config ---- private fun res(name: String): String? { val id = context.resources.getIdentifier(name, "string", context.packageName) return if (id == 0) null else context.getString(id).ifEmpty { null } } private val packageInfo by lazy { if (Build.VERSION.SDK_INT >= 33) { context.packageManager.getPackageInfo(context.packageName, PackageManager.PackageInfoFlags.of(0)) } else { @Suppress("DEPRECATION") context.packageManager.getPackageInfo(context.packageName, 0) } } private val binaryVersion: String get() { val code = if (Build.VERSION.SDK_INT >= 28) packageInfo.longVersionCode else @Suppress("DEPRECATION") packageInfo.versionCode.toLong() return "${packageInfo.versionName ?: "0"} ($code)" } /** Changes on every install/update of the binary (store or local). */ private val binaryId: String get() = "$binaryVersion#${packageInfo.lastUpdateTime}" fun configJson(): String { val state = synchronized(lock) { loadState() } return JSONObject() .put("cdnUrl", res("healkite_cdn_url") ?: "") .put("cdnFallbackUrl", res("healkite_cdn_fallback_url") ?: "") .put("channel", state.previewChannel ?: res("healkite_channel") ?: "production") .put("baseChannel", res("healkite_channel") ?: "production") .put("previewChannel", state.previewChannel ?: JSONObject.NULL) .put("runtimeVersion", res("healkite_runtime_version") ?: packageInfo.versionName ?: "0") .put("binaryVersion", binaryVersion) .put("deviceId", state.deviceId) .put("platform", "android") .put("signingRequired", signingPublicKey != null) .put("manifestSigningRequired", manifestPublicKey != null) .toString() } /** Server manifest key (`healkite_manifest_key`): manifests must be signed and never go back in time. */ private val manifestPublicKey: String? get() = res("healkite_manifest_key") /** "ok" | "no-key" | "invalid" | "stale" — see NativeHealkite.ts. */ fun verifyManifest(payload: String, signature: String, generatedAt: Double): String { val key = manifestPublicKey ?: return "no-key" val valid = try { BundleSignature.verifyManifest( payload, android.util.Base64.decode(signature, android.util.Base64.DEFAULT), android.util.Base64.decode(key, android.util.Base64.DEFAULT), ) } catch (_: IllegalArgumentException) { false } if (!valid) return "invalid" synchronized(lock) { val s = loadState() val last = s.lastManifestAt if (last != null && generatedAt < last) return "stale" s.lastManifestAt = generatedAt saveState(s) return "ok" } } /** Base64 SPKI P-256 key from `healkite_public_key`. When present, unsigned updates are refused. */ private val signingPublicKey: String? get() = res("healkite_public_key") fun stateJson(): String = synchronized(lock) { stateJson(loadState()) } // ---- Launch resolution ---- /** Absolute path of the bundle to load, or null for the embedded asset bundle. */ fun resolveBundlePath(): String? { synchronized(lock) { if (resolved && !reresolve) return resolvedPath resolved = true reresolve = false var s = loadState() if (s.binaryId != binaryId) { wipeUpdates() s = freshState(s.deviceId) } if (s.clearOnNextLaunch) { wipeUpdates() s = freshState(s.deviceId, s.failed) } s.pending?.let { p -> if (s.pendingLaunched) { s.failed = (s.failed + p).takeLast(20).toMutableList() s.lastRollback = p to System.currentTimeMillis().toDouble() appendEvent("update.rollback", null, JSONObject().put("sha256", p)) File(updatesDir, p).deleteRecursively() s.entries.remove(p) s.pending = null s.pendingLaunched = false } else { val path = entryPath(p, s) if (path != null) { s.pendingLaunched = true saveState(s) running = p resolvedPath = path return path } s.pending = null } } val current = s.current val path = current?.let { entryPath(it, s) } if (current != null && path != null) { running = current resolvedPath = path } else { s.current = null running = "embedded" resolvedPath = null } saveState(s) return resolvedPath } } // ---- JS API ---- fun notifyAppReady(): String = synchronized(lock) { val s = loadState() val p = s.pending if (p != null && s.pendingLaunched && running == p) { if (s.current != p) s.previous = s.current s.current = p s.pending = null s.pendingLaunched = false saveState(s) cleanup(s) appendEvent("update.ready", null, JSONObject().put("sha256", p)) } stateJson(s) } /** PR previews: switch to another channel key ("" = back to the configured channel). */ fun setPreviewChannel(channel: String): String { val next = channel.trim().ifEmpty { null } require(next == null || PREVIEW_CHANNEL.matches(next)) { "invalid channel key" } synchronized(lock) { val s = loadState() if (s.previewChannel != next) { s.previewChannel = next s.lastManifestAt = null // replay protection is per channel saveState(s) } } return configJson() } fun clearUpdates() = synchronized(lock) { val s = loadState() s.clearOnNextLaunch = true saveState(s) } fun prepareRestart() = synchronized(lock) { reresolve = true } fun installUpdate(sha256: String, url: String, signature: String, patchJson: String, done: (String?, String?) -> Unit) { if (!HEX64.matches(sha256)) return done(null, "Invalid sha256") // The signature covers the sha256; the result must match it (full download) or come // from a signed patch, so an unauthorised bundle is never downloaded. val publicKey = signingPublicKey if (publicKey != null && !verifySignature(sha256, signature, publicKey)) { return done(null, if (signature.isEmpty()) "Update is unsigned but this app requires signed updates" else "Update signature is invalid") } val snapshot = synchronized(lock) { loadState() } if (sha256 == running || sha256 == snapshot.pending) return done(stateJson(), null) if (snapshot.failed.contains(sha256)) { return done(null, "Update ${sha256.take(12)} previously failed on this device") } val patch = parsePatch(patchJson) executor.execute { val staging = File(updatesDir, "$sha256.partial") val final = File(updatesDir, sha256) val started = System.currentTimeMillis() try { var method = "full" var downloaded = 0L var entry: String? = null if (patch != null) { entry = try { installFromPatch(patch, sha256, staging) } catch (e: Exception) { synchronized(lock) { appendEvent("update.error", "patch_fallback", JSONObject().put("sha256", sha256).put("message", e.message ?: e.toString())) } null // fall back to the full download } if (entry != null) { method = "patch" downloaded = patch.size } } if (entry == null) { staging.deleteRecursively() staging.mkdirs() val bytes = download(url) if (sha256Hex(bytes) != sha256) throw IOException("Checksum mismatch for downloaded bundle") downloaded = bytes.size.toLong() entry = HkbReader.unpack(bytes, staging) } final.deleteRecursively() if (!staging.renameTo(final)) throw IOException("Could not move bundle into place") val json = synchronized(lock) { val s = loadState() s.pending = sha256 s.pendingLaunched = false s.entries[sha256] = entry s.clearOnNextLaunch = false s.lastInstallMethod = method saveState(s) cleanup(s) appendEvent( "update.install", method, JSONObject().put("sha256", sha256).put("bytes", downloaded).put("ms", System.currentTimeMillis() - started), ) stateJson(s) } done(json, null) } catch (e: Exception) { staging.deleteRecursively() synchronized(lock) { appendEvent("update.error", "install", JSONObject().put("sha256", sha256).put("message", e.message ?: e.toString())) } done(null, "Install failed: ${e.message}") } } } private data class PatchRef(val from: String, val url: String, val sha256: String, val size: Long, val signature: String?) private fun parsePatch(json: String): PatchRef? = if (json.isEmpty()) { null } else { try { val o = JSONObject(json) PatchRef(o.getString("from"), o.getString("url"), o.getString("sha256"), o.getLong("size"), o.optStringOrNull("signature")) } catch (_: Exception) { null } } /** Applies a patch on top of the running bundle. Throws on any problem (caller falls back). */ private fun installFromPatch(patch: PatchRef, sha256: String, staging: File): String { val baseReady = synchronized(lock) { patch.from == running && entryPath(patch.from, loadState()) != null } if (!baseReady) throw IOException("patch base is not the running bundle") val publicKey = signingPublicKey if (publicKey != null) { val sig = patch.signature ?: throw IOException("patch is unsigned") val ok = try { BundleSignature.verifyPatch( patch.from, sha256, patch.sha256, android.util.Base64.decode(sig, android.util.Base64.DEFAULT), android.util.Base64.decode(publicKey, android.util.Base64.DEFAULT), ) } catch (_: IllegalArgumentException) { false } if (!ok) throw IOException("patch signature is invalid") } val bytes = download(patch.url) if (bytes.size.toLong() != patch.size || sha256Hex(bytes) != patch.sha256) throw IOException("patch checksum mismatch") staging.deleteRecursively() staging.mkdirs() return HkpReader.apply(bytes, patch.from, sha256, File(updatesDir, patch.from), staging) } // ---- Event queue (drained and sent by the JS layer) ---- /** Call with `lock` held. */ private fun appendEvent(type: String, name: String?, data: JSONObject) { val events = loadEvents() val e = JSONObject().put("t", System.currentTimeMillis()).put("type", type).put("data", data) if (name != null) e.put("name", name) events.put(e) saveEvents(events) } private fun loadEvents(): JSONArray = try { if (eventsFile.exists()) JSONArray(eventsFile.readText()) else JSONArray() } catch (_: Exception) { JSONArray() } private fun saveEvents(events: JSONArray) { if (events.length() == 0) { eventsFile.delete() return } val start = maxOf(0, events.length() - maxQueuedEvents) val capped = JSONArray() for (i in start until events.length()) capped.put(events.get(i)) rootDir.mkdirs() eventsFile.writeText(capped.toString()) } /** Live patch: app state kept across the restart that applies an update now (read once, within 2 minutes). */ fun setHandoff(json: String): Boolean { if (json.length > MAX_HANDOFF_CHARS) return false return try { rootDir.mkdirs() handoffFile.writeText(JSONObject().put("savedAt", System.currentTimeMillis()).put("state", json).toString()) true } catch (_: Exception) { false } } fun takeHandoff(): String { if (!handoffFile.exists()) return "" return try { val o = JSONObject(handoffFile.readText()) val fresh = System.currentTimeMillis() - o.optLong("savedAt") < HANDOFF_TTL_MS if (fresh) o.optString("state", "") else "" } catch (_: Exception) { "" } finally { handoffFile.delete() } } /** Persists an event from JS synchronously (used for fatal JS errors). Only app-level types are accepted. */ fun recordEvent(json: String): Boolean { val e = try { JSONObject(json) } catch (_: Exception) { return false } val type = e.optString("type") if (type != "error" && type != "custom") return false val name = e.optStringOrNull("name")?.take(64) val data = e.optJSONObject("data") ?: JSONObject() synchronized(lock) { appendEvent(type, name, data) } return true } fun drainEventsJson(): String = synchronized(lock) { val events = loadEvents() saveEvents(JSONArray()) events.toString() } fun requeueEventsJson(json: String) { val returned = try { JSONArray(json) } catch (_: Exception) { return } if (returned.length() == 0) return synchronized(lock) { val merged = JSONArray() for (i in 0 until returned.length()) merged.put(returned.get(i)) val existing = loadEvents() for (i in 0 until existing.length()) merged.put(existing.get(i)) saveEvents(merged) } } // ---- Helpers ---- private fun verifySignature(sha256: String, signature: String, publicKey: String): Boolean = try { BundleSignature.verify( sha256, android.util.Base64.decode(signature, android.util.Base64.DEFAULT), android.util.Base64.decode(publicKey, android.util.Base64.DEFAULT), ) } catch (_: IllegalArgumentException) { false } private fun download(url: String): ByteArray { val conn = URL(url).openConnection() as HttpURLConnection conn.connectTimeout = 15_000 conn.readTimeout = 120_000 try { if (conn.responseCode !in 200..299) throw IOException("Download failed: HTTP ${conn.responseCode}") return conn.inputStream.use { it.readBytes() } } finally { conn.disconnect() } } private fun freshState(deviceId: String?, failed: List = emptyList()) = State(binaryId = binaryId, deviceId = deviceId ?: UUID.randomUUID().toString(), failed = failed.toMutableList()) private fun loadState(): State { try { if (stateFile.exists()) { val o = JSONObject(stateFile.readText()) val failed = o.optJSONArray("failed")?.let { a -> MutableList(a.length()) { a.getString(it) } } ?: mutableListOf() val entries = mutableMapOf() o.optJSONObject("entries")?.let { e -> e.keys().forEach { k -> entries[k] = e.getString(k) } } val rb = o.optJSONObject("lastRollback")?.let { it.getString("sha256") to it.getDouble("at") } return State( binaryId = o.getString("binaryId"), deviceId = o.getString("deviceId"), current = o.optStringOrNull("current"), previous = o.optStringOrNull("previous"), pending = o.optStringOrNull("pending"), pendingLaunched = o.optBoolean("pendingLaunched"), failed = failed, lastRollback = rb, clearOnNextLaunch = o.optBoolean("clearOnNextLaunch"), entries = entries, lastInstallMethod = o.optStringOrNull("lastInstallMethod"), lastManifestAt = if (o.has("lastManifestAt") && !o.isNull("lastManifestAt")) o.getDouble("lastManifestAt") else null, previewChannel = o.optStringOrNull("previewChannel"), ) } } catch (_: Exception) { // Corrupt state: start fresh (embedded bundle is always safe). } return freshState(null).also { saveState(it) } } private fun saveState(s: State) { rootDir.mkdirs() val o = JSONObject() .put("binaryId", s.binaryId) .put("deviceId", s.deviceId) .put("current", s.current ?: JSONObject.NULL) .put("previous", s.previous ?: JSONObject.NULL) .put("pending", s.pending ?: JSONObject.NULL) .put("pendingLaunched", s.pendingLaunched) .put("failed", JSONArray(s.failed)) .put("clearOnNextLaunch", s.clearOnNextLaunch) .put("entries", JSONObject(s.entries as Map<*, *>)) .put("lastInstallMethod", s.lastInstallMethod ?: JSONObject.NULL) .put("lastRollback", s.lastRollback?.let { JSONObject().put("sha256", it.first).put("at", it.second) } ?: JSONObject.NULL) .put("lastManifestAt", s.lastManifestAt ?: JSONObject.NULL) .put("previewChannel", s.previewChannel ?: JSONObject.NULL) val tmp = File(rootDir, "state.json.tmp") tmp.writeText(o.toString()) if (!tmp.renameTo(stateFile)) { stateFile.writeText(o.toString()) tmp.delete() } } private fun stateJson(s: State): String = JSONObject() .put("running", running) .put("current", s.current ?: JSONObject.NULL) .put("previous", s.previous ?: JSONObject.NULL) .put("pending", s.pending ?: JSONObject.NULL) .put("pendingLaunched", s.pendingLaunched) .put("failed", JSONArray(s.failed)) .put("clearOnNextLaunch", s.clearOnNextLaunch) .put("lastRollback", s.lastRollback?.let { JSONObject().put("sha256", it.first).put("at", it.second) } ?: JSONObject.NULL) .put("lastInstallMethod", s.lastInstallMethod ?: JSONObject.NULL) .toString() private fun entryPath(sha: String, s: State): String? { val entry = s.entries[sha] ?: return null val file = File(File(updatesDir, sha), entry) return if (file.isFile) file.absolutePath else null } private fun wipeUpdates() { updatesDir.deleteRecursively() updatesDir.mkdirs() } private fun cleanup(s: State) { val keep = setOfNotNull(s.current, s.previous, s.pending, running) updatesDir.listFiles()?.forEach { f -> if (f.name !in keep && !f.name.endsWith(".partial")) f.deleteRecursively() } } } private fun JSONObject.optStringOrNull(key: String): String? = if (isNull(key)) null else optString(key, "").ifEmpty { null }