PairedDeviceStore.kt

15.6 KB · raw

1package com.peachpasswords.sync23import android.content.Context4import androidx.security.crypto.EncryptedSharedPreferences5import androidx.security.crypto.MasterKey6import dagger.hilt.android.qualifiers.ApplicationContext7import kotlinx.coroutines.channels.awaitClose8import kotlinx.coroutines.flow.Flow9import kotlinx.coroutines.flow.callbackFlow10import kotlinx.serialization.builtins.ListSerializer11import kotlinx.serialization.json.Json12import java.util.concurrent.locks.ReentrantLock13import javax.inject.Inject14import javax.inject.Singleton15import kotlin.concurrent.withLock1617private const val MAX_REVOCATION_RECORDS = 5001819/**20 * Persistent registry of paired devices, encrypted at rest with21 * EncryptedSharedPreferences (same construction as DuressConfigStore /22 * LicenseRepository, v2.1.36). The whole list lives under a single key as a23 * kotlinx.serialization JSON array of the REAL [PairedDevice] (sync package).24 *25 * Reconciliation with the C7 brief:26 *  - The brief invents a fresh `PairedDevice(id, name, publicKey: ByteArray,27 *    lastSeen, trustStatus, lastSyncAt)`. That type does NOT exist in this28 *    shape. The real [PairedDevice] (PairedDevice.kt) keys on `deviceId`, holds29 *    the public key as `longTermPublicKeyHex` (hex, not ByteArray), and tracks30 *    `pairedAt` / `lastSyncedAt` / `lastKnownIp`. This store reuses it verbatim;31 *    Base64 publicKey storage is therefore unnecessary — the hex field is the32 *    canonical wire form already produced by PairingFrames.frameToPairedDevice.33 *  - The brief's `TrustStatus` enum does not exist either. The real model uses a34 *    nullable `trustSource: String?` (e.g. "direct", "manifest"). Trust state is35 *    expressed there. See C7-INTEGRATION.md for the trust-status delta.36 *  - `updateLastSync` here maps to the real `lastSyncedAt` field. There is no37 *    `lastSeen` field on the real PairedDevice; [updateLastSeen] folds into38 *    `lastKnownIp` refresh + `lastSyncedAt` is left untouched. It is kept as a39 *    no-op-friendly hook so callers from the brief compile; see integration note.40 */41@Singleton42class PairedDeviceStore @Inject constructor(43    @ApplicationContext context: Context,44) : PairedDeviceRegistry {45    private val masterKey = MasterKey.Builder(context)46        .setKeyScheme(MasterKey.KeyScheme.AES256_GCM)47        .build()4849    private val prefs = EncryptedSharedPreferences.create(50        context,51        PREFS_FILE,52        masterKey,53        EncryptedSharedPreferences.PrefKeyEncryptionScheme.AES256_SIV,54        EncryptedSharedPreferences.PrefValueEncryptionScheme.AES256_GCM,55    )5657    private val listSerializer = ListSerializer(PairedDevice.serializer())58    private val revocationSerializer = ListSerializer(DeviceRevocation.serializer())59    private val mutationGate = RegistryMutationGate()6061    override fun getAll(): List<PairedDevice> {62        val raw = prefs.getString(KEY_DEVICES, null) ?: return emptyList()63        return runCatching { json.decodeFromString(listSerializer, raw) }.getOrDefault(emptyList())64    }6566    override fun get(id: String): PairedDevice? = getAll().firstOrNull { it.deviceId == id }6768    override fun getByPubkey(pubkeyHex: String): PairedDevice? =69        getAll().firstOrNull {70            it.longTermPublicKeyHex?.let { key -> CryptoCompare.hex(key, pubkeyHex) } == true71        }7273    fun hasIdentityCollision(device: PairedDevice): Boolean = get(device.deviceId) != null7475    /** Insert or replace by [PairedDevice.deviceId]. */76    override fun upsert(device: PairedDevice) {77        mutationGate.withLock {78            // Peer-supplied names arrive capped so a hostile peer cannot grow the79            // registry without limit (adoption + direct-pair seams land here).80            val device = device.copy(81                deviceName = device.deviceName?.let(::capDeviceName),82                localAlias = get(device.deviceId)?.localAlias,83            )84            val next = getAll().filterNot { it.deviceId == device.deviceId } + device85            persist(next)86        }87    }8889    fun rename(deviceId: String, name: String) {90        mutationGate.withLock {91            persist(withLocalAlias(getAll(), deviceId, name))92        }93    }9495    override fun remove(deviceId: String) {96        mutationGate.withLock {97            persist(getAll().filterNot { it.deviceId == deviceId })98        }99    }100101    /**102     * Commit a staged manifest in one synchronous SharedPreferences transaction.103     * `apply()` is appropriate for ordinary UI writes, but it would expose each104     * per-device edit independently to observers and could leave an old-session105     * manifest half-applied across a lock. `commit()` updates both keys together106     * in memory and does not return until the durable write has completed.107     */108    override fun applyManifestBatch(batch: DeviceManifestRegistryBatch): Boolean {109        return mutationGate.withLock {110            val priorPrefs = readPrefsState()111            val currentDevices = getAll()112            val currentRevocations = listRevocations()113            val nextRevocations = mergeRevocationRecords(currentRevocations, batch.incomingRevocations).records114            val removed = batch.removals115            val nextDevices = currentDevices116                .filterNot { removed.contains(it.deviceId) }117                .toMutableList()118            batch.upserts.forEach { device ->119                val alias = nextDevices.firstOrNull { it.deviceId == device.deviceId }?.localAlias120                val device = device.copy(121                    deviceName = device.deviceName?.let(::capDeviceName),122                    localAlias = alias,123                )124                nextDevices.removeAll { it.deviceId == device.deviceId }125                nextDevices += device126            }127128            val nextPrefs = RegistryPrefsState(129                devices = json.encodeToString(listSerializer, nextDevices),130                revocations = json.encodeToString(revocationSerializer, nextRevocations),131            )132            // Explicitly restore the old encrypted-preference values when commit()133            // reports false. The platform usually keeps them in memory, but a real134            // store failure must not rely on that undocumented outcome.135            commitWithRollback(priorPrefs, nextPrefs, ::writePrefsState)136        }137    }138139    // ── Device revocation (Part 5 §C) ────────────────────────────────────────140141    override fun listRevocations(): List<DeviceRevocation> {142        val raw = prefs.getString(KEY_REVOCATIONS, null) ?: return emptyList()143        return runCatching { json.decodeFromString(revocationSerializer, raw) }144            .getOrDefault(emptyList())145    }146147    /**148     * Revoke a device: record it, then drop it from the registry. The record149     * rides out in every manifest this device signs from now on. A stale entry150     * may survive in the pending-vouch queue; the confirm path re-checks151     * revocation before promoting anything out of it.152     */153    fun revoke(154        deviceId: String,155        revokedByDeviceId: String,156        nowMs: Long = System.currentTimeMillis(),157    ): DeviceRevocation? = mutationGate.withLock {158        val currentDevices = getAll()159        val currentRevocations = listRevocations()160        val mutation = planDeviceRevocation(161            devices = currentDevices,162            revocations = currentRevocations,163            deviceId = deviceId,164            revokedByDeviceId = revokedByDeviceId,165            nowMs = nowMs,166        )167        if (mutation.revocations !== currentRevocations) {168            persistRevocations(mutation.revocations)169        }170        if (mutation.devices != currentDevices) {171            persist(mutation.devices)172        }173        mutation.added174    }175176    /**177     * `revokedAt` is peer-supplied and is NOT used for ordering — revocation is178     * terminal, so an incoming record can never displace one already held.179     */180    override fun mergeRevocations(incoming: List<DeviceRevocation>): List<String> {181        return mutationGate.withLock {182            val existing = listRevocations()183            val merged = mergeRevocationRecords(existing, incoming)184            if (merged.records != existing) persistRevocations(merged.records)185            merged.admitted.map { it.deviceId }186        }187    }188189    /**190     * Clear a revocation. The ONLY legitimate caller is a direct, SAS-confirmed191     * re-pair — a physically present user on both devices. Never call this from192     * a path a remote peer can reach.193     */194    override fun clearRevocation(deviceId: String) {195        mutationGate.withLock {196            val existing = listRevocations()197            val filtered = existing.filterNot { it.deviceId == deviceId }198            if (filtered.size != existing.size) persistRevocations(filtered)199        }200    }201202    fun clear() {203        mutationGate.withLock {204            prefs.edit()205                .remove(KEY_DEVICES)206                .remove(KEY_REVOCATIONS)207                .apply()208        }209    }210211    /**212     * Refresh the device's `lastKnownIp` (the closest real analogue to the213     * brief's `lastSeen`). No-op when the id is unknown or [ip] is null.214     */215    fun updateLastSeen(id: String, ip: String? = null) {216        mutationGate.withLock {217            val current = get(id) ?: return@withLock218            if (ip == null) return@withLock219            upsert(current.copy(lastKnownIp = ip))220        }221    }222223    fun updateLastSync(id: String, at: Long = System.currentTimeMillis()) {224        mutationGate.withLock {225            val current = get(id) ?: return@withLock226            upsert(current.copy(lastSyncedAt = at))227        }228    }229230    /**231     * Reconnect prefers each pair's relay over the global fallback, so a relay232     * change in Settings only reaches established pairs by being written into233     * them. Skips the write when nothing moved, so the observers behind the234     * device list do not churn on a refused change.235     */236    fun propagateRelaySetting(mode: SyncMode, storedRelayUrl: String) {237        mutationGate.withLock {238            val current = getAll()239            val next = withRelaySetting(current, mode, storedRelayUrl)240            if (next != current) persist(next)241        }242    }243244    /**245     * Observe the full list. EncryptedSharedPreferences supports246     * OnSharedPreferenceChangeListener, so this emits on every persist —247     * including writes from other components in-process.248     */249    fun observeAll(): Flow<List<PairedDevice>> = callbackFlow {250        trySend(getAll())251        val listener = android.content.SharedPreferences.OnSharedPreferenceChangeListener { _, key ->252            if (key == KEY_DEVICES || key == null) trySend(getAll())253        }254        prefs.registerOnSharedPreferenceChangeListener(listener)255        awaitClose { prefs.unregisterOnSharedPreferenceChangeListener(listener) }256    }257258    private fun persistRevocations(records: List<DeviceRevocation>) {259        prefs.edit()260            .putString(KEY_REVOCATIONS, json.encodeToString(revocationSerializer, records))261            .apply()262    }263264    private fun persist(devices: List<PairedDevice>) {265        prefs.edit()266            .putString(KEY_DEVICES, json.encodeToString(listSerializer, devices))267            .apply()268    }269270    private data class RegistryPrefsState(271        val devices: String?,272        val revocations: String?,273    )274275    private fun readPrefsState(): RegistryPrefsState = RegistryPrefsState(276        devices = prefs.getString(KEY_DEVICES, null),277        revocations = prefs.getString(KEY_REVOCATIONS, null),278    )279280    private fun writePrefsState(state: RegistryPrefsState): Boolean {281        val edit = prefs.edit()282        if (state.devices == null) edit.remove(KEY_DEVICES) else edit.putString(KEY_DEVICES, state.devices)283        if (state.revocations == null) edit.remove(KEY_REVOCATIONS) else edit.putString(KEY_REVOCATIONS, state.revocations)284        return edit.commit()285    }286287    private companion object {288        const val PREFS_FILE = "peach_paired_devices"289        const val KEY_DEVICES = "paired_devices"290        const val KEY_REVOCATIONS = "device_revocations"291        /** Bound the list so a hostile peer cannot grow storage without limit. */292        const val MAX_REVOCATIONS = MAX_REVOCATION_RECORDS293        val json = Json { encodeDefaults = true; ignoreUnknownKeys = true }294    }295}296297/** Serialises whole-list registry mutations so stale snapshots cannot win. */298internal class RegistryMutationGate {299    private val lock = ReentrantLock()300301    fun <T> withLock(block: () -> T): T = lock.withLock(block)302}303304internal fun withLocalAlias(305    devices: List<PairedDevice>,306    deviceId: String,307    name: String,308): List<PairedDevice> {309    val alias = name.trim()310    require(alias.isNotEmpty()) { "device name must not be empty" }311    require(alias.length <= MAX_DEVICE_NAME_CHARS) { "device name must be 64 chars or fewer" }312    require(devices.any { it.deviceId == deviceId }) { "device_not_found" }313    return devices.map { if (it.deviceId == deviceId) it.copy(localAlias = alias) else it }314}315316internal data class DeviceRevocationMutation(317    val devices: List<PairedDevice>,318    val revocations: List<DeviceRevocation>,319    val added: DeviceRevocation?,320)321322/**323 * Compute one revoke transaction without Android storage so the impossible324 * "paired and already revoked" state can be regression-tested directly.325 *326 * Older builds could leave that overlap behind. A repeated Remove must still327 * drop the live row even though the terminal record itself is idempotent.328 */329internal fun planDeviceRevocation(330    devices: List<PairedDevice>,331    revocations: List<DeviceRevocation>,332    deviceId: String,333    revokedByDeviceId: String,334    nowMs: Long,335): DeviceRevocationMutation {336    val remaining = devices.filterNot { it.deviceId == deviceId }337    if (revocations.any { it.deviceId == deviceId }) {338        return DeviceRevocationMutation(remaining, revocations, null)339    }340    val device = devices.firstOrNull { it.deviceId == deviceId }341    val record = DeviceRevocation(342        deviceId = deviceId,343        longTermPublicKeyHex = device?.longTermPublicKeyHex ?: "0".repeat(64),344        revokedAt = nowMs,345        revokedByDeviceId = revokedByDeviceId,346    )347    val retained = if (revocations.size < MAX_REVOCATION_RECORDS) {348        revocations349    } else {350        val removable = revocations.indexOfFirst { it.revokedByDeviceId != revokedByDeviceId }351        if (removable >= 0) revocations.toMutableList().also { it.removeAt(removable) } else revocations352    }353    return DeviceRevocationMutation(354        remaining,355        (retained + record).takeLast(MAX_REVOCATION_RECORDS),356        record,357    )358}359360internal data class RevocationMergeResult(361    val records: List<DeviceRevocation>,362    val admitted: List<DeviceRevocation>,363)364365internal fun mergeRevocationRecords(366    existing: List<DeviceRevocation>,367    incoming: List<DeviceRevocation>,368): RevocationMergeResult {369    val known = existing.map { it.deviceId }.toSet()370    val fresh = incoming.filterNot { known.contains(it.deviceId) }371    val admitted = fresh.take((MAX_REVOCATION_RECORDS - existing.size).coerceAtLeast(0))372    return RevocationMergeResult(existing + admitted, admitted)373}374375/**376 * The mesh relay is pushed out through the same gate that decides whether to377 * dial one: a relay this device refuses to use must not be handed to peers378 * either — pushing Peach's own URL out under a "Private relay" label would tell379 * the same lie one layer down.380 */381internal fun withRelaySetting(382    devices: List<PairedDevice>,383    mode: SyncMode,384    storedRelayUrl: String,385): List<PairedDevice> = when (val decision = relayInForce(mode, storedRelayUrl)) {386    is RelayDecision.Dial -> devices.map { it.copy(relayUrl = decision.relayUrl) }387    is RelayDecision.Refuse -> devices388}