astronomy: migrate to canonical structure
- Commit
e2a74d1b6b59a08c78304b451a599d37456fe413- Author
- vayun-mathur <[email protected]>
- When
- 2026-08-15 19:34 UTC (3 months ago)
- Parents
908b337
Diff
astronomy/src/main/java/com/vayunmathur/astronomy/MainActivity.kt
diff --git a/astronomy/src/main/java/com/vayunmathur/astronomy/MainActivity.kt b/astronomy/src/main/java/com/vayunmathur/astronomy/MainActivity.ktnew file mode 100644index 0000000000..5fad735b1b--- /dev/null+++ b/astronomy/src/main/java/com/vayunmathur/astronomy/MainActivity.kt@@ -0,0 +1,33 @@+package com.vayunmathur.astronomy++import android.Manifest+import android.os.Bundle+import androidx.activity.ComponentActivity+import androidx.activity.compose.setContent+import androidx.activity.enableEdgeToEdge+import androidx.activity.viewModels+import com.vayunmathur.astronomy.platform.AstronomyViewModel+import com.vayunmathur.library.ui.DynamicTheme+import com.vayunmathur.library.ui.PermissionsChecker++class MainActivity : ComponentActivity() {+ private val viewModel: AstronomyViewModel by viewModels()++ override fun onCreate(savedInstanceState: Bundle?) {+ super.onCreate(savedInstanceState)+ enableEdgeToEdge()+ setContent {+ DynamicTheme {+ PermissionsChecker(+ arrayOf(+ Manifest.permission.ACCESS_FINE_LOCATION,+ Manifest.permission.ACCESS_COARSE_LOCATION+ ),+ "Grant location permission — astronomy needs your position for horizon"+ ) {+ Navigation(viewModel)+ }+ }+ }+ }+}\ No newline at end of file
astronomy/src/main/java/com/vayunmathur/astronomy/platform/sensor/LocationProvider.kt
diff --git a/astronomy/src/main/java/com/vayunmathur/astronomy/platform/sensor/LocationProvider.kt b/astronomy/src/main/java/com/vayunmathur/astronomy/platform/sensor/LocationProvider.ktnew file mode 100644index 0000000000..537691d8e1--- /dev/null+++ b/astronomy/src/main/java/com/vayunmathur/astronomy/platform/sensor/LocationProvider.kt@@ -0,0 +1,45 @@+package com.vayunmathur.astronomy.platform.sensor++import android.Manifest+import android.annotation.SuppressLint+import android.content.Context+import android.content.pm.PackageManager+import android.location.Location+import android.location.LocationManager+import androidx.core.content.ContextCompat+import kotlinx.coroutines.suspendCancellableCoroutine+import kotlin.coroutines.resume++object LocationProvider {+ fun hasPermission(context: Context): Boolean {+ val fine = ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION)+ val coarse = ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION)+ return fine == PackageManager.PERMISSION_GRANTED || coarse == PackageManager.PERMISSION_GRANTED+ }++ @SuppressLint("MissingPermission")+ suspend fun currentLocation(context: Context): Location? {+ if (!hasPermission(context)) return null+ val lm = context.getSystemService(Context.LOCATION_SERVICE) as? LocationManager ?: return null+ val providers = listOf(LocationManager.GPS_PROVIDER, LocationManager.NETWORK_PROVIDER).filter { lm.isProviderEnabled(it) }+ if (providers.isEmpty()) return null+ providers.mapNotNull { runCatching { lm.getLastKnownLocation(it) }.getOrNull() }.maxByOrNull { it.time }?.let { return it }+ return suspendCancellableCoroutine { cont ->+ val listeners = mutableListOf<android.location.LocationListener>()+ var resumed = false+ providers.forEach { provider ->+ val listener = object : android.location.LocationListener {+ override fun onLocationChanged(location: Location) {+ if (!resumed) { resumed = true; listeners.forEach { runCatching { lm.removeUpdates(it) } }; cont.resume(location) }+ }+ override fun onProviderDisabled(provider: String) {}+ override fun onProviderEnabled(provider: String) {}+ @Deprecated("Deprecated") override fun onStatusChanged(provider: String?, status: Int, extras: android.os.Bundle?) {}+ }+ listeners += listener+ runCatching { lm.requestLocationUpdates(provider, 0L, 0f, listener, android.os.Looper.getMainLooper()) }+ }+ cont.invokeOnCancellation { listeners.forEach { runCatching { lm.removeUpdates(it) } } }+ }+ }+}
passwords/src/main/java/com/vayunmathur/passwords/platform/cable/CborReader.kt
diff --git a/passwords/src/main/java/com/vayunmathur/passwords/platform/cable/CborReader.kt b/passwords/src/main/java/com/vayunmathur/passwords/platform/cable/CborReader.ktindex 48daf17a93..ffe3c06324 100644--- a/passwords/src/main/java/com/vayunmathur/passwords/platform/cable/CborReader.kt+++ b/passwords/src/main/java/com/vayunmathur/passwords/platform/cable/CborReader.kt@@ -1,118 +1,118 @@-package com.vayunmathur.passwords.platform.cable--/**- * Minimal CBOR (RFC 8949) decoder, companion to the canonical encoder in- * [com.vayunmathur.passwords.util.Cbor]. Covers exactly what caBLE / CTAP2 / COSE need:- * unsigned + negative integers, byte strings, text strings, arrays, maps, and the- * `true`/`false`/`null` simple values.- *- * Decoded types:- * - integers -> [Long]- * - byte string -> [ByteArray]- * - text string -> [String]- * - array -> `List<Any?>`- * - map -> `LinkedHashMap<Any, Any?>` (insertion order = wire order)- * - simple -> [Boolean] or `null`- *- * Indefinite-length items and floats are intentionally unsupported (never used by these protocols).- */-class CborReader(private val bytes: ByteArray, private var pos: Int = 0) {-- /** Number of unconsumed bytes remaining. */- val remaining: Int get() = bytes.size - pos-- /** Reads a single CBOR data item, advancing the cursor. */- fun readValue(): Any? {- val initial = readByte()- val major = (initial.toInt() and 0xFF) ushr 5- val minor = initial.toInt() and 0x1F- return when (major) {- MAJOR_UNSIGNED -> readArg(minor)- MAJOR_NEGATIVE -> -1L - readArg(minor)- MAJOR_BYTE_STRING -> readBytes(readArg(minor).toIntChecked())- MAJOR_TEXT_STRING -> String(readBytes(readArg(minor).toIntChecked()), Charsets.UTF_8)- MAJOR_ARRAY -> {- val n = readArg(minor).toIntChecked()- ArrayList<Any?>(n).apply { repeat(n) { add(readValue()) } }- }- MAJOR_MAP -> {- val n = readArg(minor).toIntChecked()- LinkedHashMap<Any, Any?>(n * 2).apply {- repeat(n) {- val k = readValue() ?: error("CBOR map key must not be null")- put(k, readValue())- }- }- }- MAJOR_SIMPLE -> when (minor) {- SIMPLE_FALSE -> false- SIMPLE_TRUE -> true- SIMPLE_NULL -> null- SIMPLE_UNDEFINED -> null- else -> error("Unsupported CBOR simple value: $minor")- }- else -> error("Unsupported CBOR major type: $major")- }- }-- /** Reads a value expected to be an integer. */- fun readInt(): Long = readValue() as? Long ?: error("Expected CBOR integer")-- /** Reads a value expected to be a byte string. */- fun readByteString(): ByteArray = readValue() as? ByteArray ?: error("Expected CBOR byte string")-- /** Reads a value expected to be a map keyed by [Long] (CTAP-style integer keys). */- @Suppress("UNCHECKED_CAST")- fun readIntMap(): Map<Long, Any?> {- val map = readValue() as? Map<*, *> ?: error("Expected CBOR map")- return map.entries.associate { (k, v) -> (k as Long) to v }- }-- private fun readArg(minor: Int): Long = when (minor) {- in 0..23 -> minor.toLong()- 24 -> readByte().toLong() and 0xFF- 25 -> readUInt(2)- 26 -> readUInt(4)- 27 -> readUInt(8)- else -> error("Unsupported CBOR additional-info: $minor")- }-- private fun readUInt(n: Int): Long {- var value = 0L- repeat(n) { value = (value shl 8) or (readByte().toLong() and 0xFF) }- return value- }-- private fun readByte(): Byte {- if (pos >= bytes.size) error("Unexpected end of CBOR input")- return bytes[pos++]- }-- private fun readBytes(n: Int): ByteArray {- if (pos + n > bytes.size) error("Unexpected end of CBOR input")- return bytes.copyOfRange(pos, pos + n).also { pos += n }- }-- private fun Long.toIntChecked(): Int {- if (this < 0 || this > Int.MAX_VALUE) error("CBOR length out of range: $this")- return toInt()- }-- companion object {- private const val MAJOR_UNSIGNED = 0- private const val MAJOR_NEGATIVE = 1- private const val MAJOR_BYTE_STRING = 2- private const val MAJOR_TEXT_STRING = 3- private const val MAJOR_ARRAY = 4- private const val MAJOR_MAP = 5- private const val MAJOR_SIMPLE = 7-- private const val SIMPLE_FALSE = 20- private const val SIMPLE_TRUE = 21- private const val SIMPLE_NULL = 22- private const val SIMPLE_UNDEFINED = 23-- /** Decodes a single top-level CBOR value from [bytes]. */- fun decode(bytes: ByteArray): Any? = CborReader(bytes).readValue()- }-}+package com.vayunmathur.passwords.platform.cable++/**+ * Minimal CBOR (RFC 8949) decoder, companion to the canonical encoder in+ * [com.vayunmathur.passwords.domain.Cbor]. Covers exactly what caBLE / CTAP2 / COSE need:+ * unsigned + negative integers, byte strings, text strings, arrays, maps, and the+ * `true`/`false`/`null` simple values.+ *+ * Decoded types:+ * - integers -> [Long]+ * - byte string -> [ByteArray]+ * - text string -> [String]+ * - array -> `List<Any?>`+ * - map -> `LinkedHashMap<Any, Any?>` (insertion order = wire order)+ * - simple -> [Boolean] or `null`+ *+ * Indefinite-length items and floats are intentionally unsupported (never used by these protocols).+ */+class CborReader(private val bytes: ByteArray, private var pos: Int = 0) {++ /** Number of unconsumed bytes remaining. */+ val remaining: Int get() = bytes.size - pos++ /** Reads a single CBOR data item, advancing the cursor. */+ fun readValue(): Any? {+ val initial = readByte()+ val major = (initial.toInt() and 0xFF) ushr 5+ val minor = initial.toInt() and 0x1F+ return when (major) {+ MAJOR_UNSIGNED -> readArg(minor)+ MAJOR_NEGATIVE -> -1L - readArg(minor)+ MAJOR_BYTE_STRING -> readBytes(readArg(minor).toIntChecked())+ MAJOR_TEXT_STRING -> String(readBytes(readArg(minor).toIntChecked()), Charsets.UTF_8)+ MAJOR_ARRAY -> {+ val n = readArg(minor).toIntChecked()+ ArrayList<Any?>(n).apply { repeat(n) { add(readValue()) } }+ }+ MAJOR_MAP -> {+ val n = readArg(minor).toIntChecked()+ LinkedHashMap<Any, Any?>(n * 2).apply {+ repeat(n) {+ val k = readValue() ?: error("CBOR map key must not be null")+ put(k, readValue())+ }+ }+ }+ MAJOR_SIMPLE -> when (minor) {+ SIMPLE_FALSE -> false+ SIMPLE_TRUE -> true+ SIMPLE_NULL -> null+ SIMPLE_UNDEFINED -> null+ else -> error("Unsupported CBOR simple value: $minor")+ }+ else -> error("Unsupported CBOR major type: $major")+ }+ }++ /** Reads a value expected to be an integer. */+ fun readInt(): Long = readValue() as? Long ?: error("Expected CBOR integer")++ /** Reads a value expected to be a byte string. */+ fun readByteString(): ByteArray = readValue() as? ByteArray ?: error("Expected CBOR byte string")++ /** Reads a value expected to be a map keyed by [Long] (CTAP-style integer keys). */+ @Suppress("UNCHECKED_CAST")+ fun readIntMap(): Map<Long, Any?> {+ val map = readValue() as? Map<*, *> ?: error("Expected CBOR map")+ return map.entries.associate { (k, v) -> (k as Long) to v }+ }++ private fun readArg(minor: Int): Long = when (minor) {+ in 0..23 -> minor.toLong()+ 24 -> readByte().toLong() and 0xFF+ 25 -> readUInt(2)+ 26 -> readUInt(4)+ 27 -> readUInt(8)+ else -> error("Unsupported CBOR additional-info: $minor")+ }++ private fun readUInt(n: Int): Long {+ var value = 0L+ repeat(n) { value = (value shl 8) or (readByte().toLong() and 0xFF) }+ return value+ }++ private fun readByte(): Byte {+ if (pos >= bytes.size) error("Unexpected end of CBOR input")+ return bytes[pos++]+ }++ private fun readBytes(n: Int): ByteArray {+ if (pos + n > bytes.size) error("Unexpected end of CBOR input")+ return bytes.copyOfRange(pos, pos + n).also { pos += n }+ }++ private fun Long.toIntChecked(): Int {+ if (this < 0 || this > Int.MAX_VALUE) error("CBOR length out of range: $this")+ return toInt()+ }++ companion object {+ private const val MAJOR_UNSIGNED = 0+ private const val MAJOR_NEGATIVE = 1+ private const val MAJOR_BYTE_STRING = 2+ private const val MAJOR_TEXT_STRING = 3+ private const val MAJOR_ARRAY = 4+ private const val MAJOR_MAP = 5+ private const val MAJOR_SIMPLE = 7++ private const val SIMPLE_FALSE = 20+ private const val SIMPLE_TRUE = 21+ private const val SIMPLE_NULL = 22+ private const val SIMPLE_UNDEFINED = 23++ /** Decodes a single top-level CBOR value from [bytes]. */+ fun decode(bytes: ByteArray): Any? = CborReader(bytes).readValue()+ }+}
passwords/src/test/java/com/vayunmathur/passwords/platform/cable/CableEidTest.kt
diff --git a/passwords/src/test/java/com/vayunmathur/passwords/platform/cable/CableEidTest.kt b/passwords/src/test/java/com/vayunmathur/passwords/platform/cable/CableEidTest.ktnew file mode 100644index 0000000000..7e5f384150--- /dev/null+++ b/passwords/src/test/java/com/vayunmathur/passwords/platform/cable/CableEidTest.kt@@ -0,0 +1,58 @@+package com.vayunmathur.passwords.platform.cable++import kotlin.test.Test+import kotlin.test.assertContentEquals+import kotlin.test.assertEquals+import javax.crypto.Cipher+import javax.crypto.Mac+import javax.crypto.spec.SecretKeySpec++/** Tests for the caBLE EID construction + encryption ([CableEid]). */+class CableEidTest {++ @Test fun plaintextLayout() {+ val nonce = ByteArray(10) { (it + 1).toByte() }+ val routing = byteArrayOf(0xAA.toByte(), 0xBB.toByte(), 0xCC.toByte())+ val eid = CableEid.buildPlaintext(nonce, routing, domainId = 0x0102)++ assertEquals(CableEid.EID_SIZE, eid.size)+ assertEquals(0, eid[0].toInt())+ assertContentEquals(nonce, eid.copyOfRange(1, 11))+ assertContentEquals(routing, eid.copyOfRange(11, 14))+ assertEquals(0x02.toByte(), eid[14]) // low byte of domain, little-endian+ assertEquals(0x01.toByte(), eid[15]) // high byte+ }++ @Test fun encryptIsCorrectSizeAndDecryptable() {+ val eidKey = ByteArray(CableKeys.EID_KEY_SIZE) { it.toByte() }+ val plaintext = CableEid.buildPlaintext(+ nonce = ByteArray(10) { (it * 3).toByte() },+ routingId = byteArrayOf(1, 2, 3),+ domainId = 0,+ )+ val advert = CableEid.encrypt(plaintext, eidKey)+ assertEquals(CableEid.ADVERT_SIZE, advert.size)++ val ciphertext = advert.copyOfRange(0, CableEid.EID_SIZE)+ val tag = advert.copyOfRange(CableEid.EID_SIZE, CableEid.ADVERT_SIZE)++ // AES-256 single block decrypts back to the plaintext EID.+ val cipher = Cipher.getInstance("AES/ECB/NoPadding")+ cipher.init(Cipher.DECRYPT_MODE, SecretKeySpec(eidKey.copyOfRange(0, 32), "AES"))+ assertContentEquals(plaintext, cipher.doFinal(ciphertext))++ // HMAC tag verifies.+ val expectedTag = Mac.getInstance("HmacSHA256").run {+ init(SecretKeySpec(eidKey.copyOfRange(32, 64), "HmacSHA256"))+ doFinal(ciphertext)+ }.copyOfRange(0, CableEid.TAG_SIZE)+ assertContentEquals(expectedTag, tag)+ }++ @Test fun uuid16Expansion() {+ assertEquals(+ "0000fde2-0000-1000-8000-00805f9b34fb",+ CableAdvertiser.uuid16(0xFDE2).toString(),+ )+ }+}
passwords/src/test/java/com/vayunmathur/passwords/platform/cable/CableQrTest.kt
diff --git a/passwords/src/test/java/com/vayunmathur/passwords/platform/cable/CableQrTest.kt b/passwords/src/test/java/com/vayunmathur/passwords/platform/cable/CableQrTest.ktnew file mode 100644index 0000000000..b24ed0b2ce--- /dev/null+++ b/passwords/src/test/java/com/vayunmathur/passwords/platform/cable/CableQrTest.kt@@ -0,0 +1,95 @@+package com.vayunmathur.passwords.platform.cable++import com.vayunmathur.passwords.domain.Cbor+import kotlin.test.Test+import kotlin.test.assertContentEquals+import kotlin.test.assertEquals+import kotlin.test.assertNull++/** Tests for the caBLE QR digit codec, CBOR field parse, and HKDF derivations. */+class CableQrTest {++ // --- Digit encoding (reference impl mirroring Chromium, for round-trip testing) ---++ private val partialDigits = intArrayOf(0, 3, 5, 8, 10, 13, 15, 0)++ private fun digitEncode(bytes: ByteArray): String {+ val sb = StringBuilder()+ var i = 0+ while (bytes.size - i >= 7) {+ sb.append(readLe(bytes, i, 7).toString().padStart(17, '0'))+ i += 7+ }+ val rem = bytes.size - i+ if (rem > 0) sb.append(readLe(bytes, i, rem).toString().padStart(partialDigits[rem], '0'))+ return sb.toString()+ }++ private fun readLe(bytes: ByteArray, off: Int, n: Int): Long {+ var v = 0L+ for (j in n - 1 downTo 0) v = (v shl 8) or (bytes[off + j].toLong() and 0xFF)+ return v+ }++ @Test fun digitRoundTripAllRemainders() {+ for (len in 0..40) {+ val data = ByteArray(len) { ((it * 37 + 11) and 0xFF).toByte() }+ val encoded = digitEncode(data)+ assertContentEquals(data, CableQrData.digitDecode(encoded), "len=$len")+ }+ }++ /** Known-answer vector from Chromium v2_handshake_unittest.cc: {'a','b',0xFF} -> "16736865". */+ @Test fun digitKnownAnswerVector() {+ val bytes = byteArrayOf(0x61, 0x62, 0xFF.toByte())+ assertEquals("16736865", digitEncode(bytes))+ assertContentEquals(bytes, CableQrData.digitDecode("16736865"))+ }++ @Test fun parseFidoUri() {+ val peerKey = ByteArray(33) { (it + 1).toByte() }+ val secret = ByteArray(16) { (0xA0 + it).toByte() }+ val cbor = Cbor.encode(linkedMapOf<Any, Any>(+ 0L to peerKey,+ 1L to secret,+ 2L to 2L,+ 3L to 1_700_000_000L,+ 5L to "ga",+ ))+ val uri = CableQrData.URI_PREFIX + digitEncode(cbor)++ val qr = CableQrData.parse(uri)+ assertContentEquals(peerKey, qr.peerPublicKey)+ assertContentEquals(secret, qr.qrSecret)+ assertEquals(2, qr.numKnownDomains)+ assertEquals(1_700_000_000L, qr.timestampSeconds)+ assertEquals("ga", qr.requestTypeHint)+ assertNull(qr.supportsLinking)+ }++ // --- HKDF known-answer test: RFC 5869 Appendix A.1 (HMAC-SHA256) ---++ @Test fun hkdfRfc5869TestCase1() {+ val ikm = ByteArray(22) { 0x0b }+ val salt = ByteArray(13) { it.toByte() } // 0x00..0x0c+ val info = ByteArray(10) { (0xf0 + it).toByte() } // 0xf0..0xf9+ val expected = hex(+ "3cb25f25faacd57a90434f64d0362f2a" ++ "2d2d0a90cf1a5a4c5db02d56ecc4c5bf" ++ "34007208d5b887185865"+ )+ assertContentEquals(expected, CableKeys.hkdf(ikm, salt, info, 42))+ }++ @Test fun deriveInfoIsLittleEndianUint32() {+ assertContentEquals(byteArrayOf(3, 0, 0, 0), CableKeys.leUint32(CableKeys.Purpose.PSK.value))+ // Derived values are deterministic and length-correct.+ val secret = ByteArray(16) { it.toByte() }+ assertEquals(CableKeys.PSK_SIZE, CableKeys.psk(secret, ByteArray(16)).size)+ assertEquals(CableKeys.EID_KEY_SIZE, CableKeys.eidKey(secret).size)+ assertEquals(CableKeys.TUNNEL_ID_SIZE, CableKeys.tunnelId(secret).size)+ }++ private fun hex(s: String): ByteArray =+ s.chunked(2).map { it.toInt(16).toByte() }.toByteArray()+}
passwords/src/test/java/com/vayunmathur/passwords/platform/cable/CborTest.kt
diff --git a/passwords/src/test/java/com/vayunmathur/passwords/platform/cable/CborTest.kt b/passwords/src/test/java/com/vayunmathur/passwords/platform/cable/CborTest.ktnew file mode 100644index 0000000000..a4ba6ac6f7--- /dev/null+++ b/passwords/src/test/java/com/vayunmathur/passwords/platform/cable/CborTest.kt@@ -0,0 +1,129 @@+package com.vayunmathur.passwords.platform.cable++import com.vayunmathur.passwords.domain.Cbor+import kotlin.test.Test+import kotlin.test.assertContentEquals+import kotlin.test.assertEquals+import kotlin.test.assertNull+import kotlin.test.assertTrue++/** Round-trip tests for the CBOR encoder ([Cbor]) + decoder ([CborReader]) and the CTAP2 models. */+class CborTest {++ @Test fun unsignedInts() {+ for (v in listOf(0L, 1L, 23L, 24L, 255L, 256L, 65535L, 65536L, 1_000_000L)) {+ assertEquals(v, CborReader.decode(Cbor.encode(v)))+ }+ }++ @Test fun negativeInts() {+ for (v in listOf(-1L, -24L, -25L, -256L, -257L, -65536L)) {+ assertEquals(v, CborReader.decode(Cbor.encode(v)))+ }+ }++ @Test fun byteStringRoundTrip() {+ val data = byteArrayOf(1, 2, 3, 0, -1, 42)+ assertContentEquals(data, CborReader.decode(Cbor.encode(data)) as ByteArray)+ }++ @Test fun textStringRoundTrip() {+ val s = "example.com"+ assertEquals(s, CborReader.decode(Cbor.encode(s)))+ }++ @Test fun arrayRoundTrip() {+ val list = listOf(1L, "two", byteArrayOf(3))+ val decoded = CborReader.decode(Cbor.encode(list)) as List<*>+ assertEquals(1L, decoded[0])+ assertEquals("two", decoded[1])+ assertContentEquals(byteArrayOf(3), decoded[2] as ByteArray)+ }++ @Test fun mapRoundTrip() {+ val map = linkedMapOf<Any, Any>(1L to "a", 2L to 100L, 3L to byteArrayOf(9))+ val decoded = CborReader.decode(Cbor.encode(map)) as Map<*, *>+ assertEquals("a", decoded[1L])+ assertEquals(100L, decoded[2L])+ assertContentEquals(byteArrayOf(9), decoded[3L] as ByteArray)+ }++ @Test fun booleanValues() {+ assertEquals(true, CborReader.decode(Cbor.encode(true)))+ assertEquals(false, CborReader.decode(Cbor.encode(false)))+ // 0xf6 = null+ assertNull(CborReader.decode(byteArrayOf(0xF6.toByte())))+ }++ @Test fun coseKeyRoundTrip() {+ // Same shape produced by PasskeyAuthActivity when creating a credential.+ val x = ByteArray(32) { it.toByte() }+ val y = ByteArray(32) { (it + 32).toByte() }+ val cose = linkedMapOf<Any, Any>(1L to 2L, 3L to -7L, -1L to 1L, -2L to x, -3L to y)+ val decoded = CborReader.decode(Cbor.encode(cose)) as Map<*, *>+ assertEquals(2L, decoded[1L])+ assertEquals(-7L, decoded[3L])+ assertEquals(1L, decoded[-1L])+ assertContentEquals(x, decoded[-2L] as ByteArray)+ assertContentEquals(y, decoded[-3L] as ByteArray)+ }++ @Test fun getAssertionRequestParse() {+ val clientDataHash = ByteArray(32) { it.toByte() }+ val credId = byteArrayOf(10, 20, 30)+ val payload = Cbor.encode(linkedMapOf<Any, Any>(+ 1L to "example.com",+ 2L to clientDataHash,+ 3L to listOf(linkedMapOf<Any, Any>("type" to "public-key", "id" to credId)),+ 5L to linkedMapOf<Any, Any>("up" to true, "uv" to true),+ ))++ val req = CtapGetAssertionRequest.parse(payload)+ assertEquals("example.com", req.rpId)+ assertContentEquals(clientDataHash, req.clientDataHash)+ assertEquals(1, req.allowList.size)+ assertContentEquals(credId, req.allowList[0].id)+ assertTrue(req.userPresenceRequired)+ assertTrue(req.userVerificationRequired)+ }++ @Test fun getAssertionRequestDefaults() {+ val payload = Cbor.encode(linkedMapOf<Any, Any>(+ 1L to "site.test",+ 2L to ByteArray(32),+ ))+ val req = CtapGetAssertionRequest.parse(payload)+ assertTrue(req.allowList.isEmpty())+ assertTrue(req.userPresenceRequired) // up defaults to true+ assertTrue(!req.userVerificationRequired) // uv defaults to false+ }++ @Test fun getAssertionResponseEncodeDecode() {+ val resp = CtapGetAssertionResponse(+ credentialId = byteArrayOf(1, 2, 3),+ authData = ByteArray(37) { it.toByte() },+ signature = byteArrayOf(9, 8, 7),+ userId = byteArrayOf(4, 5, 6),+ userName = "alice",+ )+ val decoded = CborReader.decode(resp.encode()) as Map<*, *>+ val cred = decoded[1L] as Map<*, *>+ assertEquals("public-key", cred["type"])+ assertContentEquals(byteArrayOf(1, 2, 3), cred["id"] as ByteArray)+ assertContentEquals(resp.authData, decoded[2L] as ByteArray)+ assertContentEquals(byteArrayOf(9, 8, 7), decoded[3L] as ByteArray)+ val user = decoded[4L] as Map<*, *>+ assertContentEquals(byteArrayOf(4, 5, 6), user["id"] as ByteArray)+ assertEquals("alice", user["name"])+ }++ @Test fun getInfoEncode() {+ val aaguid = ByteArray(16) { it.toByte() }+ val decoded = CborReader.decode(CtapGetInfoResponse(aaguid = aaguid).encode()) as Map<*, *>+ val versions = decoded[1L] as List<*>+ assertTrue(versions.contains("FIDO_2_0"))+ assertContentEquals(aaguid, decoded[3L] as ByteArray)+ val options = decoded[4L] as Map<*, *>+ assertEquals(true, options["rk"])+ }+}
passwords/src/test/java/com/vayunmathur/passwords/platform/cable/CryptoParityTest.kt
diff --git a/passwords/src/test/java/com/vayunmathur/passwords/platform/cable/CryptoParityTest.kt b/passwords/src/test/java/com/vayunmathur/passwords/platform/cable/CryptoParityTest.ktnew file mode 100644index 0000000000..878fa88084--- /dev/null+++ b/passwords/src/test/java/com/vayunmathur/passwords/platform/cable/CryptoParityTest.kt@@ -0,0 +1,159 @@+package com.vayunmathur.passwords.platform.cable++import kotlin.test.Test+import kotlin.test.assertContentEquals+import kotlin.test.assertEquals+import kotlin.test.assertTrue+import java.math.BigInteger+import java.security.interfaces.ECPublicKey++/**+ * Known-answer tests for the platform-crypto (Conscrypt/SunEC) implementations behind the+ * caBLE handshake.+ *+ * These used to compare against Bouncy Castle as a live oracle; they now pin the same+ * behaviour to published constants instead — RFC 5869 Appendix A for HKDF-SHA256, and the+ * NIST P-256 domain parameters for point decompression — so the crypto is checked against+ * the standard rather than against another implementation, with no extra dependency.+ */+class CryptoParityTest {++ private fun hex(s: String): ByteArray {+ require(s.length % 2 == 0)+ return ByteArray(s.length / 2) { s.substring(it * 2, it * 2 + 2).toInt(16).toByte() }+ }++ // ---------------------------------------------------------------------+ // HKDF-SHA256 — RFC 5869 Appendix A test vectors+ // ---------------------------------------------------------------------++ @Test+ fun hkdf_matches_rfc5869_basic_vector() {+ // A.1: IKM 22x0b, 13-byte salt, 10-byte info, L = 42.+ assertContentEquals(+ hex("3cb25f25faacd57a90434f64d0362f2a2d2d0a90cf1a5a4c5db02d56ecc4c5bf" ++ "34007208d5b887185865"),+ CableKeys.hkdf(+ ikm = ByteArray(22) { 0x0b },+ salt = ByteArray(13) { it.toByte() },+ info = ByteArray(10) { (0xf0 + it).toByte() },+ length = 42,+ ),+ )+ }++ @Test+ fun hkdf_matches_rfc5869_long_input_vector() {+ // A.2: 80-byte IKM, 80-byte salt, 80-byte info, L = 82 — spans several expand rounds.+ assertContentEquals(+ hex("b11e398dc80327a1c8e7f78c596a49344f012eda2d4efad8a050cc4c19afa97c" ++ "59045a99cac7827271cb41c65e590e09da3275600c2f09b8367793a9aca3db71" ++ "cc30c58179ec3e87c14c01d5c1f3434f1d87"),+ CableKeys.hkdf(+ ikm = ByteArray(0x50) { it.toByte() },+ salt = ByteArray(0x50) { (0x60 + it).toByte() },+ info = ByteArray(0x50) { (0xb0 + it).toByte() },+ length = 82,+ ),+ )+ }++ @Test+ fun hkdf_matches_rfc5869_empty_salt_vector() {+ // A.3: zero-length salt and info — the shape caBLE uses for the QR-derived keys.+ val expected = hex(+ "8da4e775a563c18f715f802a063c5a31b8a11f5c5ee1879ec3454e5f3c738d2d9d201395faa4b61a96c8"+ )+ val ikm = ByteArray(22) { 0x0b }+ assertContentEquals(expected, CableKeys.hkdf(ikm, ByteArray(0), ByteArray(0), 42))+ // A null salt must be treated as the RFC's zero salt, identically to an empty one+ // (BoringSSL parity — Chromium relies on this for the QR secret).+ assertContentEquals(expected, CableKeys.hkdf(ikm, null, ByteArray(0), 42))+ }++ @Test+ fun hkdf_output_lengths_are_prefixes_of_each_other() {+ // Expand is a counter-mode stream: a shorter request must be a prefix of a longer one.+ val ikm = ByteArray(16) { it.toByte() }+ val info = "test-info".toByteArray()+ for (salt in listOf<ByteArray?>(null, ByteArray(0), "some-salt".toByteArray())) {+ val full = CableKeys.hkdf(ikm, salt, info, 100)+ for (len in intArrayOf(10, 16, 32, 64, 100)) {+ assertContentEquals(+ full.copyOf(len),+ CableKeys.hkdf(ikm, salt, info, len),+ "salt=${salt?.size} len=$len",+ )+ }+ }+ }++ // ---------------------------------------------------------------------+ // P-256 point encoding — NIST domain parameters+ // ---------------------------------------------------------------------++ private val p = BigInteger(+ "ffffffff00000001000000000000000000000000ffffffffffffffffffffffff", 16+ )+ private val curveB = BigInteger(+ "5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b", 16+ )++ /** y² == x³ - 3x + b (mod p) */+ private fun onCurve(x: BigInteger, y: BigInteger): Boolean =+ y.multiply(y).subtract(+ x.multiply(x).multiply(x).subtract(x.multiply(BigInteger.valueOf(3))).add(curveB)+ ).mod(p).signum() == 0++ @Test+ fun p256_decompresses_the_standard_base_point() {+ // The secp256r1 generator, as published in SEC 2 / FIPS 186-4.+ val gx = BigInteger(+ "6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296", 16+ )+ val gy = BigInteger(+ "4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5", 16+ )+ // Gy is odd, so the compressed form carries the 0x03 prefix.+ val compressed = hex(+ "036b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296"+ )+ val decoded = P256.decodePoint(compressed) as ECPublicKey+ assertEquals(gx, decoded.w.affineX)+ assertEquals(gy, decoded.w.affineY)+ }++ @Test+ fun p256_compressed_decode_round_trips_and_stays_on_curve() {+ repeat(20) {+ val kp = P256.generateKeyPair()+ val original = kp.public as ECPublicKey++ val fromCompressed = P256.decodePoint(P256.toCompressed(kp.public)) as ECPublicKey+ assertEquals(original.w.affineX, fromCompressed.w.affineX)+ assertEquals(original.w.affineY, fromCompressed.w.affineY)++ val fromUncompressed = P256.decodePoint(P256.toUncompressed(kp.public)) as ECPublicKey+ assertEquals(original.w.affineX, fromUncompressed.w.affineX)+ assertEquals(original.w.affineY, fromUncompressed.w.affineY)++ assertTrue(+ fromCompressed.w.affineX.let { _ -> onCurve(fromCompressed.w.affineX, fromCompressed.w.affineY) },+ "decompressed point off curve",+ )+ // The recovered Y's parity must match the prefix that was encoded.+ val prefix = P256.toCompressed(kp.public)[0].toInt() and 0xff+ assertEquals(prefix == 0x03, fromCompressed.w.affineY.testBit(0))+ }+ }++ @Test+ fun p256_ecdh_is_symmetric() {+ val a = P256.generateKeyPair()+ val b = P256.generateKeyPair()+ val ab = P256.ecdh(a.private, P256.decodePoint(P256.toUncompressed(b.public)))+ val ba = P256.ecdh(b.private, P256.decodePoint(P256.toUncompressed(a.public)))+ assertContentEquals(ab, ba)+ assertEquals(P256.DH_OUTPUT_SIZE, ab.size)+ }+}
passwords/src/test/java/com/vayunmathur/passwords/platform/cable/CtapProcessorTest.kt
diff --git a/passwords/src/test/java/com/vayunmathur/passwords/platform/cable/CtapProcessorTest.kt b/passwords/src/test/java/com/vayunmathur/passwords/platform/cable/CtapProcessorTest.ktnew file mode 100644index 0000000000..e97767be0f--- /dev/null+++ b/passwords/src/test/java/com/vayunmathur/passwords/platform/cable/CtapProcessorTest.kt@@ -0,0 +1,114 @@+package com.vayunmathur.passwords.platform.cable++import com.vayunmathur.passwords.data.Passkey+import com.vayunmathur.passwords.data.PasskeyDao+import com.vayunmathur.passwords.domain.Cbor+import kotlinx.coroutines.flow.Flow+import kotlinx.coroutines.flow.flowOf+import kotlinx.coroutines.runBlocking+import kotlin.test.Test+import kotlin.test.assertContentEquals+import kotlin.test.assertEquals+import kotlin.test.assertTrue+import java.security.KeyPairGenerator+import java.security.MessageDigest+import java.security.Signature+import java.security.spec.ECGenParameterSpec+import kotlin.io.encoding.Base64+import kotlin.io.encoding.ExperimentalEncodingApi++/**+ * End-to-end test of the caBLE getAssertion path (Phases 0/1/8): a real P-256 passkey is stored,+ * a CTAP getAssertion is processed, and the returned assertion signature is verified against the+ * stored public key. Proves the cross-device signer matches WebAuthn assertion semantics.+ */+@OptIn(ExperimentalEncodingApi::class)+class CtapProcessorTest {++ private val urlEncoder = Base64.UrlSafe.withPadding(Base64.PaddingOption.ABSENT)++ private class FakePasskeyDao(initial: List<Passkey>) : PasskeyDao() {+ val store = initial.toMutableList()+ override fun getAllFlow(): Flow<List<Passkey>> = flowOf(store.toList())+ override suspend fun getAll(): List<Passkey> = store.toList()+ override suspend fun getByRpId(rpId: String): List<Passkey> = store.filter { it.rpId == rpId }+ override suspend fun getByCredentialId(credentialId: String): Passkey? =+ store.firstOrNull { it.credentialId == credentialId }+ override suspend fun upsertRaw(passkey: Passkey): Long {+ store.removeAll { it.id == passkey.id }+ store.add(passkey)+ return passkey.id+ }+ override suspend fun delete(passkey: Passkey): Int {+ return if (store.removeAll { it.id == passkey.id }) 1 else 0+ }+ }++ @Test fun getAssertionProducesVerifiableSignature() = runBlocking {+ val kp = KeyPairGenerator.getInstance("EC").apply {+ initialize(ECGenParameterSpec("secp256r1"))+ }.generateKeyPair()++ val credIdBytes = ByteArray(16) { it.toByte() }+ val userIdBytes = byteArrayOf(9, 8, 7, 6)+ val passkey = Passkey(+ id = 1,+ rpId = "example.com",+ credentialId = urlEncoder.encode(credIdBytes),+ userId = urlEncoder.encode(userIdBytes),+ privateKeyBytes = kp.private.encoded,+ signCount = 5,+ )+ val dao = FakePasskeyDao(listOf(passkey))+ val processor = CtapProcessor(dao, userVerified = true)++ val clientDataHash = MessageDigest.getInstance("SHA-256").digest("hello".toByteArray())+ val request = Cbor.encode(linkedMapOf<Any, Any>(+ 1L to "example.com",+ 2L to clientDataHash,+ 5L to linkedMapOf<Any, Any>("up" to true, "uv" to true),+ ))+ val response = processor.process(byteArrayOf(Ctap.CMD_GET_ASSERTION.toByte()) + request)++ assertEquals(Ctap.OK.toByte(), response[0])+ val map = CborReader.decode(response.copyOfRange(1, response.size)) as Map<*, *>++ val cred = map[1L] as Map<*, *>+ assertContentEquals(credIdBytes, cred["id"] as ByteArray)+ val authData = map[2L] as ByteArray+ val signature = map[3L] as ByteArray+ val user = map[4L] as Map<*, *>+ assertContentEquals(userIdBytes, user["id"] as ByteArray)++ // The signature must verify over authData || clientDataHash against the stored public key.+ val verifier = Signature.getInstance("SHA256withECDSA").apply {+ initVerify(kp.public)+ update(authData)+ update(clientDataHash)+ }+ assertTrue(verifier.verify(signature), "assertion signature must verify")++ // signCount was bumped and persisted.+ assertEquals(6, dao.getByCredentialId(passkey.credentialId)!!.signCount)+ }++ @Test fun getAssertionNoCredentialReturnsError() = runBlocking {+ val dao = FakePasskeyDao(emptyList())+ val processor = CtapProcessor(dao, userVerified = true)+ val request = Cbor.encode(linkedMapOf<Any, Any>(1L to "nobody.example", 2L to ByteArray(32)))+ val response = processor.process(byteArrayOf(Ctap.CMD_GET_ASSERTION.toByte()) + request)+ assertEquals(Ctap.ERR_NO_CREDENTIALS.toByte(), response[0])+ }++ @Test fun getInfoReturnsZeroAaguidAndTransports() = runBlocking {+ val dao = FakePasskeyDao(emptyList())+ val processor = CtapProcessor(dao, userVerified = false)+ val response = processor.process(byteArrayOf(Ctap.CMD_GET_INFO.toByte()))+ assertEquals(Ctap.OK.toByte(), response[0])+ val map = CborReader.decode(response.copyOfRange(1, response.size)) as Map<*, *>+ assertContentEquals(ByteArray(16), map[3L] as ByteArray) // all-zero AAGUID+ assertEquals(listOf("cable", "hybrid", "internal"), map[9L]) // transports at key 9+ val options = map[4L] as Map<*, *>+ assertEquals(true, options["uv"])+ }+}
passwords/src/test/java/com/vayunmathur/passwords/platform/cable/NoiseTest.kt
diff --git a/passwords/src/test/java/com/vayunmathur/passwords/platform/cable/NoiseTest.kt b/passwords/src/test/java/com/vayunmathur/passwords/platform/cable/NoiseTest.ktnew file mode 100644index 0000000000..3214ebbe24--- /dev/null+++ b/passwords/src/test/java/com/vayunmathur/passwords/platform/cable/NoiseTest.kt@@ -0,0 +1,150 @@+package com.vayunmathur.passwords.platform.cable++import kotlin.test.Test+import kotlin.test.assertContentEquals+import kotlin.test.assertEquals+import java.security.KeyPair+import java.security.MessageDigest+import javax.crypto.Cipher+import javax.crypto.Mac+import javax.crypto.spec.GCMParameterSpec+import javax.crypto.spec.SecretKeySpec++/**+ * Handshake tests for [NoiseResponder] + [P256] + [Crypter]. The in-test initiator mirrors+ * Chromium `HandshakeInitiator` (KNpsk0 / QR variant) from `//device/fido/cable/v2_handshake.cc`,+ * so a successful handshake + transport round-trip exercises the exact protocol Chromium speaks.+ */+class NoiseTest {++ @Test fun p256CompressDecompressRoundTrip() {+ val kp = P256.generateKeyPair()+ val compressed = P256.toCompressed(kp.public)+ assertEquals(P256.COMPRESSED_SIZE, compressed.size)+ assertContentEquals(P256.toUncompressed(kp.public), P256.toUncompressed(P256.decodePoint(compressed)))+ }++ @Test fun p256EcdhIsSymmetric() {+ val a = P256.generateKeyPair()+ val b = P256.generateKeyPair()+ assertContentEquals(P256.ecdh(a.private, b.public), P256.ecdh(b.private, a.public))+ }++ @Test fun crypterRoundTripAndPadding() {+ val readKey = ByteArray(32) { it.toByte() }+ val writeKey = ByteArray(32) { (it + 1).toByte() }+ // A pair of counterpart Crypters (keys swapped) model the two ends.+ val a = Crypter(readKey, writeKey)+ val b = Crypter(writeKey, readKey)+ for (i in 0 until 4) {+ val msg = "msg-$i".toByteArray()+ assertContentEquals(msg, b.decrypt(a.encrypt(msg)))+ assertContentEquals(msg, a.decrypt(b.encrypt(msg)))+ }+ }++ @Test fun padUnpadRoundTrip() {+ for (len in 0..40) {+ val msg = ByteArray(len) { it.toByte() }+ val padded = Crypter.pad(msg)+ assertEquals(0, padded.size % 32)+ assertContentEquals(msg, Crypter.unpad(padded))+ }+ }++ @Test fun fullHandshakeAndTransport() {+ val initiatorStatic = P256.generateKeyPair()+ val qrPeerKey = P256.decodePoint(P256.toCompressed(initiatorStatic.public))+ val psk = ByteArray(32) { (it * 7 + 1).toByte() }++ val responder = NoiseResponder(qrPeerKey, psk)+ val initiator = TestInitiator(initiatorStatic, psk)++ responder.readMessage1(initiator.buildInitialMessage())+ val (msg2, respCrypter) = responder.writeMessage2()+ val initCrypter = initiator.processResponse(msg2)++ // initiator -> responder+ val req = "ctap request".toByteArray()+ assertContentEquals(req, respCrypter.decrypt(initCrypter.encrypt(req)))+ // responder -> initiator+ val resp = "ctap response".toByteArray()+ assertContentEquals(resp, initCrypter.decrypt(respCrypter.encrypt(resp)))+ }++ /** KNpsk0 initiator mirroring Chromium HandshakeInitiator (QR variant). */+ private class TestInitiator(private val staticKey: KeyPair, psk: ByteArray) {+ private var ck: ByteArray+ private var h: ByteArray+ private var key: ByteArray? = null+ private var nonce = 0+ private val ephemeral = P256.generateKeyPair()++ init {+ val name = NoiseResponder.PROTOCOL_NAME.toByteArray(Charsets.US_ASCII)+ h = name + ByteArray(32 - name.size)+ ck = h.copyOf()+ mixHash(byteArrayOf(1)) // prologue+ mixHash(P256.toUncompressed(staticKey.public)) // MixHashPoint(local identity)+ mixKeyAndHash(psk)+ }++ fun buildInitialMessage(): ByteArray {+ val ePub = P256.toUncompressed(ephemeral.public)+ mixHash(ePub); mixKey(ePub)+ // peer_identity_ is null for the QR initiator, so no `es` here.+ return ePub + encryptAndHash(ByteArray(0))+ }++ fun processResponse(message: ByteArray): Crypter {+ val peerPub = message.copyOfRange(0, P256.UNCOMPRESSED_SIZE)+ val peer = P256.decodePoint(peerPub)+ mixHash(peerPub); mixKey(peerPub)+ mixKey(P256.ecdh(ephemeral.private, peer)) // ee+ mixKey(P256.ecdh(staticKey.private, peer)) // se+ val payload = decryptAndHash(message.copyOfRange(P256.UNCOMPRESSED_SIZE, message.size))+ require(payload.isEmpty())+ val (writeKey, readKey) = hkdf2(ck, ByteArray(0)) // note: initiator swaps+ return Crypter(readKey, writeKey)+ }++ private fun mixHash(data: ByteArray) { h = sha256(h + data) }+ private fun mixKey(ikm: ByteArray) { val (c, k) = hkdf2(ck, ikm); ck = c; key = k; nonce = 0 }+ private fun mixKeyAndHash(ikm: ByteArray) {+ val (c, hh, k) = hkdf3(ck, ikm); ck = c; mixHash(hh); key = k; nonce = 0+ }+ private fun encryptAndHash(pt: ByteArray): ByteArray {+ val k = key ?: return pt.also { mixHash(it) }+ return aead(Cipher.ENCRYPT_MODE, k, pt).also { mixHash(it) }+ }+ private fun decryptAndHash(ct: ByteArray): ByteArray {+ val k = key ?: return ct.also { mixHash(it) }+ return aead(Cipher.DECRYPT_MODE, k, ct).also { mixHash(ct) }+ }+ private fun aead(mode: Int, k: ByteArray, input: ByteArray): ByteArray {+ val n = ByteArray(12)+ n[0] = ((nonce ushr 24) and 0xFF).toByte(); n[1] = ((nonce ushr 16) and 0xFF).toByte()+ n[2] = ((nonce ushr 8) and 0xFF).toByte(); n[3] = (nonce and 0xFF).toByte()+ nonce+++ return Cipher.getInstance("AES/GCM/NoPadding").run {+ init(mode, SecretKeySpec(k, "AES"), GCMParameterSpec(128, n)); updateAAD(h); doFinal(input)+ }+ }+ }++ companion object {+ private fun sha256(d: ByteArray) = MessageDigest.getInstance("SHA-256").digest(d)+ private fun hmac(key: ByteArray, d: ByteArray) = Mac.getInstance("HmacSHA256").run {+ init(SecretKeySpec(key, "HmacSHA256")); doFinal(d)+ }+ private fun hkdf2(ck: ByteArray, ikm: ByteArray): Pair<ByteArray, ByteArray> {+ val tk = hmac(ck, ikm); val o1 = hmac(tk, byteArrayOf(1)); val o2 = hmac(tk, o1 + 2)+ return o1 to o2+ }+ private fun hkdf3(ck: ByteArray, ikm: ByteArray): Triple<ByteArray, ByteArray, ByteArray> {+ val tk = hmac(ck, ikm); val o1 = hmac(tk, byteArrayOf(1))+ val o2 = hmac(tk, o1 + 2); val o3 = hmac(tk, o2 + 3)+ return Triple(o1, o2, o3)+ }+ }+}
passwords/src/test/java/com/vayunmathur/passwords/platform/cable/TunnelDomainsTest.kt
diff --git a/passwords/src/test/java/com/vayunmathur/passwords/platform/cable/TunnelDomainsTest.kt b/passwords/src/test/java/com/vayunmathur/passwords/platform/cable/TunnelDomainsTest.ktnew file mode 100644index 0000000000..3a84e353f5--- /dev/null+++ b/passwords/src/test/java/com/vayunmathur/passwords/platform/cable/TunnelDomainsTest.kt@@ -0,0 +1,34 @@+package com.vayunmathur.passwords.platform.cable++import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFailsWith+import kotlin.test.assertTrue++/** Tests for the assigned tunnel-domain table (the verifiable part of [TunnelDomains]). */+class TunnelDomainsTest {++ @Test fun assignedDomains() {+ assertEquals("cable.ua5v.com", TunnelDomains.decode(0))+ assertEquals("cable.auth.com", TunnelDomains.decode(1))+ assertEquals(0, TunnelDomains.DEFAULT_ID)+ }++ @Test fun unknownAssignedIdThrows() {+ assertFailsWith<IllegalArgumentException> {+ TunnelDomains.decode(2)+ }+ }++ @Test fun hexRoundTrip() {+ val bytes = byteArrayOf(0x00, 0x1f, 0x7a.toByte(), 0xff.toByte())+ assertEquals("001f7aff", CableTunnel.hex(bytes))+ }++ @Test fun algorithmicDomainIsDeterministic() {+ val a = TunnelDomains.decode(300)+ val b = TunnelDomains.decode(300)+ assertEquals(a, b)+ assertTrue(a.startsWith("cable."))+ }+}
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 83ce837afc..b1862b14fa 100644--- a/vpn/src/main/java/com/vayunmathur/vpn/MainActivity.kt+++ b/vpn/src/main/java/com/vayunmathur/vpn/MainActivity.kt@@ -3,43 +3,24 @@ package com.vayunmathur.vpn import android.content.Intent import android.os.Bundle import androidx.activity.ComponentActivity-import androidx.activity.compose.LocalActivity import androidx.activity.compose.setContent import androidx.activity.enableEdgeToEdge import androidx.activity.viewModels-import androidx.compose.foundation.pager.rememberPagerState-import androidx.compose.runtime.Composable import androidx.compose.runtime.mutableStateOf import androidx.lifecycle.lifecycleScope-import com.vayunmathur.library.ui.DynamicTheme-import com.vayunmathur.library.util.OfflineAware-import com.vayunmathur.library.ui.IconDashboard-import com.vayunmathur.library.ui.IconHistory-import com.vayunmathur.library.ui.IconSettings-import com.vayunmathur.library.ui.PagerTab-import com.vayunmathur.library.ui.TabStyle-import com.vayunmathur.library.ui.TabbedPagerScaffold-import com.vayunmathur.library.util.MainNavigation import com.vayunmathur.library.network.NetworkClient import com.vayunmathur.library.network.TrustBundle-import com.vayunmathur.library.util.NavBackStack-import com.vayunmathur.library.util.NavKey-import com.vayunmathur.library.util.rememberNavBackStack+import com.vayunmathur.library.ui.DynamicTheme+import com.vayunmathur.library.util.OfflineAware import com.vayunmathur.vpn.data.ConnectionLogDao import com.vayunmathur.vpn.data.VpnConfigDao import com.vayunmathur.vpn.data.VpnDatabase-import com.vayunmathur.vpn.ui.BypassListPage-import com.vayunmathur.vpn.ui.ConfigDetailPage-import com.vayunmathur.vpn.ui.ConfigListPage-import com.vayunmathur.vpn.ui.LoggingPage-import com.vayunmathur.vpn.ui.SettingsPage+import com.vayunmathur.vpn.platform.VpnViewModel+import com.vayunmathur.vpn.platform.VpnViewModelFactory import com.vayunmathur.vpn.util.VpnNative-import com.vayunmathur.vpn.util.VpnViewModel-import com.vayunmathur.vpn.util.VpnViewModelFactory import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import kotlinx.coroutines.withContext-import kotlinx.serialization.Serializable class MainActivity : ComponentActivity() { private lateinit var configDao: VpnConfigDao@@ -89,46 +70,3 @@ class MainActivity : ComponentActivity() { } } }--@Serializable-sealed interface Route : NavKey {- @Serializable- data class Main(val initialTab: Int = 0) : Route- @Serializable- data class Detail(val id: Long) : Route- @Serializable- data object BypassList : Route-}--private const val TAB_TUNNELS = 0-private const val TAB_LOGGING = 1-private const val TAB_SETTINGS = 2--@Composable-fun Navigation(vm: VpnViewModel) {- // Land on the Settings tab when opened from the system App Info page.- val activity = LocalActivity.current- val startTab = if (activity?.intent?.action == Intent.ACTION_APPLICATION_PREFERENCES) {- TAB_SETTINGS- } else {- TAB_TUNNELS- }- val backStack = rememberNavBackStack<Route>(Route.Main(startTab))- MainNavigation(backStack) {- entry<Route.Main> { VpnTabs(backStack, vm, it.initialTab) }- entry<Route.Detail> { ConfigDetailPage(backStack, vm, it.id) }- entry<Route.BypassList> { BypassListPage(backStack) }- }-}--/** The three top-level tabs, hosted in a swipeable pager. Detail and BypassList push on top. */-@Composable-private fun VpnTabs(backStack: NavBackStack<Route>, vm: VpnViewModel, initialTab: Int) {- val pagerState = rememberPagerState(initialPage = initialTab, pageCount = { 3 })- val tabs = listOf(- PagerTab("Tunnels", { IconDashboard() }) { ConfigListPage(backStack, vm) },- PagerTab("Logging", { IconHistory() }) { LoggingPage(backStack, vm) },- PagerTab("Settings", { IconSettings() }) { SettingsPage(backStack, vm) },- )- TabbedPagerScaffold(tabs = tabs, pagerState = pagerState, tabStyle = TabStyle.BottomNav)-}
vpn/src/main/java/com/vayunmathur/vpn/Navigation.kt
diff --git a/vpn/src/main/java/com/vayunmathur/vpn/Navigation.kt b/vpn/src/main/java/com/vayunmathur/vpn/Navigation.ktnew file mode 100644index 0000000000..104499470b--- /dev/null+++ b/vpn/src/main/java/com/vayunmathur/vpn/Navigation.kt@@ -0,0 +1,54 @@+package com.vayunmathur.vpn++import android.content.Intent+import androidx.activity.compose.LocalActivity+import androidx.compose.foundation.pager.rememberPagerState+import androidx.compose.runtime.Composable+import com.vayunmathur.library.ui.IconDashboard+import com.vayunmathur.library.ui.IconHistory+import com.vayunmathur.library.ui.IconSettings+import com.vayunmathur.library.ui.PagerTab+import com.vayunmathur.library.ui.TabStyle+import com.vayunmathur.library.ui.TabbedPagerScaffold+import com.vayunmathur.library.util.MainNavigation+import com.vayunmathur.library.util.NavBackStack+import com.vayunmathur.library.util.rememberNavBackStack+import com.vayunmathur.vpn.platform.VpnViewModel+import com.vayunmathur.vpn.ui.BypassListPage+import com.vayunmathur.vpn.ui.ConfigDetailPage+import com.vayunmathur.vpn.ui.ConfigListPage+import com.vayunmathur.vpn.ui.LoggingPage+import com.vayunmathur.vpn.ui.SettingsPage++private const val TAB_TUNNELS = 0+private const val TAB_LOGGING = 1+private const val TAB_SETTINGS = 2++@Composable+fun Navigation(vm: VpnViewModel) {+ // Land on the Settings tab when opened from the system App Info page.+ val activity = LocalActivity.current+ val startTab = if (activity?.intent?.action == Intent.ACTION_APPLICATION_PREFERENCES) {+ TAB_SETTINGS+ } else {+ TAB_TUNNELS+ }+ val backStack = rememberNavBackStack<Route>(Route.Main(startTab))+ MainNavigation(backStack) {+ entry<Route.Main> { VpnTabs(backStack, vm, it.initialTab) }+ entry<Route.Detail> { ConfigDetailPage(backStack, vm, it.id) }+ entry<Route.BypassList> { BypassListPage(backStack) }+ }+}++/** The three top-level tabs, hosted in a swipeable pager. Detail and BypassList push on top. */+@Composable+private fun VpnTabs(backStack: NavBackStack<Route>, vm: VpnViewModel, initialTab: Int) {+ val pagerState = rememberPagerState(initialPage = initialTab, pageCount = { 3 })+ val tabs = listOf(+ PagerTab("Tunnels", { IconDashboard() }) { ConfigListPage(backStack, vm) },+ PagerTab("Logging", { IconHistory() }) { LoggingPage(backStack, vm) },+ PagerTab("Settings", { IconSettings() }) { SettingsPage(backStack, vm) },+ )+ TabbedPagerScaffold(tabs = tabs, pagerState = pagerState, tabStyle = TabStyle.BottomNav)+}
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.ktnew file mode 100644index 0000000000..11f2a14606--- /dev/null+++ b/vpn/src/main/java/com/vayunmathur/vpn/Route.kt@@ -0,0 +1,16 @@+package com.vayunmathur.vpn++import com.vayunmathur.library.util.NavKey+import kotlinx.serialization.Serializable++@Serializable+sealed interface Route : NavKey {+ @Serializable+ data class Main(val initialTab: Int = 0) : Route++ @Serializable+ data class Detail(val id: Long) : Route++ @Serializable+ data object BypassList : Route+}
vpn/src/main/java/com/vayunmathur/vpn/platform/BypassList.kt
diff --git a/vpn/src/main/java/com/vayunmathur/vpn/util/BypassList.kt b/vpn/src/main/java/com/vayunmathur/vpn/platform/BypassList.ktsimilarity index 97%rename from vpn/src/main/java/com/vayunmathur/vpn/util/BypassList.ktrename to vpn/src/main/java/com/vayunmathur/vpn/platform/BypassList.ktindex d4efe59766..bc5de76234 100644--- a/vpn/src/main/java/com/vayunmathur/vpn/util/BypassList.kt+++ b/vpn/src/main/java/com/vayunmathur/vpn/platform/BypassList.kt@@ -1,4 +1,4 @@-package com.vayunmathur.vpn.util+package com.vayunmathur.vpn.platform import android.content.Context import com.vayunmathur.library.util.DataStoreUtils
vpn/src/main/java/com/vayunmathur/vpn/platform/VpnViewModel.kt
diff --git a/vpn/src/main/java/com/vayunmathur/vpn/util/VpnViewModel.kt b/vpn/src/main/java/com/vayunmathur/vpn/platform/VpnViewModel.ktsimilarity index 99%rename from vpn/src/main/java/com/vayunmathur/vpn/util/VpnViewModel.ktrename to vpn/src/main/java/com/vayunmathur/vpn/platform/VpnViewModel.ktindex f879ce3b44..236a106dd5 100644--- a/vpn/src/main/java/com/vayunmathur/vpn/util/VpnViewModel.kt+++ b/vpn/src/main/java/com/vayunmathur/vpn/platform/VpnViewModel.kt@@ -1,4 +1,4 @@-package com.vayunmathur.vpn.util+package com.vayunmathur.vpn.platform import android.app.Activity import android.app.Application@@ -26,6 +26,7 @@ import com.vayunmathur.vpn.data.toModel import com.vayunmathur.vpn.service.AppResolver import com.vayunmathur.vpn.service.ConnectionTracker import com.vayunmathur.vpn.service.VpnTunnelService+import com.vayunmathur.vpn.util.VpnNative import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.delay import kotlinx.coroutines.flow.MutableStateFlow
vpn/src/main/java/com/vayunmathur/vpn/service/VpnTunnelService.kt
diff --git a/vpn/src/main/java/com/vayunmathur/vpn/service/VpnTunnelService.kt b/vpn/src/main/java/com/vayunmathur/vpn/service/VpnTunnelService.ktindex c4aaf7c61b..0e6b45db66 100644--- a/vpn/src/main/java/com/vayunmathur/vpn/service/VpnTunnelService.kt+++ b/vpn/src/main/java/com/vayunmathur/vpn/service/VpnTunnelService.kt@@ -20,7 +20,7 @@ import com.vayunmathur.vpn.data.VpnDatabase import com.vayunmathur.vpn.data.endpointHost import com.vayunmathur.vpn.data.endpointPort import com.vayunmathur.vpn.data.toModel-import com.vayunmathur.vpn.util.BypassList+import com.vayunmathur.vpn.platform.BypassList import com.vayunmathur.vpn.util.VpnNative import java.io.FileInputStream import java.io.FileOutputStream
vpn/src/main/java/com/vayunmathur/vpn/ui/BypassListPage.kt
diff --git a/vpn/src/main/java/com/vayunmathur/vpn/ui/BypassListPage.kt b/vpn/src/main/java/com/vayunmathur/vpn/ui/BypassListPage.ktindex d5b17b949b..4751adf66b 100644--- a/vpn/src/main/java/com/vayunmathur/vpn/ui/BypassListPage.kt+++ b/vpn/src/main/java/com/vayunmathur/vpn/ui/BypassListPage.kt@@ -29,7 +29,7 @@ import com.vayunmathur.vpn.ui.components.AppIconImage import com.vayunmathur.vpn.ui.components.BypassApp import com.vayunmathur.vpn.ui.components.LockdownWarning import com.vayunmathur.vpn.ui.components.loadApps-import com.vayunmathur.vpn.util.BypassList+import com.vayunmathur.vpn.platform.BypassList import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext
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 15a96ede1d..4f489199d1 100644--- a/vpn/src/main/java/com/vayunmathur/vpn/ui/ConfigDetailPage.kt+++ b/vpn/src/main/java/com/vayunmathur/vpn/ui/ConfigDetailPage.kt@@ -21,7 +21,7 @@ import com.vayunmathur.library.ui.DetailScaffold import com.vayunmathur.library.ui.Text import com.vayunmathur.vpn.Route import com.vayunmathur.vpn.data.WgConfigParser-import com.vayunmathur.vpn.util.VpnViewModel+import com.vayunmathur.vpn.platform.VpnViewModel import com.vayunmathur.library.util.NavBackStack /**
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 c5dc899bfe..907ce0eee3 100644--- a/vpn/src/main/java/com/vayunmathur/vpn/ui/ConfigListPage.kt+++ b/vpn/src/main/java/com/vayunmathur/vpn/ui/ConfigListPage.kt@@ -16,7 +16,7 @@ import com.vayunmathur.library.ui.SnackbarHostState import com.vayunmathur.vpn.R import com.vayunmathur.vpn.Route import com.vayunmathur.vpn.service.VpnTunnelService-import com.vayunmathur.vpn.util.VpnViewModel+import com.vayunmathur.vpn.platform.VpnViewModel import kotlinx.coroutines.launch @Composable
vpn/src/main/java/com/vayunmathur/vpn/ui/LoggingPage.kt
diff --git a/vpn/src/main/java/com/vayunmathur/vpn/ui/LoggingPage.kt b/vpn/src/main/java/com/vayunmathur/vpn/ui/LoggingPage.ktindex d7bc15e2de..c9953a514f 100644--- a/vpn/src/main/java/com/vayunmathur/vpn/ui/LoggingPage.kt+++ b/vpn/src/main/java/com/vayunmathur/vpn/ui/LoggingPage.kt@@ -5,7 +5,7 @@ import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue import com.vayunmathur.library.util.NavBackStack import com.vayunmathur.vpn.Route-import com.vayunmathur.vpn.util.VpnViewModel+import com.vayunmathur.vpn.platform.VpnViewModel @Composable fun LoggingPage(backStack: NavBackStack<Route>, vm: VpnViewModel) {
vpn/src/main/java/com/vayunmathur/vpn/ui/SettingsPage.kt
diff --git a/vpn/src/main/java/com/vayunmathur/vpn/ui/SettingsPage.kt b/vpn/src/main/java/com/vayunmathur/vpn/ui/SettingsPage.ktindex e859623901..af22b0f3a1 100644--- a/vpn/src/main/java/com/vayunmathur/vpn/ui/SettingsPage.kt+++ b/vpn/src/main/java/com/vayunmathur/vpn/ui/SettingsPage.kt@@ -14,8 +14,8 @@ import com.vayunmathur.library.ui.SettingsRow import com.vayunmathur.library.util.NavBackStack import com.vayunmathur.vpn.R import com.vayunmathur.vpn.Route+import com.vayunmathur.vpn.platform.VpnViewModel import com.vayunmathur.vpn.ui.components.openVpnSettings-import com.vayunmathur.vpn.util.VpnViewModel @Composable fun SettingsPage(backStack: NavBackStack<Route>, vm: VpnViewModel) {