feat: v0.3.6.0 — AES-GCM field encryption, PIN/passphrase security, encryption verifier, backup codec
build / Assemble debug APK (push) Failing after 2s

This commit is contained in:
Incido Developer committed 2026-08-20 01:14:15 +12:00
1 parent 089926377c
commit 14d61c78d3
55 files changed
+2474 -715

No files matched your search

@@ -69,10 +69,15 @@ private fun String.toNoteFilter(): NoteFilter = when {
* v0.3.1.0: Holds the share-into payload (text + pre-loaded image
* bytes) so the [NoteEditorScreen] can read it on first composition.
* Cleared as soon as the editor is created.
*
* v0.3.6.0: also carries [subject] (`Intent.EXTRA_SUBJECT`) so the
* editor can put the page title on the note's first line for URL
* shares — still offline-only, no network fetch.
*/
private class ShareIntoHolder {
var text: String? = null
var images: List<SharedImage> = emptyList()
var subject: String? = null
}
@OptIn(ExperimentalMaterial3Api::class)
@@ -127,6 +132,7 @@ fun IncidoApp(
if (payload != null && !payload.isEmpty) {
shareHolder.text = payload.text
shareHolder.images = payload.images
shareHolder.subject = payload.subject
navController.navigate(Routes.editor(null)) {
popUpTo(Routes.LIST)
}
@@ -205,12 +211,21 @@ fun IncidoApp(
// doesn't re-route us into the editor with stale data.
val sharedText = shareHolder.text.also { shareHolder.text = null }
val sharedImages = shareHolder.images.also { shareHolder.images = emptyList() }
// v0.3.6.0: also drain the page-title subject from the
// share intent so the editor can format the note
// with title on the first line.
val sharedSubject = shareHolder.subject.also { shareHolder.subject = null }
NoteEditorScreen(
noteId = id,
onClose = { navController.popBackStack() },
initialSharedText = sharedText,
initialSharedImages = sharedImages,
initialSharedSubject = sharedSubject,
repository = repository,
// v0.3.4.0 hotfix: suppress auto-lock around
// the editor's picker / camera / system-viewer
// round-trips.
securityManager = resolvedSecurity,
)
}
composable(Routes.SETTINGS) {
@@ -219,6 +234,9 @@ fun IncidoApp(
onRequestPinSetup = { navController.navigate(Routes.PIN_SETUP) },
// v0.3.3.0: "Reset PIN" row navigates here.
onRequestPinChange = { navController.navigate(Routes.PIN_CHANGE) },
// v0.3.4.0 hotfix: suppress auto-lock around
// the backup export/import SAF pickers.
securityManager = resolvedSecurity,
)
}
composable(Routes.PIN_SETUP) {
@@ -0,0 +1,148 @@
package org.incido.compose.data.backup
import java.security.SecureRandom
import javax.crypto.Cipher
import javax.crypto.SecretKeyFactory
import javax.crypto.spec.GCMParameterSpec
import javax.crypto.spec.PBEKeySpec
import javax.crypto.spec.SecretKeySpec
/**
* v0.3.6.0: passphrase-encrypted recovery-key envelope.
*
* Lets the user back up (and later restore) the
* [org.incido.compose.data.security.ObjectBoxKeyProvider] at-rest
* encryption key — the same 32-byte AES key that protects every
* encrypted note + attachment row. Without this, a device migration
* with encrypted notes has no recovery path other than restoring an
* encrypted backup.
*
* On-disk layout:
*
* ```
* magic "INCKEY1\0" (8 bytes)
* salt (16 bytes)
* iv (12 bytes)
* ciphertext + tag (variable — wraps exactly 32 key bytes)
* ```
*
* Identical KDF + AEAD to [EncryptedBackupCodec] (PBKDF2-HMAC-SHA256,
* 200,000 iterations → 256-bit AES key; AES-256-GCM body) so the
* import / export code path is symmetric. The magic header is what
* lets the import side auto-detect the format — the wrapper file is
* written via SAF so the user picks the destination.
*
* The Keystore master key itself is **not exportable** (it's
* device-bound by design); we only wrap the 32-byte field key, which
* is what actually encrypts note content. The recovery envelope is
* useless without the passphrase, so a stolen recovery file alone
* does not compromise the notes.
*/
object EncryptedKeyCodec {
/** "Incido Recovery Key v1" — null terminator included so it
* never collides with `{` (the first byte of any JSON object) or
* with the backup envelope's "INCDBK1\0" header. */
val MAGIC: ByteArray = byteArrayOf(
0x49, 0x4E, 0x43, 0x4B, 0x45, 0x59, 0x31, 0x00,
)
/** Number of bytes the wrapped payload holds — must be exactly
* [org.incido.compose.data.security.ObjectBoxKeyProvider.KEY_BYTES].
* Enforced on encrypt + decrypt so a tampered file is rejected
* before the cipher is installed. */
const val KEY_PAYLOAD_BYTES = 32
private const val SALT_BYTES = 16
private const val IV_BYTES = 12
private const val GCM_TAG_BITS = 128
private const val PBKDF2_ITERATIONS = 200_000
private const val DERIVED_KEY_BITS = 256
private const val TRANSFORMATION = "AES/GCM/NoPadding"
private val secureRandom = SecureRandom()
/** True if [bytes] starts with [MAGIC] — used by the import side
* to distinguish a recovery key from any other file the user
* might pick. */
fun isEncryptedKey(bytes: ByteArray): Boolean {
if (bytes.size < MAGIC.size) return false
return bytes.copyOfRange(0, MAGIC.size).contentEquals(MAGIC)
}
/**
* Encrypt exactly [KEY_PAYLOAD_BYTES] of [rawKey] with [passphrase]
* and return the full envelope. Throws if the input isn't the
* expected length.
*/
fun encrypt(rawKey: ByteArray, passphrase: CharArray): ByteArray {
require(rawKey.size == KEY_PAYLOAD_BYTES) {
"Recovery key payload must be $KEY_PAYLOAD_BYTES bytes (got ${rawKey.size})"
}
val salt = ByteArray(SALT_BYTES).also(secureRandom::nextBytes)
val iv = ByteArray(IV_BYTES).also(secureRandom::nextBytes)
val derived = deriveKey(passphrase, salt)
try {
val cipher = Cipher.getInstance(TRANSFORMATION)
cipher.init(
Cipher.ENCRYPT_MODE,
SecretKeySpec(derived, "AES"),
GCMParameterSpec(GCM_TAG_BITS, iv),
)
val cipherText = cipher.doFinal(rawKey)
return MAGIC + salt + iv + cipherText
} finally {
derived.fill(0)
passphrase.fill('0')
}
}
/**
* Reverse of [encrypt]. Returns the 32 raw key bytes. Throws on
* bad passphrase, wrong magic, truncated file, or wrong payload
* length (any of which is sufficient proof the file isn't a real
* Incido recovery key).
*/
fun decrypt(payload: ByteArray, passphrase: CharArray): ByteArray {
require(isEncryptedKey(payload)) { "Not an Incido recovery key file" }
require(payload.size >= MAGIC.size + SALT_BYTES + IV_BYTES + GCM_TAG_BITS / 8 + KEY_PAYLOAD_BYTES) {
"Recovery key file is truncated"
}
val salt = payload.copyOfRange(MAGIC.size, MAGIC.size + SALT_BYTES)
val iv = payload.copyOfRange(
MAGIC.size + SALT_BYTES,
MAGIC.size + SALT_BYTES + IV_BYTES,
)
val cipherText = payload.copyOfRange(
MAGIC.size + SALT_BYTES + IV_BYTES,
payload.size,
)
val derived = deriveKey(passphrase, salt)
try {
val cipher = Cipher.getInstance(TRANSFORMATION)
cipher.init(
Cipher.DECRYPT_MODE,
SecretKeySpec(derived, "AES"),
GCMParameterSpec(GCM_TAG_BITS, iv),
)
val raw = cipher.doFinal(cipherText)
require(raw.size == KEY_PAYLOAD_BYTES) {
"Recovery key payload is the wrong size (${raw.size} != $KEY_PAYLOAD_BYTES)"
}
return raw
} finally {
derived.fill(0)
passphrase.fill('0')
}
}
private fun deriveKey(passphrase: CharArray, salt: ByteArray): ByteArray {
val spec = PBEKeySpec(passphrase, salt, PBKDF2_ITERATIONS, DERIVED_KEY_BITS)
try {
val factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256")
return factory.generateSecret(spec).encoded
} finally {
spec.clearPassword()
}
}
}
@@ -0,0 +1,72 @@
package org.incido.compose.data.security
import java.security.SecureRandom
import javax.crypto.Cipher
import javax.crypto.spec.GCMParameterSpec
import javax.crypto.spec.SecretKeySpec
import org.incido.data.crypto.FieldCipher
/**
* v0.3.5.0: AES-256-GCM implementation of [FieldCipher] backed by the
* Keystore-wrapped 32-byte key owned by [ObjectBoxKeyProvider].
*
* This is what actually makes "Encrypt in place" work: note content
* and attachment blobs are stored as
*
* ```
* nonce (12 bytes) | ciphertext | GCM tag (16 bytes, appended by JCE)
* ```
*
* AES-256 is the correct long-term choice for data-at-rest even under a
* post-quantum threat model — NIST considers AES-256 (GCM) to retain
* ~128-bit security against Grover's algorithm. The quantum-sensitive
* primitives (public-key exchange / signatures) are not used here.
*
* The key bytes are cached for the process lifetime (they already live
* in memory whenever [ObjectBoxKeyProvider] unwraps them at startup).
*/
class AesGcmFieldCipher(keyProvider: ObjectBoxKeyProvider) : FieldCipher {
private val keyBytes: ByteArray = keyProvider.getOrCreateKey()
private val secretKey = SecretKeySpec(keyBytes, "AES")
private val secureRandom = SecureRandom()
override fun encryptString(plaintext: String): ByteArray =
encryptBytes(plaintext.toByteArray(Charsets.UTF_8))
override fun decryptString(blob: ByteArray): String =
decryptBytes(blob).toString(Charsets.UTF_8)
override fun encryptBytes(plaintext: ByteArray): ByteArray {
val nonce = ByteArray(NONCE_BYTES).also(secureRandom::nextBytes)
val cipher = Cipher.getInstance(TRANSFORMATION)
cipher.init(
Cipher.ENCRYPT_MODE,
secretKey,
GCMParameterSpec(GCM_TAG_BITS, nonce),
)
val cipherText = cipher.doFinal(plaintext)
return nonce + cipherText
}
override fun decryptBytes(blob: ByteArray): ByteArray {
require(blob.size > NONCE_BYTES) { "Encrypted blob is truncated" }
val nonce = blob.copyOfRange(0, NONCE_BYTES)
val cipherText = blob.copyOfRange(NONCE_BYTES, blob.size)
val cipher = Cipher.getInstance(TRANSFORMATION)
cipher.init(
Cipher.DECRYPT_MODE,
secretKey,
GCMParameterSpec(GCM_TAG_BITS, nonce),
)
// Throws AEADBadTagException on corruption / wrong key — this
// is the integrity signal the startup verifier relies on.
return cipher.doFinal(cipherText)
}
companion object {
private const val NONCE_BYTES = 12
private const val GCM_TAG_BITS = 128
private const val TRANSFORMATION = "AES/GCM/NoPadding"
}
}
@@ -0,0 +1,85 @@
package org.incido.compose.data.security
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import org.incido.data.crypto.EncryptionVerification
import org.incido.data.crypto.NoteCryptoService
/**
* v0.3.5.0: runs the note-encryption integrity check and exposes the
* result as observable state for the UI.
*
* Contract (per product requirement): the "Encrypted" badge on the
* note cards may ONLY be shown for notes that are **double-checked** —
* i.e. their stored ciphertext actually decrypts cleanly under the
* current Keystore key (the AES-GCM auth tag is the integrity proof).
* The settings flag alone never earns the badge.
*
* The check runs:
* 1. On every app open ([checkNow] from Application.onCreate), and
* 2. After each encryption migration completes (enable or disable),
* so the badge set always reflects the current on-disk state.
*
* v0.3.5.1: replaced the `if (_checking.value) return` skip-guard with
* a [Mutex] so concurrent calls actually serialize instead of being
* silently dropped. The previous implementation could miss the
* post-migration re-check when the startup check was still in flight
* on a phone with many notes — the new call would early-out, the old
* (stale, pre-encryption) result would win the race, and the cards
* never earned the badge until the user toggled off+on or restarted.
* The mutex lets every call take its turn in invocation order; the
* startup check is cheap (no encrypted rows yet) so user-triggered
* checks after a real migration only wait milliseconds.
*/
class EncryptionVerifier(
private val cryptoService: NoteCryptoService,
private val scope: CoroutineScope,
) {
private val _verification = MutableStateFlow<EncryptionVerification?>(null)
/** Latest verification result. `null` until the first check completes. */
val verification: StateFlow<EncryptionVerification?> = _verification.asStateFlow()
private val _verifiedNoteIds = MutableStateFlow<Set<Long>>(emptySet())
/** Set of note ids whose ciphertext verified cleanly. Empty before
* the first check — the badge is hidden until then. */
val verifiedNoteIds: StateFlow<Set<Long>> = _verifiedNoteIds.asStateFlow()
/**
* Serializes [checkNow] calls so every caller gets a turn and the
* LAST call's result wins. Without this, concurrent checks could
* race the StateFlow and a stale pre-migration result could
* overwrite a fresh post-migration one.
*/
private val mutex = Mutex()
init {
// Mirror the verified-id set out of every verification result.
scope.launch(Dispatchers.Default) {
verification.collect { result ->
_verifiedNoteIds.value = result?.verifiedNoteIds ?: emptySet()
}
}
}
/**
* Kick off a full re-verification on the IO pool. Safe to call
* repeatedly — calls are serialized via [mutex] in invocation
* order; the most recent call always produces the final
* `_verification` value, so the StateFlow always reflects the
* latest store state.
*/
fun checkNow() {
scope.launch(Dispatchers.IO) {
mutex.withLock {
_verification.value = cryptoService.verifyAll()
}
}
}
}
@@ -1,6 +1,7 @@
package org.incido.compose.data.security
import android.content.Context
import android.net.Uri
import android.util.Base64
import androidx.datastore.preferences.core.edit
import androidx.datastore.preferences.core.stringPreferencesKey
@@ -14,6 +15,7 @@ import javax.crypto.spec.GCMParameterSpec
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.runBlocking
import org.incido.compose.data.backup.EncryptedKeyCodec
/**
* v0.3.2.0: generates, wraps, and unwraps the 32-byte key used to
@@ -67,6 +69,125 @@ class ObjectBoxKeyProvider(private val context: Context) {
/** True when a wrapped key has been persisted (i.e. encryption is configured). */
suspend fun hasKey(): Boolean = readPersistedKey() != null
/**
* Blocking variant of [hasKey] for use at `Application.onCreate`
* (AppContainer needs the answer synchronously before constructing
* the repository). Cheap: one DataStore read + one Keystore unwrap.
*/
fun hasKeyBlocking(): Boolean = runBlocking { hasKey() }
// ---- v0.3.6.0 recovery-key export / import ----
/**
* Thrown by [exportRecoveryKey] / [importRecoveryKey] when the
* underlying envelope codec rejects the payload (wrong magic,
* truncated file, GCM tag mismatch = bad passphrase).
*/
class RecoveryKeyException(message: String, cause: Throwable? = null) :
java.io.IOException(message, cause)
/**
* Write the current 32-byte field key to [outputUri], wrapped with
* [passphrase]. The destination is user-chosen via SAF — caller
* should pre-suppress auto-lock via `beginExternalActivity()`
* because the SAF picker backgrounds the app.
*
* Throws [RecoveryKeyException] (wrapping the cause) on any I/O
* failure, and `IllegalStateException` if there's no key to back
* up (caller should disable the export row until encryption is on).
*/
suspend fun exportRecoveryKey(outputUri: Uri, passphrase: CharArray) {
val raw = getOrCreateKey()
try {
val envelope = EncryptedKeyCodec.encrypt(raw, passphrase)
context.contentResolver.openOutputStream(outputUri, "w")?.use { stream ->
stream.write(envelope)
stream.flush()
} ?: throw RecoveryKeyException("Couldn't open output stream for $outputUri")
} catch (e: java.io.IOException) {
throw RecoveryKeyException("Failed to write recovery key: ${e.message}", e)
} finally {
// getOrCreateKey returns the cached unwrapped key bytes — clear them.
raw.fill(0)
passphrase.fill('0')
}
}
/**
* Read a recovery envelope from [inputUri], unwrap it with
* [passphrase], and install it as the current field key
* (overwriting any previously-persisted key).
*
* The 32 unwrapped bytes are self-verified by a roundtrip through
* [AesGcmFieldCipher] before the new wrapped blob is persisted, so
* a tampered or wrong-length payload never lands on disk.
*
* The caller is responsible for swapping the [CipherHolder.cipher]
* slot afterwards — [ObjectBoxKeyProvider] deliberately stays
* unaware of the holder to keep the dependency direction
* one-way. See [org.incido.compose.ui.settings.SettingsViewModel]
* for the install + refresh sequence.
*
* @return `true` if a brand-new key was installed (an existing key
* was overwritten), `false` if there was no previous key
* (this was the first install).
*/
suspend fun importRecoveryKey(inputUri: Uri, passphrase: CharArray): Boolean {
val payload: ByteArray = try {
context.contentResolver.openInputStream(inputUri)?.use { it.readBytes() }
?: throw RecoveryKeyException("Couldn't open input stream for $inputUri")
} catch (e: java.io.IOException) {
throw RecoveryKeyException("Failed to read recovery key: ${e.message}", e)
}
val raw = try {
EncryptedKeyCodec.decrypt(payload, passphrase)
} catch (e: IllegalArgumentException) {
// Wrong magic / wrong size / truncated file.
throw RecoveryKeyException("Not a valid Incido recovery key file.", e)
} catch (e: java.security.GeneralSecurityException) {
// AEADBadTagException — bad passphrase.
throw RecoveryKeyException("Incorrect passphrase.", e)
} finally {
payload.fill(0)
passphrase.fill('0')
}
try {
return installKey(raw)
} finally {
raw.fill(0)
}
}
/**
* Wrap [rawKey] (must be exactly [KEY_BYTES]) with the Keystore
* master key, overwrite the persisted blob, and self-verify with a
* roundtrip through [AesGcmFieldCipher].
*
* @return `true` if an existing key was overwritten, `false` if
* this is the first install.
*/
suspend fun installKey(rawKey: ByteArray): Boolean {
require(rawKey.size == KEY_BYTES) {
"Key must be $KEY_BYTES bytes (got ${rawKey.size})"
}
val hadExisting = hasKey()
// Self-verify BEFORE we touch the persisted blob — if the
// cipher roundtrip fails we want to leave the existing key
// alone. We need a transient Keystore wrap to exercise the
// install path; that's effectively what persistWrapped does.
val (iv, cipherText) = wrap(rawKey.copyOf())
// Round-trip through unwrap to prove the cipher actually
// round-trips with these bytes (catches things like passing a
// garbage buffer that happens to be 32 bytes long).
val verified = runCatching { unwrap(iv, cipherText) }.getOrNull()
if (verified == null || !verified.contentEquals(rawKey)) {
throw RecoveryKeyException("Key self-verification failed.")
}
verified.fill(0)
persistWrapped(iv, cipherText)
return hadExisting
}
// ---- internals ----
private suspend fun readPersistedKey(): ByteArray? {
@@ -47,6 +47,22 @@ class SecurityManager(
@Volatile
private var backgroundedAt: Long? = null
/**
* v0.3.4.0 hotfix: true while the user is inside an external
* activity WE launched (SAF file picker, camera, system viewer).
* The app legitimately backgrounds/foregrounds during those
* round-trips, which must NOT count as "leaving the app" for
* auto-lock purposes — otherwise Auto-Lock = Immediate locks the
* screen the moment the picker returns, tearing down the NavHost
* (and the unsaved editor state) from under the result callback.
*
* Set by [beginExternalActivity] just before launching; consumed
* exactly once by [onAppForegrounded]. Cold launch is unaffected —
* a fresh process always starts with the flag false.
*/
@Volatile
private var externalActivityInFlight: Boolean = false
/**
* Decide the initial lock state at app launch. Called from
* [org.incido.compose.IncidoApplication.onCreate]. Reads the
@@ -75,6 +91,17 @@ class SecurityManager(
}
}
/**
* v0.3.4.0 hotfix: call immediately before launching an activity
* that takes the user OUT of Incido but is part of an in-app flow
* (file picker, camera capture, system viewer for an attachment).
* Suppresses the auto-lock that would otherwise fire on return —
* see [externalActivityInFlight].
*/
fun beginExternalActivity() {
externalActivityInFlight = true
}
/** Called from the root Compose tree on `ON_RESUME`. */
fun onAppForegrounded() {
val s = settings.snapshot()
@@ -82,6 +109,17 @@ class SecurityManager(
// (PIN or biometric) re-locks after the timeout.
if (!s.isLockActive) {
_lockState.value = LockState.Unlocked
externalActivityInFlight = false
return
}
// v0.3.4.0 hotfix: returning from an external activity WE
// launched (picker / camera / system viewer) never re-locks,
// regardless of the auto-lock timeout. Consume the flag so
// subsequent genuine background/foreground cycles lock as
// configured.
if (externalActivityInFlight) {
externalActivityInFlight = false
backgroundedAt = null
return
}
val bg = backgroundedAt ?: return // already in foreground
@@ -26,77 +26,81 @@ object ReleaseNotes {
*/
val RECENT: List<ReleaseNote> = listOf(
ReleaseNote(
version = "0.3.3.4",
date = "2026-08-17",
version = "0.3.6.0",
date = "2026-08-19",
bullets = listOf(
"The favourite star on note cards no longer overlaps the " +
"\u22EE overflow button — it now sits in the " +
"bottom-right corner, vertically aligned with the " +
"three-dot button above it.",
"Sharing a webpage to Incido (browser \u2192 Share \u2192 Incido) now " +
"creates a note with the page title on the first line and " +
"the URL below it \u2014 ready to save as-is. Fully offline: " +
"the title comes from the browser's share data, so Incido " +
"still never touches the network.",
"New in Settings \u2192 Security: \"Export encryption key\" saves " +
"the AES-256 key that protects your encrypted notes to a " +
"passphrase-protected .inckey file \u2014 your backup for " +
"device migrations.",
"\"Import encryption key\" restores that key on a fresh " +
"install, with a clear warning before the current key is " +
"replaced.",
),
),
ReleaseNote(
version = "0.3.3.3",
version = "0.3.5.1",
date = "2026-08-17",
bullets = listOf(
"Importing an encrypted backup no longer crashes the app — " +
"the passphrase was being wiped after the preview " +
"step, so the final import ran without it and failed. " +
"The passphrase is now retained for the import and " +
"securely wiped afterwards.",
"Backup import errors (wrong passphrase, corrupt or " +
"truncated files, unreadable files) now surface as a " +
"snackbar message instead of crashing the app.",
"Cards now update their \"Encrypted\" indicator the moment " +
"you flip the Encrypt-at-rest switch on — no need to " +
"toggle off+on or restart the app to see the badge " +
"appear.",
"The \"Encrypted\" indicator on each note card is now " +
"just a small lock icon, sitting immediately to the " +
"left of the date/time on the bottom row (consistent " +
"position on every card, instead of a centred \"lock + " +
"label\" group at the bottom of the card).",
),
),
ReleaseNote(
version = "0.3.3.2",
version = "0.3.5.0",
date = "2026-08-17",
bullets = listOf(
"Lock screen is now readable in dark mode — it paints " +
"its own theme-aware background instead of falling " +
"through to the light Activity window (white text " +
"on white).",
"Biometric unlock works again — authentication is fully " +
"asynchronous, so the app no longer hangs waiting " +
"for the prompt's result.",
"\"Encrypt notes at rest\" now really works: your note text " +
"and attachment files are AES-256-GCM encrypted in place " +
"the moment you flip the switch (no restart), using the " +
"Android Keystore key.",
"Every time the app opens, each encrypted note is " +
"double-checked by decrypting it — a card only earns the " +
"\"Encrypted\" badge at the bottom of the card if that " +
"check passes.",
"New \"Block screenshots\" toggle (on by default): prevents " +
"screenshots, screen recording, and app-switcher previews " +
"while Incido is open.",
),
),
ReleaseNote(
version = "0.3.3.1",
version = "0.3.4.0",
date = "2026-08-17",
bullets = listOf(
"\"Encrypt notes at rest\" is now greyed out unless " +
"Security is enabled AND a PIN or Biometric is " +
"configured — you can no longer toggle at-rest " +
"encryption against an unlocked state.",
"The master \"Enable security\" toggle can now be " +
"flipped on by itself — no PIN/Biometric " +
"precondition. Pick PIN or Biometric afterwards.",
"Importing an encrypted backup now opens the import " +
"passphrase dialog (single field, no confirmation " +
"or policy check) instead of the export passphrase " +
"dialog. Wrong passphrase still surfaces " +
"\"Incorrect passphrase.\" via snackbar.",
"Note cards now show a paperclip icon on the right edge " +
"whenever a note has an attachment — lined up between " +
"the favourite star and the \u22EE menu.",
"Cards with a dark image background are now readable in " +
"Light theme — the title, preview text, timestamp and " +
"icons switch to light colours over the photo.",
"Auto-Lock set to \"Immediately\" no longer locks the app " +
"while you're picking a file to attach (or exporting / " +
"importing a backup), so your in-progress note and the " +
"attachment survive the trip to the file manager.",
),
),
ReleaseNote(
version = "0.3.3.0",
version = "0.3.3.8",
date = "2026-08-17",
bullets = listOf(
"Lock mode is now a single choice between app-only PIN and " +
"device biometric — both toggles live under the master " +
"\"Enable security\" switch and grey each other out. A " +
"new \"Reset PIN\" row appears when PIN is the active mode.",
"Encrypted backup import now prompts for the passphrase " +
"(previously the import silently no-op'd when the file " +
"was encrypted).",
"Note-card overflow menu — long-press a card (or tap the " +
"\u22EE button in the top-right) to open a popup menu " +
"with a Delete entry. Designed to host additional " +
"actions (Share, etc.) as they're added.",
"The designed Incido artwork — the glass shield with the " +
"fountain-pen nib — is now the app icon, replacing the " +
"placeholder glyph on the home screen, in the app " +
"drawer, and in the adaptive-icon layers.",
),
),
// v0.3.3.4 push drops v0.3.2.0 off the "5 most recent" tail.
// v0.3.6.0 push drops v0.3.3.7 off the "5 most recent" tail.
)
}
@@ -72,6 +72,11 @@ class SettingsRepository(private val context: Context) {
context.dataStore.edit { it[KEY_AUTO_LOCK_TIMEOUT] = timeout.minutes }
}
/** v0.3.5.0 — screenshot / screen-recording / app-preview blocking. */
suspend fun setBlockScreenshots(enabled: Boolean) {
context.dataStore.edit { it[KEY_BLOCK_SCREENSHOTS] = enabled }
}
// ---- private helpers ----
private fun Preferences.toUserSettings(): UserSettings = UserSettings(
@@ -84,6 +89,8 @@ class SettingsRepository(private val context: Context) {
pinEnabled = this[KEY_PIN_ENABLED] ?: false,
useBiometric = this[KEY_USE_BIOMETRIC] ?: false,
autoLockTimeout = AutoLockTimeout.fromMinutes(this[KEY_AUTO_LOCK_TIMEOUT] ?: 5),
// v0.3.5.0: default ON (true) — absent key means a fresh install blocks screenshots.
blockScreenshots = this[KEY_BLOCK_SCREENSHOTS] ?: true,
)
companion object {
@@ -94,6 +101,7 @@ class SettingsRepository(private val context: Context) {
private val KEY_PIN_ENABLED = booleanPreferencesKey("pin_enabled")
private val KEY_USE_BIOMETRIC = booleanPreferencesKey("use_biometric")
private val KEY_AUTO_LOCK_TIMEOUT = intPreferencesKey("auto_lock_timeout_minutes")
private val KEY_BLOCK_SCREENSHOTS = booleanPreferencesKey("block_screenshots")
}
}
@@ -35,6 +35,13 @@ data class UserSettings(
/** Auto-lock the app after this many minutes of background time.
* Ignored on cold launch (always locked regardless). */
val autoLockTimeout: AutoLockTimeout = AutoLockTimeout.FIVE_MINUTES,
/**
* v0.3.5.0 — block screenshots / screen recording / app-switcher
* previews while inside Incido (`FLAG_SECURE`). Defaults to ON:
* a privacy app should not leak note content into the system
* screenshot surface unless the user opts out.
*/
val blockScreenshots: Boolean = true,
) {
/** True when a PIN is configured AND the master security switch is on. */
val isPinLockActive: Boolean
@@ -2,10 +2,17 @@ package org.incido.compose.di
import android.content.Context
import io.objectbox.BoxStore
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import org.incido.data.ObjectBoxStore
import org.incido.data.crypto.CipherHolder
import org.incido.data.crypto.NoteCryptoService
import org.incido.data.repository.NoteRepositoryImpl
import org.incido.domain.repository.NoteRepository
import org.incido.compose.data.backup.BackupManager
import org.incido.compose.data.security.AesGcmFieldCipher
import org.incido.compose.data.security.EncryptionVerifier
import org.incido.compose.data.security.ObjectBoxKeyProvider
import org.incido.compose.data.security.SecurityManager
import org.incido.compose.data.settings.SettingsRepository
@@ -21,16 +28,25 @@ import org.incido.compose.data.settings.SettingsRepository
* - [SecurityManager] (PIN / biometric / app-lock state)
* - [BackupManager] (JSON + encrypted backup import / export)
*
* The constructor accepts a Context, builds the [SettingsRepository]
* first (so we can read the encryption preference synchronously),
* then either fetches the BoxStore encryption key from the Keystore
* (when `securityEnabled && encryptionEnabled`) or opens the store
* unencrypted.
* v0.3.5.0 — real at-rest encryption. The constructor reads the
* security preferences synchronously; when `securityEnabled &&
* encryptionEnabled` it installs an [AesGcmFieldCipher] into the
* shared [cipherHolder] so every repository read/write encrypts or
* decrypts note content + attachment bytes in place. The ObjectBox
* store file itself is still opened unencrypted (OSS ObjectBox has no
* page-level encryption) — the field-level layer IS the encryption.
* After startup the [encryptionVerifier] re-checks every encrypted row
* by trial-decrypting it; only rows that pass earn the "Encrypted"
* badge on the note cards.
*/
class AppContainer(context: Context) {
private val appContext: Context = context.applicationContext
/** Process-wide scope for fire-and-forget background work
* (verification sweeps, etc.). SupervisorJob isolates failures. */
val appScope = CoroutineScope(SupervisorJob() + Dispatchers.Default)
val settingsRepository: SettingsRepository = SettingsRepository(appContext)
val objectBoxKeyProvider: ObjectBoxKeyProvider = ObjectBoxKeyProvider(appContext)
@@ -38,17 +54,38 @@ class AppContainer(context: Context) {
val securityManager: SecurityManager =
SecurityManager(appContext, settingsRepository)
/** Shared cipher slot consulted by the repository on every I/O. */
val cipherHolder = CipherHolder()
val boxStore: BoxStore = run {
// v0.3.2.0: ObjectBox 4.0.3 OSS doesn't expose an
// `encryptionKey(byte[])` method on BoxStoreBuilder — the
// feature is only available in ObjectBox Pro. The key is
// still generated by ObjectBoxKeyProvider (so the wiring
// is ready for when/if the API lands), but we always
// open the store unencrypted for now.
ObjectBoxStore.init(appContext, encryptionKey = null)
}
val noteRepository: NoteRepository = NoteRepositoryImpl(boxStore)
/**
* v0.3.5.0: install the field cipher BEFORE the repository is
* constructed, so the very first snapshot already reads encrypted
* rows correctly. Key unwrap is a single Keystore operation — safe
* to do synchronously at Application.onCreate.
*/
init {
val s = settingsRepository.snapshot()
if (s.isEncryptionActive && objectBoxKeyProvider.hasKeyBlocking()) {
cipherHolder.cipher = AesGcmFieldCipher(objectBoxKeyProvider)
}
}
val noteRepository: NoteRepository = NoteRepositoryImpl(boxStore, cipherHolder)
val backupManager: BackupManager = BackupManager(appContext, noteRepository)
}
/** Migration sweep + startup integrity checker for the note store. */
val noteCryptoService = NoteCryptoService(boxStore, cipherHolder)
/** Runs on every app open — feeds the verified-encryption badge. */
val encryptionVerifier = EncryptionVerifier(noteCryptoService, appScope)
/** Kick the startup verification off immediately. */
init {
encryptionVerifier.checkNow()
}
}
@@ -0,0 +1,69 @@
package org.incido.compose.share
/**
* v0.3.6.0: offline-only composer for the seeded content of a "share
* with Incido" intent that contains a URL.
*
* Browsers like Chrome, Firefox, Brave, Samsung Internet, etc. fill two
* extras on their `ACTION_SEND` intent when the user picks "Share" on a
* page:
*
* - `EXTRA_SUBJECT` — the page `<title>` from the document head.
* - `EXTRA_TEXT` — the page URL (sometimes pre-prefixed with the
* title by the browser, sometimes plain URL,
* sometimes URL + a quote the user selected).
*
* Since Incido is **offline-only** (no `INTERNET` permission — see
* `app/src/main/AndroidManifest.xml`), we can't fetch the page to
* manufacture a description or summary ourselves. We just splice
* whatever the source app already gave us into a layout that the
* existing [org.incido.domain.model.Note.titleAndBody] will render as:
*
* Title: <EXTRA_SUBJECT> (first non-empty line)
* Body: <EXTRA_TEXT> (everything after)
*
* The user can still edit the note afterwards — the seeded content is
* only the starting point.
*/
object LinkedShareComposer {
/** A compact URL detector. Matches `http(s)://…` and bare `www.…`
* hosts; intentionally not over-eager (we only care about the
* "shared a webpage" case, not every `foo.com`-mention inside a
* longer note). */
private val URL_REGEX = Regex(
"""(?i)\b(?:https?://\S+|www\.[^\s]+)""",
)
/**
* Compose the seeded content for a share-into intent.
*
* @param subject The `EXTRA_SUBJECT` value, if any.
* @param text The `EXTRA_TEXT` value, if any.
* @return A single string ready to seed [org.incido.domain.model.Note.content].
* Always non-null — empty inputs collapse to empty output
* so the editor still starts blank rather than throwing.
*/
fun compose(subject: String?, text: String?): String {
val s = subject?.trim().orEmpty()
val t = text?.trim().orEmpty()
if (s.isEmpty()) return t
if (t.isEmpty()) return s
// If the text already starts with the title (some browsers
// prefix EXTRA_TEXT with the title before the URL), don't
// double-titling — just keep the text as-is.
if (t.startsWith(s)) return t
// If the text doesn't contain a URL, treat it as user-authored
// content (a quote, a note, etc.) and don't splice a title on
// top — the user clearly didn't share a webpage.
if (!URL_REGEX.containsMatchIn(t)) return t
// Standard layout: title on its own line, blank line, URL (and
// any extra text the browser appended) below.
return buildString {
append(s)
append('\n')
append('\n')
append(t)
}
}
}
@@ -21,8 +21,18 @@ object SharedIntentBuffer {
data class Payload(
val text: String?,
val images: List<SharedImage>,
/**
* v0.3.6.0 — `Intent.EXTRA_SUBJECT` from the inbound share. Most
* browsers (Chrome, Firefox, Brave, Samsung Internet, …) fill
* this with the page title when the user shares a URL. The
* editor uses [org.incido.compose.share.LinkedShareComposer]
* to format this as the note title (first line) without ever
* making a network call. Null for image-only shares.
*/
val subject: String? = null,
) {
val isEmpty: Boolean get() = text.isNullOrBlank() && images.isEmpty()
val isEmpty: Boolean
get() = text.isNullOrBlank() && subject.isNullOrBlank() && images.isEmpty()
}
@Volatile
@@ -88,6 +88,7 @@ import androidx.lifecycle.viewmodel.compose.viewModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import org.incido.compose.data.security.SecurityManager
import org.incido.compose.ui.theme.AllNoteColors
import org.incido.compose.ui.theme.swatchBorderColor
import org.incido.compose.ui.theme.toComposeColor
@@ -102,12 +103,26 @@ fun NoteEditorScreen(
onClose: () -> Unit,
initialSharedText: String? = null,
initialSharedImages: List<SharedImage> = emptyList(),
/**
* v0.3.6.0 — `Intent.EXTRA_SUBJECT` from a share-into. Browsers
* fill this with the page title when the user shares a URL; the
* view-model uses it to format the note's first line.
*/
initialSharedSubject: String? = null,
repository: org.incido.domain.repository.NoteRepository? = null,
/**
* v0.3.4.0 hotfix: used to suppress auto-lock while the user is
* inside an external activity we launched (file picker, camera,
* system attachment viewer). Null disables the suppression (the
* pre-0.3.4.0 behaviour).
*/
securityManager: SecurityManager? = null,
viewModel: NoteEditorViewModel = viewModel(
factory = NoteEditorViewModel.factory(
noteId = noteId,
initialSharedText = initialSharedText,
initialSharedImages = initialSharedImages,
initialSharedSubject = initialSharedSubject,
),
key = "editor-$noteId",
),
@@ -161,7 +176,15 @@ fun NoteEditorScreen(
ActivityResultContracts.RequestPermission()
) { granted ->
if (granted) {
pendingCameraUri?.let { uri -> cameraLauncher.launch(uri) }
pendingCameraUri?.let { uri ->
// v0.3.4.0 hotfix: the camera app takes us fully out of
// the process — with Auto-Lock = Immediate the return
// trip used to land on the lock screen (losing the
// unsaved note). Flag the round-trip so the re-lock is
// suppressed.
securityManager?.beginExternalActivity()
cameraLauncher.launch(uri)
}
} else {
Toast.makeText(ctx, "Camera permission denied", Toast.LENGTH_SHORT).show()
}
@@ -275,7 +298,13 @@ fun NoteEditorScreen(
tint = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
IconButton(onClick = { filePickerLauncher.launch(arrayOf("*/*")) }) {
IconButton(onClick = {
// v0.3.4.0 hotfix: the SAF picker backgrounds
// the app; with Auto-Lock = Immediate the return
// used to lock the app and wipe the unsaved note.
securityManager?.beginExternalActivity()
filePickerLauncher.launch(arrayOf("*/*"))
}) {
Icon(
Icons.Filled.AttachFile,
contentDescription = "Attach file",
@@ -389,6 +418,10 @@ fun NoteEditorScreen(
pendingDelete = { tempId -> viewModel.removePendingAttachment(tempId) },
// v0.3.1.1: source of bytes for persisted thumbnail lazy load
repository = repository,
// v0.3.4.0 hotfix: needed by the non-image tap
// handler so the system-viewer round-trip doesn't
// trigger an immediate re-lock.
securityManager = securityManager,
)
}
@@ -462,6 +495,9 @@ private fun AttachmentStrip(
pendingOpen: (Long) -> Unit,
pendingDelete: (Long) -> Unit,
repository: org.incido.domain.repository.NoteRepository?,
/** v0.3.4.0 hotfix: forwarded to [AttachmentThumbnail] for the
* system-viewer auto-lock suppression. */
securityManager: SecurityManager?,
) {
LazyRow(
modifier = Modifier
@@ -481,6 +517,7 @@ private fun AttachmentStrip(
// non-image taps launch a system viewer internally.
onOpenImage = { persistedOpen(persistedViewerIds[att.id] ?: ViewerAttachmentId.Persisted(att.id)) },
onRemove = { persistedDelete(att.id) },
securityManager = securityManager,
)
}
items(pending, key = { it.tempId }) { p ->
@@ -492,6 +529,7 @@ private fun AttachmentStrip(
repository = repository,
onOpenImage = { pendingOpen(p.tempId) },
onRemove = { pendingDelete(p.tempId) },
securityManager = securityManager,
)
}
}
@@ -513,6 +551,9 @@ private fun AttachmentThumbnail(
* into the bitmap decode path that would silently fail. */
onOpenImage: () -> Unit,
onRemove: () -> Unit,
/** v0.3.4.0 hotfix: suppress auto-lock around the external
* "open in system viewer" intent. */
securityManager: SecurityManager?,
) {
val isImage = mimeType.startsWith("image/")
val ctx = LocalContext.current
@@ -589,6 +630,10 @@ private fun AttachmentThumbnail(
setDataAndType(uri, mimeType)
addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
}
// v0.3.4.0 hotfix: opening an attachment in the
// system viewer also leaves the app — suppress
// the auto-lock on return.
securityManager?.beginExternalActivity()
ctx.startActivity(intent)
}.onFailure { err ->
// v0.3.1.3: distinguish "no handler" from "couldn't
@@ -16,6 +16,7 @@ import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import org.incido.compose.IncidoApplication
import org.incido.compose.share.LinkedShareComposer
import org.incido.domain.model.Hashtag
import org.incido.domain.model.Note
import org.incido.domain.model.NoteAttachment
@@ -135,8 +136,25 @@ class NoteEditorViewModel(
initialSharedText: String? = null,
/** v0.3.1.0 — pre-loaded image bytes from a share-into intent. */
initialSharedImages: List<SharedImage> = emptyList(),
/**
* v0.3.6.0 — `Intent.EXTRA_SUBJECT` from the share-into. Most
* browsers fill this with the page title for share-URL intents.
* Threaded through [LinkedShareComposer] so the note seeds with
* the title on its first line and the URL below. Null for plain
* text / image shares that have no subject.
*/
initialSharedSubject: String? = null,
) : ViewModel() {
/**
* v0.3.6.0 — the actual seed text used when there is no existing
* note. Composed from (subject, text) by the offline-only
* [LinkedShareComposer] so the resulting layout matches the rest
* of the app (title = first line, body = everything after).
*/
private val initialSeedContent: String =
LinkedShareComposer.compose(initialSharedSubject, initialSharedText)
private val _state = MutableStateFlow(NoteEditorUiState())
val state: StateFlow<NoteEditorUiState> = _state.asStateFlow()
@@ -220,7 +238,10 @@ class NoteEditorViewModel(
}
val seed = NoteEditorUiState(
existing = null,
content = initialSharedText.orEmpty(),
// v0.3.6.0: run the seed text through the LinkedShareComposer
// so a share-into URL seeds with the page title on the
// first line and the URL below (titleAndBody-friendly).
content = initialSeedContent,
isFavorite = false,
color = NoteColor.NONE,
hashtags = emptyList(),
@@ -446,6 +467,12 @@ class NoteEditorViewModel(
noteId: Long?,
initialSharedText: String? = null,
initialSharedImages: List<SharedImage> = emptyList(),
/**
* v0.3.6.0 — `Intent.EXTRA_SUBJECT` from the share-into.
* Threaded through [LinkedShareComposer] so a shared URL
* seeds the note with the page title on the first line.
*/
initialSharedSubject: String? = null,
): ViewModelProvider.Factory = viewModelFactory {
initializer {
val app = this[APPLICATION_KEY] as IncidoApplication
@@ -454,6 +481,7 @@ class NoteEditorViewModel(
noteId = noteId,
initialSharedText = initialSharedText,
initialSharedImages = initialSharedImages,
initialSharedSubject = initialSharedSubject,
)
}
}
@@ -12,18 +12,23 @@ import androidx.compose.foundation.layout.FlowRow
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import kotlinx.coroutines.withContext
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.GenericShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Add
import androidx.compose.material.icons.filled.AttachFile
import androidx.compose.material.icons.filled.CheckBox
import androidx.compose.material.icons.filled.Delete
import androidx.compose.material.icons.filled.Lock
import androidx.compose.material.icons.filled.Menu
import androidx.compose.material.icons.filled.MoreVert
import androidx.compose.material.icons.filled.PhotoCamera
@@ -82,6 +87,28 @@ private val DogEarShape = GenericShape { size, _ ->
close()
}
/**
* v0.3.3.5: fixed height for every note card on the list (originally
* 168.dp). v0.3.3.6: tuned down to 143.dp after feedback that 168.dp
* was too tall — ~15 % taller than the pre-0.3.3.5 wrap-content
* typical height (~124 dp for a title + 2-line body preview).
* Identical for every card whether or not the note carries hashtags,
* a body preview, or a checklist summary.
*/
private val CARD_HEIGHT_DP = 143.dp
/**
* v0.3.4.0: overlay palette for cards carrying an image thumbnail.
* The dark scrim (0.45 alpha black) always renders the card background
* dark, so every overlay (title, previews, timestamp, icons) must be
* light regardless of the active theme — in Light mode the default
* `onSurface` / `onSurfaceVariant` are dark and used to render all
* but invisible on dark photos.
*/
private val ThumbTitleColor = Color.White
private val ThumbSecondaryColor = Color.White.copy(alpha = 0.85f)
private val ThumbFavActiveColor = Color(0xFFFFD54F) // light amber — "favourited" stays distinguishable on dark images
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun NoteListScreen(
@@ -158,6 +185,9 @@ fun NoteListScreen(
onDelete = viewModel::delete,
onToggleFavorite = viewModel::toggleFavorite,
repository = repository,
// v0.3.5.0: ONLY notes whose ciphertext passed the
// startup trial-decrypt check earn the badge.
verifiedEncryptedIds = state.verifiedEncryptedNoteIds,
)
}
}
@@ -221,6 +251,12 @@ private fun NoteList(
onToggleFavorite: (Long, Boolean) -> Unit,
/** v0.3.1.0 — threaded through to [NoteCard] for thumbnail loading. */
repository: NoteRepository?,
/**
* v0.3.5.0 — ids of notes that were double-checked (trial GCM
* decrypt succeeded) by the startup / post-migration verification
* pass. Drives the "Encrypted" badge — nothing else does.
*/
verifiedEncryptedIds: Set<Long>,
) {
LazyColumn(
modifier = Modifier.fillMaxSize(),
@@ -239,6 +275,7 @@ private fun NoteList(
onDelete = { onDelete(note.id) },
onToggleFavorite = { onToggleFavorite(note.id, !note.isFavorite) },
repository = repository,
showEncryptionBadge = note.id in verifiedEncryptedIds,
)
}
}
@@ -261,6 +298,31 @@ private fun NoteList(
* item. The menu is designed to grow (Share, etc.) — additional
* entries are added as `DropdownMenuItem`s.
* - Card now uses `Modifier.combinedClickable` for click + long-click.
*
* v0.3.3.5:
* - Cards now have a FIXED height ([CARD_HEIGHT_DP]) so every card
* is the same size regardless of whether the note has tags, a body
* preview, or a checklist summary. Shipped at 168 dp.
* - A `Spacer(weight(1f))` pushes the timestamp row to the bottom of
* the fixed-height card so the layout stays visually consistent.
* - The left colour stripe now spans the full card height instead of
* a hardcoded 110 dp.
*
* v0.3.3.6:
* - [CARD_HEIGHT_DP] reduced 168 dp → 143 dp (~15 % shorter) after
* feedback that the v0.3.3.5 cards were too tall; still ~15 %
* taller than the pre-0.3.3.5 wrap-content typical.
*
* v0.3.4.0:
* - Attachment indicator: a paperclip icon appears on the right edge
* whenever the note carries at least one attachment (image, PDF,
* audio…). It sits in the same vertical column as the ⋮ overflow
* button (top) and the favourite star (bottom), exactly halfway
* between them via `Alignment.CenterEnd` on the fixed-height card.
* - Thumbnail readability: when an image thumbnail is present the
* scrim guarantees a dark background, so all overlay text/icons
* switch to a light palette regardless of theme (fixes invisible
* dark-on-dark text in Light mode).
*/
@OptIn(ExperimentalLayoutApi::class, androidx.compose.foundation.ExperimentalFoundationApi::class)
@Composable
@@ -272,6 +334,17 @@ private fun NoteCard(
/** v0.3.1.0 — used to load the first image attachment as a
* thumbnail background. Null disables the feature (still works). */
repository: NoteRepository?,
/**
* v0.3.5.0 — true only when this note's ciphertext was verified
* decryptable by the startup integrity check (never inferred from
* the settings flag alone).
*
* v0.3.5.1 — renders a small lock icon immediately to the LEFT of
* the timestamp in the card's bottom row (vertically centred with
* the date/time). Replaces the previous lock-plus-"Encrypted"-label
* Row that was centred at the card's bottom edge.
*/
showEncryptionBadge: Boolean = false,
) {
val (title, body) = Note.titleAndBody(note.content)
val bodyPreview = Note.bodyPreview(body)
@@ -306,6 +379,15 @@ private fun NoteCard(
else -> MaterialTheme.colorScheme.surface
}
// v0.3.4.0: overlay colours resolved once. With a thumbnail the
// scrim makes the background dark → force the light palette; plain
// cards keep the theme defaults.
val hasThumbnail = thumbnailBitmap != null
val titleColor = if (hasThumbnail) ThumbTitleColor else MaterialTheme.colorScheme.onSurface
val secondaryColor = if (hasThumbnail) ThumbSecondaryColor else MaterialTheme.colorScheme.onSurfaceVariant
val hashtagColor = if (hasThumbnail) ThumbTitleColor else MaterialTheme.colorScheme.primary
val favoriteActiveColor = if (hasThumbnail) ThumbFavActiveColor else MaterialTheme.colorScheme.primary
// v0.3.3.0: per-card menu visibility. Long-press opens; tapping
// outside the menu (or selecting an item) closes it.
var showMenu by remember { mutableStateOf(false) }
@@ -313,11 +395,20 @@ private fun NoteCard(
Card(
modifier = Modifier
.fillMaxWidth()
// v0.3.3.5: fixed card height — consistent size for every
// card, with or without tags / body preview / checklist.
.height(CARD_HEIGHT_DP)
.combinedClickable(
onClick = onClick,
onLongClick = { showMenu = true },
),
colors = CardDefaults.cardColors(containerColor = containerColor),
colors = CardDefaults.cardColors(
containerColor = containerColor,
// v0.3.4.0: on an image thumbnail the scrim darkens the
// background — default the content colour to light so any
// inheriting composables stay readable.
contentColor = if (hasThumbnail) Color.White else MaterialTheme.colorScheme.onSurface,
),
) {
// Inner Box hosts the (optional) thumbnail + scrim behind the
// existing Row of text content, with the dog-ear overlay
@@ -349,7 +440,10 @@ private fun NoteCard(
if (hasColor) {
Box(
modifier = Modifier
.size(width = 14.dp, height = 110.dp)
// v0.3.3.5: stripe spans the full height of
// the now-fixed-height card.
.fillMaxHeight()
.width(14.dp)
.background(
Brush.verticalGradient(
colors = listOf(
@@ -368,6 +462,7 @@ private fun NoteCard(
Text(
text = title,
style = MaterialTheme.typography.titleMedium,
color = titleColor,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
modifier = Modifier.weight(1f),
@@ -378,7 +473,7 @@ private fun NoteCard(
Text(
text = bodyPreview,
style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant,
color = secondaryColor,
maxLines = 2,
overflow = TextOverflow.Ellipsis,
)
@@ -390,32 +485,54 @@ private fun NoteCard(
Icons.Default.CheckBox,
contentDescription = null,
modifier = Modifier.size(14.dp),
tint = MaterialTheme.colorScheme.onSurfaceVariant,
tint = secondaryColor,
)
Spacer(Modifier.size(6.dp))
Text(
text = checklistSummary,
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
color = secondaryColor,
)
}
}
if (note.hashtags.isNotEmpty()) {
Spacer(modifier = Modifier.padding(top = 4.dp))
HashtagRow(hashtags = note.hashtags)
HashtagRow(
hashtags = note.hashtags,
tagColor = hashtagColor,
overflowColor = secondaryColor,
)
}
// v0.3.3.5: flexible spacer pushes the timestamp to
// the bottom of the fixed-height card so every card
// has a consistent layout.
Spacer(modifier = Modifier.weight(1f))
// v0.3.3.0: bottom row now only shows the
// timestamp — the overflow (long-press) menu holds
// the destructive action.
Spacer(modifier = Modifier.padding(top = 8.dp))
//
// v0.3.5.1: when the note is verified-encrypted a
// 14 dp lock icon sits immediately to the LEFT of
// the timestamp in this same row, vertically
// centred via the row's Alignment.CenterVertically
// — consistent placement on every card.
Row(
modifier = Modifier.fillMaxWidth(),
verticalAlignment = Alignment.CenterVertically,
) {
if (showEncryptionBadge) {
Icon(
Icons.Filled.Lock,
contentDescription = "Encrypted",
tint = secondaryColor,
modifier = Modifier.size(14.dp),
)
Spacer(Modifier.size(4.dp))
}
Text(
text = rememberRelativeTimestamp(note.updatedAt),
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
color = secondaryColor,
)
}
}
@@ -445,7 +562,7 @@ private fun NoteCard(
Icon(
Icons.Filled.MoreVert,
contentDescription = "More actions",
tint = MaterialTheme.colorScheme.onSurfaceVariant,
tint = secondaryColor,
)
}
DropdownMenu(
@@ -469,6 +586,16 @@ private fun NoteCard(
}
}
// v0.3.5.1: the "Encrypted" indicator moved from a
// bottom-centre Row (lock icon + "Encrypted" label) to a
// lock icon sitting immediately to the left of the
// timestamp inside the card's bottom row, so its position
// stays consistent on every card. Rendered ONLY when the
// note passed the verification pass (trial GCM decrypt
// with the current Keystore key); re-checked on every app
// open, so a corrupted or re-keyed row silently drops it
// until it verifies again.
// Hotfix: favorite star moved from the title row to the
// bottom-right corner, vertically aligned with the
// three-dot overflow button above.
@@ -477,11 +604,37 @@ private fun NoteCard(
Icon(
imageVector = if (note.isFavorite) Icons.Filled.Star else Icons.Outlined.StarOutline,
contentDescription = if (note.isFavorite) "Unfavorite" else "Favorite",
tint = if (note.isFavorite) MaterialTheme.colorScheme.primary
else MaterialTheme.colorScheme.onSurfaceVariant,
tint = if (note.isFavorite) favoriteActiveColor
else secondaryColor,
)
}
}
// v0.3.4.0: attachment indicator — a paperclip shown
// whenever the note carries at least one attachment (any
// type: image, PDF, audio…). Aligned CenterEnd so it sits
// in the same vertical column as the ⋮ overflow button
// above and the favourite star below, exactly halfway
// between them: the card has a fixed height and both
// neighbours are anchored symmetrically in the top / bottom
// corners (their 24 dp glyphs centred in 48 dp IconButtons
// with end = 4.dp padding ⇒ glyph centres at 28 dp from the
// right edge; the midpoint of those two centres IS the card
// centre). The `end = 16.dp` offset places this bare 24 dp
// Icon's glyph centre at the same 28 dp column. Rendered as
// a plain Icon (not an IconButton) so it never intercepts
// the whole-card tap that opens the editor.
if (note.attachments.isNotEmpty()) {
Icon(
Icons.Filled.AttachFile,
contentDescription = "Has attachments",
tint = secondaryColor,
modifier = Modifier
.align(Alignment.CenterEnd)
.padding(end = 16.dp)
.size(24.dp),
)
}
}
}
}
@@ -491,10 +644,19 @@ private fun NoteCard(
* compact FlowRow of label-styled text; if there are more, renders a
* "+N" abbreviation indicator. Hidden entirely by the caller when
* [hashtags] is empty.
*
* v0.3.4.0: colours are supplied by the caller — light palette on
* image-thumbnail cards, theme defaults elsewhere.
*/
@OptIn(ExperimentalLayoutApi::class)
@Composable
private fun HashtagRow(hashtags: List<String>) {
private fun HashtagRow(
hashtags: List<String>,
/** Colour for the visible "#tag" chips. */
tagColor: Color,
/** Colour for the "+N" overflow indicator. */
overflowColor: Color,
) {
val visible = hashtags.take(3)
val overflow = hashtags.size - visible.size
FlowRow(
@@ -505,15 +667,15 @@ private fun HashtagRow(hashtags: List<String>) {
Text(
text = "#$tag",
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.primary,
color = tagColor,
)
}
if (overflow > 0) {
Text(
text = "+$overflow",
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
color = overflowColor,
)
}
}
}
}
@@ -32,6 +32,15 @@ data class NoteListUiState(
val isSearchActive: Boolean = false,
val filter: NoteFilter = NoteFilter.Home,
val recentHashtags: List<HashtagUsage> = emptyList(),
/**
* v0.3.5.0 — note ids whose ciphertext was **verified** (trial
* GCM-decrypt succeeded) by the startup / post-migration check.
* This — and ONLY this — drives the "Encrypted" badge on cards.
* Re-populated on every app open.
*/
val verifiedEncryptedNoteIds: Set<Long> = emptySet(),
/** Encrypted rows that FAILED verification (corrupted / wrong key). */
val unverifiedEncryptedNoteCount: Int = 0,
) {
val isEmpty: Boolean get() = !isLoading && notes.isEmpty() && !isSearchActive && filter == NoteFilter.Home
val noResults: Boolean get() = !isLoading && notes.isEmpty() && !isEmpty
@@ -40,6 +49,8 @@ data class NoteListUiState(
@OptIn(ExperimentalCoroutinesApi::class, FlowPreview::class)
class NoteListViewModel(
private val repository: NoteRepository,
/** v0.3.5.0 — source of the verified-encryption badge set. */
private val encryptionVerifier: org.incido.compose.data.security.EncryptionVerifier? = null,
) : ViewModel() {
private val filterMode = MutableStateFlow<NoteFilter>(NoteFilter.Home)
@@ -64,7 +75,7 @@ class NoteListViewModel(
}
}
val uiState: StateFlow<NoteListUiState> = combine(
private val baseUiState: StateFlow<NoteListUiState> = combine(
notesFlow,
_isSearchActive,
filterMode,
@@ -85,6 +96,28 @@ class NoteListViewModel(
initialValue = NoteListUiState(),
)
/**
* v0.3.5.0 — merge the verification results into the UI state. The
* verifier re-checks every encrypted row on every app open (and
* after each encryption migration), so a card's badge always
* reflects a fresh proof-of-decryptability, never just the
* settings flag.
*/
val uiState: StateFlow<NoteListUiState> = combine(
baseUiState,
encryptionVerifier?.verification
?: kotlinx.coroutines.flow.flowOf(null),
) { state, verification ->
state.copy(
verifiedEncryptedNoteIds = verification?.verifiedNoteIds ?: emptySet(),
unverifiedEncryptedNoteCount = verification?.failedNoteIds?.size ?: 0,
)
}.stateIn(
scope = viewModelScope,
started = SharingStarted.WhileSubscribed(5_000),
initialValue = NoteListUiState(),
)
fun setFilter(filter: NoteFilter) {
filterMode.value = filter
// v0.3.1.0: search is now context-aware on Home / Favorites /
@@ -122,7 +155,10 @@ class NoteListViewModel(
val Factory: ViewModelProvider.Factory = viewModelFactory {
initializer {
val app = this[APPLICATION_KEY] as IncidoApplication
NoteListViewModel(app.container.noteRepository)
NoteListViewModel(
repository = app.container.noteRepository,
encryptionVerifier = app.container.encryptionVerifier,
)
}
}
}
@@ -68,7 +68,9 @@ fun PassphraseDialog(
mode: PassphraseDialogMode = PassphraseDialogMode.EXPORT,
) {
val context = LocalContext.current
val isExport = mode == PassphraseDialogMode.EXPORT
// v0.3.6.0: use the enum helper so RECOVERY_EXPORT shares the
// EXPORT chrome (policy check, Generate/Copy, Confirm field).
val isExport = mode.isExport
var passphrase by remember { mutableStateOf("") }
var confirm by remember { mutableStateOf("") }
var revealed by remember { mutableStateOf(false) }
@@ -105,16 +107,37 @@ fun PassphraseDialog(
}
}
val title = if (isExport) "Encrypt backup" else "Decrypt backup"
val intro = if (isExport) {
"Choose a passphrase to protect this backup. " +
"You'll need it again to restore. Lost passphrases " +
"cannot be recovered."
} else {
"Enter the passphrase you used when this backup was created. " +
"Lost passphrases cannot be recovered."
// v0.3.6.0: the recovery-key flows reuse this dialog but get
// their own titles / copy so the user knows they're protecting
// the encryption key, not a note backup.
val title = when (mode) {
PassphraseDialogMode.EXPORT -> "Encrypt backup"
PassphraseDialogMode.IMPORT -> "Decrypt backup"
PassphraseDialogMode.RECOVERY_EXPORT -> "Protect recovery key"
PassphraseDialogMode.RECOVERY_IMPORT -> "Unlock recovery key"
}
val intro = when (mode) {
PassphraseDialogMode.EXPORT ->
"Choose a passphrase to protect this backup. " +
"You'll need it again to restore. Lost passphrases " +
"cannot be recovered."
PassphraseDialogMode.IMPORT ->
"Enter the passphrase you used when this backup was created. " +
"Lost passphrases cannot be recovered."
PassphraseDialogMode.RECOVERY_EXPORT ->
"Choose a passphrase to protect your encryption key. " +
"You'll need this passphrase AND the exported file to " +
"restore the key on another device. Store them in " +
"separate safe places."
PassphraseDialogMode.RECOVERY_IMPORT ->
"Enter the passphrase you used when you exported this " +
"recovery key. Lost passphrases cannot be recovered."
}
val confirmLabel = when (mode) {
PassphraseDialogMode.EXPORT -> "Encrypt & export"
PassphraseDialogMode.RECOVERY_EXPORT -> "Encrypt & export"
else -> "Continue"
}
val confirmLabel = if (isExport) "Encrypt & export" else "Continue"
AlertDialog(
onDismissRequest = onDismiss,
@@ -229,8 +252,24 @@ fun PassphraseDialog(
)
}
/** v0.3.3.0: which flow is requesting a passphrase. */
enum class PassphraseDialogMode { EXPORT, IMPORT }
/**
* v0.3.3.0: which flow is requesting a passphrase. The EXPORT /
* IMPORT pair covers the encrypted backup flows; v0.3.6.0 adds the
* RECOVERY_EXPORT / RECOVERY_IMPORT pair for the at-rest key
* recovery file (UI is the same — [PassphraseDialog] just looks at
* the EXPORT vs IMPORT flag and shows the policy / Generate / Copy
* chrome accordingly).
*/
enum class PassphraseDialogMode {
EXPORT, IMPORT,
RECOVERY_EXPORT, RECOVERY_IMPORT,
;
/** True for the EXPORT-mode chrome (Generate / Copy / Confirm /
* password-policy check). Import variants skip those because
* an existing passphrase may predate the current policy. */
val isExport: Boolean get() = this == EXPORT || this == RECOVERY_EXPORT
}
private fun copyToClipboard(context: Context, value: String) {
if (value.isEmpty()) return
@@ -51,6 +51,7 @@ import androidx.lifecycle.viewmodel.compose.viewModel
import kotlinx.coroutines.launch
import org.incido.compose.data.backup.BackupPreview
import org.incido.compose.data.backup.EncryptedBackupCodec
import org.incido.compose.data.security.SecurityManager
import org.incido.compose.data.settings.AutoLockTimeout
import org.incido.compose.data.settings.ThemeMode
@@ -86,6 +87,12 @@ fun SettingsScreen(
onBack: () -> Unit,
onRequestPinSetup: () -> Unit,
onRequestPinChange: () -> Unit,
/**
* v0.3.4.0 hotfix: used to suppress auto-lock while the user is
* inside the backup export/import SAF pickers. Null disables the
* suppression (the pre-0.3.4.0 behaviour).
*/
securityManager: SecurityManager? = null,
viewModel: SettingsViewModel = viewModel(factory = SettingsViewModel.Factory),
) {
val settings by viewModel.userSettings.collectAsStateWithLifecycle()
@@ -103,6 +110,16 @@ fun SettingsScreen(
var pendingImportPassphrase by remember { mutableStateOf<CharArray?>(null) }
var pendingPreview by remember { mutableStateOf<BackupPreview?>(null) }
var showTimeoutDialog by remember { mutableStateOf(false) }
// v0.3.6.0: recovery-key flow state. The export/import share the
// PassphraseDialog with the backup flow (via [pendingPassphraseMode]
// below) but use dedicated URIs + a separate confirmation dialog
// before importing (importing a recovery key overwrites the
// current key, which can render previously-encrypted rows
// unreadable).
var pendingRecoveryExportUri by remember { mutableStateOf<android.net.Uri?>(null) }
var pendingRecoveryImportUri by remember { mutableStateOf<android.net.Uri?>(null) }
var pendingRecoveryImportPassphrase by remember { mutableStateOf<CharArray?>(null) }
var showRecoveryImportWarning by remember { mutableStateOf(false) }
// SAF launchers
val exportLauncher = rememberLauncherForActivityResult(
@@ -161,6 +178,33 @@ fun SettingsScreen(
}
}
// v0.3.6.0: SAF launchers for the recovery-key file. Distinct
// from the backup export/import above — the recovery key is
// opaque bytes, not JSON, so we ask the file picker for
// application/octet-stream.
val recoveryExportLauncher = rememberLauncherForActivityResult(
contract = ActivityResultContracts.CreateDocument("application/octet-stream"),
) { uri ->
if (uri != null) {
pendingRecoveryExportUri = uri
// Reuse the existing PassphraseDialog in EXPORT mode. The
// onConfirm handler below routes based on which URI is set.
pendingPassphraseMode = PassphraseDialogMode.RECOVERY_EXPORT
showPassphraseDialog = true
}
}
val recoveryImportLauncher = rememberLauncherForActivityResult(
contract = ActivityResultContracts.OpenDocument(),
) { uri ->
if (uri == null) return@rememberLauncherForActivityResult
pendingRecoveryImportUri = uri
// Don't ask for the passphrase yet — first show the user a
// warning dialog explaining what import-overwrite does, and
// route to PassphraseDialog.IMPORT on confirm.
showRecoveryImportWarning = true
}
// Snackbar effect
LaunchedEffect(snackbar) {
snackbar?.let {
@@ -200,6 +244,7 @@ fun SettingsScreen(
settings = settings,
onSecurityEnabled = viewModel::setSecurityEnabled,
onEncryptionEnabled = viewModel::setEncryptionEnabled,
onBlockScreenshots = viewModel::setBlockScreenshots,
onPinToggle = { on ->
viewModel.setLockMode(if (on) SettingsViewModel.LockMode.PIN else SettingsViewModel.LockMode.NONE)
if (on) onRequestPinSetup()
@@ -213,14 +258,44 @@ fun SettingsScreen(
val app = context.applicationContext as org.incido.compose.IncidoApplication
app.container.securityManager.isBiometricAvailable()
},
// v0.3.6.0: recovery-key export/import rows. Both
// are gated on encryption being active (you can't
// back up a key that doesn't exist yet).
onExportRecoveryKey = {
if (!settings.isEncryptionActive) {
scope.launch {
snackbarHostState.showSnackbar(
"Enable encryption first — there's no key to back up yet.",
)
}
} else {
// v0.3.4.0 hotfix: SAF picker backgrounds the app.
securityManager?.beginExternalActivity()
val stamp = java.text.SimpleDateFormat("yyyy-MM-dd", java.util.Locale.US)
.format(java.util.Date())
recoveryExportLauncher.launch("incido-recovery-$stamp.inckey")
}
},
onImportRecoveryKey = {
securityManager?.beginExternalActivity()
recoveryImportLauncher.launch(arrayOf("application/octet-stream", "*/*"))
},
)
BackupSection(
onExport = {
val stamp = java.text.SimpleDateFormat("yyyy-MM-dd", java.util.Locale.US)
.format(java.util.Date())
// v0.3.4.0 hotfix: the create-document picker
// backgrounds the app — with Auto-Lock = Immediate
// the return trip used to land on the lock screen.
securityManager?.beginExternalActivity()
exportLauncher.launch("incido-backup-$stamp.${org.incido.compose.data.backup.BackupCodec.FILE_EXTENSION}")
},
onImport = { importLauncher.launch(arrayOf("application/json", "*/*")) },
onImport = {
// v0.3.4.0 hotfix: same suppression for the import picker.
securityManager?.beginExternalActivity()
importLauncher.launch(arrayOf("application/json", "*/*"))
},
)
AboutSection(
version = SettingsViewModel.APP_VERSION,
@@ -270,53 +345,105 @@ fun SettingsScreen(
)
}
if (showPassphraseDialog && (pendingPassphraseUri != null || pendingImportUri != null)) {
// v0.3.6.0: the dialog opens whenever any of the four URI slots
// is set — backup export, backup import (after the user picks an
// encrypted file), recovery export, or recovery import. The mode
// flag tells the onConfirm handler how to route.
val showPassphrase = showPassphraseDialog &&
(pendingPassphraseUri != null ||
pendingImportUri != null ||
pendingRecoveryExportUri != null ||
pendingRecoveryImportUri != null)
if (showPassphrase) {
PassphraseDialog(
mode = pendingPassphraseMode,
onConfirm = { chars ->
val exportUri = pendingPassphraseUri
val importUri = pendingImportUri
val recoveryExportUri = pendingRecoveryExportUri
val recoveryImportUri = pendingRecoveryImportUri
val mode = pendingPassphraseMode
showPassphraseDialog = false
pendingPassphraseUri = null
if (mode == PassphraseDialogMode.EXPORT) {
pendingExportUri = null
if (exportUri != null) {
scope.launch { viewModel.exportEncrypted(exportUri, chars) }
}
} else {
// IMPORT — run preview with the entered passphrase.
//
// v0.3.3.3 hotfix: keep a retained COPY of the
// passphrase for the confirm-dialog import step.
// EncryptedBackupCodec.decrypt() zeroes whatever
// CharArray it's handed, and the previous code
// wiped the cached copy immediately after the
// preview — so the Import button called
// viewModel.import(uri, null), which threw
// "Encrypted backup requires a passphrase" inside
// an unguarded coroutine and crashed the app.
pendingImportPassphrase = chars.copyOf()
if (importUri != null) {
scope.launch {
// `chars` is consumed (zeroed) by the
// decrypt step; the retained copy survives.
val preview = try {
viewModel.previewImport(importUri, passphrase = chars)
} catch (_: Exception) {
null
}
if (preview == null) {
pendingImportUri = null
pendingImportPassphrase?.fill('0')
pendingImportPassphrase = null
snackbarHostState.showSnackbar("Incorrect passphrase.")
} else {
pendingPreview = preview
}
pendingImportUri = null
pendingRecoveryExportUri = null
// pendingRecoveryImportUri is drained by the warning
// dialog's confirm handler instead — we don't null it
// here so the warning flow stays coherent. Actually we
// do: the warning dialog opens the passphrase dialog,
// so by the time we get here the URI is what we want.
pendingRecoveryImportUri = null
when (mode) {
PassphraseDialogMode.EXPORT -> {
pendingExportUri = null
if (exportUri != null) {
scope.launch { viewModel.exportEncrypted(exportUri, chars) }
} else {
chars.fill('0')
}
}
PassphraseDialogMode.IMPORT -> {
// v0.3.3.3 hotfix: keep a retained COPY of the
// passphrase for the confirm-dialog import step.
// EncryptedBackupCodec.decrypt() zeroes whatever
// CharArray it's handed, and the previous code
// wiped the cached copy immediately after the
// preview — so the Import button called
// viewModel.import(uri, null), which threw
// "Encrypted backup requires a passphrase"
// inside an unguarded coroutine and crashed
// the app.
pendingImportPassphrase = chars.copyOf()
if (importUri != null) {
scope.launch {
// `chars` is consumed (zeroed) by the
// decrypt step; the retained copy survives.
val preview = try {
viewModel.previewImport(importUri, passphrase = chars)
} catch (_: Exception) {
null
}
if (preview == null) {
pendingImportUri = null
pendingImportPassphrase?.fill('0')
pendingImportPassphrase = null
snackbarHostState.showSnackbar("Incorrect passphrase.")
} else {
pendingPreview = preview
}
}
} else {
chars.fill('0')
}
}
PassphraseDialogMode.RECOVERY_EXPORT -> {
if (recoveryExportUri != null) {
// Same retained-COPY pattern: exportRecoveryKey
// zeroes the CharArray it consumes.
val retained = chars.copyOf()
scope.launch {
val ok = viewModel.exportRecoveryKey(recoveryExportUri, retained)
retained.fill('0')
if (!ok) {
// Snackbar is already set by the VM on failure.
}
}
} else {
chars.fill('0')
}
}
PassphraseDialogMode.RECOVERY_IMPORT -> {
if (recoveryImportUri != null) {
// The codec zeroes the CharArray it consumes;
// we don't need a retained copy because the
// import path is single-step (no preview/confirm
// dance like the backup import).
scope.launch {
viewModel.importRecoveryKey(recoveryImportUri, chars)
}
} else {
chars.fill('0')
}
} else {
chars.fill('0')
}
}
},
@@ -326,6 +453,10 @@ fun SettingsScreen(
pendingImportUri = null
pendingImportPassphrase?.fill('0')
pendingImportPassphrase = null
pendingRecoveryExportUri = null
pendingRecoveryImportUri = null
pendingRecoveryImportPassphrase?.fill('0')
pendingRecoveryImportPassphrase = null
},
)
}
@@ -404,6 +535,51 @@ fun SettingsScreen(
)
}
// v0.3.6.0: warning dialog before importing a recovery key.
// Importing overwrites the at-rest key, which can leave any
// previously-encrypted notes unreadable unless they came from
// the same backup the recovery key was made for. Force the user
// to acknowledge the consequence before we open the passphrase
// dialog.
if (showRecoveryImportWarning) {
AlertDialog(
onDismissRequest = {
showRecoveryImportWarning = false
pendingRecoveryImportUri = null
},
title = { Text("Replace encryption key?") },
text = {
Text(
"Importing a recovery key replaces the AES key Incido " +
"uses to encrypt your notes. Notes encrypted with the " +
"current key will become unreadable unless they came " +
"from the same backup as the imported key.\n\n" +
"Only continue if you:\n" +
" • are restoring to a fresh install, OR\n" +
" • have already imported the matching backup.\n\n" +
"You'll be asked for the passphrase you set when you " +
"exported the key.",
style = MaterialTheme.typography.bodyMedium,
)
},
confirmButton = {
TextButton(onClick = {
showRecoveryImportWarning = false
// Drain the URI here — the PassphraseDialog will
// route to importRecoveryKey on confirm.
pendingPassphraseMode = PassphraseDialogMode.RECOVERY_IMPORT
showPassphraseDialog = true
}) { Text("Continue") }
},
dismissButton = {
TextButton(onClick = {
showRecoveryImportWarning = false
pendingRecoveryImportUri = null
}) { Text("Cancel") }
},
)
}
if (showTimeoutDialog) {
TimeoutDialog(
current = settings.autoLockTimeout,
@@ -419,7 +595,7 @@ fun SettingsScreen(
is SettingsViewModel.MigrationState.Running -> {
AlertDialog(
onDismissRequest = {},
title = { Text("Re-encrypting notes…") },
title = { Text("Updating note encryption…") },
text = {
Column {
Text("This can take a few seconds. Don't close the app.")
@@ -528,11 +704,21 @@ private fun SecuritySection(
settings: org.incido.compose.data.settings.UserSettings,
onSecurityEnabled: (Boolean) -> Unit,
onEncryptionEnabled: (Boolean) -> Unit,
onBlockScreenshots: (Boolean) -> Unit,
onPinToggle: (Boolean) -> Unit,
onBiometricToggle: (Boolean) -> Unit,
onResetPin: () -> Unit,
onTimeoutClick: () -> Unit,
biometricAvailable: Boolean,
/**
* v0.3.6.0: recovery-key export/import rows. Both are no-ops when
* encryption isn't active; the parent shows a snackbar so the
* user knows why nothing happened. We don't disable the rows in
* the UI because users may have just turned encryption off and
* still want to import an old key first.
*/
onExportRecoveryKey: () -> Unit,
onImportRecoveryKey: () -> Unit,
) {
SettingsSection(title = "Security") {
Column(modifier = Modifier.padding(horizontal = 16.dp, vertical = 8.dp)) {
@@ -573,18 +759,17 @@ private fun SecuritySection(
HorizontalDivider(modifier = Modifier.padding(vertical = 4.dp))
SettingsToggle(
title = "Encrypt notes at rest",
// v0.3.3.1 hotfix: greyed out until Security is on
// AND a PIN or Biometric is configured. Matches the
// intent of `UserSettings.isEncryptionActive` (already
// gated on the securityEnabled flag) plus the lock
// requirement so the encryption key can't be set up
// against an "anyone-can-open" lock state.
// v0.3.5.0: real in-place encryption — note content and
// attachment bytes are AES-256-GCM encrypted with the
// Android-Keystore key the moment the toggle flips (no
// restart). Greyed out until Security is on AND a PIN or
// Biometric is configured (v0.3.3.1 gating kept).
subtitle = if (settings.securityEnabled && (settings.pinEnabled || settings.useBiometric)) {
"AES-256 encryption for the local database. " +
"Toggling requires an app restart."
"AES-256 encryption for your notes and attachments. " +
"Applied in place — takes effect immediately."
} else {
"AES-256 encryption for the local database. " +
"Toggling requires an app restart. " +
"AES-256 encryption for your notes and attachments. " +
"Applied in place — takes effect immediately. " +
"Enable Security and set a PIN or Biometric first."
},
checked = settings.encryptionEnabled,
@@ -593,6 +778,37 @@ private fun SecuritySection(
enabled = settings.securityEnabled && (settings.pinEnabled || settings.useBiometric),
onCheckedChange = onEncryptionEnabled,
)
// v0.3.6.0: recovery-key export / import. Both rows are
// always tappable — if encryption isn't active, the parent
// shows a snackbar telling the user to enable it first.
// We don't disable the rows because users may have just
// turned encryption off and still want to import an old
// key first.
HorizontalDivider(modifier = Modifier.padding(vertical = 4.dp))
SettingsRow(
title = "Export encryption key",
subtitle = "Save the AES key that protects your notes to " +
"a file. You'll set a passphrase. Store the file " +
"and passphrase in separate safe places.",
onClick = onExportRecoveryKey,
)
HorizontalDivider(modifier = Modifier.padding(vertical = 4.dp))
SettingsRow(
title = "Import encryption key",
subtitle = "Restore a previously-exported key. This " +
"replaces the current key — existing notes encrypted " +
"with the old key will become unreadable unless they " +
"came from the same backup.",
onClick = onImportRecoveryKey,
)
HorizontalDivider(modifier = Modifier.padding(vertical = 4.dp))
SettingsToggle(
title = "Block screenshots",
subtitle = "Prevent screenshots, screen recording, and " +
"app-switcher previews while Incido is open. On by default.",
checked = settings.blockScreenshots,
onCheckedChange = onBlockScreenshots,
)
if (settings.isLockActive) {
HorizontalDivider(modifier = Modifier.padding(vertical = 4.dp))
SettingsRow(
@@ -14,8 +14,12 @@ import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.launch
import org.incido.compose.IncidoApplication
import org.incido.compose.data.backup.BackupManager
import org.incido.compose.data.security.AesGcmFieldCipher
import org.incido.compose.data.security.EncryptionVerifier
import org.incido.compose.data.security.ObjectBoxKeyProvider
import org.incido.compose.data.security.SecurityManager
import org.incido.data.crypto.CipherHolder
import org.incido.data.crypto.NoteCryptoService
import org.incido.compose.data.settings.AutoLockTimeout
import org.incido.compose.data.settings.SettingsRepository
import org.incido.compose.data.settings.ThemeMode
@@ -42,6 +46,9 @@ class SettingsViewModel(
private val security: SecurityManager,
private val objectBoxKeyProvider: ObjectBoxKeyProvider,
private val backupManager: BackupManager,
private val noteCryptoService: NoteCryptoService,
private val cipherHolder: CipherHolder,
private val encryptionVerifier: EncryptionVerifier,
) : ViewModel() {
val userSettings: StateFlow<UserSettings> = settings.userSettingsFlow.stateIn(
@@ -82,46 +89,91 @@ class SettingsViewModel(
settings.setSecurityEnabled(true)
return@launch
}
// Disabling: clear every sub-flag + wipe the stored PIN
// hash/salt + drop the ObjectBox encryption key.
settings.setSecurityEnabled(false)
settings.setPinEnabled(false)
settings.setEncryptionEnabled(false)
settings.setUseBiometric(false)
security.clearPin()
objectBoxKeyProvider.deleteKey()
_snackbar.value = "Security disabled."
// Disabling: decrypt any encrypted rows first (so the notes
// remain readable once the key goes), then clear every sub-flag
// + wipe the stored PIN hash/salt + drop the encryption key.
// v0.3.5.0: real decrypt sweep instead of the old no-op.
_migrationState.value = MigrationState.Running(0f)
try {
if (cipherHolder.cipher != null) {
noteCryptoService.decryptAllInPlace { done, total ->
_migrationState.value = MigrationState.Running(
if (total == 0) 1f else done.toFloat() / total,
)
}
cipherHolder.cipher = null
}
settings.setSecurityEnabled(false)
settings.setPinEnabled(false)
settings.setEncryptionEnabled(false)
settings.setUseBiometric(false)
security.clearPin()
objectBoxKeyProvider.deleteKey()
_migrationState.value = MigrationState.Idle
encryptionVerifier.checkNow()
_snackbar.value = "Security disabled."
} catch (t: Throwable) {
_migrationState.value = MigrationState.Failed(t.message ?: "Decryption failed")
}
}
/**
* v0.3.5.0 — the toggle now performs a REAL in-place migration and
* takes effect immediately (no app restart):
*
* - ENABLE: generate/unwrap the Keystore key, install the cipher
* into the shared [CipherHolder] (so every concurrent write is
* already encrypted), then sweep every plaintext note +
* attachment row into ciphertext with live progress.
* - DISABLE: decrypt every row back to plaintext first, then
* remove the cipher from the holder and delete the key.
*
* Either way the startup verifier re-checks afterwards, so the
* "Encrypted" badge on the cards always reflects rows that are
* provably decryptable.
*/
fun setEncryptionEnabled(enabled: Boolean) = viewModelScope.launch {
if (!_migrationState.value.canStart) return@launch
// v0.3.2.0 MVP: toggling encryption requires the app to be
// restarted so the BoxStore can be re-opened with the right
// key. We flip the flag and surface a migration notice — the
// full BoxStore re-open is handled by AppContainer on next
// process start.
_migrationState.value = MigrationState.Running(0f)
try {
if (enabled) {
// Generate the key now so it's ready for the next launch.
// Key first (idempotent), cipher into the holder, sweep.
objectBoxKeyProvider.getOrCreateKey()
cipherHolder.cipher = AesGcmFieldCipher(objectBoxKeyProvider)
noteCryptoService.encryptAllInPlace { done, total ->
_migrationState.value = MigrationState.Running(
if (total == 0) 1f else done.toFloat() / total,
)
}
settings.setEncryptionEnabled(true)
_migrationState.value = MigrationState.Done(
message = "Notes are now encrypted on this device.",
)
} else {
noteCryptoService.decryptAllInPlace { done, total ->
_migrationState.value = MigrationState.Running(
if (total == 0) 1f else done.toFloat() / total,
)
}
cipherHolder.cipher = null
objectBoxKeyProvider.deleteKey()
settings.setEncryptionEnabled(false)
_migrationState.value = MigrationState.Done(
message = "Notes are now stored unencrypted.",
)
}
_migrationState.value = MigrationState.Done(
message = if (enabled) {
"Encryption will be enabled on next app launch."
} else {
"Encryption will be disabled on next app launch."
},
)
// Re-verify so the badge set matches the new on-disk state.
encryptionVerifier.checkNow()
} catch (t: Throwable) {
_migrationState.value = MigrationState.Failed(t.message ?: "Migration failed")
}
}
/** v0.3.5.0 — FLAG_SECURE screenshot / recording blocking. */
fun setBlockScreenshots(enabled: Boolean) = viewModelScope.launch {
settings.setBlockScreenshots(enabled)
}
/**
* v0.3.3.0: switch the lock mode. Mutually exclusive — enabling
* one wipes the other. Switching to [LockMode.NONE] disables both
@@ -193,6 +245,70 @@ class SettingsViewModel(
_snackbar.value = "Imported $count note(s)."
}
// --- v0.3.6.0 recovery key ---
/**
* Write the at-rest encryption key to a user-chosen SAF uri,
* wrapped with [passphrase]. Caller is responsible for calling
* `securityManager.beginExternalActivity()` before launching the
* picker so the SAF round-trip doesn't trigger an auto-lock.
*
* @param uri The destination content uri.
* @param passphrase The passphrase the user entered in the
* export flow (zeroed by this method on completion).
* @return `true` on success, `false` if there is no encryption
* key to export (the caller should disable the export
* row until encryption is active — see SettingsScreen).
*/
suspend fun exportRecoveryKey(uri: android.net.Uri, passphrase: CharArray): Boolean {
if (!objectBoxKeyProvider.hasKey()) {
_snackbar.value = "Encryption isn't active — nothing to back up."
return false
}
try {
objectBoxKeyProvider.exportRecoveryKey(uri, passphrase)
_snackbar.value =
"Recovery key exported. Store the file and passphrase in separate safe places."
return true
} catch (e: org.incido.compose.data.security.ObjectBoxKeyProvider.RecoveryKeyException) {
_snackbar.value = "Couldn't write recovery key: ${e.message}"
return false
}
}
/**
* Read a recovery envelope from [uri] with [passphrase] and
* install it as the current field key. After install we swap in a
* fresh [AesGcmFieldCipher] that wraps the new key, and re-run
* the encryption verifier so the "Encrypted" badge reflects the
* new state.
*
* If the user already had encrypted rows the new key makes those
* rows unreadable (GCM tag fail → row enters [failedNoteIds] in
* the verifier). That's expected — a recovery key only matches
* when the user is moving to a fresh install (or intentionally
* rotating). The UI surfaces a warning dialog before this call.
*/
suspend fun importRecoveryKey(uri: android.net.Uri, passphrase: CharArray): Boolean {
try {
val overwroteExisting = objectBoxKeyProvider.importRecoveryKey(uri, passphrase)
// Swap the live cipher to point at the freshly-installed key.
// We build a new wrapper that re-reads the (just-persisted)
// wrapped blob — no need to re-implement the unwrap here.
cipherHolder.cipher = AesGcmFieldCipher(objectBoxKeyProvider)
encryptionVerifier.checkNow()
_snackbar.value = if (overwroteExisting) {
"Recovery key installed. Previously-encrypted notes will appear as unverified."
} else {
"Recovery key installed."
}
return true
} catch (e: org.incido.compose.data.security.ObjectBoxKeyProvider.RecoveryKeyException) {
_snackbar.value = e.message ?: "Couldn't import recovery key."
return false
}
}
// --- Migration dialog ---
fun acknowledgeMigration() {
@@ -217,7 +333,7 @@ class SettingsViewModel(
/** The version string baked into backup payloads and shown on
* the About card. Mirrors `app/build.gradle.kts` `versionName`
* — if you bump one, bump both. */
const val APP_VERSION = "0.3.3.4"
const val APP_VERSION = "0.3.6.0"
val Factory: ViewModelProvider.Factory = viewModelFactory {
initializer {
@@ -228,6 +344,9 @@ class SettingsViewModel(
security = c.securityManager,
objectBoxKeyProvider = c.objectBoxKeyProvider,
backupManager = c.backupManager,
noteCryptoService = c.noteCryptoService,
cipherHolder = c.cipherHolder,
encryptionVerifier = c.encryptionVerifier,
)
}
}
@@ -68,6 +68,17 @@ import org.incido.compose.data.settings.UserSettings
* producing white-on-white text in dark mode. Biometric unlock now
* uses the callback-based [SecurityManager.authenticateWithBiometric]
* (the old synchronous busy-wait deadlocked the main thread).
*
* v0.3.3.7 (hotfix): in **biometric-only** mode the biometric prompt is
* launched automatically the moment the lock screen appears — previously
* the user had to tap the "Authenticate" button first, adding an extra
* tap of friction to every unlock (cold launch + every auto-lock). The
* auto-launch fires at most once per lock-screen appearance; if the user
* cancels (or the prompt errors), the lock screen stays and the
* "Authenticate" button remains as the manual-retry path. PIN mode is
* untouched — [UserSettings.isBiometricLockActive] is false there, so
* the auto-launch effect never runs and the PIN field keeps its
* auto-focus behaviour.
*/
@OptIn(ExperimentalMaterial3Api::class)
@Composable
@@ -91,6 +102,35 @@ fun PinEntryScreen() {
val focusRequester = remember { FocusRequester() }
val scope = rememberCoroutineScope()
// v0.3.3.7: guard flag — the biometric prompt must auto-launch at
// most once per lock-screen appearance so a cancelled prompt can't
// re-trigger in a loop.
var autoLaunched by remember { mutableStateOf(false) }
// v0.3.3.7: in biometric-only mode, open the BiometricPrompt as
// soon as the lock screen composes instead of waiting for the user
// to tap "Authenticate". Keyed on [biometricOnly] so the effect
// re-runs when the real (non-default) settings arrive — the initial
// composition sees the default UserSettings() (biometricOnly=false)
// and is intentionally skipped.
LaunchedEffect(biometricOnly) {
if (!biometricOnly) return@LaunchedEffect
if (autoLaunched) return@LaunchedEffect
if (!securityManager.isBiometricAvailable()) return@LaunchedEffect
val activity = context as? FragmentActivity ?: return@LaunchedEffect
autoLaunched = true
busy = true
error = null
securityManager.authenticateWithBiometric(activity) { ok ->
busy = false
if (ok) {
securityManager.onUnlocked()
} else {
error = "Authentication failed. Tap Authenticate to try again."
}
}
}
LaunchedEffect(Unit) {
// Only request focus on the PIN field when we're showing one.
if (!biometricOnly) focusRequester.requestFocus()
@@ -205,7 +245,14 @@ fun PinEntryScreen() {
if (ok) {
securityManager.onUnlocked()
} else {
error = "Authentication failed. Try again or use your PIN."
// v0.3.3.7: biometric-only mode has no
// Incido PIN to fall back to, so don't
// mention one.
error = if (biometricOnly) {
"Authentication failed. Tap Authenticate to try again."
} else {
"Authentication failed. Try again or use your PIN."
}
}
}
} else {