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

@@ -6,10 +6,17 @@ import androidx.datastore.preferences.core.PreferenceDataStoreFactory
import androidx.datastore.preferences.core.Preferences
import androidx.datastore.preferences.core.emptyPreferences
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.data.ImageOrientationNormalizer
import org.incido.data.ObjectBoxStore
import org.incido.data.crypto.AesGcmFieldCipher
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.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
* the Android app's `AppContainer` (Development Plan §6, Phase 1, M1b).
*
* Deliberately mirrors Android's construction order: settings first (M3),
* then open the store, then build the repository over a shared
* [CipherHolder] so installing or removing at-rest encryption later is a
* one-line change here instead of a rebuild of the graph.
* Construction order mirrors Android exactly, for the reason the plan
* names: settings first, then the cipher install from the settings
* snapshot BEFORE the repository exists (so the very first snapshot
* 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:
* - at-rest encryption (milestone M3 — needs a JVM KeyProvider; the
* recovery-key envelope is already proven portable), and
* - EXIF rotation (milestone M4 — needs a JVM image decoder, so inbound
* images are stored exactly as received for now).
* Key-source difference (M3 task 3): Android's key lives in a
* Keystore-wrapped DataStore blob; desktop's counterpart is
* [DesktopKeyProvider]'s `0600` key file — see there for why the keyring
* fallback was chosen. PIN / biometric / screenshot gating is
* 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 =
SettingsRepository(preferencesStore(dataDir, "incido_settings"))
val keyProvider = DesktopKeyProvider(dataDir)
/** Shared cipher slot consulted by the repository on every I/O. */
val cipherHolder = CipherHolder()
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(
boxStore = boxStore,
cipherHolder = cipherHolder,
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()
}
}
/**
@@ -79,4 +120,4 @@ fun defaultDataDir(): File {
val base = System.getenv("XDG_DATA_HOME")?.takeIf { it.isNotBlank() }
?: System.getProperty("user.home") + sep + ".local" + sep + "share"
return File(base + sep + "incido").also { it.mkdirs() }
}
}