PairedDeviceStore.kt

13.0 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 javax.inject.Inject13import javax.inject.Singleton1415/**16 * Persistent registry of paired devices, encrypted at rest with17 * EncryptedSharedPreferences (same construction as DuressConfigStore /18 * LicenseRepository, v2.1.36). The whole list lives under a single key as a19 * kotlinx.serialization JSON array of the REAL [PairedDevice] (sync package).20 *21 * Reconciliation with the C7 brief:22 *  - The brief invents a fresh `PairedDevice(id, name, publicKey: ByteArray,23 *    lastSeen, trustStatus, lastSyncAt)`. That type does NOT exist in this24 *    shape. The real [PairedDevice] (PairedDevice.kt) keys on `deviceId`, holds25 *    the public key as `longTermPublicKeyHex` (hex, not ByteArray), and tracks26 *    `pairedAt` / `lastSyncedAt` / `lastKnownIp`. This store reuses it verbatim;27 *    Base64 publicKey storage is therefore unnecessary — the hex field is the28 *    canonical wire form already produced by PairingFrames.frameToPairedDevice.29 *  - The brief's `TrustStatus` enum does not exist either. The real model uses a30 *    nullable `trustSource: String?` (e.g. "direct", "manifest"). Trust state is31 *    expressed there. See C7-INTEGRATION.md for the trust-status delta.32 *  - `updateLastSync` here maps to the real `lastSyncedAt` field. There is no33 *    `lastSeen` field on the real PairedDevice; [updateLastSeen] folds into34 *    `lastKnownIp` refresh + `lastSyncedAt` is left untouched. It is kept as a35 *    no-op-friendly hook so callers from the brief compile; see integration note.36 */37@Singleton38class PairedDeviceStore @Inject constructor(39    @ApplicationContext context: Context,40) : PairedDeviceRegistry {41    private val masterKey = MasterKey.Builder(context)42        .setKeyScheme(MasterKey.KeyScheme.AES256_GCM)43        .build()4445    private val prefs = EncryptedSharedPreferences.create(46        context,47        PREFS_FILE,48        masterKey,49        EncryptedSharedPreferences.PrefKeyEncryptionScheme.AES256_SIV,50        EncryptedSharedPreferences.PrefValueEncryptionScheme.AES256_GCM,51    )5253    private val listSerializer = ListSerializer(PairedDevice.serializer())54    private val revocationSerializer = ListSerializer(DeviceRevocation.serializer())5556    override fun getAll(): List<PairedDevice> {57        val raw = prefs.getString(KEY_DEVICES, null) ?: return emptyList()58        return runCatching { json.decodeFromString(listSerializer, raw) }.getOrDefault(emptyList())59    }6061    override fun get(id: String): PairedDevice? = getAll().firstOrNull { it.deviceId == id }6263    override fun getByPubkey(pubkeyHex: String): PairedDevice? =64        getAll().firstOrNull {65            it.longTermPublicKeyHex?.let { key -> CryptoCompare.hex(key, pubkeyHex) } == true66        }6768    /** Insert or replace by [PairedDevice.deviceId]. */69    override fun upsert(device: PairedDevice) {70        // Peer-supplied names arrive capped so a hostile peer cannot grow the71        // registry without limit (adoption + direct-pair seams land here).72        val device = device.copy(deviceName = device.deviceName?.let(::capDeviceName))73        val next = getAll().filterNot { it.deviceId == device.deviceId } + device74        persist(next)75    }7677    override fun remove(deviceId: String) {78        persist(getAll().filterNot { it.deviceId == deviceId })79    }8081    /**82     * Commit a staged manifest in one synchronous SharedPreferences transaction.83     * `apply()` is appropriate for ordinary UI writes, but it would expose each84     * per-device edit independently to observers and could leave an old-session85     * manifest half-applied across a lock. `commit()` updates both keys together86     * in memory and does not return until the durable write has completed.87     */88    override fun applyManifestBatch(batch: DeviceManifestRegistryBatch): Boolean {89        val priorPrefs = readPrefsState()90        val currentDevices = getAll()91        val currentRevocations = listRevocations()92        val knownRevokedIds = currentRevocations.map { it.deviceId }.toSet()93        val freshRevocations = batch.incomingRevocations.filterNot { knownRevokedIds.contains(it.deviceId) }94        val nextRevocations = (currentRevocations + freshRevocations).takeLast(MAX_REVOCATIONS)95        val removed = batch.removals96        val nextDevices = currentDevices97            .filterNot { removed.contains(it.deviceId) }98            .toMutableList()99        batch.upserts.forEach { device ->100            val device = device.copy(deviceName = device.deviceName?.let(::capDeviceName))101            nextDevices.removeAll { it.deviceId == device.deviceId }102            nextDevices += device103        }104105        val nextPrefs = RegistryPrefsState(106            devices = json.encodeToString(listSerializer, nextDevices),107            revocations = json.encodeToString(revocationSerializer, nextRevocations),108        )109        // Explicitly restore the old encrypted-preference values when commit()110        // reports false. The platform usually keeps them in memory, but a real111        // store failure must not rely on that undocumented outcome.112        return commitWithRollback(priorPrefs, nextPrefs, ::writePrefsState)113    }114115    // ── Device revocation (Part 5 §C) ────────────────────────────────────────116117    override fun listRevocations(): List<DeviceRevocation> {118        val raw = prefs.getString(KEY_REVOCATIONS, null) ?: return emptyList()119        return runCatching { json.decodeFromString(revocationSerializer, raw) }120            .getOrDefault(emptyList())121    }122123    /**124     * Revoke a device: record it, then drop it from the registry. The record125     * rides out in every manifest this device signs from now on. A stale entry126     * may survive in the pending-vouch queue; the confirm path re-checks127     * revocation before promoting anything out of it.128     */129    fun revoke(130        deviceId: String,131        revokedByDeviceId: String,132        nowMs: Long = System.currentTimeMillis(),133    ): DeviceRevocation? {134        val currentDevices = getAll()135        val currentRevocations = listRevocations()136        val mutation = planDeviceRevocation(137            devices = currentDevices,138            revocations = currentRevocations,139            deviceId = deviceId,140            revokedByDeviceId = revokedByDeviceId,141            nowMs = nowMs,142        )143        if (mutation.revocations !== currentRevocations) {144            persistRevocations(mutation.revocations)145        }146        if (mutation.devices != currentDevices) {147            persist(mutation.devices)148        }149        return mutation.added150    }151152    /**153     * `revokedAt` is peer-supplied and is NOT used for ordering — revocation is154     * terminal, so an incoming record can never displace one already held.155     */156    override fun mergeRevocations(incoming: List<DeviceRevocation>): List<String> {157        val existing = listRevocations()158        val known = existing.map { it.deviceId }.toSet()159        val fresh = incoming.filterNot { known.contains(it.deviceId) }160        if (fresh.isEmpty()) return emptyList()161        persistRevocations((existing + fresh).takeLast(MAX_REVOCATIONS))162        return fresh.map { it.deviceId }163    }164165    /**166     * Clear a revocation. The ONLY legitimate caller is a direct, SAS-confirmed167     * re-pair — a physically present user on both devices. Never call this from168     * a path a remote peer can reach.169     */170    override fun clearRevocation(deviceId: String) {171        val existing = listRevocations()172        val filtered = existing.filterNot { it.deviceId == deviceId }173        if (filtered.size != existing.size) persistRevocations(filtered)174    }175176    fun clear() {177        prefs.edit()178            .remove(KEY_DEVICES)179            .remove(KEY_REVOCATIONS)180            .apply()181    }182183    /**184     * Refresh the device's `lastKnownIp` (the closest real analogue to the185     * brief's `lastSeen`). No-op when the id is unknown or [ip] is null.186     */187    fun updateLastSeen(id: String, ip: String? = null) {188        val current = get(id) ?: return189        if (ip == null) return190        upsert(current.copy(lastKnownIp = ip))191    }192193    fun updateLastSync(id: String, at: Long = System.currentTimeMillis()) {194        val current = get(id) ?: return195        upsert(current.copy(lastSyncedAt = at))196    }197198    /**199     * Reconnect prefers each pair's relay over the global fallback, so a relay200     * change in Settings only reaches established pairs by being written into201     * them. Skips the write when nothing moved, so the observers behind the202     * device list do not churn on a refused change.203     */204    fun propagateRelaySetting(mode: SyncMode, storedRelayUrl: String) {205        val current = getAll()206        val next = withRelaySetting(current, mode, storedRelayUrl)207        if (next != current) persist(next)208    }209210    /**211     * Observe the full list. EncryptedSharedPreferences supports212     * OnSharedPreferenceChangeListener, so this emits on every persist —213     * including writes from other components in-process.214     */215    fun observeAll(): Flow<List<PairedDevice>> = callbackFlow {216        trySend(getAll())217        val listener = android.content.SharedPreferences.OnSharedPreferenceChangeListener { _, key ->218            if (key == KEY_DEVICES || key == null) trySend(getAll())219        }220        prefs.registerOnSharedPreferenceChangeListener(listener)221        awaitClose { prefs.unregisterOnSharedPreferenceChangeListener(listener) }222    }223224    private fun persistRevocations(records: List<DeviceRevocation>) {225        prefs.edit()226            .putString(KEY_REVOCATIONS, json.encodeToString(revocationSerializer, records))227            .apply()228    }229230    private fun persist(devices: List<PairedDevice>) {231        prefs.edit()232            .putString(KEY_DEVICES, json.encodeToString(listSerializer, devices))233            .apply()234    }235236    private data class RegistryPrefsState(237        val devices: String?,238        val revocations: String?,239    )240241    private fun readPrefsState(): RegistryPrefsState = RegistryPrefsState(242        devices = prefs.getString(KEY_DEVICES, null),243        revocations = prefs.getString(KEY_REVOCATIONS, null),244    )245246    private fun writePrefsState(state: RegistryPrefsState): Boolean {247        val edit = prefs.edit()248        if (state.devices == null) edit.remove(KEY_DEVICES) else edit.putString(KEY_DEVICES, state.devices)249        if (state.revocations == null) edit.remove(KEY_REVOCATIONS) else edit.putString(KEY_REVOCATIONS, state.revocations)250        return edit.commit()251    }252253    private companion object {254        const val PREFS_FILE = "peach_paired_devices"255        const val KEY_DEVICES = "paired_devices"256        const val KEY_REVOCATIONS = "device_revocations"257        /** Bound the list so a hostile peer cannot grow storage without limit. */258        const val MAX_REVOCATIONS = 500259        val json = Json { encodeDefaults = true; ignoreUnknownKeys = true }260    }261}262263internal data class DeviceRevocationMutation(264    val devices: List<PairedDevice>,265    val revocations: List<DeviceRevocation>,266    val added: DeviceRevocation?,267)268269/**270 * Compute one revoke transaction without Android storage so the impossible271 * "paired and already revoked" state can be regression-tested directly.272 *273 * Older builds could leave that overlap behind. A repeated Remove must still274 * drop the live row even though the terminal record itself is idempotent.275 */276internal fun planDeviceRevocation(277    devices: List<PairedDevice>,278    revocations: List<DeviceRevocation>,279    deviceId: String,280    revokedByDeviceId: String,281    nowMs: Long,282): DeviceRevocationMutation {283    val remaining = devices.filterNot { it.deviceId == deviceId }284    if (revocations.any { it.deviceId == deviceId }) {285        return DeviceRevocationMutation(remaining, revocations, null)286    }287    val device = devices.firstOrNull { it.deviceId == deviceId }288    val record = DeviceRevocation(289        deviceId = deviceId,290        longTermPublicKeyHex = device?.longTermPublicKeyHex ?: "0".repeat(64),291        revokedAt = nowMs,292        revokedByDeviceId = revokedByDeviceId,293    )294    return DeviceRevocationMutation(remaining, revocations + record, record)295}296297/**298 * The mesh relay is pushed out through the same gate that decides whether to299 * dial one: a relay this device refuses to use must not be handed to peers300 * either — pushing Peach's own URL out under a "Private relay" label would tell301 * the same lie one layer down.302 */303internal fun withRelaySetting(304    devices: List<PairedDevice>,305    mode: SyncMode,306    storedRelayUrl: String,307): List<PairedDevice> = when (val decision = relayInForce(mode, storedRelayUrl)) {308    is RelayDecision.Dial -> devices.map { it.copy(relayUrl = decision.relayUrl) }309    is RelayDecision.Refuse -> devices310}