VaultSyncAdapter.kt

11.2 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 KK reconnect 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 var 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 fun bindAuthenticatedPeer(peer: PairedDevice) {117        remoteDeviceName = peer.deviceName?.takeIf { it.isNotBlank() }118            ?: peer.deviceId.takeIf { it.isNotBlank() }119            ?: "paired device"120    }121122    override suspend fun buildOutgoingDeviceManifest(): SignedDeviceManifest? {123        val registry = pairedDevices ?: return null124        val master = requireMasterKey()125        return try {126            val signing = deriveSyncSigningKeypair(master, ourDeviceId)127            val devices = registry.getAll().mapNotNull { it.toManifestEntry() }128            buildSignedDeviceManifest(ourDeviceId, devices, signing.privateKey)129        } finally {130            master.fill(0)131        }132    }133134    override suspend fun applyIncomingDeviceManifest(135        manifest: SignedDeviceManifest,136        authenticatedRemoteStaticPublicKey: ByteArray,137    ) {138        val registry = pairedDevices ?: return139        val pending = pendingVouched ?: return140        if (authenticatedRemoteStaticPublicKey.size != 32) return141        val issuer = registry.getByPubkey(pubkeyToHex(authenticatedRemoteStaticPublicKey)) ?: return142        // Match the browser (`applyVerifiedPeerManifest` in sync-vault-adapter.ts):143        // trust a manifest only from a DIRECTLY paired issuer. This previously144        // keyed on deviceType == "extension" instead, which got both halves145        // wrong: it ignored manifests from other phones/tablets, so mesh trust146        // could never propagate between native devices (the whole point of the147        // mesh now that phones are the listening side), and it never checked148        // trustSource at all — so a merely VOUCHED device could introduce149        // further devices, chaining trust transitively in a way the browser150        // deliberately refuses.151        if (issuer.trustSource != "direct") return152        val signingKey = issuer.signingPublicKeyHex?.lowercase()?.takeIf { it.length == 64 } ?: return153        val body = verifyDeviceManifest(manifest, hexToPubkey(signingKey)) ?: return154        if (body.issuerDeviceId != issuer.deviceId) return155156        for (entry in body.devices) {157            if (entry.deviceId == ourDeviceId || entry.deviceId == issuer.deviceId) continue158            val existing = registry.get(entry.deviceId)159            if (existing == null) {160                pending.upsert(161                    PendingVouchedDevice(162                        deviceId = entry.deviceId,163                        deviceName = entry.deviceName,164                        deviceType = entry.deviceType,165                        longTermPublicKeyHex = entry.longTermPublicKeyHex.lowercase(),166                        signingPublicKeyHex = entry.signingPublicKeyHex.lowercase(),167                        wsPort = entry.wsPort,168                        pairedAt = entry.pairedAt,169                        receivedAt = System.currentTimeMillis(),170                        vouchedByDeviceId = issuer.deviceId,171                    ),172                )173            } else {174                deviceKeyRotationAlert(existing, entry, System.currentTimeMillis())?.let { alert ->175                    syncAlerts?.record(listOf(alert))176                }177                // S5: keys and ports propagate through the mesh, the name does178                // not. A device names itself at pairing; letting a third-party179                // issuer rewrite that is the rename-then-impersonate vector.180                registry.upsert(181                    existing.copy(182                        deviceName = existing.deviceName?.takeIf { it.isNotBlank() }183                            ?: entry.deviceName,184                        deviceType = entry.deviceType,185                        longTermPublicKeyHex = entry.longTermPublicKeyHex.lowercase(),186                        signingPublicKeyHex = entry.signingPublicKeyHex.lowercase(),187                        wsPort = existing.wsPort ?: entry.wsPort,188                        pairedAt = existing.pairedAt,189                        trustSource = existing.trustSource ?: "direct",190                    ),191                )192            }193        }194    }195196    private fun requireMasterKey(): ByteArray =197        repo.syncMasterKey() ?: throw VaultLockedException()198199    private fun deriveEntryKey(masterKey: ByteArray, entryId: String): ByteArray {200        // Null-byte separator (HKDF hardening): entryId cannot contain U+0000, so201        // the (entryId, suffix) boundary is unambiguous regardless of future id202        // formats. Coordinated wire change — peach-browser deriveEntryKey produces203        // the identical info bytes; the two MUST stay byte-for-byte in lockstep.204        val info = (entryId + "\u0000" + ENTRY_KEY_INFO_SUFFIX).toByteArray(Charsets.UTF_8)205        val gen = HKDFBytesGenerator(SHA256Digest())206        gen.init(HKDFParameters(masterKey, ByteArray(0), info))207        return ByteArray(32).also { gen.generateBytes(it, 0, it.size) }208    }209210    private fun encryptEntry(key: ByteArray, entry: VaultEntry): String {211        val plaintext = entryJson.encodeToString(VaultEntry.serializer(), entry).toByteArray(Charsets.UTF_8)212        val nonce = ByteArray(12).also(rng::nextBytes)213        val cipher = Cipher.getInstance("AES/GCM/NoPadding")214        cipher.init(Cipher.ENCRYPT_MODE, SecretKeySpec(key, "AES"), GCMParameterSpec(128, nonce))215        cipher.updateAAD(ENTRY_AAD)216        val ct = cipher.doFinal(plaintext)217        return b64(nonce + ct)218    }219220    private fun decryptEntryOrNull(key: ByteArray, envelopeB64: String): VaultEntry? = try {221        val bytes = unb64(envelopeB64)222        if (bytes.size < 12 + 16) null else {223            val nonce = bytes.copyOfRange(0, 12)224            val ct = bytes.copyOfRange(12, bytes.size)225            val cipher = Cipher.getInstance("AES/GCM/NoPadding")226            cipher.init(Cipher.DECRYPT_MODE, SecretKeySpec(key, "AES"), GCMParameterSpec(128, nonce))227            cipher.updateAAD(ENTRY_AAD)228            val pt = cipher.doFinal(ct)229            entryJson.decodeFromString(VaultEntry.serializer(), String(pt, Charsets.UTF_8))230        }231    } catch (_: Exception) {232        null233    }234235    private companion object {236        const val ENTRY_KEY_INFO_SUFFIX = "sync-entry-v1"237        val ENTRY_AAD = "peach-sync-entry-v1".toByteArray(Charsets.UTF_8)238        val rng = SecureRandom()239        val entryJson = Json { encodeDefaults = false; ignoreUnknownKeys = true }240        fun b64(b: ByteArray): String = Base64.getEncoder().encodeToString(b)241        fun unb64(s: String): ByteArray = Base64.getDecoder().decode(s)242    }243}244245class VaultLockedException : Exception("vault_locked")