1package com.peachpasswords.vault23import android.content.Context4import dagger.hilt.android.qualifiers.ApplicationContext5import kotlinx.serialization.Serializable6import kotlinx.serialization.decodeFromString7import kotlinx.serialization.encodeToString8import kotlinx.serialization.json.Json9import javax.inject.Inject10import javax.inject.Singleton111213141516171819@Serializable20data class StoredVault(21 22 val version: Int = LEGACY_ANDROID_SLOT_VERSION,23 val salt: String,24 val blob: String,25 val recoveryEscrow: RecoveryEscrow? = null,26 val rootKeyEscrow: RootKeyEscrow? = null,27)2829const val LEGACY_ANDROID_SLOT_VERSION = 130const val CURRENT_ANDROID_SLOT_VERSION = 2313233343536373839404142434445@Serializable46data class RootKeyEscrow(47 val salt: String,48 val wrappedRootKey: String,49 val nonce: String,50 val tag: String,51)5253545556575859606162@Serializable63data class RecoveryEscrow(64 val salt: String,65 val blob: String,66)6768@Serializable69data class VaultHistory(70 val snapshots: List<VaultSnapshot> = emptyList(),71)727374@Serializable75data class Tombstone(val id: String, val deletedAt: Long)76777879808182838485868788@Serializable89data class VaultPayload(90 val entries: List<VaultEntry> = emptyList(),91 val duressConfigured: Boolean = false,92 val rootKeyB64: String = "",93 94959697 val recoveryWordHash: String? = null,98 99 val recoveryWordsSet: Boolean = false,100)101102const val SLOT_RECORD_PAD: Char = '\u0000'103104105object VaultCodec {106 private val json = Json { ignoreUnknownKeys = true; encodeDefaults = true }107108 109 110 111 112 113 fun encode(payload: VaultPayload): ByteArray =114 VaultCrypto.padToBucket(json.encodeToString(payload).toByteArray(Charsets.UTF_8))115 fun decode(bytes: ByteArray): VaultPayload =116 json.decodeFromString(String(bytes, Charsets.UTF_8).trimEnd('\u0000'))117 118 internal fun decodeEntryForTest(entryJson: String): VaultEntry = json.decodeFromString(entryJson)119 internal fun encodeEntryForTest(entry: VaultEntry): String = json.encodeToString(entry)120121 fun encodeSettings(s: VaultSettings): String = json.encodeToString(s)122 fun decodeSettings(s: String): VaultSettings? = runCatching { json.decodeFromString<VaultSettings>(s) }.getOrNull()123 fun encodeSlot(s: StoredVault): String = json.encodeToString(s)124 fun decodeSlot(s: String): StoredVault? =125 runCatching { json.decodeFromString<StoredVault>(s.trimEnd(SLOT_RECORD_PAD)) }.getOrNull()126127 128129130131132 fun padSlotRecord(record: String, targetLength: Int): String =133 if (record.length >= targetLength) record else record.padEnd(targetLength, SLOT_RECORD_PAD)134135 fun slotRecordLength(record: String): Int = record.trimEnd(SLOT_RECORD_PAD).length136137 138139140141142143144145146147148149150151 fun alignSlotRecords(record: String, sibling: String?): Pair<String, String?> {152 if (sibling == null) return record to null153 val target = maxOf(record.length, slotRecordLength(sibling))154 return padSlotRecord(record, target) to padSlotRecord(sibling, target)155 }156 fun encodeHistory(h: VaultHistory): String = json.encodeToString(h)157 fun decodeHistory(s: String): VaultHistory? = runCatching { json.decodeFromString<VaultHistory>(s) }.getOrNull()158}159160interface VaultStorage {161 fun loadDecoySlot(): StoredVault?162 fun loadSlotA(): StoredVault?163 fun hasVault(): Boolean164 fun writeSlotA(slot: StoredVault): Boolean165 fun loadSlotB(): String? = null166 fun writeSlotB(blobBase64: String): Boolean167 fun writeDecoySlot(slot: StoredVault): Boolean168 169 fun restoreVaultTriad(slotA: StoredVault, slotB: String?, decoy: StoredVault): Boolean {170 val priorA = loadSlotA()171 val priorB = loadSlotB()172 val priorD = loadDecoySlot()173 return try {174 if (!writeSlotA(slotA)) return false175 if (slotB == null) clearSlotB() else if (!writeSlotB(slotB)) throw IllegalStateException("slot_b_restore_failed")176 if (!writeDecoySlot(decoy)) throw IllegalStateException("decoy_restore_failed")177 true178 } catch (_: Exception) {179 runCatching { if (priorA == null) clearVault() else writeSlotA(priorA) }180 runCatching { if (priorB == null) clearSlotB() else writeSlotB(priorB) }181 runCatching { if (priorD == null) clearDecoySlot() else writeDecoySlot(priorD) }182 false183 }184 }185 fun clearSlotB() {}186 fun hasDecoySlot(): Boolean = loadDecoySlot() != null187 fun clearDecoySlot()188 fun version(): Long189 fun stampLocalMutation(): Long190 fun loadSettings(): VaultSettings191 fun writeSettings(settings: VaultSettings): Boolean192 fun loadVaultHistory(): VaultHistory = VaultHistory()193 fun writeVaultHistory(history: VaultHistory): Boolean = true194 fun clearVaultHistory() {}195 fun clearVault()196}197198199200201202203204205@Singleton206class VaultStore @Inject constructor(207 @ApplicationContext context: Context,208) : VaultStorage {209 private val prefs = context.getSharedPreferences(PREFS, Context.MODE_PRIVATE)210211 override fun loadSlotA(): StoredVault? = prefs.getString(KEY_SLOT_A, null)?.let(VaultCodec::decodeSlot)212213 override fun hasVault(): Boolean = prefs.contains(KEY_SLOT_A)214215 override fun writeSlotA(slot: StoredVault): Boolean =216 writeAligned(KEY_SLOT_A, VaultCodec.encodeSlot(slot), KEY_SLOT_DURESS)217 override fun clearSlotB() { prefs.edit().remove(KEY_SLOT_B).commit() }218 override fun loadSlotB(): String? = prefs.getString(KEY_SLOT_B, null)219220 override fun writeSlotB(blobBase64: String): Boolean =221 prefs.edit().putString(KEY_SLOT_B, blobBase64).commit()222223 override fun loadDecoySlot(): StoredVault? = prefs.getString(KEY_SLOT_DURESS, null)?.let(VaultCodec::decodeSlot)224 override fun writeDecoySlot(slot: StoredVault): Boolean =225 writeAligned(KEY_SLOT_DURESS, VaultCodec.encodeSlot(slot), KEY_SLOT_A)226227 228 private fun writeAligned(key: String, record: String, siblingKey: String): Boolean {229 val (aligned, alignedSibling) = VaultCodec.alignSlotRecords(230 record,231 prefs.getString(siblingKey, null),232 )233 val edits = prefs.edit().putString(key, aligned)234 if (alignedSibling != null) edits.putString(siblingKey, alignedSibling)235 return edits.commit()236 }237238 override fun restoreVaultTriad(slotA: StoredVault, slotB: String?, decoy: StoredVault): Boolean {239 val edits = prefs.edit()240 .putString(KEY_SLOT_A, VaultCodec.encodeSlot(slotA))241 .putString(KEY_SLOT_DURESS, VaultCodec.encodeSlot(decoy))242 if (slotB != null) edits.putString(KEY_SLOT_B, slotB) else edits.remove(KEY_SLOT_B)243 return edits.commit()244 }245 override fun hasDecoySlot(): Boolean = prefs.contains(KEY_SLOT_DURESS)246 override fun clearDecoySlot() { prefs.edit().remove(KEY_SLOT_DURESS).commit() }247248 override fun version(): Long = prefs.getString(KEY_VERSION, null)?.toLongOrNull() ?: 0L249250 override fun stampLocalMutation(): Long {251 val next = maxOf(System.currentTimeMillis(), version() + 1L)252 253 254 255 256 if (!prefs.edit().putString(KEY_VERSION, next.toString()).commit()) {257 throw java.io.IOException("version_stamp_commit_failed")258 }259 return next260 }261262 override fun loadSettings(): VaultSettings =263 prefs.getString(KEY_SETTINGS, null)?.let(VaultCodec::decodeSettings) ?: VaultSettings()264265 override fun writeSettings(settings: VaultSettings): Boolean =266 prefs.edit().putString(KEY_SETTINGS, VaultCodec.encodeSettings(settings)).commit()267268 override fun loadVaultHistory(): VaultHistory =269 prefs.getString(KEY_HISTORY, null)?.let(VaultCodec::decodeHistory) ?: VaultHistory()270271 override fun writeVaultHistory(history: VaultHistory): Boolean =272 prefs.edit().putString(KEY_HISTORY, VaultCodec.encodeHistory(history)).commit()273274 override fun clearVaultHistory() {275 prefs.edit().remove(KEY_HISTORY).commit()276 }277278 override fun clearVault() {279 280 281 282 prefs.edit()283 .remove(KEY_SLOT_A).remove(KEY_SLOT_B).remove(KEY_SLOT_DURESS)284 .remove(KEY_VERSION).remove(KEY_SETTINGS).remove(KEY_HISTORY)285 .remove("peach_pin_salt").remove("peach_pin_verifier").remove("peach_pin_wrapped_key")286 .remove("peach_pin_preferred")287 .remove("peach_pin_format").remove("peach_pin_salt_v2")288 .remove("peach_pin_verifier_v2").remove("peach_pin_wrapped_key_v2")289 .remove("peach_pin_wrapped_iv_v2").remove("peach_pin_attempt_aliases_v2")290 .remove("peach_pin_preferred_v2")291 .commit()292 }293294 companion object {295 private const val PREFS = "peach_vault_store"296 private const val KEY_SLOT_A = "peach_vault_a"297 private const val KEY_SLOT_B = "peach_vault_b"298 private const val KEY_SLOT_DURESS = "peach_vault_duress"299 private const val KEY_VERSION = "peach_last_modified_at"300 private const val KEY_SETTINGS = "peach_settings"301 private const val KEY_HISTORY = "peach_vault_history"302 }303}