feat(phase-1/m3.3): desktop at-rest encryption — key file, container wiring, security menu

Milestone M3 task 3 (DESKTOP_PHASE_PLAN §5). Three pieces:

1. DesktopKeyProvider — the JVM FieldKeyProvider. The plan's keyring
   condition is FAILed honestly: no keyring library is in the catalog
   and the candidates are unverified on this stack, so the sanctioned
   fallback applies: the 32-byte field key lives in `field.key` inside
   the library dir, written via temp+atomic-move with 0600 POSIX perms
   (File.setReadable/setWritable fallback for non-POSIX fs). It speaks
   the phone's recovery format natively through EncryptedKeyCodec
   (importRecoveryKey / exportRecoveryKey — INCKEY1, PBKDF2-200k,
   AES-GCM, wrong passphrase throws before anything is written).
   Key retention on disable: the sweep decrypts first, then flags
   clear, but the key file stays (Android's deleteKey-on-disable is
   Keystore-scoped; keeping it lets users re-enable and re-export).
   Stated, not silent.

2. DesktopContainer now mirrors AppContainer fully: settings -> cipher
   auto-install from snapshot (isEncryptionActive AND key on disk)
   BEFORE the repository -> NoteCryptoService -> EncryptionVerifier ->
   checkNow at startup. shutdown() cancels appScope.

3. UI: SecurityActions menu (theme cycle + encrypt/decrypt toggle +
   recovery-key import/export, incl. Android's overwrite-warning gate)
   reusing the backup menu's pickFile/PassphraseDialog (now internal,
   parameterized title/extensions). theme_mode drives Material3 via
   colorScheme (M3 MaterialTheme has no darkTheme param). dynamic_color
   / use_biometric / block_screenshots are NOT shown — no JVM
   equivalent, hide-don't-fake. Window geometry persists to its own
   incido_window.preferences_pb (desktop-only state; position left to
   KWin).

Verification (scripted legs in Main.kt, --crypto-self-test / --crypto-reopen):
  leg A: probe note -> key+cipher+sweep -> verifier trial-decrypt
    PASS (verified=1 failed=0) -> transparent repo read -> WRONG KEY
    REJECTED via AEAD tag -> INCKEY1 envelope 84 bytes, wrong-pw
    rejected, key byte-match -> LEG-A PASS.
  leg B (separate process = real relaunch): settings survived, cipher
    auto-installed, sweep all-ok, decrypt sweep reverses it -> PASS.
  :desktopApp:run --self-test regression green; assembleDebug green.
  ls confirms field.key is -rw------- (0600).
One environmental note: a leg-A run earlier in the session wedged in
XWayland window teardown (never reached exitApplication); the rerun
auto-exited cleanly — same one-off as the M3.2 startup wedge.
This commit is contained in:
Incido Developer committed 2026-10-06 07:26:17 +13:00
1 parent 40e2b9ff52
commit 000f4095cc
6 files changed
+709 -30

No files matched your search

@@ -1,6 +1,7 @@
package org.incido.desktop
import androidx.compose.foundation.clickable
import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
@@ -28,6 +29,8 @@ import androidx.compose.material3.SnackbarHost
import androidx.compose.material3.SnackbarHostState
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.darkColorScheme
import androidx.compose.material3.lightColorScheme
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
@@ -43,11 +46,15 @@ import androidx.compose.ui.unit.dp
import androidx.compose.ui.window.Window
import androidx.compose.ui.window.application
import androidx.compose.ui.window.rememberWindowState
import androidx.datastore.preferences.core.edit
import androidx.datastore.preferences.core.intPreferencesKey
import java.io.File
import java.io.ByteArrayInputStream
import java.io.FileOutputStream
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import org.incido.compose.data.backup.BackupBridge
import org.incido.compose.data.backup.EncryptedBackupCodec
import org.incido.domain.model.Note
@@ -88,6 +95,11 @@ fun main(args: Array<String>) {
// M2 task 4: encrypted-envelope legs (the RequirePassphrase dialog's calls).
val backupExportEnc = args.argAfter("--backup-export-enc")
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.
val cryptoSelfTest = "--crypto-self-test" in args
val cryptoReopen = "--crypto-reopen" in args
val cryptoPassphrase = args.argAfter("--crypto-passphrase") ?: "selftest-passphrase"
println("=== Incido (desktop) — Phase 1 M1b ===")
println("JVM : ${System.getProperty("java.vendor")} ${System.getProperty("java.version")}")
@@ -95,20 +107,40 @@ fun main(args: Array<String>) {
val app = DesktopContainer(dataDir)
// M3: window geometry is desktop-only state, kept in its OWN store file
// (incido_window.preferences_pb) — settings stay the phone-shared schema.
// Position is deliberately NOT stored: KWin owns placement on this stack.
val windowStore = preferencesStore(dataDir, "incido_window")
val windowPrefs = runBlocking { windowStore.data.first() }
val savedWidth = windowPrefs[intPreferencesKey("window_width")]
?.coerceIn(640, 8_000) ?: 1100
val savedHeight = windowPrefs[intPreferencesKey("window_height")]
?.coerceIn(480, 8_000) ?: 760
application {
val windowState = rememberWindowState(
width = savedWidth.dp,
height = savedHeight.dp,
)
Window(
onCloseRequest = ::exitApplication,
state = rememberWindowState(width = 1100.dp, height = 760.dp),
state = windowState,
title = "Incido",
) {
NotesWindow(
app = app,
repository = app.repository,
windowStore = windowStore,
windowState = windowState,
exitAfterSeconds = exitAfterSeconds,
selfTest = selfTest,
backupImport = backupImport,
backupExport = backupExport,
backupExportEnc = backupExportEnc,
backupPassphrase = backupPassphrase,
cryptoSelfTest = cryptoSelfTest,
cryptoReopen = cryptoReopen,
cryptoPassphrase = cryptoPassphrase,
onExit = ::exitApplication,
)
}
@@ -120,13 +152,19 @@ fun main(args: Array<String>) {
@OptIn(ExperimentalMaterial3Api::class)
@Composable
private fun NotesWindow(
app: DesktopContainer,
repository: NoteRepository,
windowStore: androidx.datastore.core.DataStore<androidx.datastore.preferences.core.Preferences>,
windowState: androidx.compose.ui.window.WindowState,
exitAfterSeconds: Long?,
selfTest: Boolean,
backupImport: String?,
backupExport: String?,
backupExportEnc: String?,
backupPassphrase: String?,
cryptoSelfTest: Boolean,
cryptoReopen: Boolean,
cryptoPassphrase: String,
onExit: () -> Unit,
) {
val notes by remember(repository) { repository.observeAll() }
@@ -135,16 +173,29 @@ private fun NotesWindow(
val scope = rememberCoroutineScope()
val snackbar = remember { SnackbarHostState() }
// M3: theme_mode is a real shared setting here — resolveDark picks the
// scheme. (Material3's MaterialTheme has no darkTheme parameter — the
// scheme IS the switch, same shape as the app's IncidoTheme.)
// dynamic_color stays hidden (no Material You on the JVM), same rule
// as biometrics / screenshot blocking.
val userSettings by app.settingsRepository.userSettingsFlow
.collectAsState(initial = org.incido.compose.data.settings.UserSettings())
// Keep a valid selection as the library changes.
val selected = notes.firstOrNull { it.id == selectedId } ?: notes.firstOrNull()
MaterialTheme {
val darkTheme = userSettings.themeMode.resolveDark(isSystemInDarkTheme())
MaterialTheme(
colorScheme = if (darkTheme) darkColorScheme() else lightColorScheme(),
) {
Scaffold(
snackbarHost = { SnackbarHost(snackbar) },
topBar = {
CenterAlignedTopAppBar(
title = { Text("Incido") },
actions = {
// M3: theme + encryption live here (Palette menu).
SecurityActions(app = app, snackbar = snackbar)
// M2: the phone bridge lives here (Import…/Export).
BackupActions(repository = repository, snackbar = snackbar)
IconButton(
@@ -289,6 +340,32 @@ private fun NotesWindow(
}
}
}
// M3: debounced window-size persistence — desktop-only state in its own
// store file (incido_window.preferences_pb). Position is not saved; the
// window manager owns placement here (KDE), only geometry is ours.
LaunchedEffect(windowState.size) {
val width = windowState.size.width.value.toInt()
val height = windowState.size.height.value.toInt()
delay(750)
windowStore.edit { prefs ->
prefs[intPreferencesKey("window_width")] = width
prefs[intPreferencesKey("window_height")] = height
}
}
if (cryptoSelfTest || cryptoReopen) {
LaunchedEffect(Unit) {
delay(800) // past the first frame; assertions ride the flows, not frame one
val ok = if (cryptoSelfTest) {
runCryptoSelfTest(app, cryptoPassphrase)
} else {
runCryptoReopenCheck(app)
}
println(
"CRYPTO ${if (cryptoSelfTest) "leg-A" else "leg-B"} " +
if (ok) "ALL-OK" else "PROBLEMS (see FAIL lines above)",
)
}
}
if (exitAfterSeconds != null) {
LaunchedEffect(Unit) {
delay(exitAfterSeconds * 1000)