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 = 500181920212223242526272829303132333435363738394041@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 74 override fun upsert(device: PairedDevice) {75 mutationGate.withLock {76 77 78 val device = device.copy(79 deviceName = device.deviceName?.let(::capDeviceName),80 localAlias = get(device.deviceId)?.localAlias,81 )82 val next = getAll().filterNot { it.deviceId == device.deviceId } + device83 persist(next)84 }85 }8687 fun rename(deviceId: String, name: String) {88 mutationGate.withLock {89 persist(withLocalAlias(getAll(), deviceId, name))90 }91 }9293 override fun remove(deviceId: String) {94 mutationGate.withLock {95 persist(getAll().filterNot { it.deviceId == deviceId })96 }97 }9899 100101102103104105106 override fun applyManifestBatch(batch: DeviceManifestRegistryBatch): Boolean {107 return mutationGate.withLock {108 val priorPrefs = readPrefsState()109 val currentDevices = getAll()110 val currentRevocations = listRevocations()111 val nextRevocations = mergeRevocationRecords(currentRevocations, batch.incomingRevocations).records112 val removed = batch.removals113 val nextDevices = currentDevices114 .filterNot { removed.contains(it.deviceId) }115 .toMutableList()116 batch.upserts.forEach { device ->117 val alias = nextDevices.firstOrNull { it.deviceId == device.deviceId }?.localAlias118 val device = device.copy(119 deviceName = device.deviceName?.let(::capDeviceName),120 localAlias = alias,121 )122 nextDevices.removeAll { it.deviceId == device.deviceId }123 nextDevices += device124 }125126 val nextPrefs = RegistryPrefsState(127 devices = json.encodeToString(listSerializer, nextDevices),128 revocations = json.encodeToString(revocationSerializer, nextRevocations),129 )130 131 132 133 commitWithRollback(priorPrefs, nextPrefs, ::writePrefsState)134 }135 }136137 138139 override fun listRevocations(): List<DeviceRevocation> {140 val raw = prefs.getString(KEY_REVOCATIONS, null) ?: return emptyList()141 return runCatching { json.decodeFromString(revocationSerializer, raw) }142 .getOrDefault(emptyList())143 }144145 146147148149150151 fun revoke(152 deviceId: String,153 revokedByDeviceId: String,154 nowMs: Long = System.currentTimeMillis(),155 ): DeviceRevocation? = mutationGate.withLock {156 val currentDevices = getAll()157 val currentRevocations = listRevocations()158 val mutation = planDeviceRevocation(159 devices = currentDevices,160 revocations = currentRevocations,161 deviceId = deviceId,162 revokedByDeviceId = revokedByDeviceId,163 nowMs = nowMs,164 )165 if (mutation.revocations !== currentRevocations) {166 persistRevocations(mutation.revocations)167 }168 if (mutation.devices != currentDevices) {169 persist(mutation.devices)170 }171 mutation.added172 }173174 175176177178 override fun mergeRevocations(incoming: List<DeviceRevocation>): List<String> {179 return mutationGate.withLock {180 val existing = listRevocations()181 val merged = mergeRevocationRecords(existing, incoming)182 if (merged.records != existing) persistRevocations(merged.records)183 merged.admitted.map { it.deviceId }184 }185 }186187 188189190191192 override fun clearRevocation(deviceId: String) {193 mutationGate.withLock {194 val existing = listRevocations()195 val filtered = existing.filterNot { it.deviceId == deviceId }196 if (filtered.size != existing.size) persistRevocations(filtered)197 }198 }199200 fun clear() {201 mutationGate.withLock {202 prefs.edit()203 .remove(KEY_DEVICES)204 .remove(KEY_REVOCATIONS)205 .apply()206 }207 }208209 210211212213 fun updateLastSeen(id: String, ip: String? = null) {214 mutationGate.withLock {215 val current = get(id) ?: return@withLock216 if (ip == null) return@withLock217 upsert(current.copy(lastKnownIp = ip))218 }219 }220221 fun updateLastSync(id: String, at: Long = System.currentTimeMillis()) {222 mutationGate.withLock {223 val current = get(id) ?: return@withLock224 upsert(current.copy(lastSyncedAt = at))225 }226 }227228 229230231232233234 fun propagateRelaySetting(mode: SyncMode, storedRelayUrl: String) {235 mutationGate.withLock {236 val current = getAll()237 val next = withRelaySetting(current, mode, storedRelayUrl)238 if (next != current) persist(next)239 }240 }241242 243244245246247 fun observeAll(): Flow<List<PairedDevice>> = callbackFlow {248 trySend(getAll())249 val listener = android.content.SharedPreferences.OnSharedPreferenceChangeListener { _, key ->250 if (key == KEY_DEVICES || key == null) trySend(getAll())251 }252 prefs.registerOnSharedPreferenceChangeListener(listener)253 awaitClose { prefs.unregisterOnSharedPreferenceChangeListener(listener) }254 }255256 private fun persistRevocations(records: List<DeviceRevocation>) {257 prefs.edit()258 .putString(KEY_REVOCATIONS, json.encodeToString(revocationSerializer, records))259 .apply()260 }261262 private fun persist(devices: List<PairedDevice>) {263 prefs.edit()264 .putString(KEY_DEVICES, json.encodeToString(listSerializer, devices))265 .apply()266 }267268 private data class RegistryPrefsState(269 val devices: String?,270 val revocations: String?,271 )272273 private fun readPrefsState(): RegistryPrefsState = RegistryPrefsState(274 devices = prefs.getString(KEY_DEVICES, null),275 revocations = prefs.getString(KEY_REVOCATIONS, null),276 )277278 private fun writePrefsState(state: RegistryPrefsState): Boolean {279 val edit = prefs.edit()280 if (state.devices == null) edit.remove(KEY_DEVICES) else edit.putString(KEY_DEVICES, state.devices)281 if (state.revocations == null) edit.remove(KEY_REVOCATIONS) else edit.putString(KEY_REVOCATIONS, state.revocations)282 return edit.commit()283 }284285 private companion object {286 const val PREFS_FILE = "peach_paired_devices"287 const val KEY_DEVICES = "paired_devices"288 const val KEY_REVOCATIONS = "device_revocations"289 290 const val MAX_REVOCATIONS = MAX_REVOCATION_RECORDS291 val json = Json { encodeDefaults = true; ignoreUnknownKeys = true }292 }293}294295296internal class RegistryMutationGate {297 private val lock = ReentrantLock()298299 fun <T> withLock(block: () -> T): T = lock.withLock(block)300}301302internal fun withLocalAlias(303 devices: List<PairedDevice>,304 deviceId: String,305 name: String,306): List<PairedDevice> {307 val alias = name.trim()308 require(alias.isNotEmpty()) { "device name must not be empty" }309 require(alias.length <= MAX_DEVICE_NAME_CHARS) { "device name must be 64 chars or fewer" }310 require(devices.any { it.deviceId == deviceId }) { "device_not_found" }311 return devices.map { if (it.deviceId == deviceId) it.copy(localAlias = alias) else it }312}313314internal data class DeviceRevocationMutation(315 val devices: List<PairedDevice>,316 val revocations: List<DeviceRevocation>,317 val added: DeviceRevocation?,318)319320321322323324325326327internal fun planDeviceRevocation(328 devices: List<PairedDevice>,329 revocations: List<DeviceRevocation>,330 deviceId: String,331 revokedByDeviceId: String,332 nowMs: Long,333): DeviceRevocationMutation {334 val remaining = devices.filterNot { it.deviceId == deviceId }335 if (revocations.any { it.deviceId == deviceId }) {336 return DeviceRevocationMutation(remaining, revocations, null)337 }338 val device = devices.firstOrNull { it.deviceId == deviceId }339 val record = DeviceRevocation(340 deviceId = deviceId,341 longTermPublicKeyHex = device?.longTermPublicKeyHex ?: "0".repeat(64),342 revokedAt = nowMs,343 revokedByDeviceId = revokedByDeviceId,344 )345 val retained = if (revocations.size < MAX_REVOCATION_RECORDS) {346 revocations347 } else {348 val removable = revocations.indexOfFirst { it.revokedByDeviceId != revokedByDeviceId }349 if (removable >= 0) revocations.toMutableList().also { it.removeAt(removable) } else revocations350 }351 return DeviceRevocationMutation(352 remaining,353 (retained + record).takeLast(MAX_REVOCATION_RECORDS),354 record,355 )356}357358internal data class RevocationMergeResult(359 val records: List<DeviceRevocation>,360 val admitted: List<DeviceRevocation>,361)362363internal fun mergeRevocationRecords(364 existing: List<DeviceRevocation>,365 incoming: List<DeviceRevocation>,366): RevocationMergeResult {367 val known = existing.map { it.deviceId }.toSet()368 val fresh = incoming.filterNot { known.contains(it.deviceId) }369 val admitted = fresh.take((MAX_REVOCATION_RECORDS - existing.size).coerceAtLeast(0))370 return RevocationMergeResult(existing + admitted, admitted)371}372373374375376377378379internal fun withRelaySetting(380 devices: List<PairedDevice>,381 mode: SyncMode,382 storedRelayUrl: String,383): List<PairedDevice> = when (val decision = relayInForce(mode, storedRelayUrl)) {384 is RelayDecision.Dial -> devices.map { it.copy(relayUrl = decision.relayUrl) }385 is RelayDecision.Refuse -> devices386}