everysync-core: KMP shared sync brain + todo notes field fix
- Commit
79315632749848a096297849a6b1b7c9ae81ad1f- Author
- vayun-mathur <[email protected]>
- When
- 2026-10-16 18:08 UTC (1 month ago)
- Parents
2baeeb5
Diff
build-logic/src/main/kotlin/common-conventions-kmp.gradle.kts
diff --git a/build-logic/src/main/kotlin/common-conventions-kmp.gradle.kts b/build-logic/src/main/kotlin/common-conventions-kmp.gradle.ktsnew file mode 100644index 0000000000..da1c5d8926--- /dev/null+++ b/build-logic/src/main/kotlin/common-conventions-kmp.gradle.kts@@ -0,0 +1,79 @@+import org.gradle.api.tasks.bundling.AbstractArchiveTask++plugins {+ // AGP 9.x KMP host plugin (replaces com.android.library for+ // multiplatform modules — androidTarget() + com.android.library is+ // rejected when android.newDsl=true). Pairs with kotlin.androidLibrary.+ id("com.android.kotlin.multiplatform.library")+ id("org.jetbrains.kotlin.multiplatform")+ id("org.jetbrains.kotlin.plugin.serialization")+ id("dev.detekt")+}++// Static analysis (./check runs `:module:detekt`). Rules live in the committed+// root detekt.yml; findings fail the task (no ignoreFailures).+// Config-cache compatible: the config file is resolved here, never a Project.+detekt {+ config.setFrom(files(rootDir.resolve("detekt.yml")))+}++val libs = the<org.gradle.accessors.dm.LibrariesForLibs>()++// Shared sync-brain conventions for `:library:everysync-core`.+//+// Targets: android + jvm (desktop) + iosArm64 + iosSimulatorArm64.+// commonMain must stay free of Android APIs — platform coupling goes through+// expect/actual (RelayTransport, SecureStore, SyncScheduler, SyncSink, AesGcm,+// SyncDigest). In particular there is deliberately NO dependency on+// `:library:log` / `:library:network` / `:library:room` here: none of them has+// a common variant, and the shared core must not inherit their Android coupling.+kotlin {+ androidLibrary {+ namespace = "com.vayunmathur.everysync.core"+ compileSdk = 37+ minSdk = 31+ }++ jvm()++ iosArm64()+ iosSimulatorArm64()++ jvmToolchain(21)++ compilerOptions {+ optIn.add("kotlin.uuid.ExperimentalUuidApi")+ freeCompilerArgs.add("-Xexpect-actual-classes")+ }++ sourceSets {+ named("commonMain") {+ dependencies {+ implementation(libs.kotlinx.coroutines.core)+ implementation(libs.kotlinx.serialization.json)+ implementation(libs.kotlinx.datetime)+ }+ }+ named("commonTest") {+ dependencies {+ implementation(libs.kotlin.test)+ implementation(libs.kotlinx.coroutines.core)+ }+ }+ named("androidMain") {+ dependencies {+ implementation(libs.kotlinx.coroutines.android)+ }+ }+ }+}++tasks.withType<AbstractArchiveTask>().configureEach {+ isPreserveFileTimestamps = false+ isReproducibleFileOrder = true+}++// Reproducible builds: log SOURCE_DATE_EPOCH if present for verification+providers.environmentVariable("SOURCE_DATE_EPOCH").orNull?.let {+ logger.lifecycle("Reproducible build: SOURCE_DATE_EPOCH=$it")+}
gradle/libs.versions.toml
diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.tomlindex ccf74c8b1e..5cdd91147f 100644--- a/gradle/libs.versions.toml+++ b/gradle/libs.versions.toml@@ -26,6 +26,9 @@ kotlinxCoroutines = "1.11.0" kotlinxSerializationJson = "1.11.0" kotlinxDatetime = "0.8.0" +# Kotlin Multiplatform shared core (:library:everysync-core) versions live with the+# crypto section below (ktor, sqldelight, jna).+ # AndroidX – core & lifecycle coreKtx = "1.19.1" fragmentKtx = "1.9.1"@@ -126,6 +129,11 @@ onnxruntimeAndroid = "1.31.0" # Crypto, security & credential storage sqlcipherAndroid = "4.19.1"+sqldelight = "2.2.0"+# Desktop JNA binding to the e2ee Rust C ABI (Phase 1D)+jna = "5.18.1"+# Ktor client for KMP RelayTransport actuals (Phase 1C)+ktor = "3.3.0" # Pinned at 0.101.x: the CDSI enclave identity is compiled into the # native library, and 0.86.5/0.92.0 carry a retired MRENCLAVE, so contact discovery requests # /v1/{stale}/discovery and the server answers 404. 0.101.x also matches the checked-out libsignal source,@@ -176,6 +184,7 @@ desugar-jdk-libs = { module = "com.android.tools:desugar_jdk_libs", version.ref # Kotlin stdlib ecosystem (JetBrains) kotlinx-coroutines-android = { module = "org.jetbrains.kotlinx:kotlinx-coroutines-android", version.ref = "kotlinxCoroutines" }+kotlinx-coroutines-core = { module = "org.jetbrains.kotlinx:kotlinx-coroutines-core", version.ref = "kotlinxCoroutines" } kotlinx-serialization-json = { module = "org.jetbrains.kotlinx:kotlinx-serialization-json", version.ref = "kotlinxSerializationJson" } kotlinx-datetime = { module = "org.jetbrains.kotlinx:kotlinx-datetime", version.ref = "kotlinxDatetime" } kotlin-test = { group = "org.jetbrains.kotlin", name = "kotlin-test", version.ref = "kotlin" }@@ -326,6 +335,19 @@ onnxruntime-android = { module = "com.microsoft.onnxruntime:onnxruntime-android" # Crypto, security & credential storage sqlcipher-android = { module = "net.zetetic:sqlcipher-android", version.ref = "sqlcipherAndroid" }+jna = { module = "net.java.dev.jna:jna", version.ref = "jna" }++# Ktor client (KMP RelayTransport actuals, Phase 1C)+ktor-client-core = { module = "io.ktor:ktor-client-core", version.ref = "ktor" }+ktor-client-okhttp = { module = "io.ktor:ktor-client-okhttp", version.ref = "ktor" }+ktor-client-darwin = { module = "io.ktor:ktor-client-darwin", version.ref = "ktor" }+ktor-client-websockets = { module = "io.ktor:ktor-client-websockets", version.ref = "ktor" }+ktor-client-content-negotiation = { module = "io.ktor:ktor-client-content-negotiation", version.ref = "ktor" }+ktor-serialization-kotlinx-json = { module = "io.ktor:ktor-serialization-kotlinx-json", version.ref = "ktor" }++# SQLDelight (KMP caches; Room stays Android-only)+sqldelight-driver-sqlcipher = { module = "app.cash.sqldelight:sqlcipher-driver", version.ref = "sqldelight" }+sqldelight-coroutines = { module = "app.cash.sqldelight:coroutines-extensions", version.ref = "sqldelight" } libsignal-android = { module = "org.signal:libsignal-android", version.ref = "libsignalAndroid" } ringrtc-android = { module = "org.signal:ringrtc-android", version.ref = "ringrtcAndroid" } @@ -349,6 +371,7 @@ auroraoss-gplayapi = { module = "com.auroraoss:gplayapi", version.ref = "gplayap # Android & Kotlin android-application = { id = "com.android.application", version.ref = "agp" }+kotlin-multiplatform = { id = "org.jetbrains.kotlin.multiplatform", version.ref = "kotlinGradlePlugin" } compose-screenshot = { id = "com.android.compose.screenshot", version.ref = "composeScreenshot" } android-library = { id = "com.android.library", version.ref = "agp" } kotlin-compose = { id = "org.jetbrains.kotlin.plugin.compose", version.ref = "kotlin" }
library/everysync-core/AGENTS.md
diff --git a/library/everysync-core/AGENTS.md b/library/everysync-core/AGENTS.mdnew file mode 100644index 0000000000..7992e37473--- /dev/null+++ b/library/everysync-core/AGENTS.md@@ -0,0 +1,22 @@+# AGENTS.md — library/everysync-core/ (':library:everysync-core')++> Scoped supplement. Global rules in root `AGENTS.md` apply. Stay inside `library/everysync-core/` + allowed shared modules. Do not root-scan.++- Gradle: :library:everysync-core / dir: library/everysync-core/+- Targets: android + jvm (desktop) + iosArm64 + iosSimulatorArm64 (KMP plugin version == Kotlin version)+- Package: `com.vayunmathur.everysync.core` (commonMain) + platform actuals+- Entry files: `commonMain/sync/RelayMerge.kt`, `commonMain/data/RemoteModels.kt` (Phase 1A moves)+- Deps: kotlinx-coroutines-core, kotlinx-serialization-json, kotlinx-datetime (common only)+- Metadata: none (libraries have none by design)+- Rust: no (binds the `:library:e2ee-p2p` crate via JNI/JNA/cinterop — no new Rust)++## Overview+**Purpose:** Shared KMP sync brain for the EverySync E2EE relay protocol — merge, vault policy, DTOs, formats. No Android API in commonMain; platform coupling behind expect/actual (`RelayTransport`, `SecureStore`, `SyncScheduler`, `SyncSink`, `AesGcm`, `SyncDigest`).+**Invariants (verbatim from the Android impl):** a failed pull returns null = abort, never empty; only explicit tombstones delete; vault keys never user-visible. Relay contract: `https://findfamily.cc/personal` + `wss://…/ws`, `POST /register|/getkey|/append|/pull`.+**Gotchas:** never depend on `:library:log` / `:library:network` / `:library:room` from commonMain (Android-only, no common variant); pinning DERs ship as common resources under `src/commonMain/resources/ca/` when the Ktor `RelayTransport` actuals land (Phase 1C).++## Verify (this module only)+```+./gradlew :library:everysync-core:compileKotlinJvm+./gradlew :library:everysync-core:lint+```
library/everysync-core/build.gradle.kts
diff --git a/library/everysync-core/build.gradle.kts b/library/everysync-core/build.gradle.ktsnew file mode 100644index 0000000000..bd454c0a73--- /dev/null+++ b/library/everysync-core/build.gradle.kts@@ -0,0 +1,8 @@+plugins {+ id("common-conventions-kmp")+}++// KMP shared sync brain for the EverySync E2EE relay protocol.+// Targets, namespace, and common dependencies come from the convention;+// this file stays empty until Phase 1 needs module-specific wiring+// (Ktor engines, SQLDelight, JNA/cinterop bindings).
library/everysync-core/src/androidMain/kotlin/com/vayunmathur/everysync/core/crypto/CryptoAndroid.kt
diff --git a/library/everysync-core/src/androidMain/kotlin/com/vayunmathur/everysync/core/crypto/CryptoAndroid.kt b/library/everysync-core/src/androidMain/kotlin/com/vayunmathur/everysync/core/crypto/CryptoAndroid.ktnew file mode 100644index 0000000000..df3b8eb9cc--- /dev/null+++ b/library/everysync-core/src/androidMain/kotlin/com/vayunmathur/everysync/core/crypto/CryptoAndroid.kt@@ -0,0 +1,35 @@+package com.vayunmathur.everysync.core.crypto++import java.security.SecureRandom+import javax.crypto.Cipher+import javax.crypto.spec.GCMParameterSpec+import javax.crypto.spec.SecretKeySpec++/** JCE AES-256-GCM actual (shared by the Android and JVM/desktop targets). */+actual object AesGcm {+ private const val GCM_TAG_BITS = 128+ private const val IV_LEN = 12+ private const val AES_KEY_BYTES = 32++ actual fun newContentKey(): ByteArray = ByteArray(AES_KEY_BYTES).also { SecureRandom().nextBytes(it) }++ actual fun encrypt(key: ByteArray, plaintext: ByteArray): ByteArray {+ val iv = ByteArray(IV_LEN).also { SecureRandom().nextBytes(it) }+ val cipher = Cipher.getInstance("AES/GCM/NoPadding")+ cipher.init(Cipher.ENCRYPT_MODE, SecretKeySpec(key, "AES"), GCMParameterSpec(GCM_TAG_BITS, iv))+ return iv + cipher.doFinal(plaintext)+ }++ actual fun decrypt(key: ByteArray, data: ByteArray): ByteArray {+ val iv = data.copyOfRange(0, IV_LEN)+ val ct = data.copyOfRange(IV_LEN, data.size)+ val cipher = Cipher.getInstance("AES/GCM/NoPadding")+ cipher.init(Cipher.DECRYPT_MODE, SecretKeySpec(key, "AES"), GCMParameterSpec(GCM_TAG_BITS, iv))+ return cipher.doFinal(ct)+ }+}++/** `java.security.SecureRandom` actual (shared by the Android and JVM/desktop targets). */+actual object PlatformRandom {+ actual fun nextBytes(size: Int): ByteArray = ByteArray(size).also { SecureRandom().nextBytes(it) }+}
library/everysync-core/src/androidMain/kotlin/com/vayunmathur/everysync/core/passwords/HmacAndroid.kt
diff --git a/library/everysync-core/src/androidMain/kotlin/com/vayunmathur/everysync/core/passwords/HmacAndroid.kt b/library/everysync-core/src/androidMain/kotlin/com/vayunmathur/everysync/core/passwords/HmacAndroid.ktnew file mode 100644index 0000000000..50f7063fcb--- /dev/null+++ b/library/everysync-core/src/androidMain/kotlin/com/vayunmathur/everysync/core/passwords/HmacAndroid.kt@@ -0,0 +1,12 @@+package com.vayunmathur.everysync.core.passwords++/**+ * HMAC-SHA1 over a key and message (Android/JVM actual via JCE).+ */+actual object HmacSha1 {+ actual fun mac(key: ByteArray, message: ByteArray): ByteArray {+ val mac = javax.crypto.Mac.getInstance("HmacSHA1")+ mac.init(javax.crypto.spec.SecretKeySpec(key, "RAW"))+ return mac.doFinal(message)+ }+}
library/everysync-core/src/commonMain/kotlin/com/vayunmathur/everysync/core/crypto/Crypto.kt
diff --git a/library/everysync-core/src/commonMain/kotlin/com/vayunmathur/everysync/core/crypto/Crypto.kt b/library/everysync-core/src/commonMain/kotlin/com/vayunmathur/everysync/core/crypto/Crypto.ktnew file mode 100644index 0000000000..475976ae08--- /dev/null+++ b/library/everysync-core/src/commonMain/kotlin/com/vayunmathur/everysync/core/crypto/Crypto.kt@@ -0,0 +1,28 @@+package com.vayunmathur.everysync.core.crypto++/**+ * AES-256-GCM content encryption. The random 12-byte IV is prepended to the+ * ciphertext (same layout as the Android `E2ee` object).+ *+ * Platform actuals: JCE `AES/GCM/NoPadding` on Android/JVM, CryptoKit+ * `AES.GCM` on Apple. This fills the known Rust gap (AES is NOT in the+ * `e2ee_pqc` crate) — do NOT add AES to Rust.+ */+expect object AesGcm {+ /** A fresh random 256-bit content key. */+ fun newContentKey(): ByteArray++ /** Encrypts [plaintext] with [key]; the random 12-byte IV is prepended. */+ fun encrypt(key: ByteArray, plaintext: ByteArray): ByteArray++ /** Decrypts data produced by [encrypt] (IV prepended). */+ fun decrypt(key: ByteArray, data: ByteArray): ByteArray+}++/**+ * Cryptographically secure random bytes.+ * Platform actuals: `SecureRandom` on Android/JVM, `SecRandomCopyBytes` on Apple.+ */+expect object PlatformRandom {+ fun nextBytes(size: Int): ByteArray+}
library/everysync-core/src/commonMain/kotlin/com/vayunmathur/everysync/core/data/RemoteModels.kt
diff --git a/library/everysync-core/src/commonMain/kotlin/com/vayunmathur/everysync/core/data/RemoteModels.kt b/library/everysync-core/src/commonMain/kotlin/com/vayunmathur/everysync/core/data/RemoteModels.ktnew file mode 100644index 0000000000..0df4a2e9c4--- /dev/null+++ b/library/everysync-core/src/commonMain/kotlin/com/vayunmathur/everysync/core/data/RemoteModels.kt@@ -0,0 +1,143 @@+package com.vayunmathur.everysync.core.data++import kotlinx.serialization.Serializable++/** A contact resolved from a relay vault record. */+@Serializable+data class RemoteContact(+ /** Stable relay sync identity (opaque 32-char id). */+ val uid: String,+ /** Relay updatedAt stamp as a string, for change detection; null when unknown. */+ val etag: String? = null,+ val displayName: String = "",+ val prefix: String = "",+ val firstName: String = "",+ val middleName: String = "",+ val lastName: String = "",+ val suffix: String = "",+ val organization: String = "",+ val note: String = "",+ /** number -> platform type code (mirrors ContactsContract ints; see VCard kinds). */+ val phones: List<TypedValue> = emptyList(),+ val emails: List<TypedValue> = emptyList(),+ val addresses: List<TypedValue> = emptyList(),+ /** ISO-8601 birthday (yyyy-MM-dd) or null. */+ val birthday: String? = null,+ /** Relay sync identity of the vault this record belongs to. */+ val href: String? = null,+ val deleted: Boolean = false,+ /** Last local-or-remote modification (epoch ms); drives relay LWW. */+ val updatedAt: Long = 0L,+)++@Serializable+data class TypedValue(val value: String, val type: Int)++/** A calendar event resolved from a relay vault record. */+@Serializable+data class RemoteEvent(+ val uid: String,+ /** Relay updatedAt stamp as a string, for change detection; null when unknown. */+ val etag: String? = null,+ val calendarId: String,+ val summary: String = "",+ val description: String = "",+ val location: String = "",+ val startMillis: Long = 0L,+ val endMillis: Long = 0L,+ val allDay: Boolean = false,+ val timezone: String = "UTC",+ /** Raw RRULE line (without the "RRULE:" prefix), or null. */+ val rrule: String? = null,+ /** RECURRENCE-ID of an overridden instance; null for the master. */+ val recurrenceId: String? = null,+ /** Relay sync identity of the vault this record belongs to. */+ val href: String? = null,+ val deleted: Boolean = false,+ /** Last local-or-remote modification (epoch ms); drives relay LWW. */+ val updatedAt: Long = 0L,+)++/**+ * A password or passkey record for the encrypted relay. Mirrors the native+ * vault fields so no KDBX mapping is needed: passwords use the name/username/+ * email/password/note/totp/websites half, passkeys ([isPasskey]) use the+ * rp/credential half. The relay envelope is the JSON of this class.+ */+@Serializable+data class RemotePassword(+ /** Relay sync identity (opaque 32-char id). */+ val uid: String,+ /** True for a passkey record, false for a password record. */+ val isPasskey: Boolean = false,+ val name: String = "",+ val username: String = "",+ val email: String = "",+ val password: String = "",+ val note: String = "",+ val totpSecret: String? = null,+ val websites: List<String> = emptyList(),+ // Passkey half (empty for passwords).+ val rpId: String = "",+ val rpName: String = "",+ val credentialId: String = "",+ val userId: String = "",+ val userName: String = "",+ val userDisplayName: String = "",+ /** Base64 of the private-key bytes. */+ val privateKeyB64: String = "",+ val creationTime: Long = 0L,+ val lastUsedTime: Long = 0L,+ val signCount: Int = 0,+ val linkedPasswordSyncId: String? = null,+ val deleted: Boolean = false,+ /** Last local-or-remote modification (epoch ms); drives relay LWW. */+ val updatedAt: Long = 0L,+)++/**+ * A note record for the encrypted relay. [blocksJson] is the stored+ * NoteBody JSON (text / image / ink blocks); image bytes themselves live in+ * the blob channel and are referenced by file name.+ * The relay envelope is the JSON of this class.+ */+@Serializable+data class RemoteNote(+ /** Relay sync identity (opaque 32-char id). */+ val uid: String,+ val title: String = "",+ val content: String = "",+ /** Serialized NoteBody, or null for legacy text-only notes. */+ val blocksJson: String? = null,+ val position: Double = 0.0,+ val deleted: Boolean = false,+ /** Last local-or-remote modification (epoch ms); drives relay LWW. */+ val updatedAt: Long = 0L,+)++/**+ * A todo task record for the encrypted relay. The relay envelope is the JSON+ * of this class on the `todos:<vaultId>` channel.+ *+ * Phase 1 drift fix: [notes] and [createdAt] are part of the envelope AND the+ * merge hash (see TodoKind.canonical). The Android native model previously+ * dropped both on persist, so LWW on those fields never converged locally —+ * native stores must persist them.+ */+@Serializable+data class RemoteTodo(+ /** Relay sync identity (opaque 32-char id). */+ val uid: String,+ val title: String = "",+ val notes: String = "",+ val done: Boolean = false,+ /** Epoch ms the task is due, or null. */+ val dueAt: Long? = null,+ /** Sort position; excluded from the merge hash so reorder is not an edit. */+ val position: Double = 0.0,+ /** Epoch ms the task was created; part of the adoption content key. */+ val createdAt: Long = 0L,+ val deleted: Boolean = false,+ /** Last local-or-remote modification (epoch ms); drives relay LWW. */+ val updatedAt: Long = 0L,+)
library/everysync-core/src/commonMain/kotlin/com/vayunmathur/everysync/core/format/ICalendar.kt
diff --git a/library/everysync-core/src/commonMain/kotlin/com/vayunmathur/everysync/core/format/ICalendar.kt b/library/everysync-core/src/commonMain/kotlin/com/vayunmathur/everysync/core/format/ICalendar.ktnew file mode 100644index 0000000000..2ce951b834--- /dev/null+++ b/library/everysync-core/src/commonMain/kotlin/com/vayunmathur/everysync/core/format/ICalendar.kt@@ -0,0 +1,203 @@+package com.vayunmathur.everysync.core.format++import com.vayunmathur.everysync.core.data.RemoteEvent+import kotlinx.datetime.LocalDate+import kotlinx.datetime.LocalDateTime+import kotlinx.datetime.TimeZone+import kotlinx.datetime.atStartOfDayIn+import kotlinx.datetime.toInstant+import kotlinx.datetime.toLocalDateTime+import kotlinx.datetime.toInstant++/**+ * Minimal iCalendar (RFC 5545) VEVENT reader/writer covering the fields+ * EverySync maps into platform calendar stores. Self-contained; RRULE lines+ * are carried through verbatim.+ *+ * KMP port of the Android `ICalendar`: `SimpleDateFormat`/`java.util.TimeZone`+ * replaced with `kotlinx-datetime`. Behavior is identical (UTC date-only,+ * `Z`-suffixed UTC, TZID local).+ */+object ICalendar {++ /** Parse a VCALENDAR body into its VEVENTs. [calendarId] tags each result. */+ fun parse(text: String, calendarId: String, fallbackUid: String? = null): List<RemoteEvent> {+ val lines = unfold(text)+ val events = mutableListOf<RemoteEvent>()+ var cur: MutableMap<String, Pair<String, String>>? = null // key -> (params, value)+ for (line in lines) {+ val trimmed = line.trimEnd()+ when {+ trimmed.equals("BEGIN:VEVENT", true) -> cur = mutableMapOf()+ trimmed.equals("END:VEVENT", true) -> {+ cur?.let { events += toEvent(it, calendarId, fallbackUid) }+ cur = null+ }+ cur != null -> {+ val prop = splitProperty(trimmed)+ if (prop != null) {+ val (name, params, value) = prop+ cur[name.uppercase()] = params to value+ }+ }+ }+ }+ return events+ }++ fun serialize(e: RemoteEvent): String = buildString {+ append("BEGIN:VCALENDAR\r\n")+ append("VERSION:2.0\r\n")+ append("PRODID:-//vayunmathur//EverySync//EN\r\n")+ append("BEGIN:VEVENT\r\n")+ append("UID:${e.uid}\r\n")+ e.recurrenceId?.takeIf { it.isNotBlank() }?.let { append("RECURRENCE-ID:${it}\r\n") }+ if (e.allDay) {+ append("DTSTART;VALUE=DATE:${dateOnly(e.startMillis)}\r\n")+ append("DTEND;VALUE=DATE:${dateOnly(e.endMillis)}\r\n")+ } else {+ append("DTSTART:${utc(e.startMillis)}\r\n")+ append("DTEND:${utc(e.endMillis)}\r\n")+ }+ if (e.summary.isNotBlank()) append("SUMMARY:${esc(e.summary)}\r\n")+ if (e.description.isNotBlank()) append("DESCRIPTION:${esc(e.description)}\r\n")+ if (e.location.isNotBlank()) append("LOCATION:${esc(e.location)}\r\n")+ e.rrule?.takeIf { it.isNotBlank() }?.let { append("RRULE:${it.removePrefix("RRULE:")}\r\n") }+ append("END:VEVENT\r\n")+ append("END:VCALENDAR\r\n")+ }++ private fun toEvent(+ props: Map<String, Pair<String, String>>,+ calendarId: String,+ fallbackUid: String?,+ ): RemoteEvent {+ val uid = props["UID"]?.second?.ifBlank { null } ?: fallbackUid ?: props.hashCode().toString()+ val (startMillis, startAllDay, tz) = parseTime(props["DTSTART"])+ val (endMillisRaw, _, _) = parseTime(props["DTEND"])+ val start = startMillis ?: 0L+ var end = endMillisRaw ?: (start + if (startAllDay) DAY_MS else HOUR_MS)+ if (startAllDay && end == start) end = start + DAY_MS+ return RemoteEvent(+ uid = uid,+ calendarId = calendarId,+ summary = unescape(props["SUMMARY"]?.second ?: ""),+ description = unescape(props["DESCRIPTION"]?.second ?: ""),+ location = unescape(props["LOCATION"]?.second ?: ""),+ startMillis = start,+ endMillis = end,+ allDay = startAllDay,+ timezone = tz ?: "UTC",+ rrule = props["RRULE"]?.second?.ifBlank { null },+ recurrenceId = props["RECURRENCE-ID"]?.second?.ifBlank { null },+ )+ }++ /** Returns (epochMillis?, isAllDay, tzid?). */+ private fun parseTime(prop: Pair<String, String>?): Triple<Long?, Boolean, String?> {+ if (prop == null) return Triple(null, false, null)+ val (params, value) = prop+ val up = params.uppercase()+ val allDay = up.contains("VALUE=DATE") ||+ (value.length == DATE_ONLY_LEN && value.all { it.isDigit() })+ return try {+ when {+ allDay -> {+ val date = LocalDate.parse(dashDate(value))+ Triple(+ date.atStartOfDayIn(TimeZone.UTC).toEpochMilliseconds(),+ true,+ "UTC",+ )+ }+ value.endsWith("Z") -> {+ val dt = LocalDateTime.parse(dashDateTime(value.dropLast(1)))+ Triple(dt.toInstant(TimeZone.UTC).toEpochMilliseconds(), false, "UTC")+ }+ else -> {+ val tzid = extractTzid(params)+ val zone = runCatching { TimeZone.of(tzid ?: "UTC") }.getOrDefault(TimeZone.UTC)+ val dt = LocalDateTime.parse(dashDateTime(value))+ Triple(dt.toInstant(zone).toEpochMilliseconds(), false, tzid ?: "UTC")+ }+ }+ } catch (_: Exception) {+ Triple(null, allDay, null)+ }+ }++ /** `yyyyMMdd` -> `yyyy-MM-dd` (for `LocalDate.parse`). */+ private fun dashDate(v: String): String =+ if (v.length == DATE_ONLY_LEN && v.all { it.isDigit() }) {+ "${v.take(4)}-${v.substring(4, 6)}-${v.substring(6, 8)}"+ } else {+ v+ }++ /** `yyyyMMdd'T'HHmmss` -> `yyyy-MM-dd'T'HH:mm:ss` (for `LocalDateTime.parse`). */+ private fun dashDateTime(v: String): String {+ val t = v.indexOf('T')+ if (t < 0) return v+ val d = v.take(t)+ val time = v.substring(t + 1)+ val dashed = if (d.length == DATE_ONLY_LEN && d.all { it.isDigit() }) dashDate(d) else d+ val clock = if (time.length >= 6 && time.take(6).all { it.isDigit() }) {+ "${time.take(2)}:${time.substring(2, 4)}:${time.substring(4, 6)}${time.drop(6)}"+ } else {+ time+ }+ return "${dashed}T$clock"+ }++ private fun extractTzid(params: String): String? =+ params.split(";").map { it.split("=", limit = 2) }+ .firstOrNull { it.size == 2 && it[0].uppercase() == "TZID" }?.get(1)++ private fun pad2(n: Int): String = n.toString().padStart(2, '0')+ private fun pad4(n: Int): String = n.toString().padStart(4, '0')++ private fun utc(millis: Long): String {+ val dt = kotlinx.time.Instant.fromEpochMilliseconds(millis)+ .toLocalDateTime(TimeZone.UTC)+ return "${pad4(dt.year)}${pad2(dt.month.number)}${pad2(dt.day)}T" ++ "${pad2(dt.hour)}${pad2(dt.minute)}${pad2(dt.second)}Z"+ }++ private fun dateOnly(millis: Long): String {+ val d = kotlinx.time.Instant.fromEpochMilliseconds(millis)+ .toLocalDateTime(TimeZone.UTC).date+ return "${pad4(d.year)}${pad2(d.month.number)}${pad2(d.day)}"+ }++ private fun unfold(text: String): List<String> {+ val out = mutableListOf<String>()+ for (raw in text.replace("\r\n", "\n").split("\n")) {+ if ((raw.startsWith(" ") || raw.startsWith("\t")) && out.isNotEmpty()) {+ out[out.lastIndex] = out.last() + raw.trimStart()+ } else {+ out.add(raw)+ }+ }+ return out+ }++ private fun splitProperty(line: String): Triple<String, String, String>? {+ val colon = line.indexOf(':')+ if (colon <= 0) return null+ val left = line.take(colon)+ val value = line.substring(colon + 1)+ val semi = left.indexOf(';')+ return if (semi > 0) Triple(left.take(semi), left.substring(semi + 1), value)+ else Triple(left, "", value)+ }++ private fun esc(s: String): String =+ s.replace("\\", "\\\\").replace(";", "\\;").replace(",", "\\,").replace("\n", "\\n")++ private fun unescape(s: String): String =+ s.replace("\\n", "\n").replace("\\,", ",").replace("\\;", ";").replace("\\\\", "\\")++ private const val HOUR_MS = 60L * 60L * 1000L+ private const val DAY_MS = 24L * HOUR_MS+ private const val DATE_ONLY_LEN = 8+}
library/everysync-core/src/commonMain/kotlin/com/vayunmathur/everysync/core/format/VCard.kt
diff --git a/library/everysync-core/src/commonMain/kotlin/com/vayunmathur/everysync/core/format/VCard.kt b/library/everysync-core/src/commonMain/kotlin/com/vayunmathur/everysync/core/format/VCard.ktnew file mode 100644index 0000000000..d2ebb9b2f5--- /dev/null+++ b/library/everysync-core/src/commonMain/kotlin/com/vayunmathur/everysync/core/format/VCard.kt@@ -0,0 +1,220 @@+package com.vayunmathur.everysync.core.format++import com.vayunmathur.everysync.core.data.RemoteContact+import com.vayunmathur.everysync.core.data.TypedValue++/**+ * Platform type codes for contact fields. Values mirror+ * `android.provider.ContactsContract.CommonDataKinds` ints so the Android+ * `actual` can pass them through unchanged:+ * - Phone: MOBILE=2, WORK=3, HOME=1, FAX_HOME=4, FAX_WORK=5, OTHER=7+ * - Email: WORK=2, HOME=1, OTHER=3+ * - Postal: WORK=2, HOME=1, OTHER=3+ */+enum class PhoneKind(val code: Int) {+ HOME(1),+ MOBILE(2),+ WORK(3),+ FAX_HOME(4),+ FAX_WORK(5),+ OTHER(7),+}++enum class EmailKind(val code: Int) {+ HOME(1),+ WORK(2),+ OTHER(3),+}++enum class PostalKind(val code: Int) {+ HOME(1),+ WORK(2),+ OTHER(3),+}++/**+ * Minimal vCard 3.0/4.0 reader/writer covering the fields EverySync maps into+ * platform contact stores. Self-contained.+ *+ * KMP port of the Android `VCard`: `ContactsContract` type-int constants+ * replaced with [PhoneKind]/[EmailKind]/[PostalKind] (same numeric values).+ */+object VCard {++ fun parse(text: String, fallbackUid: String? = null): RemoteContact {+ val builder = VCardBuilder(fallbackUid ?: "")+ for (line in unfold(text)) {+ val prop = splitProperty(line) ?: continue+ builder.apply(prop)+ }+ return builder.build()+ }++ private class VCardBuilder(private var uid: String) {+ private var fn = ""+ private var prefix = ""+ private var first = ""+ private var middle = ""+ private var last = ""+ private var suffix = ""+ private var org = ""+ private var note = ""+ private var bday: String? = null+ private val phones = mutableListOf<TypedValue>()+ private val emails = mutableListOf<TypedValue>()+ private val addresses = mutableListOf<TypedValue>()++ fun apply(prop: Prop) {+ when (prop.name.uppercase()) {+ "UID" -> uid = prop.value.ifBlank { uid }+ "FN" -> fn = unescape(prop.value)+ "N" -> readName(prop.value)+ "ORG" -> org = unescape(prop.value.split(";").firstOrNull() ?: prop.value)+ "NOTE" -> note = unescape(prop.value)+ "BDAY" -> bday = normalizeDate(prop.value)+ "TEL" -> phones += TypedValue(unescape(prop.value), phoneType(prop.params).code)+ "EMAIL" -> emails += TypedValue(unescape(prop.value), emailType(prop.params).code)+ "ADR" -> addresses += TypedValue(formatAddress(prop.value), addressType(prop.params).code)+ }+ }++ private fun readName(value: String) {+ val parts = value.split(";")+ last = unescape(parts.getOrElse(0) { "" })+ first = unescape(parts.getOrElse(1) { "" })+ middle = unescape(parts.getOrElse(2) { "" })+ prefix = unescape(parts.getOrElse(3) { "" })+ suffix = unescape(parts.getOrElse(4) { "" })+ }++ fun build(): RemoteContact {+ val display = fn.ifBlank {+ listOf(prefix, first, middle, last, suffix)+ .filter { it.isNotBlank() }+ .joinToString(" ")+ }+ return RemoteContact(+ uid = uid,+ displayName = display,+ prefix = prefix,+ firstName = first,+ middleName = middle,+ lastName = last,+ suffix = suffix,+ organization = org,+ note = note,+ phones = phones,+ emails = emails,+ addresses = addresses,+ birthday = bday,+ )+ }+ }++ fun serialize(c: RemoteContact): String = buildString {+ append("BEGIN:VCARD\r\n")+ append("VERSION:3.0\r\n")+ append("UID:${c.uid}\r\n")+ append("N:${esc(c.lastName)};${esc(c.firstName)};${esc(c.middleName)};${esc(c.prefix)};${esc(c.suffix)}\r\n")+ append("FN:${esc(c.displayName)}\r\n")+ if (c.organization.isNotBlank()) append("ORG:${esc(c.organization)}\r\n")+ for (p in c.phones) append("TEL;TYPE=${phoneTypeName(p.type)}:${esc(p.value)}\r\n")+ for (e in c.emails) append("EMAIL;TYPE=${emailTypeName(e.type)}:${esc(e.value)}\r\n")+ for (a in c.addresses) append("ADR;TYPE=${addressTypeName(a.type)}:;;${esc(a.value)};;;;\r\n")+ c.birthday?.let { append("BDAY:$it\r\n") }+ if (c.note.isNotBlank()) append("NOTE:${esc(c.note)}\r\n")+ append("END:VCARD\r\n")+ }++ // --- helpers ---++ /** RFC 6350 line unfolding: continuation lines start with space/tab. */+ private fun unfold(text: String): List<String> {+ val out = mutableListOf<String>()+ for (raw in text.replace("\r\n", "\n").split("\n")) {+ if ((raw.startsWith(" ") || raw.startsWith("\t")) && out.isNotEmpty()) {+ out[out.lastIndex] = out.last() + raw.trimStart()+ } else {+ out.add(raw)+ }+ }+ return out+ }++ private data class Prop(val name: String, val params: String, val value: String)++ private fun splitProperty(line: String): Prop? {+ val colon = line.indexOf(':')+ if (colon <= 0) return null+ val left = line.take(colon)+ val value = line.substring(colon + 1)+ val semi = left.indexOf(';')+ return if (semi > 0) Prop(left.take(semi), left.substring(semi + 1), value)+ else Prop(left, "", value)+ }++ private fun paramTypes(params: String): List<String> =+ params.split(";")+ .flatMap { it.removePrefix("TYPE=").removePrefix("type=").split(",") }+ .map { it.trim().uppercase() }+ .filter { it.isNotBlank() }++ private fun phoneType(params: String): PhoneKind = when {+ paramTypes(params).any { it == "CELL" || it == "MOBILE" } -> PhoneKind.MOBILE+ paramTypes(params).contains("WORK") -> PhoneKind.WORK+ paramTypes(params).contains("HOME") -> PhoneKind.HOME+ paramTypes(params).contains("FAX") -> PhoneKind.FAX_HOME+ else -> PhoneKind.OTHER+ }++ private fun phoneTypeName(type: Int): String = when (type) {+ PhoneKind.MOBILE.code -> "CELL"+ PhoneKind.WORK.code -> "WORK"+ PhoneKind.HOME.code -> "HOME"+ PhoneKind.FAX_HOME.code, PhoneKind.FAX_WORK.code -> "FAX"+ else -> "VOICE"+ }++ private fun emailType(params: String): EmailKind = when {+ paramTypes(params).contains("WORK") -> EmailKind.WORK+ paramTypes(params).contains("HOME") -> EmailKind.HOME+ else -> EmailKind.OTHER+ }++ private fun emailTypeName(type: Int): String = when (type) {+ EmailKind.WORK.code -> "WORK"+ EmailKind.HOME.code -> "HOME"+ else -> "INTERNET"+ }++ private fun addressType(params: String): PostalKind = when {+ paramTypes(params).contains("WORK") -> PostalKind.WORK+ paramTypes(params).contains("HOME") -> PostalKind.HOME+ else -> PostalKind.OTHER+ }++ private fun addressTypeName(type: Int): String = when (type) {+ PostalKind.WORK.code -> "WORK"+ PostalKind.HOME.code -> "HOME"+ else -> "OTHER"+ }++ /** ADR is ;;street;city;region;code;country — flatten to a display string. */+ private fun formatAddress(value: String): String =+ value.split(";").map { unescape(it) }.filter { it.isNotBlank() }.joinToString(", ")++ private fun normalizeDate(value: String): String? {+ val v = value.trim()+ return when {+ v.matches(Regex("\\d{4}-\\d{2}-\\d{2}")) -> v+ v.matches(Regex("\\d{8}")) -> "${v.take(4)}-${v.substring(4, 6)}-${v.substring(6, 8)}"+ else -> v.takeIf { it.isNotBlank() }+ }+ }++ private fun esc(s: String): String =+ s.replace("\\", "\\\\").replace(";", "\\;").replace(",", "\\,").replace("\n", "\\n")++ private fun unescape(s: String): String =+ s.replace("\\n", "\n").replace("\\,", ",").replace("\\;", ";").replace("\\\\", "\\")+}
library/everysync-core/src/commonMain/kotlin/com/vayunmathur/everysync/core/network/RelayContract.kt
diff --git a/library/everysync-core/src/commonMain/kotlin/com/vayunmathur/everysync/core/network/RelayContract.kt b/library/everysync-core/src/commonMain/kotlin/com/vayunmathur/everysync/core/network/RelayContract.ktnew file mode 100644index 0000000000..fb685acbb2--- /dev/null+++ b/library/everysync-core/src/commonMain/kotlin/com/vayunmathur/everysync/core/network/RelayContract.kt@@ -0,0 +1,52 @@+package com.vayunmathur.everysync.core.network++/** Relay service endpoints. Contract reference: the Android `RelaySync` transport. */+const val RELAY_BASE_URL = "https://findfamily.cc/personal"+const val RELAY_WS_URL = "wss://findfamily.cc/personal/ws"++/** Channel name for a vault's record log, e.g. `passwords:<vaultId>`. */+fun recordChannel(dataType: String, vaultId: String): String = "$dataType:$vaultId"++fun membersChannel(vaultId: String): String = "members:$vaultId"+fun keysChannel(vaultId: String): String = "keys:$vaultId"+fun ownerChannel(vaultId: String): String = "owner:$vaultId"+fun titleChannel(vaultId: String): String = "title:$vaultId"+fun inboxChannel(deviceId: String): String = "inbox:$deviceId"+fun blobChannel(vaultId: String): String = "notes-blobs:$vaultId"++/**+ * Vault access roles — enforced entirely client-side via signature checks (relay is a pure log).+ * Passwords vaults never grant VIEWER: read-only passwords still disclose every secret.+ */+object RelayRoles {+ const val OWNER = "owner"+ const val EDITOR = "editor"+ const val VIEWER = "viewer"+ const val REVOKED = "revoked"++ fun canEdit(role: String) = role == OWNER || role == EDITOR+ fun canRead(role: String) = role == OWNER || role == EDITOR || role == VIEWER++ /** Roles offerable for a data type. Passwords exclude viewer (see above). */+ fun offerable(dataType: String): List<String> =+ if (dataType == "passwords") listOf(EDITOR) else listOf(EDITOR, VIEWER)+}++/** Deep-link / share-link helpers for personal vaults (mirrors office://join + voxels://join). */+object RelayLinks {+ const val SCHEME = "everysync"+ const val HOST_JOIN = "join"+ const val SHARE_BASE = "https://ma.vayunmathur.com/es/share"++ /** `https://ma.vayunmathur.com/es/share#id=<vault>&owner=<device>&type=<dataType>` — ids in fragment. */+ fun shareLinkFor(vaultId: String, ownerDeviceId: String, dataType: String): String =+ "$SHARE_BASE#id=$vaultId&owner=$ownerDeviceId&type=$dataType"++ /** `everysync://join/<vaultId>?owner=<device>&type=<dataType>`; null for any other intent. */+ fun parseJoinLink(scheme: String?, host: String?, vaultId: String?, ownerId: String?, dataType: String?)+ : Triple<String, String, String>? {+ if (scheme != SCHEME || host != HOST_JOIN) return null+ if (vaultId.isNullOrBlank() || ownerId.isNullOrBlank()) return null+ return Triple(vaultId, ownerId, dataType.orEmpty())+ }+}
library/everysync-core/src/commonMain/kotlin/com/vayunmathur/everysync/core/network/RelayDtos.kt
diff --git a/library/everysync-core/src/commonMain/kotlin/com/vayunmathur/everysync/core/network/RelayDtos.kt b/library/everysync-core/src/commonMain/kotlin/com/vayunmathur/everysync/core/network/RelayDtos.ktnew file mode 100644index 0000000000..97d82899bf--- /dev/null+++ b/library/everysync-core/src/commonMain/kotlin/com/vayunmathur/everysync/core/network/RelayDtos.kt@@ -0,0 +1,71 @@+package com.vayunmathur.everysync.core.network++import kotlinx.serialization.Serializable++/**+ * An invite to a shared vault: carries everything a device needs to join it.+ * Sealed with the recipient's PQC bundle; the relay only sees ciphertext.+ */+@Serializable+data class Invite(+ val vaultId: String,+ val key: String,+ val title: String,+ val dataType: String = "",+ val role: String = RelayRoles.EDITOR,+ val ownerKey: String = "",+ val ownerDeviceId: String = "",+ val epoch: Int = 0,+)++/** A request to join a vault, sealed to the owner. Public ids only — no key. */+@Serializable+data class JoinRequest(+ val kind: String = "req",+ val vaultId: String,+ val dataType: String = "",+ val requesterId: String,+ val name: String = "",+)++/** An author-signed envelope batch: author id, signature over [payload], and the payload JSON. */+@Serializable+data class SignedEnvelope(val author: String, val sig: String, val payload: String)++/** A vault member + their role, distributed as owner-signed records on the members channel. */+@Serializable+data class Member(val id: String, val name: String = "", val role: String = RelayRoles.EDITOR)++/** An owner-signed key epoch for cryptographic read-revocation. */+@Serializable+data class KeyEpoch(val epoch: Int, val wraps: Map<String, String>, val sig: String)++/**+ * An ownership handoff, signed by the *current* owner. Members follow the signed+ * chain from the original owner key to determine the current owner.+ */+@Serializable+data class OwnerTransferRecord(val newOwnerId: String, val newOwnerKey: String, val sig: String)++/** An owner-signed vault title (latest valid one wins). */+@Serializable+data class SignedTitle(val title: String, val sig: String)++class InvitesResult(val invites: List<Invite>, val seq: Int)+class InboxResult(val invites: List<Invite>, val requests: List<JoinRequest>, val seq: Int)++/**+ * One decrypted record-log pull. [rawCount] is the envelope count on the+ * relay; [undecryptable] is how many failed to decrypt under the vault key.+ * When most records fail to decrypt the key/epoch is suspect — the caller+ * must treat that as a failure (abort), not as an empty vault.+ */+class RecordsResult(+ val items: List<String>,+ val seq: Int,+ val rawCount: Int = items.size,+ val undecryptable: Int = 0,+) {+ /** True when decryption failed for every record that exists: key suspect, abort. */+ val fullyUndecryptable: Boolean get() = rawCount > 0 && items.isEmpty()+}
library/everysync-core/src/commonMain/kotlin/com/vayunmathur/everysync/core/network/RelayEnvelopes.kt
diff --git a/library/everysync-core/src/commonMain/kotlin/com/vayunmathur/everysync/core/network/RelayEnvelopes.kt b/library/everysync-core/src/commonMain/kotlin/com/vayunmathur/everysync/core/network/RelayEnvelopes.ktnew file mode 100644index 0000000000..d8a2b892eb--- /dev/null+++ b/library/everysync-core/src/commonMain/kotlin/com/vayunmathur/everysync/core/network/RelayEnvelopes.kt@@ -0,0 +1,123 @@+package com.vayunmathur.everysync.core.network++import com.vayunmathur.everysync.core.crypto.AesGcm+import kotlinx.serialization.encodeToString+import kotlinx.serialization.json.Json+import kotlin.io.encoding.Base64++private val envelopesJson = Json { ignoreUnknownKeys = true }++/**+ * Envelope encoding shared by every target, ported from the Android+ * `RelaySync` transport (which stays as the Android reference).+ *+ * Records are `Base64(AES_GCM(key, utf8))` per item; roster/epochs/transfers+ * double-wrap as `Base64(Json(...))`; invites and join requests are PQC-sealed+ * to the recipient's inbox. All authority stays client-side — the relay only+ * ever sees ciphertext.+ *+ * Key-hygiene invariant: vault keys are never user-visible. Share links carry+ * only vault/owner ids; keys move exclusively via PQC-sealed inbox invites.+ */++/** Appends AES-encrypted envelopes to a vault's record log; returns the new sequence, or null. */+suspend fun RelayTransport.appendRecords(channel: String, key: ByteArray, items: List<String>): Int? {+ val blobs = items.map { Base64.encode(AesGcm.encrypt(key, it.encodeToByteArray())) }+ return appendRaw(channel, blobs)+}++/**+ * Pulls + decrypts a vault's record log from [since]; null on transport failure.+ *+ * A null return is NOT an empty log: the caller must abort the cycle. Folding+ * a failure as empty would read every baseline-present id as deleted (see+ * `RelayMerge`). [RecordsResult.rawCount] is how many envelopes the relay+ * holds; [RecordsResult.items.size] is how many decrypted under [key] — a+ * large gap means a key/epoch problem, not an empty vault.+ */+suspend fun RelayTransport.pullRecords(channel: String, key: ByteArray, since: Int): RecordsResult? {+ val blobs = pullRaw(channel, since) ?: return null+ var undecryptable = 0+ val items = blobs.mapNotNull { b ->+ runCatching { AesGcm.decrypt(key, Base64.decode(b)).decodeToString() }.getOrNull()+ ?: run { undecryptable++; null }+ }+ return RecordsResult(items, seq = since + blobs.size, rawCount = blobs.size, undecryptable = undecryptable)+}++/**+ * Seals a vault invite to [recipientId]'s inbox. Carries the vault id, the AES vault+ * key, the data type, role, and owner identity — everything a device needs to join.+ */+suspend fun RelayTransport.sendInvite(+ recipientId: String,+ vaultId: String,+ dataType: String,+ key: ByteArray,+ title: String,+ role: String,+ ownerKeyB64: String,+ ownerDeviceId: String,+ epoch: Int = 0,+): Boolean {+ val peerBundle = getKey(recipientId) ?: return false+ val invite = envelopesJson.encodeToString(+ Invite(vaultId, Base64.encode(key), title, dataType, role, ownerKeyB64, ownerDeviceId, epoch),+ )+ val blob = Base64.encode(seal(peerBundle, invite.encodeToByteArray()))+ return appendRaw(inboxChannel(recipientId), listOf(blob)) != null+}++/** Pulls + unseals invites addressed to this device from [since]. */+suspend fun RelayTransport.pullInvites(since: Int): InvitesResult {+ val inbox = pullInbox(since)+ return InvitesResult(inbox.invites, inbox.seq)+}++/**+ * Sends a PQC-sealed join request to a vault owner's inbox. Carries only public ids+ * (never the AES vault key); the owner approves with one tap, which triggers the+ * existing seal-to-recipient [sendInvite]. Rides the same `inbox:<ownerId>` channel+ * as invites — distinguished by the `kind:"req"` discriminator.+ */+suspend fun RelayTransport.sendJoinRequest(+ ownerId: String,+ vaultId: String,+ dataType: String,+ requesterId: String,+ name: String,+): Boolean {+ val ownerBundle = getKey(ownerId) ?: return false+ val req = envelopesJson.encodeToString(+ JoinRequest(vaultId = vaultId, dataType = dataType, requesterId = requesterId, name = name),+ )+ val blob = Base64.encode(seal(ownerBundle, req.encodeToByteArray()))+ return appendRaw(inboxChannel(ownerId), listOf(blob)) != null+}++/**+ * Tolerant inbox reader: decrypts each blob and sorts it into invites (default kind,+ * for backward compatibility) vs join requests (`kind:"req"`). Unparseable/foreign+ * blobs are skipped so one bad item never drops the batch.+ */+suspend fun RelayTransport.pullInbox(since: Int): InboxResult {+ val blobs = pullRaw(inboxChannel(deviceId), since) ?: return InboxResult(emptyList(), emptyList(), since)+ val invites = mutableListOf<Invite>()+ val requests = mutableListOf<JoinRequest>()+ for (b in blobs) {+ val plain = runCatching { unseal(Base64.decode(b)) }.getOrNull() ?: continue+ val text = plain.decodeToString()+ val kind = runCatching {+ envelopesJson.decodeFromString<InboxEnvelope>(text).kind+ }.getOrNull().orEmpty()+ if (kind == "req") {+ runCatching { envelopesJson.decodeFromString<JoinRequest>(text) }.getOrNull()?.let { requests.add(it) }+ } else {+ runCatching { envelopesJson.decodeFromString<Invite>(text) }.getOrNull()?.let { invites.add(it) }+ }+ }+ return InboxResult(invites, requests, since + blobs.size)+}+[email protected]+private data class InboxEnvelope(val kind: String = "")
library/everysync-core/src/commonMain/kotlin/com/vayunmathur/everysync/core/network/RelayTransport.kt
diff --git a/library/everysync-core/src/commonMain/kotlin/com/vayunmathur/everysync/core/network/RelayTransport.kt b/library/everysync-core/src/commonMain/kotlin/com/vayunmathur/everysync/core/network/RelayTransport.ktnew file mode 100644index 0000000000..1ce3d95838--- /dev/null+++ b/library/everysync-core/src/commonMain/kotlin/com/vayunmathur/everysync/core/network/RelayTransport.kt@@ -0,0 +1,54 @@+package com.vayunmathur.everysync.core.network++import kotlinx.coroutines.flow.Flow+import kotlinx.serialization.Serializable++/**+ * Transport surface for the E2EE relay: one function per endpoint/operation.+ * Platform actuals: Ktor-OkHttp on Android/JVM, Ktor-Darwin on Apple.+ *+ * Loss-prevention invariant: a failed pull returns null — NEVER an empty+ * list. The merge driver aborts the cycle on null; folding a failure as+ * empty would read every baseline-present id as deleted.+ */+interface RelayTransport {+ /** This device's stable relay id. */+ val deviceId: String++ /** This device's PQC public bundle (for sealing invites to us). */+ val publicBundle: ByteArray++ /** Idempotent: registers this device's public bundle. */+ suspend fun register(): Boolean++ /** Fetches a peer's public bundle by device id. */+ suspend fun getKey(id: String): ByteArray?++ /**+ * Appends raw string records to [channel]; returns the new sequence, or+ * null on transport failure.+ */+ suspend fun appendRaw(channel: String, items: List<String>): Int?++ /**+ * Pulls raw string records from [channel] since [since]; null on+ * transport failure (NOT an empty channel — abort, don't merge).+ */+ suspend fun pullRaw(channel: String, since: Int): List<String>?++ /** Best-effort live subscription to [channel] (relay WebSocket fan-out). */+ fun subscribe(channel: String): Flow<String>++ // --- Identity / crypto primitives (PQC in Rust, AES in shared Kotlin) ---++ suspend fun sign(data: ByteArray): ByteArray+ suspend fun verify(publicBundle: ByteArray, data: ByteArray, signature: ByteArray): Boolean+ suspend fun seal(bundle: ByteArray, data: ByteArray): ByteArray+ suspend fun unseal(data: ByteArray): ByteArray++ /** A fresh random 256-bit vault content key. */+ fun newVaultKey(): ByteArray++ /** A fresh random vault id. */+ fun newVaultId(): String+}
library/everysync-core/src/commonMain/kotlin/com/vayunmathur/everysync/core/notes/NoteBlocks.kt
diff --git a/library/everysync-core/src/commonMain/kotlin/com/vayunmathur/everysync/core/notes/NoteBlocks.kt b/library/everysync-core/src/commonMain/kotlin/com/vayunmathur/everysync/core/notes/NoteBlocks.ktnew file mode 100644index 0000000000..5bf4ca331f--- /dev/null+++ b/library/everysync-core/src/commonMain/kotlin/com/vayunmathur/everysync/core/notes/NoteBlocks.kt@@ -0,0 +1,102 @@+package com.vayunmathur.everysync.core.notes++import kotlinx.serialization.SerialName+import kotlinx.serialization.Serializable+import kotlinx.serialization.SerializationException+import kotlinx.serialization.encodeToString+import kotlinx.serialization.json.Json+import kotlin.uuid.Uuid++/**+ * One piece of a note's body. A note is an ordered list of blocks so it can mix+ * typed text, inserted images, and handwriting.+ *+ * Wire shape (preserved verbatim from Android):+ * `{"blocks":[{"type":"text","id":"…","markdown":"…"},+ * {"type":"image","id":"…","fileName":"<sha256>.jpg","widthFraction":1.0},+ * {"type":"ink","id":"…","strokes":[…],"heightDp":300}]}`+ * Image bytes ride the blob channel keyed by `fileName`; they are never inline.+ */+@Serializable+sealed interface NoteBlock {+ val id: String++ @Serializable+ @SerialName("text")+ data class Text(+ val markdown: String = "",+ override val id: String = randomBlockId(),+ ) : NoteBlock++ /** [fileName] names an image file in the note-images/blob store. */+ @Serializable+ @SerialName("image")+ data class Image(+ val fileName: String,+ /** Display width as a fraction of the editor width, so images can be resized. */+ val widthFraction: Float = 1f,+ override val id: String = randomBlockId(),+ ) : NoteBlock++ /** Handwriting strokes drawn on a canvas [heightDp] tall. */+ @Serializable+ @SerialName("ink")+ data class Ink(+ val strokes: List<InkStroke> = emptyList(),+ val heightDp: Int = 300,+ override val id: String = randomBlockId(),+ ) : NoteBlock+}++/** Platform-free ink stroke: polyline points + brush attributes. */+@Serializable+data class InkPoint(+ val x: Float,+ val y: Float,+ val timeMillis: Long = 0L,+ val pressure: Float = 1f,+ val tiltRadians: Float = 0f,+ val orientationRadians: Float = 0f,+)++@Serializable+data class InkStroke(+ val brushFamily: String = "pressurePen",+ val brushSize: Float = 4f,+ val brushColor: Int = -0x1000000,+ val brushEpsilon: Float = 0.1f,+ val points: List<InkPoint> = emptyList(),+)++@OptIn(kotlin.uuid.ExperimentalUuidApi::class)+fun randomBlockId(): String = Uuid.random().toString()++/**+ * The full body of a note: an ordered list of inline [blocks].+ */+@Serializable+data class NoteBody(+ val blocks: List<NoteBlock> = emptyList(),+)++// ignoreUnknownKeys drops legacy fields (e.g. an old "floating" list) so older notes still parse.+private val blockJson = Json { ignoreUnknownKeys = true }++/** Parses a stored blocks JSON string, or falls back to a single text block. */+fun parseNoteBody(blocksJson: String?, fallbackContent: String = ""): NoteBody {+ if (blocksJson.isNullOrBlank()) return NoteBody(blocks = listOf(NoteBlock.Text(fallbackContent)))+ return try {+ blockJson.decodeFromString<NoteBody>(blocksJson)+ } catch (_: SerializationException) {+ NoteBody(blocks = listOf(NoteBlock.Text(fallbackContent)))+ }+}++/** Serializes [body] to the stored blocks JSON string. */+fun serializeNoteBody(body: NoteBody): String = blockJson.encodeToString(body)++/** Plain-text projection of [body] for search, previews, sharing, and intents. */+fun noteBodyText(body: NoteBody): String =+ body.blocks.filterIsInstance<NoteBlock.Text>()+ .joinToString("\n\n") { it.markdown }+ .trim()
library/everysync-core/src/commonMain/kotlin/com/vayunmathur/everysync/core/passwords/Cbor.kt
diff --git a/library/everysync-core/src/commonMain/kotlin/com/vayunmathur/everysync/core/passwords/Cbor.kt b/library/everysync-core/src/commonMain/kotlin/com/vayunmathur/everysync/core/passwords/Cbor.ktnew file mode 100644index 0000000000..2a53f344d8--- /dev/null+++ b/library/everysync-core/src/commonMain/kotlin/com/vayunmathur/everysync/core/passwords/Cbor.kt@@ -0,0 +1,55 @@+package com.vayunmathur.everysync.core.passwords++object Cbor {+ private const val TYPE_UNSIGNED_INT = 0x00+ private const val TYPE_NEGATIVE_INT = 0x01+ private const val TYPE_BYTE_STRING = 0x02+ private const val TYPE_TEXT_STRING = 0x03+ private const val TYPE_ARRAY = 0x04+ private const val TYPE_MAP = 0x05++ fun encode(data: Any): ByteArray = when (data) {+ is Boolean -> byteArrayOf((if (data) 0xF5 else 0xF4).toByte())+ is Number -> {+ val value = data.toLong()+ if (value >= 0) createArg(TYPE_UNSIGNED_INT, value)+ else createArg(TYPE_NEGATIVE_INT, -1 - value)+ }+ is ByteArray -> createArg(TYPE_BYTE_STRING, data.size.toLong()) + data+ // Length is the UTF-8 byte count, not String.length, which counts UTF-16 units.+ is String -> data.encodeToByteArray().let { createArg(TYPE_TEXT_STRING, it.size.toLong()) + it }+ is List<*> -> data.fold(createArg(TYPE_ARRAY, data.size.toLong())) { acc, i -> acc + encode(i!!) }+ is Map<*, *> -> {+ val byteMap = data.entries.associate { (k, v) -> encode(k!!) to encode(v!!) }+ val sortedKeys = byteMap.keys.sortedWith(Comparator { a, b ->+ if (a.size != b.size) a.size - b.size+ else a.indices.firstNotNullOfOrNull { i ->+ ((a[i].toInt() and 0xFF) - (b[i].toInt() and 0xFF)).takeIf { it != 0 }+ } ?: 0+ })+ sortedKeys.fold(createArg(TYPE_MAP, data.size.toLong())) { acc, key ->+ acc + key + byteMap[key]!!+ }+ }+ else -> throw IllegalArgumentException("Unsupported CBOR type: ${data::class}")+ }++ private fun createArg(type: Int, arg: Long): ByteArray {+ val t = type shl 5+ val a = arg.toInt()+ if (arg < 24) return byteArrayOf(((t or a) and 0xFF).toByte())+ if (arg <= 0xFF) return byteArrayOf(((t or 24) and 0xFF).toByte(), (a and 0xFF).toByte())+ if (arg <= 0xFFFF) return byteArrayOf(+ ((t or 25) and 0xFF).toByte(),+ ((a shr 8) and 0xFF).toByte(),+ (a and 0xFF).toByte()+ )+ return byteArrayOf(+ ((t or 26) and 0xFF).toByte(),+ ((a shr 24) and 0xFF).toByte(),+ ((a shr 16) and 0xFF).toByte(),+ ((a shr 8) and 0xFF).toByte(),+ (a and 0xFF).toByte()+ )+ }+}
library/everysync-core/src/commonMain/kotlin/com/vayunmathur/everysync/core/passwords/CredentialMerge.kt
diff --git a/library/everysync-core/src/commonMain/kotlin/com/vayunmathur/everysync/core/passwords/CredentialMerge.kt b/library/everysync-core/src/commonMain/kotlin/com/vayunmathur/everysync/core/passwords/CredentialMerge.ktnew file mode 100644index 0000000000..2f64c63172--- /dev/null+++ b/library/everysync-core/src/commonMain/kotlin/com/vayunmathur/everysync/core/passwords/CredentialMerge.kt@@ -0,0 +1,91 @@+package com.vayunmathur.everysync.core.passwords++import kotlinx.serialization.Serializable++/** Platform-free password record for the shared merge/match logic. */+@Serializable+data class CredentialDto(+ val name: String = "",+ val username: String = "",+ val email: String = "",+ val websites: List<String> = emptyList(),+ val syncId: String = "",+ val creationTime: Long = 0L,+)++/** Platform-free passkey record for the shared merge/match logic. */+@Serializable+data class PasskeyDto(+ val rpId: String = "",+ val rpName: String = "",+ val credentialId: String = "",+ val userId: String = "",+ val userName: String = "",+ val userDisplayName: String = "",+ val creationTime: Long = 0L,+ val syncId: String = "",+ val linkedPasswordSyncId: String? = null,+)++/**+ * A strict partition of the passkeys: each one is attached to exactly one password or is+ * standalone, never both and never neither. The list renders a row per password plus a row per+ * standalone passkey, so a passkey appearing twice would mean duplicate list keys.+ */+data class MergeResult(+ val passkeysByPasswordSyncId: Map<String, List<PasskeyDto>>,+ val standalone: List<PasskeyDto>,+)++/**+ * Pairs each passkey with the password it belongs to.+ *+ * An explicit link wins over the automatic rule in both directions. Automatic matching requires+ * both the domain and the username to agree, and only applies when exactly one password is a+ * candidate — anything ambiguous is left standalone for the user to link by hand.+ */+fun mergeCredentials(passwords: List<CredentialDto>, passkeys: List<PasskeyDto>): MergeResult {+ val bySyncId = passwords.associateBy { it.syncId }+ val attached = mutableMapOf<String, MutableList<PasskeyDto>>()+ val standalone = mutableListOf<PasskeyDto>()++ for (passkey in passkeys) {+ val target = when (val link = PasskeyLink.fromColumn(passkey.linkedPasswordSyncId)) {+ PasskeyLink.Detached -> null+ // A link can outlive its password, or arrive before it on a device that is still+ // syncing. Show it standalone but leave the link alone so it re-attaches later.+ is PasskeyLink.To -> bySyncId[link.passwordSyncId]+ PasskeyLink.Auto -> passwords.filter { matches(passkey, it) }.singleOrNull()+ }+ if (target == null) standalone.add(passkey)+ else attached.getOrPut(target.syncId) { mutableListOf() }.add(passkey)+ }++ return MergeResult(+ attached.mapValues { (_, list) -> list.sortedWith(compareBy({ it.creationTime }, { it.syncId })) },+ standalone,+ )+}++/** The passkeys shown on [password]'s detail page. Resolves identically to the list. */+fun passkeysFor(password: CredentialDto, passwords: List<CredentialDto>, passkeys: List<PasskeyDto>): List<PasskeyDto> =+ mergeCredentials(passwords, passkeys).passkeysByPasswordSyncId[password.syncId].orEmpty()++private fun matches(passkey: PasskeyDto, password: CredentialDto): Boolean =+ usernameMatches(passkey, password) && domainMatches(passkey, password)++private fun usernameMatches(passkey: PasskeyDto, password: CredentialDto): Boolean {+ val user = passkey.userName.trim()+ if (user.isEmpty()) return false+ return user.equals(password.username.trim(), ignoreCase = true) ||+ user.equals(password.email.trim(), ignoreCase = true)+}++private fun domainMatches(passkey: PasskeyDto, password: CredentialDto): Boolean {+ val rp = DomainMatch.normalizeSite(passkey.rpId)+ if (rp.isEmpty()) return false+ return password.websites.any { site ->+ !DomainMatch.isAndroidPackageSite(site) &&+ DomainMatch.isSameSiteOrSubdomain(DomainMatch.normalizeSite(site), rp)+ }+}
library/everysync-core/src/commonMain/kotlin/com/vayunmathur/everysync/core/passwords/DomainMatch.kt
diff --git a/library/everysync-core/src/commonMain/kotlin/com/vayunmathur/everysync/core/passwords/DomainMatch.kt b/library/everysync-core/src/commonMain/kotlin/com/vayunmathur/everysync/core/passwords/DomainMatch.ktnew file mode 100644index 0000000000..37ce41850d--- /dev/null+++ b/library/everysync-core/src/commonMain/kotlin/com/vayunmathur/everysync/core/passwords/DomainMatch.kt@@ -0,0 +1,41 @@+package com.vayunmathur.everysync.core.passwords++/**+ * Host comparison for deciding whether a stored site and a relying party (or a page being+ * autofilled) are the same site.+ *+ * Deliberately free of platform URI types so it runs in commonMain and unit tests on any target.+ */+object DomainMatch {++ /** Reduces a stored website or rpId to a bare lowercase host. */+ fun normalizeSite(raw: String): String {+ var s = raw.trim().lowercase()+ s = s.substringAfter("://")+ s = s.substringBefore('/')+ s = s.substringBefore('?')+ // Strip credentials and port: "user:pw@host:8443" -> "host".+ s = s.substringAfterLast('@')+ s = s.substringBefore(':')+ s = s.removeSuffix(".")+ return s.removePrefix("www.")+ }++ /** Android package targets are stored alongside websites but are not hosts. */+ fun isAndroidPackageSite(raw: String): Boolean {+ val s = raw.trim().lowercase()+ if (s.startsWith("android-app://")) return true+ // A bare package name: dotted, no scheme, no path, and no TLD-looking last label.+ return !s.contains("://") && !s.contains('/') && s.count { it == '.' } >= 2 &&+ s.startsWith("com.")+ }++ /**+ * True when [host] is [parent] or sits underneath it. Dot-aware on purpose: a plain+ * `endsWith` would make `notexample.com` a match for `example.com`.+ */+ fun isSameSiteOrSubdomain(host: String, parent: String): Boolean {+ if (host.isEmpty() || parent.isEmpty()) return false+ return host == parent || host.endsWith(".$parent")+ }+}
library/everysync-core/src/commonMain/kotlin/com/vayunmathur/everysync/core/passwords/EntryMapper.kt
diff --git a/library/everysync-core/src/commonMain/kotlin/com/vayunmathur/everysync/core/passwords/EntryMapper.kt b/library/everysync-core/src/commonMain/kotlin/com/vayunmathur/everysync/core/passwords/EntryMapper.ktnew file mode 100644index 0000000000..3196fdb5bd--- /dev/null+++ b/library/everysync-core/src/commonMain/kotlin/com/vayunmathur/everysync/core/passwords/EntryMapper.kt@@ -0,0 +1,104 @@+package com.vayunmathur.everysync.core.passwords++import com.vayunmathur.everysync.core.sync.SyncDigest+import kotlinx.serialization.encodeToString+import kotlinx.serialization.json.Json++/**+ * The single Password/Passkey <-> field-map conversion, shared by the one-shot+ * backup format and the bidirectional sync.+ *+ * The mapping must round-trip: `toFields(fromFields(f))` has to be stable, because the+ * merge compares content hashes computed from it on both sides.+ *+ * KDBX interop contract: keep every key name verbatim for desktop file-sync compat.+ */+object EntryMapper {+ const val FIELD_TYPE = "_Type"+ const val FIELD_SYNC_ID = "_SyncId"+ const val FIELD_MODIFIED = "_Modified"++ /**+ * Own-client deletion marker. When this client deletes an entry it writes+ * a tombstone entry carrying `FIELD_TOMBSTONE = TOMBSTONE_VALUE` (plus the+ * `_SyncId`) and retains it until the delete is acked, instead of dropping+ * the row from the file. Foreign clients cannot write tombstones, so a+ * baseline-present id that is merely ABSENT from the file is ambiguous+ * (format-level: no proof of deletion) and quarantines the sync rather+ * than deleting either side. Only this exact marker value deletes; any+ * other value (including a foreign client's same-named key) is treated as+ * live data and carried through.+ */+ const val FIELD_TOMBSTONE = "_Tombstone"+ const val TOMBSTONE_VALUE = "deleted"++ private const val FIELD_SIGN_COUNT = "_SignCount"+ private const val FIELD_CREATED = "_Created"+ private const val FIELD_LAST_USED = "_LastUsed"+ private const val FIELD_LINKED_PASSWORD = "_LinkedPassword"++ /**+ * Every key this mapper can emit. Keys outside this set belong to whatever client+ * wrote the vault and are carried through untouched on push.+ */+ val OWNED_KEYS = setOf(+ "Title", "UserName", "Email", "Password", "Notes", "URL", "Websites", "otp", "TOTP Seed",+ FIELD_TYPE, FIELD_SYNC_ID, FIELD_MODIFIED, FIELD_TOMBSTONE,+ FIELD_SIGN_COUNT, FIELD_CREATED, FIELD_LAST_USED, FIELD_LINKED_PASSWORD,+ "KPEX_PASSKEY_USERNAME", "KPEX_PASSKEY_PRIVATE_KEY_PEM", "KPEX_PASSKEY_CREDENTIAL_ID",+ "KPEX_PASSKEY_USER_HANDLE", "KPEX_PASSKEY_RELYING_PARTY",+ )++ /** True when this entry is an own-client deletion marker (see FIELD_TOMBSTONE). */+ fun isTombstoneEntry(entry: Map<String, String>): Boolean =+ entry[FIELD_TOMBSTONE] == TOMBSTONE_VALUE &&+ entry[FIELD_SYNC_ID]?.isNotBlank() == true++ fun isPasskeyEntry(entry: Map<String, String>): Boolean =+ entry.keys.any { it.startsWith("KPEX_PASSKEY_") }++ fun toFields(+ name: String,+ username: String,+ email: String,+ password: String,+ note: String,+ websites: List<String>,+ totpSecret: String?,+ syncId: String,+ updatedAt: Long,+ ): Map<String, String> = buildMap {+ put("Title", name)+ put("UserName", username)+ put("Email", email)+ put("Password", password)+ put("Notes", note)+ if (websites.isNotEmpty()) {+ put("URL", websites.first())+ if (websites.size > 1) put("Websites", websites.joinToString("\n"))+ }+ totpSecret?.takeIf { it.isNotBlank() }?.let { put("otp", "otpauth://totp/?secret=$it") }+ put(FIELD_TYPE, "password")+ put(FIELD_SYNC_ID, syncId)+ put(FIELD_MODIFIED, updatedAt.toString())+ }++ /** Content fingerprint ignoring identity, timestamps and tombstone markers. */+ fun contentHash(fields: Map<String, String>): String {+ val canonical = fields.entries+ .filter { it.key != FIELD_SYNC_ID && it.key != FIELD_MODIFIED && it.key != FIELD_TOMBSTONE }+ .sortedBy { it.key }+ .joinToString("") { "${it.key}=${it.value}\n" }+ return SyncDigest.sha256Hex(canonical.encodeToByteArray())+ }++ /** Match key used to adopt pre-existing vault entries on the very first sync. */+ fun passwordContentKey(name: String, username: String): String = "pw\u0000$name\u0000$username"++ fun passkeyContentKey(rpId: String, credentialId: String): String = "pk\u0000$rpId\u0000$credentialId"++ private val json = Json { ignoreUnknownKeys = true }++ /** Canonical JSON helper for callers that hash DTO maps through JSON. */+ fun fieldsJson(fields: Map<String, String>): String = json.encodeToString(fields)+}
library/everysync-core/src/commonMain/kotlin/com/vayunmathur/everysync/core/passwords/PasskeyLink.kt
diff --git a/library/everysync-core/src/commonMain/kotlin/com/vayunmathur/everysync/core/passwords/PasskeyLink.kt b/library/everysync-core/src/commonMain/kotlin/com/vayunmathur/everysync/core/passwords/PasskeyLink.ktnew file mode 100644index 0000000000..9a126cfa1a--- /dev/null+++ b/library/everysync-core/src/commonMain/kotlin/com/vayunmathur/everysync/core/passwords/PasskeyLink.kt@@ -0,0 +1,36 @@+package com.vayunmathur.everysync.core.passwords++/** Detached-link marker, shared with the Android Room column encoding. */+const val PASSKEY_LINK_DETACHED = "-"++/**+ * Which password a passkey belongs to, decoded from the linked-password sync id.+ *+ * The three states are encoded in one nullable column rather than a syncId plus a `detached`+ * flag: the vault syncs as a flat field map with last-writer-wins, and two columns can be merged+ * into a contradictory pair, while three mutually exclusive states in one column cannot disagree.+ */+sealed interface PasskeyLink {+ /** No decision recorded; the matching rule in [mergeCredentials] applies. */+ data object Auto : PasskeyLink++ /** The user disconnected it. Never auto-match, however good the match would be. */+ data object Detached : PasskeyLink++ /** Pinned to the password with this syncId, regardless of domain or username. */+ data class To(val passwordSyncId: String) : PasskeyLink++ companion object {+ fun fromColumn(raw: String?): PasskeyLink = when {+ raw.isNullOrBlank() -> Auto+ raw == PASSKEY_LINK_DETACHED -> Detached+ else -> To(raw)+ }+ }+}++fun PasskeyLink.toColumn(): String? = when (this) {+ PasskeyLink.Auto -> null+ PasskeyLink.Detached -> PASSKEY_LINK_DETACHED+ is PasskeyLink.To -> passwordSyncId+}
library/everysync-core/src/commonMain/kotlin/com/vayunmathur/everysync/core/passwords/Totp.kt
diff --git a/library/everysync-core/src/commonMain/kotlin/com/vayunmathur/everysync/core/passwords/Totp.kt b/library/everysync-core/src/commonMain/kotlin/com/vayunmathur/everysync/core/passwords/Totp.ktnew file mode 100644index 0000000000..7ab3de0e21--- /dev/null+++ b/library/everysync-core/src/commonMain/kotlin/com/vayunmathur/everysync/core/passwords/Totp.kt@@ -0,0 +1,58 @@+package com.vayunmathur.everysync.core.passwords++/**+ * HMAC-SHA1 over a key and message. Platform actuals: JCE `Mac("HmacSHA1")`+ * on Android/JVM, CryptoKit `HMAC<Insecure.SHA1>` on Apple. Pure framing+ * (counter bytes, dynamic truncation) stays in common ([Totp]).+ */+expect object HmacSha1 {+ fun mac(key: ByteArray, message: ByteArray): ByteArray+}++object Totp {+ private const val BASE32_ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"++ // RFC 4648 base32 decode. Input is expected already trimmed/uppercased with+ // padding stripped; any character outside the alphabet is ignored.+ private fun base32Decode(input: String): ByteArray {+ val out = ArrayList<Byte>(input.length * 5 / 8 + 1)+ var buffer = 0+ var bitsLeft = 0+ for (c in input) {+ val value = BASE32_ALPHABET.indexOf(c)+ if (value < 0) continue+ buffer = (buffer shl 5) or value+ bitsLeft += 5+ if (bitsLeft >= 8) {+ bitsLeft -= 8+ out.add(((buffer shr bitsLeft) and 0xFF).toByte())+ }+ }+ return out.toByteArray()+ }++ /** Big-endian 8-byte counter encoding (replaces `java.nio.ByteBuffer`). */+ private fun counterBytes(counter: Long): ByteArray {+ val out = ByteArray(8)+ for (i in 0 until 8) out[i] = (counter ushr (56 - 8 * i)).toByte()+ return out+ }++ private fun hotp(key: ByteArray, counter: Long): String {+ val hash = HmacSha1.mac(key, counterBytes(counter))+ val offset = hash.last().toInt() and 0x0f+ val binary = ((hash[offset].toInt() and 0x7f) shl 24) or+ ((hash[offset + 1].toInt() and 0xff) shl 16) or+ ((hash[offset + 2].toInt() and 0xff) shl 8) or+ (hash[offset + 3].toInt() and 0xff)+ return (binary % 1_000_000).toString().padStart(6, '0')+ }++ fun generate(secret: String, epochSecond: Long): String {+ val cleaned = secret.trim().replace("=", "").replace(" ", "").uppercase()+ val key = base32Decode(cleaned)+ val timeStep = 30L+ val counter = epochSecond / timeStep+ return hotp(key, counter)+ }+}
library/everysync-core/src/commonMain/kotlin/com/vayunmathur/everysync/core/platform/Platform.kt
diff --git a/library/everysync-core/src/commonMain/kotlin/com/vayunmathur/everysync/core/platform/Platform.kt b/library/everysync-core/src/commonMain/kotlin/com/vayunmathur/everysync/core/platform/Platform.ktnew file mode 100644index 0000000000..e2007e6ad3--- /dev/null+++ b/library/everysync-core/src/commonMain/kotlin/com/vayunmathur/everysync/core/platform/Platform.kt@@ -0,0 +1,70 @@+package com.vayunmathur.everysync.core.platform++/**+ * Encrypted key/value + blob storage. Platform actuals: AndroidKeyStore ++ * DataStore on Android; DPAPI / Keychain-via-JNA / libsecret on desktop JVM;+ * Keychain (`kSecClassGenericPassword`) on Apple.+ */+interface SecureStore {+ suspend fun getBytes(name: String): ByteArray?+ suspend fun setBytes(name: String, value: ByteArray, onlyIfAbsent: Boolean = false)+ suspend fun delete(name: String)++ suspend fun getString(name: String): String?+ suspend fun setString(name: String, value: String, onlyIfAbsent: Boolean = false)+ suspend fun getLong(name: String): Long?+ suspend fun setLong(name: String, value: Long)+}++/** Background sync scheduling. */+interface SyncScheduler {+ /** Schedules (or replaces) periodic sync for [accountName] every [intervalMinutes]. */+ fun schedulePeriodic(accountName: String, intervalMinutes: Long, wifiOnly: Boolean)++ /** Cancels periodic sync for [accountName]. */+ fun cancel(accountName: String)++ /** Runs a one-shot sync for [accountName] as soon as possible. */+ fun syncNow(accountName: String)+}++/**+ * Reads/writes one vault type's records through the owning app's storage.+ * Envelope ops map 1:1 to the Android relay-provider ops+ * (`querySince` / `upsertRaw` / `deleteByVault`; columns+ * `syncId / updatedAt / deleted / payloadJson / contentHash`).+ *+ * Passwords HARD-delete (no tombstone rows; `listLocal` never returns+ * deleted); notes/todos SOFT-delete (tombstone rows persist and propagate).+ */+interface SyncSink<T> {+ /** All local rows in relay form (tombstones included for soft-delete types). */+ suspend fun listLocal(vaultId: String): List<T>++ /** True when the last [listLocal] observed a healthy read; false aborts the merge. */+ val listLocalOk: Boolean++ /** Rows changed locally since [since] (tombstones included for soft-delete types). */+ suspend fun localChanges(vaultId: String, since: Long): List<LocalChange<T>>++ /** Idempotent upsert keyed on the relay sync identity; preserves pulled timestamps. */+ suspend fun upsert(vaultId: String, item: T)++ /**+ * Applies a pulled relay tombstone: tombstone the row (soft-delete types)+ * or hard-delete it (passwords). Merge-driven deletes ALWAYS arrive here+ * as tombstone envelopes, never as raw deletes.+ */+ suspend fun delete(vaultId: String, syncId: String)++ /** Removes every row (and snapshots) for this vault; the vault itself stays. */+ suspend fun purge(vaultId: String)+}++/** A locally-changed row detected via the store's timestamp watermark. */+data class LocalChange<T>(+ val syncId: String,+ val updatedAt: Long,+ val deleted: Boolean,+ val item: T?,+)
library/everysync-core/src/commonMain/kotlin/com/vayunmathur/everysync/core/provider/DataType.kt
diff --git a/library/everysync-core/src/commonMain/kotlin/com/vayunmathur/everysync/core/provider/DataType.kt b/library/everysync-core/src/commonMain/kotlin/com/vayunmathur/everysync/core/provider/DataType.ktnew file mode 100644index 0000000000..e54d8f68da--- /dev/null+++ b/library/everysync-core/src/commonMain/kotlin/com/vayunmathur/everysync/core/provider/DataType.kt@@ -0,0 +1,32 @@+package com.vayunmathur.everysync.core.provider++import kotlinx.serialization.Serializable++/** Every domain EverySync can land on-device: system providers or app IPC vaults, all relay-synced. */+@Serializable+enum class DataType {+ CONTACTS,+ CALENDAR,+ /** E2EE relay vault tasks (no system provider; the todo/ app owns storage). */+ TODOS,+ /** E2EE relay vault passwords (passwords app owns storage via its relay ContentProvider). */+ PASSWORDS,+ /** E2EE relay vault notes (notes app owns storage via its relay ContentProvider). */+ NOTES,+}++/** How an account authenticates. Only relay pairing remains: the relay is an untrusted log. */+enum class AuthType {+ /**+ * No remote auth: all authority is client-side (owner-signed roster/epochs/+ * transfers). The vault key lives in secure storage per (account, type).+ */+ RELAY,+}++/** Direction a sync runs in. */+enum class SyncDirection {+ PULL,+ PUSH,+ BOTH,+}
library/everysync-core/src/commonMain/kotlin/com/vayunmathur/everysync/core/provider/SyncDriver.kt
diff --git a/library/everysync-core/src/commonMain/kotlin/com/vayunmathur/everysync/core/provider/SyncDriver.kt b/library/everysync-core/src/commonMain/kotlin/com/vayunmathur/everysync/core/provider/SyncDriver.ktnew file mode 100644index 0000000000..4c028be1cb--- /dev/null+++ b/library/everysync-core/src/commonMain/kotlin/com/vayunmathur/everysync/core/provider/SyncDriver.kt@@ -0,0 +1,77 @@+package com.vayunmathur.everysync.core.provider++import com.vayunmathur.everysync.core.sync.EntityKind+import com.vayunmathur.everysync.core.sync.LocalReadException+import com.vayunmathur.everysync.core.sync.RelayMerge+import com.vayunmathur.everysync.core.sync.RelaySnapshot+import com.vayunmathur.everysync.core.sync.RelayStore++/**+ * A Context-free E2EE sync provider: drives one vault type's merge cycle+ * against an injected [RelayStore]. The Android `E2eeProvider` becomes a thin+ * adapter that builds these stores from its sinks; desktop/iOS providers do+ * the same from theirs.+ */+interface SyncProvider {+ val id: String+ val displayName: String+ val capabilities: Set<DataType>++ /** Run one sync pass in the requested [direction]. */+ suspend fun sync(direction: SyncDirection)+}++/**+ * Context-free merge driver shared by every provider on every target.+ *+ * Driver contract (the relay is an append-only log — records are never+ * rewritten, only appended):+ * 0. A null [remoteEntities] (failed pull) aborts the cycle — never merges.+ * 1. [remoteEntities] must be the FULL folded state (tombstones included).+ * 2. `remoteOut` is serialized via [RelayStore.serializeForRemote] and+ * appended to the relay BEFORE persisting locally.+ * 3. `applyLocal` persists the local half.+ */+object SyncDriver {+ suspend fun <T> drive(+ kind: EntityKind<T>,+ store: RelayStore<T>,+ remoteEntities: List<T>?,+ appendRemote: suspend (items: List<String>) -> Boolean,+ now: Long,+ ): Boolean {+ if (remoteEntities == null) return false+ val local = try {+ store.listLocal()+ } catch (_: LocalReadException) {+ return false+ }+ if (!store.listLocalOk) return false+ val baseline = store.loadBaseline()+ val plan = RelayMerge.merge(kind, local, remoteEntities, baseline, now)+ if (plan.remoteOut.isNotEmpty()) {+ val envelopes = plan.remoteOut.map { store.serializeForRemote(it) }+ if (!appendRemote(envelopes)) return false+ }+ RelayMerge.applyLocal(store, plan)+ return true+ }+}++/** The only provider EverySync ships: personal E2EE vaults. */+object ProviderIds {+ const val E2EE_RELAY = "e2ee_relay"+}++/** In-memory baseline store for tests and drivers that manage their own persistence. */+class MemoryBaselineStore {+ private val snapshots = mutableMapOf<String, RelaySnapshot>()++ fun load(): Map<String, RelaySnapshot> = snapshots.toMap()+ fun save(list: List<RelaySnapshot>) {+ for (s in list) snapshots[s.syncId] = s+ }+ fun remove(ids: List<String>) {+ for (id in ids) snapshots.remove(id)+ }+}
library/everysync-core/src/commonMain/kotlin/com/vayunmathur/everysync/core/sync/RelayMerge.kt
diff --git a/library/everysync-core/src/commonMain/kotlin/com/vayunmathur/everysync/core/sync/RelayMerge.kt b/library/everysync-core/src/commonMain/kotlin/com/vayunmathur/everysync/core/sync/RelayMerge.ktnew file mode 100644index 0000000000..a3d614ff8c--- /dev/null+++ b/library/everysync-core/src/commonMain/kotlin/com/vayunmathur/everysync/core/sync/RelayMerge.kt@@ -0,0 +1,567 @@+package com.vayunmathur.everysync.core.sync++/**+ * Local + remote access for one relay channel. This is the RelayMerge+ * replacement for the KDBX pair (`KdbxDocument` + `KdbxCodec`): the transport+ * itself stays outside, this interface only adapts typed entities to the+ * string envelopes the relay carries.+ *+ * Loss-prevention contract on [listLocal]: a failed local read must surface as+ * failure (throw `LocalReadException`, or a store whose `listLocalOk` returns+ * false), NEVER as an empty list. An empty list means "this vault provably+ * holds nothing locally" — merging a read failure as empty would delete every+ * baseline-present relay record.+ */+interface RelayStore<T> {+ suspend fun listLocal(): List<T>+ suspend fun upsertLocal(items: List<T>)+ suspend fun deleteLocal(items: List<T>)+ suspend fun loadBaseline(): Map<String, RelaySnapshot>+ suspend fun saveSnapshots(snapshots: List<RelaySnapshot>)+ suspend fun removeSnapshots(syncIds: List<String>)++ /**+ * True when the last [listLocal] observed a healthy read. Stores whose+ * read path can fail (ContentProvider IPC, system providers) track this;+ * [RelayMerge] consults it and the driver aborts on false.+ */+ val listLocalOk: Boolean+ get() = true++ /** Parse one decrypted relay envelope; null skips a foreign/corrupt entry. */+ fun parseRemote(json: String): T?++ /** Serialize one entity to a relay envelope (decrypted form). */+ fun serializeForRemote(entity: T): String+}++/** Thrown by [RelayStore.listLocal] when the local read cannot be trusted. */+class LocalReadException(message: String, cause: Throwable? = null) : Exception(message, cause)++/** Per-type behaviour for the generic three-way merge. */+abstract class EntityKind<T> {+ abstract val kind: String+ abstract fun syncId(e: T): String+ abstract fun updatedAt(e: T): Long+ abstract fun isDeleted(e: T): Boolean+ abstract fun contentHash(e: T): String+ abstract fun contentKey(e: T): String+ abstract fun rebind(e: T, syncId: String): T+ abstract fun withDeleted(e: T, deleted: Boolean): T+ abstract fun withUpdatedAt(e: T, updatedAt: Long): T++ /**+ * Whether this store's local side carries authoritative local delete marks+ * that survive in [listLocal] output. When true (soft deletes: tombstone+ * rows from system-provider DELETED flags or app tombstone rows), an id+ * that is absent from [listLocal] WITHOUT a tombstone is never a local+ * delete — it is a missed read — so the merge resurrects the relay copy+ * instead of tombstoning it. When false (hard deletes: the row is gone and+ * only the baseline remembers it), a healthy-read absence is a genuine+ * local delete and the merge propagates a tombstone to the relay.+ */+ open val localDeletesAreAuthoritative: Boolean = true++ fun snapshot(+ syncId: String,+ hash: String,+ localUpdatedAt: Long,+ remoteModified: Long,+ now: Long,+ deleted: Boolean = false,+ ) = RelaySnapshot(syncId, kind, hash, localUpdatedAt, remoteModified, now, deleted)+}++/**+ * The merge outcome. [remoteOut] holds ONLY the records the driver must append+ * to the relay log ([RelayStore.serializeForRemote] each one) — the relay is+ * append-only, so already-logged records are never re-appended.+ */+class RelayPlan<T>(+ val localUpserts: List<T>,+ val localDeletes: List<T>,+ val remoteOut: List<T>,+ val snapshots: List<RelaySnapshot>,+ val removedSyncIds: List<String>,+ val remoteChanged: Boolean,+ val pushed: Int,+ val pulled: Int,+ val deletedLocal: Int,+ val deletedRemote: Int,+)++class MergeAccumulator<T> {+ val localUpserts = mutableListOf<T>()+ val localDeletes = mutableListOf<T>()+ val remoteOut = mutableListOf<T>()+ val snapshots = mutableListOf<RelaySnapshot>()+ val removed = mutableListOf<String>()+ val freshlyIdentified = mutableSetOf<String>()++ /** Remote ids whose envelope on the relay lacks our sync id and must be re-appended. */+ val adoptedRemote = mutableSetOf<String>()+ var remoteChanged = false+ var pushed = 0+ var pulled = 0+ var deletedLocal = 0+ var deletedRemote = 0++ fun toPlan(): RelayPlan<T> = RelayPlan(+ localUpserts = localUpserts,+ localDeletes = localDeletes,+ remoteOut = remoteOut,+ snapshots = snapshots,+ removedSyncIds = removed,+ remoteChanged = remoteChanged,+ pushed = pushed,+ pulled = pulled,+ deletedLocal = deletedLocal,+ deletedRemote = deletedRemote,+ )+}++/**+ * Generic three-way merge extracted from the passwords KDBX engine, without any+ * KDBX dependency.+ *+ * LOSS-PREVENTION RULE: only an explicit tombstone deletes. An id that is+ * present on one side but absent from the folded relay log — with a baseline+ * or without — is NEVER treated as a deletion: the append-only relay log may+ * be truncated, partially read, or mid-propagation, and none of those is proof+ * that anyone deleted anything. Deletion propagates exclusively through an+ * explicit `deleted=true` envelope for that syncId in the folded log+ * (`reconcilePresent` tombstone path).+ *+ * Conflict rule is last-writer-wins by [EntityKind.updatedAt], tie-broken by+ * [EntityKind.contentHash] so equal timestamps stay deterministic across+ * devices. Tombstones ([EntityKind.isDeleted]) win or lose by the same LWW+ * comparison, so a delete races an edit exactly like two edits race.+ *+ * Driver contract (the relay is an append-only log — records are never+ * rewritten, only appended):+ * 0. NEVER call `merge` with a remote fold the transport could not prove:+ * a failed pull must abort the cycle, not produce an empty [remoteEntities]+ * list. (An empty list here means "the log provably holds nothing".)+ * 1. Fold the full decrypted record log into [remoteEntities] (tombstones+ * included; this must be the FULL state, not a delta, so absence vs+ * deletion stays decidable against the baseline).+ * 2. `val plan = RelayMerge.merge(kind, local, remote, baseline, now)`.+ * 3. Append `plan.remoteOut` (via [RelayStore.serializeForRemote]) to the+ * relay BEFORE persisting locally, so a failed append never marks+ * un-pushed records clean.+ * 4. `RelayMerge.applyLocal(store, plan)` to persist the local side.+ */+object RelayMerge {+ fun <T> merge(+ kind: EntityKind<T>,+ localEntities: List<T>,+ remoteEntities: List<T>,+ baseline: Map<String, RelaySnapshot>,+ now: Long,+ ): RelayPlan<T> {+ val accumulator = MergeAccumulator<T>()+ val local = indexLocal(kind, localEntities, accumulator)+ val remote = indexRemote(kind, local, remoteEntities, accumulator)+ reconcileAll(+ kind, local, remote, baseline, now, accumulator,+ kind.localDeletesAreAuthoritative,+ )+ return accumulator.toPlan()+ }++ /** Persists the local half of [plan]: deletes, upserts, then snapshot bookkeeping. */+ suspend fun <T> applyLocal(store: RelayStore<T>, plan: RelayPlan<T>) {+ if (plan.localDeletes.isNotEmpty()) store.deleteLocal(plan.localDeletes)+ if (plan.localUpserts.isNotEmpty()) store.upsertLocal(plan.localUpserts)+ if (plan.removedSyncIds.isNotEmpty()) store.removeSnapshots(plan.removedSyncIds)+ if (plan.snapshots.isNotEmpty()) store.saveSnapshots(plan.snapshots)+ }++ private fun <T> indexLocal(+ kind: EntityKind<T>,+ localEntities: List<T>,+ accumulator: MergeAccumulator<T>,+ ): LinkedHashMap<String, T> {+ val local = LinkedHashMap<String, T>()+ for (raw in localEntities) {+ val entity = if (kind.syncId(raw).isBlank()) {+ kind.withUpdatedAt(kind.rebind(raw, newRelaySyncId()), kind.updatedAt(raw))+ .also { accumulator.freshlyIdentified += kind.syncId(it) }+ } else {+ raw+ }+ local[kind.syncId(entity)] = entity+ }+ return local+ }++ private fun <T> indexRemote(+ kind: EntityKind<T>,+ local: Map<String, T>,+ remoteEntities: List<T>,+ accumulator: MergeAccumulator<T>,+ ): LinkedHashMap<String, T> {+ val remote = LinkedHashMap<String, T>()+ val unidentified = mutableListOf<T>()+ for (entity in remoteEntities) {+ val id = kind.syncId(entity).takeIf { it.isNotBlank() }+ if (id != null && id !in remote) {+ remote[id] = entity+ } else {+ unidentified += entity+ }+ }+ adoptUnidentified(kind, local, remote, unidentified, accumulator)+ return remote+ }++ private fun <T> adoptUnidentified(+ kind: EntityKind<T>,+ local: Map<String, T>,+ remote: LinkedHashMap<String, T>,+ unidentified: List<T>,+ accumulator: MergeAccumulator<T>,+ ) {+ val adoptableByContentKey = local.values.filter { kind.syncId(it) !in remote }+ .associateBy({ kind.contentKey(it) }, { kind.syncId(it) })+ val claimed = mutableSetOf<String>()+ for (entity in unidentified) {+ val match = adoptableByContentKey[kind.contentKey(entity)]+ val id = match?.takeIf { it !in claimed && it !in remote } ?: newRelaySyncId()+ claimed += id+ remote[id] = kind.rebind(entity, id)+ accumulator.adoptedRemote += id+ accumulator.remoteChanged = true+ }+ }++ private fun <T> reconcileAll(+ kind: EntityKind<T>,+ local: Map<String, T>,+ remote: Map<String, T>,+ baseline: Map<String, RelaySnapshot>,+ now: Long,+ accumulator: MergeAccumulator<T>,+ localDeletesAreAuthoritative: Boolean,+ ) {+ for (id in local.keys + remote.keys) {+ reconcileOne(kind, id, local[id], remote[id], baseline[id], now, accumulator, localDeletesAreAuthoritative)+ }+ }++ private fun <T> reconcileOne(+ kind: EntityKind<T>,+ id: String,+ localEntity: T?,+ remoteEntity: T?,+ base: RelaySnapshot?,+ now: Long,+ accumulator: MergeAccumulator<T>,+ localDeletesAreAuthoritative: Boolean,+ ) {+ if (localEntity != null && remoteEntity != null) {+ reconcilePresent(kind, id, localEntity, remoteEntity, base, now, accumulator)+ return+ }+ if (localEntity != null) {+ reconcileLocalOnly(kind, id, localEntity, base, now, accumulator)+ return+ }+ reconcileRemoteOnly(kind, id, remoteEntity!!, base, now, accumulator, localDeletesAreAuthoritative)+ }++ private fun <T> reconcilePresent(+ kind: EntityKind<T>,+ id: String,+ localEntity: T,+ remoteEntity: T,+ base: RelaySnapshot?,+ now: Long,+ accumulator: MergeAccumulator<T>,+ ) {+ val localHash = kind.contentHash(localEntity)+ val remoteHash = kind.contentHash(remoteEntity)+ val localDeleted = kind.isDeleted(localEntity)+ val remoteDeleted = kind.isDeleted(remoteEntity)++ if (localDeleted || remoteDeleted) {+ resolveTombstone(+ kind, id, localEntity, remoteEntity, localDeleted, remoteDeleted,+ localHash, remoteHash, base, now, accumulator,+ )+ return+ }+ if (localHash == remoteHash) {+ if (id in accumulator.freshlyIdentified) accumulator.localUpserts += localEntity+ if (id in accumulator.adoptedRemote) {+ accumulator.remoteOut += kind.rebind(remoteEntity, id)+ }+ accumulator.snapshots += kind.snapshot(+ id,+ localHash,+ kind.updatedAt(localEntity),+ kind.updatedAt(remoteEntity),+ now,+ )+ return+ }+ reconcileDiverged(kind, id, localEntity, remoteEntity, localHash, remoteHash, base, now, accumulator)+ }++ /** One side (or both) is a tombstone: LWW decides delete vs resurrect. */+ private fun <T> resolveTombstone(+ kind: EntityKind<T>,+ id: String,+ localEntity: T,+ remoteEntity: T,+ localDeleted: Boolean,+ remoteDeleted: Boolean,+ localHash: String,+ remoteHash: String,+ base: RelaySnapshot?,+ now: Long,+ accumulator: MergeAccumulator<T>,+ ) {+ val localStamp = kind.updatedAt(localEntity)+ val remoteStamp = kind.updatedAt(remoteEntity)+ val localIsNewer = if (localStamp != remoteStamp) {+ localStamp > remoteStamp+ } else {+ ("$localDeleted$localHash") >= ("$remoteDeleted$remoteHash")+ }+ val deleteWins = if (localIsNewer) localDeleted else remoteDeleted+ val stamp = maxOf(localStamp, remoteStamp)+ if (deleteWins) {+ val tombstone = kind.withUpdatedAt(+ if (localDeleted) localEntity else remoteEntity,+ stamp,+ )+ accumulator.localUpserts += tombstone+ if (localHash != remoteHash) {+ accumulator.remoteOut += tombstone+ accumulator.remoteChanged = true+ }+ accumulator.snapshots += kind.snapshot(id, kind.contentHash(tombstone), stamp, stamp, now, true)+ if (base?.deleted != true) {+ accumulator.deletedLocal+++ accumulator.deletedRemote+++ }+ } else {+ val resurrected = kind.withUpdatedAt(+ if (localDeleted) remoteEntity else localEntity,+ stamp,+ )+ accumulator.localUpserts += resurrected+ accumulator.remoteOut += resurrected+ accumulator.remoteChanged = true+ accumulator.pulled+++ accumulator.snapshots += kind.snapshot(id, kind.contentHash(resurrected), stamp, stamp, now)+ }+ }++ private fun <T> reconcileDiverged(+ kind: EntityKind<T>,+ id: String,+ localEntity: T,+ remoteEntity: T,+ localHash: String,+ remoteHash: String,+ base: RelaySnapshot?,+ now: Long,+ accumulator: MergeAccumulator<T>,+ ) {+ val localDirty = base == null || localHash != base.contentHash+ val remoteDirty = base == null || remoteHash != base.contentHash+ val localStamp = kind.updatedAt(localEntity)+ val remoteStamp = kind.updatedAt(remoteEntity)+ val localWins = when {+ localDirty && remoteDirty -> {+ if (localStamp != remoteStamp) localStamp > remoteStamp else localHash >= remoteHash+ }+ else -> localDirty+ }+ if (localWins) {+ applyLocalWins(kind, id, localEntity, localHash, now, accumulator)+ } else {+ applyRemoteWins(kind, id, localEntity, remoteEntity, remoteHash, now, accumulator)+ }+ }++ private fun <T> applyLocalWins(+ kind: EntityKind<T>,+ id: String,+ localEntity: T,+ localHash: String,+ now: Long,+ accumulator: MergeAccumulator<T>,+ ) {+ accumulator.remoteOut += localEntity+ accumulator.remoteChanged = true+ accumulator.pushed+++ if (id in accumulator.freshlyIdentified) accumulator.localUpserts += localEntity+ val stamp = kind.updatedAt(localEntity)+ accumulator.snapshots += kind.snapshot(id, localHash, stamp, stamp, now, kind.isDeleted(localEntity))+ }++ private fun <T> applyRemoteWins(+ kind: EntityKind<T>,+ id: String,+ localEntity: T,+ remoteEntity: T,+ remoteHash: String,+ now: Long,+ accumulator: MergeAccumulator<T>,+ ) {+ val localId = kind.syncId(localEntity).ifBlank { id }+ accumulator.localUpserts += kind.rebind(remoteEntity, localId)+ accumulator.pulled+++ val stamp = kind.updatedAt(remoteEntity)+ accumulator.snapshots += kind.snapshot(id, remoteHash, stamp, stamp, now, kind.isDeleted(remoteEntity))+ }++ private fun <T> reconcileLocalOnly(+ kind: EntityKind<T>,+ id: String,+ localEntity: T,+ base: RelaySnapshot?,+ now: Long,+ accumulator: MergeAccumulator<T>,+ ) {+ if (base == null) {+ if (kind.isDeleted(localEntity)) {+ accumulator.localDeletes += localEntity+ return+ }+ accumulator.remoteOut += localEntity+ accumulator.remoteChanged = true+ accumulator.pushed+++ if (id in accumulator.freshlyIdentified) accumulator.localUpserts += localEntity+ val stamp = kind.updatedAt(localEntity)+ accumulator.snapshots += kind.snapshot(+ id,+ kind.contentHash(localEntity),+ stamp,+ stamp,+ now,+ kind.isDeleted(localEntity),+ )+ return+ }+ if (base.deleted) {+ if (kind.isDeleted(localEntity)) {+ accumulator.localDeletes += localEntity+ accumulator.removed += id+ } else {+ accumulator.remoteOut += localEntity+ accumulator.remoteChanged = true+ accumulator.pushed+++ val stamp = kind.updatedAt(localEntity)+ accumulator.snapshots += kind.snapshot(+ id,+ kind.contentHash(localEntity),+ stamp,+ stamp,+ now,+ )+ }+ return+ }+ if (kind.isDeleted(localEntity)) {+ accumulator.localDeletes += localEntity+ accumulator.removed += id+ return+ }+ // Present at baseline but absent from the folded relay log WITHOUT an+ // explicit tombstone: NOT a remote delete. The log may be truncated or+ // partially read. Keep the local row and the baseline untouched.+ }++ private fun <T> reconcileRemoteOnly(+ kind: EntityKind<T>,+ id: String,+ remoteEntity: T,+ base: RelaySnapshot?,+ now: Long,+ accumulator: MergeAccumulator<T>,+ localDeletesAreAuthoritative: Boolean,+ ) {+ if (base?.deleted == true) {+ return+ }+ if (base != null && !kind.isDeleted(remoteEntity) && !localDeletesAreAuthoritative) {+ val tombstone = kind.withUpdatedAt(+ kind.withDeleted(kind.rebind(remoteEntity, id), true),+ maxOf(kind.updatedAt(remoteEntity), now),+ )+ accumulator.remoteOut += tombstone+ accumulator.remoteChanged = true+ accumulator.snapshots += kind.snapshot(+ id,+ kind.contentHash(tombstone),+ kind.updatedAt(tombstone),+ kind.updatedAt(tombstone),+ now,+ true,+ )+ accumulator.deletedRemote+++ return+ }+ if (base != null && !kind.isDeleted(remoteEntity)) {+ val rebound = kind.rebind(remoteEntity, id)+ if (kind.isDeleted(rebound)) {+ accumulator.snapshots += kind.snapshot(+ id,+ kind.contentHash(rebound),+ kind.updatedAt(rebound),+ kind.updatedAt(rebound),+ now,+ true,+ )+ accumulator.deletedRemote+++ return+ }+ accumulator.localUpserts += rebound+ if (id in accumulator.adoptedRemote) {+ accumulator.remoteOut += rebound+ accumulator.remoteChanged = true+ }+ accumulator.pulled+++ val stamp = kind.updatedAt(remoteEntity)+ accumulator.snapshots += kind.snapshot(+ id,+ kind.contentHash(rebound),+ stamp,+ stamp,+ now,+ )+ return+ }+ val rebound = kind.rebind(remoteEntity, id)+ if (kind.isDeleted(rebound)) {+ accumulator.snapshots += kind.snapshot(+ id,+ kind.contentHash(rebound),+ kind.updatedAt(rebound),+ kind.updatedAt(rebound),+ now,+ true,+ )+ accumulator.deletedRemote+++ return+ }+ accumulator.localUpserts += rebound+ if (id in accumulator.adoptedRemote) {+ accumulator.remoteOut += rebound+ accumulator.remoteChanged = true+ }+ accumulator.pulled+++ val stamp = kind.updatedAt(remoteEntity)+ accumulator.snapshots += kind.snapshot(+ id,+ kind.contentHash(rebound),+ stamp,+ stamp,+ now,+ )+ }+}
library/everysync-core/src/commonMain/kotlin/com/vayunmathur/everysync/core/sync/RelaySnapshot.kt
diff --git a/library/everysync-core/src/commonMain/kotlin/com/vayunmathur/everysync/core/sync/RelaySnapshot.kt b/library/everysync-core/src/commonMain/kotlin/com/vayunmathur/everysync/core/sync/RelaySnapshot.ktnew file mode 100644index 0000000000..e8673a8b1c--- /dev/null+++ b/library/everysync-core/src/commonMain/kotlin/com/vayunmathur/everysync/core/sync/RelaySnapshot.kt@@ -0,0 +1,27 @@+package com.vayunmathur.everysync.core.sync++import kotlin.uuid.Uuid++/**+ * Last agreed state of one relay record, written after a successful merge.+ *+ * Mirrors the passwords baseline: without it "present locally, absent remotely"+ * cannot be told apart from "created locally, not pushed yet", so deletions+ * could never propagate. [deleted] marks a retained tombstone alongside the+ * snapshot rows so a delete survives until both sides have acknowledged it.+ */+data class RelaySnapshot(+ val syncId: String,+ val kind: String,+ val contentHash: String,+ val localUpdatedAt: Long,+ val remoteModified: Long,+ val lastSyncedAt: Long,+ val deleted: Boolean = false,+)++/** Opaque 32-char identity shared between a local row and its relay record. */+fun newRelaySyncId(): String = Uuid.random().toString().replace("-", "")++fun relayContentHash(canonical: String): String =+ SyncDigest.sha256Hex(canonical.encodeToByteArray())
library/everysync-core/src/commonMain/kotlin/com/vayunmathur/everysync/core/sync/SyncDigest.kt
diff --git a/library/everysync-core/src/commonMain/kotlin/com/vayunmathur/everysync/core/sync/SyncDigest.kt b/library/everysync-core/src/commonMain/kotlin/com/vayunmathur/everysync/core/sync/SyncDigest.ktnew file mode 100644index 0000000000..9841c943ac--- /dev/null+++ b/library/everysync-core/src/commonMain/kotlin/com/vayunmathur/everysync/core/sync/SyncDigest.kt@@ -0,0 +1,116 @@+package com.vayunmathur.everysync.core.sync++/**+ * Pure-Kotlin SHA-256 (no `java.security`, no platform API) so+ * `relayContentHash` runs unchanged on Android, JVM desktop, and+ * Kotlin/Native (iOS). FIPS 180-4, verified against NIST vectors.+ */+object SyncDigest {+ private val K = intArrayOf(+ 0x428a2f98.toInt(), 0x71374491.toInt(), 0xb5c0fbcf.toInt(), 0xe9b5dba5.toInt(),+ 0x3956c25b.toInt(), 0x59f111f1.toInt(), 0x923f82a4.toInt(), 0xab1c5ed5.toInt(),+ 0xd807aa98.toInt(), 0x12835b01.toInt(), 0x243185be.toInt(), 0x550c7dc3.toInt(),+ 0x72be5d74.toInt(), 0x80deb1fe.toInt(), 0x9bdc06a7.toInt(), 0xc19bf174.toInt(),+ 0xe49b69c1.toInt(), 0xefbe4786.toInt(), 0x0fc19dc6.toInt(), 0x240ca1cc.toInt(),+ 0x2de92c6f.toInt(), 0x4a7484aa.toInt(), 0x5cb0a9dc.toInt(), 0x76f988da.toInt(),+ 0x983e5152.toInt(), 0xa831c66d.toInt(), 0xb00327c8.toInt(), 0xbf597fc7.toInt(),+ 0xc6e00bf3.toInt(), 0xd5a79147.toInt(), 0x06ca6351.toInt(), 0x14292967.toInt(),+ 0x27b70a85.toInt(), 0x2e1b2138.toInt(), 0x4d2c6dfc.toInt(), 0x53380d13.toInt(),+ 0x650a7354.toInt(), 0x766a0abb.toInt(), 0x81c2c92e.toInt(), 0x92722c85.toInt(),+ 0xa2bfe8a1.toInt(), 0xa81a664b.toInt(), 0xc24b8b70.toInt(), 0xc76c51a3.toInt(),+ 0xd192e819.toInt(), 0xd6990624.toInt(), 0xf40e3585.toInt(), 0x106aa070.toInt(),+ 0x19a4c116.toInt(), 0x1e376c08.toInt(), 0x2748774c.toInt(), 0x34b0bcb5.toInt(),+ 0x391c0cb3.toInt(), 0x4ed8aa4a.toInt(), 0x5b9cca4f.toInt(), 0x682e6ff3.toInt(),+ 0x748f82ee.toInt(), 0x78a5636f.toInt(), 0x84c87814.toInt(), 0x8cc70208.toInt(),+ 0x90befffa.toInt(), 0xa4506ceb.toInt(), 0xbef9a3f7.toInt(), 0xc67178f2.toInt(),+ )++ fun sha256(data: ByteArray): ByteArray {+ var h0 = 0x6a09e667.toInt()+ var h1 = 0xbb67ae85.toInt()+ var h2 = 0x3c6ef372.toInt()+ var h3 = 0xa54ff53a.toInt()+ var h4 = 0x510e527f.toInt()+ var h5 = 0x9b05688c.toInt()+ var h6 = 0x1f83d9ab.toInt()+ var h7 = 0x5be0cd19.toInt()++ val bitLen = data.size.toLong() * 8L+ val paddedSize = ((data.size + 9 + 63) / 64) * 64+ val padded = ByteArray(paddedSize)+ data.copyInto(padded)+ padded[data.size] = 0x80.toByte()+ for (i in 0 until 8) {+ padded[paddedSize - 8 + i] = (bitLen ushr (56 - 8 * i)).toByte()+ }++ val w = IntArray(64)+ var off = 0+ while (off < paddedSize) {+ for (i in 0 until 16) {+ w[i] = (padded[off + i * 4].toInt() and 0xff shl 24) or+ (padded[off + i * 4 + 1].toInt() and 0xff shl 16) or+ (padded[off + i * 4 + 2].toInt() and 0xff shl 8) or+ (padded[off + i * 4 + 3].toInt() and 0xff)+ }+ for (i in 16 until 64) {+ val s0 = w[i - 15].rotateRight(7) xor w[i - 15].rotateRight(18) xor (w[i - 15] ushr 3)+ val s1 = w[i - 2].rotateRight(17) xor w[i - 2].rotateRight(19) xor (w[i - 2] ushr 10)+ w[i] = w[i - 16] + s0 + w[i - 7] + s1+ }+ var a = h0+ var b = h1+ var c = h2+ var d = h3+ var e = h4+ var f = h5+ var g = h6+ var h = h7+ for (i in 0 until 64) {+ val s1 = e.rotateRight(6) xor e.rotateRight(11) xor e.rotateRight(25)+ val ch = (e and f) xor (e.inv() and g)+ val t1 = h + s1 + ch + K[i] + w[i]+ val s0 = a.rotateRight(2) xor a.rotateRight(13) xor a.rotateRight(22)+ val maj = (a and b) xor (a and c) xor (b and c)+ val t2 = s0 + maj+ h = g+ g = f+ f = e+ e = d + t1+ d = c+ c = b+ b = a+ a = t1 + t2+ }+ h0 += a+ h1 += b+ h2 += c+ h3 += d+ h4 += e+ h5 += f+ h6 += g+ h7 += h+ off += 64+ }++ fun Int.toBytes(out: ByteArray, o: Int) {+ out[o] = (this ushr 24).toByte()+ out[o + 1] = (this ushr 16).toByte()+ out[o + 2] = (this ushr 8).toByte()+ out[o + 3] = this.toByte()+ }+ val out = ByteArray(32)+ h0.toBytes(out, 0)+ h1.toBytes(out, 4)+ h2.toBytes(out, 8)+ h3.toBytes(out, 12)+ h4.toBytes(out, 16)+ h5.toBytes(out, 20)+ h6.toBytes(out, 24)+ h7.toBytes(out, 28)+ return out+ }++ fun sha256Hex(data: ByteArray): String =+ sha256(data).joinToString("") { it.toInt().and(0xff).toString(16).padStart(2, '0') }+}
library/everysync-core/src/commonMain/kotlin/com/vayunmathur/everysync/core/sync/SyncStatus.kt
diff --git a/library/everysync-core/src/commonMain/kotlin/com/vayunmathur/everysync/core/sync/SyncStatus.kt b/library/everysync-core/src/commonMain/kotlin/com/vayunmathur/everysync/core/sync/SyncStatus.ktnew file mode 100644index 0000000000..54f3fb7daf--- /dev/null+++ b/library/everysync-core/src/commonMain/kotlin/com/vayunmathur/everysync/core/sync/SyncStatus.kt@@ -0,0 +1,18 @@+package com.vayunmathur.everysync.core.sync++import kotlinx.coroutines.flow.MutableStateFlow+import kotlinx.coroutines.flow.StateFlow+import kotlinx.coroutines.flow.asStateFlow+import kotlinx.coroutines.flow.update++/**+ * In-process set of account names currently syncing. Fed by the sync driver+ * and observed by the UI to show a live progress indicator.+ */+object SyncStatus {+ private val _syncing = MutableStateFlow<Set<String>>(emptySet())+ val syncing: StateFlow<Set<String>> = _syncing.asStateFlow()++ fun begin(accountName: String) = _syncing.update { it + accountName }+ fun finish(accountName: String) = _syncing.update { it - accountName }+}
library/everysync-core/src/commonMain/kotlin/com/vayunmathur/everysync/core/sync/VaultPolicy.kt
diff --git a/library/everysync-core/src/commonMain/kotlin/com/vayunmathur/everysync/core/sync/VaultPolicy.kt b/library/everysync-core/src/commonMain/kotlin/com/vayunmathur/everysync/core/sync/VaultPolicy.ktnew file mode 100644index 0000000000..1663d333bf--- /dev/null+++ b/library/everysync-core/src/commonMain/kotlin/com/vayunmathur/everysync/core/sync/VaultPolicy.kt@@ -0,0 +1,313 @@+package com.vayunmathur.everysync.core.sync++import com.vayunmathur.everysync.core.network.KeyEpoch+import com.vayunmathur.everysync.core.network.Member+import com.vayunmathur.everysync.core.network.RelayRoles+import com.vayunmathur.everysync.core.network.RelayTransport+import com.vayunmathur.everysync.core.network.SignedEnvelope+import com.vayunmathur.everysync.core.network.keysChannel+import com.vayunmathur.everysync.core.network.membersChannel+import com.vayunmathur.everysync.core.network.ownerChannel+import kotlinx.serialization.encodeToString+import kotlinx.serialization.json.Json+import kotlin.io.encoding.Base64++/**+ * Owner-signed membership roster for a personal E2EE vault.+ *+ * The roster lives on the `members:<vaultId>` relay channel as a batch of+ * [SignedEnvelope] records: each envelope's payload is the JSON list+ * of [Member] and its signature is the owner's PQC signature over the+ * raw payload bytes. Only envelopes with a valid owner signature are honored —+ * the relay is an untrusted log, so authority is enforced entirely client-side.+ *+ * Last record wins per member id. Revocation is `role="revoked"`; removing read+ * access additionally requires a key rotation (see [VaultKeys.rotateKey]).+ *+ * KMP port: the Android singleton's `RelaySync` static calls are replaced with+ * an injected [RelayTransport] so this runs on every target.+ */+class VaultRoster(private val transport: RelayTransport) {+ private val json = Json { ignoreUnknownKeys = true }++ /**+ * Owner-signs [members] and appends them to the roster channel. The caller+ * must be the vault owner (signing uses this device's identity) — enforced+ * by the share flow, not here.+ */+ suspend fun recordMembers(vaultId: String, members: List<Member>): Boolean =+ runCatching {+ val payload = json.encodeToString(members)+ val sig = Base64.encode(transport.sign(payload.encodeToByteArray()))+ val envelope = json.encodeToString(SignedEnvelope(transport.deviceId, sig, payload))+ transport.appendRaw(membersChannel(vaultId), listOf(envelope)) != null+ }.getOrDefault(false)++ /**+ * Reads + verifies the roster: only envelopes with a valid [ownerKey]+ * signature are honored. Returns member id → member, last record wins.+ *+ * A failed pull returns an empty map (fail closed): the merge driver+ * already aborts the record cycle before consulting the roster, and+ * vault resolution treats "not on roster" as "skip this vault".+ */+ suspend fun fetchRoster(vaultId: String, ownerKey: ByteArray): Map<String, Member> {+ if (ownerKey.isEmpty()) return emptyMap()+ val raw = runCatching { transport.pullRaw(membersChannel(vaultId), 0) }.getOrNull()+ ?: return emptyMap()+ val byId = LinkedHashMap<String, Member>()+ for (r in raw) {+ val envelope = runCatching {+ json.decodeFromString<SignedEnvelope>(r)+ }.getOrNull() ?: continue+ val sig = runCatching { Base64.decode(envelope.sig) }.getOrNull() ?: continue+ if (!transport.verify(ownerKey, envelope.payload.encodeToByteArray(), sig)) continue+ val members = runCatching {+ json.decodeFromString<List<Member>>(envelope.payload)+ }.getOrNull() ?: continue+ for (member in members) {+ if (member.id.isNotBlank()) byId[member.id] = member+ }+ }+ return byId+ }++ /** This device's role in the vault, or null when it is not on the verified roster. */+ suspend fun myRole(+ vaultId: String,+ ownerKey: ByteArray,+ deviceId: String = transport.deviceId,+ ): String? = fetchRoster(vaultId, ownerKey)[deviceId]?.role++ /** Owner sets/changes one member's role, or revokes with `role="revoked"`. Owner only. */+ suspend fun setRole(vaultId: String, memberId: String, name: String = "", role: String): Boolean =+ recordMembers(vaultId, listOf(Member(memberId, name, role)))+}++/**+ * Ownership transfers for a personal E2EE vault.+ *+ * Transfers live on the `owner:<vaultId>` channel as base64(JSON) records+ * signed by the *current* owner. Members follow the signed chain from the+ * vault's base owner key ([fetchOwnerKey]) to determine the current owner; a+ * transfer whose signature does not verify against the running key is skipped,+ * and each record is consumed at most once so a forked chain cannot loop.+ */+class OwnerTransfer(+ private val transport: RelayTransport,+ private val roster: VaultRoster,+) {+ private val json = Json { ignoreUnknownKeys = true }++ /**+ * Canonical bytes the current owner signs for a handoff: binds the vault+ * id, the new owner's device id and their PQC public bundle.+ */+ fun ownerSigningBytes(vaultId: String, newOwnerId: String, newOwnerKeyB64: String): ByteArray =+ "$vaultId|owner|$newOwnerId|$newOwnerKeyB64".encodeToByteArray()++ /**+ * Follows the signed transfer chain from [baseOwnerKeyB64] (the owner's PQC+ * bundle as issued in the invite) to the current owner key. Returns null+ * when the base key is missing/corrupt.+ */+ suspend fun fetchOwnerKey(vaultId: String, baseOwnerKeyB64: String): ByteArray? {+ var ownerKey = baseOwnerKeyB64.takeIf { it.isNotBlank() }+ ?.let { runCatching { Base64.decode(it) }.getOrNull() } ?: return null+ // A failed pull keeps the base key: a transfer chain we cannot read is+ // not a chain that doesn't exist. Vault resolution re-fetches every+ // cycle, so a recovered relay is picked up on retry.+ val transfers = runCatching { transport.pullRaw(ownerChannel(vaultId), 0) }+ .getOrNull()?.mapNotNull { decodeTransfer(it) } ?: return ownerKey+ val used = HashSet<Int>()+ var advanced = true+ while (advanced) {+ advanced = false+ for ((idx, transfer) in transfers.withIndex()) {+ if (idx in used) continue+ val sig = runCatching { Base64.decode(transfer.sig) }.getOrNull() ?: continue+ if (!transport.verify(+ ownerKey,+ ownerSigningBytes(vaultId, transfer.newOwnerId, transfer.newOwnerKey),+ sig,+ )+ ) {+ continue+ }+ val decoded = runCatching { Base64.decode(transfer.newOwnerKey) }.getOrNull()+ if (decoded != null && decoded.isNotEmpty()) {+ ownerKey = decoded+ used.add(idx)+ advanced = true+ }+ }+ }+ return ownerKey+ }++ /**+ * Transfers vault ownership to [newOwnerId]. Signs with this device's+ * identity (the caller must be the current owner), records the roster+ * change (new owner promoted, self demoted to editor) and appends the+ * signed transfer. Returns true on success.+ */+ suspend fun transferOwnership(+ vaultId: String,+ newOwnerId: String,+ newOwnerName: String = "",+ selfName: String = "",+ selfDeviceId: String = transport.deviceId,+ ): Boolean = runCatching {+ val newBundle = transport.getKey(newOwnerId) ?: return@runCatching false+ val newKeyB64 = Base64.encode(newBundle)+ // Last owner-signed roster change: promote the new owner, demote self.+ // The new-owner record must land before the transfer so verifiers see a+ // consistent roster even mid-handoff.+ if (!roster.recordMembers(+ vaultId,+ listOf(+ Member(newOwnerId, newOwnerName, RelayRoles.OWNER),+ Member(selfDeviceId, selfName, RelayRoles.EDITOR),+ ),+ )+ ) {+ return@runCatching false+ }+ val sig = Base64.encode(transport.sign(ownerSigningBytes(vaultId, newOwnerId, newKeyB64)))+ val transfer = json.encodeToString(+ com.vayunmathur.everysync.core.network.OwnerTransferRecord(newOwnerId, newKeyB64, sig),+ )+ transport.appendRaw(ownerChannel(vaultId), listOf(Base64.encode(transfer.encodeToByteArray()))) != null+ }.getOrDefault(false)++ private fun decodeTransfer(blob: String): com.vayunmathur.everysync.core.network.OwnerTransferRecord? =+ runCatching {+ json.decodeFromString<com.vayunmathur.everysync.core.network.OwnerTransferRecord>(+ Base64.decode(blob).decodeToString(),+ )+ }.getOrNull()+}++/**+ * Owner-signed key epochs for a personal E2EE vault: cryptographic+ * read-revocation after a member is removed or downgraded.+ *+ * Epochs live on the `keys:<vaultId>` channel as base64(JSON([KeyEpoch]))+ * records. Each epoch wraps the fresh AES content key with every remaining+ * member's PQC bundle; only epochs with a valid owner signature over+ * [epochSigningBytes] are honored.+ *+ * Members resolve the current key with [fetchCurrentKey]: the highest verified+ * epoch they can unseal, falling back to the invite (epoch 0) key.+ *+ * KMP port: `RelaySync` statics replaced with injected [RelayTransport].+ */+class VaultKeys(+ private val transport: RelayTransport,+ private val roster: VaultRoster,+) {+ private val json = Json { ignoreUnknownKeys = true }++ /**+ * Canonical bytes the owner signs for an epoch: binds the vault id, the+ * epoch number and every wrap (sorted by member id for determinism) to the+ * vault.+ */+ fun epochSigningBytes(vaultId: String, epoch: Int, wraps: Map<String, String>): ByteArray =+ (listOf(vaultId, epoch.toString()) ++ wraps.entries.sortedBy { it.key }.map { "${it.key}=${it.value}" })+ .joinToString("|").encodeToByteArray()++ /**+ * Resolves the current content key: the highest owner-signed epoch this+ * device can unseal, falling back to ([inviteEpoch], [inviteKey]).+ * Returns (epoch, key).+ *+ * A failed pull keeps the invite key (the epoch loop simply finds nothing+ * newer); epoch-bearing history stays unreadable until the pull succeeds,+ * which is fail-closed — the record cycle aborts before merging.+ */+ suspend fun fetchCurrentKey(+ vaultId: String,+ inviteKey: ByteArray,+ ownerKey: ByteArray?,+ inviteEpoch: Int = 0,+ deviceId: String = transport.deviceId,+ ): Pair<Int, ByteArray> {+ if (ownerKey == null || ownerKey.isEmpty()) return inviteEpoch to inviteKey+ var bestEpoch = inviteEpoch+ var bestKey = inviteKey+ val blobs = runCatching { transport.pullRaw(keysChannel(vaultId), 0) }.getOrNull()+ ?: return inviteEpoch to inviteKey+ for (blob in blobs) {+ val epoch = decodeEpoch(blob) ?: continue+ val sig = runCatching { Base64.decode(epoch.sig) }.getOrNull() ?: continue+ if (!transport.verify(ownerKey, epochSigningBytes(vaultId, epoch.epoch, epoch.wraps), sig)) continue+ val wrap = epoch.wraps[deviceId] ?: continue+ val key = runCatching { transport.unseal(Base64.decode(wrap)) }.getOrNull() ?: continue+ if (epoch.epoch >= bestEpoch) {+ bestEpoch = epoch.epoch+ bestKey = key+ }+ }+ return bestEpoch to bestKey+ }++ /**+ * Owner mints a new content key sealed to [memberBundles] (member id →+ * PQC public bundle) and publishes the signed epoch. Always includes+ * [ownerDeviceId] so the owner keeps access. Returns the new key, or null+ * when the publish fails. The caller re-baselines the vault's record log+ * under the new key — rotation without a re-push would leave remaining+ * members unable to read history.+ */+ suspend fun rotateKey(+ vaultId: String,+ currentEpoch: Int,+ memberBundles: Map<String, ByteArray>,+ ownerDeviceId: String = transport.deviceId,+ ownerBundle: ByteArray = transport.publicBundle,+ ): ByteArray? {+ val newEpoch = currentEpoch + 1+ val newKey = transport.newVaultKey()+ val wraps = HashMap<String, String>()+ for ((id, bundle) in memberBundles) {+ if (bundle.isEmpty()) continue+ wraps[id] = Base64.encode(transport.seal(bundle, newKey))+ }+ // Always include ourselves so the owner keeps access even when the+ // roster fetch raced.+ wraps[ownerDeviceId] = Base64.encode(transport.seal(ownerBundle, newKey))+ val sig = Base64.encode(transport.sign(epochSigningBytes(vaultId, newEpoch, wraps)))+ val record = Base64.encode(json.encodeToString(KeyEpoch(newEpoch, wraps, sig)).encodeToByteArray())+ val ok = runCatching { transport.appendRaw(keysChannel(vaultId), listOf(record)) }.getOrNull() != null+ return if (ok) newKey else null+ }++ /**+ * Downgrades/removes [memberId] from the roster and rotates the content key+ * so the removed member can no longer decrypt new content. Owner only.+ * Returns the new key, or null on failure.+ */+ suspend fun revokeAndRotate(+ vaultId: String,+ memberId: String,+ memberName: String = "",+ role: String = RelayRoles.REVOKED,+ currentEpoch: Int,+ memberBundles: Map<String, ByteArray>,+ ownerKey: ByteArray,+ ownerDeviceId: String = transport.deviceId,+ ): ByteArray? {+ if (!roster.setRole(vaultId, memberId, memberName, role)) return null+ val remaining = roster.fetchRoster(vaultId, ownerKey)+ .filter { it.key != memberId && it.value.role != RelayRoles.REVOKED }+ .mapNotNull { (id, _) -> memberBundles[id]?.let { id to it } }+ .toMap()+ return rotateKey(vaultId, currentEpoch, remaining, ownerDeviceId)+ }++ private fun decodeEpoch(blob: String): KeyEpoch? = runCatching {+ json.decodeFromString<KeyEpoch>(Base64.decode(blob).decodeToString())+ }.getOrNull()+}
library/everysync-core/src/commonMain/kotlin/com/vayunmathur/everysync/core/sync/adapters/CalendarKind.kt
diff --git a/library/everysync-core/src/commonMain/kotlin/com/vayunmathur/everysync/core/sync/adapters/CalendarKind.kt b/library/everysync-core/src/commonMain/kotlin/com/vayunmathur/everysync/core/sync/adapters/CalendarKind.ktnew file mode 100644index 0000000000..acc69bf869--- /dev/null+++ b/library/everysync-core/src/commonMain/kotlin/com/vayunmathur/everysync/core/sync/adapters/CalendarKind.kt@@ -0,0 +1,70 @@+package com.vayunmathur.everysync.core.sync.adapters++import com.vayunmathur.everysync.core.data.RemoteEvent+import com.vayunmathur.everysync.core.format.ICalendar+import com.vayunmathur.everysync.core.sync.EntityKind+import com.vayunmathur.everysync.core.sync.relayContentHash+import kotlinx.serialization.encodeToString+import kotlinx.serialization.json.Json++/**+ * Relay merge behaviour for calendar events. Identity is UID plus RECURRENCE-ID+ * ([RemoteEvent.recurrenceId]): each overridden instance merges independently+ * while the master keeps a null recurrence id. The relay envelope is the+ * [RemoteEvent] JSON.+ */+object CalendarKind : EntityKind<RemoteEvent>() {+ override val kind = "event"++ /** Calendar soft-deletes at the platform layer (DELETED flags); the default holds. */+ override val localDeletesAreAuthoritative = true++ private val json = Json { ignoreUnknownKeys = true }++ /** UID + RECURRENCE-ID so one instance never collides with its master. */+ override fun syncId(e: RemoteEvent): String =+ if (e.recurrenceId.isNullOrBlank()) e.uid else "${e.uid}\u0000${e.recurrenceId}"++ override fun updatedAt(e: RemoteEvent) = e.updatedAt+ override fun isDeleted(e: RemoteEvent) = e.deleted++ override fun contentHash(e: RemoteEvent): String =+ relayContentHash(canonical(e) + "\u0000deleted=${e.deleted}")++ override fun contentKey(e: RemoteEvent): String =+ "event\u0000${e.calendarId}\u0000${e.uid}\u0000${e.recurrenceId.orEmpty()}"++ override fun rebind(e: RemoteEvent, syncId: String): RemoteEvent {+ val sep = syncId.indexOf('\u0000')+ return if (sep < 0) {+ e.copy(uid = syncId)+ } else {+ e.copy(uid = syncId.take(sep), recurrenceId = syncId.substring(sep + 1).ifBlank { null })+ }+ }++ override fun withDeleted(e: RemoteEvent, deleted: Boolean) = e.copy(deleted = deleted)+ override fun withUpdatedAt(e: RemoteEvent, updatedAt: Long) = e.copy(updatedAt = updatedAt)++ /**+ * Canonical iCalendar without identity or transport metadata, so a fresh+ * sync id or a server re-tag never looks like an edit. RECURRENCE-ID is+ * kept: it distinguishes an overridden instance from its master.+ */+ fun canonical(e: RemoteEvent): String =+ ICalendar.serialize(+ e.copy(+ uid = "",+ etag = null,+ href = null,+ calendarId = "",+ updatedAt = 0L,+ ),+ )++ fun toJson(e: RemoteEvent): String = json.encodeToString(e)++ fun fromJson(raw: String): RemoteEvent? = runCatching {+ json.decodeFromString<RemoteEvent>(raw)+ }.getOrNull()+}
library/everysync-core/src/commonMain/kotlin/com/vayunmathur/everysync/core/sync/adapters/ContactKind.kt
diff --git a/library/everysync-core/src/commonMain/kotlin/com/vayunmathur/everysync/core/sync/adapters/ContactKind.kt b/library/everysync-core/src/commonMain/kotlin/com/vayunmathur/everysync/core/sync/adapters/ContactKind.ktnew file mode 100644index 0000000000..8e56ac58f3--- /dev/null+++ b/library/everysync-core/src/commonMain/kotlin/com/vayunmathur/everysync/core/sync/adapters/ContactKind.kt@@ -0,0 +1,51 @@+package com.vayunmathur.everysync.core.sync.adapters++import com.vayunmathur.everysync.core.data.RemoteContact+import com.vayunmathur.everysync.core.format.VCard+import com.vayunmathur.everysync.core.sync.EntityKind+import com.vayunmathur.everysync.core.sync.relayContentHash+import kotlinx.serialization.encodeToString+import kotlinx.serialization.json.Json++/**+ * Relay merge behaviour for contacts. The relay envelope is the+ * [RemoteContact] JSON; the canonical content form for hashing is the vCard+ * text with identity and transport metadata stripped, so a server re-tag or+ * a fresh sync id never looks like an edit.+ */+object ContactKind : EntityKind<RemoteContact>() {+ override val kind = "contact"++ /** Contacts soft-delete at the platform layer (DELETED flags); the default holds. */+ override val localDeletesAreAuthoritative = true++ private val json = Json { ignoreUnknownKeys = true }++ override fun syncId(e: RemoteContact) = e.uid+ override fun updatedAt(e: RemoteContact) = e.updatedAt+ override fun isDeleted(e: RemoteContact) = e.deleted++ override fun contentHash(e: RemoteContact): String =+ relayContentHash(canonical(e) + "\u0000deleted=${e.deleted}")++ override fun contentKey(e: RemoteCont
Diff truncated.