Open source Grok Bot alternative, Bring your own agent and subscription: message Claude Code, Codex, Gemini CLI, Cursor, Copilot and 40+ AI agents as bots on your own computer, from iPhone, Mac, Windows, Linux or terminal. Agent-agnostic and free. Also a Muse and Dots alternative. Built in Rust.
Rust acpagent-client-protocolai-agentsai-assistantclaudeclaude-codecodexcoding-agentscursorgeminigemini-cligrok-bot-alternativeiosiphonelinuxmacosmcpopen-sourcerustself-hosted
feat(android): prove the account when pairing and join unowned computers
leepokai68e1955fb8d7
diff --git a/apps/android/app/src/main/kotlin/com/codync/android/AccountStore.kt b/apps/android/app/src/main/kotlin/com/codync/android/AccountStore.ktindex 81764b69..db895357 100644--- a/apps/android/app/src/main/kotlin/com/codync/android/AccountStore.kt+++ b/apps/android/app/src/main/kotlin/com/codync/android/AccountStore.kt@@ -26,6 +26,8 @@ class AccountStore(application: Application) : AndroidViewModel(application) {/** One change to the saved computers at a time. */private val computerChanges = Mutex()internal var cloud: CloudClient? = null+ /** The account proof pairing sends, kept for this account context while it lasts. */+ internal var deviceCertificate: DeviceCertificate? = nullprivate var sessionJob: Job? = nullinternal var linkJob: Job? = nullinternal var pairingJob: Job? = null@@ -121,7 +123,7 @@ class AccountStore(application: Application) : AndroidViewModel(application) {contextJob.cancelAndJoin()AccountImages.retire()pairingJob = null- actions.clear(); cloud = null+ actions.clear(); cloud = null; deviceCertificate = nullwithContext(Dispatchers.IO) { ConnectorOAuthBook(local.directory).clear() }contextJob = SupervisorJob(viewModelScope.coroutineContext[Job])contextScope = CoroutineScope(contextJob + Dispatchers.Main.immediate)diff --git a/apps/android/app/src/main/kotlin/com/codync/android/AccountStoreLinks.kt b/apps/android/app/src/main/kotlin/com/codync/android/AccountStoreLinks.ktindex 34922b81..7195f7c2 100644--- a/apps/android/app/src/main/kotlin/com/codync/android/AccountStoreLinks.kt+++ b/apps/android/app/src/main/kotlin/com/codync/android/AccountStoreLinks.kt@@ -2,6 +2,7 @@ package com.codync.androidimport android.net.Uriimport android.os.Build+import java.io.IOExceptionimport androidx.lifecycle.viewModelScopeimport com.codync.android.core.*import kotlinx.coroutines.*@@ -21,22 +22,58 @@ internal fun AccountStore.pair(text: String, via: PairedVia) {val old = state.value.computers.firstOrNull { it.id == pairing.computer.id }require(old == null || old.signKey == pairing.computer.signKey) { "This computer's identity changed. Start over before pairing again." }val identity = withContext(Dispatchers.IO) { local.identity() }+ mutableState.update { it.copy(pairingCheck = pairing.checkCode(identity)) }+ val certificate = accountProof()+ val client = cloud+ // Without a claim a computer in no account still lets the phone in; it just doesn't join the account.+ val claim = client?.let { bestEffort("start a claim") { it.createClaim() } }+ val paired = HostConnector.pair(pairing, identity, Build.MODEL.take(100), certificate, claim)// Picked on this phone: pairing again keeps them (iOS `AccountStore.pair`).- val computer = HostConnector.pair(pairing, identity, Build.MODEL.take(100)).keepingDevicePicks(old)+ val computer = paired.computer.keepingDevicePicks(old)transitions.withLock { addComputer(computer) }withContext(Dispatchers.IO) { local.completeSetup() }mutableState.update { it.copy(setupComplete = true) }Analytics.capture(AnalyticsEvent.ComputerPaired(via, computer.id))Analytics.completeOnboarding(OnboardingVia.Paired)+ // The computer joined this account: the account takes it in (or it stays paired, outside the account).+ val signed = paired.claim+ if (client != null && claim != null && signed != null) {+ bestEffort("complete the claim") { client.completeClaim(claim.claimId, signed) }+ refreshCloud()+ }} catch (error: CancellationException) { throw error }catch (error: Exception) {Analytics.capture(AnalyticsEvent.PairingFailed(PairingFailure.of(error)))showError(error)}- finally { mutableState.update { it.copy(pairing = false) } }+ finally { mutableState.update { it.copy(pairing = false, pairingCheck = null) } }}}+/**+ * The certificate `pair` sends: the one kept for this account while more than a day is left, else a new one; with the+ * cloud out of reach, the kept one while it's valid at all. Pairing needs the account's word, so without one it fails.+ */+private suspend fun AccountStore.accountProof(): DeviceCertificate {+ val cached = deviceCertificate+ val fresh = try { cloud?.certificate(cached, Build.MODEL.take(100)) }+ catch (error: CancellationException) { throw error }+ catch (error: IOException) {+ if (error is CloudError && !error.isTransient) throw error+ android.util.Log.i("Codync", "Couldn't get a device certificate: ${error.message}")+ null+ }+ val proof = fresh ?: cached?.takeIf { it.expiresAt > System.currentTimeMillis() }+ ?: throw IOException("Connect to the internet to pair, so Codync can confirm your account.")+ deviceCertificate = proof+ return proof+}++/** [step] of joining the account, which pairing goes on without: a failure is only logged. */+private suspend fun <T> bestEffort(what: String, step: suspend () -> T): T? = try { step() }+ catch (error: CancellationException) { throw error }+ catch (error: Exception) { android.util.Log.i("Codync", "Couldn't $what: ${error.message}"); null }+/** The state once the signed-in (or local) account has loaded: where a link can be opened. */internal suspend fun AccountStore.activated(): AccountContext = state.first { current -> !current.loading &&(current.account.ready || !current.account.configured || current.account.error != null) &&diff --git a/apps/android/app/src/main/kotlin/com/codync/android/AppState.kt b/apps/android/app/src/main/kotlin/com/codync/android/AppState.ktindex a8ee5871..f69c11fe 100644--- a/apps/android/app/src/main/kotlin/com/codync/android/AppState.kt+++ b/apps/android/app/src/main/kotlin/com/codync/android/AppState.kt@@ -27,6 +27,8 @@ data class AccountContext(val setupComplete: Boolean = false,val loading: Boolean = true,val pairing: Boolean = false,+ /** While pairing, the code the computer shows if it asks whether to let this phone in. */+ val pairingCheck: String? = null,/** This phone's computers, in the order it shows them. */val computers: List<Computer> = emptyList(),/** The computer whose lead "Talk to Codync" calls; null is Automatic (iOS `shortcutLeadComputer`). */diff --git a/apps/android/app/src/main/kotlin/com/codync/android/ConnectionPresentation.kt b/apps/android/app/src/main/kotlin/com/codync/android/ConnectionPresentation.ktindex e6b98d2d..c4d9a945 100644--- a/apps/android/app/src/main/kotlin/com/codync/android/ConnectionPresentation.kt+++ b/apps/android/app/src/main/kotlin/com/codync/android/ConnectionPresentation.kt@@ -94,6 +94,9 @@ internal fun pairingLine(cloud: String?): String {internal fun pairingLine(pasted: String, scheme: String): String =pairingLine(runCatching { Pairing.parse(pasted, scheme).computer.cloud }.getOrNull())+/** What the pairing page shows while it pairs: the code a computer in no account shows when it asks, as `123 456`. */+internal fun pairingCheckLine(code: String): String = "If the computer asks, check it shows ${code.take(3)} ${code.drop(3)}."+/** A sentence to translate, and the counts that fill its `%d`s in order. */internal data class Phrase(val template: String, val counts: List<Int> = emptyList()) {/** [translated] (the template in the app's language) with the counts filled in. */diff --git a/apps/android/app/src/main/kotlin/com/codync/android/PairingView.kt b/apps/android/app/src/main/kotlin/com/codync/android/PairingView.ktindex 2e3bb316..e25fe073 100644--- a/apps/android/app/src/main/kotlin/com/codync/android/PairingView.kt+++ b/apps/android/app/src/main/kotlin/com/codync/android/PairingView.kt@@ -58,6 +58,7 @@ import androidx.compose.ui.text.TextStyleimport androidx.compose.ui.text.font.FontWeightimport androidx.compose.ui.text.input.ImeActionimport androidx.compose.ui.text.input.KeyboardCapitalization+import androidx.compose.ui.text.style.TextAlignimport androidx.compose.ui.unit.dpimport androidx.compose.ui.unit.spimport com.codync.android.design.*@@ -225,8 +226,13 @@ private enum class ComputerOS { Mac, Linux }Box(Modifier.fillMaxWidth().aspectRatio(1f).clip(RoundedRectangle(24.dp))) {key(attempt) { QrViewfinder({ pair(it) }, Modifier.fillMaxSize()) { message -> if (message != null) error = message } }val dim by animateFloatAsState(if (state.pairing) 1f else 0f, Motion.fade(), label = "Pairing")- if (dim > 0f) Box(Modifier.fillMaxSize().graphicsLayer { alpha = dim }.background(Palette.background.copy(alpha = 0.7f)),- contentAlignment = Alignment.Center) { Spinner(28.dp) }+ if (dim > 0f) Column(Modifier.fillMaxSize().graphicsLayer { alpha = dim }.background(Palette.background.copy(alpha = 0.7f))+ .padding(24.dp), Arrangement.spacedBy(16.dp, Alignment.CenterVertically), Alignment.CenterHorizontally) {+ Spinner(28.dp)+ // A computer in no account asks its user first: the same code on both says it's this phone.+ state.pairingCheck?.let { Text(tr(pairingCheckLine(it)), style = Type.callout.monospacedDigit, color = Palette.text,+ textAlign = TextAlign.Center) }+ }}Row(Modifier.fillMaxWidth().clip(RoundedRectangle(12.dp)).background(Palette.surface).padding(start = 14.dp, end = 4.dp, top = 4.dp, bottom = 4.dp),verticalAlignment = Alignment.CenterVertically) {diff --git a/apps/android/app/src/test/kotlin/com/codync/android/PairingCopyTest.kt b/apps/android/app/src/test/kotlin/com/codync/android/PairingCopyTest.ktindex e0948671..f28670a1 100644--- a/apps/android/app/src/test/kotlin/com/codync/android/PairingCopyTest.kt+++ b/apps/android/app/src/test/kotlin/com/codync/android/PairingCopyTest.kt@@ -1,5 +1,7 @@package com.codync.android+import com.codync.android.design.AppLanguage+import com.codync.android.design.translateimport java.net.URLEncoderimport org.junit.Assert.assertEqualsimport org.junit.Assert.assertTrue@@ -19,4 +21,11 @@ class PairingCopyTest {).entries.joinToString("&") { "${it.key}=${URLEncoder.encode(it.value, "UTF-8")}" }assertTrue(pairingLine(link, "codync").contains("Private relay (relay.example.com)"))}++ @Test fun `the pairing check reads as two groups of three and fills the shared phrase`() {+ val line = pairingCheckLine("855066")+ assertEquals("If the computer asks, check it shows 855 066.", line)+ val table = mapOf("If the computer asks, check it shows {code}." to "如果電腦問你,確認它顯示 {code}。")+ assertEquals("如果電腦問你,確認它顯示 855 066。", translate(line, AppLanguage.ZhHant, systemIsChinese = false, table))+ }}diff --git a/apps/android/core/src/main/kotlin/com/codync/android/core/CloudClient.kt b/apps/android/core/src/main/kotlin/com/codync/android/core/CloudClient.ktindex 18487667..3de8010d 100644--- a/apps/android/core/src/main/kotlin/com/codync/android/core/CloudClient.kt+++ b/apps/android/core/src/main/kotlin/com/codync/android/core/CloudClient.kt@@ -36,6 +36,16 @@ data class AccessStatus(val requestId: String, val status: String, val computerIval state: String get() = status.takeIf { it in setOf("pending", "approved", "denied", "expired", "cancelled") } ?: "expired"}+/** The cloud's word that this device key is in the account, which `pair` shows the computer (`{payload, sig}`). */+data class DeviceCertificate(val payload: String, val sig: String) {+ /** When it stops being valid (ms), from the signed payload. */+ val expiresAt: Long = Json.parseToJsonElement(payload).jsonObject.getValue("exp").jsonPrimitive.long+ internal val json: JsonObject get() = buildJsonObject { put("payload", payload); put("sig", sig) }+}++/** What a computer that joins this phone's account by pairing signs, so the account takes it in. */+data class PairingClaim(val claimId: String, val nonce: String)+class CloudError(val status: Int, val code: String, detail: String? = null) : IOException(when (code) {"requestExpired" -> "The request expired. Ask again.""accountDeleted" -> "This account was deleted."@@ -63,6 +73,32 @@ class CloudClient private constructor(base: String, private val identity: Devicesuspend fun registerDevice(name: String) { request("POST", listOf("v1", "devices"),buildJsonObject { put("name", name); put("platform", "android") }, signed = true) }+ suspend fun deviceCertificate(): DeviceCertificate {+ val certificate = request("POST", listOf("v1", "devices", "certificate"), buildJsonObject { }, signed = true)+ .getValue("certificate").jsonObject+ return DeviceCertificate(requireNotNull(certificate.text("payload")), requireNotNull(certificate.text("sig")))+ }++ /** [cached] while more than a day of it is left, else a new certificate; a key the cloud doesn't know is registered first. */+ suspend fun certificate(cached: DeviceCertificate?, deviceName: String): DeviceCertificate {+ if (cached != null && cached.expiresAt - System.currentTimeMillis() > CERTIFICATE_REUSE) return cached+ return try { deviceCertificate() } catch (error: CloudError) {+ if (error.status != 403) throw error+ registerDevice(deviceName)+ deviceCertificate()+ }+ }++ suspend fun createClaim(): PairingClaim {+ val claim = request("POST", listOf("v1", "claims"), buildJsonObject { })+ return PairingClaim(requireNotNull(claim.text("claimId")), requireNotNull(claim.text("nonce")))+ }++ /** Hands the account [signed], the claim the computer signed when it let this phone in. */+ suspend fun completeClaim(claimId: String, signed: JsonObject) {+ request("POST", listOf("v1", "claims", claimId, "complete"), signed)+ }+suspend fun computers(): List<CloudComputer> {val result = request("GET", listOf("v1", "computers"), signed = true)return json.decodeFromJsonElement(result.getValue("computers"))@@ -147,5 +183,8 @@ class CloudClient private constructor(base: String, private val identity: Devicereturn value}- companion object { private const val MAX_RESPONSE = 2L * 1024 * 1024 }+ companion object {+ private const val MAX_RESPONSE = 2L * 1024 * 1024+ private const val CERTIFICATE_REUSE = 24L * 60 * 60 * 1000+ }}diff --git a/apps/android/core/src/main/kotlin/com/codync/android/core/HostConnector.kt b/apps/android/core/src/main/kotlin/com/codync/android/core/HostConnector.ktindex 3511c5f2..8a7b5a28 100644--- a/apps/android/core/src/main/kotlin/com/codync/android/core/HostConnector.kt+++ b/apps/android/core/src/main/kotlin/com/codync/android/core/HostConnector.kt@@ -7,21 +7,32 @@ import kotlinx.coroutines.coroutineScopeimport kotlinx.coroutines.delayimport kotlinx.coroutines.launchimport kotlinx.coroutines.withTimeoutOrNull+import kotlinx.serialization.json.JsonObjectimport kotlinx.serialization.json.buildJsonObjectimport kotlinx.serialization.json.jsonObjectimport kotlinx.serialization.json.putimport okhttp3.HttpUrl.Companion.toHttpUrlimport okhttp3.Request+/** A computer pairing let in, and the claim it signed when it joined this phone's account (null when it didn't). */+data class Paired(val computer: Computer, val claim: JsonObject?)+object HostConnector {- suspend fun pair(pairing: Pairing, identity: DeviceIdentity, deviceName: String): Computer {+ /**+ * Pairs with [certificate] as the account proof; a computer in no account first asks its user (up to two minutes),+ * then signs [claim] to join the phone's account.+ */+ suspend fun pair(pairing: Pairing, identity: DeviceIdentity, deviceName: String, certificate: DeviceCertificate,+ claim: PairingClaim? = null): Paired {require(deviceName.isNotBlank() && deviceName.codePointCount(0, deviceName.length) <= 100)val channel = connect(pairing.computer, identity, pairing)try {val response = try {channel.call("pair", buildJsonObject {put("code", pairing.code); put("name", deviceName); put("platform", "android")- }, timeoutMillis = 30_000)+ put("certificate", certificate.json)+ claim?.let { put("claim", buildJsonObject { put("claimId", it.claimId); put("nonce", it.nonce) }) }+ }, timeoutMillis = 150_000)} catch (error: HostError) {// Hosts from before Android support turn the platform down: say what to do, not the wire error.if (error.status == 400 && "platform" in error.message) throw HostError(400, "Update Codync on this computer to pair an Android phone.")@@ -29,7 +40,8 @@ object HostConnector {}val result = response.jsonObjectrequire(result.text("computerId") == pairing.computer.id) { "This computer's identity changed. Pair it again." }- return pairing.computer.copy(name = result.text("name")?.takeIf(String::isNotBlank) ?: pairing.computer.name)+ return Paired(pairing.computer.copy(name = result.text("name")?.takeIf(String::isNotBlank) ?: pairing.computer.name),+ result["claim"] as? JsonObject)} finally {channel.close()}diff --git a/apps/android/core/src/main/kotlin/com/codync/android/core/Pairing.kt b/apps/android/core/src/main/kotlin/com/codync/android/core/Pairing.ktindex b79396da..bd9dada4 100644--- a/apps/android/core/src/main/kotlin/com/codync/android/core/Pairing.kt+++ b/apps/android/core/src/main/kotlin/com/codync/android/core/Pairing.kt@@ -17,6 +17,9 @@ class PairingProblem(val kind: Kind, cause: Throwable? = null) : IllegalArgumentdata class Pairing(val computer: Computer, val code: String) {internal val offerId: String get() = RelayCrypto.offerId(code.decodeBase64Url(16))+ /** The code the computer shows if it asks whether to let [identity]'s phone in. */+ fun checkCode(identity: DeviceIdentity): String = RelayCrypto.pairCheck(identity.deviceKey, computer.signKey.decodeBase64Url(32))+companion object {fun parse(text: String, scheme: String): Pairing {if (text.length > 16 * 1024) throw PairingProblem(PairingProblem.Kind.Invalid)diff --git a/apps/android/core/src/main/kotlin/com/codync/android/core/RelayCrypto.kt b/apps/android/core/src/main/kotlin/com/codync/android/core/RelayCrypto.ktindex cb9f3180..b340029f 100644--- a/apps/android/core/src/main/kotlin/com/codync/android/core/RelayCrypto.kt+++ b/apps/android/core/src/main/kotlin/com/codync/android/core/RelayCrypto.kt@@ -41,7 +41,17 @@ object RelayCrypto {fun sasCode(hostSignKey: ByteArray, deviceKey: ByteArray, deviceNonce: ByteArray, hostNonce: ByteArray): String {require(listOf(hostSignKey, deviceKey, deviceNonce, hostNonce).all { it.size == 32 }) { "Invalid access request" }- val hash = sha256(label("codync/sas/v2"), hostSignKey, deviceKey, deviceNonce, hostNonce)+ return sixDigits(sha256(label("codync/sas/v2"), hostSignKey, deviceKey, deviceNonce, hostNonce))+ }++ /** The code a computer shows when it asks whether to let this phone in by pairing (host `pairing_requests::check_code`). */+ fun pairCheck(deviceKey: ByteArray, hostSignKey: ByteArray): String {+ require(deviceKey.size == 32 && hostSignKey.size == 32) { "Invalid pairing code" }+ return sixDigits(sha256(label("codync/pair-check/v1"), deviceKey, hostSignKey))+ }++ /** The first four bytes as a big-endian number, modulo a million, as six digits. */+ private fun sixDigits(hash: ByteArray): String {val number = hash.take(4).fold(0L) { value, byte -> (value shl 8) or (byte.toLong() and 255) }return (number % 1_000_000).toString().padStart(6, '0')}diff --git a/apps/android/core/src/test/kotlin/com/codync/android/core/ChannelIntegrationTest.kt b/apps/android/core/src/test/kotlin/com/codync/android/core/ChannelIntegrationTest.ktindex 746055b5..3f298728 100644--- a/apps/android/core/src/test/kotlin/com/codync/android/core/ChannelIntegrationTest.kt+++ b/apps/android/core/src/test/kotlin/com/codync/android/core/ChannelIntegrationTest.kt@@ -106,8 +106,13 @@ class ChannelIntegrationTest {put("type", "bot"); put("rev", 4); put("bot", buildJsonObject { put("id", "bot-1"); put("name", "Reviewer"); put("rev", 4) })}) })} else if (request.text("m") == "pair") {- pairBody.set(request.getValue("b").jsonObject)- send(webSocket, buildJsonObject { put("id", id); put("ok", buildJsonObject { put("computerId", cid); put("name", "Paired computer") }) })+ val body = request.getValue("b").jsonObject+ pairBody.set(body)+ send(webSocket, buildJsonObject { put("id", id); put("ok", buildJsonObject {+ put("computerId", cid); put("name", "Paired computer")+ // A computer in no account signs the phone's claim.+ body["claim"]?.let { put("claim", buildJsonObject { put("computerId", cid); put("sig", "signed") }) }+ }) })webSocket.close(4100, "paired")} else {send(webSocket, buildJsonObject { put("id", id); put("ok", buildJsonObject {@@ -166,13 +171,27 @@ class ChannelIntegrationTest {} finally { channel.close() }}+ private val certificate = DeviceCertificate("""{"v":1,"exp":1}""", "sig")+@Test fun `pairing sends the Android platform and returns the pinned computer`() = runBlocking {enqueueHost()val pinned = computer()- val result = withTimeout(5_000) { HostConnector.pair(Pairing(pinned, ByteArray(16) { 8 }.base64Url()), identity(), "Android phone") }- assertEquals(cid, result.id)- assertEquals("Paired computer", result.name)- assertEquals("android", pairBody.get().text("platform"))+ val result = withTimeout(5_000) { HostConnector.pair(Pairing(pinned, ByteArray(16) { 8 }.base64Url()), identity(), "Android phone", certificate) }+ assertEquals(cid, result.computer.id)+ assertEquals("Paired computer", result.computer.name)+ assertEquals(null, result.claim)+ val body = pairBody.get()+ assertEquals("android", body.text("platform"))+ assertEquals(buildJsonObject { put("payload", certificate.payload); put("sig", "sig") }, body["certificate"])+ assertEquals(null, body["claim"])+ }++ @Test fun `pairing sends the claim and returns the one the computer signed`() = runBlocking {+ enqueueHost()+ val pairing = Pairing(computer(), ByteArray(16) { 8 }.base64Url())+ val result = withTimeout(5_000) { HostConnector.pair(pairing, identity(), "Android phone", certificate, PairingClaim("clm_1", "n")) }+ assertEquals(buildJsonObject { put("claimId", "clm_1"); put("nonce", "n") }, pairBody.get()["claim"])+ assertEquals("signed", result.claim?.text("sig"))}@Test fun `encrypted RPC and event subscriptions preserve host payloads`() = runBlocking {diff --git a/apps/android/core/src/test/kotlin/com/codync/android/core/CloudClientTest.kt b/apps/android/core/src/test/kotlin/com/codync/android/core/CloudClientTest.ktindex 79f6c757..d0fe332e 100644--- a/apps/android/core/src/test/kotlin/com/codync/android/core/CloudClientTest.kt+++ b/apps/android/core/src/test/kotlin/com/codync/android/core/CloudClientTest.kt@@ -132,4 +132,52 @@ class CloudClientTest {assertEquals("/v1/devices", server.takeRequest().path)} finally { server.shutdown() }}++ private fun certificateBody(exp: Long) =+ """{"certificate":{"payload":${JsonPrimitive("""{"v":1,"deviceKey":"${identity.publicKey}","userId":"u","exp":$exp}""")},"sig":"s"}}"""++ @Test fun `a certificate is reused while more than a day is left and a new key is registered first`() = runBlocking {+ val server = MockWebServer()+ server.start()+ try {+ val client = CloudClient(server.url("/").toString(), identity, { "session" }, OkHttpClient(), 1, Unit)+ val day = 24L * 60 * 60 * 1000+ val lasting = DeviceCertificate("""{"exp":${System.currentTimeMillis() + 2 * day}}""", "s")+ assertSame(lasting, client.certificate(lasting, "Pixel"))+ assertEquals(0, server.requestCount)++ val exp = System.currentTimeMillis() + 7 * day+ server.enqueue(MockResponse().setResponseCode(403).setBody("""{"error":{"code":"forbidden"}}"""))+ server.enqueue(MockResponse().setBody("{}"))+ server.enqueue(MockResponse().setBody(certificateBody(exp)))+ val ending = DeviceCertificate("""{"exp":${System.currentTimeMillis() + day / 2}}""", "s")+ val fresh = client.certificate(ending, "Pixel")+ assertEquals(exp, fresh.expiresAt)+ assertEquals("s", fresh.sig)+ val asked = server.takeRequest()+ assertEquals("POST", asked.method)+ assertEquals("/v1/devices/certificate", asked.path)+ assertEquals("Bearer session", asked.getHeader("Authorization"))+ assertTrue(requireNotNull(asked.getHeader("Codync-Sig")).contains("kid=${identity.publicKey}"))+ assertEquals("/v1/devices", server.takeRequest().path)+ assertEquals("/v1/devices/certificate", server.takeRequest().path)+ } finally { server.shutdown() }+ }++ @Test fun `a claim is made then completed with the computer's signed object as is`() = runBlocking {+ val server = MockWebServer()+ server.start()+ try {+ server.enqueue(MockResponse().setBody("""{"claimId":"clm_1","nonce":"n","expiresAt":1}"""))+ server.enqueue(MockResponse().setBody("""{"computer":{}}"""))+ val client = CloudClient(server.url("/").toString(), identity, { "session" }, OkHttpClient(), 1, Unit)+ assertEquals(PairingClaim("clm_1", "n"), client.createClaim())+ val signed = buildJsonObject { put("computerId", id); put("signKey", hostKey.base64Url()); put("sig", "x"); put("device", JsonNull) }+ client.completeClaim("clm_1", signed)+ assertEquals("/v1/claims", server.takeRequest().path)+ val complete = server.takeRequest()+ assertEquals("/v1/claims/clm_1/complete", complete.path)+ assertEquals(signed, Json.parseToJsonElement(complete.body.readUtf8()))+ } finally { server.shutdown() }+ }}diff --git a/apps/android/core/src/test/kotlin/com/codync/android/core/HostInteropTest.kt b/apps/android/core/src/test/kotlin/com/codync/android/core/HostInteropTest.ktindex 932021e9..d735a871 100644--- a/apps/android/core/src/test/kotlin/com/codync/android/core/HostInteropTest.kt+++ b/apps/android/core/src/test/kotlin/com/codync/android/core/HostInteropTest.kt@@ -23,11 +23,15 @@ class HostInteropTest {val relay = System.getenv("CODYNC_ANDROID_TEST_ROUTE") == "relay"val pairing = if (relay) parsed.copy(computer = parsed.computer.copy(route = ConnectionRoute.CloudflareFirst, urls = emptyList())) else parsedval random = SecureRandom()- val identity = DeviceIdentity(ByteArray(32).also(random::nextBytes), ByteArray(32).also(random::nextBytes))+ // Pairing needs the account's word for the device key: a cloud certificate and the seed it was issued for.+ val proof = Json.parseToJsonElement(File(requireNotNull(System.getenv("CODYNC_ANDROID_CERTIFICATE_FILE")) {+ "Live pairing requires a certificate file: {seed, payload, sig}" }).readText()).jsonObject+ val identity = DeviceIdentity(requireNotNull(proof.text("seed")).decodeBase64Url(32), ByteArray(32).also(random::nextBytes))+ val certificate = DeviceCertificate(requireNotNull(proof.text("payload")), requireNotNull(proof.text("sig")))val cleanup = System.getenv("CODYNC_ANDROID_CLEANUP_KEY_FILE")requireNotNull(cleanup) { "Live acceptance requires a cleanup key file" }File(cleanup).writeText(identity.publicKey)- val paired = withTimeout(30_000) { HostConnector.pair(pairing, identity, "Android protocol acceptance") }+ val paired = withTimeout(150_000) { HostConnector.pair(pairing, identity, "Android protocol acceptance", certificate).computer }val target = paired.copy(route = if (relay) ConnectionRoute.CloudflareFirst else ConnectionRoute.DirectOnly,urls = if (relay) emptyList() else paired.urls)val channel = withTimeout(30_000) { HostConnector.connect(target, identity) }diff --git a/apps/android/core/src/test/kotlin/com/codync/android/core/PairingTest.kt b/apps/android/core/src/test/kotlin/com/codync/android/core/PairingTest.ktindex 55aa2d4a..254cc318 100644--- a/apps/android/core/src/test/kotlin/com/codync/android/core/PairingTest.kt+++ b/apps/android/core/src/test/kotlin/com/codync/android/core/PairingTest.kt@@ -74,5 +74,11 @@ class PairingTest {for (value in listOf("AA=", "AB", "A", "+A", "AA ")) assertFails<IllegalArgumentException> { value.decodeBase64Url() }assertFails<IllegalArgumentException> { "AA".decodeBase64Url(32) }}-}+ @Test fun `the pairing check code matches the host's`() {+ assertEquals("855066", RelayCrypto.pairCheck(ByteArray(32) { 1 }, ByteArray(32) { 2 }))+ val pairing = Pairing.parse(link(), "codync")+ val identity = DeviceIdentity(ByteArray(32) { 3 }, ByteArray(32) { 12 })+ assertEquals(RelayCrypto.pairCheck(identity.deviceKey, pairing.computer.signKey.decodeBase64Url(32)), pairing.checkCode(identity))+ }+}