diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml
index 588ca46..15fe2cd 100644
--- a/app/src/main/AndroidManifest.xml
+++ b/app/src/main/AndroidManifest.xml
@@ -11,6 +11,13 @@
+
+
+
diff --git a/app/src/main/java/com/bansify/browser/ui/BrowserApp.kt b/app/src/main/java/com/bansify/browser/ui/BrowserApp.kt
index 80c3a95..372a309 100644
--- a/app/src/main/java/com/bansify/browser/ui/BrowserApp.kt
+++ b/app/src/main/java/com/bansify/browser/ui/BrowserApp.kt
@@ -113,6 +113,7 @@ fun BrowserApp(viewModel: BrowserViewModel) {
val sitePermissionDecisions by viewModel.sitePermissionDecisions.collectAsStateWithLifecycle()
val downloadProgress by viewModel.downloadProgress.collectAsStateWithLifecycle()
val adBlockAllowlist by viewModel.adBlockAllowlist.collectAsStateWithLifecycle()
+ val updateState by viewModel.updateState.collectAsStateWithLifecycle()
val bookmarks by viewModel.bookmarks.collectAsStateWithLifecycle()
val history by viewModel.history.collectAsStateWithLifecycle()
val downloads by viewModel.downloads.collectAsStateWithLifecycle()
@@ -845,7 +846,18 @@ fun BrowserApp(viewModel: BrowserViewModel) {
onForgetAllSitePermissions = { viewModel.forgetAllSitePermissions() },
adBlockAllowlist = adBlockAllowlist,
onDisallowAds = { host -> viewModel.disallowAds(host) },
- onClearAdsAllowlist = { viewModel.clearAdBlockAllowlist() }
+ onClearAdsAllowlist = { viewModel.clearAdBlockAllowlist() },
+ updateState = updateState,
+ appVersionName = com.bansify.browser.BuildConfig.VERSION_NAME,
+ onCheckForUpdates = { viewModel.checkForUpdates() },
+ onDownloadUpdate = { viewModel.downloadUpdate() },
+ onInstallUpdate = {
+ if (!viewModel.installPendingUpdate()) {
+ viewModel.openInstallPermissionSettings()
+ }
+ },
+ onOpenPlayListing = { viewModel.openPlayListing() },
+ onOpenInstallPermissionSettings = { viewModel.openInstallPermissionSettings() }
)
}
}
diff --git a/app/src/main/java/com/bansify/browser/ui/screens/SettingsScreen.kt b/app/src/main/java/com/bansify/browser/ui/screens/SettingsScreen.kt
index 0a259e1..ed33fd2 100644
--- a/app/src/main/java/com/bansify/browser/ui/screens/SettingsScreen.kt
+++ b/app/src/main/java/com/bansify/browser/ui/screens/SettingsScreen.kt
@@ -101,7 +101,14 @@ fun SettingsScreen(
onForgetAllSitePermissions: () -> Unit = {},
adBlockAllowlist: Set = emptySet(),
onDisallowAds: (String) -> Unit = {},
- onClearAdsAllowlist: () -> Unit = {}
+ onClearAdsAllowlist: () -> Unit = {},
+ updateState: com.bansify.browser.updater.UpdateState = com.bansify.browser.updater.UpdateState.Idle,
+ appVersionName: String = "",
+ onCheckForUpdates: () -> Unit = {},
+ onDownloadUpdate: () -> Unit = {},
+ onInstallUpdate: () -> Unit = {},
+ onOpenPlayListing: () -> Unit = {},
+ onOpenInstallPermissionSettings: () -> Unit = {}
) {
BackHandler { onBack() }
@@ -150,7 +157,14 @@ fun SettingsScreen(
onForgetAllSitePermissions = onForgetAllSitePermissions,
adBlockAllowlist = adBlockAllowlist,
onDisallowAds = onDisallowAds,
- onClearAdsAllowlist = onClearAdsAllowlist
+ onClearAdsAllowlist = onClearAdsAllowlist,
+ updateState = updateState,
+ appVersionName = appVersionName,
+ onCheckForUpdates = onCheckForUpdates,
+ onDownloadUpdate = onDownloadUpdate,
+ onInstallUpdate = onInstallUpdate,
+ onOpenPlayListing = onOpenPlayListing,
+ onOpenInstallPermissionSettings = onOpenInstallPermissionSettings
)
return
}
diff --git a/app/src/main/java/com/bansify/browser/ui/screens/SettingsSubScreens.kt b/app/src/main/java/com/bansify/browser/ui/screens/SettingsSubScreens.kt
index 1f161ce..ef15110 100644
--- a/app/src/main/java/com/bansify/browser/ui/screens/SettingsSubScreens.kt
+++ b/app/src/main/java/com/bansify/browser/ui/screens/SettingsSubScreens.kt
@@ -60,6 +60,7 @@ import com.bansify.browser.data.SafeBrowsingLevel
import com.bansify.browser.data.SearchEngine
import com.bansify.browser.data.SettingsSubScreen
import com.bansify.browser.data.SitePermissionDecision
+import com.bansify.browser.updater.UpdateState
import com.bansify.browser.data.ThemeMode
import com.bansify.browser.data.ThirdPartyCookiePolicy
import com.bansify.browser.data.ToolbarShortcut
@@ -86,7 +87,14 @@ fun SettingsSubScreenContent(
onForgetAllSitePermissions: () -> Unit = {},
adBlockAllowlist: Set = emptySet(),
onDisallowAds: (String) -> Unit = {},
- onClearAdsAllowlist: () -> Unit = {}
+ onClearAdsAllowlist: () -> Unit = {},
+ updateState: UpdateState = UpdateState.Idle,
+ appVersionName: String = "",
+ onCheckForUpdates: () -> Unit = {},
+ onDownloadUpdate: () -> Unit = {},
+ onInstallUpdate: () -> Unit = {},
+ onOpenPlayListing: () -> Unit = {},
+ onOpenInstallPermissionSettings: () -> Unit = {}
) {
val canvasBg = expressiveCanvasColor()
val context = LocalContext.current
@@ -933,6 +941,20 @@ fun SettingsSubScreenContent(
}
SettingsSubScreen.ABOUT -> {
+ item {
+ UpdateCard(
+ state = updateState,
+ currentVersion = appVersionName.ifBlank { "unknown" },
+ onCheck = onCheckForUpdates,
+ onDownload = onDownloadUpdate,
+ onInstall = {
+ onInstallUpdate()
+ onOpenInstallPermissionSettings()
+ },
+ onOpenPlay = onOpenPlayListing
+ )
+ }
+
item {
val webViewPkg = remember {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
@@ -942,7 +964,7 @@ fun SettingsSubScreenContent(
}
}
val aboutItems = listOf(
- "Application version" to "Bansify Browser 1.0.0",
+ "Application version" to "Bansify Browser ${appVersionName.ifBlank { "unknown" }}",
"Package name" to "com.bansify.browser",
"WebView engine" to (webViewPkg?.let { "${it.packageName} (${it.versionName})" }
?: "Android System WebView"),
@@ -1106,3 +1128,96 @@ private fun ExpressiveSwitchCard(
}
}
}
+
+/**
+ * "Check for updates" row.
+ *
+ * The button label and the action depend on where this copy came from: a Google Play install
+ * may only update through Play (policy), while a sideloaded build installs the verified APK
+ * itself.
+ */
+@Composable
+private fun UpdateCard(
+ state: UpdateState,
+ currentVersion: String,
+ onCheck: () -> Unit,
+ onDownload: () -> Unit,
+ onInstall: () -> Unit,
+ onOpenPlay: () -> Unit
+) {
+ val title: String
+ val body: String
+ when (state) {
+ is UpdateState.Idle -> {
+ title = "Bansify Browser $currentVersion"
+ body = "Check whether a newer build is available."
+ }
+ is UpdateState.Checking -> {
+ title = "Checking for updates..."
+ body = "Contacting the release server."
+ }
+ is UpdateState.UpToDate -> {
+ title = "You are up to date"
+ body = "Bansify Browser ${state.currentVersion} is the latest build."
+ }
+ is UpdateState.Available -> {
+ title = "Update available: v${state.release.versionName}"
+ body = if (state.fromPlay) {
+ "This copy came from Google Play, so the update installs through Play."
+ } else {
+ "Your tabs, bookmarks and settings are kept. The file is verified before it installs."
+ }
+ }
+ is UpdateState.Downloading -> {
+ title = "Downloading ${(state.progress * 100).toInt()}%"
+ body = "The file is checked against the app signature before anything is installed."
+ }
+ is UpdateState.ReadyToInstall -> {
+ title = "Ready to install"
+ body = "Tap install and confirm the system prompt."
+ }
+ is UpdateState.Failed -> {
+ title = "Could not check for updates"
+ body = state.message
+ }
+ }
+
+ ExpressiveGroupedCard(index = 0, totalCount = 1) {
+ Column(
+ modifier = Modifier
+ .fillMaxWidth()
+ .padding(20.dp),
+ verticalArrangement = Arrangement.spacedBy(10.dp)
+ ) {
+ Text(
+ text = title,
+ style = MaterialTheme.typography.titleMedium,
+ fontWeight = FontWeight.SemiBold,
+ color = MaterialTheme.colorScheme.onSurface
+ )
+ Text(
+ text = body,
+ style = MaterialTheme.typography.bodyMedium,
+ color = MaterialTheme.colorScheme.onSurfaceVariant
+ )
+ when (state) {
+ is UpdateState.Available -> Button(
+ onClick = if (state.fromPlay) onOpenPlay else onDownload,
+ shape = RoundedCornerShape(24.dp)
+ ) {
+ Text(if (state.fromPlay) "Update on Play" else "Download update")
+ }
+ is UpdateState.ReadyToInstall -> Button(
+ onClick = onInstall,
+ shape = RoundedCornerShape(24.dp)
+ ) {
+ Text("Install update")
+ }
+ is UpdateState.Checking, is UpdateState.Downloading -> Unit
+ else -> Button(onClick = onCheck, shape = RoundedCornerShape(24.dp)) {
+ Text("Check for updates")
+ }
+ }
+ }
+ }
+}
diff --git a/app/src/main/java/com/bansify/browser/updater/UpdateChecker.kt b/app/src/main/java/com/bansify/browser/updater/UpdateChecker.kt
new file mode 100644
index 0000000..8bccb5c
--- /dev/null
+++ b/app/src/main/java/com/bansify/browser/updater/UpdateChecker.kt
@@ -0,0 +1,88 @@
+package com.bansify.browser.updater
+
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.withContext
+import org.json.JSONObject
+import java.net.HttpURLConnection
+import java.net.URL
+
+/**
+ * Reads the latest published build from the GitHub releases feed.
+ *
+ * Nothing is downloaded here — the caller gets a [RemoteRelease] and decides what to do with
+ * it. No account, no key, no tracking.
+ */
+object UpdateChecker {
+
+ private const val LATEST_URL =
+ "https://api.github.com/repos/Bansify/browser/releases/latest"
+
+ /** Returns null when the installed build is already current. */
+ suspend fun latest(currentVersionName: String): Result =
+ withContext(Dispatchers.IO) {
+ runCatching {
+ val connection = (URL(LATEST_URL).openConnection() as HttpURLConnection).apply {
+ connectTimeout = 15_000
+ readTimeout = 15_000
+ setRequestProperty("Accept", "application/vnd.github+json")
+ setRequestProperty("User-Agent", "BansifyBrowser")
+ }
+ val body = try {
+ connection.inputStream.bufferedReader().use { it.readText() }
+ } finally {
+ connection.disconnect()
+ }
+
+ val json = JSONObject(body)
+ val tag = json.optString("tag_name").removePrefix("v").removePrefix("V")
+ if (tag.isBlank()) return@runCatching null
+
+ val assets = json.optJSONArray("assets") ?: return@runCatching null
+ var apkUrl: String? = null
+ var checksumUrl: String? = null
+ var apkSize = 0L
+ for (i in 0 until assets.length()) {
+ val asset = assets.getJSONObject(i)
+ val name = asset.optString("name")
+ when {
+ name.endsWith("-Release.apk") -> {
+ apkUrl = asset.optString("browser_download_url")
+ apkSize = asset.optLong("size")
+ }
+ name.endsWith(".apk.sha256") -> {
+ checksumUrl = asset.optString("browser_download_url")
+ }
+ }
+ }
+ val downloadUrl = apkUrl ?: return@runCatching null
+
+ if (compareVersions(tag, currentVersionName) <= 0) {
+ null
+ } else {
+ RemoteRelease(
+ versionName = tag,
+ apkUrl = downloadUrl,
+ sha256Url = checksumUrl,
+ sizeBytes = apkSize,
+ releasePageUrl = json.optString("html_url")
+ )
+ }
+ }
+ }
+
+ /**
+ * Compares dotted versions numerically: "1.0.152" vs "1.0.99" -> 1 (a is newer).
+ * Anything that is not a number is treated as 0, so "1.0.152-beta" still compares sanely.
+ */
+ fun compareVersions(a: String, b: String): Int {
+ val left = a.split('.', '-', '+')
+ val right = b.split('.', '-', '+')
+ val size = maxOf(left.size, right.size)
+ for (i in 0 until size) {
+ val l = left.getOrNull(i)?.takeWhile { it.isDigit() }?.toIntOrNull() ?: 0
+ val r = right.getOrNull(i)?.takeWhile { it.isDigit() }?.toIntOrNull() ?: 0
+ if (l != r) return if (l > r) 1 else -1
+ }
+ return 0
+ }
+}
diff --git a/app/src/main/java/com/bansify/browser/updater/UpdateInstaller.kt b/app/src/main/java/com/bansify/browser/updater/UpdateInstaller.kt
new file mode 100644
index 0000000..916beb4
--- /dev/null
+++ b/app/src/main/java/com/bansify/browser/updater/UpdateInstaller.kt
@@ -0,0 +1,201 @@
+package com.bansify.browser.updater
+
+import android.content.Context
+import android.content.Intent
+import android.content.pm.PackageManager
+import android.net.Uri
+import android.os.Build
+import android.provider.Settings
+import androidx.core.content.FileProvider
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.withContext
+import java.io.File
+import java.net.HttpURLConnection
+import java.net.URL
+import java.security.MessageDigest
+
+/**
+ * Downloads and installs a sideloaded update — only ever for a build that did not come from
+ * Google Play. A Play-installed app must update through Play (Device and Network Abuse
+ * policy), so [isInstalledFromPlay] gates every install path.
+ *
+ * The APK is never trusted: its signing certificate has to match the running app byte for
+ * byte, and its version code has to be newer. A tampered file fails both checks and is deleted.
+ */
+object UpdateInstaller {
+
+ private const val PLAY_PACKAGE = "com.android.vending"
+
+ fun isInstalledFromPlay(context: Context): Boolean {
+ val pm = context.packageManager
+ val installer = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
+ runCatching {
+ pm.getInstallSourceInfo(context.packageName).installingPackageName
+ }.getOrNull()
+ } else {
+ @Suppress("DEPRECATION")
+ pm.getInstallerPackageName(context.packageName)
+ }
+ return installer == PLAY_PACKAGE
+ }
+
+ /** True when the user has allowed this app to install packages. */
+ fun canInstallPackages(context: Context): Boolean =
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
+ context.packageManager.canRequestPackageInstalls()
+ } else {
+ true
+ }
+
+ /** Screen where the user grants "install unknown apps" for this browser. */
+ fun unknownSourcesSettingsIntent(context: Context): Intent =
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
+ Intent(
+ Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES,
+ Uri.parse("package:${context.packageName}")
+ ).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
+ } else {
+ Intent(Settings.ACTION_SECURITY_SETTINGS).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
+ }
+
+ /** Play listing for the app, falling back to the web page when Play is not installed. */
+ fun playListingIntent(context: Context): Intent {
+ val market = Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=${context.packageName}"))
+ .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
+ val web = Intent(
+ Intent.ACTION_VIEW,
+ Uri.parse("https://play.google.com/store/apps/details?id=${context.packageName}")
+ ).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
+ return if (market.resolveActivity(context.packageManager) != null) market else web
+ }
+
+ suspend fun download(
+ context: Context,
+ release: RemoteRelease,
+ onProgress: (Float) -> Unit
+ ): Result = withContext(Dispatchers.IO) {
+ runCatching {
+ val dir = File(context.cacheDir, "updates").apply { mkdirs() }
+ // A stale APK from an earlier attempt must not be installable by mistake.
+ dir.listFiles()?.forEach { it.delete() }
+ val target = File(dir, "bansify-${release.versionName}.apk")
+
+ val connection = (URL(release.apkUrl).openConnection() as HttpURLConnection).apply {
+ connectTimeout = 20_000
+ readTimeout = 60_000
+ instanceFollowRedirects = true
+ setRequestProperty("Accept", "application/octet-stream")
+ setRequestProperty("User-Agent", "BansifyBrowser")
+ }
+ val total = connection.contentLengthLong.takeIf { it > 0 } ?: release.sizeBytes
+ connection.inputStream.use { input ->
+ target.outputStream().use { output ->
+ val buffer = ByteArray(64 * 1024)
+ var copied = 0L
+ var lastReported = -1
+ while (true) {
+ val read = input.read(buffer)
+ if (read <= 0) break
+ output.write(buffer, 0, read)
+ copied += read
+ if (total > 0) {
+ val percent = ((copied * 100) / total).toInt()
+ if (percent != lastReported) {
+ lastReported = percent
+ onProgress((copied.toFloat() / total).coerceIn(0f, 1f))
+ }
+ }
+ }
+ }
+ }
+ connection.disconnect()
+
+ if (target.length() <= 0L) {
+ target.delete()
+ error("The downloaded file is empty")
+ }
+ release.sha256Url?.let { checksumUrl ->
+ val expected = fetchChecksum(checksumUrl)
+ if (expected != null && !expected.equals(sha256(target), ignoreCase = true)) {
+ target.delete()
+ error("The update file did not match its published checksum")
+ }
+ }
+ target
+ }
+ }
+
+ /**
+ * True only when the APK is signed by the same key as the running app. This is the check
+ * that makes self-updating safe: anything else is refused and deleted by the caller.
+ */
+ fun verifySignature(context: Context, apk: File): Boolean {
+ val pm = context.packageManager
+ @Suppress("DEPRECATION")
+ val archive = pm.getPackageArchiveInfo(apk.absolutePath, PackageManager.GET_SIGNATURES)
+ ?: return false
+ if (archive.packageName != context.packageName) return false
+
+ @Suppress("DEPRECATION")
+ val apkSignatures = archive.signatures ?: return false
+ @Suppress("DEPRECATION")
+ val selfSignatures = pm.getPackageInfo(context.packageName, PackageManager.GET_SIGNATURES)
+ .signatures ?: return false
+
+ val apkFingerprints = apkSignatures.map { sha256(it.toByteArray()) }.toSet()
+ val selfFingerprints = selfSignatures.map { sha256(it.toByteArray()) }.toSet()
+ return apkFingerprints.intersect(selfFingerprints).isNotEmpty()
+ }
+
+ fun apkVersionCode(context: Context, apk: File): Long {
+ val pm = context.packageManager
+ val info = pm.getPackageArchiveInfo(apk.absolutePath, 0) ?: return -1L
+ return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
+ info.longVersionCode
+ } else {
+ @Suppress("DEPRECATION")
+ info.versionCode.toLong()
+ }
+ }
+
+ fun installIntent(context: Context, apk: File): Intent {
+ val uri = FileProvider.getUriForFile(
+ context,
+ "${context.packageName}.fileprovider",
+ apk
+ )
+ return Intent(Intent.ACTION_VIEW).apply {
+ setDataAndType(uri, "application/vnd.android.package-archive")
+ addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_ACTIVITY_NEW_TASK)
+ }
+ }
+
+ private fun fetchChecksum(url: String): String? = runCatching {
+ val connection = (URL(url).openConnection() as HttpURLConnection).apply {
+ connectTimeout = 10_000
+ readTimeout = 10_000
+ setRequestProperty("User-Agent", "BansifyBrowser")
+ }
+ val text = connection.inputStream.bufferedReader().use { it.readText() }
+ connection.disconnect()
+ // Accept "abc123", "abc123 filename" and "SHA256 (file) = abc123".
+ Regex("[a-fA-F0-9]{64}").find(text)?.value
+ }.getOrNull()
+
+ private fun sha256(bytes: ByteArray): String =
+ MessageDigest.getInstance("SHA-256").digest(bytes)
+ .joinToString("") { "%02x".format(it) }
+
+ private fun sha256(file: File): String {
+ val digest = MessageDigest.getInstance("SHA-256")
+ file.inputStream().use { input ->
+ val buffer = ByteArray(64 * 1024)
+ while (true) {
+ val read = input.read(buffer)
+ if (read <= 0) break
+ digest.update(buffer, 0, read)
+ }
+ }
+ return digest.digest().joinToString("") { "%02x".format(it) }
+ }
+}
diff --git a/app/src/main/java/com/bansify/browser/updater/UpdateModels.kt b/app/src/main/java/com/bansify/browser/updater/UpdateModels.kt
new file mode 100644
index 0000000..b06205b
--- /dev/null
+++ b/app/src/main/java/com/bansify/browser/updater/UpdateModels.kt
@@ -0,0 +1,28 @@
+package com.bansify.browser.updater
+
+/** A newer build found on the release server. */
+data class RemoteRelease(
+ val versionName: String,
+ val apkUrl: String,
+ val sha256Url: String?,
+ val sizeBytes: Long,
+ val releasePageUrl: String
+)
+
+/**
+ * Everything the "Check for updates" row can show.
+ *
+ * [Available.fromPlay] decides the only path that is allowed: an app installed by Google
+ * Play must be updated through Play (Play policy, Device and Network Abuse), so the Play
+ * path opens the listing instead of installing an APK. A sideloaded build may install the
+ * verified APK itself.
+ */
+sealed interface UpdateState {
+ data object Idle : UpdateState
+ data object Checking : UpdateState
+ data class UpToDate(val currentVersion: String) : UpdateState
+ data class Available(val release: RemoteRelease, val fromPlay: Boolean) : UpdateState
+ data class Downloading(val progress: Float) : UpdateState
+ data object ReadyToInstall : UpdateState
+ data class Failed(val message: String) : UpdateState
+}
diff --git a/app/src/main/java/com/bansify/browser/viewmodel/BrowserViewModel.kt b/app/src/main/java/com/bansify/browser/viewmodel/BrowserViewModel.kt
index 6b78bf7..2d13d56 100644
--- a/app/src/main/java/com/bansify/browser/viewmodel/BrowserViewModel.kt
+++ b/app/src/main/java/com/bansify/browser/viewmodel/BrowserViewModel.kt
@@ -35,6 +35,10 @@ import com.bansify.browser.data.SettingsSubScreen
import com.bansify.browser.data.SitePermission
import com.bansify.browser.data.SitePermissionDecision
import com.bansify.browser.data.SitePermissionStore
+import com.bansify.browser.updater.RemoteRelease
+import com.bansify.browser.updater.UpdateChecker
+import com.bansify.browser.updater.UpdateInstaller
+import com.bansify.browser.updater.UpdateState
import com.bansify.browser.data.ShortcutEntity
import com.bansify.browser.data.SnackbarEvent
import com.bansify.browser.data.ThirdPartyCookiePolicy
@@ -675,6 +679,112 @@ class BrowserViewModel(application: Application) : AndroidViewModel(application)
private val _downloadProgress = MutableStateFlow