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 fun upsertAndClearRevocation(device: PairedDevice) {78 mutationGate.withLock {79 val currentDevices = getAll()80 val existing = currentDevices.firstOrNull { it.deviceId == device.deviceId }81 val bound = bindImmutableIdentity(existing, device)82 val nextDevice = bound.copy(83 deviceName = bound.deviceName?.let(::capDeviceName),84 localAlias = existing?.localAlias,85 )86 val nextDevices = currentDevices.filterNot { it.deviceId == device.deviceId } + nextDevice87 val currentRevocations = listRevocations()88 val nextRevocations = currentRevocations.filterNot { it.deviceId == device.deviceId }89 val nextPrefs = RegistryPrefsState(90 devices = json.encodeToString(listSerializer, nextDevices),91 revocations = json.encodeToString(revocationSerializer, nextRevocations),92 )93 check(commitWithRollback(readPrefsState(), nextPrefs, ::writePrefsState)) {94 "paired_device_persist_failed"95 }96 }97 }9899 100 override fun upsert(device: PairedDevice) {101 mutationGate.withLock {102 val currentDevices = getAll()103 val existing = currentDevices.firstOrNull { it.deviceId == device.deviceId }104 val bound = bindImmutableIdentity(existing, device)105 106 107 val nextDevice = bound.copy(108 deviceName = bound.deviceName?.let(::capDeviceName),109 localAlias = existing?.localAlias,110 )111 val next = currentDevices.filterNot { it.deviceId == device.deviceId } + nextDevice112 persist(next)113 }114 }115116 117118119120121122123 override fun applyManifestBatch(batch: DeviceManifestRegistryBatch): Boolean {124 return mutationGate.withLock {125 val priorPrefs = readPrefsState()126 val currentDevices = getAll()127 val currentById = currentDevices.associateBy { it.deviceId }128 val currentRevocations = listRevocations()129 val nextRevocations = mergeRevocationRecords(currentRevocations, batch.incomingRevocations).records130 val removed = batch.removals131 val nextDevices = currentDevices132 .filterNot { removed.contains(it.deviceId) }133 .toMutableList()134 batch.upserts.forEach { incoming ->135 val existing = currentById[incoming.deviceId]136 ?: nextDevices.firstOrNull { it.deviceId == incoming.deviceId }137 require(!nextDevices.any { candidate ->138 candidate.deviceId != incoming.deviceId &&139 ((candidate.longTermPublicKeyHex != null && incoming.longTermPublicKeyHex != null && CryptoCompare.hex(candidate.longTermPublicKeyHex, incoming.longTermPublicKeyHex)) ||140 (candidate.signingPublicKeyHex != null && incoming.signingPublicKeyHex != null && CryptoCompare.hex(candidate.signingPublicKeyHex, incoming.signingPublicKeyHex)))141 }) { "device_identity_collision" }142 val bound = bindImmutableIdentity(existing, incoming)143 val alias = nextDevices.firstOrNull { it.deviceId == incoming.deviceId }?.localAlias144 val device = bound.copy(145 deviceName = bound.deviceName?.let(::capDeviceName),146 localAlias = alias,147 )148 nextDevices.removeAll { it.deviceId == device.deviceId }149 nextDevices += device150 }151152 val nextPrefs = RegistryPrefsState(153 devices = json.encodeToString(listSerializer, nextDevices),154 revocations = json.encodeToString(revocationSerializer, nextRevocations),155 )156 157 158 159 commitWithRollback(priorPrefs, nextPrefs, ::writePrefsState)160 }161 }162163 fun rename(deviceId: String, name: String) {164 mutationGate.withLock {165 persist(withLocalAlias(getAll(), deviceId, name))166 }167 }168169 override fun remove(deviceId: String) {170 mutationGate.withLock {171 persist(getAll().filterNot { it.deviceId == deviceId })172 }173 }174175176177 178179 override fun listRevocations(): List<DeviceRevocation> {180 val raw = prefs.getString(KEY_REVOCATIONS, null) ?: return emptyList()181 return runCatching { json.decodeFromString(revocationSerializer, raw) }182 .getOrDefault(emptyList())183 }184185 186187188189190191 fun revoke(192 deviceId: String,193 revokedByDeviceId: String,194 nowMs: Long = System.currentTimeMillis(),195 ): DeviceRevocation? = mutationGate.withLock {196 val currentDevices = getAll()197 val currentRevocations = listRevocations()198 val mutation = planDeviceRevocation(199 devices = currentDevices,200 revocations = currentRevocations,201 deviceId = deviceId,202 revokedByDeviceId = revokedByDeviceId,203 nowMs = nowMs,204 )205 if (mutation.revocations !== currentRevocations) {206 persistRevocations(mutation.revocations)207 }208 if (mutation.devices != currentDevices) {209 persist(mutation.devices)210 }211 mutation.added212 }213214 215216217218 override fun mergeRevocations(incoming: List<DeviceRevocation>): List<String> {219 return mutationGate.withLock {220 val existing = listRevocations()221 val merged = mergeRevocationRecords(existing, incoming)222 if (merged.records != existing) persistRevocations(merged.records)223 merged.admitted.map { it.deviceId }224 }225 }226227 228229230231232 override fun clearRevocation(deviceId: String) {233 mutationGate.withLock {234 val existing = listRevocations()235 val filtered = existing.filterNot { it.deviceId == deviceId }236 if (filtered.size != existing.size) persistRevocations(filtered)237 }238 }239240 fun clear() {241 mutationGate.withLock {242 prefs.edit()243 .remove(KEY_DEVICES)244 .remove(KEY_REVOCATIONS)245 .apply()246 }247 }248249 250251252253 fun updateLastSeen(id: String, ip: String? = null) {254 mutationGate.withLock {255 val current = get(id) ?: return@withLock256 if (ip == null) return@withLock257 upsert(current.copy(lastKnownIp = ip))258 }259 }260261 fun updateLastSync(id: String, at: Long = System.currentTimeMillis()) {262 mutationGate.withLock {263 val current = get(id) ?: return@withLock264 upsert(current.copy(lastSyncedAt = at))265 }266 }267268 269270271272273274 fun propagateRelaySetting(mode: SyncMode, storedRelayUrl: String) {275 mutationGate.withLock {276 val current = getAll()277 val next = withRelaySetting(current, mode, storedRelayUrl)278 if (next != current) persist(next)279 }280 }281282 283284285286287 fun observeAll(): Flow<List<PairedDevice>> = callbackFlow {288 trySend(getAll())289 val listener = android.content.SharedPreferences.OnSharedPreferenceChangeListener { _, key ->290 if (key == KEY_DEVICES || key == null) trySend(getAll())291 }292 prefs.registerOnSharedPreferenceChangeListener(listener)293 awaitClose { prefs.unregisterOnSharedPreferenceChangeListener(listener) }294 }295296 private fun persistRevocations(records: List<DeviceRevocation>) {297 prefs.edit()298 .putString(KEY_REVOCATIONS, json.encodeToString(revocationSerializer, records))299 .apply()300 }301302 private fun persist(devices: List<PairedDevice>) {303 prefs.edit()304 .putString(KEY_DEVICES, json.encodeToString(listSerializer, devices))305 .apply()306 }307308 private data class RegistryPrefsState(309 val devices: String?,310 val revocations: String?,311 )312313 private fun readPrefsState(): RegistryPrefsState = RegistryPrefsState(314 devices = prefs.getString(KEY_DEVICES, null),315 revocations = prefs.getString(KEY_REVOCATIONS, null),316 )317318 private fun writePrefsState(state: RegistryPrefsState): Boolean {319 val edit = prefs.edit()320 if (state.devices == null) edit.remove(KEY_DEVICES) else edit.putString(KEY_DEVICES, state.devices)321 if (state.revocations == null) edit.remove(KEY_REVOCATIONS) else edit.putString(KEY_REVOCATIONS, state.revocations)322 return edit.commit()323 }324325 private companion object {326 const val PREFS_FILE = "peach_paired_devices"327 const val KEY_DEVICES = "paired_devices"328 const val KEY_REVOCATIONS = "device_revocations"329 330 const val MAX_REVOCATIONS = MAX_REVOCATION_RECORDS331 val json = Json { encodeDefaults = true; ignoreUnknownKeys = true }332 }333}334335internal fun bindImmutableIdentity(existing: PairedDevice?, incoming: PairedDevice): PairedDevice {336 if (existing == null) return incoming337338 val longTermChanged = existing.longTermPublicKeyHex != null &&339 incoming.longTermPublicKeyHex != null &&340 !CryptoCompare.hex(existing.longTermPublicKeyHex, incoming.longTermPublicKeyHex)341 val signingChanged = existing.signingPublicKeyHex != null &&342 incoming.signingPublicKeyHex != null &&343 !CryptoCompare.hex(existing.signingPublicKeyHex, incoming.signingPublicKeyHex)344 require(!longTermChanged && !signingChanged) { "device_identity_immutable" }345346 return incoming.copy(347 longTermPublicKeyHex = incoming.longTermPublicKeyHex ?: existing.longTermPublicKeyHex,348 signingPublicKeyHex = incoming.signingPublicKeyHex ?: existing.signingPublicKeyHex,349 )350}351352353internal class RegistryMutationGate {354 private val lock = ReentrantLock()355356 fun <T> withLock(block: () -> T): T = lock.withLock(block)357}358359internal fun withLocalAlias(360 devices: List<PairedDevice>,361 deviceId: String,362 name: String,363): List<PairedDevice> {364 val alias = name.trim()365 require(alias.isNotEmpty()) { "device name must not be empty" }366 require(alias.length <= MAX_DEVICE_NAME_CHARS) { "device name must be 64 chars or fewer" }367 require(devices.any { it.deviceId == deviceId }) { "device_not_found" }368 return devices.map { if (it.deviceId == deviceId) it.copy(localAlias = alias) else it }369}370371internal data class DeviceRevocationMutation(372 val devices: List<PairedDevice>,373 val revocations: List<DeviceRevocation>,374 val added: DeviceRevocation?,375)376377378internal fun hasAdoptionIdentityConflict(379 incoming: PairedDevice,380 devices: List<PairedDevice>,381 revocations: List<DeviceRevocation>,382): Boolean {383 if (devices.any { it.deviceId == incoming.deviceId }) return true384 if (devices.any {385 it.longTermPublicKeyHex?.let { key -> incoming.longTermPublicKeyHex?.let { candidate -> CryptoCompare.hex(key, candidate) } } == true ||386 it.signingPublicKeyHex?.let { key -> incoming.signingPublicKeyHex?.let { candidate -> CryptoCompare.hex(key, candidate) } } == true387 }) return true388 return revocations.any { revoked ->389 revoked.deviceId == incoming.deviceId ||390 incoming.longTermPublicKeyHex?.let { CryptoCompare.hex(revoked.longTermPublicKeyHex, it) } == true391 }392}393394395396397398399400401internal fun planDeviceRevocation(402 devices: List<PairedDevice>,403 revocations: List<DeviceRevocation>,404 deviceId: String,405 revokedByDeviceId: String,406 nowMs: Long,407): DeviceRevocationMutation {408 val remaining = devices.filterNot { it.deviceId == deviceId }409 if (revocations.any { it.deviceId == deviceId }) {410 return DeviceRevocationMutation(remaining, revocations, null)411 }412 val device = devices.firstOrNull { it.deviceId == deviceId }413 val record = DeviceRevocation(414 deviceId = deviceId,415 longTermPublicKeyHex = device?.longTermPublicKeyHex ?: "0".repeat(64),416 revokedAt = nowMs,417 revokedByDeviceId = revokedByDeviceId,418 )419 return DeviceRevocationMutation(420 remaining,421 capRevocationRecords(revocations + record),422 record,423 )424}425426internal data class RevocationMergeResult(427 val records: List<DeviceRevocation>,428 val admitted: List<DeviceRevocation>,429)430431internal fun mergeRevocationRecords(432 existing: List<DeviceRevocation>,433 incoming: List<DeviceRevocation>,434): RevocationMergeResult {435 val known = existing.map { it.deviceId }.toSet()436 val fresh = incoming.filterNot { known.contains(it.deviceId) }437 return RevocationMergeResult(capRevocationRecords(existing + fresh), fresh)438}439440441442443444445internal fun capRevocationRecords(records: List<DeviceRevocation>): List<DeviceRevocation> {446 if (records.size <= MAX_REVOCATION_RECORDS) return records447 val liveCounts = records.groupingBy { it.revokedByDeviceId }.eachCount().toMutableMap()448 val dropped = BooleanArray(records.size)449 repeat(records.size - MAX_REVOCATION_RECORDS) {450 val largestIssuer = liveCounts.maxByOrNull { it.value }?.key ?: return@repeat451 val oldestIndex = records.indices.firstOrNull { index ->452 !dropped[index] && records[index].revokedByDeviceId == largestIssuer453 } ?: return@repeat454 dropped[oldestIndex] = true455 liveCounts[largestIssuer] = liveCounts.getValue(largestIssuer) - 1456 }457 return records.filterIndexed { index, _ -> !dropped[index] }458}459460461462463464465466internal fun withRelaySetting(467 devices: List<PairedDevice>,468 mode: SyncMode,469 storedRelayUrl: String,470): List<PairedDevice> = when (val decision = relayInForce(mode, storedRelayUrl)) {471 is RelayDecision.Dial -> devices.map { it.copy(relayUrl = decision.relayUrl) }472 is RelayDecision.Refuse -> devices473}