PairedDeviceStore.kt

23.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 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 try {64            json.decodeFromString(listSerializer, raw)65        } catch (e: Exception) {66            throw TrustDataCorruptedException(KEY_DEVICES, e.message ?: "decode_failed")67        }68    }6970    override fun get(id: String): PairedDevice? = getAll().firstOrNull { it.deviceId == id }7172    override fun getByPubkey(pubkeyHex: String): PairedDevice? =73        getAll().firstOrNull {74            it.longTermPublicKeyHex?.let { key -> CryptoCompare.hex(key, pubkeyHex) } == true75        }7677    fun hasIdentityCollision(device: PairedDevice): Boolean =78        hasAdoptionIdentityConflict(device, getAll(), listRevocations())7980    /** Insert or replace a directly re-paired device and clear its terminal revocation atomically. */81    fun upsertAndClearRevocation(device: PairedDevice) {82        mutationGate.withLock {83            val currentDevices = getAll()84            val existing = currentDevices.firstOrNull { it.deviceId == device.deviceId }85            val bound = bindImmutableIdentity(existing, device)86            val nextDevice = bound.copy(87                deviceName = bound.deviceName?.let(::capDeviceName),88                localAlias = existing?.localAlias,89            )90            val nextDevices = currentDevices.filterNot { it.deviceId == device.deviceId } + nextDevice91            val currentRevocations = listRevocations()92            val nextRevocations = currentRevocations.filterNot { it.deviceId == device.deviceId }93            val nextPrefs = RegistryPrefsState(94                devices = json.encodeToString(listSerializer, nextDevices),95                revocations = json.encodeToString(revocationSerializer, nextRevocations),96            )97            check(commitWithRollback(readPrefsState(), nextPrefs, ::writePrefsState)) {98                "paired_device_persist_failed"99            }100        }101    }102103    /** Insert or replace by [PairedDevice.deviceId], without changing its cryptographic identity. */104    override fun upsert(device: PairedDevice) {105        mutationGate.withLock {106            val currentDevices = getAll()107            val existing = currentDevices.firstOrNull { it.deviceId == device.deviceId }108            val bound = bindImmutableIdentity(existing, device)109            // Peer-supplied names arrive capped so a hostile peer cannot grow the110            // registry without limit (adoption + direct-pair seams land here).111            val nextDevice = bound.copy(112                deviceName = bound.deviceName?.let(::capDeviceName),113                localAlias = existing?.localAlias,114            )115            val next = currentDevices.filterNot { it.deviceId == device.deviceId } + nextDevice116            persist(next)117        }118    }119120    /**121     * Commit a staged manifest in one synchronous SharedPreferences transaction.122     * `apply()` is appropriate for ordinary UI writes, but it would expose each123     * per-device edit independently to observers and could leave an old-session124     * manifest half-applied across a lock. `commit()` updates both keys together125     * in memory and does not return until the durable write has completed.126     */127    override fun applyManifestBatch(batch: DeviceManifestRegistryBatch): Boolean {128        return mutationGate.withLock {129            val priorPrefs = readPrefsState()130            val currentDevices = getAll()131            val currentById = currentDevices.associateBy { it.deviceId }132            val currentRevocations = listRevocations()133            val nextRevocations = mergeRevocationRecords(currentRevocations, batch.incomingRevocations).records134            val removed = batch.removals135            val nextDevices = currentDevices136                .filterNot { removed.contains(it.deviceId) }137                .toMutableList()138            batch.upserts.forEach { incoming ->139                val existing = currentById[incoming.deviceId]140                    ?: nextDevices.firstOrNull { it.deviceId == incoming.deviceId }141                require(!nextDevices.any { candidate ->142                    candidate.deviceId != incoming.deviceId &&143                        ((candidate.longTermPublicKeyHex != null && incoming.longTermPublicKeyHex != null && CryptoCompare.hex(candidate.longTermPublicKeyHex, incoming.longTermPublicKeyHex)) ||144                            (candidate.signingPublicKeyHex != null && incoming.signingPublicKeyHex != null && CryptoCompare.hex(candidate.signingPublicKeyHex, incoming.signingPublicKeyHex)))145                }) { "device_identity_collision" }146                val bound = bindImmutableIdentity(existing, incoming)147                val alias = nextDevices.firstOrNull { it.deviceId == incoming.deviceId }?.localAlias148                val device = bound.copy(149                    deviceName = bound.deviceName?.let(::capDeviceName),150                    localAlias = alias,151                )152                nextDevices.removeAll { it.deviceId == device.deviceId }153                nextDevices += device154            }155156            val nextPrefs = RegistryPrefsState(157                devices = json.encodeToString(listSerializer, nextDevices),158                revocations = json.encodeToString(revocationSerializer, nextRevocations),159            )160            // Explicitly restore the old encrypted-preference values when commit()161            // reports false. The platform usually keeps them in memory, but a real162            // store failure must not rely on that undocumented outcome.163            commitWithRollback(priorPrefs, nextPrefs, ::writePrefsState)164        }165    }166167    fun rename(deviceId: String, name: String) {168        mutationGate.withLock {169            persist(withLocalAlias(getAll(), deviceId, name))170        }171    }172173    override fun remove(deviceId: String) {174        mutationGate.withLock {175            persist(getAll().filterNot { it.deviceId == deviceId })176        }177    }178179180181    // ── Device revocation (Part 5 §C) ────────────────────────────────────────182183    override fun listRevocations(): List<DeviceRevocation> {184        val raw = prefs.getString(KEY_REVOCATIONS, null) ?: return emptyList()185        return try {186            json.decodeFromString(revocationSerializer, raw)187        } catch (e: Exception) {188            throw TrustDataCorruptedException(KEY_REVOCATIONS, e.message ?: "decode_failed")189        }190    }191192    /**193     * Revoke a device: record it, then drop it from the registry. The record194     * rides out in every manifest this device signs from now on. A stale entry195     * may survive in the pending-vouch queue; the confirm path re-checks196     * revocation before promoting anything out of it.197     */198    fun revoke(199        deviceId: String,200        revokedByDeviceId: String,201        nowMs: Long = System.currentTimeMillis(),202    ): DeviceRevocation? = mutationGate.withLock {203        val currentDevices = getAll()204        val currentRevocations = listRevocations()205        val mutation = planDeviceRevocation(206            devices = currentDevices,207            revocations = currentRevocations,208            deviceId = deviceId,209            revokedByDeviceId = revokedByDeviceId,210            nowMs = nowMs,211        )212        // One verified transaction for both keys. Two independent apply() calls213        // can land separately, and a device removed without its revocation214        // record stops being blocked from re-admission — a silent failure of the215        // ejection path rather than a visible error.216        val nextPrefs = RegistryPrefsState(217            devices = json.encodeToString(listSerializer, mutation.devices),218            revocations = json.encodeToString(revocationSerializer, mutation.revocations),219        )220        check(commitWithRollback(readPrefsState(), nextPrefs, ::writePrefsState)) {221            "paired_device_persist_failed"222        }223        mutation.added224    }225226    /**227     * `revokedAt` is peer-supplied and is NOT used for ordering — revocation is228     * terminal, so an incoming record can never displace one already held.229     */230    override fun mergeRevocations(incoming: List<DeviceRevocation>): List<String> {231        return mutationGate.withLock {232            val existing = listRevocations()233            val merged = mergeRevocationRecords(existing, incoming)234            if (merged.records != existing) persistRevocations(merged.records)235            merged.admitted.map { it.deviceId }236        }237    }238239    /**240     * Clear a revocation. The ONLY legitimate caller is a direct, SAS-confirmed241     * re-pair — a physically present user on both devices. Never call this from242     * a path a remote peer can reach.243     */244    override fun clearRevocation(deviceId: String) {245        mutationGate.withLock {246            val existing = listRevocations()247            val filtered = existing.filterNot { it.deviceId == deviceId }248            if (filtered.size != existing.size) persistRevocations(filtered)249        }250    }251252    fun clear() {253        mutationGate.withLock {254            val edit = prefs.edit()255                .remove(KEY_DEVICES)256                .remove(KEY_REVOCATIONS)257            // Known-key history is trust state: leaving it behind would keep a258            // cleared installation admitting keys it no longer holds devices259            // for, so it goes with the rest of the registry.260            for (key in prefs.all.keys.filter { it.startsWith(KEY_ISSUER_KEYS_PREFIX) }) {261                edit.remove(key)262            }263            edit.commit()264        }265    }266267    /** Verbatim logical copy of the whole registry, for the secure-reset archive. */268    internal fun snapshot(): Map<String, Any?> = prefs.all269270    /**271     * Refresh the device's `lastKnownIp` (the closest real analogue to the272     * brief's `lastSeen`). No-op when the id is unknown or [ip] is null.273     */274    fun updateLastSeen(id: String, ip: String? = null) {275        mutationGate.withLock {276            val current = get(id) ?: return@withLock277            if (ip == null) return@withLock278            upsert(current.copy(lastKnownIp = ip))279        }280    }281282    fun updateLastSync(id: String, at: Long = System.currentTimeMillis()) {283        mutationGate.withLock {284            val current = get(id) ?: return@withLock285            upsert(current.copy(lastSyncedAt = at))286        }287    }288289    /**290     * Reconnect prefers each pair's relay over the global fallback, so a relay291     * change in Settings only reaches established pairs by being written into292     * them. Skips the write when nothing moved, so the observers behind the293     * device list do not churn on a refused change.294     */295    fun propagateRelaySetting(mode: SyncMode, storedRelayUrl: String) {296        mutationGate.withLock {297            val current = getAll()298            val next = withRelaySetting(current, mode, storedRelayUrl)299            if (next != current) persist(next)300        }301    }302303    /**304     * Observe the full list. EncryptedSharedPreferences supports305     * OnSharedPreferenceChangeListener, so this emits on every persist —306     * including writes from other components in-process.307     */308    fun observeAll(): Flow<List<PairedDevice>> = callbackFlow {309        trySend(getAll())310        val listener = android.content.SharedPreferences.OnSharedPreferenceChangeListener { _, key ->311            if (key == KEY_DEVICES || key == null) trySend(getAll())312        }313        prefs.registerOnSharedPreferenceChangeListener(listener)314        awaitClose { prefs.unregisterOnSharedPreferenceChangeListener(listener) }315    }316317    override fun issuerSigningKeys(issuerDeviceId: String): Set<String> =318        prefs.getStringSet("$KEY_ISSUER_KEYS_PREFIX$issuerDeviceId", emptySet())319            .orEmpty().map(String::lowercase).toSet()320321    /** Any known-key history at all: legacy trust state for the reset probe. */322    fun hasIssuerSigningKeys(): Boolean = prefs.all.keys.any { it.startsWith(KEY_ISSUER_KEYS_PREFIX) }323324    override fun appendIssuerSigningKey(issuerDeviceId: String, signingKeyHex: String): Boolean {325        val key = signingKeyHex.lowercase()326        if (issuerDeviceId.isBlank() || key.length != 64) return false327        synchronized(mutationGate) {328            val existing = issuerSigningKeys(issuerDeviceId)329            if (key in existing) return true330            return prefs.edit()331                .putStringSet("$KEY_ISSUER_KEYS_PREFIX$issuerDeviceId", existing + key)332                .commit()333        }334    }335336    /**337     * Revocation mutations must be durable and verified. `apply()` returns338     * before the write is on disk, and losing the terminal ledger silently339     * un-revokes devices, so the ledger is never written that way.340     */341    private fun persistRevocations(records: List<DeviceRevocation>) {342        val prior = readPrefsState()343        val next = prior.copy(344            revocations = json.encodeToString(revocationSerializer, records),345        )346        check(commitWithRollback(prior, next, ::writePrefsState)) {347            "paired_device_persist_failed"348        }349    }350351    private fun persist(devices: List<PairedDevice>) {352        prefs.edit()353            .putString(KEY_DEVICES, json.encodeToString(listSerializer, devices))354            .apply()355    }356357    private data class RegistryPrefsState(358        val devices: String?,359        val revocations: String?,360    )361362    private fun readPrefsState(): RegistryPrefsState = RegistryPrefsState(363        devices = prefs.getString(KEY_DEVICES, null),364        revocations = prefs.getString(KEY_REVOCATIONS, null),365    )366367    private fun writePrefsState(state: RegistryPrefsState): Boolean {368        val edit = prefs.edit()369        if (state.devices == null) edit.remove(KEY_DEVICES) else edit.putString(KEY_DEVICES, state.devices)370        if (state.revocations == null) edit.remove(KEY_REVOCATIONS) else edit.putString(KEY_REVOCATIONS, state.revocations)371        return edit.commit()372    }373374    private companion object {375        const val PREFS_FILE = "peach_paired_devices"376        const val KEY_DEVICES = "paired_devices"377        const val KEY_REVOCATIONS = "device_revocations"378        const val KEY_ISSUER_KEYS_PREFIX = "issuer_signing_keys:"379        const val MAX_REVOCATIONS = MAX_REVOCATION_RECORDS380        val json = Json { encodeDefaults = true; ignoreUnknownKeys = true }381    }382}383384/**385 * §18.4: a corrupt persisted registry or revocation ledger is an integrity386 * error, not an empty list. Silently returning empty un-revokes every device.387 * The corrupt payload is preserved (the store never writes on this path) so a388 * future repair can attempt recovery.389 */390class TrustDataCorruptedException(key: String, detail: String) :391    RuntimeException("trust_data_corrupted:$key:$detail")392/** Preserve a persisted device's cryptographic identity across metadata updates. */393internal fun bindImmutableIdentity(existing: PairedDevice?, incoming: PairedDevice): PairedDevice {394    if (existing == null) return incoming395396    val longTermChanged = existing.longTermPublicKeyHex != null &&397        incoming.longTermPublicKeyHex != null &&398        !CryptoCompare.hex(existing.longTermPublicKeyHex, incoming.longTermPublicKeyHex)399    val signingChanged = existing.signingPublicKeyHex != null &&400        incoming.signingPublicKeyHex != null &&401        !CryptoCompare.hex(existing.signingPublicKeyHex, incoming.signingPublicKeyHex)402    require(!longTermChanged && !signingChanged) { "device_identity_immutable" }403404    return incoming.copy(405        longTermPublicKeyHex = incoming.longTermPublicKeyHex ?: existing.longTermPublicKeyHex,406        signingPublicKeyHex = incoming.signingPublicKeyHex ?: existing.signingPublicKeyHex,407    )408}409410/** Serialises whole-list registry mutations so stale snapshots cannot win. */411internal class RegistryMutationGate {412    private val lock = ReentrantLock()413414    fun <T> withLock(block: () -> T): T = lock.withLock(block)415}416417internal fun withLocalAlias(418    devices: List<PairedDevice>,419    deviceId: String,420    name: String,421): List<PairedDevice> {422    val alias = name.trim()423    require(alias.isNotEmpty()) { "device name must not be empty" }424    require(alias.length <= MAX_DEVICE_NAME_CHARS) { "device name must be 64 chars or fewer" }425    require(devices.any { it.deviceId == deviceId }) { "device_not_found" }426    return devices.map { if (it.deviceId == deviceId) it.copy(localAlias = alias) else it }427}428429internal data class DeviceRevocationMutation(430    val devices: List<PairedDevice>,431    val revocations: List<DeviceRevocation>,432    val added: DeviceRevocation?,433)434435/** A fresh pairing ceremony must not reuse terminally revoked identity material. */436internal fun hasAdoptionIdentityConflict(437    incoming: PairedDevice,438    devices: List<PairedDevice>,439    revocations: List<DeviceRevocation>,440): Boolean {441    if (devices.any { it.deviceId == incoming.deviceId }) return true442    if (devices.any {443        it.longTermPublicKeyHex?.let { key -> incoming.longTermPublicKeyHex?.let { candidate -> CryptoCompare.hex(key, candidate) } } == true ||444            it.signingPublicKeyHex?.let { key -> incoming.signingPublicKeyHex?.let { candidate -> CryptoCompare.hex(key, candidate) } } == true445    }) return true446    return revocations.any { revoked ->447        revoked.deviceId == incoming.deviceId ||448            incoming.longTermPublicKeyHex?.let { CryptoCompare.hex(revoked.longTermPublicKeyHex, it) } == true449    }450}451452/**453 * Compute one revoke transaction without Android storage so the impossible454 * "paired and already revoked" state can be regression-tested directly.455 *456 * Older builds could leave that overlap behind. A repeated Remove must still457 * drop the live row even though the terminal record itself is idempotent.458 */459internal fun planDeviceRevocation(460    devices: List<PairedDevice>,461    revocations: List<DeviceRevocation>,462    deviceId: String,463    revokedByDeviceId: String,464    nowMs: Long,465): DeviceRevocationMutation {466    val remaining = devices.filterNot { it.deviceId == deviceId }467    if (revocations.any { it.deviceId == deviceId }) {468        return DeviceRevocationMutation(remaining, revocations, null)469    }470    val device = devices.firstOrNull { it.deviceId == deviceId }471    val record = DeviceRevocation(472        deviceId = deviceId,473        longTermPublicKeyHex = device?.longTermPublicKeyHex ?: "0".repeat(64),474        revokedAt = nowMs,475        revokedByDeviceId = revokedByDeviceId,476    )477    return DeviceRevocationMutation(478        remaining,479        capRevocationRecords(revocations + record),480        record,481    )482}483484internal data class RevocationMergeResult(485    val records: List<DeviceRevocation>,486    val admitted: List<DeviceRevocation>,487)488489internal fun mergeRevocationRecords(490    existing: List<DeviceRevocation>,491    incoming: List<DeviceRevocation>,492): RevocationMergeResult {493    val known = existing.map { it.deviceId }.toSet()494    val fresh = incoming.filterNot { known.contains(it.deviceId) }495    return RevocationMergeResult(capRevocationRecords(existing + fresh), fresh)496}497498/**499 * Keep the terminal ledger bounded without letting one issuer permanently500 * consume every slot. Each overflow drops the oldest record belonging to the501 * currently largest issuer, matching Browser's `capRevocations` policy.502 */503internal fun capRevocationRecords(records: List<DeviceRevocation>): List<DeviceRevocation> {504    if (records.size <= MAX_REVOCATION_RECORDS) return records505    val liveCounts = records.groupingBy { it.revokedByDeviceId }.eachCount().toMutableMap()506    val dropped = BooleanArray(records.size)507    repeat(records.size - MAX_REVOCATION_RECORDS) {508        val largestIssuer = liveCounts.maxByOrNull { it.value }?.key ?: return@repeat509        val oldestIndex = records.indices.firstOrNull { index ->510            !dropped[index] && records[index].revokedByDeviceId == largestIssuer511        } ?: return@repeat512        dropped[oldestIndex] = true513        liveCounts[largestIssuer] = liveCounts.getValue(largestIssuer) - 1514    }515    return records.filterIndexed { index, _ -> !dropped[index] }516}517518/**519 * The mesh relay is pushed out through the same gate that decides whether to520 * dial one: a relay this device refuses to use must not be handed to peers521 * either — pushing Peach's own URL out under a "Private relay" label would tell522 * the same lie one layer down.523 */524internal fun withRelaySetting(525    devices: List<PairedDevice>,526    mode: SyncMode,527    storedRelayUrl: String,528): List<PairedDevice> = when (val decision = relayInForce(mode, storedRelayUrl)) {529    is RelayDecision.Dial -> devices.map { it.copy(relayUrl = decision.relayUrl) }530    is RelayDecision.Refuse -> devices531}