spike(desktop): Phase 0 feasibility probes + findings

Adds the throwaway Phase-0 spike (Development Plan §6.3) that answers
whether Incido can become a Compose Multiplatform desktop app without
abandoning ObjectBox, its crypto layer, or its UI layer. All six
questions came back PASS; findings live in tools/DESKTOP_FEASIBILITY.md.

  :spike:data-jvm    ObjectBox kapt codegen + native runtime on a plain
                     JVM, DataStore Preferences without a Context, and
                     the app's own EncryptedKeyCodec round-tripping.
  :spike:compose-jvm Compose Desktop rendering the app's real theme
                     layer + core:domain, plus jpackage packaging.

Additive only: nothing outside spike/ depends on these, and the Android
build is untouched (assembleDebug verified green).
This commit is contained in:
Incido Developer committed 2026-10-05 18:20:46 +13:00
1 parent f87ca17ded
commit 8b66e82acb
20 files changed
+1822

No files matched your search

@@ -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,19 @@
package org.incido.data.entity
import io.objectbox.annotation.Entity
import io.objectbox.annotation.Id
import io.objectbox.annotation.Index
/**
* A single normalised hashtag. Case-insensitive uniqueness is
* enforced at the repository layer (`NoteRepositoryImpl.addHashtag`
* uses `findFirst` and reuses the existing row); the index here just
* speeds up the lookup.
*
* The "many-to-many" link to notes lives in [NoteHashtagCrossRef].
*/
@Entity
data class HashtagEntity(
@Id var id: Long = 0,
@Index var name: String = "",
)
@@ -0,0 +1,91 @@
package org.incido.data.entity
import io.objectbox.annotation.Entity
import io.objectbox.annotation.Id
import io.objectbox.annotation.Index
import org.incido.domain.model.NoteAttachment
/**
* v0.3.1.0 — One uploaded file (photo, document, etc.) attached to a
* note. File **bytes** live directly in the database (ObjectBox
* stores `ByteArray` columns natively) so the entire note + its
* attachments are backed up and restored as a single unit, with no
* filesystem paths to keep in sync.
*
* [bytes] is intentionally NOT part of [NoteAttachment] in the
* domain layer — list snapshots stay cheap because they don't load
* the (potentially large) blob. Callers fetch bytes on demand via
* [org.incido.domain.repository.NoteRepository.getAttachmentBytes].
*
* v0.3.5.0 — at-rest field encryption. [cipherVersion] records the
* state of the row: `0` = plaintext ([bytes] holds the raw file),
* `1` = AES-256-GCM encrypted ([bytesBlob] holds `nonce | ciphertext
* + tag` and [bytes] is kept empty). Both columns are additive so
* existing stores auto-migrate.
*/
@Entity
data class NoteAttachmentEntity(
@Id var id: Long = 0,
@Index var noteId: Long = 0,
var mimeType: String = "",
var displayName: String = "",
var createdAt: Long = 0,
var sizeBytes: Long = 0,
var bytes: ByteArray = ByteArray(0),
/** 0 = plaintext, 1 = AES-256-GCM encrypted into [bytesBlob]. */
var cipherVersion: Int = 0,
/** Encrypted payload: `nonce (12) | ciphertext + GCM tag`. Empty when plaintext. */
var bytesBlob: ByteArray = ByteArray(0),
) {
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is NoteAttachmentEntity) return false
if (id != other.id) return false
if (noteId != other.noteId) return false
if (mimeType != other.mimeType) return false
if (displayName != other.displayName) return false
if (createdAt != other.createdAt) return false
if (sizeBytes != other.sizeBytes) return false
if (!bytes.contentEquals(other.bytes)) return false
if (cipherVersion != other.cipherVersion) return false
if (!bytesBlob.contentEquals(other.bytesBlob)) return false
return true
}
override fun hashCode(): Int {
var result = id.hashCode()
result = 31 * result + noteId.hashCode()
result = 31 * result + mimeType.hashCode()
result = 31 * result + displayName.hashCode()
result = 31 * result + createdAt.hashCode()
result = 31 * result + sizeBytes.hashCode()
result = 31 * result + bytes.contentHashCode()
result = 31 * result + cipherVersion.hashCode()
result = 31 * result + bytesBlob.contentHashCode()
return result
}
}
internal fun NoteAttachmentEntity.toDomain(): NoteAttachment = NoteAttachment(
id = id,
noteId = noteId,
mimeType = mimeType,
displayName = displayName,
createdAt = createdAt,
sizeBytes = sizeBytes,
)
/**
* Inverse mapper from the domain layer — used when the editor or
* the share-into flow persists a freshly-imported attachment. The
* [id] field is left at 0L so ObjectBox assigns a fresh id on put.
*/
internal fun NoteAttachment.toEntity(): NoteAttachmentEntity = NoteAttachmentEntity(
id = 0L,
noteId = noteId,
mimeType = mimeType,
displayName = displayName,
createdAt = createdAt,
sizeBytes = sizeBytes,
bytes = ByteArray(0), // never serialised from the domain — bytes are set explicitly in the impl
)
@@ -0,0 +1,104 @@
package org.incido.data.entity
import io.objectbox.annotation.Entity
import io.objectbox.annotation.Id
import io.objectbox.annotation.Index
import org.incido.domain.model.Note
import org.incido.domain.model.NoteColor
import org.incido.domain.model.NoteType
/**
* ObjectBox entity. The plugin generates a corresponding property mirror
* class (`NoteEntity_`) at build time, plus the [MyObjectBox] container.
*
* v0.2 adds [isFavorite] and [color]. Both are additive (the prior v0.1
* schema had neither) so existing user notes auto-migrate on first launch.
*
* v0.3.5.0 — at-rest field encryption. [cipherVersion] records the
* state of the row: `0` = plaintext ([content] holds the note text),
* `1` = AES-256-GCM encrypted ([contentBlob] holds `nonce | ciphertext
* + tag` and [content] is kept empty). The two columns are additive so
* existing stores auto-migrate. The repository transparently
* encrypts/decrypts on write/read when a [org.incido.data.crypto.FieldCipher]
* is supplied.
*
* v0.3.8.0 — [typeKey] records the note editor mode
* ([org.incido.domain.model.NoteType]: 0 text, 1 task list, 2 shopping
* list). Additive column — existing stores auto-migrate and old rows
* default to plain text.
*/
@Entity
data class NoteEntity(
@Id var id: Long = 0,
var content: String = "",
@Index var createdAt: Long = 0,
var updatedAt: Long = 0,
@Index var isFavorite: Boolean = false,
var colorKey: Short = 0,
/** 0 = plaintext, 1 = AES-256-GCM encrypted into [contentBlob]. */
var cipherVersion: Int = 0,
/** Encrypted payload: `nonce (12) | ciphertext + GCM tag`. Empty when plaintext. */
var contentBlob: ByteArray = ByteArray(0),
/** True only for notes moved to the Trash view; active-note queries exclude these rows. */
@Index var isTrashed: Boolean = false,
/** v0.3.8.0 — [org.incido.domain.model.NoteType] storage key (0 text, 1 task, 2 shopping). */
var typeKey: Short = 0,
/** True while a new note is being drafted; only the Drafts view shows these rows. */
@Index var isDraft: Boolean = false,
) {
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is NoteEntity) return false
if (id != other.id) return false
if (content != other.content) return false
if (createdAt != other.createdAt) return false
if (updatedAt != other.updatedAt) return false
if (isFavorite != other.isFavorite) return false
if (colorKey != other.colorKey) return false
if (isTrashed != other.isTrashed) return false
if (cipherVersion != other.cipherVersion) return false
if (!contentBlob.contentEquals(other.contentBlob)) return false
if (typeKey != other.typeKey) return false
if (isDraft != other.isDraft) return false
return true
}
override fun hashCode(): Int {
var result = id.hashCode()
result = 31 * result + content.hashCode()
result = 31 * result + createdAt.hashCode()
result = 31 * result + updatedAt.hashCode()
result = 31 * result + isFavorite.hashCode()
result = 31 * result + colorKey.hashCode()
result = 31 * result + isTrashed.hashCode()
result = 31 * result + cipherVersion.hashCode()
result = 31 * result + contentBlob.contentHashCode()
result = 31 * result + typeKey.hashCode()
result = 31 * result + isDraft.hashCode()
return result
}
}
internal fun NoteEntity.toDomain(): Note = Note(
id = id,
content = content,
createdAt = createdAt,
updatedAt = updatedAt,
isFavorite = isFavorite,
color = NoteColor.fromStorageKey(colorKey),
isTrashed = isTrashed,
type = NoteType.fromStorageKey(typeKey),
isDraft = isDraft,
)
internal fun Note.toEntity(): NoteEntity = NoteEntity(
id = id,
content = content,
createdAt = createdAt,
updatedAt = updatedAt,
isFavorite = isFavorite,
colorKey = color.storageKey,
isTrashed = isTrashed,
typeKey = type.storageKey,
isDraft = isDraft,
)
@@ -0,0 +1,19 @@
package org.incido.data.entity
import io.objectbox.annotation.Entity
import io.objectbox.annotation.Id
import io.objectbox.annotation.Index
/**
* Many-to-many junction between [NoteEntity] and [HashtagEntity].
* Each row is one (`noteId`, `hashtagId`) pair.
*
* Both columns are indexed for fast lookups in either direction
* (notes for a hashtag, hashtags for a note).
*/
@Entity
data class NoteHashtagCrossRef(
@Id var id: Long = 0,
@Index var noteId: Long = 0,
@Index var hashtagId: Long = 0,
)
@@ -0,0 +1,156 @@
package org.incido.spike.data
import io.objectbox.BoxStore
import java.io.File
import org.incido.data.entity.HashtagEntity
import org.incido.data.entity.MyObjectBox
import org.incido.data.entity.NoteAttachmentEntity
import org.incido.data.entity.NoteEntity
import org.incido.data.entity.NoteHashtagCrossRef
/**
* spike/data-jvm — THROWAWAY probe (desktop feasibility S1, §6.3).
*
* Proves the four things that decide the desktop plan:
* 1. the ObjectBox generator produced `MyObjectBox` for a JVM module;
* 2. the JVM native library loads on this OS;
* 3. the real Incido schema (copied `objectbox-models/default.json`) opens
* with no UID churn, including the `ByteArray` blob columns the field
* cipher writes to;
* 4. data survives a close/reopen cycle against the same directory.
*
* Prints PASS/FAIL per step and exits non-zero on any failure so CI can gate
* on it. Usage: `./gradlew :spike:data-jvm:run --args="<dir>"`.
*/
fun main(args: Array<String>) {
println("=== Incido desktop spike S1: ObjectBox on the JVM ===")
println("JVM : ${System.getProperty("java.vendor")} ${System.getProperty("java.version")}")
println("OS : ${System.getProperty("os.name")} ${System.getProperty("os.arch")}")
val storeDir = File(args.firstOrNull() ?: "build/spike-db").absoluteFile
storeDir.mkdirs()
println("DB dir : $storeDir")
var failures = 0
fun step(name: String, body: () -> String): String? {
print("${name.padEnd(34)} ")
return runCatching(body)
.onSuccess { println("PASS — $it") }
.onFailure { t ->
println("FAIL — ${t::class.java.simpleName}: ${t.message}")
t.cause?.let { println("${"".padEnd(34)} caused by ${it::class.java.name}: ${it.message}") }
failures++
}
.getOrNull()
}
// 1 + 2: generator output + native library load. Building the store is the
// first moment either can fail, so they share this step.
var store: BoxStore? = null
step("build BoxStore (codegen + native)") {
store = MyObjectBox.builder().directory(storeDir).build()
val name = runCatching { BoxStore::class.java.getMethod("getName").invoke(store) }.getOrNull()
"native lib loaded; store name = ${name ?: "(default)"}"
}
if (store == null) { reportAndExit(failures); return }
step("ObjectBox versions") {
listOf("getVersion", "getNativeLibraryVersion", "hasEncryption", "hasSynchronous").joinToString("; ") { name ->
runCatching {
val m = BoxStore::class.java.getMethod(name)
"${m.returnType.simpleName} $name() = ${m.invoke(null)}"
}.getOrDefault("$name() — not present")
}
}
// 3: write + read through the real schema, incl. blob columns and indexes.
val now = System.currentTimeMillis()
val blob = ByteArray(4096) { (it % 251).toByte() }
step("put NoteEntity (plaintext row)") {
store!!.boxFor(NoteEntity::class.java).put(
NoteEntity(content = "shopping list: milk", createdAt = now, updatedAt = now, isFavorite = true),
).let { "id=$it" }
}
var noteId = 0L
step("put NoteEntity (cipherVersion=1 blob)") {
noteId = store!!.boxFor(NoteEntity::class.java).put(
NoteEntity(
content = "", createdAt = now + 1, updatedAt = now + 1,
cipherVersion = 1, contentBlob = blob, isDraft = true, typeKey = 2,
),
)
"id=$noteId"
}
step("put Hashtag + Attachment + CrossRef") {
val tags = store!!.boxFor(HashtagEntity::class.java)
val atts = store!!.boxFor(NoteAttachmentEntity::class.java)
val refs = store!!.boxFor(NoteHashtagCrossRef::class.java)
val tagId = tags.put(HashtagEntity(name = "#spike"))
val attId = atts.put(
NoteAttachmentEntity(
noteId = noteId, mimeType = "audio/ogg", displayName = "take.opus",
createdAt = now, sizeBytes = blob.size.toLong(), bytesBlob = blob, cipherVersion = 1,
),
)
val refId = refs.put(NoteHashtagCrossRef(noteId = noteId, hashtagId = tagId))
"tag=$tagId attachment=$attId ref=$refId"
}
// Generated mirror classes are inspected reflectively on purpose: it keeps
// this probe compiling whatever the generator names its fields, and prints
// the real names so the findings doc records them.
step("generated mirror classes present") {
val mirror = Class.forName("org.incido.data.entity.NoteEntity_")
val props = mirror.declaredFields
.filter { f -> f.type.name == "io.objectbox.model.Property" || f.type.simpleName == "Property" }
.map { it.name }
require(mirror.classLoader != null)
"MyObjectBox + ${mirror.simpleName} OK; property fields = $props"
}
step("query all + read indexed flag") {
val q = store!!.boxFor(NoteEntity::class.java).query().build()
val rows = q.find().sortedBy { it.createdAt }
q.close()
val active = rows.filter { !it.isTrashed }
require(rows.size >= 2) { "expected >=2 rows, got ${rows.size}" }
"${rows.size} rows, ${active.size} not trashed; drafts=${rows.count { it.isDraft }}"
}
step("blob round-trip integrity") {
val n = store!!.boxFor(NoteEntity::class.java).get(noteId)
?: error("row $noteId vanished")
require(n.contentBlob.contentEquals(blob)) { "blob differs after read (size ${n.contentBlob.size})" }
"4096 bytes identical; cipherVersion=${n.cipherVersion} typeKey=${n.typeKey} isDraft=${n.isDraft}"
}
// 4: persistence across a reopen of the same directory.
step("close + reopen same directory") {
store!!.close(); store = null
store = MyObjectBox.builder().directory(storeDir).build()
val notes = store!!.boxFor(NoteEntity::class.java).count()
val tags = store!!.boxFor(HashtagEntity::class.java).count()
require(notes >= 2L) { "notes lost on reopen (count=$notes)" }
"notes=$notes hashtags=$tags"
}
store?.close()
// Q5a/Q5b: the non-UI platform layer (settings store + crypto).
println()
println("--- settings / crypto on the JVM (Q5a + Q5b) ---")
failures += probeSettingsAndCrypto(storeDir)
println()
if (failures == 0) {
println("RESULT: S1 PASS — ObjectBox runs on the JVM with the Incido schema.")
} else {
println("RESULT: S1 FAIL — $failures step(s) failed (see above).")
}
reportAndExit(failures)
}
private fun reportAndExit(failures: Int) {
if (failures > 0) kotlin.system.exitProcess(1)
}
@@ -0,0 +1,138 @@
package org.incido.spike.data
import androidx.datastore.core.DataStore
import androidx.datastore.core.handlers.ReplaceFileCorruptionHandler
import androidx.datastore.preferences.core.PreferenceDataStoreFactory
import androidx.datastore.preferences.core.Preferences
import androidx.datastore.preferences.core.booleanPreferencesKey
import androidx.datastore.preferences.core.edit
import androidx.datastore.preferences.core.emptyPreferences
import androidx.datastore.preferences.core.stringPreferencesKey
import java.io.File
import javax.crypto.Cipher
import javax.crypto.SecretKeyFactory
import javax.crypto.spec.GCMParameterSpec
import javax.crypto.spec.PBEKeySpec
import javax.crypto.spec.SecretKeySpec
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.runBlocking
import org.incido.compose.data.backup.EncryptedKeyCodec
/**
* spike/data-jvm — THROWAWAY probe, Q5a + Q5b: the non-UI parts of the
* settings/security layer on a plain JVM.
*
* - DataStore Preferences WITHOUT a Context (the app's three stores —
* incido_settings / incido_security_keys / incido_pin — are all built with
* the Android-only `preferencesDataStore(name = …)` extension).
* - The app's REAL recovery-key envelope (EncryptedKeyCodec.kt copied in
* verbatim): if this round-trips, a key exported from the phone opens
* encrypted notes on desktop with zero format changes.
* - The PBKDF2 cost that envelope uses (200k iterations), timed — that's what
* a passphrase-derived desktop master key would cost on every launch.
* - AES-256-GCM field encryption in the AesGcmFieldCipher blob layout.
*
* Returns the number of failed steps.
*/
fun probeSettingsAndCrypto(baseDir: File): Int {
var failures = 0
fun step(name: String, body: () -> String) {
print("${name.padEnd(29)} ")
runCatching(body)
.onSuccess { println("PASS — $it") }
.onFailure {
println("FAIL — ${it::class.java.simpleName}: ${it.message}")
failures++
}
}
// Where a desktop build would actually keep its data — documents the
// Phase-2 path decision instead of inventing a fourth option.
// NOTE (spike quirk): the multi-arg java.io.File constructors are not
// resolvable from this kapt-driven JVM module on this JDK build, so paths
// are composed as strings — single-arg File() works fine.
val sep = java.io.File.separator
val xdgPath = System.getenv("XDG_DATA_HOME")?.takeIf { it.isNotBlank() }
?: System.getProperty("user.home") + sep + ".local" + sep + "share"
val appDir = java.io.File(xdgPath + sep + "incido").also { it.mkdirs() }
println("data dir — would be $appDir")
step("DataStore prefs (no Context)") {
// SPIKE FINDING: on the JVM there is no `preferencesDataStore(name=…)`
// extension and no public PreferenceSerializer — the right entry point
// is PreferenceDataStoreFactory.create(corruptionHandler, produceFile)
// taking a java.io.File (a createWithPath(okio.Path) overload also
// exists). Same Preferences keys and the same .preferences_pb format.
val settingsFile = java.io.File(appDir.absolutePath + sep + "incido_settings.preferences_pb")
val store: DataStore<Preferences> = PreferenceDataStoreFactory.create(
corruptionHandler = ReplaceFileCorruptionHandler { emptyPreferences() },
produceFile = { settingsFile },
)
// Exactly the keys SettingsRepository writes on Android.
runBlocking {
store.edit {
it[stringPreferencesKey("theme_mode")] = "SYSTEM"
it[booleanPreferencesKey("security_enabled")] = true
it[booleanPreferencesKey("block_screenshots")] = false
}
}
val prefs = runBlocking { store.data.first() }
require(prefs[stringPreferencesKey("theme_mode")] == "SYSTEM") { "theme_mode lost" }
require(prefs[booleanPreferencesKey("block_screenshots")] == false) { "flag lost" }
"${prefs.asMap().size} keys, file=${settingsFile.name} (${settingsFile.length()} bytes)"
}
step("recovery-key envelope (real codec)") {
val raw = ByteArray(EncryptedKeyCodec.KEY_PAYLOAD_BYTES) { (it + 7).toByte() }
val envelope = EncryptedKeyCodec.encrypt(raw, "correct horse battery staple".toCharArray())
require(EncryptedKeyCodec.isEncryptedKey(envelope)) { "magic header missing" }
val back = EncryptedKeyCodec.decrypt(envelope, "correct horse battery staple".toCharArray())
require(back.contentEquals(raw)) { "key changed through the envelope" }
"envelope=${envelope.size} bytes, ${raw.size}-byte key round-tripped"
}
step("wrong passphrase is rejected") {
val raw = ByteArray(EncryptedKeyCodec.KEY_PAYLOAD_BYTES) { (it + 3).toByte() }
val envelope = EncryptedKeyCodec.encrypt(raw, "right passphrase here!!".toCharArray())
val rejected = runCatching {
EncryptedKeyCodec.decrypt(envelope, "wrong wrong wrong wrong".toCharArray())
}.exceptionOrNull()
require(rejected != null) { "bad passphrase was ACCEPTED" }
"rejected with ${rejected::class.java.simpleName}"
}
step("PBKDF2 200k cost (per unlock)") {
val salt = ByteArray(16) { it.toByte() }
val millis = (1..2).map {
val t = System.nanoTime()
val spec = PBEKeySpec("correct horse battery staple".toCharArray(), salt, 200_000, 256)
val key = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256")
.generateSecret(spec).encoded
spec.clearPassword()
require(key.size == 32)
(System.nanoTime() - t) / 1_000_000
}
"samples=$millis ms per unlock on this CPU"
}
step("AES-256-GCM field cipher layout") {
val key = SecretKeySpec(ByteArray(32) { (it * 3).toByte() }, "AES")
val payload = ByteArray(4096) { (it % 127).toByte() }
val nonce = ByteArray(12) { (it + 1).toByte() }
val enc = Cipher.getInstance("AES/GCM/NoPadding").apply {
init(Cipher.ENCRYPT_MODE, key, GCMParameterSpec(128, nonce))
}.doFinal(payload)
val dec = Cipher.getInstance("AES/GCM/NoPadding").apply {
init(Cipher.DECRYPT_MODE, key, GCMParameterSpec(128, nonce))
}.doFinal(enc)
require(dec.contentEquals(payload)) { "field cipher round-trip differs" }
val t = System.nanoTime()
repeat(500) {
Cipher.getInstance("AES/GCM/NoPadding").apply {
init(Cipher.ENCRYPT_MODE, key, GCMParameterSpec(128, nonce))
}.doFinal(payload)
}
"4KB ok; 500 encrypts in ${(System.nanoTime() - t) / 1_000_000} ms"
}
return failures
}