feat: v0.3.6.0 — AES-GCM field encryption, PIN/passphrase security, encryption verifier, backup codec
build / Assemble debug APK (push) Failing after 2s
build / Assemble debug APK (push) Failing after 2s
This commit is contained in:
1 parent
089926377c
commit
14d61c78d3
55 files changed
+2474
-715
No files matched your search
@@ -8,13 +8,15 @@ import org.incido.data.entity.MyObjectBox
|
||||
* Singleton holder for the process-wide [BoxStore]. Initialised once from
|
||||
* the Application/Activity context.
|
||||
*
|
||||
* v0.3.2.0 — kept an `encryptionKey` parameter for forward compatibility,
|
||||
* but the open-source ObjectBox 4.0.3 distribution doesn't expose a
|
||||
* public `encryptionKey(byte[])` method on [io.objectbox.BoxStoreBuilder].
|
||||
* At-rest encryption is only available in ObjectBox Sync / Pro; the
|
||||
* `:composeApp` `ObjectBoxKeyProvider` keeps the wrapping logic
|
||||
* ready for when the API becomes available (or for migration to the
|
||||
* commercial build). For now the store always opens unencrypted.
|
||||
* v0.3.5.0 — the open-source ObjectBox 4.0.3 distribution does not
|
||||
* expose a public `encryptionKey(byte[])` builder method (that is
|
||||
* ObjectBox Sync / Pro only), so the store file itself is opened
|
||||
* unencrypted. At-rest protection is instead done one layer up:
|
||||
* note content and attachment blobs are field-encrypted with
|
||||
* AES-256-GCM by `NoteRepositoryImpl` / `NoteCryptoService` using the
|
||||
* Keystore-wrapped key managed by `ObjectBoxKeyProvider`. The
|
||||
* `encryptionKey` parameter is kept for forward compatibility with a
|
||||
* commercial ObjectBox build but remains a no-op here.
|
||||
*/
|
||||
object ObjectBoxStore {
|
||||
@Volatile
|
||||
@@ -25,10 +27,9 @@ object ObjectBoxStore {
|
||||
* return the existing instance.
|
||||
*
|
||||
* @param context application context
|
||||
* @param encryptionKey reserved for future at-rest encryption support
|
||||
* (currently a no-op — ObjectBox 4.0.3 OSS doesn't expose the
|
||||
* API). The key is wrapped via Android Keystore by
|
||||
* `ObjectBoxKeyProvider` and ready to plug in.
|
||||
* @param encryptionKey reserved for future ObjectBox-native at-rest
|
||||
* encryption (OSS 4.0.3 doesn't expose the API — currently a
|
||||
* no-op; see class KDoc for the field-encryption approach).
|
||||
*/
|
||||
@Suppress("UNUSED_PARAMETER")
|
||||
fun init(context: Context, encryptionKey: ByteArray? = null): BoxStore =
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
package org.incido.data.crypto
|
||||
|
||||
/**
|
||||
* v0.3.5.0: abstraction for the field-level encryption used by the
|
||||
* repository to protect note content and attachment bytes at rest.
|
||||
*
|
||||
* The [core:data] module stays free of Android Keystore dependencies —
|
||||
* the concrete implementation lives in `:composeApp`
|
||||
* (`AesGcmFieldCipher`), backed by the Keystore-wrapped key managed by
|
||||
* `ObjectBoxKeyProvider`, and is injected via the repository
|
||||
* constructor.
|
||||
*
|
||||
* Blob layout produced by all `encrypt*` methods:
|
||||
*
|
||||
* ```
|
||||
* nonce (12 bytes) | ciphertext | GCM tag (16 bytes, appended by JCE)
|
||||
* ```
|
||||
*
|
||||
* All `decrypt*` methods throw [javax.crypto.AEADBadTagException]
|
||||
* (wrapped in [IllegalArgumentException] on some providers) when the
|
||||
* payload is corrupted or was encrypted with a different key — callers
|
||||
* use this as a **verification** signal (see the startup "Encrypted"
|
||||
* badge re-check).
|
||||
*/
|
||||
interface FieldCipher {
|
||||
|
||||
/** Encrypt [plaintext] (UTF-8) into a self-describing blob. */
|
||||
fun encryptString(plaintext: String): ByteArray
|
||||
|
||||
/**
|
||||
* Reverse of [encryptString]. Throws if the blob is truncated,
|
||||
* corrupted, or not encrypted with the current key.
|
||||
*/
|
||||
fun decryptString(blob: ByteArray): String
|
||||
|
||||
/** Encrypt raw [plaintext] bytes into a self-describing blob. */
|
||||
fun encryptBytes(plaintext: ByteArray): ByteArray
|
||||
|
||||
/** Reverse of [encryptBytes]. Throws on integrity failure. */
|
||||
fun decryptBytes(blob: ByteArray): ByteArray
|
||||
}
|
||||
|
||||
/** Value stored in `cipherVersion` columns for plaintext rows. */
|
||||
const val CIPHER_VERSION_PLAIN: Int = 0
|
||||
|
||||
/** Value stored in `cipherVersion` columns for AES-256-GCM encrypted rows. */
|
||||
const val CIPHER_VERSION_AES_GCM: Int = 1
|
||||
@@ -0,0 +1,184 @@
|
||||
package org.incido.data.crypto
|
||||
|
||||
import io.objectbox.BoxStore
|
||||
import io.objectbox.kotlin.boxFor
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.withContext
|
||||
import org.incido.data.entity.NoteAttachmentEntity
|
||||
import org.incido.data.entity.NoteEntity
|
||||
|
||||
/**
|
||||
* v0.3.5.0: process-wide holder for the currently-active [FieldCipher].
|
||||
*
|
||||
* The repository consults [cipher] on every read/write, which lets the
|
||||
* settings flow flip encryption on or off **live** (no app restart):
|
||||
*
|
||||
* - enable → set the cipher, then run [NoteCryptoService.encryptAllInPlace]
|
||||
* - disable → run [NoteCryptoService.decryptAllInPlace], then clear the cipher
|
||||
*
|
||||
* Rows stay self-describing via their `cipherVersion` column, so a mix
|
||||
* of plaintext and encrypted rows is always readable.
|
||||
*/
|
||||
class CipherHolder {
|
||||
@Volatile
|
||||
var cipher: FieldCipher? = null
|
||||
}
|
||||
|
||||
/**
|
||||
* Result of the startup integrity check over every encrypted note row.
|
||||
*
|
||||
* [verifiedNoteIds] — rows whose ciphertext decrypts cleanly under the
|
||||
* current key (the GCM auth tag is the proof of integrity). This is the
|
||||
* ONLY source of truth for the "Encrypted" badge on the note cards —
|
||||
* the badge is never shown based on the settings flag alone.
|
||||
*
|
||||
* [failedNoteIds] — rows marked encrypted whose ciphertext fails to
|
||||
* decrypt (corruption or wrong key). Surfaced to the user as a warning.
|
||||
*/
|
||||
data class EncryptionVerification(
|
||||
val verifiedNoteIds: Set<Long>,
|
||||
val failedNoteIds: Set<Long>,
|
||||
/** [System.currentTimeMillis] when the check ran. */
|
||||
val checkedAt: Long,
|
||||
) {
|
||||
val allOk: Boolean get() = failedNoteIds.isEmpty()
|
||||
}
|
||||
|
||||
/**
|
||||
* v0.3.5.0: the service that makes "Encrypt in place" real. Operates
|
||||
* directly on the ObjectBox store (bypassing the repository's
|
||||
* domain-mapping layer) to sweep every note + attachment row and flip
|
||||
* its `cipherVersion` in place, reporting progress for the migration
|
||||
* dialog.
|
||||
*
|
||||
* It is also the startup **verifier**: [verifyAll] re-checks every
|
||||
* encrypted note row by performing a full GCM decrypt — this runs on
|
||||
* every app open so the "Encrypted" badge only ever reflects rows that
|
||||
* are demonstrably decryptable right now.
|
||||
*/
|
||||
class NoteCryptoService(
|
||||
private val boxStore: BoxStore,
|
||||
private val cipherHolder: CipherHolder,
|
||||
) {
|
||||
|
||||
private val noteBox = boxStore.boxFor<NoteEntity>()
|
||||
private val attachmentBox = boxStore.boxFor<NoteAttachmentEntity>()
|
||||
|
||||
/**
|
||||
* Encrypt every plaintext row in place (notes + attachments).
|
||||
* Rows already at `cipherVersion = 1` are skipped, which makes the
|
||||
* sweep idempotent and safe to re-run (e.g. resuming an interrupted
|
||||
* migration). [onProgress] receives `(completed, total)` — called
|
||||
* from a background thread; thread-safe sinks only (MutableStateFlow).
|
||||
*/
|
||||
suspend fun encryptAllInPlace(onProgress: (completed: Int, total: Int) -> Unit = { _, _ -> }) =
|
||||
withContext(Dispatchers.IO) {
|
||||
val cipher = cipherHolder.cipher
|
||||
?: throw IllegalStateException("No cipher configured — cannot encrypt")
|
||||
|
||||
val notes = noteBox.all
|
||||
val attachments = attachmentBox.all
|
||||
val total = notes.count { it.cipherVersion == CIPHER_VERSION_PLAIN } +
|
||||
attachments.count { it.cipherVersion == CIPHER_VERSION_PLAIN }
|
||||
var done = 0
|
||||
onProgress(done, total)
|
||||
|
||||
for (entity in notes) {
|
||||
if (entity.cipherVersion != CIPHER_VERSION_PLAIN) continue
|
||||
entity.contentBlob = cipher.encryptString(entity.content)
|
||||
entity.content = ""
|
||||
entity.cipherVersion = CIPHER_VERSION_AES_GCM
|
||||
noteBox.put(entity)
|
||||
done++
|
||||
onProgress(done, total)
|
||||
}
|
||||
for (entity in attachments) {
|
||||
if (entity.cipherVersion != CIPHER_VERSION_PLAIN) continue
|
||||
entity.bytesBlob = cipher.encryptBytes(entity.bytes)
|
||||
entity.bytes = ByteArray(0)
|
||||
entity.cipherVersion = CIPHER_VERSION_AES_GCM
|
||||
attachmentBox.put(entity)
|
||||
done++
|
||||
onProgress(done, total)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Reverse of [encryptAllInPlace] — decrypt every encrypted row back
|
||||
* to plaintext. Idempotent; plaintext rows are skipped. Call this
|
||||
* BEFORE clearing [CipherHolder.cipher] so any concurrent write
|
||||
* still has a key while the sweep runs.
|
||||
*/
|
||||
suspend fun decryptAllInPlace(onProgress: (completed: Int, total: Int) -> Unit = { _, _ -> }) =
|
||||
withContext(Dispatchers.IO) {
|
||||
val cipher = cipherHolder.cipher
|
||||
?: throw IllegalStateException("No cipher configured — cannot decrypt")
|
||||
|
||||
val notes = noteBox.all
|
||||
val attachments = attachmentBox.all
|
||||
val total = notes.count { it.cipherVersion == CIPHER_VERSION_AES_GCM } +
|
||||
attachments.count { it.cipherVersion == CIPHER_VERSION_AES_GCM }
|
||||
var done = 0
|
||||
onProgress(done, total)
|
||||
|
||||
for (entity in notes) {
|
||||
if (entity.cipherVersion != CIPHER_VERSION_AES_GCM) continue
|
||||
entity.content = cipher.decryptString(entity.contentBlob)
|
||||
entity.contentBlob = ByteArray(0)
|
||||
entity.cipherVersion = CIPHER_VERSION_PLAIN
|
||||
noteBox.put(entity)
|
||||
done++
|
||||
onProgress(done, total)
|
||||
}
|
||||
for (entity in attachments) {
|
||||
if (entity.cipherVersion != CIPHER_VERSION_AES_GCM) continue
|
||||
entity.bytes = cipher.decryptBytes(entity.bytesBlob)
|
||||
entity.bytesBlob = ByteArray(0)
|
||||
entity.cipherVersion = CIPHER_VERSION_PLAIN
|
||||
attachmentBox.put(entity)
|
||||
done++
|
||||
onProgress(done, total)
|
||||
}
|
||||
}
|
||||
|
||||
/** True when any row is still marked encrypted. */
|
||||
fun hasEncryptedRows(): Boolean =
|
||||
noteBox.all.any { it.cipherVersion == CIPHER_VERSION_AES_GCM } ||
|
||||
attachmentBox.all.any { it.cipherVersion == CIPHER_VERSION_AES_GCM }
|
||||
|
||||
/**
|
||||
* Startup integrity check. Runs a **full trial decrypt** over every
|
||||
* note row marked `cipherVersion = 1` — the GCM auth tag failing is
|
||||
* our proof the row is corrupt / wrong-key, and such a row is
|
||||
* reported in [EncryptionVerification.failedNoteIds] instead of
|
||||
* earning the badge.
|
||||
*
|
||||
* Blocking — call from a background dispatcher (never the main
|
||||
* thread). When no cipher is configured, any encrypted row is
|
||||
* counted as failed (it is unreadable until the key is restored).
|
||||
*/
|
||||
fun verifyAll(): EncryptionVerification = run {
|
||||
val cipher = cipherHolder.cipher
|
||||
val verified = HashSet<Long>()
|
||||
val failed = HashSet<Long>()
|
||||
|
||||
for (entity in noteBox.all) {
|
||||
if (entity.cipherVersion != CIPHER_VERSION_AES_GCM) continue
|
||||
val ok = cipher != null && runCatching {
|
||||
if (entity.contentBlob.isEmpty()) {
|
||||
false
|
||||
} else {
|
||||
cipher.decryptString(entity.contentBlob)
|
||||
true
|
||||
}
|
||||
}.getOrDefault(false)
|
||||
if (ok) verified.add(entity.id) else failed.add(entity.id)
|
||||
}
|
||||
|
||||
EncryptionVerification(
|
||||
verifiedNoteIds = verified,
|
||||
failedNoteIds = failed,
|
||||
checkedAt = System.currentTimeMillis(),
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -16,6 +16,12 @@ import org.incido.domain.model.NoteAttachment
|
||||
* 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(
|
||||
@@ -26,7 +32,39 @@ data class NoteAttachmentEntity(
|
||||
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,
|
||||
|
||||
@@ -12,6 +12,14 @@ import org.incido.domain.model.NoteColor
|
||||
*
|
||||
* 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.
|
||||
*/
|
||||
@Entity
|
||||
data class NoteEntity(
|
||||
@@ -21,7 +29,37 @@ data class NoteEntity(
|
||||
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),
|
||||
) {
|
||||
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 (cipherVersion != other.cipherVersion) return false
|
||||
if (!contentBlob.contentEquals(other.contentBlob)) 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 + cipherVersion.hashCode()
|
||||
result = 31 * result + contentBlob.contentHashCode()
|
||||
return result
|
||||
}
|
||||
}
|
||||
|
||||
internal fun NoteEntity.toDomain(): Note = Note(
|
||||
id = id,
|
||||
|
||||
@@ -17,6 +17,9 @@ import kotlinx.coroutines.flow.callbackFlow
|
||||
import kotlinx.coroutines.flow.flowOn
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.withContext
|
||||
import org.incido.data.crypto.CIPHER_VERSION_AES_GCM
|
||||
import org.incido.data.crypto.CIPHER_VERSION_PLAIN
|
||||
import org.incido.data.crypto.CipherHolder
|
||||
import org.incido.data.entity.HashtagEntity
|
||||
import org.incido.data.entity.HashtagEntity_
|
||||
import org.incido.data.entity.NoteAttachmentEntity
|
||||
@@ -45,11 +48,24 @@ import org.incido.domain.repository.NoteRepository
|
||||
* Note: ObjectBox 4.0.3's Kotlin stubs are finicky around
|
||||
* `QueryBuilder.equal(Property, String, ...)` — passing the
|
||||
* `StringOrder` argument explicitly is the most reliable way to call it.
|
||||
*
|
||||
* v0.3.5.0 — at-rest field encryption. The repository consults
|
||||
* [cipherHolder] on every read/write: when a cipher is active (settings
|
||||
* "Encrypt notes at rest" is on), note content and attachment bytes are
|
||||
* stored AES-256-GCM encrypted (`cipherVersion = 1`) and transparently
|
||||
* decrypted on every read. Rows are self-describing via `cipherVersion`,
|
||||
* so a store can hold a mix of plaintext and encrypted rows during
|
||||
* (or after an interrupted) migration, and toggling encryption does not
|
||||
* require an app restart. With no cipher set the repository behaves
|
||||
* exactly like v0.3.4.0.
|
||||
*/
|
||||
class NoteRepositoryImpl(
|
||||
private val boxStore: BoxStore,
|
||||
private val cipherHolder: CipherHolder = CipherHolder(),
|
||||
) : NoteRepository {
|
||||
|
||||
private val fieldCipher get() = cipherHolder.cipher
|
||||
|
||||
private val noteBox = boxStore.boxFor<NoteEntity>()
|
||||
private val tagBox = boxStore.boxFor<HashtagEntity>()
|
||||
private val xrefBox = boxStore.boxFor<NoteHashtagCrossRef>()
|
||||
@@ -158,7 +174,8 @@ class NoteRepositoryImpl(
|
||||
}.flowOn(Dispatchers.Default)
|
||||
|
||||
override suspend fun getAttachmentBytes(id: Long): ByteArray? {
|
||||
return attachmentBox.get(id)?.bytes
|
||||
val entity = attachmentBox.get(id) ?: return null
|
||||
return decryptAttachmentBytes(entity)
|
||||
}
|
||||
|
||||
override suspend fun addAttachment(
|
||||
@@ -185,7 +202,102 @@ class NoteRepositoryImpl(
|
||||
sizeBytes = storedBytes.size.toLong(),
|
||||
bytes = storedBytes,
|
||||
)
|
||||
return attachmentBox.put(entity)
|
||||
return attachmentBox.put(applyAttachmentEncryption(entity))
|
||||
}
|
||||
|
||||
/**
|
||||
* v0.3.5.0 — encrypt the attachment blob before it hits disk when
|
||||
* a [fieldCipher] is active. Plaintext rows pass through unchanged
|
||||
* (and any stale blob/version from a previous state is cleared).
|
||||
*/
|
||||
private fun applyAttachmentEncryption(entity: NoteAttachmentEntity): NoteAttachmentEntity {
|
||||
val cipher = fieldCipher
|
||||
return if (cipher == null) {
|
||||
entity.apply {
|
||||
cipherVersion = CIPHER_VERSION_PLAIN
|
||||
bytesBlob = ByteArray(0)
|
||||
}
|
||||
} else {
|
||||
entity.apply {
|
||||
bytesBlob = cipher.encryptBytes(bytes)
|
||||
bytes = ByteArray(0)
|
||||
cipherVersion = CIPHER_VERSION_AES_GCM
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* v0.3.5.0 — reverse of [applyAttachmentEncryption]. Rows are
|
||||
* self-describing via `cipherVersion`, so a row written while
|
||||
* encryption was off still reads correctly after it is turned on
|
||||
* (and vice-versa) until the migration sweep re-keys it.
|
||||
*/
|
||||
private fun decryptAttachmentBytes(entity: NoteAttachmentEntity): ByteArray {
|
||||
return when {
|
||||
entity.cipherVersion == CIPHER_VERSION_AES_GCM -> {
|
||||
val cipher = fieldCipher
|
||||
?: error("Encrypted attachment row ${entity.id} but no cipher configured")
|
||||
cipher.decryptBytes(entity.bytesBlob)
|
||||
}
|
||||
else -> entity.bytes
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* v0.3.5.0 — return a plaintext *view* of [entity] for domain
|
||||
* mapping. Encrypted rows (`cipherVersion = 1`) are decrypted on
|
||||
* the fly; plaintext rows pass through unchanged. The returned
|
||||
* entity must never be `put` back into the box — it is read-only.
|
||||
*/
|
||||
private fun toReadable(entity: NoteEntity): NoteEntity {
|
||||
if (entity.cipherVersion != CIPHER_VERSION_AES_GCM) return entity
|
||||
val cipher = fieldCipher
|
||||
if (cipher == null || entity.contentBlob.isEmpty()) {
|
||||
// Encrypted row but no key configured (e.g. encryption was
|
||||
// disabled and the reverse migration didn't finish). The
|
||||
// content is unreadable — surface it empty rather than
|
||||
// crash the whole list; the startup verifier reports it.
|
||||
return entity
|
||||
}
|
||||
return entity.copy(content = cipher.decryptString(entity.contentBlob))
|
||||
}
|
||||
|
||||
/**
|
||||
* v0.3.5.0 — prepare an entity for storage. When a cipher is
|
||||
* active the content is encrypted into [NoteEntity.contentBlob]
|
||||
* and the plaintext column is cleared; otherwise any stale
|
||||
* ciphertext is wiped so the row is genuinely plaintext.
|
||||
*/
|
||||
private fun toWritable(entity: NoteEntity): NoteEntity {
|
||||
val cipher = fieldCipher ?: return entity.apply {
|
||||
cipherVersion = CIPHER_VERSION_PLAIN
|
||||
contentBlob = ByteArray(0)
|
||||
}
|
||||
return entity.apply {
|
||||
contentBlob = cipher.encryptString(content)
|
||||
content = ""
|
||||
cipherVersion = CIPHER_VERSION_AES_GCM
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* v0.3.5.0 — cipher-aware content matcher. ObjectBox's `contains()`
|
||||
* query cannot see ciphertext, so when encryption is active we
|
||||
* decrypt and filter in-memory (fine at notes-app scale). Hashtag
|
||||
* matching is unaffected — tag names stay plaintext.
|
||||
*/
|
||||
private fun contentMatchingNoteIds(query: String): List<Long> {
|
||||
if (fieldCipher == null) {
|
||||
return noteBox.query()
|
||||
.contains(NoteEntity_.content, query, QueryBuilder.StringOrder.CASE_INSENSITIVE)
|
||||
.build()
|
||||
.find()
|
||||
.map { it.id }
|
||||
}
|
||||
val needle = query.lowercase()
|
||||
return noteBox.all
|
||||
.filter { toReadable(it).content.lowercase().contains(needle) }
|
||||
.map { it.id }
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -236,8 +348,9 @@ class NoteRepositoryImpl(
|
||||
} else {
|
||||
note.copy(updatedAt = now).toEntity()
|
||||
}
|
||||
val assignedId = noteBox.put(toPersist)
|
||||
return noteBox.get(assignedId)?.toDomain() ?: note.copy(id = assignedId)
|
||||
val assignedId = noteBox.put(toWritable(toPersist))
|
||||
return noteBox.get(assignedId)?.let { toReadable(it).toDomain() }
|
||||
?: note.copy(id = assignedId)
|
||||
}
|
||||
|
||||
override suspend fun delete(id: Long) {
|
||||
@@ -289,8 +402,8 @@ class NoteRepositoryImpl(
|
||||
// tagBox observer could fire between the tagBox.put and the
|
||||
// xrefBox.put, leaving the snapshot stuck on emptyList().
|
||||
return boxStore.callInTx(Callable {
|
||||
val assignedId = noteBox.put(toPersist)
|
||||
val saved = noteBox.get(assignedId)?.toDomain()
|
||||
val assignedId = noteBox.put(toWritable(toPersist))
|
||||
val saved = noteBox.get(assignedId)?.let { toReadable(it).toDomain() }
|
||||
?: note.copy(id = assignedId)
|
||||
hashtagsToRemove.forEach { removeHashtagInternal(saved.id, it) }
|
||||
hashtagsToAdd.forEach { addHashtagInternal(saved.id, it) }
|
||||
@@ -394,7 +507,7 @@ class NoteRepositoryImpl(
|
||||
compareByDescending<NoteEntity> { it.isFavorite }
|
||||
.thenByDescending { it.updatedAt }
|
||||
).map { e ->
|
||||
val base = e.toDomain()
|
||||
val base = toReadable(e).toDomain()
|
||||
base.copy(
|
||||
hashtags = tags[e.id].orEmpty(),
|
||||
attachments = attachments[e.id].orEmpty(),
|
||||
@@ -409,11 +522,9 @@ class NoteRepositoryImpl(
|
||||
if (q.isEmpty()) return snapshotAll()
|
||||
|
||||
// Match against content (contains, case-insensitive).
|
||||
val contentMatches: List<Long> = noteBox.query()
|
||||
.contains(NoteEntity_.content, q, QueryBuilder.StringOrder.CASE_INSENSITIVE)
|
||||
.build()
|
||||
.find()
|
||||
.map { it.id }
|
||||
// v0.3.5.0: cipher-aware — ObjectBox `contains()` can't see
|
||||
// ciphertext, so encrypted stores match in-memory.
|
||||
val contentMatches: List<Long> = contentMatchingNoteIds(q)
|
||||
|
||||
// Match against hashtag names (case-insensitive exact equality).
|
||||
val matchingTag: HashtagEntity? = tagBox.query()
|
||||
@@ -474,11 +585,7 @@ class NoteRepositoryImpl(
|
||||
val q = query.trim()
|
||||
if (q.isEmpty()) return snapshotUntagged()
|
||||
val noteIdsWithTags: Set<Long> = xrefBox.all.mapTo(HashSet(xrefBox.all.size)) { it.noteId }
|
||||
val contentMatches: List<Long> = noteBox.query()
|
||||
.contains(NoteEntity_.content, q, QueryBuilder.StringOrder.CASE_INSENSITIVE)
|
||||
.build()
|
||||
.find()
|
||||
.map { it.id }
|
||||
val contentMatches: List<Long> = contentMatchingNoteIds(q)
|
||||
val matching: List<NoteEntity> = contentMatches
|
||||
.mapNotNull { id -> noteBox.get(id) }
|
||||
.filter { it.id !in noteIdsWithTags }
|
||||
@@ -491,11 +598,7 @@ class NoteRepositoryImpl(
|
||||
*/
|
||||
private fun snapshotSearchMatchingNoteIds(query: String): Set<Long> {
|
||||
// Match against content (contains, case-insensitive).
|
||||
val contentMatches: List<Long> = noteBox.query()
|
||||
.contains(NoteEntity_.content, query, QueryBuilder.StringOrder.CASE_INSENSITIVE)
|
||||
.build()
|
||||
.find()
|
||||
.map { it.id }
|
||||
val contentMatches: List<Long> = contentMatchingNoteIds(query)
|
||||
|
||||
// Match against hashtag names (case-insensitive exact equality).
|
||||
val matchingTag: HashtagEntity? = tagBox.query()
|
||||
@@ -533,7 +636,7 @@ class NoteRepositoryImpl(
|
||||
val entity = noteBox.get(id) ?: return null
|
||||
val tags = hashtagsByNoteId()[id].orEmpty()
|
||||
val attachments = attachmentsByNoteId()[id].orEmpty()
|
||||
return entity.toDomain().copy(
|
||||
return toReadable(entity).toDomain().copy(
|
||||
hashtags = tags,
|
||||
attachments = attachments,
|
||||
)
|
||||
|
||||
Reference in new issue
Block a user