1package com.peachpasswords.sync23import android.content.Context4import androidx.security.crypto.EncryptedSharedPreferences5import androidx.security.crypto.MasterKey6import com.peachpasswords.vault.VaultCrypto7import com.peachpasswords.vault.VaultRepository8import dagger.hilt.android.qualifiers.ApplicationContext9import kotlinx.serialization.Serializable10import kotlinx.serialization.json.Json11import org.bouncycastle.crypto.params.X25519PrivateKeyParameters12import java.security.MessageDigest13import javax.inject.Inject14import javax.inject.Singleton1516@Serializable17internal data class LockedSyncCachedEntry(val modifiedAt: Long, val ciphertext: String)1819@Serializable20internal data class LockedSyncSpool(21 val version: Int = 1,22 val vaultId: String,23 val deviceId: String,24 val deviceName: String,25 val localVersion: Long,26 val longTermPublicKeyHex: String,27 val longTermPrivateKeyHex: String? = null,28 val signingPublicKeyHex: String,29 val entries: Map<String, LockedSyncCachedEntry>,30 val tombstones: Map<String, Long>,31 val inboxEntries: Map<String, LockedSyncCachedEntry> = emptyMap(),32 val inboxTombstones: Map<String, Long> = emptyMap(),33) {34 init {35 require(entries.size <= SyncLimits.MAX_ENTRY_COUNT) { "sync_entry_count_exceeded" }36 require(inboxEntries.size <= SyncLimits.MAX_ENTRY_COUNT) { "sync_entry_count_exceeded" }37 require(tombstones.size <= SyncLimits.MAX_TOMBSTONE_COUNT) { "sync_tombstone_count_exceeded" }38 require(inboxTombstones.size <= SyncLimits.MAX_TOMBSTONE_COUNT) { "sync_tombstone_count_exceeded" }39 }40}414243@Singleton44class LockedSyncSpoolStore @Inject constructor(45 @ApplicationContext private val context: Context,46) {47 private val masterKey = MasterKey.Builder(context)48 .setKeyScheme(MasterKey.KeyScheme.AES256_GCM)49 .build()50 private val prefs = EncryptedSharedPreferences.create(51 context,52 PREFS_FILE,53 masterKey,54 EncryptedSharedPreferences.PrefKeyEncryptionScheme.AES256_SIV,55 EncryptedSharedPreferences.PrefValueEncryptionScheme.AES256_GCM,56 )5758 @Synchronized59 internal fun refresh(repo: VaultRepository) {60 val snapshot = repo.syncMasterKeySnapshot() ?: return61 val root = snapshot.key62 val credentials = loadOrCreateLocalIdentity(context)63 val deviceId = credentials.deviceId64 val keys = localSyncKeypair(credentials)65 try {66 val prior = read()67 val entries = repo.getEntries().associate { entry ->68 entry.id to LockedSyncCachedEntry(69 entry.modifiedAt,70 VaultSyncAdapter.encryptEntryWithMasterKey(root, entry),71 )72 }73 if (!repo.isSessionEpochCurrent(snapshot.epoch)) return74 val signing = localSigningKeypair(credentials)75 write(76 LockedSyncSpool(77 vaultId = computeVaultId(root),78 deviceId = deviceId,79 deviceName = getDeviceName(context),80 localVersion = repo.getVaultVersion(),81 longTermPublicKeyHex = pubkeyToHex(keys.publicKey),82 longTermPrivateKeyHex = pubkeyToHex(keys.secretKey),83 signingPublicKeyHex = pubkeyToHex(signing.publicKeyRaw),84 entries = entries,85 tombstones = repo.getTombstones().associate { it.id to it.deletedAt },86 inboxEntries = prior?.inboxEntries ?: emptyMap(),87 inboxTombstones = prior?.inboxTombstones ?: emptyMap(),88 ),89 )90 } finally {91 VaultCrypto.zero(root)92 VaultCrypto.zero(keys.secretKey)93 }94 }9596 internal fun identity(): Pair<SyncIdentityKeypair, LocalDeviceIdentity>? {97 val state = read() ?: return null98 return lockedSyncIdentity(state, RelaySettingsStore.readRelayUrl(context))99 }100101 internal fun adapter(): SyncVaultAdapter? = read()?.let { LockedSyncVaultAdapter(this, it.vaultId) }102103 internal suspend fun drainInto(repo: VaultRepository) {104 val staged = read() ?: return105 if (staged.inboxEntries.isNotEmpty() || staged.inboxTombstones.isNotEmpty()) {106 val live = VaultSyncAdapter(repo, staged.deviceId)107 live.applyEntries(108 staged.inboxEntries.mapValues { it.value.ciphertext },109 staged.inboxEntries.mapValues { it.value.modifiedAt },110 )111 live.applyTombstones(staged.inboxTombstones)112 synchronized(this) {113 val current = read() ?: return@synchronized114 write(115 current.copy(116 inboxEntries = current.inboxEntries.filter { (id, value) ->117 staged.inboxEntries[id]?.ciphertext != value.ciphertext118 },119 inboxTombstones = current.inboxTombstones.filter { (id, value) ->120 staged.inboxTombstones[id] != value121 },122 ),123 )124 }125 }126 refresh(repo)127 }128129 @Synchronized130 internal fun stageEntries(vaultId: String, entries: Map<String, String>, manifest: Map<String, Long>) {131 val current = read()?.takeIf { it.vaultId == vaultId } ?: return132 require(entries.size <= SyncLimits.MAX_ENTRY_COUNT) { "sync_entry_count_exceeded" }133 val now = System.currentTimeMillis()134 val inbox = current.inboxEntries.toMutableMap()135 entries.forEach { (id, ciphertext) ->136 val claimed = manifest[id] ?: return@forEach137 if (claimed <= 0L || ciphertext.length > SyncLimits.MAX_ENTRY_ENVELOPE_BYTES) return@forEach138 val modifiedAt = SyncLimits.clampSyncTimestamp(claimed, now)139 if ((inbox[id]?.modifiedAt ?: 0L) < modifiedAt) {140 inbox[id] = LockedSyncCachedEntry(modifiedAt, ciphertext)141 }142 }143 write(current.copy(inboxEntries = inbox))144 }145146 @Synchronized147 internal fun stageTombstones(vaultId: String, tombstones: Map<String, Long>) {148 val current = read()?.takeIf { it.vaultId == vaultId } ?: return149 require(tombstones.size <= SyncLimits.MAX_TOMBSTONE_COUNT) { "sync_tombstone_count_exceeded" }150 val now = System.currentTimeMillis()151 val inbox = current.inboxTombstones.toMutableMap()152 tombstones.forEach { (id, timestamp) ->153 if (timestamp <= 0L) return@forEach154 val deletedAt = SyncLimits.clampSyncTimestamp(timestamp, now)155 if ((inbox[id] ?: 0L) < deletedAt) inbox[id] = deletedAt156 }157 write(current.copy(inboxTombstones = inbox))158 }159160 internal fun snapshot(vaultId: String): LockedSyncSpool? = read()?.takeIf { it.vaultId == vaultId }161 fun clear() { prefs.edit().remove(KEY_STATE).commit() }162163 private fun read(): LockedSyncSpool? {164 val raw = prefs.getString(KEY_STATE, null) ?: return null165 return runCatching { json.decodeFromString(LockedSyncSpool.serializer(), raw) }166 .getOrNull()167 ?.takeIf { it.version == 1 && it.vaultId.matches(Regex("^[0-9a-f]{64}$")) }168 }169170 private fun write(state: LockedSyncSpool) {171 check(prefs.edit().putString(KEY_STATE, json.encodeToString(LockedSyncSpool.serializer(), state)).commit()) {172 "locked_sync_spool_write_failed"173 }174 }175176 private companion object {177 const val PREFS_FILE = "peach_locked_sync_spool_v1"178 const val KEY_STATE = "state"179 val json = Json { encodeDefaults = true; ignoreUnknownKeys = true }180 }181}182183internal fun lockedSyncIdentity(184 state: LockedSyncSpool,185 relayUrl: String,186): Pair<SyncIdentityKeypair, LocalDeviceIdentity>? {187 val privateHex = state.longTermPrivateKeyHex ?: return null188 val secret = runCatching { hexToBytes(privateHex) }.getOrNull() ?: return null189 if (secret.size != 32) {190 VaultCrypto.zero(secret)191 return null192 }193 return try {194 val public = X25519PrivateKeyParameters(secret, 0).generatePublicKey().encoded195 val expectedPublic = hexToPubkey(state.longTermPublicKeyHex)196 if (!MessageDigest.isEqual(public, expectedPublic)) {197 VaultCrypto.zero(public)198 VaultCrypto.zero(secret)199 null200 } else {201 SyncIdentityKeypair(public, secret) to LocalDeviceIdentity(202 deviceId = state.deviceId,203 deviceName = state.deviceName,204 deviceType = DeviceType.ANDROID,205 longTermPublicKeyHex = state.longTermPublicKeyHex,206 signingPublicKeyHex = state.signingPublicKeyHex,207 relayUrl = relayUrl,208 )209 }210 } catch (_: RuntimeException) {211 VaultCrypto.zero(secret)212 null213 }214}215216internal class LockedSyncVaultAdapter(217 private val store: LockedSyncSpoolStore,218 private val vaultId: String,219) : SyncVaultAdapter {220 private fun state() = store.snapshot(vaultId) ?: throw VaultLockedException()221 override suspend fun computeVaultId() = vaultId222 override suspend fun getOurDeviceId() = state().deviceId223 override suspend fun getLocalVersion() = state().localVersion224 override suspend fun buildEntryManifest() = state().entries.mapValues { it.value.modifiedAt }225 override suspend fun buildTombstoneManifest() = state().tombstones226 override suspend fun getEncryptedEntries(entryIds: List<String>): Map<String, String> {227 val entries = state().entries228 return entryIds.mapNotNull { id -> entries[id]?.ciphertext?.let { id to it } }.toMap()229 }230 override suspend fun applyEntries(entries: Map<String, String>, remoteManifest: Map<String, Long>) =231 store.stageEntries(vaultId, entries, remoteManifest)232 override suspend fun applyTombstones(tombstones: Map<String, Long>) =233 store.stageTombstones(vaultId, tombstones)234}235236internal object LockedSyncSpoolHooks {237 @Volatile var refresh: (VaultRepository) -> Unit = {}238}