PairedDeviceStore.kt

22.4 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 a directly re-paired device and clear its terminal revocation atomically. */77    fun upsertAndClearRevocation(device: PairedDevice) {78        mutationGate.withLock {79            val currentDevices = getAll()80            val existing = currentDevices.firstOrNull { it.deviceId == device.deviceId }81            val bound = bindImmutableIdentity(existing, device)82            val nextDevice = bound.copy(83                deviceName = bound.deviceName?.let(::capDeviceName),84                localAlias = existing?.localAlias,85            )86            val nextDevices = currentDevices.filterNot { it.deviceId == device.deviceId } + nextDevice87            val currentRevocations = listRevocations()88            val nextRevocations = currentRevocations.filterNot { it.deviceId == device.deviceId }89            val nextPrefs = RegistryPrefsState(90                devices = json.encodeToString(listSerializer, nextDevices),91                revocations = json.encodeToString(revocationSerializer, nextRevocations),92            )93            check(commitWithRollback(readPrefsState(), nextPrefs, ::writePrefsState)) {94                "paired_device_persist_failed"95            }96        }97    }9899    /** Insert or replace by [PairedDevice.deviceId], without changing its cryptographic identity. */100    override fun upsert(device: PairedDevice) {101        mutationGate.withLock {102            val currentDevices = getAll()103            val existing = currentDevices.firstOrNull { it.deviceId == device.deviceId }104            val bound = bindImmutableIdentity(existing, device)105            // Peer-supplied names arrive capped so a hostile peer cannot grow the106            // registry without limit (adoption + direct-pair seams land here).107            val nextDevice = bound.copy(108                deviceName = bound.deviceName?.let(::capDeviceName),109                localAlias = existing?.localAlias,110            )111            val next = currentDevices.filterNot { it.deviceId == device.deviceId } + nextDevice112            persist(next)113        }114    }115116    /**117     * Commit a staged manifest in one synchronous SharedPreferences transaction.118     * `apply()` is appropriate for ordinary UI writes, but it would expose each119     * per-device edit independently to observers and could leave an old-session120     * manifest half-applied across a lock. `commit()` updates both keys together121     * in memory and does not return until the durable write has completed.122     */123    override fun applyManifestBatch(batch: DeviceManifestRegistryBatch): Boolean {124        return mutationGate.withLock {125            val priorPrefs = readPrefsState()126            val currentDevices = getAll()127            val currentById = currentDevices.associateBy { it.deviceId }128            val currentRevocations = listRevocations()129            val nextRevocations = mergeRevocationRecords(currentRevocations, batch.incomingRevocations).records130            val removed = batch.removals131            val nextDevices = currentDevices132                .filterNot { removed.contains(it.deviceId) }133                .toMutableList()134            batch.upserts.forEach { incoming ->135                val existing = currentById[incoming.deviceId]136                    ?: nextDevices.firstOrNull { it.deviceId == incoming.deviceId }137                require(!nextDevices.any { candidate ->138                    candidate.deviceId != incoming.deviceId &&139                        ((candidate.longTermPublicKeyHex != null && incoming.longTermPublicKeyHex != null && CryptoCompare.hex(candidate.longTermPublicKeyHex, incoming.longTermPublicKeyHex)) ||140                            (candidate.signingPublicKeyHex != null && incoming.signingPublicKeyHex != null && CryptoCompare.hex(candidate.signingPublicKeyHex, incoming.signingPublicKeyHex)))141                }) { "device_identity_collision" }142                val bound = bindImmutableIdentity(existing, incoming)143                val alias = nextDevices.firstOrNull { it.deviceId == incoming.deviceId }?.localAlias144                val device = bound.copy(145                    deviceName = bound.deviceName?.let(::capDeviceName),146                    localAlias = alias,147                )148                nextDevices.removeAll { it.deviceId == device.deviceId }149                nextDevices += device150            }151152            val nextPrefs = RegistryPrefsState(153                devices = json.encodeToString(listSerializer, nextDevices),154                revocations = json.encodeToString(revocationSerializer, nextRevocations),155            )156            // Explicitly restore the old encrypted-preference values when commit()157            // reports false. The platform usually keeps them in memory, but a real158            // store failure must not rely on that undocumented outcome.159            commitWithRollback(priorPrefs, nextPrefs, ::writePrefsState)160        }161    }162163    fun rename(deviceId: String, name: String) {164        mutationGate.withLock {165            persist(withLocalAlias(getAll(), deviceId, name))166        }167    }168169    override fun remove(deviceId: String) {170        mutationGate.withLock {171            persist(getAll().filterNot { it.deviceId == deviceId })172        }173    }174175176177    // ── Device revocation (Part 5 §C) ────────────────────────────────────────178179    override fun listRevocations(): List<DeviceRevocation> {180        val raw = prefs.getString(KEY_REVOCATIONS, null) ?: return emptyList()181        return runCatching { json.decodeFromString(revocationSerializer, raw) }182            .getOrDefault(emptyList())183    }184185    /**186     * Revoke a device: record it, then drop it from the registry. The record187     * rides out in every manifest this device signs from now on. A stale entry188     * may survive in the pending-vouch queue; the confirm path re-checks189     * revocation before promoting anything out of it.190     */191    fun revoke(192        deviceId: String,193        revokedByDeviceId: String,194        nowMs: Long = System.currentTimeMillis(),195    ): DeviceRevocation? = mutationGate.withLock {196        val currentDevices = getAll()197        val currentRevocations = listRevocations()198        val mutation = planDeviceRevocation(199            devices = currentDevices,200            revocations = currentRevocations,201            deviceId = deviceId,202            revokedByDeviceId = revokedByDeviceId,203            nowMs = nowMs,204        )205        // One verified transaction for both keys. Two independent apply() calls206        // can land separately, and a device removed without its revocation207        // record stops being blocked from re-admission — a silent failure of the208        // ejection path rather than a visible error.209        val nextPrefs = RegistryPrefsState(210            devices = json.encodeToString(listSerializer, mutation.devices),211            revocations = json.encodeToString(revocationSerializer, mutation.revocations),212        )213        check(commitWithRollback(readPrefsState(), nextPrefs, ::writePrefsState)) {214            "paired_device_persist_failed"215        }216        mutation.added217    }218219    /**220     * `revokedAt` is peer-supplied and is NOT used for ordering — revocation is221     * terminal, so an incoming record can never displace one already held.222     */223    override fun mergeRevocations(incoming: List<DeviceRevocation>): List<String> {224        return mutationGate.withLock {225            val existing = listRevocations()226            val merged = mergeRevocationRecords(existing, incoming)227            if (merged.records != existing) persistRevocations(merged.records)228            merged.admitted.map { it.deviceId }229        }230    }231232    /**233     * Clear a revocation. The ONLY legitimate caller is a direct, SAS-confirmed234     * re-pair — a physically present user on both devices. Never call this from235     * a path a remote peer can reach.236     */237    override fun clearRevocation(deviceId: String) {238        mutationGate.withLock {239            val existing = listRevocations()240            val filtered = existing.filterNot { it.deviceId == deviceId }241            if (filtered.size != existing.size) persistRevocations(filtered)242        }243    }244245    fun clear() {246        mutationGate.withLock {247            val edit = prefs.edit()248                .remove(KEY_DEVICES)249                .remove(KEY_REVOCATIONS)250            // Known-key history is trust state: leaving it behind would keep a251            // cleared installation admitting keys it no longer holds devices252            // for, so it goes with the rest of the registry.253            for (key in prefs.all.keys.filter { it.startsWith(KEY_ISSUER_KEYS_PREFIX) }) {254                edit.remove(key)255            }256            edit.commit()257        }258    }259260    /** Verbatim logical copy of the whole registry, for the secure-reset archive. */261    internal fun snapshot(): Map<String, Any?> = prefs.all262263    /**264     * Refresh the device's `lastKnownIp` (the closest real analogue to the265     * brief's `lastSeen`). No-op when the id is unknown or [ip] is null.266     */267    fun updateLastSeen(id: String, ip: String? = null) {268        mutationGate.withLock {269            val current = get(id) ?: return@withLock270            if (ip == null) return@withLock271            upsert(current.copy(lastKnownIp = ip))272        }273    }274275    fun updateLastSync(id: String, at: Long = System.currentTimeMillis()) {276        mutationGate.withLock {277            val current = get(id) ?: return@withLock278            upsert(current.copy(lastSyncedAt = at))279        }280    }281282    /**283     * Reconnect prefers each pair's relay over the global fallback, so a relay284     * change in Settings only reaches established pairs by being written into285     * them. Skips the write when nothing moved, so the observers behind the286     * device list do not churn on a refused change.287     */288    fun propagateRelaySetting(mode: SyncMode, storedRelayUrl: String) {289        mutationGate.withLock {290            val current = getAll()291            val next = withRelaySetting(current, mode, storedRelayUrl)292            if (next != current) persist(next)293        }294    }295296    /**297     * Observe the full list. EncryptedSharedPreferences supports298     * OnSharedPreferenceChangeListener, so this emits on every persist —299     * including writes from other components in-process.300     */301    fun observeAll(): Flow<List<PairedDevice>> = callbackFlow {302        trySend(getAll())303        val listener = android.content.SharedPreferences.OnSharedPreferenceChangeListener { _, key ->304            if (key == KEY_DEVICES || key == null) trySend(getAll())305        }306        prefs.registerOnSharedPreferenceChangeListener(listener)307        awaitClose { prefs.unregisterOnSharedPreferenceChangeListener(listener) }308    }309310    override fun issuerSigningKeys(issuerDeviceId: String): Set<String> =311        prefs.getStringSet("$KEY_ISSUER_KEYS_PREFIX$issuerDeviceId", emptySet())312            .orEmpty().map(String::lowercase).toSet()313314    /** Any known-key history at all: legacy trust state for the reset probe. */315    fun hasIssuerSigningKeys(): Boolean = prefs.all.keys.any { it.startsWith(KEY_ISSUER_KEYS_PREFIX) }316317    override fun appendIssuerSigningKey(issuerDeviceId: String, signingKeyHex: String): Boolean {318        val key = signingKeyHex.lowercase()319        if (issuerDeviceId.isBlank() || key.length != 64) return false320        synchronized(mutationGate) {321            val existing = issuerSigningKeys(issuerDeviceId)322            if (key in existing) return true323            return prefs.edit()324                .putStringSet("$KEY_ISSUER_KEYS_PREFIX$issuerDeviceId", existing + key)325                .commit()326        }327    }328329    /**330     * Revocation mutations must be durable and verified. `apply()` returns331     * before the write is on disk, and losing the terminal ledger silently332     * un-revokes devices, so the ledger is never written that way.333     */334    private fun persistRevocations(records: List<DeviceRevocation>) {335        val prior = readPrefsState()336        val next = prior.copy(337            revocations = json.encodeToString(revocationSerializer, records),338        )339        check(commitWithRollback(prior, next, ::writePrefsState)) {340            "paired_device_persist_failed"341        }342    }343344    private fun persist(devices: List<PairedDevice>) {345        prefs.edit()346            .putString(KEY_DEVICES, json.encodeToString(listSerializer, devices))347            .apply()348    }349350    private data class RegistryPrefsState(351        val devices: String?,352        val revocations: String?,353    )354355    private fun readPrefsState(): RegistryPrefsState = RegistryPrefsState(356        devices = prefs.getString(KEY_DEVICES, null),357        revocations = prefs.getString(KEY_REVOCATIONS, null),358    )359360    private fun writePrefsState(state: RegistryPrefsState): Boolean {361        val edit = prefs.edit()362        if (state.devices == null) edit.remove(KEY_DEVICES) else edit.putString(KEY_DEVICES, state.devices)363        if (state.revocations == null) edit.remove(KEY_REVOCATIONS) else edit.putString(KEY_REVOCATIONS, state.revocations)364        return edit.commit()365    }366367    private companion object {368        const val PREFS_FILE = "peach_paired_devices"369        const val KEY_DEVICES = "paired_devices"370        const val KEY_REVOCATIONS = "device_revocations"371        const val KEY_ISSUER_KEYS_PREFIX = "issuer_signing_keys:"372        const val MAX_REVOCATIONS = MAX_REVOCATION_RECORDS373        val json = Json { encodeDefaults = true; ignoreUnknownKeys = true }374    }375}376/** Preserve a persisted device's cryptographic identity across metadata updates. */377internal fun bindImmutableIdentity(existing: PairedDevice?, incoming: PairedDevice): PairedDevice {378    if (existing == null) return incoming379380    val longTermChanged = existing.longTermPublicKeyHex != null &&381        incoming.longTermPublicKeyHex != null &&382        !CryptoCompare.hex(existing.longTermPublicKeyHex, incoming.longTermPublicKeyHex)383    val signingChanged = existing.signingPublicKeyHex != null &&384        incoming.signingPublicKeyHex != null &&385        !CryptoCompare.hex(existing.signingPublicKeyHex, incoming.signingPublicKeyHex)386    require(!longTermChanged && !signingChanged) { "device_identity_immutable" }387388    return incoming.copy(389        longTermPublicKeyHex = incoming.longTermPublicKeyHex ?: existing.longTermPublicKeyHex,390        signingPublicKeyHex = incoming.signingPublicKeyHex ?: existing.signingPublicKeyHex,391    )392}393394/** Serialises whole-list registry mutations so stale snapshots cannot win. */395internal class RegistryMutationGate {396    private val lock = ReentrantLock()397398    fun <T> withLock(block: () -> T): T = lock.withLock(block)399}400401internal fun withLocalAlias(402    devices: List<PairedDevice>,403    deviceId: String,404    name: String,405): List<PairedDevice> {406    val alias = name.trim()407    require(alias.isNotEmpty()) { "device name must not be empty" }408    require(alias.length <= MAX_DEVICE_NAME_CHARS) { "device name must be 64 chars or fewer" }409    require(devices.any { it.deviceId == deviceId }) { "device_not_found" }410    return devices.map { if (it.deviceId == deviceId) it.copy(localAlias = alias) else it }411}412413internal data class DeviceRevocationMutation(414    val devices: List<PairedDevice>,415    val revocations: List<DeviceRevocation>,416    val added: DeviceRevocation?,417)418419/** A fresh pairing ceremony must not reuse terminally revoked identity material. */420internal fun hasAdoptionIdentityConflict(421    incoming: PairedDevice,422    devices: List<PairedDevice>,423    revocations: List<DeviceRevocation>,424): Boolean {425    if (devices.any { it.deviceId == incoming.deviceId }) return true426    if (devices.any {427        it.longTermPublicKeyHex?.let { key -> incoming.longTermPublicKeyHex?.let { candidate -> CryptoCompare.hex(key, candidate) } } == true ||428            it.signingPublicKeyHex?.let { key -> incoming.signingPublicKeyHex?.let { candidate -> CryptoCompare.hex(key, candidate) } } == true429    }) return true430    return revocations.any { revoked ->431        revoked.deviceId == incoming.deviceId ||432            incoming.longTermPublicKeyHex?.let { CryptoCompare.hex(revoked.longTermPublicKeyHex, it) } == true433    }434}435436/**437 * Compute one revoke transaction without Android storage so the impossible438 * "paired and already revoked" state can be regression-tested directly.439 *440 * Older builds could leave that overlap behind. A repeated Remove must still441 * drop the live row even though the terminal record itself is idempotent.442 */443internal fun planDeviceRevocation(444    devices: List<PairedDevice>,445    revocations: List<DeviceRevocation>,446    deviceId: String,447    revokedByDeviceId: String,448    nowMs: Long,449): DeviceRevocationMutation {450    val remaining = devices.filterNot { it.deviceId == deviceId }451    if (revocations.any { it.deviceId == deviceId }) {452        return DeviceRevocationMutation(remaining, revocations, null)453    }454    val device = devices.firstOrNull { it.deviceId == deviceId }455    val record = DeviceRevocation(456        deviceId = deviceId,457        longTermPublicKeyHex = device?.longTermPublicKeyHex ?: "0".repeat(64),458        revokedAt = nowMs,459        revokedByDeviceId = revokedByDeviceId,460    )461    return DeviceRevocationMutation(462        remaining,463        capRevocationRecords(revocations + record),464        record,465    )466}467468internal data class RevocationMergeResult(469    val records: List<DeviceRevocation>,470    val admitted: List<DeviceRevocation>,471)472473internal fun mergeRevocationRecords(474    existing: List<DeviceRevocation>,475    incoming: List<DeviceRevocation>,476): RevocationMergeResult {477    val known = existing.map { it.deviceId }.toSet()478    val fresh = incoming.filterNot { known.contains(it.deviceId) }479    return RevocationMergeResult(capRevocationRecords(existing + fresh), fresh)480}481482/**483 * Keep the terminal ledger bounded without letting one issuer permanently484 * consume every slot. Each overflow drops the oldest record belonging to the485 * currently largest issuer, matching Browser's `capRevocations` policy.486 */487internal fun capRevocationRecords(records: List<DeviceRevocation>): List<DeviceRevocation> {488    if (records.size <= MAX_REVOCATION_RECORDS) return records489    val liveCounts = records.groupingBy { it.revokedByDeviceId }.eachCount().toMutableMap()490    val dropped = BooleanArray(records.size)491    repeat(records.size - MAX_REVOCATION_RECORDS) {492        val largestIssuer = liveCounts.maxByOrNull { it.value }?.key ?: return@repeat493        val oldestIndex = records.indices.firstOrNull { index ->494            !dropped[index] && records[index].revokedByDeviceId == largestIssuer495        } ?: return@repeat496        dropped[oldestIndex] = true497        liveCounts[largestIssuer] = liveCounts.getValue(largestIssuer) - 1498    }499    return records.filterIndexed { index, _ -> !dropped[index] }500}501502/**503 * The mesh relay is pushed out through the same gate that decides whether to504 * dial one: a relay this device refuses to use must not be handed to peers505 * either — pushing Peach's own URL out under a "Private relay" label would tell506 * the same lie one layer down.507 */508internal fun withRelaySetting(509    devices: List<PairedDevice>,510    mode: SyncMode,511    storedRelayUrl: String,512): List<PairedDevice> = when (val decision = relayInForce(mode, storedRelayUrl)) {513    is RelayDecision.Dial -> devices.map { it.copy(relayUrl = decision.relayUrl) }514    is RelayDecision.Refuse -> devices515}