From 6b8db18cdf3c9a6d1f5e3d83034c912f13319f73 Mon Sep 17 00:00:00 2001 From: Incido Developer Date: Tue, 6 Oct 2026 07:39:54 +1300 Subject: [PATCH] docs(phase-1/m3.4): M3 status + scripted key-envelope legs; plan handed to M4 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Closes milestone M3 (DESKTOP_PHASE_PLAN §5). Code (one addition): --key-export / --key-import CLI legs in Main.kt — the SecurityActions menu's exact codec calls, headless. This makes the pending physical-phone leg a one-liner once a Waydroid container is live (recipe recorded in the feasibility doc). Docs: DESKTOP_FEASIBILITY.md gains the M3.1–M3.4 status section with the actual run output (leg A/B, KEYENV logs, 0600 ls lines); plan §1 lists the two crypto legs among the must-stay-green commands; §5 marked DONE; first-actions now point a fresh session at M4 task 1. Exit criteria, per the plan's wording: - encrypted desktop library passes EncryptionVerifier's trial-decrypt sweep: MET (leg A verified=1 failed=0, wrong key -> AEAD failure count, leg B relaunch all-ok). - phone-exported recovery key decrypts on desktop: MET at format level (shared codec source, 84B INCKEY1 envelope, AEADBadTagException on wrong passphrase, byte-identical key into a fresh 0600 file); the physical phone export is FLAGGED pending (Waydroid container FROZEN, start is sudo-gated) with the exact re-run recipe — not assumed done. Verified: ./gradlew assembleDebug, :core:data-jvm:smoke, :spike:data-jvm:run, :desktopApp:run --self-test, and both crypto legs — all green in one final pass (one self-test teardown hang under the compositor, rc=124, clean on immediate rerun — recorded, environmental). --- .../main/kotlin/org/incido/desktop/Main.kt | 59 ++++++++++ tools/DESKTOP_FEASIBILITY.md | 105 ++++++++++++++++++ tools/DESKTOP_PHASE_PLAN.md | 15 ++- 3 files changed, 175 insertions(+), 4 deletions(-) diff --git a/desktopApp/src/main/kotlin/org/incido/desktop/Main.kt b/desktopApp/src/main/kotlin/org/incido/desktop/Main.kt index 831f6f4..f9e704b 100644 --- a/desktopApp/src/main/kotlin/org/incido/desktop/Main.kt +++ b/desktopApp/src/main/kotlin/org/incido/desktop/Main.kt @@ -51,12 +51,16 @@ import androidx.datastore.preferences.core.intPreferencesKey import java.io.File import java.io.ByteArrayInputStream import java.io.FileOutputStream +import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.delay import kotlinx.coroutines.flow.first import kotlinx.coroutines.launch import kotlinx.coroutines.runBlocking +import kotlinx.coroutines.withContext import org.incido.compose.data.backup.BackupBridge import org.incido.compose.data.backup.EncryptedBackupCodec +import org.incido.compose.data.backup.EncryptedKeyCodec +import org.incido.data.crypto.AesGcmFieldCipher import org.incido.domain.model.Note import org.incido.domain.repository.NoteRepository @@ -100,6 +104,12 @@ fun main(args: Array) { val cryptoSelfTest = "--crypto-self-test" in args val cryptoReopen = "--crypto-reopen" in args val cryptoPassphrase = args.argAfter("--crypto-passphrase") ?: "selftest-passphrase" + // Recovery-envelope file legs: --key-export writes the INCKEY1 envelope + // the phone's Settings screen writes; --key-import reads one (e.g. a + // REAL phone export) with the passphrase and installs the key — the + // scripted version of the SecurityActions import menu. + val keyExport = args.argAfter("--key-export") + val keyImport = args.argAfter("--key-import") println("=== Incido (desktop) — Phase 1 M1b ===") println("JVM : ${System.getProperty("java.vendor")} ${System.getProperty("java.version")}") @@ -141,6 +151,8 @@ fun main(args: Array) { cryptoSelfTest = cryptoSelfTest, cryptoReopen = cryptoReopen, cryptoPassphrase = cryptoPassphrase, + keyExport = keyExport, + keyImport = keyImport, onExit = ::exitApplication, ) } @@ -165,6 +177,8 @@ private fun NotesWindow( cryptoSelfTest: Boolean, cryptoReopen: Boolean, cryptoPassphrase: String, + keyExport: String?, + keyImport: String?, onExit: () -> Unit, ) { val notes by remember(repository) { repository.observeAll() } @@ -352,6 +366,51 @@ private fun NotesWindow( prefs[intPreferencesKey("window_height")] = height } } + if (keyExport != null || keyImport != null) { + LaunchedEffect(Unit) { + delay(800) + withContext(Dispatchers.IO) { + if (keyExport != null) { + // Same codec call the SecurityActions export menu makes — + // the exact envelope the phone's ObjectBoxKeyProvider writes. + val out = File(keyExport) + out.writeBytes(app.keyProvider.exportRecoveryKey(cryptoPassphrase.toCharArray())) + val magic = out.readBytes() + .copyOf(EncryptedKeyCodec.MAGIC.size) + .contentEquals(EncryptedKeyCodec.MAGIC) + println( + "KEYENV exported=${out.length()}B to $out " + + "(magic=${if (magic) "INCKEY1 ok" else "BAD"})", + ) + } + if (keyImport != null) { + val bytes = File(keyImport).readBytes() + val rejectedWrongPw = runCatching { + app.keyProvider.importRecoveryKey(bytes, "wrong-pass".toCharArray()) + }.isFailure + val result = runCatching { + app.keyProvider.importRecoveryKey(bytes, cryptoPassphrase.toCharArray()) + if (app.settingsRepository.snapshot().isEncryptionActive) { + app.cipherHolder.cipher = AesGcmFieldCipher(app.keyProvider) + } + app.noteCryptoService.verifyAll() + } + result.fold( + onSuccess = { v -> + println( + "KEYENV import ok wrong-pw=" + + (if (rejectedWrongPw) "rejected" else "LEAKED!") + + " verify verified=${v.verifiedNoteIds.size} failed=${v.failedNoteIds.size}", + ) + }, + onFailure = { + println("KEYENV import FAILED: ${it.javaClass.simpleName}: ${it.message}") + }, + ) + } + } + } + } if (cryptoSelfTest || cryptoReopen) { LaunchedEffect(Unit) { delay(800) // past the first frame; assertions ride the flows, not frame one diff --git a/tools/DESKTOP_FEASIBILITY.md b/tools/DESKTOP_FEASIBILITY.md index 7c93225..5944e4b 100644 --- a/tools/DESKTOP_FEASIBILITY.md +++ b/tools/DESKTOP_FEASIBILITY.md @@ -499,6 +499,111 @@ before a 3 s-delayed screenshot — burst-capture spectacle at 1 s intervals; `waydroid shell` needs sudo, but `waydroid app install` and `pkill -f org.incido.app` from the host need none. +**M3.1 — `:core:settings`: DONE.** `UserSettings` + `SettingsRepository` +moved to a plain `kotlin("jvm")` module with package +`org.incido.compose.data.settings` kept, so the Android diff is two +constructor lines + one new provider file (`AndroidSettingsStore.kt` — +the `preferencesDataStore(name = "incido_settings")` Context extension, +moved verbatim). The repository now takes an **injected** +`DataStore`; the desktop creates the identical format with +`PreferenceDataStoreFactory.create(corruptionHandler, produceFile)` +(the Phase-0 API delta). `:app` gained `implementation(":core:settings")` +— MainActivity reads `userSettingsFlow` and the type moved with the +class, same reason `:core:domain` is there. `snapshot()`'s `runBlocking` +kept for startup-only use. `dynamic_color` / `use_biometric` / +`block_screenshots` ride in the file but have no desktop UI (hidden, +not faked). Verified: `assembleDebug` + `:desktopApp:run … --self-test` ++ `:core:data-jvm:smoke` green. + +**M3.2 — cipher seam: DONE.** `AesGcmFieldCipher` moved into +`core/data/src/main/kotlin/…/crypto/` (compiled by BOTH modules) behind +new `fun interface FieldKeyProvider { getOrCreateKey(): ByteArray }`; +`EncryptionVerifier` (pure coroutines) moved with it. Android passes +`objectBoxKeyProvider::getOrCreateKey` (SAM). Verified: `assembleDebug` ++ desktop self-test green. + +**M3.3 — desktop key + wiring + UI: DONE.** `DesktopKeyProvider`: the +32-byte key in `field.key` (temp+atomic-move, `0600` POSIX perms — +visible as `-rw-------` in every `ls` below). KEYRING STATUS, STATED +PLAINLY: no keyring library is in the catalog and no candidate was +verified on this stack, so the plan's fallback (file + `0600`) stands; +revisit in Phase 2 with `secret-service` behind a real test. +`DesktopContainer` now mirrors `AppContainer` completely — settings → +cipher auto-install (`isEncryptionActive` AND key on disk) BEFORE the +repository → `NoteCryptoService` → `EncryptionVerifier.checkNow()`. +`SecurityActions` menu: theme cycle (real shared `theme_mode` key — +Material3 switches via `colorScheme`, there is no `darkTheme` param), +encrypt/decrypt toggle (Android's enable/disable call order), recovery +key import/export (with Android's overwrite-warning gate); no dynamic +color, no biometrics, no screenshot blocking, no PIN — desktop hides +all four. Window geometry → its own `incido_window.preferences_pb` +(position deliberately not stored; KWin owns placement). Scripted legs +(`--crypto-self-test` / separate-process `--crypto-reopen`): + +``` +=== leg A: enable === (fresh /tmp/incido-desktop-crypto) +probe note written PASS id=1 +encrypt sweep flipped rows PASS +verifier trial-decrypt sweep PASS verified=1 failed=0 +repository decrypts transparently PASS notes=1 +wrong key rejected (AEAD tag) PASS failed=1 +recovery envelope (INCKEY1) PASS len=84 +wrong passphrase rejected PASS +envelope carries library key PASS +CRYPTO LEG-A PASS (library left encrypted for leg B) + +=== leg B: reopen (separate process = the real relaunch) === +settings survived restart PASS +cipher auto-installed PASS +reopen verifier sweep all-ok PASS verified=1 failed=0 +decrypt sweep reverses it PASS +CRYPTO LEG-B PASS +``` + +**M3.4 — recovery-key envelope file legs: DONE (desktop side).** +`--key-export` / `--key-import` drive the menu's exact codec calls +headlessly — export from one library, import into a FRESH one: + +``` +KEYENV exported=84B to /tmp/incido-recovery-key.incidokey (magic=INCKEY1 ok) +KEYENV import ok wrong-pw=rejected verify verified=0 failed=0 +KEYENV import FAILED: AEADBadTagException: Tag mismatch! (wrong passphrase) +-rw------- 1 nick nick 32 … /tmp/incido-key-dst/field.key (imported key is 0600) +``` + +**M3 exit criteria:** (1) "an encrypted desktop library passes +`EncryptionVerifier`'s trial-decrypt sweep" — **met**, leg A step 3 + +leg B (auto-install + full-library sweep on relaunch). (2) "a +phone-exported recovery key decrypts … on desktop" — **met at format +level** (one shared `EncryptedKeyCodec` source compiled into both +platforms; 84-byte envelope, wrong-pw AEAD rejection, byte-identical +key — above); the **physical phone leg is the one item pending**: the +Waydroid container was FROZEN at session end and starting it is +sudo-gated, so the phone→desktop `Settings → Export recovery key` run +could not be executed here. Recipe for it (≈15 min with a live +container, mirrors the M2.4b pass): enable encryption on the phone → +export the recovery key to a shared-storage file → copy to host → +`./gradlew :desktopApp:run --args="--data-dir /tmp/incido-phonekey +--backup-import --key-import + --crypto-passphrase --exit-after 25"` → +enable encryption in that library → every imported note earns the badge. + +Honesty notes: (a) intermittent XWayland window flakiness struck this +session's scripted runs three times — a startup wedge (never reached +first composition) and two teardown wedges (all output flushed, never +reached `exitApplication`); every occurrence passed cleanly on rerun, +none touched the data paths, and the first predates all M3 code, so it +is environmental (likely compositor power state after long uptime), not +a regression. Scripted verification should retry once before believing +a hang; +(b) `field.key` protects at-rest notes only against someone reading the +files — it cannot gate app opening (no desktop lock is wired; PIN gating +is deferred); (c) the PBKDF2 recovery path costs ~55 ms per unlock here, +so desktop may skip Android's async key handling for good. + +**Next up: M4** — `composeApp` → Compose Multiplatform (plan §6). + + diff --git a/tools/DESKTOP_PHASE_PLAN.md b/tools/DESKTOP_PHASE_PLAN.md index 3005dc4..39dd0b6 100644 --- a/tools/DESKTOP_PHASE_PLAN.md +++ b/tools/DESKTOP_PHASE_PLAN.md @@ -47,6 +47,10 @@ Commands that must stay green: ./gradlew :spike:data-jvm:run --args="/tmp/incido-spike-db" # Phase-0 probes ./gradlew assembleDebug # Android — every single step ./gradlew :desktopApp:createDistributable # packaging (M5) +# M3 (settings + at-rest encryption). Leg B must run as a SEPARATE process +# after leg A (it proves the relaunch), against the same fresh data dir: +./gradlew :desktopApp:run --args="--data-dir /tmp/incido-desktop-crypto --crypto-self-test --crypto-passphrase m3-script-pw --exit-after 20" # leg A (leaves lib encrypted) +./gradlew :desktopApp:run --args="--data-dir /tmp/incido-desktop-crypto --crypto-reopen --exit-after 15" # leg B (verifies + decrypts back) ``` Versions that matter: Compose Multiplatform `1.7.3`, AndroidX Compose BOM @@ -128,7 +132,7 @@ is additive and forces `id = 0`. The only Android code in the path is Exit criteria: bidirectional lossless round-trip; importing twice adds nothing; `:core:backup` compiles for both platforms; Android backup screens unchanged. -## 5. M3 — settings + at-rest encryption on desktop +## 5. M3 — settings + at-rest encryption on desktop — **DONE** (status + run logs in `DESKTOP_FEASIBILITY.md`; the physical phone→desktop recovery-key leg is the one pending manual run, recipe recorded there) **Settings.** Move `SettingsRepository` (116 LOC, 8 keys: `theme_mode`, `dynamic_color`, `security_enabled`, `encryption_enabled`, `pin_enabled`, @@ -238,6 +242,9 @@ abstraction, justify it in the commit message. Flag anything unverifiable instead of assuming it works. **First actions for a new session:** `git log --oneline -6` → read -`tools/DESKTOP_FEASIBILITY.md` → run `:core:data-jvm:smoke` and the -`:desktopApp:run … --self-test` command above to confirm the tree matches this -description → start M2 task 1 (extract `:core:backup`). \ No newline at end of file +`tools/DESKTOP_FEASIBILITY.md` → run `:core:data-jvm:smoke`, the +`:desktopApp:run … --self-test` command, and the M3 crypto legs above to +confirm the tree matches this description → start M4 task 1 (convert +`:composeApp` in-place to `kotlin("multiplatform")` with +`androidTarget()` + `jvm()`, per §6 order of attack — decide within a day +of real friction whether to fall back to a `:ui-shared` module). \ No newline at end of file