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 =74 hasAdoptionIdentityConflict(device, getAll(), listRevocations())7576 77 override fun upsert(device: PairedDevice) {78 mutationGate.withLock {79 80 81 val device = device.copy(82 deviceName = device.deviceName?.let(::capDeviceName),83 localAlias = get(device.deviceId)?.localAlias,84 )85 val next = getAll().filterNot { it.deviceId == device.deviceId } + device86 persist(next)87 }88 }8990 fun rename(deviceId: String, name: String) {91 mutationGate.withLock {92 persist(withLocalAlias(getAll(), deviceId, name))93 }94 }9596 override fun remove(deviceId: String) {97 mutationGate.withLock {98 persist(getAll().filterNot { it.deviceId == deviceId })99 }100 }101102 103104105106107108109 override fun applyManifestBatch(batch: DeviceManifestRegistryBatch): Boolean {110 return mutationGate.withLock {111 val priorPrefs = readPrefsState()112 val currentDevices = getAll()113 val currentRevocations = listRevocations()114 val nextRevocations = mergeRevocationRecords(currentRevocations, batch.incomingRevocations).records115 val removed = batch.removals116 val nextDevices = currentDevices117 .filterNot { removed.contains(it.deviceId) }118 .toMutableList()119 batch.upserts.forEach { device ->120 val alias = nextDevices.firstOrNull { it.deviceId == device.deviceId }?.localAlias121 val device = device.copy(122 deviceName = device.deviceName?.let(::capDeviceName),123 localAlias = alias,124 )125 nextDevices.removeAll { it.deviceId == device.deviceId }126 nextDevices += device127 }128129 val nextPrefs = RegistryPrefsState(130 devices = json.encodeToString(listSerializer, nextDevices),131 revocations = json.encodeToString(revocationSerializer, nextRevocations),132 )133 134 135 136 commitWithRollback(priorPrefs, nextPrefs, ::writePrefsState)137 }138 }139140 141142 override fun listRevocations(): List<DeviceRevocation> {143 val raw = prefs.getString(KEY_REVOCATIONS, null) ?: return emptyList()144 return runCatching { json.decodeFromString(revocationSerializer, raw) }145 .getOrDefault(emptyList())146 }147148 149150151152153154 fun revoke(155 deviceId: String,156 revokedByDeviceId: String,157 nowMs: Long = System.currentTimeMillis(),158 ): DeviceRevocation? = mutationGate.withLock {159 val currentDevices = getAll()160 val currentRevocations = listRevocations()161 val mutation = planDeviceRevocation(162 devices = currentDevices,163 revocations = currentRevocations,164 deviceId = deviceId,165 revokedByDeviceId = revokedByDeviceId,166 nowMs = nowMs,167 )168 if (mutation.revocations !== currentRevocations) {169 persistRevocations(mutation.revocations)170 }171 if (mutation.devices != currentDevices) {172 persist(mutation.devices)173 }174 mutation.added175 }176177 178179180181 override fun mergeRevocations(incoming: List<DeviceRevocation>): List<String> {182 return mutationGate.withLock {183 val existing = listRevocations()184 val merged = mergeRevocationRecords(existing, incoming)185 if (merged.records != existing) persistRevocations(merged.records)186 merged.admitted.map { it.deviceId }187 }188 }189190 191192193194195 override fun clearRevocation(deviceId: String) {196 mutationGate.withLock {197 val existing = listRevocations()198 val filtered = existing.filterNot { it.deviceId == deviceId }199 if (filtered.size != existing.size) persistRevocations(filtered)200 }201 }202203 fun clear() {204 mutationGate.withLock {205 prefs.edit()206 .remove(KEY_DEVICES)207 .remove(KEY_REVOCATIONS)208 .apply()209 }210 }211212 213214215216 fun updateLastSeen(id: String, ip: String? = null) {217 mutationGate.withLock {218 val current = get(id) ?: return@withLock219 if (ip == null) return@withLock220 upsert(current.copy(lastKnownIp = ip))221 }222 }223224 fun updateLastSync(id: String, at: Long = System.currentTimeMillis()) {225 mutationGate.withLock {226 val current = get(id) ?: return@withLock227 upsert(current.copy(lastSyncedAt = at))228 }229 }230231 232233234235236237 fun propagateRelaySetting(mode: SyncMode, storedRelayUrl: String) {238 mutationGate.withLock {239 val current = getAll()240 val next = withRelaySetting(current, mode, storedRelayUrl)241 if (next != current) persist(next)242 }243 }244245 246247248249250 fun observeAll(): Flow<List<PairedDevice>> = callbackFlow {251 trySend(getAll())252 val listener = android.content.SharedPreferences.OnSharedPreferenceChangeListener { _, key ->253 if (key == KEY_DEVICES || key == null) trySend(getAll())254 }255 prefs.registerOnSharedPreferenceChangeListener(listener)256 awaitClose { prefs.unregisterOnSharedPreferenceChangeListener(listener) }257 }258259 private fun persistRevocations(records: List<DeviceRevocation>) {260 prefs.edit()261 .putString(KEY_REVOCATIONS, json.encodeToString(revocationSerializer, records))262 .apply()263 }264265 private fun persist(devices: List<PairedDevice>) {266 prefs.edit()267 .putString(KEY_DEVICES, json.encodeToString(listSerializer, devices))268 .apply()269 }270271 private data class RegistryPrefsState(272 val devices: String?,273 val revocations: String?,274 )275276 private fun readPrefsState(): RegistryPrefsState = RegistryPrefsState(277 devices = prefs.getString(KEY_DEVICES, null),278 revocations = prefs.getString(KEY_REVOCATIONS, null),279 )280281 private fun writePrefsState(state: RegistryPrefsState): Boolean {282 val edit = prefs.edit()283 if (state.devices == null) edit.remove(KEY_DEVICES) else edit.putString(KEY_DEVICES, state.devices)284 if (state.revocations == null) edit.remove(KEY_REVOCATIONS) else edit.putString(KEY_REVOCATIONS, state.revocations)285 return edit.commit()286 }287288 private companion object {289 const val PREFS_FILE = "peach_paired_devices"290 const val KEY_DEVICES = "paired_devices"291 const val KEY_REVOCATIONS = "device_revocations"292 293 const val MAX_REVOCATIONS = MAX_REVOCATION_RECORDS294 val json = Json { encodeDefaults = true; ignoreUnknownKeys = true }295 }296}297298299internal class RegistryMutationGate {300 private val lock = ReentrantLock()301302 fun <T> withLock(block: () -> T): T = lock.withLock(block)303}304305internal fun withLocalAlias(306 devices: List<PairedDevice>,307 deviceId: String,308 name: String,309): List<PairedDevice> {310 val alias = name.trim()311 require(alias.isNotEmpty()) { "device name must not be empty" }312 require(alias.length <= MAX_DEVICE_NAME_CHARS) { "device name must be 64 chars or fewer" }313 require(devices.any { it.deviceId == deviceId }) { "device_not_found" }314 return devices.map { if (it.deviceId == deviceId) it.copy(localAlias = alias) else it }315}316317internal data class DeviceRevocationMutation(318 val devices: List<PairedDevice>,319 val revocations: List<DeviceRevocation>,320 val added: DeviceRevocation?,321)322323324internal fun hasAdoptionIdentityConflict(325 incoming: PairedDevice,326 devices: List<PairedDevice>,327 revocations: List<DeviceRevocation>,328): Boolean {329 if (devices.any { it.deviceId == incoming.deviceId }) return true330 return revocations.any { revoked ->331 revoked.deviceId == incoming.deviceId ||332 incoming.longTermPublicKeyHex?.let {333 CryptoCompare.hex(revoked.longTermPublicKeyHex, it)334 } == true335 }336}337338339340341342343344345internal fun planDeviceRevocation(346 devices: List<PairedDevice>,347 revocations: List<DeviceRevocation>,348 deviceId: String,349 revokedByDeviceId: String,350 nowMs: Long,351): DeviceRevocationMutation {352 val remaining = devices.filterNot { it.deviceId == deviceId }353 if (revocations.any { it.deviceId == deviceId }) {354 return DeviceRevocationMutation(remaining, revocations, null)355 }356 val device = devices.firstOrNull { it.deviceId == deviceId }357 val record = DeviceRevocation(358 deviceId = deviceId,359 longTermPublicKeyHex = device?.longTermPublicKeyHex ?: "0".repeat(64),360 revokedAt = nowMs,361 revokedByDeviceId = revokedByDeviceId,362 )363 return DeviceRevocationMutation(364 remaining,365 capRevocationRecords(revocations + record),366 record,367 )368}369370internal data class RevocationMergeResult(371 val records: List<DeviceRevocation>,372 val admitted: List<DeviceRevocation>,373)374375internal fun mergeRevocationRecords(376 existing: List<DeviceRevocation>,377 incoming: List<DeviceRevocation>,378): RevocationMergeResult {379 val known = existing.map { it.deviceId }.toSet()380 val fresh = incoming.filterNot { known.contains(it.deviceId) }381 return RevocationMergeResult(capRevocationRecords(existing + fresh), fresh)382}383384385386387388389internal fun capRevocationRecords(records: List<DeviceRevocation>): List<DeviceRevocation> {390 if (records.size <= MAX_REVOCATION_RECORDS) return records391 val liveCounts = records.groupingBy { it.revokedByDeviceId }.eachCount().toMutableMap()392 val dropped = BooleanArray(records.size)393 repeat(records.size - MAX_REVOCATION_RECORDS) {394 val largestIssuer = liveCounts.maxByOrNull { it.value }?.key ?: return@repeat395 val oldestIndex = records.indices.firstOrNull { index ->396 !dropped[index] && records[index].revokedByDeviceId == largestIssuer397 } ?: return@repeat398 dropped[oldestIndex] = true399 liveCounts[largestIssuer] = liveCounts.getValue(largestIssuer) - 1400 }401 return records.filterIndexed { index, _ -> !dropped[index] }402}403404405406407408409410internal fun withRelaySetting(411 devices: List<PairedDevice>,412 mode: SyncMode,413 storedRelayUrl: String,414): List<PairedDevice> = when (val decision = relayInForce(mode, storedRelayUrl)) {415 is RelayDecision.Dial -> devices.map { it.copy(relayUrl = decision.relayUrl) }416 is RelayDecision.Refuse -> devices417}