package com.peachpasswords.sync import com.peachpasswords.vault.Tombstone import com.peachpasswords.vault.VaultEntry import com.peachpasswords.vault.VaultRepository import kotlinx.serialization.json.Json import org.bouncycastle.crypto.digests.SHA256Digest import org.bouncycastle.crypto.generators.HKDFBytesGenerator import org.bouncycastle.crypto.params.HKDFParameters import java.security.SecureRandom import java.util.Base64 import javax.crypto.Cipher import javax.crypto.spec.GCMParameterSpec import javax.crypto.spec.SecretKeySpec /** * Production [ChirpSyncVaultAdapter] backing the coordinator with the live * [VaultRepository]. Exact port of the browser `chirp-sync-vault-adapter.ts`: * the coordinator only ever moves opaque base64 envelopes; plaintext crosses * this boundary and nowhere else. * * Envelope cipher: AES-GCM under a PER-ENTRY key * HKDF-SHA256(ikm = syncMasterKey, salt = "", info = entryId + "\u0000" + "sync-entry-v1") * with a random 12-byte nonce and aad = "peach-sync-entry-v1". Binding the key * to the entry id means a ciphertext minted for one slot cannot be replayed * into another — [applyEntries] rejects any envelope whose decrypted id does * not match the map key it arrived under. Both paired devices hold the same * syncMasterKey (same vault root key), so keys match without negotiation; the * Noise XX session is a second, independent encryption layer on top. */ class VaultSyncAdapter( private val repo: VaultRepository, private val ourDeviceId: String, override val supportsDeviceManifest: Boolean = false, ) : ChirpSyncVaultAdapter { override suspend fun computeVaultId(): String = repo.syncVaultId() ?: throw VaultLockedException() override suspend fun getOurDeviceId(): String = ourDeviceId override suspend fun getLocalVersion(): Long = repo.getVaultVersion() override suspend fun buildEntryManifest(): Map = repo.getEntries().associate { it.id to it.modifiedAt } override suspend fun buildTombstoneManifest(): Map = repo.getTombstones().associate { it.id to it.deletedAt } override suspend fun getEncryptedEntries(entryIds: List): Map { val master = requireMasterKey() try { val out = LinkedHashMap() for (id in entryIds) { val entry = repo.getEntry(id) ?: continue out[id] = encryptEntry(deriveEntryKey(master, id), entry) } return out } finally { master.fill(0) } } override suspend fun applyEntries(entries: Map) { val master = requireMasterKey() val decrypted = try { entries.mapNotNull { (id, envelope) -> val entry = decryptEntryOrNull(deriveEntryKey(master, id), envelope) // The map key is the authority on id — refuse a swapped envelope // so a ciphertext can't poison a different entry slot. if (entry != null && entry.id == id) entry else null } } finally { master.fill(0) } if (decrypted.isNotEmpty()) repo.applyMergedRemoteEntries(decrypted, emptyList()) } override suspend fun applyTombstones(tombstones: Map) { val cleaned = tombstones .filterValues { it > 0L } .map { (id, ts) -> Tombstone(id, ts) } if (cleaned.isNotEmpty()) repo.applyMergedRemoteEntries(emptyList(), cleaned) } private fun requireMasterKey(): ByteArray = repo.syncMasterKey() ?: throw VaultLockedException() private fun deriveEntryKey(masterKey: ByteArray, entryId: String): ByteArray { // Null-byte separator (HKDF hardening): entryId cannot contain U+0000, so // the (entryId, suffix) boundary is unambiguous regardless of future id // formats. Coordinated wire change — peach-browser deriveEntryKey produces // the identical info bytes; the two MUST stay byte-for-byte in lockstep. val info = (entryId + "\u0000" + ENTRY_KEY_INFO_SUFFIX).toByteArray(Charsets.UTF_8) val gen = HKDFBytesGenerator(SHA256Digest()) gen.init(HKDFParameters(masterKey, ByteArray(0), info)) return ByteArray(32).also { gen.generateBytes(it, 0, it.size) } } private fun encryptEntry(key: ByteArray, entry: VaultEntry): String { val plaintext = entryJson.encodeToString(VaultEntry.serializer(), entry).toByteArray(Charsets.UTF_8) val nonce = ByteArray(12).also(rng::nextBytes) val cipher = Cipher.getInstance("AES/GCM/NoPadding") cipher.init(Cipher.ENCRYPT_MODE, SecretKeySpec(key, "AES"), GCMParameterSpec(128, nonce)) cipher.updateAAD(ENTRY_AAD) val ct = cipher.doFinal(plaintext) return b64(nonce + ct) } private fun decryptEntryOrNull(key: ByteArray, envelopeB64: String): VaultEntry? = try { val bytes = unb64(envelopeB64) if (bytes.size < 12 + 16) null else { val nonce = bytes.copyOfRange(0, 12) val ct = bytes.copyOfRange(12, bytes.size) val cipher = Cipher.getInstance("AES/GCM/NoPadding") cipher.init(Cipher.DECRYPT_MODE, SecretKeySpec(key, "AES"), GCMParameterSpec(128, nonce)) cipher.updateAAD(ENTRY_AAD) val pt = cipher.doFinal(ct) entryJson.decodeFromString(VaultEntry.serializer(), String(pt, Charsets.UTF_8)) } } catch (_: Exception) { null } private companion object { const val ENTRY_KEY_INFO_SUFFIX = "sync-entry-v1" val ENTRY_AAD = "peach-sync-entry-v1".toByteArray(Charsets.UTF_8) val rng = SecureRandom() val entryJson = Json { encodeDefaults = false; ignoreUnknownKeys = true } fun b64(b: ByteArray): String = Base64.getEncoder().encodeToString(b) fun unb64(s: String): ByteArray = Base64.getDecoder().decode(s) } } class VaultLockedException : Exception("vault_locked")