4ccb3c874e48
implement the secure reset generation state machine
- time
- 2026-09-10 22:55 UTC · 2 months ago
- machine
- koh2
- agent
- deepseek/deepseek-v4-flash
- session
- secure sync reset migration
- parent
- 1830b6bc2816
↓ peach-android-4ccb3c87.tar.gzatlas at this save
files changed23 files
VERSION+1 −1app/src/main/java/com/peachpasswords/di/VaultModule.kt+6 −0app/src/main/java/com/peachpasswords/sync/BackgroundSyncCoordinator.kt+4 −1app/src/main/java/com/peachpasswords/sync/DeviceIdentity.kt+19 −1app/src/main/java/com/peachpasswords/sync/ForegroundSyncCoordinator.kt+14 −0app/src/main/java/com/peachpasswords/sync/PairedDeviceStore.kt+14 −2app/src/main/java/com/peachpasswords/sync/PeachSyncService.kt+20 −3app/src/main/java/com/peachpasswords/sync/PendingVouchedDeviceStore.kt+3 −0app/src/main/java/com/peachpasswords/sync/RelayAdoptionHost.kt+26 −1app/src/main/java/com/peachpasswords/sync/RelayAdoptionReceiver.kt+23 −3app/src/main/java/com/peachpasswords/sync/SyncFreshStartResetter.kt+4 −0app/src/main/java/com/peachpasswords/sync/SyncGeneration.kt+220 −0app/src/main/java/com/peachpasswords/sync/SyncGenerationStore.kt+153 −0app/src/main/java/com/peachpasswords/sync/SyncOutcomeReason.kt+8 −0app/src/main/java/com/peachpasswords/ui/settings/SettingsCardBodies.kt+106 −0app/src/main/java/com/peachpasswords/ui/sync/SyncViewModel.kt+54 −0app/src/main/res/xml/backup_rules.xml+2 −0app/src/main/res/xml/data_extraction_rules.xml+4 −0app/src/test/java/com/peachpasswords/sync/FakeSyncGeneration.kt+105 −0app/src/test/java/com/peachpasswords/sync/RelayAdoptionHostTest.kt+120 −0app/src/test/java/com/peachpasswords/sync/RelayAdoptionInitiatorSourceTest.kt+2 −2app/src/test/java/com/peachpasswords/sync/SyncGenerationTest.kt+316 −0app/src/test/java/com/peachpasswords/sync/SyncOutcomeTest.kt+4 −0app/src/main/java/com/peachpasswords/di/VaultModule.kt+6 −0
@@ -2,6 +2,8 @@22 33 import com.peachpasswords.sync.PairedDeviceRegistry44 import com.peachpasswords.sync.PairedDeviceStore5+import com.peachpasswords.sync.SyncGenerationPort6+import com.peachpasswords.sync.SyncGenerationStore57 import com.peachpasswords.vault.VaultRepository68 import com.peachpasswords.vault.VaultStorage79 import com.peachpasswords.vault.VaultStore@@ -22,6 +24,10 @@2224 @Binds2325 @Singleton2426 abstract fun bindPairedDeviceRegistry(impl: PairedDeviceStore): PairedDeviceRegistry27+28+ @Binds29+ @Singleton30+ abstract fun bindSyncGenerationPort(impl: SyncGenerationStore): SyncGenerationPort2531 }2632 2733 /** QA seam: lets instrumented tests reach the vault without any UI. */app/src/main/java/com/peachpasswords/sync/BackgroundSyncCoordinator.kt+4 −1
@@ -26,10 +26,13 @@2626 private val isUnlocked: StateFlow<Boolean>,2727 private val preferenceEnabled: StateFlow<Boolean>,2828 private val syncVaultId: () -> String? = { "unknown" },29+ /** §11: a device that must reset does not bring the sync service up at all. */30+ private val syncAllowed: () -> Boolean = { true },2931 ) {3032 fun setEnabled(enabled: Boolean) {3133 if (enabled) {3234 if (isUnlocked.value && syncVaultId() == null) return35+ if (!syncAllowed()) return3336 start()3437 } else stop()3538 }@@ -38,7 +41,7 @@3841 fun observe(scope: CoroutineScope) {3942 scope.launch {4043 isUnlocked.collect { unlocked ->41- if (unlocked && preferenceEnabled.value && syncVaultId() != null) start()44+ if (unlocked && preferenceEnabled.value && syncVaultId() != null && syncAllowed()) start()4245 }4346 }4447 }app/src/main/java/com/peachpasswords/sync/DeviceIdentity.kt+19 −1
@@ -32,6 +32,9 @@3232 }3333 return when (val record = readIdentityRecord(stored)) {3434 is IdentityRecord.Absent -> {35+ if (resetRequiredByExistingTrustState(context)) {36+ throw IllegalStateException("identity_migration_required")37+ }3538 val fresh = randomLocalIdentityCredentials(UUID.randomUUID().toString())3639 persistIdentity(context, fresh, System.currentTimeMillis())3740 fresh@@ -43,9 +46,24 @@4346 record.credentials4447 }4548 is IdentityRecord.Current -> record.credentials46- IdentityRecord.Invalid -> throw IllegalStateException("identity_migration_required")49+ IdentityRecord.Invalid -> {50+ resetRequiredByExistingTrustState(context)51+ throw IllegalStateException("identity_migration_required")52+ }4753 }4854 }55+56+/**57+ * A missing or corrupt identity may only be minted on a genuinely fresh58+ * installation. With any trust state present it is a reset condition (§11.5):59+ * minting would hand every peer an unknown device whose new keys no longer match60+ * the revocation ledger. An unresolvable store therefore counts as trust state —61+ * the refusal is the safe direction.62+ */63+private fun resetRequiredByExistingTrustState(context: Context): Boolean = runCatching {64+ mintDecision(syncGenerationStore(context), System.currentTimeMillis()) ==65+ IdentityMintDecision.REFUSE_RESET_REQUIRED66+}.getOrDefault(true)4967 5068 private fun persistIdentity(5169 context: Context,app/src/main/java/com/peachpasswords/sync/ForegroundSyncCoordinator.kt+14 −0
@@ -20,6 +20,7 @@2020 private val deviceStore: PairedDeviceStore,2121 private val pendingVouchedStore: PendingVouchedDeviceStore,2222 private val syncAlertStore: SyncAlertStore,23+ private val generation: SyncGenerationStore,2324 ) {2425 private val scope = CoroutineScope(Dispatchers.Main.immediate + SupervisorJob())2526 private var inFlight: Job? = null@@ -37,6 +38,10 @@3738 fun triggerForegroundSync() {3839 if (!vault.isUnlocked.value || vault.syncVaultId() == null || !backgroundSync.enabled.value) return3940 if (foregroundSyncPeers(deviceStore.getAll()).isEmpty()) return41+ // §11: this device has retired or is retiring its legacy generation, so42+ // it opens no room at all. Nothing to report — the settings surface43+ // already states the reset.44+ if (!syncAllowedNow(generation)) return4045 PeachSyncService.start(context)4146 }4247 @@ -49,6 +54,7 @@4954 5055 private fun buildAdapter(): SyncVaultAdapter? {5156 if (!vault.isUnlocked.value || vault.syncVaultId() == null) return null57+ if (!syncAllowedNow(generation)) return null5258 val credentials = loadOrCreateLocalIdentity(context)5359 return VaultSyncAdapter(5460 repo = vault,@@ -60,6 +66,14 @@6066 )6167 }6268 }69+70+/**71+ * The §11 gate for pre-session paths: a device that must reset opens no room.72+ * The session itself is gated again in [PeachSyncService], which every path73+ * routes through.74+ */75+internal fun syncAllowedNow(generation: SyncGenerationPort): Boolean =76+ assertSyncAllowed(generation, System.currentTimeMillis()) == SyncDecision.ALLOWED6377 6478 internal fun foregroundSyncPeers(devices: List<PairedDevice>): List<PairedDevice> =6579 devices.filter { device ->app/src/main/java/com/peachpasswords/sync/PairedDeviceStore.kt+14 −2
@@ -244,13 +244,22 @@244244 245245 fun clear() {246246 mutationGate.withLock {247- prefs.edit()247+ val edit = prefs.edit()248248 .remove(KEY_DEVICES)249249 .remove(KEY_REVOCATIONS)250- .apply()250+ // Known-key history is trust state: leaving it behind would keep a251+ // cleared installation admitting keys it no longer holds devices252+ // for, so it goes with the rest of the registry.253+ for (key in prefs.all.keys.filter { it.startsWith(KEY_ISSUER_KEYS_PREFIX) }) {254+ edit.remove(key)255+ }256+ edit.commit()251257 }252258 }253259 260+ /** Verbatim logical copy of the whole registry, for the secure-reset archive. */261+ internal fun snapshot(): Map<String, Any?> = prefs.all262+254263 /**255264 * Refresh the device's `lastKnownIp` (the closest real analogue to the256265 * brief's `lastSeen`). No-op when the id is unknown or [ip] is null.@@ -301,6 +310,9 @@301310 override fun issuerSigningKeys(issuerDeviceId: String): Set<String> =302311 prefs.getStringSet("$KEY_ISSUER_KEYS_PREFIX$issuerDeviceId", emptySet())303312 .orEmpty().map(String::lowercase).toSet()313+314+ /** Any known-key history at all: legacy trust state for the reset probe. */315+ fun hasIssuerSigningKeys(): Boolean = prefs.all.keys.any { it.startsWith(KEY_ISSUER_KEYS_PREFIX) }304316 305317 override fun appendIssuerSigningKey(issuerDeviceId: String, signingKeyHex: String): Boolean {306318 val key = signingKeyHex.lowercase()app/src/main/java/com/peachpasswords/sync/PeachSyncService.kt+20 −3
@@ -47,11 +47,20 @@4747 @Inject lateinit var syncAlertStore: SyncAlertStore4848 @Inject lateinit var syncOutcomes: SyncOutcomeStore4949 @Inject lateinit var lockedSyncSpool: LockedSyncSpoolStore50+ @Inject lateinit var syncGeneration: SyncGenerationStore5051 5152 private val scope = CoroutineScope(SupervisorJob())5253 5354 override fun onBind(intent: Intent?): IBinder? = null5455 56+ /**57+ * The reported reason when this device must not sync, or null when it may.58+ * §11.3: RESET_REQUIRED and RESET_CONFIRMED block every session.59+ */60+ private fun syncRefusal(): SyncOutcomeSummary? =61+ syncRefusalReason(syncGeneration, System.currentTimeMillis())62+ ?.let { SyncOutcomeSummary(reason = it) }63+5564 override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {5665 // A decoy unlock has no sync identity. Stop before foreground promotion5766 // so it cannot expose a notification or drain the locked spool.@@ -125,8 +134,16 @@125134 // without reporting a misleading locked-vault outcome.126135 when {127136 vault.syncVaultId() == null -> throw CancellationException("decoy session")128- !vault.isUnlocked.value -> lockedSyncSpool.adapter()129- else -> {137+ // §11: a device waiting on, or part-way through, its reset opens138+ // no session at all — neither unlocked nor through the locked139+ // spool, whose staged ciphertext belongs to the retired140+ // generation and must not be applied.141+ else -> syncRefusal()?.let { refusal ->142+ syncOutcomes.report(refusal)143+ null144+ } ?: if (!vault.isUnlocked.value) {145+ lockedSyncSpool.adapter()146+ } else {130147 val credentials = loadOrCreateLocalIdentity(this)131148 VaultSyncAdapter(132149 repo = vault,@@ -137,7 +154,7 @@137154 localCredentials = credentials,138155 )139156 }140- }157+ }141158 }142159 } finally {143160 master?.let(VaultCrypto::zero)app/src/main/java/com/peachpasswords/sync/PendingVouchedDeviceStore.kt+3 −0
@@ -185,6 +185,9 @@185185 persist(emptyList())186186 }187187 188+ /** Verbatim logical copy of the pending registry, for the secure-reset archive. */189+ internal fun snapshot(): Map<String, Any?> = prefs.all190+188191 fun observeAll(): Flow<List<PendingVouchedDevice>> = callbackFlow {189192 trySend(getAll())190193 val listener = android.content.SharedPreferences.OnSharedPreferenceChangeListener { _, key ->app/src/main/java/com/peachpasswords/sync/RelayAdoptionHost.kt+26 −1
@@ -29,6 +29,8 @@2929 @Singleton3030 class RelayAdoptionHost @Inject constructor(3131 private val relaySettings: RelaySettingsStore,32+ private val generation: SyncGenerationPort,33+ private val deviceStore: PairedDeviceRegistry,3234 ) {3335 private var job: Job? = null3436 private var socket: RelayBinarySocket? = null@@ -71,6 +73,7 @@7173 // until the source WebSocket is open and waiting in the room.7274 trySend(RelayAdoptionEvent.InvitationReady(invitation))7375 76+ var peerOutdated = false7477 val adopted = withTimeout(windowMs) {7578 runRelayAdoptionSourceSession(7679 socket = connected,@@ -80,6 +83,12 @@8083 ourStaticPublicKey = ourStaticPublicKey,8184 localIdentity = localIdentity,8285 sourceDeps = sourceDeps,86+ // §11.6: once this device has reset its generation, a v187+ // peer is repair-required exactly as an outdated sync88+ // peer is. The invitation still goes out; the refusal89+ // happens at the first frame.90+ postReset = { generation.isPostReset(System.currentTimeMillis()) },91+ onPeerOutdated = { peerOutdated = true },8392 confirm = { sas, request ->8493 trySend(8594 RelayAdoptionEvent.AwaitingPeerConfirmation(@@ -94,9 +103,16 @@94103 },95104 )96105 }97- if (adopted == null) {106+ if (peerOutdated) {107+ trySend(RelayAdoptionEvent.Rejected(PEER_PROTOCOL_OUTDATED))108+ } else if (adopted == null) {98109 trySend(RelayAdoptionEvent.Rejected("adoption_rejected"))99110 } else {111+ onDirectV2PairingEstablished(112+ generation,113+ hasDirectDevice = deviceStore.getAll().any { it.trustSource == "direct" },114+ nowMs = System.currentTimeMillis(),115+ )100116 trySend(101117 RelayAdoptionEvent.Adopted(102118 capDeviceName(adopted.deviceName?.takeIf(String::isNotBlank) ?: "New device"),@@ -148,6 +164,8 @@148164 localIdentity: LocalDeviceIdentity,149165 sourceDeps: AdoptionSourceV2Deps,150166 confirm: suspend (sas: String, request: AdoptionFrame.Request) -> Boolean,167+ postReset: () -> Boolean = { false },168+ onPeerOutdated: () -> Unit = {},151169 ): PairedDevice? {152170 val hello = JSONObject(String(socket.receive(), Charsets.UTF_8))153171 require(hello.optString("type") == "PEACH_HELLO") { "expected PEACH_HELLO" }@@ -184,6 +202,13 @@184202 185203 val request = receiveFrame(channel)186204 require(request is AdoptionFrame.Request || request is AdoptionFrame.RequestV2) { "expected ADOPT_REQUEST" }205+ // §11.6: refused before any SAS prompt and before any grant. §10.3206+ // freezes the wire reason set to the two v1 peers already understand, so207+ // this is a local refusal rather than a new ADOPT_REJECT reason.208+ if (request is AdoptionFrame.Request && postReset()) {209+ onPeerOutdated()210+ return null211+ }187212 if (request is AdoptionFrame.Request && !confirm(SASDerivation.derive(noise.handshakeHash), request)) return null188213 189214 val pairState = AdoptionPairState(app/src/main/java/com/peachpasswords/sync/RelayAdoptionReceiver.kt+23 −3
@@ -16,7 +16,10 @@1616 * vault material; those enter only after the Noise NK session is established.1717 */1818 @Singleton19-class RelayAdoptionReceiver @Inject constructor() {19+class RelayAdoptionReceiver @Inject constructor(20+ private val generation: SyncGenerationPort,21+ private val deviceStore: PairedDeviceRegistry,22+) {2023 /**2124 * Phone as receiver: scan a [VaultStatus.POPULATED] invitation, dial the2225 * relay room, complete Noise, and receive the source's root key. This is@@ -34,16 +37,31 @@3437 "receiver adopt() expects a populated invitation; got ${invitation.vaultStatus}"3538 }3639 val socket = OkHttpRelaySocket.connectPairing(invitation.roomUrl())37- return adoptFromRelaySocket(40+ val adopted = adoptFromRelaySocket(3841 socket = socket,3942 invitation = invitation,4043 deps = deps,4144 confirm = confirm,4245 windowMs = windowMs,4346 )47+ markRepairProgress()48+ return adopted4449 }4550 4651 /**52+ * §11.3 REPAIRING → V2_ACTIVE. Any adoption that reaches here while this53+ * device is still anchored is a v2 one: the post-reset source refuses v1 at54+ * the first frame, and a v1 source cannot answer a v2 request.55+ */56+ private fun markRepairProgress() {57+ onDirectV2PairingEstablished(58+ generation,59+ hasDirectDevice = deviceStore.getAll().any { it.trustSource == "direct" },60+ nowMs = System.currentTimeMillis(),61+ )62+ }63+64+ /**4765 * Phone as source: scan a [VaultStatus.EMPTY] invitation from an empty4866 * device, dial the relay room, complete Noise, and hand our root key over.4967 * Symmetric to [adopt]: the initiator runs Noise NK, but the payload@@ -62,13 +80,15 @@6280 "grantFromInvitation() expects an empty invitation; got ${invitation.vaultStatus}"6381 }6482 val socket = OkHttpRelaySocket.connectPairing(invitation.roomUrl())65- return grantFromRelaySocket(83+ val granted = grantFromRelaySocket(6684 socket = socket,6785 invitation = invitation,6886 sourceDeps = sourceDeps,6987 confirm = confirm,7088 windowMs = windowMs,7189 )90+ markRepairProgress()91+ return granted7292 }7393 }7494 app/src/main/java/com/peachpasswords/sync/SyncFreshStartResetter.kt+4 −0
@@ -19,6 +19,7 @@1919 private val relaySettings: RelaySettingsStore,2020 private val backgroundSync: BackgroundSyncPreference,2121 private val lockedSyncSpool: LockedSyncSpoolStore,22+ private val generation: SyncGenerationStore,2223 ) {2324 fun reset() {2425 resetSyncStateForFreshStart(@@ -31,6 +32,7 @@3132 clearBackgroundPreference = backgroundSync::reset,3233 clearLocalIdentity = { clearDeviceIdentity(context) },3334 clearLockedSyncSpool = lockedSyncSpool::clear,35+ clearGeneration = generation::clear,3436 )3537 }3638 }@@ -45,6 +47,7 @@4547 clearBackgroundPreference: () -> Unit,4648 clearLocalIdentity: () -> Unit,4749 clearLockedSyncSpool: () -> Unit = {},50+ clearGeneration: () -> Unit = {},4851 ) {4952 stopService()5053 clearDevices()@@ -55,4 +58,5 @@5558 clearBackgroundPreference()5659 clearLocalIdentity()5760 clearLockedSyncSpool()61+ clearGeneration()5862 }app/src/main/java/com/peachpasswords/sync/SyncGeneration.kt+220 −0
@@ -0,0 +1,220 @@1+package com.peachpasswords.sync2+3+import kotlinx.serialization.Serializable4+import kotlinx.serialization.json.Json5+6+/**7+ * The durable Sync-generation state machine (protocol §11).8+ *9+ * Pure and storage-agnostic so every transition — and every crash point inside10+ * one — is unit-testable without a Keystore. [SyncGenerationStore] is the only11+ * adapter that touches storage.12+ */13+14+const val LEGACY_ACTIVE = "LEGACY_ACTIVE"15+const val RESET_REQUIRED = "RESET_REQUIRED"16+const val RESET_CONFIRMED = "RESET_CONFIRMED"17+const val V2_ANCHOR = "V2_ANCHOR"18+const val REPAIRING = "REPAIRING"19+const val V2_ACTIVE = "V2_ACTIVE"20+21+/** No record could be read or derived. Refuses sync rather than guessing a generation. */22+const val UNKNOWN_STATE = "UNKNOWN"23+24+/** User-visible outcomes. Distinct on purpose: they ask the user for different things. */25+const val RESET_REQUIRED_OUTCOME = "reset_required"26+const val RESET_NOT_COMPLETED = "reset_not_completed"27+const val PEER_PROTOCOL_OUTDATED = "peer_protocol_outdated"28+const val SYNC_GENERATION_UNKNOWN = "sync_generation_unknown"29+30+const val SYNC_GENERATION_SCHEMA_VERSION = 131+private const val LEGACY_GENERATION = 132+private const val V2_GENERATION = 233+34+@Serializable35+data class SyncGeneration(36+ val schemaVersion: Int = SYNC_GENERATION_SCHEMA_VERSION,37+ val generation: Int,38+ val state: String,39+ val anchorDeviceId: String? = null,40+ val legacyArchiveRef: String? = null,41+ val createdAt: Long,42+)43+44+/**45+ * One blob, one key. `previous` is retained so a rewrite of the active record46+ * can be validated against what it replaces, and so a crash on either side of47+ * that write is recoverable (§11.2, seal before switch).48+ */49+@Serializable50+data class SyncGenerationBlob(51+ val schemaVersion: Int = SYNC_GENERATION_SCHEMA_VERSION,52+ val active: SyncGeneration,53+ val previous: SyncGeneration? = null,54+)55+56+enum class SyncDecision { ALLOWED, RESET_REQUIRED, UNKNOWN }57+58+enum class ResetResult { V2_ANCHOR, RESET_NOT_COMPLETED }59+60+/**61+ * The storage boundary. Deliberately coarse: the trust probe is split per class62+ * so a test can assert the refusal for each one, and the archive and clear steps63+ * are separate so a crash between them is injectable.64+ */65+interface SyncGenerationPort {66+ fun readBlob(): String?67+ fun writeBlob(blob: String): Boolean68+ fun hasPairedDevices(): Boolean69+ fun hasRevocations(): Boolean70+ fun hasIssuerSigningKeys(): Boolean71+ fun hasPendingVouchedDevices(): Boolean72+ fun archiveLegacyState(generation: Int): String?73+ fun clearLegacyTrustState(): Boolean74+ fun ensureV2Identity(): Boolean75+ fun localDeviceId(): String?76+}77+78+// ignoreUnknownKeys keeps a future additive field readable; schemaVersion is79+// checked explicitly, so an unrecognised schema still resolves to UNKNOWN.80+private val json = Json { ignoreUnknownKeys = true }81+private val states = setOf(LEGACY_ACTIVE, RESET_REQUIRED, RESET_CONFIRMED, V2_ANCHOR, REPAIRING, V2_ACTIVE)82+83+private fun unknownGeneration(nowMs: Long) = SyncGeneration(84+ generation = LEGACY_GENERATION,85+ state = UNKNOWN_STATE,86+ createdAt = nowMs,87+)88+89+fun SyncGenerationPort.hasLegacyTrustState(): Boolean =90+ hasPairedDevices() || hasRevocations() || hasIssuerSigningKeys() || hasPendingVouchedDevices()91+92+/**93+ * Read the persisted record, or derive one when none has ever been written.94+ * A blob that is unreadable, of another schema, or in an unknown state is95+ * never reinterpreted: it resolves to UNKNOWN and sync stops.96+ */97+fun resolveGeneration(port: SyncGenerationPort, nowMs: Long): SyncGeneration {98+ val raw = port.readBlob()99+ if (raw != null) {100+ return runCatching {101+ json.decodeFromString<SyncGenerationBlob>(raw).takeIf { it.schemaVersion == SYNC_GENERATION_SCHEMA_VERSION }102+ ?.active103+ ?.takeIf { it.generation >= LEGACY_GENERATION && it.state in states }104+ }.getOrNull() ?: unknownGeneration(nowMs)105+ }106+107+ val hasTrustState = port.hasLegacyTrustState()108+ val derived = SyncGeneration(109+ generation = if (hasTrustState) LEGACY_GENERATION else V2_GENERATION,110+ state = if (hasTrustState) LEGACY_ACTIVE else V2_ACTIVE,111+ createdAt = nowMs,112+ )113+ return if (port.writeBlob(encodeGeneration(SyncGenerationBlob(active = derived)))) derived else unknownGeneration(nowMs)114+}115+116+/**117+ * Enter the state that blocks sync and states the migration. Reached by the118+ * user asking for a reset, and by the create-on-miss refusal. Idempotent, and119+ * never moves a device that has already reset back into the legacy generation.120+ */121+fun enterResetRequired(port: SyncGenerationPort, nowMs: Long): SyncGeneration {122+ val current = resolveGeneration(port, nowMs)123+ if (current.state != LEGACY_ACTIVE && current.state != RESET_REQUIRED) return current124+ val next = current.copy(state = RESET_REQUIRED)125+ port.writeBlob(encodeGeneration(SyncGenerationBlob(active = next, previous = current)))126+ return next127+}128+129+/**130+ * Archive the legacy generation, mint the v2 identity, then flip the pointer —131+ * in that order, so every crash point leaves either a recoverable132+ * RESET_CONFIRMED or a committed V2_ANCHOR, and never a lost archive (§11.3).133+ *134+ * The caller has already confirmed the master password. `checkpoint` fires135+ * immediately before each step that can fail; a test throws from it to inject a136+ * crash at exactly that point.137+ */138+fun confirmSecureReset(port: SyncGenerationPort, nowMs: Long, checkpoint: (String) -> Unit = {}): ResetResult {139+ val current = resolveGeneration(port, nowMs)140+ if (current.state !in setOf(LEGACY_ACTIVE, RESET_REQUIRED, RESET_CONFIRMED)) return ResetResult.RESET_NOT_COMPLETED141+142+ fun persist(state: SyncGeneration): Boolean =143+ port.writeBlob(encodeGeneration(SyncGenerationBlob(active = state, previous = current)))144+145+ checkpoint("before-confirmed")146+ if (!persist(current.copy(state = RESET_CONFIRMED))) return ResetResult.RESET_NOT_COMPLETED147+148+ checkpoint("before-archive")149+ val archiveRef = port.archiveLegacyState(current.generation) ?: return ResetResult.RESET_NOT_COMPLETED150+ checkpoint("after-archive")151+152+ checkpoint("before-clear")153+ if (!port.clearLegacyTrustState()) return ResetResult.RESET_NOT_COMPLETED154+ checkpoint("after-clear")155+156+ checkpoint("before-identity")157+ if (!port.ensureV2Identity()) return ResetResult.RESET_NOT_COMPLETED158+ checkpoint("after-identity")159+160+ val next = SyncGeneration(161+ generation = current.generation + 1,162+ state = V2_ANCHOR,163+ anchorDeviceId = port.localDeviceId(),164+ legacyArchiveRef = archiveRef,165+ createdAt = nowMs,166+ )167+ checkpoint("before-generation-write")168+ if (!port.writeBlob(encodeGeneration(SyncGenerationBlob(active = next, previous = current)))) {169+ return ResetResult.RESET_NOT_COMPLETED170+ }171+ checkpoint("after-generation-write")172+ return ResetResult.V2_ANCHOR173+}174+175+/** An anchored device stops being "not re-paired" once a direct v2 peer exists. */176+fun onDirectV2PairingEstablished(port: SyncGenerationPort, hasDirectDevice: Boolean, nowMs: Long) {177+ val current = resolveGeneration(port, nowMs)178+ if (current.state != V2_ANCHOR && current.state != REPAIRING) return179+ val next = current.copy(state = if (hasDirectDevice) V2_ACTIVE else REPAIRING)180+ runCatching { port.writeBlob(encodeGeneration(SyncGenerationBlob(active = next, previous = current))) }181+}182+183+/** Consulted before a sync session or an adoption grant is opened. */184+fun assertSyncAllowed(port: SyncGenerationPort, nowMs: Long): SyncDecision =185+ when (resolveGeneration(port, nowMs).state) {186+ LEGACY_ACTIVE, V2_ANCHOR, REPAIRING, V2_ACTIVE -> SyncDecision.ALLOWED187+ RESET_REQUIRED, RESET_CONFIRMED -> SyncDecision.RESET_REQUIRED188+ else -> SyncDecision.UNKNOWN189+ }190+191+/** The user-facing reason when sync must not start, or null when it may. */192+internal fun syncRefusalReason(port: SyncGenerationPort, nowMs: Long): SyncOutcomeReason? =193+ when (assertSyncAllowed(port, nowMs)) {194+ SyncDecision.ALLOWED -> null195+ SyncDecision.RESET_REQUIRED -> SyncOutcomeReason.RESET_REQUIRED196+ SyncDecision.UNKNOWN -> SyncOutcomeReason.SYNC_GENERATION_UNKNOWN197+ }198+199+/** True once a reset has retired the legacy generation. */200+fun SyncGenerationPort.isPostReset(nowMs: Long): Boolean =201+ resolveGeneration(this, nowMs).state in setOf(V2_ANCHOR, REPAIRING, V2_ACTIVE)202+203+enum class IdentityMintDecision { MINT, REFUSE_RESET_REQUIRED }204+205+/**206+ * Whether a missing or corrupt identity may be minted (§11.5). Split out of the207+ * Android loader so every class of trust state can be asserted without storage:208+ * a missing identity is only mintable on a genuinely fresh installation, never209+ * over any trust this device already holds.210+ */211+fun mintDecision(port: SyncGenerationPort, nowMs: Long): IdentityMintDecision =212+ if (port.hasLegacyTrustState()) {213+ enterResetRequired(port, nowMs)214+ IdentityMintDecision.REFUSE_RESET_REQUIRED215+ } else {216+ IdentityMintDecision.MINT217+ }218+219+internal fun encodeGeneration(blob: SyncGenerationBlob): String =220+ json.encodeToString(SyncGenerationBlob.serializer(), blob)app/src/main/java/com/peachpasswords/sync/SyncGenerationStore.kt+153 −0
@@ -0,0 +1,153 @@1+package com.peachpasswords.sync2+3+import android.content.Context4+import android.content.SharedPreferences5+import androidx.security.crypto.EncryptedSharedPreferences6+import androidx.security.crypto.MasterKey7+import dagger.hilt.android.EntryPointAccessors8+import dagger.hilt.android.qualifiers.ApplicationContext9+import dagger.hilt.EntryPoint10+import dagger.hilt.InstallIn11+import dagger.hilt.components.SingletonComponent12+import javax.inject.Inject13+import javax.inject.Singleton14+15+/**16+ * Storage adapter for the Sync-generation state machine.17+ *18+ * The record itself lives in plain prefs under a key no legacy build knows, so19+ * an older build cannot overwrite it and a Keystore failure cannot masquerade as20+ * a trust reset. Everything it *reads* — the paired registry, the terminal21+ * ledger, known-key history, pending holders — comes from the real stores,22+ * because those are Keystore-encrypted and a plain re-read of their file would23+ * silently see nothing.24+ */25+@Singleton26+class SyncGenerationStore @Inject constructor(27+ @ApplicationContext private val context: Context,28+ private val devices: PairedDeviceStore,29+ private val pendingDevices: PendingVouchedDeviceStore,30+ private val lockedSyncSpool: LockedSyncSpoolStore,31+) : SyncGenerationPort {32+33+ private val generationPrefs =34+ context.getSharedPreferences(GENERATION_PREFS_FILE, Context.MODE_PRIVATE)35+36+ override fun readBlob(): String? = generationPrefs.getString(KEY_GENERATION, null)37+38+ override fun writeBlob(blob: String): Boolean =39+ generationPrefs.edit().putString(KEY_GENERATION, blob).commit() && readBlob() == blob40+41+ override fun hasPairedDevices(): Boolean = devices.getAll().isNotEmpty()42+43+ override fun hasRevocations(): Boolean = devices.listRevocations().isNotEmpty()44+45+ override fun hasIssuerSigningKeys(): Boolean = devices.hasIssuerSigningKeys()46+47+ override fun hasPendingVouchedDevices(): Boolean = pendingDevices.getAll().isNotEmpty()48+49+ /**50+ * Copy the legacy trust material verbatim into an archive tagged with its51+ * generation. Encrypted with the same construction as its source: the52+ * registry carries per-pair rendezvous secrets, so a plaintext archive would53+ * downgrade them at rest.54+ *55+ * One fixed file, with the generation in every key: Android's backup rules56+ * take literal paths only, so a per-generation filename could not be57+ * excluded from cloud backup and device transfer.58+ */59+ override fun archiveLegacyState(generation: Int): String? = runCatching {60+ val archive = encryptedPrefs(context, ARCHIVE_PREFS_FILE)61+ val prefix = "g$generation:"62+ val expected = buildMap<String, Any?> {63+ put("${prefix}meta", """{"schemaVersion":1,"generation":$generation,"archivedAt":${System.currentTimeMillis()}}""")64+ for ((key, value) in devices.snapshot()) put("$prefix$ARCHIVE_DEVICES_PREFIX$key", value)65+ for ((key, value) in pendingDevices.snapshot()) put("$prefix$ARCHIVE_PENDING_PREFIX$key", value)66+ }67+ val edit = archive.edit()68+ for ((key, value) in expected) {69+ when (value) {70+ is String -> edit.putString(key, value)71+ is Set<*> -> edit.putStringSet(key, value.filterIsInstance<String>().toSet())72+ }73+ }74+ check(edit.commit()) { "generation_archive_persist_failed" }75+ check(expected.all { (key, value) -> archiveMatches(archive, key, value) }) {76+ "generation_archive_verify_failed"77+ }78+ ARCHIVE_PREFS_FILE79+ }.getOrNull()80+81+ private fun archiveMatches(archive: SharedPreferences, key: String, expected: Any?): Boolean =82+ when (expected) {83+ is String -> archive.getString(key, null) == expected84+ is Set<*> -> archive.getStringSet(key, null) == expected.filterIsInstance<String>().toSet()85+ else -> false86+ }87+88+ override fun clearLegacyTrustState(): Boolean = runCatching {89+ PeachSyncService.stop(context)90+ lockedSyncSpool.clear()91+ devices.clear()92+ pendingDevices.clear()93+ devices.getAll().isEmpty() && devices.listRevocations().isEmpty() &&94+ !devices.hasIssuerSigningKeys() && pendingDevices.getAll().isEmpty()95+ }.getOrDefault(false)96+97+ /**98+ * The reset's identity step (§11.3). Only reached at RESET_CONFIRMED, after99+ * the legacy trust has been archived and cleared, so minting here is the100+ * anchored device's own deliberate action rather than a silent replacement.101+ * The guard still refuses to mint over live trust, which is what would102+ * otherwise turn the create-on-miss refusal into a bypass.103+ */104+ override fun ensureV2Identity(): Boolean = runCatching {105+ loadOrCreateLocalIdentity(context)106+ true107+ }.recoverCatching {108+ check(!hasLegacyTrustState()) { "identity_mint_over_live_trust" }109+ rotateDeviceId(context)110+ true111+ }.getOrDefault(false)112+113+ override fun localDeviceId(): String? =114+ runCatching { loadOrCreateLocalIdentity(context).deviceId }.getOrNull()115+116+ /** Forget the generation record: only a genuinely destroyed vault reaches this. */117+ fun clear() {118+ generationPrefs.edit().clear().commit()119+ }120+121+ private companion object {122+ const val GENERATION_PREFS_FILE = "peach_sync_generation_v1"123+ const val ARCHIVE_PREFS_FILE = "peach_sync_archive_v1"124+ const val KEY_GENERATION = "sync_generation"125+ const val ARCHIVE_DEVICES_PREFIX = "paired:"126+ const val ARCHIVE_PENDING_PREFIX = "pending:"127+ }128+}129+130+/**131+ * [loadOrCreateLocalIdentity] is called from services and screens that hold no132+ * injector, so the singleton is fetched here the same way [PeachSyncService]133+ * fetches its outcome store.134+ */135+internal fun syncGenerationStore(context: Context): SyncGenerationStore =136+ EntryPointAccessors137+ .fromApplication(context.applicationContext, SyncGenerationEntryPoint::class.java)138+ .syncGenerationStore()139+140+@EntryPoint141+@InstallIn(SingletonComponent::class)142+internal interface SyncGenerationEntryPoint {143+ fun syncGenerationStore(): SyncGenerationStore144+}145+146+private fun encryptedPrefs(context: Context, name: String): SharedPreferences =147+ EncryptedSharedPreferences.create(148+ context,149+ name,150+ MasterKey.Builder(context).setKeyScheme(MasterKey.KeyScheme.AES256_GCM).build(),151+ EncryptedSharedPreferences.PrefKeyEncryptionScheme.AES256_SIV,152+ EncryptedSharedPreferences.PrefValueEncryptionScheme.AES256_GCM,153+ )app/src/main/java/com/peachpasswords/sync/SyncOutcomeReason.kt+8 −0
@@ -43,6 +43,8 @@4343 HANDSHAKE_FAILED,4444 VAULT_ID_MISMATCH,4545 PEER_PROTOCOL_OUTDATED,46+ RESET_REQUIRED,47+ SYNC_GENERATION_UNKNOWN,4648 SYNC_TIMEOUT,4749 CONNECTION_LOST,4850 RUN_FAILED,@@ -59,6 +61,8 @@5961 FOREGROUND_START_BLOCKED,6062 VAULT_ID_MISMATCH,6163 PEER_PROTOCOL_OUTDATED,64+ RESET_REQUIRED,65+ SYNC_GENERATION_UNKNOWN,6266 RUN_FAILED,6367 -> true6468 @@ -169,6 +173,10 @@169173 SyncOutcomeReason.VAULT_ID_MISMATCH -> "That device holds a different vault"170174 SyncOutcomeReason.PEER_PROTOCOL_OUTDATED ->171175 "Update Peach on both devices, then re-pair them"176+ SyncOutcomeReason.RESET_REQUIRED ->177+ "Sync is reset on this device — update Peach everywhere, then re-pair each device"178+ SyncOutcomeReason.SYNC_GENERATION_UNKNOWN ->179+ "This device's sync generation is unreadable — sync is stopped"172180 SyncOutcomeReason.SYNC_TIMEOUT -> "The device stopped responding mid-sync"173181 SyncOutcomeReason.CONNECTION_LOST -> "The connection dropped mid-sync — will retry"174182 SyncOutcomeReason.RUN_FAILED -> "Sync failed"app/src/main/java/com/peachpasswords/ui/settings/SettingsCardBodies.kt+106 −0
@@ -32,7 +32,14 @@3232 import androidx.compose.runtime.getValue3333 import com.peachpasswords.feedback.FeedbackState3434 import com.peachpasswords.shared.PeachClipboard35+import com.peachpasswords.sync.LEGACY_ACTIVE36+import com.peachpasswords.sync.REPAIRING37+import com.peachpasswords.sync.RESET_CONFIRMED38+import com.peachpasswords.sync.RESET_REQUIRED3539 import com.peachpasswords.sync.SyncMode40+import com.peachpasswords.sync.UNKNOWN_STATE41+import com.peachpasswords.sync.V2_ACTIVE42+import com.peachpasswords.sync.V2_ANCHOR3643 import com.peachpasswords.sync.canShowBackgroundSyncNotification3744 import com.peachpasswords.sync.describeSyncOutcome3845 import com.peachpasswords.sync.privateRelayDraftOf@@ -943,6 +950,44 @@943950 944951 /* ──────────────────────────────── Sync ────────────────────────────────── */945952 953+/**954+ * The §11 migration copy. It must never imply that old peers keep working: the955+ * whole point of the reset is that they cannot.956+ */957+private const val SECURE_RESET_DISCLOSURE =958+ "Peach will archive this device's old Sync trust and start the new Sync generation. " +959+ "Every other device must be updated first, then re-paired with this one — they will " +960+ "not continue on their own. Your vault and your recovery words are not changed."961+962+private fun secureResetHeadline(state: String): String = when (state) {963+ LEGACY_ACTIVE -> "Legacy Sync generation"964+ RESET_REQUIRED -> "Reset required"965+ RESET_CONFIRMED -> "Reset not completed"966+ V2_ANCHOR, REPAIRING -> "Not re-paired"967+ V2_ACTIVE -> "New Sync generation"968+ UNKNOWN_STATE -> "Sync generation unreadable"969+ else -> "Sync generation"970+}971+972+private fun secureResetDetail(state: String): String = when (state) {973+ LEGACY_ACTIVE ->974+ "This device still holds the old Sync trust. Resetting retires it for good: update " +975+ "Peach on every other device, then re-pair each one."976+ RESET_REQUIRED ->977+ "Sync is stopped until the reset completes. Update Peach on every other device, then " +978+ "reset this one and re-pair each device."979+ RESET_CONFIRMED ->980+ "The reset did not finish. Nothing was lost — the old trust is archived. Try again."981+ V2_ANCHOR, REPAIRING ->982+ "This device anchors the new Sync generation and is not re-paired yet. Pair each device " +983+ "again; until then it keeps its own vault and cannot sync."984+ V2_ACTIVE ->985+ "This device is on the new Sync generation. Each device is re-paired individually."986+ UNKNOWN_STATE ->987+ "This device's Sync generation can't be read, so sync is stopped. Reinstall or contact support."988+ else -> "Sync state is unavailable."989+}990+946991 @Composable947992 private fun SyncBody(fg: Color, onNavigate: (PeachNav) -> Unit) {948993 val context = LocalContext.current@@ -970,6 +1015,67 @@9701015 var relayUrlStatus by remember { mutableStateOf<String?>(null) }9711016 var showConnection by remember { mutableStateOf(false) }9721017 var showRecovery by remember { mutableStateOf(false) }1018+1019+ SubLabel("SECURE SYNC RESET", fg)1020+ val generation by syncVm.generationState.collectAsState()1021+ var resetOpen by remember { mutableStateOf(false) }1022+ var resetPassword by remember { mutableStateOf("") }1023+ var resetError by remember { mutableStateOf<String?>(null) }1024+ var resetting by remember { mutableStateOf(false) }1025+ val resetOffered = generation.state == LEGACY_ACTIVE ||1026+ generation.state == RESET_REQUIRED ||1027+ generation.state == RESET_CONFIRMED1028+1029+ RowLine(fg) {1030+ Column(Modifier.weight(1f)) {1031+ Text(secureResetHeadline(generation.state), color = fg, fontFamily = PeachType.Body, fontSize = 13.sp)1032+ Text(1033+ secureResetDetail(generation.state),1034+ color = fg.copy(alpha = 0.7f), fontFamily = PeachType.Body, fontSize = 11.sp, lineHeight = 16.sp,1035+ modifier = Modifier.padding(top = 2.dp),1036+ )1037+ resetError?.let {1038+ Text(it, color = peachColors.Breach, fontFamily = PeachType.Mono, fontSize = 10.sp, modifier = Modifier.padding(top = 2.dp))1039+ }1040+ }1041+ if (resetOffered) {1042+ SubtleButton("reset sync", fg) {1043+ resetError = null1044+ resetPassword = ""1045+ resetOpen = true1046+ }1047+ }1048+ }1049+1050+ if (resetOpen) {1051+ AlertDialog(1052+ onDismissRequest = { if (!resetting) resetOpen = false },1053+ title = { Text("Reset Sync on this device?", color = fg, fontFamily = PeachType.Body) },1054+ text = {1055+ Column(verticalArrangement = Arrangement.spacedBy(PeachSpacing.sm)) {1056+ Text(1057+ SECURE_RESET_DISCLOSURE,1058+ color = fg.copy(alpha = 0.8f), fontFamily = PeachType.Body, fontSize = 12.sp, lineHeight = 17.sp,1059+ )1060+ PwField("master password", resetPassword, fg) { resetPassword = it }1061+ }1062+ },1063+ confirmButton = {1064+ SubtleButton(if (resetting) "resetting..." else "reset", peachColors.Breach) {1065+ if (!resetting) scope.launch {1066+ resetting = true1067+ resetError = syncVm.confirmReset(resetPassword)1068+ resetPassword = ""1069+ resetting = false1070+ if (resetError == null) resetOpen = false1071+ }1072+ }1073+ },1074+ dismissButton = {1075+ SubtleButton("cancel", fg) { if (!resetting) resetOpen = false }1076+ },1077+ )1078+ }9731079 9741080 SubLabel("ADD A DEVICE", fg, top = 0.dp)9751081 RowLine(fg) {app/src/main/java/com/peachpasswords/ui/sync/SyncViewModel.kt+54 −0
@@ -5,7 +5,15 @@55 import androidx.lifecycle.viewModelScope66 import com.peachpasswords.sync.BackgroundSyncCoordinator77 import com.peachpasswords.sync.BackgroundSyncPreference8+import com.peachpasswords.sync.RESET_NOT_COMPLETED9+import com.peachpasswords.sync.ResetResult10+import com.peachpasswords.sync.SyncGeneration11+import com.peachpasswords.sync.SyncGenerationStore812 import com.peachpasswords.sync.SyncVaultAdapter13+import com.peachpasswords.sync.confirmSecureReset14+import com.peachpasswords.sync.enterResetRequired15+import com.peachpasswords.sync.resolveGeneration16+import com.peachpasswords.sync.syncAllowedNow917 import com.peachpasswords.sync.PairedDevice1018 import com.peachpasswords.sync.PairedDeviceStore1119 import com.peachpasswords.sync.PendingVouchedDevice@@ -29,9 +37,11 @@2937 import kotlinx.coroutines.flow.asStateFlow3038 import kotlinx.coroutines.flow.combine3139 import kotlinx.coroutines.flow.stateIn40+import kotlinx.coroutines.Dispatchers3241 import kotlinx.coroutines.delay3342 import kotlinx.coroutines.Job3443 import kotlinx.coroutines.launch44+import kotlinx.coroutines.withContext3545 import javax.inject.Inject3646 3747 /**@@ -55,6 +65,7 @@5565 private val backgroundSync: BackgroundSyncPreference,5666 private val relaySettings: RelaySettingsStore,5767 private val syncOutcomes: SyncOutcomeStore,68+ private val generation: SyncGenerationStore,5869 ) : ViewModel() {5970 6071 /** The last sync attempt, whatever it was. Survives process death. */@@ -83,6 +94,7 @@8394 isUnlocked = vault.isUnlocked,8495 preferenceEnabled = backgroundSync.enabled,8596 syncVaultId = vault::syncVaultId,97+ syncAllowed = { syncAllowedNow(generation) },8698 )8799 88100 init {@@ -213,6 +225,7 @@213225 /** Adapter over the live vault; null while the vault is locked. */214226 fun buildAdapter(): SyncVaultAdapter? {215227 if (!vault.isUnlocked.value || isDecoySession()) return null228+ if (!syncAllowedNow(generation)) return null216229 val credentials = loadOrCreateLocalIdentity(context)217230 return VaultSyncAdapter(218231 repo = vault,@@ -222,6 +235,47 @@222235 syncAlerts = syncAlertStore,223236 localCredentials = credentials,224237 )238+ }239+240+ /**241+ * The §11 migration panel: what this device's Sync generation is, and what242+ * it still owes the user. Not secret — it is a version and a state name —243+ * so a decoy session shows the same thing without leaking anything.244+ */245+ private val _generationState = MutableStateFlow(generationRecord())246+ val generationState: StateFlow<SyncGeneration> = _generationState.asStateFlow()247+248+ private fun generationRecord(): SyncGeneration = resolveGeneration(generation, System.currentTimeMillis())249+250+ /**251+ * Enter the state that blocks sync, then run the migration. Entry is252+ * separate from confirmation so a crash between them leaves the device253+ * refusing sync rather than mid-reset with trust still live (§11.3).254+ *255+ * The master password confirms a trust-resetting action (§11.9), then the256+ * archive → identity → pointer-flip sequence runs in that order. Returns257+ * null on success, or the line to show the user.258+ */259+ suspend fun confirmReset(masterPassword: String): String? {260+ if (isDecoySession()) return "Reset is unavailable in this session"261+ if (masterPassword.isBlank()) return "Enter your master password"262+ val masterMatches = withContext(Dispatchers.Default) {263+ vault.tryUnlockSlotA(masterPassword)?.let {264+ vault.discardSlotAUnlock(it)265+ true266+ } ?: false267+ }268+ if (!masterMatches) return "Incorrect master password"269+ val result = withContext(Dispatchers.Default) {270+ _generationState.value = enterResetRequired(generation, System.currentTimeMillis())271+ confirmSecureReset(generation, System.currentTimeMillis())272+ }273+ _generationState.value = generationRecord()274+ return when (result) {275+ ResetResult.V2_ANCHOR -> null276+ ResetResult.RESET_NOT_COMPLETED ->277+ "The reset did not complete — nothing was lost, try again ($RESET_NOT_COMPLETED)"278+ }225279 }226280 227281 /**app/src/main/res/xml/backup_rules.xml+2 −0
@@ -24,4 +24,6 @@2424 <exclude domain="sharedpref" path="peach_sync_alerts.xml" />2525 <exclude domain="sharedpref" path="peach_locked_sync_spool_v1.xml" />2626 <exclude domain="sharedpref" path="peach_local_identity_v2.xml" />27+ <exclude domain="sharedpref" path="peach_sync_generation_v1.xml" />28+ <exclude domain="sharedpref" path="peach_sync_archive_v1.xml" />2729 </full-backup-content>app/src/main/res/xml/data_extraction_rules.xml+4 −0
@@ -25,6 +25,8 @@2525 <exclude domain="sharedpref" path="peach_sync_alerts.xml" />2626 <exclude domain="sharedpref" path="peach_locked_sync_spool_v1.xml" />2727 <exclude domain="sharedpref" path="peach_local_identity_v2.xml" />28+ <exclude domain="sharedpref" path="peach_sync_generation_v1.xml" />29+ <exclude domain="sharedpref" path="peach_sync_archive_v1.xml" />2830 </cloud-backup>2931 <device-transfer>3032 <exclude domain="sharedpref" path="peach_vault_store.xml" />@@ -46,5 +48,7 @@4648 <exclude domain="sharedpref" path="peach_sync_alerts.xml" />4749 <exclude domain="sharedpref" path="peach_locked_sync_spool_v1.xml" />4850 <exclude domain="sharedpref" path="peach_local_identity_v2.xml" />51+ <exclude domain="sharedpref" path="peach_sync_generation_v1.xml" />52+ <exclude domain="sharedpref" path="peach_sync_archive_v1.xml" />4953 </device-transfer>5054 </data-extraction-rules>app/src/test/java/com/peachpasswords/sync/FakeSyncGeneration.kt+105 −0
@@ -0,0 +1,105 @@1+package com.peachpasswords.sync2+3+/**4+ * In-memory [SyncGenerationPort] for the JVM tests. Doubles as the crash seam:5+ * [crashAt] makes the matching checkpoint throw, and [archive] / [cleared]6+ * record what survived so a test can assert no trust material was lost.7+ */8+internal class FakeSyncGeneration(9+ var pairedDevices: Boolean = false,10+ var revocations: Boolean = false,11+ var issuerSigningKeys: Boolean = false,12+ var pendingVouchedDevices: Boolean = false,13+) : SyncGenerationPort {14+15+ var blob: String? = null16+ private set17+18+ /** Writes that report failure, to model storage that cannot land the record. */19+ var failWrites: Boolean = false20+21+ /** Simulated process death: the checkpoint with this name throws. */22+ var crashAt: String? = null23+24+ var archiveRef: String? = null25+ private set26+ var archiveCount: Int = 027+ private set28+ var cleared: Boolean = false29+ private set30+ var failArchive: Boolean = false31+ var failClear: Boolean = false32+ var failIdentity: Boolean = false33+ var identityMints: Int = 034+ private set35+ var deviceId: String? = "anchor-device"36+37+ /** The order the reset actually touched storage, for the ordering assertion. */38+ val calls = mutableListOf<String>()39+40+ val record: SyncGeneration?41+ get() = blob?.let {42+ runCatching { jsonForTest.decodeFromString<SyncGenerationBlob>(it).active }.getOrNull()43+ }44+45+ override fun readBlob(): String? = blob46+47+ override fun writeBlob(blob: String): Boolean {48+ if (failWrites) return false49+ this.blob = blob50+ return true51+ }52+53+ override fun hasPairedDevices() = pairedDevices54+55+ override fun hasRevocations() = revocations56+57+ override fun hasIssuerSigningKeys() = issuerSigningKeys58+59+ override fun hasPendingVouchedDevices() = pendingVouchedDevices60+61+ override fun archiveLegacyState(generation: Int): String? {62+ if (failArchive) return null63+ archiveCount++64+ archiveRef = "peach_sync_archive_v1"65+ calls += "archive:$generation"66+ return archiveRef67+ }68+69+ override fun clearLegacyTrustState(): Boolean {70+ if (failClear) return false71+ cleared = true72+ pairedDevices = false73+ revocations = false74+ issuerSigningKeys = false75+ pendingVouchedDevices = false76+ calls += "clear"77+ return true78+ }79+80+ override fun ensureV2Identity(): Boolean {81+ if (failIdentity) return false82+ identityMints++83+ calls += "identity"84+ return true85+ }86+87+ override fun localDeviceId(): String? = deviceId88+89+ /** Runs [confirmSecureReset] so a checkpoint in [crashAt] throws as a crash would. */90+ fun reset(nowMs: Long = 1_000L): ResetResult = confirmSecureReset(this, nowMs) { name ->91+ if (name == crashAt) throw SimulatedCrash(name)92+ }93+94+ class SimulatedCrash(name: String) : RuntimeException("crash at $name")95+}96+97+private val jsonForTest = kotlinx.serialization.json.Json { ignoreUnknownKeys = true }98+99+/** The minimum registry the adoption dispatch paths need: nothing paired. */100+internal object EmptyRegistry : PairedDeviceRegistry {101+ override fun getAll(): List<PairedDevice> = emptyList()102+ override fun get(id: String): PairedDevice? = null103+ override fun upsert(device: PairedDevice) = Unit104+ override fun applyManifestBatch(batch: DeviceManifestRegistryBatch): Boolean = true105+}app/src/test/java/com/peachpasswords/sync/RelayAdoptionHostTest.kt+120 −0
@@ -228,6 +228,126 @@228228 assertFalse(rootRequested.get())229229 }230230 231+ @Test fun `a pre-reset source still runs the v1 transcript`() = runBlocking {232+ val (sourceSocket, receiverSocket) = socketPair()233+ val token = "AAECAwQFBgcICQoLDA0ODw"234+ val root = ByteArray(32) { (it + 9).toByte() }235+ val sourceKeys = localSyncKeypair(randomLocalIdentityCredentials("source-id"))236+ val rootRequested = AtomicBoolean(false)237+ val prompted = AtomicBoolean(false)238+ val outdated = AtomicBoolean(false)239+240+ val sourceJob = async {241+ sourceSession(242+ socket = sourceSocket,243+ token = token,244+ root = root,245+ sourceKeys = sourceKeys,246+ rootRequested = rootRequested,247+ confirm = { _, _ -> prompted.set(true); false },248+ postReset = { false },249+ onPeerOutdated = { outdated.set(true) },250+ )251+ }252+ receiverSocket.send(253+ JSONObject().put("type", "PEACH_HELLO").put("token", token)254+ .toString().toByteArray(),255+ )256+ val ack = JSONObject(String(receiverSocket.receive()))257+ val noise = noiseNKInitiator(258+ hexToPubkey(ack.getString("ephemeralPublicKeyHex")),259+ receiverSocket::send,260+ receiverSocket::receive,261+ )262+ val channel = encryptedChannel(receiverSocket, noise)263+ sendFrame(channel, AdoptionFrame.Request("session-request", "receiver", "extension"))264+265+ assertNull(sourceJob.await())266+ assertTrue("v1 is still offered before a reset", prompted.get())267+ assertFalse("v1 is not an outdated peer before a reset", outdated.get())268+ assertFalse("a declined prompt never reads the root", rootRequested.get())269+ }270+271+ @Test fun `a post-reset source refuses v1 before any prompt or grant`() = runBlocking {272+ val (sourceSocket, receiverSocket) = socketPair()273+ val token = "AAECAwQFBgcICQoLDA0ODw"274+ val root = ByteArray(32) { (it + 13).toByte() }275+ val sourceKeys = localSyncKeypair(randomLocalIdentityCredentials("source-id"))276+ val rootRequested = AtomicBoolean(false)277+ val prompted = AtomicBoolean(false)278+ val outdated = AtomicBoolean(false)279+280+ val sourceJob = async {281+ sourceSession(282+ socket = sourceSocket,283+ token = token,284+ root = root,285+ sourceKeys = sourceKeys,286+ rootRequested = rootRequested,287+ confirm = { _, _ -> prompted.set(true); true },288+ postReset = { true },289+ onPeerOutdated = { outdated.set(true) },290+ )291+ }292+ receiverSocket.send(293+ JSONObject().put("type", "PEACH_HELLO").put("token", token)294+ .toString().toByteArray(),295+ )296+ val ack = JSONObject(String(receiverSocket.receive()))297+ val noise = noiseNKInitiator(298+ hexToPubkey(ack.getString("ephemeralPublicKeyHex")),299+ receiverSocket::send,300+ receiverSocket::receive,301+ )302+ val channel = encryptedChannel(receiverSocket, noise)303+ sendFrame(channel, AdoptionFrame.Request("session-request", "receiver", "extension"))304+305+ assertNull(sourceJob.await())306+ assertTrue("the refusal must be reported as an outdated peer", outdated.get())307+ assertFalse("no SAS prompt for a peer that is refused", prompted.get())308+ assertFalse("the root must never be read for a refused peer", rootRequested.get())309+ }310+311+ /** Runs the production source session with only the deps these two cases need. */312+ private suspend fun sourceSession(313+ socket: RelayBinarySocket,314+ token: String,315+ root: ByteArray,316+ sourceKeys: SyncIdentityKeypair,317+ rootRequested: AtomicBoolean,318+ confirm: suspend (String, AdoptionFrame.Request) -> Boolean,319+ postReset: () -> Boolean,320+ onPeerOutdated: () -> Unit,321+ ): PairedDevice? = runRelayAdoptionSourceSession(322+ socket,323+ token,324+ "wss://relay.example.test",325+ sourceKeys.secretKey,326+ sourceKeys.publicKey,327+ identity("source", sourceKeys.publicKey),328+ object : AdoptionSourceV2Deps {329+ override suspend fun rotateSourceIdentity() = sourceIdentity330+ override fun hasDeviceIdentityCollision(device: PairedDevice) = false331+ override suspend fun persistPendingIdentity(device: PairedDevice, nowMs: Long) = true332+ override suspend fun completePendingIdentity(device: PairedDevice) = true333+ override fun snapshotCapable() = true334+335+ override val sourceIdentity = identity("source", sourceKeys.publicKey)336+ override suspend fun rootKeyHex(): String {337+ rootRequested.set(true)338+ return Rendezvous.bytesToHex(root)339+ }340+341+ override suspend fun vaultId() = computeVaultId(root)342+ override suspend fun onConsent(request: AdoptionFrame.Request) = true343+ override suspend fun onConsent(request: AdoptionFrame.RequestV2) = true344+ override suspend fun upsertPairedDevice(device: PairedDevice) = Unit345+ },346+ confirm = confirm,347+ postReset = postReset,348+ onPeerOutdated = onPeerOutdated,349+ )350+231351 @Test fun `receiver session completes real Noise adoption with matching pair state`() = runBlocking {232352 val (sourceSocket, receiverSocket) = socketPair()233353 val token = "AAECAwQFBgcICQoLDA0ODw"app/src/test/java/com/peachpasswords/sync/RelayAdoptionInitiatorSourceTest.kt+2 −2
@@ -506,7 +506,7 @@506506 class RelayAdoptionReceiverDispatchTest {507507 508508 @Test fun `adopt rejects empty invitations so the source path is used instead`() = runBlocking {509- val receiver = RelayAdoptionReceiver()509+ val receiver = RelayAdoptionReceiver(FakeSyncGeneration(), EmptyRegistry)510510 val empty = createPairingInvitation(511511 "wss://relay.example.test",512512 "AAECAwQFBgcICQoLDA0ODw",@@ -542,7 +542,7 @@542542 }543543 544544 @Test fun `grantFromInvitation rejects populated invitations so the receiver path is used instead`() = runBlocking {545- val receiver = RelayAdoptionReceiver()545+ val receiver = RelayAdoptionReceiver(FakeSyncGeneration(), EmptyRegistry)546546 val populated = createPairingInvitation(547547 "wss://relay.example.test",548548 "AAECAwQFBgcICQoLDA0ODw",app/src/test/java/com/peachpasswords/sync/SyncGenerationTest.kt+316 −0
@@ -0,0 +1,316 @@1+package com.peachpasswords.sync2+3+import org.junit.Assert.assertEquals4+import org.junit.Assert.assertFalse5+import org.junit.Assert.assertNotNull6+import org.junit.Assert.assertNull7+import org.junit.Assert.assertTrue8+import org.junit.Assert.fail9+import org.junit.Test10+11+/**12+ * The §11 secure-reset contract: the durable generation record, the six states,13+ * create-on-miss refusal, archival by generation, crash recovery at every step,14+ * and the sync gate. Runs entirely against [FakeSyncGeneration] — no Keystore,15+ * no Context, no Hilt.16+ */17+class SyncGenerationTest {18+19+ private val checkpointNames = listOf(20+ "before-confirmed",21+ "before-archive",22+ "after-archive",23+ "before-clear",24+ "after-clear",25+ "before-identity",26+ "after-identity",27+ "before-generation-write",28+ "after-generation-write",29+ )30+31+ // --- derived state -------------------------------------------------------------------32+33+ @Test34+ fun `fresh install derives V2_ACTIVE at generation 2 and persists it`() {35+ val port = FakeSyncGeneration()36+37+ val record = resolveGeneration(port, 1_000L)38+39+ assertEquals(V2_ACTIVE, record.state)40+ assertEquals(2, record.generation)41+ assertEquals(record, port.record)42+ }43+44+ @Test45+ fun `existing trust state derives LEGACY_ACTIVE at generation 1`() {46+ val port = FakeSyncGeneration(pairedDevices = true)47+48+ val record = resolveGeneration(port, 1_000L)49+50+ assertEquals(LEGACY_ACTIVE, record.state)51+ assertEquals(1, record.generation)52+ assertEquals(record, port.record)53+ }54+55+ @Test56+ fun `an unreadable record resolves to UNKNOWN rather than to a generation`() {57+ val port = FakeSyncGeneration()58+ port.writeBlob("{ not json")59+60+ assertEquals(UNKNOWN_STATE, resolveGeneration(port, 1_000L).state)61+ }62+63+ @Test64+ fun `a record this build does not understand refuses sync instead of misreading it`() {65+ // The rollback case: a build that does not know the generation must not66+ // treat v2 state as legacy trust.67+ val port = FakeSyncGeneration()68+ port.writeBlob("""{"schemaVersion":99,"active":{"schemaVersion":99,"generation":7,"state":"V2_ACTIVE","createdAt":1}}""")69+70+ assertEquals(UNKNOWN_STATE, resolveGeneration(port, 1_000L).state)71+ assertEquals(SyncDecision.UNKNOWN, assertSyncAllowed(port, 1_000L))72+ }73+74+ @Test75+ fun `an unknown state string refuses sync instead of guessing`() {76+ val port = FakeSyncGeneration()77+ port.writeBlob("""{"schemaVersion":1,"active":{"schemaVersion":1,"generation":1,"state":"WOBBLING","createdAt":1}}""")78+79+ assertEquals(SyncDecision.UNKNOWN, assertSyncAllowed(port, 1_000L))80+ }81+82+ // --- create-on-miss refusal (§11.5) --------------------------------------------------83+84+ @Test85+ fun `create-on-miss is refused for every class of trust state`() {86+ val classes = mapOf(87+ "paired device" to FakeSyncGeneration(pairedDevices = true),88+ "revocation" to FakeSyncGeneration(revocations = true),89+ "known-key history" to FakeSyncGeneration(issuerSigningKeys = true),90+ "pending holder" to FakeSyncGeneration(pendingVouchedDevices = true),91+ )92+93+ for ((label, port) in classes) {94+ assertEquals(95+ "minting must be refused over a $label",96+ IdentityMintDecision.REFUSE_RESET_REQUIRED,97+ mintDecision(port, 1_000L),98+ )99+ assertEquals("$label must leave the device in RESET_REQUIRED", RESET_REQUIRED, port.record?.state)100+ assertEquals("$label must not mint an identity", 0, port.identityMints)101+ assertEquals("$label must block sync", SyncDecision.RESET_REQUIRED, assertSyncAllowed(port, 1_000L))102+ }103+ }104+105+ @Test106+ fun `create-on-miss mints only on a genuinely fresh installation`() {107+ val port = FakeSyncGeneration()108+109+ assertEquals(IdentityMintDecision.MINT, mintDecision(port, 1_000L))110+ assertNull("a fresh install writes no reset state", port.record)111+ }112+113+ // --- the reset itself ----------------------------------------------------------------114+115+ @Test116+ fun `reset archives, clears, mints, then flips the pointer — in that order`() {117+ val port = FakeSyncGeneration(pairedDevices = true, revocations = true)118+119+ assertEquals(ResetResult.V2_ANCHOR, port.reset())120+121+ assertEquals(listOf("archive:1", "clear", "identity"), port.calls)122+ val record = port.record!!123+ assertEquals(V2_ANCHOR, record.state)124+ assertEquals(2, record.generation)125+ assertEquals("anchor-device", record.anchorDeviceId)126+ assertEquals("peach_sync_archive_v1", record.legacyArchiveRef)127+ assertTrue(port.cleared)128+ }129+130+ @Test131+ fun `reset is idempotent from RESET_CONFIRMED and keeps the same archive`() {132+ val port = FakeSyncGeneration(pairedDevices = true)133+ port.reset()134+135+ val firstArchive = port.record!!.legacyArchiveRef136+ // A second attempt from a committed V2_ANCHOR must not retire the v2137+ // generation or mint a second identity.138+ assertEquals(ResetResult.RESET_NOT_COMPLETED, port.reset())139+ assertEquals(firstArchive, port.record!!.legacyArchiveRef)140+ assertEquals(1, port.identityMints)141+ }142+143+ @Test144+ fun `a failing step stays in RESET_CONFIRMED and reports reset not completed`() {145+ val failures = listOf<(FakeSyncGeneration) -> Unit>(146+ { it.failArchive = true },147+ { it.failClear = true },148+ { it.failIdentity = true },149+ )150+151+ for (configure in failures) {152+ val port = FakeSyncGeneration(pairedDevices = true)153+ configure(port)154+155+ assertEquals(ResetResult.RESET_NOT_COMPLETED, port.reset())156+ assertEquals(RESET_CONFIRMED, port.record?.state)157+ assertEquals(SyncDecision.RESET_REQUIRED, assertSyncAllowed(port, 1_000L))158+ }159+ }160+161+ @Test162+ fun `a record that cannot be persisted is not trusted as a generation`() {163+ val port = FakeSyncGeneration(pairedDevices = true)164+ port.failWrites = true165+166+ val record = resolveGeneration(port, 1_000L)167+168+ assertEquals("a derived record that did not persist must not be trusted", UNKNOWN_STATE, record.state)169+ assertEquals(SyncDecision.UNKNOWN, assertSyncAllowed(port, 1_000L))170+ }171+172+ // --- crash injection (§11.8) ---------------------------------------------------------173+174+ @Test175+ fun `a crash at any step leaves the archive durable and the retry reaches V2_ANCHOR`() {176+ for (name in checkpointNames) {177+ val port = FakeSyncGeneration(pairedDevices = true)178+ port.crashAt = name179+180+ try {181+ port.reset()182+ fail("expected a simulated crash at $name")183+ } catch (expected: FakeSyncGeneration.SimulatedCrash) {184+ assertEquals(name, expected.message!!.removePrefix("crash at "))185+ }186+187+ // Never a wrong outcome: either nothing was retired yet, or the188+ // reset is mid-flight, or it committed. Never a lost archive.189+ val state = port.record?.state190+ assertTrue(191+ "crash at $name left $state",192+ state == LEGACY_ACTIVE || state == RESET_CONFIRMED || state == V2_ANCHOR,193+ )194+ assertFalse(195+ "crash at $name cleared live trust without an archive",196+ port.cleared && port.archiveCount == 0,197+ )198+199+ // A retry must finish the job.200+ port.crashAt = null201+ port.reset()202+ assertEquals("retry after a crash at $name", V2_ANCHOR, port.record?.state)203+ assertEquals(2, port.record?.generation)204+ assertNotNull(port.archiveRef)205+ }206+ }207+208+ @Test209+ fun `a crash before the pointer flip blocks sync and a crash after it allows it`() {210+ val before = FakeSyncGeneration(pairedDevices = true)211+ before.crashAt = "before-generation-write"212+ runCatching { before.reset() }213+ assertEquals(RESET_CONFIRMED, before.record?.state)214+ assertEquals(SyncDecision.RESET_REQUIRED, assertSyncAllowed(before, 1_000L))215+216+ val after = FakeSyncGeneration(pairedDevices = true)217+ after.crashAt = "after-generation-write"218+ runCatching { after.reset() }219+ assertEquals(V2_ANCHOR, after.record?.state)220+ assertEquals(SyncDecision.ALLOWED, assertSyncAllowed(after, 1_000L))221+ assertNotNull("the archive must be durable before the flip", after.archiveRef)222+ assertEquals(1, after.identityMints)223+ }224+225+ @Test226+ fun `a crash after the archive but before the clear loses nothing`() {227+ val port = FakeSyncGeneration(pairedDevices = true, revocations = true)228+ port.crashAt = "before-clear"229+ runCatching { port.reset() }230+231+ assertEquals("the archive is already durable", 1, port.archiveCount)232+ assertFalse("the live stores are untouched", port.cleared)233+ assertTrue("the trust state is still there to archive again", port.hasLegacyTrustState())234+ }235+236+ // --- the sync gate (§7) --------------------------------------------------------------237+238+ @Test239+ fun `a device that has already reset is allowed to sync and pair again`() {240+ val port = FakeSyncGeneration(pairedDevices = true)241+ port.reset()242+243+ assertEquals(SyncDecision.ALLOWED, assertSyncAllowed(port, 1_000L))244+ assertTrue(port.isPostReset(1_000L))245+ }246+247+ @Test248+ fun `a legacy device may still sync before it resets`() {249+ val port = FakeSyncGeneration(pairedDevices = true)250+251+ assertEquals(SyncDecision.ALLOWED, assertSyncAllowed(port, 1_000L))252+ assertFalse("legacy sync is not post-reset", port.isPostReset(1_000L))253+ }254+255+ @Test256+ fun `enterResetRequired blocks sync and never walks a reset device backwards`() {257+ val legacy = FakeSyncGeneration(pairedDevices = true)258+ assertEquals(RESET_REQUIRED, enterResetRequired(legacy, 1_000L).state)259+ assertEquals(SyncDecision.RESET_REQUIRED, assertSyncAllowed(legacy, 1_000L))260+261+ val reset = FakeSyncGeneration(pairedDevices = true)262+ reset.reset()263+ assertEquals("a reset device is not put back into the legacy generation", V2_ANCHOR, enterResetRequired(reset, 1_000L).state)264+ }265+266+ // --- repair progression (§11.3) ------------------------------------------------------267+268+ @Test269+ fun `an anchored device is REPAIRING until a direct peer exists, then V2_ACTIVE`() {270+ val port = FakeSyncGeneration(pairedDevices = true)271+ port.reset()272+273+ onDirectV2PairingEstablished(port, hasDirectDevice = false, nowMs = 2_000L)274+ assertEquals(REPAIRING, port.record?.state)275+ assertTrue("still not re-paired", port.isPostReset(2_000L))276+277+ onDirectV2PairingEstablished(port, hasDirectDevice = true, nowMs = 3_000L)278+ assertEquals(V2_ACTIVE, port.record?.state)279+ }280+281+ @Test282+ fun `pairing progress never disturbs a device that never reset`() {283+ val port = FakeSyncGeneration(pairedDevices = true)284+285+ onDirectV2PairingEstablished(port, hasDirectDevice = true, nowMs = 2_000L)286+287+ assertEquals(LEGACY_ACTIVE, port.record?.state)288+ }289+290+ // --- §15.4: the reset retires the generation, it does not rotate the root -------------291+292+ @Test293+ fun `the reset retires the legacy generation without touching vault or recovery material`() {294+ val port = FakeSyncGeneration(pairedDevices = true, revocations = true, issuerSigningKeys = true)295+296+ assertEquals(ResetResult.V2_ANCHOR, port.reset())297+298+ // The port is the whole surface the reset can reach. It carries no root299+ // key, no recovery material, and no vault-id parameter, so no rotation300+ // is possible by construction; assert the ordering that makes the301+ // archive safe instead.302+ assertEquals(listOf("archive:1", "clear", "identity"), port.calls)303+ assertEquals("the archive names the retired generation", "peach_sync_archive_v1", port.record?.legacyArchiveRef)304+ assertEquals("the live generation is the new one", 2, port.record?.generation)305+ }306+307+ // --- message vocabulary --------------------------------------------------------------308+309+ @Test310+ fun `the three reset outcomes stay distinct`() {311+ assertEquals(setOf("reset_required", "reset_not_completed", "peer_protocol_outdated", "sync_generation_unknown"),312+ setOf(RESET_REQUIRED_OUTCOME, RESET_NOT_COMPLETED, PEER_PROTOCOL_OUTDATED, SYNC_GENERATION_UNKNOWN))313+ assertEquals(RESET_REQUIRED_OUTCOME, SyncOutcomeReason.RESET_REQUIRED.wire())314+ assertEquals(SYNC_GENERATION_UNKNOWN, SyncOutcomeReason.SYNC_GENERATION_UNKNOWN.wire())315+ }316+}app/src/test/java/com/peachpasswords/sync/SyncOutcomeTest.kt+4 −0
@@ -51,6 +51,10 @@5151 SyncOutcomeReason.FOREGROUND_START_BLOCKED,5252 SyncOutcomeReason.VAULT_ID_MISMATCH,5353 SyncOutcomeReason.PEER_PROTOCOL_OUTDATED,54+ // §11: a device that owes a secure reset, or whose generation55+ // cannot be read, has not synced and must be told so.56+ SyncOutcomeReason.RESET_REQUIRED,57+ SyncOutcomeReason.SYNC_GENERATION_UNKNOWN,5458 SyncOutcomeReason.RUN_FAILED,5559 ),5660 SyncOutcomeReason.entries.filter { it.isFailure }.toSet(),