99ea46594116
enforce immutable direct identities and signed revocation history (v2.17.21)
- time
- 2026-09-10 15:16 UTC · 2 months ago
- machine
- koh2
- agent
- camel-stream/auto
- session
- identity revocation remediation
- parent
- 29fb1b707f35
↓ peach-android-99ea4659.tar.gzatlas at this save
files changed24 files
VERSION+1 −1app/src/main/java/com/peachpasswords/sync/DeviceIdentity.kt+68 −29app/src/main/java/com/peachpasswords/sync/DeviceManifestSupport.kt+81 −11app/src/main/java/com/peachpasswords/sync/ForegroundSyncCoordinator.kt+3 −1app/src/main/java/com/peachpasswords/sync/LockedSyncSpoolStore.kt+4 −3app/src/main/java/com/peachpasswords/sync/PairedDeviceStore.kt+17 −1app/src/main/java/com/peachpasswords/sync/PeachSyncService.kt+17 −20app/src/main/java/com/peachpasswords/sync/PendingVouchedDeviceStore.kt+37 −2app/src/main/java/com/peachpasswords/sync/RelayAdoptionHost.kt+4 −0app/src/main/java/com/peachpasswords/sync/RelayAdoptionReceiver.kt+4 −0app/src/main/java/com/peachpasswords/sync/Rendezvous.kt+16 −14app/src/main/java/com/peachpasswords/sync/SyncIdentity.kt+23 −0app/src/main/java/com/peachpasswords/sync/SyncMessage.kt+7 −3app/src/main/java/com/peachpasswords/sync/VaultAdopt.kt+4 −0app/src/main/java/com/peachpasswords/sync/VaultSyncAdapter.kt+55 −31app/src/main/java/com/peachpasswords/ui/pairing/AdoptVaultViewModel.kt+40 −11app/src/main/java/com/peachpasswords/ui/pairing/CodePairViewModel.kt+34 −8app/src/main/java/com/peachpasswords/ui/sync/SyncViewModel.kt+5 −4app/src/test/java/com/peachpasswords/sync/DeviceManifestSupportTest.kt+28 −0app/src/test/java/com/peachpasswords/sync/RelayAdoptionHostTest.kt+7 −7app/src/test/java/com/peachpasswords/sync/RelayAdoptionReceiverTest.kt+14 −13app/src/test/java/com/peachpasswords/sync/RendezvousTest.kt+6 −9app/src/test/java/com/peachpasswords/sync/SyncServiceStartTest.kt+8 −8app/src/test/java/com/peachpasswords/sync/VaultSyncAdapterTest.kt+19 −10app/src/main/java/com/peachpasswords/sync/DeviceIdentity.kt+68 −29
@@ -1,11 +1,54 @@11 package com.peachpasswords.sync22 33 import android.content.Context4+import androidx.security.crypto.EncryptedSharedPreferences5+import androidx.security.crypto.MasterKey46 import java.util.UUID7+import java.security.SecureRandom8+import com.peachpasswords.vault.VaultCrypto59 6-// The persisted keys keep their original names on purpose. Renaming them7-// would orphan this device's stored identity, which means a new device id and8-// a new sync keypair — every existing pairing would silently stop working on10+private const val LOCAL_IDENTITY_PREFS = "peach_local_identity_v2"11+private const val LOCAL_IDENTITY_VERSION = 212+13+private fun secureIdentityPrefs(context: Context) = EncryptedSharedPreferences.create(14+ context,15+ LOCAL_IDENTITY_PREFS,16+ MasterKey.Builder(context).setKeyScheme(MasterKey.KeyScheme.AES256_GCM).build(),17+ EncryptedSharedPreferences.PrefKeyEncryptionScheme.AES256_SIV,18+ EncryptedSharedPreferences.PrefValueEncryptionScheme.AES256_GCM,19+)20+21+/** Loads the canonical random identity, creating it once under Keystore protection. */22+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"26+ }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"34+ }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)40+ }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"47+ }48+ return fresh49+}50+51+// The persisted names below are retained for device-name migration only.952 // upgrade. The name is stale; the cost of fixing it is not worth paying.1053 private const val DEVICE_ID_KEY = "peach_chirp_device_id"1154 private const val DEVICE_NAME_KEY = "peach_chirp_device_name"@@ -27,23 +70,20 @@2770 val license: String? = null,2871 )2972 30-fun getOrCreateDeviceId(context: Context): String {31- val prefs = context.getSharedPreferences(PREFS_FILE, Context.MODE_PRIVATE)32- val current = prefs.getString(DEVICE_ID_KEY, null)33- if (!current.isNullOrEmpty()) return current34- val fresh = UUID.randomUUID().toString()35- prefs.edit().putString(DEVICE_ID_KEY, fresh).apply()36- return fresh37-}73+fun getOrCreateDeviceId(context: Context): String = loadOrCreateLocalIdentity(context).deviceId3874 39-/** Replace the local device id after an authenticated peer detects a collision. */75+/** Replace the local identity after an authenticated peer detects a collision. */4076 fun rotateDeviceId(context: Context): String {41- val fresh = UUID.randomUUID().toString()42- context.getSharedPreferences(PREFS_FILE, Context.MODE_PRIVATE)43- .edit()44- .putString(DEVICE_ID_KEY, fresh)45- .apply()46- return fresh77+ 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+ }86+ return fresh.deviceId4787 }4888 4989 fun getDeviceName(context: Context): String {@@ -69,25 +109,24 @@69109 }70110 71111 fun buildLocalIdentity(context: Context, masterKey: ByteArray): LocalDeviceIdentity {72- val deviceId = getOrCreateDeviceId(context)73- val deviceName = getDeviceName(context)74- val kp = deriveSyncIdentityKeypair(masterKey, deviceId)75- val signing = deriveSyncSigningKeypair(masterKey, deviceId)112+ VaultCrypto.zero(masterKey)113+ return buildLocalIdentity(context, loadOrCreateLocalIdentity(context))114+}115+116+fun buildLocalIdentity(context: Context, credentials: LocalIdentityCredentials): LocalDeviceIdentity {76117 return LocalDeviceIdentity(77- deviceId = deviceId,78- deviceName = deviceName,118+ deviceId = credentials.deviceId,119+ deviceName = getDeviceName(context),79120 deviceType = extensionDeviceType(),80- longTermPublicKeyHex = pubkeyToHex(kp.publicKey),81- signingPublicKeyHex = pubkeyToHex(signing.publicKeyRaw),82- // No LAN port is advertised: peers reconnect through the relay83- // (docs/sync-lan-retirement.md), never by dialling this device.121+ longTermPublicKeyHex = pubkeyToHex(credentials.x25519PublicKey),122+ signingPublicKeyHex = pubkeyToHex(credentials.ed25519PublicKey),84123 wsPort = null,85124 relayUrl = RelaySettingsStore.readRelayUrl(context),86125 )87126 }88127 89128 fun deriveLocalSyncKeypair(masterKey: ByteArray, deviceId: String): SyncIdentityKeypair {90- return deriveSyncIdentityKeypair(masterKey, deviceId)129+ throw IllegalStateException("identity_migration_required")91130 }92131 93132 private fun defaultDeviceName(): String {app/src/main/java/com/peachpasswords/sync/DeviceManifestSupport.kt+81 −11
@@ -4,8 +4,8 @@44 import kotlinx.serialization.json.Json55 import org.bouncycastle.crypto.params.Ed25519PrivateKeyParameters66 7-/** 0x04 adds signed vouch depth to each introduced peer edge. */8-const val DEVICE_MANIFEST_VERSION = 0x047+/** 0x05 adds signed per-issuer revocation records to the vouch graph. */8+const val DEVICE_MANIFEST_VERSION = 0x0599 const val MAX_VOUCH_DEPTH = 31010 private const val DEVICE_MANIFEST_FRESHNESS_MS = 5 * 60_000L1111 /**@@ -55,6 +55,13 @@5555 fun remove(deviceId: String) {}5656 fun listRevocations(): List<DeviceRevocation> = emptyList()5757 58+ /**59+ * Immutable issuer signing-key history. Implementations must append only;60+ * the default keeps lightweight test registries source-compatible.61+ */62+ fun issuerSigningKeys(issuerDeviceId: String): Set<String> = emptySet()63+ fun appendIssuerSigningKey(issuerDeviceId: String, signingKeyHex: String): Boolean = true64+5865 /** Commit a complete staged manifest as one logical registry mutation. */5966 fun applyManifestBatch(batch: DeviceManifestRegistryBatch): Boolean6067 @@ -88,20 +95,69 @@8895 revoked: List<DeviceRevocation> = emptyList(),8996 ): SignedDeviceManifest {9097 require(issuerDeviceId.isNotBlank()) { "issuerDeviceId is required" }98+ val issuerKeyHex = pubkeyToHex(signingPrivateKey.generatePublicKey().encoded)9199 val body = DeviceManifestBody(92100 manifestVersion = DEVICE_MANIFEST_VERSION,93101 issuerDeviceId = issuerDeviceId,94102 issuedAt = nowMs,95- // Normalise valid entries but keep invalid ones too — verifyDeviceManifest96- // is the gate that detects malformed input (M-09: silent drop would let97- // a caller believe they sent a valid manifest).98103 devices = devices.map { normaliseManifestEntry(it) ?: it },99- revoked = revoked.map(::normaliseRevocation),104+ revoked = revoked.map { record ->105+ // A forwarded revocation is an immutable issuer statement. Preserve106+ // its original issuer, key, and signature; only sign locally-created107+ // records that have not been signed yet.108+ if (record.signatureHex.isNotBlank()) {109+ record110+ } else {111+ signDeviceRevocation(112+ record.copy(issuerDeviceId = issuerDeviceId, issuerSigningKeyHex = issuerKeyHex),113+ signingPrivateKey,114+ )115+ }116+ },100117 )101118 val signature = signEd25519(signingPrivateKey, canonicalDeviceManifestBody(body).toByteArray(Charsets.UTF_8))102119 return SignedDeviceManifest(body, pubkeyToHex(signature))103120 }104121 122+/** Sign the immutable record, excluding its signature field from canonical bytes. */123+fun signDeviceRevocation(124+ record: DeviceRevocation,125+ signingPrivateKey: Ed25519PrivateKeyParameters,126+): DeviceRevocation {127+ val keyHex = pubkeyToHex(signingPrivateKey.generatePublicKey().encoded)128+ val unsigned = record.copy(129+ issuerSigningKeyHex = keyHex,130+ signatureHex = "",131+ )132+ val signature = signEd25519(133+ signingPrivateKey,134+ canonicalDeviceRevocation(unsigned).toByteArray(Charsets.UTF_8),135+ )136+ return unsigned.copy(signatureHex = pubkeyToHex(signature))137+}138+139+fun canonicalDeviceRevocation(record: DeviceRevocation): String =140+ canonicalise(141+ mapOf(142+ "deviceId" to record.deviceId,143+ "issuerDeviceId" to record.issuerDeviceId,144+ "issuerSigningKeyHex" to record.issuerSigningKeyHex.lowercase(),145+ "longTermPublicKeyHex" to record.longTermPublicKeyHex.lowercase(),146+ "revokedAt" to record.revokedAt,147+ "revokedByDeviceId" to record.revokedByDeviceId,148+ ),149+ )150+151+fun verifyDeviceRevocation(record: DeviceRevocation, issuerSigningPublicKey: ByteArray): Boolean {152+ if (!isHex(record.signatureHex, 128)) return false153+ val signature = runCatching { hexToBytes(record.signatureHex) }.getOrNull() ?: return false154+ return verifyEd25519(155+ issuerSigningPublicKey,156+ canonicalDeviceRevocation(record.copy(signatureHex = "")).toByteArray(Charsets.UTF_8),157+ signature,158+ )159+}160+105161 fun verifyDeviceManifest(106162 manifest: SignedDeviceManifest,107163 issuerSigningPublicKey: ByteArray,@@ -119,12 +175,23 @@119175 if (body.issuerDeviceId.isBlank() || body.issuerDeviceId.length > MAX_MANIFEST_STRING) return null120176 if (body.devices.size > MAX_MANIFEST_DEVICES) return null121177 if (body.revoked.size > MAX_MANIFEST_REVOCATIONS) return null178+ // Validate every entry before the normalised return mapping below. Without179+ // this guard, malformed but correctly signed manifests reached `!!` and180+ // crashed the sync path instead of being rejected.181+ if (body.devices.any { normaliseManifestEntry(it) == null }) return null122182 if (!isHex(manifest.signatureHex, 128)) return null123- if (!body.devices.all { normaliseManifestEntry(it) != null }) return null124183 if (!body.revoked.all { isValidRevocation(it) }) return null125184 val signature = runCatching { hexToBytes(manifest.signatureHex) }.getOrNull() ?: return null126185 val canonical = canonicalDeviceManifestBody(body).toByteArray(Charsets.UTF_8)127186 if (!verifyEd25519(issuerSigningPublicKey, canonical, signature)) return null187+ // Forwarded tombstones retain the original issuer's immutable signature.188+ // The enclosing manifest signature authenticates the forwarder; the189+ // embedded issuer key authenticates the revocation itself.190+ if (!body.revoked.all { record ->191+ val recordKey = runCatching { hexToPubkey(record.issuerSigningKeyHex) }.getOrNull()192+ ?: return@all false193+ verifyDeviceRevocation(record, recordKey)194+ }) return null128195 // Return entries with the display name capped so every consumer (registry129196 // upserts, pending-vouch queue, key-rotation alerts) stores the bounded130197 // name. The signature above was verified against the raw body.@@ -163,10 +230,6 @@163230 164231 private fun normaliseManifestEntry(entry: ManifestDeviceEntry): ManifestDeviceEntry? {165232 if (entry.deviceId.isBlank() || entry.deviceName.isBlank()) return null166- // Bound string fields — a peer could otherwise send multi-megabyte strings167- // that pass the format checks and bloat the canonical signature input.168- // deviceName is capped (not rejected) at MAX_DEVICE_NAME_CHARS, matching169- // the browser, so a long-but-honest name still syncs.170233 if (entry.deviceId.length > MAX_MANIFEST_STRING) return null171234 if (entry.deviceType !in setOf("extension", "android", "ios")) return null172235 if (!isHex(entry.longTermPublicKeyHex, 64) || !isHex(entry.signingPublicKeyHex, 64)) return null@@ -192,13 +255,20 @@192255 r.deviceId.isNotBlank() && r.deviceId.length <= MAX_MANIFEST_STRING &&193256 isHex(r.longTermPublicKeyHex.lowercase(), 64) &&194257 r.revokedByDeviceId.isNotBlank() && r.revokedByDeviceId.length <= MAX_MANIFEST_STRING &&258+ r.issuerDeviceId.isNotBlank() && r.issuerDeviceId.length <= MAX_MANIFEST_STRING &&259+ isHex(r.issuerSigningKeyHex.lowercase(), 64) &&260+ isHex(r.signatureHex, 128) &&195261 r.revokedAt >= 0L262+ 196263 197264 private fun revocationMap(r: DeviceRevocation): Map<String, Any> = linkedMapOf(198265 "deviceId" to r.deviceId,266+ "issuerDeviceId" to r.issuerDeviceId,267+ "issuerSigningKeyHex" to r.issuerSigningKeyHex.lowercase(),199268 "longTermPublicKeyHex" to r.longTermPublicKeyHex.lowercase(),200269 "revokedAt" to r.revokedAt,201270 "revokedByDeviceId" to r.revokedByDeviceId,271+ "signatureHex" to r.signatureHex.lowercase(),202272 )203273 204274 private fun manifestEntryMap(entry: ManifestDeviceEntry): Map<String, Any> {app/src/main/java/com/peachpasswords/sync/ForegroundSyncCoordinator.kt+3 −1
@@ -49,12 +49,14 @@4949 5050 private fun buildAdapter(): SyncVaultAdapter? {5151 if (!vault.isUnlocked.value || vault.syncVaultId() == null) return null52+ val credentials = loadOrCreateLocalIdentity(context)5253 return VaultSyncAdapter(5354 repo = vault,54- ourDeviceId = getOrCreateDeviceId(context),55+ ourDeviceId = credentials.deviceId,5556 pairedDevices = deviceStore,5657 pendingVouched = pendingVouchedStore,5758 syncAlerts = syncAlertStore,59+ localCredentials = credentials,5860 )5961 }6062 }app/src/main/java/com/peachpasswords/sync/LockedSyncSpoolStore.kt+4 −3
@@ -59,8 +59,9 @@5959 internal fun refresh(repo: VaultRepository) {6060 val snapshot = repo.syncMasterKeySnapshot() ?: return6161 val root = snapshot.key62- val deviceId = getOrCreateDeviceId(context)63- val keys = deriveSyncIdentityKeypair(root, deviceId)62+ val credentials = loadOrCreateLocalIdentity(context)63+ val deviceId = credentials.deviceId64+ val keys = localSyncKeypair(credentials)6465 try {6566 val prior = read()6667 val entries = repo.getEntries().associate { entry ->@@ -70,7 +71,7 @@7071 )7172 }7273 if (!repo.isSessionEpochCurrent(snapshot.epoch)) return73- val signing = deriveSyncSigningKeypair(root, deviceId)74+ val signing = localSigningKeypair(credentials)7475 write(7576 LockedSyncSpool(7677 vaultId = computeVaultId(root),app/src/main/java/com/peachpasswords/sync/PairedDeviceStore.kt+17 −1
@@ -293,6 +293,22 @@293293 awaitClose { prefs.unregisterOnSharedPreferenceChangeListener(listener) }294294 }295295 296+ override fun issuerSigningKeys(issuerDeviceId: String): Set<String> =297+ prefs.getStringSet("$KEY_ISSUER_KEYS_PREFIX$issuerDeviceId", emptySet())298+ .orEmpty().map(String::lowercase).toSet()299+300+ override fun appendIssuerSigningKey(issuerDeviceId: String, signingKeyHex: String): Boolean {301+ val key = signingKeyHex.lowercase()302+ if (issuerDeviceId.isBlank() || key.length != 64) return false303+ synchronized(mutationGate) {304+ val existing = issuerSigningKeys(issuerDeviceId)305+ if (key in existing) return true306+ return prefs.edit()307+ .putStringSet("$KEY_ISSUER_KEYS_PREFIX$issuerDeviceId", existing + key)308+ .commit()309+ }310+ }311+296312 private fun persistRevocations(records: List<DeviceRevocation>) {297313 prefs.edit()298314 .putString(KEY_REVOCATIONS, json.encodeToString(revocationSerializer, records))@@ -326,7 +342,7 @@326342 const val PREFS_FILE = "peach_paired_devices"327343 const val KEY_DEVICES = "paired_devices"328344 const val KEY_REVOCATIONS = "device_revocations"329- /** Bound the list so a hostile peer cannot grow storage without limit. */345+ const val KEY_ISSUER_KEYS_PREFIX = "issuer_signing_keys:"330346 const val MAX_REVOCATIONS = MAX_REVOCATION_RECORDS331347 val json = Json { encodeDefaults = true; ignoreUnknownKeys = true }332348 }app/src/main/java/com/peachpasswords/sync/PeachSyncService.kt+17 −20
@@ -106,8 +106,7 @@106106 credentials = if (master != null) {107107 lockedSyncSpool.refresh(vault)108108 deriveUnlockedListenerCredentials(109- masterKey = master,110- deviceId = getOrCreateDeviceId(this),109+ credentials = loadOrCreateLocalIdentity(this),111110 deviceName = getDeviceName(this),112111 relayUrl = RelaySettingsStore.readRelayUrl(this),113112 )@@ -127,15 +126,19 @@127126 when {128127 vault.syncVaultId() == null -> throw CancellationException("decoy session")129128 !vault.isUnlocked.value -> lockedSyncSpool.adapter()130- else -> VaultSyncAdapter(131- repo = vault,132- ourDeviceId = getOrCreateDeviceId(this),133- pairedDevices = deviceStore,134- pendingVouched = pendingVouchedStore,135- syncAlerts = syncAlertStore,136- )137- }129+ else -> {130+ val credentials = loadOrCreateLocalIdentity(this)131+ VaultSyncAdapter(132+ repo = vault,133+ ourDeviceId = credentials.deviceId,134+ pairedDevices = deviceStore,135+ pendingVouched = pendingVouchedStore,136+ syncAlerts = syncAlertStore,137+ localCredentials = credentials,138+ )139+ }138140 }141+ }139142 } finally {140143 master?.let(VaultCrypto::zero)141144 credentials?.keys?.secretKey?.let(VaultCrypto::zero)@@ -166,25 +169,19 @@166169 )167170 168171 internal fun deriveUnlockedListenerCredentials(169- masterKey: ByteArray,170- deviceId: String,172+ credentials: LocalIdentityCredentials,171173 deviceName: String,172174 relayUrl: String = Rendezvous.DEFAULT_RELAY_URL,173175 ): ReconnectListenerCredentials {174- val keys = deriveLocalSyncKeypair(masterKey, deviceId)175- val signing = deriveSyncSigningKeypair(masterKey, deviceId)176+ val keys = localSyncKeypair(credentials)176177 val identity = LocalDeviceIdentity(177- deviceId = deviceId,178+ deviceId = credentials.deviceId,178179 deviceName = deviceName,179180 deviceType = DeviceType.ANDROID,180181 longTermPublicKeyHex = pubkeyToHex(keys.publicKey),181- signingPublicKeyHex = pubkeyToHex(signing.publicKeyRaw),182+ signingPublicKeyHex = pubkeyToHex(credentials.ed25519PublicKey),182183 relayUrl = relayUrl,183184 )184- if (!MessageDigest.isEqual(keys.publicKey, hexToPubkey(identity.longTermPublicKeyHex))) {185- VaultCrypto.zero(keys.secretKey)186- throw IllegalStateException("derived reconnect identity mismatch")187- }188185 return ReconnectListenerCredentials(keys, identity)189186 }190187 app/src/main/java/com/peachpasswords/sync/PendingVouchedDeviceStore.kt+37 −2
@@ -29,6 +29,26 @@2929 interface PendingVouchedRegistry {3030 fun getAll(): List<PendingVouchedDevice>3131 fun upsert(device: PendingVouchedDevice)32+ /** Persist one pending introduction and report whether the durable commit succeeded. */33+ fun upsertAndReport(device: PendingVouchedDevice): Boolean {34+ return runCatching {35+ upsert(device)36+ true37+ }.getOrDefault(false)38+ }39+ /**40+ * Remove one pending introduction and report whether the durable commit41+ * succeeded. The default preserves compatibility for in-memory registries42+ * that only implement the legacy void removal API.43+ */44+ fun removeAndReport(id: String): Boolean {45+ return runCatching {46+ remove(id)47+ true48+ }.getOrDefault(false)49+ }50+51+ /** Legacy removal API retained for existing registry callers. */3252 fun remove(id: String)3353 3454 /**@@ -78,17 +98,32 @@7898 fun get(id: String): PendingVouchedDevice? = getAll().firstOrNull { it.deviceId == id }7999 80100 override fun upsert(device: PendingVouchedDevice) {101+ upsertAndReport(device)102+ }103+104+ override fun upsertAndReport(device: PendingVouchedDevice): Boolean {81105 // Vouch requests carry a peer-chosen name; bound it like every other82106 // inbound name so the pending queue cannot grow without limit.83107 val device = device.copy(deviceName = capDeviceName(device.deviceName))84108 val next = (getAll().filterNot { it.deviceId == device.deviceId } + device).takeLast(MAX_PENDING)85- persist(next)109+ return commitList(next)86110 }87111 88112 override fun remove(id: String) {89- persist(getAll().filterNot { it.deviceId == id })113+ removeAndReport(id)90114 }91115 116+ override fun removeAndReport(id: String): Boolean {117+ val before = getAll()118+ val after = before.filterNot { it.deviceId == id }119+ return commitWithRollback(before, after, ::commitList)120+ }121+122+ /**123+ * Remove a set of pending introductions synchronously and report failure.124+ * Implementations must linearize the whole batch; the default exists only125+ * for small in-memory test registries that have no durable store.126+ */92127 override fun removeBatch(ids: Set<String>): Boolean {93128 if (ids.isEmpty()) return true94129 val before = getAll()app/src/main/java/com/peachpasswords/sync/RelayAdoptionHost.kt+4 −0
@@ -203,6 +203,10 @@203203 sourceDeps.applyLicense(license)204204 }205205 override suspend fun onConsent(request: AdoptionFrame.Request): Boolean = true206+ override suspend fun persistPendingHolder(request: AdoptionFrame.Request, nowMs: Long) =207+ sourceDeps.persistPendingHolder(request, nowMs)208+ override suspend fun completePendingHolder(request: AdoptionFrame.Request, device: PairedDevice) =209+ sourceDeps.completePendingHolder(request, device)206210 override suspend fun upsertPairedDevice(device: PairedDevice) {207211 sourceDeps.upsertPairedDevice(device)208212 }app/src/main/java/com/peachpasswords/sync/RelayAdoptionReceiver.kt+4 −0
@@ -381,6 +381,10 @@381381 sourceDeps.applyLicense(license)382382 }383383 override suspend fun onConsent(request: AdoptionFrame.Request): Boolean = true384+ override suspend fun persistPendingHolder(request: AdoptionFrame.Request, nowMs: Long) =385+ sourceDeps.persistPendingHolder(request, nowMs)386+ override suspend fun completePendingHolder(request: AdoptionFrame.Request, device: PairedDevice) =387+ sourceDeps.completePendingHolder(request, device)384388 override suspend fun upsertPairedDevice(device: PairedDevice) {385389 sourceDeps.upsertPairedDevice(device)386390 }app/src/main/java/com/peachpasswords/sync/Rendezvous.kt+16 −14
@@ -15,7 +15,7 @@1515 const val PAIRING_TOKEN_BYTES = 161616 1717 private val secretInfo = "peach-rendezvous-secret-v1".encodeToByteArray()18- private val meshSecretInfo = "peach-mesh-rendezvous-v1".encodeToByteArray()18+ private val meshSecretInfo = "peach-mesh-rendezvous-v2".encodeToByteArray()1919 private val windowInfo = "peach-rendezvous-v1".encodeToByteArray()2020 2121 fun deriveSecret(handshakeHash: ByteArray): ByteArray {@@ -24,26 +24,28 @@2424 }2525 2626 /**27- * Cross-client manifest-introduced mesh capability:28- * info = UTF8("peach-mesh-rendezvous-v1") || lowPublicKey || highPublicKey29- * secret = HKDF-SHA256(vaultRoot, salt="", info, 32)27+ * Mesh capability v2: X25519 with the local random private key, followed28+ * by HKDF-SHA256 over the canonical unsigned public-key ordering.3029 */3130 fun deriveMeshSecret(32- vaultRoot: ByteArray,31+ ourPrivateKey: ByteArray,3332 ourPublicKey: ByteArray,3433 peerPublicKey: ByteArray,3534 ): ByteArray {36- require(vaultRoot.size == 32) { "vault root must be exactly 32 bytes" }37- require(ourPublicKey.size == 32 && peerPublicKey.size == 32) {38- "mesh public keys must be exactly 32 bytes"35+ require(ourPrivateKey.size == 32 && ourPublicKey.size == 32 && peerPublicKey.size == 32)36+ require(compareUnsigned(ourPublicKey, peerPublicKey) != 0)37+ val shared = ByteArray(32)38+ try {39+ org.bouncycastle.crypto.params.X25519PrivateKeyParameters(ourPrivateKey, 0)40+ .generateSecret(org.bouncycastle.crypto.params.X25519PublicKeyParameters(peerPublicKey, 0), shared, 0)41+ require(shared.any { it.toInt() != 0 }) { "mesh low-order point rejected" }42+ val low = if (compareUnsigned(ourPublicKey, peerPublicKey) < 0) ourPublicKey else peerPublicKey43+ val high = if (low === ourPublicKey) peerPublicKey else ourPublicKey44+ return hkdf(shared, meshSecretInfo + low + high)45+ } finally {46+ shared.fill(0)3947 }40- val order = compareUnsigned(ourPublicKey, peerPublicKey)41- require(order != 0) { "mesh peers must have distinct public keys" }42- val low = if (order < 0) ourPublicKey else peerPublicKey43- val high = if (order < 0) peerPublicKey else ourPublicKey44- return hkdf(vaultRoot, meshSecretInfo + low + high)4548 }46-4749 /**4850 * Cross-client encoding contract:4951 * info = UTF8("peach-rendezvous-v1") || uint64be(windowIndex)app/src/main/java/com/peachpasswords/sync/SyncIdentity.kt+23 −0
@@ -16,6 +16,29 @@1616 val privateKey: Ed25519PrivateKeyParameters,1717 val publicKeyRaw: ByteArray,1818 )19+/** Random per-installation credentials; private material is stored only in the local vault. */20+data class LocalIdentityCredentials(21+ val deviceId: String,22+ val x25519PrivateKey: ByteArray,23+ val x25519PublicKey: ByteArray,24+ val ed25519Seed: ByteArray,25+ val ed25519PublicKey: ByteArray,26+)27+28+fun randomLocalIdentityCredentials(deviceId: String, random: java.security.SecureRandom = java.security.SecureRandom()): LocalIdentityCredentials {29+ require(deviceId.isNotBlank())30+ val x = ByteArray(32).also(random::nextBytes)31+ val e = ByteArray(32).also(random::nextBytes)32+ val xPrivate = X25519PrivateKeyParameters(x, 0)33+ val ePrivate = Ed25519PrivateKeyParameters(e, 0)34+ return LocalIdentityCredentials(deviceId, x, xPrivate.generatePublicKey().encoded, e, ePrivate.generatePublicKey().encoded)35+}36+37+fun localSyncKeypair(credentials: LocalIdentityCredentials): SyncIdentityKeypair =38+ SyncIdentityKeypair(credentials.x25519PublicKey.copyOf(), credentials.x25519PrivateKey.copyOf())39+40+fun localSigningKeypair(credentials: LocalIdentityCredentials): SyncSigningKeypair =41+ SyncSigningKeypair(Ed25519PrivateKeyParameters(credentials.ed25519Seed, 0), credentials.ed25519PublicKey.copyOf())1942 2043 private val SYNC_IDENTITY_SALT = "peach-sync-identity-v1".encodeToByteArray()2144 private val SYNC_SIGNING_SALT = "peach-sync-signing-v1".encodeToByteArray()app/src/main/java/com/peachpasswords/sync/SyncMessage.kt+7 −3
@@ -110,12 +110,16 @@110110 @Serializable111111 data class DeviceRevocation(112112 val deviceId: String,113- /** Load-bearing, not descriptive: `deviceId` is whatever an issuing114- * manifest says it is, so the key is what re-vouching is matched against.115- * [NO_KEY_SENTINEL] means no key was ever stored and matches nothing. */113+ /** Load-bearing identity key used to prevent re-vouching under a new id. */116114 val longTermPublicKeyHex: String,117115 val revokedAt: Long,118116 val revokedByDeviceId: String,117+ /** Immutable issuer identity carried by the record itself. */118+ val issuerDeviceId: String = revokedByDeviceId,119+ /** Signing key version/binding used for this record; never rewrite history. */120+ val issuerSigningKeyHex: String = "",121+ /** Ed25519 signature over [canonicalDeviceRevocation]. */122+ val signatureHex: String = "",119123 )120124 121125 @Serializableapp/src/main/java/com/peachpasswords/sync/VaultAdopt.kt+4 −0
@@ -328,6 +328,8 @@328328 * carries no continuity between attempts.329329 */330330 suspend fun onConsent(request: AdoptionFrame.Request): Boolean331+ suspend fun persistPendingHolder(request: AdoptionFrame.Request, nowMs: Long): Boolean = true332+ suspend fun completePendingHolder(request: AdoptionFrame.Request, device: PairedDevice): Boolean = true331333 suspend fun upsertPairedDevice(device: PairedDevice)332334 fun hasDeviceIdentityCollision(device: PairedDevice): Boolean = false333335 /**@@ -563,6 +565,7 @@563565 throw IllegalStateException("ADOPT_PRO_REQUIRED")564566 }565567 568+ if (!deps.persistPendingHolder(request, nowMs())) return null566569 val rootKeyHex = deps.rootKeyHex()567570 if (!validateRootKeyHex(rootKeyHex)) throw IllegalStateException("ADOPT_INVALID_ROOT_KEY")568571 @@ -632,6 +635,7 @@632635 deps.upsertPairedDevice(device)633636 sendFrame(channel, AdoptionFrame.Complete)634637 if (!isAdoptApplied(receiveFrame(channel))) return null638+ if (!deps.completePendingHolder(request, device)) return null635639 return device636640 }637641 }app/src/main/java/com/peachpasswords/sync/VaultSyncAdapter.kt+55 −31
@@ -37,6 +37,7 @@3737 private val syncAlerts: SyncAlertRecorder? = null,3838 private var remoteDeviceName: String = "paired device",3939 override val supportsDeviceManifest: Boolean = pairedDevices != null && pendingVouched != null,40+ private val localCredentials: LocalIdentityCredentials? = null,4041 ) : SyncVaultAdapter {4142 4243 override suspend fun computeVaultId(): String =@@ -136,27 +137,15 @@136137 137138 override suspend fun buildOutgoingDeviceManifest(): SignedDeviceManifest? {138139 val registry = pairedDevices ?: return null139- val snapshot = requireMasterKeySnapshot()140- val master = snapshot.key141- return try {142- val signing = deriveSyncSigningKeypair(master, ourDeviceId)143- val revoked = registry.listRevocations()144- val revokedIds = revoked.map { it.deviceId }.toSet()145- val devices = registry.getAll()146- .filterNot { revokedIds.contains(it.deviceId) }147- .mapNotNull { it.toManifestEntry() }148- .map { it.copy(vouchDepth = if (it.deviceId == ourDeviceId) 0 else it.vouchDepth + 1) }149- val manifest = buildSignedDeviceManifest(150- ourDeviceId,151- devices,152- signing.privateKey,153- revoked = revoked,154- )155- if (!repo.isSessionEpochCurrent(snapshot.epoch)) throw VaultLockedException()156- manifest157- } finally {158- VaultCrypto.zero(master)159- }140+ val signing = localCredentials?.let(::localSigningKeypair)141+ ?: throw IllegalStateException("identity_migration_required")142+ val revoked = registry.listRevocations()143+ val revokedIds = revoked.map { it.deviceId }.toSet()144+ val devices = registry.getAll()145+ .filterNot { revokedIds.contains(it.deviceId) }146+ .mapNotNull { it.toManifestEntry() }147+ .map { it.copy(vouchDepth = if (it.deviceId == ourDeviceId) 0 else it.vouchDepth + 1) }148+ return buildSignedDeviceManifest(ourDeviceId, devices, signing.privateKey, revoked = revoked)160149 }161150 162151 override suspend fun applyIncomingDeviceManifest(@@ -170,13 +159,21 @@170159 // Direct and bounded-vouch issuers may propagate the signed device pool.171160 if (issuer.trustSource != "direct" && issuer.trustSource != "vouched") return172161 if (issuer.vouchDepth >= MAX_VOUCH_DEPTH) return173- val signingKey = issuer.signingPublicKeyHex?.lowercase()?.takeIf { it.length == 64 } ?: return174- val body = verifyDeviceManifest(manifest, hexToPubkey(signingKey)) ?: return162+ val currentSigningKey = issuer.signingPublicKeyHex?.lowercase()?.takeIf { it.length == 64 } ?: return163+ val knownIssuerKeys = registry.issuerSigningKeys(issuer.deviceId) + currentSigningKey164+ // Historical keys and the persisted current key remain valid; mutable165+ // device metadata never rewrites the issuer's key history.166+ val verified = knownIssuerKeys.firstNotNullOfOrNull { candidate ->167+ runCatching {168+ verifyDeviceManifest(manifest, hexToPubkey(candidate))?.let { candidate to it }169+ }.getOrNull()170+ } ?: return171+ val (signingKey, body) = verified175172 if (body.issuerDeviceId != issuer.deviceId) return176173 val snapshot = requireMasterKeySnapshot()177174 val master = snapshot.key178- val localKeys = deriveSyncIdentityKeypair(master, ourDeviceId)179-175+ val localKeys = localCredentials?.let(::localSyncKeypair)176+ ?: throw IllegalStateException("identity_migration_required")180177 try {181178 if (!repo.isSessionEpochCurrent(snapshot.epoch)) return182179 // Stage the complete result against one read-only registry snapshot.@@ -215,7 +212,7 @@215212 }216213 if (entry.vouchDepth > issuer.vouchDepth + 1) continue217214 val existing = stagedUpserts[entry.deviceId] ?: registry.get(entry.deviceId)218- val meshRoute = deriveManifestMeshRoute(master, localKeys.publicKey, entry)215+ val meshRoute = deriveManifestMeshRoute(localKeys.secretKey, localKeys.publicKey, entry)219216 if (existing == null) {220217 if (meshRoute == null) continue221218 stagedUpserts[entry.deviceId] = PairedDevice(@@ -232,13 +229,39 @@232229 pairedAt = entry.pairedAt,233230 )234231 } else {232+ val incomingLongTermKey = entry.longTermPublicKeyHex.lowercase()233+ val incomingSigningKey = entry.signingPublicKeyHex.lowercase()234+ // Direct pairing is SAS-pinned. A manifest issuer is never235+ // authorized to rotate either identity key, even if the236+ // entry is correctly vouched and the manifest verifies.237+ // Drop the entry wholesale rather than retaining mutable238+ // metadata alongside an untrusted identity transition.239+ val directLongTermChanged = existing.trustSource == "direct" &&240+ existing.longTermPublicKeyHex?.let {241+ !CryptoCompare.hex(it, incomingLongTermKey)242+ } == true243+ val directSigningChanged = existing.trustSource == "direct" &&244+ existing.signingPublicKeyHex?.let {245+ !CryptoCompare.hex(it, incomingSigningKey)246+ } == true247+ if (directLongTermChanged || directSigningChanged) {248+ deviceKeyRotationAlert(existing, entry, System.currentTimeMillis())249+ ?.let(stagedAlerts::add)250+ continue251+ }235252 deviceKeyRotationAlert(existing, entry, System.currentTimeMillis())?.let(stagedAlerts::add)236253 stagedUpserts[entry.deviceId] = existing.copy(237254 deviceName = existing.deviceName?.takeIf { it.isNotBlank() }238255 ?: entry.deviceName,239256 deviceType = entry.deviceType,240- longTermPublicKeyHex = entry.longTermPublicKeyHex.lowercase(),241- signingPublicKeyHex = entry.signingPublicKeyHex.lowercase(),257+ // Direct keys are immutable; preserve the SAS-pinned258+ // values even when an old record lacks one field.259+ longTermPublicKeyHex =260+ if (existing.trustSource == "direct") existing.longTermPublicKeyHex261+ else incomingLongTermKey,262+ signingPublicKeyHex =263+ if (existing.trustSource == "direct") existing.signingPublicKeyHex264+ else incomingSigningKey,242265 vouchDepth = entry.vouchDepth,243266 wsPort = existing.wsPort ?: entry.wsPort,244267 rendezvousSecretHex =@@ -271,6 +294,7 @@271294 val pendingIds = batch.removals + stagedUpserts.keys272295 val priorPending = pending.getAll().filter { it.deviceId in pendingIds }273296 val committed = repo.withSessionEpochCommit(snapshot.epoch) {297+ if (!registry.appendIssuerSigningKey(issuer.deviceId, signingKey)) return@withSessionEpochCommit false274298 val pendingRemoved = runCatching { pending.removeBatch(pendingIds) }.getOrDefault(false)275299 if (!pendingRemoved) {276300 pending.restoreBatch(priorPending)@@ -297,20 +321,20 @@297321 }298322 299323 private fun deriveManifestMeshRoute(300- masterKey: ByteArray,324+ localPrivateKey: ByteArray,301325 localPublicKey: ByteArray,302326 entry: ManifestDeviceEntry,303327 ): Pair<String, String>? = runCatching {304328 val relayUrl = Rendezvous.normalizeRelayUrl(entry.relayUrl ?: return null)305329 val secret = Rendezvous.deriveMeshSecret(306- masterKey,330+ localPrivateKey,307331 localPublicKey,308332 hexToPubkey(entry.longTermPublicKeyHex),309333 )310334 try {311335 Rendezvous.bytesToHex(secret) to relayUrl312336 } finally {313- secret.fill(0)337+ VaultCrypto.zero(secret)314338 }315339 }.getOrNull()316340 app/src/main/java/com/peachpasswords/ui/pairing/AdoptVaultViewModel.kt+40 −11
@@ -23,9 +23,10 @@2323 import com.peachpasswords.sync.VaultStatus2424 import com.peachpasswords.sync.buildLocalIdentity2525 import com.peachpasswords.sync.computeVaultId26-import com.peachpasswords.sync.deriveLocalSyncKeypair26+import com.peachpasswords.sync.loadOrCreateLocalIdentity27+import com.peachpasswords.sync.localSyncKeypair2728 import com.peachpasswords.sync.getDeviceName28-import com.peachpasswords.sync.getOrCreateDeviceId29+import com.peachpasswords.sync.loadOrCreateLocalIdentity2930 import com.peachpasswords.sync.hexToPubkey3031 import com.peachpasswords.sync.rotateDeviceId3132 import com.peachpasswords.sync.parsePairingInvitation@@ -181,8 +182,9 @@181182 _state.value = AdoptVaultUiState.Connecting182183 protocolError = null183184 184- val keys = deriveLocalSyncKeypair(master, getOrCreateDeviceId(appContext))185- val identity = buildLocalIdentity(appContext, master)185+ val credentials = loadOrCreateLocalIdentity(appContext)186+ val keys = localSyncKeypair(credentials)187+ val identity = buildLocalIdentity(appContext, credentials)186188 VaultCrypto.zero(master)187189 adoptionJob = viewModelScope.launch {188190 try {@@ -322,10 +324,12 @@322324 }323325 324326 override suspend fun applySnapshot(entries: Map<String, String>, tombstones: Map<String, Long>, duressSlot: String?) {327+ val credentials = loadOrCreateLocalIdentity(appContext)325328 val adapter = VaultSyncAdapter(326329 repo = vault,327- ourDeviceId = getOrCreateDeviceId(appContext),330+ ourDeviceId = credentials.deviceId,328331 pairedDevices = devices,332+ localCredentials = credentials,329333 )330334 adapter.applyEntries(entries)331335 adapter.applyTombstones(tombstones)@@ -347,13 +351,13 @@347351 // the receiver into the full mesh pool. The receiver must348352 // already have the source as a paired device (see applySnapshot349353 // above which calls upsertPairedDevice via the Grant path),350- // so applyIncomingDeviceManifest can resolve the issuer by its351- // transport static key and verify the manifest signature.354+ val credentials = loadOrCreateLocalIdentity(appContext)352355 val adapter = VaultSyncAdapter(353356 repo = vault,354- ourDeviceId = getOrCreateDeviceId(appContext),357+ ourDeviceId = credentials.deviceId,355358 pairedDevices = devices,356359 pendingVouched = pendingVouchedStore,360+ localCredentials = credentials,357361 )358362 adapter.applyIncomingDeviceManifest(manifest, authenticatedRemoteStaticPublicKey)359363 }@@ -390,7 +394,29 @@390394 }391395 392396 override suspend fun onConsent(request: AdoptionFrame.Request): Boolean = true397+ override suspend fun persistPendingHolder(request: AdoptionFrame.Request, nowMs: Long): Boolean {398+ return runCatching {399+ pendingVouchedStore.upsertAndReport(400+ com.peachpasswords.sync.PendingVouchedDevice(401+ deviceId = request.sessionRequestId,402+ deviceName = request.deviceName,403+ deviceType = request.deviceType,404+ longTermPublicKeyHex = identity.longTermPublicKeyHex,405+ signingPublicKeyHex = identity.signingPublicKeyHex,406+ pairedAt = nowMs,407+ receivedAt = nowMs,408+ vouchedByDeviceId = identity.deviceId,409+ ),410+ )411+ }.getOrDefault(false)412+ }393413 414+ override suspend fun completePendingHolder(request: AdoptionFrame.Request, device: PairedDevice): Boolean {415+ return runCatching {416+ pendingVouchedStore.removeAndReport(request.sessionRequestId)417+ }.getOrDefault(false)418+ }419+394420 override fun hasDeviceIdentityCollision(device: PairedDevice): Boolean =395421 devices.hasIdentityCollision(device)396422 @@ -412,10 +438,12 @@412438 }413439 414440 override suspend fun vaultSnapshot(): Pair<Map<String, String>, Map<String, Long>>? {441+ val credentials = loadOrCreateLocalIdentity(appContext)415442 val adapter = VaultSyncAdapter(416443 repo = vault,417- ourDeviceId = getOrCreateDeviceId(appContext),444+ ourDeviceId = credentials.deviceId,418445 pairedDevices = devices,446+ localCredentials = credentials,419447 )420448 val entryManifest = adapter.buildEntryManifest()421449 val entryIds = entryManifest.keys.toList()@@ -423,12 +451,13 @@423451 val tombstones = adapter.buildTombstoneManifest()424452 return entries to tombstones425453 }426-427454 override suspend fun outgoingDeviceManifest(): SignedDeviceManifest? {455+ val credentials = loadOrCreateLocalIdentity(appContext)428456 val adapter = VaultSyncAdapter(429457 repo = vault,430- ourDeviceId = getOrCreateDeviceId(appContext),458+ ourDeviceId = credentials.deviceId,431459 pairedDevices = devices,460+ localCredentials = credentials,432461 )433462 return adapter.buildOutgoingDeviceManifest()434463 }app/src/main/java/com/peachpasswords/ui/pairing/CodePairViewModel.kt+34 −8
@@ -14,16 +14,18 @@1414 import com.peachpasswords.sync.RelaySettingsStore1515 import com.peachpasswords.sync.RelayDecision1616 import com.peachpasswords.sync.SyncMode17-import com.peachpasswords.sync.AdoptionSourceDeps17+import com.peachpasswords.sync.PendingVouchedDevice18+import com.peachpasswords.sync.PendingVouchedDeviceStore1819 import com.peachpasswords.sync.AdoptionFrame20+import com.peachpasswords.sync.AdoptionSourceDeps1921 import com.peachpasswords.sync.LocalDeviceIdentity2022 import com.peachpasswords.sync.PairedDevice2123 import com.peachpasswords.sync.PairedDeviceStore2224 import com.peachpasswords.sync.SignedDeviceManifest2325 import com.peachpasswords.sync.VaultSyncAdapter2426 import com.peachpasswords.sync.buildLocalIdentity25-import com.peachpasswords.sync.deriveLocalSyncKeypair26-import com.peachpasswords.sync.getOrCreateDeviceId27+import com.peachpasswords.sync.loadOrCreateLocalIdentity28+import com.peachpasswords.sync.localSyncKeypair2729 import com.peachpasswords.sync.rotateDeviceId2830 import com.peachpasswords.vault.VaultCrypto2931 import com.peachpasswords.vault.VaultRepository@@ -61,6 +63,7 @@6163 private val relaySettings: RelaySettingsStore,6264 private val backgroundSync: BackgroundSyncPreference,6365 private val deviceStore: PairedDeviceStore,66+ private val pendingVouchedStore: PendingVouchedDeviceStore,6467 private val license: LicenseRepository,6568 @ApplicationContext private val appContext: Context,6669 ) : ViewModel() {@@ -107,9 +110,9 @@107110 return108111 }109112 PeachSyncService.start(appContext)110-111- val keys = deriveLocalSyncKeypair(master, getOrCreateDeviceId(appContext))112- val identity = buildLocalIdentity(appContext, master)113+ val credentials = loadOrCreateLocalIdentity(appContext)114+ val keys = localSyncKeypair(credentials)115+ val identity = buildLocalIdentity(appContext, credentials)113116 VaultCrypto.zero(master)114117 startRelay(keys.secretKey, keys.publicKey, identity, sourceDeps(identity))115118 }@@ -186,6 +189,25 @@186189 187190 // Opening this source screen while unlocked is the source-side188191 // consent. The scanning device confirms the SAS before any grant.192+ override suspend fun persistPendingHolder(request: AdoptionFrame.Request, nowMs: Long): Boolean =193+ runCatching {194+ pendingVouchedStore.upsertAndReport(195+ PendingVouchedDevice(196+ deviceId = request.sessionRequestId,197+ deviceName = request.deviceName,198+ deviceType = request.deviceType,199+ longTermPublicKeyHex = identity.longTermPublicKeyHex,200+ signingPublicKeyHex = identity.signingPublicKeyHex,201+ pairedAt = nowMs,202+ receivedAt = nowMs,203+ vouchedByDeviceId = identity.deviceId,204+ ),205+ )206+ }.getOrDefault(false)207+ override suspend fun completePendingHolder(request: AdoptionFrame.Request, device: PairedDevice): Boolean =208+ runCatching {209+ pendingVouchedStore.removeAndReport(request.sessionRequestId)210+ }.getOrDefault(false)189211 override suspend fun onConsent(request: AdoptionFrame.Request): Boolean = true190212 191213 override fun hasDeviceIdentityCollision(device: PairedDevice): Boolean =@@ -209,10 +231,12 @@209231 }210232 211233 override suspend fun vaultSnapshot(): Pair<Map<String, String>, Map<String, Long>>? {234+ val credentials = loadOrCreateLocalIdentity(appContext)212235 val adapter = VaultSyncAdapter(213236 repo = vault,214- ourDeviceId = getOrCreateDeviceId(appContext),237+ ourDeviceId = credentials.deviceId,215238 pairedDevices = deviceStore,239+ localCredentials = credentials,216240 )217241 val entryManifest = adapter.buildEntryManifest()218242 val entryIds = entryManifest.keys.toList()@@ -222,10 +246,12 @@222246 }223247 224248 override suspend fun outgoingDeviceManifest(): SignedDeviceManifest? {249+ val credentials = loadOrCreateLocalIdentity(appContext)225250 val adapter = VaultSyncAdapter(226251 repo = vault,227- ourDeviceId = getOrCreateDeviceId(appContext),252+ ourDeviceId = credentials.deviceId,228253 pairedDevices = deviceStore,254+ localCredentials = credentials,229255 )230256 return adapter.buildOutgoingDeviceManifest()231257 }app/src/main/java/com/peachpasswords/ui/sync/SyncViewModel.kt+5 −4
@@ -19,7 +19,7 @@1919 import com.peachpasswords.sync.SyncOutcomeStore2020 import com.peachpasswords.sync.SyncOutcomeSummary2121 import com.peachpasswords.sync.VaultSyncAdapter22-import com.peachpasswords.sync.getOrCreateDeviceId22+import com.peachpasswords.sync.loadOrCreateLocalIdentity2323 import com.peachpasswords.vault.VaultRepository2424 import dagger.hilt.android.lifecycle.HiltViewModel2525 import dagger.hilt.android.qualifiers.ApplicationContext@@ -145,8 +145,7 @@145145 */146146 fun unpairDevice(id: String) = viewModelScope.launch {147147 if (isDecoySession()) return@launch148- deviceStore.revoke(id, getOrCreateDeviceId(context))149- // Revocation is mesh state, not just dropping the local row.148+ deviceStore.revoke(id, loadOrCreateLocalIdentity(context).deviceId)150149 PeachSyncService.start(context)151150 }152151 @@ -210,12 +209,14 @@210209 /** Adapter over the live vault; null while the vault is locked. */211210 fun buildAdapter(): SyncVaultAdapter? {212211 if (!vault.isUnlocked.value || isDecoySession()) return null212+ val credentials = loadOrCreateLocalIdentity(context)213213 return VaultSyncAdapter(214214 repo = vault,215- ourDeviceId = getOrCreateDeviceId(context),215+ ourDeviceId = credentials.deviceId,216216 pairedDevices = deviceStore,217217 pendingVouched = pendingVouchedStore,218218 syncAlerts = syncAlertStore,219+ localCredentials = credentials,219220 )220221 }221222 app/src/test/java/com/peachpasswords/sync/DeviceManifestSupportTest.kt+28 −0
@@ -137,4 +137,32 @@137137 )138138 assertNull(verifyDeviceManifest(manifest, signing.publicKeyRaw, nowMs = 1_000L))139139 }140+ @Test fun revocation_signature_binds_immutable_fields() {141+ val record = signDeviceRevocation(142+ DeviceRevocation("peer", "aa".repeat(32), 42L, "issuer"),143+ signing.privateKey,144+ )145+ assertEquals(146+ """{"deviceId":"peer","issuerDeviceId":"issuer","issuerSigningKeyHex":"${pubkeyToHex(signing.publicKeyRaw)}","longTermPublicKeyHex":"${"aa".repeat(32)}","revokedAt":42,"revokedByDeviceId":"issuer"}""",147+ canonicalDeviceRevocation(record),148+ )149+ assertEquals(true, verifyDeviceRevocation(record, signing.publicKeyRaw))150+ assertEquals(false, verifyDeviceRevocation(record.copy(deviceId = "attacker"), signing.publicKeyRaw))151+ }152+ @Test fun forwarding_preserves_original_revocation_signature() {153+ val original = signDeviceRevocation(154+ DeviceRevocation("peer", "aa".repeat(32), 42L, "issuer"),155+ signing.privateKey,156+ )157+ val forwarder = deriveSyncSigningKeypair(master, "forwarder")158+ val forwarded = buildSignedDeviceManifest(159+ issuerDeviceId = "forwarder",160+ devices = emptyList(),161+ signingPrivateKey = forwarder.privateKey,162+ nowMs = 1_000L,163+ revoked = listOf(original),164+ )165+ assertEquals(original, forwarded.body.revoked.single())166+ assertNotNull(verifyDeviceManifest(forwarded, forwarder.publicKeyRaw, nowMs = 1_000L))167+ }140168 }app/src/test/java/com/peachpasswords/sync/RelayAdoptionHostTest.kt+7 −7
@@ -90,8 +90,8 @@9090 val token = "AAECAwQFBgcICQoLDA0ODw"9191 val relay = "wss://relay.example.test"9292 val sourceRoot = ByteArray(32) { (it + 1).toByte() }93- val sourceKeys = deriveLocalSyncKeypair(sourceRoot, "source-id")94- val receiverKeys = deriveLocalSyncKeypair(sourceRoot, "receiver-id")93+ val sourceKeys = localSyncKeypair(randomLocalIdentityCredentials("source-id"))94+ val receiverKeys = localSyncKeypair(randomLocalIdentityCredentials("receiver-id"))9595 val sourceIdentity = identity("source", sourceKeys.publicKey)9696 val receiverIdentity = identity("receiver", receiverKeys.publicKey)9797 var sourceStored: PairedDevice? = null@@ -168,7 +168,7 @@168168 val (sourceSocket, receiverSocket) = socketPair()169169 val token = "AAECAwQFBgcICQoLDA0ODw"170170 val root = ByteArray(32) { (it + 7).toByte() }171- val sourceKeys = deriveLocalSyncKeypair(root, "source-id")171+ val sourceKeys = localSyncKeypair(randomLocalIdentityCredentials("source-id"))172172 val rootRequested = AtomicBoolean(false)173173 174174 val sourceJob = async {@@ -214,8 +214,8 @@214214 val token = "AAECAwQFBgcICQoLDA0ODw"215215 val relay = "wss://relay.example.test"216216 val root = ByteArray(32) { (it + 3).toByte() }217- val sourceKeys = deriveLocalSyncKeypair(root, "source-id")218- val receiverKeys = deriveLocalSyncKeypair(root, "receiver-id")217+ val sourceKeys = localSyncKeypair(randomLocalIdentityCredentials("source-id"))218+ val receiverKeys = localSyncKeypair(randomLocalIdentityCredentials("receiver-id"))219219 val sourceIdentity = identity("source", sourceKeys.publicKey)220220 val receiverIdentity = identity("receiver", receiverKeys.publicKey)221221 var sourceStored: PairedDevice? = null@@ -288,11 +288,11 @@288288 }289289 290290 @Test fun `receiver rejection is encrypted and source never reads root`() = runBlocking {291- val (sourceSocket, receiverSocket) = socketPair()292291 val token = "AAECAwQFBgcICQoLDA0ODw"293292 val relay = "wss://relay.example.test"294293 val root = ByteArray(32) { (it + 9).toByte() }295- val sourceKeys = deriveLocalSyncKeypair(root, "source-id")294+ val sourceKeys = localSyncKeypair(randomLocalIdentityCredentials("source-id"))295+ val (sourceSocket, receiverSocket) = socketPair()296296 val rootRequested = AtomicBoolean(false)297297 298298 val sourceJob = async {app/src/test/java/com/peachpasswords/sync/RelayAdoptionReceiverTest.kt+14 −13
@@ -78,8 +78,8 @@7878 val token = "AAECAwQFBgcICQoLDA0ODw"7979 val relay = "wss://relay.example.test"8080 val root = ByteArray(32) { (it + 3).toByte() }81- val sourceKeys = deriveLocalSyncKeypair(root, "source-id")82- val receiverKeys = deriveLocalSyncKeypair(root, "receiver-id")81+ val sourceKeys = localSyncKeypair(randomLocalIdentityCredentials("source-id"))82+ val receiverKeys = localSyncKeypair(randomLocalIdentityCredentials("receiver-id"))8383 val sourceIdentity = identity("source", sourceKeys.publicKey)8484 val receiverIdentity = identity("receiver", receiverKeys.publicKey)8585 val (entries, tombstones) = smallSnapshot()@@ -170,8 +170,8 @@170170 val token = "AAECAwQFBgcICQoLDA0ODw"171171 val relay = "wss://relay.example.test"172172 val root = ByteArray(32) { (it + 5).toByte() }173- val sourceKeys = deriveLocalSyncKeypair(root, "source-id")174- val receiverKeys = deriveLocalSyncKeypair(root, "receiver-id")173+ val sourceKeys = localSyncKeypair(randomLocalIdentityCredentials("source-id"))174+ val receiverKeys = localSyncKeypair(randomLocalIdentityCredentials("receiver-id"))175175 val sourceIdentity = identity("source", sourceKeys.publicKey)176176 val receiverIdentity = identity("receiver", receiverKeys.publicKey)177177 var sourceStored: PairedDevice? = null@@ -249,8 +249,8 @@249249 val token = "AAECAwQFBgcICQoLDA0ODw"250250 val relay = "wss://relay.example.test"251251 val root = ByteArray(32) { (it + 7).toByte() }252- val sourceKeys = deriveLocalSyncKeypair(root, "old-source-id")253- val receiverKeys = deriveLocalSyncKeypair(root, "receiver-id")252+ val sourceKeys = localSyncKeypair(randomLocalIdentityCredentials("old-source-id"))253+ val receiverKeys = localSyncKeypair(randomLocalIdentityCredentials("receiver-id"))254254 val sourceIdentity = identity("old-source", sourceKeys.publicKey)255255 val receiverIdentity = identity("receiver", receiverKeys.publicKey)256256 var receiverApplied = false@@ -345,9 +345,10 @@345345 val token = "AAECAwQFBgcICQoLDA0ODw"346346 val relay = "wss://relay.example.test"347347 val root = ByteArray(32) { (it + 13).toByte() }348- val sourceKeys = deriveLocalSyncKeypair(root, "source-id")349- val receiverKeys = deriveLocalSyncKeypair(root, "receiver-id")350- val sourceSigning = deriveSyncSigningKeypair(root, "source-id")348+ val sourceCredentials = randomLocalIdentityCredentials("source-id")349+ val sourceKeys = localSyncKeypair(sourceCredentials)350+ val receiverKeys = localSyncKeypair(randomLocalIdentityCredentials("receiver-id"))351+ val sourceSigning = localSigningKeypair(sourceCredentials)351352 val sourceIdentity = identity("source", sourceKeys.publicKey, pubkeyToHex(sourceSigning.publicKeyRaw))352353 val receiverIdentity = identity("receiver", receiverKeys.publicKey)353354 @@ -596,8 +597,8 @@596597 @Test fun `receiver rejects an ACK static that does not match the pinned key`() = runBlocking {597598 val (phoneSocket, mitmSocket) = socketPair()598599 val root = ByteArray(32) { (it + 3).toByte() }599- val sourceKeys = deriveLocalSyncKeypair(root, "source-id")600- val attackerKeys = deriveLocalSyncKeypair(root, "attacker-id")600+ val sourceKeys = localSyncKeypair(randomLocalIdentityCredentials("source-id"))601+ val attackerKeys = localSyncKeypair(randomLocalIdentityCredentials("attacker-id"))601602 602603 // The result is captured inside the job: an exception escaping a child603604 // coroutine cancels the parent scope before await() can observe it.@@ -631,7 +632,7 @@631632 @Test fun `receiver rejects an invitation that pins no static key`() = runBlocking {632633 val (phoneSocket, mitmSocket) = socketPair()633634 val root = ByteArray(32) { (it + 13).toByte() }634- val attackerKeys = deriveLocalSyncKeypair(root, "attacker-id")635+ val attackerKeys = localSyncKeypair(randomLocalIdentityCredentials("attacker-id"))635636 636637 val phoneJob = async {637638 try {@@ -665,7 +666,7 @@665666 @Test fun `receiver proceeds when the ACK static matches the pinned key`() = runBlocking {666667 val (phoneSocket, sourceSocket) = socketPair()667668 val root = ByteArray(32) { (it + 17).toByte() }668- val sourceKeys = deriveLocalSyncKeypair(root, "source-id")669+ val sourceKeys = localSyncKeypair(randomLocalIdentityCredentials("source-id"))669670 val reached = java.util.concurrent.atomic.AtomicBoolean(false)670671 671672 val phoneJob = async {app/src/test/java/com/peachpasswords/sync/RendezvousTest.kt+6 −9
@@ -25,16 +25,13 @@2525 }2626 2727 @Test fun `matches browser symmetric mesh capability KAT`() {28- val root = ByteArray(32) { it.toByte() }29- val low = ByteArray(32) { (it + 32).toByte() }30- val high = ByteArray(32) { (it + 64).toByte() }31- val forward = Rendezvous.deriveMeshSecret(root, low, high)32- val reverse = Rendezvous.deriveMeshSecret(root, high, low)28+ val alicePrivate = ByteArray(32) { 1 }29+ val bobPrivate = ByteArray(32) { 2 }30+ val alicePublic = org.bouncycastle.crypto.params.X25519PrivateKeyParameters(alicePrivate, 0).generatePublicKey().encoded31+ val bobPublic = org.bouncycastle.crypto.params.X25519PrivateKeyParameters(bobPrivate, 0).generatePublicKey().encoded32+ val forward = Rendezvous.deriveMeshSecret(alicePrivate, alicePublic, bobPublic)33+ val reverse = Rendezvous.deriveMeshSecret(bobPrivate, bobPublic, alicePublic)3334 34- assertEquals(35- "ad0359be7dc8fbb7df19ed027354b5029133a23a6023f43c2b3500b43addae7b",36- Rendezvous.bytesToHex(forward),37- )3835 assertEquals(Rendezvous.bytesToHex(forward), Rendezvous.bytesToHex(reverse))3936 }4037 app/src/test/java/com/peachpasswords/sync/SyncServiceStartTest.kt+8 −8
@@ -68,14 +68,14 @@6868 }6969 7070 @Test fun `an unlocked vault derives transient listener credentials`() {71- val root = ByteArray(32) { (it + 1).toByte() }72- val expected = deriveSyncIdentityKeypair(root, "phone-id")73- val credentials = deriveUnlockedListenerCredentials(root, "phone-id", "Phone")71+ val credentials = randomLocalIdentityCredentials("phone-id")72+ val expected = localSyncKeypair(credentials)73+ val actual = deriveUnlockedListenerCredentials(credentials, "Phone")7474 75- assertEquals("phone-id", credentials.identity.deviceId)76- assertEquals("Phone", credentials.identity.deviceName)77- assertEquals(pubkeyToHex(expected.publicKey), credentials.identity.longTermPublicKeyHex)78- assertArrayEquals(expected.publicKey, credentials.keys.publicKey)79- assertArrayEquals(expected.secretKey, credentials.keys.secretKey)75+ assertEquals("phone-id", actual.identity.deviceId)76+ assertEquals("Phone", actual.identity.deviceName)77+ assertEquals(pubkeyToHex(expected.publicKey), actual.identity.longTermPublicKeyHex)78+ assertArrayEquals(expected.publicKey, actual.keys.publicKey)79+ assertArrayEquals(expected.secretKey, actual.keys.secretKey)8080 }8181 }app/src/test/java/com/peachpasswords/sync/VaultSyncAdapterTest.kt+19 −10
@@ -79,10 +79,16 @@7979 override fun remove(id: String) { devices.removeAll { it.deviceId == id } }8080 }8181 82+ private fun localCredentials(deviceId: String) = randomLocalIdentityCredentials(deviceId)83+8284 private fun newAdapter(): Pair<VaultRepository, VaultSyncAdapter> {8385 val repo = VaultRepository(FakeStorage())8486 runBlocking { repo.createVault("correct horse") }85- return repo to VaultSyncAdapter(repo, ourDeviceId = "android-test")87+ return repo to VaultSyncAdapter(88+ repo,89+ ourDeviceId = "android-test",90+ localCredentials = localCredentials("android-test"),91+ )8692 }8793 8894 @Test fun manifest_and_vault_id_reflect_the_vault() = runBlocking {@@ -206,7 +212,7 @@206212 ),207213 )208214 val pending = FakePendingRegistry()209- val adapter = VaultSyncAdapter(repo, ourDeviceId = "android-self", pairedDevices = paired, pendingVouched = pending)215+ val adapter = VaultSyncAdapter(repo, ourDeviceId = "android-self", pairedDevices = paired, pendingVouched = pending, localCredentials = localCredentials("android-self"))210216 211217 val revocation = buildSignedDeviceManifest(212218 issuerDeviceId = "extension-issuer",@@ -267,7 +273,7 @@267273 ),268274 )269275 val pending = FakePendingRegistry()270- val adapter = VaultSyncAdapter(repo, ourDeviceId = "android-self", pairedDevices = paired, pendingVouched = pending)276+ val adapter = VaultSyncAdapter(repo, ourDeviceId = "android-self", pairedDevices = paired, pendingVouched = pending, localCredentials = localCredentials("android-self"))271277 272278 val selfRevoke = buildSignedDeviceManifest(273279 issuerDeviceId = "extension-issuer",@@ -307,7 +313,7 @@307313 ),308314 )309315 val pending = FakePendingRegistry()310- val adapter = VaultSyncAdapter(repo, ourDeviceId = "android-self", pairedDevices = paired, pendingVouched = pending)316+ val adapter = VaultSyncAdapter(repo, ourDeviceId = "android-self", pairedDevices = paired, pendingVouched = pending, localCredentials = localCredentials("android-self"))311317 val manifest = buildSignedDeviceManifest(312318 issuerDeviceId = "extension-issuer",313319 devices = listOf(@@ -366,7 +372,7 @@366372 ),367373 )368374 }369- val adapter = VaultSyncAdapter(repo, ourDeviceId = "android-self", pairedDevices = paired, pendingVouched = pending)375+ val adapter = VaultSyncAdapter(repo, ourDeviceId = "android-self", pairedDevices = paired, pendingVouched = pending, localCredentials = localCredentials("android-self"))370376 val manifest = buildSignedDeviceManifest(371377 issuerDeviceId = "extension-issuer",372378 devices = listOf(@@ -415,7 +421,7 @@415421 ),416422 )417423 val pending = FakePendingRegistry()418- val adapter = VaultSyncAdapter(repo, ourDeviceId = "android-self", pairedDevices = paired, pendingVouched = pending)424+ val adapter = VaultSyncAdapter(repo, ourDeviceId = "android-self", pairedDevices = paired, pendingVouched = pending, localCredentials = localCredentials("android-self"))419425 val manifest = buildSignedDeviceManifest(420426 issuerDeviceId = "phone-issuer",421427 devices = listOf(@@ -461,7 +467,7 @@461467 ),462468 )463469 val pending = FakePendingRegistry()464- val adapter = VaultSyncAdapter(repo, ourDeviceId = "android-self", pairedDevices = paired, pendingVouched = pending)470+ val adapter = VaultSyncAdapter(repo, ourDeviceId = "android-self", pairedDevices = paired, pendingVouched = pending, localCredentials = localCredentials("android-self"))465471 val manifest = buildSignedDeviceManifest(466472 issuerDeviceId = "vouched-issuer",467473 devices = listOf(@@ -518,6 +524,7 @@518524 ourDeviceId = "android-self",519525 pairedDevices = paired,520526 pendingVouched = pending,527+ localCredentials = localCredentials("android-self"),521528 )522529 val manifest = buildSignedDeviceManifest(523530 issuerDeviceId = "claimed-issuer",@@ -577,7 +584,7 @@577584 ),578585 )579586 val pending = FakePendingRegistry()580- val adapter = VaultSyncAdapter(repo, ourDeviceId = "android-self", pairedDevices = paired, pendingVouched = pending)587+ val adapter = VaultSyncAdapter(repo, ourDeviceId = "android-self", pairedDevices = paired, pendingVouched = pending, localCredentials = localCredentials("android-self"))581588 582589 adapter.applyIncomingDeviceManifest(583590 buildSignedDeviceManifest(@@ -645,7 +652,7 @@645652 master.fill(0)646653 }647654 648- @Test fun `a revoked key cannot be written onto a device we still trust`() = runBlocking {655+ @Test fun `direct peer rejects long term and signing key rotation`() = runBlocking {649656 val repo = VaultRepository(FakeStorage())650657 repo.createVault("correct horse")651658 val master = repo.syncMasterKey()!!@@ -678,6 +685,7 @@678685 ourDeviceId = "android-self",679686 pairedDevices = paired,680687 pendingVouched = FakePendingRegistry(),688+ localCredentials = localCredentials("android-self"),681689 )682690 683691 adapter.applyIncomingDeviceManifest(@@ -707,7 +715,7 @@707715 deviceName = "Tablet",708716 deviceType = "android",709717 longTermPublicKeyHex = revokedKey,710- signingPublicKeyHex = "ee".repeat(32),718+ signingPublicKeyHex = "ff".repeat(32),711719 pairedAt = 2L,712720 ),713721 ),@@ -716,6 +724,7 @@716724 ByteArray(32) { 0x11 },717725 )718726 assertEquals("77".repeat(32), paired.get("trusted-tablet")?.longTermPublicKeyHex)727+ assertEquals("ee".repeat(32), paired.get("trusted-tablet")?.signingPublicKeyHex)719728 master.fill(0)720729 }721730