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.Serializable11import kotlinx.serialization.builtins.ListSerializer12import kotlinx.serialization.json.Json13import javax.inject.Inject14import javax.inject.Singleton1516@Serializable17data class PendingVouchedDevice(18 val deviceId: String,19 val deviceName: String,20 val deviceType: String,21 val longTermPublicKeyHex: String,22 val signingPublicKeyHex: String,23 val wsPort: Int? = null,24 val pairedAt: Long,25 val receivedAt: Long,26 val vouchedByDeviceId: String,27)2829interface PendingVouchedRegistry {30 fun getAll(): List<PendingVouchedDevice>31 fun upsert(device: PendingVouchedDevice)32 33 fun upsertAndReport(device: PendingVouchedDevice): Boolean {34 return runCatching {35 upsert(device)36 true37 }.getOrDefault(false)38 }39 4041424344 fun removeAndReport(id: String): Boolean {45 return runCatching {46 remove(id)47 true48 }.getOrDefault(false)49 }5051 52 fun remove(id: String)5354 5556575859 fun removeBatch(ids: Set<String>): Boolean {60 return runCatching {61 ids.forEach(::remove)62 true63 }.getOrDefault(false)64 }6566 67 fun restoreBatch(devices: List<PendingVouchedDevice>): Boolean {68 return runCatching {69 devices.forEach(::upsert)70 true71 }.getOrDefault(false)72 }73}7475@Singleton76class PendingVouchedDeviceStore @Inject constructor(77 @ApplicationContext context: Context,78) : PendingVouchedRegistry {79 private val masterKey = MasterKey.Builder(context)80 .setKeyScheme(MasterKey.KeyScheme.AES256_GCM)81 .build()8283 private val prefs = EncryptedSharedPreferences.create(84 context,85 PREFS_FILE,86 masterKey,87 EncryptedSharedPreferences.PrefKeyEncryptionScheme.AES256_SIV,88 EncryptedSharedPreferences.PrefValueEncryptionScheme.AES256_GCM,89 )9091 private val listSerializer = ListSerializer(PendingVouchedDevice.serializer())9293 override fun getAll(): List<PendingVouchedDevice> {94 val raw = prefs.getString(KEY_PENDING, null) ?: return emptyList()95 return runCatching { json.decodeFromString(listSerializer, raw) }.getOrDefault(emptyList())96 }9798 fun get(id: String): PendingVouchedDevice? = getAll().firstOrNull { it.deviceId == id }99100 override fun upsert(device: PendingVouchedDevice) {101 upsertAndReport(device)102 }103104 override fun upsertAndReport(device: PendingVouchedDevice): Boolean {105 106 107 val device = device.copy(deviceName = capDeviceName(device.deviceName))108 val next = (getAll().filterNot { it.deviceId == device.deviceId } + device).takeLast(MAX_PENDING)109 return commitList(next)110 }111112 override fun remove(id: String) {113 removeAndReport(id)114 }115116 override fun removeAndReport(id: String): Boolean {117 val before = getAll()118 val after = before.filterNot { it.deviceId == id }119 return commitWithRollback(before, after, ::commitList)120 }121122 123124125126127 override fun removeBatch(ids: Set<String>): Boolean {128 if (ids.isEmpty()) return true129 val before = getAll()130 val after = before.filterNot { it.deviceId in ids }131 return commitWithRollback(before, after, ::commitList)132 }133134 override fun restoreBatch(devices: List<PendingVouchedDevice>): Boolean {135 if (devices.isEmpty()) return true136 val before = getAll()137 val restoredIds = devices.map { it.deviceId }.toSet()138 val after = (before.filterNot { it.deviceId in restoredIds } + devices).takeLast(MAX_PENDING)139 return commitWithRollback(before, after, ::commitList)140 }141142 fun clear() {143 persist(emptyList())144 }145146 fun observeAll(): Flow<List<PendingVouchedDevice>> = callbackFlow {147 trySend(getAll())148 val listener = android.content.SharedPreferences.OnSharedPreferenceChangeListener { _, key ->149 if (key == KEY_PENDING || key == null) trySend(getAll())150 }151 prefs.registerOnSharedPreferenceChangeListener(listener)152 awaitClose { prefs.unregisterOnSharedPreferenceChangeListener(listener) }153 }154155 private fun persist(devices: List<PendingVouchedDevice>) {156 prefs.edit()157 .putString(KEY_PENDING, json.encodeToString(listSerializer, devices))158 159 160 161 162 163 .commit()164 }165166 167 private fun commitList(devices: List<PendingVouchedDevice>): Boolean =168 prefs.edit()169 .putString(KEY_PENDING, json.encodeToString(listSerializer, devices))170 .commit()171172 private companion object {173 const val PREFS_FILE = "peach_pending_vouched_devices"174 const val KEY_PENDING = "pending_vouched_devices"175 const val MAX_PENDING = 50176 val json = Json { encodeDefaults = true; ignoreUnknownKeys = true }177 }178}179180181182183184185186187internal fun <T> commitWithRollback(188 before: T,189 after: T,190 commit: (T) -> Boolean,191): Boolean {192 val applied = runCatching { commit(after) }.getOrDefault(false)193 if (applied) return true194 runCatching { commit(before) }195 return false196}