Revert "vpn: recognize outdated .mavpn bundles and check for updates"
- Commit
90a6facf012a55f3428e9ef7c0847ae83f1c051e- Author
- Vayun Mathur <[email protected]>
- When
- 2026-11-17 17:24 UTC (18 days ago)
- Parents
6672056
This reverts commit 6672056ac392f824818c45700a5cdfb6305f07c9.
Diff
vpn/docs/MAVPN.md
diff --git a/vpn/docs/MAVPN.md b/vpn/docs/MAVPN.mdindex d3766fcc61..f84bfc9235 100644--- a/vpn/docs/MAVPN.md+++ b/vpn/docs/MAVPN.md@@ -75,73 +75,3 @@ servers/<name>.conf never ship it as a real provider bundle. - Providers: zip the manifest and configs with any ZIP tool, e.g. `zip -r provider.mavpn manifest.json servers/`.--## Freshness metadata (optional, `mavpn/1`)--All fields below are optional top-level `manifest.json` fields. Bundles-without them are *legacy* bundles: they import unchanged and the app reports-their freshness as **Unknown**. Unknown extra fields remain ignored within-major 1, so no new format major was needed.--| Field | Meaning |-|---|---|-| `providerId` | Stable provider identity (`[A-Za-z0-9][A-Za-z0-9._-]*`). Survives catalogue/name changes; anchors bundle identity and update matching. |-| `revision` | Provider-monotonic non-negative integer. Bump on every published bundle change. Floats and negatives are rejected. |-| `issuedAt` | ISO-8601 UTC instant, e.g. `2026-01-01T00:00:00Z`. |-| `expiresAt` | ISO-8601 UTC instant; must be after `issuedAt` when both are present. |-| `updateUrl` | `https://` URL of `mavpn-update/1` metadata (below). `http://` is rejected. |--### How the app classifies a bundle--- **Current** — expiry metadata is in the future, or a revision is known and- no newer remote revision has been seen. The app never calls a bundle- current or outdated from its age alone.-- **Outdated (expired)** — `expiresAt` has passed. This is a warning only:- servers stay connectable. (The app does not disable servers on expiry —- there is no safety reason to strand a user whose bundle merely aged out.)-- **Update available** — the last manual check found a higher remote revision.-- **Unknown freshness** — legacy bundle, or metadata too thin to judge- (e.g. only `issuedAt`).-- **Check failed** — the last manual check failed (network, bad metadata, or- provider mismatch).--Every imported server row retains `providerId`, `revision`, `issuedAt`,-`expiresAt` and `updateUrl` (Room v4, migration `MIGRATION_3_4`; defaults keep-legacy rows intact). Provider identity with a `providerId` is stable across-revisions, so updates replace that provider's servers in place and drop-servers the new revision removed.--## Update metadata (`mavpn-update/1`)--Serve JSON like this from the bundle's `updateUrl`:--```json-{- "format": "mavpn-update/1",- "providerId": "example-vpn",- "revision": 8,- "issuedAt": "2026-06-01T00:00:00Z",- "expiresAt": "2026-12-01T00:00:00Z",- "downloadUrl": "https://provider.example/bundle.mavpn",- "sha256": "<64 lower-case hex chars>"-}-```--`format`, `providerId` and `revision` are required; the rest are optional-and validated with the same rules as the manifest (`downloadUrl` must be-HTTPS, expiry after issue, `sha256` must be 64 hex chars).--### Publishing / rotating a bundle (provider checklist)--1. Bump `revision` (never reuse one), refresh `issuedAt`/`expiresAt`, rebuild- the `.mavpn`, and compute its SHA-256 (`sha256sum bundle.mavpn`).-2. Upload the bundle to `downloadUrl` first, then update the metadata JSON —- in that order, so a check never points at a missing or stale download.-3. In the app: open the tunnel detail (or Browse by location), tap- **Check for updates**, then **Update now**. Checks are manual only; the- app never polls in the background.-4. The app fetches over `NetworkClient` with system trust (provider hosts- are user-supplied), verifies the SHA-256 and fully parses the new bundle- *before* replacing anything — a failed hash or bad bundle leaves the- installed servers untouched. Updates without `downloadUrl`+`sha256` are- reported but not applied in-app; re-import a new `.mavpn` file instead.
vpn/src/main/java/com/vayunmathur/vpn/data/MavpnImport.kt
diff --git a/vpn/src/main/java/com/vayunmathur/vpn/data/MavpnImport.kt b/vpn/src/main/java/com/vayunmathur/vpn/data/MavpnImport.ktindex 7e8a4030b1..5e16558d76 100644--- a/vpn/src/main/java/com/vayunmathur/vpn/data/MavpnImport.kt+++ b/vpn/src/main/java/com/vayunmathur/vpn/data/MavpnImport.kt@@ -1,10 +1,8 @@ package com.vayunmathur.vpn.data import android.content.Context-import com.vayunmathur.vpn.domain.BundleFreshness import com.vayunmathur.vpn.domain.GeoServer import com.vayunmathur.vpn.domain.MavpnBundle-import com.vayunmathur.vpn.domain.MavpnManifest import com.vayunmathur.vpn.domain.ParsedMavpnServer import java.io.File import java.security.MessageDigest@@ -24,39 +22,6 @@ fun bundleIdFor(provider: String, serverIds: List<String>): String { return "$slug-$short" } -/**- * Bundle identity for an imported manifest. Bundles with a stable- * `providerId` keep one identity across revisions and server-catalogue- * changes, so an update replaces its rows in place; legacy bundles keep the- * historic provider+server-ids digest so existing installs are unchanged.- */-fun bundleIdForManifest(manifest: MavpnManifest, serverIds: List<String>): String {- val providerId = manifest.freshness.providerId ?: return bundleIdFor(manifest.provider, serverIds)- val slug = providerId.lowercase().map { char -> if (char.isLetterOrDigit()) char else '-' }- .joinToString("").trim('-').ifBlank { "provider" }- val digest = MessageDigest.getInstance("SHA-256").digest(providerId.encodeToByteArray())- val short = digest.take(DIGEST_BYTES).joinToString("") { "%02x".format(it) }- return "$slug-$short"-}--/** Freshness columns for [freshness], using the entity sentinel defaults for absent fields. */-fun BundleFreshness.toConfigFields(): FreshnessFields = FreshnessFields(- providerId = providerId.orEmpty(),- bundleRevision = revision ?: -1,- bundleIssuedAt = issuedAtEpochMs ?: 0,- bundleExpiresAt = expiresAtEpochMs ?: 0,- bundleUpdateUrl = updateUrl.orEmpty(),-)--/** The five freshness columns carried on each imported config row. */-data class FreshnessFields(- val providerId: String,- val bundleRevision: Long,- val bundleIssuedAt: Long,- val bundleExpiresAt: Long,- val bundleUpdateUrl: String,-)- /** * Maps a validated bundle to selectable configs in the app's existing tunnel * model. Each imported server becomes a normal [VpnConfig] (so the tunnel@@ -68,7 +33,7 @@ fun MavpnBundle<WgQuickImport>.toVpnConfigs( existing: List<VpnConfig> = emptyList(), derivePublicKey: (String) -> String = { "" }, ): List<VpnConfig> = servers.map { server ->- server.toVpnConfig(bundleId, manifest.provider, existing, derivePublicKey, manifest.freshness)+ server.toVpnConfig(bundleId, manifest.provider, existing, derivePublicKey) } fun ParsedMavpnServer<WgQuickImport>.toVpnConfig(@@ -76,7 +41,6 @@ fun ParsedMavpnServer<WgQuickImport>.toVpnConfig( provider: String, existing: List<VpnConfig> = emptyList(), derivePublicKey: (String) -> String = { "" },- freshness: BundleFreshness = BundleFreshness.EMPTY, ): VpnConfig { val imp = config val previous = existing.firstOrNull { it.bundleId == bundleId && it.bundleServerId == entry.id }@@ -99,11 +63,6 @@ fun ParsedMavpnServer<WgQuickImport>.toVpnConfig( city = entry.city, bundleId = bundleId, bundleServerId = entry.id,- providerId = freshness.providerId.orEmpty(),- bundleRevision = freshness.revision ?: -1,- bundleIssuedAt = freshness.issuedAtEpochMs ?: 0,- bundleExpiresAt = freshness.expiresAtEpochMs ?: 0,- bundleUpdateUrl = freshness.updateUrl.orEmpty(), ) } @@ -116,8 +75,6 @@ fun VpnConfig.toGeoServerOrNull(): GeoServer? = city = city, name = name, endpoint = peerEndpoint,- freshness = bundleFreshness(),- bundleId = bundleId, ) private const val DIGEST_BYTES = 6
vpn/src/main/java/com/vayunmathur/vpn/data/MavpnUpdate.kt
diff --git a/vpn/src/main/java/com/vayunmathur/vpn/data/MavpnUpdate.kt b/vpn/src/main/java/com/vayunmathur/vpn/data/MavpnUpdate.ktdeleted file mode 100644index 284b338792..0000000000--- a/vpn/src/main/java/com/vayunmathur/vpn/data/MavpnUpdate.kt+++ /dev/null@@ -1,40 +0,0 @@-package com.vayunmathur.vpn.data--import com.vayunmathur.library.network.NetworkClient-import com.vayunmathur.vpn.domain.MavpnUpdateMetadata-import com.vayunmathur.vpn.domain.parseMavpnUpdateMetadata-import com.vayunmathur.vpn.domain.verifySha256--/**- * Fetches `mavpn-update/1` metadata and replacement bundles for a manual,- * user-triggered update check. Provider hosts are user-supplied, so requests- * go through [NetworkClient] with system trust (the app already initialises- * `NetworkClient` with `TrustBundle.SYSTEM` for exactly this reason; see- * `vpn/build.gradle.kts`). No background or silent checks are made.- *- * The byte fetcher is injectable so unit tests exercise check/download logic- * without a network or any non-HTTPS test seam.- */-class MavpnUpdateClient(- private val fetchBytes: suspend (String) -> ByteArray = { url ->- val response = NetworkClient.execute(url, useSystemTrust = true)- if (!response.isSuccess) error("HTTP ${response.status} fetching update")- response.bytes- },-) {- suspend fun fetchMetadata(updateUrl: String): MavpnUpdateMetadata =- parseMavpnUpdateMetadata(fetchBytes(updateUrl).decodeToString())-- /**- * Downloads a replacement bundle and verifies it before any import runs.- * Throws without touching local state when the download or the SHA-256- * check fails, so a bad update can never partially replace a bundle.- */- suspend fun fetchVerifiedBundle(metadata: MavpnUpdateMetadata): ByteArray {- val downloadUrl = metadata.downloadUrl ?: error("Update metadata has no downloadUrl")- val bytes = fetchBytes(downloadUrl)- val sha = metadata.sha256 ?: error("Update metadata has no sha256; refusing unverified bundle")- if (!verifySha256(bytes, sha)) error("Downloaded bundle failed SHA-256 verification")- return bytes- }-}
vpn/src/main/java/com/vayunmathur/vpn/data/VpnConfig.kt
diff --git a/vpn/src/main/java/com/vayunmathur/vpn/data/VpnConfig.kt b/vpn/src/main/java/com/vayunmathur/vpn/data/VpnConfig.ktindex da7c6f08aa..b85b28e2da 100644--- a/vpn/src/main/java/com/vayunmathur/vpn/data/VpnConfig.kt+++ b/vpn/src/main/java/com/vayunmathur/vpn/data/VpnConfig.kt@@ -1,7 +1,6 @@ package com.vayunmathur.vpn.data import com.vayunmathur.library.util.DatabaseItem-import com.vayunmathur.vpn.domain.BundleFreshness import kotlinx.serialization.Serializable /** Immutable value describing vpn config. */@@ -26,24 +25,7 @@ data class VpnConfig( val city: String = "", val bundleId: String = "", val bundleServerId: String = "",- /** Freshness metadata from the bundle manifest; empty/-1/0 for legacy bundles. */- val providerId: String = "",- val bundleRevision: Long = -1,- val bundleIssuedAt: Long = 0,- val bundleExpiresAt: Long = 0,- val bundleUpdateUrl: String = "",-) : DatabaseItem {-- /** This config's bundle freshness, reconstructed from the retained columns. */- fun bundleFreshness(): BundleFreshness =- BundleFreshness(- providerId = providerId.takeIf { it.isNotBlank() },- revision = bundleRevision.takeIf { it >= 0 },- issuedAtEpochMs = bundleIssuedAt.takeIf { it > 0 },- expiresAtEpochMs = bundleExpiresAt.takeIf { it > 0 },- updateUrl = bundleUpdateUrl.takeIf { it.isNotBlank() },- )-}+) : DatabaseItem /** Immutable value describing wg quick import. */ data class WgQuickImport(
vpn/src/main/java/com/vayunmathur/vpn/data/VpnDatabase.kt
diff --git a/vpn/src/main/java/com/vayunmathur/vpn/data/VpnDatabase.kt b/vpn/src/main/java/com/vayunmathur/vpn/data/VpnDatabase.ktindex 95f26a21bb..4770a481f6 100644--- a/vpn/src/main/java/com/vayunmathur/vpn/data/VpnDatabase.kt+++ b/vpn/src/main/java/com/vayunmathur/vpn/data/VpnDatabase.kt@@ -39,11 +39,6 @@ data class VpnConfigEntity( val city: String = "", val bundleId: String = "", val bundleServerId: String = "",- val providerId: String = "",- val bundleRevision: Long = -1,- val bundleIssuedAt: Long = 0,- val bundleExpiresAt: Long = 0,- val bundleUpdateUrl: String = "", ) : DatabaseItem fun VpnConfigEntity.toModel() = VpnConfig(@@ -52,9 +47,7 @@ fun VpnConfigEntity.toModel() = VpnConfig( peerPublicKey = peerPublicKey, peerPresharedKey = peerPresharedKey, peerAllowedIPs = peerAllowedIPs, peerEndpoint = peerEndpoint, peerKeepalive = peerKeepalive, lastUsed = lastUsed, provider = provider, countryCode = countryCode, city = city,- bundleId = bundleId, bundleServerId = bundleServerId, providerId = providerId,- bundleRevision = bundleRevision, bundleIssuedAt = bundleIssuedAt,- bundleExpiresAt = bundleExpiresAt, bundleUpdateUrl = bundleUpdateUrl,+ bundleId = bundleId, bundleServerId = bundleServerId, ) fun VpnConfig.toEntity() = VpnConfigEntity(@@ -63,9 +56,7 @@ fun VpnConfig.toEntity() = VpnConfigEntity( peerPublicKey = peerPublicKey, peerPresharedKey = peerPresharedKey, peerAllowedIPs = peerAllowedIPs, peerEndpoint = peerEndpoint, peerKeepalive = peerKeepalive, lastUsed = lastUsed, provider = provider, countryCode = countryCode, city = city,- bundleId = bundleId, bundleServerId = bundleServerId, providerId = providerId,- bundleRevision = bundleRevision, bundleIssuedAt = bundleIssuedAt,- bundleExpiresAt = bundleExpiresAt, bundleUpdateUrl = bundleUpdateUrl,+ bundleId = bundleId, bundleServerId = bundleServerId, ) /** Contract for vpn config dao. */@@ -134,17 +125,6 @@ val MIGRATION_1_2 = object : Migration(1, 2) { } } -val MIGRATION_3_4 = object : Migration(3, 4) {- override suspend fun migrate(connection: SQLiteConnection) {- // Freshness metadata retained from the bundle manifest; legacy rows keep the defaults.- connection.execSQL("ALTER TABLE `VpnConfigEntity` ADD COLUMN `providerId` TEXT NOT NULL DEFAULT ''")- connection.execSQL("ALTER TABLE `VpnConfigEntity` ADD COLUMN `bundleRevision` INTEGER NOT NULL DEFAULT -1")- connection.execSQL("ALTER TABLE `VpnConfigEntity` ADD COLUMN `bundleIssuedAt` INTEGER NOT NULL DEFAULT 0")- connection.execSQL("ALTER TABLE `VpnConfigEntity` ADD COLUMN `bundleExpiresAt` INTEGER NOT NULL DEFAULT 0")- connection.execSQL("ALTER TABLE `VpnConfigEntity` ADD COLUMN `bundleUpdateUrl` TEXT NOT NULL DEFAULT ''")- }-}- val MIGRATION_2_3 = object : Migration(2, 3) { override suspend fun migrate(connection: SQLiteConnection) { // `.mavpn` bundle metadata on imported configs; plain `.conf` rows keep the empty defaults.@@ -155,14 +135,14 @@ val MIGRATION_2_3 = object : Migration(2, 3) { } /** Vpn Database: a room database implementation for vpn database. */-@Database(entities = [VpnConfigEntity::class, ConnectionLogEntity::class], version = 4, exportSchema = false)+@Database(entities = [VpnConfigEntity::class, ConnectionLogEntity::class], version = 3, exportSchema = false) abstract class VpnDatabase : RoomDatabase() { abstract fun vpnConfigDao(): VpnConfigDao abstract fun connectionLogDao(): ConnectionLogDao /** Shared constants and helpers for VpnDatabase. */ companion object : DatabaseMigrations {- override val migrations: List<Migration> = listOf(MIGRATION_1_2, MIGRATION_2_3, MIGRATION_3_4)+ override val migrations: List<Migration> = listOf(MIGRATION_1_2, MIGRATION_2_3) /** * The process-wide database. Delegates to [VpnRepository] so the single
vpn/src/main/java/com/vayunmathur/vpn/domain/GeoPickerData.kt
diff --git a/vpn/src/main/java/com/vayunmathur/vpn/domain/GeoPickerData.kt b/vpn/src/main/java/com/vayunmathur/vpn/domain/GeoPickerData.ktindex 92d34b1f3a..3d104bd9cf 100644--- a/vpn/src/main/java/com/vayunmathur/vpn/domain/GeoPickerData.kt+++ b/vpn/src/main/java/com/vayunmathur/vpn/domain/GeoPickerData.kt@@ -10,46 +10,8 @@ data class GeoServer( val city: String, val name: String, val endpoint: String,- /** Bundle freshness shared by every server of the provider; empty for legacy bundles. */- val freshness: BundleFreshness = BundleFreshness.EMPTY,- val bundleId: String = "", ) -/** One imported provider bundle, summarised for the picker header / update UI. */-data class GeoProvider(- val provider: String,- val providerId: String?,- val bundleId: String,- val freshness: BundleFreshness,- val state: BundleFreshnessState,- val serverCount: Int,-)--/** Distinct provider bundles in [servers], in provider-name order, classified at [nowEpochMs]. */-fun buildGeoProviders(- servers: List<GeoServer>,- nowEpochMs: Long = System.currentTimeMillis(),- remoteRevisions: Map<String, Long?> = emptyMap(),- failedBundleIds: Set<String> = emptySet(),-): List<GeoProvider> =- servers.groupBy { it.bundleId.ifBlank { it.provider } }- .map { (bundleKey, inBundle) ->- val first = inBundle.first()- GeoProvider(- provider = first.provider,- providerId = first.freshness.providerId,- bundleId = bundleKey,- freshness = first.freshness,- state = classifyFreshness(- first.freshness, nowEpochMs,- remoteRevision = remoteRevisions[bundleKey],- checkFailed = bundleKey in failedBundleIds,- ),- serverCount = inBundle.size,- )- }- .sortedBy { it.provider.lowercase(Locale.ROOT) }- /** A city and its servers, sorted by server name. */ data class GeoCity( val city: String,
vpn/src/main/java/com/vayunmathur/vpn/domain/MavpnBundle.kt
diff --git a/vpn/src/main/java/com/vayunmathur/vpn/domain/MavpnBundle.kt b/vpn/src/main/java/com/vayunmathur/vpn/domain/MavpnBundle.ktindex f1c9509ee3..153a3e0e8a 100644--- a/vpn/src/main/java/com/vayunmathur/vpn/domain/MavpnBundle.kt+++ b/vpn/src/main/java/com/vayunmathur/vpn/domain/MavpnBundle.kt@@ -25,8 +25,6 @@ data class MavpnManifest( val format: String, val provider: String, val servers: List<MavpnServerEntry>,- /** Optional freshness metadata; [BundleFreshness.EMPTY] for legacy bundles. */- val freshness: BundleFreshness = BundleFreshness.EMPTY, ) /** A manifest entry together with its WireGuard config text and its parsed config. */@@ -177,21 +175,7 @@ object MavpnParser { val servers = serverArray.map { element -> parseServer(element.jsonObject) } val duplicate = servers.groupBy { it.id }.entries.firstOrNull { it.value.size > 1 }?.key if (duplicate != null) throw MavpnFormatException("Duplicate server id '$duplicate'")- return MavpnManifest(format, provider, servers, parseFreshness(root))- }-- /** Optional `mavpn/1` freshness fields; absent fields stay null for legacy bundles. */- private fun parseFreshness(root: JsonObject): BundleFreshness {- val issued = parseInstantEpochMs(root.optionalString("issuedAt"), "issuedAt")- val expires = parseInstantEpochMs(root.optionalString("expiresAt"), "expiresAt")- checkExpiryAfterIssue(issued, expires)- return BundleFreshness(- providerId = parseProviderId(root.optionalString("providerId"), "providerId"),- revision = parseRevision(root.optionalString("revision"), "revision"),- issuedAtEpochMs = issued,- expiresAtEpochMs = expires,- updateUrl = parseHttpsUrl(root.optionalString("updateUrl"), "updateUrl"),- )+ return MavpnManifest(format, provider, servers) } private fun checkFormat(format: String) {
vpn/src/main/java/com/vayunmathur/vpn/domain/MavpnFreshness.kt
diff --git a/vpn/src/main/java/com/vayunmathur/vpn/domain/MavpnFreshness.kt b/vpn/src/main/java/com/vayunmathur/vpn/domain/MavpnFreshness.ktdeleted file mode 100644index c27f17326c..0000000000--- a/vpn/src/main/java/com/vayunmathur/vpn/domain/MavpnFreshness.kt+++ /dev/null@@ -1,218 +0,0 @@-package com.vayunmathur.vpn.domain--import java.security.MessageDigest-import java.time.Instant-import java.time.format.DateTimeParseException-import kotlinx.serialization.json.Json-import kotlinx.serialization.json.JsonObject-import kotlinx.serialization.json.contentOrNull-import kotlinx.serialization.json.jsonObject-import kotlinx.serialization.json.jsonPrimitive--/**- * Optional freshness metadata carried by a `mavpn/1` manifest (and retained- * on every imported config row). All fields are optional so legacy bundles- * without any of them keep importing exactly as before.- *- * Timestamps are epoch milliseconds parsed from ISO-8601 UTC instants- * (`2026-01-01T00:00:00Z`); `revision` is a provider-monotonic counter.- */-data class BundleFreshness(- val providerId: String? = null,- val revision: Long? = null,- val issuedAtEpochMs: Long? = null,- val expiresAtEpochMs: Long? = null,- val updateUrl: String? = null,-) {- /** True when the bundle carried no freshness metadata at all (legacy bundle). */- val isEmpty: Boolean- get() = providerId == null && revision == null && issuedAtEpochMs == null &&- expiresAtEpochMs == null && updateUrl == null-- /** Shared constants. */- companion object {- val EMPTY = BundleFreshness()- }-}--/** Local/remote freshness states shown in the provider and picker UI. */-enum class BundleFreshnessState {- /** Metadata present, not expired, and no newer remote revision is known. */- CURRENT,-- /** `expiresAt` has passed. A warning only: servers remain usable. */- OUTDATED,-- /** A checked update endpoint reports a newer revision. */- UPDATE_AVAILABLE,-- /** Legacy bundle or metadata too thin to judge (no expiry and no revision). */- UNKNOWN,-- /** The last user-triggered update check failed (network, parse or mismatch). */- CHECK_FAILED,-}--/**- * Classifies [freshness] at [nowEpochMs]. Never claims [BundleFreshnessState.CURRENT]- * from age alone: current requires unexpired `expiresAt` metadata or a known- * revision with no newer remote revision. Expiry is a warning state only.- */-fun classifyFreshness(- freshness: BundleFreshness,- nowEpochMs: Long,- remoteRevision: Long? = null,- checkFailed: Boolean = false,-): BundleFreshnessState = when {- checkFailed -> BundleFreshnessState.CHECK_FAILED- remoteRevision != null && (freshness.revision == null || remoteRevision > freshness.revision) ->- BundleFreshnessState.UPDATE_AVAILABLE- freshness.expiresAtEpochMs != null && nowEpochMs >= freshness.expiresAtEpochMs ->- BundleFreshnessState.OUTDATED- freshness.isEmpty -> BundleFreshnessState.UNKNOWN- freshness.expiresAtEpochMs == null && freshness.revision == null -> BundleFreshnessState.UNKNOWN- else -> BundleFreshnessState.CURRENT-}--/** Parsed `mavpn-update/1` freshness metadata served from a bundle's `updateUrl`. */-data class MavpnUpdateMetadata(- val format: String,- val providerId: String,- val revision: Long,- val issuedAtEpochMs: Long? = null,- val expiresAtEpochMs: Long? = null,- val downloadUrl: String? = null,- val sha256: String? = null,-) {- fun toFreshness(updateUrl: String? = null): BundleFreshness = BundleFreshness(- providerId = providerId,- revision = revision,- issuedAtEpochMs = issuedAtEpochMs,- expiresAtEpochMs = expiresAtEpochMs,- updateUrl = updateUrl,- )-}--/** Result of comparing local bundle freshness against remote update metadata. */-sealed interface UpdateComparison {- /** Remote revision is not newer than the local one. */- data object UpToDate : UpdateComparison-- /** Remote revision is newer; [remote] carries its metadata. */- data class UpdateAvailable(val remote: MavpnUpdateMetadata) : UpdateComparison-- /** Remote metadata names a different provider; it is never applied. */- data class ProviderMismatch(val localProviderId: String?, val remoteProviderId: String) : UpdateComparison-}--/** Compares [local] with [remote]; a provider mismatch never counts as an update. */-fun compareUpdate(local: BundleFreshness, remote: MavpnUpdateMetadata): UpdateComparison = when {- local.providerId != null && local.providerId != remote.providerId ->- UpdateComparison.ProviderMismatch(local.providerId, remote.providerId)- local.revision != null && remote.revision <= local.revision -> UpdateComparison.UpToDate- else -> UpdateComparison.UpdateAvailable(remote)-}--/** Lower-case hex SHA-256 of [bytes]. */-fun sha256Hex(bytes: ByteArray): String =- MessageDigest.getInstance("SHA-256").digest(bytes).joinToString("") { "%02x".format(it) }--/** True when [bytes] hash to [expectedHex] (case-insensitive); false for malformed expectations. */-fun verifySha256(bytes: ByteArray, expectedHex: String): Boolean {- val expected = expectedHex.trim().lowercase()- if (!SHA256_HEX.matches(expected)) return false- return MessageDigest.isEqual(sha256Hex(bytes).encodeToByteArray(), expected.encodeToByteArray())-}--private val SHA256_HEX = Regex("[0-9a-f]{64}")-private val PROVIDER_ID_PATTERN = Regex("[A-Za-z0-9][A-Za-z0-9._-]*")--internal fun parseProviderId(raw: String?, field: String): String? {- if (raw == null) return null- val value = raw.trim()- if (value.isEmpty() || !PROVIDER_ID_PATTERN.matches(value)) {- throw MavpnFormatException("Invalid $field '$raw'")- }- return value-}--internal fun parseRevision(raw: String?, field: String): Long? {- if (raw == null) return null- val value = raw.trim()- val parsed = value.toLongOrNull()- // Reject floats/exponents and negatives: revision is a monotonic counter.- if (parsed == null || value != parsed.toString() || parsed < 0) {- throw MavpnFormatException("Invalid $field '$raw' (expected a non-negative integer)")- }- return parsed-}--internal fun parseInstantEpochMs(raw: String?, field: String): Long? {- if (raw == null) return null- return runCatching { Instant.parse(raw.trim()).toEpochMilli() }.getOrElse { error ->- val why = if (error is DateTimeParseException) {- "expected ISO-8601 UTC, e.g. 2026-01-01T00:00:00Z"- } else {- "timestamp out of range"- }- throw MavpnFormatException("Invalid $field '$raw' ($why)")- }-}--internal fun checkExpiryAfterIssue(issuedAtEpochMs: Long?, expiresAtEpochMs: Long?) {- if (issuedAtEpochMs != null && expiresAtEpochMs != null && expiresAtEpochMs <= issuedAtEpochMs) {- throw MavpnFormatException("expiresAt must be after issuedAt")- }-}--/**- * Validates an HTTPS URL field. Non-HTTPS URLs are rejected with no test seam- * in the parsers: tests inject fake fetchers instead of weakening TLS/URL rules.- */-internal fun parseHttpsUrl(raw: String?, field: String): String? {- if (raw == null) return null- val value = raw.trim()- if (!isHttpsUrl(value)) throw MavpnFormatException("Invalid $field (expected an https:// URL)")- return value-}--internal fun isHttpsUrl(value: String): Boolean {- if (value.any { it.isWhitespace() } || !value.startsWith("https://")) return false- val host = value.removePrefix("https://").substringBefore('/').substringBefore('?').substringBefore('#')- return host.isNotBlank() && !host.startsWith(".") && !host.endsWith(".")-}--internal fun JsonObject.optionalString(key: String): String? =- this[key]?.jsonPrimitive?.contentOrNull?.takeIf { it.isNotBlank() }--/** Parses and validates a `mavpn-update/1` metadata document. */-fun parseMavpnUpdateMetadata(text: String): MavpnUpdateMetadata {- val root = runCatching { Json.parseToJsonElement(text).jsonObject }.getOrElse {- throw MavpnFormatException("Update metadata is not valid JSON")- }- val format = root.optionalString("format") ?: throw MavpnFormatException("Update metadata is missing 'format'")- if (format != MavpnUpdateParser.FORMAT) throw MavpnFormatException("Unsupported update format '$format'")- val providerId = parseProviderId(root.optionalString("providerId"), "providerId")- ?: throw MavpnFormatException("Update metadata is missing 'providerId'")- val revision = parseRevision(root.optionalString("revision"), "revision")- ?: throw MavpnFormatException("Update metadata is missing 'revision'")- val issued = parseInstantEpochMs(root.optionalString("issuedAt"), "issuedAt")- val expires = parseInstantEpochMs(root.optionalString("expiresAt"), "expiresAt")- checkExpiryAfterIssue(issued, expires)- val sha = root.optionalString("sha256")?.trim()?.lowercase()- if (sha != null && !SHA256_HEX.matches(sha)) throw MavpnFormatException("Invalid sha256 in update metadata")- return MavpnUpdateMetadata(- format = format,- providerId = providerId,- revision = revision,- issuedAtEpochMs = issued,- expiresAtEpochMs = expires,- downloadUrl = parseHttpsUrl(root.optionalString("downloadUrl"), "downloadUrl"),- sha256 = sha,- )-}--/** Constants for the update-metadata format. */-object MavpnUpdateParser {- const val FORMAT = "mavpn-update/1"-}
vpn/src/main/java/com/vayunmathur/vpn/platform/VpnViewModel.kt
diff --git a/vpn/src/main/java/com/vayunmathur/vpn/platform/VpnViewModel.kt b/vpn/src/main/java/com/vayunmathur/vpn/platform/VpnViewModel.ktindex 03e7349add..d63b1036dc 100644--- a/vpn/src/main/java/com/vayunmathur/vpn/platform/VpnViewModel.kt+++ b/vpn/src/main/java/com/vayunmathur/vpn/platform/VpnViewModel.kt@@ -22,21 +22,15 @@ import com.vayunmathur.vpn.data.VpnConfigDao import com.vayunmathur.vpn.data.WgConfigParser import com.vayunmathur.vpn.data.endpointHostOf import com.vayunmathur.vpn.data.MavpnBundleStore-import com.vayunmathur.vpn.data.MavpnUpdateClient-import com.vayunmathur.vpn.data.bundleIdForManifest+import com.vayunmathur.vpn.data.bundleIdFor import com.vayunmathur.vpn.data.toEntity import com.vayunmathur.vpn.data.toGeoServerOrNull import com.vayunmathur.vpn.data.toModel import com.vayunmathur.vpn.data.toVpnConfigs import com.vayunmathur.vpn.domain.GeoCountry-import com.vayunmathur.vpn.domain.GeoProvider import com.vayunmathur.vpn.domain.MavpnBundle import com.vayunmathur.vpn.domain.MavpnParser-import com.vayunmathur.vpn.domain.MavpnUpdateMetadata-import com.vayunmathur.vpn.domain.UpdateComparison import com.vayunmathur.vpn.domain.buildGeoCountries-import com.vayunmathur.vpn.domain.buildGeoProviders-import com.vayunmathur.vpn.domain.compareUpdate import com.vayunmathur.vpn.service.AppResolver import com.vayunmathur.vpn.service.ConnectionTracker import com.vayunmathur.vpn.service.VpnTunnelService@@ -47,7 +41,6 @@ import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.SharingStarted import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow-import kotlinx.coroutines.flow.combine import kotlinx.coroutines.flow.map import kotlinx.coroutines.flow.stateIn import kotlinx.coroutines.launch@@ -64,7 +57,6 @@ class VpnViewModel( application: Application, private val dao: VpnConfigDao, private val logDao: ConnectionLogDao,- private val updateClient: MavpnUpdateClient = MavpnUpdateClient(), ) : AndroidViewModel(application) { val configs: StateFlow<List<VpnConfig>> =@@ -92,21 +84,6 @@ class VpnViewModel( configs.map { list -> list.map { it.provider }.filter { it.isNotBlank() }.distinct().sorted() } .stateIn(viewModelScope, SharingStarted.WhileSubscribed(STOP_TIMEOUT_MS), emptyList()) - private val _updateChecks = MutableStateFlow<Map<String, UpdateCheckOutcome>>(emptyMap())- val updateChecks: StateFlow<Map<String, UpdateCheckOutcome>> = _updateChecks.asStateFlow()-- /** Provider bundles with freshness state, for the picker header and detail surfaces. */- val geoProviders: StateFlow<List<GeoProvider>> =- combine(configs, _updateChecks) { list, checks ->- buildGeoProviders(- list.mapNotNull { it.toGeoServerOrNull() },- remoteRevisions = checks.mapValues { (_, outcome) ->- (outcome as? UpdateCheckOutcome.Available)?.metadata?.revision- },- failedBundleIds = checks.filterValues { it is UpdateCheckOutcome.Failed }.keys,- )- }.stateIn(viewModelScope, SharingStarted.WhileSubscribed(STOP_TIMEOUT_MS), emptyList())- /** Imported servers grouped countries → cities → servers for the geo picker routes. */ val geoCountries: StateFlow<List<GeoCountry>> = configs.map { list -> buildGeoCountries(list.mapNotNull { it.toGeoServerOrNull() }) }@@ -281,126 +258,30 @@ class VpnViewModel( * place (matched by bundle id + server id) instead of duplicating them. * Config contents are never logged; failures report only the reason. */- private suspend fun importBundle(- context: Context,- bytes: ByteArray,- preserveBundleId: String? = null,- expectedUpdate: MavpnUpdateMetadata? = null,- ) {- // Parse and validate everything before touching storage or the database:- // a rejected or mismatched bundle leaves the installed one untouched.+ private suspend fun importBundle(context: Context, bytes: ByteArray) { val bundle = MavpnParser.parse(bytes, WgConfigParser::parse).getOrElse { _status.value = "Import failed: ${it.message}" return }- if (expectedUpdate != null) {- val fresh = bundle.manifest.freshness- if (fresh.providerId != expectedUpdate.providerId || fresh.revision != expectedUpdate.revision) {- _status.value = "Update failed: downloaded bundle does not match update metadata"- return- }- }- val bundleId = preserveBundleId- ?: bundleIdForManifest(bundle.manifest, bundle.servers.map { it.entry.id })- val existing = dao.getAll().map { it.toModel() }- val models = bundle.toVpnConfigs(bundleId, existing) { privateKey ->- runCatching { VpnNative.derivePublicKey(privateKey) }.getOrNull() ?: ""- }+ val bundleId = bundleIdFor(bundle.manifest.provider, bundle.servers.map { it.entry.id }) runCatching { MavpnBundleStore.save(context, bundleId, bundle, manifestJson(bundle)) }.onFailure { _status.value = "Import failed: could not store bundle" return }+ val existing = dao.getAll().map { it.toModel() }+ val models = bundle.toVpnConfigs(bundleId, existing) { privateKey ->+ runCatching { VpnNative.derivePublicKey(privateKey) }.getOrNull() ?: ""+ } models.forEach { dao.upsert(it.toEntity()) }- // Replacing a bundle in place: drop its servers that the new revision removed.- val newIds = models.map { it.bundleServerId }.toSet()- existing.filter { it.bundleId == bundleId && it.bundleServerId !in newIds }- .forEach { dao.delete(it.toEntity()) } _status.value = "Imported ${models.size} servers from ${bundle.manifest.provider}" } - /** User-triggered freshness check for one bundle; never runs in the background. */- fun checkForUpdate(bundleId: String) {- viewModelScope.launch(Dispatchers.IO) {- val representative = dao.getAll().map { it.toModel() }- .firstOrNull { it.bundleId == bundleId }- if (representative == null) {- _status.value = "Update check failed: bundle not found"- return@launch- }- val updateUrl = representative.bundleUpdateUrl- if (updateUrl.isBlank()) {- _updateChecks.value += bundleId to UpdateCheckOutcome.Failed- _status.value = "No update URL for ${representative.provider}"- return@launch- }- _updateChecks.value += bundleId to UpdateCheckOutcome.Checking- runCatching { updateClient.fetchMetadata(updateUrl) }- .onSuccess { metadata ->- when (val result = compareUpdate(representative.bundleFreshness(), metadata)) {- is UpdateComparison.ProviderMismatch -> {- _updateChecks.value += bundleId to UpdateCheckOutcome.Failed- _status.value = "Update check failed: provider mismatch"- }- UpdateComparison.UpToDate -> {- _updateChecks.value += bundleId to UpdateCheckOutcome.UpToDate- _status.value = "${representative.provider} is up to date"- }- is UpdateComparison.UpdateAvailable -> {- _updateChecks.value += bundleId to- UpdateCheckOutcome.Available(result.remote)- _status.value = "Update available for ${representative.provider}"- }- }- }- .onFailure {- _updateChecks.value += bundleId to UpdateCheckOutcome.Failed- _status.value = "Update check failed: ${it.message}"- }- }- }-- /**- * Downloads, SHA-256-verifies and re-imports a bundle in place. Verification- * and parsing both complete before any row or file is replaced, so a bad- * download leaves the installed bundle untouched.- */- fun applyBundleUpdate(bundleId: String) {- val metadata = (_updateChecks.value[bundleId] as? UpdateCheckOutcome.Available)?.metadata- if (metadata == null) {- _status.value = "Check for updates first"- return- }- if (metadata.downloadUrl == null || metadata.sha256 == null) {- _status.value = "Update has no verified download; re-import a new .mavpn file"- return- }- viewModelScope.launch(Dispatchers.IO) {- runCatching { updateClient.fetchVerifiedBundle(metadata) }- .onSuccess { bytes ->- importBundle(getApplication(), bytes, preserveBundleId = bundleId, expectedUpdate = metadata)- if (_status.value?.startsWith("Imported") == true) {- _updateChecks.value += bundleId to UpdateCheckOutcome.UpToDate- }- }- .onFailure { _status.value = "Update failed: ${it.message}" }- }- }- private fun manifestJson(bundle: MavpnBundle<*>): String = buildJsonObject { put("format", bundle.manifest.format) put("provider", bundle.manifest.provider)- bundle.manifest.freshness.providerId?.let { put("providerId", it) }- bundle.manifest.freshness.revision?.let { put("revision", it) }- bundle.manifest.freshness.issuedAtEpochMs?.let {- put("issuedAt", java.time.Instant.ofEpochMilli(it).toString())- }- bundle.manifest.freshness.expiresAtEpochMs?.let {- put("expiresAt", java.time.Instant.ofEpochMilli(it).toString())- }- bundle.manifest.freshness.updateUrl?.let { put("updateUrl", it) } putJsonArray("servers") { bundle.manifest.servers.forEach { server -> addJsonObject {@@ -438,21 +319,6 @@ class VpnViewModel( } } -/** Outcome of a user-triggered update check for one bundle. */-sealed interface UpdateCheckOutcome {- /** A check is in flight. */- data object Checking : UpdateCheckOutcome-- /** The last check failed; no freshness claim is made from it. */- data object Failed : UpdateCheckOutcome-- /** The last check found no newer revision. */- data object UpToDate : UpdateCheckOutcome-- /** The last check found a newer revision, carried here for the update action. */- data class Available(val metadata: MavpnUpdateMetadata) : UpdateCheckOutcome-}- /** Creates vpn view model instances. */ class VpnViewModelFactory( private val application: Application,
vpn/src/main/java/com/vayunmathur/vpn/ui/ConfigDetailPage.kt
diff --git a/vpn/src/main/java/com/vayunmathur/vpn/ui/ConfigDetailPage.kt b/vpn/src/main/java/com/vayunmathur/vpn/ui/ConfigDetailPage.ktindex 39b06df7c2..b979cd2a9d 100644--- a/vpn/src/main/java/com/vayunmathur/vpn/ui/ConfigDetailPage.kt+++ b/vpn/src/main/java/com/vayunmathur/vpn/ui/ConfigDetailPage.kt@@ -7,7 +7,6 @@ import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.material3.MaterialTheme import androidx.compose.runtime.Composable-import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember@@ -23,12 +22,7 @@ import com.vayunmathur.library.ui.Text import com.vayunmathur.library.ui.appBarScrollBehavior import com.vayunmathur.vpn.Route import com.vayunmathur.vpn.data.WgConfigParser-import com.vayunmathur.vpn.domain.BundleFreshnessState-import com.vayunmathur.vpn.domain.classifyFreshness-import com.vayunmathur.vpn.platform.UpdateCheckOutcome import com.vayunmathur.vpn.platform.VpnViewModel-import com.vayunmathur.vpn.ui.components.BundleFreshnessBadge-import java.time.Instant import com.vayunmathur.library.util.NavBackStack import com.vayunmathur.library.util.sharedText @@ -39,7 +33,6 @@ import com.vayunmathur.library.util.sharedText @Composable fun ConfigDetailPage(backStack: NavBackStack<Route>, vm: VpnViewModel, id: Long) { val cfg = vm.configState(id)- val updateChecks by vm.updateChecks.collectAsState() var exportText by remember { mutableStateOf<String?>(null) } DetailScaffold(@@ -71,48 +64,6 @@ fun ConfigDetailPage(backStack: NavBackStack<Route>, vm: VpnViewModel, id: Long) Text(stringResource(R.string.publickey, cfg.publicKey), fontSize = 11.sp, fontFamily = FontFamily.Monospace) Text(stringResource(R.string.peer_publickey, cfg.peerPublicKey), fontSize = 11.sp, fontFamily = FontFamily.Monospace) - if (cfg.bundleId.isNotBlank()) {- val freshness = cfg.bundleFreshness()- val outcome = updateChecks[cfg.bundleId]- val state = when (outcome) {- is UpdateCheckOutcome.Available -> BundleFreshnessState.UPDATE_AVAILABLE- UpdateCheckOutcome.Failed -> BundleFreshnessState.CHECK_FAILED- else -> classifyFreshness(freshness, System.currentTimeMillis())- }- BundleFreshnessBadge(- state,- updateRevision = (outcome as? UpdateCheckOutcome.Available)?.metadata?.revision,- )- freshness.providerId?.let { Text(stringResource(R.string.bundle_provider_id, it), fontSize = 12.sp) }- freshness.revision?.let { Text(stringResource(R.string.bundle_revision, it), fontSize = 12.sp) }- freshness.issuedAtEpochMs?.let {- Text(stringResource(R.string.bundle_issued, Instant.ofEpochMilli(it).toString()), fontSize = 12.sp)- }- freshness.expiresAtEpochMs?.let {- Text(stringResource(R.string.bundle_expires, Instant.ofEpochMilli(it).toString()), fontSize = 12.sp)- }- if (cfg.bundleUpdateUrl.isNotBlank()) {- Button({ vm.checkForUpdate(cfg.bundleId) }, Modifier.fillMaxWidth()) {- Text(- stringResource(- if (outcome is UpdateCheckOutcome.Checking) {- R.string.checking_for_updates- } else {- R.string.check_for_updates- },- ),- )- }- }- if (outcome is UpdateCheckOutcome.Available &&- outcome.metadata.downloadUrl != null && outcome.metadata.sha256 != null- ) {- Button({ vm.applyBundleUpdate(cfg.bundleId) }, Modifier.fillMaxWidth()) {- Text(stringResource(R.string.update_now))- }- }- }- Button({ exportText = WgConfigParser.toWgQuick(cfg) }, Modifier.fillMaxWidth()) { Text(stringResource(R.string.export_as_conf)) } if (exportText != null) {
vpn/src/main/java/com/vayunmathur/vpn/ui/GeoPickerPage.kt
diff --git a/vpn/src/main/java/com/vayunmathur/vpn/ui/GeoPickerPage.kt b/vpn/src/main/java/com/vayunmathur/vpn/ui/GeoPickerPage.ktindex f7f062f8d0..e45122f052 100644--- a/vpn/src/main/java/com/vayunmathur/vpn/ui/GeoPickerPage.kt+++ b/vpn/src/main/java/com/vayunmathur/vpn/ui/GeoPickerPage.kt@@ -28,9 +28,6 @@ import com.vayunmathur.vpn.Route import com.vayunmathur.vpn.domain.filterGeoCountries import com.vayunmathur.vpn.domain.flattenServers import com.vayunmathur.vpn.platform.VpnViewModel-import com.vayunmathur.library.ui.Button-import com.vayunmathur.vpn.platform.UpdateCheckOutcome-import com.vayunmathur.vpn.ui.components.BundleFreshnessBadge import com.vayunmathur.vpn.ui.components.GeoServerRow import com.vayunmathur.vpn.ui.components.rememberServerActivation @@ -43,8 +40,6 @@ import com.vayunmathur.vpn.ui.components.rememberServerActivation @Composable fun GeoPickerPage(backStack: NavBackStack<Route>, vm: VpnViewModel) { val countries by vm.geoCountries.collectAsState()- val providers by vm.geoProviders.collectAsState()- val updateChecks by vm.updateChecks.collectAsState() val configs by vm.configs.collectAsState() var query by rememberSaveable { mutableStateOf("") } val filtered = filterGeoCountries(countries, query)@@ -56,47 +51,6 @@ fun GeoPickerPage(backStack: NavBackStack<Route>, vm: VpnViewModel) { verticalArrangement = Arrangement.spacedBy(12.dp), scrollBehavior = appBarScrollBehavior(), ) {- items(providers, key = { it.bundleId }) { provider ->- Card(Modifier.fillMaxWidth(), shape = RoundedCornerShape(16.dp)) {- Text(- provider.provider,- fontWeight = FontWeight.Bold, fontSize = 16.sp,- modifier = Modifier.padding(16.dp, 12.dp, 16.dp, 2.dp),- )- androidx.compose.foundation.layout.Column(Modifier.padding(16.dp, 0.dp, 16.dp, 12.dp)) {- BundleFreshnessBadge(- provider.state,- updateRevision = (updateChecks[provider.bundleId] as? UpdateCheckOutcome.Available)- ?.metadata?.revision,- )- provider.freshness.revision?.let {- Text(stringResource(R.string.bundle_revision, it), fontSize = 12.sp)- }- provider.freshness.expiresAtEpochMs?.let {- Text(- stringResource(- R.string.bundle_expires,- java.time.Instant.ofEpochMilli(it).toString(),- ),- fontSize = 12.sp,- )- }- if (provider.freshness.updateUrl != null) {- Button(onClick = { vm.checkForUpdate(provider.bundleId) }) {- Text(stringResource(R.string.check_for_updates))- }- }- val outcome = updateChecks[provider.bundleId]- if (outcome is UpdateCheckOutcome.Available &&- outcome.metadata.downloadUrl != null && outcome.metadata.sha256 != null- ) {- Button(onClick = { vm.applyBundleUpdate(provider.bundleId) }) {- Text(stringResource(R.string.update_now))- }- }- }- }- } item { CommonSearchBar( value = query,
vpn/src/main/java/com/vayunmathur/vpn/ui/components/BundleFreshnessBadge.kt
diff --git a/vpn/src/main/java/com/vayunmathur/vpn/ui/components/BundleFreshnessBadge.kt b/vpn/src/main/java/com/vayunmathur/vpn/ui/components/BundleFreshnessBadge.ktdeleted file mode 100644index 23d9e4ed95..0000000000--- a/vpn/src/main/java/com/vayunmathur/vpn/ui/components/BundleFreshnessBadge.kt+++ /dev/null@@ -1,23 +0,0 @@-package com.vayunmathur.vpn.ui.components--import androidx.compose.runtime.Composable-import androidx.compose.ui.res.stringResource-import androidx.compose.ui.unit.sp-import com.vayunmathur.library.ui.Text-import com.vayunmathur.vpn.R-import com.vayunmathur.vpn.domain.BundleFreshnessState--/** One-line freshness label for a provider bundle; server rows stay unadorned. */-@Composable-fun BundleFreshnessBadge(state: BundleFreshnessState, updateRevision: Long? = null) {- val text = when (state) {- BundleFreshnessState.CURRENT -> stringResource(R.string.bundle_freshness_current)- BundleFreshnessState.OUTDATED -> stringResource(R.string.bundle_freshness_outdated)- BundleFreshnessState.UPDATE_AVAILABLE -> stringResource(- R.string.bundle_freshness_update_available, updateRevision ?: 0,- )- BundleFreshnessState.UNKNOWN -> stringResource(R.string.bundle_freshness_unknown)- BundleFreshnessState.CHECK_FAILED -> stringResource(R.string.bundle_freshness_check_failed)- }- Text(text, fontSize = 12.sp)-}
vpn/src/main/res/values/strings.xml
diff --git a/vpn/src/main/res/values/strings.xml b/vpn/src/main/res/values/strings.xmlindex 1ee3217b96..62dc56917b 100644--- a/vpn/src/main/res/values/strings.xml+++ b/vpn/src/main/res/values/strings.xml@@ -47,16 +47,4 @@ <string name="geo_no_matches">No servers match your search</string> <string name="geo_server_count">%1$d servers</string> <string name="geo_connect">Connect</string>- <string name="bundle_freshness_current">Bundle current</string>- <string name="bundle_freshness_outdated">Bundle expired — servers still work; import a newer bundle</string>- <string name="bundle_freshness_update_available">Update available (revision %1$d)</string>- <string name="bundle_freshness_unknown">Freshness unknown (no bundle metadata)</string>- <string name="bundle_freshness_check_failed">Update check failed</string>- <string name="bundle_revision">Revision %1$d</string>- <string name="bundle_issued">Issued %1$s</string>- <string name="bundle_expires">Expires %1$s</string>- <string name="bundle_provider_id">Provider ID: %1$s</string>- <string name="check_for_updates">Check for updates</string>- <string name="update_now">Update now</string>- <string name="checking_for_updates">Checking…</string> </resources>
vpn/src/test/java/com/vayunmathur/vpn/data/MavpnImportTest.kt
diff --git a/vpn/src/test/java/com/vayunmathur/vpn/data/MavpnImportTest.kt b/vpn/src/test/java/com/vayunmathur/vpn/data/MavpnImportTest.ktindex 2e3946ca03..eef200b149 100644--- a/vpn/src/test/java/com/vayunmathur/vpn/data/MavpnImportTest.kt+++ b/vpn/src/test/java/com/vayunmathur/vpn/data/MavpnImportTest.kt@@ -134,33 +134,6 @@ class MavpnImportTest { } } - @Test fun freshnessRetainedAndProviderIdIdentityStableAcrossRevisions() {- val manifest = "{\"format\":\"mavpn/1\",\"provider\":\"Example VPN\",\"providerId\":\"ex\"," +- "\"revision\":2,\"issuedAt\":\"2026-01-01T00:00:00Z\",\"expiresAt\":\"2027-01-01T00:00:00Z\"," +- "\"updateUrl\":\"https://example.invalid/u.json\",\"servers\":" +- "[{\"id\":\"de-1\",\"country\":\"DE\",\"city\":\"Frankfurt\",\"file\":\"servers/de-1.conf\"}]}"- val out = ByteArrayOutputStream()- ZipOutputStream(out).use { zip ->- for ((n, txt) in listOf("manifest.json" to manifest, "servers/de-1.conf" to conf)) {- zip.putNextEntry(ZipEntry(n)); zip.write(txt.encodeToByteArray()); zip.closeEntry()- }- }- val bundle = MavpnParser.parse(out.toByteArray(), WgConfigParser::parse).getOrThrow()- val cfg = bundle.toVpnConfigs(bundleIdForManifest(bundle.manifest, listOf("de-1"))).single()- assertEquals("ex", cfg.providerId); assertEquals(2L, cfg.bundleRevision)- assertEquals("https://example.invalid/u.json", cfg.bundleUpdateUrl)- assertTrue(cfg.bundleExpiresAt > cfg.bundleIssuedAt && cfg.bundleIssuedAt > 0)- // Same providerId, changed server catalogue: identity is preserved for in-place update.- assertEquals(- bundleIdForManifest(bundle.manifest, listOf("de-1")),- bundleIdForManifest(bundle.manifest, listOf("de-1", "us-9")),- )- // Legacy bundles keep the historic server-ids digest.- val legacy = bundle.manifest.copy(freshness = com.vayunmathur.vpn.domain.BundleFreshness.EMPTY)- assertEquals(bundleIdFor("Example VPN", listOf("de-1")), bundleIdForManifest(legacy, listOf("de-1")))- assertEquals(cfg, cfg.toEntity().toModel())- }- @Test fun entityRoundTripKeepsBundleMetadata() { val config = VpnConfig( id = 7, name = "n", provider = "P", countryCode = "DE", city = "Berlin",
vpn/src/test/java/com/vayunmathur/vpn/data/MavpnUpdateTest.kt
diff --git a/vpn/src/test/java/com/vayunmathur/vpn/data/MavpnUpdateTest.kt b/vpn/src/test/java/com/vayunmathur/vpn/data/MavpnUpdateTest.ktdeleted file mode 100644index 0b0ac6227d..0000000000--- a/vpn/src/test/java/com/vayunmathur/vpn/data/MavpnUpdateTest.kt+++ /dev/null@@ -1,32 +0,0 @@-package com.vayunmathur.vpn.data--import com.vayunmathur.vpn.domain.MavpnUpdateMetadata-import com.vayunmathur.vpn.domain.sha256Hex-import kotlin.test.Test-import kotlin.test.assertEquals-import kotlin.test.assertTrue-import kotlinx.coroutines.runBlocking--class MavpnUpdateTest {- @Test fun verifiedBundleDownloadsOnlyWithGoodHash() { runBlocking {- val bundle = "zip-bytes".encodeToByteArray()- val client = MavpnUpdateClient { bundle }- val good = MavpnUpdateMetadata(- "mavpn-update/1", "p", 2,- downloadUrl = "https://example.invalid/b.mavpn", sha256 = sha256Hex(bundle),- )- assertEquals(bundle.toList(), client.fetchVerifiedBundle(good).toList())- val bad = good.copy(sha256 = sha256Hex("other".encodeToByteArray()))- assertTrue(runCatching { client.fetchVerifiedBundle(bad) }.isFailure)- assertTrue(runCatching { client.fetchVerifiedBundle(good.copy(sha256 = null)) }.isFailure)- assertTrue(runCatching { client.fetchVerifiedBundle(good.copy(downloadUrl = null)) }.isFailure)- } }-- @Test fun metadataFetchedThroughInjectedFetcher() { runBlocking {- val client = MavpnUpdateClient {- """{"format":"mavpn-update/1","providerId":"p","revision":5}""".encodeToByteArray()- }- val meta = client.fetchMetadata("https://example.invalid/u.json")- assertEquals(5L, meta.revision)- } }-}
vpn/src/test/java/com/vayunmathur/vpn/data/VpnDatabaseTest.kt
diff --git a/vpn/src/test/java/com/vayunmathur/vpn/data/VpnDatabaseTest.kt b/vpn/src/test/java/com/vayunmathur/vpn/data/VpnDatabaseTest.ktindex 87be322794..9f48d685e0 100644--- a/vpn/src/test/java/com/vayunmathur/vpn/data/VpnDatabaseTest.kt+++ b/vpn/src/test/java/com/vayunmathur/vpn/data/VpnDatabaseTest.kt@@ -86,12 +86,10 @@ class VpnDatabaseTest { // getters are exercised through the in-memory database above instead. val repo = VpnRepository.get(ctx) assertTrue(VpnRepository.get(ctx) === repo)- assertEquals(listOf(MIGRATION_1_2, MIGRATION_2_3, MIGRATION_3_4), VpnDatabase.migrations)+ assertEquals(listOf(MIGRATION_1_2, MIGRATION_2_3), VpnDatabase.migrations) assertEquals(1, VpnDatabase.migrations.first().startVersion) assertEquals(2, VpnDatabase.migrations.first().endVersion) assertEquals(2, MIGRATION_2_3.startVersion) assertEquals(3, MIGRATION_2_3.endVersion)- assertEquals(3, MIGRATION_3_4.startVersion)- assertEquals(4, MIGRATION_3_4.endVersion) } }
vpn/src/test/java/com/vayunmathur/vpn/domain/MavpnFreshnessTest.kt
diff --git a/vpn/src/test/java/com/vayunmathur/vpn/domain/MavpnFreshnessTest.kt b/vpn/src/test/java/com/vayunmathur/vpn/domain/MavpnFreshnessTest.ktdeleted file mode 100644index b0a693956a..0000000000--- a/vpn/src/test/java/com/vayunmathur/vpn/domain/MavpnFreshnessTest.kt+++ /dev/null@@ -1,83 +0,0 @@-package com.vayunmathur.vpn.domain--import java.time.Instant-import kotlin.test.Test-import kotlin.test.assertEquals-import kotlin.test.assertFalse-import kotlin.test.assertTrue--class MavpnFreshnessTest {- private fun ms(iso: String): Long = Instant.parse(iso).toEpochMilli()-- private val now = ms("2026-06-01T00:00:00Z")-- @Test fun legacyBundleIsUnknown() {- assertEquals(BundleFreshnessState.UNKNOWN, classifyFreshness(BundleFreshness.EMPTY, now))- }-- @Test fun expiredBundleIsOutdatedButIssuedAgeAloneIsNot() {- val expired = BundleFreshness(- providerId = "p", revision = 1,- issuedAtEpochMs = ms("2026-01-01T00:00:00Z"), expiresAtEpochMs = ms("2026-02-01T00:00:00Z"),- )- assertEquals(BundleFreshnessState.OUTDATED, classifyFreshness(expired, now))- // Old issuedAt with no expiry must not be called outdated or current from age alone.- val oldIssuedOnly = BundleFreshness(issuedAtEpochMs = ms("2020-01-01T00:00:00Z"))- assertEquals(BundleFreshnessState.UNKNOWN, classifyFreshness(oldIssuedOnly, now))- }-- @Test fun unexpiredOrRevisionOnlyBundleIsCurrent() {- val unexpired = BundleFreshness(expiresAtEpochMs = ms("2027-01-01T00:00:00Z"))- assertEquals(BundleFreshnessState.CURRENT, classifyFreshness(unexpired, now))- assertEquals(- BundleFreshnessState.CURRENT,- classifyFreshness(BundleFreshness(providerId = "p", revision = 3), now),- )- }-- @Test fun remoteRevisionAndCheckFailureWin() {- val local = BundleFreshness(providerId = "p", revision = 2, expiresAtEpochMs = ms("2027-01-01T00:00:00Z"))- assertEquals(BundleFreshnessState.UPDATE_AVAILABLE, classifyFreshness(local, now, remoteRevision = 3))- assertEquals(BundleFreshnessState.CURRENT, classifyFreshness(local, now, remoteRevision = 2))- assertEquals(BundleFreshnessState.CHECK_FAILED, classifyFreshness(local, now, checkFailed = true))- }-- @Test fun compareUpdateHandlesMismatchAndEqualRevision() {- val local = BundleFreshness(providerId = "p", revision = 2)- val remote = MavpnUpdateMetadata("mavpn-update/1", "p", 3)- assertTrue(compareUpdate(local, remote) is UpdateComparison.UpdateAvailable)- assertEquals(UpdateComparison.UpToDate, compareUpdate(local, remote.copy(revision = 2)))- assertTrue(- compareUpdate(local, remote.copy(providerId = "other")) is UpdateComparison.ProviderMismatch,- )- }-- @Test fun parsesUpdateMetadataAndRejectsBadValues() {- val parsed = parseMavpnUpdateMetadata(- """{"format":"mavpn-update/1","providerId":"p","revision":4,""" +- """"issuedAt":"2026-01-01T00:00:00Z","expiresAt":"2027-01-01T00:00:00Z",""" +- """"downloadUrl":"https://example.invalid/b.mavpn",""" +- """"sha256":"${"a".repeat(64)}"}""",- )- assertEquals(4L, parsed.revision)- assertEquals("p", parsed.providerId)- for (bad in listOf(- """{"format":"mavpn-update/2","providerId":"p","revision":1}""",- """{"format":"mavpn-update/1","providerId":"p","revision":-1}""",- """{"format":"mavpn-update/1","providerId":"p","revision":1.5}""",- """{"format":"mavpn-update/1","providerId":"p","revision":1,"downloadUrl":"http://x.invalid/b"}""",- """{"format":"mavpn-update/1","providerId":"p","revision":1,"sha256":"zz"}""",- """{"format":"mavpn-update/1","providerId":"p","revision":1,""" +- """"issuedAt":"2027-01-01T00:00:00Z","expiresAt":"2026-01-01T00:00:00Z"}""",- )) {- assertTrue(runCatching { parseMavpnUpdateMetadata(bad) }.isFailure, bad)- }- }-- @Test fun sha256Verification() {- val bytes = "bundle".encodeToByteArray()- assertTrue(verifySha256(bytes, sha256Hex(bytes)))- assertFalse(verifySha256(bytes, sha256Hex("other".encodeToByteArray())))- assertFalse(verifySha256(bytes, "not-a-hash"))- }-}
vpn/src/test/java/com/vayunmathur/vpn/domain/MavpnParserTest.kt
diff --git a/vpn/src/test/java/com/vayunmathur/vpn/domain/MavpnParserTest.kt b/vpn/src/test/java/com/vayunmathur/vpn/domain/MavpnParserTest.ktindex 73a5afbfff..8a1b46bfcc 100644--- a/vpn/src/test/java/com/vayunmathur/vpn/domain/MavpnParserTest.kt+++ b/vpn/src/test/java/com/vayunmathur/vpn/domain/MavpnParserTest.kt@@ -55,43 +55,11 @@ class MavpnParserTest { assertEquals("vpn.example.com:51820", server.config.peerEndpoint) } - @Test fun parsesFreshnessFieldsAndLegacyBundles() {- val text = "{\"format\":\"mavpn/1\",\"provider\":\"Example\",\"providerId\":\"example\"," +- "\"revision\":7,\"issuedAt\":\"2026-01-01T00:00:00Z\",\"expiresAt\":\"2027-01-01T00:00:00Z\"," +- "\"updateUrl\":\"https://example.invalid/u.json\",\"servers\":" +- "[{\"id\":\"de-1\",\"country\":\"DE\",\"city\":\"Frankfurt\",\"file\":\"servers/de-1.conf\"}]}"- val parsed = parse(bundle(manifestText = text)).getOrThrow()- assertEquals("example", parsed.manifest.freshness.providerId)- assertEquals(7L, parsed.manifest.freshness.revision)- assertEquals("https://example.invalid/u.json", parsed.manifest.freshness.updateUrl)- assertTrue(parsed.manifest.freshness.issuedAtEpochMs!! < parsed.manifest.freshness.expiresAtEpochMs!!)- // Legacy bundle: no freshness fields still parses, with empty freshness.- assertTrue(parse(bundle()).getOrThrow().manifest.freshness.isEmpty)- }-- @Test fun rejectsNonsensicalFreshness() {- fun withFresh(extra: String): String =- "{\"format\":\"mavpn/1\",\"provider\":\"Example\",$extra,\"servers\":" +- "[{\"id\":\"de-1\",\"country\":\"DE\",\"city\":\"Frankfurt\",\"file\":\"servers/de-1.conf\"}]}"- for (bad in listOf(- "\"revision\":-1",- "\"revision\":1.5",- "\"providerId\":\"bad id!\"",- "\"issuedAt\":\"not-a-date\"",- "\"issuedAt\":\"2027-01-01T00:00:00Z\",\"expiresAt\":\"2026-01-01T00:00:00Z\"",- "\"updateUrl\":\"http://example.invalid/u.json\"",- )) {- assertTrue(parse(bundle(manifestText = withFresh(bad))).isFailure, bad)- }- }- @Test fun loadsCommittedDemoFixture() { val bytes = javaClass.getResourceAsStream("/mavpn/demo.mavpn")?.readBytes() ?: fail("missing test fixture /mavpn/demo.mavpn (regenerate with vpn/tools/generate_sample_mavpn.py)") val parsed = parse(bytes).getOrThrow() assertEquals("EXAMPLE Demo VPN (fictional)", parsed.manifest.provider)- assertEquals("example-demo-vpn", parsed.manifest.freshness.providerId)- assertEquals(1L, parsed.manifest.freshness.revision) assertEquals(listOf("de-fra-1", "de-ber-1", "us-nyc-1"), parsed.servers.map { it.entry.id }) assertTrue(parsed.servers.all { it.config.peerEndpoint.endsWith(".example.invalid:51820") }) }
vpn/src/test/java/com/vayunmathur/vpn/platform/VpnViewModelTest.kt
diff --git a/vpn/src/test/java/com/vayunmathur/vpn/platform/VpnViewModelTest.kt b/vpn/src/test/java/com/vayunmathur/vpn/platform/VpnViewModelTest.ktindex 872201e051..935876d12a 100644--- a/vpn/src/test/java/com/vayunmathur/vpn/platform/VpnViewModelTest.kt+++ b/vpn/src/test/java/com/vayunmathur/vpn/platform/VpnViewModelTest.kt@@ -11,7 +11,6 @@ import com.vayunmathur.vpn.data.DomainBytesSummary import com.vayunmathur.vpn.data.DomainCountSummary import com.vayunmathur.vpn.data.VpnConfig import com.vayunmathur.vpn.data.VpnConfigDao-import com.vayunmathur.vpn.data.MavpnUpdateClient import com.vayunmathur.vpn.data.VpnConfigEntity import java.io.File import kotlin.test.Test@@ -250,41 +249,4 @@ class VpnViewModelTest { withTimeout(5000) { while (BypassList.load(ctx).contains("com.example.a")) delay(25) } assertEquals("bypass_packages", BypassList.KEY) } }-- @Test fun updateCheckAndBadHashLeavesBundleUntouched() { runBlocking {- val dao = FakeConfigDao()- dao.rows.value = listOf(- VpnConfigEntity(- id = 1, name = "Example — Frankfurt", provider = "Example", bundleId = "b1",- bundleServerId = "de-1", providerId = "ex", bundleRevision = 1,- bundleUpdateUrl = "https://example.invalid/u.json",- ),- )- val bundleBytes = "not-a-bundle".encodeToByteArray()- val sha = com.vayunmathur.vpn.domain.sha256Hex(bundleBytes)- val metadata = """{"format":"mavpn-update/1","providerId":"ex","revision":2,""" +- """"downloadUrl":"https://example.invalid/b.mavpn","sha256":"$sha"}"""- val client = MavpnUpdateClient { url ->- if (url.endsWith("u.json")) metadata.encodeToByteArray() else bundleBytes- }- val vm2 = VpnViewModel(app, dao, FakeLogDao(), client)- vm2.checkForUpdate("b1")- val outcome = withTimeout(5000) {- vm2.updateChecks.first { it["b1"] is UpdateCheckOutcome.Available }- }- assertTrue((outcome["b1"] as UpdateCheckOutcome.Available).metadata.revision == 2L)- // The "bundle" is not a valid .mavpn, so applying must fail before any row changes.- val before = dao.rows.value- vm2.applyBundleUpdate("b1")- withTimeout(5000) { vm2.status.first { it?.startsWith("Update failed") == true || it?.startsWith("Import failed") == true } }- assertEquals(before, dao.rows.value)-- // Provider mismatch is a failed check, never an update.- val mismatchClient = MavpnUpdateClient {- """{"format":"mavpn-update/1","providerId":"other","revision":9}""".encodeToByteArray()- }- val vm3 = VpnViewModel(app, dao, FakeLogDao(), mismatchClient)- vm3.checkForUpdate("b1")- withTimeout(5000) { vm3.updateChecks.first { it["b1"] is UpdateCheckOutcome.Failed } }- } } }
vpn/src/test/resources/mavpn/demo.mavpn
diff --git a/vpn/src/test/resources/mavpn/demo.mavpn b/vpn/src/test/resources/mavpn/demo.mavpnindex 57e8684146..424d6e2c7d 100644Binary files a/vpn/src/test/resources/mavpn/demo.mavpn and b/vpn/src/test/resources/mavpn/demo.mavpn differ
vpn/tools/generate_sample_mavpn.py
diff --git a/vpn/tools/generate_sample_mavpn.py b/vpn/tools/generate_sample_mavpn.pyindex 06be5f4504..b6a7e67c3c 100644--- a/vpn/tools/generate_sample_mavpn.py+++ b/vpn/tools/generate_sample_mavpn.py@@ -58,11 +58,6 @@ def main() -> None: manifest = { "format": "mavpn/1", "provider": "EXAMPLE Demo VPN (fictional)",- "providerId": "example-demo-vpn",- "revision": 1,- "issuedAt": "2026-01-01T00:00:00Z",- "expiresAt": "2027-01-01T00:00:00Z",- "updateUrl": "https://example.invalid/mavpn-update.json", "servers": [ { "id": server_id,
vpn/tools/sample.mavpn
diff --git a/vpn/tools/sample.mavpn b/vpn/tools/sample.mavpnindex 57e8684146..424d6e2c7d 100644Binary files a/vpn/tools/sample.mavpn and b/vpn/tools/sample.mavpn differ