Modern Apps git

← Modern-Apps.git

madeveloper: pair push socket via server registration

Commit
d80a8b988280febcdc36864f10eebf00858300f0
Author
Vayun Mathur <[email protected]>
When
2026-11-17 15:47 UTC (18 days ago)
Parents
4b8463d
The app generated a pairing code locally, opened
wss://api.maproj.org/dev/ws?code=<local> with no token, and waited
for a Paired frame. The deployed server never sends that frame: it
registers devices via POST /dev/register {deviceName} returning
{deviceId, pushToken, pairingCode} as pending, the owner approves
the 6-digit code in the server /dev panel, and GET /dev/ws only
upgrades for active devices presenting Authorization: Bearer
<pushToken> (401 unknown token, 403 not active). The old socket
was refused pre-upgrade, connectPush swallowed the exception, and
the UI showed push socket offline forever.

Align the app with that contract:

- DevRegistrar (new seam in data/, mirroring transportFactory)
  POSTs /dev/register through NetworkClient (FIRST_PARTY, set by
  the activity) with the Build.MANUFACTURER/MODEL device name;
  DevProtocol gains the pure request-body builder and reply parser.
- PairingStore now only persists server-issued credentials via
  saveRegistration; local code generation is gone. A legacy
  locally generated code is stored without a token, so no-token
  means register fresh and overwrite it (migration).
- connectPush registers on first need, then opens the socket at
  the bare DEV_WS_URL with the stored pushToken as Bearer. Paired
  is false until the socket actually connects; a 403 handshake
  sets awaitingApproval so PushScreen can say waiting for approval
  instead of generic offline (minimal text change only).
- Connect failures are logged via Log.status instead of being
  swallowed silently, and only IOException is caught so coroutine
  cancellation still propagates.
- DevMessage.Paired is removed; a stray paired frame parses as
  Unknown. The listApps reply now matches the server frame it
  parses (type installed, key packages, not apps).

Tests: DevProtocol register round-trip and installed-reply shape;
ViewModel register-then-connect with token/URL assertions, legacy
code migration, stored-token skip, and 403 awaiting-approval;
PairingStore server-credentials-only; PushScreen approval text.

Verified: :madeveloper:testDevUnitTest (43 tests), :madeveloper:lintDev
and :madeveloper:detekt all green.

Diff

madeveloper/src/main/java/com/vayunmathur/madeveloper/data/DevPushClient.kt
diff --git a/madeveloper/src/main/java/com/vayunmathur/madeveloper/data/DevPushClient.kt b/madeveloper/src/main/java/com/vayunmathur/madeveloper/data/DevPushClient.ktindex 3d4d5a5753..d1a278c7b6 100644--- a/madeveloper/src/main/java/com/vayunmathur/madeveloper/data/DevPushClient.kt+++ b/madeveloper/src/main/java/com/vayunmathur/madeveloper/data/DevPushClient.kt@@ -1,8 +1,11 @@ package com.vayunmathur.madeveloper.data +import com.vayunmathur.library.network.NetworkClient import com.vayunmathur.library.network.WebSocketClient import com.vayunmathur.madeveloper.domain.DevMessage import com.vayunmathur.madeveloper.domain.DevProtocol+import com.vayunmathur.madeveloper.domain.DevRegistration+import java.io.IOException import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.mapNotNull @@ -16,6 +19,32 @@ interface DevSocketTransport {     suspend fun close() } +/**+ * Registers this device with the server (`POST /dev/register`). The server+ * returns the pairing code the owner approves in its `/dev` panel and the+ * push token the socket later presents as a bearer token; until approval+ * the device is `pending` server-side and the socket is refused with 403.+ */+class DevRegistrar(+    // The one network seam: how a URL + JSON body becomes its reply text.+    private val poster: suspend (String, String) -> String = { url, body -> postViaNetwork(url, body) },+) {+    /** Registers [deviceName] and returns the server-issued credentials. */+    suspend fun register(deviceName: String): DevRegistration {+        val body = poster(GitHostRepository.DEV_REGISTER_URL, DevProtocol.registerRequestBody(deviceName))+        return DevProtocol.parseRegistration(body)+            ?: throw IOException("Malformed /dev/register reply")+    }+}++/** Production [DevRegistrar] post: NetworkClient (FIRST_PARTY, set by the activity). */+private suspend fun postViaNetwork(url: String, body: String): String {+    val headers = mapOf("Content-Type" to "application/json", "Accept" to "application/json")+    val response = NetworkClient.performRequest(url, method = "POST", headers = headers, body = body)+    if (!response.isSuccess) throw IOException("HTTP " + response.status + " for " + url)+    return response.body+}+ /** [DevSocketTransport] over the shared [WebSocketClient]. */ class WebSocketDevTransport private constructor(private val client: WebSocketClient) : DevSocketTransport {     override val messages: Flow<DevMessage> = client.incomingFlow().mapNotNull { frame ->
madeveloper/src/main/java/com/vayunmathur/madeveloper/data/GitHostRepository.kt
diff --git a/madeveloper/src/main/java/com/vayunmathur/madeveloper/data/GitHostRepository.kt b/madeveloper/src/main/java/com/vayunmathur/madeveloper/data/GitHostRepository.ktindex 087a7b70b8..6f45d34c6f 100644--- a/madeveloper/src/main/java/com/vayunmathur/madeveloper/data/GitHostRepository.kt+++ b/madeveloper/src/main/java/com/vayunmathur/madeveloper/data/GitHostRepository.kt@@ -86,6 +86,7 @@ class GitHostRepository(         const val GIT_HOST = "https://git.maproj.org"         const val FDROID_BASE = "https://static.maproj.org/fdroid/repo"         const val DEV_WS_URL = "wss://api.maproj.org/dev/ws"+        const val DEV_REGISTER_URL = "https://api.maproj.org/dev/register"          /** Default commits page size for the commits screen. */         const val COMMITS_PAGE_SIZE = 30
madeveloper/src/main/java/com/vayunmathur/madeveloper/domain/DevProtocol.kt
diff --git a/madeveloper/src/main/java/com/vayunmathur/madeveloper/domain/DevProtocol.kt b/madeveloper/src/main/java/com/vayunmathur/madeveloper/domain/DevProtocol.ktindex 273702283d..1e4f20de92 100644--- a/madeveloper/src/main/java/com/vayunmathur/madeveloper/domain/DevProtocol.kt+++ b/madeveloper/src/main/java/com/vayunmathur/madeveloper/domain/DevProtocol.kt@@ -14,8 +14,6 @@ sealed interface DevMessage {     data object Ping : DevMessage     /** The server asks which first-party packages are installed. */     data object ListApps : DevMessage-    /** The server has paired this device and issued a durable token. */-    data class Paired(val token: String, val deviceId: String) : DevMessage     /** A build the server wants installed on this device. */     data class Install(         val pkg: String, val versionCode: Long, val apkUrl: String,@@ -28,6 +26,9 @@ sealed interface DevMessage { /** One installed first-party package reported back to the server. */ data class InstalledAppInfo(val pkg: String, val versionCode: Long) +/** Credentials returned by `POST /dev/register`; the device stays pending until approved. */+data class DevRegistration(val deviceId: String, val pushToken: String, val pairingCode: String)+ /** Lifecycle of one pushed install, from push to the system installer. */ enum class InstallPhase { PUSHED, DOWNLOADING, VERIFYING, READY, INSTALLING, DONE, FAILED } @@ -40,14 +41,27 @@ data class PendingInstall( /** Pure protocol and install-state logic for the dev push channel. */ object DevProtocol {     private val json = Json { ignoreUnknownKeys = true; isLenient = true }-    private const val CODE_ALPHABET = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789"-    private const val CODE_LENGTH = 6     private const val MAX_BACKOFF_MS = 60_000L     private const val BASE_BACKOFF_MS = 1_000L -    /** A short human-typable pairing code shown on first launch. */-    fun newPairingCode(random: java.util.Random = java.security.SecureRandom()): String =-        buildString { repeat(CODE_LENGTH) { append(CODE_ALPHABET[random.nextInt(CODE_ALPHABET.length)]) } }+    /** The `POST /dev/register` request body for [deviceName]. */+    fun registerRequestBody(deviceName: String): String =+        kotlinx.serialization.json.buildJsonObject {+            put("deviceName", kotlinx.serialization.json.JsonPrimitive(deviceName))+        }.toString()++    /** Parses a `/dev/register` reply; null when any credential field is missing or blank. */+    fun parseRegistration(text: String): DevRegistration? {+        val root = try {+            json.parseToJsonElement(text).jsonObject+        } catch (_: Exception) {+            return null+        }+        val registration = DevRegistration(root.s("deviceId"), root.s("pushToken"), root.s("pairingCode"))+        return registration.takeIf {+            it.deviceId.isNotBlank() && it.pushToken.isNotBlank() && it.pairingCode.isNotBlank()+        }+    }      /** Parses one text frame from the server; malformed frames become [DevMessage.Unknown]. */     fun parse(text: String): DevMessage {@@ -59,7 +73,6 @@ object DevProtocol {         return when (root.s("type")) {             "ping" -> DevMessage.Ping             "listApps" -> DevMessage.ListApps-            "paired" -> DevMessage.Paired(root.s("token"), root.s("deviceId"))             "install" -> DevMessage.Install(                 pkg = root.s("package"), versionCode = root["versionCode"]?.jsonPrimitive?.longOrNull ?: 0L,                 apkUrl = root.s("apkUrl"), sha256 = root.s("sha256"),@@ -69,9 +82,9 @@ object DevProtocol {         }     } -    /** The reply to a [DevMessage.ListApps] request. */+    /** The reply to a [DevMessage.ListApps] request (server frame: `installed` + `packages`). */     fun listAppsReply(apps: List<InstalledAppInfo>): String = buildString {-        append("{\"type\":\"apps\",\"apps\":[")+        append("{\"type\":\"installed\",\"packages\":[")         apps.forEachIndexed { index, app ->             if (index > 0) append(',')             append("{\"package\":\"").append(app.pkg).append("\",\"versionCode\":").append(app.versionCode).append('}')
madeveloper/src/main/java/com/vayunmathur/madeveloper/platform/MaDevViewModel.kt
diff --git a/madeveloper/src/main/java/com/vayunmathur/madeveloper/platform/MaDevViewModel.kt b/madeveloper/src/main/java/com/vayunmathur/madeveloper/platform/MaDevViewModel.ktindex 889d0e6e15..b2358d2fce 100644--- a/madeveloper/src/main/java/com/vayunmathur/madeveloper/platform/MaDevViewModel.kt+++ b/madeveloper/src/main/java/com/vayunmathur/madeveloper/platform/MaDevViewModel.kt@@ -2,6 +2,7 @@ package com.vayunmathur.madeveloper.platform  import android.app.Application import android.app.PendingIntent+import android.os.Build import android.content.Intent import android.content.pm.PackageInstaller import android.content.pm.PackageManager@@ -10,12 +11,16 @@ import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.setValue import androidx.lifecycle.AndroidViewModel import androidx.lifecycle.viewModelScope+import com.vayunmathur.library.log.Log import com.vayunmathur.library.network.NetworkClient+import com.vayunmathur.library.network.WebSocketHandshakeException+import com.vayunmathur.madeveloper.data.DevRegistrar import com.vayunmathur.madeveloper.data.GitHostRepository import com.vayunmathur.madeveloper.data.DevSocketTransport import com.vayunmathur.madeveloper.data.WebSocketDevTransport import com.vayunmathur.madeveloper.domain.CatalogApp import com.vayunmathur.madeveloper.domain.DevMessage+import com.vayunmathur.madeveloper.domain.DevRegistration import com.vayunmathur.madeveloper.domain.DevProtocol import com.vayunmathur.madeveloper.domain.GitFile import com.vayunmathur.madeveloper.domain.GitIssue@@ -51,6 +56,8 @@ data class MaDevUiState(     val connected: Boolean = false,     val pairingCode: String = "",     val paired: Boolean = false,+    /** Registered but the server has not approved this device yet (socket refused 403). */+    val awaitingApproval: Boolean = false,     val pending: List<PendingInstall> = emptyList(), ) @@ -63,13 +70,17 @@ class MaDevViewModel(app: Application) : AndroidViewModel(app) {     internal var repo: GitHostRepository = GitHostRepository()     internal var transportFactory: suspend (String, String?) -> DevSocketTransport =         { url, token -> WebSocketDevTransport.connect(url, token) }+    internal var deviceRegistrar: suspend (String) -> DevRegistration =+        { deviceName -> DevRegistrar().register(deviceName) }     internal var apkFetcher: suspend (String) -> Pair<Int, ByteArray> =         { url -> NetworkClient.performRequestBytes(url) }     private val pairing = PairingStore(app)     private var transport: DevSocketTransport? = null     private var reconnectAttempt = 0 -    var state by mutableStateOf(MaDevUiState(pairingCode = pairing.pairingCode(), paired = pairing.token() != null))+    // Paired stays false until the socket actually connects: holding a token+    // only proves registration, not that the owner approved this device.+    var state by mutableStateOf(MaDevUiState(pairingCode = pairing.pairingCode() ?: ""))         private set      /** Loads home data and starts the push socket. */@@ -179,19 +190,22 @@ class MaDevViewModel(app: Application) : AndroidViewModel(app) {      // ---- Push socket ---- -    /** Connects the dev push socket, reconnecting with backoff on failure. */+    /** Registers on first need, then connects the push socket, reconnecting with backoff. */     fun connectPush() {         viewModelScope.launch {             while (true) {                 try {-                    val url = GitHostRepository.DEV_WS_URL + "?code=" + pairing.pairingCode()-                    val socket = transportFactory(url, pairing.token())+                    ensureRegistered()+                    val socket = transportFactory(GitHostRepository.DEV_WS_URL, pairing.token())                     transport = socket                     reconnectAttempt = 0-                    state = state.copy(connected = true)+                    state = state.copy(connected = true, paired = true, awaitingApproval = false)                     socket.messages.collect { message -> onServerMessage(message, socket) }-                } catch (_: Exception) {-                    // Fall through to the backoff below.+                } catch (e: java.io.IOException) {+                    Log.status(TAG, "dev push connect failed (attempt $reconnectAttempt): ${e.message}", e)+                    state = state.copy(+                        awaitingApproval = (e as? WebSocketHandshakeException)?.statusCode == HTTP_FORBIDDEN,+                    )                 }                 transport = null                 state = state.copy(connected = false)@@ -200,14 +214,35 @@ class MaDevViewModel(app: Application) : AndroidViewModel(app) {         }     } +    /**+     * Registers this device once and persists the server-issued credentials.+     * A legacy locally generated code is stored without a token, so "no token"+     * covers both first launch and that migration: register fresh either way.+     */+    private suspend fun ensureRegistered() {+        if (!pairing.token().isNullOrBlank()) {+            if (state.pairingCode.isBlank()) {+                state = state.copy(pairingCode = pairing.pairingCode() ?: "")+            }+            return+        }+        val registration = deviceRegistrar(deviceName())+        pairing.saveRegistration(registration.deviceId, registration.pushToken, registration.pairingCode)+        state = state.copy(pairingCode = registration.pairingCode, paired = false)+    }++    /** The user-visible device name sent to `/dev/register`. */+    private fun deviceName(): String {+        val model = listOf(Build.MANUFACTURER, Build.MODEL)+            .filter { it.isNotBlank() && !it.equals("unknown", ignoreCase = true) }+            .joinToString(" ").trim()+        return model.ifBlank { "Android device" }.take(MAX_DEVICE_NAME)+    }+     private suspend fun onServerMessage(message: DevMessage, socket: DevSocketTransport) {         when (message) {             DevMessage.Ping -> socket.send("{\"type\":\"pong\"}")             DevMessage.ListApps -> socket.send(DevProtocol.listAppsReply(installedApps()))-            is DevMessage.Paired -> {-                pairing.savePaired(message.token, message.deviceId)-                state = state.copy(paired = true)-            }             is DevMessage.Install -> onPushInstall(                 PendingInstall(message.pkg, message.versionCode, message.apkUrl, message.sha256, message.sizeBytes),             )@@ -309,4 +344,10 @@ class MaDevViewModel(app: Application) : AndroidViewModel(app) {      /** Whether the system will show an install prompt for this app. */     fun canInstall(): Boolean = getApplication<Application>().packageManager.canRequestPackageInstalls()++    private companion object {+        const val TAG = "MaDevViewModel"+        const val HTTP_FORBIDDEN = 403+        const val MAX_DEVICE_NAME = 120+    } }
madeveloper/src/main/java/com/vayunmathur/madeveloper/platform/PairingStore.kt
diff --git a/madeveloper/src/main/java/com/vayunmathur/madeveloper/platform/PairingStore.kt b/madeveloper/src/main/java/com/vayunmathur/madeveloper/platform/PairingStore.ktindex 17a3787091..35115f7bb4 100644--- a/madeveloper/src/main/java/com/vayunmathur/madeveloper/platform/PairingStore.kt+++ b/madeveloper/src/main/java/com/vayunmathur/madeveloper/platform/PairingStore.kt@@ -2,29 +2,37 @@ package com.vayunmathur.madeveloper.platform  import android.content.Context import androidx.core.content.edit-import com.vayunmathur.madeveloper.domain.DevProtocol -/** Persists the pairing code and the server-issued push token for this device. */+/**+ * Persists the server-issued pairing credentials for this device.+ *+ * Registration (`POST /dev/register`) is the only source of a pairing code:+ * older builds generated a code locally and stored it under the same key+ * without a token, so a stored code with no token is stale and the caller+ * registers fresh, overwriting it.+ */ class PairingStore(context: Context) {     private val prefs = context.getSharedPreferences(PREFS, Context.MODE_PRIVATE) -    /** The pairing code shown until the server pairs this device. */-    fun pairingCode(): String = prefs.getString(KEY_CODE, null) ?: DevProtocol.newPairingCode().also {-        prefs.edit { putString(KEY_CODE, it) }-    }+    /** The server-issued pairing code, or null while this device is unregistered. */+    fun pairingCode(): String? = prefs.getString(KEY_CODE, null)?.takeIf { it.isNotBlank() } -    /** The durable push token, or null while unpaired. */-    fun token(): String? = prefs.getString(KEY_TOKEN, null)+    /** The durable push token, or null while unregistered. */+    fun token(): String? = prefs.getString(KEY_TOKEN, null)?.takeIf { it.isNotBlank() } -    /** The server-issued device id, or null while unpaired. */-    fun deviceId(): String? = prefs.getString(KEY_DEVICE, null)+    /** The server-issued device id, or null while unregistered. */+    fun deviceId(): String? = prefs.getString(KEY_DEVICE, null)?.takeIf { it.isNotBlank() } -    /** Stores the credentials from a paired message. */-    fun savePaired(token: String, deviceId: String) {-        prefs.edit { putString(KEY_TOKEN, token); putString(KEY_DEVICE, deviceId) }+    /** Stores the credentials returned by `/dev/register`. */+    fun saveRegistration(deviceId: String, pushToken: String, pairingCode: String) {+        prefs.edit {+            putString(KEY_CODE, pairingCode)+            putString(KEY_TOKEN, pushToken)+            putString(KEY_DEVICE, deviceId)+        }     } -    /** Clears pairing so a new code is generated on next launch. */+    /** Clears pairing so the device registers fresh on next launch. */     fun clear() { prefs.edit { clear() } }      private companion object {
madeveloper/src/main/java/com/vayunmathur/madeveloper/ui/PushScreen.kt
diff --git a/madeveloper/src/main/java/com/vayunmathur/madeveloper/ui/PushScreen.kt b/madeveloper/src/main/java/com/vayunmathur/madeveloper/ui/PushScreen.ktindex d4f47147dc..7dbcbd680e 100644--- a/madeveloper/src/main/java/com/vayunmathur/madeveloper/ui/PushScreen.kt+++ b/madeveloper/src/main/java/com/vayunmathur/madeveloper/ui/PushScreen.kt@@ -27,9 +27,21 @@ fun PushScreen(state: MaDevUiState, onInstall: (String) -> Unit, onBack: () -> U             item {                 Card(Modifier.fillMaxWidth()) {                     Column(Modifier.padding(16.dp), verticalArrangement = Arrangement.spacedBy(4.dp)) {-                        Text(if (state.paired) "Paired" else "Pairing code: " + state.pairingCode)-                        Text(if (state.connected) "Socket connected to api.maproj.org" else "Socket offline; reconnecting with backoff")-                        Text("Give the pairing code to the server admin to register this device.")+                        Text(+                            when {+                                state.paired -> "Paired"+                                state.pairingCode.isNotBlank() -> "Pairing code: " + state.pairingCode+                                else -> "Registering this device…"+                            },+                        )+                        Text(+                            when {+                                state.connected -> "Socket connected to api.maproj.org"+                                state.awaitingApproval -> "Waiting for approval in the server's /dev panel"+                                else -> "Socket offline; reconnecting with backoff"+                            },+                        )+                        Text("Approve the pairing code in the server's /dev panel to activate this device.")                     }                 }             }
madeveloper/src/test/java/com/vayunmathur/madeveloper/DevProtocolTest.kt
diff --git a/madeveloper/src/test/java/com/vayunmathur/madeveloper/DevProtocolTest.kt b/madeveloper/src/test/java/com/vayunmathur/madeveloper/DevProtocolTest.ktindex 8bc13638d1..0370b8185c 100644--- a/madeveloper/src/test/java/com/vayunmathur/madeveloper/DevProtocolTest.kt+++ b/madeveloper/src/test/java/com/vayunmathur/madeveloper/DevProtocolTest.kt@@ -21,13 +21,27 @@ class DevProtocolTest {         assertTrue(DevProtocol.parse("not json") is DevMessage.Unknown)     } -    @Test fun pairingCodeAndBackoff() {-        assertEquals(6, DevProtocol.newPairingCode(java.util.Random(1)).length)+    @Test fun backoff() {         assertEquals(1000L, DevProtocol.backoffMs(0))         assertEquals(2000L, DevProtocol.backoffMs(1))         assertEquals(60000L, DevProtocol.backoffMs(20))     } +    @Test fun registerContractRoundTrip() {+        assertEquals("""{"deviceName":"Pixel 9"}""", DevProtocol.registerRequestBody("Pixel 9"))+        assertEquals("""{"deviceName":"a\"b"}""", DevProtocol.registerRequestBody("a\"b"))+        val registration = DevProtocol.parseRegistration(+            """{"deviceId":"dev-1","pushToken":"tok-1","pairingCode":"123456"}""",+        )+        assertEquals("dev-1", registration?.deviceId)+        assertEquals("tok-1", registration?.pushToken)+        assertEquals("123456", registration?.pairingCode)+        assertEquals(null, DevProtocol.parseRegistration("""{"deviceId":"dev-1"}"""))+        assertEquals(null, DevProtocol.parseRegistration("not json"))+        // A stale server "paired" frame is tolerated as unknown, never acted on.+        assertTrue(DevProtocol.parse("""{"type":"paired","token":"t","deviceId":"d"}""") is DevMessage.Unknown)+    }+     @Test fun shaVerification() {         val bytes = "hello".toByteArray()         val hash = DevProtocol.sha256Hex(bytes)@@ -44,6 +58,6 @@ class DevProtocolTest {      @Test fun listAppsReplyShape() {         val reply = DevProtocol.listAppsReply(listOf(InstalledAppInfo("com.vayunmathur.notes", 5)))-        assertTrue(reply.contains("\"versionCode\":5"))+        assertEquals("""{"type":"installed","packages":[{"package":"com.vayunmathur.notes","versionCode":5}]}""", reply)     } }
madeveloper/src/test/java/com/vayunmathur/madeveloper/platform/MaDevPushInstallTest.kt
diff --git a/madeveloper/src/test/java/com/vayunmathur/madeveloper/platform/MaDevPushInstallTest.kt b/madeveloper/src/test/java/com/vayunmathur/madeveloper/platform/MaDevPushInstallTest.ktindex f67c15f7e7..226ed859ec 100644--- a/madeveloper/src/test/java/com/vayunmathur/madeveloper/platform/MaDevPushInstallTest.kt+++ b/madeveloper/src/test/java/com/vayunmathur/madeveloper/platform/MaDevPushInstallTest.kt@@ -4,6 +4,7 @@ import android.app.Application import androidx.test.core.app.ApplicationProvider import com.vayunmathur.madeveloper.data.GitHostRepository import com.vayunmathur.madeveloper.domain.DevMessage+import com.vayunmathur.madeveloper.domain.DevRegistration import com.vayunmathur.madeveloper.domain.InstallPhase import java.io.File import java.security.MessageDigest@@ -55,44 +56,101 @@ class MaDevPushInstallTest {         val transport = FakeTransport()         var apkBytes: ByteArray = "fake-apk-bytes".toByteArray()         var apkStatus: Int = 200+        var registrations = 0+        var registeredName: String? = null+        var socketUrl: String? = null+        var socketToken: String? = null+        var transportError: Exception? = null         val scope = CoroutineScope(Dispatchers.Main + Job())          fun viewModel(app: Application): MaDevViewModel {             val viewModel = MaDevViewModel(app)             viewModel.repo = GitHostRepository(FakeGitHost().fetcher)-            viewModel.transportFactory = { _, _ -> transport }+            viewModel.deviceRegistrar = { name ->+                registrations+++                registeredName = name+                DevRegistration("dev-7", "tok-42", "123456")+            }+            viewModel.transportFactory = { url, token ->+                socketUrl = url+                socketToken = token+                transportError?.let { throw it }+                transport+            }             viewModel.apkFetcher = { apkStatus to apkBytes }             return viewModel         }     } -    @Test fun socketLifecyclePingListAppsAndPairing() {+    @Test fun socketLifecycleRegistersThenPingAndListApps() {         val harness = Harness()         val viewModel = harness.viewModel(app)+        assertFalse(viewModel.state.paired, "unpaired until the socket connects")         viewModel.connectPush()         await("connected") { viewModel.state.connected } +        // Registration happened first, once, and its token opens the socket.+        assertEquals(1, harness.registrations)+        assertTrue(!harness.registeredName.isNullOrBlank())+        assertEquals(GitHostRepository.DEV_WS_URL, harness.socketUrl)+        assertFalse(harness.socketUrl.orEmpty().contains("?code="), "the socket URL carries no pairing code")+        assertEquals("tok-42", harness.socketToken)+        assertEquals("tok-42", PairingStore(app).token())+        assertEquals("dev-7", PairingStore(app).deviceId())+        assertEquals("123456", PairingStore(app).pairingCode())+        assertEquals("123456", viewModel.state.pairingCode)+        assertTrue(viewModel.state.paired, "a live socket proves approval")+         harness.transport.incoming.tryEmit(DevMessage.Ping)         await("pong sent") { synchronized(harness.transport.sent) { harness.transport.sent.contains("{\"type\":\"pong\"}") } }          harness.transport.incoming.tryEmit(DevMessage.ListApps)         await("app list sent") {             synchronized(harness.transport.sent) {-                harness.transport.sent.any { it.contains("\"type\":\"apps\"") }+                harness.transport.sent.any { it.contains("\"type\":\"installed\"") && it.contains("\"packages\"") }             }         } -        harness.transport.incoming.tryEmit(DevMessage.Paired("tok-42", "dev-7"))-        await("paired state") { viewModel.state.paired }-        assertEquals("tok-42", PairingStore(app).token())-        assertEquals("dev-7", PairingStore(app).deviceId())-         harness.transport.incoming.tryEmit(DevMessage.Unknown("{\"type\":\"future\"}"))         Thread.sleep(300)         assertTrue(viewModel.state.connected, "unknown server messages must not drop the socket")         harness.scope.cancel()     } +    @Test fun storedTokenSkipsRegistrationAndLegacyCodeRegistersFresh() {+        // Legacy migration: an old locally generated code with no token.+        app.getSharedPreferences("dev_push", android.content.Context.MODE_PRIVATE)+            .edit().putString("pairing_code", "ABC234").commit()+        val harness = Harness()+        val viewModel = harness.viewModel(app)+        viewModel.connectPush()+        await("connected after fresh registration") { viewModel.state.connected }+        assertEquals(1, harness.registrations, "a tokenless legacy code must register fresh")+        assertEquals("123456", PairingStore(app).pairingCode(), "the server code replaces the local one")++        // With a stored token, no second registration happens.+        val harness2 = Harness()+        val viewModel2 = harness2.viewModel(app)+        viewModel2.connectPush()+        await("connected with stored token") { viewModel2.state.connected }+        assertEquals(0, harness2.registrations)+        assertEquals("tok-42", harness2.socketToken)+        harness.scope.cancel()+        harness2.scope.cancel()+    }++    @Test fun forbiddenSocketMeansWaitingForApproval() {+        val harness = Harness()+        harness.transportError = com.vayunmathur.library.network.WebSocketHandshakeException(403, "HTTP 403")+        val viewModel = harness.viewModel(app)+        viewModel.connectPush()+        await("awaiting approval") { viewModel.state.awaitingApproval }+        assertFalse(viewModel.state.connected)+        assertFalse(viewModel.state.paired)+        assertEquals("123456", viewModel.state.pairingCode)+        harness.scope.cancel()+    }+     @Test fun pushedInstallDownloadsVerifiesAndBecomesReady() {         val harness = Harness()         val viewModel = harness.viewModel(app)
madeveloper/src/test/java/com/vayunmathur/madeveloper/platform/MaDevViewModelTest.kt
diff --git a/madeveloper/src/test/java/com/vayunmathur/madeveloper/platform/MaDevViewModelTest.kt b/madeveloper/src/test/java/com/vayunmathur/madeveloper/platform/MaDevViewModelTest.ktindex 9186662182..20eaeb3401 100644--- a/madeveloper/src/test/java/com/vayunmathur/madeveloper/platform/MaDevViewModelTest.kt+++ b/madeveloper/src/test/java/com/vayunmathur/madeveloper/platform/MaDevViewModelTest.kt@@ -228,19 +228,23 @@ class MaDevViewModelTest {         assertFalse(viewModel.canInstall(), "host JVM never holds the install permission")     } -    @Test fun pairingStoreCodeIsStableAndPairingPersists() {+    @Test fun pairingStoreHoldsOnlyServerIssuedCredentials() {         val store = PairingStore(app)-        val code = store.pairingCode()-        assertEquals(6, code.length)-        assertEquals(code, store.pairingCode(), "the code is generated once and kept")+        assertNull(store.pairingCode(), "no code exists before server registration")         assertNull(store.token())+        assertNull(store.deviceId())+        // Holding credentials alone does not mark the device paired; only a+        // live socket does.         assertFalse(MaDevViewModel(app).state.paired)-        store.savePaired("token-1", "device-9")+        store.saveRegistration("device-9", "token-1", "123456")+        assertEquals("123456", store.pairingCode())         assertEquals("token-1", store.token())         assertEquals("device-9", store.deviceId())-        assertTrue(MaDevViewModel(app).state.paired)+        assertEquals("123456", MaDevViewModel(app).state.pairingCode)+        assertFalse(MaDevViewModel(app).state.paired)         store.clear()         assertNull(store.token())+        assertNull(store.pairingCode())     } } 
madeveloper/src/test/java/com/vayunmathur/madeveloper/ui/MaDevScreensTest.kt
diff --git a/madeveloper/src/test/java/com/vayunmathur/madeveloper/ui/MaDevScreensTest.kt b/madeveloper/src/test/java/com/vayunmathur/madeveloper/ui/MaDevScreensTest.ktindex ab871848f4..59258d4cc8 100644--- a/madeveloper/src/test/java/com/vayunmathur/madeveloper/ui/MaDevScreensTest.kt+++ b/madeveloper/src/test/java/com/vayunmathur/madeveloper/ui/MaDevScreensTest.kt@@ -179,6 +179,17 @@ class MaDevScreensTest {         assertEquals("com.example.ready", installed)     } +    @Test fun pushScreenWaitingForApproval() {+        rule.setContent {+            PushScreen(+                MaDevUiState(pairingCode = "123456", awaitingApproval = true),+                onInstall = {},+            ) {}+        }+        rule.onNodeWithText("Pairing code: 123456").assertIsDisplayed()+        rule.onNodeWithText("Waiting for approval in the server's /dev panel").assertIsDisplayed()+    }+     @Test fun pushScreenPairedAndEmpty() {         rule.setContent { PushScreen(MaDevUiState(connected = true, paired = true), onInstall = {}) {} }         rule.onNodeWithText("Paired").assertIsDisplayed()