VaultSyncAdapter.kt

9.9 KB · raw

1package com.peachpasswords.sync23import com.peachpasswords.vault.Tombstone4import com.peachpasswords.vault.VaultEntry5import com.peachpasswords.vault.VaultRepository6import kotlinx.serialization.json.Json7import org.bouncycastle.crypto.digests.SHA256Digest8import org.bouncycastle.crypto.generators.HKDFBytesGenerator9import org.bouncycastle.crypto.params.HKDFParameters10import java.security.SecureRandom11import java.util.Base6412import javax.crypto.Cipher13import javax.crypto.spec.GCMParameterSpec14import javax.crypto.spec.SecretKeySpec1516/**17 * Production [ChirpSyncVaultAdapter] backing the coordinator with the live18 * [VaultRepository]. Exact port of the browser `chirp-sync-vault-adapter.ts`:19 * the coordinator only ever moves opaque base64 envelopes; plaintext crosses20 * this boundary and nowhere else.21 *22 * Envelope cipher: AES-GCM under a PER-ENTRY key23 *   HKDF-SHA256(ikm = syncMasterKey, salt = "", info = entryId + "\u0000" + "sync-entry-v1")24 * with a random 12-byte nonce and aad = "peach-sync-entry-v1". Binding the key25 * to the entry id means a ciphertext minted for one slot cannot be replayed26 * into another — [applyEntries] rejects any envelope whose decrypted id does27 * not match the map key it arrived under. Both paired devices hold the same28 * syncMasterKey (same vault root key), so keys match without negotiation; the29 * Noise XX session is a second, independent encryption layer on top.30 */31class VaultSyncAdapter(32    private val repo: VaultRepository,33    private val ourDeviceId: String,34    private val pairedDevices: PairedDeviceRegistry? = null,35    private val pendingVouched: PendingVouchedRegistry? = null,36    private val syncAlerts: SyncAlertRecorder? = null,37    private val remoteDeviceName: String = "paired device",38    override val supportsDeviceManifest: Boolean = pairedDevices != null && pendingVouched != null,39) : ChirpSyncVaultAdapter {4041    override suspend fun computeVaultId(): String =42        repo.syncVaultId() ?: throw VaultLockedException()4344    override suspend fun getOurDeviceId(): String = ourDeviceId4546    override suspend fun getLocalVersion(): Long = repo.getVaultVersion()4748    override suspend fun buildEntryManifest(): Map<String, Long> =49        repo.getEntries().associate { it.id to it.modifiedAt }5051    override suspend fun buildTombstoneManifest(): Map<String, Long> =52        repo.getTombstones().associate { it.id to it.deletedAt }5354    override suspend fun getEncryptedEntries(entryIds: List<String>): Map<String, String> {55        val master = requireMasterKey()56        try {57            val out = LinkedHashMap<String, String>()58            for (id in entryIds) {59                val entry = repo.getEntry(id) ?: continue60                out[id] = encryptEntry(deriveEntryKey(master, id), entry)61            }62            return out63        } finally {64            master.fill(0)65        }66    }6768    override suspend fun applyEntries(entries: Map<String, String>) {69        val before = if (syncAlerts != null) repo.getEntries() else emptyList()70        val master = requireMasterKey()71        val decrypted = try {72            entries.mapNotNull { (id, envelope) ->73                val entry = decryptEntryOrNull(deriveEntryKey(master, id), envelope)74                // The map key is the authority on id — refuse a swapped envelope75                // so a ciphertext can't poison a different entry slot.76                if (entry != null && entry.id == id) entry else null77            }78        } finally {79            master.fill(0)80        }81        if (decrypted.isNotEmpty()) {82            val applied = repo.applyMergedRemoteEntries(decrypted, emptyList())83            if (applied > 0) {84                syncAlerts?.record(85                    remoteEntrySyncAlerts(86                        localEntries = before,87                        remoteEntries = decrypted,88                        deviceName = remoteDeviceName,89                        nowMs = System.currentTimeMillis(),90                    ),91                )92            }93        }94    }9596    override suspend fun applyTombstones(tombstones: Map<String, Long>) {97        val before = if (syncAlerts != null) repo.getEntries() else emptyList()98        val cleaned = tombstones99            .filterValues { it > 0L }100            .map { (id, ts) -> Tombstone(id, ts) }101        if (cleaned.isNotEmpty()) {102            val applied = repo.applyMergedRemoteEntries(emptyList(), cleaned)103            if (applied > 0) {104                syncAlerts?.record(105                    remoteTombstoneSyncAlerts(106                        localEntries = before,107                        remoteTombstones = cleaned,108                        deviceName = remoteDeviceName,109                        nowMs = System.currentTimeMillis(),110                    ),111                )112            }113        }114    }115116    override suspend fun buildOutgoingDeviceManifest(): SignedDeviceManifest? {117        val registry = pairedDevices ?: return null118        val master = requireMasterKey()119        return try {120            val signing = deriveSyncSigningKeypair(master, ourDeviceId)121            val devices = registry.getAll().mapNotNull { it.toManifestEntry() }122            buildSignedDeviceManifest(ourDeviceId, devices, signing.privateKey)123        } finally {124            master.fill(0)125        }126    }127128    override suspend fun applyIncomingDeviceManifest(manifest: SignedDeviceManifest) {129        val registry = pairedDevices ?: return130        val pending = pendingVouched ?: return131        val issuerId = manifest.body.issuerDeviceId132        val issuer = registry.get(issuerId) ?: return133        if (issuer.deviceType != "extension") return134        val signingKey = issuer.signingPublicKeyHex?.lowercase()?.takeIf { it.length == 64 } ?: return135        val body = verifyDeviceManifest(manifest, hexToPubkey(signingKey)) ?: return136        if (body.issuerDeviceId != issuer.deviceId) return137138        for (entry in body.devices) {139            if (entry.deviceId == ourDeviceId || entry.deviceId == issuer.deviceId) continue140            val existing = registry.get(entry.deviceId)141            if (existing == null) {142                pending.upsert(143                    PendingVouchedDevice(144                        deviceId = entry.deviceId,145                        deviceName = entry.deviceName,146                        deviceType = entry.deviceType,147                        longTermPublicKeyHex = entry.longTermPublicKeyHex.lowercase(),148                        signingPublicKeyHex = entry.signingPublicKeyHex.lowercase(),149                        wsPort = entry.wsPort,150                        pairedAt = entry.pairedAt,151                        receivedAt = System.currentTimeMillis(),152                        vouchedByDeviceId = issuer.deviceId,153                    ),154                )155            } else {156                deviceKeyRotationAlert(existing, entry, System.currentTimeMillis())?.let { alert ->157                    syncAlerts?.record(listOf(alert))158                }159                registry.upsert(160                    existing.copy(161                        deviceName = entry.deviceName,162                        deviceType = entry.deviceType,163                        longTermPublicKeyHex = entry.longTermPublicKeyHex.lowercase(),164                        signingPublicKeyHex = entry.signingPublicKeyHex.lowercase(),165                        wsPort = existing.wsPort ?: entry.wsPort,166                        pairedAt = existing.pairedAt,167                        trustSource = existing.trustSource ?: "direct",168                    ),169                )170            }171        }172    }173174    private fun requireMasterKey(): ByteArray =175        repo.syncMasterKey() ?: throw VaultLockedException()176177    private fun deriveEntryKey(masterKey: ByteArray, entryId: String): ByteArray {178        // Null-byte separator (HKDF hardening): entryId cannot contain U+0000, so179        // the (entryId, suffix) boundary is unambiguous regardless of future id180        // formats. Coordinated wire change — peach-browser deriveEntryKey produces181        // the identical info bytes; the two MUST stay byte-for-byte in lockstep.182        val info = (entryId + "\u0000" + ENTRY_KEY_INFO_SUFFIX).toByteArray(Charsets.UTF_8)183        val gen = HKDFBytesGenerator(SHA256Digest())184        gen.init(HKDFParameters(masterKey, ByteArray(0), info))185        return ByteArray(32).also { gen.generateBytes(it, 0, it.size) }186    }187188    private fun encryptEntry(key: ByteArray, entry: VaultEntry): String {189        val plaintext = entryJson.encodeToString(VaultEntry.serializer(), entry).toByteArray(Charsets.UTF_8)190        val nonce = ByteArray(12).also(rng::nextBytes)191        val cipher = Cipher.getInstance("AES/GCM/NoPadding")192        cipher.init(Cipher.ENCRYPT_MODE, SecretKeySpec(key, "AES"), GCMParameterSpec(128, nonce))193        cipher.updateAAD(ENTRY_AAD)194        val ct = cipher.doFinal(plaintext)195        return b64(nonce + ct)196    }197198    private fun decryptEntryOrNull(key: ByteArray, envelopeB64: String): VaultEntry? = try {199        val bytes = unb64(envelopeB64)200        if (bytes.size < 12 + 16) null else {201            val nonce = bytes.copyOfRange(0, 12)202            val ct = bytes.copyOfRange(12, bytes.size)203            val cipher = Cipher.getInstance("AES/GCM/NoPadding")204            cipher.init(Cipher.DECRYPT_MODE, SecretKeySpec(key, "AES"), GCMParameterSpec(128, nonce))205            cipher.updateAAD(ENTRY_AAD)206            val pt = cipher.doFinal(ct)207            entryJson.decodeFromString(VaultEntry.serializer(), String(pt, Charsets.UTF_8))208        }209    } catch (_: Exception) {210        null211    }212213    private companion object {214        const val ENTRY_KEY_INFO_SUFFIX = "sync-entry-v1"215        val ENTRY_AAD = "peach-sync-entry-v1".toByteArray(Charsets.UTF_8)216        val rng = SecureRandom()217        val entryJson = Json { encodeDefaults = false; ignoreUnknownKeys = true }218        fun b64(b: ByteArray): String = Base64.getEncoder().encodeToString(b)219        fun unb64(s: String): ByteArray = Base64.getDecoder().decode(s)220    }221}222223class VaultLockedException : Exception("vault_locked")