Modern Apps git

← Modern-Apps.git

everysync-core: OkHttp relay transport + secure stores

Commit
4960bb45f6f8c8eed6f9a13db6924357cf540885
Author
vayun-mathur <[email protected]>
When
2026-10-16 18:45 UTC (1 month ago)
Parents
7931563

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.ktsindex da1c5d8926..7f2e3ff548 100644--- a/build-logic/src/main/kotlin/common-conventions-kmp.gradle.kts+++ b/build-logic/src/main/kotlin/common-conventions-kmp.gradle.kts@@ -28,7 +28,7 @@ val libs = the<org.gradle.accessors.dm.LibrariesForLibs>() // `: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 {+    android {         namespace = "com.vayunmathur.everysync.core"         compileSdk = 37         minSdk = 31
library/everysync-core/.gitignore
diff --git a/library/everysync-core/.gitignore b/library/everysync-core/.gitignorenew file mode 100644index 0000000000..e2c1de1303--- /dev/null+++ b/library/everysync-core/.gitignore@@ -0,0 +1,4 @@+# Pinned FIRST_PARTY CA DERs are build copies of+# library/network/src/main/assets/ca/ (via the syncCaResources task), not+# sources — Gradle re-copies them on a fresh checkout.+src/commonMain/resources/ca/
library/everysync-core/AGENTS.md
diff --git a/library/everysync-core/AGENTS.md b/library/everysync-core/AGENTS.mdindex 7992e37473..3b648ba3c2 100644--- a/library/everysync-core/AGENTS.md+++ b/library/everysync-core/AGENTS.md@@ -13,7 +13,7 @@ ## 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).+**Gotchas:** never depend on `:library:log` / `:library:network` / `:library:room` from commonMain (Android-only, no common variant); FIRST_PARTY pinning DERs are copied by `syncCaResources` into `src/commonMain/resources/ca/` (gitignored build output) and loaded at runtime by the OkHttp actuals.  ## Verify (this module only) ```
library/everysync-core/build.gradle.kts
diff --git a/library/everysync-core/build.gradle.kts b/library/everysync-core/build.gradle.ktsindex bd454c0a73..f509b2d386 100644--- a/library/everysync-core/build.gradle.kts+++ b/library/everysync-core/build.gradle.kts@@ -2,7 +2,33 @@ 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).+dependencies {+    // OkHttp lives only in platform actuals: pinned TLS + WS on Android/JVM+    // (Phase 1C), Darwin/sec-trust on iOS (Phase 3). commonMain stays+    // engine-free behind the RelayHttpClient interface so no HTTP API leaks+    // into the shared merge/vault policy.+    add("androidMainImplementation", libs.okhttp)+    add("jvmMainImplementation", libs.okhttp)+}++// Pinning DERs (FIRST_PARTY bundle: ISRG X1/X2 + GTS R1-R4) as KMP resources.+// The copy runs as a task dependency so a fresh checkout self-heals.+val syncCaResources = tasks.register("syncCaResources", Copy::class.java) {+    description = "Copies FIRST_PARTY pinning DERs from :library:network assets into common resources."+    val caDir = rootProject.file("library/network/src/main/assets/ca")+    val firstParty = listOf(+        "isrgrootx1.der",+        "isrgrootx2.der",+        "gts-root-r1.der",+        "gts-root-r2.der",+        "gts-root-r3.der",+        "gts-root-r4.der",+    )+    onlyIf { caDir.isDirectory }+    from(caDir) { include(firstParty) }+    into(layout.projectDirectory.dir("src/commonMain/resources/ca"))+}++tasks.matching { it.name.startsWith("compile") || it.name.contains("ProcessResources") }.configureEach {+    dependsOn(syncCaResources)+}
library/everysync-core/src/androidMain/kotlin/com/vayunmathur/everysync/core/network/OkHttpRelayClient.kt
diff --git a/library/everysync-core/src/androidMain/kotlin/com/vayunmathur/everysync/core/network/OkHttpRelayClient.kt b/library/everysync-core/src/androidMain/kotlin/com/vayunmathur/everysync/core/network/OkHttpRelayClient.ktnew file mode 100644index 0000000000..3352c9a40b--- /dev/null+++ b/library/everysync-core/src/androidMain/kotlin/com/vayunmathur/everysync/core/network/OkHttpRelayClient.kt@@ -0,0 +1,139 @@+package com.vayunmathur.everysync.core.network++import com.vayunmathur.everysync.core.platform.SecureStore+import kotlinx.coroutines.channels.awaitClose+import kotlinx.coroutines.flow.Flow+import kotlinx.coroutines.flow.callbackFlow+import okhttp3.MediaType.Companion.toMediaType+import okhttp3.OkHttpClient+import okhttp3.Request+import okhttp3.RequestBody.Companion.toRequestBody+import okhttp3.WebSocket+import okhttp3.WebSocketListener+import okio.ByteString+import java.io.ByteArrayInputStream+import java.security.KeyStore+import java.security.cert.CertificateFactory+import java.security.cert.X509Certificate+import javax.net.ssl.SSLContext+import javax.net.ssl.TrustManagerFactory+import javax.net.ssl.X509TrustManager++/**+ * `RelayHttpClient` over OkHttp3 with FIRST_PARTY pinning (ISRG X1/X2 ++ * GTS R1-R4 for `findfamily.cc`).+ *+ * TWIN: `jvmMain/.../OkHttpRelayClient.kt` is the same file for desktop JVM+ * (classloader resources + OkHttp are identical on both). Keep them in sync;+ * the only intended difference is the factory + SecureStore wiring below.+ */+class OkHttpRelayClient private constructor(+    private val client: OkHttpClient,+) : RelayHttpClient {++    override suspend fun post(url: String, jsonBody: String): RelayHttpResponse {+        val request = Request.Builder()+            .url(url)+            .post(jsonBody.toRequestBody(JSON_MEDIA_TYPE))+            .header("Content-Type", "application/json")+            .build()+        client.newCall(request).execute().use { response ->+            return RelayHttpResponse(response.code, response.body?.string().orEmpty())+        }+    }++    override fun subscribe(wsUrl: String, channel: String): Flow<String> = callbackFlow {+        val request = Request.Builder().url(wsUrl).build()+        val socket = client.newWebSocket(request, object : WebSocketListener() {+            override fun onOpen(webSocket: WebSocket, response: okhttp3.Response) {+                webSocket.send("""{"t":"sub","channel":"$channel"}""")+            }++            override fun onMessage(webSocket: WebSocket, text: String) {+                trySend(text)+            }++            override fun onMessage(webSocket: WebSocket, bytes: ByteString) {+                trySend(bytes.utf8())+            }++            override fun onFailure(webSocket: WebSocket, t: Throwable, response: okhttp3.Response?) {+                close(t)+            }+        })+        awaitClose { socket.close(1000, null) }+    }++    companion object {+        private val JSON_MEDIA_TYPE = "application/json".toMediaType()++        /** Builds a pinned client: FIRST_PARTY DERs from classloader resources + system issuers. */+        fun pinned(): OkHttpRelayClient {+            val pins = FirstPartyPins.fileNames.mapNotNull { name ->+                loadResource("ca/$name")+            }+            val trustManager = FirstPartyPins.trustManager(pins)+            val sslContext = SSLContext.getInstance("TLS").apply {+                init(null, arrayOf(trustManager), null)+            }+            val client = OkHttpClient.Builder()+                .sslSocketFactory(sslContext.socketFactory, trustManager)+                .build()+            return OkHttpRelayClient(client)+        }++        private fun loadResource(path: String): ByteArray? =+            runCatching {+                OkHttpRelayClient::class.java.classLoader?.getResourceAsStream(path)?.use { it.readBytes() }+            }.getOrNull()+    }+}++/**+ * FIRST_PARTY pinning roots (ISRG X1/X2 + GTS R1-R4) for `findfamily.cc`,+ * copied by `syncCaResources` into `src/commonMain/resources/ca/`.+ */+object FirstPartyPins {+    val fileNames = listOf(+        "isrgrootx1.der",+        "isrgrootx2.der",+        "gts-root-r1.der",+        "gts-root-r2.der",+        "gts-root-r3.der",+        "gts-root-r4.der",+    )++    /**+     * Builds a trust manager over the pinned roots plus system issuers+     * (rotation headroom — a freshly rotated relay cert chains to a public+     * root while pins catch up). When [pinnedDer] is empty (resources missing+     * from the AAR), falls back to system trust rather than failing closed+     * at the TLS layer — the relay is untrusted anyway; E2EE does not depend+     * on TLS.+     */+    fun trustManager(pinnedDer: List<ByteArray>): X509TrustManager {+        val cf = CertificateFactory.getInstance("X.509")+        val ks = KeyStore.getInstance(KeyStore.getDefaultType()).apply { load(null, null) }+        pinnedDer.forEachIndexed { idx, der ->+            val cert = cf.generateCertificate(ByteArrayInputStream(der)) as X509Certificate+            ks.setCertificateEntry("pin-$idx", cert)+        }+        TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm())+            .apply { init(null as KeyStore?) }+            .trustManagers.filterIsInstance<X509TrustManager>()+            .flatMap { it.acceptedIssuers.toList() }+            .forEachIndexed { idx, cert -> ks.setCertificateEntry("system-$idx", cert) }+        val tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm())+            .apply { init(ks) }+        return tmf.trustManagers.first { it is X509TrustManager } as X509TrustManager+    }+}++/** Android entry point: pinned transport over the caller's store + crypto. */+class AndroidRelayTransport(+    store: SecureStore,+    crypto: PqcCrypto,+    private val http: RelayHttpClient = OkHttpRelayClient.pinned(),+) : SharedRelayTransport(store, crypto) {+    override fun client(): RelayHttpClient = http+}
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.ktindex 2ce951b834..79029640f4 100644--- 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.kt@@ -7,7 +7,6 @@ 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@@ -157,16 +156,16 @@ object ICalendar {     private fun pad4(n: Int): String = n.toString().padStart(4, '0')      private fun utc(millis: Long): String {-        val dt = kotlinx.time.Instant.fromEpochMilliseconds(millis)+        val dt = kotlinx.datetime.Instant.fromEpochMilliseconds(millis)             .toLocalDateTime(TimeZone.UTC)-        return "${pad4(dt.year)}${pad2(dt.month.number)}${pad2(dt.day)}T" ++        return "${pad4(dt.year)}${pad2(dt.month.ordinal + 1)}${pad2(dt.dayOfMonth)}T" +             "${pad2(dt.hour)}${pad2(dt.minute)}${pad2(dt.second)}Z"     }      private fun dateOnly(millis: Long): String {-        val d = kotlinx.time.Instant.fromEpochMilliseconds(millis)+        val d = kotlinx.datetime.Instant.fromEpochMilliseconds(millis)             .toLocalDateTime(TimeZone.UTC).date-        return "${pad4(d.year)}${pad2(d.month.number)}${pad2(d.day)}"+        return "${pad4(d.year)}${pad2(d.month.ordinal + 1)}${pad2(d.dayOfMonth)}"     }      private fun unfold(text: String): List<String> {
library/everysync-core/src/commonMain/kotlin/com/vayunmathur/everysync/core/network/SharedRelayTransport.kt
diff --git a/library/everysync-core/src/commonMain/kotlin/com/vayunmathur/everysync/core/network/SharedRelayTransport.kt b/library/everysync-core/src/commonMain/kotlin/com/vayunmathur/everysync/core/network/SharedRelayTransport.ktnew file mode 100644index 0000000000..8996425b4d--- /dev/null+++ b/library/everysync-core/src/commonMain/kotlin/com/vayunmathur/everysync/core/network/SharedRelayTransport.kt@@ -0,0 +1,222 @@+package com.vayunmathur.everysync.core.network++import com.vayunmathur.everysync.core.crypto.AesGcm+import com.vayunmathur.everysync.core.crypto.PlatformRandom+import com.vayunmathur.everysync.core.platform.SecureStore+import kotlinx.coroutines.flow.Flow+import kotlinx.coroutines.flow.flow+import kotlinx.serialization.Serializable+import kotlinx.serialization.json.Json+import kotlin.io.encoding.Base64++private val ktorJson = Json { ignoreUnknownKeys = true }++/**+ * `RelayTransport` over OkHttp: POST JSON to `/register|/getkey|/append|/pull`+ * plus a WebSocket fan-in for [subscribe]. Platform actuals supply the+ * pinned `RelayHttpClient` ([OkHttpRelayClient.pinned] on Android/JVM,+ * Darwin/sec-trust on iOS in Phase 3); envelope codec, channel names, and the+ * null-on-failure invariant live here in common.+ *+ * Loss-prevention invariant: [pullRaw] returns null on ANY transport failure+ * (exception, non-200, unparseable body) — never an empty list.+ */+abstract class SharedRelayTransport(+    private val store: SecureStore,+    private val crypto: PqcCrypto,+) : RelayTransport {++    /** Pinned HTTP client, supplied per target (OkHttp on Android/JVM, Darwin on Apple). */+    protected abstract fun client(): RelayHttpClient++    /** This transport's stable device id, loaded or created in [init]. */+    private var selfDeviceId: String = ""+    override val deviceId: String get() = selfDeviceId++    private lateinit var identity: PqcIdentityHandle+    override val publicBundle: ByteArray get() = identity.publicBundle++    /**+     * Idempotent: loads/creates this device's PQC identity + stable id and+     * registers its public bundle. Must be called before any other op.+     */+    suspend fun init(): Boolean {+        identity = PqcIdentityHandle.loadOrCreate(store, crypto, "personal")+        var id = store.getString("personalDeviceId")+        if (id == null) {+            id = newUuidString()+            store.setString("personalDeviceId", id, onlyIfAbsent = true)+            id = store.getString("personalDeviceId") ?: id+        }+        selfDeviceId = id+        return register()+    }++    override suspend fun register(): Boolean {+        val body = ktorJson.encodeToString(RegisterReq(deviceId, Base64.encode(publicBundle)))+        return post("/register", body)+    }++    override suspend fun getKey(id: String): ByteArray? {+        val body = ktorJson.encodeToString(IdReq(id))+        val raw = raw("/getkey", body) ?: return null+        if (raw.status != 200) return null+        return runCatching { Base64.decode(raw.body) }.getOrNull()+    }++    override suspend fun appendRaw(channel: String, items: List<String>): Int? {+        val body = ktorJson.encodeToString(AppendReq(channel, items))+        val raw = raw("/append", body) ?: return null+        if (raw.status != 200) return null+        return runCatching { ktorJson.decodeFromString<SeqResp>(raw.body).seq }.getOrNull()+    }++    override suspend fun pullRaw(channel: String, since: Int): List<String>? {+        val body = ktorJson.encodeToString(PullReq(channel, since))+        val raw = raw("/pull", body) ?: return null+        if (raw.status != 200) return null+        return runCatching { ktorJson.decodeFromString<PullResp>(raw.body).actions }.getOrNull()+    }++    override fun subscribe(channel: String): Flow<String> = flow {+        client().subscribe(RELAY_WS_URL, channel).collect { emit(it) }+    }++    override suspend fun sign(data: ByteArray): ByteArray = identity.sign(data)+    override suspend fun verify(publicBundle: ByteArray, data: ByteArray, signature: ByteArray): Boolean =+        crypto.verify(publicBundle, data, signature)+    override suspend fun seal(bundle: ByteArray, data: ByteArray): ByteArray = crypto.seal(bundle, data)+    override suspend fun unseal(data: ByteArray): ByteArray = identity.decrypt(data)+    override fun newVaultKey(): ByteArray = AesGcm.newContentKey()+    override fun newVaultId(): String = newUuidString()++    private suspend fun post(path: String, body: String): Boolean {+        val raw = raw(path, body) ?: return false+        return raw.status in 200..299+    }++    private suspend fun raw(path: String, body: String): RelayHttpResponse? =+        runCatching { client().post(RELAY_BASE_URL + path, body) }.getOrNull()++    @Serializable private data class RegisterReq(val id: String, val key: String)+    @Serializable private data class IdReq(val id: String)+    @Serializable private data class AppendReq(val channel: String, val actions: List<String>)+    @Serializable private data class PullReq(val channel: String, val since: Int)+    @Serializable private data class SeqResp(val seq: Int = 0)+    @Serializable private data class PullResp(val actions: List<String> = emptyList(), val seq: Int = 0)+}++/** Minimal HTTP surface the OkHttp/Darwin actuals implement (keeps engines out of common). */+interface RelayHttpClient {+    suspend fun post(url: String, jsonBody: String): RelayHttpResponse+    fun subscribe(wsUrl: String, channel: String): Flow<String>+}++data class RelayHttpResponse(val status: Int, val body: String)++/**+ * PQC primitives. Production actuals delegate to the shared Rust crate+ * (`lib.rs` via JNI/JNA/cinterop); tests use [FakePqcCrypto].+ */+interface PqcCrypto {+    fun generateKem(): Pair<ByteArray, ByteArray>+    fun generateDsa(): Pair<ByteArray, ByteArray>+    fun bundle(kemPub: ByteArray, dsaPub: ByteArray): ByteArray+    fun splitBundle(bundle: ByteArray): Pair<ByteArray, ByteArray>?+    fun seal(bundle: ByteArray, data: ByteArray): ByteArray+    fun decrypt(kemPrivate: ByteArray, data: ByteArray): ByteArray+    fun sign(dsaPrivate: ByteArray, data: ByteArray): ByteArray+    fun verify(publicBundle: ByteArray, data: ByteArray, signature: ByteArray): Boolean+}++/** Device PQC identity: ML-KEM pair (decrypt) + ML-DSA pair (sign). */+class PqcIdentityHandle(+    val publicBundle: ByteArray,+    private val kemPrivate: ByteArray,+    private val dsaPrivate: ByteArray,+    private val crypto: PqcCrypto,+) {+    fun decrypt(ciphertext: ByteArray): ByteArray = crypto.decrypt(kemPrivate, ciphertext)+    fun sign(data: ByteArray): ByteArray = crypto.sign(dsaPrivate, data)++    companion object {+        suspend fun loadOrCreate(store: SecureStore, crypto: PqcCrypto, prefix: String): PqcIdentityHandle {+            readPersisted(store, crypto, prefix)?.let { return it }+            val (kemPub, kemPriv) = crypto.generateKem()+            val (dsaPub, dsaPriv) = crypto.generateDsa()+            store.setBytes("${prefix}KemPub", kemPub, onlyIfAbsent = true)+            store.setBytes("${prefix}KemPriv", kemPriv, onlyIfAbsent = true)+            store.setBytes("${prefix}DsaPub", dsaPub, onlyIfAbsent = true)+            store.setBytes("${prefix}DsaPriv", dsaPriv, onlyIfAbsent = true)+            // Re-read final persisted (winner of concurrent race).+            return readPersisted(store, crypto, prefix)+                ?: error("PQC identity store returned no keys")+        }++        private suspend fun readPersisted(+            store: SecureStore,+            crypto: PqcCrypto,+            prefix: String,+        ): PqcIdentityHandle? {+            val kemPub = store.getBytes("${prefix}KemPub") ?: return null+            val kemPriv = store.getBytes("${prefix}KemPriv") ?: return null+            val dsaPub = store.getBytes("${prefix}DsaPub") ?: return null+            val dsaPriv = store.getBytes("${prefix}DsaPriv") ?: return null+            return PqcIdentityHandle(crypto.bundle(kemPub, dsaPub), kemPriv, dsaPriv, crypto)+        }+    }+}++/** Test-only PQC: XOR "seal" + prefixed "signatures". NEVER production crypto. */+class FakePqcCrypto : PqcCrypto {+    override fun generateKem(): Pair<ByteArray, ByteArray> {+        val pub = ("kem-pub-" + randomSuffix()).encodeToByteArray()+        val priv = ("kem-priv-" + randomSuffix()).encodeToByteArray()+        return pub to priv+    }++    override fun generateDsa(): Pair<ByteArray, ByteArray> {+        val pub = ("dsa-pub-" + randomSuffix()).encodeToByteArray()+        val priv = ("dsa-priv-" + randomSuffix()).encodeToByteArray()+        return pub to priv+    }++    override fun bundle(kemPub: ByteArray, dsaPub: ByteArray): ByteArray =+        ("bundle|${Base64.encode(kemPub)}|${Base64.encode(dsaPub)}").encodeToByteArray()++    override fun splitBundle(bundle: ByteArray): Pair<ByteArray, ByteArray>? {+        val parts = bundle.decodeToString().split("|")+        if (parts.size != 3 || parts[0] != "bundle") return null+        return Base64.decode(parts[1]) to Base64.decode(parts[2])+    }++    override fun seal(bundle: ByteArray, data: ByteArray): ByteArray =+        (Base64.encode(bundle) + "." + Base64.encode(data)).encodeToByteArray()++    override fun decrypt(kemPrivate: ByteArray, data: ByteArray): ByteArray {+        // Fake seal embeds the bundle, not the private key — recover by lookup+        // is impossible, so tests seal/unseal through the same instance only+        // for shape (see RelayConformanceTest envelope assertions).+        val s = data.decodeToString()+        val payload = s.substringAfter(".", missingDelimiterValue = "")+        return if (payload.isEmpty()) data else Base64.decode(payload)+    }++    override fun sign(dsaPrivate: ByteArray, data: ByteArray): ByteArray =+        ("sig:${Base64.encode(dsaPrivate)}:${Base64.encode(data)}").encodeToByteArray()++    override fun verify(publicBundle: ByteArray, data: ByteArray, signature: ByteArray): Boolean =+        signature.decodeToString().endsWith(":${Base64.encode(data)}")++    private fun randomSuffix(): String =+        PlatformRandom.nextBytes(6).joinToString("") { it.toInt().and(0xff).toString(16).padStart(2, '0') }+}++/** Random UUID string without `java.util.UUID` (common-safe, matches `Uuid.random()` shape). */+fun newUuidString(): String {+    val b = PlatformRandom.nextBytes(16)+    b[6] = ((b[6].toInt() and 0x0f) or 0x40).toByte()+    b[8] = ((b[8].toInt() and 0x3f) or 0x80).toByte()+    val h = b.joinToString("") { it.toInt().and(0xff).toString(16).padStart(2, '0') }+    return "${h.take(8)}-${h.substring(8, 12)}-${h.substring(12, 16)}-${h.substring(16, 20)}-${h.substring(20)}"+}
library/everysync-core/src/commonMain/kotlin/com/vayunmathur/everysync/core/platform/SecureStores.kt
diff --git a/library/everysync-core/src/commonMain/kotlin/com/vayunmathur/everysync/core/platform/SecureStores.kt b/library/everysync-core/src/commonMain/kotlin/com/vayunmathur/everysync/core/platform/SecureStores.ktnew file mode 100644index 0000000000..710fe1b2b8--- /dev/null+++ b/library/everysync-core/src/commonMain/kotlin/com/vayunmathur/everysync/core/platform/SecureStores.kt@@ -0,0 +1,76 @@+package com.vayunmathur.everysync.core.platform++import kotlinx.coroutines.sync.Mutex+import kotlinx.coroutines.sync.withLock++/**+ * In-memory [SecureStore] for tests and for drivers that manage their own+ * persistence. `onlyIfAbsent` is honored atomically.+ */+class MemorySecureStore : SecureStore {+    private val bytes = mutableMapOf<String, ByteArray>()+    private val strings = mutableMapOf<String, String>()+    private val longs = mutableMapOf<String, Long>()+    private val mutex = Mutex()++    override suspend fun getBytes(name: String): ByteArray? = mutex.withLock { bytes[name] }++    override suspend fun setBytes(name: String, value: ByteArray, onlyIfAbsent: Boolean) {+        mutex.withLock {+            if (!onlyIfAbsent || name !in bytes) bytes[name] = value+        }+    }++    override suspend fun delete(name: String) {+        mutex.withLock {+            bytes.remove(name)+            strings.remove(name)+            longs.remove(name)+        }+    }++    override suspend fun getString(name: String): String? = mutex.withLock { strings[name] }++    override suspend fun setString(name: String, value: String, onlyIfAbsent: Boolean) {+        mutex.withLock {+            if (!onlyIfAbsent || name !in strings) strings[name] = value+        }+    }++    override suspend fun getLong(name: String): Long? = mutex.withLock { longs[name] }++    override suspend fun setLong(name: String, value: Long) {+        mutex.withLock { longs[name] = value }+    }+}++/**+ * Cursor + baseline persistence over any [SecureStore]. Key layouts mirror+ * the Android stores (`relay_cursor:<type>:<vault>:<channel>`,+ * `relay_baseline:<vault>:<kind>`), so a future Android migration to the+ * shared core can adopt existing DataStore values verbatim.+ */+class RelayCursorStore(private val store: SecureStore) {+    private fun key(dataType: String, vaultId: String, channel: String): String =+        "relay_cursor:$dataType:$vaultId:$channel"++    suspend fun get(dataType: String, vaultId: String, channel: String): Int =+        store.getLong(key(dataType, vaultId, channel))?.toInt() ?: 0++    suspend fun set(dataType: String, vaultId: String, channel: String, seq: Int) {+        store.setLong(key(dataType, vaultId, channel), seq.toLong())+    }++    /** Advances the cursor only forward; returns true when it moved. */+    suspend fun advance(dataType: String, vaultId: String, channel: String, seq: Int): Boolean {+        val k = key(dataType, vaultId, channel)+        val cur = store.getLong(k)?.toInt() ?: 0+        if (seq <= cur) return false+        store.setLong(k, seq.toLong())+        return true+    }++    suspend fun clearVault(dataType: String, vaultId: String, channels: List<String>) {+        for (c in channels) store.delete(key(dataType, vaultId, c))+    }+}
library/everysync-core/src/commonTest/kotlin/com/vayunmathur/everysync/core/network/RelayConformanceTest.kt
diff --git a/library/everysync-core/src/commonTest/kotlin/com/vayunmathur/everysync/core/network/RelayConformanceTest.kt b/library/everysync-core/src/commonTest/kotlin/com/vayunmathur/everysync/core/network/RelayConformanceTest.ktindex 7666ba18ca..aad9639684 100644--- a/library/everysync-core/src/commonTest/kotlin/com/vayunmathur/everysync/core/network/RelayConformanceTest.kt+++ b/library/everysync-core/src/commonTest/kotlin/com/vayunmathur/everysync/core/network/RelayConformanceTest.kt@@ -1,6 +1,8 @@ package com.vayunmathur.everysync.core.network  import com.vayunmathur.everysync.core.crypto.AesGcm+import com.vayunmathur.everysync.core.platform.MemorySecureStore+import com.vayunmathur.everysync.core.platform.RelayCursorStore import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.emptyFlow import kotlinx.coroutines.flow.flowOf
library/everysync-core/src/commonTest/kotlin/com/vayunmathur/everysync/core/network/SharedTransportTest.kt
diff --git a/library/everysync-core/src/commonTest/kotlin/com/vayunmathur/everysync/core/network/SharedTransportTest.kt b/library/everysync-core/src/commonTest/kotlin/com/vayunmathur/everysync/core/network/SharedTransportTest.ktnew file mode 100644index 0000000000..22266dba4a--- /dev/null+++ b/library/everysync-core/src/commonTest/kotlin/com/vayunmathur/everysync/core/network/SharedTransportTest.kt@@ -0,0 +1,120 @@+package com.vayunmathur.everysync.core.network++import com.vayunmathur.everysync.core.platform.MemorySecureStore+import com.vayunmathur.everysync.core.platform.RelayCursorStore+import kotlinx.coroutines.flow.Flow+import kotlinx.coroutines.flow.emptyFlow+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNotEquals+import kotlin.test.assertNotNull+import kotlin.test.assertTrue++/**+ * Identity + init coverage for [SharedRelayTransport]: stable device id,+ * load-or-create PQC identity (race-safe re-read), register-on-init, and+ * device-scoped channels. Runs against the fake HTTP client (no network).+ */+class SharedTransportTest {++    private class FakeHttp(val log: MutableMap<String, MutableList<String>> = mutableMapOf()) : RelayHttpClient {+        val posts = mutableListOf<Pair<String, String>>()+        var status = 200++        override suspend fun post(url: String, jsonBody: String): RelayHttpResponse {+            posts.add(url to jsonBody)+            return RelayHttpResponse(status, """{"seq":${log.size},"actions":[]}""")+        }++        override fun subscribe(wsUrl: String, channel: String): Flow<String> = emptyFlow()+    }++    private class TestTransport(+        store: MemorySecureStore = MemorySecureStore(),+        crypto: PqcCrypto = FakePqcCrypto(),+        val http: FakeHttp = FakeHttp(),+    ) : SharedRelayTransport(store, crypto) {+        val backingStore = store+        override fun client(): RelayHttpClient = http+    }++    @Test+    fun initRegistersAndAssignsStableId() = kotlinx.coroutines.runBlocking {+        val store = MemorySecureStore()+        val t = TestTransport(store)+        assertTrue(t.init())+        val firstId = t.deviceId+        assertTrue(firstId.isNotBlank())+        // Registered to /register with our id.+        assertTrue(t.http.posts.any { (url, _) -> url.endsWith("/register") })++        // Second transport on the same store reuses the id + identity.+        val t2 = TestTransport(store)+        assertTrue(t2.init())+        assertEquals(firstId, t2.deviceId)+    }++    @Test+    fun identitySurvivesReload() = kotlinx.coroutines.runBlocking {+        val store = MemorySecureStore()+        val t = TestTransport(store)+        t.init()+        val bundle = t.publicBundle.copyOf()+        assertTrue(bundle.isNotEmpty())++        val t2 = TestTransport(store)+        t2.init()+        assertTrue(bundle.contentEquals(t2.publicBundle))+    }++    @Test+    fun vaultIdsAreUnique() = kotlinx.coroutines.runBlocking {+        val t = TestTransport()+        t.init()+        val ids = (1..50).map { t.newVaultId() }.toSet()+        assertEquals(50, ids.size)+        // UUID v4 shape.+        assertTrue(ids.all { it.length == 36 && it[14] == '4' })+    }++    @Test+    fun vaultKeysAreUnique256Bit() = kotlinx.coroutines.runBlocking {+        val t = TestTransport()+        t.init()+        val k1 = t.newVaultKey()+        val k2 = t.newVaultKey()+        assertEquals(32, k1.size)+        assertEquals(32, k2.size)+        assertNotEquals(k1.toList(), k2.toList())+    }++    @Test+    fun inboxChannelIsDeviceScoped() {+        assertEquals("inbox:aaa", inboxChannel("aaa"))+        assertNotEquals(inboxChannel("aaa"), inboxChannel("bbb"))+    }++    @Test+    fun cursorStoreAdvancesForwardOnly() = kotlinx.coroutines.runBlocking {+        val cursors = RelayCursorStore(MemorySecureStore())+        assertEquals(0, cursors.get("notes", "v1", "notes:v1"))+        assertTrue(cursors.advance("notes", "v1", "notes:v1", 7))+        assertEquals(7, cursors.get("notes", "v1", "notes:v1"))+        // Stale or equal seq never moves the cursor.+        assertTrue(!cursors.advance("notes", "v1", "notes:v1", 7))+        assertTrue(!cursors.advance("notes", "v1", "notes:v1", 3))+        assertEquals(7, cursors.get("notes", "v1", "notes:v1"))+    }++    @Test+    fun memoryStoreHonorsOnlyIfAbsent() = kotlinx.coroutines.runBlocking {+        val store = MemorySecureStore()+        store.setBytes("k", "a".encodeToByteArray(), onlyIfAbsent = true)+        store.setBytes("k", "b".encodeToByteArray(), onlyIfAbsent = true)+        assertEquals("a", store.getBytes("k")!!.decodeToString())+        store.setBytes("k", "b".encodeToByteArray())+        assertEquals("b", store.getBytes("k")!!.decodeToString())+        store.delete("k")+        assertEquals(null, store.getBytes("k"))+    }+}
library/everysync-core/src/iosMain/kotlin/com/vayunmathur/everysync/core/network/IosRelayTransport.kt
diff --git a/library/everysync-core/src/iosMain/kotlin/com/vayunmathur/everysync/core/network/IosRelayTransport.kt b/library/everysync-core/src/iosMain/kotlin/com/vayunmathur/everysync/core/network/IosRelayTransport.ktnew file mode 100644index 0000000000..31a40b2c3c--- /dev/null+++ b/library/everysync-core/src/iosMain/kotlin/com/vayunmathur/everysync/core/network/IosRelayTransport.kt@@ -0,0 +1,36 @@+package com.vayunmathur.everysync.core.network++import com.vayunmathur.everysync.core.platform.SecureStore+import kotlinx.coroutines.flow.Flow+import kotlinx.coroutines.flow.emptyFlow++/**+ * iOS `RelayTransport`: Ktor-Darwin engine + sec-trust pinning land with the+ * Phase 3 Apple shell (which also wires the XCFramework + cinterop Rust+ * bindings). Until then this stub keeps the iosMain source set honest about+ * the interface without pretending to ship networking.+ */+class IosRelayTransport(+    private val store: SecureStore,+    private val crypto: PqcCrypto,+) : RelayTransport {+    override val deviceId: String get() = throw UnsupportedOperationException("iOS transport lands in Phase 3")+    override val publicBundle: ByteArray get() = throw UnsupportedOperationException("iOS transport lands in Phase 3")+    override suspend fun register(): Boolean = throw UnsupportedOperationException("iOS transport lands in Phase 3")+    override suspend fun getKey(id: String): ByteArray? = throw UnsupportedOperationException("iOS transport lands in Phase 3")+    override suspend fun appendRaw(channel: String, items: List<String>): Int? =+        throw UnsupportedOperationException("iOS transport lands in Phase 3")+    override suspend fun pullRaw(channel: String, since: Int): List<String>? =+        throw UnsupportedOperationException("iOS transport lands in Phase 3")+    override fun subscribe(channel: String): Flow<String> = emptyFlow()+    override suspend fun sign(data: ByteArray): ByteArray =+        throw UnsupportedOperationException("iOS transport lands in Phase 3")+    override suspend fun verify(publicBundle: ByteArray, data: ByteArray, signature: ByteArray): Boolean =+        throw UnsupportedOperationException("iOS transport lands in Phase 3")+    override suspend fun seal(bundle: ByteArray, data: ByteArray): ByteArray =+        throw UnsupportedOperationException("iOS transport lands in Phase 3")+    override suspend fun unseal(data: ByteArray): ByteArray =+        throw UnsupportedOperationException("iOS transport lands in Phase 3")+    override fun newVaultKey(): ByteArray = throw UnsupportedOperationException("iOS transport lands in Phase 3")+    override fun newVaultId(): String = throw UnsupportedOperationException("iOS transport lands in Phase 3")+}
library/everysync-core/src/jvmMain/kotlin/com/vayunmathur/everysync/core/network/OkHttpRelayClient.kt
diff --git a/library/everysync-core/src/jvmMain/kotlin/com/vayunmathur/everysync/core/network/OkHttpRelayClient.kt b/library/everysync-core/src/jvmMain/kotlin/com/vayunmathur/everysync/core/network/OkHttpRelayClient.ktnew file mode 100644index 0000000000..27af5be26a--- /dev/null+++ b/library/everysync-core/src/jvmMain/kotlin/com/vayunmathur/everysync/core/network/OkHttpRelayClient.kt@@ -0,0 +1,139 @@+package com.vayunmathur.everysync.core.network++import com.vayunmathur.everysync.core.platform.SecureStore+import kotlinx.coroutines.channels.awaitClose+import kotlinx.coroutines.flow.Flow+import kotlinx.coroutines.flow.callbackFlow+import okhttp3.MediaType.Companion.toMediaType+import okhttp3.OkHttpClient+import okhttp3.Request+import okhttp3.RequestBody.Companion.toRequestBody+import okhttp3.WebSocket+import okhttp3.WebSocketListener+import okio.ByteString+import java.io.ByteArrayInputStream+import java.security.KeyStore+import java.security.cert.CertificateFactory+import java.security.cert.X509Certificate+import javax.net.ssl.SSLContext+import javax.net.ssl.TrustManagerFactory+import javax.net.ssl.X509TrustManager++/**+ * `RelayHttpClient` over OkHttp3 with FIRST_PARTY pinning (ISRG X1/X2 ++ * GTS R1-R4 for `findfamily.cc`).+ *+ * TWIN: `androidMain/.../OkHttpRelayClient.kt` is the same file for Android+ * (classloader resources + OkHttp are identical on both). Keep them in sync;+ * the only intended difference is the factory + SecureStore wiring below.+ */+class OkHttpRelayClient private constructor(+    private val client: OkHttpClient,+) : RelayHttpClient {++    override suspend fun post(url: String, jsonBody: String): RelayHttpResponse {+        val request = Request.Builder()+            .url(url)+            .post(jsonBody.toRequestBody(JSON_MEDIA_TYPE))+            .header("Content-Type", "application/json")+            .build()+        client.newCall(request).execute().use { response ->+            return RelayHttpResponse(response.code, response.body?.string().orEmpty())+        }+    }++    override fun subscribe(wsUrl: String, channel: String): Flow<String> = callbackFlow {+        val request = Request.Builder().url(wsUrl).build()+        val socket = client.newWebSocket(request, object : WebSocketListener() {+            override fun onOpen(webSocket: WebSocket, response: okhttp3.Response) {+                webSocket.send("""{"t":"sub","channel":"$channel"}""")+            }++            override fun onMessage(webSocket: WebSocket, text: String) {+                trySend(text)+            }++            override fun onMessage(webSocket: WebSocket, bytes: ByteString) {+                trySend(bytes.utf8())+            }++            override fun onFailure(webSocket: WebSocket, t: Throwable, response: okhttp3.Response?) {+                close(t)+            }+        })+        awaitClose { socket.close(1000, null) }+    }++    companion object {+        private val JSON_MEDIA_TYPE = "application/json".toMediaType()++        /** Builds a pinned client: FIRST_PARTY DERs from classloader resources + system issuers. */+        fun pinned(): OkHttpRelayClient {+            val pins = FirstPartyPins.fileNames.mapNotNull { name ->+                loadResource("ca/$name")+            }+            val trustManager = FirstPartyPins.trustManager(pins)+            val sslContext = SSLContext.getInstance("TLS").apply {+                init(null, arrayOf(trustManager), null)+            }+            val client = OkHttpClient.Builder()+                .sslSocketFactory(sslContext.socketFactory, trustManager)+                .build()+            return OkHttpRelayClient(client)+        }++        private fun loadResource(path: String): ByteArray? =+            runCatching {+                OkHttpRelayClient::class.java.classLoader?.getResourceAsStream(path)?.use { it.readBytes() }+            }.getOrNull()+    }+}++/**+ * FIRST_PARTY pinning roots (ISRG X1/X2 + GTS R1-R4) for `findfamily.cc`,+ * copied by `syncCaResources` into `src/commonMain/resources/ca/`.+ */+object FirstPartyPins {+    val fileNames = listOf(+        "isrgrootx1.der",+        "isrgrootx2.der",+        "gts-root-r1.der",+        "gts-root-r2.der",+        "gts-root-r3.der",+        "gts-root-r4.der",+    )++    /**+     * Builds a trust manager over the pinned roots plus system issuers+     * (rotation headroom — a freshly rotated relay cert chains to a public+     * root while pins catch up). When [pinnedDer] is empty (resources missing+     * from the jar), falls back to system trust rather than failing closed+     * at the TLS layer — the relay is untrusted anyway; E2EE does not depend+     * on TLS.+     */+    fun trustManager(pinnedDer: List<ByteArray>): X509TrustManager {+        val cf = CertificateFactory.getInstance("X.509")+        val ks = KeyStore.getInstance(KeyStore.getDefaultType()).apply { load(null, null) }+        pinnedDer.forEachIndexed { idx, der ->+            val cert = cf.generateCertificate(ByteArrayInputStream(der)) as X509Certificate+            ks.setCertificateEntry("pin-$idx", cert)+        }+        TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm())+            .apply { init(null as KeyStore?) }+            .trustManagers.filterIsInstance<X509TrustManager>()+            .flatMap { it.acceptedIssuers.toList() }+            .forEachIndexed { idx, cert -> ks.setCertificateEntry("system-$idx", cert) }+        val tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm())+            .apply { init(ks) }+        return tmf.trustManagers.first { it is X509TrustManager } as X509TrustManager+    }+}++/** Desktop JVM entry point: pinned transport over the caller's store + crypto. */+class JvmRelayTransport(+    store: SecureStore,+    crypto: PqcCrypto,+    private val http: RelayHttpClient = OkHttpRelayClient.pinned(),+) : SharedRelayTransport(store, crypto) {+    override fun client(): RelayHttpClient = http+}