ExportScreen.kt

19.7 KB · raw

1package com.peachpasswords.ui.vault23import android.content.ClipData4import android.content.ClipboardManager5import android.content.Context6import android.net.Uri7import androidx.activity.compose.rememberLauncherForActivityResult8import androidx.activity.result.contract.ActivityResultContracts9import androidx.compose.foundation.background10import androidx.compose.foundation.border11import androidx.compose.foundation.clickable12import androidx.compose.foundation.layout.Box13import androidx.compose.foundation.layout.Column14import androidx.compose.foundation.layout.Row15import androidx.compose.foundation.layout.Spacer16import androidx.compose.foundation.layout.fillMaxSize17import androidx.compose.foundation.layout.fillMaxWidth18import androidx.compose.foundation.layout.height19import androidx.compose.foundation.layout.padding20import androidx.compose.foundation.layout.size21import androidx.compose.foundation.layout.systemBarsPadding22import androidx.compose.foundation.layout.width23import androidx.compose.foundation.rememberScrollState24import androidx.compose.foundation.shape.RoundedCornerShape25import androidx.compose.foundation.text.BasicTextField26import androidx.compose.foundation.verticalScroll27import androidx.compose.material.icons.Icons28import androidx.compose.material.icons.automirrored.rounded.ArrowBack29import androidx.compose.material3.Icon30import androidx.compose.material3.Text31import androidx.compose.runtime.Composable32import androidx.compose.runtime.getValue33import androidx.compose.runtime.mutableStateOf34import androidx.compose.runtime.remember35import androidx.compose.runtime.setValue36import androidx.compose.ui.Alignment37import androidx.compose.ui.Modifier38import androidx.compose.ui.draw.clip39import androidx.compose.ui.graphics.Color40import androidx.compose.ui.graphics.SolidColor41import androidx.compose.ui.platform.LocalContext42import androidx.compose.ui.text.TextStyle43import androidx.compose.ui.text.font.FontStyle44import androidx.compose.ui.text.input.PasswordVisualTransformation45import androidx.compose.ui.text.input.VisualTransformation46import androidx.compose.ui.unit.dp47import androidx.compose.ui.unit.sp48import androidx.hilt.navigation.compose.hiltViewModel49import androidx.lifecycle.ViewModel50import com.peachpasswords.ui.theme.LocalPeachAccent51import com.peachpasswords.ui.theme.PeachColors52import com.peachpasswords.ui.theme.PeachType53import com.peachpasswords.ui.theme.ShellBackground54import com.peachpasswords.vault.VaultEntry55import com.peachpasswords.vault.VaultRepository56import dagger.hilt.android.lifecycle.HiltViewModel57import dagger.hilt.android.qualifiers.ApplicationContext58import javax.inject.Inject5960// ─────────────────────────────────────────────────────────────────────────────61// Password strength scorer (local, dependency-free)62// ─────────────────────────────────────────────────────────────────────────────6364/**65 * Lightweight 0–4 strength score from length + character-class variety. No66 * external lib, no network — this is a UI gate, not a security guarantee.67 *68 * Thresholds (deliberately simple and explainable):69 *   - +1 if length >= 870 *   - +1 if length >= 1271 *   - +1 if at least 3 of {lowercase, uppercase, digit, symbol} are present72 *   - +1 if all 4 classes are present73 * Empty input scores 0. Result is clamped to 0..4. The C2 gate requires >= 374 * ("good"); see [strengthLabel].75 */76internal fun scorePassword(pw: String): Int {77    if (pw.isEmpty()) return 078    var classes = 079    if (pw.any { it in 'a'..'z' }) classes++80    if (pw.any { it in 'A'..'Z' }) classes++81    if (pw.any { it.isDigit() }) classes++82    if (pw.any { !it.isLetterOrDigit() }) classes++8384    var score = 085    if (pw.length >= 8) score++86    if (pw.length >= 12) score++87    if (classes >= 3) score++88    if (classes >= 4) score++89    return score.coerceIn(0, 4)90}9192internal fun strengthLabel(score: Int): String = when (score) {93    0 -> "very weak"94    1 -> "weak"95    2 -> "fair"96    3 -> "good"97    else -> "strong"98}99100// ─────────────────────────────────────────────────────────────────────────────101// ViewModel102// ─────────────────────────────────────────────────────────────────────────────103104@HiltViewModel105class ExportViewModel @Inject constructor(106    private val vault: VaultRepository,107    @ApplicationContext private val appContext: Context,108) : ViewModel() {109110    /** Active (non-deleted) entries to export. */111    fun entries(): List<VaultEntry> = vault.getEntries()112113    fun entryCount(): Int = vault.getEntries().size114115    /** Encrypted PeachScript export (backup-password protected). */116    fun buildPeachScript(backupPassword: String): String =117        PeachScriptExport.buildEncrypted(entries(), backupPassword)118119    /** Unencrypted CSV export. */120    fun buildCsv(): String = CsvExport.toCsv(entries())121122    /** Write [content] to the SAF [uri]; returns false on any IO failure. */123    fun writeToUri(uri: Uri, content: String): Boolean =124        runCatching {125            appContext.contentResolver.openOutputStream(uri)?.use {126                it.write(content.toByteArray(Charsets.UTF_8))127            } ?: return false128            true129        }.getOrDefault(false)130}131132// ─────────────────────────────────────────────────────────────────────────────133// Screen134// ─────────────────────────────────────────────────────────────────────────────135136object ExportStrings {137    const val EMPTY_VAULT = "Your vault is empty — nothing to export."138    const val WEAK_PASSWORD = "Backup password too weak (score < 3)"139    const val MISMATCH = "Passwords don't match."140    const val SAVE_FAILED = "Couldn't write that file."141    const val SAVED = "Saved."142    const val COPIED = "Copied to clipboard."143}144145private enum class ExportRoute { CHOOSE, PEACHSCRIPT, CSV }146147@Composable148fun ExportScreen(149    onBack: () -> Unit,150    vm: ExportViewModel = hiltViewModel(),151) {152    var route by remember { mutableStateOf(ExportRoute.CHOOSE) }153154    ShellBackground {155        Column(156            modifier = Modifier157                .fillMaxSize()158                .systemBarsPadding()159                .padding(horizontal = 20.dp, vertical = 16.dp),160        ) {161            Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth()) {162                Icon(163                    Icons.AutoMirrored.Rounded.ArrowBack,164                    contentDescription = "back",165                    tint = PeachColors.T0,166                    modifier = Modifier167                        .size(22.dp)168                        .clip(RoundedCornerShape(8.dp))169                        .clickable {170                            if (route != ExportRoute.CHOOSE) route = ExportRoute.CHOOSE else onBack()171                        },172                )173                Spacer(Modifier.width(14.dp))174                Text(175                    "Export",176                    color = PeachColors.T0,177                    style = TextStyle(fontFamily = PeachType.Display, fontStyle = FontStyle.Italic, fontSize = 22.sp),178                )179            }180181            Spacer(Modifier.size(18.dp))182183            Column(Modifier.fillMaxSize().verticalScroll(rememberScrollState())) {184                when (route) {185                    ExportRoute.CHOOSE -> ChooseView(186                        onPeachScript = { route = ExportRoute.PEACHSCRIPT },187                        onCsv = { route = ExportRoute.CSV },188                    )189                    ExportRoute.PEACHSCRIPT -> PeachScriptExportView(vm)190                    ExportRoute.CSV -> CsvExportView(vm)191                }192            }193        }194    }195}196197// ---- Choose view ----------------------------------------------------------198199@Composable200private fun ChooseView(onPeachScript: () -> Unit, onCsv: () -> Unit) {201    OptionCard(202        title = "PeachScript (encrypted)",203        subtitle = "A backup encrypted with a separate password. Restores into Peach.",204        onClick = onPeachScript,205    )206    Spacer(Modifier.size(12.dp))207    OptionCard(208        title = "CSV (unencrypted)",209        subtitle = "Plain text for moving into another manager. Not encrypted.",210        onClick = onCsv,211    )212}213214@Composable215private fun OptionCard(title: String, subtitle: String, onClick: () -> Unit) {216    Column(217        modifier = Modifier218            .fillMaxWidth()219            .clip(RoundedCornerShape(18.dp))220            .background(PeachColors.SurfaceElevated)221            .border(1.dp, PeachColors.T3, RoundedCornerShape(18.dp))222            .clickable(onClick = onClick)223            .padding(20.dp),224    ) {225        Text(226            title,227            color = PeachColors.T0,228            style = TextStyle(fontFamily = PeachType.Display, fontStyle = FontStyle.Italic, fontSize = 22.sp),229        )230        Spacer(Modifier.size(6.dp))231        Text(subtitle, color = PeachColors.T1, style = PeachType.body)232    }233}234235// ---- PeachScript sub-view -------------------------------------------------236237@Composable238private fun PeachScriptExportView(vm: ExportViewModel) {239    val accent = LocalPeachAccent.current240    val context = LocalContext.current241    val isEmpty = remember { vm.entryCount() == 0 }242243    var password by remember { mutableStateOf("") }244    var confirm by remember { mutableStateOf("") }245246    // Generated artefact (the encrypted JSON string), set after [Generate backup].247    var output by remember { mutableStateOf<String?>(null) }248    var status by remember { mutableStateOf<String?>(null) }249250    val score = remember(password) { scorePassword(password) }251    val matches = password.isNotEmpty() && password == confirm252    val strongEnough = score >= 3253    val canGenerate = !isEmpty && strongEnough && matches254255    val saveLauncher = rememberLauncherForActivityResult(256        ActivityResultContracts.CreateDocument("*/*"),257    ) { uri ->258        val text = output259        if (uri != null && text != null) {260            status = if (vm.writeToUri(uri, text)) ExportStrings.SAVED else ExportStrings.SAVE_FAILED261        }262    }263264    GlassCard {265        Text(266            "create a\nbackup.",267            color = PeachColors.T0,268            style = TextStyle(269                fontFamily = PeachType.Display, fontStyle = FontStyle.Italic,270                fontSize = 24.sp, lineHeight = 26.sp,271            ),272        )273        Spacer(Modifier.size(10.dp))274        Text(275            "Your vault will be encrypted with a separate backup password.",276            color = PeachColors.T1, style = PeachType.body,277        )278279        if (isEmpty) {280            Spacer(Modifier.size(16.dp))281            InlineError(ExportStrings.EMPTY_VAULT)282        }283284        Spacer(Modifier.size(18.dp))285        FieldLabel("Backup password")286        Spacer(Modifier.size(6.dp))287        PeachUnderlineField(value = password, onValueChange = { password = it; output = null; status = null }, isPassword = true)288289        Spacer(Modifier.size(16.dp))290        FieldLabel("Confirm backup password")291        Spacer(Modifier.size(6.dp))292        PeachUnderlineField(value = confirm, onValueChange = { confirm = it; output = null; status = null }, isPassword = true)293294        Spacer(Modifier.size(16.dp))295        StrengthBar(score = score, accent = accent)296        Spacer(Modifier.size(6.dp))297        Row(modifier = Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) {298            Text(299                "strength: ${strengthLabel(score)}",300                color = if (strongEnough) accent else PeachColors.T2,301                style = PeachType.labelMono,302            )303        }304305        if (password.isNotEmpty() && !strongEnough) {306            Spacer(Modifier.size(8.dp))307            Text(ExportStrings.WEAK_PASSWORD, color = PeachColors.Breach, style = PeachType.bodyMono)308        }309        if (confirm.isNotEmpty() && !matches) {310            Spacer(Modifier.size(8.dp))311            Text(ExportStrings.MISMATCH, color = PeachColors.Breach, style = PeachType.bodyMono)312        }313    }314315    Spacer(Modifier.size(18.dp))316317    if (output == null) {318        AccentButton(319            label = "Generate backup",320            enabled = canGenerate,321            onClick = {322                output = vm.buildPeachScript(password)323                status = null324            },325        )326    } else {327        val text = output!!328        GhostButton("Copy to clipboard", accent) {329            val cm = context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager330            cm.setPrimaryClip(ClipData.newPlainText("peach backup", text))331            status = ExportStrings.COPIED332        }333        Spacer(Modifier.size(8.dp))334        GhostButton("Save to file", PeachColors.T1) {335            saveLauncher.launch("peach-backup.peach")336        }337        status?.let {338            Spacer(Modifier.size(12.dp))339            Text(340                it,341                color = if (it == ExportStrings.SAVE_FAILED) PeachColors.Breach else accent,342                style = PeachType.labelMono,343            )344        }345    }346}347348@Composable349private fun StrengthBar(score: Int, accent: Color) {350    // Four segments; filled count == score. Color shifts to accent once "good".351    val fillColor = if (score >= 3) accent else PeachColors.T2352    Row(modifier = Modifier.fillMaxWidth()) {353        repeat(4) { i ->354            Box(355                modifier = Modifier356                    .weight(1f)357                    .height(4.dp)358                    .padding(end = if (i < 3) 4.dp else 0.dp)359                    .clip(RoundedCornerShape(2.dp))360                    .background(if (i < score) fillColor else PeachColors.T3),361            )362        }363    }364}365366// ---- CSV sub-view ---------------------------------------------------------367368@Composable369private fun CsvExportView(vm: ExportViewModel) {370    val accent = LocalPeachAccent.current371    val isEmpty = remember { vm.entryCount() == 0 }372373    var acknowledged by remember { mutableStateOf(false) }374    var status by remember { mutableStateOf<String?>(null) }375376    val saveLauncher = rememberLauncherForActivityResult(377        ActivityResultContracts.CreateDocument("text/csv"),378    ) { uri ->379        if (uri != null) {380            val csv = vm.buildCsv()381            status = if (vm.writeToUri(uri, csv)) ExportStrings.SAVED else ExportStrings.SAVE_FAILED382        }383    }384385    WarningCard(accent) {386        Text(387            "⚠ CSV exports are not encrypted. Store this file securely and delete it after importing.",388            color = PeachColors.T0, style = PeachType.body,389        )390        Spacer(Modifier.size(16.dp))391        CheckboxRow(392            label = "I understand this file is unencrypted",393            checked = acknowledged,394            accent = accent,395            onToggle = { acknowledged = !acknowledged },396        )397    }398399    if (isEmpty) {400        Spacer(Modifier.size(16.dp))401        InlineError(ExportStrings.EMPTY_VAULT)402    }403404    Spacer(Modifier.size(18.dp))405    AccentButton(406        label = "Export CSV",407        enabled = acknowledged && !isEmpty,408        onClick = { saveLauncher.launch("peach-export.csv") },409    )410    status?.let {411        Spacer(Modifier.size(12.dp))412        Text(413            it,414            color = if (it == ExportStrings.SAVE_FAILED) PeachColors.Breach else accent,415            style = PeachType.labelMono,416        )417    }418}419420@Composable421private fun WarningCard(accent: Color, content: @Composable () -> Unit) {422    Column(423        modifier = Modifier424            .fillMaxWidth()425            .clip(RoundedCornerShape(18.dp))426            .background(accent.copy(alpha = 0.08f))427            .border(1.dp, accent.copy(alpha = 0.35f), RoundedCornerShape(18.dp))428            .padding(20.dp),429        content = { content() },430    )431}432433@Composable434private fun CheckboxRow(label: String, checked: Boolean, accent: Color, onToggle: () -> Unit) {435    Row(436        verticalAlignment = Alignment.CenterVertically,437        modifier = Modifier.fillMaxWidth().clickable(onClick = onToggle).padding(vertical = 4.dp),438    ) {439        Box(440            modifier = Modifier441                .size(18.dp)442                .clip(RoundedCornerShape(5.dp))443                .background(if (checked) accent else Color.Transparent)444                .border(1.5.dp, if (checked) accent else PeachColors.T2, RoundedCornerShape(5.dp)),445            contentAlignment = Alignment.Center,446        ) {447            if (checked) Text("✓", color = Color(0xFF0C0A06), style = PeachType.tinyMono.copy(fontSize = 12.sp))448        }449        Spacer(Modifier.width(12.dp))450        Text(label, color = PeachColors.T0, style = PeachType.body)451    }452}453454// ---- Shared building blocks (private to this draft) -----------------------455456@Composable457private fun InlineError(message: String) {458    Box(459        modifier = Modifier460            .fillMaxWidth()461            .clip(RoundedCornerShape(12.dp))462            .background(PeachColors.BreachBg)463            .border(1.dp, PeachColors.BreachBorder, RoundedCornerShape(12.dp))464            .padding(14.dp),465    ) {466        Text(message, color = PeachColors.Breach, style = PeachType.bodyMono)467    }468}469470@Composable471private fun FieldLabel(text: String) {472    Text(text.uppercase(), color = PeachColors.T2, style = PeachType.labelMono)473}474475@Composable476private fun PeachUnderlineField(477    value: String,478    onValueChange: (String) -> Unit,479    isPassword: Boolean = false,480) {481    val accent = LocalPeachAccent.current482    Column(Modifier.fillMaxWidth()) {483        BasicTextField(484            value = value,485            onValueChange = onValueChange,486            singleLine = true,487            textStyle = PeachType.bodyMono.copy(color = PeachColors.T0),488            cursorBrush = SolidColor(accent),489            visualTransformation = if (isPassword) PasswordVisualTransformation() else VisualTransformation.None,490            modifier = Modifier.fillMaxWidth().padding(vertical = 6.dp),491        )492        Box(Modifier.fillMaxWidth().height(1.dp).background(PeachColors.T3))493    }494}495496@Composable497private fun GlassCard(content: @Composable () -> Unit) {498    Column(499        modifier = Modifier500            .fillMaxWidth()501            .clip(RoundedCornerShape(18.dp))502            .background(PeachColors.SurfaceElevated)503            .border(1.dp, PeachColors.T3, RoundedCornerShape(18.dp))504            .padding(20.dp),505        content = { content() },506    )507}508509@Composable510private fun GhostButton(label: String, color: Color, onClick: () -> Unit) {511    Box(512        modifier = Modifier513            .fillMaxWidth()514            .clip(RoundedCornerShape(12.dp))515            .border(1.dp, color.copy(alpha = 0.4f), RoundedCornerShape(12.dp))516            .clickable(onClick = onClick)517            .padding(vertical = 12.dp),518        contentAlignment = Alignment.Center,519    ) {520        Text(label, color = color, style = PeachType.bodyMono)521    }522}523524@Composable525private fun AccentButton(label: String, onClick: () -> Unit, enabled: Boolean = true) {526    val accent = LocalPeachAccent.current527    Box(528        modifier = Modifier529            .fillMaxWidth()530            .clip(RoundedCornerShape(12.dp))531            .background(if (enabled) accent else accent.copy(alpha = 0.3f))532            .clickable(enabled = enabled, onClick = onClick)533            .padding(vertical = 14.dp),534        contentAlignment = Alignment.Center,535    ) {536        Text(label, color = Color(0xFF0C0A06), style = PeachType.bodyMono)537    }538}