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 206 207 208 209 val nextPrefs = RegistryPrefsState(210 devices = json.encodeToString(listSerializer, mutation.devices),211 revocations = json.encodeToString(revocationSerializer, mutation.revocations),212 )213 check(commitWithRollback(readPrefsState(), nextPrefs, ::writePrefsState)) {214 "paired_device_persist_failed"215 }216 mutation.added217 }218219 220221222223 override fun mergeRevocations(incoming: List<DeviceRevocation>): List<String> {224 return mutationGate.withLock {225 val existing = listRevocations()226 val merged = mergeRevocationRecords(existing, incoming)227 if (merged.records != existing) persistRevocations(merged.records)228 merged.admitted.map { it.deviceId }229 }230 }231232 233234235236237 override fun clearRevocation(deviceId: String) {238 mutationGate.withLock {239 val existing = listRevocations()240 val filtered = existing.filterNot { it.deviceId == deviceId }241 if (filtered.size != existing.size) persistRevocations(filtered)242 }243 }244245 fun clear() {246 mutationGate.withLock {247 prefs.edit()248 .remove(KEY_DEVICES)249 .remove(KEY_REVOCATIONS)250 .apply()251 }252 }253254 255256257258 fun updateLastSeen(id: String, ip: String? = null) {259 mutationGate.withLock {260 val current = get(id) ?: return@withLock261 if (ip == null) return@withLock262 upsert(current.copy(lastKnownIp = ip))263 }264 }265266 fun updateLastSync(id: String, at: Long = System.currentTimeMillis()) {267 mutationGate.withLock {268 val current = get(id) ?: return@withLock269 upsert(current.copy(lastSyncedAt = at))270 }271 }272273 274275276277278279 fun propagateRelaySetting(mode: SyncMode, storedRelayUrl: String) {280 mutationGate.withLock {281 val current = getAll()282 val next = withRelaySetting(current, mode, storedRelayUrl)283 if (next != current) persist(next)284 }285 }286287 288289290291292 fun observeAll(): Flow<List<PairedDevice>> = callbackFlow {293 trySend(getAll())294 val listener = android.content.SharedPreferences.OnSharedPreferenceChangeListener { _, key ->295 if (key == KEY_DEVICES || key == null) trySend(getAll())296 }297 prefs.registerOnSharedPreferenceChangeListener(listener)298 awaitClose { prefs.unregisterOnSharedPreferenceChangeListener(listener) }299 }300301 override fun issuerSigningKeys(issuerDeviceId: String): Set<String> =302 prefs.getStringSet("$KEY_ISSUER_KEYS_PREFIX$issuerDeviceId", emptySet())303 .orEmpty().map(String::lowercase).toSet()304305 override fun appendIssuerSigningKey(issuerDeviceId: String, signingKeyHex: String): Boolean {306 val key = signingKeyHex.lowercase()307 if (issuerDeviceId.isBlank() || key.length != 64) return false308 synchronized(mutationGate) {309 val existing = issuerSigningKeys(issuerDeviceId)310 if (key in existing) return true311 return prefs.edit()312 .putStringSet("$KEY_ISSUER_KEYS_PREFIX$issuerDeviceId", existing + key)313 .commit()314 }315 }316317 318319320321322 private fun persistRevocations(records: List<DeviceRevocation>) {323 val prior = readPrefsState()324 val next = prior.copy(325 revocations = json.encodeToString(revocationSerializer, records),326 )327 check(commitWithRollback(prior, next, ::writePrefsState)) {328 "paired_device_persist_failed"329 }330 }331332 private fun persist(devices: List<PairedDevice>) {333 prefs.edit()334 .putString(KEY_DEVICES, json.encodeToString(listSerializer, devices))335 .apply()336 }337338 private data class RegistryPrefsState(339 val devices: String?,340 val revocations: String?,341 )342343 private fun readPrefsState(): RegistryPrefsState = RegistryPrefsState(344 devices = prefs.getString(KEY_DEVICES, null),345 revocations = prefs.getString(KEY_REVOCATIONS, null),346 )347348 private fun writePrefsState(state: RegistryPrefsState): Boolean {349 val edit = prefs.edit()350 if (state.devices == null) edit.remove(KEY_DEVICES) else edit.putString(KEY_DEVICES, state.devices)351 if (state.revocations == null) edit.remove(KEY_REVOCATIONS) else edit.putString(KEY_REVOCATIONS, state.revocations)352 return edit.commit()353 }354355 private companion object {356 const val PREFS_FILE = "peach_paired_devices"357 const val KEY_DEVICES = "paired_devices"358 const val KEY_REVOCATIONS = "device_revocations"359 const val KEY_ISSUER_KEYS_PREFIX = "issuer_signing_keys:"360 const val MAX_REVOCATIONS = MAX_REVOCATION_RECORDS361 val json = Json { encodeDefaults = true; ignoreUnknownKeys = true }362 }363}364365internal fun bindImmutableIdentity(existing: PairedDevice?, incoming: PairedDevice): PairedDevice {366 if (existing == null) return incoming367368 val longTermChanged = existing.longTermPublicKeyHex != null &&369 incoming.longTermPublicKeyHex != null &&370 !CryptoCompare.hex(existing.longTermPublicKeyHex, incoming.longTermPublicKeyHex)371 val signingChanged = existing.signingPublicKeyHex != null &&372 incoming.signingPublicKeyHex != null &&373 !CryptoCompare.hex(existing.signingPublicKeyHex, incoming.signingPublicKeyHex)374 require(!longTermChanged && !signingChanged) { "device_identity_immutable" }375376 return incoming.copy(377 longTermPublicKeyHex = incoming.longTermPublicKeyHex ?: existing.longTermPublicKeyHex,378 signingPublicKeyHex = incoming.signingPublicKeyHex ?: existing.signingPublicKeyHex,379 )380}381382383internal class RegistryMutationGate {384 private val lock = ReentrantLock()385386 fun <T> withLock(block: () -> T): T = lock.withLock(block)387}388389internal fun withLocalAlias(390 devices: List<PairedDevice>,391 deviceId: String,392 name: String,393): List<PairedDevice> {394 val alias = name.trim()395 require(alias.isNotEmpty()) { "device name must not be empty" }396 require(alias.length <= MAX_DEVICE_NAME_CHARS) { "device name must be 64 chars or fewer" }397 require(devices.any { it.deviceId == deviceId }) { "device_not_found" }398 return devices.map { if (it.deviceId == deviceId) it.copy(localAlias = alias) else it }399}400401internal data class DeviceRevocationMutation(402 val devices: List<PairedDevice>,403 val revocations: List<DeviceRevocation>,404 val added: DeviceRevocation?,405)406407408internal fun hasAdoptionIdentityConflict(409 incoming: PairedDevice,410 devices: List<PairedDevice>,411 revocations: List<DeviceRevocation>,412): Boolean {413 if (devices.any { it.deviceId == incoming.deviceId }) return true414 if (devices.any {415 it.longTermPublicKeyHex?.let { key -> incoming.longTermPublicKeyHex?.let { candidate -> CryptoCompare.hex(key, candidate) } } == true ||416 it.signingPublicKeyHex?.let { key -> incoming.signingPublicKeyHex?.let { candidate -> CryptoCompare.hex(key, candidate) } } == true417 }) return true418 return revocations.any { revoked ->419 revoked.deviceId == incoming.deviceId ||420 incoming.longTermPublicKeyHex?.let { CryptoCompare.hex(revoked.longTermPublicKeyHex, it) } == true421 }422}423424425426427428429430431internal fun planDeviceRevocation(432 devices: List<PairedDevice>,433 revocations: List<DeviceRevocation>,434 deviceId: String,435 revokedByDeviceId: String,436 nowMs: Long,437): DeviceRevocationMutation {438 val remaining = devices.filterNot { it.deviceId == deviceId }439 if (revocations.any { it.deviceId == deviceId }) {440 return DeviceRevocationMutation(remaining, revocations, null)441 }442 val device = devices.firstOrNull { it.deviceId == deviceId }443 val record = DeviceRevocation(444 deviceId = deviceId,445 longTermPublicKeyHex = device?.longTermPublicKeyHex ?: "0".repeat(64),446 revokedAt = nowMs,447 revokedByDeviceId = revokedByDeviceId,448 )449 return DeviceRevocationMutation(450 remaining,451 capRevocationRecords(revocations + record),452 record,453 )454}455456internal data class RevocationMergeResult(457 val records: List<DeviceRevocation>,458 val admitted: List<DeviceRevocation>,459)460461internal fun mergeRevocationRecords(462 existing: List<DeviceRevocation>,463 incoming: List<DeviceRevocation>,464): RevocationMergeResult {465 val known = existing.map { it.deviceId }.toSet()466 val fresh = incoming.filterNot { known.contains(it.deviceId) }467 return RevocationMergeResult(capRevocationRecords(existing + fresh), fresh)468}469470471472473474475internal fun capRevocationRecords(records: List<DeviceRevocation>): List<DeviceRevocation> {476 if (records.size <= MAX_REVOCATION_RECORDS) return records477 val liveCounts = records.groupingBy { it.revokedByDeviceId }.eachCount().toMutableMap()478 val dropped = BooleanArray(records.size)479 repeat(records.size - MAX_REVOCATION_RECORDS) {480 val largestIssuer = liveCounts.maxByOrNull { it.value }?.key ?: return@repeat481 val oldestIndex = records.indices.firstOrNull { index ->482 !dropped[index] && records[index].revokedByDeviceId == largestIssuer483 } ?: return@repeat484 dropped[oldestIndex] = true485 liveCounts[largestIssuer] = liveCounts.getValue(largestIssuer) - 1486 }487 return records.filterIndexed { index, _ -> !dropped[index] }488}489490491492493494495496internal fun withRelaySetting(497 devices: List<PairedDevice>,498 mode: SyncMode,499 storedRelayUrl: String,500): List<PairedDevice> = when (val decision = relayInForce(mode, storedRelayUrl)) {501 is RelayDecision.Dial -> devices.map { it.copy(relayUrl = decision.relayUrl) }502 is RelayDecision.Refuse -> devices503}