Modern Apps git

← Modern-Apps.git

sdk/controller: a divergent remembered key falls back to code pairing instead of locking out

Commit
5e4a993eb66e5fab37955391d0045704015376f2
Author
Vayun Mathur <[email protected]>
When
2026-12-01 10:34 UTC (5 days ago)
Parents
c876dfd
The gate returns a recoverable Wrong for a failed device
proof ('falls back to the code', 'no lockout' — the module's
own documented contract), but the host treated every Wrong
as terminal (PAIR_FAILED + socket close) and the client had
no transition out of remembered-device proof except
PAIRED/FAILED. With one side re-paired/restored and the
other keeping its key, every reconnect deterministically
repeated the identical failing proof: permanent lockout,
with no delete path for the stored keys on either side.

After a failed device proof the host now puts its code on
screen, re-sends PAIR_REQUIRED(code=true) on the same
session, and verifies the next proof as a code proof;
success mints one fresh device key both ends persist,
repairing the divergence. The client transitions to
AWAITING_CODE on that message (pending transcript already
held). No DTO, field or version change — new/old pairs in
either combination degrade to today's outcome. Regression
test seeds divergent stored keys and drives the full
fallback to JOINED with identical fresh keys (timed out at
FAILED pre-fix). The openassistant SDK was audited and
cleared. Verified: :sdk:controller:testDebugUnitTest 86
tests pass; lint no issues.

Diff

sdk/controller/src/main/java/com/vayunmathur/sdk/controller/ControllerClient.kt
diff --git a/sdk/controller/src/main/java/com/vayunmathur/sdk/controller/ControllerClient.kt b/sdk/controller/src/main/java/com/vayunmathur/sdk/controller/ControllerClient.ktindex c0af7de94c..1b181a33ad 100644--- a/sdk/controller/src/main/java/com/vayunmathur/sdk/controller/ControllerClient.kt+++ b/sdk/controller/src/main/java/com/vayunmathur/sdk/controller/ControllerClient.kt@@ -227,9 +227,20 @@ class ControllerClient(     ) {         val proof = keys.deviceProof(remembered, transcript.value())         socket.send(ControllerPairProof(ClientBase64.encode(proof))) ?: return failed(socket)-        val ok = socket.receive() ?: return failed(socket)-        if (ok.message !is ControllerPairOk) return failed(socket)-        _state.value = ClientState.PAIRED+        val answer = socket.receive() ?: return failed(socket)+        when (val message = answer.message) {+            is ControllerPairOk -> _state.value = ClientState.PAIRED+            is ControllerPairRequired -> {+                // The TV no longer matches the remembered key and has put a code on+                // screen instead: fall back to typing it. pendingSession() already+                // holds this session's keys and transcript, so proveCode picks up+                // exactly where this leaves off.+                if (!message.code) return failed(socket)+                pendingWantsCode = true+                _state.value = ClientState.AWAITING_CODE+            }+            else -> failed(socket)+        }     }      private fun runCodeProof(code: String) {
sdk/controller/src/main/java/com/vayunmathur/sdk/controller/ControllerHost.kt
diff --git a/sdk/controller/src/main/java/com/vayunmathur/sdk/controller/ControllerHost.kt b/sdk/controller/src/main/java/com/vayunmathur/sdk/controller/ControllerHost.ktindex 7c421f44d5..52d10be8ba 100644--- a/sdk/controller/src/main/java/com/vayunmathur/sdk/controller/ControllerHost.kt+++ b/sdk/controller/src/main/java/com/vayunmathur/sdk/controller/ControllerHost.kt@@ -218,7 +218,7 @@ class ControllerHost(         transcript: ControllerTranscript,     ) {         val remembered = loadDeviceKey(hello.senderId)-        val wantsCode = remembered == null || !hello.paired+        var wantsCode = remembered == null || !hello.paired         val gate = ControllerPairingGate()         synchronized(lock) { pairingGates[socket] = gate }         if (wantsCode) pairingCode = gate.code@@ -228,8 +228,26 @@ class ControllerHost(             return         }         val proofBytes = receiveProof(socket) ?: return-        val result = verifyProof(socket, gate, wantsCode, keys, transcript.value(), remembered, proofBytes)+        var result = verifyProof(socket, gate, wantsCode, keys, transcript.value(), remembered, proofBytes)             ?: return+        if (result is ControllerPairResult.Wrong && !wantsCode) {+            // The remembered-device proof failed: the phone holds a key this TV no+            // longer matches (or vice versa). Falling back to the code on this same+            // session is the only repair - closing here would repeat the identical+            // failing proof on every reconnect, because neither end has a reason to+            // drop its stored key, and the phone would be locked out for good.+            wantsCode = true+            pairingCode = gate.code+            if (socket.send(ControllerPairRequired(code = true)) == null) {+                finishPairing(socket)+                socket.close()+                return+            }+            val codeProofBytes = receiveProof(socket) ?: return+            result = verifyProof(+                socket, gate, wantsCode, keys, transcript.value(), remembered, codeProofBytes,+            ) ?: return+        }         when (result) {             is ControllerPairResult.Ok -> {                 result.deviceKey?.let { saveDeviceKey(hello.senderId, it) }
sdk/controller/src/main/java/com/vayunmathur/sdk/controller/ControllerModels.kt
diff --git a/sdk/controller/src/main/java/com/vayunmathur/sdk/controller/ControllerModels.kt b/sdk/controller/src/main/java/com/vayunmathur/sdk/controller/ControllerModels.ktindex 487e52f883..fff6f43d6c 100644--- a/sdk/controller/src/main/java/com/vayunmathur/sdk/controller/ControllerModels.kt+++ b/sdk/controller/src/main/java/com/vayunmathur/sdk/controller/ControllerModels.kt@@ -128,11 +128,12 @@ data class ControllerHostHello( data class ControllerSealedSecret(val sealed: String) : ControllerMessage  /**- * The TV's answer to `SEALED_SECRET`, and always exactly one message so the sequence has no branch- * the phone has to guess at.+ * The TV's answer to `SEALED_SECRET`, and again after a remembered-device proof the TV cannot+ * verify, so a phone holding a stale device key falls back to the code on the same session instead+ * of being refused on every reconnect.  *  * [code] false means the TV remembers this phone and wants only a proof of the device key it holds;- * true means it does not, and six digits are on screen.+ * true means it does not (or no longer matches it), and six digits are on screen.  */ @Serializable @SerialName("PAIR_REQUIRED")
sdk/controller/src/test/java/com/vayunmathur/sdk/controller/ControllerPairingFallbackTest.kt
diff --git a/sdk/controller/src/test/java/com/vayunmathur/sdk/controller/ControllerPairingFallbackTest.kt b/sdk/controller/src/test/java/com/vayunmathur/sdk/controller/ControllerPairingFallbackTest.ktnew file mode 100644index 0000000000..7ff47a01f9--- /dev/null+++ b/sdk/controller/src/test/java/com/vayunmathur/sdk/controller/ControllerPairingFallbackTest.kt@@ -0,0 +1,118 @@+package com.vayunmathur.sdk.controller++import androidx.test.ext.junit.runners.AndroidJUnit4+import java.net.InetAddress+import java.net.ServerSocket+import java.util.concurrent.ConcurrentHashMap+import kotlin.test.Test+import kotlin.test.assertNotNull+import kotlin.test.assertTrue+import org.junit.runner.RunWith++/**+ * Regression test: a remembered device whose key no longer matches the TV's copy must+ * fall back to the six-digit code on the same session (see+ * [ControllerPairingGate.verifyDevice]), not lose the session and repeat the same+ * failing device proof on every reconnect.+ */+@RunWith(AndroidJUnit4::class)+class ControllerPairingFallbackTest {++    private fun await(desc: String, timeoutMs: Long = 15_000, condition: () -> Boolean) {+        val deadline = System.currentTimeMillis() + timeoutMs+        while (System.currentTimeMillis() < deadline) {+            if (condition()) return+            Thread.sleep(10)+        }+        throw AssertionError("timed out waiting for: $desc")+    }++    private class Harness(+        val hostKeys: MutableMap<String, ByteArray> = ConcurrentHashMap(),+    ) {+        val host = ControllerHost(+            gameId = "kart",+            hostId = "tv-1",+            hostName = "Test TV",+            providePublicBundle = { byteArrayOf(9, 8, 7) },+            unsealSecret = { sealed -> sealed },+            loadDeviceKey = { hostKeys[it] },+            saveDeviceKey = { id, key -> hostKeys[id] = key },+        )+        private val server = ServerSocket(0, 8, InetAddress.getByName("127.0.0.1"))+        val port: Int = server.localPort+        @Volatile var running = true++        init {+            Thread {+                while (running) {+                    try {+                        val socket = ControllerSocket()+                        socket.attach(server.accept())+                        host.accept(socket)+                    } catch (_: Exception) {+                        if (running) throw AssertionError("accept failed")+                    }+                }+            }.apply { isDaemon = true }.start()+        }++        fun hostInfo(): ControllerHostInfo = ControllerHostInfo(+            id = "tv-1", instanceName = "Test TV (Game Host)", friendlyName = "Test TV",+            host = "127.0.0.1", port = port,+            protocolVersion = ControllerContract.CONTROLLER_PROTOCOL_VERSION, gameId = "kart",+        )++        fun close() {+            running = false+            runCatching { server.close() }+            host.close()+        }+    }++    @Test+    fun divergentRememberedKeyFallsBackToCodeAndRepairs() {+        val tvKey = ByteArray(32) { 1 }+        val stalePhoneKey = ByteArray(32) { 2 }+        val harness = Harness()+        harness.hostKeys["phone-1"] = tvKey+        val clientKeys = ConcurrentHashMap<String, ByteArray>()+        clientKeys["tv-1"] = stalePhoneKey+        val client = ControllerClient(+            senderId = "phone-1",+            senderName = "Phone phone-1",+            sealToBundle = { _, secret -> secret },+            loadDeviceKey = { clientKeys[it] },+            saveDeviceKey = { hostId, key -> clientKeys[hostId] = key },+        )+        try {+            client.connect(harness.hostInfo())+            // The device proof cannot match, so the TV must put a code on screen and+            // the phone must ask for it instead of ending FAILED.+            await("awaiting code after device-proof mismatch") {+                client.state.value == ClientState.AWAITING_CODE+            }+            val code = assertNotNull(harness.host.pairingCode)+            assertTrue(ControllerPairCode.isWellFormed(code))++            client.proveCode(code)+            await("paired via fallback code") { client.state.value == ClientState.PAIRED }+            // Code pairing mints one fresh device key and both ends persist that same+            // key, replacing the divergent pair that caused the fallback.+            val savedOnPhone = assertNotNull(clientKeys["tv-1"])+            val savedOnTv = assertNotNull(harness.hostKeys["phone-1"])+            assertTrue(savedOnPhone.contentEquals(savedOnTv))+            assertTrue(!savedOnPhone.contentEquals(stalePhoneKey))+            assertTrue(!savedOnPhone.contentEquals(tvKey))++            client.join("Alice")+            await("joined after fallback pairing") { client.state.value == ClientState.JOINED }+            await("host seated phone") {+                harness.host.lobby.value.slots.any { it.playerId == "phone-1" }+            }+        } finally {+            client.close()+            harness.close()+        }+    }+}