PairedDeviceStore.kt

31.2 KB · raw

1package com.peachpasswords.sync23import android.content.Context4import android.content.SharedPreferences5import androidx.security.crypto.EncryptedSharedPreferences6import androidx.security.crypto.MasterKey7import dagger.hilt.android.qualifiers.ApplicationContext8import kotlinx.coroutines.channels.awaitClose9import kotlinx.coroutines.flow.Flow10import kotlinx.coroutines.flow.callbackFlow11import kotlinx.serialization.builtins.ListSerializer12import kotlinx.serialization.json.Json13import java.util.concurrent.locks.ReentrantLock14import javax.inject.Inject15import javax.inject.Singleton16import kotlin.concurrent.withLock1718private const val MAX_REVOCATION_RECORDS = 5001920/**21 * Persistent registry of paired devices, encrypted at rest with22 * EncryptedSharedPreferences (same construction as DuressConfigStore /23 * LicenseRepository, v2.1.36). The whole list lives under a single key as a24 * kotlinx.serialization JSON array of the REAL [PairedDevice] (sync package).25 *26 * Reconciliation with the C7 brief:27 *  - The brief invents a fresh `PairedDevice(id, name, publicKey: ByteArray,28 *    lastSeen, trustStatus, lastSyncAt)`. That type does NOT exist in this29 *    shape. The real [PairedDevice] (PairedDevice.kt) keys on `deviceId`, holds30 *    the public key as `longTermPublicKeyHex` (hex, not ByteArray), and tracks31 *    `pairedAt` / `lastSyncedAt` / `lastKnownIp`. This store reuses it verbatim;32 *    Base64 publicKey storage is therefore unnecessary — the hex field is the33 *    canonical wire form already produced by PairingFrames.frameToPairedDevice.34 *  - The brief's `TrustStatus` enum does not exist either. The real model uses a35 *    nullable `trustSource: String?` (e.g. "direct", "manifest"). Trust state is36 *    expressed there. See C7-INTEGRATION.md for the trust-status delta.37 *  - `updateLastSync` here maps to the real `lastSyncedAt` field. There is no38 *    `lastSeen` field on the real PairedDevice; [updateLastSeen] folds into39 *    `lastKnownIp` refresh + `lastSyncedAt` is left untouched. It is kept as a40 *    no-op-friendly hook so callers from the brief compile; see integration note.41 */42@Singleton43class PairedDeviceStore internal constructor(44    private val prefs: SharedPreferences,45) : PairedDeviceRegistry {46    @Inject constructor(@ApplicationContext context: Context) : this(47        EncryptedSharedPreferences.create(48            context,49            PREFS_FILE,50            MasterKey.Builder(context).setKeyScheme(MasterKey.KeyScheme.AES256_GCM).build(),51            EncryptedSharedPreferences.PrefKeyEncryptionScheme.AES256_SIV,52            EncryptedSharedPreferences.PrefValueEncryptionScheme.AES256_GCM,53        ),54    )5556    private val listSerializer = ListSerializer(PairedDevice.serializer())57    private val revocationSerializer = ListSerializer(DeviceRevocation.serializer())58    private val mutationGate = RegistryMutationGate()5960    /** Set by [revoke]; see [protectedRevocationIssuers]. */61    @Volatile private var knownLocalDeviceId: String? = null6263    override fun getAll(): List<PairedDevice> = mutationGate.withLock {64        decodeDevices(readStringPreference(KEY_DEVICES))65    }6667    private fun decodeDevices(raw: String?): List<PairedDevice> {68        if (raw == null) return emptyList()69        return try {70            json.decodeFromString(listSerializer, raw)71        } catch (e: Exception) {72            throw TrustDataCorruptedException(KEY_DEVICES, e.message ?: "decode_failed")73        }74    }7576    override fun manifestSnapshot(requestedIssuerIds: Set<String>): DeviceManifestRegistrySnapshot = mutationGate.withLock {77        manifestSnapshot(readPrefsState())78    }7980    private fun manifestSnapshot(state: RegistryPrefsState): DeviceManifestRegistrySnapshot =81        DeviceManifestRegistrySnapshot(82            devices = decodeDevices(state.devices),83            revocations = decodeRevocations(state.revocations),84            issuerSigningKeys = state.issuerKeys.mapValues { (_, keys) -> keys.map(String::lowercase).toSet() },85        )8687    private fun readStringPreference(key: String): String? = try {88        prefs.getString(key, null)89    } catch (e: ClassCastException) {90        throw TrustDataCorruptedException(key, "invalid_string")91    }9293    override fun get(id: String): PairedDevice? = getAll().firstOrNull { it.deviceId == id }9495    override fun getByPubkey(pubkeyHex: String): PairedDevice? =96        getAll().firstOrNull {97            it.longTermPublicKeyHex?.let { key -> CryptoCompare.hex(key, pubkeyHex) } == true98        }99100    fun hasIdentityCollision(device: PairedDevice): Boolean = mutationGate.withLock {101        hasAdoptionIdentityConflict(device, getAll(), listRevocations())102    }103104    /** Insert or replace a directly re-paired device and clear its terminal revocation atomically. */105    fun upsertAndClearRevocation(device: PairedDevice) {106        mutationGate.withLock {107            val currentDevices = getAll()108            val existing = currentDevices.firstOrNull { it.deviceId == device.deviceId }109            val bound = bindImmutableIdentity(existing, device)110            val nextDevice = bound.copy(111                deviceName = bound.deviceName?.let(::capDeviceName),112                localAlias = existing?.localAlias,113            )114            val nextDevices = currentDevices.filterNot { it.deviceId == device.deviceId } + nextDevice115            val currentRevocations = listRevocations()116            val nextRevocations = currentRevocations.filterNot { it.deviceId == device.deviceId }117            val priorPrefs = readPrefsState()118            val nextPrefs = priorPrefs.copy(119                devices = json.encodeToString(listSerializer, nextDevices),120                revocations = json.encodeToString(revocationSerializer, nextRevocations),121            )122            check(commitPrefsState(priorPrefs, nextPrefs)) {123                "paired_device_persist_failed"124            }125        }126    }127128    /** Insert or replace by [PairedDevice.deviceId], without changing its cryptographic identity. */129    override fun upsert(device: PairedDevice) {130        mutationGate.withLock {131            val currentDevices = getAll()132            val existing = currentDevices.firstOrNull { it.deviceId == device.deviceId }133            val bound = bindImmutableIdentity(existing, device)134            // Peer-supplied names arrive capped so a hostile peer cannot grow the135            // registry without limit (adoption + direct-pair seams land here).136            val nextDevice = bound.copy(137                deviceName = bound.deviceName?.let(::capDeviceName),138                localAlias = existing?.localAlias,139            )140            val next = currentDevices.filterNot { it.deviceId == device.deviceId } + nextDevice141            persist(next)142        }143    }144145    /**146     * Commit a staged manifest in one synchronous SharedPreferences transaction.147     * Per-device edits could leave an old-session manifest half-applied across148     * a lock. `commit()` updates registry, ledger and history together in memory149     * and does not return until the durable write has completed.150     */151    override fun applyManifestBatch(batch: DeviceManifestRegistryBatch): Boolean {152        return mutationGate.withLock {153            val priorPrefs = readPrefsState()154            val currentSnapshot = manifestSnapshot(priorPrefs)155            if (!sameTrustSnapshot(currentSnapshot, batch.expectedSnapshot)) return@withLock false156            val currentDevices = currentSnapshot.devices157            val currentById = currentDevices.associateBy { it.deviceId }158            val currentRevocations = currentSnapshot.revocations159            val admissionRevocations = currentRevocations + batch.incomingRevocations160            val revokedIds = admissionRevocations.map { it.deviceId }.toSet()161            val revokedKeys = admissionRevocations.map { it.longTermPublicKeyHex.lowercase() }162                .filterNot { it == NO_KEY_SENTINEL }.toSet()163            fun isTerminal(deviceId: String, longTermKey: String?): Boolean =164                deviceId in revokedIds || longTermKey?.lowercase() in revokedKeys165166            val expectedIssuer = batch.authenticatedIssuer167            val issuer = currentById[expectedIssuer.deviceId] ?: return@withLock false168            // Incoming records may revoke their still-authorized forwarder.169            val issuerAlreadyRevoked = currentRevocations.any {170                it.deviceId == issuer.deviceId ||171                    (it.longTermPublicKeyHex.lowercase() != NO_KEY_SENTINEL &&172                        it.longTermPublicKeyHex.equals(issuer.longTermPublicKeyHex, ignoreCase = true))173            }174            if (issuer.longTermPublicKeyHex?.let { CryptoCompare.hex(it, expectedIssuer.longTermPublicKeyHex) } != true ||175                issuer.signingPublicKeyHex?.let { CryptoCompare.hex(it, expectedIssuer.signingPublicKeyHex) } != true ||176                (issuer.trustSource != "direct" && issuer.trustSource != "vouched") ||177                issuer.vouchDepth >= MAX_VOUCH_DEPTH || issuerAlreadyRevoked178            ) return@withLock false179            val allowedIssuerKeys = priorPrefs.issuerKeys[issuer.deviceId].orEmpty().map(String::lowercase).toSet() +180                expectedIssuer.signingPublicKeyHex.lowercase()181            if (batch.issuerSigningKeys.any { (id, keys) ->182                id != issuer.deviceId || keys.any { !isSigningKey(it) || it.lowercase() !in allowedIssuerKeys }183            }) return@withLock false184            if (batch.upserts.any {185                isTerminal(it.deviceId, it.longTermPublicKeyHex ?: currentById[it.deviceId]?.longTermPublicKeyHex)186            }) return@withLock false187188            val nextRevocations = mergeRevocationRecords(currentRevocations, batch.incomingRevocations).records189            val removed = batch.removals190            val nextDevices = currentDevices191                .filterNot { removed.contains(it.deviceId) || isTerminal(it.deviceId, it.longTermPublicKeyHex) }192                .toMutableList()193            batch.upserts.forEach { incoming ->194                val existing = currentById[incoming.deviceId]195                    ?: nextDevices.firstOrNull { it.deviceId == incoming.deviceId }196                require(!nextDevices.any { candidate ->197                    candidate.deviceId != incoming.deviceId &&198                        ((candidate.longTermPublicKeyHex != null && incoming.longTermPublicKeyHex != null && CryptoCompare.hex(candidate.longTermPublicKeyHex, incoming.longTermPublicKeyHex)) ||199                            (candidate.signingPublicKeyHex != null && incoming.signingPublicKeyHex != null && CryptoCompare.hex(candidate.signingPublicKeyHex, incoming.signingPublicKeyHex)))200                }) { "device_identity_collision" }201                val bound = bindImmutableIdentity(existing, incoming)202                val alias = existing?.localAlias203                val device = bound.copy(204                    deviceName = bound.deviceName?.let(::capDeviceName),205                    localAlias = alias,206                    lastSyncedAt = if (existing != null) existing.lastSyncedAt else bound.lastSyncedAt,207                    lastKnownIp = if (existing != null) existing.lastKnownIp else bound.lastKnownIp,208                )209                nextDevices.removeAll { it.deviceId == device.deviceId }210                nextDevices += device211            }212213            val nextPrefs = priorPrefs.copy(214                devices = json.encodeToString(listSerializer, nextDevices),215                revocations = json.encodeToString(revocationSerializer, nextRevocations),216                issuerKeys = withIssuerSigningKeys(priorPrefs.issuerKeys, batch.issuerSigningKeys),217            )218            // Explicitly restore the old encrypted-preference values when commit()219            // reports false. The platform usually keeps them in memory, but a real220            // store failure must not rely on that undocumented outcome.221            commitPrefsState(priorPrefs, nextPrefs)222        }223    }224225    fun rename(deviceId: String, name: String) {226        mutationGate.withLock {227            persist(withLocalAlias(getAll(), deviceId, name))228        }229    }230231    override fun remove(deviceId: String) {232        mutationGate.withLock {233            persist(getAll().filterNot { it.deviceId == deviceId })234        }235    }236237238239    // ── Device revocation (Part 5 §C) ────────────────────────────────────────240241    override fun listRevocations(): List<DeviceRevocation> = mutationGate.withLock {242        decodeRevocations(readStringPreference(KEY_REVOCATIONS))243    }244245    private fun decodeRevocations(raw: String?): List<DeviceRevocation> {246        if (raw == null) return emptyList()247        return try {248            json.decodeFromString(revocationSerializer, raw)249        } catch (e: Exception) {250            throw TrustDataCorruptedException(KEY_REVOCATIONS, e.message ?: "decode_failed")251        }252    }253254    /**255     * Revoke a device: record it, then drop it from the registry. The record256     * rides out in every manifest this device signs from now on. A stale entry257     * may survive in the pending-vouch queue; the confirm path re-checks258     * revocation before promoting anything out of it.259     */260    fun revoke(261        deviceId: String,262        revokedByDeviceId: String,263        nowMs: Long = System.currentTimeMillis(),264    ): DeviceRevocation? = mutationGate.withLock {265        knownLocalDeviceId = revokedByDeviceId266        val currentDevices = getAll()267        val currentRevocations = listRevocations()268        val mutation = planDeviceRevocation(269            devices = currentDevices,270            revocations = currentRevocations,271            deviceId = deviceId,272            revokedByDeviceId = revokedByDeviceId,273            nowMs = nowMs,274            protectedIssuerIds = protectedRevocationIssuers(),275        )276        // One verified transaction for both keys. Two independent apply() calls277        // can land separately, and a device removed without its revocation278        // record stops being blocked from re-admission — a silent failure of the279        // ejection path rather than a visible error.280        val priorPrefs = readPrefsState()281        val nextPrefs = priorPrefs.copy(282            devices = json.encodeToString(listSerializer, mutation.devices),283            revocations = json.encodeToString(revocationSerializer, mutation.revocations),284        )285        check(commitPrefsState(priorPrefs, nextPrefs)) {286            "paired_device_persist_failed"287        }288        mutation.added289    }290291    /**292     * `revokedAt` is peer-supplied and is NOT used for ordering. Existing293     * terminal records remain authoritative; only unprotected relayed records294     * may be evicted when the bounded ledger is full.295     */296    override fun mergeRevocations(incoming: List<DeviceRevocation>): List<String> {297        return mutationGate.withLock {298            val existing = listRevocations()299            val merged = mergeRevocationRecords(existing, incoming, protectedRevocationIssuers())300            if (merged.records != existing) persistRevocations(merged.records)301            merged.admitted.map { it.deviceId }302        }303    }304305    /**306     * Revocations this device issued, and those issued by a direct peer it307     * SAS-confirmed, are terminal: evicting one to make room would re-admit a308     * device the ledger exists to block (PB-26-130). Only relayed/indirect309     * records may be pruned when the ledger is full.310     *311     * The local device id is learned from [revoke] rather than loaded here: the312     * identity loader can mint, and a trust-decision path must not have that313     * side effect.314     */315    private fun protectedRevocationIssuers(): Set<String> = buildSet {316        knownLocalDeviceId?.let(::add)317        getAll().filter { it.trustSource == "direct" }.forEach { add(it.deviceId) }318    }319320    /**321     * Clear a revocation. The ONLY legitimate caller is a direct, SAS-confirmed322     * re-pair — a physically present user on both devices. Never call this from323     * a path a remote peer can reach.324     */325    override fun clearRevocation(deviceId: String) {326        mutationGate.withLock {327            val existing = listRevocations()328            val filtered = existing.filterNot { it.deviceId == deviceId }329            if (filtered.size != existing.size) persistRevocations(filtered)330        }331    }332333    fun clear() {334        mutationGate.withLock {335            val prior = copyRawTrustPreferences(prefs.all)336            val removed = prior.keys.filter { it == KEY_DEVICES || it == KEY_REVOCATIONS || it.startsWith(KEY_ISSUER_KEYS_PREFIX) }.toSet()337            val next = prior.filterKeys { it !in removed }338            check(commitWithRollback(prior, next) { state ->339                val edit = prefs.edit()340                removed.forEach(edit::remove)341                putRawTrustPreferences(edit, state.filterKeys { it in removed })342                edit.commit()343            }) { "paired_device_persist_failed" }344        }345    }346347    /** Verbatim logical copy of the whole registry, for the secure-reset archive. */348    internal fun snapshot(): Map<String, Any?> = mutationGate.withLock {349        copyRawTrustPreferences(prefs.all)350    }351352    /**353     * Refresh the device's `lastKnownIp` (the closest real analogue to the354     * brief's `lastSeen`). No-op when the id is unknown or [ip] is null.355     */356    fun updateLastSeen(id: String, ip: String? = null) {357        mutationGate.withLock {358            val current = get(id) ?: return@withLock359            if (ip == null) return@withLock360            upsert(current.copy(lastKnownIp = ip))361        }362    }363364    fun updateLastSync(id: String, at: Long = System.currentTimeMillis()) {365        mutationGate.withLock {366            val current = get(id) ?: return@withLock367            upsert(current.copy(lastSyncedAt = at))368        }369    }370371    /**372     * Reconnect prefers each pair's relay over the global fallback, so a relay373     * change in Settings only reaches established pairs by being written into374     * them. Skips the write when nothing moved, so the observers behind the375     * device list do not churn on a refused change.376     */377    fun propagateRelaySetting(mode: SyncMode, storedRelayUrl: String) {378        mutationGate.withLock {379            val current = getAll()380            val next = withRelaySetting(current, mode, storedRelayUrl)381            if (next != current) persist(next)382        }383    }384385    /**386     * Observe the full list. EncryptedSharedPreferences supports387     * OnSharedPreferenceChangeListener, so this emits on every persist —388     * including writes from other components in-process.389     */390    fun observeAll(): Flow<List<PairedDevice>> = callbackFlow {391        trySend(getAll())392        val listener = android.content.SharedPreferences.OnSharedPreferenceChangeListener { _, key ->393            if (key == KEY_DEVICES || key == null) trySend(getAll())394        }395        prefs.registerOnSharedPreferenceChangeListener(listener)396        awaitClose { prefs.unregisterOnSharedPreferenceChangeListener(listener) }397    }398399    override fun issuerSigningKeys(issuerDeviceId: String): Set<String> = mutationGate.withLock {400        readPrefsState().issuerKeys[issuerDeviceId].orEmpty().map(String::lowercase).toSet()401    }402403    /** Any known-key history at all: legacy trust state for the reset probe. */404    fun hasIssuerSigningKeys(): Boolean = mutationGate.withLock {405        readPrefsState().issuerKeys.isNotEmpty()406    }407408    override fun appendIssuerSigningKey(issuerDeviceId: String, signingKeyHex: String): Boolean {409        if (issuerDeviceId.isBlank() || !isSigningKey(signingKeyHex)) return false410        return mutationGate.withLock {411            val prior = readPrefsState()412            val key = signingKeyHex.lowercase()413            if (prior.issuerKeys[issuerDeviceId].orEmpty().any { it.equals(key, ignoreCase = true) }) {414                return@withLock true415            }416            val next = prior.copy(issuerKeys = withIssuerSigningKeys(prior.issuerKeys, mapOf(issuerDeviceId to setOf(key))))417            commitPrefsState(prior, next)418        }419    }420421    /**422     * Revocation mutations must be durable and verified. `apply()` returns423     * before the write is on disk, and losing the terminal ledger silently424     * un-revokes devices, so the ledger is never written that way.425     */426    private fun persistRevocations(records: List<DeviceRevocation>) {427        val prior = readPrefsState()428        val next = prior.copy(429            revocations = json.encodeToString(revocationSerializer, records),430        )431        check(commitPrefsState(prior, next)) {432            "paired_device_persist_failed"433        }434    }435436    private fun persist(devices: List<PairedDevice>) {437        prefs.edit().putString(KEY_DEVICES, json.encodeToString(listSerializer, devices)).apply()438    }439440    private fun sameTrustSnapshot(441        current: DeviceManifestRegistrySnapshot,442        expected: DeviceManifestRegistrySnapshot,443    ): Boolean {444        fun deviceCounts(devices: List<PairedDevice>) = devices.map {445            it.copy(lastSyncedAt = null, lastKnownIp = null, localAlias = null)446        }.groupingBy { it }.eachCount()447        return deviceCounts(current.devices) == deviceCounts(expected.devices) &&448            current.revocations == expected.revocations && current.issuerSigningKeys == expected.issuerSigningKeys449    }450451    private data class RegistryPrefsState(452        val devices: String?,453        val revocations: String?,454        val issuerKeys: Map<String, Set<String>>,455    )456457    private fun readPrefsState(): RegistryPrefsState {458        val all = prefs.all459        val issuerKeys = all.filterKeys { it.startsWith(KEY_ISSUER_KEYS_PREFIX) }.map { (key, value) ->460            val issuer = key.removePrefix(KEY_ISSUER_KEYS_PREFIX)461            if (issuer.isBlank() || value !is Set<*> || value.any { it !is String || !isSigningKey(it) }) {462                throw TrustDataCorruptedException(key, "invalid_issuer_signing_keys")463            }464            issuer to value.map { it as String }.toSet()465        }.toMap()466        return RegistryPrefsState(467            devices = snapshotString(all, KEY_DEVICES),468            revocations = snapshotString(all, KEY_REVOCATIONS),469            issuerKeys = issuerKeys,470        )471    }472473    private fun snapshotString(all: Map<String, *>, key: String): String? {474        val value = all[key]475        if (value == null && !all.containsKey(key)) return null476        if (value !is String) throw TrustDataCorruptedException(key, "invalid_string")477        return value478    }479480    private fun withIssuerSigningKeys(481        existing: Map<String, Set<String>>,482        incoming: Map<String, Set<String>>,483    ): Map<String, Set<String>> {484        val next = existing.toMutableMap()485        incoming.forEach { (issuer, keys) ->486            require(issuer.isNotBlank() && keys.all(::isSigningKey)) { "invalid_issuer_signing_keys" }487            val prior = next[issuer].orEmpty()488            val known = prior.map(String::lowercase).toSet()489            next[issuer] = prior + keys.map(String::lowercase).filterNot { it in known }490        }491        return next.toMap()492    }493494    private fun isSigningKey(key: String): Boolean =495        key.length == 64 && key.all { it in '0'..'9' || it in 'a'..'f' || it in 'A'..'F' }496497    private fun commitPrefsState(prior: RegistryPrefsState, next: RegistryPrefsState): Boolean {498        val changedIssuers = (prior.issuerKeys.keys + next.issuerKeys.keys).filter {499            prior.issuerKeys[it] != next.issuerKeys[it]500        }501        return commitWithRollback(prior, next) { state ->502            val edit = prefs.edit()503            if (prior.devices != next.devices) {504                if (state.devices == null) edit.remove(KEY_DEVICES) else edit.putString(KEY_DEVICES, state.devices)505            }506            if (prior.revocations != next.revocations) {507                if (state.revocations == null) edit.remove(KEY_REVOCATIONS) else edit.putString(KEY_REVOCATIONS, state.revocations)508            }509            changedIssuers.forEach { issuer ->510                val key = "$KEY_ISSUER_KEYS_PREFIX$issuer"511                val keys = state.issuerKeys[issuer]512                if (keys == null) edit.remove(key) else edit.putStringSet(key, keys.toSet())513            }514            edit.commit()515        }516    }517518    private companion object {519        const val PREFS_FILE = "peach_paired_devices"520        const val KEY_DEVICES = "paired_devices"521        const val KEY_REVOCATIONS = "device_revocations"522        const val KEY_ISSUER_KEYS_PREFIX = "issuer_signing_keys:"523        const val MAX_REVOCATIONS = MAX_REVOCATION_RECORDS524        val json = Json { encodeDefaults = true; ignoreUnknownKeys = true }525    }526}527528/**529 * §18.4: a corrupt persisted registry or revocation ledger is an integrity530 * error, not an empty list. Silently returning empty un-revokes every device.531 * The corrupt payload is preserved (the store never writes on this path) so a532 * future repair can attempt recovery.533 */534class TrustDataCorruptedException(key: String, detail: String) :535    RuntimeException("trust_data_corrupted:$key:$detail")536/** Preserve a persisted device's cryptographic identity across metadata updates. */537internal fun bindImmutableIdentity(existing: PairedDevice?, incoming: PairedDevice): PairedDevice {538    if (existing == null) return incoming539540    val longTermChanged = existing.longTermPublicKeyHex != null &&541        incoming.longTermPublicKeyHex != null &&542        !CryptoCompare.hex(existing.longTermPublicKeyHex, incoming.longTermPublicKeyHex)543    val signingChanged = existing.signingPublicKeyHex != null &&544        incoming.signingPublicKeyHex != null &&545        !CryptoCompare.hex(existing.signingPublicKeyHex, incoming.signingPublicKeyHex)546    require(!longTermChanged && !signingChanged) { "device_identity_immutable" }547548    return incoming.copy(549        longTermPublicKeyHex = incoming.longTermPublicKeyHex ?: existing.longTermPublicKeyHex,550        signingPublicKeyHex = incoming.signingPublicKeyHex ?: existing.signingPublicKeyHex,551    )552}553554/** Serialises whole-list registry mutations so stale snapshots cannot win. */555internal class RegistryMutationGate {556    private val lock = ReentrantLock()557558    fun <T> withLock(block: () -> T): T = lock.withLock(block)559}560561internal fun withLocalAlias(562    devices: List<PairedDevice>,563    deviceId: String,564    name: String,565): List<PairedDevice> {566    val alias = name.trim()567    require(alias.isNotEmpty()) { "device name must not be empty" }568    require(alias.length <= MAX_DEVICE_NAME_CHARS) { "device name must be 64 chars or fewer" }569    require(devices.any { it.deviceId == deviceId }) { "device_not_found" }570    return devices.map { if (it.deviceId == deviceId) it.copy(localAlias = alias) else it }571}572573internal data class DeviceRevocationMutation(574    val devices: List<PairedDevice>,575    val revocations: List<DeviceRevocation>,576    val added: DeviceRevocation?,577)578579/** A fresh pairing ceremony must not reuse terminally revoked identity material. */580internal fun hasAdoptionIdentityConflict(581    incoming: PairedDevice,582    devices: List<PairedDevice>,583    revocations: List<DeviceRevocation>,584): Boolean {585    if (devices.any { it.deviceId == incoming.deviceId }) return true586    if (devices.any {587        it.longTermPublicKeyHex?.let { key -> incoming.longTermPublicKeyHex?.let { candidate -> CryptoCompare.hex(key, candidate) } } == true ||588            it.signingPublicKeyHex?.let { key -> incoming.signingPublicKeyHex?.let { candidate -> CryptoCompare.hex(key, candidate) } } == true589    }) return true590    return revocations.any { revoked ->591        revoked.deviceId == incoming.deviceId ||592            incoming.longTermPublicKeyHex?.let { CryptoCompare.hex(revoked.longTermPublicKeyHex, it) } == true593    }594}595596/**597 * Compute one revoke transaction without Android storage so the impossible598 * "paired and already revoked" state can be regression-tested directly.599 *600 * Older builds could leave that overlap behind. A repeated Remove must still601 * drop the live row even though the terminal record itself is idempotent.602 */603internal fun planDeviceRevocation(604    devices: List<PairedDevice>,605    revocations: List<DeviceRevocation>,606    deviceId: String,607    revokedByDeviceId: String,608    nowMs: Long,609    protectedIssuerIds: Set<String> = emptySet(),610): DeviceRevocationMutation {611    val remaining = devices.filterNot { it.deviceId == deviceId }612    if (revocations.any { it.deviceId == deviceId }) {613        return DeviceRevocationMutation(remaining, revocations, null)614    }615    val device = devices.firstOrNull { it.deviceId == deviceId }616    val record = DeviceRevocation(617        deviceId = deviceId,618        longTermPublicKeyHex = device?.longTermPublicKeyHex ?: "0".repeat(64),619        revokedAt = nowMs,620        revokedByDeviceId = revokedByDeviceId,621    )622    return DeviceRevocationMutation(623        remaining,624        capRevocationRecords(revocations + record, protectedIssuerIds).records,625        record,626    )627}628internal data class RevocationMergeResult(629    val records: List<DeviceRevocation>,630    val admitted: List<DeviceRevocation>,631    val outcome: RevocationMergeOutcome = RevocationMergeOutcome.MERGED,632)633634internal enum class RevocationMergeOutcome {635    MERGED,636    OVERFLOW_PROTECTED_LEDGER,637}638639internal data class RevocationCapResult(640    val records: List<DeviceRevocation>,641    val outcome: RevocationMergeOutcome,642)643644internal fun mergeRevocationRecords(645    existing: List<DeviceRevocation>,646    incoming: List<DeviceRevocation>,647    protectedIssuerIds: Set<String> = emptySet(),648): RevocationMergeResult {649    val known = existing.map { it.deviceId }.toSet()650    val fresh = incoming.filterNot { known.contains(it.deviceId) }651    val capped = capRevocationRecords(existing + fresh, protectedIssuerIds)652    if (capped.outcome == RevocationMergeOutcome.OVERFLOW_PROTECTED_LEDGER) {653        return RevocationMergeResult(existing, emptyList(), capped.outcome)654    }655    val admitted = fresh.filter { candidate -> capped.records.any { it.deviceId == candidate.deviceId } }656    return RevocationMergeResult(capped.records, admitted, capped.outcome)657}658659/**660 * Keep the terminal ledger bounded. Records issued by this device or a direct661 * peer are protected; only relayed/indirect issuers are eviction candidates.662 * If all candidates are protected, refuse the new records rather than dropping663 * trusted state. The overflow outcome is explicit in the cap result.664 */665internal fun capRevocationRecords(666    records: List<DeviceRevocation>,667    protectedIssuerIds: Set<String> = emptySet(),668): RevocationCapResult {669    if (records.size <= MAX_REVOCATION_RECORDS) {670        return RevocationCapResult(records, RevocationMergeOutcome.MERGED)671    }672    val candidates = records.indices.filter { records[it].revokedByDeviceId !in protectedIssuerIds }673    if (candidates.size < records.size - MAX_REVOCATION_RECORDS) {674        return RevocationCapResult(records, RevocationMergeOutcome.OVERFLOW_PROTECTED_LEDGER)675    }676    val dropped = candidates.take(records.size - MAX_REVOCATION_RECORDS).toSet()677    return RevocationCapResult(678        records.filterIndexed { index, _ -> index !in dropped },679        RevocationMergeOutcome.MERGED,680    )681}682683/**684 * The mesh relay is pushed out through the same gate that decides whether to685 * dial one: a relay this device refuses to use must not be handed to peers686 * either — pushing Peach's own URL out under a "Private relay" label would tell687 * the same lie one layer down.688 */689internal fun withRelaySetting(690    devices: List<PairedDevice>,691    mode: SyncMode,692    storedRelayUrl: String,693): List<PairedDevice> = when (val decision = relayInForce(mode, storedRelayUrl)) {694    is RelayDecision.Dial -> devices.map { it.copy(relayUrl = decision.relayUrl) }695    is RelayDecision.Refuse -> devices696}