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:
1 parent
f87ca17ded
commit
8b66e82acb
20 files changed
+1822
No files matched your search
@@ -0,0 +1,70 @@
|
||||
// spike/data-jvm — THROWAWAY probe, not shipped. Desktop feasibility spike S1
|
||||
// (Development Plan §6.3). Answers Q2 + Q3:
|
||||
// Q2: does the ObjectBox generator + native runtime work on a plain JVM?
|
||||
// Q3: which data-module shape can Phase 1 use — one KMP module, or sibling
|
||||
// JVM/Android modules? This module is the "sibling JVM module" shape,
|
||||
// with the four entities copied verbatim from :core:data.
|
||||
//
|
||||
// Delete with the rest of `spike/` + its two `include()` lines in
|
||||
// settings.gradle.kts. Findings live in tools/DESKTOP_FEASIBILITY.md.
|
||||
|
||||
// The ObjectBox Gradle plugin publishes no plugin marker (same reason
|
||||
// :core/data/build.gradle.kts wires it through a buildscript classpath).
|
||||
buildscript {
|
||||
repositories {
|
||||
google()
|
||||
mavenCentral()
|
||||
}
|
||||
dependencies {
|
||||
classpath("io.objectbox:objectbox-gradle-plugin:${libs.versions.objectbox.get()}")
|
||||
}
|
||||
}
|
||||
|
||||
plugins {
|
||||
alias(libs.plugins.kotlinJvm)
|
||||
application
|
||||
}
|
||||
|
||||
// SPIKE FINDING: `alias(libs.plugins.kotlinKapt)` fails here with "plugin is
|
||||
// already on the classpath with an unknown version" because the root build
|
||||
// script already loads the Kotlin Gradle Plugin (kapt ships inside it).
|
||||
// Applying it by id — no version — reuses that copy. Same applies to Phase 1:
|
||||
// any JVM/KMP module needs kapt this way, or the root must declare
|
||||
// `alias(libs.plugins.kotlinKapt) apply false`.
|
||||
apply(plugin = "org.jetbrains.kotlin.kapt")
|
||||
|
||||
// Applied after the java/application plugins, as ObjectBox requires.
|
||||
apply(plugin = "io.objectbox")
|
||||
|
||||
java {
|
||||
sourceCompatibility = JavaVersion.VERSION_17
|
||||
targetCompatibility = JavaVersion.VERSION_17
|
||||
}
|
||||
|
||||
kotlin {
|
||||
jvmToolchain(17)
|
||||
}
|
||||
|
||||
application {
|
||||
mainClass.set("org.incido.spike.data.MainKt")
|
||||
}
|
||||
|
||||
dependencies {
|
||||
// The existing pure-Kotlin domain module — consumed as-is, no changes.
|
||||
implementation(project(":core:domain"))
|
||||
implementation(libs.kotlinx.coroutines.core)
|
||||
|
||||
// JVM counterparts of objectbox-android / the AAR the Android app uses.
|
||||
implementation(libs.objectbox.java)
|
||||
implementation(libs.objectbox.kotlin)
|
||||
|
||||
// Q5a: the multiplatform half of the settings layer. The Android app uses
|
||||
// the `preferencesDataStore(name = …)` Context extension; desktop must
|
||||
// build the same Preferences store from a file path instead.
|
||||
implementation(libs.androidx.datastore.preferences.core)
|
||||
|
||||
// Native database library for the target OS. The plugin auto-adds the
|
||||
// one for the *build* machine only; declaring it keeps the probe honest
|
||||
// about what a packaged desktop app must bundle.
|
||||
runtimeOnly(libs.objectbox.linux)
|
||||
}
|
||||
Binary file not shown.
@@ -0,0 +1,195 @@
|
||||
{
|
||||
"_note1": "KEEP THIS FILE! Check it into a version control system (VCS) like git.",
|
||||
"_note2": "ObjectBox manages crucial IDs for your object model. See docs for details.",
|
||||
"_note3": "If you have VCS merge conflicts, you must resolve them according to ObjectBox docs.",
|
||||
"entities": [
|
||||
{
|
||||
"id": "1:2086366869756073512",
|
||||
"lastPropertyId": "11:3900643584337280163",
|
||||
"name": "NoteEntity",
|
||||
"properties": [
|
||||
{
|
||||
"id": "1:504738300062779212",
|
||||
"name": "id",
|
||||
"type": 6,
|
||||
"flags": 1
|
||||
},
|
||||
{
|
||||
"id": "2:934725261850395537",
|
||||
"name": "content",
|
||||
"type": 9
|
||||
},
|
||||
{
|
||||
"id": "3:7787800412489145126",
|
||||
"name": "createdAt",
|
||||
"indexId": "1:2377104061956606005",
|
||||
"type": 6,
|
||||
"flags": 8
|
||||
},
|
||||
{
|
||||
"id": "4:7214601561419742071",
|
||||
"name": "updatedAt",
|
||||
"type": 6
|
||||
},
|
||||
{
|
||||
"id": "5:8997711518431222149",
|
||||
"name": "isFavorite",
|
||||
"indexId": "2:2889322420050596277",
|
||||
"type": 1,
|
||||
"flags": 8
|
||||
},
|
||||
{
|
||||
"id": "6:2157877161769308588",
|
||||
"name": "colorKey",
|
||||
"type": 3
|
||||
},
|
||||
{
|
||||
"id": "7:9124062984393699059",
|
||||
"name": "cipherVersion",
|
||||
"type": 5
|
||||
},
|
||||
{
|
||||
"id": "8:505259681403080579",
|
||||
"name": "contentBlob",
|
||||
"type": 23
|
||||
},
|
||||
{
|
||||
"id": "9:2838488564098834737",
|
||||
"name": "isTrashed",
|
||||
"indexId": "7:9172152715891628247",
|
||||
"type": 1,
|
||||
"flags": 8
|
||||
},
|
||||
{
|
||||
"id": "10:5547426387212371555",
|
||||
"name": "typeKey",
|
||||
"type": 3
|
||||
},
|
||||
{
|
||||
"id": "11:3900643584337280163",
|
||||
"name": "isDraft",
|
||||
"indexId": "8:9185376899648223266",
|
||||
"type": 1,
|
||||
"flags": 8
|
||||
}
|
||||
],
|
||||
"relations": []
|
||||
},
|
||||
{
|
||||
"id": "2:2528940840759116824",
|
||||
"lastPropertyId": "2:6290673541624313354",
|
||||
"name": "HashtagEntity",
|
||||
"properties": [
|
||||
{
|
||||
"id": "1:6991393863924167484",
|
||||
"name": "id",
|
||||
"type": 6,
|
||||
"flags": 1
|
||||
},
|
||||
{
|
||||
"id": "2:6290673541624313354",
|
||||
"name": "name",
|
||||
"indexId": "3:8935974229325273672",
|
||||
"type": 9,
|
||||
"flags": 2048
|
||||
}
|
||||
],
|
||||
"relations": []
|
||||
},
|
||||
{
|
||||
"id": "3:1814708994588042328",
|
||||
"lastPropertyId": "3:4619895459374594011",
|
||||
"name": "NoteHashtagCrossRef",
|
||||
"properties": [
|
||||
{
|
||||
"id": "1:8394679598512920368",
|
||||
"name": "id",
|
||||
"type": 6,
|
||||
"flags": 1
|
||||
},
|
||||
{
|
||||
"id": "2:7132785913803437080",
|
||||
"name": "noteId",
|
||||
"indexId": "4:4609493987894622099",
|
||||
"type": 6,
|
||||
"flags": 8
|
||||
},
|
||||
{
|
||||
"id": "3:4619895459374594011",
|
||||
"name": "hashtagId",
|
||||
"indexId": "5:4178528765644585892",
|
||||
"type": 6,
|
||||
"flags": 8
|
||||
}
|
||||
],
|
||||
"relations": []
|
||||
},
|
||||
{
|
||||
"id": "4:715630424595534313",
|
||||
"lastPropertyId": "9:5604884960166980615",
|
||||
"name": "NoteAttachmentEntity",
|
||||
"properties": [
|
||||
{
|
||||
"id": "1:8895066388904375968",
|
||||
"name": "id",
|
||||
"type": 6,
|
||||
"flags": 1
|
||||
},
|
||||
{
|
||||
"id": "2:5099883303141941942",
|
||||
"name": "noteId",
|
||||
"indexId": "6:644263235201197567",
|
||||
"type": 6,
|
||||
"flags": 8
|
||||
},
|
||||
{
|
||||
"id": "3:5923891227223085632",
|
||||
"name": "mimeType",
|
||||
"type": 9
|
||||
},
|
||||
{
|
||||
"id": "4:5969004045087908818",
|
||||
"name": "displayName",
|
||||
"type": 9
|
||||
},
|
||||
{
|
||||
"id": "5:1484939891319950467",
|
||||
"name": "createdAt",
|
||||
"type": 6
|
||||
},
|
||||
{
|
||||
"id": "6:4541111239334797694",
|
||||
"name": "sizeBytes",
|
||||
"type": 6
|
||||
},
|
||||
{
|
||||
"id": "7:5483350198068298485",
|
||||
"name": "bytes",
|
||||
"type": 23
|
||||
},
|
||||
{
|
||||
"id": "8:6354828434115894982",
|
||||
"name": "cipherVersion",
|
||||
"type": 5
|
||||
},
|
||||
{
|
||||
"id": "9:5604884960166980615",
|
||||
"name": "bytesBlob",
|
||||
"type": 23
|
||||
}
|
||||
],
|
||||
"relations": []
|
||||
}
|
||||
],
|
||||
"lastEntityId": "4:715630424595534313",
|
||||
"lastIndexId": "8:9185376899648223266",
|
||||
"lastRelationId": "0:0",
|
||||
"lastSequenceId": "0:0",
|
||||
"modelVersion": 5,
|
||||
"modelVersionParserMinimum": 5,
|
||||
"retiredEntityUids": [],
|
||||
"retiredIndexUids": [],
|
||||
"retiredPropertyUids": [],
|
||||
"retiredRelationUids": [],
|
||||
"version": 1
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
Reference in new issue
Block a user