12345678910111213141516171819202122232425package com.peachpasswords.ui.recovery2627import androidx.compose.foundation.background28import androidx.compose.foundation.border29import androidx.compose.foundation.clickable30import androidx.compose.foundation.interaction.MutableInteractionSource31import androidx.compose.foundation.interaction.collectIsFocusedAsState32import androidx.compose.foundation.layout.Arrangement33import androidx.compose.foundation.layout.Box34import androidx.compose.foundation.layout.Column35import androidx.compose.foundation.layout.Row36import androidx.compose.foundation.layout.Spacer37import androidx.compose.foundation.layout.fillMaxSize38import androidx.compose.foundation.layout.fillMaxWidth39import androidx.compose.foundation.layout.height40import androidx.compose.foundation.layout.padding41import androidx.compose.foundation.layout.size42import androidx.compose.foundation.layout.systemBarsPadding43import androidx.compose.foundation.layout.width44import androidx.compose.foundation.rememberScrollState45import androidx.compose.foundation.shape.RoundedCornerShape46import androidx.compose.foundation.text.BasicTextField47import androidx.compose.foundation.text.KeyboardActions48import androidx.compose.foundation.text.KeyboardOptions49import androidx.compose.foundation.verticalScroll50import androidx.compose.material3.Text51import androidx.compose.runtime.Composable52import androidx.compose.runtime.collectAsState53import androidx.compose.runtime.getValue54import androidx.compose.runtime.mutableStateListOf55import androidx.compose.runtime.mutableStateOf56import androidx.compose.runtime.remember57import androidx.compose.runtime.setValue58import androidx.compose.ui.Alignment59import androidx.compose.ui.Modifier60import androidx.compose.ui.draw.clip61import androidx.compose.ui.draw.drawBehind62import androidx.compose.ui.focus.FocusRequester63import androidx.compose.ui.focus.focusRequester64import androidx.compose.ui.geometry.Offset65import androidx.compose.ui.geometry.Size66import androidx.compose.ui.graphics.Color67import androidx.compose.ui.graphics.SolidColor68import androidx.compose.ui.text.TextStyle69import androidx.compose.ui.text.font.FontStyle70import androidx.compose.ui.text.input.ImeAction71import androidx.compose.ui.text.input.KeyboardType72import androidx.compose.ui.text.input.PasswordVisualTransformation73import androidx.compose.ui.text.input.VisualTransformation74import androidx.compose.ui.text.style.TextAlign75import androidx.compose.ui.unit.dp76import androidx.compose.ui.unit.em77import androidx.compose.ui.unit.sp78import androidx.hilt.navigation.compose.hiltViewModel79import androidx.lifecycle.ViewModel80import androidx.lifecycle.viewModelScope81import com.peachpasswords.ui.lock.MIN_PASSWORD_LENGTH82import com.peachpasswords.ui.security.StrengthBar83import com.peachpasswords.ui.security.scorePassword84import com.peachpasswords.ui.security.strengthColor85import com.peachpasswords.ui.security.strengthLabel86import com.peachpasswords.ui.theme.LocalPeachAccent87import com.peachpasswords.ui.theme.PeachColors88import com.peachpasswords.ui.theme.PeachType89import com.peachpasswords.ui.theme.ShellBackground90import com.peachpasswords.vault.VaultRepository91import com.peachpasswords.vault.WORD_LIST92import com.peachpasswords.vault.getWordSuggestions93import com.peachpasswords.vault.wordsToRootKeyMaterial94import dagger.hilt.android.lifecycle.HiltViewModel95import kotlinx.coroutines.Dispatchers96import kotlinx.coroutines.flow.MutableStateFlow97import kotlinx.coroutines.flow.StateFlow98import kotlinx.coroutines.flow.asStateFlow99import kotlinx.coroutines.flow.update100import kotlinx.coroutines.launch101import kotlinx.coroutines.withContext102import javax.inject.Inject103104private const val WORD_COUNT = 12105106private enum class RecoveryStep { WORDS, PASSWORD, NO_ESCROW }107108data class RecoveryEntryUiState(109 val step: RecoveryStep = RecoveryStep.WORDS,110 val checksumValid: Boolean = false,111 val wordsError: String? = null,112 val passwordError: String? = null,113 val working: Boolean = false,114)115116@HiltViewModel117class RecoveryEntryViewModel @Inject constructor(118 private val vault: VaultRepository,119) : ViewModel() {120121 private val _state = MutableStateFlow(122 RecoveryEntryUiState(123 124 125 step = if (vault.hasRecoveryEscrow()) RecoveryStep.WORDS else RecoveryStep.NO_ESCROW,126 ),127 )128 val state: StateFlow<RecoveryEntryUiState> = _state.asStateFlow()129130 private var validatedWords: List<String> = emptyList()131132 133 fun validateWords(words: List<String>) {134 viewModelScope.launch {135 val ok = withContext(Dispatchers.Default) {136 runCatching { wordsToRootKeyMaterial(words) }.isSuccess137 }138 validatedWords = if (ok) words.map { it.trim().lowercase() } else emptyList()139 _state.update {140 it.copy(141 checksumValid = ok,142 wordsError = if (!ok && words.all { w -> w.isNotBlank() }) {143 "These words don't form a valid recovery phrase — check for typos"144 } else null,145 )146 }147 }148 }149150 fun continueToPassword() {151 if (_state.value.checksumValid) _state.update { it.copy(step = RecoveryStep.PASSWORD) }152 }153154 155156157158 fun recover(newPassword: String, confirm: String, onSuccess: () -> Unit) {159 val s = _state.value160 if (s.working) return161 when {162 newPassword.length < MIN_PASSWORD_LENGTH ->163 return _state.update { it.copy(passwordError = "Password must be at least $MIN_PASSWORD_LENGTH characters") }164 newPassword != confirm ->165 return _state.update { it.copy(passwordError = "Passwords do not match") }166 scorePassword(newPassword) < 2 ->167 return _state.update { it.copy(passwordError = "Password too weak — try a longer or more varied password") }168 }169 _state.update { it.copy(working = true, passwordError = null) }170 viewModelScope.launch {171 val unlocked = vault.unlockWithRecoveryWords(validatedWords)172 if (!unlocked) {173 _state.update { it.copy(working = false, passwordError = "Incorrect recovery words — vault cannot be unlocked") }174 return@launch175 }176 val reset = vault.resetPasswordWithRecoveryWords(validatedWords, newPassword)177 if (!reset) {178 _state.update { it.copy(working = false, passwordError = "Something went wrong — please try again") }179 return@launch180 }181 _state.update { it.copy(working = false) }182 onSuccess()183 }184 }185}186187@Composable188fun RecoveryWordEntryScreen(189 onSuccess: () -> Unit,190 onBack: () -> Unit,191 onRestore: () -> Unit = onBack,192 vm: RecoveryEntryViewModel = hiltViewModel(),193) {194 val state by vm.state.collectAsState()195 ShellBackground {196 Column(197 modifier = Modifier198 .fillMaxSize()199 .systemBarsPadding()200 .padding(horizontal = 22.dp, vertical = 18.dp)201 .verticalScroll(rememberScrollState()),202 ) {203 when (state.step) {204 RecoveryStep.WORDS -> WordStep(state, vm, onBack)205 RecoveryStep.PASSWORD -> PasswordStep(state, vm, onSuccess)206 RecoveryStep.NO_ESCROW -> NoEscrowStep(onRestore = onRestore, onBack = onBack)207 }208 }209 }210}211212@Composable213private fun WordStep(state: RecoveryEntryUiState, vm: RecoveryEntryViewModel, onBack: () -> Unit) {214 val words = remember { mutableStateListOf(*Array(WORD_COUNT) { "" }) }215 val focusers = remember { List(WORD_COUNT) { FocusRequester() } }216217 fun onWordChange(i: Int, raw: String) {218 words[i] = raw.trim().lowercase().filter { it.isLetter() }219 220 221 if (words.all { it.isNotBlank() } || state.checksumValid || state.wordsError != null) {222 vm.validateWords(words.toList())223 }224 }225226 Eyebrow("VAULT RECOVERY")227 Spacer(Modifier.height(10.dp))228 Headline("enter your\nrecovery words.")229 Spacer(Modifier.height(18.dp))230231 GlassPanel {232 233 for (row in 0 until 4) {234 Row(Modifier.fillMaxWidth().padding(vertical = 6.dp), horizontalArrangement = Arrangement.spacedBy(8.dp)) {235 for (col in 0 until 3) {236 val i = row * 3 + col237 WordSlot(238 index = i,239 value = words[i],240 focusRequester = focusers[i],241 onValueChange = { onWordChange(i, it) },242 onPicked = { picked ->243 words[i] = picked244 if (i + 1 < WORD_COUNT) focusers[i + 1].requestFocus()245 if (words.all { it.isNotBlank() }) vm.validateWords(words.toList())246 },247 imeAction = if (i == WORD_COUNT - 1) ImeAction.Done else ImeAction.Next,248 onNext = { if (i + 1 < WORD_COUNT) focusers[i + 1].requestFocus() },249 modifier = Modifier.weight(1f),250 )251 }252 }253 }254255 if (state.wordsError != null) {256 Spacer(Modifier.height(10.dp))257 Text(258 state.wordsError,259 color = PeachColors.Breach,260 style = PeachType.labelMono.copy(fontSize = 10.sp),261 )262 }263 }264265 Spacer(Modifier.height(18.dp))266 AccentButton("Continue", enabled = state.checksumValid, onClick = vm::continueToPassword)267 Spacer(Modifier.height(10.dp))268 GhostButton("Back to login", PeachColors.T1, onBack)269}270271@Composable272private fun WordSlot(273 index: Int,274 value: String,275 focusRequester: FocusRequester,276 onValueChange: (String) -> Unit,277 onPicked: (String) -> Unit,278 imeAction: ImeAction,279 onNext: () -> Unit,280 modifier: Modifier = Modifier,281) {282 val accent = LocalPeachAccent.current283 val interaction = remember { MutableInteractionSource() }284 val focused by interaction.collectIsFocusedAsState()285 val isValidWord = remember(value) { value.isNotBlank() && WORD_LIST.contains(value) }286 val suggestions = remember(value, focused) {287 if (focused && value.isNotBlank() && !isValidWord) getWordSuggestions(value, 4) else emptyList()288 }289290 Column(modifier = modifier) {291 Row(verticalAlignment = Alignment.CenterVertically) {292 Text(293 "${index + 1}",294 color = accent,295 style = PeachType.recoveryNumeral,296 textAlign = TextAlign.End,297 modifier = Modifier.width(20.dp),298 )299 Spacer(Modifier.width(4.dp))300 BasicTextField(301 value = value,302 onValueChange = onValueChange,303 singleLine = true,304 textStyle = PeachType.recoveryWord.copy(color = PeachColors.T0),305 cursorBrush = SolidColor(accent),306 keyboardOptions = KeyboardOptions(307 keyboardType = KeyboardType.Password, 308 imeAction = imeAction,309 ),310 keyboardActions = KeyboardActions(onNext = { onNext() }, onDone = { onNext() }),311 interactionSource = interaction,312 modifier = Modifier313 .weight(1f)314 .focusRequester(focusRequester)315 .background(if (isValidWord) accent.copy(alpha = 0.08f) else Color.Transparent)316 .drawBehind {317 drawRect(318 color = if (focused) accent else PeachColors.T3,319 topLeft = Offset(0f, size.height - 1.dp.toPx()),320 size = Size(size.width, 1.dp.toPx()),321 )322 }323 .padding(vertical = 6.dp, horizontal = 2.dp),324 )325 }326 327 if (suggestions.isNotEmpty()) {328 Column(329 Modifier330 .fillMaxWidth()331 .clip(RoundedCornerShape(6.dp))332 .background(PeachColors.S2)333 .padding(vertical = 2.dp),334 ) {335 suggestions.forEach { word ->336 Text(337 word,338 color = PeachColors.T1,339 style = PeachType.labelMono.copy(fontSize = 11.sp),340 modifier = Modifier341 .fillMaxWidth()342 .clickable { onPicked(word) }343 .padding(horizontal = 8.dp, vertical = 5.dp),344 )345 }346 }347 }348 }349}350351@Composable352private fun PasswordStep(state: RecoveryEntryUiState, vm: RecoveryEntryViewModel, onSuccess: () -> Unit) {353 var password by remember { mutableStateOf("") }354 var confirm by remember { mutableStateOf("") }355 var reveal by remember { mutableStateOf(false) }356 val score = remember(password) { scorePassword(password) }357 val canSubmit = score >= 2 && password.isNotEmpty() && password == confirm && !state.working358359 Eyebrow("VAULT RECOVERY")360 Spacer(Modifier.height(10.dp))361 Headline("set a new\npassword.")362 Spacer(Modifier.height(18.dp))363364 GlassPanel {365 FieldLabel("new password")366 Spacer(Modifier.height(4.dp))367 PasswordField(368 value = password,369 onChange = { password = it },370 reveal = reveal,371 onToggleReveal = { reveal = !reveal },372 imeAction = ImeAction.Next,373 )374375 if (password.isNotEmpty()) {376 Spacer(Modifier.height(14.dp))377 StrengthBar(score = score)378 Spacer(Modifier.height(6.dp))379 Text(380 "strength: ${strengthLabel(score)}",381 color = strengthColor(score),382 style = PeachType.labelMono,383 modifier = Modifier.fillMaxWidth(),384 textAlign = TextAlign.Center,385 )386 }387388 Spacer(Modifier.height(16.dp))389 FieldLabel("confirm password")390 Spacer(Modifier.height(4.dp))391 PasswordField(392 value = confirm,393 onChange = { confirm = it },394 reveal = reveal,395 onToggleReveal = { reveal = !reveal },396 imeAction = ImeAction.Done,397 )398399 Text(400 state.passwordError ?: " ",401 color = PeachColors.Breach,402 style = PeachType.labelMono.copy(fontSize = 10.sp),403 textAlign = TextAlign.Center,404 modifier = Modifier.fillMaxWidth().padding(top = 12.dp).height(16.dp),405 )406 }407408 Spacer(Modifier.height(18.dp))409 AccentButton(410 label = if (state.working) "recovering…" else "Recover vault",411 enabled = canSubmit,412 onClick = { vm.recover(password, confirm, onSuccess) },413 )414}415416@Composable417private fun NoEscrowStep(onRestore: () -> Unit, onBack: () -> Unit) {418 GlassPanel {419 Text("⊘", color = PeachColors.T2, style = TextStyle(fontFamily = PeachType.Display, fontSize = 40.sp))420 Spacer(Modifier.height(12.dp))421 Text(422 "recovery not available",423 color = PeachColors.T1,424 style = TextStyle(fontFamily = PeachType.Display, fontStyle = FontStyle.Italic, fontSize = 26.sp),425 )426 Spacer(Modifier.height(10.dp))427 Text(428 "Recovery words were not set up for this vault. You can restore from a backup instead.",429 color = PeachColors.T2,430 style = PeachType.labelMono.copy(fontSize = 10.sp),431 )432 Spacer(Modifier.height(18.dp))433 GhostButton("Restore from backup", LocalPeachAccent.current, onRestore)434 Spacer(Modifier.height(8.dp))435 GhostButton("Back to login", PeachColors.T1, onBack)436 }437}438439440441@Composable442private fun Eyebrow(text: String) =443 Text(text, color = PeachColors.T2, style = PeachType.lockEyebrow)444445@Composable446private fun Headline(text: String) =447 Text(448 text,449 color = PeachColors.T0,450 style = PeachType.lockHeadline,451 )452453@Composable454private fun FieldLabel(text: String) =455 Text(text.uppercase(), color = PeachColors.T2, style = PeachType.labelMono.copy(letterSpacing = 0.08.em))456457@Composable458private fun PasswordField(459 value: String,460 onChange: (String) -> Unit,461 reveal: Boolean,462 onToggleReveal: () -> Unit,463 imeAction: ImeAction,464) {465 val accent = LocalPeachAccent.current466 val interaction = remember { MutableInteractionSource() }467 val focused by interaction.collectIsFocusedAsState()468 Row(verticalAlignment = Alignment.CenterVertically) {469 BasicTextField(470 value = value,471 onValueChange = onChange,472 singleLine = true,473 textStyle = PeachType.unlockInput.copy(color = PeachColors.T0),474 cursorBrush = SolidColor(accent),475 visualTransformation = if (reveal) VisualTransformation.None else PasswordVisualTransformation(),476 keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Password, imeAction = imeAction),477 interactionSource = interaction,478 modifier = Modifier479 .weight(1f)480 .drawBehind {481 drawRect(482 color = if (focused) accent else PeachColors.T3,483 topLeft = Offset(0f, size.height - 1.dp.toPx()),484 size = Size(size.width, 1.dp.toPx()),485 )486 }487 .padding(vertical = 8.dp),488 )489 Text(490 if (reveal) "hide" else "show",491 color = accent,492 style = PeachType.labelMono,493 modifier = Modifier.clickable(onClick = onToggleReveal).padding(start = 8.dp, top = 6.dp, bottom = 6.dp),494 )495 }496}497498@Composable499private fun GlassPanel(content: @Composable androidx.compose.foundation.layout.ColumnScope.() -> Unit) {500 Column(501 modifier = Modifier502 .fillMaxWidth()503 .clip(RoundedCornerShape(18.dp))504 .background(Color(0xE0131109))505 .border(1.dp, PeachColors.T3, RoundedCornerShape(18.dp))506 .padding(20.dp),507 content = content,508 )509}510511@Composable512private fun AccentButton(label: String, enabled: Boolean, onClick: () -> Unit) {513 val accent = LocalPeachAccent.current514 Box(515 modifier = Modifier516 .fillMaxWidth()517 .clip(RoundedCornerShape(12.dp))518 .background(if (enabled) accent else accent.copy(alpha = 0.3f))519 .clickable(enabled = enabled, onClick = onClick)520 .padding(vertical = 14.dp),521 contentAlignment = Alignment.Center,522 ) {523 Text(label, color = Color(0xFF0C0A06), style = PeachType.bodyMono)524 }525}526527@Composable528private fun GhostButton(label: String, color: Color, onClick: () -> Unit) {529 Box(530 modifier = Modifier531 .fillMaxWidth()532 .clip(RoundedCornerShape(12.dp))533 .border(1.dp, color.copy(alpha = 0.4f), RoundedCornerShape(12.dp))534 .clickable(onClick = onClick)535 .padding(vertical = 12.dp),536 contentAlignment = Alignment.Center,537 ) {538 Text(label, color = color, style = PeachType.bodyMono)539 }540}