PairedDeviceStore.kt

4.7 KB · raw

1// Intended source path: app/src/main/java/com/peachpasswords/sync/PairedDeviceStore.kt2package com.peachpasswords.sync34import android.content.Context5import androidx.security.crypto.EncryptedSharedPreferences6import androidx.security.crypto.MasterKey7import dagger.hilt.android.qualifiers.ApplicationContext8import kotlinx.coroutines.channels.awaitClose9import kotlinx.coroutines.flow.Flow10import kotlinx.coroutines.flow.callbackFlow11import kotlinx.serialization.builtins.ListSerializer12import kotlinx.serialization.json.Json13import javax.inject.Inject14import javax.inject.Singleton1516/**17 * Persistent registry of paired devices, encrypted at rest with18 * EncryptedSharedPreferences (same construction as DuressConfigStore /19 * LicenseRepository, v2.1.36). The whole list lives under a single key as a20 * kotlinx.serialization JSON array of the REAL [PairedDevice] (sync package).21 *22 * Reconciliation with the C7 brief:23 *  - The brief invents a fresh `PairedDevice(id, name, publicKey: ByteArray,24 *    lastSeen, trustStatus, lastSyncAt)`. That type does NOT exist in this25 *    shape. The real [PairedDevice] (PairedDevice.kt) keys on `deviceId`, holds26 *    the public key as `longTermPublicKeyHex` (hex, not ByteArray), and tracks27 *    `pairedAt` / `lastSyncedAt` / `lastKnownIp`. This store reuses it verbatim;28 *    Base64 publicKey storage is therefore unnecessary — the hex field is the29 *    canonical wire form already produced by ChirpPairing.frameToPairedDevice.30 *  - The brief's `TrustStatus` enum does not exist either. The real model uses a31 *    nullable `trustSource: String?` (e.g. "direct", "manifest"). Trust state is32 *    expressed there. See C7-INTEGRATION.md for the trust-status delta.33 *  - `updateLastSync` here maps to the real `lastSyncedAt` field. There is no34 *    `lastSeen` field on the real PairedDevice; [updateLastSeen] folds into35 *    `lastKnownIp` refresh + `lastSyncedAt` is left untouched. It is kept as a36 *    no-op-friendly hook so callers from the brief compile; see integration note.37 */38@Singleton39class PairedDeviceStore @Inject constructor(40    @ApplicationContext context: Context,41) {42    private val masterKey = MasterKey.Builder(context)43        .setKeyScheme(MasterKey.KeyScheme.AES256_GCM)44        .build()4546    private val prefs = EncryptedSharedPreferences.create(47        context,48        PREFS_FILE,49        masterKey,50        EncryptedSharedPreferences.PrefKeyEncryptionScheme.AES256_SIV,51        EncryptedSharedPreferences.PrefValueEncryptionScheme.AES256_GCM,52    )5354    private val listSerializer = ListSerializer(PairedDevice.serializer())5556    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    fun get(id: String): PairedDevice? = getAll().firstOrNull { it.deviceId == id }6263    /** Insert or replace by [PairedDevice.deviceId]. */64    fun upsert(device: PairedDevice) {65        val next = getAll().filterNot { it.deviceId == device.deviceId } + device66        persist(next)67    }6869    fun remove(id: String) {70        persist(getAll().filterNot { it.deviceId == id })71    }7273    fun clear() {74        prefs.edit().remove(KEY_DEVICES).apply()75    }7677    /**78     * Refresh the device's `lastKnownIp` (the closest real analogue to the79     * brief's `lastSeen`). No-op when the id is unknown or [ip] is null.80     */81    fun updateLastSeen(id: String, ip: String? = null) {82        val current = get(id) ?: return83        if (ip == null) return84        upsert(current.copy(lastKnownIp = ip))85    }8687    fun updateLastSync(id: String, at: Long = System.currentTimeMillis()) {88        val current = get(id) ?: return89        upsert(current.copy(lastSyncedAt = at))90    }9192    /**93     * Observe the full list. EncryptedSharedPreferences supports94     * OnSharedPreferenceChangeListener, so this emits on every persist —95     * including writes from other components in-process.96     */97    fun observeAll(): Flow<List<PairedDevice>> = callbackFlow {98        trySend(getAll())99        val listener = android.content.SharedPreferences.OnSharedPreferenceChangeListener { _, key ->100            if (key == KEY_DEVICES || key == null) trySend(getAll())101        }102        prefs.registerOnSharedPreferenceChangeListener(listener)103        awaitClose { prefs.unregisterOnSharedPreferenceChangeListener(listener) }104    }105106    private fun persist(devices: List<PairedDevice>) {107        prefs.edit()108            .putString(KEY_DEVICES, json.encodeToString(listSerializer, devices))109            .apply()110    }111112    private companion object {113        const val PREFS_FILE = "peach_paired_devices"114        const val KEY_DEVICES = "paired_devices"115        val json = Json { encodeDefaults = true; ignoreUnknownKeys = true }116    }117}