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 fun hasIdentityCollision(device: PairedDevice): Boolean = get(device.deviceId) != null7475 76 override fun upsert(device: PairedDevice) {77 mutationGate.withLock {78 79 80 val device = device.copy(81 deviceName = device.deviceName?.let(::capDeviceName),82 localAlias = get(device.deviceId)?.localAlias,83 )84 val next = getAll().filterNot { it.deviceId == device.deviceId } + device85 persist(next)86 }87 }8889 fun rename(deviceId: String, name: String) {90 mutationGate.withLock {91 persist(withLocalAlias(getAll(), deviceId, name))92 }93 }9495 override fun remove(deviceId: String) {96 mutationGate.withLock {97 persist(getAll().filterNot { it.deviceId == deviceId })98 }99 }100101 102103104105106107108 override fun applyManifestBatch(batch: DeviceManifestRegistryBatch): Boolean {109 return mutationGate.withLock {110 val priorPrefs = readPrefsState()111 val currentDevices = getAll()112 val currentRevocations = listRevocations()113 val nextRevocations = mergeRevocationRecords(currentRevocations, batch.incomingRevocations).records114 val removed = batch.removals115 val nextDevices = currentDevices116 .filterNot { removed.contains(it.deviceId) }117 .toMutableList()118 batch.upserts.forEach { device ->119 val alias = nextDevices.firstOrNull { it.deviceId == device.deviceId }?.localAlias120 val device = device.copy(121 deviceName = device.deviceName?.let(::capDeviceName),122 localAlias = alias,123 )124 nextDevices.removeAll { it.deviceId == device.deviceId }125 nextDevices += device126 }127128 val nextPrefs = RegistryPrefsState(129 devices = json.encodeToString(listSerializer, nextDevices),130 revocations = json.encodeToString(revocationSerializer, nextRevocations),131 )132 133 134 135 commitWithRollback(priorPrefs, nextPrefs, ::writePrefsState)136 }137 }138139 140141 override fun listRevocations(): List<DeviceRevocation> {142 val raw = prefs.getString(KEY_REVOCATIONS, null) ?: return emptyList()143 return runCatching { json.decodeFromString(revocationSerializer, raw) }144 .getOrDefault(emptyList())145 }146147 148149150151152153 fun revoke(154 deviceId: String,155 revokedByDeviceId: String,156 nowMs: Long = System.currentTimeMillis(),157 ): DeviceRevocation? = mutationGate.withLock {158 val currentDevices = getAll()159 val currentRevocations = listRevocations()160 val mutation = planDeviceRevocation(161 devices = currentDevices,162 revocations = currentRevocations,163 deviceId = deviceId,164 revokedByDeviceId = revokedByDeviceId,165 nowMs = nowMs,166 )167 if (mutation.revocations !== currentRevocations) {168 persistRevocations(mutation.revocations)169 }170 if (mutation.devices != currentDevices) {171 persist(mutation.devices)172 }173 mutation.added174 }175176 177178179180 override fun mergeRevocations(incoming: List<DeviceRevocation>): List<String> {181 return mutationGate.withLock {182 val existing = listRevocations()183 val merged = mergeRevocationRecords(existing, incoming)184 if (merged.records != existing) persistRevocations(merged.records)185 merged.admitted.map { it.deviceId }186 }187 }188189 190191192193194 override fun clearRevocation(deviceId: String) {195 mutationGate.withLock {196 val existing = listRevocations()197 val filtered = existing.filterNot { it.deviceId == deviceId }198 if (filtered.size != existing.size) persistRevocations(filtered)199 }200 }201202 fun clear() {203 mutationGate.withLock {204 prefs.edit()205 .remove(KEY_DEVICES)206 .remove(KEY_REVOCATIONS)207 .apply()208 }209 }210211 212213214215 fun updateLastSeen(id: String, ip: String? = null) {216 mutationGate.withLock {217 val current = get(id) ?: return@withLock218 if (ip == null) return@withLock219 upsert(current.copy(lastKnownIp = ip))220 }221 }222223 fun updateLastSync(id: String, at: Long = System.currentTimeMillis()) {224 mutationGate.withLock {225 val current = get(id) ?: return@withLock226 upsert(current.copy(lastSyncedAt = at))227 }228 }229230 231232233234235236 fun propagateRelaySetting(mode: SyncMode, storedRelayUrl: String) {237 mutationGate.withLock {238 val current = getAll()239 val next = withRelaySetting(current, mode, storedRelayUrl)240 if (next != current) persist(next)241 }242 }243244 245246247248249 fun observeAll(): Flow<List<PairedDevice>> = callbackFlow {250 trySend(getAll())251 val listener = android.content.SharedPreferences.OnSharedPreferenceChangeListener { _, key ->252 if (key == KEY_DEVICES || key == null) trySend(getAll())253 }254 prefs.registerOnSharedPreferenceChangeListener(listener)255 awaitClose { prefs.unregisterOnSharedPreferenceChangeListener(listener) }256 }257258 private fun persistRevocations(records: List<DeviceRevocation>) {259 prefs.edit()260 .putString(KEY_REVOCATIONS, json.encodeToString(revocationSerializer, records))261 .apply()262 }263264 private fun persist(devices: List<PairedDevice>) {265 prefs.edit()266 .putString(KEY_DEVICES, json.encodeToString(listSerializer, devices))267 .apply()268 }269270 private data class RegistryPrefsState(271 val devices: String?,272 val revocations: String?,273 )274275 private fun readPrefsState(): RegistryPrefsState = RegistryPrefsState(276 devices = prefs.getString(KEY_DEVICES, null),277 revocations = prefs.getString(KEY_REVOCATIONS, null),278 )279280 private fun writePrefsState(state: RegistryPrefsState): Boolean {281 val edit = prefs.edit()282 if (state.devices == null) edit.remove(KEY_DEVICES) else edit.putString(KEY_DEVICES, state.devices)283 if (state.revocations == null) edit.remove(KEY_REVOCATIONS) else edit.putString(KEY_REVOCATIONS, state.revocations)284 return edit.commit()285 }286287 private companion object {288 const val PREFS_FILE = "peach_paired_devices"289 const val KEY_DEVICES = "paired_devices"290 const val KEY_REVOCATIONS = "device_revocations"291 292 const val MAX_REVOCATIONS = MAX_REVOCATION_RECORDS293 val json = Json { encodeDefaults = true; ignoreUnknownKeys = true }294 }295}296297298internal class RegistryMutationGate {299 private val lock = ReentrantLock()300301 fun <T> withLock(block: () -> T): T = lock.withLock(block)302}303304internal fun withLocalAlias(305 devices: List<PairedDevice>,306 deviceId: String,307 name: String,308): List<PairedDevice> {309 val alias = name.trim()310 require(alias.isNotEmpty()) { "device name must not be empty" }311 require(alias.length <= MAX_DEVICE_NAME_CHARS) { "device name must be 64 chars or fewer" }312 require(devices.any { it.deviceId == deviceId }) { "device_not_found" }313 return devices.map { if (it.deviceId == deviceId) it.copy(localAlias = alias) else it }314}315316internal data class DeviceRevocationMutation(317 val devices: List<PairedDevice>,318 val revocations: List<DeviceRevocation>,319 val added: DeviceRevocation?,320)321322323324325326327328329internal fun planDeviceRevocation(330 devices: List<PairedDevice>,331 revocations: List<DeviceRevocation>,332 deviceId: String,333 revokedByDeviceId: String,334 nowMs: Long,335): DeviceRevocationMutation {336 val remaining = devices.filterNot { it.deviceId == deviceId }337 if (revocations.any { it.deviceId == deviceId }) {338 return DeviceRevocationMutation(remaining, revocations, null)339 }340 val device = devices.firstOrNull { it.deviceId == deviceId }341 val record = DeviceRevocation(342 deviceId = deviceId,343 longTermPublicKeyHex = device?.longTermPublicKeyHex ?: "0".repeat(64),344 revokedAt = nowMs,345 revokedByDeviceId = revokedByDeviceId,346 )347 val retained = if (revocations.size < MAX_REVOCATION_RECORDS) {348 revocations349 } else {350 val removable = revocations.indexOfFirst { it.revokedByDeviceId != revokedByDeviceId }351 if (removable >= 0) revocations.toMutableList().also { it.removeAt(removable) } else revocations352 }353 return DeviceRevocationMutation(354 remaining,355 (retained + record).takeLast(MAX_REVOCATION_RECORDS),356 record,357 )358}359360internal data class RevocationMergeResult(361 val records: List<DeviceRevocation>,362 val admitted: List<DeviceRevocation>,363)364365internal fun mergeRevocationRecords(366 existing: List<DeviceRevocation>,367 incoming: List<DeviceRevocation>,368): RevocationMergeResult {369 val known = existing.map { it.deviceId }.toSet()370 val fresh = incoming.filterNot { known.contains(it.deviceId) }371 val admitted = fresh.take((MAX_REVOCATION_RECORDS - existing.size).coerceAtLeast(0))372 return RevocationMergeResult(existing + admitted, admitted)373}374375376377378379380381internal fun withRelaySetting(382 devices: List<PairedDevice>,383 mode: SyncMode,384 storedRelayUrl: String,385): List<PairedDevice> = when (val decision = relayInForce(mode, storedRelayUrl)) {386 is RelayDecision.Dial -> devices.map { it.copy(relayUrl = decision.relayUrl) }387 is RelayDecision.Refuse -> devices388}