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) : SyncVaultAdapter {4142 override suspend fun computeVaultId(): String =43 repo.syncVaultId() ?: throw VaultLockedException()4445 override suspend fun getOurDeviceId(): String = ourDeviceId4647 override suspend fun getLocalVersion(): Long = repo.getVaultVersion()4849 override suspend fun buildEntryManifest(): Map<String, Long> {50 val snapshot = requireMasterKeySnapshot()51 VaultCrypto.zero(snapshot.key)52 val manifest = repo.getEntries().associate { it.id to it.modifiedAt }53 if (!repo.isSessionEpochCurrent(snapshot.epoch)) throw VaultLockedException()54 return manifest55 }5657 override suspend fun buildTombstoneManifest(): Map<String, Long> {58 val snapshot = requireMasterKeySnapshot()59 VaultCrypto.zero(snapshot.key)60 val manifest = repo.getTombstones().associate { it.id to it.deletedAt }61 if (!repo.isSessionEpochCurrent(snapshot.epoch)) throw VaultLockedException()62 return manifest63 }6465 override suspend fun getEncryptedEntries(entryIds: List<String>): Map<String, String> {66 val snapshot = requireMasterKeySnapshot()67 val master = snapshot.key68 try {69 val out = LinkedHashMap<String, String>()70 for (id in entryIds) {71 val entry = repo.getEntry(id) ?: continue72 73 74 75 var entryKey: ByteArray? = null76 try {77 entryKey = deriveEntryKey(master, id)78 out[id] = encryptEntry(entryKey, entry)79 } finally {80 entryKey?.let(VaultCrypto::zero)81 }82 }83 if (!repo.isSessionEpochCurrent(snapshot.epoch)) throw VaultLockedException()84 return out85 } finally {86 VaultCrypto.zero(master)87 }88 }8990 override suspend fun applyEntries(entries: Map<String, String>) {91 val snapshot = requireMasterKeySnapshot()92 val master = snapshot.key93 val decrypted = try {94 entries.mapNotNull { (id, envelope) ->95 96 97 98 var entryKey: ByteArray? = null99 val entry = try {100 entryKey = deriveEntryKey(master, id)101 decryptEntryOrNull(entryKey, envelope)102 } finally {103 entryKey?.let(VaultCrypto::zero)104 }105 106 107 if (entry != null && entry.id == id) entry else null108 }109 } finally {110 VaultCrypto.zero(master)111 }112 if (decrypted.isNotEmpty()) {113 repo.applyMergedRemoteEntries(decrypted, emptyList(), expectedEpoch = snapshot.epoch)114 }115 }116117 override suspend fun applyTombstones(tombstones: Map<String, Long>) {118 val cleaned = tombstones119 .filterValues { it > 0L }120 .map { (id, ts) -> Tombstone(id, ts) }121 if (cleaned.isNotEmpty()) {122 val snapshot = requireMasterKeySnapshot()123 VaultCrypto.zero(snapshot.key)124 repo.applyMergedRemoteEntries(emptyList(), cleaned, expectedEpoch = snapshot.epoch)125 }126 }127128 override fun bindAuthenticatedPeer(peer: PairedDevice) {129 remoteDeviceName = peer.deviceName?.takeIf { it.isNotBlank() }130 ?: peer.deviceId.takeIf { it.isNotBlank() }131 ?: "paired device"132 }133134 override suspend fun buildOutgoingDeviceManifest(): SignedDeviceManifest? {135 val registry = pairedDevices ?: return null136 val snapshot = requireMasterKeySnapshot()137 val master = snapshot.key138 return try {139 val signing = deriveSyncSigningKeypair(master, ourDeviceId)140 val revoked = registry.listRevocations()141 val revokedIds = revoked.map { it.deviceId }.toSet()142 val devices = registry.getAll()143 .filterNot { revokedIds.contains(it.deviceId) }144 .mapNotNull { it.toManifestEntry() }145 val manifest = buildSignedDeviceManifest(146 ourDeviceId,147 devices,148 signing.privateKey,149 revoked = revoked,150 )151 if (!repo.isSessionEpochCurrent(snapshot.epoch)) throw VaultLockedException()152 manifest153 } finally {154 VaultCrypto.zero(master)155 }156 }157158 override suspend fun applyIncomingDeviceManifest(159 manifest: SignedDeviceManifest,160 authenticatedRemoteStaticPublicKey: ByteArray,161 ) {162 val registry = pairedDevices ?: return163 val pending = pendingVouched ?: return164 if (authenticatedRemoteStaticPublicKey.size != 32) return165 val issuer = registry.getByPubkey(pubkeyToHex(authenticatedRemoteStaticPublicKey)) ?: return166 167 168 169 170 171 172 if (issuer.trustSource != "direct" && issuer.trustSource != "vouched") return173 val signingKey = issuer.signingPublicKeyHex?.lowercase()?.takeIf { it.length == 64 } ?: return174 val body = verifyDeviceManifest(manifest, hexToPubkey(signingKey)) ?: return175 if (body.issuerDeviceId != issuer.deviceId) return176 val snapshot = requireMasterKeySnapshot()177 val master = snapshot.key178 val localKeys = deriveSyncIdentityKeypair(master, ourDeviceId)179180 try {181 if (!repo.isSessionEpochCurrent(snapshot.epoch)) return182 183 184 185 186 val incomingRevocations = body.revoked.filterNot { it.deviceId == ourDeviceId }187 val currentRevocations = registry.listRevocations()188 val knownRevokedIds = currentRevocations.map { it.deviceId }.toSet()189 val newlyRevoked = incomingRevocations.filterNot { knownRevokedIds.contains(it.deviceId) }190 val revokedIds = (knownRevokedIds + incomingRevocations.map { it.deviceId }).toSet()191 val revokedKeys = (currentRevocations + incomingRevocations)192 .map { it.longTermPublicKeyHex.lowercase() }193 .filterNot { it == NO_KEY_SENTINEL }194 .toSet()195 fun revokedInStagedBatch(deviceId: String, longTermKey: String): Boolean {196 return deviceId in revokedIds || longTermKey.lowercase() in revokedKeys197 }198199 val stagedUpserts = LinkedHashMap<String, PairedDevice>()200 val stagedAlerts = ArrayList<SyncAlert>()201 newlyRevoked.forEach { revocation ->202 stagedAlerts += SyncAlert(203 type = SyncAlertType.DEVICE_REVOKED,204 deviceName = issuer.deviceName ?: "paired device",205 entryTitle = revocation.deviceId,206 timestamp = System.currentTimeMillis(),207 )208 }209 for (entry in body.devices) {210 if (entry.deviceId == ourDeviceId || entry.deviceId == issuer.deviceId) continue211 if (revokedInStagedBatch(entry.deviceId, entry.longTermPublicKeyHex)) continue212 val existing = stagedUpserts[entry.deviceId] ?: registry.get(entry.deviceId)213 val meshRoute = deriveManifestMeshRoute(master, localKeys.publicKey, entry)214 if (existing == null) {215 if (meshRoute == null) continue216 stagedUpserts[entry.deviceId] = PairedDevice(217 deviceId = entry.deviceId,218 deviceName = entry.deviceName,219 deviceType = entry.deviceType,220 longTermPublicKeyHex = entry.longTermPublicKeyHex.lowercase(),221 signingPublicKeyHex = entry.signingPublicKeyHex.lowercase(),222 trustSource = "vouched",223 wsPort = entry.wsPort,224 rendezvousSecretHex = meshRoute.first,225 relayUrl = meshRoute.second,226 pairedAt = entry.pairedAt,227 )228 } else {229 deviceKeyRotationAlert(existing, entry, System.currentTimeMillis())?.let(stagedAlerts::add)230 stagedUpserts[entry.deviceId] = existing.copy(231 deviceName = existing.deviceName?.takeIf { it.isNotBlank() }232 ?: entry.deviceName,233 deviceType = entry.deviceType,234 longTermPublicKeyHex = entry.longTermPublicKeyHex.lowercase(),235 signingPublicKeyHex = entry.signingPublicKeyHex.lowercase(),236 wsPort = existing.wsPort ?: entry.wsPort,237 rendezvousSecretHex =238 if (existing.trustSource == "vouched" && meshRoute != null) {239 meshRoute.first240 } else {241 existing.rendezvousSecretHex242 },243 relayUrl =244 if (existing.trustSource == "vouched" && meshRoute != null) {245 meshRoute.second246 } else {247 existing.relayUrl248 },249 pairedAt = existing.pairedAt,250 trustSource = existing.trustSource ?: "direct",251 )252 }253 }254255 val batch = DeviceManifestRegistryBatch(256 incomingRevocations = incomingRevocations,257 removals = newlyRevoked.map { it.deviceId }.toSet(),258 upserts = stagedUpserts.values.toList(),259 )260 261 262 263 264 val pendingIds = batch.removals + stagedUpserts.keys265 val priorPending = pending.getAll().filter { it.deviceId in pendingIds }266 val committed = repo.withSessionEpochCommit(snapshot.epoch) {267 val pendingRemoved = runCatching { pending.removeBatch(pendingIds) }.getOrDefault(false)268 if (!pendingRemoved) {269 pending.restoreBatch(priorPending)270 false271 } else {272 val registryCommitted = runCatching { registry.applyManifestBatch(batch) }.getOrDefault(false)273 if (registryCommitted) {274 275 276 277 if (stagedAlerts.isNotEmpty()) syncAlerts?.record(stagedAlerts)278 true279 } else {280 pending.restoreBatch(priorPending)281 false282 }283 }284 }285 if (committed != true) return286 } finally {287 VaultCrypto.zero(master)288 VaultCrypto.zero(localKeys.secretKey)289 }290 }291292 private fun deriveManifestMeshRoute(293 masterKey: ByteArray,294 localPublicKey: ByteArray,295 entry: ManifestDeviceEntry,296 ): Pair<String, String>? = runCatching {297 val relayUrl = Rendezvous.normalizeRelayUrl(entry.relayUrl ?: return null)298 val secret = Rendezvous.deriveMeshSecret(299 masterKey,300 localPublicKey,301 hexToPubkey(entry.longTermPublicKeyHex),302 )303 try {304 Rendezvous.bytesToHex(secret) to relayUrl305 } finally {306 secret.fill(0)307 }308 }.getOrNull()309310 private fun requireMasterKeySnapshot(): VaultRepository.SyncMasterKeySnapshot =311 repo.syncMasterKeySnapshot() ?: throw VaultLockedException()312313314 private fun deriveEntryKey(masterKey: ByteArray, entryId: String): ByteArray {315 316 317 318 319 val info = (entryId + "\u0000" + ENTRY_KEY_INFO_SUFFIX).toByteArray(Charsets.UTF_8)320 val gen = HKDFBytesGenerator(SHA256Digest())321 gen.init(HKDFParameters(masterKey, ByteArray(0), info))322 return ByteArray(32).also { gen.generateBytes(it, 0, it.size) }323 }324325 private fun encryptEntry(key: ByteArray, entry: VaultEntry): String {326 327 328 var plaintext: ByteArray? = null329 return try {330 plaintext = entryJson.encodeToString(VaultEntry.serializer(), entry).toByteArray(Charsets.UTF_8)331 val nonce = ByteArray(12).also(rng::nextBytes)332 val cipher = Cipher.getInstance("AES/GCM/NoPadding")333 cipher.init(Cipher.ENCRYPT_MODE, SecretKeySpec(key, "AES"), GCMParameterSpec(128, nonce))334 cipher.updateAAD(ENTRY_AAD)335 val ct = cipher.doFinal(plaintext)336 b64(nonce + ct)337 } finally {338 plaintext?.let(VaultCrypto::zero)339 }340 }341342 private fun decryptEntryOrNull(key: ByteArray, envelopeB64: String): VaultEntry? {343 var pt: ByteArray? = null344 return try {345 val bytes = unb64(envelopeB64)346 if (bytes.size < 12 + 16) null else {347 val nonce = bytes.copyOfRange(0, 12)348 val ct = bytes.copyOfRange(12, bytes.size)349 val cipher = Cipher.getInstance("AES/GCM/NoPadding")350 cipher.init(Cipher.DECRYPT_MODE, SecretKeySpec(key, "AES"), GCMParameterSpec(128, nonce))351 cipher.updateAAD(ENTRY_AAD)352 pt = cipher.doFinal(ct)353 entryJson.decodeFromString(VaultEntry.serializer(), String(pt, Charsets.UTF_8))354 }355 } catch (_: Exception) {356 null357 } finally {358 359 360 361 pt?.let(VaultCrypto::zero)362 }363 }364365 private companion object {366 const val ENTRY_KEY_INFO_SUFFIX = "sync-entry-v1"367 val ENTRY_AAD = "peach-sync-entry-v1".toByteArray(Charsets.UTF_8)368 val rng = SecureRandom()369 val entryJson = Json { encodeDefaults = false; ignoreUnknownKeys = true }370 fun b64(b: ByteArray): String = Base64.getEncoder().encodeToString(b)371 fun unb64(s: String): ByteArray = Base64.getDecoder().decode(s)372 }373}374375class VaultLockedException : Exception("vault_locked")