1package com.peachpasswords.sync23import com.peachpasswords.vault.Tombstone4import com.peachpasswords.vault.VaultCrypto5import com.peachpasswords.vault.VaultEntry6import com.peachpasswords.vault.VaultRepository7import kotlinx.serialization.json.Json8import org.bouncycastle.crypto.digests.SHA256Digest9import org.bouncycastle.crypto.generators.HKDFBytesGenerator10import org.bouncycastle.crypto.params.HKDFParameters11import java.security.SecureRandom12import java.util.Base6413import javax.crypto.Cipher14import javax.crypto.spec.GCMParameterSpec15import javax.crypto.spec.SecretKeySpec1617181920212223242526272829303132class VaultSyncAdapter(33 private val repo: VaultRepository,34 private val ourDeviceId: String,35 private val pairedDevices: PairedDeviceRegistry? = null,36 private val pendingVouched: PendingVouchedRegistry? = null,37 private val syncAlerts: SyncAlertRecorder? = null,38 private var remoteDeviceName: String = "paired device",39 override val supportsDeviceManifest: Boolean = pairedDevices != null && pendingVouched != null,40 private val localCredentials: LocalIdentityCredentials? = null,41) : SyncVaultAdapter {4243 override suspend fun computeVaultId(): String =44 repo.syncVaultId() ?: throw VaultLockedException()4546 override suspend fun getOurDeviceId(): String = ourDeviceId4748 override suspend fun getLocalVersion(): Long = repo.getVaultVersion()4950 override suspend fun buildEntryManifest(): Map<String, Long> {51 val snapshot = requireMasterKeySnapshot()52 VaultCrypto.zero(snapshot.key)53 val manifest = repo.getEntries().associate { it.id to it.modifiedAt }54 if (!repo.isSessionEpochCurrent(snapshot.epoch)) throw VaultLockedException()55 return manifest56 }5758 override suspend fun buildTombstoneManifest(): Map<String, Long> {59 val snapshot = requireMasterKeySnapshot()60 VaultCrypto.zero(snapshot.key)61 val manifest = repo.getTombstones().associate { it.id to it.deletedAt }62 if (!repo.isSessionEpochCurrent(snapshot.epoch)) throw VaultLockedException()63 return manifest64 }6566 override suspend fun getEncryptedEntries(entryIds: List<String>): Map<String, String> {67 val snapshot = requireMasterKeySnapshot()68 val master = snapshot.key69 try {70 val out = LinkedHashMap<String, String>()71 for (id in entryIds) {72 val entry = repo.getEntry(id) ?: continue73 74 75 76 var entryKey: ByteArray? = null77 try {78 entryKey = deriveEntryKey(master, id)79 out[id] = encryptEntry(entryKey, entry)80 } finally {81 entryKey?.let(VaultCrypto::zero)82 }83 }84 if (!repo.isSessionEpochCurrent(snapshot.epoch)) throw VaultLockedException()85 return out86 } finally {87 VaultCrypto.zero(master)88 }89 }9091 override suspend fun applyEntries(92 entries: Map<String, String>,93 remoteManifest: Map<String, Long>,94 ) {95 val snapshot = requireMasterKeySnapshot()96 val master = snapshot.key97 val decrypted = try {98 entries.mapNotNull { (id, envelope) ->99 100 101 102 var entryKey: ByteArray? = null103 val entry = try {104 entryKey = deriveEntryKey(master, id)105 decryptEntryOrNull(entryKey, envelope)106 } finally {107 entryKey?.let(VaultCrypto::zero)108 }109 110 111 if (entry != null && entry.id == id) entry else null112 }113 } finally {114 VaultCrypto.zero(master)115 }116 if (decrypted.isNotEmpty()) {117 repo.applyMergedRemoteEntries(decrypted, emptyList(), expectedEpoch = snapshot.epoch)118 }119 }120121 override suspend fun applyTombstones(tombstones: Map<String, Long>) {122 val cleaned = tombstones123 .filterValues { it > 0L }124 .map { (id, ts) -> Tombstone(id, ts) }125 if (cleaned.isNotEmpty()) {126 val snapshot = requireMasterKeySnapshot()127 VaultCrypto.zero(snapshot.key)128 repo.applyMergedRemoteEntries(emptyList(), cleaned, expectedEpoch = snapshot.epoch)129 }130 }131132 override fun bindAuthenticatedPeer(peer: PairedDevice) {133 remoteDeviceName = peer.deviceName?.takeIf { it.isNotBlank() }134 ?: peer.deviceId.takeIf { it.isNotBlank() }135 ?: "paired device"136 }137138 override suspend fun buildOutgoingDeviceManifest(): SignedDeviceManifest? {139 val registry = pairedDevices ?: return null140 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)149 }150151 override suspend fun applyIncomingDeviceManifest(152 manifest: SignedDeviceManifest,153 authenticatedRemoteStaticPublicKey: ByteArray,154 ) {155 val registry = pairedDevices ?: return156 val pending = pendingVouched ?: return157 if (authenticatedRemoteStaticPublicKey.size != 32) return158 val issuer = registry.getByPubkey(pubkeyToHex(authenticatedRemoteStaticPublicKey)) ?: return159 160 if (issuer.trustSource != "direct" && issuer.trustSource != "vouched") return161 if (issuer.vouchDepth >= MAX_VOUCH_DEPTH) return162 val currentSigningKey = issuer.signingPublicKeyHex?.lowercase()?.takeIf { it.length == 64 } ?: return163 val knownIssuerKeys = registry.issuerSigningKeys(issuer.deviceId) + currentSigningKey164 165 166 val verified = knownIssuerKeys.firstNotNullOfOrNull { candidate ->167 runCatching {168 verifyDeviceManifest(manifest, hexToPubkey(candidate))?.let { candidate to it }169 }.getOrNull()170 } ?: return171 val (signingKey, body) = verified172 if (body.issuerDeviceId != issuer.deviceId) return173 val snapshot = requireMasterKeySnapshot()174 val master = snapshot.key175 val localKeys = localCredentials?.let(::localSyncKeypair)176 ?: throw IllegalStateException("identity_migration_required")177 try {178 if (!repo.isSessionEpochCurrent(snapshot.epoch)) return179 180 181 182 183 val incomingRevocations = body.revoked.filterNot { it.deviceId == ourDeviceId }184 val currentRevocations = registry.listRevocations()185 val knownRevokedIds = currentRevocations.map { it.deviceId }.toSet()186 val newlyRevoked = incomingRevocations.filterNot { knownRevokedIds.contains(it.deviceId) }187 val revokedIds = (knownRevokedIds + incomingRevocations.map { it.deviceId }).toSet()188 val revokedKeys = (currentRevocations + incomingRevocations)189 .map { it.longTermPublicKeyHex.lowercase() }190 .filterNot { it == NO_KEY_SENTINEL }191 .toSet()192 fun revokedInStagedBatch(deviceId: String, longTermKey: String): Boolean {193 return deviceId in revokedIds || longTermKey.lowercase() in revokedKeys194 }195196 val stagedUpserts = LinkedHashMap<String, PairedDevice>()197 val stagedAlerts = ArrayList<SyncAlert>()198 newlyRevoked.forEach { revocation ->199 stagedAlerts += SyncAlert(200 type = SyncAlertType.DEVICE_REVOKED,201 deviceName = issuer.deviceName ?: "paired device",202 entryTitle = revocation.deviceId,203 timestamp = System.currentTimeMillis(),204 )205 }206 for (entry in body.devices) {207 if (entry.deviceId == ourDeviceId || entry.deviceId == issuer.deviceId) {208 continue209 }210 if (revokedInStagedBatch(entry.deviceId, entry.longTermPublicKeyHex)) {211 continue212 }213 if (entry.vouchDepth > issuer.vouchDepth + 1) continue214 val existing = stagedUpserts[entry.deviceId] ?: registry.get(entry.deviceId)215 val meshRoute = deriveManifestMeshRoute(localKeys.secretKey, localKeys.publicKey, entry)216 if (existing == null) {217 if (meshRoute == null) continue218 stagedUpserts[entry.deviceId] = PairedDevice(219 deviceId = entry.deviceId,220 deviceName = entry.deviceName,221 deviceType = entry.deviceType,222 longTermPublicKeyHex = entry.longTermPublicKeyHex.lowercase(),223 signingPublicKeyHex = entry.signingPublicKeyHex.lowercase(),224 trustSource = "vouched",225 vouchDepth = issuer.vouchDepth + 1,226 wsPort = entry.wsPort,227 rendezvousSecretHex = meshRoute.first,228 relayUrl = meshRoute.second,229 pairedAt = entry.pairedAt,230 )231 } else {232 val incomingLongTermKey = entry.longTermPublicKeyHex.lowercase()233 val incomingSigningKey = entry.signingPublicKeyHex.lowercase()234 235 236 237 238 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 }252 deviceKeyRotationAlert(existing, entry, System.currentTimeMillis())?.let(stagedAlerts::add)253 stagedUpserts[entry.deviceId] = existing.copy(254 deviceName = existing.deviceName?.takeIf { it.isNotBlank() }255 ?: entry.deviceName,256 deviceType = entry.deviceType,257 258 259 longTermPublicKeyHex =260 if (existing.trustSource == "direct") existing.longTermPublicKeyHex261 else incomingLongTermKey,262 signingPublicKeyHex =263 if (existing.trustSource == "direct") existing.signingPublicKeyHex264 else incomingSigningKey,265 vouchDepth = entry.vouchDepth,266 wsPort = existing.wsPort ?: entry.wsPort,267 rendezvousSecretHex =268 if (existing.trustSource == "vouched" && meshRoute != null) {269 meshRoute.first270 } else {271 existing.rendezvousSecretHex272 },273 relayUrl =274 if (existing.trustSource == "vouched" && meshRoute != null) {275 meshRoute.second276 } else {277 existing.relayUrl278 },279 pairedAt = existing.pairedAt,280 trustSource = existing.trustSource,281 )282 }283 }284285 val batch = DeviceManifestRegistryBatch(286 incomingRevocations = incomingRevocations,287 removals = newlyRevoked.map { it.deviceId }.toSet(),288 upserts = stagedUpserts.values.toList(),289 )290 291 292 293 294 val pendingIds = batch.removals + stagedUpserts.keys295 val priorPending = pending.getAll().filter { it.deviceId in pendingIds }296 val committed = repo.withSessionEpochCommit(snapshot.epoch) {297 if (!registry.appendIssuerSigningKey(issuer.deviceId, signingKey)) return@withSessionEpochCommit false298 val pendingRemoved = runCatching { pending.removeBatch(pendingIds) }.getOrDefault(false)299 if (!pendingRemoved) {300 pending.restoreBatch(priorPending)301 false302 } else {303 val registryCommitted = runCatching { registry.applyManifestBatch(batch) }.getOrDefault(false)304 if (registryCommitted) {305 306 307 308 if (stagedAlerts.isNotEmpty()) syncAlerts?.record(stagedAlerts)309 true310 } else {311 pending.restoreBatch(priorPending)312 false313 }314 }315 }316 if (committed != true) return317 } finally {318 VaultCrypto.zero(master)319 VaultCrypto.zero(localKeys.secretKey)320 }321 }322323 private fun deriveManifestMeshRoute(324 localPrivateKey: ByteArray,325 localPublicKey: ByteArray,326 entry: ManifestDeviceEntry,327 ): Pair<String, String>? = runCatching {328 val relayUrl = Rendezvous.normalizeRelayUrl(entry.relayUrl ?: return null)329 val secret = Rendezvous.deriveMeshSecret(330 localPrivateKey,331 localPublicKey,332 hexToPubkey(entry.longTermPublicKeyHex),333 )334 try {335 Rendezvous.bytesToHex(secret) to relayUrl336 } finally {337 VaultCrypto.zero(secret)338 }339 }.getOrNull()340341 private fun requireMasterKeySnapshot(): VaultRepository.SyncMasterKeySnapshot =342 repo.syncMasterKeySnapshot() ?: throw VaultLockedException()343344 internal companion object {345 internal fun deriveEntryKey(masterKey: ByteArray, entryId: String): ByteArray {346 347 348 349 350 val info = (entryId + "\u0000" + ENTRY_KEY_INFO_SUFFIX).toByteArray(Charsets.UTF_8)351 val gen = HKDFBytesGenerator(SHA256Digest())352 gen.init(HKDFParameters(masterKey, ByteArray(0), info))353 return ByteArray(32).also { gen.generateBytes(it, 0, it.size) }354 }355356 internal fun encryptEntry(key: ByteArray, entry: VaultEntry): String {357 358 359 var plaintext: ByteArray? = null360 return try {361 plaintext = entryJson.encodeToString(VaultEntry.serializer(), entry).toByteArray(Charsets.UTF_8)362 val nonce = ByteArray(12).also(rng::nextBytes)363 val cipher = Cipher.getInstance("AES/GCM/NoPadding")364 cipher.init(Cipher.ENCRYPT_MODE, SecretKeySpec(key, "AES"), GCMParameterSpec(128, nonce))365 cipher.updateAAD(ENTRY_AAD)366 val ct = cipher.doFinal(plaintext)367 b64(nonce + ct)368 } finally {369 plaintext?.let(VaultCrypto::zero)370 }371 }372373 internal fun encryptEntryWithMasterKey(masterKey: ByteArray, entry: VaultEntry): String {374 val key = deriveEntryKey(masterKey, entry.id)375 return try { encryptEntry(key, entry) } finally { VaultCrypto.zero(key) }376 }377378 internal fun decryptEntryOrNull(key: ByteArray, envelopeB64: String): VaultEntry? {379 var pt: ByteArray? = null380 return try {381 val bytes = unb64(envelopeB64)382 if (bytes.size < 12 + 16) null else {383 val nonce = bytes.copyOfRange(0, 12)384 val ct = bytes.copyOfRange(12, bytes.size)385 val cipher = Cipher.getInstance("AES/GCM/NoPadding")386 cipher.init(Cipher.DECRYPT_MODE, SecretKeySpec(key, "AES"), GCMParameterSpec(128, nonce))387 cipher.updateAAD(ENTRY_AAD)388 pt = cipher.doFinal(ct)389 entryJson.decodeFromString(VaultEntry.serializer(), String(pt, Charsets.UTF_8))390 }391 } catch (_: Exception) {392 null393 } finally {394 395 396 397 pt?.let(VaultCrypto::zero)398 }399 }400401 const val ENTRY_KEY_INFO_SUFFIX = "sync-entry-v1"402 val ENTRY_AAD = "peach-sync-entry-v1".toByteArray(Charsets.UTF_8)403 val rng = SecureRandom()404 val entryJson = Json { encodeDefaults = false; ignoreUnknownKeys = true }405 fun b64(b: ByteArray): String = Base64.getEncoder().encodeToString(b)406 fun unb64(s: String): ByteArray = Base64.getDecoder().decode(s)407 }408}409410class VaultLockedException : Exception("vault_locked")