PairedDeviceStore.kt

15.5 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    /** Insert or replace by [PairedDevice.deviceId]. */74    override fun upsert(device: PairedDevice) {75        mutationGate.withLock {76            // Peer-supplied names arrive capped so a hostile peer cannot grow the77            // registry without limit (adoption + direct-pair seams land here).78            val device = device.copy(79                deviceName = device.deviceName?.let(::capDeviceName),80                localAlias = get(device.deviceId)?.localAlias,81            )82            val next = getAll().filterNot { it.deviceId == device.deviceId } + device83            persist(next)84        }85    }8687    fun rename(deviceId: String, name: String) {88        mutationGate.withLock {89            persist(withLocalAlias(getAll(), deviceId, name))90        }91    }9293    override fun remove(deviceId: String) {94        mutationGate.withLock {95            persist(getAll().filterNot { it.deviceId == deviceId })96        }97    }9899    /**100     * Commit a staged manifest in one synchronous SharedPreferences transaction.101     * `apply()` is appropriate for ordinary UI writes, but it would expose each102     * per-device edit independently to observers and could leave an old-session103     * manifest half-applied across a lock. `commit()` updates both keys together104     * in memory and does not return until the durable write has completed.105     */106    override fun applyManifestBatch(batch: DeviceManifestRegistryBatch): Boolean {107        return mutationGate.withLock {108            val priorPrefs = readPrefsState()109            val currentDevices = getAll()110            val currentRevocations = listRevocations()111            val nextRevocations = mergeRevocationRecords(currentRevocations, batch.incomingRevocations).records112            val removed = batch.removals113            val nextDevices = currentDevices114                .filterNot { removed.contains(it.deviceId) }115                .toMutableList()116            batch.upserts.forEach { device ->117                val alias = nextDevices.firstOrNull { it.deviceId == device.deviceId }?.localAlias118                val device = device.copy(119                    deviceName = device.deviceName?.let(::capDeviceName),120                    localAlias = alias,121                )122                nextDevices.removeAll { it.deviceId == device.deviceId }123                nextDevices += device124            }125126            val nextPrefs = RegistryPrefsState(127                devices = json.encodeToString(listSerializer, nextDevices),128                revocations = json.encodeToString(revocationSerializer, nextRevocations),129            )130            // Explicitly restore the old encrypted-preference values when commit()131            // reports false. The platform usually keeps them in memory, but a real132            // store failure must not rely on that undocumented outcome.133            commitWithRollback(priorPrefs, nextPrefs, ::writePrefsState)134        }135    }136137    // ── Device revocation (Part 5 §C) ────────────────────────────────────────138139    override fun listRevocations(): List<DeviceRevocation> {140        val raw = prefs.getString(KEY_REVOCATIONS, null) ?: return emptyList()141        return runCatching { json.decodeFromString(revocationSerializer, raw) }142            .getOrDefault(emptyList())143    }144145    /**146     * Revoke a device: record it, then drop it from the registry. The record147     * rides out in every manifest this device signs from now on. A stale entry148     * may survive in the pending-vouch queue; the confirm path re-checks149     * revocation before promoting anything out of it.150     */151    fun revoke(152        deviceId: String,153        revokedByDeviceId: String,154        nowMs: Long = System.currentTimeMillis(),155    ): DeviceRevocation? = mutationGate.withLock {156        val currentDevices = getAll()157        val currentRevocations = listRevocations()158        val mutation = planDeviceRevocation(159            devices = currentDevices,160            revocations = currentRevocations,161            deviceId = deviceId,162            revokedByDeviceId = revokedByDeviceId,163            nowMs = nowMs,164        )165        if (mutation.revocations !== currentRevocations) {166            persistRevocations(mutation.revocations)167        }168        if (mutation.devices != currentDevices) {169            persist(mutation.devices)170        }171        mutation.added172    }173174    /**175     * `revokedAt` is peer-supplied and is NOT used for ordering — revocation is176     * terminal, so an incoming record can never displace one already held.177     */178    override fun mergeRevocations(incoming: List<DeviceRevocation>): List<String> {179        return mutationGate.withLock {180            val existing = listRevocations()181            val merged = mergeRevocationRecords(existing, incoming)182            if (merged.records != existing) persistRevocations(merged.records)183            merged.admitted.map { it.deviceId }184        }185    }186187    /**188     * Clear a revocation. The ONLY legitimate caller is a direct, SAS-confirmed189     * re-pair — a physically present user on both devices. Never call this from190     * a path a remote peer can reach.191     */192    override fun clearRevocation(deviceId: String) {193        mutationGate.withLock {194            val existing = listRevocations()195            val filtered = existing.filterNot { it.deviceId == deviceId }196            if (filtered.size != existing.size) persistRevocations(filtered)197        }198    }199200    fun clear() {201        mutationGate.withLock {202            prefs.edit()203                .remove(KEY_DEVICES)204                .remove(KEY_REVOCATIONS)205                .apply()206        }207    }208209    /**210     * Refresh the device's `lastKnownIp` (the closest real analogue to the211     * brief's `lastSeen`). No-op when the id is unknown or [ip] is null.212     */213    fun updateLastSeen(id: String, ip: String? = null) {214        mutationGate.withLock {215            val current = get(id) ?: return@withLock216            if (ip == null) return@withLock217            upsert(current.copy(lastKnownIp = ip))218        }219    }220221    fun updateLastSync(id: String, at: Long = System.currentTimeMillis()) {222        mutationGate.withLock {223            val current = get(id) ?: return@withLock224            upsert(current.copy(lastSyncedAt = at))225        }226    }227228    /**229     * Reconnect prefers each pair's relay over the global fallback, so a relay230     * change in Settings only reaches established pairs by being written into231     * them. Skips the write when nothing moved, so the observers behind the232     * device list do not churn on a refused change.233     */234    fun propagateRelaySetting(mode: SyncMode, storedRelayUrl: String) {235        mutationGate.withLock {236            val current = getAll()237            val next = withRelaySetting(current, mode, storedRelayUrl)238            if (next != current) persist(next)239        }240    }241242    /**243     * Observe the full list. EncryptedSharedPreferences supports244     * OnSharedPreferenceChangeListener, so this emits on every persist —245     * including writes from other components in-process.246     */247    fun observeAll(): Flow<List<PairedDevice>> = callbackFlow {248        trySend(getAll())249        val listener = android.content.SharedPreferences.OnSharedPreferenceChangeListener { _, key ->250            if (key == KEY_DEVICES || key == null) trySend(getAll())251        }252        prefs.registerOnSharedPreferenceChangeListener(listener)253        awaitClose { prefs.unregisterOnSharedPreferenceChangeListener(listener) }254    }255256    private fun persistRevocations(records: List<DeviceRevocation>) {257        prefs.edit()258            .putString(KEY_REVOCATIONS, json.encodeToString(revocationSerializer, records))259            .apply()260    }261262    private fun persist(devices: List<PairedDevice>) {263        prefs.edit()264            .putString(KEY_DEVICES, json.encodeToString(listSerializer, devices))265            .apply()266    }267268    private data class RegistryPrefsState(269        val devices: String?,270        val revocations: String?,271    )272273    private fun readPrefsState(): RegistryPrefsState = RegistryPrefsState(274        devices = prefs.getString(KEY_DEVICES, null),275        revocations = prefs.getString(KEY_REVOCATIONS, null),276    )277278    private fun writePrefsState(state: RegistryPrefsState): Boolean {279        val edit = prefs.edit()280        if (state.devices == null) edit.remove(KEY_DEVICES) else edit.putString(KEY_DEVICES, state.devices)281        if (state.revocations == null) edit.remove(KEY_REVOCATIONS) else edit.putString(KEY_REVOCATIONS, state.revocations)282        return edit.commit()283    }284285    private companion object {286        const val PREFS_FILE = "peach_paired_devices"287        const val KEY_DEVICES = "paired_devices"288        const val KEY_REVOCATIONS = "device_revocations"289        /** Bound the list so a hostile peer cannot grow storage without limit. */290        const val MAX_REVOCATIONS = MAX_REVOCATION_RECORDS291        val json = Json { encodeDefaults = true; ignoreUnknownKeys = true }292    }293}294295/** Serialises whole-list registry mutations so stale snapshots cannot win. */296internal class RegistryMutationGate {297    private val lock = ReentrantLock()298299    fun <T> withLock(block: () -> T): T = lock.withLock(block)300}301302internal fun withLocalAlias(303    devices: List<PairedDevice>,304    deviceId: String,305    name: String,306): List<PairedDevice> {307    val alias = name.trim()308    require(alias.isNotEmpty()) { "device name must not be empty" }309    require(alias.length <= MAX_DEVICE_NAME_CHARS) { "device name must be 64 chars or fewer" }310    require(devices.any { it.deviceId == deviceId }) { "device_not_found" }311    return devices.map { if (it.deviceId == deviceId) it.copy(localAlias = alias) else it }312}313314internal data class DeviceRevocationMutation(315    val devices: List<PairedDevice>,316    val revocations: List<DeviceRevocation>,317    val added: DeviceRevocation?,318)319320/**321 * Compute one revoke transaction without Android storage so the impossible322 * "paired and already revoked" state can be regression-tested directly.323 *324 * Older builds could leave that overlap behind. A repeated Remove must still325 * drop the live row even though the terminal record itself is idempotent.326 */327internal fun planDeviceRevocation(328    devices: List<PairedDevice>,329    revocations: List<DeviceRevocation>,330    deviceId: String,331    revokedByDeviceId: String,332    nowMs: Long,333): DeviceRevocationMutation {334    val remaining = devices.filterNot { it.deviceId == deviceId }335    if (revocations.any { it.deviceId == deviceId }) {336        return DeviceRevocationMutation(remaining, revocations, null)337    }338    val device = devices.firstOrNull { it.deviceId == deviceId }339    val record = DeviceRevocation(340        deviceId = deviceId,341        longTermPublicKeyHex = device?.longTermPublicKeyHex ?: "0".repeat(64),342        revokedAt = nowMs,343        revokedByDeviceId = revokedByDeviceId,344    )345    val retained = if (revocations.size < MAX_REVOCATION_RECORDS) {346        revocations347    } else {348        val removable = revocations.indexOfFirst { it.revokedByDeviceId != revokedByDeviceId }349        if (removable >= 0) revocations.toMutableList().also { it.removeAt(removable) } else revocations350    }351    return DeviceRevocationMutation(352        remaining,353        (retained + record).takeLast(MAX_REVOCATION_RECORDS),354        record,355    )356}357358internal data class RevocationMergeResult(359    val records: List<DeviceRevocation>,360    val admitted: List<DeviceRevocation>,361)362363internal fun mergeRevocationRecords(364    existing: List<DeviceRevocation>,365    incoming: List<DeviceRevocation>,366): RevocationMergeResult {367    val known = existing.map { it.deviceId }.toSet()368    val fresh = incoming.filterNot { known.contains(it.deviceId) }369    val admitted = fresh.take((MAX_REVOCATION_RECORDS - existing.size).coerceAtLeast(0))370    return RevocationMergeResult(existing + admitted, admitted)371}372373/**374 * The mesh relay is pushed out through the same gate that decides whether to375 * dial one: a relay this device refuses to use must not be handed to peers376 * either — pushing Peach's own URL out under a "Private relay" label would tell377 * the same lie one layer down.378 */379internal fun withRelaySetting(380    devices: List<PairedDevice>,381    mode: SyncMode,382    storedRelayUrl: String,383): List<PairedDevice> = when (val decision = relayInForce(mode, storedRelayUrl)) {384    is RelayDecision.Dial -> devices.map { it.copy(relayUrl = decision.relayUrl) }385    is RelayDecision.Refuse -> devices386}