1package com.peachpasswords.sync23import android.content.Context4import android.content.SharedPreferences5import androidx.security.crypto.EncryptedSharedPreferences6import androidx.security.crypto.MasterKey7import dagger.hilt.android.qualifiers.ApplicationContext8import kotlinx.coroutines.channels.awaitClose9import kotlinx.coroutines.flow.Flow10import kotlinx.coroutines.flow.callbackFlow11import kotlinx.serialization.builtins.ListSerializer12import kotlinx.serialization.json.Json13import java.util.concurrent.locks.ReentrantLock14import javax.inject.Inject15import javax.inject.Singleton16import kotlin.concurrent.withLock1718private const val MAX_REVOCATION_RECORDS = 500192021222324252627282930313233343536373839404142@Singleton43class PairedDeviceStore internal constructor(44 private val prefs: SharedPreferences,45) : PairedDeviceRegistry {46 @Inject constructor(@ApplicationContext context: Context) : this(47 EncryptedSharedPreferences.create(48 context,49 PREFS_FILE,50 MasterKey.Builder(context).setKeyScheme(MasterKey.KeyScheme.AES256_GCM).build(),51 EncryptedSharedPreferences.PrefKeyEncryptionScheme.AES256_SIV,52 EncryptedSharedPreferences.PrefValueEncryptionScheme.AES256_GCM,53 ),54 )5556 private val listSerializer = ListSerializer(PairedDevice.serializer())57 private val revocationSerializer = ListSerializer(DeviceRevocation.serializer())58 private val mutationGate = RegistryMutationGate()5960 61 @Volatile private var knownLocalDeviceId: String? = null6263 override fun getAll(): List<PairedDevice> = mutationGate.withLock {64 decodeDevices(readStringPreference(KEY_DEVICES))65 }6667 private fun decodeDevices(raw: String?): List<PairedDevice> {68 if (raw == null) return emptyList()69 return try {70 json.decodeFromString(listSerializer, raw)71 } catch (e: Exception) {72 throw TrustDataCorruptedException(KEY_DEVICES, e.message ?: "decode_failed")73 }74 }7576 override fun manifestSnapshot(requestedIssuerIds: Set<String>): DeviceManifestRegistrySnapshot = mutationGate.withLock {77 manifestSnapshot(readPrefsState())78 }7980 private fun manifestSnapshot(state: RegistryPrefsState): DeviceManifestRegistrySnapshot =81 DeviceManifestRegistrySnapshot(82 devices = decodeDevices(state.devices),83 revocations = decodeRevocations(state.revocations),84 issuerSigningKeys = state.issuerKeys.mapValues { (_, keys) -> keys.map(String::lowercase).toSet() },85 )8687 private fun readStringPreference(key: String): String? = try {88 prefs.getString(key, null)89 } catch (e: ClassCastException) {90 throw TrustDataCorruptedException(key, "invalid_string")91 }9293 override fun get(id: String): PairedDevice? = getAll().firstOrNull { it.deviceId == id }9495 override fun getByPubkey(pubkeyHex: String): PairedDevice? =96 getAll().firstOrNull {97 it.longTermPublicKeyHex?.let { key -> CryptoCompare.hex(key, pubkeyHex) } == true98 }99100 fun hasIdentityCollision(device: PairedDevice): Boolean = mutationGate.withLock {101 hasAdoptionIdentityConflict(device, getAll(), listRevocations())102 }103104 105 fun upsertAndClearRevocation(device: PairedDevice) {106 mutationGate.withLock {107 val currentDevices = getAll()108 val existing = currentDevices.firstOrNull { it.deviceId == device.deviceId }109 val bound = bindImmutableIdentity(existing, device)110 val nextDevice = bound.copy(111 deviceName = bound.deviceName?.let(::capDeviceName),112 localAlias = existing?.localAlias,113 )114 val nextDevices = currentDevices.filterNot { it.deviceId == device.deviceId } + nextDevice115 val currentRevocations = listRevocations()116 val nextRevocations = currentRevocations.filterNot { it.deviceId == device.deviceId }117 val priorPrefs = readPrefsState()118 val nextPrefs = priorPrefs.copy(119 devices = json.encodeToString(listSerializer, nextDevices),120 revocations = json.encodeToString(revocationSerializer, nextRevocations),121 )122 check(commitPrefsState(priorPrefs, nextPrefs)) {123 "paired_device_persist_failed"124 }125 }126 }127128 129 override fun upsert(device: PairedDevice) {130 mutationGate.withLock {131 val currentDevices = getAll()132 val existing = currentDevices.firstOrNull { it.deviceId == device.deviceId }133 val bound = bindImmutableIdentity(existing, device)134 135 136 val nextDevice = bound.copy(137 deviceName = bound.deviceName?.let(::capDeviceName),138 localAlias = existing?.localAlias,139 )140 val next = currentDevices.filterNot { it.deviceId == device.deviceId } + nextDevice141 persist(next)142 }143 }144145 146147148149150151 override fun applyManifestBatch(batch: DeviceManifestRegistryBatch): Boolean {152 return mutationGate.withLock {153 val priorPrefs = readPrefsState()154 val currentSnapshot = manifestSnapshot(priorPrefs)155 if (!sameTrustSnapshot(currentSnapshot, batch.expectedSnapshot)) return@withLock false156 val currentDevices = currentSnapshot.devices157 val currentById = currentDevices.associateBy { it.deviceId }158 val currentRevocations = currentSnapshot.revocations159 val admissionRevocations = currentRevocations + batch.incomingRevocations160 val revokedIds = admissionRevocations.map { it.deviceId }.toSet()161 val revokedKeys = admissionRevocations.map { it.longTermPublicKeyHex.lowercase() }162 .filterNot { it == NO_KEY_SENTINEL }.toSet()163 fun isTerminal(deviceId: String, longTermKey: String?): Boolean =164 deviceId in revokedIds || longTermKey?.lowercase() in revokedKeys165166 val expectedIssuer = batch.authenticatedIssuer167 val issuer = currentById[expectedIssuer.deviceId] ?: return@withLock false168 169 val issuerAlreadyRevoked = currentRevocations.any {170 it.deviceId == issuer.deviceId ||171 (it.longTermPublicKeyHex.lowercase() != NO_KEY_SENTINEL &&172 it.longTermPublicKeyHex.equals(issuer.longTermPublicKeyHex, ignoreCase = true))173 }174 if (issuer.longTermPublicKeyHex?.let { CryptoCompare.hex(it, expectedIssuer.longTermPublicKeyHex) } != true ||175 issuer.signingPublicKeyHex?.let { CryptoCompare.hex(it, expectedIssuer.signingPublicKeyHex) } != true ||176 (issuer.trustSource != "direct" && issuer.trustSource != "vouched") ||177 issuer.vouchDepth >= MAX_VOUCH_DEPTH || issuerAlreadyRevoked178 ) return@withLock false179 val allowedIssuerKeys = priorPrefs.issuerKeys[issuer.deviceId].orEmpty().map(String::lowercase).toSet() +180 expectedIssuer.signingPublicKeyHex.lowercase()181 if (batch.issuerSigningKeys.any { (id, keys) ->182 id != issuer.deviceId || keys.any { !isSigningKey(it) || it.lowercase() !in allowedIssuerKeys }183 }) return@withLock false184 if (batch.upserts.any {185 isTerminal(it.deviceId, it.longTermPublicKeyHex ?: currentById[it.deviceId]?.longTermPublicKeyHex)186 }) return@withLock false187188 val nextRevocations = mergeRevocationRecords(currentRevocations, batch.incomingRevocations).records189 val removed = batch.removals190 val nextDevices = currentDevices191 .filterNot { removed.contains(it.deviceId) || isTerminal(it.deviceId, it.longTermPublicKeyHex) }192 .toMutableList()193 batch.upserts.forEach { incoming ->194 val existing = currentById[incoming.deviceId]195 ?: nextDevices.firstOrNull { it.deviceId == incoming.deviceId }196 require(!nextDevices.any { candidate ->197 candidate.deviceId != incoming.deviceId &&198 ((candidate.longTermPublicKeyHex != null && incoming.longTermPublicKeyHex != null && CryptoCompare.hex(candidate.longTermPublicKeyHex, incoming.longTermPublicKeyHex)) ||199 (candidate.signingPublicKeyHex != null && incoming.signingPublicKeyHex != null && CryptoCompare.hex(candidate.signingPublicKeyHex, incoming.signingPublicKeyHex)))200 }) { "device_identity_collision" }201 val bound = bindImmutableIdentity(existing, incoming)202 val alias = existing?.localAlias203 val device = bound.copy(204 deviceName = bound.deviceName?.let(::capDeviceName),205 localAlias = alias,206 lastSyncedAt = if (existing != null) existing.lastSyncedAt else bound.lastSyncedAt,207 lastKnownIp = if (existing != null) existing.lastKnownIp else bound.lastKnownIp,208 )209 nextDevices.removeAll { it.deviceId == device.deviceId }210 nextDevices += device211 }212213 val nextPrefs = priorPrefs.copy(214 devices = json.encodeToString(listSerializer, nextDevices),215 revocations = json.encodeToString(revocationSerializer, nextRevocations),216 issuerKeys = withIssuerSigningKeys(priorPrefs.issuerKeys, batch.issuerSigningKeys),217 )218 219 220 221 commitPrefsState(priorPrefs, nextPrefs)222 }223 }224225 fun rename(deviceId: String, name: String) {226 mutationGate.withLock {227 persist(withLocalAlias(getAll(), deviceId, name))228 }229 }230231 override fun remove(deviceId: String) {232 mutationGate.withLock {233 persist(getAll().filterNot { it.deviceId == deviceId })234 }235 }236237238239 240241 override fun listRevocations(): List<DeviceRevocation> = mutationGate.withLock {242 decodeRevocations(readStringPreference(KEY_REVOCATIONS))243 }244245 private fun decodeRevocations(raw: String?): List<DeviceRevocation> {246 if (raw == null) return emptyList()247 return try {248 json.decodeFromString(revocationSerializer, raw)249 } catch (e: Exception) {250 throw TrustDataCorruptedException(KEY_REVOCATIONS, e.message ?: "decode_failed")251 }252 }253254 255256257258259260 fun revoke(261 deviceId: String,262 revokedByDeviceId: String,263 nowMs: Long = System.currentTimeMillis(),264 ): DeviceRevocation? = mutationGate.withLock {265 knownLocalDeviceId = revokedByDeviceId266 val currentDevices = getAll()267 val currentRevocations = listRevocations()268 val mutation = planDeviceRevocation(269 devices = currentDevices,270 revocations = currentRevocations,271 deviceId = deviceId,272 revokedByDeviceId = revokedByDeviceId,273 nowMs = nowMs,274 protectedIssuerIds = protectedRevocationIssuers(),275 )276 277 278 279 280 val priorPrefs = readPrefsState()281 val nextPrefs = priorPrefs.copy(282 devices = json.encodeToString(listSerializer, mutation.devices),283 revocations = json.encodeToString(revocationSerializer, mutation.revocations),284 )285 check(commitPrefsState(priorPrefs, nextPrefs)) {286 "paired_device_persist_failed"287 }288 mutation.added289 }290291 292293294295296 override fun mergeRevocations(incoming: List<DeviceRevocation>): List<String> {297 return mutationGate.withLock {298 val existing = listRevocations()299 val merged = mergeRevocationRecords(existing, incoming, protectedRevocationIssuers())300 if (merged.records != existing) persistRevocations(merged.records)301 merged.admitted.map { it.deviceId }302 }303 }304305 306307308309310311312313314315 private fun protectedRevocationIssuers(): Set<String> = buildSet {316 knownLocalDeviceId?.let(::add)317 getAll().filter { it.trustSource == "direct" }.forEach { add(it.deviceId) }318 }319320 321322323324325 override fun clearRevocation(deviceId: String) {326 mutationGate.withLock {327 val existing = listRevocations()328 val filtered = existing.filterNot { it.deviceId == deviceId }329 if (filtered.size != existing.size) persistRevocations(filtered)330 }331 }332333 fun clear() {334 mutationGate.withLock {335 val prior = copyRawTrustPreferences(prefs.all)336 val removed = prior.keys.filter { it == KEY_DEVICES || it == KEY_REVOCATIONS || it.startsWith(KEY_ISSUER_KEYS_PREFIX) }.toSet()337 val next = prior.filterKeys { it !in removed }338 check(commitWithRollback(prior, next) { state ->339 val edit = prefs.edit()340 removed.forEach(edit::remove)341 putRawTrustPreferences(edit, state.filterKeys { it in removed })342 edit.commit()343 }) { "paired_device_persist_failed" }344 }345 }346347 348 internal fun snapshot(): Map<String, Any?> = mutationGate.withLock {349 copyRawTrustPreferences(prefs.all)350 }351352 353354355356 fun updateLastSeen(id: String, ip: String? = null) {357 mutationGate.withLock {358 val current = get(id) ?: return@withLock359 if (ip == null) return@withLock360 upsert(current.copy(lastKnownIp = ip))361 }362 }363364 fun updateLastSync(id: String, at: Long = System.currentTimeMillis()) {365 mutationGate.withLock {366 val current = get(id) ?: return@withLock367 upsert(current.copy(lastSyncedAt = at))368 }369 }370371 372373374375376377 fun propagateRelaySetting(mode: SyncMode, storedRelayUrl: String) {378 mutationGate.withLock {379 val current = getAll()380 val next = withRelaySetting(current, mode, storedRelayUrl)381 if (next != current) persist(next)382 }383 }384385 386387388389390 fun observeAll(): Flow<List<PairedDevice>> = callbackFlow {391 trySend(getAll())392 val listener = android.content.SharedPreferences.OnSharedPreferenceChangeListener { _, key ->393 if (key == KEY_DEVICES || key == null) trySend(getAll())394 }395 prefs.registerOnSharedPreferenceChangeListener(listener)396 awaitClose { prefs.unregisterOnSharedPreferenceChangeListener(listener) }397 }398399 override fun issuerSigningKeys(issuerDeviceId: String): Set<String> = mutationGate.withLock {400 readPrefsState().issuerKeys[issuerDeviceId].orEmpty().map(String::lowercase).toSet()401 }402403 404 fun hasIssuerSigningKeys(): Boolean = mutationGate.withLock {405 readPrefsState().issuerKeys.isNotEmpty()406 }407408 override fun appendIssuerSigningKey(issuerDeviceId: String, signingKeyHex: String): Boolean {409 if (issuerDeviceId.isBlank() || !isSigningKey(signingKeyHex)) return false410 return mutationGate.withLock {411 val prior = readPrefsState()412 val key = signingKeyHex.lowercase()413 if (prior.issuerKeys[issuerDeviceId].orEmpty().any { it.equals(key, ignoreCase = true) }) {414 return@withLock true415 }416 val next = prior.copy(issuerKeys = withIssuerSigningKeys(prior.issuerKeys, mapOf(issuerDeviceId to setOf(key))))417 commitPrefsState(prior, next)418 }419 }420421 422423424425426 private fun persistRevocations(records: List<DeviceRevocation>) {427 val prior = readPrefsState()428 val next = prior.copy(429 revocations = json.encodeToString(revocationSerializer, records),430 )431 check(commitPrefsState(prior, next)) {432 "paired_device_persist_failed"433 }434 }435436 private fun persist(devices: List<PairedDevice>) {437 prefs.edit().putString(KEY_DEVICES, json.encodeToString(listSerializer, devices)).apply()438 }439440 private fun sameTrustSnapshot(441 current: DeviceManifestRegistrySnapshot,442 expected: DeviceManifestRegistrySnapshot,443 ): Boolean {444 fun deviceCounts(devices: List<PairedDevice>) = devices.map {445 it.copy(lastSyncedAt = null, lastKnownIp = null, localAlias = null)446 }.groupingBy { it }.eachCount()447 return deviceCounts(current.devices) == deviceCounts(expected.devices) &&448 current.revocations == expected.revocations && current.issuerSigningKeys == expected.issuerSigningKeys449 }450451 private data class RegistryPrefsState(452 val devices: String?,453 val revocations: String?,454 val issuerKeys: Map<String, Set<String>>,455 )456457 private fun readPrefsState(): RegistryPrefsState {458 val all = prefs.all459 val issuerKeys = all.filterKeys { it.startsWith(KEY_ISSUER_KEYS_PREFIX) }.map { (key, value) ->460 val issuer = key.removePrefix(KEY_ISSUER_KEYS_PREFIX)461 if (issuer.isBlank() || value !is Set<*> || value.any { it !is String || !isSigningKey(it) }) {462 throw TrustDataCorruptedException(key, "invalid_issuer_signing_keys")463 }464 issuer to value.map { it as String }.toSet()465 }.toMap()466 return RegistryPrefsState(467 devices = snapshotString(all, KEY_DEVICES),468 revocations = snapshotString(all, KEY_REVOCATIONS),469 issuerKeys = issuerKeys,470 )471 }472473 private fun snapshotString(all: Map<String, *>, key: String): String? {474 val value = all[key]475 if (value == null && !all.containsKey(key)) return null476 if (value !is String) throw TrustDataCorruptedException(key, "invalid_string")477 return value478 }479480 private fun withIssuerSigningKeys(481 existing: Map<String, Set<String>>,482 incoming: Map<String, Set<String>>,483 ): Map<String, Set<String>> {484 val next = existing.toMutableMap()485 incoming.forEach { (issuer, keys) ->486 require(issuer.isNotBlank() && keys.all(::isSigningKey)) { "invalid_issuer_signing_keys" }487 val prior = next[issuer].orEmpty()488 val known = prior.map(String::lowercase).toSet()489 next[issuer] = prior + keys.map(String::lowercase).filterNot { it in known }490 }491 return next.toMap()492 }493494 private fun isSigningKey(key: String): Boolean =495 key.length == 64 && key.all { it in '0'..'9' || it in 'a'..'f' || it in 'A'..'F' }496497 private fun commitPrefsState(prior: RegistryPrefsState, next: RegistryPrefsState): Boolean {498 val changedIssuers = (prior.issuerKeys.keys + next.issuerKeys.keys).filter {499 prior.issuerKeys[it] != next.issuerKeys[it]500 }501 return commitWithRollback(prior, next) { state ->502 val edit = prefs.edit()503 if (prior.devices != next.devices) {504 if (state.devices == null) edit.remove(KEY_DEVICES) else edit.putString(KEY_DEVICES, state.devices)505 }506 if (prior.revocations != next.revocations) {507 if (state.revocations == null) edit.remove(KEY_REVOCATIONS) else edit.putString(KEY_REVOCATIONS, state.revocations)508 }509 changedIssuers.forEach { issuer ->510 val key = "$KEY_ISSUER_KEYS_PREFIX$issuer"511 val keys = state.issuerKeys[issuer]512 if (keys == null) edit.remove(key) else edit.putStringSet(key, keys.toSet())513 }514 edit.commit()515 }516 }517518 private companion object {519 const val PREFS_FILE = "peach_paired_devices"520 const val KEY_DEVICES = "paired_devices"521 const val KEY_REVOCATIONS = "device_revocations"522 const val KEY_ISSUER_KEYS_PREFIX = "issuer_signing_keys:"523 const val MAX_REVOCATIONS = MAX_REVOCATION_RECORDS524 val json = Json { encodeDefaults = true; ignoreUnknownKeys = true }525 }526}527528529530531532533534class TrustDataCorruptedException(key: String, detail: String) :535 RuntimeException("trust_data_corrupted:$key:$detail")536537internal fun bindImmutableIdentity(existing: PairedDevice?, incoming: PairedDevice): PairedDevice {538 if (existing == null) return incoming539540 val longTermChanged = existing.longTermPublicKeyHex != null &&541 incoming.longTermPublicKeyHex != null &&542 !CryptoCompare.hex(existing.longTermPublicKeyHex, incoming.longTermPublicKeyHex)543 val signingChanged = existing.signingPublicKeyHex != null &&544 incoming.signingPublicKeyHex != null &&545 !CryptoCompare.hex(existing.signingPublicKeyHex, incoming.signingPublicKeyHex)546 require(!longTermChanged && !signingChanged) { "device_identity_immutable" }547548 return incoming.copy(549 longTermPublicKeyHex = incoming.longTermPublicKeyHex ?: existing.longTermPublicKeyHex,550 signingPublicKeyHex = incoming.signingPublicKeyHex ?: existing.signingPublicKeyHex,551 )552}553554555internal class RegistryMutationGate {556 private val lock = ReentrantLock()557558 fun <T> withLock(block: () -> T): T = lock.withLock(block)559}560561internal fun withLocalAlias(562 devices: List<PairedDevice>,563 deviceId: String,564 name: String,565): List<PairedDevice> {566 val alias = name.trim()567 require(alias.isNotEmpty()) { "device name must not be empty" }568 require(alias.length <= MAX_DEVICE_NAME_CHARS) { "device name must be 64 chars or fewer" }569 require(devices.any { it.deviceId == deviceId }) { "device_not_found" }570 return devices.map { if (it.deviceId == deviceId) it.copy(localAlias = alias) else it }571}572573internal data class DeviceRevocationMutation(574 val devices: List<PairedDevice>,575 val revocations: List<DeviceRevocation>,576 val added: DeviceRevocation?,577)578579580internal fun hasAdoptionIdentityConflict(581 incoming: PairedDevice,582 devices: List<PairedDevice>,583 revocations: List<DeviceRevocation>,584): Boolean {585 if (devices.any { it.deviceId == incoming.deviceId }) return true586 if (devices.any {587 it.longTermPublicKeyHex?.let { key -> incoming.longTermPublicKeyHex?.let { candidate -> CryptoCompare.hex(key, candidate) } } == true ||588 it.signingPublicKeyHex?.let { key -> incoming.signingPublicKeyHex?.let { candidate -> CryptoCompare.hex(key, candidate) } } == true589 }) return true590 return revocations.any { revoked ->591 revoked.deviceId == incoming.deviceId ||592 incoming.longTermPublicKeyHex?.let { CryptoCompare.hex(revoked.longTermPublicKeyHex, it) } == true593 }594}595596597598599600601602603internal fun planDeviceRevocation(604 devices: List<PairedDevice>,605 revocations: List<DeviceRevocation>,606 deviceId: String,607 revokedByDeviceId: String,608 nowMs: Long,609 protectedIssuerIds: Set<String> = emptySet(),610): DeviceRevocationMutation {611 val remaining = devices.filterNot { it.deviceId == deviceId }612 if (revocations.any { it.deviceId == deviceId }) {613 return DeviceRevocationMutation(remaining, revocations, null)614 }615 val device = devices.firstOrNull { it.deviceId == deviceId }616 val record = DeviceRevocation(617 deviceId = deviceId,618 longTermPublicKeyHex = device?.longTermPublicKeyHex ?: "0".repeat(64),619 revokedAt = nowMs,620 revokedByDeviceId = revokedByDeviceId,621 )622 return DeviceRevocationMutation(623 remaining,624 capRevocationRecords(revocations + record, protectedIssuerIds).records,625 record,626 )627}628internal data class RevocationMergeResult(629 val records: List<DeviceRevocation>,630 val admitted: List<DeviceRevocation>,631 val outcome: RevocationMergeOutcome = RevocationMergeOutcome.MERGED,632)633634internal enum class RevocationMergeOutcome {635 MERGED,636 OVERFLOW_PROTECTED_LEDGER,637}638639internal data class RevocationCapResult(640 val records: List<DeviceRevocation>,641 val outcome: RevocationMergeOutcome,642)643644internal fun mergeRevocationRecords(645 existing: List<DeviceRevocation>,646 incoming: List<DeviceRevocation>,647 protectedIssuerIds: Set<String> = emptySet(),648): RevocationMergeResult {649 val known = existing.map { it.deviceId }.toSet()650 val fresh = incoming.filterNot { known.contains(it.deviceId) }651 val capped = capRevocationRecords(existing + fresh, protectedIssuerIds)652 if (capped.outcome == RevocationMergeOutcome.OVERFLOW_PROTECTED_LEDGER) {653 return RevocationMergeResult(existing, emptyList(), capped.outcome)654 }655 val admitted = fresh.filter { candidate -> capped.records.any { it.deviceId == candidate.deviceId } }656 return RevocationMergeResult(capped.records, admitted, capped.outcome)657}658659660661662663664665internal fun capRevocationRecords(666 records: List<DeviceRevocation>,667 protectedIssuerIds: Set<String> = emptySet(),668): RevocationCapResult {669 if (records.size <= MAX_REVOCATION_RECORDS) {670 return RevocationCapResult(records, RevocationMergeOutcome.MERGED)671 }672 val candidates = records.indices.filter { records[it].revokedByDeviceId !in protectedIssuerIds }673 if (candidates.size < records.size - MAX_REVOCATION_RECORDS) {674 return RevocationCapResult(records, RevocationMergeOutcome.OVERFLOW_PROTECTED_LEDGER)675 }676 val dropped = candidates.take(records.size - MAX_REVOCATION_RECORDS).toSet()677 return RevocationCapResult(678 records.filterIndexed { index, _ -> index !in dropped },679 RevocationMergeOutcome.MERGED,680 )681}682683684685686687688689internal fun withRelaySetting(690 devices: List<PairedDevice>,691 mode: SyncMode,692 storedRelayUrl: String,693): List<PairedDevice> = when (val decision = relayInForce(mode, storedRelayUrl)) {694 is RelayDecision.Dial -> devices.map { it.copy(relayUrl = decision.relayUrl) }695 is RelayDecision.Refuse -> devices696}