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 try {64 json.decodeFromString(listSerializer, raw)65 } catch (e: Exception) {66 throw TrustDataCorruptedException(KEY_DEVICES, e.message ?: "decode_failed")67 }68 }6970 override fun get(id: String): PairedDevice? = getAll().firstOrNull { it.deviceId == id }7172 override fun getByPubkey(pubkeyHex: String): PairedDevice? =73 getAll().firstOrNull {74 it.longTermPublicKeyHex?.let { key -> CryptoCompare.hex(key, pubkeyHex) } == true75 }7677 fun hasIdentityCollision(device: PairedDevice): Boolean =78 hasAdoptionIdentityConflict(device, getAll(), listRevocations())7980 81 fun upsertAndClearRevocation(device: PairedDevice) {82 mutationGate.withLock {83 val currentDevices = getAll()84 val existing = currentDevices.firstOrNull { it.deviceId == device.deviceId }85 val bound = bindImmutableIdentity(existing, device)86 val nextDevice = bound.copy(87 deviceName = bound.deviceName?.let(::capDeviceName),88 localAlias = existing?.localAlias,89 )90 val nextDevices = currentDevices.filterNot { it.deviceId == device.deviceId } + nextDevice91 val currentRevocations = listRevocations()92 val nextRevocations = currentRevocations.filterNot { it.deviceId == device.deviceId }93 val nextPrefs = RegistryPrefsState(94 devices = json.encodeToString(listSerializer, nextDevices),95 revocations = json.encodeToString(revocationSerializer, nextRevocations),96 )97 check(commitWithRollback(readPrefsState(), nextPrefs, ::writePrefsState)) {98 "paired_device_persist_failed"99 }100 }101 }102103 104 override fun upsert(device: PairedDevice) {105 mutationGate.withLock {106 val currentDevices = getAll()107 val existing = currentDevices.firstOrNull { it.deviceId == device.deviceId }108 val bound = bindImmutableIdentity(existing, device)109 110 111 val nextDevice = bound.copy(112 deviceName = bound.deviceName?.let(::capDeviceName),113 localAlias = existing?.localAlias,114 )115 val next = currentDevices.filterNot { it.deviceId == device.deviceId } + nextDevice116 persist(next)117 }118 }119120 121122123124125126127 override fun applyManifestBatch(batch: DeviceManifestRegistryBatch): Boolean {128 return mutationGate.withLock {129 val priorPrefs = readPrefsState()130 val currentDevices = getAll()131 val currentById = currentDevices.associateBy { it.deviceId }132 val currentRevocations = listRevocations()133 val nextRevocations = mergeRevocationRecords(currentRevocations, batch.incomingRevocations).records134 val removed = batch.removals135 val nextDevices = currentDevices136 .filterNot { removed.contains(it.deviceId) }137 .toMutableList()138 batch.upserts.forEach { incoming ->139 val existing = currentById[incoming.deviceId]140 ?: nextDevices.firstOrNull { it.deviceId == incoming.deviceId }141 require(!nextDevices.any { candidate ->142 candidate.deviceId != incoming.deviceId &&143 ((candidate.longTermPublicKeyHex != null && incoming.longTermPublicKeyHex != null && CryptoCompare.hex(candidate.longTermPublicKeyHex, incoming.longTermPublicKeyHex)) ||144 (candidate.signingPublicKeyHex != null && incoming.signingPublicKeyHex != null && CryptoCompare.hex(candidate.signingPublicKeyHex, incoming.signingPublicKeyHex)))145 }) { "device_identity_collision" }146 val bound = bindImmutableIdentity(existing, incoming)147 val alias = nextDevices.firstOrNull { it.deviceId == incoming.deviceId }?.localAlias148 val device = bound.copy(149 deviceName = bound.deviceName?.let(::capDeviceName),150 localAlias = alias,151 )152 nextDevices.removeAll { it.deviceId == device.deviceId }153 nextDevices += device154 }155156 val nextPrefs = RegistryPrefsState(157 devices = json.encodeToString(listSerializer, nextDevices),158 revocations = json.encodeToString(revocationSerializer, nextRevocations),159 )160 161 162 163 commitWithRollback(priorPrefs, nextPrefs, ::writePrefsState)164 }165 }166167 fun rename(deviceId: String, name: String) {168 mutationGate.withLock {169 persist(withLocalAlias(getAll(), deviceId, name))170 }171 }172173 override fun remove(deviceId: String) {174 mutationGate.withLock {175 persist(getAll().filterNot { it.deviceId == deviceId })176 }177 }178179180181 182183 override fun listRevocations(): List<DeviceRevocation> {184 val raw = prefs.getString(KEY_REVOCATIONS, null) ?: return emptyList()185 return try {186 json.decodeFromString(revocationSerializer, raw)187 } catch (e: Exception) {188 throw TrustDataCorruptedException(KEY_REVOCATIONS, e.message ?: "decode_failed")189 }190 }191192 193194195196197198 fun revoke(199 deviceId: String,200 revokedByDeviceId: String,201 nowMs: Long = System.currentTimeMillis(),202 ): DeviceRevocation? = mutationGate.withLock {203 val currentDevices = getAll()204 val currentRevocations = listRevocations()205 val mutation = planDeviceRevocation(206 devices = currentDevices,207 revocations = currentRevocations,208 deviceId = deviceId,209 revokedByDeviceId = revokedByDeviceId,210 nowMs = nowMs,211 )212 213 214 215 216 val nextPrefs = RegistryPrefsState(217 devices = json.encodeToString(listSerializer, mutation.devices),218 revocations = json.encodeToString(revocationSerializer, mutation.revocations),219 )220 check(commitWithRollback(readPrefsState(), nextPrefs, ::writePrefsState)) {221 "paired_device_persist_failed"222 }223 mutation.added224 }225226 227228229230 override fun mergeRevocations(incoming: List<DeviceRevocation>): List<String> {231 return mutationGate.withLock {232 val existing = listRevocations()233 val merged = mergeRevocationRecords(existing, incoming)234 if (merged.records != existing) persistRevocations(merged.records)235 merged.admitted.map { it.deviceId }236 }237 }238239 240241242243244 override fun clearRevocation(deviceId: String) {245 mutationGate.withLock {246 val existing = listRevocations()247 val filtered = existing.filterNot { it.deviceId == deviceId }248 if (filtered.size != existing.size) persistRevocations(filtered)249 }250 }251252 fun clear() {253 mutationGate.withLock {254 val edit = prefs.edit()255 .remove(KEY_DEVICES)256 .remove(KEY_REVOCATIONS)257 258 259 260 for (key in prefs.all.keys.filter { it.startsWith(KEY_ISSUER_KEYS_PREFIX) }) {261 edit.remove(key)262 }263 edit.commit()264 }265 }266267 268 internal fun snapshot(): Map<String, Any?> = prefs.all269270 271272273274 fun updateLastSeen(id: String, ip: String? = null) {275 mutationGate.withLock {276 val current = get(id) ?: return@withLock277 if (ip == null) return@withLock278 upsert(current.copy(lastKnownIp = ip))279 }280 }281282 fun updateLastSync(id: String, at: Long = System.currentTimeMillis()) {283 mutationGate.withLock {284 val current = get(id) ?: return@withLock285 upsert(current.copy(lastSyncedAt = at))286 }287 }288289 290291292293294295 fun propagateRelaySetting(mode: SyncMode, storedRelayUrl: String) {296 mutationGate.withLock {297 val current = getAll()298 val next = withRelaySetting(current, mode, storedRelayUrl)299 if (next != current) persist(next)300 }301 }302303 304305306307308 fun observeAll(): Flow<List<PairedDevice>> = callbackFlow {309 trySend(getAll())310 val listener = android.content.SharedPreferences.OnSharedPreferenceChangeListener { _, key ->311 if (key == KEY_DEVICES || key == null) trySend(getAll())312 }313 prefs.registerOnSharedPreferenceChangeListener(listener)314 awaitClose { prefs.unregisterOnSharedPreferenceChangeListener(listener) }315 }316317 override fun issuerSigningKeys(issuerDeviceId: String): Set<String> =318 prefs.getStringSet("$KEY_ISSUER_KEYS_PREFIX$issuerDeviceId", emptySet())319 .orEmpty().map(String::lowercase).toSet()320321 322 fun hasIssuerSigningKeys(): Boolean = prefs.all.keys.any { it.startsWith(KEY_ISSUER_KEYS_PREFIX) }323324 override fun appendIssuerSigningKey(issuerDeviceId: String, signingKeyHex: String): Boolean {325 val key = signingKeyHex.lowercase()326 if (issuerDeviceId.isBlank() || key.length != 64) return false327 synchronized(mutationGate) {328 val existing = issuerSigningKeys(issuerDeviceId)329 if (key in existing) return true330 return prefs.edit()331 .putStringSet("$KEY_ISSUER_KEYS_PREFIX$issuerDeviceId", existing + key)332 .commit()333 }334 }335336 337338339340341 private fun persistRevocations(records: List<DeviceRevocation>) {342 val prior = readPrefsState()343 val next = prior.copy(344 revocations = json.encodeToString(revocationSerializer, records),345 )346 check(commitWithRollback(prior, next, ::writePrefsState)) {347 "paired_device_persist_failed"348 }349 }350351 private fun persist(devices: List<PairedDevice>) {352 prefs.edit()353 .putString(KEY_DEVICES, json.encodeToString(listSerializer, devices))354 .apply()355 }356357 private data class RegistryPrefsState(358 val devices: String?,359 val revocations: String?,360 )361362 private fun readPrefsState(): RegistryPrefsState = RegistryPrefsState(363 devices = prefs.getString(KEY_DEVICES, null),364 revocations = prefs.getString(KEY_REVOCATIONS, null),365 )366367 private fun writePrefsState(state: RegistryPrefsState): Boolean {368 val edit = prefs.edit()369 if (state.devices == null) edit.remove(KEY_DEVICES) else edit.putString(KEY_DEVICES, state.devices)370 if (state.revocations == null) edit.remove(KEY_REVOCATIONS) else edit.putString(KEY_REVOCATIONS, state.revocations)371 return edit.commit()372 }373374 private companion object {375 const val PREFS_FILE = "peach_paired_devices"376 const val KEY_DEVICES = "paired_devices"377 const val KEY_REVOCATIONS = "device_revocations"378 const val KEY_ISSUER_KEYS_PREFIX = "issuer_signing_keys:"379 const val MAX_REVOCATIONS = MAX_REVOCATION_RECORDS380 val json = Json { encodeDefaults = true; ignoreUnknownKeys = true }381 }382}383384385386387388389390class TrustDataCorruptedException(key: String, detail: String) :391 RuntimeException("trust_data_corrupted:$key:$detail")392393internal fun bindImmutableIdentity(existing: PairedDevice?, incoming: PairedDevice): PairedDevice {394 if (existing == null) return incoming395396 val longTermChanged = existing.longTermPublicKeyHex != null &&397 incoming.longTermPublicKeyHex != null &&398 !CryptoCompare.hex(existing.longTermPublicKeyHex, incoming.longTermPublicKeyHex)399 val signingChanged = existing.signingPublicKeyHex != null &&400 incoming.signingPublicKeyHex != null &&401 !CryptoCompare.hex(existing.signingPublicKeyHex, incoming.signingPublicKeyHex)402 require(!longTermChanged && !signingChanged) { "device_identity_immutable" }403404 return incoming.copy(405 longTermPublicKeyHex = incoming.longTermPublicKeyHex ?: existing.longTermPublicKeyHex,406 signingPublicKeyHex = incoming.signingPublicKeyHex ?: existing.signingPublicKeyHex,407 )408}409410411internal class RegistryMutationGate {412 private val lock = ReentrantLock()413414 fun <T> withLock(block: () -> T): T = lock.withLock(block)415}416417internal fun withLocalAlias(418 devices: List<PairedDevice>,419 deviceId: String,420 name: String,421): List<PairedDevice> {422 val alias = name.trim()423 require(alias.isNotEmpty()) { "device name must not be empty" }424 require(alias.length <= MAX_DEVICE_NAME_CHARS) { "device name must be 64 chars or fewer" }425 require(devices.any { it.deviceId == deviceId }) { "device_not_found" }426 return devices.map { if (it.deviceId == deviceId) it.copy(localAlias = alias) else it }427}428429internal data class DeviceRevocationMutation(430 val devices: List<PairedDevice>,431 val revocations: List<DeviceRevocation>,432 val added: DeviceRevocation?,433)434435436internal fun hasAdoptionIdentityConflict(437 incoming: PairedDevice,438 devices: List<PairedDevice>,439 revocations: List<DeviceRevocation>,440): Boolean {441 if (devices.any { it.deviceId == incoming.deviceId }) return true442 if (devices.any {443 it.longTermPublicKeyHex?.let { key -> incoming.longTermPublicKeyHex?.let { candidate -> CryptoCompare.hex(key, candidate) } } == true ||444 it.signingPublicKeyHex?.let { key -> incoming.signingPublicKeyHex?.let { candidate -> CryptoCompare.hex(key, candidate) } } == true445 }) return true446 return revocations.any { revoked ->447 revoked.deviceId == incoming.deviceId ||448 incoming.longTermPublicKeyHex?.let { CryptoCompare.hex(revoked.longTermPublicKeyHex, it) } == true449 }450}451452453454455456457458459internal fun planDeviceRevocation(460 devices: List<PairedDevice>,461 revocations: List<DeviceRevocation>,462 deviceId: String,463 revokedByDeviceId: String,464 nowMs: Long,465): DeviceRevocationMutation {466 val remaining = devices.filterNot { it.deviceId == deviceId }467 if (revocations.any { it.deviceId == deviceId }) {468 return DeviceRevocationMutation(remaining, revocations, null)469 }470 val device = devices.firstOrNull { it.deviceId == deviceId }471 val record = DeviceRevocation(472 deviceId = deviceId,473 longTermPublicKeyHex = device?.longTermPublicKeyHex ?: "0".repeat(64),474 revokedAt = nowMs,475 revokedByDeviceId = revokedByDeviceId,476 )477 return DeviceRevocationMutation(478 remaining,479 capRevocationRecords(revocations + record),480 record,481 )482}483484internal data class RevocationMergeResult(485 val records: List<DeviceRevocation>,486 val admitted: List<DeviceRevocation>,487)488489internal fun mergeRevocationRecords(490 existing: List<DeviceRevocation>,491 incoming: List<DeviceRevocation>,492): RevocationMergeResult {493 val known = existing.map { it.deviceId }.toSet()494 val fresh = incoming.filterNot { known.contains(it.deviceId) }495 return RevocationMergeResult(capRevocationRecords(existing + fresh), fresh)496}497498499500501502503internal fun capRevocationRecords(records: List<DeviceRevocation>): List<DeviceRevocation> {504 if (records.size <= MAX_REVOCATION_RECORDS) return records505 val liveCounts = records.groupingBy { it.revokedByDeviceId }.eachCount().toMutableMap()506 val dropped = BooleanArray(records.size)507 repeat(records.size - MAX_REVOCATION_RECORDS) {508 val largestIssuer = liveCounts.maxByOrNull { it.value }?.key ?: return@repeat509 val oldestIndex = records.indices.firstOrNull { index ->510 !dropped[index] && records[index].revokedByDeviceId == largestIssuer511 } ?: return@repeat512 dropped[oldestIndex] = true513 liveCounts[largestIssuer] = liveCounts.getValue(largestIssuer) - 1514 }515 return records.filterIndexed { index, _ -> !dropped[index] }516}517518519520521522523524internal fun withRelaySetting(525 devices: List<PairedDevice>,526 mode: SyncMode,527 storedRelayUrl: String,528): List<PairedDevice> = when (val decision = relayInForce(mode, storedRelayUrl)) {529 is RelayDecision.Dial -> devices.map { it.copy(relayUrl = decision.relayUrl) }530 is RelayDecision.Refuse -> devices531}