PairedDeviceStore.kt

16.8 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 =74        hasAdoptionIdentityConflict(device, getAll(), listRevocations())7576    /** Insert or replace by [PairedDevice.deviceId]. */77    override fun upsert(device: PairedDevice) {78        mutationGate.withLock {79            // Peer-supplied names arrive capped so a hostile peer cannot grow the80            // 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,84            )85            val next = getAll().filterNot { it.deviceId == device.deviceId } + device86            persist(next)87        }88    }8990    fun rename(deviceId: String, name: String) {91        mutationGate.withLock {92            persist(withLocalAlias(getAll(), deviceId, name))93        }94    }9596    override fun remove(deviceId: String) {97        mutationGate.withLock {98            persist(getAll().filterNot { it.deviceId == deviceId })99        }100    }101102    /**103     * Commit a staged manifest in one synchronous SharedPreferences transaction.104     * `apply()` is appropriate for ordinary UI writes, but it would expose each105     * per-device edit independently to observers and could leave an old-session106     * manifest half-applied across a lock. `commit()` updates both keys together107     * in memory and does not return until the durable write has completed.108     */109    override fun applyManifestBatch(batch: DeviceManifestRegistryBatch): Boolean {110        return mutationGate.withLock {111            val priorPrefs = readPrefsState()112            val currentDevices = getAll()113            val currentRevocations = listRevocations()114            val nextRevocations = mergeRevocationRecords(currentRevocations, batch.incomingRevocations).records115            val removed = batch.removals116            val nextDevices = currentDevices117                .filterNot { removed.contains(it.deviceId) }118                .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),123                    localAlias = alias,124                )125                nextDevices.removeAll { it.deviceId == device.deviceId }126                nextDevices += device127            }128129            val nextPrefs = RegistryPrefsState(130                devices = json.encodeToString(listSerializer, nextDevices),131                revocations = json.encodeToString(revocationSerializer, nextRevocations),132            )133            // Explicitly restore the old encrypted-preference values when commit()134            // reports false. The platform usually keeps them in memory, but a real135            // store failure must not rely on that undocumented outcome.136            commitWithRollback(priorPrefs, nextPrefs, ::writePrefsState)137        }138    }139140    // ── Device revocation (Part 5 §C) ────────────────────────────────────────141142    override fun listRevocations(): List<DeviceRevocation> {143        val raw = prefs.getString(KEY_REVOCATIONS, null) ?: return emptyList()144        return runCatching { json.decodeFromString(revocationSerializer, raw) }145            .getOrDefault(emptyList())146    }147148    /**149     * Revoke a device: record it, then drop it from the registry. The record150     * rides out in every manifest this device signs from now on. A stale entry151     * may survive in the pending-vouch queue; the confirm path re-checks152     * revocation before promoting anything out of it.153     */154    fun revoke(155        deviceId: String,156        revokedByDeviceId: String,157        nowMs: Long = System.currentTimeMillis(),158    ): DeviceRevocation? = mutationGate.withLock {159        val currentDevices = getAll()160        val currentRevocations = listRevocations()161        val mutation = planDeviceRevocation(162            devices = currentDevices,163            revocations = currentRevocations,164            deviceId = deviceId,165            revokedByDeviceId = revokedByDeviceId,166            nowMs = nowMs,167        )168        if (mutation.revocations !== currentRevocations) {169            persistRevocations(mutation.revocations)170        }171        if (mutation.devices != currentDevices) {172            persist(mutation.devices)173        }174        mutation.added175    }176177    /**178     * `revokedAt` is peer-supplied and is NOT used for ordering — revocation is179     * terminal, so an incoming record can never displace one already held.180     */181    override fun mergeRevocations(incoming: List<DeviceRevocation>): List<String> {182        return mutationGate.withLock {183            val existing = listRevocations()184            val merged = mergeRevocationRecords(existing, incoming)185            if (merged.records != existing) persistRevocations(merged.records)186            merged.admitted.map { it.deviceId }187        }188    }189190    /**191     * Clear a revocation. The ONLY legitimate caller is a direct, SAS-confirmed192     * re-pair — a physically present user on both devices. Never call this from193     * a path a remote peer can reach.194     */195    override fun clearRevocation(deviceId: String) {196        mutationGate.withLock {197            val existing = listRevocations()198            val filtered = existing.filterNot { it.deviceId == deviceId }199            if (filtered.size != existing.size) persistRevocations(filtered)200        }201    }202203    fun clear() {204        mutationGate.withLock {205            prefs.edit()206                .remove(KEY_DEVICES)207                .remove(KEY_REVOCATIONS)208                .apply()209        }210    }211212    /**213     * Refresh the device's `lastKnownIp` (the closest real analogue to the214     * brief's `lastSeen`). No-op when the id is unknown or [ip] is null.215     */216    fun updateLastSeen(id: String, ip: String? = null) {217        mutationGate.withLock {218            val current = get(id) ?: return@withLock219            if (ip == null) return@withLock220            upsert(current.copy(lastKnownIp = ip))221        }222    }223224    fun updateLastSync(id: String, at: Long = System.currentTimeMillis()) {225        mutationGate.withLock {226            val current = get(id) ?: return@withLock227            upsert(current.copy(lastSyncedAt = at))228        }229    }230231    /**232     * Reconnect prefers each pair's relay over the global fallback, so a relay233     * change in Settings only reaches established pairs by being written into234     * them. Skips the write when nothing moved, so the observers behind the235     * device list do not churn on a refused change.236     */237    fun propagateRelaySetting(mode: SyncMode, storedRelayUrl: String) {238        mutationGate.withLock {239            val current = getAll()240            val next = withRelaySetting(current, mode, storedRelayUrl)241            if (next != current) persist(next)242        }243    }244245    /**246     * Observe the full list. EncryptedSharedPreferences supports247     * OnSharedPreferenceChangeListener, so this emits on every persist —248     * including writes from other components in-process.249     */250    fun observeAll(): Flow<List<PairedDevice>> = callbackFlow {251        trySend(getAll())252        val listener = android.content.SharedPreferences.OnSharedPreferenceChangeListener { _, key ->253            if (key == KEY_DEVICES || key == null) trySend(getAll())254        }255        prefs.registerOnSharedPreferenceChangeListener(listener)256        awaitClose { prefs.unregisterOnSharedPreferenceChangeListener(listener) }257    }258259    private fun persistRevocations(records: List<DeviceRevocation>) {260        prefs.edit()261            .putString(KEY_REVOCATIONS, json.encodeToString(revocationSerializer, records))262            .apply()263    }264265    private fun persist(devices: List<PairedDevice>) {266        prefs.edit()267            .putString(KEY_DEVICES, json.encodeToString(listSerializer, devices))268            .apply()269    }270271    private data class RegistryPrefsState(272        val devices: String?,273        val revocations: String?,274    )275276    private fun readPrefsState(): RegistryPrefsState = RegistryPrefsState(277        devices = prefs.getString(KEY_DEVICES, null),278        revocations = prefs.getString(KEY_REVOCATIONS, null),279    )280281    private fun writePrefsState(state: RegistryPrefsState): Boolean {282        val edit = prefs.edit()283        if (state.devices == null) edit.remove(KEY_DEVICES) else edit.putString(KEY_DEVICES, state.devices)284        if (state.revocations == null) edit.remove(KEY_REVOCATIONS) else edit.putString(KEY_REVOCATIONS, state.revocations)285        return edit.commit()286    }287288    private companion object {289        const val PREFS_FILE = "peach_paired_devices"290        const val KEY_DEVICES = "paired_devices"291        const val KEY_REVOCATIONS = "device_revocations"292        /** Bound the list so a hostile peer cannot grow storage without limit. */293        const val MAX_REVOCATIONS = MAX_REVOCATION_RECORDS294        val json = Json { encodeDefaults = true; ignoreUnknownKeys = true }295    }296}297298/** Serialises whole-list registry mutations so stale snapshots cannot win. */299internal class RegistryMutationGate {300    private val lock = ReentrantLock()301302    fun <T> withLock(block: () -> T): T = lock.withLock(block)303}304305internal fun withLocalAlias(306    devices: List<PairedDevice>,307    deviceId: String,308    name: String,309): List<PairedDevice> {310    val alias = name.trim()311    require(alias.isNotEmpty()) { "device name must not be empty" }312    require(alias.length <= MAX_DEVICE_NAME_CHARS) { "device name must be 64 chars or fewer" }313    require(devices.any { it.deviceId == deviceId }) { "device_not_found" }314    return devices.map { if (it.deviceId == deviceId) it.copy(localAlias = alias) else it }315}316317internal data class DeviceRevocationMutation(318    val devices: List<PairedDevice>,319    val revocations: List<DeviceRevocation>,320    val added: DeviceRevocation?,321)322323/** A fresh pairing ceremony must not reuse terminally revoked identity material. */324internal fun hasAdoptionIdentityConflict(325    incoming: PairedDevice,326    devices: List<PairedDevice>,327    revocations: List<DeviceRevocation>,328): Boolean {329    if (devices.any { it.deviceId == incoming.deviceId }) return true330    return revocations.any { revoked ->331        revoked.deviceId == incoming.deviceId ||332            incoming.longTermPublicKeyHex?.let {333                CryptoCompare.hex(revoked.longTermPublicKeyHex, it)334            } == true335    }336}337338/**339 * Compute one revoke transaction without Android storage so the impossible340 * "paired and already revoked" state can be regression-tested directly.341 *342 * Older builds could leave that overlap behind. A repeated Remove must still343 * drop the live row even though the terminal record itself is idempotent.344 */345internal fun planDeviceRevocation(346    devices: List<PairedDevice>,347    revocations: List<DeviceRevocation>,348    deviceId: String,349    revokedByDeviceId: String,350    nowMs: Long,351): DeviceRevocationMutation {352    val remaining = devices.filterNot { it.deviceId == deviceId }353    if (revocations.any { it.deviceId == deviceId }) {354        return DeviceRevocationMutation(remaining, revocations, null)355    }356    val device = devices.firstOrNull { it.deviceId == deviceId }357    val record = DeviceRevocation(358        deviceId = deviceId,359        longTermPublicKeyHex = device?.longTermPublicKeyHex ?: "0".repeat(64),360        revokedAt = nowMs,361        revokedByDeviceId = revokedByDeviceId,362    )363    return DeviceRevocationMutation(364        remaining,365        capRevocationRecords(revocations + record),366        record,367    )368}369370internal data class RevocationMergeResult(371    val records: List<DeviceRevocation>,372    val admitted: List<DeviceRevocation>,373)374375internal fun mergeRevocationRecords(376    existing: List<DeviceRevocation>,377    incoming: List<DeviceRevocation>,378): RevocationMergeResult {379    val known = existing.map { it.deviceId }.toSet()380    val fresh = incoming.filterNot { known.contains(it.deviceId) }381    return RevocationMergeResult(capRevocationRecords(existing + fresh), fresh)382}383384/**385 * Keep the terminal ledger bounded without letting one issuer permanently386 * consume every slot. Each overflow drops the oldest record belonging to the387 * currently largest issuer, matching Browser's `capRevocations` policy.388 */389internal fun capRevocationRecords(records: List<DeviceRevocation>): List<DeviceRevocation> {390    if (records.size <= MAX_REVOCATION_RECORDS) return records391    val liveCounts = records.groupingBy { it.revokedByDeviceId }.eachCount().toMutableMap()392    val dropped = BooleanArray(records.size)393    repeat(records.size - MAX_REVOCATION_RECORDS) {394        val largestIssuer = liveCounts.maxByOrNull { it.value }?.key ?: return@repeat395        val oldestIndex = records.indices.firstOrNull { index ->396            !dropped[index] && records[index].revokedByDeviceId == largestIssuer397        } ?: return@repeat398        dropped[oldestIndex] = true399        liveCounts[largestIssuer] = liveCounts.getValue(largestIssuer) - 1400    }401    return records.filterIndexed { index, _ -> !dropped[index] }402}403404/**405 * The mesh relay is pushed out through the same gate that decides whether to406 * dial one: a relay this device refuses to use must not be handed to peers407 * either — pushing Peach's own URL out under a "Private relay" label would tell408 * the same lie one layer down.409 */410internal fun withRelaySetting(411    devices: List<PairedDevice>,412    mode: SyncMode,413    storedRelayUrl: String,414): List<PairedDevice> = when (val decision = relayInForce(mode, storedRelayUrl)) {415    is RelayDecision.Dial -> devices.map { it.copy(relayUrl = decision.relayUrl) }416    is RelayDecision.Refuse -> devices417}