1package com.peachpasswords.sync23import android.content.Context4import android.content.SharedPreferences5import androidx.security.crypto.EncryptedSharedPreferences6import androidx.security.crypto.MasterKey7import dagger.hilt.android.EntryPointAccessors8import dagger.hilt.android.qualifiers.ApplicationContext9import dagger.hilt.EntryPoint10import dagger.hilt.InstallIn11import dagger.hilt.components.SingletonComponent12import javax.inject.Inject13import javax.inject.Singleton141516171819202122232425@Singleton26class SyncGenerationStore @Inject constructor(27 @ApplicationContext private val context: Context,28 private val devices: PairedDeviceStore,29 private val pendingDevices: PendingVouchedDeviceStore,30 private val lockedSyncSpool: LockedSyncSpoolStore,31) : SyncGenerationPort {3233 private val generationPrefs =34 context.getSharedPreferences(GENERATION_PREFS_FILE, Context.MODE_PRIVATE)3536 override fun readBlob(): String? = generationPrefs.getString(KEY_GENERATION, null)3738 override fun writeBlob(blob: String): Boolean =39 generationPrefs.edit().putString(KEY_GENERATION, blob).commit() && readBlob() == blob4041 override fun hasPairedDevices(): Boolean = devices.getAll().isNotEmpty()4243 override fun hasRevocations(): Boolean = devices.listRevocations().isNotEmpty()4445 override fun hasIssuerSigningKeys(): Boolean = devices.hasIssuerSigningKeys()4647 override fun hasPendingVouchedDevices(): Boolean = pendingDevices.getAll().isNotEmpty()4849 50515253545556575859 override fun archiveLegacyState(generation: Int): String? = runCatching {60 val archive = encryptedPrefs(context, ARCHIVE_PREFS_FILE)61 val prefix = "g$generation:"62 val expected = buildMap<String, Any?> {63 put("${prefix}meta", """{"schemaVersion":1,"generation":$generation,"archivedAt":${System.currentTimeMillis()}}""")64 for ((key, value) in devices.snapshot()) put("$prefix$ARCHIVE_DEVICES_PREFIX$key", value)65 for ((key, value) in pendingDevices.snapshot()) put("$prefix$ARCHIVE_PENDING_PREFIX$key", value)66 }67 check(archiveTrustPreferenceValues(archive, expected)) { "generation_archive_persist_failed" }68 ARCHIVE_PREFS_FILE69 }.getOrNull()7071 override fun clearLegacyTrustState(): Boolean = runCatching {72 PeachSyncService.stop(context)73 lockedSyncSpool.clear()74 devices.clear()75 pendingDevices.clear()76 devices.getAll().isEmpty() && devices.listRevocations().isEmpty() &&77 !devices.hasIssuerSigningKeys() && pendingDevices.getAll().isEmpty()78 }.getOrDefault(false)7980 81828384858687 override fun ensureV2Identity(): Boolean = runCatching {88 loadOrCreateLocalIdentity(context)89 true90 }.recoverCatching {91 check(!hasLegacyTrustState()) { "identity_mint_over_live_trust" }92 rotateDeviceId(context)93 true94 }.getOrDefault(false)9596 override fun localDeviceId(): String? =97 runCatching { loadOrCreateLocalIdentity(context).deviceId }.getOrNull()9899 100 fun clear() {101 generationPrefs.edit().clear().commit()102 }103104 private companion object {105 const val GENERATION_PREFS_FILE = "peach_sync_generation_v1"106 const val ARCHIVE_PREFS_FILE = "peach_sync_archive_v1"107 const val KEY_GENERATION = "sync_generation"108 const val ARCHIVE_DEVICES_PREFIX = "paired:"109 const val ARCHIVE_PENDING_PREFIX = "pending:"110 }111}112113114115116117118internal fun syncGenerationStore(context: Context): SyncGenerationStore =119 EntryPointAccessors120 .fromApplication(context.applicationContext, SyncGenerationEntryPoint::class.java)121 .syncGenerationStore()122123@EntryPoint124@InstallIn(SingletonComponent::class)125internal interface SyncGenerationEntryPoint {126 fun syncGenerationStore(): SyncGenerationStore127}128129private fun encryptedPrefs(context: Context, name: String): SharedPreferences =130 EncryptedSharedPreferences.create(131 context,132 name,133 MasterKey.Builder(context).setKeyScheme(MasterKey.KeyScheme.AES256_GCM).build(),134 EncryptedSharedPreferences.PrefKeyEncryptionScheme.AES256_SIV,135 EncryptedSharedPreferences.PrefValueEncryptionScheme.AES256_GCM,136 )137138internal fun copyRawTrustPreferences(values: Map<String, *>): Map<String, Any> = values.mapValues { (key, value) ->139 when (value) {140 is String, is Int, is Long, is Float, is Boolean -> value141 is Set<*> -> value.map { item ->142 require(item is String) { "unsupported_trust_preference:$key" }143 item144 }.toSet()145 else -> throw IllegalArgumentException("unsupported_trust_preference:$key")146 }147}148149internal fun putRawTrustPreferences(edit: SharedPreferences.Editor, values: Map<String, Any>) {150 values.forEach { (key, value) ->151 when (value) {152 is String -> edit.putString(key, value)153 is Int -> edit.putInt(key, value)154 is Long -> edit.putLong(key, value)155 is Float -> edit.putFloat(key, value)156 is Boolean -> edit.putBoolean(key, value)157 is Set<*> -> edit.putStringSet(key, value.map { item ->158 require(item is String) { "unsupported_trust_preference:$key" }159 item160 }.toSet())161 else -> throw IllegalArgumentException("unsupported_trust_preference:$key")162 }163 }164}165166internal fun archiveTrustPreferenceValues(archive: SharedPreferences, expected: Map<String, Any?>): Boolean {167 val raw = copyRawTrustPreferences(expected)168 val edit = archive.edit()169 putRawTrustPreferences(edit, raw)170 if (!edit.commit()) return false171 val actual = archive.all172 return raw.all { (key, value) -> actual[key] == value }173}