Modern Apps git

← Modern-Apps.git

security: seal stored tokens with device Keystore keys

Commit
b410ababa7949d2dca6e24d2694fc9ff748fc5ab
Author
Vayun Mathur <[email protected]>
When
2026-11-20 21:02 UTC (15 days ago)
Parents
2e76a04
Lichess (games/chess), git (code), Lyft (taxi) and fooddelivery
tokens sat in plain DataStore/SharedPreferences - and chess's
token even left the device in backups. Each store now seals
with a non-exportable AndroidKeyStore AES-GCM key (v1: prefix,
IV-prefixed ciphertext), copying everysync's TokenStore
pattern. Legacy plain values are used once and rewritten
sealed with verify-before-overwrite; unseal failure means
signed-out, never a crash and never ciphertext-as-token;
fooddelivery migrates inside its AppInit restore/persist
callbacks so cold-process services keep working. communicate's
Google Voice/WhatsApp/Signal auth stores get the same sealing
(Signal's blob is never destroyed on failure - a failed unseal
just reads as not registered).

Also in this range: auto's CarStartupService gains a caller
guard, web drops WebView file/content access and defaults
mixed content off, the Google Voice bridge is origin-locked,
and the flake work's shared-test harness (build-logic) lands.

Tests use a contract-identical fake sealer (Robolectric has no
AndroidKeyStore) + real-AES round trips: chess 253, code 632,
taxi 257, fooddelivery 162, communicate suites pass.

Diff

build-logic/shared-test/java/com/vayunmathur/testsupport/DeterministicAwait.kt
diff --git a/build-logic/shared-test/java/com/vayunmathur/testsupport/DeterministicAwait.kt b/build-logic/shared-test/java/com/vayunmathur/testsupport/DeterministicAwait.ktnew file mode 100644index 0000000000..0163767d02--- /dev/null+++ b/build-logic/shared-test/java/com/vayunmathur/testsupport/DeterministicAwait.kt@@ -0,0 +1,88 @@+package com.vayunmathur.testsupport++import android.os.Looper+import androidx.compose.ui.test.junit4.ComposeContentTestRule+import kotlinx.coroutines.flow.Flow+import kotlinx.coroutines.flow.first+import kotlinx.coroutines.runBlocking+import org.robolectric.Shadows++/**+ * Shared deterministic waits for JVM/Robolectric tests.+ *+ * This is the repo's one shared test-await helper. It lives in+ * `build-logic/shared-test/java`, which both convention plugins+ * (`common-conventions-app` and `common-conventions-library`) add to every+ * module's unit-test source set — the same mechanism that already shares+ * `build-logic/shared-test-resources/robolectric.properties`. There is no+ * shared test-util Gradle module in this repo, and none is invented here.+ *+ * Every wait below is a wait *on a signal*, never on a wall clock:+ * - [awaitValue] suspends until a [Flow] emits a value matching a predicate+ *   (a StateFlow terminal state, a Room/DataStore flow, a completion flow).+ * - [awaitWithMainIdle] pumps Robolectric's paused main looper until a+ *   terminal condition holds. Idling the looper is what lets a coroutine+ *   resumed on Main actually run; sleeping would only bet on load.+ * - [awaitSemantics] is a Compose semantics wait on a terminal node state,+ *   idling the main looper on every check for the same reason.+ *+ * None of these sleep, burn CPU, or read `System.currentTimeMillis`.+ */++/** Runs every task currently queued on Robolectric's paused main looper. */+fun idleMainLooper() {+    Shadows.shadowOf(Looper.getMainLooper()).idle()+}++/**+ * Suspends until [this] flow emits a value matching [predicate], and returns+ * that value. For a [kotlinx.coroutines.flow.StateFlow] this is a wait for a+ * terminal state: the caller is resumed by the emission itself, not by a poll.+ */+suspend fun <T> Flow<T>.awaitValue(predicate: (T) -> Boolean): T = first(predicate)++/**+ * Blocking form of [awaitValue] for plain (non-coroutine) JUnit tests.+ * Safe when the flow's producers run on IO/Default dispatchers or on an+ * unconfined Main dispatcher; do not use it for a value whose only producer+ * is queued on Robolectric's paused main looper — use [awaitWithMainIdle].+ */+fun <T> awaitValueBlocking(flow: Flow<T>, predicate: (T) -> Boolean): T =+    runBlocking { flow.awaitValue(predicate) }++/**+ * Idles the main looper until [condition] holds, then returns.+ *+ * Step-counted as a failure bound only: each step is a full looper idle,+ * which is the work that makes progress possible, and the thread yields+ * between steps so IO/Default producers on other threads can run. This+ * replaces `Thread.sleep` + `System.currentTimeMillis` deadline loops,+ * which under Robolectric measured a substituted clock and gave up before+ * real IO had landed.+ */+fun awaitWithMainIdle(description: String, maxSteps: Int = 10_000, condition: () -> Boolean) {+    var step = 0+    while (step++ < maxSteps) {+        idleMainLooper()+        if (condition()) return+        Thread.yield()+    }+    // One last idle + check so the failure reports the settled state.+    idleMainLooper()+    check(condition()) { "timed out (step-bounded, no wall clock): $description after $maxSteps looper idles" }+}++/**+ * Compose semantics wait on a terminal state: [ComposeContentTestRule.waitUntil]+ * re-checks [condition] after every idle, and each check first pumps the+ * main looper so a parse/load resumed on Main can land and compose.+ * The timeout is the framework's failure bound, not the mechanism.+ */+fun ComposeContentTestRule.awaitSemantics(description: String, condition: () -> Boolean) {+    waitUntil(15_000) {+        idleMainLooper()+        condition()+    }+    idleMainLooper()+    check(condition()) { "terminal semantics state not reached: $description" }+}
code/src/main/java/com/vayunmathur/code/data/TokenSealer.kt
diff --git a/code/src/main/java/com/vayunmathur/code/data/TokenSealer.kt b/code/src/main/java/com/vayunmathur/code/data/TokenSealer.ktnew file mode 100644index 0000000000..b2473f4e9a--- /dev/null+++ b/code/src/main/java/com/vayunmathur/code/data/TokenSealer.kt@@ -0,0 +1,117 @@+package com.vayunmathur.code.data++import android.security.keystore.KeyGenParameterSpec+import android.security.keystore.KeyProperties+import com.vayunmathur.library.log.Log+import java.security.KeyStore+import javax.crypto.Cipher+import javax.crypto.KeyGenerator+import javax.crypto.SecretKey+import javax.crypto.spec.GCMParameterSpec+import kotlin.io.encoding.Base64++/**+ * Seals a secret string for at-rest storage and unseals it on read.+ *+ * Sealed values carry the [KeystoreTokenSealer.PREFIX] marker so callers can tell them+ * apart from legacy plaintext written before sealing existed: [unseal] returns a+ * non-sealed value unchanged (it is legacy plain), while a sealed value that cannot be+ * decrypted (wrong device after a backup restore, rotated/lost Keystore key) yields+ * null — callers must treat that as signed-out, never crash and never fall back to+ * using the ciphertext as the secret.+ */+interface TokenSealer {+    /** Sealed form of [plain], or null when sealing failed (caller must not persist plain). */+    fun seal(plain: String): String?++    /** Plain form of [stored]; legacy non-sealed values pass through, failures give null. */+    fun unseal(stored: String): String?++    /** True when [stored] carries the sealed marker (whether or not it still decrypts). */+    fun isSealed(stored: String): Boolean+}++/**+ * [TokenSealer] backed by a non-exportable AES key in the Android Keystore, copied from+ * everysync's TokenStore: AES/GCM/NoPadding, the 12-byte GCM IV prefixed to the+ * ciphertext, the whole blob Base64-encoded behind [PREFIX] for string storage. The+ * Keystore key never leaves the device, so a sealed value carried off-device by backup+ * or device transfer is undecryptable on the destination.+ */+class KeystoreTokenSealer(private val keyAlias: String) : TokenSealer {++    /** Test seam: a software key replacing the AndroidKeyStore key (which Robolectric lacks). */+    internal var secretKeyForTest: SecretKey? = null++    private fun secretKey(): SecretKey {+        secretKeyForTest?.let { return it }+        val ks = KeyStore.getInstance(ANDROID_KEYSTORE).apply { load(null) }+        (ks.getEntry(keyAlias, null) as? KeyStore.SecretKeyEntry)?.let { return it.secretKey }+        val generator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, ANDROID_KEYSTORE)+        generator.init(+            KeyGenParameterSpec.Builder(+                keyAlias,+                KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT,+            )+                .setBlockModes(KeyProperties.BLOCK_MODE_GCM)+                .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE)+                .build(),+        )+        return generator.generateKey()+    }++    private fun encrypt(plain: ByteArray): ByteArray {+        val cipher = Cipher.getInstance(TRANSFORMATION)+        cipher.init(Cipher.ENCRYPT_MODE, secretKey())+        val iv = cipher.iv+        val ct = cipher.doFinal(plain)+        // Prefix the 12-byte GCM IV so we can recover it on decrypt.+        return ByteArray(iv.size + ct.size).also {+            iv.copyInto(it, 0)+            ct.copyInto(it, iv.size)+        }+    }++    private fun decrypt(blob: ByteArray): ByteArray {+        val iv = blob.copyOfRange(0, GCM_IV_LEN)+        val ct = blob.copyOfRange(GCM_IV_LEN, blob.size)+        val cipher = Cipher.getInstance(TRANSFORMATION)+        cipher.init(Cipher.DECRYPT_MODE, secretKey(), GCMParameterSpec(GCM_TAG_BITS, iv))+        return cipher.doFinal(ct)+    }++    override fun seal(plain: String): String? = try {+        PREFIX + Base64.encode(encrypt(plain.toByteArray(Charsets.UTF_8)))+    } catch (expected: Exception) {+        Log.error(TAG, "Failed to seal token", expected)+        null+    }++    override fun unseal(stored: String): String? {+        if (!isSealed(stored)) return stored+        return try {+            val blob = Base64.decode(stored.removePrefix(PREFIX))+            if (blob.size <= GCM_IV_LEN) {+                null+            } else {+                String(decrypt(blob), Charsets.UTF_8)+            }+        } catch (expected: Exception) {+            Log.error(TAG, "Failed to unseal token", expected)+            null+        }+    }++    override fun isSealed(stored: String): Boolean = stored.startsWith(PREFIX)++    /** Keystore constants for sealed token storage. */+    companion object {+        /** Marker distinguishing sealed values from legacy plaintext. */+        const val PREFIX = "v1:"+        private const val ANDROID_KEYSTORE = "AndroidKeyStore"+        private const val TRANSFORMATION = "AES/GCM/NoPadding"+        private const val GCM_IV_LEN = 12+        private const val GCM_TAG_BITS = 128+        private const val TAG = "CodeTokenSealer"+    }+}
code/src/test/java/com/vayunmathur/code/data/CodeTokenSealingTest.kt
diff --git a/code/src/test/java/com/vayunmathur/code/data/CodeTokenSealingTest.kt b/code/src/test/java/com/vayunmathur/code/data/CodeTokenSealingTest.ktnew file mode 100644index 0000000000..f740772a65--- /dev/null+++ b/code/src/test/java/com/vayunmathur/code/data/CodeTokenSealingTest.kt@@ -0,0 +1,91 @@+package com.vayunmathur.code.data++import androidx.test.core.app.ApplicationProvider+import javax.crypto.spec.SecretKeySpec+import kotlinx.coroutines.flow.first+import kotlinx.coroutines.runBlocking+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import kotlin.test.AfterTest+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertNull+import kotlin.test.assertTrue++/** Sealing contract for the git token: sealed at rest, legacy migration, fail-closed reads. */+@RunWith(RobolectricTestRunner::class)+class CodeTokenSealingTest {++    private val ctx get() = ApplicationProvider.getApplicationContext<android.content.Context>()++    /** Writes values verbatim, so tests can plant legacy plaintext / foreign sealed values. */+    private object PassThroughSealer : TokenSealer {+        override fun seal(plain: String): String = plain+        override fun unseal(stored: String): String = stored+        override fun isSealed(stored: String): Boolean = false+    }++    /** Unseals only [FakeTokenSealer] output; plain values fail — proves a rewrite happened. */+    private object StrictSealer : TokenSealer {+        override fun seal(plain: String): String = "v1:fake:$plain"+        override fun unseal(stored: String): String? =+            if (stored.startsWith("v1:fake:")) stored.removePrefix("v1:fake:") else null+        override fun isSealed(stored: String): Boolean = stored.startsWith("v1:")+    }++    @AfterTest fun removeFakeSealer() {+        EditorPrefs.sealerForTest = null+    }++    @Test fun `git token round trips sealed and clears to empty`() = runBlocking {+        EditorPrefs.sealerForTest = FakeTokenSealer()+        val prefs = EditorPrefs(ctx)+        prefs.setGitToken("ghp_secret")+        assertEquals("ghp_secret", prefs.gitToken.first())+        prefs.setGitToken("")+        assertEquals("", prefs.gitToken.first())+    }++    @Test fun `legacy plaintext git token migrates to sealed on first read`() = runBlocking {+        EditorPrefs.sealerForTest = PassThroughSealer+        val prefs = EditorPrefs(ctx)+        prefs.setGitToken("legacy-pat")+        EditorPrefs.sealerForTest = FakeTokenSealer()+        assertEquals("legacy-pat", prefs.gitToken.first())+        // Migration rewrite is fire-and-forget from the Flow; poll with a sealer that+        // rejects plaintext outright — success proves the stored value is now sealed.+        EditorPrefs.sealerForTest = StrictSealer+        val deadline = System.currentTimeMillis() + 10_000+        var migrated = ""+        while (System.currentTimeMillis() < deadline) {+            migrated = prefs.gitToken.first()+            if (migrated == "legacy-pat") break+            Thread.sleep(50)+        }+        assertEquals("legacy-pat", migrated)+        EditorPrefs.sealerForTest = FakeTokenSealer()+        prefs.setGitToken("")+    }++    @Test fun `unsealable sealed git token reads as signed out`() = runBlocking {+        EditorPrefs.sealerForTest = PassThroughSealer+        val prefs = EditorPrefs(ctx)+        prefs.setGitToken("v1:foreign-sealed-value")+        EditorPrefs.sealerForTest = FakeTokenSealer()+        assertEquals("", prefs.gitToken.first())+        prefs.setGitToken("")+    }++    @Test fun `keystore sealer round trips with a software key and fails closed`() {+        val sealer = KeystoreTokenSealer("test_alias")+        sealer.secretKeyForTest = SecretKeySpec(ByteArray(32) { (it * 7 + 1).toByte() }, "AES")+        val sealed = sealer.seal("hello-token")!!+        assertTrue(sealer.isSealed(sealed))+        assertFalse(sealed.contains("hello-token"))+        assertEquals("hello-token", sealer.unseal(sealed))+        assertEquals("plain-legacy", sealer.unseal("plain-legacy"))+        assertFalse(sealer.isSealed("plain-legacy"))+        assertNull(sealer.unseal(sealed.dropLast(4) + "AAAA"))+    }+}
code/src/test/java/com/vayunmathur/code/data/FakeTokenSealer.kt
diff --git a/code/src/test/java/com/vayunmathur/code/data/FakeTokenSealer.kt b/code/src/test/java/com/vayunmathur/code/data/FakeTokenSealer.ktnew file mode 100644index 0000000000..bce7767232--- /dev/null+++ b/code/src/test/java/com/vayunmathur/code/data/FakeTokenSealer.kt@@ -0,0 +1,23 @@+package com.vayunmathur.code.data++/**+ * Host-test [TokenSealer]: Robolectric has no AndroidKeyStore, so tests seal with a+ * reversible marker transform instead of AES-GCM. Mirrors the real sealer's contract —+ * sealed values carry the `v1:` prefix, legacy values pass through, foreign sealed+ * values fail (null) rather than passing through.+ */+class FakeTokenSealer : TokenSealer {+    override fun seal(plain: String): String = SEALED_PREFIX + plain++    override fun unseal(stored: String): String? = when {+        stored.startsWith(SEALED_PREFIX) -> stored.removePrefix(SEALED_PREFIX)+        isSealed(stored) -> null+        else -> stored+    }++    override fun isSealed(stored: String): Boolean = stored.startsWith(KeystoreTokenSealer.PREFIX)++    private companion object {+        private const val SEALED_PREFIX = "v1:fake:"+    }+}
communicate/src/main/java/com/vayunmathur/communicate/data/SecretSealer.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/data/SecretSealer.kt b/communicate/src/main/java/com/vayunmathur/communicate/data/SecretSealer.ktnew file mode 100644index 0000000000..8a54b3a912--- /dev/null+++ b/communicate/src/main/java/com/vayunmathur/communicate/data/SecretSealer.kt@@ -0,0 +1,125 @@+package com.vayunmathur.communicate.data++import android.security.keystore.KeyGenParameterSpec+import android.security.keystore.KeyProperties+import android.util.Base64+import com.vayunmathur.library.log.Log+import java.security.KeyStore+import javax.crypto.Cipher+import javax.crypto.KeyGenerator+import javax.crypto.SecretKey+import javax.crypto.spec.GCMParameterSpec++/**+ * Seal/unseal for communicate's persisted secrets, mirroring everysync's+ * `TokenStore`: AES-GCM with a non-exportable AndroidKeyStore key, ciphertext+ * prefixed with its 12-byte GCM IV. The stored string form is+ * `"v1:" + Base64(iv || ciphertext)` so a sealed value is unambiguously+ * distinguishable from a legacy plaintext value (which never carries the+ * prefix) — that distinction is what makes migration-on-first-read possible.+ *+ * Failure contract (all stores using this):+ * - [seal] returns null on failure; callers must not fall back to plaintext.+ * - [unseal] returns null on failure (bad prefix, bad Base64, GCM tag+ *   mismatch, missing key); callers return signed-out / not-registered and+ *   must leave the stored blob untouched for a later retry.+ */+interface SecretSealer {+    /** Sealed form of [plain], or null if sealing failed. */+    fun seal(plain: String): String?++    /** Plaintext for a value produced by [seal], or null if it cannot be unsealed. */+    fun unseal(sealed: String): String?++    /** True if [value] carries the sealed prefix (regardless of whether it decrypts). */+    fun isSealed(value: String): Boolean+}++/**+ * AndroidKeyStore-backed [SecretSealer] (everysync `TokenStore` pattern, same+ * alias style / transformation / IV-prefix layout, communicate-scoped alias).+ */+class KeystoreSecretSealer : SecretSealer {++    /** Test seam: a software key replacing the AndroidKeyStore key (which Robolectric lacks). */+    internal var secretKeyForTest: SecretKey? = null++    // Ephemeral software key, used only when AndroidKeyStore is unavailable+    // (JVM/Robolectric tests). On a real device the Keystore path always+    // succeeds, so production secrets never touch this key; if it were ever+    // used on-device, its loss on process death yields unseal-failure+    // (signed-out, blob intact), never plaintext.+    @Volatile+    private var softwareFallbackKey: SecretKey? = null++    private fun secretKey(): SecretKey {+        secretKeyForTest?.let { return it }+        try {+            val ks = KeyStore.getInstance(ANDROID_KEYSTORE).apply { load(null) }+            (ks.getEntry(KEY_ALIAS, null) as? KeyStore.SecretKeyEntry)?.let { return it.secretKey }+            val generator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, ANDROID_KEYSTORE)+            generator.init(+                KeyGenParameterSpec.Builder(+                    KEY_ALIAS,+                    KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT,+                )+                    .setBlockModes(KeyProperties.BLOCK_MODE_GCM)+                    .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE)+                    .build(),+            )+            return generator.generateKey()+        } catch (expected: Exception) {+            Log.error(TAG, "AndroidKeyStore unavailable, using ephemeral software key", expected)+            return softwareFallbackKey ?: synchronized(this) {+                softwareFallbackKey ?: KeyGenerator.getInstance("AES").apply { init(256) }+                    .generateKey().also { softwareFallbackKey = it }+            }+        }+    }++    override fun seal(plain: String): String? = try {+        val cipher = Cipher.getInstance(TRANSFORMATION)+        cipher.init(Cipher.ENCRYPT_MODE, secretKey())+        val iv = cipher.iv+        val ct = cipher.doFinal(plain.toByteArray(Charsets.UTF_8))+        val blob = ByteArray(iv.size + ct.size).also {+            iv.copyInto(it, 0)+            ct.copyInto(it, iv.size)+        }+        SEALED_PREFIX + Base64.encodeToString(blob, Base64.NO_WRAP)+    } catch (expected: Exception) {+        Log.error(TAG, "Failed to seal secret", expected)+        null+    }++    override fun unseal(sealed: String): String? {+        if (!isSealed(sealed)) return null+        return try {+            val blob = Base64.decode(sealed.removePrefix(SEALED_PREFIX), Base64.NO_WRAP)+            if (blob.size <= GCM_IV_LEN) return null+            val iv = blob.copyOfRange(0, GCM_IV_LEN)+            val ct = blob.copyOfRange(GCM_IV_LEN, blob.size)+            val cipher = Cipher.getInstance(TRANSFORMATION)+            cipher.init(Cipher.DECRYPT_MODE, secretKey(), GCMParameterSpec(GCM_TAG_BITS, iv))+            String(cipher.doFinal(ct), Charsets.UTF_8)+        } catch (expected: Exception) {+            Log.error(TAG, "Failed to unseal secret", expected)+            null+        }+    }++    override fun isSealed(value: String): Boolean = value.startsWith(SEALED_PREFIX)++    companion object {+        private const val ANDROID_KEYSTORE = "AndroidKeyStore"+        private const val KEY_ALIAS = "communicate_secret_key"+        private const val TRANSFORMATION = "AES/GCM/NoPadding"+        private const val GCM_IV_LEN = 12+        private const val GCM_TAG_BITS = 128+        private const val SEALED_PREFIX = "v1:"+        private const val TAG = "SecretSealer"++        /** Process-wide instance shared by all communicate secret stores. */+        val shared: KeystoreSecretSealer = KeystoreSecretSealer()+    }+}
communicate/src/test/java/com/vayunmathur/communicate/data/SecretSealingTest.kt
diff --git a/communicate/src/test/java/com/vayunmathur/communicate/data/SecretSealingTest.kt b/communicate/src/test/java/com/vayunmathur/communicate/data/SecretSealingTest.ktnew file mode 100644index 0000000000..5346ce2754--- /dev/null+++ b/communicate/src/test/java/com/vayunmathur/communicate/data/SecretSealingTest.kt@@ -0,0 +1,266 @@+package com.vayunmathur.communicate.data++import android.content.Context+import android.util.Base64+import androidx.core.content.edit+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.communicate.data.googlevoice.GoogleVoiceSession+import com.vayunmathur.communicate.data.signal.SignalAuthData+import com.vayunmathur.communicate.data.whatsapp.WhatsAppAuthData+import com.vayunmathur.library.util.DataStoreUtils+import kotlinx.coroutines.test.runTest+import kotlinx.serialization.encodeToString+import kotlinx.serialization.json.Json as KotlinJson+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertNotEquals+import kotlin.test.assertNull+import kotlin.test.assertTrue++/**+ * Token-sealing migration for communicate's three plain secret stores.+ * Uses a deterministic fake [SecretSealer] (AndroidKeyStore is unavailable+ * under Robolectric, mirroring everysync TokenStore's software-key seam):+ * sealed form is `"v1:" + Base64(plain)`, so tests can assert on the raw+ * persisted bytes without real crypto.+ */+@RunWith(RobolectricTestRunner::class)+class SecretSealingTest {++    private class FakeSealer(+        var failSeal: Boolean = false,+        var failUnseal: Boolean = false,+    ) : SecretSealer {+        override fun seal(plain: String): String? =+            if (failSeal) null else "v1:" + Base64.encodeToString(plain.toByteArray(), Base64.NO_WRAP)++        override fun unseal(sealed: String): String? {+            if (failUnseal || !isSealed(sealed)) return null+            return try {+                String(Base64.decode(sealed.removePrefix("v1:"), Base64.NO_WRAP))+            } catch (_: Exception) {+                null+            }+        }++        override fun isSealed(value: String): Boolean = value.startsWith("v1:")+    }++    private val context: Context get() = ApplicationProvider.getApplicationContext()++    // ---------- Google Voice ----------++    private fun gvSession(sealer: SecretSealer) =+        GoogleVoiceSession(DataStoreUtils.getInstance(context), sealer)++    @Test+    fun googleVoice_saveSealsAllThreeSecrets() = runTest {+        val sealer = FakeSealer()+        val session = gvSession(sealer)+        session.signOut()+        session.save(cookieHeader = "SAPISID=sid9; OTHER=1", apiKey = "key1", authUser = "2")+        val store = DataStoreUtils.getInstance(context)+        for (key in listOf("gv_cookie", "gv_sapisid", "gv_api_key")) {+            val raw = store.getStringAwait(key)+            assertTrue(raw != null && sealer.isSealed(raw), "$key must be sealed, was $raw")+        }+        assertEquals("SAPISID=sid9; OTHER=1", session.cookieHeader())+        assertEquals("sid9", session.sapisid())+        assertEquals("key1", session.apiKey())+        assertTrue(session.hasUsableCredentials())+    }++    @Test+    fun googleVoice_legacyPlaintextMigratesOnFirstReadIdempotently() = runTest {+        val sealer = FakeSealer()+        val store = DataStoreUtils.getInstance(context)+        gvSession(sealer).signOut()+        store.setString("gv_cookie", "SAPISID=old; OTHER=1")+        store.setString("gv_sapisid", "old")+        store.setString("gv_api_key", "oldkey")+        val session = gvSession(sealer)+        assertEquals("SAPISID=old; OTHER=1", session.cookieHeader())+        assertEquals("old", session.sapisid())+        assertEquals("oldkey", session.apiKey())+        val afterFirst = listOf("gv_cookie", "gv_sapisid", "gv_api_key").map { store.getStringAwait(it) }+        assertTrue(afterFirst.all { it != null && sealer.isSealed(it) })+        // Second read: no rewrite, same values.+        assertEquals("SAPISID=old; OTHER=1", session.cookieHeader())+        assertEquals(afterFirst, listOf("gv_cookie", "gv_sapisid", "gv_api_key").map { store.getStringAwait(it) })+    }++    @Test+    fun googleVoice_unsealFailureIsSignedOutAndLeavesBlobIntact() = runTest {+        val store = DataStoreUtils.getInstance(context)+        gvSession(FakeSealer()).signOut()+        store.setString("gv_cookie", "v1:not-valid-base64!!!")+        store.setString("gv_api_key", "v1:AAAA")+        val session = gvSession(FakeSealer(failUnseal = true))+        assertNull(session.cookieHeader())+        assertNull(session.apiKey())+        assertFalse(session.hasUsableCredentials())+        assertEquals("v1:not-valid-base64!!!", store.getStringAwait("gv_cookie"))+        assertEquals("v1:AAAA", store.getStringAwait("gv_api_key"))+    }++    @Test+    fun googleVoice_sealFailureWritesNoPlaintext() = runTest {+        val session = gvSession(FakeSealer(failSeal = true))+        session.signOut()+        session.save(cookieHeader = "SAPISID=s; O=1", apiKey = "k", authUser = "0")+        val store = DataStoreUtils.getInstance(context)+        assertNull(store.getStringAwait("gv_cookie"))+        assertNull(store.getStringAwait("gv_api_key"))+    }++    // ---------- WhatsApp ----------++    private fun waPrefs() = context.getSharedPreferences("communicate_whatsapp_auth", Context.MODE_PRIVATE)+    private fun waRaw(): String? = waPrefs().getString("auth_data", null)++    private fun sampleWhatsApp() = WhatsAppAuthData(+        phoneNumber = "+15551234567", pushName = "Ada", wid = "[email protected]",+        noisePrivateKey = "np", noisePublicKey = "nP", identityPrivateKey = "ip", identityPublicKey = "iP",+        registrationId = 7, signedPreKeyId = 3, signedPreKeyPublic = "sp", signedPreKeyPrivate = "sP",+        signedPreKeySignature = "sig", registered = true,+    )++    @Test+    fun whatsApp_saveSealsWholeJsonAndLoadsBack() {+        val sealer = FakeSealer()+        WhatsAppAuthData.clear(context)+        WhatsAppAuthData.save(context, sampleWhatsApp(), sealer)+        val raw = waRaw()+        assertTrue(raw != null && sealer.isSealed(raw))+        assertFalse(raw!!.contains("identityPrivateKey"))+        assertEquals(sampleWhatsApp(), WhatsAppAuthData.load(context, sealer))+    }++    @Test+    fun whatsApp_legacyPlaintextMigratesOnlyAfterSuccessfulParse() {+        val sealer = FakeSealer()+        val legacyJson = KotlinJson.encodeToString(sampleWhatsApp())+        waPrefs().edit { putString("auth_data", legacyJson) }+        assertEquals(sampleWhatsApp(), WhatsAppAuthData.load(context, sealer))+        val migrated = waRaw()+        assertTrue(migrated != null && sealer.isSealed(migrated))+        // Idempotent second load.+        assertEquals(sampleWhatsApp(), WhatsAppAuthData.load(context, sealer))+        assertEquals(migrated, waRaw())+    }++    @Test+    fun whatsApp_legacyCorruptJsonIsNotOverwritten() {+        waPrefs().edit { putString("auth_data", "{not json") }+        assertNull(WhatsAppAuthData.load(context, FakeSealer()))+        assertEquals("{not json", waRaw())+    }++    @Test+    fun whatsApp_unsealFailureIsSignedOutAndLeavesBlobIntact() {+        val sealer = FakeSealer()+        WhatsAppAuthData.save(context, sampleWhatsApp(), sealer)+        val sealed = waRaw()+        assertNull(WhatsAppAuthData.load(context, FakeSealer(failUnseal = true)))+        assertEquals(sealed, waRaw())+        // Sealed-but-unparseable plaintext also fails without touching the blob.+        waPrefs().edit { putString("auth_data", FakeSealer().seal("{nope")) }+        val badSealed = waRaw()+        assertNull(WhatsAppAuthData.load(context, FakeSealer()))+        assertEquals(badSealed, waRaw())+    }++    @Test+    fun whatsApp_sealFailureWritesNothing() {+        WhatsAppAuthData.clear(context)+        WhatsAppAuthData.save(context, sampleWhatsApp(), FakeSealer(failSeal = true))+        assertNull(waRaw())+    }++    // ---------- Signal (most careful: identity keys, never destroy blob) ----------++    private fun sigPrefs() = context.getSharedPreferences("communicate_signal_auth", Context.MODE_PRIVATE)+    private fun sigRaw(): String? = sigPrefs().getString("auth_data", null)++    private fun sampleSignal() = SignalAuthData(+        phoneNumber = "+15551234567", aci = "aci-1", identityPrivateKey = "id-priv",+        identityPublicKey = "id-pub", aciIdentityPrivateKey = "aci-priv", aciIdentityPublicKey = "aci-pub",+        registrationId = 9, password = "pw", registered = true,+    )++    @Test+    fun signal_saveSealsWholeJsonAndLoadsBack() {+        val sealer = FakeSealer()+        SignalAuthData.clear(context)+        SignalAuthData.save(context, sampleSignal(), sealer)+        val raw = sigRaw()+        assertTrue(raw != null && sealer.isSealed(raw))+        assertFalse(raw!!.contains("aci-priv"))+        assertEquals(sampleSignal(), SignalAuthData.load(context, sealer))+    }++    @Test+    fun signal_legacyPlaintextMigratesOnlyAfterSuccessfulParse() {+        val sealer = FakeSealer()+        val legacyJson = KotlinJson.encodeToString(sampleSignal())+        sigPrefs().edit { putString("auth_data", legacyJson) }+        assertEquals(sampleSignal(), SignalAuthData.load(context, sealer))+        val migrated = sigRaw()+        assertTrue(migrated != null && sealer.isSealed(migrated))+        assertEquals(sampleSignal(), SignalAuthData.load(context, sealer))+        assertEquals(migrated, sigRaw())+    }++    @Test+    fun signal_legacyCorruptJsonIsNotOverwritten() {+        sigPrefs().edit { putString("auth_data", "{not json") }+        assertNull(SignalAuthData.load(context, FakeSealer()))+        assertEquals("{not json", sigRaw())+    }++    @Test+    fun signal_unsealFailureBehavesNotRegisteredAndNeverDestroysBlob() {+        val sealer = FakeSealer()+        SignalAuthData.save(context, sampleSignal(), sealer)+        val sealed = sigRaw()+        assertNotEquals(null, sealed)+        // Every failure mode returns null and leaves the blob byte-identical,+        // so identity-key material survives for retry on the next launch.+        assertNull(SignalAuthData.load(context, FakeSealer(failUnseal = true)))+        assertEquals(sealed, sigRaw())+        sigPrefs().edit { putString("auth_data", "v1:!!!corrupt") }+        assertNull(SignalAuthData.load(context, FakeSealer()))+        assertEquals("v1:!!!corrupt", sigRaw())+        sigPrefs().edit { putString("auth_data", FakeSealer().seal("{nope")) }+        val badSealed = sigRaw()+        assertNull(SignalAuthData.load(context, FakeSealer()))+        assertEquals(badSealed, sigRaw())+        // And a later load with a working sealer still recovers the original.+        sigPrefs().edit { putString("auth_data", sealed) }+        assertEquals(sampleSignal(), SignalAuthData.load(context, sealer))+    }++    @Test+    fun signal_sealFailureWritesNothing() {+        SignalAuthData.clear(context)+        SignalAuthData.save(context, sampleSignal(), FakeSealer(failSeal = true))+        assertNull(sigRaw())+    }++    // ---------- Real Keystore sealer shape (software fallback under Robolectric) ----------++    @Test+    fun keystoreSealer_roundTripsAndDistinguishesLegacy() {+        val sealer = KeystoreSecretSealer.shared+        val sealed = sealer.seal("secret-value")+        assertTrue(sealed != null && sealer.isSealed(sealed))+        assertFalse(sealed!!.contains("secret-value"))+        assertEquals("secret-value", sealer.unseal(sealed))+        assertFalse(sealer.isSealed("secret-value"))+        assertNull(sealer.unseal("secret-value"))+        assertNull(sealer.unseal("v1:!!!"))+    }+}
fooddelivery/src/main/java/com/vayunmathur/fooddelivery/platform/TokenSealer.kt
diff --git a/fooddelivery/src/main/java/com/vayunmathur/fooddelivery/platform/TokenSealer.kt b/fooddelivery/src/main/java/com/vayunmathur/fooddelivery/platform/TokenSealer.ktnew file mode 100644index 0000000000..d74426a8b0--- /dev/null+++ b/fooddelivery/src/main/java/com/vayunmathur/fooddelivery/platform/TokenSealer.kt@@ -0,0 +1,117 @@+package com.vayunmathur.fooddelivery.platform++import android.security.keystore.KeyGenParameterSpec+import android.security.keystore.KeyProperties+import com.vayunmathur.library.log.Log+import java.security.KeyStore+import javax.crypto.Cipher+import javax.crypto.KeyGenerator+import javax.crypto.SecretKey+import javax.crypto.spec.GCMParameterSpec+import kotlin.io.encoding.Base64++/**+ * Seals a secret string for at-rest storage and unseals it on read.+ *+ * Sealed values carry the [KeystoreTokenSealer.PREFIX] marker so callers can tell them+ * apart from legacy plaintext written before sealing existed: [unseal] returns a+ * non-sealed value unchanged (it is legacy plain), while a sealed value that cannot be+ * decrypted (wrong device after a backup restore, rotated/lost Keystore key) yields+ * null — callers must treat that as signed-out, never crash and never fall back to+ * using the ciphertext as the secret.+ */+interface TokenSealer {+    /** Sealed form of [plain], or null when sealing failed (caller must not persist plain). */+    fun seal(plain: String): String?++    /** Plain form of [stored]; legacy non-sealed values pass through, failures give null. */+    fun unseal(stored: String): String?++    /** True when [stored] carries the sealed marker (whether or not it still decrypts). */+    fun isSealed(stored: String): Boolean+}++/**+ * [TokenSealer] backed by a non-exportable AES key in the Android Keystore, copied from+ * everysync's TokenStore: AES/GCM/NoPadding, the 12-byte GCM IV prefixed to the+ * ciphertext, the whole blob Base64-encoded behind [PREFIX] for string storage. The+ * Keystore key never leaves the device, so a sealed value carried off-device by backup+ * or device transfer is undecryptable on the destination.+ */+class KeystoreTokenSealer(private val keyAlias: String) : TokenSealer {++    /** Test seam: a software key replacing the AndroidKeyStore key (which Robolectric lacks). */+    internal var secretKeyForTest: SecretKey? = null++    private fun secretKey(): SecretKey {+        secretKeyForTest?.let { return it }+        val ks = KeyStore.getInstance(ANDROID_KEYSTORE).apply { load(null) }+        (ks.getEntry(keyAlias, null) as? KeyStore.SecretKeyEntry)?.let { return it.secretKey }+        val generator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, ANDROID_KEYSTORE)+        generator.init(+            KeyGenParameterSpec.Builder(+                keyAlias,+                KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT,+            )+                .setBlockModes(KeyProperties.BLOCK_MODE_GCM)+                .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE)+                .build(),+        )+        return generator.generateKey()+    }++    private fun encrypt(plain: ByteArray): ByteArray {+        val cipher = Cipher.getInstance(TRANSFORMATION)+        cipher.init(Cipher.ENCRYPT_MODE, secretKey())+        val iv = cipher.iv+        val ct = cipher.doFinal(plain)+        // Prefix the 12-byte GCM IV so we can recover it on decrypt.+        return ByteArray(iv.size + ct.size).also {+            iv.copyInto(it, 0)+            ct.copyInto(it, iv.size)+        }+    }++    private fun decrypt(blob: ByteArray): ByteArray {+        val iv = blob.copyOfRange(0, GCM_IV_LEN)+        val ct = blob.copyOfRange(GCM_IV_LEN, blob.size)+        val cipher = Cipher.getInstance(TRANSFORMATION)+        cipher.init(Cipher.DECRYPT_MODE, secretKey(), GCMParameterSpec(GCM_TAG_BITS, iv))+        return cipher.doFinal(ct)+    }++    override fun seal(plain: String): String? = try {+        PREFIX + Base64.encode(encrypt(plain.toByteArray(Charsets.UTF_8)))+    } catch (expected: Exception) {+        Log.error(TAG, "Failed to seal token", expected)+        null+    }++    override fun unseal(stored: String): String? {+        if (!isSealed(stored)) return stored+        return try {+            val blob = Base64.decode(stored.removePrefix(PREFIX))+            if (blob.size <= GCM_IV_LEN) {+                null+            } else {+                String(decrypt(blob), Charsets.UTF_8)+            }+        } catch (expected: Exception) {+            Log.error(TAG, "Failed to unseal token", expected)+            null+        }+    }++    override fun isSealed(stored: String): Boolean = stored.startsWith(PREFIX)++    /** Keystore constants for sealed token storage. */+    companion object {+        /** Marker distinguishing sealed values from legacy plaintext. */+        const val PREFIX = "v1:"+        private const val ANDROID_KEYSTORE = "AndroidKeyStore"+        private const val TRANSFORMATION = "AES/GCM/NoPadding"+        private const val GCM_IV_LEN = 12+        private const val GCM_TAG_BITS = 128+        private const val TAG = "FoodDeliveryTokenSealer"+    }+}
fooddelivery/src/test/java/com/vayunmathur/fooddelivery/platform/AppInitTokenSealingTest.kt
diff --git a/fooddelivery/src/test/java/com/vayunmathur/fooddelivery/platform/AppInitTokenSealingTest.kt b/fooddelivery/src/test/java/com/vayunmathur/fooddelivery/platform/AppInitTokenSealingTest.ktnew file mode 100644index 0000000000..c7ba404c9b--- /dev/null+++ b/fooddelivery/src/test/java/com/vayunmathur/fooddelivery/platform/AppInitTokenSealingTest.kt@@ -0,0 +1,75 @@+package com.vayunmathur.fooddelivery.platform++import android.content.Context+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.fooddelivery.data.AuthToken+import com.vayunmathur.fooddelivery.network.BitesAuth+import javax.crypto.spec.SecretKeySpec+import kotlinx.coroutines.runBlocking+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import kotlin.test.AfterTest+import kotlin.test.BeforeTest+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertNull+import kotlin.test.assertTrue++/**+ * Sealing contract for the persisted auth token, exercised through [AppInit]'s+ * restore/persist callbacks (the warm-up path cold-process services rely on).+ * AppInit.start is once-per-process, so the restore assertions share one test.+ */+@RunWith(RobolectricTestRunner::class)+class AppInitTokenSealingTest {++    private val ctx: Context get() = ApplicationProvider.getApplicationContext()+    private val prefs get() = ctx.getSharedPreferences("fooddelivery_prefs", Context.MODE_PRIVATE)++    private val legacyJson =+        """{"access_token":"legacy-access","refresh_token":"legacy-refresh",""" ++            """"token_type":"Bearer","expires_in":3600,"expires_at_ms":9999999999999}"""++    @BeforeTest fun installFakeSealer() {+        AppInit.sealerForTest = FakeTokenSealer()+        BitesAuth.clearToken()+        prefs.edit().clear().commit()+    }++    @AfterTest fun removeFakeSealer() {+        BitesAuth.clearToken()+        prefs.edit().clear().commit()+        AppInit.sealerForTest = null+    }++    @Test fun `legacy token restores and migrates sealed, updates persist sealed`() = runBlocking {+        prefs.edit().putString("token_json", legacyJson).commit()+        AppInit.start(ctx)+        AppInit.awaitReady()+        // Legacy plaintext was restored (signed in) and rewritten sealed in place.+        assertTrue(BitesAuth.isLoggedIn())+        val migrated = prefs.getString("token_json", null)!!+        assertTrue(migrated.startsWith("v1:"), "legacy token must be rewritten sealed, was: $migrated")+        // Persist callback seals: a fresh sign-in never writes plaintext.+        BitesAuth.setToken(AuthToken("fresh-access", "fresh-refresh", "Bearer", 3600))+        val persisted = prefs.getString("token_json", null)!!+        assertTrue(persisted.startsWith("v1:"), "persisted token must be sealed, was: $persisted")+        // Sign-out removal still clears the key.+        BitesAuth.clearToken()+        assertNull(prefs.getString("token_json", null))+        assertFalse(BitesAuth.isLoggedIn())+    }++    @Test fun `keystore sealer round trips with a software key and fails closed`() {+        val sealer = KeystoreTokenSealer("test_alias")+        sealer.secretKeyForTest = SecretKeySpec(ByteArray(32) { (it * 7 + 1).toByte() }, "AES")+        val sealed = sealer.seal("hello-token")!!+        assertTrue(sealer.isSealed(sealed))+        assertFalse(sealed.contains("hello-token"))+        assertEquals("hello-token", sealer.unseal(sealed))+        assertEquals("plain-legacy", sealer.unseal("plain-legacy"))+        assertFalse(sealer.isSealed("plain-legacy"))+        assertNull(sealer.unseal(sealed.dropLast(4) + "AAAA"))+    }+}
fooddelivery/src/test/java/com/vayunmathur/fooddelivery/platform/FakeTokenSealer.kt
diff --git a/fooddelivery/src/test/java/com/vayunmathur/fooddelivery/platform/FakeTokenSealer.kt b/fooddelivery/src/test/java/com/vayunmathur/fooddelivery/platform/FakeTokenSealer.ktnew file mode 100644index 0000000000..4fd8635fa5--- /dev/null+++ b/fooddelivery/src/test/java/com/vayunmathur/fooddelivery/platform/FakeTokenSealer.kt@@ -0,0 +1,23 @@+package com.vayunmathur.fooddelivery.platform++/**+ * Host-test [TokenSealer]: Robolectric has no AndroidKeyStore, so tests seal with a+ * reversible marker transform instead of AES-GCM. Mirrors the real sealer's contract —+ * sealed values carry the `v1:` prefix, legacy values pass through, foreign sealed+ * values fail (null) rather than passing through.+ */+class FakeTokenSealer : TokenSealer {+    override fun seal(plain: String): String = SEALED_PREFIX + plain++    override fun unseal(stored: String): String? = when {+        stored.startsWith(SEALED_PREFIX) -> stored.removePrefix(SEALED_PREFIX)+        isSealed(stored) -> null+        else -> stored+    }++    override fun isSealed(stored: String): Boolean = stored.startsWith(KeystoreTokenSealer.PREFIX)++    private companion object {+        private const val SEALED_PREFIX = "v1:fake:"+    }+}
games/chess/src/main/java/com/vayunmathur/games/chess/auth/TokenSealer.kt
diff --git a/games/chess/src/main/java/com/vayunmathur/games/chess/auth/TokenSealer.kt b/games/chess/src/main/java/com/vayunmathur/games/chess/auth/TokenSealer.ktnew file mode 100644index 0000000000..a2676a2b40--- /dev/null+++ b/games/chess/src/main/java/com/vayunmathur/games/chess/auth/TokenSealer.kt@@ -0,0 +1,117 @@+package com.vayunmathur.games.chess.auth++import android.security.keystore.KeyGenParameterSpec+import android.security.keystore.KeyProperties+import com.vayunmathur.library.log.Log+import java.security.KeyStore+import javax.crypto.Cipher+import javax.crypto.KeyGenerator+import javax.crypto.SecretKey+import javax.crypto.spec.GCMParameterSpec+import kotlin.io.encoding.Base64++/**+ * Seals a secret string for at-rest storage and unseals it on read.+ *+ * Sealed values carry the [KeystoreTokenSealer.PREFIX] marker so callers can tell them+ * apart from legacy plaintext written before sealing existed: [unseal] returns a+ * non-sealed value unchanged (it is legacy plain), while a sealed value that cannot be+ * decrypted (wrong device after a backup restore, rotated/lost Keystore key) yields+ * null — callers must treat that as signed-out, never crash and never fall back to+ * using the ciphertext as the secret.+ */+interface TokenSealer {+    /** Sealed form of [plain], or null when sealing failed (caller must not persist plain). */+    fun seal(plain: String): String?++    /** Plain form of [stored]; legacy non-sealed values pass through, failures give null. */+    fun unseal(stored: String): String?++    /** True when [stored] carries the sealed marker (whether or not it still decrypts). */+    fun isSealed(stored: String): Boolean+}++/**+ * [TokenSealer] backed by a non-exportable AES key in the Android Keystore, copied from+ * everysync's TokenStore: AES/GCM/NoPadding, the 12-byte GCM IV prefixed to the+ * ciphertext, the whole blob Base64-encoded behind [PREFIX] for string storage. The+ * Keystore key never leaves the device, so a sealed value carried off-device by backup+ * or device transfer is undecryptable on the destination.+ */+class KeystoreTokenSealer(private val keyAlias: String) : TokenSealer {++    /** Test seam: a software key replacing the AndroidKeyStore key (which Robolectric lacks). */+    internal var secretKeyForTest: SecretKey? = null++    private fun secretKey(): SecretKey {+        secretKeyForTest?.let { return it }+        val ks = KeyStore.getInstance(ANDROID_KEYSTORE).apply { load(null) }+        (ks.getEntry(keyAlias, null) as? KeyStore.SecretKeyEntry)?.let { return it.secretKey }+        val generator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, ANDROID_KEYSTORE)+        generator.init(+            KeyGenParameterSpec.Builder(+                keyAlias,+                KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT,+            )+                .setBlockModes(KeyProperties.BLOCK_MODE_GCM)+                .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE)+                .build(),+        )+        return generator.generateKey()+    }++    private fun encrypt(plain: ByteArray): ByteArray {+        val cipher = Cipher.getInstance(TRANSFORMATION)+        cipher.init(Cipher.ENCRYPT_MODE, secretKey())+        val iv = cipher.iv+        val ct = cipher.doFinal(plain)+        // Prefix the 12-byte GCM IV so we can recover it on decrypt.+        return ByteArray(iv.size + ct.size).also {+            iv.copyInto(it, 0)+            ct.copyInto(it, iv.size)+        }+    }++    private fun decrypt(blob: ByteArray): ByteArray {+        val iv = blob.copyOfRange(0, GCM_IV_LEN)+        val ct = blob.copyOfRange(GCM_IV_LEN, blob.size)+        val cipher = Cipher.getInstance(TRANSFORMATION)+        cipher.init(Cipher.DECRYPT_MODE, secretKey(), GCMParameterSpec(GCM_TAG_BITS, iv))+        return cipher.doFinal(ct)+    }++    override fun seal(plain: String): String? = try {+        PREFIX + Base64.encode(encrypt(plain.toByteArray(Charsets.UTF_8)))+    } catch (expected: Exception) {+        Log.error(TAG, "Failed to seal token", expected)+        null+    }++    override fun unseal(stored: String): String? {+        if (!isSealed(stored)) return stored+        return try {+            val blob = Base64.decode(stored.removePrefix(PREFIX))+            if (blob.size <= GCM_IV_LEN) {+                null+            } else {+                String(decrypt(blob), Charsets.UTF_8)+            }+        } catch (expected: Exception) {+            Log.error(TAG, "Failed to unseal token", expected)+            null+        }+    }++    override fun isSealed(stored: String): Boolean = stored.startsWith(PREFIX)++    /** Keystore constants for sealed token storage. */+    companion object {+        /** Marker distinguishing sealed values from legacy plaintext. */+        const val PREFIX = "v1:"+        private const val ANDROID_KEYSTORE = "AndroidKeyStore"+        private const val TRANSFORMATION = "AES/GCM/NoPadding"+        private const val GCM_IV_LEN = 12+        private const val GCM_TAG_BITS = 128+        private const val TAG = "ChessTokenSealer"+    }+}
games/chess/src/test/java/com/vayunmathur/games/chess/auth/FakeTokenSealer.kt
diff --git a/games/chess/src/test/java/com/vayunmathur/games/chess/auth/FakeTokenSealer.kt b/games/chess/src/test/java/com/vayunmathur/games/chess/auth/FakeTokenSealer.ktnew file mode 100644index 0000000000..fed76c71d2--- /dev/null+++ b/games/chess/src/test/java/com/vayunmathur/games/chess/auth/FakeTokenSealer.kt@@ -0,0 +1,23 @@+package com.vayunmathur.games.chess.auth++/**+ * Host-test [TokenSealer]: Robolectric has no AndroidKeyStore, so tests seal with a+ * reversible marker transform instead of AES-GCM. Mirrors the real sealer's contract —+ * sealed values carry the `v1:` prefix, legacy values pass through, foreign sealed+ * values fail (null) rather than passing through.+ */+class FakeTokenSealer : TokenSealer {+    override fun seal(plain: String): String = SEALED_PREFIX + plain++    override fun unseal(stored: String): String? = when {+        stored.startsWith(SEALED_PREFIX) -> stored.removePrefix(SEALED_PREFIX)+        isSealed(stored) -> null+        else -> stored+    }++    override fun isSealed(stored: String): Boolean = stored.startsWith(KeystoreTokenSealer.PREFIX)++    private companion object {+        private const val SEALED_PREFIX = "v1:fake:"+    }+}
taxi/src/main/java/com/vayunmathur/taxi/data/lyft/TokenSealer.kt
diff --git a/taxi/src/main/java/com/vayunmathur/taxi/data/lyft/TokenSealer.kt b/taxi/src/main/java/com/vayunmathur/taxi/data/lyft/TokenSealer.ktnew file mode 100644index 0000000000..3e7e371537--- /dev/null+++ b/taxi/src/main/java/com/vayunmathur/taxi/data/lyft/TokenSealer.kt@@ -0,0 +1,117 @@+package com.vayunmathur.taxi.data.lyft++import android.security.keystore.KeyGenParameterSpec+import android.security.keystore.KeyProperties+import com.vayunmathur.library.log.Log+import java.security.KeyStore+import javax.crypto.Cipher+import javax.crypto.KeyGenerator+import javax.crypto.SecretKey+import javax.crypto.spec.GCMParameterSpec+import kotlin.io.encoding.Base64++/**+ * Seals a secret string for at-rest storage and unseals it on read.+ *+ * Sealed values carry the [KeystoreTokenSealer.PREFIX] marker so callers can tell them+ * apart from legacy plaintext written before sealing existed: [unseal] returns a+ * non-sealed value unchanged (it is legacy plain), while a sealed value that cannot be+ * decrypted (wrong device after a backup restore, rotated/lost Keystore key) yields+ * null — callers must treat that as signed-out, never crash and never fall back to+ * using the ciphertext as the secret.+ */+interface TokenSealer {+    /** Sealed form of [plain], or null when sealing failed (caller must not persist plain). */+    fun seal(plain: String): String?++    /** Plain form of [stored]; legacy non-sealed values pass through, failures give null. */+    fun unseal(stored: String): String?++    /** True when [stored] carries the sealed marker (whether or not it still decrypts). */+    fun isSealed(stored: String): Boolean+}++/**+ * [TokenSealer] backed by a non-exportable AES key in the Android Keystore, copied from+ * everysync's TokenStore: AES/GCM/NoPadding, the 12-byte GCM IV prefixed to the+ * ciphertext, the whole blob Base64-encoded behind [PREFIX] for string storage. The+ * Keystore key never leaves the device, so a sealed value carried off-device by backup+ * or device transfer is undecryptable on the destination.+ */+class KeystoreTokenSealer(private val keyAlias: String) : TokenSealer {++    /** Test seam: a software key replacing the AndroidKeyStore key (which Robolectric lacks). */+    internal var secretKeyForTest: SecretKey? = null++    private fun secretKey(): SecretKey {+        secretKeyForTest?.let { return it }+        val ks = KeyStore.getInstance(ANDROID_KEYSTORE).apply { load(null) }+        (ks.getEntry(keyAlias, null) as? KeyStore.SecretKeyEntry)?.let { return it.secretKey }+        val generator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, ANDROID_KEYSTORE)+        generator.init(+            KeyGenParameterSpec.Builder(+                keyAlias,+                KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT,+            )+                .setBlockModes(KeyProperties.BLOCK_MODE_GCM)+                .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE)+                .build(),+        )+        return generator.generateKey()+    }++    private fun encrypt(plain: ByteArray): ByteArray {+        val cipher = Cipher.getInstance(TRANSFORMATION)+        cipher.init(Cipher.ENCRYPT_MODE, secretKey())+        val iv = cipher.iv+        val ct = cipher.doFinal(plain)+        // Prefix the 12-byte GCM IV so we can recover it on decrypt.+        return ByteArray(iv.size + ct.size).also {+            iv.copyInto(it, 0)+            ct.copyInto(it, iv.size)+        }+    }++    private fun decrypt(blob: ByteArray): ByteArray {+        val iv = blob.copyOfRange(0, GCM_IV_LEN)+        val ct = blob.copyOfRange(GCM_IV_LEN, blob.size)+        val cipher = Cipher.getInstance(TRANSFORMATION)+        cipher.init(Cipher.DECRYPT_MODE, secretKey(), GCMParameterSpec(GCM_TAG_BITS, iv))+        return cipher.doFinal(ct)+    }++    override fun seal(plain: String): String? = try {+        PREFIX + Base64.encode(encrypt(plain.toByteArray(Charsets.UTF_8)))+    } catch (expected: Exception) {+        Log.error(TAG, "Failed to seal token", expected)+        null+    }++    override fun unseal(stored: String): String? {+        if (!isSealed(stored)) return stored+        return try {+            val blob = Base64.decode(stored.removePrefix(PREFIX))+            if (blob.size <= GCM_IV_LEN) {+                null+            } else {+                String(decrypt(blob), Charsets.UTF_8)+            }+        } catch (expected: Exception) {+            Log.error(TAG, "Failed to unseal token", expected)+            null+        }+    }++    override fun isSealed(stored: String): Boolean = stored.startsWith(PREFIX)++    /** Keystore constants for sealed token storage. */+    companion object {+        /** Marker distinguishing sealed values from legacy plaintext. */+        const val PREFIX = "v1:"+        private const val ANDROID_KEYSTORE = "AndroidKeyStore"+        private const val TRANSFORMATION = "AES/GCM/NoPadding"+        private const val GCM_IV_LEN = 12+        private const val GCM_TAG_BITS = 128+        private const val TAG = "TaxiTokenSealer"+    }+}
taxi/src/test/java/com/vayunmathur/taxi/data/lyft/FakeTokenSealer.kt
diff --git a/taxi/src/test/java/com/vayunmathur/taxi/data/lyft/FakeTokenSealer.kt b/taxi/src/test/java/com/vayunmathur/taxi/data/lyft/FakeTokenSealer.ktnew file mode 100644index 0000000000..2a0a32216b--- /dev/null+++ b/taxi/src/test/java/com/vayunmathur/taxi/data/lyft/FakeTokenSealer.kt@@ -0,0 +1,23 @@+package com.vayunmathur.taxi.data.lyft++/**+ * Host-test [TokenSealer]: Robolectric has no AndroidKeyStore, so tests seal with a+ * reversible marker transform instead of AES-GCM. Mirrors the real sealer's contract —+ * sealed values carry the `v1:` prefix, legacy values pass through, foreign sealed+ * values fail (null) rather than passing through.+ */+class FakeTokenSealer : TokenSealer {+    override fun seal(plain: String): String = SEALED_PREFIX + plain++    override fun unseal(stored: String): String? = when {+        stored.startsWith(SEALED_PREFIX) -> stored.removePrefix(SEALED_PREFIX)+        isSealed(stored) -> null+        else -> stored+    }++    override fun isSealed(stored: String): Boolean = stored.startsWith(KeystoreTokenSealer.PREFIX)++    private companion object {+        private const val SEALED_PREFIX = "v1:fake:"+    }+}
taxi/src/test/java/com/vayunmathur/taxi/data/lyft/LyftTokenStoreSealingTest.kt
diff --git a/taxi/src/test/java/com/vayunmathur/taxi/data/lyft/LyftTokenStoreSealingTest.kt b/taxi/src/test/java/com/vayunmathur/taxi/data/lyft/LyftTokenStoreSealingTest.ktnew file mode 100644index 0000000000..8c8a6266dc--- /dev/null+++ b/taxi/src/test/java/com/vayunmathur/taxi/data/lyft/LyftTokenStoreSealingTest.kt@@ -0,0 +1,100 @@+package com.vayunmathur.taxi.data.lyft++import android.content.Context+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.taxi.network.lyft.LyftToken+import javax.crypto.spec.SecretKeySpec+import kotlinx.coroutines.runBlocking+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import kotlin.test.AfterTest+import kotlin.test.BeforeTest+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertNull+import kotlin.test.assertTrue++/** Sealing contract for Lyft tokens: sealed at persist, unseal-or-migrate at read. */+@RunWith(RobolectricTestRunner::class)+class LyftTokenStoreSealingTest {++    private val context: Context get() = ApplicationProvider.getApplicationContext()++    /** Writes values verbatim, so tests can plant legacy plaintext / foreign sealed values. */+    private object PassThroughSealer : TokenSealer {+        override fun seal(plain: String): String = plain+        override fun unseal(stored: String): String = stored+        override fun isSealed(stored: String): Boolean = false+    }++    /** Unseals only [FakeTokenSealer] output; plain values fail — proves a rewrite happened. */+    private object StrictSealer : TokenSealer {+        override fun seal(plain: String): String = "v1:fake:$plain"+        override fun unseal(stored: String): String? =+            if (stored.startsWith("v1:fake:")) stored.removePrefix("v1:fake:") else null+        override fun isSealed(stored: String): Boolean = stored.startsWith("v1:")+    }++    @BeforeTest fun installFakeSealer() {+        LyftTokenStore.sealerForTest = FakeTokenSealer()+        runBlocking { LyftTokenStore(context).clear() }+    }++    @AfterTest fun removeFakeSealer() {+        runBlocking { LyftTokenStore(context).clear() }+        LyftTokenStore.sealerForTest = null+    }++    @Test fun `tokens round trip and sign-in state follows`() = runBlocking {+        val store = LyftTokenStore(context)+        assertFalse(store.isSignedIn())+        store.save(LyftToken(accessToken = "access-tok", refreshToken = "refresh-tok", expiresIn = 3600, userId = "42"))+        assertEquals("access-tok", store.accessToken())+        assertEquals("refresh-tok", store.refreshToken())+        assertEquals("42", store.userId())+        assertTrue(store.isSignedIn())+        store.clear()+        assertNull(store.accessToken())+        assertFalse(store.isSignedIn())+    }++    @Test fun `legacy plaintext tokens migrate to sealed on read`() = runBlocking {+        LyftTokenStore.sealerForTest = PassThroughSealer+        LyftTokenStore(context).save(+            LyftToken(accessToken = "legacy-access", refreshToken = "legacy-refresh", expiresIn = 3600, userId = "7"),+        )+        LyftTokenStore.sealerForTest = FakeTokenSealer()+        val store = LyftTokenStore(context)+        assertEquals("legacy-access", store.accessToken())+        assertEquals("legacy-refresh", store.refreshToken())+        // Both reads rewrote sealed: a sealer rejecting plaintext now still reads them.+        LyftTokenStore.sealerForTest = StrictSealer+        assertEquals("legacy-access", store.accessToken())+        assertEquals("legacy-refresh", store.refreshToken())+    }++    @Test fun `unsealable sealed tokens read as signed out`() = runBlocking {+        LyftTokenStore.sealerForTest = PassThroughSealer+        LyftTokenStore(context).save(+            LyftToken(accessToken = "v1:foreign-sealed", refreshToken = "v1:foreign-refresh", expiresIn = 3600, userId = "7"),+        )+        LyftTokenStore.sealerForTest = FakeTokenSealer()+        val store = LyftTokenStore(context)+        assertNull(store.accessToken())+        assertNull(store.refreshToken())+        assertFalse(store.isSignedIn())+    }++    @Test fun `keystore sealer round trips with a software key and fails closed`() {+        val sealer = KeystoreTokenSealer("test_alias")+        sealer.secretKeyForTest = SecretKeySpec(ByteArray(32) { (it * 7 + 1).toByte() }, "AES")+        val sealed = sealer.seal("hello-token")!!+        assertTrue(sealer.isSealed(sealed))+        assertFalse(sealed.contains("hello-token"))+        assertEquals("hello-token", sealer.unseal(sealed))+        assertEquals("plain-legacy", sealer.unseal("plain-legacy"))+        assertFalse(sealer.isSealed("plain-legacy"))+        assertNull(sealer.unseal(sealed.dropLast(4) + "AAAA"))+    }+}