48bc7f6765ee

harden immutable device identity and decoy Slot-B migration (v2.17.19)

time
2026-09-10 08:10 UTC · 2 months ago
machine
koh2
agent
camel-stream/auto
session
identity trust remediation
parent
4f7099738dff
16 files VERSION+1 −1app/src/main/java/com/peachpasswords/sync/BackgroundSyncCoordinator.kt+6 −2app/src/main/java/com/peachpasswords/sync/ForegroundSyncCoordinator.kt+9 −2app/src/main/java/com/peachpasswords/sync/PairedDeviceStore.kt+80 −24app/src/main/java/com/peachpasswords/sync/PeachSyncService.kt+21 −7app/src/main/java/com/peachpasswords/sync/RelayAdoptionReceiver.kt+4 −1app/src/main/java/com/peachpasswords/sync/VaultAdopt.kt+14 −5app/src/main/java/com/peachpasswords/ui/lock/LockViewModel.kt+8 −1app/src/main/java/com/peachpasswords/ui/pairing/AdoptVaultViewModel.kt+7 −2app/src/main/java/com/peachpasswords/ui/pairing/CodePairViewModel.kt+3 −4app/src/main/java/com/peachpasswords/ui/sync/SyncViewModel.kt+48 −23app/src/main/java/com/peachpasswords/vault/VaultRepository.kt+140 −38app/src/main/java/com/peachpasswords/vault/VaultStore.kt+34 −9app/src/test/java/com/peachpasswords/sync/C7TransportTest.kt+34 −7app/src/test/java/com/peachpasswords/vault/AdoptDuressSlotTest.kt+1 −1app/src/test/java/com/peachpasswords/vault/DuressSlotBTest.kt+52 −3
VERSION+1 −1
@@ -1 +1 @@1-2.17.181+2.17.19

view file

app/src/main/java/com/peachpasswords/sync/BackgroundSyncCoordinator.kt+6 −2
@@ -25,16 +25,20 @@2525     private val stop: () -> Unit,2626     private val isUnlocked: StateFlow<Boolean>,2727     private val preferenceEnabled: StateFlow<Boolean>,28+    private val syncVaultId: () -> String? = { "unknown" },2829 ) {2930     fun setEnabled(enabled: Boolean) {30-        if (enabled) start() else stop()31+        if (enabled) {32+            if (isUnlocked.value && syncVaultId() == null) return33+            start()34+        } else stop()3135     }3236 3337     /** Fires the current value of [isUnlocked] immediately on subscription. */3438     fun observe(scope: CoroutineScope) {3539         scope.launch {3640             isUnlocked.collect { unlocked ->37-                if (unlocked && preferenceEnabled.value) start()41+                if (unlocked && preferenceEnabled.value && syncVaultId() != null) start()3842             }3943         }4044     }

view file

app/src/main/java/com/peachpasswords/sync/ForegroundSyncCoordinator.kt+9 −2
@@ -35,13 +35,20 @@3535      * See docs/sync-lan-retirement.md.3636      */3737     fun triggerForegroundSync() {38-        if (!vault.isUnlocked.value || !backgroundSync.enabled.value) return38+        if (!vault.isUnlocked.value || vault.syncVaultId() == null || !backgroundSync.enabled.value) return3939         if (foregroundSyncPeers(deviceStore.getAll()).isEmpty()) return4040         PeachSyncService.start(context)4141     }4242 43+    /** Tear down transport immediately when the active session is decoy. */44+    fun stopForDecoySession() {45+        inFlight?.cancel()46+        inFlight = null47+        PeachSyncService.stop(context)48+    }49+4350     private fun buildAdapter(): SyncVaultAdapter? {44-        if (!vault.isUnlocked.value) return null51+        if (!vault.isUnlocked.value || vault.syncVaultId() == null) return null4552         return VaultSyncAdapter(4653             repo = vault,4754             ourDeviceId = getOrCreateDeviceId(context),

view file

app/src/main/java/com/peachpasswords/sync/PairedDeviceStore.kt+80 −24
@@ -73,32 +73,46 @@7373     fun hasIdentityCollision(device: PairedDevice): Boolean =7474         hasAdoptionIdentityConflict(device, getAll(), listRevocations())7575 76-    /** Insert or replace by [PairedDevice.deviceId]. */76+    /** Insert or replace a directly re-paired device and clear its terminal revocation atomically. */77+    fun upsertAndClearRevocation(device: PairedDevice) {78+        mutationGate.withLock {79+            val currentDevices = getAll()80+            val existing = currentDevices.firstOrNull { it.deviceId == device.deviceId }81+            val bound = bindImmutableIdentity(existing, device)82+            val nextDevice = bound.copy(83+                deviceName = bound.deviceName?.let(::capDeviceName),84+                localAlias = existing?.localAlias,85+            )86+            val nextDevices = currentDevices.filterNot { it.deviceId == device.deviceId } + nextDevice87+            val currentRevocations = listRevocations()88+            val nextRevocations = currentRevocations.filterNot { it.deviceId == device.deviceId }89+            val nextPrefs = RegistryPrefsState(90+                devices = json.encodeToString(listSerializer, nextDevices),91+                revocations = json.encodeToString(revocationSerializer, nextRevocations),92+            )93+            check(commitWithRollback(readPrefsState(), nextPrefs, ::writePrefsState)) {94+                "paired_device_persist_failed"95+            }96+        }97+    }98+99+    /** Insert or replace by [PairedDevice.deviceId], without changing its cryptographic identity. */77100     override fun upsert(device: PairedDevice) {78101         mutationGate.withLock {102+            val currentDevices = getAll()103+            val existing = currentDevices.firstOrNull { it.deviceId == device.deviceId }104+            val bound = bindImmutableIdentity(existing, device)79105             // Peer-supplied names arrive capped so a hostile peer cannot grow the80106             // registry without limit (adoption + direct-pair seams land here).81-            val device = device.copy(82-                deviceName = device.deviceName?.let(::capDeviceName),83-                localAlias = get(device.deviceId)?.localAlias,107+            val nextDevice = bound.copy(108+                deviceName = bound.deviceName?.let(::capDeviceName),109+                localAlias = existing?.localAlias,84110             )85-            val next = getAll().filterNot { it.deviceId == device.deviceId } + device111+            val next = currentDevices.filterNot { it.deviceId == device.deviceId } + nextDevice86112             persist(next)87113         }88114     }89115 90-    fun rename(deviceId: String, name: String) {91-        mutationGate.withLock {92-            persist(withLocalAlias(getAll(), deviceId, name))93-        }94-    }95-96-    override fun remove(deviceId: String) {97-        mutationGate.withLock {98-            persist(getAll().filterNot { it.deviceId == deviceId })99-        }100-    }101-102116     /**103117      * Commit a staged manifest in one synchronous SharedPreferences transaction.104118      * `apply()` is appropriate for ordinary UI writes, but it would expose each@@ -110,16 +124,25 @@110124         return mutationGate.withLock {111125             val priorPrefs = readPrefsState()112126             val currentDevices = getAll()127+            val currentById = currentDevices.associateBy { it.deviceId }113128             val currentRevocations = listRevocations()114129             val nextRevocations = mergeRevocationRecords(currentRevocations, batch.incomingRevocations).records115130             val removed = batch.removals116131             val nextDevices = currentDevices117132                 .filterNot { removed.contains(it.deviceId) }118133                 .toMutableList()119-            batch.upserts.forEach { device ->120-                val alias = nextDevices.firstOrNull { it.deviceId == device.deviceId }?.localAlias121-                val device = device.copy(122-                    deviceName = device.deviceName?.let(::capDeviceName),134+            batch.upserts.forEach { incoming ->135+                val existing = currentById[incoming.deviceId]136+                    ?: nextDevices.firstOrNull { it.deviceId == incoming.deviceId }137+                require(!nextDevices.any { candidate ->138+                    candidate.deviceId != incoming.deviceId &&139+                        ((candidate.longTermPublicKeyHex != null && incoming.longTermPublicKeyHex != null && CryptoCompare.hex(candidate.longTermPublicKeyHex, incoming.longTermPublicKeyHex)) ||140+                            (candidate.signingPublicKeyHex != null && incoming.signingPublicKeyHex != null && CryptoCompare.hex(candidate.signingPublicKeyHex, incoming.signingPublicKeyHex)))141+                }) { "device_identity_collision" }142+                val bound = bindImmutableIdentity(existing, incoming)143+                val alias = nextDevices.firstOrNull { it.deviceId == incoming.deviceId }?.localAlias144+                val device = bound.copy(145+                    deviceName = bound.deviceName?.let(::capDeviceName),123146                     localAlias = alias,124147                 )125148                 nextDevices.removeAll { it.deviceId == device.deviceId }@@ -137,6 +160,20 @@137160         }138161     }139162 163+    fun rename(deviceId: String, name: String) {164+        mutationGate.withLock {165+            persist(withLocalAlias(getAll(), deviceId, name))166+        }167+    }168+169+    override fun remove(deviceId: String) {170+        mutationGate.withLock {171+            persist(getAll().filterNot { it.deviceId == deviceId })172+        }173+    }174+175+176+140177     // ── Device revocation (Part 5 §C) ────────────────────────────────────────141178 142179     override fun listRevocations(): List<DeviceRevocation> {@@ -294,7 +331,24 @@294331         val json = Json { encodeDefaults = true; ignoreUnknownKeys = true }295332     }296333 }334+/** Preserve a persisted device's cryptographic identity across metadata updates. */335+internal fun bindImmutableIdentity(existing: PairedDevice?, incoming: PairedDevice): PairedDevice {336+    if (existing == null) return incoming297337 338+    val longTermChanged = existing.longTermPublicKeyHex != null &&339+        incoming.longTermPublicKeyHex != null &&340+        !CryptoCompare.hex(existing.longTermPublicKeyHex, incoming.longTermPublicKeyHex)341+    val signingChanged = existing.signingPublicKeyHex != null &&342+        incoming.signingPublicKeyHex != null &&343+        !CryptoCompare.hex(existing.signingPublicKeyHex, incoming.signingPublicKeyHex)344+    require(!longTermChanged && !signingChanged) { "device_identity_immutable" }345+346+    return incoming.copy(347+        longTermPublicKeyHex = incoming.longTermPublicKeyHex ?: existing.longTermPublicKeyHex,348+        signingPublicKeyHex = incoming.signingPublicKeyHex ?: existing.signingPublicKeyHex,349+    )350+}351+298352 /** Serialises whole-list registry mutations so stale snapshots cannot win. */299353 internal class RegistryMutationGate {300354     private val lock = ReentrantLock()@@ -327,11 +381,13 @@327381     revocations: List<DeviceRevocation>,328382 ): Boolean {329383     if (devices.any { it.deviceId == incoming.deviceId }) return true384+    if (devices.any {385+        it.longTermPublicKeyHex?.let { key -> incoming.longTermPublicKeyHex?.let { candidate -> CryptoCompare.hex(key, candidate) } } == true ||386+            it.signingPublicKeyHex?.let { key -> incoming.signingPublicKeyHex?.let { candidate -> CryptoCompare.hex(key, candidate) } } == true387+    }) return true330388     return revocations.any { revoked ->331389         revoked.deviceId == incoming.deviceId ||332-            incoming.longTermPublicKeyHex?.let {333-                CryptoCompare.hex(revoked.longTermPublicKeyHex, it)334-            } == true390+            incoming.longTermPublicKeyHex?.let { CryptoCompare.hex(revoked.longTermPublicKeyHex, it) } == true335391     }336392 }337393 

view file

app/src/main/java/com/peachpasswords/sync/PeachSyncService.kt+21 −7
@@ -20,6 +20,7 @@2020 import dagger.hilt.components.SingletonComponent2121 import com.peachpasswords.vault.VaultCrypto2222 import com.peachpasswords.vault.VaultRepository23+import kotlinx.coroutines.CancellationException2324 import kotlinx.coroutines.CoroutineScope2425 import kotlinx.coroutines.SupervisorJob2526 import kotlinx.coroutines.cancel@@ -52,6 +53,12 @@5253     override fun onBind(intent: Intent?): IBinder? = null5354 5455     override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {56+        // A decoy unlock has no sync identity. Stop before foreground promotion57+        // so it cannot expose a notification or drain the locked spool.58+        if (vault.isUnlocked.value && vault.syncVaultId() == null) {59+            stopSelf()60+            return START_NOT_STICKY61+        }5562         // The same restriction that can refuse [start] applies again here, and5663         // a START_STICKY restart is exactly when it bites: the system brings us5764         // back while the app is in the background. A service that stays up@@ -114,13 +121,20 @@114121                 credentials.keys.publicKey,115122                 credentials.identity,116123             ) {117-                if (!vault.isUnlocked.value) lockedSyncSpool.adapter() else VaultSyncAdapter(118-                    repo = vault,119-                    ourDeviceId = getOrCreateDeviceId(this),120-                    pairedDevices = deviceStore,121-                    pendingVouched = pendingVouchedStore,122-                    syncAlerts = syncAlertStore,123-                )124+                // A decoy session can replace a real unlock while an existing125+                // relay callback is still being scheduled. Cancel that callback126+                // without reporting a misleading locked-vault outcome.127+                when {128+                    vault.syncVaultId() == null -> throw CancellationException("decoy session")129+                    !vault.isUnlocked.value -> lockedSyncSpool.adapter()130+                    else -> VaultSyncAdapter(131+                        repo = vault,132+                        ourDeviceId = getOrCreateDeviceId(this),133+                        pairedDevices = deviceStore,134+                        pendingVouched = pendingVouchedStore,135+                        syncAlerts = syncAlertStore,136+                    )137+                }124138             }125139         } finally {126140             master?.let(VaultCrypto::zero)

view file

app/src/main/java/com/peachpasswords/sync/RelayAdoptionReceiver.kt+4 −1
@@ -216,9 +216,12 @@216216 217217             override suspend fun deriveLocalIdentity(): LocalDeviceIdentity =218218                 receiverDeps.deriveLocalIdentity()219-220219             override suspend fun clearPairedDeviceRevocation(deviceId: String) {221220                 receiverDeps.clearPairedDeviceRevocation(deviceId)221+            }222+223+            override suspend fun upsertPairedDeviceAndClearRevocation(device: PairedDevice) {224+                receiverDeps.upsertPairedDeviceAndClearRevocation(device)222225             }223226 224227             override suspend fun upsertPairedDevice(device: PairedDevice) {

view file

app/src/main/java/com/peachpasswords/sync/VaultAdopt.kt+14 −5
@@ -280,8 +280,13 @@280280 281281     /** Seal a fresh local vault under the receiver's password, reusing [rootKeyHex]. Returns the vault id. */282282     suspend fun createVaultFromRootKey(rootKeyHex: String): String283+    /** Build the receiver's local identity after the adopted vault exists. */283284     suspend fun deriveLocalIdentity(): LocalDeviceIdentity284-    /** Only called after a successful, SAS-confirmed direct pairing. */285+    /** Persist the direct pairing and lift its terminal revocation as one store operation. */286+    suspend fun upsertPairedDeviceAndClearRevocation(device: PairedDevice) {287+        upsertPairedDevice(device)288+        clearPairedDeviceRevocation(device.deviceId)289+    }285290     suspend fun clearPairedDeviceRevocation(deviceId: String) {}286291     suspend fun upsertPairedDevice(device: PairedDevice)287292     suspend fun applyLicense(license: String) {}@@ -478,7 +483,12 @@478483             freshRootBytes.fill(0)479484         }480485     }486+    if (receiverLicense == null && acceptedGrant.license == null) {487+        deps.onError("ADOPT_PRO_REQUIRED")488+        return null489+    }481490 491+482492     if (receiverLicense == null) {483493         acceptedGrant.license?.let { deps.applyLicense(it) }484494     }@@ -516,10 +526,9 @@516526         pairedAt = nowMs(),517527     )518528     // A physically confirmed direct re-pair is the sole path allowed to lift519-    // terminal revocation. Clear before upsert so storage can never expose the520-    // source as both paired and revoked, even transiently.521-    deps.clearPairedDeviceRevocation(sourceDevice.deviceId)522-    deps.upsertPairedDevice(sourceDevice)529+    // terminal revocation. The registry validates identity before either value530+    // is changed, so a mismatch leaves the revocation intact.531+    deps.upsertPairedDeviceAndClearRevocation(sourceDevice)523532     sendFrame(channel, AdoptionFrame.Applied)524533     return sourceDevice525534 }

view file

app/src/main/java/com/peachpasswords/ui/lock/LockViewModel.kt+8 −1
@@ -293,7 +293,14 @@293293     private suspend fun handleDuress(duressUnlock: VaultRepository.DuressUnlock) {294294         when (duress.action()) {295295             DuressAction.DECOY -> when (vault.commitDuressUnlock(duressUnlock)) {296-                is UnlockResult.Success -> { lockTimer.start(); vault.clearUiGate(); _state.update { it.copy(loading = false, unlocked = true) } }296+                is UnlockResult.Success -> {297+                    // Stop an already-running real sync listener/service before298+                    // exposing the decoy session.299+                    foregroundSync.stopForDecoySession()300+                    lockTimer.start()301+                    vault.clearUiGate()302+                    _state.update { it.copy(loading = false, unlocked = true) }303+                }297304                 else -> _state.update {298305                     it.copy(loading = false, error = "incorrect password", shakeNonce = it.shakeNonce + 1)299306                 }

view file

app/src/main/java/com/peachpasswords/ui/pairing/AdoptVaultViewModel.kt+7 −2
@@ -300,6 +300,10 @@300300                 devices.clearRevocation(deviceId)301301             }302302 303+            override suspend fun upsertPairedDeviceAndClearRevocation(device: PairedDevice) {304+                devices.upsertAndClearRevocation(device)305+            }306+303307             override suspend fun upsertPairedDevice(device: PairedDevice) {304308                 devices.upsert(device)305309             }@@ -402,8 +406,9 @@402406             }403407 404408             override suspend fun upsertPairedDevice(device: PairedDevice) {405-                devices.clearRevocation(device.deviceId)406-                devices.upsert(device)409+                // SAS-confirmed direct adoption atomically validates identity,410+                // lifts terminal revocation, and persists the paired row.411+                devices.upsertAndClearRevocation(device)407412             }408413 409414             override suspend fun vaultSnapshot(): Pair<Map<String, String>, Map<String, Long>>? {

view file

app/src/main/java/com/peachpasswords/ui/pairing/CodePairViewModel.kt+3 −4
@@ -203,10 +203,9 @@203203             }204204 205205             override suspend fun upsertPairedDevice(device: PairedDevice) {206-                // SAS-confirmed direct adoption — the one consent signal strong207-                // enough to lift a terminal revocation.208-                deviceStore.clearRevocation(device.deviceId)209-                deviceStore.upsert(device)206+                // SAS-confirmed direct adoption atomically validates identity,207+                // lifts terminal revocation, and persists the paired row.208+                deviceStore.upsertAndClearRevocation(device)210209             }211210 212211             override suspend fun vaultSnapshot(): Pair<Map<String, String>, Map<String, Long>>? {

view file

app/src/main/java/com/peachpasswords/ui/sync/SyncViewModel.kt+48 −23
@@ -10,7 +10,6 @@1010 import com.peachpasswords.sync.PairedDeviceStore1111 import com.peachpasswords.sync.PendingVouchedDevice1212 import com.peachpasswords.sync.PendingVouchedDeviceStore13-import com.peachpasswords.sync.hexToPubkey1413 import com.peachpasswords.sync.PeachSyncService1514 import com.peachpasswords.sync.RelayDecision1615 import com.peachpasswords.sync.RelaySettingsStore@@ -20,10 +19,7 @@2019 import com.peachpasswords.sync.SyncOutcomeStore2120 import com.peachpasswords.sync.SyncOutcomeSummary2221 import com.peachpasswords.sync.VaultSyncAdapter23-import com.peachpasswords.sync.buildLocalIdentity24-import com.peachpasswords.sync.deriveLocalSyncKeypair2522 import com.peachpasswords.sync.getOrCreateDeviceId26-import com.peachpasswords.vault.VaultCrypto2723 import com.peachpasswords.vault.VaultRepository2824 import dagger.hilt.android.lifecycle.HiltViewModel2925 import dagger.hilt.android.qualifiers.ApplicationContext@@ -31,6 +27,7 @@3127 import kotlinx.coroutines.flow.SharingStarted3228 import kotlinx.coroutines.flow.StateFlow3329 import kotlinx.coroutines.flow.asStateFlow30+import kotlinx.coroutines.flow.combine3431 import kotlinx.coroutines.flow.stateIn3532 import kotlinx.coroutines.delay3633 import kotlinx.coroutines.Job@@ -61,10 +58,19 @@6158 ) : ViewModel() {6259 6360     /** The last sync attempt, whatever it was. Survives process death. */64-    val status: StateFlow<SyncOutcomeSummary> = syncOutcomes.summary61+    val status: StateFlow<SyncOutcomeSummary> =62+        combine(syncOutcomes.summary, vault.isUnlocked) { summary, unlocked ->63+            if (unlocked && vault.syncVaultId() == null) SyncOutcomeSummary() else summary64+        }.stateIn(65+            viewModelScope,66+            SharingStarted.WhileSubscribed(5_000),67+            if (vault.isUnlocked.value && vault.syncVaultId() == null) {68+                SyncOutcomeSummary()69+            } else {70+                syncOutcomes.summary.value71+            },72+        )6573 66-    val backgroundSyncEnabled: StateFlow<Boolean> = backgroundSync.enabled67-6874     /**6975      * Decides when the sync service actually runs for the background-sync7076      * preference. The service's own locked-handling is the gate — refusing to@@ -76,6 +82,7 @@7682         stop = { PeachSyncService.stop(context) },7783         isUnlocked = vault.isUnlocked,7884         preferenceEnabled = backgroundSync.enabled,85+        syncVaultId = vault::syncVaultId,7986     )8087 8188     init {@@ -87,9 +94,11 @@8794     }8895 8996     fun setBackgroundSyncEnabled(enabled: Boolean) {97+        if (isDecoySession()) return9098         backgroundSync.setEnabled(enabled)9199         backgroundSyncCoordinator.setEnabled(enabled)92100     }101+    val backgroundSyncEnabled: StateFlow<Boolean> = backgroundSync.enabled93102 94103     /** Blank while no private relay is configured, so the field stays honest. */95104     private val _privateRelayUrl = MutableStateFlow(relaySettings.privateRelayUrl())@@ -100,28 +109,34 @@100109     val syncMode: StateFlow<SyncMode> = _syncMode.asStateFlow()101110 102111     fun setSyncMode(mode: SyncMode) {112+        if (isDecoySession()) return103113         relaySettings.setSyncMode(mode)104114         _syncMode.value = relaySettings.syncMode()105115         _privateRelayUrl.value = relaySettings.privateRelayUrl()106116     }107117 108118     /** A custom URL implies private mode. Returns false on an invalid URL. */109-    fun setRelayUrl(input: String): Boolean = runCatching {110-        relaySettings.setRelayUrl(input)111-        _privateRelayUrl.value = relaySettings.privateRelayUrl()112-        _syncMode.value = relaySettings.syncMode()113-        true114-    }.getOrDefault(false)119+    fun setRelayUrl(input: String): Boolean {120+        if (isDecoySession()) return false121+        return runCatching {122+            relaySettings.setRelayUrl(input)123+            _privateRelayUrl.value = relaySettings.privateRelayUrl()124+            _syncMode.value = relaySettings.syncMode()125+            true126+        }.getOrDefault(false)127+    }115128 116129 117-    /** Live list of trusted peers, backing the Sync settings card device list (C7). */130+    /** Live list of trusted peers, redacted while a decoy session is active (C7). */118131     val pairedDevices: StateFlow<List<PairedDevice>> =119-        deviceStore.observeAll()120-            .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), emptyList())132+        combine(deviceStore.observeAll(), vault.isUnlocked) { devices, unlocked ->133+            if (unlocked && vault.syncVaultId() == null) emptyList() else devices134+        }.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), emptyList())121135 122136     val pendingVouched: StateFlow<List<PendingVouchedDevice>> =123-        pendingVouchedStore.observeAll()124-            .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), emptyList())137+        combine(pendingVouchedStore.observeAll(), vault.isUnlocked) { pending, unlocked ->138+            if (unlocked && vault.syncVaultId() == null) emptyList() else pending139+        }.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), emptyList())125140 126141     /**127142      * Revoke a paired device. Removing it REVOKES rather than just dropping the@@ -129,20 +144,20 @@129144      * back through a manifest, which is exactly what the relay makes easy.130145      */131146     fun unpairDevice(id: String) = viewModelScope.launch {147+        if (isDecoySession()) return@launch132148         deviceStore.revoke(id, getOrCreateDeviceId(context))133-        // Revocation is mesh state, not a vault-entry mutation. Wake the relay134-        // service immediately so the signed revocation reaches every remaining135-        // peer instead of waiting for a later foreground or periodic trigger.149+        // Revocation is mesh state, not just dropping the local row.136150         PeachSyncService.start(context)137151     }138152 139153     fun renameDevice(id: String, name: String) = viewModelScope.launch {154+        if (isDecoySession()) return@launch140155         deviceStore.rename(id, name)141156     }142157 143158     fun confirmVouchedDevice(id: String) = viewModelScope.launch {159+        if (isDecoySession()) return@launch144160         val pending = pendingVouchedStore.get(id) ?: return@launch145-        // Last gate before a vouched device becomes a sync peer. A queue entry146161         // can predate the revocation that names it, so revocation is re-checked147162         // here rather than trusted to have swept the queue.148163         if (deviceStore.isRevoked(pending.deviceId, pending.longTermPublicKeyHex)) {@@ -176,11 +191,14 @@176191     }177192 178193     fun rejectVouchedDevice(id: String) = viewModelScope.launch {194+        if (isDecoySession()) return@launch179195         pendingVouchedStore.remove(id)180196     }181197 198+182199     /** Browser-style nuclear recovery path: re-key sync and forget every peer. */183200     suspend fun rotateSyncIdentity(): Boolean {201+        if (isDecoySession()) return false184202         val ok = vault.rotateSyncIdentity()185203         if (ok) {186204             deviceStore.clear()@@ -191,7 +209,7 @@191209 192210     /** Adapter over the live vault; null while the vault is locked. */193211     fun buildAdapter(): SyncVaultAdapter? {194-        if (!vault.isUnlocked.value) return null212+        if (!vault.isUnlocked.value || isDecoySession()) return null195213         return VaultSyncAdapter(196214             repo = vault,197215             ourDeviceId = getOrCreateDeviceId(context),@@ -211,6 +229,10 @@211229      * comes from whoever actually finishes it.212230      */213231     fun syncNow() {232+        // A decoy session must not touch the real outcome store or start the233+        // sync service: either would expose or mutate real-session history.234+        if (isDecoySession()) return235+214236         val decision = relaySettings.relayInForce()215237         if (decision is RelayDecision.Refuse) {216238             syncOutcomes.report(SyncOutcomeSummary(reason = decision.reason))@@ -220,6 +242,7 @@220242             syncOutcomes.report(SyncOutcomeSummary(reason = SyncOutcomeReason.VAULT_LOCKED))221243             return222244         }245+223246         // Read the store, not `pairedDevices.value`: that flow only holds a real224247         // list while something is collecting it, so pull-to-refresh on the vault225248         // list — which collects `status` and nothing else — always saw an empty@@ -265,6 +288,8 @@265288             }266289         }267290     }291+    private fun isDecoySession(): Boolean =292+        vault.isUnlocked.value && vault.syncVaultId() == null268293 269294     /**270295      * Legacy manual / discovery trigger kept for existing callers; now routes

view file

app/src/main/java/com/peachpasswords/vault/VaultRepository.kt+140 −38
@@ -325,13 +325,9 @@325325             // translating browser-shaped slots to Android's StoredVault shape.326326             val codexDuressJson = wrapper["b"].asSlotJson()327327             val codexDuress: StoredVault? = codexDuressJson?.let {328-                VaultCodec.decodeSlot(it) ?: BrowserSlot.parse(it)?.let { b ->329-                    // H-04: pass-through — the browser duress slot is sealed330-                    // under the duress passphrase, not the main password. Trying331-                    // to decrypt with the slot-A password fails the GCM tag and332-                    // silently drops a real decoy. Re-encode the browser hex333-                    // fields as Android base64 salt/blob so tryUnlockDuress can334-                    // still open it with the duress passphrase.328+                VaultCodec.decodeSlot(it)?.let { slot ->329+                    if (slot.version != LEGACY_ANDROID_SLOT_VERSION && slot.version != CURRENT_ANDROID_SLOT_VERSION) null else slot330+                } ?: BrowserSlot.parse(it)?.let { b ->335331                     browserDuressPassthrough(b)336332                 }337333             }@@ -901,21 +897,111 @@901897     fun tryUnlockDuress(password: String): DuressUnlock? {902898         val epoch = currentEpoch()903899         val slot = store.loadDecoySlot() ?: return null904-        val key = VaultCrypto.deriveKey(password, unb64(slot.salt))900+        if (slot.version != LEGACY_ANDROID_SLOT_VERSION && slot.version != CURRENT_ANDROID_SLOT_VERSION) return null901+        var key: ByteArray? = VaultCrypto.deriveKey(password, unb64(slot.salt))905902         return try {906-            val plaintext = VaultCrypto.decrypt(unb64(slot.blob), key, VaultCrypto.AAD_SLOT_A)903+            val plaintext = try {904+                if (slot.version == CURRENT_ANDROID_SLOT_VERSION) {905+                    VaultCrypto.decrypt(unb64(slot.blob), key!!, VaultCrypto.AAD_SLOT_B)906+                } else {907+                    runCatching {908+                        VaultCrypto.decrypt(unb64(slot.blob), key!!, VaultCrypto.AAD_SLOT_A)909+                    }.getOrElse {910+                        VaultCrypto.decrypt(unb64(slot.blob), key!!, VaultCrypto.AAD_SLOT_B)911+                    }912+                }913+            } catch (_: Exception) {914+                VaultCrypto.zero(key!!)915+                key = null916+                return null917+            }907918             val payload = try {908919                 VaultCodec.decode(plaintext)909920             } finally {910921                 VaultCrypto.zero(plaintext)911922             }912-            DuressUnlock(key, payload, epoch)923+            if (slot.version == LEGACY_ANDROID_SLOT_VERSION) {924+                val migratedKey = migrateLegacyDuressSlot(slot, password, payload, key!!, epoch)925+                    ?: run {926+                        VaultCrypto.zero(key!!)927+                        key = null928+                        return null929+                    }930+                if (migratedKey !== key) {931+                    VaultCrypto.zero(key!!)932+                    key = migratedKey933+                }934+            }935+            DuressUnlock(key!!, payload, epoch).also { key = null }913936         } catch (_: Exception) {914-            VaultCrypto.zero(key)937+            key?.let(VaultCrypto::zero)915938             null916939         }917940     }918941 942+    /**943+     * Re-seal an authenticated legacy decoy under the current Slot-B AAD.944+     * A failed write or verification restores the exact legacy record, while945+     * already-authenticated unlock remains usable for this session.946+     */947+    private fun migrateLegacyDuressSlot(948+        legacy: StoredVault,949+        password: String,950+        payload: VaultPayload,951+        legacyKey: ByteArray,952+        epoch: Long,953+    ): ByteArray? {954+        var salt: ByteArray? = null955+        var migratedKey: ByteArray? = null956+        var plaintext: ByteArray? = null957+        var restoredLegacy = false958+        var migrated = false959+        try {960+            salt = VaultCrypto.generateSalt()961+            migratedKey = VaultCrypto.deriveKey(password, salt)962+            plaintext = VaultCodec.encode(payload)963+            val next = StoredVault(964+                version = CURRENT_ANDROID_SLOT_VERSION,965+                salt = b64(salt),966+                blob = b64(VaultCrypto.encrypt(plaintext, migratedKey, VaultCrypto.AAD_SLOT_B)),967+            )968+            var priorA: StoredVault? = null969+            var priorB: String? = null970+            withSessionEpochCommit(epoch) {971+                priorA = store.loadSlotA()972+                priorB = store.loadSlotB()973+                if (store.loadDecoySlot() != legacy) return@withSessionEpochCommit false974+                if (!store.writeDecoySlot(next)) {975+                    restoredLegacy = store.loadDecoySlot() == legacy976+                    return@withSessionEpochCommit restoredLegacy977+                }978+                val reopened = store.loadDecoySlot()979+                val verified = reopened?.version == CURRENT_ANDROID_SLOT_VERSION && runCatching {980+                    val reopenedPlaintext = VaultCrypto.decrypt(unb64(reopened.blob), migratedKey!!, VaultCrypto.AAD_SLOT_B)981+                    try { VaultCodec.decode(reopenedPlaintext) == payload } finally { VaultCrypto.zero(reopenedPlaintext) }982+                }.getOrDefault(false)983+                if (verified) {984+                    migrated = true985+                    return@withSessionEpochCommit true986+                }987+                val restored = priorA != null && store.restoreVaultTriad(priorA!!, priorB, legacy)988+                restoredLegacy = restored && store.loadSlotA() == priorA && store.loadSlotB() == priorB && store.loadDecoySlot() == legacy989+                restoredLegacy990+            }991+            if (migrated) {992+                VaultCrypto.zero(legacyKey)993+                return migratedKey.also { migratedKey = null }994+            }995+            if (restoredLegacy) return legacyKey996+        } catch (_: Exception) {997+            // A failed migration must not claim a legacy key unless the exact998+            // legacy record was durably restored and observed.999+        }1000+        if (!restoredLegacy) runCatching { store.loadDecoySlot() == legacy }1001+        migratedKey?.let(VaultCrypto::zero)1002+        return if (restoredLegacy) legacyKey else null1003+    }1004+9191005     /** Adopt a derived [DuressUnlock] as a live decoy session (edits persist to slot B only). */9201006     suspend fun commitDuressUnlock(unlock: DuressUnlock): UnlockResult = mutex.withLock {9211007         val key = unlock.takeKey() ?: return@withLock UnlockResult.Error("unlock_token_consumed")@@ -997,7 +1083,7 @@9971083             val targetSize = slotA?.let(::matchingCiphertextLength) ?: 09981084             val plaintext = if (targetSize > basePlaintext!!.size) basePlaintext!!.copyOf(targetSize) else basePlaintext!!9991085             val blob = try {1000-                b64(VaultCrypto.encrypt(plaintext, key!!, VaultCrypto.AAD_SLOT_A))1086+                b64(VaultCrypto.encrypt(plaintext, key!!, VaultCrypto.AAD_SLOT_B))10011087             } finally {10021088                 VaultCrypto.zero(plaintext)10031089                 // Padding creates a second array; scrub the original encoded@@ -1009,17 +1095,24 @@10091095             }10101096             beforeDurableCommit()10111097             val ok = withEpochCommit(expectedEpoch) {1012-                store.writeDecoySlot(StoredVault(version = 1, salt = b64(salt), blob = blob))1098+                store.writeDecoySlot(StoredVault(version = CURRENT_ANDROID_SLOT_VERSION, salt = b64(salt), blob = blob))10131099             } ?: false1014-            if (ok && mutateIfCurrentEpoch(expectedEpoch) {1100+            if (!ok) return false1101+            val marked = mutateIfCurrentEpoch(expectedEpoch) {10151102                 authenticatedDuressConfigured = true10161103                 _duressConfigured.value = true1017-            } != null) {1018-                runCatching { persistSlotA(bumpVersion = false, expectedEpoch = expectedEpoch) }1019-            } else if (ok) {1104+                true1105+            } ?: false1106+            if (!marked) return false1107+            if (!runCatching { persistSlotA(bumpVersion = false, expectedEpoch = expectedEpoch) }.getOrDefault(false)) {1108+                mutateIfCurrentEpoch(expectedEpoch) {1109+                    authenticatedDuressConfigured = false1110+                    _duressConfigured.value = false1111+                }1112+                runCatching { writeFakeDuressSlot(store.loadSlotA()!!) }10201113                 return false10211114             }1022-            ok1115+            true10231116         } catch (_: Exception) {10241117             false10251118         } finally {@@ -1092,17 +1185,11 @@10921185 10931186     /**10941187      * Install a browser-shaped duress slot received through adoption.1095-     *1096-     * Parses [json] as a [BrowserSlotA], re-encodes it to Android's1097-     * [StoredVault] via [browserDuressPassthrough] (no decryption), and1098-     * writes the result to the decoy slot. Epoch-fenced like the Codex1099-     * restore path so a concurrent lock() cannot strand the write.1100-     *1101-     * Returns false on invalid input, no live session, or write failure.11021188      */11031189     suspend fun installAdoptedDuressSlot(json: String): Boolean = mutex.withLock {11041190         val b = BrowserSlot.parse(json) ?: return false1105-        var stored: StoredVault? = null1191+        if (b.version != 1) return false1192+        val expectedEpoch = currentEpoch()11061193         var salt: ByteArray? = null11071194         var nonce: ByteArray? = null11081195         var ct: ByteArray? = null@@ -1118,12 +1205,28 @@11181205                 System.arraycopy(ct, 0, it, nonce.size, ct.size)11191206                 System.arraycopy(tag, 0, it, nonce.size + ct.size, tag.size)11201207             }1121-            stored = StoredVault(version = 1, salt = b64(salt), blob = b64(blob))1122-            val expectedEpoch = sessionEpoch1208+            val stored = StoredVault(version = LEGACY_ANDROID_SLOT_VERSION, salt = b64(salt), blob = b64(blob))1209+            val priorA = store.loadSlotA() ?: return false1210+            val priorB = store.loadSlotB()1211+            val priorD = store.loadDecoySlot() ?: return false11231212             beforeDurableCommit()1124-            withEpochCommit(expectedEpoch) {1125-                store.writeDecoySlot(stored)1213+            val committed = withEpochCommit(expectedEpoch) {1214+                if (!store.writeDecoySlot(stored)) return@withEpochCommit false1215+                authenticatedDuressConfigured = true1216+                _duressConfigured.value = true1217+                true11261218             } ?: false1219+            if (!committed) return false1220+            if (runCatching { persistSlotA(bumpVersion = false, expectedEpoch = expectedEpoch) }.getOrDefault(false)) {1221+                true1222+            } else {1223+                mutateIfCurrentEpoch(expectedEpoch) {1224+                    authenticatedDuressConfigured = false1225+                    _duressConfigured.value = false1226+                }1227+                withEpochCommit(expectedEpoch) { store.restoreVaultTriad(priorA, priorB, priorD) }1228+                false1229+            }11271230         } catch (_: Exception) {11281231             false11291232         } finally {@@ -1994,7 +2097,7 @@19942097             val target = VaultCrypto.NONCE_SIZE + matchingCiphertextLength(restoredA) + 1619952098             val fakeBlob = ByteArray(target).also(rng::nextBytes)19962099             val fakeSalt = VaultCrypto.generateSalt()1997-            StoredVault(version = 1, salt = b64(fakeSalt), blob = b64(fakeBlob))2100+            StoredVault(version = CURRENT_ANDROID_SLOT_VERSION, salt = b64(fakeSalt), blob = b64(fakeBlob))19982101         }19992102         if (!commitRestoreAtomic(restoredA, snapshot.vault_b, nextD, priorA, priorB, priorD, expectedEpoch)) {20002103             withEpochCommit(expectedEpoch) { store.writeVaultHistory(priorHistory) }@@ -2618,7 +2721,7 @@26182721             val target = VaultCrypto.NONCE_SIZE + matchingCiphertextLength(slotA) + 1626192722             val fakeBlob = ByteArray(target).also(rng::nextBytes)26202723             val fakeSalt = VaultCrypto.generateSalt()2621-            VaultCodec.encodeSlot(StoredVault(version = 1, salt = b64(fakeSalt), blob = b64(fakeBlob)))2724+            VaultCodec.encodeSlot(StoredVault(version = CURRENT_ANDROID_SLOT_VERSION, salt = b64(fakeSalt), blob = b64(fakeBlob)))26222725         }26232726         val history = store.loadVaultHistory()26242727         val latest = history.snapshots.firstOrNull()@@ -2782,7 +2885,7 @@27822885         var plaintext = VaultCodec.encode(currentPayload())27832886         return try {27842887             val blob = b64(VaultCrypto.encrypt(plaintext, key, VaultCrypto.AAD_SLOT_A))2785-            StoredVault(version = 1, salt = b64(salt), blob = blob)2888+            StoredVault(version = LEGACY_ANDROID_SLOT_VERSION, salt = b64(salt), blob = blob)27862889         } finally {27872890             // M-05: full vault plaintext is allocated here once per createVault.27882891             // Zeroing in finally keeps the transient copy off the heap after the@@ -2815,7 +2918,7 @@28152918         val blobSize = VaultCrypto.NONCE_SIZE + matchingCiphertextLength(slotA) + 1628162919         val fakeBlob = ByteArray(blobSize).also(rng::nextBytes)28172920         val fakeSalt = VaultCrypto.generateSalt()2818-        return store.writeDecoySlot(StoredVault(version = 1, salt = b64(fakeSalt), blob = b64(fakeBlob)))2921+        return store.writeDecoySlot(StoredVault(version = CURRENT_ANDROID_SLOT_VERSION, salt = b64(fakeSalt), blob = b64(fakeBlob)))28192922     }28202923 28212924     /** H-04: keep the duress record present on every persist. A real decoy is@@ -2846,9 +2949,8 @@28462949             System.arraycopy(ct, 0, it, nonce.size, ct.size)28472950             System.arraycopy(tag, 0, it, nonce.size + ct.size, tag.size)28482951         }2849-        return StoredVault(version = 1, salt = b64(salt), blob = b64(blob))2952+        return StoredVault(version = LEGACY_ANDROID_SLOT_VERSION, salt = b64(salt), blob = b64(blob))28502953     }2851-28522954     /** Re-seal slot A from the current in-memory state under the live key. */28532955     private fun persistSlotA(28542956         bumpVersion: Boolean,@@ -2863,7 +2965,7 @@28632965                 val prior = store.loadDecoySlot() ?: throw IllegalStateException("missing decoy slot")28642966                 val plaintext = VaultCodec.encode(snapshot.payload)28652967                 val blob = try {2866-                    b64(VaultCrypto.encrypt(plaintext, snapshot.key, VaultCrypto.AAD_SLOT_A))2968+                    b64(VaultCrypto.encrypt(plaintext, snapshot.key, VaultCrypto.AAD_SLOT_B))28672969                 } finally {28682970                     // Keep the last reference alive until the zero, including the28692971                     // successful encrypt path (M-05).@@ -2871,7 +2973,7 @@28712973                 }28722974                 beforeDurableCommit()28732975                 return withEpochCommit(snapshot.epoch) {2874-                    store.writeDecoySlot(prior.copy(blob = blob))2976+                    store.writeDecoySlot(prior.copy(version = CURRENT_ANDROID_SLOT_VERSION, blob = blob))28752977                 } ?: false28762978             }28772979             val prior = store.loadSlotA() ?: throw IllegalStateException("missing slot A")

view file

app/src/main/java/com/peachpasswords/vault/VaultStore.kt+34 −9
@@ -18,13 +18,17 @@1818  */1919 @Serializable2020 data class StoredVault(21-    val version: Int = 1,21+    /** Version 1 is the legacy Slot-A-AAD record; current decoys use version 2. */22+    val version: Int = LEGACY_ANDROID_SLOT_VERSION,2223     val salt: String,2324     val blob: String,2425     val recoveryEscrow: RecoveryEscrow? = null,2526     val rootKeyEscrow: RootKeyEscrow? = null,2627 )2728 29+const val LEGACY_ANDROID_SLOT_VERSION = 130+const val CURRENT_ANDROID_SLOT_VERSION = 231+2832 /**2933  * Browser-byte-compatible recovery escrow that wraps ONLY the 32-byte root key,3034  * so the same 12 recovery words unwrap the same root key on either platform@@ -153,20 +157,33 @@153157     fun decodeHistory(s: String): VaultHistory? = runCatching { json.decodeFromString<VaultHistory>(s) }.getOrNull()154158 }155159 156-/**157- * Persistence for the two vault slots, the monotonic version counter, and the158- * settings blob. Abstracted behind an interface so the repository can be159- * exercised against an in-memory fake in plain JUnit.160- */161160 interface VaultStorage {161+    fun loadDecoySlot(): StoredVault?162162     fun loadSlotA(): StoredVault?163163     fun hasVault(): Boolean164164     fun writeSlotA(slot: StoredVault): Boolean165165     fun loadSlotB(): String? = null166166     fun writeSlotB(blobBase64: String): Boolean167-    fun loadDecoySlot(): StoredVault?168167     fun writeDecoySlot(slot: StoredVault): Boolean169-    fun hasDecoySlot(): Boolean168+    /** Restore the exact triad, rolling back each write if a later write fails. */169+    fun restoreVaultTriad(slotA: StoredVault, slotB: String?, decoy: StoredVault): Boolean {170+        val priorA = loadSlotA()171+        val priorB = loadSlotB()172+        val priorD = loadDecoySlot()173+        return try {174+            if (!writeSlotA(slotA)) return false175+            if (slotB == null) clearSlotB() else if (!writeSlotB(slotB)) throw IllegalStateException("slot_b_restore_failed")176+            if (!writeDecoySlot(decoy)) throw IllegalStateException("decoy_restore_failed")177+            true178+        } catch (_: Exception) {179+            runCatching { if (priorA == null) clearVault() else writeSlotA(priorA) }180+            runCatching { if (priorB == null) clearSlotB() else writeSlotB(priorB) }181+            runCatching { if (priorD == null) clearDecoySlot() else writeDecoySlot(priorD) }182+            false183+        }184+    }185+    fun clearSlotB() {}186+    fun hasDecoySlot(): Boolean = loadDecoySlot() != null170187     fun clearDecoySlot()171188     fun version(): Long172189     fun stampLocalMutation(): Long@@ -197,7 +214,7 @@197214 198215     override fun writeSlotA(slot: StoredVault): Boolean =199216         writeAligned(KEY_SLOT_A, VaultCodec.encodeSlot(slot), KEY_SLOT_DURESS)200-217+    override fun clearSlotB() { prefs.edit().remove(KEY_SLOT_B).commit() }201218     override fun loadSlotB(): String? = prefs.getString(KEY_SLOT_B, null)202219 203220     override fun writeSlotB(blobBase64: String): Boolean =@@ -215,6 +232,14 @@215232         )216233         val edits = prefs.edit().putString(key, aligned)217234         if (alignedSibling != null) edits.putString(siblingKey, alignedSibling)235+        return edits.commit()236+    }237+238+    override fun restoreVaultTriad(slotA: StoredVault, slotB: String?, decoy: StoredVault): Boolean {239+        val edits = prefs.edit()240+            .putString(KEY_SLOT_A, VaultCodec.encodeSlot(slotA))241+            .putString(KEY_SLOT_DURESS, VaultCodec.encodeSlot(decoy))242+        if (slotB != null) edits.putString(KEY_SLOT_B, slotB) else edits.remove(KEY_SLOT_B)218243         return edits.commit()219244     }220245     override fun hasDecoySlot(): Boolean = prefs.contains(KEY_SLOT_DURESS)

view file

app/src/test/java/com/peachpasswords/sync/C7TransportTest.kt+34 −7
@@ -58,19 +58,46 @@5858         assertEquals("ab".repeat(32), decoded[1].longTermPublicKeyHex)5959     }6060 61-    /** Test 2: upsert replaces an existing entry by deviceId (store semantics). */61+    /** Test 2: same identity permits metadata-only replacement without duplication. */6262     @Test63-    fun `upsert by deviceId replaces rather than duplicates`() {64-        // Mirror PairedDeviceStore.upsert's pure list transform.65-        fun upsert(list: List<PairedDevice>, d: PairedDevice) =66-            list.filterNot { it.deviceId == d.deviceId } + d63+    fun `upsert by deviceId preserves identity while updating metadata`() {64+        fun upsert(list: List<PairedDevice>, incoming: PairedDevice): List<PairedDevice> {65+            val existing = list.firstOrNull { it.deviceId == incoming.deviceId }66+            val bound = bindImmutableIdentity(existing, incoming)67+            return list.filterNot { it.deviceId == incoming.deviceId } + bound68+        }6769 68-        var list = listOf(device("a", "Alice"))70+        val original = device("a", "Alice").copy(signingPublicKeyHex = "cd".repeat(32))71+        var list = listOf(original)6972         list = upsert(list, device("b", "Bob"))7073         assertEquals(2, list.size)71-        list = upsert(list, device("a", "Alice-renamed"))74+        list = upsert(list, device("a", "Alice-renamed").copy(signingPublicKeyHex = null))7275         assertEquals(2, list.size)7376         assertEquals("Alice-renamed", list.first { it.deviceId == "a" }.deviceName)77+        assertEquals(original.longTermPublicKeyHex, list.first { it.deviceId == "a" }.longTermPublicKeyHex)78+        assertEquals(original.signingPublicKeyHex, list.first { it.deviceId == "a" }.signingPublicKeyHex)79+    }80+81+    @Test82+    fun `identity key changes are rejected before list replacement`() {83+        val original = device("a").copy(signingPublicKeyHex = "cd".repeat(32))84+        val list = listOf(original)85+        val changedLongTerm = original.copy(longTermPublicKeyHex = "ef".repeat(32), deviceName = "spoofed")86+        val changedSigning = original.copy(signingPublicKeyHex = "12".repeat(32), deviceName = "spoofed")87+88+        assertEquals(89+            "device_identity_immutable",90+            assertThrows(IllegalArgumentException::class.java) {91+                bindImmutableIdentity(list.first { it.deviceId == changedLongTerm.deviceId }, changedLongTerm)92+            }.message,93+        )94+        assertEquals(95+            "device_identity_immutable",96+            assertThrows(IllegalArgumentException::class.java) {97+                bindImmutableIdentity(list.first { it.deviceId == changedSigning.deviceId }, changedSigning)98+            }.message,99+        )100+        assertEquals(listOf(original), list)74101     }75102 76103     /** Test 3: writeFrame/readFrame round-trip across payload sizes. */

view file

app/src/test/java/com/peachpasswords/vault/AdoptDuressSlotTest.kt+1 −1
@@ -63,7 +63,7 @@6363         val ct = ctAndTag.copyOfRange(0, ctAndTag.size - 16)6464         val tag = ctAndTag.copyOfRange(ctAndTag.size - 16, ctAndTag.size)6565         val browserSlot = BrowserSlotA(66-            version = slot.version,66+            version = 1,6767             salt = hex(salt),6868             nonce = hex(nonce),6969             ciphertext = hex(ct),

view file

app/src/test/java/com/peachpasswords/vault/DuressSlotBTest.kt+52 −3
@@ -14,18 +14,22 @@1414 1515 /** In-memory [VaultStorage] including a decoy (slot B) slot, for the MF-6 duress model. */1616 private class DuressFakeStorage : VaultStorage {17+    var failWriteDecoy = false1718     var slotA: StoredVault? = null1819     var slotB: String? = null1920     private var ver: Long = 02021     private var settings = VaultSettings()22+    override fun loadDecoySlot() = decoy2123     override fun loadSlotA() = slotA2224     override fun hasVault() = slotA != null2325     override fun writeSlotA(slot: StoredVault): Boolean { slotA = slot; return true }2426     override fun writeSlotB(blobBase64: String): Boolean { slotB = blobBase64; return true }2527     var decoy: StoredVault? = null26-    override fun loadDecoySlot() = decoy27-    override fun writeDecoySlot(slot: StoredVault): Boolean { decoy = slot; return true }28-    override fun hasDecoySlot() = decoy != null28+    override fun writeDecoySlot(slot: StoredVault): Boolean {29+        if (failWriteDecoy) return false30+        decoy = slot31+        return true32+    }2933     override fun clearDecoySlot() { decoy = null }3034     override fun version() = ver3135     override fun stampLocalMutation(): Long { ver = maxOf(System.currentTimeMillis(), ver + 1); return ver }@@ -84,6 +88,51 @@8488         val repo = configuredRepo()8589         assertNull(repo.tryUnlockSlotA("totally-wrong"))8690         assertNull(repo.tryUnlockDuress("totally-wrong"))91+    }92+    @Test fun legacy_slot_a_decoy_unlocks_and_migrates_to_slot_b_aad() = runBlocking {93+        val storage = DuressFakeStorage()94+        val repo = VaultRepository(storage)95+        repo.createVault(real)96+        assertTrue(repo.setDuressPassphrase(duressPass))97+        val current = storage.decoy!!98+        val key = VaultCrypto.deriveKey(duressPass, Base64.getDecoder().decode(current.salt))99+        val plaintext = VaultCrypto.decrypt(Base64.getDecoder().decode(current.blob), key, VaultCrypto.AAD_SLOT_B)100+        val legacyBlob = try {101+            VaultCrypto.encrypt(plaintext, key, VaultCrypto.AAD_SLOT_A)102+        } finally {103+            VaultCrypto.zero(plaintext)104+            VaultCrypto.zero(key)105+        }106+        storage.decoy = current.copy(version = LEGACY_ANDROID_SLOT_VERSION, blob = Base64.getEncoder().encodeToString(legacyBlob))107+        assertNotNull(repo.tryUnlockDuress(duressPass))108+        assertEquals(CURRENT_ANDROID_SLOT_VERSION, storage.decoy!!.version)109+        val migratedKey = VaultCrypto.deriveKey(duressPass, Base64.getDecoder().decode(storage.decoy!!.salt))110+        assertNotNull(VaultCrypto.decrypt(Base64.getDecoder().decode(storage.decoy!!.blob), migratedKey, VaultCrypto.AAD_SLOT_B))111+        VaultCrypto.zero(migratedKey)112+    }113+114+    @Test fun legacy_migration_write_failure_preserves_legacy_record() = runBlocking {115+        val storage = DuressFakeStorage()116+        val repo = VaultRepository(storage)117+        repo.createVault(real)118+        assertTrue(repo.setDuressPassphrase(duressPass))119+        val current = storage.decoy!!120+        val key = VaultCrypto.deriveKey(duressPass, Base64.getDecoder().decode(current.salt))121+        val plaintext = VaultCrypto.decrypt(Base64.getDecoder().decode(current.blob), key, VaultCrypto.AAD_SLOT_B)122+        val legacyBlob = try {123+            VaultCrypto.encrypt(plaintext, key, VaultCrypto.AAD_SLOT_A)124+        } finally {125+            VaultCrypto.zero(plaintext)126+            VaultCrypto.zero(key)127+        }128+        val legacy = current.copy(129+            version = LEGACY_ANDROID_SLOT_VERSION,130+            blob = Base64.getEncoder().encodeToString(legacyBlob),131+        )132+        storage.decoy = legacy133+        storage.failWriteDecoy = true134+        assertNotNull(repo.tryUnlockDuress(duressPass))135+        assertEquals(legacy, storage.decoy)87136     }88137 89138     @Test fun duress_passphrase_cannot_equal_real_password() = runBlocking {

view file