diff --git a/composeApp/build.gradle.kts b/composeApp/build.gradle.kts index ca9a2cc..785f0c3 100644 --- a/composeApp/build.gradle.kts +++ b/composeApp/build.gradle.kts @@ -43,6 +43,10 @@ android { dependencies { implementation(project(":core:domain")) 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 implementation(libs.androidx.core.ktx) diff --git a/composeApp/src/main/kotlin/org/incido/compose/data/backup/BackupManager.kt b/composeApp/src/main/kotlin/org/incido/compose/data/backup/BackupManager.kt index c387231..2311b5b 100644 --- a/composeApp/src/main/kotlin/org/incido/compose/data/backup/BackupManager.kt +++ b/composeApp/src/main/kotlin/org/incido/compose/data/backup/BackupManager.kt @@ -2,6 +2,7 @@ package org.incido.compose.data.backup import android.content.Context import android.net.Uri +import java.io.IOException import java.io.InputStream import java.io.OutputStream import kotlinx.coroutines.Dispatchers @@ -11,15 +12,16 @@ import org.incido.domain.repository.NoteRepository /** * v0.3.2.0: orchestration layer for Backup / Import / Export. * - * Reads / writes go through the Storage Access Framework — the - * Activity hands in [Uri]s from - * `ActivityResultContracts.CreateDocument` / `OpenDocument` and the - * manager streams bytes in / out via ContentResolver. No fixed-path - * writes, no extra permissions. + * Phase 1 (M2 task 1): this class is now a **thin Storage Access + * Framework shim**. It converts the [Uri]s that + * `ActivityResultContracts.CreateDocument` / `OpenDocument` hand back + * into streams and delegates everything else — format, crypto, + * 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; - * the codecs themselves ([BackupCodec], [EncryptedBackupCodec]) hold - * the format / cipher details. + * Public API is unchanged: [SettingsViewModel] and the backup screens + * compile exactly as before. */ class BackupManager( private val context: Context, @@ -37,14 +39,7 @@ class BackupManager( appVersion: String, onProgress: (current: Int, total: Int) -> Unit = { _, _ -> }, ): Int = withContext(Dispatchers.IO) { - val file = BackupCodec.exportSnapshot(repository, appVersion) - 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 + BackupBridge.exportPlain(repository, openOutput(uri), appVersion, onProgress) } /** @@ -58,15 +53,7 @@ class BackupManager( appVersion: String, onProgress: (current: Int, total: Int) -> Unit = { _, _ -> }, ): Int = withContext(Dispatchers.IO) { - val file = BackupCodec.exportSnapshot(repository, appVersion) - 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 + BackupBridge.exportEncrypted(repository, openOutput(uri), passphrase, appVersion, onProgress) } /** @@ -82,20 +69,7 @@ class BackupManager( passphrase: CharArray? = null, onProgress: (current: Int, total: Int) -> Unit = { _, _ -> }, ): Int = withContext(Dispatchers.IO) { - val bytes = context.contentResolver.openInputStream(uri)?.use { it.readBytes() } - ?: 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 + BackupBridge.import(repository, openInput(uri), passphrase, onProgress) } /** @@ -108,60 +82,19 @@ class BackupManager( */ suspend fun preview(uri: Uri, passphrase: CharArray? = null): BackupPreview? = withContext(Dispatchers.IO) { - val bytes: ByteArray = try { - context.contentResolver.openInputStream(uri)?.use(InputStream::readBytes) - ?: return@withContext null - } catch (_: java.io.IOException) { + val input: InputStream = try { + context.contentResolver.openInputStream(uri) ?: return@withContext null + } catch (_: IOException) { return@withContext null } - val json: String = if (EncryptedBackupCodec.isEncrypted(bytes)) { - 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, - ) + BackupBridge.preview(input, passphrase) } -} -/** Lightweight DTO shown in the import confirmation dialog. */ -data class BackupPreview( - val noteCount: Int, - val attachmentCount: Int, - val appVersion: String, - val exportedAt: Long, -) + private fun openOutput(uri: Uri): OutputStream = + context.contentResolver.openOutputStream(uri, "wt") + ?: throw IOException("Could not open output stream for $uri") + + private fun openInput(uri: Uri): InputStream = + context.contentResolver.openInputStream(uri) + ?: throw IOException("Could not open input stream for $uri") +} diff --git a/core/backup/build.gradle.kts b/core/backup/build.gradle.kts new file mode 100644 index 0000000..9aa6497 --- /dev/null +++ b/core/backup/build.gradle.kts @@ -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) +} diff --git a/core/backup/src/main/kotlin/org/incido/compose/data/backup/BackupBridge.kt b/core/backup/src/main/kotlin/org/incido/compose/data/backup/BackupBridge.kt new file mode 100644 index 0000000..807095d --- /dev/null +++ b/core/backup/src/main/kotlin/org/incido/compose/data/backup/BackupBridge.kt @@ -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, +) + diff --git a/composeApp/src/main/kotlin/org/incido/compose/data/backup/BackupCodec.kt b/core/backup/src/main/kotlin/org/incido/compose/data/backup/BackupCodec.kt similarity index 100% rename from composeApp/src/main/kotlin/org/incido/compose/data/backup/BackupCodec.kt rename to core/backup/src/main/kotlin/org/incido/compose/data/backup/BackupCodec.kt diff --git a/composeApp/src/main/kotlin/org/incido/compose/data/backup/EncryptedBackupCodec.kt b/core/backup/src/main/kotlin/org/incido/compose/data/backup/EncryptedBackupCodec.kt similarity index 100% rename from composeApp/src/main/kotlin/org/incido/compose/data/backup/EncryptedBackupCodec.kt rename to core/backup/src/main/kotlin/org/incido/compose/data/backup/EncryptedBackupCodec.kt diff --git a/composeApp/src/main/kotlin/org/incido/compose/data/backup/EncryptedKeyCodec.kt b/core/backup/src/main/kotlin/org/incido/compose/data/backup/EncryptedKeyCodec.kt similarity index 100% rename from composeApp/src/main/kotlin/org/incido/compose/data/backup/EncryptedKeyCodec.kt rename to core/backup/src/main/kotlin/org/incido/compose/data/backup/EncryptedKeyCodec.kt diff --git a/settings.gradle.kts b/settings.gradle.kts index af5412a..7ca8a72 100644 --- a/settings.gradle.kts +++ b/settings.gradle.kts @@ -37,6 +37,12 @@ include(":core:data-jvm") // file is the only bridge to the phone (M2). 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) --- // 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 diff --git a/tools/DESKTOP_FEASIBILITY.md b/tools/DESKTOP_FEASIBILITY.md index d740353..04d2c78 100644 --- a/tools/DESKTOP_FEASIBILITY.md +++ b/tools/DESKTOP_FEASIBILITY.md @@ -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 `composeApp` commonMain conversion. Not yet wired: settings, encryption (M3), 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). +