b07ad0091d9e
fix: Settle cross-client Sync and revocation parity (v2.17.14)
- time
- 2026-09-09 13:35 UTC · 2 months ago
- machine
- koh2
- agent
- gpt-5
- session
- settle cross-client sync
- parent
- 4e32b3437c15
↓ peach-android-b07ad009.tar.gzatlas at this save
files changed10 files
VERSION+1 −1app/src/main/java/com/peachpasswords/sync/DeviceIdentity.kt+10 −0app/src/main/java/com/peachpasswords/sync/PairedDeviceStore.kt+22 −9app/src/main/java/com/peachpasswords/sync/SyncCoordinator.kt+5 −5app/src/main/java/com/peachpasswords/sync/VaultAdopt.kt+111 −49app/src/main/java/com/peachpasswords/ui/pairing/AdoptVaultViewModel.kt+15 −0app/src/main/java/com/peachpasswords/ui/pairing/CodePairViewModel.kt+12 −0app/src/test/java/com/peachpasswords/sync/PairedDeviceRevocationTest.kt+27 −3app/src/test/java/com/peachpasswords/sync/SyncCoordinatorTest.kt+8 −0app/src/test/java/com/peachpasswords/sync/VaultAdoptTest.kt+89 −0app/src/main/java/com/peachpasswords/sync/DeviceIdentity.kt+10 −0
@@ -36,6 +36,16 @@3636 return fresh3737 }3838 39+/** Replace the local device id after an authenticated peer detects a collision. */40+fun rotateDeviceId(context: Context): String {41+ val fresh = UUID.randomUUID().toString()42+ context.getSharedPreferences(PREFS_FILE, Context.MODE_PRIVATE)43+ .edit()44+ .putString(DEVICE_ID_KEY, fresh)45+ .apply()46+ return fresh47+}48+3949 fun getDeviceName(context: Context): String {4050 val prefs = context.getSharedPreferences(PREFS_FILE, Context.MODE_PRIVATE)4151 return prefs.getString(DEVICE_NAME_KEY, null).orEmpty().ifBlank { defaultDeviceName() }app/src/main/java/com/peachpasswords/sync/PairedDeviceStore.kt+22 −9
@@ -360,15 +360,9 @@360360 revokedAt = nowMs,361361 revokedByDeviceId = revokedByDeviceId,362362 )363- val retained = if (revocations.size < MAX_REVOCATION_RECORDS) {364- revocations365- } else {366- val removable = revocations.indexOfFirst { it.revokedByDeviceId != revokedByDeviceId }367- if (removable >= 0) revocations.toMutableList().also { it.removeAt(removable) } else revocations368- }369363 return DeviceRevocationMutation(370364 remaining,371- (retained + record).takeLast(MAX_REVOCATION_RECORDS),365+ capRevocationRecords(revocations + record),372366 record,373367 )374368 }@@ -384,8 +378,27 @@384378 ): RevocationMergeResult {385379 val known = existing.map { it.deviceId }.toSet()386380 val fresh = incoming.filterNot { known.contains(it.deviceId) }387- val admitted = fresh.take((MAX_REVOCATION_RECORDS - existing.size).coerceAtLeast(0))388- return RevocationMergeResult(existing + admitted, admitted)381+ return RevocationMergeResult(capRevocationRecords(existing + fresh), fresh)382+}383+384+/**385+ * Keep the terminal ledger bounded without letting one issuer permanently386+ * consume every slot. Each overflow drops the oldest record belonging to the387+ * currently largest issuer, matching Browser's `capRevocations` policy.388+ */389+internal 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] }389402 }390403 391404 /**app/src/main/java/com/peachpasswords/sync/SyncCoordinator.kt+5 −5
@@ -308,12 +308,12 @@308308 * follows the legacy sequence, and the session hangs until the 30s timeout.309309 */310310 private fun SyncVaultAdapter.negotiatesDeviceManifest(hello: SyncMessage.Hello): Boolean {311- if (!supportsDeviceManifest) return false312- val theirs = hello.deviceManifestVersion ?: return false313- // The negotiated version is the minimum of both advertisements, and we only314- // implement one — a peer advertising older falls back to the legacy path.315- return minOf(DEVICE_MANIFEST_VERSION, theirs) == DEVICE_MANIFEST_VERSION311+ return negotiatesDeviceManifest(supportsDeviceManifest, hello.deviceManifestVersion)316312 }313+314+/** Both peers must advertise the exact schema they will exchange. */315+internal fun negotiatesDeviceManifest(localSupports: Boolean, peerVersion: Int?): Boolean =316+ localSupports && peerVersion == DEVICE_MANIFEST_VERSION317317 318318 /** Entry ids the peer holds at a strictly newer mtime than we do. */319319 private fun diffNewer(remote: Map<String, Long>, local: Map<String, Long>): List<String> =app/src/main/java/com/peachpasswords/sync/VaultAdopt.kt+111 −49
@@ -271,6 +271,13 @@271271 */272272 suspend fun validateSource(source: AdoptionFrame.Source) {}273273 274+ /**275+ * True when the source's identity (from ADOPT_GRANT) is in the local276+ * terminal revocation ledger. When true, the receiver sends277+ * ADOPT_DEVICE_ID_COLLISION so the source rotates and resends the grant.278+ */279+ suspend fun hasSourceIdentityCollision(source: AdoptionFrame.Source): Boolean = false280+274281 /** Seal a fresh local vault under the receiver's password, reusing [rootKeyHex]. Returns the vault id. */275282 suspend fun createVaultFromRootKey(rootKeyHex: String): String276283 suspend fun deriveLocalIdentity(): LocalDeviceIdentity@@ -318,6 +325,12 @@318325 suspend fun onConsent(request: AdoptionFrame.Request): Boolean319326 suspend fun upsertPairedDevice(device: PairedDevice)320327 fun hasDeviceIdentityCollision(device: PairedDevice): Boolean = false328+ /**329+ * Rotate the source's identity after the receiver reports a collision on330+ * the source's own identity. Returns the fresh identity for the resent331+ * ADOPT_GRANT.332+ */333+ suspend fun rotateSourceIdentity(): LocalDeviceIdentity = error("rotateSourceIdentity not wired")321334 val pairState: AdoptionPairState? get() = null322335 /** Return all encrypted entries + tombstones for the inline snapshot. */323336 suspend fun vaultSnapshot(): Pair<Map<String, String>, Map<String, Long>>? = null@@ -363,7 +376,8 @@363376 frame is AdoptionFrame.Applied364377 365378 fun isAdoptReject(frame: AdoptionFrame?): Boolean =366- frame is AdoptionFrame.Reject && frame.reason == "ADOPT_PRO_REQUIRED"379+ frame is AdoptionFrame.Reject &&380+ (frame.reason == "ADOPT_PRO_REQUIRED" || frame.reason == "ADOPT_DEVICE_ID_COLLISION")367381 368382 fun isAdoptSnapshot(frame: AdoptionFrame?): Boolean =369383 frame is AdoptionFrame.Snapshot &&@@ -433,14 +447,46 @@433447 }434448 435449 deps.validateSource(grant.source)436- val vaultId = deps.createVaultFromRootKey(grant.rootKeyHex)437- if (vaultId != grant.vaultId) {450+451+ // Check the source's identity against the local revocation ledger. A452+ // previously-revoked device must present a fresh identity so that stale453+ // signed revocations held by other mesh peers cannot remove it after454+ // re-pair. If the source's identity is revoked, send ADOPT_DEVICE_ID_COLLISION455+ // and wait for a fresh grant (one retry).456+ var acceptedGrant = grant457+ if (deps.hasSourceIdentityCollision(acceptedGrant.source)) {458+ sendFrame(channel, AdoptionFrame.Reject("ADOPT_DEVICE_ID_COLLISION"))459+ val retry = receiveFrame(channel)460+ if (!isAdoptGrant(retry)) {461+ deps.onError("ADOPT_SOURCE_COLLISION_NOT_RESOLVED")462+ return null463+ }464+ acceptedGrant = retry as AdoptionFrame.Grant465+ if (deps.hasSourceIdentityCollision(acceptedGrant.source)) {466+ sendFrame(channel, AdoptionFrame.Reject("ADOPT_DEVICE_ID_COLLISION"))467+ deps.onError("ADOPT_SOURCE_COLLISION_NOT_RESOLVED")468+ return null469+ }470+ // Re-validate the fresh grant's vault id.471+ val freshRootBytes = hexToPubkey(acceptedGrant.rootKeyHex)472+ try {473+ if (computeVaultId(freshRootBytes) != acceptedGrant.vaultId) {474+ deps.onError("ADOPT_VAULT_ID_MISMATCH")475+ return null476+ }477+ } finally {478+ freshRootBytes.fill(0)479+ }480+ }481+482+ val vaultId = deps.createVaultFromRootKey(acceptedGrant.rootKeyHex)483+ if (vaultId != acceptedGrant.vaultId) {438484 deps.onError("ADOPT_VAULT_ID_MISMATCH")439485 return null440486 }441487 442488 if (receiverLicense == null) {443- grant.license?.let { deps.applyLicense(it) }489+ acceptedGrant.license?.let { deps.applyLicense(it) }444490 }445491 446492 val identity = deps.deriveLocalIdentity()@@ -458,15 +504,15 @@458504 }459505 460506 val sourceDevice = PairedDevice(461- deviceId = grant.source.deviceId,462- deviceName = grant.source.deviceName,463- deviceType = grant.source.deviceType,464- longTermPublicKeyHex = grant.source.longTermPublicKeyHex,465- signingPublicKeyHex = grant.source.signingPublicKeyHex,507+ deviceId = acceptedGrant.source.deviceId,508+ deviceName = acceptedGrant.source.deviceName,509+ deviceType = acceptedGrant.source.deviceType,510+ longTermPublicKeyHex = acceptedGrant.source.longTermPublicKeyHex,511+ signingPublicKeyHex = acceptedGrant.source.signingPublicKeyHex,466512 trustSource = "direct",467- wsPort = grant.source.wsPort,513+ wsPort = acceptedGrant.source.wsPort,468514 rendezvousSecretHex = deps.pairState?.rendezvousSecretHex,469- relayUrl = deps.pairState?.relayUrl ?: grant.source.relayUrl,515+ relayUrl = deps.pairState?.relayUrl ?: acceptedGrant.source.relayUrl,470516 pairedAt = nowMs(),471517 )472518 // A physically confirmed direct re-pair is the sole path allowed to lift@@ -511,58 +557,74 @@511557 val rootKeyHex = deps.rootKeyHex()512558 if (!validateRootKeyHex(rootKeyHex)) throw IllegalStateException("ADOPT_INVALID_ROOT_KEY")513559 514- sendFrame(channel, AdoptionFrame.Grant(515- rootKeyHex = rootKeyHex,516- vaultId = deps.vaultId(),517- license = sourceLicense,518- source = AdoptionFrame.Source(519- deviceId = deps.sourceIdentity.deviceId,520- deviceName = deps.sourceIdentity.deviceName,521- deviceType = deps.sourceIdentity.deviceType.wireValue,522- longTermPublicKeyHex = deps.sourceIdentity.longTermPublicKeyHex,523- signingPublicKeyHex = deps.sourceIdentity.signingPublicKeyHex,524- wsPort = deps.sourceIdentity.wsPort,525- relayUrl = deps.pairState?.relayUrl,526- ),527- snapshotCapable = request.snapshotCapable == true,528- ))560+ var sourceIdentity = deps.sourceIdentity561+ var grantAttempts = 0562+ while (true) {563+ sendFrame(channel, AdoptionFrame.Grant(564+ rootKeyHex = rootKeyHex,565+ vaultId = deps.vaultId(),566+ license = sourceLicense,567+ source = AdoptionFrame.Source(568+ deviceId = sourceIdentity.deviceId,569+ deviceName = sourceIdentity.deviceName,570+ deviceType = sourceIdentity.deviceType.wireValue,571+ longTermPublicKeyHex = sourceIdentity.longTermPublicKeyHex,572+ signingPublicKeyHex = sourceIdentity.signingPublicKeyHex,573+ wsPort = sourceIdentity.wsPort,574+ relayUrl = deps.pairState?.relayUrl,575+ ),576+ snapshotCapable = request.snapshotCapable == true,577+ ))529578 530- var identity = receiveFrame(channel)531- if (!isAdoptIdentity(identity)) return null532- identity as AdoptionFrame.Identity579+ var identity = receiveFrame(channel)533580 534- var device = PairedDevice(535- deviceId = identity.deviceId,536- deviceName = identity.deviceName,537- deviceType = identity.deviceType,538- longTermPublicKeyHex = identity.longTermPublicKeyHex,539- signingPublicKeyHex = identity.signingPublicKeyHex,540- trustSource = "direct",541- rendezvousSecretHex = deps.pairState?.rendezvousSecretHex,542- relayUrl = deps.pairState?.relayUrl,543- pairedAt = nowMs(),544- )545- if (deps.hasDeviceIdentityCollision(device)) {546- sendFrame(channel, AdoptionFrame.Reject("ADOPT_DEVICE_ID_COLLISION"))547- identity = receiveFrame(channel)581+ // Receiver may reject the source's identity if it is in the receiver's582+ // revocation ledger. Rotate and resend (one retry).583+ if (identity is AdoptionFrame.Reject &&584+ identity.reason == "ADOPT_DEVICE_ID_COLLISION" &&585+ grantAttempts == 0586+ ) {587+ sourceIdentity = deps.rotateSourceIdentity()588+ grantAttempts++589+ continue590+ }591+548592 if (!isAdoptIdentity(identity)) return null549593 identity as AdoptionFrame.Identity550- device = device.copy(594+595+ var device = PairedDevice(551596 deviceId = identity.deviceId,552597 deviceName = identity.deviceName,553598 deviceType = identity.deviceType,554599 longTermPublicKeyHex = identity.longTermPublicKeyHex,555600 signingPublicKeyHex = identity.signingPublicKeyHex,601+ trustSource = "direct",602+ rendezvousSecretHex = deps.pairState?.rendezvousSecretHex,603+ relayUrl = deps.pairState?.relayUrl,604+ pairedAt = nowMs(),556605 )557606 if (deps.hasDeviceIdentityCollision(device)) {558607 sendFrame(channel, AdoptionFrame.Reject("ADOPT_DEVICE_ID_COLLISION"))559- return null608+ identity = receiveFrame(channel)609+ if (!isAdoptIdentity(identity)) return null610+ identity as AdoptionFrame.Identity611+ device = device.copy(612+ deviceId = identity.deviceId,613+ deviceName = identity.deviceName,614+ deviceType = identity.deviceType,615+ longTermPublicKeyHex = identity.longTermPublicKeyHex,616+ signingPublicKeyHex = identity.signingPublicKeyHex,617+ )618+ if (deps.hasDeviceIdentityCollision(device)) {619+ sendFrame(channel, AdoptionFrame.Reject("ADOPT_DEVICE_ID_COLLISION"))620+ return null621+ }560622 }623+ deps.upsertPairedDevice(device)624+ sendFrame(channel, AdoptionFrame.Complete)625+ if (!isAdoptApplied(receiveFrame(channel))) return null626+ return device561627 }562- deps.upsertPairedDevice(device)563- sendFrame(channel, AdoptionFrame.Complete)564- if (!isAdoptApplied(receiveFrame(channel))) return null565- return device566628 }567629 568630 /**app/src/main/java/com/peachpasswords/ui/pairing/AdoptVaultViewModel.kt+15 −0
@@ -27,6 +27,7 @@2727 import com.peachpasswords.sync.getDeviceName2828 import com.peachpasswords.sync.getOrCreateDeviceId2929 import com.peachpasswords.sync.hexToPubkey30+import com.peachpasswords.sync.rotateDeviceId3031 import com.peachpasswords.sync.parsePairingInvitation3132 import com.peachpasswords.ui.security.scorePassword3233 import com.peachpasswords.vault.AdoptVaultResult@@ -254,6 +255,9 @@254255 if (!joining) return255256 }256257 258+ override suspend fun hasSourceIdentityCollision(source: AdoptionFrame.Source): Boolean =259+ devices.isRevoked(source.deviceId, source.longTermPublicKeyHex)260+257261 override suspend fun createVaultFromRootKey(rootKeyHex: String): String {258262 // Same protocol seam, two safe outcomes: a fresh device builds259263 // around the granted key; a populated device may only refresh a@@ -393,6 +397,17 @@393397 394398 override fun hasDeviceIdentityCollision(device: PairedDevice): Boolean =395399 devices.hasIdentityCollision(device)400+401+ override suspend fun rotateSourceIdentity(): LocalDeviceIdentity {402+ rotateDeviceId(appContext)403+ val master = vault.syncMasterKey()404+ ?: throw IllegalStateException("vault_locked")405+ return try {406+ buildLocalIdentity(appContext, master)407+ } finally {408+ VaultCrypto.zero(master)409+ }410+ }396411 397412 override suspend fun upsertPairedDevice(device: PairedDevice) {398413 devices.clearRevocation(device.deviceId)app/src/main/java/com/peachpasswords/ui/pairing/CodePairViewModel.kt+12 −0
@@ -24,6 +24,7 @@2424 import com.peachpasswords.sync.buildLocalIdentity2525 import com.peachpasswords.sync.deriveLocalSyncKeypair2626 import com.peachpasswords.sync.getOrCreateDeviceId27+import com.peachpasswords.sync.rotateDeviceId2728 import com.peachpasswords.vault.VaultCrypto2829 import com.peachpasswords.vault.VaultRepository2930 import com.peachpasswords.license.LicenseRepository@@ -193,6 +194,17 @@193194 194195 override fun hasDeviceIdentityCollision(device: PairedDevice): Boolean =195196 deviceStore.hasIdentityCollision(device)197+198+ override suspend fun rotateSourceIdentity(): LocalDeviceIdentity {199+ rotateDeviceId(appContext)200+ val master = vault.syncMasterKey()201+ ?: throw IllegalStateException("vault_locked")202+ return try {203+ buildLocalIdentity(appContext, master)204+ } finally {205+ VaultCrypto.zero(master)206+ }207+ }196208 197209 override suspend fun upsertPairedDevice(device: PairedDevice) {198210 // SAS-confirmed direct adoption — the one consent signal strongapp/src/test/java/com/peachpasswords/sync/PairedDeviceRevocationTest.kt+27 −3
@@ -30,7 +30,7 @@3030 }3131 3232 @Test33- fun `full ledger keeps terminal records during peer merge capacity`() {33+ fun `full ledger admits another issuer by evicting the largest issuer oldest record`() {3434 val existing = List(500) { index ->3535 DeviceRevocation("terminal-$index", index.toString(16).padStart(64, '0'), index.toLong(), "issuer-a")3636 }@@ -38,8 +38,9 @@3838 DeviceRevocation("peer-extra", "ff".repeat(32), 501L, "issuer-b"),3939 ))4040 assertEquals(500, merged.records.size)41- assertEquals(0, merged.admitted.size)42- assertEquals("terminal-0", merged.records.first().deviceId)41+ assertEquals(listOf("peer-extra"), merged.admitted.map { it.deviceId })42+ assertEquals(false, merged.records.any { it.deviceId == "terminal-0" })43+ assertEquals(true, merged.records.any { it.deviceId == "peer-extra" })4344 }4445 4546 @Test@@ -64,6 +65,29 @@6465 assertEquals(500, records.size)6566 assertEquals("terminal-0", records.first().deviceId)6667 assertEquals("local-new", records.last().deviceId)68+ }69+70+ @Test71+ fun `peer flood evicts only its own oldest records once it is largest issuer`() {72+ val existing = listOf(73+ DeviceRevocation("genuine", "aa".repeat(32), 1L, "honest-issuer"),74+ )75+ val flood = List(600) { index ->76+ DeviceRevocation(77+ "junk-$index",78+ index.toString(16).padStart(64, '0'),79+ index.toLong() + 2,80+ "flooding-issuer",81+ )82+ }83+84+ val merged = mergeRevocationRecords(existing, flood)85+86+ assertEquals(500, merged.records.size)87+ assertEquals(600, merged.admitted.size)88+ assertEquals(true, merged.records.any { it.deviceId == "genuine" })89+ assertEquals(false, merged.records.any { it.deviceId == "junk-0" })90+ assertEquals(true, merged.records.any { it.deviceId == "junk-599" })6791 }6892 6993 @Testapp/src/test/java/com/peachpasswords/sync/SyncCoordinatorTest.kt+8 −0
@@ -71,6 +71,14 @@7171 7272 class SyncCoordinatorTest {7373 74+ @Test fun device_manifest_negotiation_requires_the_exact_supported_version() {75+ assertTrue(negotiatesDeviceManifest(true, DEVICE_MANIFEST_VERSION))76+ assertFalse(negotiatesDeviceManifest(false, DEVICE_MANIFEST_VERSION))77+ assertFalse(negotiatesDeviceManifest(true, DEVICE_MANIFEST_VERSION - 1))78+ assertFalse(negotiatesDeviceManifest(true, DEVICE_MANIFEST_VERSION + 1))79+ assertFalse(negotiatesDeviceManifest(true, null))80+ }81+7482 @Test fun full_round_trip_exchanges_entries_both_ways() = runBlocking {7583 val (sa, sb) = duplex()7684 val a = FakeAdapter("A", version = 1).apply { put("x", 100) }app/src/test/java/com/peachpasswords/sync/VaultAdoptTest.kt+89 −0
@@ -64,6 +64,7 @@6464 val revocationsCleared = mutableListOf<String>()6565 val upserted = mutableListOf<PairedDevice>()6666 val errors = mutableListOf<String>()67+ var collidingSourceDeviceId: String? = null6768 override fun generateDeviceId(): String = "receiver-ephemeral"6869 override suspend fun confirmSas(): Boolean = sasConfirmed6970 override suspend fun createVaultFromRootKey(rootKeyHex: String): String {@@ -72,6 +73,8 @@7273 return vaultId ?: error("no vault id")7374 }7475 override suspend fun deriveLocalIdentity(): LocalDeviceIdentity = derived ?: error("no identity")76+ override suspend fun hasSourceIdentityCollision(source: AdoptionFrame.Source): Boolean =77+ source.deviceId == collidingSourceDeviceId7578 override suspend fun clearPairedDeviceRevocation(deviceId: String) {7679 revocationsCleared += deviceId7780 }@@ -94,6 +97,7 @@9497 var consentAsked = false9598 var rootRequested = false9699 var collidingDeviceId: String? = null100+ var rotatedSourceIdentity: LocalDeviceIdentity? = null97101 override suspend fun rootKeyHex(): String {98102 rootRequested = true99103 return rootKeyHex@@ -110,6 +114,8 @@110114 }111115 override fun hasDeviceIdentityCollision(device: PairedDevice): Boolean =112116 device.deviceId == collidingDeviceId117+ override suspend fun rotateSourceIdentity(): LocalDeviceIdentity =118+ rotatedSourceIdentity ?: error("no rotated source identity")113119 override suspend fun upsertPairedDevice(device: PairedDevice) { upserted += device }114120 }115121 @@ -181,6 +187,89 @@181187 182188 assertEquals("firefox-id", sourcePromise.await()?.deviceId)183189 assertEquals(listOf("firefox-id"), source.upserted.map { it.deviceId })190+ }191+192+ @Test fun receiver_rejects_revoked_source_identity_and_accepts_one_rotation() = runBlocking {193+ val (receiverCh, sourceCh) = memoryPair()194+ val rootKeyHex = "14".repeat(32)195+ val vaultId = vaultIdFor(rootKeyHex)196+ val receiver = RecorderReceiver(197+ "Android",198+ DeviceType.ANDROID,199+ vaultId,200+ derived = identity("receiver").copy(deviceType = DeviceType.ANDROID),201+ ).apply {202+ collidingSourceDeviceId = "chrome-id"203+ }204+205+ val receiverJob = async { requestAdoption(receiverCh, receiver) { 0L } }206+ receiveFrame(sourceCh) // ADOPT_REQUEST207+ receiveFrame(sourceCh) // ADOPT_CONFIRM208+ sendFrame(sourceCh, AdoptionFrame.Grant(209+ rootKeyHex = rootKeyHex,210+ vaultId = vaultId,211+ source = AdoptionFrame.Source(212+ "chrome-id",213+ "Chrome",214+ "extension",215+ "ab".repeat(32),216+ ),217+ ))218+ val rejection = receiveFrame(sourceCh)219+ assertEquals("ADOPT_DEVICE_ID_COLLISION", (rejection as AdoptionFrame.Reject).reason)220+221+ receiver.collidingSourceDeviceId = null222+ sendFrame(sourceCh, AdoptionFrame.Grant(223+ rootKeyHex = rootKeyHex,224+ vaultId = vaultId,225+ source = AdoptionFrame.Source(226+ "chrome-fresh-id",227+ "Chrome",228+ "extension",229+ "ef".repeat(32),230+ ),231+ ))232+ assertTrue(receiveFrame(sourceCh) is AdoptionFrame.Identity)233+ sendFrame(sourceCh, AdoptionFrame.Complete)234+ assertTrue(receiveFrame(sourceCh) is AdoptionFrame.Applied)235+236+ assertEquals("chrome-fresh-id", receiverJob.await()?.deviceId)237+ assertEquals(listOf("chrome-fresh-id"), receiver.revocationsCleared)238+ assertEquals(listOf("chrome-fresh-id"), receiver.upserted.map { it.deviceId })239+ }240+241+ @Test fun source_rotates_its_revoked_identity_and_resends_grant_once() = runBlocking {242+ val (receiverCh, sourceCh) = memoryPair()243+ val rootKeyHex = "15".repeat(32)244+ val vaultId = vaultIdFor(rootKeyHex)245+ val source = RecorderSource(identity("chrome"), rootKeyHex, vaultId).apply {246+ rotatedSourceIdentity = identity("chrome-fresh")247+ }248+249+ val sourceJob = async {250+ grantAdoption(sourceCh, AdoptionFrame.Request(251+ sessionRequestId = "receiver-ephemeral",252+ deviceName = "Android",253+ deviceType = DeviceType.ANDROID.wireValue,254+ ), source)255+ }256+ sendFrame(receiverCh, AdoptionFrame.Confirm(true))257+ val firstGrant = receiveFrame(receiverCh) as AdoptionFrame.Grant258+ assertEquals("chrome-id", firstGrant.source.deviceId)259+ sendFrame(receiverCh, AdoptionFrame.Reject("ADOPT_DEVICE_ID_COLLISION"))260+ val secondGrant = receiveFrame(receiverCh) as AdoptionFrame.Grant261+ assertEquals("chrome-fresh-id", secondGrant.source.deviceId)262+ sendFrame(receiverCh, AdoptionFrame.Identity(263+ deviceId = "android-id",264+ deviceName = "Android",265+ deviceType = DeviceType.ANDROID.wireValue,266+ longTermPublicKeyHex = "22".repeat(32),267+ ))268+ assertTrue(receiveFrame(receiverCh) is AdoptionFrame.Complete)269+ sendFrame(receiverCh, AdoptionFrame.Applied)270+271+ assertEquals("android-id", sourceJob.await()?.deviceId)272+ assertEquals(listOf("android-id"), source.upserted.map { it.deviceId })184273 }185274 186275 @Test fun rejects_without_creating_or_pairing_when_neither_peer_has_pro() = runBlocking {