386cd7dfe00d
align Sync protocol v3 parity and freeze the versioned local identity schema (wip: 4 pre-existing manifest/revocation tests still fail)
- time
- 2026-09-10 17:06 UTC · 2 months ago
- machine
- koh2
- agent
- deepseek/deepseek-v4-flash
- session
- cross-client remediation
- parent
- 66c44da81b2d
↓ peach-android-386cd7df.tar.gzatlas at this save
files changed13 files
VERSION+1 −1app/src/main/java/com/peachpasswords/sync/DeviceIdentity.kt+41 −36app/src/main/java/com/peachpasswords/sync/LocalIdentityRecord.kt+121 −0app/src/main/java/com/peachpasswords/sync/SyncCoordinator.kt+36 −9app/src/main/java/com/peachpasswords/sync/SyncIdentity.kt+0 −36app/src/main/java/com/peachpasswords/sync/SyncOutcomeReason.kt+2 −1app/src/main/res/xml/backup_rules.xml+1 −0app/src/main/res/xml/data_extraction_rules.xml+2 −0app/src/test/java/com/peachpasswords/sync/LegacyIdentityDerivation.kt+62 −0app/src/test/java/com/peachpasswords/sync/LocalIdentityRecordTest.kt+107 −0app/src/test/java/com/peachpasswords/sync/RelayAdoptionInitiatorSourceTest.kt+12 −12app/src/test/java/com/peachpasswords/sync/SyncCoordinatorTest.kt+66 −3app/src/test/java/com/peachpasswords/sync/SyncOutcomeTest.kt+1 −1app/src/main/java/com/peachpasswords/sync/DeviceIdentity.kt+41 −36
@@ -8,7 +8,6 @@88 import com.peachpasswords.vault.VaultCrypto99 1010 private const val LOCAL_IDENTITY_PREFS = "peach_local_identity_v2"11-private const val LOCAL_IDENTITY_VERSION = 21211 1312 private fun secureIdentityPrefs(context: Context) = EncryptedSharedPreferences.create(1413 context,@@ -18,34 +17,51 @@1817 EncryptedSharedPreferences.PrefValueEncryptionScheme.AES256_GCM,1918 )2019 21-/** Loads the canonical random identity, creating it once under Keystore protection. */20+/**21+ * Loads the canonical random identity, creating it once under Keystore22+ * protection. A record that is absent, partial, of an unknown version, or23+ * inconsistent between its private and stored public values fails closed with24+ * `identity_migration_required`; it is never regenerated underneath an existing25+ * installation. The schema and its consistency rules live in [readIdentityRecord].26+ */2227 fun loadOrCreateLocalIdentity(context: Context): LocalIdentityCredentials {23- val prefs = secureIdentityPrefs(context)24- check(prefs.getInt("version", LOCAL_IDENTITY_VERSION) == LOCAL_IDENTITY_VERSION) {25- "identity_migration_required"28+ val stored: Map<String, Any?> = try {29+ secureIdentityPrefs(context).all30+ } catch (_: Exception) {31+ throw IllegalStateException("identity_migration_required")2632 }27- val id = prefs.getString("device_id", null)28- val xHex = prefs.getString("x25519_private", null)29- val eHex = prefs.getString("ed25519_seed", null)30- if (id != null || xHex != null || eHex != null) {31- require(!id.isNullOrBlank() && xHex != null && eHex != null) { "identity_migration_required" }32- require(xHex.matches(Regex("^[0-9a-fA-F]{64}$")) && eHex.matches(Regex("^[0-9a-fA-F]{64}$"))) {33- "identity_migration_required"33+ return when (val record = readIdentityRecord(stored)) {34+ is IdentityRecord.Absent -> {35+ val fresh = randomLocalIdentityCredentials(UUID.randomUUID().toString())36+ persistIdentity(context, fresh, System.currentTimeMillis())37+ fresh3438 }35- val x = hexToBytes(xHex)36- val e = hexToBytes(eHex)37- val xp = org.bouncycastle.crypto.params.X25519PrivateKeyParameters(x, 0)38- val ep = org.bouncycastle.crypto.params.Ed25519PrivateKeyParameters(e, 0)39- return LocalIdentityCredentials(id, x, xp.generatePublicKey().encoded, e, ep.generatePublicKey().encoded)39+ is IdentityRecord.LegacyRandom -> {40+ // Same private material, missing stored public values and creation41+ // time: complete the record without changing the identity.42+ persistIdentity(context, record.credentials, System.currentTimeMillis())43+ record.credentials44+ }45+ is IdentityRecord.Current -> record.credentials46+ IdentityRecord.Invalid -> throw IllegalStateException("identity_migration_required")4047 }41- val fresh = randomLocalIdentityCredentials(UUID.randomUUID().toString())42- check(prefs.edit().putInt("version", LOCAL_IDENTITY_VERSION)43- .putString("device_id", fresh.deviceId)44- .putString("x25519_private", pubkeyToHex(fresh.x25519PrivateKey))45- .putString("ed25519_seed", pubkeyToHex(fresh.ed25519Seed)).commit()) {46- "identity_persist_failed"48+}49+50+private fun persistIdentity(51+ context: Context,52+ credentials: LocalIdentityCredentials,53+ createdAt: Long,54+) {55+ val editor = secureIdentityPrefs(context).edit()56+ for ((key, value) in identityRecordFields(credentials, createdAt)) {57+ when (value) {58+ is Int -> editor.putInt(key, value)59+ is Long -> editor.putLong(key, value)60+ is String -> editor.putString(key, value)61+ else -> error("unsupported identity record field: $key")62+ }4763 }48- return fresh64+ check(editor.commit()) { "identity_persist_failed" }4965 }5066 5167 // The persisted names below are retained for device-name migration only.@@ -75,14 +91,7 @@7591 /** Replace the local identity after an authenticated peer detects a collision. */7692 fun rotateDeviceId(context: Context): String {7793 val fresh = randomLocalIdentityCredentials(UUID.randomUUID().toString())78- check(secureIdentityPrefs(context).edit()79- .putInt("version", LOCAL_IDENTITY_VERSION)80- .putString("device_id", fresh.deviceId)81- .putString("x25519_private", pubkeyToHex(fresh.x25519PrivateKey))82- .putString("ed25519_seed", pubkeyToHex(fresh.ed25519Seed))83- .commit()) {84- "identity_persist_failed"85- }94+ persistIdentity(context, fresh, System.currentTimeMillis())8695 return fresh.deviceId8796 }8897 @@ -123,10 +132,6 @@123132 wsPort = null,124133 relayUrl = RelaySettingsStore.readRelayUrl(context),125134 )126-}127-128-fun deriveLocalSyncKeypair(masterKey: ByteArray, deviceId: String): SyncIdentityKeypair {129- throw IllegalStateException("identity_migration_required")130135 }131136 132137 private fun defaultDeviceName(): String {app/src/main/java/com/peachpasswords/sync/LocalIdentityRecord.kt+121 −0
@@ -0,0 +1,121 @@1+package com.peachpasswords.sync2+3+import org.bouncycastle.crypto.params.Ed25519PrivateKeyParameters4+import org.bouncycastle.crypto.params.X25519PrivateKeyParameters5+6+/**7+ * Persisted local-identity record codec (campaign task 2.1).8+ *9+ * Pure and storage-agnostic so the frozen schema — version, device ID, X2551910+ * private/public, Ed25519 seed/public, creation time, and the consistency check11+ * between the stored public values and the private material — is unit-testable12+ * without a Keystore. `DeviceIdentity` adapts this to EncryptedSharedPreferences.13+ */14+internal const val LOCAL_IDENTITY_RECORD_VERSION = 315+16+/**17+ * The first random-identity format stored only the two private seeds. It is18+ * completed in place — never regenerated — so an installation that predates the19+ * frozen schema keeps its device ID and keys.20+ */21+internal const val LOCAL_IDENTITY_RECORD_VERSION_LEGACY_RANDOM = 222+23+internal const val FIELD_VERSION = "version"24+internal const val FIELD_DEVICE_ID = "device_id"25+internal const val FIELD_X25519_PRIVATE = "x25519_private"26+internal const val FIELD_X25519_PUBLIC = "x25519_public"27+internal const val FIELD_ED25519_SEED = "ed25519_seed"28+internal const val FIELD_ED25519_PUBLIC = "ed25519_public"29+internal const val FIELD_CREATED_AT = "created_at"30+31+private val HEX_64 = Regex("^[0-9a-fA-F]{64}$")32+33+internal sealed interface IdentityRecord {34+ /** No identity has ever been stored on this installation. */35+ data object Absent : IdentityRecord36+37+ /** Frozen-schema record that passed every consistency check. */38+ data class Current(39+ val credentials: LocalIdentityCredentials,40+ val createdAt: Long,41+ ) : IdentityRecord42+43+ /** Random record written before the frozen schema: private material only. */44+ data class LegacyRandom(val credentials: LocalIdentityCredentials) : IdentityRecord45+46+ /** Partial, unknown-version, or internally inconsistent: never regenerated. */47+ data object Invalid : IdentityRecord48+}49+50+internal fun readIdentityRecord(fields: Map<String, Any?>): IdentityRecord {51+ val deviceId = fields[FIELD_DEVICE_ID] as? String52+ val xPrivateHex = fields[FIELD_X25519_PRIVATE] as? String53+ val edSeedHex = fields[FIELD_ED25519_SEED] as? String54+ val storedVersion = (fields[FIELD_VERSION] as? Number)?.toInt()55+56+ if (deviceId == null && xPrivateHex == null && edSeedHex == null) {57+ return if (storedVersion == null) IdentityRecord.Absent else IdentityRecord.Invalid58+ }59+ if (storedVersion == null ||60+ deviceId.isNullOrBlank() ||61+ xPrivateHex == null || !HEX_64.matches(xPrivateHex) ||62+ edSeedHex == null || !HEX_64.matches(edSeedHex)63+ ) {64+ return IdentityRecord.Invalid65+ }66+67+ val xPrivate = hexToBytes(xPrivateHex)68+ val edSeed = hexToBytes(edSeedHex)69+ val credentials = LocalIdentityCredentials(70+ deviceId = deviceId,71+ x25519PrivateKey = xPrivate,72+ x25519PublicKey = X25519PrivateKeyParameters(xPrivate, 0).generatePublicKey().encoded,73+ ed25519Seed = edSeed,74+ ed25519PublicKey = Ed25519PrivateKeyParameters(edSeed, 0).generatePublicKey().encoded,75+ )76+77+ return when (storedVersion) {78+ LOCAL_IDENTITY_RECORD_VERSION_LEGACY_RANDOM -> IdentityRecord.LegacyRandom(credentials)79+ LOCAL_IDENTITY_RECORD_VERSION -> readFrozenRecord(fields, credentials)80+ else -> IdentityRecord.Invalid81+ }82+}83+84+/**85+ * The version-3 record must carry public values that match the private material86+ * and a real creation time. Recomputation alone would accept a record whose87+ * public half was tampered with; comparison makes the mismatch explicit.88+ */89+private fun readFrozenRecord(90+ fields: Map<String, Any?>,91+ credentials: LocalIdentityCredentials,92+): IdentityRecord {93+ val xPublicHex = fields[FIELD_X25519_PUBLIC] as? String94+ val edPublicHex = fields[FIELD_ED25519_PUBLIC] as? String95+ val createdAt = (fields[FIELD_CREATED_AT] as? Number)?.toLong() ?: 0L96+ if (xPublicHex == null || !HEX_64.matches(xPublicHex) ||97+ edPublicHex == null || !HEX_64.matches(edPublicHex) ||98+ createdAt <= 0L99+ ) {100+ return IdentityRecord.Invalid101+ }102+ if (!xPublicHex.equals(pubkeyToHex(credentials.x25519PublicKey), ignoreCase = true) ||103+ !edPublicHex.equals(pubkeyToHex(credentials.ed25519PublicKey), ignoreCase = true)104+ ) {105+ return IdentityRecord.Invalid106+ }107+ return IdentityRecord.Current(credentials, createdAt)108+}109+110+internal fun identityRecordFields(111+ credentials: LocalIdentityCredentials,112+ createdAt: Long,113+): Map<String, Any?> = mapOf(114+ FIELD_VERSION to LOCAL_IDENTITY_RECORD_VERSION,115+ FIELD_DEVICE_ID to credentials.deviceId,116+ FIELD_X25519_PRIVATE to pubkeyToHex(credentials.x25519PrivateKey),117+ FIELD_X25519_PUBLIC to pubkeyToHex(credentials.x25519PublicKey),118+ FIELD_ED25519_SEED to pubkeyToHex(credentials.ed25519Seed),119+ FIELD_ED25519_PUBLIC to pubkeyToHex(credentials.ed25519PublicKey),120+ FIELD_CREATED_AT to createdAt,121+)app/src/main/java/com/peachpasswords/sync/SyncCoordinator.kt+36 −9
@@ -29,9 +29,16 @@2929 /** Internal so the dialler's outer bound can be derived from it, never guessed. */3030 internal const val SESSION_TIMEOUT_MS = 30_000L3131 private const val CLOCK_SKEW_WARN_MS = 120_000L32-private const val SYNC_PROTOCOL_VERSION = 23332 3433 /**34+ * The one Sync wire protocol this build speaks (manifest v5, DH rendezvous v2,35+ * adoption v2). Peers must advertise this exact value: a migration is breaking,36+ * so a lower OR higher value is a repair-required mismatch, never a37+ * continue-under-assumptions path.38+ */39+internal const val SYNC_PROTOCOL_VERSION = 340+41+/**3542 * Vault-side dependency of the coordinator. The vault holds the canonical3643 * entry/tombstone tables; the coordinator pulls a manifest, requests entries by3744 * id, applies remote entries, and applies remote tombstones. Mirrors the@@ -117,8 +124,23 @@117124 if (vault.supportsDeviceManifest) DEVICE_MANIFEST_VERSION else null,118125 ),119126 )120- val hello = session.recvAs<SyncMessage.Hello>("initiator", "SYNC_HELLO")121- if ((hello.protocolVersion ?: 1) < SYNC_PROTOCOL_VERSION) {127+ // The responder rejects an incompatible HELLO before sending its128+ // own, so the initiator can receive that SYNC_ERROR first. Surface129+ // it as the same repair-required outcome instead of a generic130+ // "expected SYNC_HELLO" failure.131+ val first = session.recvMessage("initiator", "SYNC_HELLO")132+ if (first is SyncMessage.Error && first.error.contains("PEER_PROTOCOL_OUTDATED")) {133+ return@withTimeout SyncOutcome(134+ SyncOutcomeStatus.ERRORED,135+ error = "PEER_PROTOCOL_OUTDATED",136+ )137+ }138+ val hello = first as? SyncMessage.Hello139+ ?: throw IllegalStateException(140+ "expected SYNC_HELLO, got ${first::class.simpleName}",141+ )142+ // Exact equality: the breaking migration has one supported version.143+ if (hello.protocolVersion != SYNC_PROTOCOL_VERSION) {122144 session.sendMsg(SyncMessage.Error("PEER_PROTOCOL_OUTDATED"))123145 return@withTimeout SyncOutcome(124146 SyncOutcomeStatus.ERRORED,@@ -213,7 +235,8 @@213235 val localVersion = vault.getLocalVersion()214236 215237 val hello = session.recvAs<SyncMessage.Hello>("responder", "SYNC_HELLO")216- if ((hello.protocolVersion ?: 1) < SYNC_PROTOCOL_VERSION) {238+ // Exact equality: a lower or higher peer version is repair-required.239+ if (hello.protocolVersion != SYNC_PROTOCOL_VERSION) {217240 session.sendMsg(SyncMessage.Error("PEER_PROTOCOL_OUTDATED"))218241 return@withTimeout SyncOutcome(219242 SyncOutcomeStatus.ERRORED,@@ -339,17 +362,21 @@339362 send(bytes)340363 }341364 342-private suspend inline fun <reified T : SyncMessage> SyncSession.recvAs(343- role: String,344- expected: String,345-): T {365+private suspend fun SyncSession.recvMessage(role: String, expected: String): SyncMessage {346366 // Stage-only diagnostics: no device names, entry ids, counts, payloads,347367 // room capabilities, or key material. The final marker before a timeout348368 // identifies the protocol edge where the peers stopped agreeing.349369 PeachSyncLog.i("sync-stage: role=$role wait=$expected")350370 val bytes = receive()351371 requireSyncFrameSize(bytes.size)352- val msg = decodeSyncMessage(bytes).also { it.requireBounded() }372+ return decodeSyncMessage(bytes).also { it.requireBounded() }373+}374+375+private suspend inline fun <reified T : SyncMessage> SyncSession.recvAs(376+ role: String,377+ expected: String,378+): T {379+ val msg = recvMessage(role, expected)353380 return msg as? T ?: throw IllegalStateException("expected $expected, got ${msg::class.simpleName}")354381 }355382 app/src/main/java/com/peachpasswords/sync/SyncIdentity.kt+0 −36
@@ -4,8 +4,6 @@44 import org.bouncycastle.crypto.digests.Blake3Digest55 import org.bouncycastle.crypto.params.X25519PrivateKeyParameters66 import org.bouncycastle.crypto.params.Ed25519PrivateKeyParameters7-import org.bouncycastle.crypto.generators.HKDFBytesGenerator8-import org.bouncycastle.crypto.params.HKDFParameters97 108 data class SyncIdentityKeypair(119 val publicKey: ByteArray,@@ -40,19 +38,8 @@4038 fun localSigningKeypair(credentials: LocalIdentityCredentials): SyncSigningKeypair =4139 SyncSigningKeypair(Ed25519PrivateKeyParameters(credentials.ed25519Seed, 0), credentials.ed25519PublicKey.copyOf())4240 43-private val SYNC_IDENTITY_SALT = "peach-sync-identity-v1".encodeToByteArray()44-private val SYNC_SIGNING_SALT = "peach-sync-signing-v1".encodeToByteArray()4541 private val VAULT_ID_INFO = "peach-vault-id".encodeToByteArray()4642 47-fun deriveSyncIdentityKeypair(masterKey: ByteArray, deviceId: String): SyncIdentityKeypair {48- require(masterKey.isNotEmpty()) { "masterKey must not be empty" }49- require(deviceId.isNotEmpty()) { "deviceId must not be empty" }50- val info = deviceId.encodeToByteArray()51- val seed = hkdf(masterKey, SYNC_IDENTITY_SALT, info, 32)52- val priv = X25519PrivateKeyParameters(seed, 0)53- return SyncIdentityKeypair(publicKey = priv.generatePublicKey().encoded, secretKey = seed)54-}55-5643 fun computeVaultId(masterKey: ByteArray): String {5744 require(masterKey.isNotEmpty()) { "masterKey must not be empty" }5845 val buf = masterKey + VAULT_ID_INFO@@ -68,21 +55,6 @@6855 }6956 }7057 71-fun deriveSyncSigningKeypair(masterKey: ByteArray, deviceId: String): SyncSigningKeypair {72- require(masterKey.isNotEmpty()) { "masterKey must not be empty" }73- require(deviceId.isNotEmpty()) { "deviceId must not be empty" }74- val info = deviceId.encodeToByteArray()75- val seed = hkdf(masterKey, SYNC_SIGNING_SALT, info, 32)76- return try {77- val privateKey = Ed25519PrivateKeyParameters(seed, 0)78- SyncSigningKeypair(privateKey = privateKey, publicKeyRaw = privateKey.generatePublicKey().encoded)79- } finally {80- // Ed25519PrivateKeyParameters copies the seed into its own immutable81- // key object; the HKDF output itself is only constructor workspace.82- VaultCrypto.zero(seed)83- }84-}85-8658 fun verifyEd25519(publicKeyRaw: ByteArray, message: ByteArray, signature: ByteArray): Boolean {8759 return try {8860 if (publicKeyRaw.size != 32 || signature.size != 64) return false@@ -118,12 +90,4 @@11890 fun hexToPubkey(hex: String): ByteArray {11991 require(hex.length == 64) { "public key must be exactly 32 bytes" }12092 return hexToBytes(hex)121-}122-123-private fun hkdf(ikm: ByteArray, salt: ByteArray, info: ByteArray, length: Int): ByteArray {124- val generator = HKDFBytesGenerator(org.bouncycastle.crypto.digests.SHA256Digest())125- generator.init(HKDFParameters(ikm, salt, info))126- val out = ByteArray(length)127- generator.generateBytes(out, 0, length)128- return out12993 }app/src/main/java/com/peachpasswords/sync/SyncOutcomeReason.kt+2 −1
@@ -167,7 +167,8 @@167167 SyncOutcomeReason.RELAY_UNREACHABLE -> "Couldn't reach the relay"168168 SyncOutcomeReason.HANDSHAKE_FAILED -> "Reached the relay, but the device didn't answer"169169 SyncOutcomeReason.VAULT_ID_MISMATCH -> "That device holds a different vault"170- SyncOutcomeReason.PEER_PROTOCOL_OUTDATED -> "Your other device needs to update before it can sync"170+ SyncOutcomeReason.PEER_PROTOCOL_OUTDATED ->171+ "Update Peach on both devices, then re-pair them"171172 SyncOutcomeReason.SYNC_TIMEOUT -> "The device stopped responding mid-sync"172173 SyncOutcomeReason.CONNECTION_LOST -> "The connection dropped mid-sync — will retry"173174 SyncOutcomeReason.RUN_FAILED -> "Sync failed"app/src/main/res/xml/backup_rules.xml+1 −0
@@ -23,4 +23,5 @@2323 <exclude domain="sharedpref" path="peach_paired_devices.xml" />2424 <exclude domain="sharedpref" path="peach_sync_alerts.xml" />2525 <exclude domain="sharedpref" path="peach_locked_sync_spool_v1.xml" />26+ <exclude domain="sharedpref" path="peach_local_identity_v2.xml" />2627 </full-backup-content>app/src/main/res/xml/data_extraction_rules.xml+2 −0
@@ -24,6 +24,7 @@2424 <exclude domain="sharedpref" path="peach_paired_devices.xml" />2525 <exclude domain="sharedpref" path="peach_sync_alerts.xml" />2626 <exclude domain="sharedpref" path="peach_locked_sync_spool_v1.xml" />27+ <exclude domain="sharedpref" path="peach_local_identity_v2.xml" />2728 </cloud-backup>2829 <device-transfer>2930 <exclude domain="sharedpref" path="peach_vault_store.xml" />@@ -44,5 +45,6 @@4445 <exclude domain="sharedpref" path="peach_paired_devices.xml" />4546 <exclude domain="sharedpref" path="peach_sync_alerts.xml" />4647 <exclude domain="sharedpref" path="peach_locked_sync_spool_v1.xml" />48+ <exclude domain="sharedpref" path="peach_local_identity_v2.xml" />4749 </device-transfer>4850 </data-extraction-rules>app/src/test/java/com/peachpasswords/sync/LegacyIdentityDerivation.kt+62 −0
@@ -0,0 +1,62 @@1+package com.peachpasswords.sync2+3+import com.peachpasswords.vault.VaultCrypto4+import org.bouncycastle.crypto.digests.SHA256Digest5+import org.bouncycastle.crypto.generators.HKDFBytesGenerator6+import org.bouncycastle.crypto.params.Ed25519PrivateKeyParameters7+import org.bouncycastle.crypto.params.HKDFParameters8+import org.bouncycastle.crypto.params.X25519PrivateKeyParameters9+10+/**11+ * Root→device key derivation, retained **for tests only** — campaign task 2.4.12+ *13+ * Production no longer derives any device key material from the vault root:14+ * device identities are random per installation (`randomLocalIdentityCredentials`)15+ * and route capabilities come from `Rendezvous.deriveMeshSecret`. Nothing in16+ * `app/src/main` may reference this file; fixtures use it only to build17+ * deterministic keypairs.18+ */19+private val LEGACY_SYNC_IDENTITY_SALT = "peach-sync-identity-v1".encodeToByteArray()20+private val LEGACY_SYNC_SIGNING_SALT = "peach-sync-signing-v1".encodeToByteArray()21+22+internal fun deriveSyncIdentityKeypair(23+ masterKey: ByteArray,24+ deviceId: String,25+): SyncIdentityKeypair {26+ require(masterKey.isNotEmpty()) { "masterKey must not be empty" }27+ require(deviceId.isNotEmpty()) { "deviceId must not be empty" }28+ val seed = legacyHkdf(masterKey, LEGACY_SYNC_IDENTITY_SALT, deviceId.encodeToByteArray(), 32)29+ val priv = X25519PrivateKeyParameters(seed, 0)30+ return SyncIdentityKeypair(publicKey = priv.generatePublicKey().encoded, secretKey = seed)31+}32+33+internal fun deriveSyncSigningKeypair(34+ masterKey: ByteArray,35+ deviceId: String,36+): SyncSigningKeypair {37+ require(masterKey.isNotEmpty()) { "masterKey must not be empty" }38+ require(deviceId.isNotEmpty()) { "deviceId must not be empty" }39+ val seed = legacyHkdf(masterKey, LEGACY_SYNC_SIGNING_SALT, deviceId.encodeToByteArray(), 32)40+ return try {41+ val privateKey = Ed25519PrivateKeyParameters(seed, 0)42+ SyncSigningKeypair(43+ privateKey = privateKey,44+ publicKeyRaw = privateKey.generatePublicKey().encoded,45+ )46+ } finally {47+ VaultCrypto.zero(seed)48+ }49+}50+51+private fun legacyHkdf(52+ ikm: ByteArray,53+ salt: ByteArray,54+ info: ByteArray,55+ length: Int,56+): ByteArray {57+ val generator = HKDFBytesGenerator(SHA256Digest())58+ generator.init(HKDFParameters(ikm, salt, info))59+ val out = ByteArray(length)60+ generator.generateBytes(out, 0, length)61+ return out62+}app/src/test/java/com/peachpasswords/sync/LocalIdentityRecordTest.kt+107 −0
@@ -0,0 +1,107 @@1+package com.peachpasswords.sync2+3+import org.junit.Assert.assertEquals4+import org.junit.Assert.assertTrue5+import org.junit.Test6+7+/**8+ * Frozen local-identity schema (campaign task 2.1): round trip, legacy9+ * completion, and every malformed-shape rejection. These run on the JVM because10+ * the codec is storage-agnostic; `DeviceIdentity` only adapts it to11+ * EncryptedSharedPreferences.12+ */13+class LocalIdentityRecordTest {14+15+ @Test fun round_trips_every_frozen_field() {16+ val credentials = randomLocalIdentityCredentials("device-a")17+ val fields = identityRecordFields(credentials, createdAt = 1_700_000_000_000L)18+19+ val decoded = readIdentityRecord(fields)20+21+ assertTrue(decoded is IdentityRecord.Current)22+ val current = decoded as IdentityRecord.Current23+ assertEquals("device-a", current.credentials.deviceId)24+ assertTrue(current.credentials.x25519PrivateKey.contentEquals(credentials.x25519PrivateKey))25+ assertTrue(current.credentials.x25519PublicKey.contentEquals(credentials.x25519PublicKey))26+ assertTrue(current.credentials.ed25519Seed.contentEquals(credentials.ed25519Seed))27+ assertTrue(current.credentials.ed25519PublicKey.contentEquals(credentials.ed25519PublicKey))28+ assertEquals(1_700_000_000_000L, current.createdAt)29+ }30+31+ @Test fun no_stored_fields_is_absent() {32+ assertEquals(IdentityRecord.Absent, readIdentityRecord(emptyMap()))33+ }34+35+ @Test fun legacy_random_record_completes_without_changing_the_identity() {36+ val credentials = randomLocalIdentityCredentials("legacy-id")37+ val fields = mapOf<String, Any?>(38+ FIELD_VERSION to LOCAL_IDENTITY_RECORD_VERSION_LEGACY_RANDOM,39+ FIELD_DEVICE_ID to credentials.deviceId,40+ FIELD_X25519_PRIVATE to pubkeyToHex(credentials.x25519PrivateKey),41+ FIELD_ED25519_SEED to pubkeyToHex(credentials.ed25519Seed),42+ )43+44+ val decoded = readIdentityRecord(fields)45+46+ assertTrue(decoded is IdentityRecord.LegacyRandom)47+ val legacy = decoded as IdentityRecord.LegacyRandom48+ assertEquals("legacy-id", legacy.credentials.deviceId)49+ assertTrue(legacy.credentials.x25519PrivateKey.contentEquals(credentials.x25519PrivateKey))50+ assertTrue(legacy.credentials.ed25519Seed.contentEquals(credentials.ed25519Seed))51+ }52+53+ @Test fun unknown_version_is_invalid() {54+ val credentials = randomLocalIdentityCredentials("device-a")55+ val fields = identityRecordFields(credentials, 1L) + (FIELD_VERSION to 99)56+ assertEquals(IdentityRecord.Invalid, readIdentityRecord(fields))57+ }58+59+ @Test fun stored_public_key_that_does_not_match_the_private_key_is_invalid() {60+ val credentials = randomLocalIdentityCredentials("device-a")61+ val fields = identityRecordFields(credentials, 1L) + (FIELD_X25519_PUBLIC to "aa".repeat(32))62+ assertEquals(IdentityRecord.Invalid, readIdentityRecord(fields))63+ }64+65+ @Test fun missing_creation_time_is_invalid() {66+ val credentials = randomLocalIdentityCredentials("device-a")67+ val fields = identityRecordFields(credentials, 1L) - FIELD_CREATED_AT68+ assertEquals(IdentityRecord.Invalid, readIdentityRecord(fields))69+ }70+71+ @Test fun missing_stored_public_value_is_invalid() {72+ val credentials = randomLocalIdentityCredentials("device-a")73+ val fields = identityRecordFields(credentials, 1L) - FIELD_ED25519_PUBLIC74+ assertEquals(IdentityRecord.Invalid, readIdentityRecord(fields))75+ }76+77+ @Test fun private_material_without_a_version_is_invalid() {78+ val credentials = randomLocalIdentityCredentials("device-a")79+ val fields = identityRecordFields(credentials, 1L) - FIELD_VERSION80+ assertEquals(IdentityRecord.Invalid, readIdentityRecord(fields))81+ }82+83+ @Test fun partial_private_material_is_invalid() {84+ val fields = mapOf<String, Any?>(85+ FIELD_VERSION to LOCAL_IDENTITY_RECORD_VERSION,86+ FIELD_DEVICE_ID to "device-a",87+ FIELD_ED25519_SEED to "22".repeat(32),88+ )89+ assertEquals(IdentityRecord.Invalid, readIdentityRecord(fields))90+ }91+92+ @Test fun malformed_private_hex_is_invalid() {93+ val fields = mapOf<String, Any?>(94+ FIELD_VERSION to LOCAL_IDENTITY_RECORD_VERSION,95+ FIELD_DEVICE_ID to "device-a",96+ FIELD_X25519_PRIVATE to "not-hex",97+ FIELD_ED25519_SEED to "22".repeat(32),98+ )99+ assertEquals(IdentityRecord.Invalid, readIdentityRecord(fields))100+ }101+102+ @Test fun blank_device_id_is_invalid() {103+ val credentials = randomLocalIdentityCredentials("device-a")104+ val fields = identityRecordFields(credentials, 1L) + (FIELD_DEVICE_ID to "")105+ assertEquals(IdentityRecord.Invalid, readIdentityRecord(fields))106+ }107+}app/src/test/java/com/peachpasswords/sync/RelayAdoptionInitiatorSourceTest.kt+12 −12
@@ -68,8 +68,8 @@6868 val token = "AAECAwQFBgcICQoLDA0ODw"6969 val relay = "wss://relay.example.test"7070 val root = ByteArray(32) { (it + 5).toByte() }71- val phoneKeys = deriveLocalSyncKeypair(root, "phone-id")72- val responderKeys = deriveLocalSyncKeypair(root, "responder-id")71+ val phoneKeys = deriveSyncIdentityKeypair(root, "phone-id")72+ val responderKeys = deriveSyncIdentityKeypair(root, "responder-id")7373 val phoneIdentity = identity("phone", phoneKeys.publicKey)7474 val responderIdentity = identity("responder", responderKeys.publicKey)7575 var phoneStored: PairedDevice? = null@@ -168,12 +168,12 @@168168 val token = "AAECAwQFBgcICQoLDA0ODw"169169 val relay = "wss://relay.example.test"170170 val root = ByteArray(32) { (it + 19).toByte() }171- val phoneKeys = deriveLocalSyncKeypair(root, "phone-id")172- val responderKeys = deriveLocalSyncKeypair(root, "responder-id")171+ val phoneKeys = deriveSyncIdentityKeypair(root, "phone-id")172+ val responderKeys = deriveSyncIdentityKeypair(root, "responder-id")173173 val phoneIdentity = identity("phone", phoneKeys.publicKey)174174 val rotatedPhoneIdentity = identity(175175 "phone-fresh",176- deriveLocalSyncKeypair(root, "phone-fresh-id").publicKey,176+ deriveSyncIdentityKeypair(root, "phone-fresh-id").publicKey,177177 ).copy(deviceId = "phone-fresh-id")178178 val responderIdentity = identity("responder", responderKeys.publicKey)179179 var rotations = 0@@ -283,8 +283,8 @@283283 val (phoneSocket, mitmSocket) = socketPair()284284 val token = "AAECAwQFBgcICQoLDA0ODw"285285 val root = ByteArray(32) { (it + 7).toByte() }286- val responderKeys = deriveLocalSyncKeypair(root, "responder-id")287- val attackerKeys = deriveLocalSyncKeypair(root, "attacker-id")286+ val responderKeys = deriveSyncIdentityKeypair(root, "responder-id")287+ val attackerKeys = deriveSyncIdentityKeypair(root, "attacker-id")288288 var rootRequested = false289289 290290 // The result is captured inside the job: an exception escaping a child@@ -301,7 +301,7 @@301301 ),302302 sourceDeps = object : AdoptionSourceDeps {303303 override val sourceIdentity =304- identity("phone", deriveLocalSyncKeypair(root, "phone-id").publicKey)304+ identity("phone", deriveSyncIdentityKeypair(root, "phone-id").publicKey)305305 override suspend fun rootKeyHex(): String {306306 rootRequested = true307307 return Rendezvous.bytesToHex(root)@@ -342,7 +342,7 @@342342 @Test fun `phone source rejects an invitation that pins no static key`() = runBlocking {343343 val (phoneSocket, mitmSocket) = socketPair()344344 val root = ByteArray(32) { (it + 23).toByte() }345- val attackerKeys = deriveLocalSyncKeypair(root, "attacker-id")345+ val attackerKeys = deriveSyncIdentityKeypair(root, "attacker-id")346346 347347 val phoneJob = async {348348 try {@@ -357,7 +357,7 @@357357 ),358358 sourceDeps = object : AdoptionSourceDeps {359359 override val sourceIdentity =360- identity("phone", deriveLocalSyncKeypair(root, "phone-id").publicKey)360+ identity("phone", deriveSyncIdentityKeypair(root, "phone-id").publicKey)361361 override suspend fun rootKeyHex() = Rendezvous.bytesToHex(root)362362 override suspend fun vaultId() = computeVaultId(root)363363 override suspend fun onConsent(request: AdoptionFrame.Request) = true@@ -390,8 +390,8 @@390390 val (phoneSocket, responderSocket) = socketPair()391391 val token = "AAECAwQFBgcICQoLDA0ODw"392392 val root = ByteArray(32) { (it + 11).toByte() }393- val phoneKeys = deriveLocalSyncKeypair(root, "phone-id")394- val responderKeys = deriveLocalSyncKeypair(root, "responder-id")393+ val phoneKeys = deriveSyncIdentityKeypair(root, "phone-id")394+ val responderKeys = deriveSyncIdentityKeypair(root, "responder-id")395395 var rootRequested = false396396 var upserted = false397397 app/src/test/java/com/peachpasswords/sync/SyncCoordinatorTest.kt+66 −3
@@ -199,11 +199,58 @@199199 }200200 201201 @Test fun stale_peer_is_rejected_with_protocol_outdated() = runBlocking {202+ val sent = mutableListOf<SyncMessage>()202203 val staleHello =203- SyncMessage.Hello("VAULT", "B", version = 2, deviceTime = 0L).encodeToBytes()204+ SyncMessage.Hello(205+ "VAULT",206+ "B",207+ version = 2,208+ deviceTime = 0L,209+ protocolVersion = SYNC_PROTOCOL_VERSION - 1,210+ ).encodeToBytes()204211 val queue = ArrayDeque(listOf(staleHello))205212 val session = SyncSession(206213 remoteStaticPublicKey = ByteArray(32),214+ send = { bytes -> sent += decodeSyncMessage(bytes) },215+ receive = { queue.removeFirstOrNull() ?: throw java.io.IOException("WebSocket closed") },216+ close = { },217+ )218+ val out = runSyncResponder(session, FakeAdapter("B", version = 2), nowMs = 0L)219+ assertEquals(SyncOutcomeStatus.ERRORED, out.status)220+ assertEquals("PEER_PROTOCOL_OUTDATED", out.error)221+ // No manifest frame may follow the rejection.222+ assertEquals(listOf<SyncMessage>(SyncMessage.Error("PEER_PROTOCOL_OUTDATED")), sent)223+ }224+225+ @Test fun future_peer_is_rejected_before_any_manifest_frame() = runBlocking {226+ val sent = mutableListOf<SyncMessage>()227+ val futureHello =228+ SyncMessage.Hello(229+ "VAULT",230+ "B",231+ version = 2,232+ deviceTime = 0L,233+ protocolVersion = SYNC_PROTOCOL_VERSION + 1,234+ ).encodeToBytes()235+ val queue = ArrayDeque(listOf(futureHello))236+ val session = SyncSession(237+ remoteStaticPublicKey = ByteArray(32),238+ send = { bytes -> sent += decodeSyncMessage(bytes) },239+ receive = { queue.removeFirstOrNull() ?: throw java.io.IOException("WebSocket closed") },240+ close = { },241+ )242+ val out = runSyncResponder(session, FakeAdapter("B", version = 2), nowMs = 0L)243+ assertEquals(SyncOutcomeStatus.ERRORED, out.status)244+ assertEquals("PEER_PROTOCOL_OUTDATED", out.error)245+ assertEquals(listOf<SyncMessage>(SyncMessage.Error("PEER_PROTOCOL_OUTDATED")), sent)246+ }247+248+ @Test fun absent_protocol_version_peer_is_rejected_as_legacy() = runBlocking {249+ val legacyHello =250+ SyncMessage.Hello("VAULT", "B", version = 2, deviceTime = 0L).encodeToBytes()251+ val queue = ArrayDeque(listOf(legacyHello))252+ val session = SyncSession(253+ remoteStaticPublicKey = ByteArray(32),207254 send = { },208255 receive = { queue.removeFirstOrNull() ?: throw java.io.IOException("WebSocket closed") },209256 close = { },@@ -213,6 +260,22 @@213260 assertEquals("PEER_PROTOCOL_OUTDATED", out.error)214261 }215262 263+ @Test fun initiator_surfaces_repair_required_when_responder_rejects_first() = runBlocking {264+ // A future responder rejects our HELLO before sending its own; the265+ // initiator must still report the defined repair-required outcome.266+ val rejection = SyncMessage.Error("PEER_PROTOCOL_OUTDATED").encodeToBytes()267+ val queue = ArrayDeque(listOf(rejection))268+ val session = SyncSession(269+ remoteStaticPublicKey = ByteArray(32),270+ send = { },271+ receive = { queue.removeFirstOrNull() ?: throw java.io.IOException("WebSocket closed") },272+ close = { },273+ )274+ val out = runSyncInitiator(session, FakeAdapter("A", version = 2), nowMs = 0L)275+ assertEquals(SyncOutcomeStatus.ERRORED, out.status)276+ assertEquals("PEER_PROTOCOL_OUTDATED", out.error)277+ }278+216279 @Test fun tombstone_propagates_to_peer() = runBlocking {217280 val (sa, sb) = duplex()218281 val a = FakeAdapter("A", version = 3).apply { tombstones["gone"] = 500 }@@ -322,7 +385,7 @@322385 // 1: peer's HELLO (same vault, different version, with a future323386 // mtime so the equal-version short-circuit doesn't fire).324387 frames.add(325- SyncMessage.Hello("VAULT", "B", version = 2, deviceTime = 0L, protocolVersion = 2).encodeToBytes(),388+ SyncMessage.Hello("VAULT", "B", version = 2, deviceTime = 0L, protocolVersion = SYNC_PROTOCOL_VERSION).encodeToBytes(),326389 )327390 // 2: peer's MANIFEST (y@200).328391 frames.add(@@ -374,7 +437,7 @@374437 }375438 376439 private fun hello() =377- SyncMessage.Hello("VAULT", "A", version = 1, deviceTime = 0L, protocolVersion = 2)440+ SyncMessage.Hello("VAULT", "A", version = 1, deviceTime = 0L, protocolVersion = SYNC_PROTOCOL_VERSION)378441 379442 @Test fun oversized_manifest_is_refused() {380443 val over = (0..SyncLimits.MAX_ENTRY_COUNT).associate { "id-$it" to 1L }app/src/test/java/com/peachpasswords/sync/SyncOutcomeTest.kt+1 −1
@@ -138,7 +138,7 @@138138 assertEquals("Reached the relay, but the device didn't answer", copy(SyncOutcomeReason.HANDSHAKE_FAILED))139139 assertEquals("That device holds a different vault", copy(SyncOutcomeReason.VAULT_ID_MISMATCH))140140 assertEquals(141- "Your other device needs to update before it can sync",141+ "Update Peach on both devices, then re-pair them",142142 copy(SyncOutcomeReason.PEER_PROTOCOL_OUTDATED),143143 )144144 assertEquals("The device stopped responding mid-sync", copy(SyncOutcomeReason.SYNC_TIMEOUT))