vpn: add .mavpn provider bundle import and geo picker
- Commit
3404c70369887e32103c4449cd3515243791e5f6- Author
- Vayun Mathur <[email protected]>
- When
- 2026-11-17 16:39 UTC (18 days ago)
- Parents
aeddf41
Add support for .mavpn bundles: a ZIP with manifest.json (format mavpn/1) and stock WireGuard servers/<name>.conf files, as specified in vpn/docs/MAVPN.md and noted in metadata_data/vpn.md. Domain (pure, no Android): MavpnParser safely unzips with entry-count, per-entry and total size caps, rejects traversal/absolute/backslash entry paths, validates the manifest (unknown format majors rejected, ISO country codes, unique server ids, servers/*.conf files), and loads every config through the app's existing WgConfigParser injected by the caller - no second WireGuard parser was written. GeoPickerData groups imported servers countries -> cities -> servers with flag emoji from the country code and localised country names from the platform Locale. Data: VpnConfig gains provider/countryCode/city/bundleId/bundleServerId (Room migration 2->3; plain .conf imports keep empty defaults), so imported servers are ordinary selectable configs in the existing tunnel model, list, detail and activation path. MavpnBundleStore writes bundles to app-private files/mavpn-bundles/<bundleId>/ with canonical-path confinement, and re-imports update servers in place by bundle + server id. Private keys are never logged. UI: import keeps the existing file picker and .conf path; the ViewModel sniffs ZIP magic / .mavpn name and routes bundles through the new importer. Server selection stays navigation: new Route.GeoPicker -> Route.GeoCountry -> Route.GeoCity destinations mirror how tunnels push Route.Detail today, with search as in-screen state. Selecting a server activates it via the existing VpnViewModel.startVpn consent flow, cards open the normal detail route, and the tunnel list gains a Browse by location entry showing provider/city on imported rows. Sample/testing: vpn/tools/generate_sample_mavpn.py reproducibly generates a fictional EXAMPLE bundle (example.invalid endpoints, fake keys) at vpn/tools/sample.mavpn and the committed parser fixture vpn/src/test/resources/mavpn/demo.mavpn. Tests cover manifest/format errors, traversal and oversize rejection, invalid WireGuard configs without leaking key material, fixture loading, import-to-config and geo-picker mapping, endpoint override, wg-quick round-trip for activation, re-import id reuse, and the Room migration. Verified: ./gradlew :vpn:testDevUnitTest :vpn:lintDev :vpn:detekt green (132 unit tests, detekt at zero findings), and ./gradlew :vpn:metadata regenerated the tunnel screenshots for the new Browse by location row. Baseline on origin/main was also green before the change. No live tunnel was tested (needs a device and a real endpoint).
Diff
metadata_data/photos/vpn/large-tablet/1.png
diff --git a/metadata_data/photos/vpn/large-tablet/1.png b/metadata_data/photos/vpn/large-tablet/1.pngindex 4154ecdaa8..be57fcbfc2 100644Binary files a/metadata_data/photos/vpn/large-tablet/1.png and b/metadata_data/photos/vpn/large-tablet/1.png differ
metadata_data/photos/vpn/phone/1.png
diff --git a/metadata_data/photos/vpn/phone/1.png b/metadata_data/photos/vpn/phone/1.pngindex 11bc781476..61aa11116e 100644Binary files a/metadata_data/photos/vpn/phone/1.png and b/metadata_data/photos/vpn/phone/1.png differ
metadata_data/vpn.md
diff --git a/metadata_data/vpn.md b/metadata_data/vpn.mdindex ab113f0b07..b8677670bf 100644--- a/metadata_data/vpn.md+++ b/metadata_data/vpn.md@@ -3,6 +3,7 @@ A simple, open-source VPN client with WireGuard support Features: - WireGuard protocol via a native Rust library - Import your own WireGuard config manually+- Import .mavpn provider bundles and pick a server by country and city (format: vpn/docs/MAVPN.md) - Per-app VPN bypass list - Connection logging - Material You design with dynamic theming
vpn/docs/MAVPN.md
diff --git a/vpn/docs/MAVPN.md b/vpn/docs/MAVPN.mdnew file mode 100644index 0000000000..f84bfc9235--- /dev/null+++ b/vpn/docs/MAVPN.md@@ -0,0 +1,77 @@+# The `.mavpn` bundle format (`mavpn/1`)++A `.mavpn` file is how a VPN provider ships a whole catalogue of WireGuard+servers to this app in one file, instead of one hand-imported `.conf` at a+time. Importing it adds every server to the tunnel list (with provider,+country and city attached) and to the *Browse by location* picker.++## Layout++A `.mavpn` file is a plain ZIP archive:++```+manifest.json+servers/<name>.conf+servers/<name>.conf+...+```++- `manifest.json` — at the ZIP root, UTF-8 JSON (below).+- `servers/*.conf` — stock WireGuard *wg-quick* configs, one per server,+ exactly as `wg-quick`, the WireGuard apps and this app's `.conf` import+ already accept (`[Interface]` + `[Peer]`). Do not invent a new config+ dialect: the app feeds these files to its existing WireGuard parser.++## `manifest.json`++```json+{+ "format": "mavpn/1",+ "provider": "Example VPN",+ "servers": [+ {+ "id": "de-fra-1",+ "country": "DE",+ "city": "Frankfurt",+ "file": "servers/de-fra-1.conf",+ "endpoint": "fra1.example.invalid:51820"+ },+ {+ "id": "us-nyc-1",+ "country": "US",+ "city": "New York",+ "file": "servers/us-nyc-1.conf"+ }+ ]+}+```++| Field | Required | Meaning |+|---|---|---|+| `format` | yes | Must be `"mavpn/1"`. A different major is rejected, so `mavpn/2` can break compatibility safely. Unknown extra fields are ignored within major 1. |+| `provider` | yes | Human-readable provider name, shown in the tunnel list and picker. |+| `servers[].id` | yes | Stable, unique per bundle: letters, digits, `.`, `_`, `-`. Re-importing a bundle updates the server with the same provider + `id` instead of duplicating it. |+| `servers[].country` | yes | ISO 3166-1 alpha-2 country code, upper-case (`"DE"`, `"US"`). Drives the flag and the localised country name in the picker. |+| `servers[].city` | yes | Human-readable city name, shown as-is. |+| `servers[].file` | yes | The server's config inside the ZIP: `servers/<name>.conf`. Must exist. |+| `servers[].endpoint` | no | Display/activation override for the config's `Endpoint`. When present it wins over the `.conf`; use it when the public endpoint differs from the one baked into the config. |++## Limits and safety (enforced on import)++- At most 256 ZIP entries, 200 servers, 1 MiB per entry, 8 MiB total+ uncompressed, 256 KiB of manifest.+- Entry paths must stay inside the bundle: absolute paths, `..`/`.` segments+ and backslash separators are rejected.+- Every referenced `.conf` must parse as a WireGuard config with an+ `[Interface]` `PrivateKey` and a `[Peer]` `PublicKey`.+- Configs are stored only in app-private storage+ (`files/mavpn-bundles/<bundle>/`) and in the app's encrypted config+ database. Private keys are never logged.++## Producing a bundle++- `vpn/tools/generate_sample_mavpn.py` writes a demo bundle with fictional+ `*.example.invalid` endpoints and clearly fake, `EXAMPLE`-labelled keys —+ 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/`.
vpn/src/main/java/com/vayunmathur/vpn/MainActivity.kt
diff --git a/vpn/src/main/java/com/vayunmathur/vpn/MainActivity.kt b/vpn/src/main/java/com/vayunmathur/vpn/MainActivity.ktindex 659eca8f34..7db50432b4 100644--- a/vpn/src/main/java/com/vayunmathur/vpn/MainActivity.kt+++ b/vpn/src/main/java/com/vayunmathur/vpn/MainActivity.kt@@ -60,7 +60,7 @@ class MainActivity : MaActivity() { private fun handleIntent(intent: Intent?) { intent ?: return- // Accept VIEW intents for .conf files from Files / Downloads etc.+ // Accept VIEW intents for .conf / .mavpn files from Files / Downloads etc. if (intent.action == Intent.ACTION_VIEW) { val uri = intent.data ?: return vm.importFromUri(this, uri)
vpn/src/main/java/com/vayunmathur/vpn/Route.kt
diff --git a/vpn/src/main/java/com/vayunmathur/vpn/Route.kt b/vpn/src/main/java/com/vayunmathur/vpn/Route.ktindex b7b9e39372..9cac8c9a5d 100644--- a/vpn/src/main/java/com/vayunmathur/vpn/Route.kt+++ b/vpn/src/main/java/com/vayunmathur/vpn/Route.kt@@ -30,4 +30,21 @@ sealed interface Route : NavKey { /** Singleton holding bypass list state and operations. */ @Serializable data object BypassList : Route++ /**+ * The geo picker for `.mavpn`-imported servers: a pushed destination+ * listing countries. Drilling into a country/city and picking a server+ * are navigation too (see [GeoCountry]/[GeoCity]), matching how a tunnel+ * is picked today — the tunnel list pushes [Detail] with the config id.+ */+ @Serializable+ data object GeoPicker : Route++ /** One country in the geo picker; carries the ISO alpha-2 [countryCode]. */+ @Serializable+ data class GeoCountry(val countryCode: String) : Route++ /** One city in the geo picker; carries its [countryCode] and [city]. */+ @Serializable+ data class GeoCity(val countryCode: String, val city: String) : Route }
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.ktnew file mode 100644index 0000000000..f825d17071--- /dev/null+++ b/vpn/src/main/java/com/vayunmathur/vpn/data/MavpnImport.kt@@ -0,0 +1,112 @@+package com.vayunmathur.vpn.data++import android.content.Context+import com.vayunmathur.vpn.domain.GeoServer+import com.vayunmathur.vpn.domain.MavpnBundle+import com.vayunmathur.vpn.domain.ParsedMavpnServer+import java.io.File+import java.security.MessageDigest++/**+ * Stable on-disk/database identity for one imported bundle: a slug of the+ * provider plus a short digest of provider + server ids, so re-importing the+ * same provider catalogue reuses the same bundle instead of duplicating it.+ * The digest is over ids only — never over config (key) material.+ */+fun bundleIdFor(provider: String, serverIds: List<String>): String {+ val slug = provider.lowercase().map { char -> if (char.isLetterOrDigit()) char else '-' }+ .joinToString("").trim('-').ifBlank { "provider" }+ val digest = MessageDigest.getInstance("SHA-256")+ .digest((provider + "\n" + serverIds.sorted().joinToString("\n")).encodeToByteArray())+ val short = digest.take(DIGEST_BYTES).joinToString("") { "%02x".format(it) }+ return "$slug-$short"+}++/**+ * Maps a validated bundle to selectable configs in the app's existing tunnel+ * model. Each imported server becomes a normal [VpnConfig] (so the tunnel+ * list, detail screen and activation path work unchanged), carrying its+ * provider/country/city/bundle metadata alongside.+ */+fun MavpnBundle<WgQuickImport>.toVpnConfigs(+ bundleId: String,+ existing: List<VpnConfig> = emptyList(),+ derivePublicKey: (String) -> String = { "" },+): List<VpnConfig> = servers.map { server ->+ server.toVpnConfig(bundleId, manifest.provider, existing, derivePublicKey)+}++fun ParsedMavpnServer<WgQuickImport>.toVpnConfig(+ bundleId: String,+ provider: String,+ existing: List<VpnConfig> = emptyList(),+ derivePublicKey: (String) -> String = { "" },+): VpnConfig {+ val imp = config+ val previous = existing.firstOrNull { it.bundleId == bundleId && it.bundleServerId == entry.id }+ return VpnConfig(+ id = previous?.id ?: 0,+ name = "$provider — ${entry.city}",+ privateKey = imp.privateKey,+ publicKey = runCatching { derivePublicKey(imp.privateKey) }.getOrDefault(""),+ address = imp.address,+ dns = imp.dns,+ mtu = imp.mtu,+ peerPublicKey = imp.peerPublicKey,+ peerPresharedKey = imp.peerPresharedKey,+ peerAllowedIPs = imp.peerAllowedIps,+ peerEndpoint = effectiveEndpoint { imp.peerEndpoint },+ peerKeepalive = imp.peerKeepalive,+ lastUsed = previous?.lastUsed ?: 0,+ provider = provider,+ countryCode = entry.country,+ city = entry.city,+ bundleId = bundleId,+ bundleServerId = entry.id,+ )+}++/** Flattens a config into the geo picker's server model, or null for non-bundle configs. */+fun VpnConfig.toGeoServerOrNull(): GeoServer? =+ if (bundleId.isBlank() && provider.isBlank()) null else GeoServer(+ configId = id,+ provider = provider,+ countryCode = countryCode,+ city = city,+ name = name,+ endpoint = peerEndpoint,+ )++private const val DIGEST_BYTES = 6++/**+ * Stores imported bundles under app-private storage:+ * `files/mavpn-bundles/<bundleId>/manifest.json` + `servers/<name>.conf`.+ * File names come only from the validated manifest (the parser already+ * rejected traversal), and every write is re-confined to the bundle dir.+ * Config contents — including private keys — are never logged here.+ */+object MavpnBundleStore {+ fun bundleDir(context: Context, bundleId: String): File =+ File(File(context.filesDir, "mavpn-bundles"), safeSegment(bundleId))++ fun save(context: Context, bundleId: String, bundle: MavpnBundle<WgQuickImport>, manifestJson: String) {+ val dir = bundleDir(context, bundleId)+ val serversDir = File(dir, "servers").apply { mkdirs() }+ File(dir, "manifest.json").writeText(manifestJson)+ for (server in bundle.servers) {+ val target = File(serversDir, File(server.entry.file).name)+ check(target.canonicalPath.startsWith(serversDir.canonicalPath)) { "Server file escapes bundle dir" }+ target.writeText(server.confText)+ }+ }++ /** Provider names of every bundle currently stored, sorted; empty when none were imported. */+ fun storedBundleIds(context: Context): List<String> =+ File(context.filesDir, "mavpn-bundles").listFiles { file -> file.isDirectory }+ ?.map { it.name }?.sorted().orEmpty()++ private fun safeSegment(raw: String): String =+ raw.map { char -> if (char.isLetterOrDigit() || char in "._-") char else '-' }+ .joinToString("").ifBlank { "bundle" }+}
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 5ca77939ae..b85b28e2da 100644--- a/vpn/src/main/java/com/vayunmathur/vpn/data/VpnConfig.kt+++ b/vpn/src/main/java/com/vayunmathur/vpn/data/VpnConfig.kt@@ -19,6 +19,12 @@ data class VpnConfig( val peerEndpoint: String = "", val peerKeepalive: Int = 25, val lastUsed: Long = 0,+ /** Bundle metadata for `.mavpn`-imported servers; empty for plain `.conf` imports. */+ val provider: String = "",+ val countryCode: String = "",+ val city: String = "",+ val bundleId: String = "",+ val bundleServerId: String = "", ) : DatabaseItem /** Immutable value describing wg quick import. */
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 b30503b862..4770a481f6 100644--- a/vpn/src/main/java/com/vayunmathur/vpn/data/VpnDatabase.kt+++ b/vpn/src/main/java/com/vayunmathur/vpn/data/VpnDatabase.kt@@ -34,6 +34,11 @@ data class VpnConfigEntity( val peerEndpoint: String = "", val peerKeepalive: Int = 25, val lastUsed: Long = 0,+ val provider: String = "",+ val countryCode: String = "",+ val city: String = "",+ val bundleId: String = "",+ val bundleServerId: String = "", ) : DatabaseItem fun VpnConfigEntity.toModel() = VpnConfig(@@ -41,7 +46,8 @@ fun VpnConfigEntity.toModel() = VpnConfig( address = address, dns = dns, mtu = mtu, peerPublicKey = peerPublicKey, peerPresharedKey = peerPresharedKey, peerAllowedIPs = peerAllowedIPs, peerEndpoint = peerEndpoint, peerKeepalive = peerKeepalive,- lastUsed = lastUsed,+ lastUsed = lastUsed, provider = provider, countryCode = countryCode, city = city,+ bundleId = bundleId, bundleServerId = bundleServerId, ) fun VpnConfig.toEntity() = VpnConfigEntity(@@ -49,7 +55,8 @@ fun VpnConfig.toEntity() = VpnConfigEntity( address = address, dns = dns, mtu = mtu, peerPublicKey = peerPublicKey, peerPresharedKey = peerPresharedKey, peerAllowedIPs = peerAllowedIPs, peerEndpoint = peerEndpoint, peerKeepalive = peerKeepalive,- lastUsed = lastUsed,+ lastUsed = lastUsed, provider = provider, countryCode = countryCode, city = city,+ bundleId = bundleId, bundleServerId = bundleServerId, ) /** Contract for vpn config dao. */@@ -118,15 +125,24 @@ val MIGRATION_1_2 = object : Migration(1, 2) { } } +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.+ for (column in listOf("provider", "countryCode", "city", "bundleId", "bundleServerId")) {+ connection.execSQL("ALTER TABLE `VpnConfigEntity` ADD COLUMN `$column` TEXT NOT NULL DEFAULT ''")+ }+ }+}+ /** Vpn Database: a room database implementation for vpn database. */-@Database(entities = [VpnConfigEntity::class, ConnectionLogEntity::class], version = 2, 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)+ 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.ktnew file mode 100644index 0000000000..3d104bd9cf--- /dev/null+++ b/vpn/src/main/java/com/vayunmathur/vpn/domain/GeoPickerData.kt@@ -0,0 +1,72 @@+package com.vayunmathur.vpn.domain++import java.util.Locale++/** One selectable imported server, flattened for the geo picker (config id + bundle metadata). */+data class GeoServer(+ val configId: Long,+ val provider: String,+ val countryCode: String,+ val city: String,+ val name: String,+ val endpoint: String,+)++/** A city and its servers, sorted by server name. */+data class GeoCity(+ val city: String,+ val servers: List<GeoServer>,+)++/** A country and its cities, sorted by localised country name then city. */+data class GeoCountry(+ val countryCode: String,+ val countryName: String,+ val flag: String,+ val cities: List<GeoCity>,+) {+ val serverCount: Int get() = cities.sumOf { it.servers.size }+}++/**+ * Groups imported servers into countries → cities → servers for the geo+ * picker. Pure: country names come from the platform [Locale] data, so the UI+ * gets localisation without a bundled country table.+ */+fun buildGeoCountries(servers: List<GeoServer>, locale: Locale = Locale.getDefault()): List<GeoCountry> =+ servers.groupBy { it.countryCode.uppercase(Locale.ROOT) }+ .map { (code, inCountry) ->+ GeoCountry(+ countryCode = code,+ countryName = countryDisplayName(code, locale),+ flag = flagEmoji(code),+ cities = inCountry.groupBy { it.city }+ .map { (city, inCity) -> GeoCity(city, inCity.sortedBy { it.name.lowercase(locale) }) }+ .sortedBy { it.city.lowercase(locale) },+ )+ }+ .sortedBy { it.countryName.lowercase(locale) }++/** Case-insensitive search over country, city, provider, server name and endpoint. */+fun filterGeoCountries(countries: List<GeoCountry>, query: String): List<GeoCountry> {+ val needle = query.trim().lowercase(Locale.ROOT)+ if (needle.isEmpty()) return countries+ return countries.mapNotNull { country ->+ val countryHit = needle in country.countryName.lowercase(Locale.ROOT) ||+ needle in country.countryCode.lowercase(Locale.ROOT)+ val cities = country.cities.mapNotNull { city ->+ val cityHit = countryHit || needle in city.city.lowercase(Locale.ROOT)+ val servers = city.servers.filter { server ->+ cityHit || needle in server.provider.lowercase(Locale.ROOT) ||+ needle in server.name.lowercase(Locale.ROOT) ||+ needle in server.endpoint.lowercase(Locale.ROOT)+ }+ if (servers.isEmpty()) null else GeoCity(city.city, servers)+ }+ if (cities.isEmpty()) null else country.copy(cities = cities)+ }+}++/** Flattens grouped countries back to their servers, in picker display order. */+fun List<GeoCountry>.flattenServers(): List<GeoServer> =+ flatMap { country -> country.cities.flatMap { it.servers } }
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.ktnew file mode 100644index 0000000000..153a3e0e8a--- /dev/null+++ b/vpn/src/main/java/com/vayunmathur/vpn/domain/MavpnBundle.kt@@ -0,0 +1,228 @@+package com.vayunmathur.vpn.domain++import java.io.ByteArrayInputStream+import java.io.ByteArrayOutputStream+import java.util.Locale+import java.util.zip.ZipInputStream+import kotlinx.serialization.json.Json+import kotlinx.serialization.json.JsonObject+import kotlinx.serialization.json.contentOrNull+import kotlinx.serialization.json.jsonArray+import kotlinx.serialization.json.jsonObject+import kotlinx.serialization.json.jsonPrimitive++/** One server entry from a `.mavpn` bundle manifest (`mavpn/1`). See `vpn/docs/MAVPN.md`. */+data class MavpnServerEntry(+ val id: String,+ val country: String,+ val city: String,+ val file: String,+ val endpoint: String? = null,+)++/** The parsed `manifest.json` of a `.mavpn` bundle. */+data class MavpnManifest(+ val format: String,+ val provider: String,+ val servers: List<MavpnServerEntry>,+)++/** A manifest entry together with its WireGuard config text and its parsed config. */+data class ParsedMavpnServer<T>(+ val entry: MavpnServerEntry,+ val confText: String,+ val config: T,+) {+ /** Endpoint shown and used for activation: the manifest override wins over the `.conf`. */+ fun effectiveEndpoint(confEndpoint: (T) -> String): String =+ entry.endpoint?.takeIf { it.isNotBlank() } ?: confEndpoint(config)+}++/** A fully validated `.mavpn` bundle: manifest plus every referenced, parsed server config. */+data class MavpnBundle<T>(+ val manifest: MavpnManifest,+ val servers: List<ParsedMavpnServer<T>>,+)++/** Why a `.mavpn` bundle was rejected. Messages never contain config (key) material. */+class MavpnFormatException(message: String) : IllegalArgumentException(message)++/**+ * Pure parser for `.mavpn` bundles (ZIP + `manifest.json` + `servers/<id>.conf`).+ *+ * No Android APIs: callers inject the app's existing WireGuard parser as+ * [MavpnParser.parse]'s `parseConf`, so this module never grows a second+ * WireGuard parser. Unzipping is defensive: entry count, per-entry size and+ * total size are capped and any path that would escape the bundle root+ * (absolute paths, `..` segments, backslash separators) is rejected before a+ * single byte of it is read.+ */+object MavpnParser {+ const val FORMAT = "mavpn/1"+ const val MANIFEST_NAME = "manifest.json"+ const val MAX_ENTRIES = 256+ const val MAX_SERVERS = 200+ const val MAX_ENTRY_BYTES = 1_048_576+ const val MAX_TOTAL_BYTES = 8_388_608+ const val MAX_MANIFEST_BYTES = 262_144++ private val idPattern = Regex("[A-Za-z0-9][A-Za-z0-9._-]*")+ private val serverFilePattern = Regex("servers/[A-Za-z0-9][A-Za-z0-9._-]*\\.conf")+ private val isoCountries: Set<String> by lazy { Locale.getISOCountries().toSet() }++ /**+ * Parses [bytes] as a `.mavpn` bundle, loading each referenced `.conf`+ * through [parseConf]. Fails with [MavpnFormatException] on any format,+ * safety or WireGuard problem; the underlying parser's error is wrapped+ * without echoing config contents.+ */+ fun <T> parse(bytes: ByteArray, parseConf: (String) -> Result<T>): Result<MavpnBundle<T>> = runCatching {+ val entries = unzip(bytes)+ val manifestText = entries[MANIFEST_NAME]+ ?: throw MavpnFormatException("Missing $MANIFEST_NAME at bundle root")+ val manifest = parseManifest(manifestText.decodeToString())+ val servers = manifest.servers.map { entry -> loadServer(entry, entries, parseConf) }+ MavpnBundle(manifest, servers)+ }.recoverCatching { error ->+ if (error is MavpnFormatException) throw error+ throw MavpnFormatException(error.message ?: "Invalid .mavpn bundle")+ }++ private fun <T> loadServer(+ entry: MavpnServerEntry,+ entries: Map<String, ByteArray>,+ parseConf: (String) -> Result<T>,+ ): ParsedMavpnServer<T> {+ val confBytes = entries[entry.file]+ ?: throw MavpnFormatException("Server '${entry.id}' references missing file '${entry.file}'")+ val confText = confBytes.decodeToString()+ val config = parseConf(confText).getOrElse {+ throw MavpnFormatException("Server '${entry.id}' has an invalid WireGuard config")+ }+ return ParsedMavpnServer(entry, confText, config)+ }++ /** Reads the whole ZIP into memory under the size/count caps, or throws [MavpnFormatException]. */+ internal fun unzip(bytes: ByteArray): Map<String, ByteArray> {+ val entries = LinkedHashMap<String, ByteArray>()+ var total = 0L+ ZipInputStream(ByteArrayInputStream(bytes)).use { zip ->+ while (true) {+ val entry = zip.nextEntry ?: break+ try {+ if (entries.size >= MAX_ENTRIES) {+ throw MavpnFormatException("Too many entries (limit $MAX_ENTRIES)")+ }+ val name = checkedEntryName(entry.name)+ if (entry.isDirectory) continue+ if (entries.containsKey(name)) throw MavpnFormatException("Duplicate entry '$name'")+ val cap = if (name == MANIFEST_NAME) MAX_MANIFEST_BYTES else MAX_ENTRY_BYTES+ val data = readCapped(zip, cap, name)+ total += data.size+ if (total > MAX_TOTAL_BYTES) {+ throw MavpnFormatException("Bundle too large (limit $MAX_TOTAL_BYTES bytes)")+ }+ entries[name] = data+ } finally {+ zip.closeEntry()+ }+ }+ }+ if (entries.isEmpty()) throw MavpnFormatException("Empty bundle")+ return entries+ }++ private fun readCapped(zip: ZipInputStream, cap: Int, name: String): ByteArray {+ val out = ByteArrayOutputStream()+ val buffer = ByteArray(DEFAULT_BUFFER_SIZE)+ while (true) {+ val read = zip.read(buffer)+ if (read < 0) break+ out.write(buffer, 0, read)+ if (out.size() > cap) throw MavpnFormatException("Entry '$name' too large (limit $cap bytes)")+ }+ return out.toByteArray()+ }++ /** Rejects absolute paths, drive-style/backslash separators and `..` traversal segments. */+ internal fun checkedEntryName(rawName: String): String {+ val name = rawName.trim()+ if (name.isEmpty()) throw MavpnFormatException("Empty entry name")+ if (name.startsWith("/") || name.startsWith("\\") || name.contains('\\')) {+ throw MavpnFormatException("Unsafe entry path '$rawName'")+ }+ if (name.split('/').any { it == ".." || it == "." }) {+ throw MavpnFormatException("Unsafe entry path '$rawName'")+ }+ if (name.length > 1 && name[1] == ':') throw MavpnFormatException("Unsafe entry path '$rawName'")+ return name+ }++ /** Parses and validates `manifest.json`; unknown fields are ignored within major 1. */+ internal fun parseManifest(text: String): MavpnManifest {+ val root = runCatching { Json.parseToJsonElement(text).jsonObject }.getOrElse {+ throw MavpnFormatException("manifest.json is not valid JSON")+ }+ val format = root.requiredString("format")+ checkFormat(format)+ val provider = root.requiredString("provider")+ val serverArray = root["servers"]?.let { runCatching { it.jsonArray }.getOrNull() }+ ?: throw MavpnFormatException("manifest.json is missing 'servers'")+ if (serverArray.isEmpty()) throw MavpnFormatException("manifest.json lists no servers")+ if (serverArray.size > MAX_SERVERS) {+ throw MavpnFormatException("Too many servers (limit $MAX_SERVERS)")+ }+ 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)+ }++ private fun checkFormat(format: String) {+ val parts = format.split('/')+ if (parts.size != 2 || parts[0] != "mavpn") {+ throw MavpnFormatException("Unknown bundle format '$format'")+ }+ val major = parts[1].toIntOrNull()+ ?: throw MavpnFormatException("Unknown bundle format '$format'")+ if (major != 1) throw MavpnFormatException("Unsupported mavpn format major $major")+ }++ private fun parseServer(obj: JsonObject): MavpnServerEntry {+ val id = obj.requiredString("id")+ if (!idPattern.matches(id)) throw MavpnFormatException("Invalid server id '$id'")+ val country = obj.requiredString("country")+ if (country !in isoCountries) throw MavpnFormatException("Invalid country code '$country'")+ val city = obj.requiredString("city")+ val file = obj.requiredString("file")+ if (!serverFilePattern.matches(file)) {+ throw MavpnFormatException("Invalid server file '$file' (expected servers/<name>.conf)")+ }+ val endpoint = obj["endpoint"]?.jsonPrimitive?.contentOrNull?.takeIf { it.isNotBlank() }+ return MavpnServerEntry(id, country, city, file, endpoint)+ }++ private fun JsonObject.requiredString(key: String): String {+ val value = this[key]?.jsonPrimitive?.contentOrNull+ if (value.isNullOrBlank()) throw MavpnFormatException("manifest.json is missing '$key'")+ return value.trim()+ }+}++/** Regional-indicator flag emoji for an ISO 3166-1 alpha-2 [countryCode], or the code itself. */+fun flagEmoji(countryCode: String): String {+ val code = countryCode.uppercase(Locale.ROOT)+ if (code.length != 2 || !code.all { it in 'A'..'Z' }) return code+ val first = Character.toChars(REGIONAL_INDICATOR_BASE + (code[0] - 'A'))+ val second = Character.toChars(REGIONAL_INDICATOR_BASE + (code[1] - 'A'))+ return String(first) + String(second)+}++/** Localised country name for [countryCode] in [locale] (the platform locale by default). */+fun countryDisplayName(countryCode: String, locale: Locale = Locale.getDefault()): String {+ val name = Locale.Builder().setRegion(countryCode.uppercase(Locale.ROOT)).build()+ .getDisplayCountry(locale)+ return name.ifBlank { countryCode.uppercase(Locale.ROOT) }+}++private const val REGIONAL_INDICATOR_BASE = 0x1F1E6
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 34630c3b4b..271afee314 100644--- a/vpn/src/main/java/com/vayunmathur/vpn/platform/VpnViewModel.kt+++ b/vpn/src/main/java/com/vayunmathur/vpn/platform/VpnViewModel.kt@@ -21,8 +21,16 @@ import com.vayunmathur.vpn.data.VpnConfig 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.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.MavpnBundle+import com.vayunmathur.vpn.domain.MavpnParser+import com.vayunmathur.vpn.domain.buildGeoCountries import com.vayunmathur.vpn.service.AppResolver import com.vayunmathur.vpn.service.ConnectionTracker import com.vayunmathur.vpn.service.VpnTunnelService@@ -38,6 +46,10 @@ import kotlinx.coroutines.flow.stateIn import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import kotlinx.serialization.json.Json+import kotlinx.serialization.json.addJsonObject+import kotlinx.serialization.json.buildJsonObject+import kotlinx.serialization.json.put+import kotlinx.serialization.json.putJsonArray import java.io.IOException /** View model for the vpn screen: holds UI state and handles its actions. */@@ -67,6 +79,16 @@ class VpnViewModel( val domainsByBytesFlow: StateFlow<List<DomainBytesSummary>> = logDao.flowDomainsByBytes() .stateIn(viewModelScope, SharingStarted.WhileSubscribed(STOP_TIMEOUT_MS), emptyList()) + /** Providers of imported `.mavpn` bundles, from the same config list the tunnels tab shows. */+ val importedProviders: StateFlow<List<String>> =+ configs.map { list -> list.map { it.provider }.filter { it.isNotBlank() }.distinct().sorted() }+ .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() }) }+ .stateIn(viewModelScope, SharingStarted.WhileSubscribed(STOP_TIMEOUT_MS), emptyList())+ init { viewModelScope.launch { while (true) {@@ -151,7 +173,8 @@ class VpnViewModel( } /**- * The only way to create a new tunnel — open a WireGuard .conf file.+ * Creates tunnels from a picked file: a `.mavpn` bundle (ZIP magic or+ * `.mavpn` name) or a single WireGuard `.conf`. * Parses [Interface] + [Peer] using the same tiny wg-quick parser the Rust side (gotatun/mullvad) expects. * Derives public key via Rust X25519 if native .so is loaded; otherwise stores empty pubkey. */@@ -164,12 +187,15 @@ class VpnViewModel( } catch (expected: SecurityException) { Log.status("VpnVM", "persist permission denied for $uri", expected) }- val text = context.contentResolver.openInputStream(uri)?.use {- it.bufferedReader().readText()- } ?: run {+ val bytes = context.contentResolver.openInputStream(uri)?.use { it.readBytes() } ?: run { _status.value = "Failed to read file" return@launch }+ if (isBundle(bytes, uri)) {+ importBundle(context, bytes)+ return@launch+ }+ val text = bytes.decodeToString() val imp = WgConfigParser.parse(text).getOrElse { _status.value = "Import failed: ${it.message}" return@launch@@ -209,6 +235,54 @@ class VpnViewModel( } } + private fun isBundle(bytes: ByteArray, uri: Uri): Boolean =+ uri.lastPathSegment?.endsWith(".mavpn", ignoreCase = true) == true ||+ (bytes.size >= ZIP_MAGIC.size && ZIP_MAGIC.indices.all { bytes[it] == ZIP_MAGIC[it] })++ /**+ * Validates a `.mavpn` bundle through the existing WireGuard parser,+ * stores it in app-private storage, and upserts every server as a normal+ * selectable config. Re-importing the same bundle updates its servers in+ * 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) {+ val bundle = MavpnParser.parse(bytes, WgConfigParser::parse).getOrElse {+ _status.value = "Import failed: ${it.message}"+ return+ }+ 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()) }+ _status.value = "Imported ${models.size} servers from ${bundle.manifest.provider}"+ }++ private fun manifestJson(bundle: MavpnBundle<*>): String =+ buildJsonObject {+ put("format", bundle.manifest.format)+ put("provider", bundle.manifest.provider)+ putJsonArray("servers") {+ bundle.manifest.servers.forEach { server ->+ addJsonObject {+ put("id", server.id)+ put("country", server.country)+ put("city", server.city)+ put("file", server.file)+ server.endpoint?.let { put("endpoint", it) }+ }+ }+ }+ }.toString()+ fun deleteAllLogs() { viewModelScope.launch(Dispatchers.IO) { logDao.deleteAll()@@ -229,6 +303,7 @@ class VpnViewModel( companion object { private const val STOP_TIMEOUT_MS = 5_000L private const val POLL_RUNNING_MS = 500L+ private val ZIP_MAGIC = byteArrayOf('P'.code.toByte(), 'K'.code.toByte(), 3, 4) } }
vpn/src/main/java/com/vayunmathur/vpn/ui/ConfigListContent.kt
diff --git a/vpn/src/main/java/com/vayunmathur/vpn/ui/ConfigListContent.kt b/vpn/src/main/java/com/vayunmathur/vpn/ui/ConfigListContent.ktindex 1cbce41081..c90d852996 100644--- a/vpn/src/main/java/com/vayunmathur/vpn/ui/ConfigListContent.kt+++ b/vpn/src/main/java/com/vayunmathur/vpn/ui/ConfigListContent.kt@@ -49,6 +49,7 @@ fun ConfigListContent( activeId: Long?, snackbar: SnackbarHostState = remember { SnackbarHostState() }, onImport: () -> Unit = {},+ onGeoPicker: () -> Unit = {}, onToggleConnect: (VpnConfig) -> Unit = {}, onOpen: (VpnConfig) -> Unit = {}, onDelete: (VpnConfig) -> Unit = {},@@ -65,6 +66,9 @@ fun ConfigListContent( verticalArrangement = Arrangement.spacedBy(12.dp), scrollBehavior = appBarScrollBehavior(), ) {+ item {+ Button(onGeoPicker, Modifier.fillMaxWidth()) { Text(stringResource(R.string.browse_by_location)) }+ } if (configs.isEmpty()) { item { Box(Modifier.fillParentMaxSize(), contentAlignment = Alignment.Center) {@@ -115,6 +119,14 @@ private fun ConfigRow( fontSize = 16.sp, modifier = Modifier.sharedText("vpn-title-${cfg.id}"), )+ if (cfg.provider.isNotBlank()) {+ Text(+ listOf(cfg.provider, cfg.city, cfg.countryCode).filter { it.isNotBlank() }+ .joinToString(" — "),+ fontSize = 12.sp,+ color = MaterialTheme.colorScheme.onSurfaceVariant,+ )+ } Text( cfg.peerEndpoint, fontSize = 12.sp,
vpn/src/main/java/com/vayunmathur/vpn/ui/ConfigListPage.kt
diff --git a/vpn/src/main/java/com/vayunmathur/vpn/ui/ConfigListPage.kt b/vpn/src/main/java/com/vayunmathur/vpn/ui/ConfigListPage.ktindex 8f6f3eeaf2..66e01413e5 100644--- a/vpn/src/main/java/com/vayunmathur/vpn/ui/ConfigListPage.kt+++ b/vpn/src/main/java/com/vayunmathur/vpn/ui/ConfigListPage.kt@@ -70,8 +70,9 @@ fun ConfigListPage(backStack: NavBackStack<Route>, vm: VpnViewModel) { // and that point the row shows the spinner instead. activeId = connectingId?.takeIf { VpnTunnelService.isRunning }, snackbar = snackbar,- // Open a .conf file — only import option per user request.+ // Open a .conf or .mavpn bundle file via SAF; the ViewModel sniffs which it is. onImport = { filePicker.launch(arrayOf("*/*")) },+ onGeoPicker = { backStack.add(Route.GeoPicker) }, onToggleConnect = { cfg -> if (connectingId != null && VpnTunnelService.isRunning) { vm.stopVpn()
vpn/src/main/java/com/vayunmathur/vpn/ui/GeoCityPage.kt
diff --git a/vpn/src/main/java/com/vayunmathur/vpn/ui/GeoCityPage.kt b/vpn/src/main/java/com/vayunmathur/vpn/ui/GeoCityPage.ktnew file mode 100644index 0000000000..9afa43d2e6--- /dev/null+++ b/vpn/src/main/java/com/vayunmathur/vpn/ui/GeoCityPage.kt@@ -0,0 +1,49 @@+package com.vayunmathur.vpn.ui++import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.lazy.items+import androidx.compose.runtime.Composable+import androidx.compose.runtime.collectAsState+import androidx.compose.runtime.getValue+import androidx.compose.ui.unit.dp+import com.vayunmathur.library.ui.LazyListScaffold+import com.vayunmathur.library.ui.Text+import com.vayunmathur.library.ui.appBarScrollBehavior+import com.vayunmathur.library.util.NavBackStack+import com.vayunmathur.vpn.Route+import com.vayunmathur.vpn.platform.VpnViewModel+import com.vayunmathur.vpn.ui.components.GeoServerRow+import com.vayunmathur.vpn.ui.components.rememberServerActivation++/**+ * Geo picker city (`Route.GeoCity`): its servers, each showing its endpoint.+ * Selecting a server activates that config through the existing tunnel path;+ * tapping its card opens the normal tunnel detail route.+ */+@Composable+fun GeoCityPage(backStack: NavBackStack<Route>, vm: VpnViewModel, countryCode: String, city: String) {+ val countries by vm.geoCountries.collectAsState()+ val configs by vm.configs.collectAsState()+ val activate = rememberServerActivation(vm)+ val geoCity = countries.firstOrNull { it.countryCode == countryCode }+ ?.cities?.firstOrNull { it.city == city }+ LazyListScaffold(+ title = city,+ horizontalPadding = 16.dp,+ verticalArrangement = Arrangement.spacedBy(12.dp),+ scrollBehavior = appBarScrollBehavior(),+ ) {+ if (geoCity == null) {+ item { Text(city) }+ } else {+ items(geoCity.servers, key = { it.configId }) { server ->+ val config = configs.firstOrNull { it.id == server.configId }+ GeoServerRow(+ server = server,+ onConnect = { if (config != null) activate(config) },+ onOpen = { backStack.add(Route.Detail(server.configId)) },+ )+ }+ }+ }+}
vpn/src/main/java/com/vayunmathur/vpn/ui/GeoCountryPage.kt
diff --git a/vpn/src/main/java/com/vayunmathur/vpn/ui/GeoCountryPage.kt b/vpn/src/main/java/com/vayunmathur/vpn/ui/GeoCountryPage.ktnew file mode 100644index 0000000000..227b2f9017--- /dev/null+++ b/vpn/src/main/java/com/vayunmathur/vpn/ui/GeoCountryPage.kt@@ -0,0 +1,59 @@+package com.vayunmathur.vpn.ui++import androidx.compose.foundation.clickable+import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.lazy.items+import androidx.compose.foundation.shape.RoundedCornerShape+import androidx.compose.material3.Card+import androidx.compose.runtime.Composable+import androidx.compose.runtime.collectAsState+import androidx.compose.runtime.getValue+import androidx.compose.ui.Modifier+import androidx.compose.ui.text.font.FontWeight+import androidx.compose.ui.unit.dp+import androidx.compose.ui.unit.sp+import com.vayunmathur.library.ui.LazyListScaffold+import com.vayunmathur.library.ui.Text+import com.vayunmathur.library.ui.appBarScrollBehavior+import com.vayunmathur.library.util.NavBackStack+import com.vayunmathur.vpn.Route+import com.vayunmathur.vpn.platform.VpnViewModel++/** Geo picker country (`Route.GeoCountry`): its cities; tapping a city is navigation. */+@Composable+fun GeoCountryPage(backStack: NavBackStack<Route>, vm: VpnViewModel, countryCode: String) {+ val countries by vm.geoCountries.collectAsState()+ val country = countries.firstOrNull { it.countryCode == countryCode }+ LazyListScaffold(+ title = if (country != null) "${country.flag} ${country.countryName}" else countryCode,+ horizontalPadding = 16.dp,+ verticalArrangement = Arrangement.spacedBy(12.dp),+ scrollBehavior = appBarScrollBehavior(),+ ) {+ if (country == null) {+ item { Text(countryCode) }+ } else {+ items(country.cities, key = { it.city }) { city ->+ Card(+ Modifier.fillMaxWidth()+ .clickable { backStack.add(Route.GeoCity(countryCode, city.city)) },+ shape = RoundedCornerShape(16.dp),+ ) {+ Text(+ city.city,+ fontWeight = FontWeight.Bold,+ fontSize = 16.sp,+ modifier = Modifier.padding(16.dp, 12.dp, 16.dp, 2.dp),+ )+ Text(+ "${city.servers.size}",+ fontSize = 12.sp,+ modifier = Modifier.padding(16.dp, 0.dp, 16.dp, 12.dp),+ )+ }+ }+ }+ }+}
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.ktnew file mode 100644index 0000000000..e45122f052--- /dev/null+++ b/vpn/src/main/java/com/vayunmathur/vpn/ui/GeoPickerPage.kt@@ -0,0 +1,93 @@+package com.vayunmathur.vpn.ui++import androidx.compose.foundation.clickable+import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.lazy.items+import androidx.compose.foundation.shape.RoundedCornerShape+import androidx.compose.material3.Card+import androidx.compose.runtime.Composable+import androidx.compose.runtime.collectAsState+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.saveable.rememberSaveable+import androidx.compose.runtime.setValue+import androidx.compose.ui.Modifier+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.text.font.FontWeight+import androidx.compose.ui.unit.dp+import androidx.compose.ui.unit.sp+import com.vayunmathur.library.ui.CommonSearchBar+import com.vayunmathur.library.ui.LazyListScaffold+import com.vayunmathur.library.ui.Text+import com.vayunmathur.library.ui.appBarScrollBehavior+import com.vayunmathur.library.util.NavBackStack+import com.vayunmathur.vpn.R+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.vpn.ui.components.GeoServerRow+import com.vayunmathur.vpn.ui.components.rememberServerActivation++/**+ * Geo picker root (`Route.GeoPicker`): countries from imported `.mavpn`+ * bundles, with in-screen search. Drilling into a country is navigation+ * ([Route.GeoCountry]); tapping a search-hit server activates it through the+ * existing tunnel path, and tapping its card opens its normal detail route.+ */+@Composable+fun GeoPickerPage(backStack: NavBackStack<Route>, vm: VpnViewModel) {+ val countries by vm.geoCountries.collectAsState()+ val configs by vm.configs.collectAsState()+ var query by rememberSaveable { mutableStateOf("") }+ val filtered = filterGeoCountries(countries, query)+ val activate = rememberServerActivation(vm)++ LazyListScaffold(+ title = stringResource(R.string.geo_picker_title),+ horizontalPadding = 16.dp,+ verticalArrangement = Arrangement.spacedBy(12.dp),+ scrollBehavior = appBarScrollBehavior(),+ ) {+ item {+ CommonSearchBar(+ value = query,+ onValueChange = { query = it },+ placeholder = stringResource(R.string.geo_search_hint),+ padding = androidx.compose.foundation.layout.PaddingValues(0.dp),+ )+ }+ when {+ countries.isEmpty() -> item { Text(stringResource(R.string.geo_no_bundles)) }+ filtered.isEmpty() -> item { Text(stringResource(R.string.geo_no_matches)) }+ query.isNotBlank() -> items(filtered.flattenServers(), key = { it.configId }) { server ->+ val config = configs.firstOrNull { it.id == server.configId }+ GeoServerRow(+ server = server,+ onConnect = { if (config != null) activate(config) },+ onOpen = { backStack.add(Route.Detail(server.configId)) },+ )+ }+ else -> items(filtered, key = { it.countryCode }) { country ->+ Card(+ Modifier.fillMaxWidth().clickable { backStack.add(Route.GeoCountry(country.countryCode)) },+ shape = RoundedCornerShape(16.dp),+ ) {+ Text(+ "${country.flag} ${country.countryName}",+ fontWeight = FontWeight.Bold,+ fontSize = 16.sp,+ modifier = Modifier.padding(16.dp, 12.dp, 16.dp, 2.dp),+ )+ Text(+ stringResource(R.string.geo_server_count, country.serverCount),+ fontSize = 12.sp,+ modifier = Modifier.padding(16.dp, 0.dp, 16.dp, 12.dp),+ )+ }+ }+ }+ }+}
vpn/src/main/java/com/vayunmathur/vpn/ui/VpnTabs.kt
diff --git a/vpn/src/main/java/com/vayunmathur/vpn/ui/VpnTabs.kt b/vpn/src/main/java/com/vayunmathur/vpn/ui/VpnTabs.ktindex 75487fc8d0..44686acb9a 100644--- a/vpn/src/main/java/com/vayunmathur/vpn/ui/VpnTabs.kt+++ b/vpn/src/main/java/com/vayunmathur/vpn/ui/VpnTabs.kt@@ -69,6 +69,11 @@ fun VpnTabs(backStack: NavBackStack<Route>, vm: VpnViewModel) { ConfigDetailPage(backStack, vm, it.id) } entry<Route.BypassList>(metadata = ListDetailPage()) { BypassListPage(backStack) }+ entry<Route.GeoPicker>(metadata = ListDetailPage()) { GeoPickerPage(backStack, vm) }+ entry<Route.GeoCountry>(metadata = ListDetailPage()) { GeoCountryPage(backStack, vm, it.countryCode) }+ entry<Route.GeoCity>(metadata = ListDetailPage()) {+ GeoCityPage(backStack, vm, it.countryCode, it.city)+ } } } }
vpn/src/main/java/com/vayunmathur/vpn/ui/components/GeoActivation.kt
diff --git a/vpn/src/main/java/com/vayunmathur/vpn/ui/components/GeoActivation.kt b/vpn/src/main/java/com/vayunmathur/vpn/ui/components/GeoActivation.ktnew file mode 100644index 0000000000..bb485e2d96--- /dev/null+++ b/vpn/src/main/java/com/vayunmathur/vpn/ui/components/GeoActivation.kt@@ -0,0 +1,48 @@+package com.vayunmathur.vpn.ui.components++import android.app.Activity+import android.content.Intent+import androidx.activity.compose.rememberLauncherForActivityResult+import androidx.activity.result.contract.ActivityResultContracts+import androidx.compose.runtime.Composable+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.setValue+import androidx.compose.ui.platform.LocalContext+import com.vayunmathur.vpn.data.VpnConfig+import com.vayunmathur.vpn.platform.VpnViewModel++/**+ * Remembers a `(VpnConfig) -> Unit` that activates a server through the app's+ * existing tunnel path ([VpnViewModel.startVpn]), running the system VPN+ * consent flow first when needed and retrying the same config after a grant —+ * the same pattern the tunnel list uses.+ */+@Composable+fun rememberServerActivation(vm: VpnViewModel): (VpnConfig) -> Unit {+ val context = LocalContext.current+ val activity = context as? Activity+ var pendingConfig by remember { mutableStateOf<VpnConfig?>(null) }+ lateinit var launchPermission: (Intent) -> Unit+ val permissionLauncher = rememberLauncherForActivityResult(+ contract = ActivityResultContracts.StartActivityForResult(),+ ) { result ->+ val granted = pendingConfig+ pendingConfig = null+ if (result.resultCode == Activity.RESULT_OK && granted != null) {+ vm.startVpn(granted, launchPermission)+ } else {+ vm.onVpnPermissionDenied()+ }+ }+ launchPermission = permissionLauncher::launch+ return remember(vm, activity) {+ { config: VpnConfig ->+ if (activity != null) {+ pendingConfig = config+ vm.startVpn(config, permissionLauncher::launch)+ }+ }+ }+}
vpn/src/main/java/com/vayunmathur/vpn/ui/components/GeoServerRow.kt
diff --git a/vpn/src/main/java/com/vayunmathur/vpn/ui/components/GeoServerRow.kt b/vpn/src/main/java/com/vayunmathur/vpn/ui/components/GeoServerRow.ktnew file mode 100644index 0000000000..a0f83e36a8--- /dev/null+++ b/vpn/src/main/java/com/vayunmathur/vpn/ui/components/GeoServerRow.kt@@ -0,0 +1,32 @@+package com.vayunmathur.vpn.ui.components++import androidx.compose.foundation.clickable+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.shape.RoundedCornerShape+import androidx.compose.material3.Card+import androidx.compose.runtime.Composable+import androidx.compose.ui.Modifier+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.text.font.FontFamily+import androidx.compose.ui.text.font.FontWeight+import androidx.compose.ui.unit.dp+import androidx.compose.ui.unit.sp+import com.vayunmathur.library.ui.Button+import com.vayunmathur.library.ui.Text+import com.vayunmathur.vpn.R+import com.vayunmathur.vpn.domain.GeoServer++/** One imported server in the geo picker: name, provider/city and endpoint, with a connect action. */+@Composable+fun GeoServerRow(server: GeoServer, onConnect: () -> Unit, onOpen: () -> Unit) {+ Card(Modifier.fillMaxWidth().clickable(onClick = onOpen), shape = RoundedCornerShape(16.dp)) {+ Column(Modifier.fillMaxWidth().padding(16.dp)) {+ Text(server.name, fontWeight = FontWeight.Bold, fontSize = 16.sp)+ Text("${server.provider} — ${server.city}", fontSize = 12.sp)+ Text(server.endpoint, fontSize = 12.sp, fontFamily = FontFamily.Monospace)+ Button(onClick = onConnect) { Text(stringResource(R.string.geo_connect)) }+ }+ }+}
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 6bc5325cd8..62dc56917b 100644--- a/vpn/src/main/res/values/strings.xml+++ b/vpn/src/main/res/values/strings.xml@@ -39,4 +39,12 @@ <string name="publickey">PublicKey: %1$s</string> <string name="peer_publickey">Peer PublicKey: %1$s</string> <string name="vpn_channel_name">VPN Tunnel</string>+ <!-- Geo picker (Route.GeoPicker/GeoCountry/GeoCity) for .mavpn-imported servers -->+ <string name="browse_by_location">Browse by location</string>+ <string name="geo_picker_title">Browse by location</string>+ <string name="geo_search_hint">Search countries, cities, providers</string>+ <string name="geo_no_bundles">No provider bundles imported yet. Import a .mavpn file from the tunnels tab to browse servers by location.</string>+ <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> </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.ktnew file mode 100644index 0000000000..0ec6f8ec4c--- /dev/null+++ b/vpn/src/test/java/com/vayunmathur/vpn/data/MavpnImportTest.kt@@ -0,0 +1,106 @@+package com.vayunmathur.vpn.data++import com.vayunmathur.vpn.domain.MavpnParser+import java.io.ByteArrayOutputStream+import java.util.zip.ZipEntry+import java.util.zip.ZipOutputStream+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNotEquals+import kotlin.test.assertNull+import kotlin.test.assertTrue++class MavpnImportTest {+ private val conf = """+ [Interface]+ PrivateKey = cGFzc3dvcmQxMjM0NTY3ODkwYWJjZGVmZ2hpamtsbW4=+ Address = 10.0.0.2/32+ DNS = 1.1.1.1+ [Peer]+ PublicKey = cGVlcnB1YmxpY2tleTEyMzQ1Njc4OTBhYmNkZWZnaGk=+ Endpoint = conf.example:51820+ """.trimIndent()++ private fun bundleBytes(): ByteArray {+ val manifest = """{"format":"mavpn/1","provider":"Example VPN","servers":[""" ++ """{"id":"de-1","country":"DE","city":"Frankfurt","file":"servers/de-1.conf",""" ++ """"endpoint":"manifest.example:9999"},""" ++ """{"id":"us-1","country":"US","city":"New York","file":"servers/us-1.conf"}]}"""+ val out = ByteArrayOutputStream()+ ZipOutputStream(out).use { zip ->+ for ((name, text) in listOf(+ "manifest.json" to manifest,+ "servers/de-1.conf" to conf,+ "servers/us-1.conf" to conf.replace("conf.example", "us.example"),+ )) {+ zip.putNextEntry(ZipEntry(name))+ zip.write(text.encodeToByteArray())+ zip.closeEntry()+ }+ }+ return out.toByteArray()+ }++ @Test fun importMapsServersToSelectableConfigs() {+ val bundle = MavpnParser.parse(bundleBytes(), WgConfigParser::parse).getOrThrow()+ val bundleId = bundleIdFor(bundle.manifest.provider, bundle.servers.map { it.entry.id })+ val configs = bundle.toVpnConfigs(bundleId) { "derived:" + it.take(4) }+ assertEquals(2, configs.size)+ val frankfurt = configs.first { it.bundleServerId == "de-1" }+ // Manifest endpoint wins over the .conf endpoint for activation/display.+ assertEquals("manifest.example:9999", frankfurt.peerEndpoint)+ assertEquals("Example VPN", frankfurt.provider)+ assertEquals("DE", frankfurt.countryCode)+ assertEquals("Frankfurt", frankfurt.city)+ assertEquals(bundleId, frankfurt.bundleId)+ assertEquals("derived:cGFz", frankfurt.publicKey)+ assertEquals("10.0.0.2/32", frankfurt.address)+ val newYork = configs.first { it.bundleServerId == "us-1" }+ assertEquals("us.example:51820", newYork.peerEndpoint)+ }++ @Test fun activationUsesSameConfigModelAndWgQuickRoundTrip() {+ val bundle = MavpnParser.parse(bundleBytes(), WgConfigParser::parse).getOrThrow()+ val config = bundle.toVpnConfigs("bundle-1").first { it.bundleServerId == "de-1" }+ // The existing tunnel activation serialises a VpnConfig; the imported+ // server must survive that path with its effective endpoint intact.+ val reparsed = WgConfigParser.parse(WgConfigParser.toWgQuick(config)).getOrThrow()+ assertEquals(config.privateKey, reparsed.privateKey)+ assertEquals("manifest.example:9999", reparsed.peerEndpoint)+ assertEquals(config.peerPublicKey, reparsed.peerPublicKey)+ }++ @Test fun reimportReusesExistingConfigIds() {+ val bundle = MavpnParser.parse(bundleBytes(), WgConfigParser::parse).getOrThrow()+ val bundleId = bundleIdFor(bundle.manifest.provider, bundle.servers.map { it.entry.id })+ val first = bundle.toVpnConfigs(bundleId)+ val saved = first.mapIndexed { index, config -> config.copy(id = 10L + index, lastUsed = 42) }+ val second = bundle.toVpnConfigs(bundleId, saved)+ assertEquals(saved.map { it.id }, second.map { it.id })+ assertEquals(listOf(42L, 42L), second.map { it.lastUsed })+ assertEquals(bundleId, bundleIdFor(bundle.manifest.provider, bundle.servers.map { it.entry.id }))+ assertNotEquals(bundleId, bundleIdFor("Other", bundle.servers.map { it.entry.id }))+ }++ @Test fun geoServerMappingOnlyForBundleConfigs() {+ val plain = VpnConfig(id = 1, name = "plain")+ assertNull(plain.toGeoServerOrNull())+ val imported = VpnConfig(+ id = 2, name = "Example VPN — Frankfurt", peerEndpoint = "h:1",+ provider = "Example VPN", countryCode = "DE", city = "Frankfurt", bundleId = "b",+ bundleServerId = "de-1",+ )+ val geo = imported.toGeoServerOrNull()+ assertEquals(2L, geo?.configId)+ assertEquals("h:1", geo?.endpoint)+ assertTrue(geo?.name?.contains("Frankfurt") == true)+ }++ @Test fun entityRoundTripKeepsBundleMetadata() {+ val config = VpnConfig(+ id = 7, name = "n", provider = "P", countryCode = "DE", city = "Berlin",+ bundleId = "p-abc", bundleServerId = "de-1",+ )+ assertEquals(config, config.toEntity().toModel())+ }+}
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 30121597fc..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,8 +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), 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) } }
vpn/src/test/java/com/vayunmathur/vpn/domain/GeoPickerDataTest.kt
diff --git a/vpn/src/test/java/com/vayunmathur/vpn/domain/GeoPickerDataTest.kt b/vpn/src/test/java/com/vayunmathur/vpn/domain/GeoPickerDataTest.ktnew file mode 100644index 0000000000..e95d2d26f5--- /dev/null+++ b/vpn/src/test/java/com/vayunmathur/vpn/domain/GeoPickerDataTest.kt@@ -0,0 +1,51 @@+package com.vayunmathur.vpn.domain++import java.util.Locale+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue++class GeoPickerDataTest {+ private val servers = listOf(+ GeoServer(3, "Example", "US", "New York", "Example — New York", "nyc.example:51820"),+ GeoServer(1, "Example", "DE", "Frankfurt", "Example — Frankfurt", "fra.example:51820"),+ GeoServer(2, "Example", "DE", "Berlin", "Example — Berlin", "ber.example:51820"),+ GeoServer(4, "Other", "DE", "Frankfurt", "Other — Frankfurt", "fra2.example:51820"),+ )++ @Test fun flagsFromCountryCodes() {+ assertEquals("🇩🇪", flagEmoji("DE"))+ assertEquals("🇺🇸", flagEmoji("us"))+ assertEquals("X", flagEmoji("X"))+ assertEquals("Germany", countryDisplayName("DE", Locale.US))+ assertEquals("United States", countryDisplayName("US", Locale.US))+ }++ @Test fun groupsCountriesCitiesServersSorted() {+ val countries = buildGeoCountries(servers, Locale.US)+ assertEquals(listOf("Germany", "United States"), countries.map { it.countryName })+ val germany = countries.first()+ assertEquals("🇩🇪", germany.flag)+ assertEquals(3, germany.serverCount)+ assertEquals(listOf("Berlin", "Frankfurt"), germany.cities.map { it.city })+ assertEquals(+ listOf("Example — Frankfurt", "Other — Frankfurt"),+ germany.cities.last().servers.map { it.name },+ )+ }++ @Test fun importedServersFlattenInPickerOrder() {+ val countries = buildGeoCountries(servers, Locale.US)+ assertEquals(listOf(2L, 1L, 4L, 3L), countries.flattenServers().map { it.configId })+ }++ @Test fun searchMatchesCountryCityProviderAndEndpoint() {+ val countries = buildGeoCountries(servers, Locale.US)+ assertEquals(listOf(3L), filterGeoCountries(countries, "new york").flattenServers().map { it.configId })+ assertEquals(listOf(4L), filterGeoCountries(countries, "other").flattenServers().map { it.configId })+ assertEquals(listOf(1L), filterGeoCountries(countries, "fra.example").flattenServers().map { it.configId })+ assertEquals(3, filterGeoCountries(countries, "germany").flattenServers().size)+ assertEquals(countries, filterGeoCountries(countries, " "))+ assertTrue(filterGeoCountries(countries, "zzz").isEmpty())+ }+}
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.ktnew file mode 100644index 0000000000..8a1b46bfcc--- /dev/null+++ b/vpn/src/test/java/com/vayunmathur/vpn/domain/MavpnParserTest.kt@@ -0,0 +1,135 @@+package com.vayunmathur.vpn.domain++import com.vayunmathur.vpn.data.WgConfigParser+import java.io.ByteArrayOutputStream+import java.util.zip.ZipEntry+import java.util.zip.ZipOutputStream+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue+import kotlin.test.fail++class MavpnParserTest {+ private val conf = """+ [Interface]+ PrivateKey = cGFzc3dvcmQxMjM0NTY3ODkwYWJjZGVmZ2hpamtsbW4=+ Address = 10.0.0.2/32+ [Peer]+ PublicKey = cGVlcnB1YmxpY2tleTEyMzQ1Njc4OTBhYmNkZWZnaGk=+ Endpoint = vpn.example.com:51820+ """.trimIndent()++ private fun manifest(+ format: String = "mavpn/1",+ servers: String = """[{"id":"de-1","country":"DE","city":"Frankfurt","file":"servers/de-1.conf"}]""",+ ) = """{"format":"$format","provider":"Example","servers":$servers}"""++ private fun zipOf(vararg entries: Pair<String, String>): ByteArray {+ val out = ByteArrayOutputStream()+ ZipOutputStream(out).use { zip ->+ for ((name, text) in entries) {+ zip.putNextEntry(ZipEntry(name))+ zip.write(text.encodeToByteArray())+ zip.closeEntry()+ }+ }+ return out.toByteArray()+ }++ private fun bundle(+ manifestText: String = manifest(),+ confText: String = conf,+ extra: Array<Pair<String, String>> = emptyArray(),+ ) = zipOf("manifest.json" to manifestText, "servers/de-1.conf" to confText, *extra)++ private fun parse(bytes: ByteArray) = MavpnParser.parse(bytes, WgConfigParser::parse)++ @Test fun parsesValidBundleThroughExistingWireGuardParser() {+ val parsed = parse(bundle()).getOrThrow()+ assertEquals("Example", parsed.manifest.provider)+ assertEquals(1, parsed.servers.size)+ val server = parsed.servers.single()+ assertEquals("DE", server.entry.country)+ assertEquals("Frankfurt", server.entry.city)+ assertEquals("cGFzc3dvcmQxMjM0NTY3ODkwYWJjZGVmZ2hpamtsbW4=", server.config.privateKey)+ assertEquals("vpn.example.com:51820", server.config.peerEndpoint)+ }++ @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(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") })+ }++ @Test fun manifestEndpointOverridesConfEndpoint() {+ val text = manifest(+ servers = """[{"id":"de-1","country":"DE","city":"Frankfurt","file":"servers/de-1.conf",""" ++ """"endpoint":"override.example:9999"}]""",+ )+ val server = parse(bundle(manifestText = text)).getOrThrow().servers.single()+ assertEquals("override.example:9999", server.effectiveEndpoint { it.peerEndpoint })+ }++ @Test fun rejectsUnknownFormatMajorAndBadFormat() {+ assertTrue(parse(bundle(manifestText = manifest(format = "mavpn/2"))).isFailure)+ assertTrue(parse(bundle(manifestText = manifest(format = "other/1"))).isFailure)+ assertTrue(parse(bundle(manifestText = manifest(format = "mavpn/x"))).isFailure)+ assertTrue(parse(bundle(manifestText = "{}")).isFailure)+ assertTrue(parse(bundle(manifestText = "not json")).isFailure)+ }++ @Test fun rejectsMissingManifestAndMissingServerFile() {+ assertTrue(parse(zipOf("servers/de-1.conf" to conf)).isFailure)+ val missing = manifest(+ servers = """[{"id":"de-1","country":"DE","city":"Frankfurt","file":"servers/nope.conf"}]""",+ )+ assertTrue(parse(bundle(manifestText = missing)).isFailure)+ }++ @Test fun rejectsTraversalAndAbsoluteEntries() {+ for (evil in listOf("../evil.conf", "servers/../../evil.conf", "/abs.conf", "servers\\evil.conf")) {+ val bytes = zipOf("manifest.json" to manifest(), evil to conf)+ val result = parse(bytes)+ assertTrue(result.isFailure, "expected rejection for $evil")+ }+ assertTrue(MavpnParser.runCatching { checkedEntryName("a/../b") }.isFailure)+ assertEquals("servers/de-1.conf", MavpnParser.checkedEntryName("servers/de-1.conf"))+ }++ @Test fun rejectsOversizeEntryAndTooManyEntries() {+ val bigConf = conf + "\n# " + "x".repeat(MavpnParser.MAX_ENTRY_BYTES)+ assertTrue(parse(bundle(confText = bigConf)).isFailure)+ val many = Array(MavpnParser.MAX_ENTRIES + 1) { "extra/$it.txt" to "x" }+ assertTrue(parse(bundle(extra = many)).isFailure)+ }++ @Test fun rejectsBadManifestFields() {+ val cases = listOf(+ """[{"id":"bad id!","country":"DE","city":"X","file":"servers/de-1.conf"}]""",+ """[{"id":"de-1","country":"XX","city":"X","file":"servers/de-1.conf"}]""",+ """[{"id":"de-1","country":"DE","city":"","file":"servers/de-1.conf"}]""",+ """[{"id":"de-1","country":"DE","city":"X","file":"elsewhere/de-1.conf"}]""",+ """[{"id":"de-1","country":"DE","city":"X","file":"servers/de-1.conf"},""" ++ """{"id":"de-1","country":"DE","city":"Y","file":"servers/de-1.conf"}]""",+ """[]""",+ )+ for (servers in cases) {+ assertTrue(parse(bundle(manifestText = manifest(servers = servers))).isFailure, servers)+ }+ }++ @Test fun rejectsInvalidWireGuardConfWithoutLeakingKeyMaterial() {+ val result = parse(bundle(confText = "[Interface]\nPrivateKey = SECRETKEY\n"))+ assertTrue(result.isFailure)+ val message = result.exceptionOrNull()?.message.orEmpty()+ assertTrue("SECRETKEY" !in message, "parser error leaked config contents: $message")+ }++ @Test fun rejectsNonZipAndEmptyInput() {+ assertTrue(parse(ByteArray(0)).isFailure)+ assertTrue(parse("not a zip".encodeToByteArray()).isFailure)+ }+}
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 3357b44bc0..f6959f8c1f 100644--- a/vpn/src/test/java/com/vayunmathur/vpn/platform/VpnViewModelTest.kt+++ b/vpn/src/test/java/com/vayunmathur/vpn/platform/VpnViewModelTest.kt@@ -145,6 +145,37 @@ class VpnViewModelTest { delay(200) } } + @Test fun importFromUriMavpnBundle() { runBlocking {+ val dao = FakeConfigDao(); val vm = vm(dao)+ val ctx = app as Context+ val manifest = """{"format":"mavpn/1","provider":"Example VPN","servers":[""" ++ """{"id":"de-1","country":"DE","city":"Frankfurt","file":"servers/de-1.conf", """ ++ """"endpoint":"manifest.example:9999"}]}"""+ val conf = "[Interface]\nPrivateKey = abc=\nAddress = 10.0.0.2/32\n[Peer]\nPublicKey = def=\nEndpoint = conf.example:51820\n"+ val bundleFile = File(ctx.cacheDir, "demo.mavpn")+ java.util.zip.ZipOutputStream(bundleFile.outputStream()).use { zip ->+ for ((name, text) in listOf("manifest.json" to manifest, "servers/de-1.conf" to conf)) {+ zip.putNextEntry(java.util.zip.ZipEntry(name)); zip.write(text.encodeToByteArray()); zip.closeEntry()+ }+ }+ vm.importFromUri(ctx, Uri.fromFile(bundleFile))+ withTimeout(8000) { while (dao.rows.value.isEmpty()) delay(25) }+ val row = dao.rows.value.single()+ assertEquals("Example VPN", row.provider); assertEquals("DE", row.countryCode)+ assertEquals("Frankfurt", row.city); assertEquals("de-1", row.bundleServerId)+ assertEquals("manifest.example:9999", row.peerEndpoint)+ withTimeout(5000) { while (vm.status.value?.startsWith("Imported 1 servers") != true) delay(25) }+ assertEquals(listOf("Example VPN"), withTimeout(5000) { vm.importedProviders.first { it.isNotEmpty() } })+ assertEquals("Frankfurt", withTimeout(5000) { vm.geoCountries.first { it.isNotEmpty() } }.single().cities.single().city)+ // The bundle was stored in app-private storage under its bundle id.+ assertTrue(java.io.File(ctx.filesDir, "mavpn-bundles").listFiles()?.isNotEmpty() == true)+ // A corrupt bundle fails cleanly with no new rows.+ val badFile = File(ctx.cacheDir, "bad.mavpn").apply { writeBytes("not a zip".encodeToByteArray()) }+ vm.importFromUri(ctx, Uri.fromFile(badFile))+ withTimeout(5000) { while (vm.status.value?.startsWith("Import failed") != true) delay(25) }+ assertEquals(1, dao.rows.value.size)+ } }+ @Test fun importNameFromEndpointWhenNoFileName() { runBlocking { val dao = FakeConfigDao(); val vm = vm(dao) val ctx = app as Context
vpn/src/test/resources/mavpn/demo.mavpn
diff --git a/vpn/src/test/resources/mavpn/demo.mavpn b/vpn/src/test/resources/mavpn/demo.mavpnnew file mode 100644index 0000000000..424d6e2c7dBinary files /dev/null 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.pynew file mode 100644index 0000000000..b6a7e67c3c--- /dev/null+++ b/vpn/tools/generate_sample_mavpn.py@@ -0,0 +1,85 @@+#!/usr/bin/env python3+"""Generate a demo .mavpn bundle with fictional servers.++Usage:+ python3 vpn/tools/generate_sample_mavpn.py [output.mavpn]++Defaults to vpn/tools/sample.mavpn. Also used to (re)generate the parser+test fixture at vpn/src/test/resources/mavpn/demo.mavpn:++ python3 vpn/tools/generate_sample_mavpn.py vpn/src/test/resources/mavpn/demo.mavpn++Every endpoint is under example.invalid and every key is a clearly fake,+EXAMPLE-labelled placeholder derived from a fixed byte pattern. Never use+this bundle to connect anywhere. ZIP timestamps are pinned so the output is+byte-for-byte reproducible.+"""++import base64+import json+import sys+import zipfile++FIXED_DATE = (2020, 1, 1, 0, 0, 0)+++def example_key(seed: int) -> str:+ """A well-formed 44-char WireGuard-shaped key that is obviously fake."""+ raw = bytes((seed + i) % 256 for i in range(32))+ return base64.b64encode(raw).decode()+++def conf(server_id: str, host: str, seed: int) -> str:+ return (+ "# EXAMPLE fake WireGuard config for the .mavpn demo bundle.\n"+ "# EXAMPLE keys only - not real, never use to connect.\n"+ "[Interface]\n"+ f"PrivateKey = {example_key(seed)}\n"+ "Address = 10.66.0.2/32\n"+ "DNS = 1.1.1.1\n"+ "\n"+ "[Peer]\n"+ f"PublicKey = {example_key(seed + 100)}\n"+ "AllowedIPs = 0.0.0.0/0, ::/0\n"+ f"Endpoint = {host}:51820\n"+ "PersistentKeepalive = 25\n"+ )+++SERVERS = [+ ("de-fra-1", "DE", "Frankfurt", "fra1.example.invalid", 11),+ ("de-ber-1", "DE", "Berlin", "ber1.example.invalid", 22),+ ("us-nyc-1", "US", "New York", "nyc1.example.invalid", 33),+]+++def main() -> None:+ out = sys.argv[1] if len(sys.argv) > 1 else "vpn/tools/sample.mavpn"+ manifest = {+ "format": "mavpn/1",+ "provider": "EXAMPLE Demo VPN (fictional)",+ "servers": [+ {+ "id": server_id,+ "country": country,+ "city": city,+ "file": f"servers/{server_id}.conf",+ "endpoint": f"{host}:51820",+ }+ for server_id, country, city, host, _ in SERVERS+ ],+ }+ with zipfile.ZipFile(out, "w", zipfile.ZIP_DEFLATED) as bundle:+ def write(name: str, text: str) -> None:+ info = zipfile.ZipInfo(name, FIXED_DATE)+ info.compress_type = zipfile.ZIP_DEFLATED+ bundle.writestr(info, text)++ write("manifest.json", json.dumps(manifest, indent=2) + "\n")+ for server_id, _, _, host, seed in SERVERS:+ write(f"servers/{server_id}.conf", conf(server_id, host, seed))+ print(f"wrote {out}")+++if __name__ == "__main__":+ main()
vpn/tools/sample.mavpn
diff --git a/vpn/tools/sample.mavpn b/vpn/tools/sample.mavpnnew file mode 100644index 0000000000..424d6e2c7dBinary files /dev/null and b/vpn/tools/sample.mavpn differ