diff --git a/composeApp/src/commonMain/kotlin/org/incido/compose/ui/settings/SettingsSections.kt b/composeApp/src/commonMain/kotlin/org/incido/compose/ui/settings/SettingsSections.kt index de2b87d..cfd97c0 100644 --- a/composeApp/src/commonMain/kotlin/org/incido/compose/ui/settings/SettingsSections.kt +++ b/composeApp/src/commonMain/kotlin/org/incido/compose/ui/settings/SettingsSections.kt @@ -36,7 +36,7 @@ import org.incido.compose.data.settings.ThemeMode // --------------------------------------------------------------------------- @Composable -internal fun AppearanceSection( +fun AppearanceSection( themeMode: ThemeMode, dynamicColor: Boolean, onThemeMode: (ThemeMode) -> Unit, @@ -88,7 +88,7 @@ internal fun AppearanceSection( } @Composable -internal fun BackupSection( +fun BackupSection( onExport: () -> Unit, onImport: () -> Unit, /** Null hides the Carnet row — its importer lives in androidMain. */ @@ -124,7 +124,7 @@ internal fun BackupSection( } @Composable -internal fun AboutSection( +fun AboutSection( version: String, onVersionClick: () -> Unit, ) { @@ -156,12 +156,13 @@ internal fun AboutSection( } // --------------------------------------------------------------------------- -// Building blocks — M4.4d: internal so SettingsScreen (androidMain) and -// the desktop settings surface (commonMain) share one vocabulary. +// Building blocks — M4.4d: shared vocabulary for SettingsScreen +// (androidMain) and DesktopSettingsScreen. M4.5 note: public, not +// internal — desktopApp is a separate Gradle module. // --------------------------------------------------------------------------- @Composable -internal fun SettingsSection(title: String, content: @Composable () -> Unit) { +fun SettingsSection(title: String, content: @Composable () -> Unit) { Column { Text( text = title, @@ -179,7 +180,7 @@ internal fun SettingsSection(title: String, content: @Composable () -> Unit) { /** v0.3.3.0: optionally renders a disabled (greyed) switch — used for * the mutually-exclusive PIN / Biometric toggles. */ @Composable -internal fun SettingsToggle( +fun SettingsToggle( title: String, subtitle: String, checked: Boolean, @@ -215,7 +216,7 @@ internal fun SettingsToggle( } @Composable -internal fun SettingsRow( +fun SettingsRow( title: String, subtitle: String, onClick: () -> Unit, diff --git a/desktopApp/src/main/kotlin/org/incido/desktop/BackupActions.kt b/desktopApp/src/main/kotlin/org/incido/desktop/BackupActions.kt index 9a9c553..df6806a 100644 --- a/desktopApp/src/main/kotlin/org/incido/desktop/BackupActions.kt +++ b/desktopApp/src/main/kotlin/org/incido/desktop/BackupActions.kt @@ -59,14 +59,26 @@ const val DESKTOP_APP_VERSION = "0.4.2.0" * PassphraseDialog.kt is deliberately NOT ported (M4 will move the real * one into common code). */ +/** + * M4.5: the import/export machinery, extracted from the menu so the real + * settings screen (BackupSection buttons) drives the EXACT flows M2 proved — + * same pickFile, same BackupBridge calls, same passphrase/confirm dialogs. + * BackupActions is now just the menu skin over it; the state + dialogs + * belong to whoever remembers the flows (one host at a time renders them). + */ +class BackupFlows internal constructor( + val launchImport: () -> Unit, + val launchExportPlain: () -> Unit, + val launchExportEncrypted: () -> Unit, + val Dialogs: @Composable () -> Unit, +) + @Composable -fun BackupActions( +fun rememberBackupFlows( repository: NoteRepository, snackbar: SnackbarHostState, - modifier: Modifier = Modifier, -) { +): BackupFlows { val scope = rememberCoroutineScope() - var menuOpen by remember { mutableStateOf(false) } var importStage by remember { mutableStateOf(null) } var exportStage by remember { mutableStateOf(null) } // M2 task 3: dedupe is ON by default; the confirm dialog exposes it. @@ -74,24 +86,15 @@ fun BackupActions( fun say(message: String) { scope.launch { snackbar.showSnackbar(message) } } - IconButton(onClick = { menuOpen = true }, modifier = modifier) { - Icon(Icons.Default.MoreVert, contentDescription = "Backup menu") - } - DropdownMenu(expanded = menuOpen, onDismissRequest = { menuOpen = false }) { - DropdownMenuItem( - text = { Text("Import from file…") }, - onClick = { - menuOpen = false + return remember(repository) { + BackupFlows( + launchImport = { scope.launch { val file = pickFile(load = true, title = "Import backup") ?: return@launch startImport(file, ::say) { stage -> importStage = stage } } }, - ) - DropdownMenuItem( - text = { Text("Export (plain)") }, - onClick = { - menuOpen = false + launchExportPlain = { scope.launch { val file = pickFile(load = false, title = "Export backup", suggested = suggestedExportName()) ?: return@launch runCatching { @@ -102,96 +105,128 @@ fun BackupActions( .onFailure { say("Export failed: ${it.message}") } } }, + launchExportEncrypted = { + exportStage = ExportStage.AwaitingPassphrase + }, + Dialogs = { + // ---- import dialogs (verbatim M2 behaviour) -------------- + when (val stage = importStage) { + is ImportStage.NeedPassphrase -> PassphraseDialog( + blurb = "This backup is encrypted (INCDBK1). Enter its passphrase to preview it.", + onDismiss = { importStage = null }, + onConfirm = { pass -> + scope.launch { + val preview = withContext(Dispatchers.IO) { + runCatching { + BackupBridge.preview(FileInputStream(stage.file), pass.toCharArray()) + }.getOrNull() + } + if (preview == null) { + say("Wrong passphrase") // dialog stays open for a retry + } else { + importStage = ImportStage.Confirm(stage.file, preview, pass) + } + } + }, + ) + + is ImportStage.Confirm -> ConfirmImportDialog( + preview = stage.preview, + skipExisting = skipDuplicates, + onSkipChange = { skipDuplicates = it }, + onDismiss = { importStage = null }, + onConfirm = { + importStage = null + scope.launch { + runCatching { + withContext(Dispatchers.IO) { + BackupBridge.import( + repository, + FileInputStream(stage.file), + stage.passphrase?.toCharArray(), + skipExisting = skipDuplicates, + ) + } + }.onSuccess { + say( + "Imported ${it.imported} notes" + + if (it.skipped > 0) " · skipped ${it.skipped} already imported" else "", + ) + } + .onFailure { say("Import failed: ${it.message}") } + } + }, + ) + + null -> Unit + } + // ---- export dialogs (verbatim M2 behaviour) -------------- + when (exportStage) { + ExportStage.AwaitingPassphrase -> PassphraseDialog( + blurb = "Choose the passphrase for the encrypted backup (same INCDBK1 envelope as the phone).", + onDismiss = { exportStage = null }, + onConfirm = { pass -> + exportStage = null + scope.launch { + val file = pickFile(load = false, title = "Export backup", suggested = suggestedExportName()) ?: return@launch + runCatching { + withContext(Dispatchers.IO) { + BackupBridge.exportEncrypted( + repository, + FileOutputStream(file), + pass.toCharArray(), + DESKTOP_APP_VERSION, + ) + } + }.onSuccess { say("Exported $it encrypted notes to ${file.name}") } + .onFailure { say("Export failed: ${it.message}") } + } + }, + ) + + null -> Unit + } + }, + ) + } +} + +@Composable +fun BackupActions( + repository: NoteRepository, + snackbar: SnackbarHostState, + modifier: Modifier = Modifier, +) { + val flows = rememberBackupFlows(repository, snackbar) + var menuOpen by remember { mutableStateOf(false) } + + IconButton(onClick = { menuOpen = true }, modifier = modifier) { + Icon(Icons.Default.MoreVert, contentDescription = "Backup menu") + } + DropdownMenu(expanded = menuOpen, onDismissRequest = { menuOpen = false }) { + DropdownMenuItem( + text = { Text("Import from file…") }, + onClick = { + menuOpen = false + flows.launchImport() + }, + ) + DropdownMenuItem( + text = { Text("Export (plain)") }, + onClick = { + menuOpen = false + flows.launchExportPlain() + }, ) DropdownMenuItem( text = { Text("Export (encrypted)…") }, onClick = { menuOpen = false - exportStage = ExportStage.AwaitingPassphrase + flows.launchExportEncrypted() }, ) } - - // ---- import dialogs -------------------------------------------------- - - when (val stage = importStage) { - is ImportStage.NeedPassphrase -> PassphraseDialog( - blurb = "This backup is encrypted (INCDBK1). Enter its passphrase to preview it.", - onDismiss = { importStage = null }, - onConfirm = { pass -> - scope.launch { - val preview = withContext(Dispatchers.IO) { - runCatching { - BackupBridge.preview(FileInputStream(stage.file), pass.toCharArray()) - }.getOrNull() - } - if (preview == null) { - say("Wrong passphrase") // dialog stays open for a retry - } else { - importStage = ImportStage.Confirm(stage.file, preview, pass) - } - } - }, - ) - - is ImportStage.Confirm -> ConfirmImportDialog( - preview = stage.preview, - skipExisting = skipDuplicates, - onSkipChange = { skipDuplicates = it }, - onDismiss = { importStage = null }, - onConfirm = { - importStage = null - scope.launch { - runCatching { - withContext(Dispatchers.IO) { - BackupBridge.import( - repository, - FileInputStream(stage.file), - stage.passphrase?.toCharArray(), - skipExisting = skipDuplicates, - ) - } - }.onSuccess { - say( - "Imported ${it.imported} notes" + - if (it.skipped > 0) " · skipped ${it.skipped} already imported" else "", - ) - } - .onFailure { say("Import failed: ${it.message}") } - } - }, - ) - - null -> Unit - } - - // ---- export dialogs -------------------------------------------------- - - when (exportStage) { - ExportStage.AwaitingPassphrase -> PassphraseDialog( - blurb = "Choose the passphrase for the encrypted backup (same INCDBK1 envelope as the phone).", - onDismiss = { exportStage = null }, - onConfirm = { pass -> - exportStage = null - scope.launch { - val file = pickFile(load = false, title = "Export backup", suggested = suggestedExportName()) ?: return@launch - runCatching { - withContext(Dispatchers.IO) { - BackupBridge.exportEncrypted( - repository, - FileOutputStream(file), - pass.toCharArray(), - DESKTOP_APP_VERSION, - ) - } - }.onSuccess { say("Exported $it encrypted notes to ${file.name}") } - .onFailure { say("Export failed: ${it.message}") } - } - }, - ) - - null -> Unit - } + flows.Dialogs() } /** Where the import flow stands (the file is already chosen). */ diff --git a/desktopApp/src/main/kotlin/org/incido/desktop/DesktopSettingsScreen.kt b/desktopApp/src/main/kotlin/org/incido/desktop/DesktopSettingsScreen.kt new file mode 100644 index 0000000..7bbd9e7 --- /dev/null +++ b/desktopApp/src/main/kotlin/org/incido/desktop/DesktopSettingsScreen.kt @@ -0,0 +1,138 @@ +package org.incido.desktop + +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.verticalScroll +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.automirrored.filled.ArrowBack +import androidx.compose.material3.ExperimentalMaterial3Api +import androidx.compose.material3.Icon +import androidx.compose.material3.IconButton +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Scaffold +import androidx.compose.material3.SnackbarHost +import androidx.compose.material3.SnackbarHostState +import androidx.compose.material3.Text +import androidx.compose.material3.TopAppBar +import androidx.compose.runtime.Composable +import androidx.compose.runtime.collectAsState +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.rememberCoroutineScope +import androidx.compose.runtime.setValue +import androidx.compose.ui.Modifier +import androidx.compose.ui.unit.dp +import kotlinx.coroutines.launch +import org.incido.compose.ui.settings.AboutSection +import org.incido.compose.ui.settings.AppearanceSection +import org.incido.compose.ui.settings.ReleaseNotesDialog +import org.incido.compose.ui.settings.BackupSection +import org.incido.compose.ui.settings.SettingsRow +import org.incido.compose.ui.settings.SettingsSection +import org.incido.compose.ui.settings.SettingsToggle + +/** + * Phase 1 (M4.5): the desktop settings screen. + * + * Composes the SAME section composables the phone's SettingsScreen uses — + * Appearance / Backup / About moved to commonMain in M4.4d — plus two + * desktop rows. The Android-only surfaces are hidden per §6.5: + * SecuritySection (PIN / biometric / screenshot blocking — no + * BiometricPrompt, no FLAG_SECURE, desktop lock deferred), the + * dynamic-color row (AppearanceSection drops it when onDynamicColor is + * null) and the 3rd-party importer (onImportCarnet null). + * + * The encryption row mirrors SecurityActions' menu logic — the two share + * DesktopContainer's services and the Android SettingsViewModel's enable/ + * disable ordering (key → cipher → sweep → flags; disable sweeps first). + */ +@OptIn(ExperimentalMaterial3Api::class) +@Composable +fun DesktopSettingsScreen(app: DesktopContainer, onBack: () -> Unit) { + val scope = rememberCoroutineScope() + val snackbar = remember { SnackbarHostState() } + fun say(message: String) { scope.launch { snackbar.showSnackbar(message) } } + + val settings by app.settingsRepository.userSettingsFlow + .collectAsState(initial = org.incido.compose.data.settings.UserSettings()) + val backup = rememberBackupFlows(app.noteRepository, snackbar) + val keys = rememberSecurityKeyFlows(app, snackbar) + var showNotes by remember { mutableStateOf(false) } + + Scaffold( + snackbarHost = { SnackbarHost(snackbar) }, + topBar = { + TopAppBar( + title = { Text("Settings") }, + navigationIcon = { + IconButton(onClick = onBack) { + Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = "Back") + } + }, + ) + }, + ) { padding -> + Column( + modifier = Modifier + .fillMaxSize() + .padding(padding) + .verticalScroll(rememberScrollState()) + .padding(horizontal = 16.dp), + ) { + AppearanceSection( + themeMode = settings.themeMode, + dynamicColor = settings.dynamicColor, + onThemeMode = { mode -> scope.launch { app.settingsRepository.setThemeMode(mode) } }, + onDynamicColor = null, // no Material You on the JVM (§6.5) + ) + // Desktop-only: the two rows SecurityActions' menu carried. + SettingsSection(title = "Encryption") { + Column(Modifier.padding(horizontal = 16.dp, vertical = 4.dp)) { + SettingsToggle( + title = if (settings.isEncryptionActive) "Encrypt all notes" else "Decrypt all notes", + subtitle = "At-rest AES-GCM on this device — the same sweep the phone runs.", + checked = settings.isEncryptionActive, + onCheckedChange = { want -> + if (want != settings.isEncryptionActive) { + scope.launch { toggleDesktopEncryption(app, want, ::say) } + } + }, + ) + SettingsRow( + title = "Export recovery key…", + subtitle = "Save the INCKEY1 envelope (passphrase-protected).", + onClick = { keys.launchExport() }, + ) + SettingsRow( + title = "Import recovery key…", + subtitle = "Restore the key from an INCKEY1 file (phone export works).", + onClick = { keys.launchImport() }, + ) + } + } + BackupSection( + onExport = { backup.launchExportPlain() }, + onImport = { backup.launchImport() }, + onImportCarnet = null, // the Carnet importer lives in androidMain + ) + AboutSection( + version = DESKTOP_APP_VERSION, + onVersionClick = { showNotes = true }, + ) + Spacer(Modifier.padding(bottom = 24.dp)) + } + } + + // Both dialog hosts render here; only one set of flows is live + // per trigger, so they never stack unexpectedly. + backup.Dialogs() + keys.Dialogs() + if (showNotes) { + ReleaseNotesDialog(onDismiss = { showNotes = false }) + } +} diff --git a/desktopApp/src/main/kotlin/org/incido/desktop/Main.kt b/desktopApp/src/main/kotlin/org/incido/desktop/Main.kt index 455d2ab..ef98e89 100644 --- a/desktopApp/src/main/kotlin/org/incido/desktop/Main.kt +++ b/desktopApp/src/main/kotlin/org/incido/desktop/Main.kt @@ -15,6 +15,7 @@ import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.items import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Add +import androidx.compose.material.icons.filled.Settings import androidx.compose.material.icons.filled.Star import androidx.compose.material.icons.outlined.StarBorder import androidx.compose.material3.CenterAlignedTopAppBar @@ -101,6 +102,9 @@ fun main(args: Array) { val backupPassphrase = args.argAfter("--backup-passphrase") // M3 task 4: scripted at-rest encryption legs — leg A enables + proves, // leg B (a SEPARATE process) proves the relaunch auto-install + sweep. + // M4.5: scripted settings leg — opens the real settings screen mid-run + // so the shared sections (M4.4d) render on the JVM before auto-exit. + val settingsSmoke = "--settings-smoke" in args val cryptoSelfTest = "--crypto-self-test" in args val cryptoReopen = "--crypto-reopen" in args val cryptoPassphrase = args.argAfter("--crypto-passphrase") ?: "selftest-passphrase" @@ -144,6 +148,7 @@ fun main(args: Array) { windowState = windowState, exitAfterSeconds = exitAfterSeconds, selfTest = selfTest, + settingsSmoke = settingsSmoke, backupImport = backupImport, backupExport = backupExport, backupExportEnc = backupExportEnc, @@ -170,6 +175,7 @@ private fun NotesWindow( windowState: androidx.compose.ui.window.WindowState, exitAfterSeconds: Long?, selfTest: Boolean, + settingsSmoke: Boolean, backupImport: String?, backupExport: String?, backupExportEnc: String?, @@ -184,6 +190,8 @@ private fun NotesWindow( val notes by remember(repository) { repository.observeAll() } .collectAsState(initial = emptyList()) var selectedId by remember { mutableStateOf(null) } + // M4.5: the real settings screen replaces the M1b placeholder list. + var showSettings by remember { mutableStateOf(false) } val scope = rememberCoroutineScope() val snackbar = remember { SnackbarHostState() } @@ -202,6 +210,9 @@ private fun NotesWindow( MaterialTheme( colorScheme = if (darkTheme) darkColorScheme() else lightColorScheme(), ) { + if (showSettings) { + DesktopSettingsScreen(app = app, onBack = { showSettings = false }) + } else { Scaffold( snackbarHost = { SnackbarHost(snackbar) }, topBar = { @@ -230,6 +241,9 @@ private fun NotesWindow( } }, ) { Icon(Icons.Filled.Add, contentDescription = "New note") } + IconButton(onClick = { showSettings = true }) { + Icon(Icons.Filled.Settings, contentDescription = "Settings") + } }, ) }, @@ -267,6 +281,7 @@ private fun NotesWindow( Editor(repository = repository, note = selected) } } + } } LaunchedEffect(notes.size) { @@ -295,6 +310,15 @@ private fun NotesWindow( println("SELFTEST wrote note id=${saved.id}") } } + if (settingsSmoke) { + LaunchedEffect(Unit) { + delay(1500) + // Compose the real screen (crash = failure); it stays up as the + // window's content until --exit-after closes the app. + showSettings = true + println("SETTINGS shown (shared Appearance/Backup/About + desktop rows)") + } + } if (backupImport != null || backupExportEnc != null) { LaunchedEffect(Unit) { delay(800) // mirror the self-test pacing; wait past first frame diff --git a/desktopApp/src/main/kotlin/org/incido/desktop/SecurityActions.kt b/desktopApp/src/main/kotlin/org/incido/desktop/SecurityActions.kt index 6207b38..13faaee 100644 --- a/desktopApp/src/main/kotlin/org/incido/desktop/SecurityActions.kt +++ b/desktopApp/src/main/kotlin/org/incido/desktop/SecurityActions.kt @@ -51,9 +51,7 @@ fun SecurityActions( ) { val scope = rememberCoroutineScope() var menuOpen by remember { mutableStateOf(false) } - var pendingKeyExport by remember { mutableStateOf(false) } - var pendingKeyImport by remember { mutableStateOf(null) } - var confirmOverwrite by remember { mutableStateOf?>(null) } + val keys = rememberSecurityKeyFlows(app, snackbar) val settings by app.settingsRepository.userSettingsFlow .collectAsState(initial = org.incido.compose.data.settings.UserSettings()) @@ -98,46 +96,94 @@ fun SecurityActions( text = { Text(if (active) "Decrypt all notes…" else "Encrypt all notes") }, onClick = { menuOpen = false - scope.launch { - val message = withContext(Dispatchers.IO) { - if (!app.settingsRepository.snapshot().isEncryptionActive) { - // Android SettingsViewModel's enable order: - // key → cipher into holder → sweep → flags. - app.keyProvider.getOrCreateKey() - app.cipherHolder.cipher = AesGcmFieldCipher(app.keyProvider) - app.noteCryptoService.encryptAllInPlace() - app.settingsRepository.setSecurityEnabled(true) - app.settingsRepository.setEncryptionEnabled(true) - "Notes are now encrypted on this device." - } else { - // Disable order: sweep FIRST, then cipher, then flags. - app.noteCryptoService.decryptAllInPlace() - app.cipherHolder.cipher = null - app.settingsRepository.setEncryptionEnabled(false) - app.settingsRepository.setSecurityEnabled(false) - "Notes are now stored unencrypted." - } - } - app.encryptionVerifier.checkNow() - say(message) - } + scope.launch { toggleDesktopEncryption(app, want = !active, ::say) } }, ) DropdownMenuItem( text = { Text("Export recovery key…") }, onClick = { menuOpen = false - if (!app.keyProvider.hasKey()) { - say("Encryption isn't active — nothing to back up.") - } else { - pendingKeyExport = true - } + keys.launchExport() }, ) DropdownMenuItem( text = { Text("Import recovery key…") }, onClick = { menuOpen = false + keys.launchImport() + }, + ) + } + keys.Dialogs() +} + +/** + * M4.5: the enable/disable sweep, extracted from the menu so the real + * settings screen's toggle drives the identical sequence — Android + * SettingsViewModel's ordering either way (enable: key → cipher → + * sweep → flags; disable: sweep → cipher → flags). + */ +internal suspend fun toggleDesktopEncryption( + app: DesktopContainer, + want: Boolean, + say: (String) -> Unit, +) { + val message = withContext(Dispatchers.IO) { + if (!want) { + // Disable order: sweep FIRST, then cipher, then flags. + app.noteCryptoService.decryptAllInPlace() + app.cipherHolder.cipher = null + app.settingsRepository.setEncryptionEnabled(false) + app.settingsRepository.setSecurityEnabled(false) + "Notes are now stored unencrypted." + } else { + // Enable order: key → cipher into holder → sweep → flags. + app.keyProvider.getOrCreateKey() + app.cipherHolder.cipher = AesGcmFieldCipher(app.keyProvider) + app.noteCryptoService.encryptAllInPlace() + app.settingsRepository.setSecurityEnabled(true) + app.settingsRepository.setEncryptionEnabled(true) + "Notes are now encrypted on this device." + } + } + app.encryptionVerifier.checkNow() + say(message) +} + +// SEC_PART_B +/** + * M4.5: recovery-key export/import, extracted from the menu so the + * settings screen's rows drive the exact same flows (same passphrases, + * same hasKey gate, same overwrite warning gate, same import leg). + */ +internal class SecurityKeyFlows constructor( + val launchExport: () -> Unit, + val launchImport: () -> Unit, + val Dialogs: @Composable () -> Unit, +) + +@Composable +internal fun rememberSecurityKeyFlows( + app: DesktopContainer, + snackbar: SnackbarHostState, +): SecurityKeyFlows { + val scope = rememberCoroutineScope() + var pendingKeyExport by remember { mutableStateOf(false) } + var pendingKeyImport by remember { mutableStateOf(null) } + var confirmOverwrite by remember { mutableStateOf?>(null) } + + fun say(message: String) { scope.launch { snackbar.showSnackbar(message) } } + + return remember(app) { + SecurityKeyFlows( + launchExport = { + if (!app.keyProvider.hasKey()) { + say("Encryption isn't active — nothing to back up.") + } else { + pendingKeyExport = true + } + }, + launchImport = { scope.launch { val file = pickFile( load = true, @@ -147,90 +193,91 @@ fun SecurityActions( pendingKeyImport = file } }, - ) - } + Dialogs = { + // ---- passphrase dialogs (shared with the backup menu) ---- - // ---- passphrase dialogs (shared with the backup menu) ---- - - if (pendingKeyExport) { - PassphraseDialog( - blurb = "This passphrase protects the recovery file. Notes can only " + - "be opened on another device with this file AND the passphrase.", - onDismiss = { pendingKeyExport = false }, - onConfirm = { passphrase -> - pendingKeyExport = false - scope.launch { - val outcome = runCatching { - withContext(Dispatchers.IO) { - val target = pickFile( - load = false, - title = "Export recovery key", - suggested = "incido-recovery-key.incidokey", - extensions = listOf("incidokey"), - ) ?: return@withContext null - target.writeBytes(app.keyProvider.exportRecoveryKey(passphrase.toCharArray())) - target - } - } - // The codec zeroes the CharArray derived from the - // passphrase inside exportRecoveryKey (fill('0')). - say( - outcome.fold( - onSuccess = { if (it == null) "Export cancelled." else "Recovery key exported to ${it.name}." }, - onFailure = { "Export failed: ${it.message}" }, - ), + if (pendingKeyExport) { + PassphraseDialog( + blurb = "This passphrase protects the recovery file. Notes can only " + + "be opened on another device with this file AND the passphrase.", + onDismiss = { pendingKeyExport = false }, + onConfirm = { passphrase -> + pendingKeyExport = false + scope.launch { + val outcome = runCatching { + withContext(Dispatchers.IO) { + val target = pickFile( + load = false, + title = "Export recovery key", + suggested = "incido-recovery-key.incidokey", + extensions = listOf("incidokey"), + ) ?: return@withContext null + target.writeBytes(app.keyProvider.exportRecoveryKey(passphrase.toCharArray())) + target + } + } + // The codec zeroes the CharArray derived from the + // passphrase inside exportRecoveryKey (fill('0')). + say( + outcome.fold( + onSuccess = { if (it == null) "Export cancelled." else "Recovery key exported to ${it.name}." }, + onFailure = { "Export failed: ${it.message}" }, + ), + ) + } + }, ) } - }, - ) - } - pendingKeyImport?.let { file -> - PassphraseDialog( - blurb = "Unlock the recovery key file. Importing it replaces this " + - "library's encryption key.", - onDismiss = { pendingKeyImport = null }, - onConfirm = { passphrase -> - pendingKeyImport = null - scope.launch { - val bytes = withContext(Dispatchers.IO) { file.readBytes() } - if (!org.incido.compose.data.backup.EncryptedKeyCodec.isEncryptedKey(bytes)) { - say("Not an Incido recovery key file.") - return@launch - } - if (app.noteCryptoService.hasEncryptedRows()) { - // Android warns before overwriting a live key — same gate. - confirmOverwrite = file to passphrase - } else { - importKey(app, bytes, passphrase, ::say) - } + pendingKeyImport?.let { file -> + PassphraseDialog( + blurb = "Unlock the recovery key file. Importing it replaces this " + + "library's encryption key.", + onDismiss = { pendingKeyImport = null }, + onConfirm = { passphrase -> + pendingKeyImport = null + scope.launch { + val bytes = withContext(Dispatchers.IO) { file.readBytes() } + if (!org.incido.compose.data.backup.EncryptedKeyCodec.isEncryptedKey(bytes)) { + say("Not an Incido recovery key file.") + return@launch + } + if (app.noteCryptoService.hasEncryptedRows()) { + // Android warns before overwriting a live key — same gate. + confirmOverwrite = file to passphrase + } else { + importKey(app, bytes, passphrase, ::say) + } + } + }, + ) } - }, - ) - } - confirmOverwrite?.let { (file, passphrase) -> - AlertDialog( - onDismissRequest = { confirmOverwrite = null }, - title = { Text("Replace encryption key?") }, - text = { - Text( - "This library already has encrypted notes. Installing a " + - "different key makes those notes unreadable unless they " + - "were encrypted with the SAME key (e.g. restoring this " + - "device's own recovery file).", - ) - }, - confirmButton = { - TextButton( - onClick = { - confirmOverwrite = null - scope.launch { importKey(app, file.readBytes(), passphrase, ::say) } - }, - ) { Text("Replace") } - }, - dismissButton = { - TextButton(onClick = { confirmOverwrite = null }) { Text("Cancel") } + confirmOverwrite?.let { (file, passphrase) -> + AlertDialog( + onDismissRequest = { confirmOverwrite = null }, + title = { Text("Replace encryption key?") }, + text = { + Text( + "This library already has encrypted notes. Installing a " + + "different key makes those notes unreadable unless they " + + "were encrypted with the SAME key (e.g. restoring this " + + "device's own recovery file).", + ) + }, + confirmButton = { + TextButton( + onClick = { + confirmOverwrite = null + scope.launch { importKey(app, file.readBytes(), passphrase, ::say) } + }, + ) { Text("Replace") } + }, + dismissButton = { + TextButton(onClick = { confirmOverwrite = null }) { Text("Cancel") } + }, + ) + } }, ) }