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
+708 -29

No files matched your search

@@ -83,7 +83,7 @@ fun BackupActions(
onClick = { onClick = {
menuOpen = false menuOpen = false
scope.launch { scope.launch {
val file = pickFile(load = true) ?: return@launch val file = pickFile(load = true, title = "Import backup") ?: return@launch
startImport(file, ::say) { stage -> importStage = stage } startImport(file, ::say) { stage -> importStage = stage }
} }
}, },
@@ -93,7 +93,7 @@ fun BackupActions(
onClick = { onClick = {
menuOpen = false menuOpen = false
scope.launch { scope.launch {
val file = pickFile(load = false, suggested = suggestedExportName()) ?: return@launch val file = pickFile(load = false, title = "Export backup", suggested = suggestedExportName()) ?: return@launch
runCatching { runCatching {
withContext(Dispatchers.IO) { withContext(Dispatchers.IO) {
BackupBridge.exportPlain(repository, FileOutputStream(file), DESKTOP_APP_VERSION) BackupBridge.exportPlain(repository, FileOutputStream(file), DESKTOP_APP_VERSION)
@@ -174,7 +174,7 @@ fun BackupActions(
onConfirm = { pass -> onConfirm = { pass ->
exportStage = null exportStage = null
scope.launch { scope.launch {
val file = pickFile(load = false, suggested = suggestedExportName()) ?: return@launch val file = pickFile(load = false, title = "Export backup", suggested = suggestedExportName()) ?: return@launch
runCatching { runCatching {
withContext(Dispatchers.IO) { withContext(Dispatchers.IO) {
BackupBridge.exportEncrypted( BackupBridge.exportEncrypted(
@@ -269,7 +269,7 @@ private fun ConfirmImportDialog(
} }
@Composable @Composable
private fun PassphraseDialog( internal fun PassphraseDialog(
blurb: String, blurb: String,
onDismiss: () -> Unit, onDismiss: () -> Unit,
onConfirm: (String) -> Unit, onConfirm: (String) -> Unit,
@@ -304,18 +304,27 @@ private fun suggestedExportName(): String =
/** /**
* Blocking AWT/GTK file picker. Safe off the EDT (AWT marshals internally); * Blocking AWT/GTK file picker. Safe off the EDT (AWT marshals internally);
* callers run it on the IO dispatcher so the composition stays responsive. * callers run it on the IO dispatcher so the composition stays responsive.
*
* M3: shared with SecurityActions (recovery-key import/export) — the
* dialog title and the accepted extensions are now the caller's choice;
* the backup callers keep their previous behaviour exactly.
*/ */
private suspend fun pickFile(load: Boolean, suggested: String? = null): File? = internal suspend fun pickFile(
load: Boolean,
title: String,
suggested: String? = null,
extensions: List<String> = listOf("json", "incido", "incido.enc"),
): File? =
withContext(Dispatchers.IO) { withContext(Dispatchers.IO) {
val dialog = FileDialog( val dialog = FileDialog(
Frame.getFrames().firstOrNull(), Frame.getFrames().firstOrNull(),
if (load) "Import backup" else "Export backup", title,
if (load) FileDialog.LOAD else FileDialog.SAVE, if (load) FileDialog.LOAD else FileDialog.SAVE,
).apply { ).apply {
directory = System.getProperty("user.home") + File.separator directory = System.getProperty("user.home") + File.separator
suggested?.let { file = it } suggested?.let { file = it }
filenameFilter = FilenameFilter { dir, name -> filenameFilter = FilenameFilter { dir, name ->
dir.isDirectory || name.endsWith(".json") || name.endsWith(".incido") || name.endsWith(".incido.enc") dir.isDirectory || extensions.any { name.endsWith(".$it") }
} }
isVisible = true isVisible = true
} }
@@ -0,0 +1,156 @@
package org.incido.desktop
import java.io.File
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.withContext
import org.incido.compose.data.backup.EncryptedKeyCodec
import org.incido.data.crypto.AesGcmFieldCipher
import org.incido.data.crypto.FieldKeyProvider
import org.incido.domain.model.Note
/**
* Phase 1 (M3 task 4): scripted verification of desktop at-rest
* encryption — the headless equivalent of flipping the Encrypt switch in
* Settings and restarting the app. Drives the SAME calls the security
* menu (SecurityActions.kt) and Android's SettingsViewModel make:
* key → cipher into the holder → [org.incido.data.crypto.NoteCryptoService]
* sweep → flags → verifier.
*
* The reopen leg is deliberately a SECOND process ([runCryptoReopenCheck]):
* relaunching is the real-world path the exit criteria describe, closing
* the store under the live composition would fight the UI's flow, and a
* fresh JVM is exactly what a user returning to the app gets.
*
* Flags in Main.kt: `--crypto-self-test` (leg A), `--crypto-reopen`
* (leg B). Run A leaves the library encrypted; run B verifies and
* decrypts back, so the pair is idempotent against a fixed data dir.
*/
/** Leg A — enable + prove (run 1). */
suspend fun runCryptoSelfTest(app: DesktopContainer, passphrase: String): Boolean =
withContext(Dispatchers.IO) {
println("=== M3 crypto self-test (leg A: enable) ===")
var ok = true
fun check(name: String, pass: Boolean, detail: String = "") {
if (!pass) ok = false
println("%-36s %s %s".format(name, if (pass) "PASS" else "FAIL", detail))
}
// 1. A probe note whose exact content we can look for again later.
val marker = "M3-PROBE-${System.currentTimeMillis()} secret-at-rest"
val now = System.currentTimeMillis()
val probe = app.repository.saveNoteWithHashtags(
Note(id = 0L, content = marker, createdAt = now, updatedAt = now),
hashtagsToAdd = emptySet(),
hashtagsToRemove = emptySet(),
)
check("probe note written", probe.id != 0L, "id=${probe.id}")
// 2. Enable, in Android SettingsViewModel's order: key first
// (idempotent), cipher into the holder, sweep, flags last.
app.keyProvider.getOrCreateKey()
app.cipherHolder.cipher = AesGcmFieldCipher(app.keyProvider)
app.noteCryptoService.encryptAllInPlace()
app.settingsRepository.setSecurityEnabled(true)
app.settingsRepository.setEncryptionEnabled(true)
check("encrypt sweep flipped rows", app.noteCryptoService.hasEncryptedRows())
// 3. The exit criterion: EncryptionVerifier's trial-decrypt sweep.
val v1 = app.noteCryptoService.verifyAll()
check(
"verifier trial-decrypt sweep",
probe.id in v1.verifiedNoteIds && v1.failedNoteIds.isEmpty(),
"verified=${v1.verifiedNoteIds.size} failed=${v1.failedNoteIds.size}",
)
// 4. Repository reads decrypt transparently.
val readBack = app.repository.observeAll().first()
check(
"repository decrypts transparently",
readBack.any { it.content == marker },
"notes=${readBack.size}",
)
// 5. Negative leg: a wrong key must fail the GCM tag on every row
// (this is the integrity signal the badge is built on).
app.cipherHolder.cipher =
AesGcmFieldCipher(FieldKeyProvider { ByteArray(32) { (it + 1).toByte() } })
val vBad = app.noteCryptoService.verifyAll()
check(
"wrong key rejected (AEAD tag)",
probe.id in vBad.failedNoteIds && vBad.verifiedNoteIds.isEmpty(),
"failed=${vBad.failedNoteIds.size}",
)
app.cipherHolder.cipher = AesGcmFieldCipher(app.keyProvider)
// 6. Recovery envelope — the phone-interop format (INCKEY1,
// PBKDF2-200k, AES-GCM). Export, reject wrong passphrase, import
// into a scratch provider, byte-compare the keys.
val envelope = app.keyProvider.exportRecoveryKey(passphrase.toCharArray())
check(
"recovery envelope (INCKEY1)",
envelope.size == 84 && EncryptedKeyCodec.isEncryptedKey(envelope),
"len=${envelope.size}",
)
val scratchDir = File(app.dataDir, "scratch-keys")
val scratch = DesktopKeyProvider(scratchDir)
val rejected = runCatching {
scratch.importRecoveryKey(envelope, "wrong-passphrase".toCharArray())
}.isFailure
check("wrong passphrase rejected", rejected)
val libraryKey = app.keyProvider.readKey()
scratch.importRecoveryKey(envelope, passphrase.toCharArray())
check(
"envelope carries library key",
libraryKey != null && scratch.readKey()?.contentEquals(libraryKey) == true,
)
scratchDir.deleteRecursively()
println(if (ok) "CRYPTO LEG-A PASS (library left encrypted for leg B)" else "CRYPTO LEG-A FAIL")
ok
}
/**
* Leg B — relaunch check (run 2): the container must auto-install the
* cipher purely from persisted settings + the key file (exactly the
* AppContainer rule), every encrypted row must pass the trial-decrypt
* sweep, and the disable path must reverse cleanly so the A→B pair is
* idempotent against a fixed data dir.
*/
suspend fun runCryptoReopenCheck(app: DesktopContainer): Boolean =
withContext(Dispatchers.IO) {
println("=== M3 crypto self-test (leg B: reopen) ===")
var ok = true
fun check(name: String, pass: Boolean, detail: String = "") {
if (!pass) ok = false
println("%-36s %s %s".format(name, if (pass) "PASS" else "FAIL", detail))
}
val s = app.settingsRepository.snapshot()
check("settings survived restart", s.isEncryptionActive)
check("cipher auto-installed", app.cipherHolder.cipher is AesGcmFieldCipher)
val v = app.noteCryptoService.verifyAll()
check(
"reopen verifier sweep all-ok",
v.allOk && v.verifiedNoteIds.isNotEmpty(),
"verified=${v.verifiedNoteIds.size} failed=${v.failedNoteIds.size}",
)
// Undo cleanly (the disable path the UI takes): decrypt sweep
// FIRST, then drop cipher + flags.
app.noteCryptoService.decryptAllInPlace()
app.cipherHolder.cipher = null
app.settingsRepository.setEncryptionEnabled(false)
app.settingsRepository.setSecurityEnabled(false)
val after = app.noteCryptoService.verifyAll()
check(
"decrypt sweep reverses it",
!app.noteCryptoService.hasEncryptedRows() && after.failedNoteIds.isEmpty(),
)
println(if (ok) "CRYPTO LEG-B PASS" else "CRYPTO LEG-B FAIL")
ok
}
@@ -6,10 +6,17 @@ import androidx.datastore.preferences.core.PreferenceDataStoreFactory
import androidx.datastore.preferences.core.Preferences import androidx.datastore.preferences.core.Preferences
import androidx.datastore.preferences.core.emptyPreferences import androidx.datastore.preferences.core.emptyPreferences
import java.io.File import java.io.File
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.cancel
import org.incido.compose.data.settings.SettingsRepository import org.incido.compose.data.settings.SettingsRepository
import org.incido.data.ImageOrientationNormalizer import org.incido.data.ImageOrientationNormalizer
import org.incido.data.ObjectBoxStore import org.incido.data.ObjectBoxStore
import org.incido.data.crypto.AesGcmFieldCipher
import org.incido.data.crypto.CipherHolder import org.incido.data.crypto.CipherHolder
import org.incido.data.crypto.EncryptionVerifier
import org.incido.data.crypto.NoteCryptoService
import org.incido.data.repository.NoteRepositoryImpl import org.incido.data.repository.NoteRepositoryImpl
import org.incido.domain.repository.NoteRepository import org.incido.domain.repository.NoteRepository
@@ -17,42 +24,76 @@ import org.incido.domain.repository.NoteRepository
* Hand-rolled DI container for the desktop build — the JVM counterpart of * Hand-rolled DI container for the desktop build — the JVM counterpart of
* the Android app's `AppContainer` (Development Plan §6, Phase 1, M1b). * the Android app's `AppContainer` (Development Plan §6, Phase 1, M1b).
* *
* Deliberately mirrors Android's construction order: settings first (M3), * Construction order mirrors Android exactly, for the reason the plan
* then open the store, then build the repository over a shared * names: settings first, then the cipher install from the settings
* [CipherHolder] so installing or removing at-rest encryption later is a * snapshot BEFORE the repository exists (so the very first snapshot
* one-line change here instead of a rebuild of the graph. * already reads encrypted rows correctly), then the repository over the
* shared [CipherHolder], then the crypto service + startup verifier.
* *
* Two Android behaviours are intentionally absent, both planned work: * Key-source difference (M3 task 3): Android's key lives in a
* - at-rest encryption (milestone M3 — needs a JVM KeyProvider; the * Keystore-wrapped DataStore blob; desktop's counterpart is
* recovery-key envelope is already proven portable), and * [DesktopKeyProvider]'s `0600` key file — see there for why the keyring
* - EXIF rotation (milestone M4 — needs a JVM image decoder, so inbound * fallback was chosen. PIN / biometric / screenshot gating is
* images are stored exactly as received for now). * intentionally NOT ported (BiometricPrompt and FLAG_SECURE are
* Android-only; the plan says hide, don't fake — the desktop security
* story is theme + encryption + recovery key only).
*
* [dataDir] owns every desktop-side file this container wires: the
* ObjectBox library, `incido_settings.preferences_pb`, the `0600` field
* key, and (separately) the window-state store.
*
* EXIF rotation remains the one absent Android behaviour (M4 — needs a
* JVM image decoder).
*/ */
class DesktopContainer(dataDir: File) { class DesktopContainer(val dataDir: File) {
/** Process-wide scope for the verifier, mirroring AppContainer.appScope. */
val appScope = CoroutineScope(SupervisorJob() + Dispatchers.Default)
/**
* Phase 1 (M3 task 1): the same settings the phone stores, in the same
* `.preferences_pb` format, living inside this library's data dir.
* SPIKE FINDING applied: the multiplatform DataStore has no
* `preferencesDataStore(name = …)` extension — the store is created
* from a file with PreferenceDataStoreFactory + a corruption handler
* that replaces an unreadable file with empty preferences (same
* semantics as Android's default).
*/
val settingsRepository: SettingsRepository = val settingsRepository: SettingsRepository =
SettingsRepository(preferencesStore(dataDir, "incido_settings")) SettingsRepository(preferencesStore(dataDir, "incido_settings"))
val keyProvider = DesktopKeyProvider(dataDir)
/** Shared cipher slot consulted by the repository on every I/O. */
val cipherHolder = CipherHolder() val cipherHolder = CipherHolder()
val boxStore = ObjectBoxStore.init(dataDir) val boxStore = ObjectBoxStore.init(dataDir)
/**
* Install the field cipher BEFORE the repository is constructed
* (AppContainer's rule). `snapshot()`'s runBlocking is startup-safe —
* the desktop equivalent of Application.onCreate is main() before the
* window opens. The key file is only trusted when BOTH signals agree:
* `isEncryptionActive` (user intent) AND a key actually on disk.
*/
init {
val s = settingsRepository.snapshot()
if (s.isEncryptionActive && keyProvider.hasKey()) {
cipherHolder.cipher = AesGcmFieldCipher(keyProvider)
}
}
val repository: NoteRepository = NoteRepositoryImpl( val repository: NoteRepository = NoteRepositoryImpl(
boxStore = boxStore, boxStore = boxStore,
cipherHolder = cipherHolder, cipherHolder = cipherHolder,
orientationNormalizer = ImageOrientationNormalizer.NoOp, orientationNormalizer = ImageOrientationNormalizer.NoOp,
) )
fun shutdown() = ObjectBoxStore.reset() /** Migration sweep + startup integrity checker — the shared service. */
val noteCryptoService = NoteCryptoService(boxStore, cipherHolder)
/** Runs on every launch — feeds the "Encrypted" badge state. */
val encryptionVerifier = EncryptionVerifier(noteCryptoService, appScope)
init {
encryptionVerifier.checkNow()
}
fun shutdown() {
appScope.cancel()
ObjectBoxStore.reset()
}
} }
/** /**
@@ -0,0 +1,124 @@
package org.incido.desktop
import java.io.File
import java.nio.file.Files
import java.nio.file.StandardCopyOption
import java.nio.file.attribute.PosixFilePermissions
import java.security.SecureRandom
import org.incido.compose.data.backup.EncryptedKeyCodec
import org.incido.data.crypto.FieldKeyProvider
/**
* Phase 1 (M3 task 3): the desktop field-key owner — JVM counterpart of
* Android's `ObjectBoxKeyProvider` (Keystore + DataStore).
*
* Storage choice, stated plainly per the M3 rules of engagement: the key
* lives in a plain `field.key` file (32 raw bytes) inside the library
* directory, created with `0600` permissions. **No OS-keyring library is
* in the version catalog and the candidates are unverified** on this
* stack (KDE/Wayland, secret-service availability unproven for a jpackaged
* app), so the plan's sanctioned fallback applies: file + `0600`. The
* Android Keystore cannot be mirrored here anyway — its master key is
* non-exportable by design; cross-device key portability goes through the
* [EncryptedKeyCodec] recovery envelope, which this class speaks natively
* (same magic, KDF and AEAD the phone writes).
*
* Implements [FieldKeyProvider] directly, so the cipher takes this object
* as-is: `AesGcmFieldCipher(keyProvider)`.
*/
class DesktopKeyProvider(private val dataDir: File) : FieldKeyProvider {
private val keyFile = File(dataDir, KEY_FILE_NAME)
/** Read the persisted key, generating + persisting one on first call.
* Idempotent; blocking (one tiny file read). */
override fun getOrCreateKey(): ByteArray {
readKey()?.let { return it }
val fresh = ByteArray(KEY_BYTES).also(SecureRandom()::nextBytes)
writeKey(fresh)
return fresh
}
/** True when a well-formed key file exists. */
fun hasKey(): Boolean = readKey() != null
/** The persisted key, or null. Rejects wrong-size files (a torn write
* or a stray file must never be installed as a cipher key). */
fun readKey(): ByteArray? {
if (!keyFile.isFile) return null
val bytes = keyFile.readBytes()
require(bytes.size == KEY_BYTES) {
"Field key file is the wrong size (${bytes.size} != $KEY_BYTES)"
}
return bytes
}
/**
* Unlock a phone-exported (or desktop-exported) recovery envelope and
* install its 32 bytes as this library's field key. Throws on wrong
* passphrase (AEADBadTagException from the codec) or bad magic —
* nothing is written until the envelope decrypts cleanly.
*
* Mirrors Android's `ObjectBoxKeyProvider.importRecoveryKey`: overwriting
* an existing key makes previously-encrypted rows unreadable, which the
* caller must warn about first.
*/
fun importRecoveryKey(envelope: ByteArray, passphrase: CharArray) {
// decrypt() zeroizes the passphrase on both paths; it throws before
// any write when the envelope or passphrase is wrong.
val raw = EncryptedKeyCodec.decrypt(envelope, passphrase)
writeKey(raw)
}
/** Wrap the current key in a recovery envelope for export. */
fun exportRecoveryKey(passphrase: CharArray): ByteArray =
EncryptedKeyCodec.encrypt(getOrCreateKey(), passphrase)
/** Remove the key file. Only safe after every row has been decrypted
* back to plaintext (the settings flow guarantees that order). */
fun deleteKey() {
keyFile.delete()
}
// ---- persistence ----
/** Atomic write (temp + move) with owner-only `0600` permissions set
* at creation, so the plaintext bytes are never group/world readable.
* Falls back to File.setReadable/setWritable owner-scoping on
* non-POSIX filesystems. */
private fun writeKey(bytes: ByteArray) {
dataDir.mkdirs()
val tmp = File(dataDir, "$KEY_FILE_NAME.tmp")
try {
runCatching {
Files.createFile(
tmp.toPath(),
PosixFilePermissions.asFileAttribute(
PosixFilePermissions.fromString("rw-------"),
),
)
}
tmp.writeBytes(bytes)
runCatching {
Files.setPosixFilePermissions(tmp.toPath(), PosixFilePermissions.fromString("rw-------"))
}
if (!tmp.setReadable(false, false) || !tmp.setReadable(true, true)) {
// Non-POSIX fallback best-effort; POSIX path above already secured it.
}
if (!tmp.setWritable(false, false) || !tmp.setWritable(true, true)) {
// ditto
}
Files.move(
tmp.toPath(), keyFile.toPath(),
StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE,
)
} finally {
tmp.delete()
}
}
companion object {
const val KEY_BYTES = 32
private const val KEY_FILE_NAME = "field.key"
}
}
@@ -1,6 +1,7 @@
package org.incido.desktop package org.incido.desktop
import androidx.compose.foundation.clickable import androidx.compose.foundation.clickable
import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Column
@@ -28,6 +29,8 @@ import androidx.compose.material3.SnackbarHost
import androidx.compose.material3.SnackbarHostState import androidx.compose.material3.SnackbarHostState
import androidx.compose.material3.Surface import androidx.compose.material3.Surface
import androidx.compose.material3.Text import androidx.compose.material3.Text
import androidx.compose.material3.darkColorScheme
import androidx.compose.material3.lightColorScheme
import androidx.compose.runtime.Composable import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState 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.Window
import androidx.compose.ui.window.application import androidx.compose.ui.window.application
import androidx.compose.ui.window.rememberWindowState 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.File
import java.io.ByteArrayInputStream import java.io.ByteArrayInputStream
import java.io.FileOutputStream import java.io.FileOutputStream
import kotlinx.coroutines.delay import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.launch import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import org.incido.compose.data.backup.BackupBridge import org.incido.compose.data.backup.BackupBridge
import org.incido.compose.data.backup.EncryptedBackupCodec import org.incido.compose.data.backup.EncryptedBackupCodec
import org.incido.domain.model.Note 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). // M2 task 4: encrypted-envelope legs (the RequirePassphrase dialog's calls).
val backupExportEnc = args.argAfter("--backup-export-enc") val backupExportEnc = args.argAfter("--backup-export-enc")
val backupPassphrase = args.argAfter("--backup-passphrase") 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("=== Incido (desktop) — Phase 1 M1b ===")
println("JVM : ${System.getProperty("java.vendor")} ${System.getProperty("java.version")}") println("JVM : ${System.getProperty("java.vendor")} ${System.getProperty("java.version")}")
@@ -95,20 +107,40 @@ fun main(args: Array<String>) {
val app = DesktopContainer(dataDir) 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 { application {
val windowState = rememberWindowState(
width = savedWidth.dp,
height = savedHeight.dp,
)
Window( Window(
onCloseRequest = ::exitApplication, onCloseRequest = ::exitApplication,
state = rememberWindowState(width = 1100.dp, height = 760.dp), state = windowState,
title = "Incido", title = "Incido",
) { ) {
NotesWindow( NotesWindow(
app = app,
repository = app.repository, repository = app.repository,
windowStore = windowStore,
windowState = windowState,
exitAfterSeconds = exitAfterSeconds, exitAfterSeconds = exitAfterSeconds,
selfTest = selfTest, selfTest = selfTest,
backupImport = backupImport, backupImport = backupImport,
backupExport = backupExport, backupExport = backupExport,
backupExportEnc = backupExportEnc, backupExportEnc = backupExportEnc,
backupPassphrase = backupPassphrase, backupPassphrase = backupPassphrase,
cryptoSelfTest = cryptoSelfTest,
cryptoReopen = cryptoReopen,
cryptoPassphrase = cryptoPassphrase,
onExit = ::exitApplication, onExit = ::exitApplication,
) )
} }
@@ -120,13 +152,19 @@ fun main(args: Array<String>) {
@OptIn(ExperimentalMaterial3Api::class) @OptIn(ExperimentalMaterial3Api::class)
@Composable @Composable
private fun NotesWindow( private fun NotesWindow(
app: DesktopContainer,
repository: NoteRepository, repository: NoteRepository,
windowStore: androidx.datastore.core.DataStore<androidx.datastore.preferences.core.Preferences>,
windowState: androidx.compose.ui.window.WindowState,
exitAfterSeconds: Long?, exitAfterSeconds: Long?,
selfTest: Boolean, selfTest: Boolean,
backupImport: String?, backupImport: String?,
backupExport: String?, backupExport: String?,
backupExportEnc: String?, backupExportEnc: String?,
backupPassphrase: String?, backupPassphrase: String?,
cryptoSelfTest: Boolean,
cryptoReopen: Boolean,
cryptoPassphrase: String,
onExit: () -> Unit, onExit: () -> Unit,
) { ) {
val notes by remember(repository) { repository.observeAll() } val notes by remember(repository) { repository.observeAll() }
@@ -135,16 +173,29 @@ private fun NotesWindow(
val scope = rememberCoroutineScope() val scope = rememberCoroutineScope()
val snackbar = remember { SnackbarHostState() } 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. // Keep a valid selection as the library changes.
val selected = notes.firstOrNull { it.id == selectedId } ?: notes.firstOrNull() val selected = notes.firstOrNull { it.id == selectedId } ?: notes.firstOrNull()
MaterialTheme { val darkTheme = userSettings.themeMode.resolveDark(isSystemInDarkTheme())
MaterialTheme(
colorScheme = if (darkTheme) darkColorScheme() else lightColorScheme(),
) {
Scaffold( Scaffold(
snackbarHost = { SnackbarHost(snackbar) }, snackbarHost = { SnackbarHost(snackbar) },
topBar = { topBar = {
CenterAlignedTopAppBar( CenterAlignedTopAppBar(
title = { Text("Incido") }, title = { Text("Incido") },
actions = { actions = {
// M3: theme + encryption live here (Palette menu).
SecurityActions(app = app, snackbar = snackbar)
// M2: the phone bridge lives here (Import…/Export). // M2: the phone bridge lives here (Import…/Export).
BackupActions(repository = repository, snackbar = snackbar) BackupActions(repository = repository, snackbar = snackbar)
IconButton( 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) { if (exitAfterSeconds != null) {
LaunchedEffect(Unit) { LaunchedEffect(Unit) {
delay(exitAfterSeconds * 1000) delay(exitAfterSeconds * 1000)
@@ -0,0 +1,272 @@
package org.incido.desktop
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Palette
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Divider
import androidx.compose.material3.DropdownMenu
import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.SnackbarHostState
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
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 java.io.File
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import org.incido.compose.data.settings.ThemeMode
import org.incido.data.crypto.AesGcmFieldCipher
/**
* Phase 1 (M3 task 3): the desktop security menu.
*
* Deliberately SMALL — the real settings screen arrives with M4. It
* exposes exactly what desktop can honestly offer, per the M3 rules:
* theme mode (works), encryption + recovery key (work, through the same
* shared services Android drives), and NOTHING that can't exist here:
* dynamic color, biometrics and screenshot blocking are hidden, not
* faked (no Material You, no BiometricPrompt, no FLAG_SECURE on the JVM).
* PIN gating is deliberately absent too — the desktop lock story is
* deferred, so [org.incido.compose.data.settings.UserSettings.isLockActive]
* is never true on desktop and the notes open straight away.
*/
@Composable
fun SecurityActions(
app: DesktopContainer,
snackbar: SnackbarHostState,
modifier: Modifier = Modifier,
) {
val scope = rememberCoroutineScope()
var menuOpen by remember { mutableStateOf(false) }
var pendingKeyExport by remember { mutableStateOf(false) }
var pendingKeyImport by remember { mutableStateOf<File?>(null) }
var confirmOverwrite by remember { mutableStateOf<Pair<File, String>?>(null) }
val settings by app.settingsRepository.userSettingsFlow
.collectAsState(initial = org.incido.compose.data.settings.UserSettings())
val verification by app.encryptionVerifier.verification.collectAsState(null)
fun say(message: String) { scope.launch { snackbar.showSnackbar(message) } }
IconButton(onClick = { menuOpen = true }, modifier = modifier) {
Icon(Icons.Default.Palette, contentDescription = "Security & theme menu")
}
DropdownMenu(expanded = menuOpen, onDismissRequest = { menuOpen = false }) {
val active = settings.isEncryptionActive
val badge = verification?.let {
"encrypted ${it.verifiedNoteIds.size} · failed ${it.failedNoteIds.size}"
} ?: "checking…"
DropdownMenuItem(
text = {
Column(verticalArrangement = Arrangement.spacedBy(2.dp)) {
Text("Encryption: ${if (active) "on" else "off"}")
Text(badge, style = MaterialTheme.typography.bodySmall)
}
},
onClick = {},
enabled = false,
)
Divider()
DropdownMenuItem(
text = { Text("Theme: ${settings.themeMode.name.lowercase()} (tap to cycle)") },
onClick = {
scope.launch {
val next = when (settings.themeMode) {
ThemeMode.SYSTEM -> ThemeMode.DARK
ThemeMode.DARK -> ThemeMode.LIGHT
ThemeMode.LIGHT -> ThemeMode.SYSTEM
}
app.settingsRepository.setThemeMode(next)
}
},
)
Divider()
DropdownMenuItem(
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)
}
},
)
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
}
},
)
DropdownMenuItem(
text = { Text("Import recovery key…") },
onClick = {
menuOpen = false
scope.launch {
val file = pickFile(
load = true,
title = "Import recovery key",
extensions = listOf("incidokey"),
) ?: return@launch
pendingKeyImport = file
}
},
)
}
// ---- 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}" },
),
)
}
},
)
}
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") }
},
)
}
}
/** The import leg shared by the direct and confirm-overwrite paths —
* mirrors Android's SettingsViewModel.importRecoveryKey: install, swap
* the live cipher when encryption is on, re-verify, report. */
private suspend fun importKey(
app: DesktopContainer,
envelope: ByteArray,
passphrase: String,
say: (String) -> Unit,
) {
val result = runCatching {
withContext(Dispatchers.IO) {
val hadKey = app.keyProvider.hasKey()
app.keyProvider.importRecoveryKey(envelope, passphrase.toCharArray())
if (app.settingsRepository.snapshot().isEncryptionActive) {
app.cipherHolder.cipher = AesGcmFieldCipher(app.keyProvider)
}
hadKey
}
}
app.encryptionVerifier.checkNow()
result.fold(
onSuccess = { hadKey ->
say(
if (hadKey) {
"Recovery key installed. Previously-encrypted notes will appear as unverified."
} else {
"Recovery key installed."
},
)
},
onFailure = { say("Recovery key rejected: wrong passphrase or corrupt file.") },
)
}