feat(phase-1/m2.1): :core:backup — codecs + stream-based BackupBridge

Phase 1 M2 task 1 (tools/DESKTOP_PHASE_PLAN.md §4): extract the backup
bridge from :composeApp into a plain kotlin("jvm") module so the desktop
build can import/export the phone file format.

- git mv BackupCodec / EncryptedBackupCodec / EncryptedKeyCodec into
  core/backup, keeping the org.incido.compose.data.backup package so the
  Android diff is file moves + one dependency line (no import churn).
- New BackupBridge: the four BackupManager operations over
  InputStream/OutputStream instead of Uri (incl. the v0.3.3.3 preview
  hotfix catches); BackupPreview moves with it, same package.
- BackupManager stays in :composeApp as a thin Uri -> stream SAF shim,
  public API unchanged. Dedupe = task 3, desktop picker UI = task 2.

Verification passed: ./gradlew :core:backup:build :core:data-jvm:smoke
:spike:data-jvm:run + assembleDebug + :desktopApp:run --args="--data-dir
/tmp/incido-desktop-smoke --self-test --exit-after 6" — all green; run
output recorded in tools/DESKTOP_FEASIBILITY.md (Phase 1 status).
This commit is contained in:
Incido Developer committed 2026-10-05 18:51:07 +13:00
1 parent b11c02e1b4
commit 7cc4eda90d
9 files changed
+262 -92

No files matched your search

+4
View File
@@ -43,6 +43,10 @@ android {
dependencies { dependencies {
implementation(project(":core:domain")) implementation(project(":core:domain"))
implementation(project(":core:data")) implementation(project(":core:data"))
// Phase 1 (M2 task 1): backup codecs + bridge now live here; the
// org.incido.compose.data.backup package name was kept, so no imports
// changed — only this dependency line.
implementation(project(":core:backup"))
// Core / lifecycle // Core / lifecycle
implementation(libs.androidx.core.ktx) implementation(libs.androidx.core.ktx)
@@ -2,6 +2,7 @@ package org.incido.compose.data.backup
import android.content.Context import android.content.Context
import android.net.Uri import android.net.Uri
import java.io.IOException
import java.io.InputStream import java.io.InputStream
import java.io.OutputStream import java.io.OutputStream
import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Dispatchers
@@ -11,15 +12,16 @@ import org.incido.domain.repository.NoteRepository
/** /**
* v0.3.2.0: orchestration layer for Backup / Import / Export. * v0.3.2.0: orchestration layer for Backup / Import / Export.
* *
* Reads / writes go through the Storage Access Framework — the * Phase 1 (M2 task 1): this class is now a **thin Storage Access
* Activity hands in [Uri]s from * Framework shim**. It converts the [Uri]s that
* `ActivityResultContracts.CreateDocument` / `OpenDocument` and the * `ActivityResultContracts.CreateDocument` / `OpenDocument` hand back
* manager streams bytes in / out via ContentResolver. No fixed-path * into streams and delegates everything else — format, crypto,
* writes, no extra permissions. * snapshotting — to [BackupManager]'s former body, now the platform-
* neutral [BackupBridge] in `:core:backup`. The desktop app (M2 task 2)
* calls [BackupBridge] directly with file streams.
* *
* Encrypt-on-export and decrypt-on-import are selected by the caller; * Public API is unchanged: [SettingsViewModel] and the backup screens
* the codecs themselves ([BackupCodec], [EncryptedBackupCodec]) hold * compile exactly as before.
* the format / cipher details.
*/ */
class BackupManager( class BackupManager(
private val context: Context, private val context: Context,
@@ -37,14 +39,7 @@ class BackupManager(
appVersion: String, appVersion: String,
onProgress: (current: Int, total: Int) -> Unit = { _, _ -> }, onProgress: (current: Int, total: Int) -> Unit = { _, _ -> },
): Int = withContext(Dispatchers.IO) { ): Int = withContext(Dispatchers.IO) {
val file = BackupCodec.exportSnapshot(repository, appVersion) BackupBridge.exportPlain(repository, openOutput(uri), appVersion, onProgress)
val json = BackupCodec.encode(file)
context.contentResolver.openOutputStream(uri, "wt")?.use { out: OutputStream ->
out.write(json.toByteArray(Charsets.UTF_8))
out.flush()
} ?: throw java.io.IOException("Could not open output stream for $uri")
onProgress(file.notes.size, file.notes.size)
file.notes.size
} }
/** /**
@@ -58,15 +53,7 @@ class BackupManager(
appVersion: String, appVersion: String,
onProgress: (current: Int, total: Int) -> Unit = { _, _ -> }, onProgress: (current: Int, total: Int) -> Unit = { _, _ -> },
): Int = withContext(Dispatchers.IO) { ): Int = withContext(Dispatchers.IO) {
val file = BackupCodec.exportSnapshot(repository, appVersion) BackupBridge.exportEncrypted(repository, openOutput(uri), passphrase, appVersion, onProgress)
val json = BackupCodec.encode(file)
val payload = EncryptedBackupCodec.encrypt(json, passphrase)
context.contentResolver.openOutputStream(uri, "wt")?.use { out ->
out.write(payload)
out.flush()
} ?: throw java.io.IOException("Could not open output stream for $uri")
onProgress(file.notes.size, file.notes.size)
file.notes.size
} }
/** /**
@@ -82,20 +69,7 @@ class BackupManager(
passphrase: CharArray? = null, passphrase: CharArray? = null,
onProgress: (current: Int, total: Int) -> Unit = { _, _ -> }, onProgress: (current: Int, total: Int) -> Unit = { _, _ -> },
): Int = withContext(Dispatchers.IO) { ): Int = withContext(Dispatchers.IO) {
val bytes = context.contentResolver.openInputStream(uri)?.use { it.readBytes() } BackupBridge.import(repository, openInput(uri), passphrase, onProgress)
?: throw java.io.IOException("Could not open input stream for $uri")
val json: String = if (EncryptedBackupCodec.isEncrypted(bytes)) {
val pass = passphrase
?: throw IllegalArgumentException("Encrypted backup requires a passphrase")
EncryptedBackupCodec.decrypt(bytes, pass)
} else {
String(bytes, Charsets.UTF_8)
}
val file = BackupCodec.decode(json)
BackupCodec.importSnapshot(file, repository) { cur, tot -> onProgress(cur, tot) }
file.notes.size
} }
/** /**
@@ -108,60 +82,19 @@ class BackupManager(
*/ */
suspend fun preview(uri: Uri, passphrase: CharArray? = null): BackupPreview? = suspend fun preview(uri: Uri, passphrase: CharArray? = null): BackupPreview? =
withContext(Dispatchers.IO) { withContext(Dispatchers.IO) {
val bytes: ByteArray = try { val input: InputStream = try {
context.contentResolver.openInputStream(uri)?.use(InputStream::readBytes) context.contentResolver.openInputStream(uri) ?: return@withContext null
?: return@withContext null } catch (_: IOException) {
} catch (_: java.io.IOException) {
return@withContext null return@withContext null
} }
val json: String = if (EncryptedBackupCodec.isEncrypted(bytes)) { BackupBridge.preview(input, passphrase)
val pass = passphrase ?: return@withContext null
try {
EncryptedBackupCodec.decrypt(bytes, pass)
} catch (_: javax.crypto.AEADBadTagException) {
return@withContext null
} catch (_: javax.crypto.BadPaddingException) {
return@withContext null
} catch (_: IllegalArgumentException) {
// v0.3.3.3 hotfix: a truncated / corrupt envelope
// fails the require(...) size checks inside
// decrypt() with an IllegalArgumentException.
// Previously that escaped preview() and crashed the
// coroutine; treat it the same as a bad passphrase.
return@withContext null
} catch (_: java.security.GeneralSecurityException) {
// Catch-all for any other cipher-layer failure.
return@withContext null
}
} else {
try {
String(bytes, Charsets.UTF_8)
} catch (_: java.io.IOException) {
return@withContext null
}
}
val file: BackupFile = try {
BackupCodec.decode(json)
} catch (_: kotlinx.serialization.SerializationException) {
return@withContext null
} catch (_: Exception) {
// v0.3.3.3 hotfix: any other decode failure (e.g. the
// payload wasn't JSON after all) must not escape.
return@withContext null
}
BackupPreview(
noteCount = file.notes.size,
attachmentCount = file.notes.sumOf { it.attachments.size },
appVersion = file.appVersion,
exportedAt = file.exportedAt,
)
}
} }
/** Lightweight DTO shown in the import confirmation dialog. */ private fun openOutput(uri: Uri): OutputStream =
data class BackupPreview( context.contentResolver.openOutputStream(uri, "wt")
val noteCount: Int, ?: throw IOException("Could not open output stream for $uri")
val attachmentCount: Int,
val appVersion: String, private fun openInput(uri: Uri): InputStream =
val exportedAt: Long, context.contentResolver.openInputStream(uri)
) ?: throw IOException("Could not open input stream for $uri")
}
+34
View File
@@ -0,0 +1,34 @@
// core/backup — Phase 1 (M2 task 1): the backup bridge, extracted from
// :composeApp so the desktop build can speak the phone's file format.
//
// Everything here is pure JVM/kotlinx (verified by reading the code in the
// Phase-0 spike: zero android.* imports in the codecs). The package name
// stays org.incido.compose.data.backup so the Android diff is file moves
// only — no import churn in composeApp.
//
// Shape follows :core:domain (plain kotlin("jvm"), consumed by both the
// Android app and the desktop app). No ObjectBox here: the codec talks to
// the app only through the NoteRepository interface from :core:domain.
plugins {
alias(libs.plugins.kotlinJvm)
// @Serializable DTOs (BackupFile / BackupNote / BackupAttachment) live in
// BackupCodec.kt — the plugin generates their serializers here.
alias(libs.plugins.kotlinSerialization)
}
java {
sourceCompatibility = JavaVersion.VERSION_17
targetCompatibility = JavaVersion.VERSION_17
}
kotlin {
jvmToolchain(17)
}
dependencies {
// Public API speaks domain types (Note, NoteRepository) — api, not impl.
api(project(":core:domain"))
implementation(libs.kotlinx.coroutines.core)
implementation(libs.kotlinx.serialization.json)
}
@@ -0,0 +1,164 @@
package org.incido.compose.data.backup
import java.io.IOException
import java.io.InputStream
import java.io.OutputStream
import java.security.GeneralSecurityException
import javax.crypto.AEADBadTagException
import javax.crypto.BadPaddingException
import org.incido.domain.repository.NoteRepository
/**
* Phase 1 (M2 task 1): platform-neutral orchestration for Backup /
* Import / Export, extracted from `BackupManager` so the desktop build
* can speak the exact same file format as the phone.
*
* The only difference from the old `BackupManager` internals is the I/O
* boundary: streams in, streams out — no `Uri`, no `ContentResolver`, no
* `Context`. Android keeps a thin `Uri → stream` shim around this object;
* desktop will hand it `FileInputStream` / `FileOutputStream` (task 2).
*
* Format / cipher details stay in [BackupCodec] and
* [EncryptedBackupCodec]; this class only sequences them. Like the codecs,
* these functions are **not** dispatcher-wrapped — the caller decides
* (Android's shim uses `withContext(Dispatchers.IO)`).
*/
object BackupBridge {
/**
* Snapshot every note in [repository] and write it to [output] as
* plain JSON. Closes [output]. Throws on I/O failure.
*
* Returns the number of notes exported.
*/
suspend fun exportPlain(
repository: NoteRepository,
output: OutputStream,
appVersion: String,
onProgress: (current: Int, total: Int) -> Unit = { _, _ -> },
): Int {
val file = BackupCodec.exportSnapshot(repository, appVersion)
val json = BackupCodec.encode(file)
output.use { out ->
out.write(json.toByteArray(Charsets.UTF_8))
out.flush()
}
onProgress(file.notes.size, file.notes.size)
return file.notes.size
}
/**
* Snapshot every note and write it to [output] as a passphrase-
* encrypted envelope. Closes [output]. [passphrase] is consumed
* (zeroed) inside [EncryptedBackupCodec.encrypt].
*
* Returns the number of notes exported.
*/
suspend fun exportEncrypted(
repository: NoteRepository,
output: OutputStream,
passphrase: CharArray,
appVersion: String,
onProgress: (current: Int, total: Int) -> Unit = { _, _ -> },
): Int {
val file = BackupCodec.exportSnapshot(repository, appVersion)
val json = BackupCodec.encode(file)
val payload = EncryptedBackupCodec.encrypt(json, passphrase)
output.use { out ->
out.write(payload)
out.flush()
}
onProgress(file.notes.size, file.notes.size)
return file.notes.size
}
/**
* Read [input] and import every note it contains. Closes [input].
* Auto-detects plain vs encrypted via the magic header. For
* encrypted files, [passphrase] is required (caller validates with
* `PasswordPolicy`).
*
* Errors surface as thrown exceptions, same as the old
* `BackupManager.import`: missing passphrase →
* [IllegalArgumentException]; bad passphrase / corrupt envelope →
* `GeneralSecurityException` family.
*
* Returns the number of notes imported.
*/
suspend fun import(
repository: NoteRepository,
input: InputStream,
passphrase: CharArray? = null,
onProgress: (current: Int, total: Int) -> Unit = { _, _ -> },
): Int {
val bytes = input.use(InputStream::readBytes)
val json = payloadJson(bytes, passphrase)
val file = BackupCodec.decode(json)
BackupCodec.importSnapshot(file, repository) { cur, tot -> onProgress(cur, tot) }
return file.notes.size
}
/**
* Cheap metadata preview — used by the "Import from file…" flow
* to show the user how many notes / attachments they're about to
* bring in before they commit. Closes [input].
*
* Returns `null` if the file can't be read or the passphrase is
* wrong (so the UI can surface "wrong passphrase" cleanly).
*/
fun preview(input: InputStream, passphrase: CharArray? = null): BackupPreview? {
val bytes: ByteArray = try {
input.use(InputStream::readBytes)
} catch (_: IOException) {
return null
}
val json: String = try {
payloadJson(bytes, passphrase)
} catch (_: AEADBadTagException) {
return null
} catch (_: BadPaddingException) {
return null
} catch (_: IllegalArgumentException) {
// v0.3.3.3 hotfix (kept from BackupManager.preview): a
// truncated / corrupt envelope fails the require(...) size
// checks inside decrypt(); treat it like a bad passphrase
// instead of letting it escape and crash the coroutine.
return null
} catch (_: GeneralSecurityException) {
// Catch-all for any other cipher-layer failure.
return null
}
val file: BackupFile = try {
BackupCodec.decode(json)
} catch (_: kotlinx.serialization.SerializationException) {
return null
} catch (_: Exception) {
// v0.3.3.3 hotfix: any other decode failure (e.g. the
// payload wasn't JSON after all) must not escape.
return null
}
return BackupPreview(
noteCount = file.notes.size,
attachmentCount = file.notes.sumOf { it.attachments.size },
appVersion = file.appVersion,
exportedAt = file.exportedAt,
)
}
/** Decrypt-if-encrypted / pass-through-if-plain, shared by import + preview. */
private fun payloadJson(bytes: ByteArray, passphrase: CharArray?): String {
if (!EncryptedBackupCodec.isEncrypted(bytes)) return String(bytes, Charsets.UTF_8)
val pass = passphrase
?: throw IllegalArgumentException("Encrypted backup requires a passphrase")
return EncryptedBackupCodec.decrypt(bytes, pass)
}
}
/** Lightweight DTO shown in the import confirmation dialog. */
data class BackupPreview(
val noteCount: Int,
val attachmentCount: Int,
val appVersion: String,
val exportedAt: Long,
)
+6
View File
@@ -37,6 +37,12 @@ include(":core:data-jvm")
// file is the only bridge to the phone (M2). // file is the only bridge to the phone (M2).
include(":desktopApp") include(":desktopApp")
// Phase 1 (M2 task 1): the backup bridge — codecs + stream-based
// import/export, extracted from :composeApp so :desktopApp can read and
// write the SAME file format the phone produces. Plain kotlin("jvm"),
// consumed by both platforms.
include(":core:backup")
// --- Desktop feasibility spike (Development Plan §6.3, throwaway) --- // --- Desktop feasibility spike (Development Plan §6.3, throwaway) ---
// Throwaway probes that answer "can the existing stack run on the JVM" // Throwaway probes that answer "can the existing stack run on the JVM"
// before any of Phases 1-6 are committed to. They are additive: no module // before any of Phases 1-6 are committed to. They are additive: no module
+29
View File
@@ -266,3 +266,32 @@ Still synthetic in this build: the theme (Material 3 defaults, not Incido's)
and the screens (this is a two-pane stand-in). Both are replaced by the M4 and the screens (this is a two-pane stand-in). Both are replaced by the M4
`composeApp` commonMain conversion. Not yet wired: settings, encryption (M3), `composeApp` commonMain conversion. Not yet wired: settings, encryption (M3),
backups (M2), packaging (M5). backups (M2), packaging (M5).
**M2 task 1 — extract `:core:backup`: DONE.** New plain-`kotlin("jvm")`
module holding `BackupCodec.kt`, `EncryptedBackupCodec.kt` and
`EncryptedKeyCodec.kt` (`git mv` — the Android diff is the three moves plus
one dependency line) and a new `BackupBridge`: the four `BackupManager`
operations re-expressed over `InputStream`/`OutputStream` instead of `Uri`.
The package name `org.incido.compose.data.backup` was kept on purpose, so no
consumer import changed; `BackupManager` stays in `:composeApp` as a thin
`Uri → stream` SAF shim with an identical public API (`BackupPreview` moved
to the bridge file, same package). Dedupe is task 3, desktop picker UI is
task 2 — deliberately not here.
Verification (all after the move, from a clean state):
```
./gradlew :core:backup:build BUILD SUCCESSFUL (serializers generated in the new module)
./gradlew assembleDebug BUILD SUCCESSFUL — Android unchanged
./gradlew :core:data-jvm:smoke RESULT: M1a PASS — the shared data layer runs on the JVM
./gradlew :desktopApp:run --args="--data-dir /tmp/incido-desktop-smoke --self-test --exit-after 6"
SELFTEST wrote note id=1 → RENDER notes=1 selected=1
./gradlew :spike:data-jvm:run … recovery-key envelope (real codec) PASS — 84-byte envelope,
32-byte key round-tripped; wrong passphrase → AEADBadTagException
```
Housekeeping found on the way: `:core:data-jvm:smoke` does not clear
`build/data-jvm-smoke/`, and the script asserts on a fresh library — a
second consecutive run fails with "expected 1 note, got 2". Run it against
a deleted directory (worth fixing in a later milestone).