From c66d7097f1140a0c069b6930a0bc074366cd8f1b Mon Sep 17 00:00:00 2001 From: DorJay Date: Sun, 8 Nov 2026 20:50:24 +0800 Subject: [PATCH 1/6] chore(android): extract companion app into a git submodule (v0.4.3) --- .gitmodules | 3 + mobile/android | 1 + mobile/android/.gitignore | 8 - mobile/android/README.md | 33 ---- mobile/android/app/build.gradle.kts | 42 ----- .../android/app/src/main/AndroidManifest.xml | 19 -- .../dev/vibex/companion/app/MainActivity.kt | 83 --------- .../app/src/main/res/values/strings.xml | 4 - mobile/android/build.gradle.kts | 6 - .../android/companion-core/build.gradle.kts | 25 --- mobile/android/companion-core/smoke.test.js | 164 ------------------ .../dev/vibex/companion/CompanionScopes.kt | 27 --- .../kotlin/dev/vibex/companion/HostOrigin.kt | 32 ---- .../dev/vibex/companion/PairingClient.kt | 118 ------------- .../kotlin/dev/vibex/companion/RemoteJson.kt | 46 ----- .../dev/vibex/companion/CompanionCoreSmoke.kt | 70 -------- .../vibex/companion/CompanionScopesTest.kt | 18 -- .../dev/vibex/companion/PairingClientTest.kt | 87 ---------- mobile/android/gradle.properties | 4 - .../gradle/wrapper/gradle-wrapper.properties | 7 - mobile/android/settings.gradle.kts | 23 --- 21 files changed, 4 insertions(+), 816 deletions(-) create mode 160000 mobile/android delete mode 100644 mobile/android/.gitignore delete mode 100644 mobile/android/README.md delete mode 100644 mobile/android/app/build.gradle.kts delete mode 100644 mobile/android/app/src/main/AndroidManifest.xml delete mode 100644 mobile/android/app/src/main/java/dev/vibex/companion/app/MainActivity.kt delete mode 100644 mobile/android/app/src/main/res/values/strings.xml delete mode 100644 mobile/android/build.gradle.kts delete mode 100644 mobile/android/companion-core/build.gradle.kts delete mode 100644 mobile/android/companion-core/smoke.test.js delete mode 100644 mobile/android/companion-core/src/main/kotlin/dev/vibex/companion/CompanionScopes.kt delete mode 100644 mobile/android/companion-core/src/main/kotlin/dev/vibex/companion/HostOrigin.kt delete mode 100644 mobile/android/companion-core/src/main/kotlin/dev/vibex/companion/PairingClient.kt delete mode 100644 mobile/android/companion-core/src/main/kotlin/dev/vibex/companion/RemoteJson.kt delete mode 100644 mobile/android/companion-core/src/smoke/kotlin/dev/vibex/companion/CompanionCoreSmoke.kt delete mode 100644 mobile/android/companion-core/src/test/kotlin/dev/vibex/companion/CompanionScopesTest.kt delete mode 100644 mobile/android/companion-core/src/test/kotlin/dev/vibex/companion/PairingClientTest.kt delete mode 100644 mobile/android/gradle.properties delete mode 100644 mobile/android/gradle/wrapper/gradle-wrapper.properties delete mode 100644 mobile/android/settings.gradle.kts diff --git a/.gitmodules b/.gitmodules index 411f6ba36..54ca2b774 100644 --- a/.gitmodules +++ b/.gitmodules @@ -1,3 +1,6 @@ [submodule "mobile/ios"] path = mobile/ios url = https://github.com/Xircth/vibex-remote-ios.git +[submodule "mobile/android"] + path = mobile/android + url = https://github.com/DorJay007/vibex-remote-android.git diff --git a/mobile/android b/mobile/android new file mode 160000 index 000000000..cbd056ebb --- /dev/null +++ b/mobile/android @@ -0,0 +1 @@ +Subproject commit cbd056ebb13559f3d5b537161ba238a72f87ad7b diff --git a/mobile/android/.gitignore b/mobile/android/.gitignore deleted file mode 100644 index aadc78b5a..000000000 --- a/mobile/android/.gitignore +++ /dev/null @@ -1,8 +0,0 @@ -.gradle/ -build/ -local.properties -**/.cxx/ -captures/ -*.apk -*.ap_ -*.aab diff --git a/mobile/android/README.md b/mobile/android/README.md deleted file mode 100644 index 538aa5e06..000000000 --- a/mobile/android/README.md +++ /dev/null @@ -1,33 +0,0 @@ -# VibeX Companion (Android) - -Android is a Companion Device. It pairs with the Host using the `companion` -preset and never runs Agent, Git, or plugins. - -## Pairing - -1. On the Host, start Remote Protocol and create a pairing with - `{ "preset": "companion" }`. -2. Enter the Host origin and one-time pairing token in the app. -3. `companion-core` redeems `POST /api/v1/auth/pairings/redeem`, refuses any - scope outside the Companion allowlist, then checks - `GET /api/v1/capabilities`. -4. Store the device credential in Android Keystore. - -Wire models come from `docs/protocol/v1/generated/kotlin/RemoteProtocolModels.kt`. -Do not hand-edit a second protocol copy. - -## Layout - -- `companion-core` — JVM pairing client. Compiles with a JDK; no Android SDK. -- `app` — Jetpack Compose shell that calls `companion-core`. - -```bash -# pairing client and scope tests; needs JDK 17 -./gradlew :companion-core:test - -# full APK; needs Android SDK -./gradlew :app:assembleDebug -``` - -If this tree has no Gradle wrapper yet, generate one with Gradle 8.11+ or run -the same tasks from Android Studio. diff --git a/mobile/android/app/build.gradle.kts b/mobile/android/app/build.gradle.kts deleted file mode 100644 index 39546402a..000000000 --- a/mobile/android/app/build.gradle.kts +++ /dev/null @@ -1,42 +0,0 @@ -plugins { - id("com.android.application") - id("org.jetbrains.kotlin.android") - id("org.jetbrains.kotlin.plugin.compose") -} - -android { - namespace = "dev.vibex.companion.app" - compileSdk = 35 - defaultConfig { - applicationId = "dev.vibex.companion" - minSdk = 26 - targetSdk = 35 - versionCode = 1 - versionName = "0.1.3" - } - buildTypes { - release { - isMinifyEnabled = false - } - } - buildFeatures { - compose = true - } - compileOptions { - sourceCompatibility = JavaVersion.VERSION_17 - targetCompatibility = JavaVersion.VERSION_17 - } - kotlinOptions { - jvmTarget = "17" - } -} - -dependencies { - implementation(project(":companion-core")) - implementation(platform("androidx.compose:compose-bom:2024.10.01")) - implementation("androidx.activity:activity-compose:1.9.3") - implementation("androidx.compose.material3:material3") - implementation("androidx.compose.ui:ui") - implementation("androidx.compose.ui:ui-tooling-preview") - implementation("org.jetbrains.kotlinx:kotlinx-coroutines-android:1.9.0") -} diff --git a/mobile/android/app/src/main/AndroidManifest.xml b/mobile/android/app/src/main/AndroidManifest.xml deleted file mode 100644 index 43e0e63af..000000000 --- a/mobile/android/app/src/main/AndroidManifest.xml +++ /dev/null @@ -1,19 +0,0 @@ - - - - - - - - - - - - diff --git a/mobile/android/app/src/main/java/dev/vibex/companion/app/MainActivity.kt b/mobile/android/app/src/main/java/dev/vibex/companion/app/MainActivity.kt deleted file mode 100644 index 96f4de680..000000000 --- a/mobile/android/app/src/main/java/dev/vibex/companion/app/MainActivity.kt +++ /dev/null @@ -1,83 +0,0 @@ -package dev.vibex.companion.app - -import android.os.Bundle -import androidx.activity.ComponentActivity -import androidx.activity.compose.setContent -import androidx.compose.foundation.layout.Arrangement -import androidx.compose.foundation.layout.Column -import androidx.compose.foundation.layout.fillMaxSize -import androidx.compose.foundation.layout.fillMaxWidth -import androidx.compose.foundation.layout.padding -import androidx.compose.material3.Button -import androidx.compose.material3.MaterialTheme -import androidx.compose.material3.OutlinedTextField -import androidx.compose.material3.Surface -import androidx.compose.material3.Text -import androidx.compose.runtime.getValue -import androidx.compose.runtime.mutableStateOf -import androidx.compose.runtime.remember -import androidx.compose.runtime.rememberCoroutineScope -import androidx.compose.runtime.setValue -import androidx.compose.ui.Modifier -import androidx.compose.ui.unit.dp -import dev.vibex.companion.HostOrigin -import dev.vibex.companion.PairingClient -import kotlinx.coroutines.Dispatchers -import kotlinx.coroutines.launch -import kotlinx.coroutines.withContext - -class MainActivity : ComponentActivity() { - override fun onCreate(savedInstanceState: Bundle?) { - super.onCreate(savedInstanceState) - setContent { - MaterialTheme { - Surface(modifier = Modifier.fillMaxSize()) { - var origin by remember { mutableStateOf("http://127.0.0.1:17891") } - var token by remember { mutableStateOf("") } - var status by remember { mutableStateOf("Enter the Host origin and pairing token.") } - val scope = rememberCoroutineScope() - Column( - modifier = Modifier.padding(24.dp), - verticalArrangement = Arrangement.spacedBy(12.dp), - ) { - Text("VibeX Companion", style = MaterialTheme.typography.headlineSmall) - OutlinedTextField( - value = origin, - onValueChange = { origin = it }, - label = { Text("Host origin") }, - modifier = Modifier.fillMaxWidth(), - ) - OutlinedTextField( - value = token, - onValueChange = { token = it }, - label = { Text("Pairing token") }, - modifier = Modifier.fillMaxWidth(), - ) - Button( - onClick = { - scope.launch { - status = runCatching { - val session = withContext(Dispatchers.IO) { - PairingClient().redeem( - HostOrigin.parse(origin), - token, - android.os.Build.MODEL, - ) - } - "Paired as ${session.credential.device_id}" - }.getOrElse { error -> - error.message ?: "Pairing failed" - } - } - }, - modifier = Modifier.fillMaxWidth(), - ) { - Text("Pair") - } - Text(status, style = MaterialTheme.typography.bodyMedium) - } - } - } - } - } -} diff --git a/mobile/android/app/src/main/res/values/strings.xml b/mobile/android/app/src/main/res/values/strings.xml deleted file mode 100644 index 5e47f9893..000000000 --- a/mobile/android/app/src/main/res/values/strings.xml +++ /dev/null @@ -1,4 +0,0 @@ - - - VibeX Companion - diff --git a/mobile/android/build.gradle.kts b/mobile/android/build.gradle.kts deleted file mode 100644 index e008439b3..000000000 --- a/mobile/android/build.gradle.kts +++ /dev/null @@ -1,6 +0,0 @@ -plugins { - id("com.android.application") version "8.7.3" apply false - id("org.jetbrains.kotlin.android") version "2.0.21" apply false - id("org.jetbrains.kotlin.jvm") version "2.0.21" apply false - id("org.jetbrains.kotlin.plugin.compose") version "2.0.21" apply false -} diff --git a/mobile/android/companion-core/build.gradle.kts b/mobile/android/companion-core/build.gradle.kts deleted file mode 100644 index af242a983..000000000 --- a/mobile/android/companion-core/build.gradle.kts +++ /dev/null @@ -1,25 +0,0 @@ -plugins { - id("org.jetbrains.kotlin.jvm") -} - -kotlin { - jvmToolchain(17) -} - -sourceSets { - main { - kotlin.srcDir("src/main/kotlin") - kotlin.srcDir("../../../docs/protocol/v1/generated/kotlin") - } - test { - kotlin.srcDir("src/test/kotlin") - } -} - -dependencies { - testImplementation(kotlin("test")) -} - -tasks.test { - useJUnitPlatform() -} diff --git a/mobile/android/companion-core/smoke.test.js b/mobile/android/companion-core/smoke.test.js deleted file mode 100644 index 508ec8224..000000000 --- a/mobile/android/companion-core/smoke.test.js +++ /dev/null @@ -1,164 +0,0 @@ -const assert = require("node:assert/strict"); -const crypto = require("node:crypto"); -const { spawnSync } = require("node:child_process"); -const fs = require("node:fs"); -const os = require("node:os"); -const path = require("node:path"); -const test = require("node:test"); - -const root = path.resolve(__dirname, "../../.."); -const core = __dirname; -const kotlinVersion = "2.4.10"; -const kotlinArchiveSha256 = - "473dd66c7a3ef4b182065b3da670466c1bf2773a9dbb0ed8b33a39fe9d4f876d"; -const temurinVersion = "21.0.11_10"; -const temurinMacArm64Sha256 = - "4b7a8cd23102c251c8b8be42a9a5f1263fb337cf1037f6f64b25f3070efe4b76"; - -function commandOnPath(command) { - const locator = process.platform === "win32" ? "where" : "which"; - const result = spawnSync(locator, [command], { encoding: "utf8" }); - return result.status === 0 ? result.stdout.trim().split(/\r?\n/)[0] : undefined; -} - -function run(command, commandArgs) { - const result = spawnSync(command, commandArgs, { encoding: "utf8" }); - if (result.status !== 0) { - throw new Error( - `${command} ${commandArgs.join(" ")} failed (${result.status})\n${ - result.stderr || result.stdout || "" - }`, - ); - } - return result; -} - -function downloadVerified(url, archive, expectedSha256) { - if (!fs.existsSync(archive)) { - run("curl", ["--fail", "--location", "--output", archive, url]); - } - const digest = crypto.createHash("sha256").update(fs.readFileSync(archive)).digest("hex"); - if (digest !== expectedSha256) { - throw new Error(`tool checksum mismatch for ${path.basename(archive)}: ${digest}`); - } -} - -function resolveKotlinCompiler() { - if (process.env.VIBEX_KOTLINC) { - return process.env.VIBEX_KOTLINC; - } - const existing = commandOnPath("kotlinc"); - if (existing) { - return existing; - } - const tools = path.join(root, "target", "tools"); - const archive = path.join(tools, `kotlin-compiler-${kotlinVersion}.zip`); - const extracted = path.join(tools, `kotlin-compiler-${kotlinVersion}`); - const compiler = path.join( - extracted, - "kotlinc", - "bin", - process.platform === "win32" ? "kotlinc.bat" : "kotlinc", - ); - if (fs.existsSync(compiler)) { - return compiler; - } - fs.mkdirSync(tools, { recursive: true }); - downloadVerified( - `https://github.com/JetBrains/kotlin/releases/download/v${kotlinVersion}/kotlin-compiler-${kotlinVersion}.zip`, - archive, - kotlinArchiveSha256, - ); - fs.rmSync(extracted, { recursive: true, force: true }); - fs.mkdirSync(extracted, { recursive: true }); - run("unzip", ["-q", archive, "-d", extracted]); - return compiler; -} - -function resolveJava() { - if (process.env.JAVA_HOME) { - return path.join( - process.env.JAVA_HOME, - "bin", - process.platform === "win32" ? "java.exe" : "java", - ); - } - const existing = commandOnPath("java"); - if (existing) { - const probe = spawnSync(existing, ["-version"], { encoding: "utf8" }); - if (probe.status === 0) { - return existing; - } - } - if (process.platform !== "darwin" || process.arch !== "arm64") { - throw new Error("a Java 21+ runtime is required to compile companion-core"); - } - const tools = path.join(root, "target", "tools"); - const archive = path.join(tools, `temurin-jre-${temurinVersion}-mac-arm64.tar.gz`); - const extracted = path.join(tools, `temurin-jre-${temurinVersion}-mac-arm64`); - const home = path.join( - extracted, - `jdk-${temurinVersion.replace("_", "+")}-jre`, - "Contents", - "Home", - ); - const java = path.join(home, "bin", "java"); - if (fs.existsSync(java)) { - return java; - } - fs.mkdirSync(tools, { recursive: true }); - downloadVerified( - "https://github.com/adoptium/temurin21-binaries/releases/download/" + - "jdk-21.0.11%2B10/OpenJDK21U-jre_aarch64_mac_hotspot_21.0.11_10.tar.gz", - archive, - temurinMacArm64Sha256, - ); - fs.rmSync(extracted, { recursive: true, force: true }); - fs.mkdirSync(extracted, { recursive: true }); - run("tar", ["-xzf", archive, "-C", extracted]); - return java; -} - -function collectKotlin(dir) { - const files = []; - for (const entry of fs.readdirSync(dir, { withFileTypes: true })) { - const fullPath = path.join(dir, entry.name); - if (entry.isDirectory()) { - files.push(...collectKotlin(fullPath)); - } else if (entry.name.endsWith(".kt")) { - files.push(fullPath); - } - } - return files; -} - -test("companion-core pairing client compiles and rejects workstation scopes", () => { - const kotlinc = resolveKotlinCompiler(); - const java = resolveJava(); - const javaHome = path.resolve(java, "..", ".."); - const sources = [ - path.join(root, "docs/protocol/v1/generated/kotlin/RemoteProtocolModels.kt"), - ...collectKotlin(path.join(core, "src/main/kotlin")), - path.join(core, "src/smoke/kotlin/dev/vibex/companion/CompanionCoreSmoke.kt"), - ]; - const output = path.join(os.tmpdir(), `vibex-companion-core-${process.pid}.jar`); - const compile = spawnSync(kotlinc, [...sources, "-include-runtime", "-d", output], { - encoding: "utf8", - env: { ...process.env, JAVA_HOME: javaHome }, - }); - assert.equal( - compile.status, - 0, - compile.stderr || compile.stdout || "kotlinc failed", - ); - const runResult = spawnSync(java, ["-jar", output], { - encoding: "utf8", - env: { ...process.env, JAVA_HOME: javaHome }, - }); - fs.rmSync(output, { force: true }); - assert.equal( - runResult.status, - 0, - runResult.stderr || runResult.stdout || "companion-core smoke failed", - ); -}); diff --git a/mobile/android/companion-core/src/main/kotlin/dev/vibex/companion/CompanionScopes.kt b/mobile/android/companion-core/src/main/kotlin/dev/vibex/companion/CompanionScopes.kt deleted file mode 100644 index 2ccb2cb38..000000000 --- a/mobile/android/companion-core/src/main/kotlin/dev/vibex/companion/CompanionScopes.kt +++ /dev/null @@ -1,27 +0,0 @@ -package dev.vibex.companion - -/** - * Companion Device scopes from ADR-0054. Authorization still checks each - * scope; this set is only the pairing allowlist the phone will accept. - */ -object CompanionScopes { - val allowed: Set = setOf( - "conversation.read", - "conversation.write", - "conversation.attach", - "conversation.permission", - "conversation.question", - "conversation.cancel", - "conversation.steer", - "plugin.read", - "artifact.read", - "workflow.read", - "automation.read", - "delegation.read", - "notification.summary", - "offline.read", - ) - - fun extras(scopes: Collection): Set = - scopes.filterNot { it in allowed }.toSet() -} diff --git a/mobile/android/companion-core/src/main/kotlin/dev/vibex/companion/HostOrigin.kt b/mobile/android/companion-core/src/main/kotlin/dev/vibex/companion/HostOrigin.kt deleted file mode 100644 index 4459b829c..000000000 --- a/mobile/android/companion-core/src/main/kotlin/dev/vibex/companion/HostOrigin.kt +++ /dev/null @@ -1,32 +0,0 @@ -package dev.vibex.companion - -import java.net.URI - -data class HostOrigin(val value: String) { - fun resolve(path: String): String { - val suffix = if (path.startsWith("/")) path else "/$path" - return value + suffix - } - - companion object { - fun parse(raw: String): HostOrigin { - val trimmed = raw.trim().trimEnd('/') - require(trimmed.isNotEmpty()) { "Host origin is required" } - val uri = try { - URI(trimmed) - } catch (error: Exception) { - throw IllegalArgumentException("Host origin is not a valid URI", error) - } - require(uri.scheme == "http" || uri.scheme == "https") { - "Host origin must be http or https" - } - require(uri.host.isNullOrBlank().not()) { "Host origin must include a host" } - require(uri.userInfo == null) { "Host origin must not include credentials" } - require(uri.query == null) { "Host origin must not include a query string" } - require(uri.fragment == null) { "Host origin must not include a fragment" } - val port = if (uri.port == -1) "" else ":${uri.port}" - val path = uri.path.orEmpty().trimEnd('/') - return HostOrigin("${uri.scheme}://${uri.host}$port$path") - } - } -} diff --git a/mobile/android/companion-core/src/main/kotlin/dev/vibex/companion/PairingClient.kt b/mobile/android/companion-core/src/main/kotlin/dev/vibex/companion/PairingClient.kt deleted file mode 100644 index d02250686..000000000 --- a/mobile/android/companion-core/src/main/kotlin/dev/vibex/companion/PairingClient.kt +++ /dev/null @@ -1,118 +0,0 @@ -package dev.vibex.companion - -import dev.vibex.remote.v1.DeviceCredential -import dev.vibex.remote.v1.RedeemPairingRequest -import dev.vibex.remote.v1.ServerCapabilities -import java.net.HttpURLConnection -import java.net.URI - -data class HttpExchange( - val status: Int, - val body: String, -) - -fun interface HttpTransport { - fun execute( - method: String, - url: String, - headers: Map, - body: String?, - ): HttpExchange -} - -class PairingException(message: String) : RuntimeException(message) - -data class CompanionSession( - val origin: HostOrigin, - val credential: DeviceCredential, - val capabilities: ServerCapabilities, -) - -class PairingClient( - private val transport: HttpTransport = UrlConnectionTransport(), - private val protocolVersion: String = CLIENT_PROTOCOL_VERSION, -) { - fun redeem( - origin: HostOrigin, - pairingToken: String, - deviceName: String = "Android Companion", - ): CompanionSession { - require(pairingToken.isNotBlank()) { "Pairing token is required" } - require(deviceName.isNotBlank()) { "Device name is required" } - - val redeemBody = RedeemPairingRequest( - pairing_token = pairingToken.trim(), - device_name = deviceName.trim(), - ).encodeJson() - val redeem = transport.execute( - "POST", - origin.resolve("/api/v1/auth/pairings/redeem"), - mapOf( - "content-type" to "application/json", - PROTOCOL_HEADER to protocolVersion, - ), - redeemBody, - ) - if (redeem.status !in 200..299) { - throw PairingException("Pairing redeem failed (${redeem.status})") - } - val credential = parseDeviceCredential(redeem.body) - val extras = CompanionScopes.extras(credential.scopes) - if (extras.isNotEmpty()) { - throw PairingException( - "Host granted non-companion scopes: ${extras.sorted().joinToString(", ")}", - ) - } - - val capabilitiesResponse = transport.execute( - "GET", - origin.resolve("/api/v1/capabilities"), - mapOf( - "authorization" to "Bearer ${credential.access_token}", - PROTOCOL_HEADER to protocolVersion, - ), - null, - ) - if (capabilitiesResponse.status !in 200..299) { - throw PairingException("Capabilities check failed (${capabilitiesResponse.status})") - } - val capabilities = parseServerCapabilities(capabilitiesResponse.body) - if (protocolMajor(capabilities.protocol_version) != protocolMajor(protocolVersion)) { - throw PairingException( - "Protocol ${capabilities.protocol_version} is incompatible with $protocolVersion", - ) - } - return CompanionSession(origin, credential, capabilities) - } - - companion object { - const val CLIENT_PROTOCOL_VERSION = "1.0" - const val PROTOCOL_HEADER = "x-vibex-protocol-version" - } -} - -class UrlConnectionTransport : HttpTransport { - override fun execute( - method: String, - url: String, - headers: Map, - body: String?, - ): HttpExchange { - val connection = URI(url).toURL().openConnection() as HttpURLConnection - connection.connectTimeout = 10_000 - connection.readTimeout = 20_000 - connection.requestMethod = method - connection.doInput = true - headers.forEach { (key, value) -> connection.setRequestProperty(key, value) } - if (body != null) { - connection.doOutput = true - connection.outputStream.use { output -> - output.write(body.toByteArray(Charsets.UTF_8)) - } - } - val status = connection.responseCode - val stream = if (status >= 400) connection.errorStream else connection.inputStream - val responseBody = stream?.bufferedReader(Charsets.UTF_8)?.use { it.readText() }.orEmpty() - return HttpExchange(status, responseBody) - } -} diff --git a/mobile/android/companion-core/src/main/kotlin/dev/vibex/companion/RemoteJson.kt b/mobile/android/companion-core/src/main/kotlin/dev/vibex/companion/RemoteJson.kt deleted file mode 100644 index c3fb93abd..000000000 --- a/mobile/android/companion-core/src/main/kotlin/dev/vibex/companion/RemoteJson.kt +++ /dev/null @@ -1,46 +0,0 @@ -package dev.vibex.companion - -import dev.vibex.remote.v1.DeviceCredential -import dev.vibex.remote.v1.JsonValue -import dev.vibex.remote.v1.RedeemPairingRequest -import dev.vibex.remote.v1.ServerCapabilities - -internal fun RedeemPairingRequest.encodeJson(): String = - JsonValue.Object( - mapOf( - "pairing_token" to JsonValue.Text(pairing_token), - "device_name" to JsonValue.Text(device_name), - ), - ).encode() - -internal fun JsonValue.Object.text(key: String): String = - (value[key] as? JsonValue.Text)?.value - ?: error("missing string field $key") - -internal fun JsonValue.Object.strings(key: String): List { - val array = value[key] as? JsonValue.Array ?: error("missing array field $key") - return array.value.map { item -> - (item as? JsonValue.Text)?.value ?: error("expected string in $key") - } -} - -internal fun parseServerCapabilities(body: String): ServerCapabilities { - val root = JsonValue.parse(body) as JsonValue.Object - return ServerCapabilities( - server_version = root.text("server_version"), - protocol_version = root.text("protocol_version"), - minimum_client_version = root.text("minimum_client_version"), - capabilities = root.strings("capabilities"), - ) -} - -internal fun parseDeviceCredential(body: String): DeviceCredential { - val root = JsonValue.parse(body) as JsonValue.Object - return DeviceCredential( - device_id = root.text("device_id"), - access_token = root.text("access_token"), - scopes = root.strings("scopes"), - ) -} - -internal fun protocolMajor(version: String): String = version.substringBefore('.') diff --git a/mobile/android/companion-core/src/smoke/kotlin/dev/vibex/companion/CompanionCoreSmoke.kt b/mobile/android/companion-core/src/smoke/kotlin/dev/vibex/companion/CompanionCoreSmoke.kt deleted file mode 100644 index 6d3a392ca..000000000 --- a/mobile/android/companion-core/src/smoke/kotlin/dev/vibex/companion/CompanionCoreSmoke.kt +++ /dev/null @@ -1,70 +0,0 @@ -package dev.vibex.companion - -fun main() { - check(CompanionScopes.allowed.contains("conversation.read")) - check(CompanionScopes.allowed.contains("offline.read")) - check(!CompanionScopes.allowed.contains("plugin.write")) - check( - CompanionScopes.extras(listOf("conversation.read", "plugin.write")) == - setOf("plugin.write"), - ) - - val origin = HostOrigin.parse("http://127.0.0.1:17891/") - check(origin.value == "http://127.0.0.1:17891") - check(origin.resolve("/api/v1/capabilities") == "http://127.0.0.1:17891/api/v1/capabilities") - - var threw = false - try { - HostOrigin.parse("http://user:secret@127.0.0.1:17891") - } catch (_: IllegalArgumentException) { - threw = true - } - check(threw) - - val transport = object : HttpTransport { - override fun execute( - method: String, - url: String, - headers: Map, - body: String?, - ): HttpExchange { - return if (method == "POST") { - check(url.endsWith("/api/v1/auth/pairings/redeem")) - check(body!!.contains("\"pairing_token\":\"one-time-secret\"")) - HttpExchange( - 201, - """{"device_id":"11111111-1111-1111-1111-111111111111","access_token":"device-token","scopes":["conversation.read","offline.read"]}""", - ) - } else { - check(headers["authorization"] == "Bearer device-token") - HttpExchange( - 200, - """{"server_version":"0.1.3","protocol_version":"1.0","minimum_client_version":"1.0","capabilities":["conversation.attach"]}""", - ) - } - } - } - val session = PairingClient(transport).redeem(origin, "one-time-secret", "Pixel") - check(session.credential.access_token == "device-token") - check(session.capabilities.protocol_version == "1.0") - - val rejected = object : HttpTransport { - override fun execute( - method: String, - url: String, - headers: Map, - body: String?, - ): HttpExchange = - HttpExchange( - 201, - """{"device_id":"11111111-1111-1111-1111-111111111111","access_token":"device-token","scopes":["plugin.write"]}""", - ) - } - var rejectedPairing = false - try { - PairingClient(rejected).redeem(origin, "token") - } catch (error: PairingException) { - rejectedPairing = error.message!!.contains("plugin.write") - } - check(rejectedPairing) -} diff --git a/mobile/android/companion-core/src/test/kotlin/dev/vibex/companion/CompanionScopesTest.kt b/mobile/android/companion-core/src/test/kotlin/dev/vibex/companion/CompanionScopesTest.kt deleted file mode 100644 index e07f9024b..000000000 --- a/mobile/android/companion-core/src/test/kotlin/dev/vibex/companion/CompanionScopesTest.kt +++ /dev/null @@ -1,18 +0,0 @@ -package dev.vibex.companion - -import kotlin.test.Test -import kotlin.test.assertEquals -import kotlin.test.assertTrue - -class CompanionScopesTest { - @Test - fun companionAllowlistMatchesHostPreset() { - assertTrue(CompanionScopes.allowed.contains("conversation.read")) - assertTrue(CompanionScopes.allowed.contains("offline.read")) - assertTrue(CompanionScopes.allowed.contains("notification.summary")) - assertEquals(emptySet(), CompanionScopes.extras(CompanionScopes.allowed)) - assertEquals(setOf("plugin.write", "workflow.write"), CompanionScopes.extras( - listOf("conversation.read", "plugin.write", "workflow.write"), - )) - } -} diff --git a/mobile/android/companion-core/src/test/kotlin/dev/vibex/companion/PairingClientTest.kt b/mobile/android/companion-core/src/test/kotlin/dev/vibex/companion/PairingClientTest.kt deleted file mode 100644 index 2d24adfb5..000000000 --- a/mobile/android/companion-core/src/test/kotlin/dev/vibex/companion/PairingClientTest.kt +++ /dev/null @@ -1,87 +0,0 @@ -package dev.vibex.companion - -import kotlin.test.Test -import kotlin.test.assertEquals -import kotlin.test.assertFailsWith -import kotlin.test.assertTrue - -class PairingClientTest { - @Test - fun redeemStoresCompanionCredentialAndNegotiatesV1() { - val transport = ScriptedTransport( - listOf( - HttpExchange( - 201, - """{"device_id":"11111111-1111-1111-1111-111111111111","access_token":"device-token","scopes":["conversation.read","conversation.write","offline.read"]}""", - ), - HttpExchange( - 200, - """{"server_version":"0.1.3","protocol_version":"1.0","minimum_client_version":"1.0","capabilities":["conversation.attach"]}""", - ), - ), - ) - val session = PairingClient(transport).redeem( - HostOrigin.parse("http://127.0.0.1:17891"), - "one-time-secret", - "Pixel", - ) - assertEquals("device-token", session.credential.access_token) - assertEquals("1.0", session.capabilities.protocol_version) - assertEquals(2, transport.requests.size) - assertEquals("POST", transport.requests[0].method) - assertTrue(transport.requests[0].url.endsWith("/api/v1/auth/pairings/redeem")) - assertTrue(transport.requests[0].body!!.contains("\"pairing_token\":\"one-time-secret\"")) - assertEquals("GET", transport.requests[1].method) - assertEquals("Bearer device-token", transport.requests[1].headers["authorization"]) - } - - @Test - fun redeemRejectsWorkstationScopes() { - val transport = ScriptedTransport( - listOf( - HttpExchange( - 201, - """{"device_id":"11111111-1111-1111-1111-111111111111","access_token":"device-token","scopes":["conversation.read","plugin.write"]}""", - ), - ), - ) - val error = assertFailsWith { - PairingClient(transport).redeem( - HostOrigin.parse("https://host.example"), - "token", - ) - } - assertTrue(error.message!!.contains("plugin.write")) - } - - @Test - fun hostOriginRejectsCredentialsInUrl() { - assertFailsWith { - HostOrigin.parse("http://user:secret@127.0.0.1:17891") - } - } -} - -private data class RecordedRequest( - val method: String, - val url: String, - val headers: Map, - val body: String?, -) - -private class ScriptedTransport( - private val responses: List, -) : HttpTransport { - val requests = mutableListOf() - private var index = 0 - - override fun execute( - method: String, - url: String, - headers: Map, - body: String?, - ): HttpExchange { - requests += RecordedRequest(method, url, headers, body) - return responses[index++] - } -} diff --git a/mobile/android/gradle.properties b/mobile/android/gradle.properties deleted file mode 100644 index 96e300987..000000000 --- a/mobile/android/gradle.properties +++ /dev/null @@ -1,4 +0,0 @@ -org.gradle.jvmargs=-Xmx2g -Dfile.encoding=UTF-8 -android.useAndroidX=true -kotlin.code.style=official -org.gradle.parallel=true diff --git a/mobile/android/gradle/wrapper/gradle-wrapper.properties b/mobile/android/gradle/wrapper/gradle-wrapper.properties deleted file mode 100644 index e2847c820..000000000 --- a/mobile/android/gradle/wrapper/gradle-wrapper.properties +++ /dev/null @@ -1,7 +0,0 @@ -distributionBase=GRADLE_USER_HOME -distributionPath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-8.11.1-bin.zip -networkTimeout=10000 -validateDistributionUrl=true -zipStoreBase=GRADLE_USER_HOME -zipStorePath=wrapper/dists diff --git a/mobile/android/settings.gradle.kts b/mobile/android/settings.gradle.kts deleted file mode 100644 index 84700a867..000000000 --- a/mobile/android/settings.gradle.kts +++ /dev/null @@ -1,23 +0,0 @@ -pluginManagement { - repositories { - google() - mavenCentral() - gradlePluginPortal() - } -} - -dependencyResolutionManagement { - repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS) - repositories { - google() - mavenCentral() - } -} - -rootProject.name = "vibex-companion" -include(":companion-core") - -val androidHome = System.getenv("ANDROID_HOME") ?: System.getenv("ANDROID_SDK_ROOT") -if (!androidHome.isNullOrBlank()) { - include(":app") -} From 9f8ec933ae82ea696b805b9ba3b4978820c0c1c1 Mon Sep 17 00:00:00 2001 From: DorJay Date: Sun, 8 Nov 2026 21:28:04 +0800 Subject: [PATCH 2/6] chore(android): update mobile/android submodule to 1:1 iOS UI parity --- mobile/android | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/mobile/android b/mobile/android index cbd056ebb..65c2f6990 160000 --- a/mobile/android +++ b/mobile/android @@ -1 +1 @@ -Subproject commit cbd056ebb13559f3d5b537161ba238a72f87ad7b +Subproject commit 65c2f6990d5ae4e18e775cccefb33c138d199fe7 From fd7580df7f5209d64a1cc4274e0f2c1c5925c296 Mon Sep 17 00:00:00 2001 From: DorJay Date: Sun, 8 Nov 2026 21:53:08 +0800 Subject: [PATCH 3/6] chore(android): bump submodule with plugin.read scope fix --- mobile/android | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/mobile/android b/mobile/android index 65c2f6990..6c469b613 160000 --- a/mobile/android +++ b/mobile/android @@ -1 +1 @@ -Subproject commit 65c2f6990d5ae4e18e775cccefb33c138d199fe7 +Subproject commit 6c469b61380c5569ff1df19a697c80b0fd2fa102 From c08bf2cdcfdc6dece1846e3f7c0de85f9cc5e7b4 Mon Sep 17 00:00:00 2001 From: DorJay Date: Sun, 8 Nov 2026 22:24:45 +0800 Subject: [PATCH 4/6] chore(mobile): update android submodule with conversation timeline and initial prompt fix --- mobile/android | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/mobile/android b/mobile/android index 6c469b613..d265268de 160000 --- a/mobile/android +++ b/mobile/android @@ -1 +1 @@ -Subproject commit 6c469b61380c5569ff1df19a697c80b0fd2fa102 +Subproject commit d265268ded55cdbc020b61c4f2108d3f35ad29d7 From c5e58e2e0b6825e06853addcfb87964e3ec729bd Mon Sep 17 00:00:00 2001 From: DorJay Date: Mon, 9 Nov 2026 21:57:30 +0800 Subject: [PATCH 5/6] chore(mobile): update android submodule with 1:1 iOS components --- mobile/android | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/mobile/android b/mobile/android index d265268de..15e78881d 160000 --- a/mobile/android +++ b/mobile/android @@ -1 +1 @@ -Subproject commit d265268ded55cdbc020b61c4f2108d3f35ad29d7 +Subproject commit 15e78881d5a222bdd898474281e9d2636dd28a10 From cace2220fe2f9efae697998f5727891d45f13ae6 Mon Sep 17 00:00:00 2001 From: DorJay Date: Tue, 10 Nov 2026 03:32:06 +0800 Subject: [PATCH 6/6] feat: optimize remote connection experience, add cloud service support and end-to-end encryption --- Cargo.lock | 2 + ...000_webrtc_device_keys_and_idempotency.sql | 28 + ...20261109020000_device_connect_requests.sql | 16 + crates/remote-protocol/src/device_auth.rs | 53 + crates/remote-protocol/src/lib.rs | 13 +- crates/remote-protocol/src/webrtc.rs | 217 ++++ .../remote-protocol/tests/webrtc_protocol.rs | 177 ++++ crates/server/Cargo.toml | 2 + crates/server/src/auth.rs | 992 +++++++++++++++++- crates/server/src/e2ee.rs | 556 ++++++++++ crates/server/src/lib.rs | 8 +- crates/server/src/runtime.rs | 230 +++- crates/server/src/transport_session.rs | 529 ++++++++++ crates/server/src/ws.rs | 76 +- crates/server/tests/device_pairing.rs | 12 + .../tests/webrtc_security_and_session.rs | 653 ++++++++++++ crates/utils/src/net.rs | 512 ++++++++- crates/utils/src/tunnel.rs | 64 +- frontend/src/components/layout/IDELayout.tsx | 2 + .../layout/MobileDeviceConnectBanner.test.tsx | 73 ++ .../layout/MobileDeviceConnectBanner.tsx | 301 ++++++ frontend/src/i18n/locales/en/settings.json | 43 +- frontend/src/i18n/locales/zh-CN/settings.json | 45 +- frontend/src/lib/api/config.ts | 24 + frontend/src/lib/api/index.ts | 1 + .../settings/DevicePairingPanel.test.tsx | 4 +- .../src/pages/settings/DevicePairingPanel.tsx | 233 +++- .../pages/settings/HostTunnelPanel.test.tsx | 22 +- .../src/pages/settings/HostTunnelPanel.tsx | 247 +++-- .../settings/WebServiceSettings.test.tsx | 6 +- .../src/pages/settings/WebServiceSettings.tsx | 148 ++- mobile/android | 2 +- mobile/ios | 2 +- scripts/host-tunnel/test_public_ip.sh | 10 +- shared/hostCommands.ts | 2 + src-tauri/src/bin/generate_types.rs | 2 + src-tauri/src/commands/host_tunnel.rs | 651 +++++++++++- src-tauri/src/commands/web_service.rs | 45 +- src-tauri/src/host_client.rs | 3 + src-tauri/src/lib.rs | 2 + 40 files changed, 5670 insertions(+), 338 deletions(-) create mode 100644 crates/db/migrations/20261109010000_webrtc_device_keys_and_idempotency.sql create mode 100644 crates/db/migrations/20261109020000_device_connect_requests.sql create mode 100644 crates/remote-protocol/src/webrtc.rs create mode 100644 crates/remote-protocol/tests/webrtc_protocol.rs create mode 100644 crates/server/src/e2ee.rs create mode 100644 crates/server/src/transport_session.rs create mode 100644 crates/server/tests/webrtc_security_and_session.rs create mode 100644 frontend/src/components/layout/MobileDeviceConnectBanner.test.tsx create mode 100644 frontend/src/components/layout/MobileDeviceConnectBanner.tsx diff --git a/Cargo.lock b/Cargo.lock index 8acd2c0a5..ea66d749c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -5921,6 +5921,7 @@ dependencies = [ "futures", "git", "git2", + "hkdf", "ignore", "local-deployment", "plugins", @@ -5928,6 +5929,7 @@ dependencies = [ "regex", "remote-protocol", "reqwest 0.12.28", + "ring", "rustls", "serde", "serde_json", diff --git a/crates/db/migrations/20261109010000_webrtc_device_keys_and_idempotency.sql b/crates/db/migrations/20261109010000_webrtc_device_keys_and_idempotency.sql new file mode 100644 index 000000000..940e71988 --- /dev/null +++ b/crates/db/migrations/20261109010000_webrtc_device_keys_and_idempotency.sql @@ -0,0 +1,28 @@ +ALTER TABLE server_device_credentials + ADD COLUMN public_key_ed25519 TEXT; + +CREATE UNIQUE INDEX server_device_credentials_ed25519_active +ON server_device_credentials (public_key_ed25519) +WHERE public_key_ed25519 IS NOT NULL AND revoked_at_unix IS NULL; + +CREATE TABLE webrtc_signaling_nonces ( + session_nonce TEXT PRIMARY KEY NOT NULL, + sender_device_id TEXT NOT NULL, + expires_at_unix INTEGER NOT NULL +); + +CREATE INDEX webrtc_signaling_nonces_expiry +ON webrtc_signaling_nonces (expires_at_unix); + +CREATE TABLE companion_idempotency_ledger ( + credential_id TEXT NOT NULL, + operation_id TEXT NOT NULL, + command TEXT NOT NULL, + response_json TEXT NOT NULL, + created_at_unix INTEGER NOT NULL, + expires_at_unix INTEGER NOT NULL, + PRIMARY KEY (credential_id, operation_id) +); + +CREATE INDEX companion_idempotency_ledger_expiry +ON companion_idempotency_ledger (expires_at_unix); diff --git a/crates/db/migrations/20261109020000_device_connect_requests.sql b/crates/db/migrations/20261109020000_device_connect_requests.sql new file mode 100644 index 000000000..ecd83df4e --- /dev/null +++ b/crates/db/migrations/20261109020000_device_connect_requests.sql @@ -0,0 +1,16 @@ +CREATE TABLE IF NOT EXISTS server_device_connect_requests ( + id TEXT PRIMARY KEY NOT NULL, + device_name TEXT NOT NULL, + client_kind TEXT NOT NULL, + ip_address TEXT, + public_key_ed25519 TEXT, + sas_code TEXT NOT NULL, + status TEXT NOT NULL DEFAULT 'pending', + issued_credential_json TEXT, + created_at_unix INTEGER NOT NULL, + expires_at_unix INTEGER NOT NULL, + responded_at_unix INTEGER +); + +CREATE INDEX IF NOT EXISTS server_device_connect_requests_status_expiry +ON server_device_connect_requests (status, expires_at_unix); diff --git a/crates/remote-protocol/src/device_auth.rs b/crates/remote-protocol/src/device_auth.rs index 2880e3400..feb6e99a6 100644 --- a/crates/remote-protocol/src/device_auth.rs +++ b/crates/remote-protocol/src/device_auth.rs @@ -168,6 +168,12 @@ pub struct PairingChallenge { pub struct RedeemPairingRequest { pub pairing_token: String, pub device_name: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub public_key_ed25519: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub client_kind: Option, + #[serde(default)] + pub replace_existing_mobile: bool, } #[derive(Clone, Deserialize, Eq, JsonSchema, PartialEq, Serialize, TS)] @@ -182,3 +188,50 @@ pub struct RevokeDeviceResponse { pub device_id: DeviceId, pub revoked: bool, } + +#[derive(Clone, Debug, Default, Deserialize, Eq, JsonSchema, PartialEq, Serialize, TS)] +pub struct CreateDeviceConnectRequest { + pub device_name: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub client_kind: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub public_key_ed25519: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub session_nonce: Option, + #[serde(default)] + pub replace_existing_mobile: bool, +} + +#[derive(Clone, Copy, Debug, Deserialize, Eq, JsonSchema, PartialEq, Serialize, TS)] +#[serde(rename_all = "snake_case")] +pub enum DeviceConnectRequestStatus { + Pending, + Approved, + Rejected, + Expired, +} + +#[derive(Clone, Debug, Deserialize, Eq, JsonSchema, PartialEq, Serialize, TS)] +pub struct PendingDeviceConnectRequest { + pub request_id: PairingId, + pub device_name: String, + pub client_kind: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub ip_address: Option, + pub sas_code: String, + pub created_at: String, + pub expires_at: String, +} + +#[derive(Clone, Deserialize, Eq, JsonSchema, PartialEq, Serialize, TS)] +pub struct PollDeviceConnectResponse { + pub request_id: PairingId, + pub host_id: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub host_name: Option, + pub sas_code: String, + pub status: DeviceConnectRequestStatus, + pub expires_at: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub credential: Option, +} diff --git a/crates/remote-protocol/src/lib.rs b/crates/remote-protocol/src/lib.rs index b3b6c1c0c..33e6914f1 100644 --- a/crates/remote-protocol/src/lib.rs +++ b/crates/remote-protocol/src/lib.rs @@ -9,12 +9,14 @@ mod notification; mod pairing_invitation; mod schema; mod subscription; +mod webrtc; pub use capabilities::{CapabilityId, ServerCapabilities}; pub use command::{CommandRequest, CommandResponse}; pub use device_auth::{ - CreatePairingRequest, DeviceCredential, DeviceId, DevicePermissionPreset, PairingChallenge, - PairingId, RedeemPairingRequest, RevokeDeviceResponse, + CreateDeviceConnectRequest, CreatePairingRequest, DeviceConnectRequestStatus, DeviceCredential, + DeviceId, DevicePermissionPreset, PairingChallenge, PairingId, PendingDeviceConnectRequest, + PollDeviceConnectResponse, RedeemPairingRequest, RevokeDeviceResponse, }; pub use error::{ErrorCode, ErrorEnvelope}; pub use ids::{ConversationId, OperationId, SubscriptionId}; @@ -32,6 +34,13 @@ pub use subscription::{ SubscriptionClientMessage, SubscriptionRequest, SubscriptionResource, SubscriptionServerMessage, SubscriptionSnapshot, }; +pub use webrtc::{ + BULK_BUFFERED_HIGH_WATER_BYTES, BULK_BUFFERED_LOW_THRESHOLD_BYTES, BULK_CHANNEL_LABEL, + BULK_CHUNK_MAX_BYTES, BULK_CHUNK_MIN_BYTES, BulkChannelFrame, CHANNEL_BINDING_MAX_SKEW_SECONDS, + CHANNEL_BINDING_PREFIX, CONTROL_CHANNEL_LABEL, CONTROL_MAX_FRAME_BYTES, ChannelBindingClaims, + ControlChannelFrame, SIGNALING_PIGGYBACK_MAX_BYTES, SignalingPiggybackEvents, + SignalingResumeCursor, extract_sdp_sha256_fingerprint, +}; /// Remote protocol major/minor version implemented by this crate. pub const PROTOCOL_VERSION: &str = "1.0"; diff --git a/crates/remote-protocol/src/webrtc.rs b/crates/remote-protocol/src/webrtc.rs new file mode 100644 index 000000000..ee0071fcb --- /dev/null +++ b/crates/remote-protocol/src/webrtc.rs @@ -0,0 +1,217 @@ +use schemars::JsonSchema; +use serde::{Deserialize, Serialize}; +use ts_rs::TS; + +use crate::{ + CommandResponse, ConversationId, ErrorEnvelope, OperationId, RemoteEvent, + SubscriptionClientMessage, SubscriptionServerMessage, +}; + +pub const CONTROL_CHANNEL_LABEL: &str = "vibex.control.v1"; +pub const BULK_CHANNEL_LABEL: &str = "vibex.bulk.v1"; + +pub const CONTROL_MAX_FRAME_BYTES: usize = 64 * 1024; +pub const BULK_CHUNK_MIN_BYTES: usize = 16 * 1024; +pub const BULK_CHUNK_MAX_BYTES: usize = 32 * 1024; +pub const BULK_BUFFERED_LOW_THRESHOLD_BYTES: usize = 64 * 1024; +pub const BULK_BUFFERED_HIGH_WATER_BYTES: usize = 128 * 1024; +pub const SIGNALING_PIGGYBACK_MAX_BYTES: usize = 32 * 1024; + +pub const CHANNEL_BINDING_PREFIX: &str = "vibex-webrtc-v1"; +pub const CHANNEL_BINDING_MAX_SKEW_SECONDS: i64 = 60; + +/// Canonical claims bound to a WebRTC SDP offer/answer DTLS fingerprint and +/// signed with the sender's Ed25519 private key. +#[derive(Clone, Debug, Deserialize, Eq, JsonSchema, PartialEq, Serialize, TS)] +pub struct ChannelBindingClaims { + pub session_nonce: String, + pub sender_device_id: String, + pub recipient_device_id: String, + pub unix_timestamp: i64, + pub dtls_fingerprint: String, +} + +impl ChannelBindingClaims { + /// Canonical signing string: + /// `vibex-webrtc-v1|||||` + pub fn signing_input(&self) -> String { + format!( + "{}|{}|{}|{}|{}|{}", + CHANNEL_BINDING_PREFIX, + self.session_nonce, + self.sender_device_id, + self.recipient_device_id, + self.unix_timestamp, + self.dtls_fingerprint + ) + } +} + +/// Extracts and normalizes (uppercase colon-separated hex) the first +/// `a=fingerprint:sha-256 ` attribute from an SDP blob. +pub fn extract_sdp_sha256_fingerprint(sdp: &str) -> Option { + for raw_line in sdp.lines() { + let line = raw_line.trim(); + let Some(rest) = line.strip_prefix("a=fingerprint:") else { + continue; + }; + let mut parts = rest.split_whitespace(); + let Some(algo) = parts.next() else { + continue; + }; + if !algo.eq_ignore_ascii_case("sha-256") { + continue; + } + let Some(fingerprint) = parts.next() else { + continue; + }; + let normalized = fingerprint.trim().to_ascii_uppercase(); + if !normalized.is_empty() { + return Some(normalized); + } + } + None +} + +/// Optional resume cursor piggybacked onto a foreground-reconnect Signaling Offer. +#[derive(Clone, Debug, Deserialize, Eq, JsonSchema, PartialEq, Serialize, TS)] +pub struct SignalingResumeCursor { + pub conversation_id: ConversationId, + pub after_sequence: i64, +} + +/// Incremental events piggybacked onto a Signaling Answer when total serialized +/// size is `<= 32KB` (`SIGNALING_PIGGYBACK_MAX_BYTES`). +#[derive(Clone, Debug, Deserialize, JsonSchema, PartialEq, Serialize, TS)] +pub struct SignalingPiggybackEvents { + pub conversation_id: ConversationId, + pub events: Vec, + pub high_water_mark: i64, +} + +/// JSON envelope carried over the `vibex.control.v1` DataChannel. +#[derive(Clone, Debug, Deserialize, JsonSchema, PartialEq, Serialize, TS)] +#[serde(tag = "frame", rename_all = "snake_case")] +pub enum ControlChannelFrame { + RpcRequest { + operation_id: OperationId, + command: String, + #[serde(default)] + args: serde_json::Value, + }, + RpcResponse { + operation_id: OperationId, + status: u16, + data: serde_json::Value, + }, + RpcError { + operation_id: OperationId, + status: u16, + error: ErrorEnvelope, + }, + SubClient { + payload: SubscriptionClientMessage, + }, + SubServer { + payload: SubscriptionServerMessage, + }, + Ping { + timestamp_ms: i64, + }, + Pong { + timestamp_ms: i64, + }, + Suspend, +} + +impl ControlChannelFrame { + pub fn from_command_response( + status: u16, + response: CommandResponse, + ) -> Self { + Self::RpcResponse { + operation_id: response.operation_id, + status, + data: response.data, + } + } +} + +/// Chunked envelope carried over the `vibex.bulk.v1` DataChannel (`16KB ~ 32KB` per chunk). +#[derive(Clone, Debug, Deserialize, Eq, JsonSchema, PartialEq, Serialize, TS)] +#[serde(tag = "frame", rename_all = "snake_case")] +pub enum BulkChannelFrame { + BulkStart { + operation_id: OperationId, + content_type: String, + total_bytes: usize, + total_chunks: usize, + }, + BulkChunk { + operation_id: OperationId, + chunk_index: usize, + data_base64: String, + }, + BulkEnd { + operation_id: OperationId, + }, + BulkCancel { + operation_id: OperationId, + }, +} + +impl BulkChannelFrame { + pub fn chunk_payload( + operation_id: OperationId, + content_type: impl Into, + payload: &[u8], + max_chunk_bytes: usize, + ) -> Vec { + let chunk_size = max_chunk_bytes.clamp(1, BULK_CHUNK_MAX_BYTES); + let chunks: Vec<&[u8]> = if payload.is_empty() { + Vec::new() + } else { + payload.chunks(chunk_size).collect() + }; + let mut frames = Vec::with_capacity(chunks.len() + 2); + frames.push(Self::BulkStart { + operation_id, + content_type: content_type.into(), + total_bytes: payload.len(), + total_chunks: chunks.len(), + }); + for (chunk_index, chunk) in chunks.into_iter().enumerate() { + frames.push(Self::BulkChunk { + operation_id, + chunk_index, + data_base64: encode_base64(chunk), + }); + } + frames.push(Self::BulkEnd { operation_id }); + frames + } +} + +fn encode_base64(input: &[u8]) -> String { + const TABLE: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; + let mut out = String::with_capacity(input.len().div_ceil(3) * 4); + for chunk in input.chunks(3) { + let b0 = chunk[0] as u32; + let b1 = if chunk.len() > 1 { chunk[1] as u32 } else { 0 }; + let b2 = if chunk.len() > 2 { chunk[2] as u32 } else { 0 }; + let triple = (b0 << 16) | (b1 << 8) | b2; + out.push(TABLE[((triple >> 18) & 0x3f) as usize] as char); + out.push(TABLE[((triple >> 12) & 0x3f) as usize] as char); + if chunk.len() > 1 { + out.push(TABLE[((triple >> 6) & 0x3f) as usize] as char); + } else { + out.push('='); + } + if chunk.len() > 2 { + out.push(TABLE[(triple & 0x3f) as usize] as char); + } else { + out.push('='); + } + } + out +} diff --git a/crates/remote-protocol/tests/webrtc_protocol.rs b/crates/remote-protocol/tests/webrtc_protocol.rs new file mode 100644 index 000000000..bdec5c1b4 --- /dev/null +++ b/crates/remote-protocol/tests/webrtc_protocol.rs @@ -0,0 +1,177 @@ +use remote_protocol::{ + BULK_CHANNEL_LABEL, BULK_CHUNK_MAX_BYTES, BulkChannelFrame, CONTROL_CHANNEL_LABEL, + ChannelBindingClaims, CommandResponse, ControlChannelFrame, ConversationId, ErrorCode, + ErrorEnvelope, OperationId, RedeemPairingRequest, RemoteEvent, SubscriptionClientMessage, + SubscriptionId, SubscriptionRequest, SubscriptionResource, SubscriptionServerMessage, + extract_sdp_sha256_fingerprint, +}; +use serde_json::json; +use uuid::Uuid; + +#[test] +fn channel_binding_claims_format_canonical_signing_input_and_extract_sdp_fingerprint() { + let sdp = concat!( + "v=0\r\n", + "o=- 4611731400430051336 2 IN IP4 127.0.0.1\r\n", + "s=-\r\n", + "t=0 0\r\n", + "a=fingerprint:sha-256 aa:bb:cc:dd:ee:ff:00:11:22:33:44:55:66:77:88:99:aa:bb:cc:dd:ee:ff:00:11:22:33:44:55:66:77:88:99\r\n", + ); + let fingerprint = extract_sdp_sha256_fingerprint(sdp).expect("extract sha-256 fingerprint"); + assert_eq!( + fingerprint, + "AA:BB:CC:DD:EE:FF:00:11:22:33:44:55:66:77:88:99:AA:BB:CC:DD:EE:FF:00:11:22:33:44:55:66:77:88:99" + ); + + let claims = ChannelBindingClaims { + session_nonce: "nonce-01930c8a".to_owned(), + sender_device_id: "dev-phone-1".to_owned(), + recipient_device_id: "host-mac-1".to_owned(), + unix_timestamp: 1_762_660_000, + dtls_fingerprint: fingerprint.clone(), + }; + assert_eq!( + claims.signing_input(), + format!("vibex-webrtc-v1|nonce-01930c8a|dev-phone-1|host-mac-1|1762660000|{fingerprint}") + ); +} + +#[test] +fn control_channel_frames_round_trip_spec_envelopes() { + assert_eq!(CONTROL_CHANNEL_LABEL, "vibex.control.v1"); + assert_eq!(BULK_CHANNEL_LABEL, "vibex.bulk.v1"); + + let op_id = OperationId::from_uuid( + Uuid::parse_str("01930c8a-7b12-7000-8000-000000000001").expect("uuid"), + ); + let req_frame = ControlChannelFrame::RpcRequest { + operation_id: op_id, + command: "conversation_input_submit".to_owned(), + args: json!({ + "request": { + "conversationId": "c8b6d31f-0000-4000-8000-000000000000", + "payload": { + "agentId": "claude_code", + "workspaceId": "w1", + "text": "帮我检查一下单元测试" + } + } + }), + }; + let serialized = serde_json::to_value(&req_frame).expect("serialize rpc_request"); + assert_eq!(serialized["frame"], "rpc_request"); + assert_eq!( + serialized["operation_id"], + "01930c8a-7b12-7000-8000-000000000001" + ); + assert_eq!(serialized["command"], "conversation_input_submit"); + let decoded: ControlChannelFrame = + serde_json::from_value(serialized).expect("deserialize rpc_request"); + assert_eq!(decoded, req_frame); + + let resp_frame = ControlChannelFrame::from_command_response( + 200, + CommandResponse::new(op_id, json!({ "accepted": true })), + ); + let resp_json = serde_json::to_value(&resp_frame).expect("serialize rpc_response"); + assert_eq!(resp_json["frame"], "rpc_response"); + assert_eq!(resp_json["status"], 200); + assert_eq!(resp_json["data"]["accepted"], true); + + let err_frame = ControlChannelFrame::RpcError { + operation_id: op_id, + status: 409, + error: ErrorEnvelope::new( + ErrorCode::Conflict, + "turn has already completed", + false, + op_id, + ), + }; + let err_json = serde_json::to_value(&err_frame).expect("serialize rpc_error"); + assert_eq!(err_json["frame"], "rpc_error"); + assert_eq!(err_json["status"], 409); + + let sub_id = SubscriptionId::from_uuid( + Uuid::parse_str("01930c8a-7b12-7000-8000-000000000010").expect("sub uuid"), + ); + let conv_id = ConversationId::parse("c8b6d31f-0000-4000-8000-000000000000").expect("conv id"); + let sub_client = ControlChannelFrame::SubClient { + payload: SubscriptionClientMessage::Attach { + request: SubscriptionRequest { + subscription_id: sub_id, + resource: SubscriptionResource::Conversation { + conversation_id: conv_id, + after_sequence: 142, + }, + }, + }, + }; + let sub_client_json = serde_json::to_value(&sub_client).expect("serialize sub_client"); + assert_eq!(sub_client_json["frame"], "sub_client"); + assert_eq!(sub_client_json["payload"]["type"], "attach"); + assert_eq!(sub_client_json["payload"]["request"]["after_sequence"], 142); + + let sub_server = ControlChannelFrame::SubServer { + payload: SubscriptionServerMessage::Event { + subscription_id: sub_id, + event: RemoteEvent { + sequence: 143, + kind: "assistant_text_delta".to_owned(), + payload: json!({ "delta": "hello" }), + }, + }, + }; + let sub_server_json = serde_json::to_value(&sub_server).expect("serialize sub_server"); + assert_eq!(sub_server_json["frame"], "sub_server"); + assert_eq!(sub_server_json["payload"]["type"], "event"); + assert_eq!(sub_server_json["payload"]["event"]["sequence"], 143); +} + +#[test] +fn bulk_channel_splits_payload_into_bounded_chunks_and_supports_cancel() { + let op_id = OperationId::new(); + let payload = vec![b'x'; BULK_CHUNK_MAX_BYTES * 2 + 123]; + let frames = + BulkChannelFrame::chunk_payload(op_id, "application/json", &payload, BULK_CHUNK_MAX_BYTES); + assert_eq!(frames.len(), 5); // start + 3 chunks + end + assert!(matches!( + frames.first(), + Some(BulkChannelFrame::BulkStart { + total_bytes, + total_chunks: 3, + .. + }) if *total_bytes == payload.len() + )); + assert!(matches!( + frames.last(), + Some(BulkChannelFrame::BulkEnd { .. }) + )); + + let cancel = BulkChannelFrame::BulkCancel { + operation_id: op_id, + }; + let cancel_json = serde_json::to_value(&cancel).expect("serialize bulk_cancel"); + assert_eq!(cancel_json["frame"], "bulk_cancel"); +} + +#[test] +fn redeem_pairing_request_accepts_optional_ed25519_public_key() { + let without_key: RedeemPairingRequest = serde_json::from_value(json!({ + "pairing_token": "ABCD-EFGH", + "device_name": "Pixel 9" + })) + .expect("deserialize without key"); + assert_eq!(without_key.public_key_ed25519, None); + + let with_key: RedeemPairingRequest = serde_json::from_value(json!({ + "pairing_token": "ABCD-EFGH", + "device_name": "Pixel 9", + "public_key_ed25519": "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=" + })) + .expect("deserialize with key"); + assert_eq!( + with_key.public_key_ed25519.as_deref(), + Some("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=") + ); +} diff --git a/crates/server/Cargo.toml b/crates/server/Cargo.toml index 182b28f16..487e96189 100644 --- a/crates/server/Cargo.toml +++ b/crates/server/Cargo.toml @@ -24,6 +24,7 @@ executors = { path = "../executors" } futures = { workspace = true } git = { path = "../git" } git2 = { workspace = true } +hkdf = "0.12" ignore = "0.4" local-deployment = { path = "../local-deployment" } prost = "0.13" @@ -31,6 +32,7 @@ plugins = { path = "../plugins" } remote-protocol = { path = "../remote-protocol" } regex = { workspace = true } reqwest = { workspace = true } +ring = "0.17" rustls = { workspace = true } serde = { workspace = true } serde_json = { workspace = true } diff --git a/crates/server/src/auth.rs b/crates/server/src/auth.rs index 6e75b7a91..0ad840da9 100644 --- a/crates/server/src/auth.rs +++ b/crates/server/src/auth.rs @@ -7,12 +7,17 @@ use std::{ use application::Principal; use async_trait::async_trait; +use base64::{Engine as _, engine::general_purpose::STANDARD as BASE64}; use chrono::{DateTime, Utc}; +use hkdf::Hkdf; use remote_protocol::{ - CreatePairingRequest, DeviceCredential, DeviceId, DevicePermissionPreset, - PAIRING_TTL_DEFAULT_SECONDS, PairingChallenge, PairingId, RedeemPairingRequest, + CHANNEL_BINDING_MAX_SKEW_SECONDS, ChannelBindingClaims, CreateDeviceConnectRequest, + CreatePairingRequest, DeviceConnectRequestStatus, DeviceCredential, DeviceId, + DevicePermissionPreset, PAIRING_TTL_DEFAULT_SECONDS, PairingChallenge, PairingId, + PendingDeviceConnectRequest, PollDeviceConnectResponse, RedeemPairingRequest, RevokeDeviceResponse, resolve_pairing_ttl_seconds, }; +use ring::signature::{ED25519, UnparsedPublicKey}; use serde::{Deserialize, Serialize}; use sha2::{Digest, Sha256}; use sqlx::{Row, SqlitePool}; @@ -166,6 +171,67 @@ pub struct PairedDeviceRecord { pub ip_address: Option, #[serde(default)] pub last_connected_at: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub public_key_ed25519: Option, +} + +#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)] +pub struct TrustWebRtcDeviceRequest { + pub device_id: DeviceId, + pub device_name: String, + pub public_key_ed25519: String, + pub preset: DevicePermissionPreset, +} + +/// Derives the 4-digit decimal Short Authentication String (SAS) from both +/// peers' Ed25519 public keys and the `session_nonce` via HKDF-SHA256. +pub fn compute_sas_code( + host_pub_ed25519: &[u8; 32], + device_pub_ed25519: &[u8; 32], + session_nonce: &str, +) -> String { + let mut ikm = [0u8; 64]; + ikm[..32].copy_from_slice(host_pub_ed25519); + ikm[32..].copy_from_slice(device_pub_ed25519); + let hk = Hkdf::::new(Some(session_nonce.as_bytes()), &ikm); + let mut okm = [0u8; 2]; + hk.expand(b"vibex-webrtc-sas-v1", &mut okm) + .expect("2-byte HKDF expansion never exceeds max length"); + let code = u16::from_be_bytes(okm) % 10_000; + format!("{code:04}") +} + +/// Verifies that the DTLS peer certificate SHA-256 fingerprint from the active +/// WebRTC transport matches the `` signed in the signaling offer/answer. +pub fn verify_peer_dtls_fingerprint( + expected_signed_fingerprint: &str, + peer_cert_fingerprint: &str, +) -> bool { + let expected = expected_signed_fingerprint.trim().to_ascii_uppercase(); + let actual = peer_cert_fingerprint.trim().to_ascii_uppercase(); + if expected.is_empty() || expected.len() != actual.len() { + return false; + } + expected + .bytes() + .zip(actual.bytes()) + .fold(0_u8, |diff, (a, b)| diff | (a ^ b)) + == 0 +} + +fn parse_ed25519_public_key(raw: &str) -> Result<([u8; 32], String), AuthStoreError> { + let trimmed = raw.trim(); + if trimmed.is_empty() { + return Err(AuthStoreError::InvalidPublicKey); + } + let decoded = BASE64 + .decode(trimmed) + .or_else(|_| base64::engine::general_purpose::URL_SAFE_NO_PAD.decode(trimmed)) + .map_err(|_| AuthStoreError::InvalidPublicKey)?; + let bytes: [u8; 32] = decoded + .try_into() + .map_err(|_| AuthStoreError::InvalidPublicKey)?; + Ok((bytes, BASE64.encode(bytes))) } #[derive(Clone, Debug, Eq, PartialEq)] @@ -236,12 +302,27 @@ pub enum AuthStoreError { PairingRedeemed, #[error("device name is invalid")] InvalidDeviceName, + #[error("device Ed25519 public key is invalid")] + InvalidPublicKey, + #[error("channel binding signature is invalid")] + InvalidChannelBindingSignature, + #[error("channel binding recipient host_id does not match")] + ChannelBindingRecipientMismatch, + #[error("channel binding timestamp is outside the allowed 60s window")] + ChannelBindingTimestampSkew, + #[error("channel binding session_nonce was already used")] + ChannelBindingReplay, #[error("device credential was not found")] DeviceNotFound, #[error("credential lacks the required scope")] Forbidden, #[error("device pairing is unavailable for this server composition")] PairingUnavailable, + #[error("another mobile device ({existing_device_name}) is already connected to this computer")] + MobileDeviceConflict { + existing_device_id: DeviceId, + existing_device_name: String, + }, } pub trait AuthClock: Send + Sync { @@ -299,6 +380,39 @@ pub trait ServerAuth: Send + Sync { ) -> Result<(), AuthStoreError> { Ok(()) } + + async fn create_connect_request( + &self, + _host_id: &str, + _request: CreateDeviceConnectRequest, + _ip_address: Option<&str>, + ) -> Result { + Err(AuthStoreError::PairingUnavailable) + } + + async fn poll_connect_request( + &self, + _host_id: &str, + _request_id: PairingId, + ) -> Result { + Err(AuthStoreError::PairingUnavailable) + } + + async fn list_connect_requests( + &self, + _actor: &AuthenticatedCredential, + ) -> Result, AuthStoreError> { + Err(AuthStoreError::PairingUnavailable) + } + + async fn respond_connect_request( + &self, + _actor: &AuthenticatedCredential, + _request_id: PairingId, + _approve: bool, + ) -> Result<(), AuthStoreError> { + Err(AuthStoreError::PairingUnavailable) + } } pub(crate) struct StaticServerAuth { @@ -407,15 +521,18 @@ impl ServerAuth for SqliteServerAuth { candidate: &str, ) -> Result, AuthStoreError> { let digest = TokenDigest::from_secret(candidate); - if let Some(row) = sqlx::query( - "SELECT lower(hex(id)) AS id_key, scopes_json - FROM server_access_tokens - WHERE token_hash = ? AND revoked_at IS NULL - LIMIT 1", - ) - .bind(digest.as_bytes().as_slice()) - .fetch_optional(&self.pool) - .await? + let prefer_device = candidate.starts_with("vbx_device_"); + + if !prefer_device + && let Some(row) = sqlx::query( + "SELECT lower(hex(id)) AS id_key, scopes_json + FROM server_access_tokens + WHERE token_hash = ? AND revoked_at IS NULL + LIMIT 1", + ) + .bind(digest.as_bytes().as_slice()) + .fetch_optional(&self.pool) + .await? { return Ok(Some(AuthenticatedCredential { credential_id: row.try_get("id_key")?, @@ -426,7 +543,7 @@ impl ServerAuth for SqliteServerAuth { })); } - let Some(row) = sqlx::query( + if let Some(row) = sqlx::query( "SELECT id, device_name, scopes_json FROM server_device_credentials WHERE token_hash = ? AND revoked_at_unix IS NULL @@ -435,20 +552,41 @@ impl ServerAuth for SqliteServerAuth { .bind(digest.as_bytes().as_slice()) .fetch_optional(&self.pool) .await? - else { - return Ok(None); - }; - let id: String = row.try_get("id")?; - let device_id = id - .parse() - .map_err(|error| sqlx::Error::Protocol(format!("invalid device id: {error}")))?; - Ok(Some(AuthenticatedCredential { - credential_id: id, - kind: CredentialKind::Device, - subject: format!("device:{}", row.try_get::("device_name")?), - device_id: Some(device_id), - scopes: parse_scopes(row.try_get("scopes_json")?)?, - })) + { + let id: String = row.try_get("id")?; + let device_id = id + .parse() + .map_err(|error| sqlx::Error::Protocol(format!("invalid device id: {error}")))?; + return Ok(Some(AuthenticatedCredential { + credential_id: id, + kind: CredentialKind::Device, + subject: format!("device:{}", row.try_get::("device_name")?), + device_id: Some(device_id), + scopes: parse_scopes(row.try_get("scopes_json")?)?, + })); + } + + if prefer_device + && let Some(row) = sqlx::query( + "SELECT lower(hex(id)) AS id_key, scopes_json + FROM server_access_tokens + WHERE token_hash = ? AND revoked_at IS NULL + LIMIT 1", + ) + .bind(digest.as_bytes().as_slice()) + .fetch_optional(&self.pool) + .await? + { + return Ok(Some(AuthenticatedCredential { + credential_id: row.try_get("id_key")?, + kind: CredentialKind::Server, + subject: "server-token".to_owned(), + device_id: None, + scopes: parse_scopes(row.try_get("scopes_json")?)?, + })); + } + + Ok(None) } async fn is_active( @@ -571,6 +709,35 @@ impl ServerAuth for SqliteServerAuth { serde_json::from_str(row.try_get("scopes_json")?).map_err(|error| { sqlx::Error::Protocol(format!("invalid pairing scopes: {error}")) })?; + let preset = infer_preset(&scopes); + let client_kind = request + .client_kind + .as_deref() + .map(str::trim) + .filter(|v| !v.is_empty()) + .map(ToOwned::to_owned) + .unwrap_or_else(|| infer_client_kind(device_name, preset, None, false)); + let canonical_pubkey = match request.public_key_ed25519.as_deref() { + Some(raw) => Some(parse_ed25519_public_key(raw)?.1), + None => None, + }; + + if client_kind == "mobile" && !request.replace_existing_mobile { + if let Some((existing_device_id, existing_device_name)) = + find_conflicting_mobile_device( + &mut *connection, + device_name, + canonical_pubkey.as_deref(), + ) + .await? + { + return Err(AuthStoreError::MobileDeviceConflict { + existing_device_id, + existing_device_name, + }); + } + } + let claimed = sqlx::query( "UPDATE server_pairing_challenges SET redeemed_at_unix = ? @@ -592,12 +759,24 @@ impl ServerAuth for SqliteServerAuth { Uuid::new_v4().simple() ); let device_digest = TokenDigest::from_secret(&access_token); - let preset = infer_preset(&scopes); - let client_kind = infer_client_kind(device_name, preset, None, false); + if client_kind == "mobile" { + revoke_all_active_mobile_devices(&mut *connection, now).await?; + } else if let Some(ref pubkey) = canonical_pubkey { + sqlx::query( + "UPDATE server_device_credentials + SET revoked_at_unix = ? + WHERE public_key_ed25519 = ? AND revoked_at_unix IS NULL", + ) + .bind(now) + .bind(pubkey) + .execute(&mut *connection) + .await?; + } sqlx::query( "INSERT INTO server_device_credentials - (id, token_hash, device_name, scopes_json, created_at_unix, client_kind, last_connected_at_unix) - VALUES (?, ?, ?, ?, ?, ?, ?)", + (id, token_hash, device_name, scopes_json, created_at_unix, client_kind, + last_connected_at_unix, public_key_ed25519) + VALUES (?, ?, ?, ?, ?, ?, ?, ?)", ) .bind(device_id.to_string()) .bind(device_digest.as_bytes().as_slice()) @@ -606,6 +785,7 @@ impl ServerAuth for SqliteServerAuth { .bind(now) .bind(&client_kind) .bind(now) + .bind(canonical_pubkey) .execute(&mut *connection) .await?; sqlx::query( @@ -689,7 +869,7 @@ impl ServerAuth for SqliteServerAuth { } let rows = sqlx::query( "SELECT id, device_name, scopes_json, created_at_unix, - client_kind, last_ip, last_connected_at_unix + client_kind, last_ip, last_connected_at_unix, public_key_ed25519 FROM server_device_credentials WHERE revoked_at_unix IS NULL ORDER BY COALESCE(last_connected_at_unix, created_at_unix) DESC, created_at_unix DESC", @@ -720,6 +900,11 @@ impl ServerAuth for SqliteServerAuth { .filter(|value| !value.trim().is_empty()); let last_connected_at_unix: Option = row.try_get("last_connected_at_unix").ok().flatten(); + let public_key_ed25519: Option = row + .try_get::, _>("public_key_ed25519") + .ok() + .flatten() + .filter(|value| !value.trim().is_empty()); devices.push(PairedDeviceRecord { device_id, device_name, @@ -731,6 +916,7 @@ impl ServerAuth for SqliteServerAuth { last_connected_at: Some(unix_timestamp( last_connected_at_unix.unwrap_or(created_at_unix), )), + public_key_ed25519, }); } Ok(devices) @@ -758,6 +944,639 @@ impl ServerAuth for SqliteServerAuth { .await?; Ok(()) } + + async fn create_connect_request( + &self, + host_id: &str, + request: CreateDeviceConnectRequest, + ip_address: Option<&str>, + ) -> Result { + let device_name = request.device_name.trim(); + if device_name.is_empty() || device_name.len() > 128 { + return Err(AuthStoreError::InvalidDeviceName); + } + let parsed_pubkey = match request + .public_key_ed25519 + .as_deref() + .filter(|v| !v.trim().is_empty()) + { + Some(raw) => Some(parse_ed25519_public_key(raw)?), + None => None, + }; + let client_kind = request + .client_kind + .as_deref() + .map(str::trim) + .filter(|v| !v.is_empty()) + .map(ToOwned::to_owned) + .unwrap_or_else(|| { + infer_client_kind( + device_name, + Some(DevicePermissionPreset::Companion), + None, + false, + ) + }); + + let now = self.now(); + let expires_at = now.saturating_add(180); + let host_name = utils::net::local_hostname(); + let incoming_pk = parsed_pubkey.as_ref().map(|(_, pk)| pk.as_str()); + + if client_kind == "mobile" { + let mut conn = self.pool.acquire().await?; + if request.replace_existing_mobile { + revoke_all_active_mobile_devices(&mut *conn, now).await?; + } else if let Some((existing_device_id, existing_device_name)) = + find_conflicting_mobile_device(&mut *conn, device_name, incoming_pk).await? + { + return Err(AuthStoreError::MobileDeviceConflict { + existing_device_id, + existing_device_name, + }); + } + } + + let existing_pending = if let Some((_, ref canonical_pk)) = parsed_pubkey { + sqlx::query( + "SELECT id, sas_code + FROM server_device_connect_requests + WHERE public_key_ed25519 = ? AND status = 'pending' AND expires_at_unix > ? + ORDER BY created_at_unix DESC + LIMIT 1", + ) + .bind(canonical_pk) + .bind(now) + .fetch_optional(&self.pool) + .await? + } else { + sqlx::query( + "SELECT id, sas_code + FROM server_device_connect_requests + WHERE public_key_ed25519 IS NULL AND device_name = ? AND status = 'pending' AND expires_at_unix > ? + ORDER BY created_at_unix DESC + LIMIT 1", + ) + .bind(device_name) + .bind(now) + .fetch_optional(&self.pool) + .await? + }; + + if let Some(existing) = existing_pending { + let id_str: String = existing.try_get("id")?; + let sas_code: String = existing.try_get("sas_code")?; + if let Ok(request_id) = id_str.parse::() { + sqlx::query( + "UPDATE server_device_connect_requests + SET device_name = ?, ip_address = COALESCE(?, ip_address), expires_at_unix = ? + WHERE id = ?", + ) + .bind(device_name) + .bind(ip_address) + .bind(expires_at) + .bind(&id_str) + .execute(&self.pool) + .await?; + return Ok(PollDeviceConnectResponse { + request_id, + host_id: host_id.to_owned(), + host_name, + sas_code, + status: DeviceConnectRequestStatus::Pending, + expires_at: unix_timestamp(expires_at), + credential: None, + }); + } + } + + let request_id = PairingId::new(); + let request_id_str = request_id.to_string(); + let host_bytes: [u8; 32] = Sha256::digest(host_id.as_bytes()).into(); + let device_bytes: [u8; 32] = match parsed_pubkey { + Some((bytes, _)) => bytes, + None => Sha256::digest(device_name.as_bytes()).into(), + }; + let nonce = request + .session_nonce + .as_deref() + .map(str::trim) + .filter(|v| !v.is_empty()) + .unwrap_or(&request_id_str); + let sas_code = compute_sas_code(&host_bytes, &device_bytes, nonce); + let canonical_pubkey = parsed_pubkey.map(|(_, pk)| pk); + + sqlx::query( + "INSERT INTO server_device_connect_requests + (id, device_name, client_kind, ip_address, public_key_ed25519, sas_code, + status, created_at_unix, expires_at_unix) + VALUES (?, ?, ?, ?, ?, ?, 'pending', ?, ?)", + ) + .bind(&request_id_str) + .bind(device_name) + .bind(&client_kind) + .bind(ip_address) + .bind(canonical_pubkey) + .bind(&sas_code) + .bind(now) + .bind(expires_at) + .execute(&self.pool) + .await?; + + Ok(PollDeviceConnectResponse { + request_id, + host_id: host_id.to_owned(), + host_name, + sas_code, + status: DeviceConnectRequestStatus::Pending, + expires_at: unix_timestamp(expires_at), + credential: None, + }) + } + + async fn poll_connect_request( + &self, + host_id: &str, + request_id: PairingId, + ) -> Result { + let now = self.now(); + let id_str = request_id.to_string(); + let Some(row) = sqlx::query( + "SELECT sas_code, status, issued_credential_json, expires_at_unix + FROM server_device_connect_requests + WHERE id = ? + LIMIT 1", + ) + .bind(&id_str) + .fetch_optional(&self.pool) + .await? + else { + return Err(AuthStoreError::InvalidPairing); + }; + + let sas_code: String = row.try_get("sas_code")?; + let raw_status: String = row.try_get("status")?; + let expires_at_unix: i64 = row.try_get("expires_at_unix")?; + let issued_json: Option = row.try_get("issued_credential_json")?; + + let status = match raw_status.as_str() { + "approved" => DeviceConnectRequestStatus::Approved, + "rejected" => DeviceConnectRequestStatus::Rejected, + _ if expires_at_unix <= now => DeviceConnectRequestStatus::Expired, + _ => DeviceConnectRequestStatus::Pending, + }; + + let credential = if status == DeviceConnectRequestStatus::Approved { + if let Some(json_str) = issued_json { + let parsed = serde_json::from_str::(&json_str).ok(); + if parsed.is_some() { + sqlx::query( + "UPDATE server_device_connect_requests + SET issued_credential_json = NULL + WHERE id = ?", + ) + .bind(&id_str) + .execute(&self.pool) + .await?; + } + parsed + } else { + None + } + } else { + None + }; + + Ok(PollDeviceConnectResponse { + request_id, + host_id: host_id.to_owned(), + host_name: utils::net::local_hostname(), + sas_code, + status, + expires_at: unix_timestamp(expires_at_unix), + credential, + }) + } + + async fn list_connect_requests( + &self, + actor: &AuthenticatedCredential, + ) -> Result, AuthStoreError> { + if !actor.allows("device.pair") { + return Err(AuthStoreError::Forbidden); + } + let now = self.now(); + let rows = sqlx::query( + "SELECT id, device_name, client_kind, ip_address, sas_code, created_at_unix, expires_at_unix + FROM server_device_connect_requests + WHERE status = 'pending' AND expires_at_unix > ? + ORDER BY created_at_unix DESC", + ) + .bind(now) + .fetch_all(&self.pool) + .await?; + + let mut items = Vec::with_capacity(rows.len()); + for row in rows { + let id_str: String = row.try_get("id")?; + let Ok(request_id) = id_str.parse::() else { + continue; + }; + let created_at_unix: i64 = row.try_get("created_at_unix")?; + let expires_at_unix: i64 = row.try_get("expires_at_unix")?; + items.push(PendingDeviceConnectRequest { + request_id, + device_name: row.try_get("device_name")?, + client_kind: row.try_get("client_kind")?, + ip_address: row + .try_get::, _>("ip_address") + .ok() + .flatten() + .filter(|v| !v.trim().is_empty()), + sas_code: row.try_get("sas_code")?, + created_at: unix_timestamp(created_at_unix), + expires_at: unix_timestamp(expires_at_unix), + }); + } + Ok(items) + } + + async fn respond_connect_request( + &self, + actor: &AuthenticatedCredential, + request_id: PairingId, + approve: bool, + ) -> Result<(), AuthStoreError> { + if !actor.allows("device.pair") { + return Err(AuthStoreError::Forbidden); + } + let now = self.now(); + let id_str = request_id.to_string(); + + if !approve { + let updated = sqlx::query( + "UPDATE server_device_connect_requests + SET status = 'rejected', responded_at_unix = ? + WHERE id = ? AND status = 'pending'", + ) + .bind(now) + .bind(&id_str) + .execute(&self.pool) + .await?; + if updated.rows_affected() == 0 { + return Err(AuthStoreError::InvalidPairing); + } + return Ok(()); + } + + let mut connection = self.pool.acquire().await?; + sqlx::query("BEGIN IMMEDIATE") + .execute(&mut *connection) + .await?; + let result: Result<(), AuthStoreError> = async { + let Some(row) = sqlx::query( + "SELECT device_name, client_kind, ip_address, public_key_ed25519, status, expires_at_unix + FROM server_device_connect_requests + WHERE id = ? + LIMIT 1", + ) + .bind(&id_str) + .fetch_optional(&mut *connection) + .await? + else { + return Err(AuthStoreError::InvalidPairing); + }; + + let status: String = row.try_get("status")?; + let expires_at_unix: i64 = row.try_get("expires_at_unix")?; + if status != "pending" { + return Err(AuthStoreError::PairingRedeemed); + } + if expires_at_unix <= now { + return Err(AuthStoreError::PairingExpired); + } + + let device_name: String = row.try_get("device_name")?; + let client_kind: String = row.try_get("client_kind")?; + let ip_address: Option = row.try_get("ip_address")?; + let public_key_ed25519: Option = row.try_get("public_key_ed25519")?; + + let preset = if client_kind == "mobile" { + DevicePermissionPreset::Companion + } else { + DevicePermissionPreset::Workstation + }; + let scopes = resolve_pairing_scopes( + &actor.scopes, + CreatePairingRequest { + preset: Some(preset), + requested_scopes: Vec::new(), + ttl_seconds: None, + }, + )?; + let device_id = DeviceId::new(); + let access_token = format!( + "vbx_device_{}{}", + Uuid::new_v4().simple(), + Uuid::new_v4().simple() + ); + let device_digest = TokenDigest::from_secret(&access_token); + + if client_kind == "mobile" { + revoke_all_active_mobile_devices(&mut *connection, now).await?; + } else if let Some(ref pubkey) = public_key_ed25519 { + sqlx::query( + "UPDATE server_device_credentials + SET revoked_at_unix = ? + WHERE public_key_ed25519 = ? AND revoked_at_unix IS NULL", + ) + .bind(now) + .bind(pubkey) + .execute(&mut *connection) + .await?; + } + + sqlx::query( + "INSERT INTO server_device_credentials + (id, token_hash, device_name, scopes_json, created_at_unix, client_kind, + last_ip, last_connected_at_unix, public_key_ed25519) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)", + ) + .bind(device_id.to_string()) + .bind(device_digest.as_bytes().as_slice()) + .bind(&device_name) + .bind(serde_json::to_string(&scopes).expect("scopes serialize")) + .bind(now) + .bind(&client_kind) + .bind(ip_address) + .bind(now) + .bind(&public_key_ed25519) + .execute(&mut *connection) + .await?; + + let credential = DeviceCredential { + device_id, + access_token, + scopes, + }; + let credential_json = + serde_json::to_string(&credential).expect("credential serializes"); + + let claimed = sqlx::query( + "UPDATE server_device_connect_requests + SET status = 'approved', issued_credential_json = ?, responded_at_unix = ? + WHERE id = ? AND status = 'pending'", + ) + .bind(credential_json) + .bind(now) + .bind(&id_str) + .execute(&mut *connection) + .await?; + if claimed.rows_affected() != 1 { + return Err(AuthStoreError::PairingRedeemed); + } + + sqlx::query( + "INSERT INTO server_auth_audit_events + (id, event_kind, actor_credential_id, actor_device_id, target_id, outcome, + occurred_at_unix) + VALUES (?, 'pairing_redeemed', ?, ?, ?, 'succeeded', ?)", + ) + .bind(Uuid::new_v4().to_string()) + .bind(&actor.credential_id) + .bind(actor.device_id.map(|id| id.to_string())) + .bind(device_id.to_string()) + .bind(now) + .execute(&mut *connection) + .await?; + + Ok(()) + } + .await; + + match result { + Ok(()) => { + sqlx::query("COMMIT").execute(&mut *connection).await?; + Ok(()) + } + Err(error) => { + let _ = sqlx::query("ROLLBACK").execute(&mut *connection).await; + Err(error) + } + } + } +} + +impl SqliteServerAuth { + /// Persists a WebRTC device after the user approves the SAS prompt on the Host. + pub async fn trust_webrtc_device( + &self, + actor: &AuthenticatedCredential, + request: TrustWebRtcDeviceRequest, + ) -> Result { + if !actor.allows("device.pair") { + return Err(AuthStoreError::Forbidden); + } + let device_name = request.device_name.trim(); + if device_name.is_empty() || device_name.len() > 128 { + return Err(AuthStoreError::InvalidDeviceName); + } + let (_, canonical_pubkey) = parse_ed25519_public_key(&request.public_key_ed25519)?; + let scopes = resolve_pairing_scopes( + &actor.scopes, + CreatePairingRequest { + preset: Some(request.preset), + requested_scopes: Vec::new(), + ttl_seconds: None, + }, + )?; + let now = self.now(); + let synthetic_token = format!( + "vbx_device_{}{}", + Uuid::new_v4().simple(), + Uuid::new_v4().simple() + ); + let token_digest = TokenDigest::from_secret(&synthetic_token); + let client_kind = infer_client_kind(device_name, Some(request.preset), None, false); + let mut tx = self.pool.begin().await?; + sqlx::query( + "INSERT INTO server_device_credentials + (id, token_hash, device_name, scopes_json, created_at_unix, client_kind, + last_connected_at_unix, public_key_ed25519) + VALUES (?, ?, ?, ?, ?, ?, ?, ?) + ON CONFLICT(id) DO UPDATE SET + device_name = excluded.device_name, + scopes_json = excluded.scopes_json, + client_kind = excluded.client_kind, + last_connected_at_unix = excluded.last_connected_at_unix, + public_key_ed25519 = excluded.public_key_ed25519, + revoked_at_unix = NULL", + ) + .bind(request.device_id.to_string()) + .bind(token_digest.as_bytes().as_slice()) + .bind(device_name) + .bind(serde_json::to_string(&scopes).expect("scopes serialize")) + .bind(now) + .bind(&client_kind) + .bind(now) + .bind(&canonical_pubkey) + .execute(&mut *tx) + .await?; + sqlx::query( + "INSERT INTO server_auth_audit_events + (id, event_kind, actor_credential_id, actor_device_id, target_id, outcome, + occurred_at_unix) + VALUES (?, 'pairing_redeemed', ?, ?, ?, 'succeeded', ?)", + ) + .bind(Uuid::new_v4().to_string()) + .bind(&actor.credential_id) + .bind(actor.device_id.map(|id| id.to_string())) + .bind(request.device_id.to_string()) + .bind(now) + .execute(&mut *tx) + .await?; + tx.commit().await?; + Ok(PairedDeviceRecord { + device_id: request.device_id, + device_name: device_name.to_owned(), + scopes, + created_at: unix_timestamp(now), + preset: Some(request.preset), + client_kind: Some(client_kind), + ip_address: None, + last_connected_at: Some(unix_timestamp(now)), + public_key_ed25519: Some(canonical_pubkey), + }) + } + + /// Authenticates a WebRTC signaling offer/answer using its Ed25519-signed + /// [`ChannelBindingClaims`], enforcing recipient match, `±60s` timestamp + /// window, and replay protection on `session_nonce`. + pub async fn authenticate_channel_binding( + &self, + local_host_id: &str, + claims: &ChannelBindingClaims, + signature_base64: &str, + ) -> Result { + if claims.recipient_device_id != local_host_id { + return Err(AuthStoreError::ChannelBindingRecipientMismatch); + } + let now = self.now(); + if (now - claims.unix_timestamp).abs() > CHANNEL_BINDING_MAX_SKEW_SECONDS { + return Err(AuthStoreError::ChannelBindingTimestampSkew); + } + let signature_bytes = BASE64 + .decode(signature_base64.trim()) + .or_else(|_| { + base64::engine::general_purpose::URL_SAFE_NO_PAD.decode(signature_base64.trim()) + }) + .map_err(|_| AuthStoreError::InvalidChannelBindingSignature)?; + + let Some(row) = sqlx::query( + "SELECT id, device_name, scopes_json, public_key_ed25519 + FROM server_device_credentials + WHERE id = ? AND revoked_at_unix IS NULL AND public_key_ed25519 IS NOT NULL + LIMIT 1", + ) + .bind(&claims.sender_device_id) + .fetch_optional(&self.pool) + .await? + else { + return Err(AuthStoreError::DeviceNotFound); + }; + + let stored_pubkey: String = row.try_get("public_key_ed25519")?; + let (pubkey_bytes, _) = parse_ed25519_public_key(&stored_pubkey)?; + let verifier = UnparsedPublicKey::new(&ED25519, pubkey_bytes); + verifier + .verify(claims.signing_input().as_bytes(), &signature_bytes) + .map_err(|_| AuthStoreError::InvalidChannelBindingSignature)?; + + let mut tx = self.pool.begin().await?; + sqlx::query("DELETE FROM webrtc_signaling_nonces WHERE expires_at_unix <= ?") + .bind(now) + .execute(&mut *tx) + .await?; + let inserted = sqlx::query( + "INSERT OR IGNORE INTO webrtc_signaling_nonces + (session_nonce, sender_device_id, expires_at_unix) + VALUES (?, ?, ?)", + ) + .bind(&claims.session_nonce) + .bind(&claims.sender_device_id) + .bind(now.saturating_add(CHANNEL_BINDING_MAX_SKEW_SECONDS * 2)) + .execute(&mut *tx) + .await?; + if inserted.rows_affected() != 1 { + return Err(AuthStoreError::ChannelBindingReplay); + } + tx.commit().await?; + + let id: String = row.try_get("id")?; + let device_id: DeviceId = id + .parse() + .map_err(|error| sqlx::Error::Protocol(format!("invalid device id: {error}")))?; + let device_name: String = row.try_get("device_name")?; + let scopes = parse_scopes(row.try_get("scopes_json")?)?; + let _ = self + .record_device_connection(device_id, None, Some("webrtc")) + .await; + + Ok(AuthenticatedCredential { + credential_id: id, + kind: CredentialKind::Device, + subject: format!("device:{device_name}"), + device_id: Some(device_id), + scopes, + }) + } + + /// Synchronizes a list of revoked device IDs pulled from the Cloud directory + /// upon Host startup before accepting inbound connections (Section 5.4 Step 3). + pub async fn sync_revoked_devices( + &self, + actor: &AuthenticatedCredential, + revoked_device_ids: &[DeviceId], + ) -> Result { + if !actor.allows("device.revoke") { + return Err(AuthStoreError::Forbidden); + } + if revoked_device_ids.is_empty() { + return Ok(0); + } + let now = self.now(); + let mut tx = self.pool.begin().await?; + let mut count = 0_usize; + for device_id in revoked_device_ids { + let updated = sqlx::query( + "UPDATE server_device_credentials + SET revoked_at_unix = ? + WHERE id = ? AND revoked_at_unix IS NULL", + ) + .bind(now) + .bind(device_id.to_string()) + .execute(&mut *tx) + .await?; + if updated.rows_affected() == 1 { + count += 1; + sqlx::query( + "INSERT INTO server_auth_audit_events + (id, event_kind, actor_credential_id, actor_device_id, target_id, outcome, + occurred_at_unix) + VALUES (?, 'device_revoked', ?, ?, ?, 'succeeded', ?)", + ) + .bind(Uuid::new_v4().to_string()) + .bind(&actor.credential_id) + .bind(actor.device_id.map(|id| id.to_string())) + .bind(device_id.to_string()) + .bind(now) + .execute(&mut *tx) + .await?; + } + } + tx.commit().await?; + Ok(count) + } } pub(crate) fn infer_client_kind( @@ -782,6 +1601,18 @@ pub(crate) fn infer_client_kind( || lower_name.contains("android") || lower_name.contains("pixel") || lower_name.contains("mobile") + || lower_name.contains("honor") + || lower_name.contains("huawei") + || lower_name.contains("xiaomi") + || lower_name.contains("redmi") + || lower_name.contains("oppo") + || lower_name.contains("vivo") + || lower_name.contains("oneplus") + || lower_name.contains("samsung") + || lower_name.contains("galaxy") + || lower_name.contains("an00") + || lower_name.contains("al00") + || lower_name.starts_with("dio-") || preset == Some(DevicePermissionPreset::Companion) { return "mobile".to_owned(); @@ -810,6 +1641,102 @@ pub(crate) fn infer_client_kind( "desktop".to_owned() } +fn is_mobile_device_record( + device_name: &str, + stored_client_kind: Option<&str>, + scopes_json: &str, +) -> bool { + if let Some(kind) = stored_client_kind.map(str::trim).filter(|v| !v.is_empty()) { + if kind.eq_ignore_ascii_case("mobile") { + return true; + } + if kind.eq_ignore_ascii_case("web") { + return false; + } + } + let scopes: Vec = serde_json::from_str(scopes_json).unwrap_or_default(); + let preset = infer_preset(&scopes); + infer_client_kind(device_name, preset, None, false) == "mobile" +} + +async fn find_conflicting_mobile_device( + connection: &mut sqlx::SqliteConnection, + incoming_device_name: &str, + incoming_pubkey: Option<&str>, +) -> Result, AuthStoreError> { + let rows = sqlx::query( + "SELECT id, device_name, scopes_json, client_kind, public_key_ed25519 + FROM server_device_credentials + WHERE revoked_at_unix IS NULL + ORDER BY COALESCE(last_connected_at_unix, created_at_unix) DESC, created_at_unix DESC", + ) + .fetch_all(&mut *connection) + .await?; + + let incoming_name_trimmed = incoming_device_name.trim(); + for row in rows { + let id_str: String = row.try_get("id")?; + let existing_name: String = row.try_get("device_name")?; + let scopes_json: String = row.try_get("scopes_json")?; + let stored_kind: Option = row.try_get("client_kind").ok().flatten(); + let existing_pk: Option = row + .try_get::, _>("public_key_ed25519") + .ok() + .flatten() + .filter(|v| !v.trim().is_empty()); + + if !is_mobile_device_record(&existing_name, stored_kind.as_deref(), &scopes_json) { + continue; + } + let same_pubkey = match (incoming_pubkey, existing_pk.as_deref()) { + (Some(a), Some(b)) => a == b, + _ => false, + }; + let same_name = existing_name + .trim() + .eq_ignore_ascii_case(incoming_name_trimmed); + if same_pubkey || same_name { + continue; + } + if let Ok(device_id) = id_str.parse::() { + return Ok(Some((device_id, existing_name))); + } + } + Ok(None) +} + +async fn revoke_all_active_mobile_devices( + connection: &mut sqlx::SqliteConnection, + now: i64, +) -> Result<(), AuthStoreError> { + let rows = sqlx::query( + "SELECT id, device_name, scopes_json, client_kind + FROM server_device_credentials + WHERE revoked_at_unix IS NULL", + ) + .fetch_all(&mut *connection) + .await?; + + for row in rows { + let id_str: String = row.try_get("id")?; + let existing_name: String = row.try_get("device_name")?; + let scopes_json: String = row.try_get("scopes_json")?; + let stored_kind: Option = row.try_get("client_kind").ok().flatten(); + if is_mobile_device_record(&existing_name, stored_kind.as_deref(), &scopes_json) { + sqlx::query( + "UPDATE server_device_credentials + SET revoked_at_unix = ? + WHERE id = ? AND revoked_at_unix IS NULL", + ) + .bind(now) + .bind(&id_str) + .execute(&mut *connection) + .await?; + } + } + Ok(()) +} + fn resolve_pairing_scopes( creator_scopes: &BTreeSet, request: CreatePairingRequest, @@ -981,6 +1908,9 @@ mod host_console_pairing_tests { .redeem_pairing(RedeemPairingRequest { pairing_token: challenge.pairing_token, device_name: "Pixel 9".to_owned(), + public_key_ed25519: None, + client_kind: None, + replace_existing_mobile: false, }) .await .expect("redeem pairing"); diff --git a/crates/server/src/e2ee.rs b/crates/server/src/e2ee.rs new file mode 100644 index 000000000..7aad7f0e3 --- /dev/null +++ b/crates/server/src/e2ee.rs @@ -0,0 +1,556 @@ +//! End-to-End Encryption (E2EE v1) for Host <-> Mobile Companion communication. +//! +//! Uses ephemeral-ephemeral / session ECDH over NIST P-256 (`secp256r1`) with +//! `HKDF-SHA256` key derivation and `AES-256-GCM` authenticated encryption so +//! that cloud relays and untrusted network intermediaries +//! only ever observe opaque AEAD ciphertexts. + +use std::{ + collections::HashMap, + sync::{OnceLock, RwLock}, + time::Instant, +}; + +use axum::{ + body::Body, + extract::Request, + http::{HeaderValue, StatusCode, header}, + middleware::Next, + response::{IntoResponse, Response}, +}; +use base64::{ + Engine as _, + engine::general_purpose::{STANDARD, URL_SAFE_NO_PAD}, +}; +use hkdf::Hkdf; +use ring::{ + aead::{AES_256_GCM, Aad, LessSafeKey, Nonce, UnboundKey}, + agreement::{ECDH_P256, EphemeralPrivateKey, UnparsedPublicKey, agree_ephemeral}, + rand::{SecureRandom, SystemRandom}, +}; +use sha2::Sha256; + +pub const HEADER_E2EE: &str = "x-vibex-e2ee"; +pub const HEADER_E2EE_CLIENT_PUB: &str = "x-vibex-e2ee-client-pub"; +pub const HEADER_E2EE_SERVER_PUB: &str = "x-vibex-e2ee-server-pub"; +pub const HEADER_E2EE_SESSION: &str = "x-vibex-e2ee-session"; +pub const HEADER_E2EE_AUTH: &str = "x-vibex-e2ee-auth"; +pub const E2EE_VERSION: &str = "v1"; + +pub const HKDF_SALT: &[u8] = b"vibex-e2ee-v1-salt"; +pub const HKDF_INFO: &[u8] = b"vibex-e2ee-v1-aes256gcm"; + +pub const AAD_AUTH: &[u8] = b"vibex-e2ee-auth-v1"; +pub const AAD_REQ: &[u8] = b"vibex-e2ee-req-v1"; +pub const AAD_RESP: &[u8] = b"vibex-e2ee-resp-v1"; +pub const AAD_WS: &[u8] = b"vibex-e2ee-ws-v1"; + +const MAX_E2EE_BODY_BYTES: usize = 16 * 1024 * 1024; +const MAX_CACHED_SESSIONS: usize = 512; + +#[derive(Clone, Debug)] +pub struct E2eeSession { + pub session_id: String, + pub key: [u8; 32], + pub client_pub_b64: String, + pub server_pub_b64: String, + pub active_e2ee: bool, + pub last_used: Instant, +} + +#[derive(Default)] +struct E2eeSessionStore { + by_session_id: HashMap, + by_client_pub: HashMap, +} + +static SESSION_STORE: OnceLock> = OnceLock::new(); + +fn session_store() -> &'static RwLock { + SESSION_STORE.get_or_init(|| RwLock::new(E2eeSessionStore::default())) +} + +fn decode_b64_flexible(encoded: &str) -> Option> { + let trimmed = encoded.trim(); + if trimmed.is_empty() { + return None; + } + STANDARD + .decode(trimmed) + .or_else(|_| URL_SAFE_NO_PAD.decode(trimmed)) + .ok() +} + +pub fn derive_aes256_key(shared_secret: &[u8]) -> [u8; 32] { + let hk = Hkdf::::new(Some(HKDF_SALT), shared_secret); + let mut okm = [0u8; 32]; + hk.expand(HKDF_INFO, &mut okm) + .expect("32-byte HKDF-SHA256 output is always valid"); + okm +} + +pub fn encrypt_payload( + key: &[u8; 32], + aad: &[u8], + plaintext: &[u8], +) -> Result { + let rng = SystemRandom::new(); + let mut nonce_bytes = [0u8; 12]; + rng.fill(&mut nonce_bytes) + .map_err(|_| "failed to generate E2EE nonce")?; + + let unbound = UnboundKey::new(&AES_256_GCM, key).map_err(|_| "invalid AES-256-GCM key")?; + let sealing_key = LessSafeKey::new(unbound); + + let mut buffer = Vec::with_capacity(12 + plaintext.len() + 16); + buffer.extend_from_slice(&nonce_bytes); + buffer.extend_from_slice(plaintext); + + let tag = sealing_key + .seal_in_place_separate_tag( + Nonce::assume_unique_for_key(nonce_bytes), + Aad::from(aad), + &mut buffer[12..], + ) + .map_err(|_| "AES-256-GCM encryption failed")?; + buffer.extend_from_slice(tag.as_ref()); + + Ok(STANDARD.encode(&buffer)) +} + +pub fn decrypt_payload(key: &[u8; 32], aad: &[u8], encoded: &str) -> Result, &'static str> { + let mut raw = decode_b64_flexible(encoded).ok_or("invalid E2EE base64 payload")?; + if raw.len() < 12 + 16 { + return Err("E2EE payload too short"); + } + let mut nonce_bytes = [0u8; 12]; + nonce_bytes.copy_from_slice(&raw[..12]); + let ciphertext_and_tag = &mut raw[12..]; + + let unbound = UnboundKey::new(&AES_256_GCM, key).map_err(|_| "invalid AES-256-GCM key")?; + let opening_key = LessSafeKey::new(unbound); + + let plaintext = opening_key + .open_in_place( + Nonce::assume_unique_for_key(nonce_bytes), + Aad::from(aad), + ciphertext_and_tag, + ) + .map_err(|_| "AES-256-GCM authentication failed")?; + + Ok(plaintext.to_vec()) +} + +pub fn lookup_session_by_id(session_id: &str) -> Option { + let trimmed = session_id.trim(); + if trimmed.is_empty() { + return None; + } + let mut guard = session_store().write().ok()?; + let session = guard.by_session_id.get_mut(trimmed)?; + session.last_used = Instant::now(); + Some(session.clone()) +} + +pub fn get_or_create_session_for_client_pub(client_pub_b64: &str) -> Option { + let clean_pub = client_pub_b64.trim(); + if clean_pub.is_empty() { + return None; + } + if let Ok(mut guard) = session_store().write() + && let Some(existing_id) = guard.by_client_pub.get(clean_pub).cloned() + && let Some(session) = guard.by_session_id.get_mut(&existing_id) + { + session.last_used = Instant::now(); + return Some(session.clone()); + } + + let client_pub_bytes = decode_b64_flexible(clean_pub)?; + if client_pub_bytes.len() != 65 || client_pub_bytes[0] != 0x04 { + return None; + } + + let rng = SystemRandom::new(); + let server_priv = EphemeralPrivateKey::generate(&ECDH_P256, &rng).ok()?; + let server_pub = server_priv.compute_public_key().ok()?; + let server_pub_b64 = STANDARD.encode(server_pub.as_ref()); + + let peer_pub = UnparsedPublicKey::new(&ECDH_P256, &client_pub_bytes); + let key = agree_ephemeral(server_priv, &peer_pub, |shared_secret| { + derive_aes256_key(shared_secret) + }) + .ok()?; + + let mut id_bytes = [0u8; 16]; + rng.fill(&mut id_bytes).ok()?; + let session_id = id_bytes + .iter() + .map(|b| format!("{b:02x}")) + .collect::(); + + let session = E2eeSession { + session_id: session_id.clone(), + key, + client_pub_b64: clean_pub.to_owned(), + server_pub_b64, + active_e2ee: false, + last_used: Instant::now(), + }; + + if let Ok(mut guard) = session_store().write() { + if guard.by_session_id.len() >= MAX_CACHED_SESSIONS + && let Some(oldest_key) = guard + .by_session_id + .iter() + .min_by_key(|(_, v)| v.last_used) + .map(|(k, _)| k.clone()) + && let Some(removed) = guard.by_session_id.remove(&oldest_key) + { + guard.by_client_pub.remove(&removed.client_pub_b64); + } + guard + .by_client_pub + .insert(clean_pub.to_owned(), session_id.clone()); + guard.by_session_id.insert(session_id, session.clone()); + } + + Some(session) +} + +fn ws_session_from_protocols(protocols: &str) -> Option { + protocols + .split(',') + .map(str::trim) + .find_map(|protocol| protocol.strip_prefix("vibex.e2ee.")) + .and_then(lookup_session_by_id) +} + +fn attach_handshake_headers(headers: &mut axum::http::HeaderMap, session: &E2eeSession) { + if let Ok(val) = HeaderValue::from_str(&session.session_id) { + headers.insert(HEADER_E2EE_SESSION, val); + } + if let Ok(val) = HeaderValue::from_str(&session.server_pub_b64) { + headers.insert(HEADER_E2EE_SERVER_PUB, val); + } +} + +fn precondition_failed_rekey(session: &E2eeSession) -> Response { + let mut response = ( + StatusCode::PRECONDITION_FAILED, + "E2EE session key out of sync; re-key using response headers", + ) + .into_response(); + attach_handshake_headers(response.headers_mut(), session); + response +} + +pub async fn e2ee_middleware(mut request: Request, next: Next) -> Response { + let requested_session_id = request + .headers() + .get(HEADER_E2EE_SESSION) + .and_then(|v| v.to_str().ok()) + .map(str::trim) + .filter(|s| !s.is_empty()) + .map(ToOwned::to_owned); + + let client_pub_b64 = request + .headers() + .get(HEADER_E2EE_CLIENT_PUB) + .and_then(|v| v.to_str().ok()) + .map(str::trim) + .filter(|s| !s.is_empty()) + .map(ToOwned::to_owned); + + let ws_protocol_session = request + .headers() + .get("sec-websocket-protocol") + .and_then(|v| v.to_str().ok()) + .and_then(ws_session_from_protocols); + + let mut session = requested_session_id + .as_deref() + .and_then(lookup_session_by_id) + .or(ws_protocol_session) + .or_else(|| { + client_pub_b64 + .as_deref() + .and_then(get_or_create_session_for_client_pub) + }); + + let request_is_e2ee = request + .headers() + .get(HEADER_E2EE) + .and_then(|v| v.to_str().ok()) + .is_some_and(|v| v.eq_ignore_ascii_case(E2EE_VERSION)); + + if request_is_e2ee { + let Some(active_session) = session.as_mut() else { + return ( + StatusCode::PRECONDITION_FAILED, + "E2EE session not established; provide x-vibex-e2ee-client-pub", + ) + .into_response(); + }; + active_session.active_e2ee = true; + + // If the client specified a session ID from before a Host restart and it didn't match, + // trigger an immediate 412 re-key with the new server public key. + if let Some(req_id) = requested_session_id.as_deref() + && req_id != active_session.session_id + { + return precondition_failed_rekey(active_session); + } + + if let Some(enc_auth) = request + .headers() + .get(HEADER_E2EE_AUTH) + .and_then(|v| v.to_str().ok()) + .map(ToOwned::to_owned) + { + let Ok(decrypted_auth) = decrypt_payload(&active_session.key, AAD_AUTH, &enc_auth) + else { + return precondition_failed_rekey(active_session); + }; + let Ok(auth_str) = String::from_utf8(decrypted_auth) else { + return precondition_failed_rekey(active_session); + }; + let normalized = if auth_str.starts_with("Bearer ") || auth_str.starts_with("bearer ") { + auth_str + } else { + format!("Bearer {}", auth_str.trim()) + }; + if let Ok(header_val) = HeaderValue::from_str(&normalized) { + request + .headers_mut() + .insert(header::AUTHORIZATION, header_val); + } + } + + let (mut parts, body) = request.into_parts(); + let Ok(body_bytes) = axum::body::to_bytes(body, MAX_E2EE_BODY_BYTES).await else { + return (StatusCode::PAYLOAD_TOO_LARGE, "E2EE request body too large").into_response(); + }; + + if !body_bytes.is_empty() { + let Ok(encoded_str) = std::str::from_utf8(&body_bytes) else { + return precondition_failed_rekey(active_session); + }; + let Ok(plaintext_bytes) = + decrypt_payload(&active_session.key, AAD_REQ, encoded_str.trim()) + else { + return precondition_failed_rekey(active_session); + }; + parts.headers.insert( + header::CONTENT_TYPE, + HeaderValue::from_static("application/json"), + ); + parts.headers.remove(header::CONTENT_LENGTH); + request = Request::from_parts(parts, Body::from(plaintext_bytes)); + } else { + request = Request::from_parts(parts, Body::empty()); + } + } else if let Some(active_session) = session.as_mut() + && request + .headers() + .get("sec-websocket-protocol") + .and_then(|v| v.to_str().ok()) + .is_some_and(|p| p.contains("vibex.e2ee.")) + { + active_session.active_e2ee = true; + } + + if let Some(ref active_session) = session { + request.extensions_mut().insert(active_session.clone()); + } + + let mut response = next.run(request).await; + + if let Some(ref active_session) = session { + attach_handshake_headers(response.headers_mut(), active_session); + + let is_ws_upgrade = response.status() == StatusCode::SWITCHING_PROTOCOLS; + let is_sse = response + .headers() + .get(header::CONTENT_TYPE) + .and_then(|v| v.to_str().ok()) + .is_some_and(|ct| ct.contains("text/event-stream")); + + if request_is_e2ee && !is_ws_upgrade && !is_sse { + let (mut parts, body) = response.into_parts(); + if let Ok(resp_bytes) = axum::body::to_bytes(body, MAX_E2EE_BODY_BYTES).await { + if !resp_bytes.is_empty() + && let Ok(encrypted_b64) = + encrypt_payload(&active_session.key, AAD_RESP, &resp_bytes) + { + parts + .headers + .insert(HEADER_E2EE, HeaderValue::from_static(E2EE_VERSION)); + parts.headers.insert( + header::CONTENT_TYPE, + HeaderValue::from_static("text/plain; charset=utf-8"), + ); + parts.headers.remove(header::CONTENT_LENGTH); + return Response::from_parts(parts, Body::from(encrypted_b64)); + } + return Response::from_parts(parts, Body::from(resp_bytes)); + } + return Response::from_parts(parts, Body::empty()); + } + } + + response +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn ecdh_p256_handshake_and_aes256gcm_roundtrip_succeeds() { + let rng = SystemRandom::new(); + let client_priv = EphemeralPrivateKey::generate(&ECDH_P256, &rng).expect("client key"); + let client_pub = client_priv.compute_public_key().expect("client pub"); + let client_pub_b64 = STANDARD.encode(client_pub.as_ref()); + + let server_session = + get_or_create_session_for_client_pub(&client_pub_b64).expect("server session"); + let server_pub_bytes = STANDARD + .decode(&server_session.server_pub_b64) + .expect("server pub decode"); + + let client_key = agree_ephemeral( + client_priv, + &UnparsedPublicKey::new(&ECDH_P256, &server_pub_bytes), + |shared_secret| derive_aes256_key(shared_secret), + ) + .expect("client agree"); + + assert_eq!(client_key, server_session.key); + + let message = br#"{"operation_id":"op-1","args":{"prompt":"hello end-to-end encryption"}}"#; + let encrypted = + encrypt_payload(&client_key, AAD_REQ, message).expect("client encrypts request"); + let decrypted = decrypt_payload(&server_session.key, AAD_REQ, &encrypted) + .expect("server decrypts request"); + assert_eq!(decrypted, message); + + // Wrong AAD must fail authentication + assert!(decrypt_payload(&server_session.key, AAD_RESP, &encrypted).is_err()); + } + + #[tokio::test] + async fn e2ee_middleware_decrypts_request_and_encrypts_response() { + use axum::{ + Json, Router, + body::Body, + http::{Request, StatusCode, header}, + middleware, + routing::{get, post}, + }; + use tower::ServiceExt; + + let app = Router::new() + .route( + "/health", + get(|| async { Json(serde_json::json!({"status": "ok", "e2ee": true})) }), + ) + .route( + "/api/v1/echo", + post(|headers: axum::http::HeaderMap, body: String| async move { + let auth = headers + .get(header::AUTHORIZATION) + .and_then(|v| v.to_str().ok()) + .unwrap_or("") + .to_owned(); + Json(serde_json::json!({ + "auth": auth, + "received": serde_json::from_str::(&body).unwrap_or_default(), + })) + }), + ) + .layer(middleware::from_fn(e2ee_middleware)); + + let rng = SystemRandom::new(); + let client_priv = EphemeralPrivateKey::generate(&ECDH_P256, &rng).expect("client key"); + let client_pub = client_priv.compute_public_key().expect("client pub"); + let client_pub_b64 = STANDARD.encode(client_pub.as_ref()); + + // 1. Handshake on /health + let health_resp = app + .clone() + .oneshot( + Request::builder() + .uri("/health") + .header(HEADER_E2EE_CLIENT_PUB, &client_pub_b64) + .body(Body::empty()) + .unwrap(), + ) + .await + .expect("health response"); + assert_eq!(health_resp.status(), StatusCode::OK); + let session_id = health_resp + .headers() + .get(HEADER_E2EE_SESSION) + .unwrap() + .to_str() + .unwrap() + .to_owned(); + let server_pub_b64 = health_resp + .headers() + .get(HEADER_E2EE_SERVER_PUB) + .unwrap() + .to_str() + .unwrap() + .to_owned(); + + let server_pub_bytes = STANDARD.decode(&server_pub_b64).expect("decode server pub"); + let client_key = agree_ephemeral( + client_priv, + &UnparsedPublicKey::new(&ECDH_P256, &server_pub_bytes), + |shared_secret| derive_aes256_key(shared_secret), + ) + .expect("derive client key"); + + // 2. Encrypted POST request with encrypted Authorization header + let encrypted_auth = + encrypt_payload(&client_key, AAD_AUTH, b"Bearer secret-companion-token").unwrap(); + let encrypted_body = + encrypt_payload(&client_key, AAD_REQ, br#"{"hello":"world"}"#).unwrap(); + + let echo_resp = app + .oneshot( + Request::builder() + .method("POST") + .uri("/api/v1/echo") + .header(HEADER_E2EE, E2EE_VERSION) + .header(HEADER_E2EE_SESSION, &session_id) + .header(HEADER_E2EE_CLIENT_PUB, &client_pub_b64) + .header(HEADER_E2EE_AUTH, &encrypted_auth) + .header(header::AUTHORIZATION, "Bearer e2ee") + .body(Body::from(encrypted_body)) + .unwrap(), + ) + .await + .expect("echo response"); + + assert_eq!(echo_resp.status(), StatusCode::OK); + assert_eq!( + echo_resp + .headers() + .get(HEADER_E2EE) + .unwrap() + .to_str() + .unwrap(), + E2EE_VERSION + ); + let resp_cipher_bytes = axum::body::to_bytes(echo_resp.into_body(), 1024 * 1024) + .await + .unwrap(); + let resp_cipher_str = std::str::from_utf8(&resp_cipher_bytes).unwrap(); + let decrypted_resp = + decrypt_payload(&client_key, AAD_RESP, resp_cipher_str).expect("decrypt response"); + let json_resp: serde_json::Value = serde_json::from_slice(&decrypted_resp).unwrap(); + assert_eq!(json_resp["auth"], "Bearer secret-companion-token"); + assert_eq!(json_resp["received"]["hello"], "world"); + } +} diff --git a/crates/server/src/lib.rs b/crates/server/src/lib.rs index 39afeb0e5..c93743443 100644 --- a/crates/server/src/lib.rs +++ b/crates/server/src/lib.rs @@ -12,6 +12,7 @@ mod composition; mod config; mod delegation_runtime; mod domains; +pub mod e2ee; mod host; mod host_core; mod host_ops; @@ -23,6 +24,7 @@ mod preview_proxy; mod product_mcp; mod runtime; mod token_store; +mod transport_session; mod update; mod weixin_ilink; mod ws; @@ -35,7 +37,7 @@ pub use artifact_sink::ServerArtifactEventSink; pub use auth::{ AuthClock, AuthStoreError, AuthenticatedCredential, CredentialKind, PairedDeviceRecord, ServerAuth, ServerCredentials, ServerToken, ServerTokenError, SqliteServerAuth, - SystemAuthClock, + SystemAuthClock, TrustWebRtcDeviceRequest, compute_sas_code, verify_peer_dtls_fingerprint, }; pub use automation_runtime::HeadlessAutomationRuntime; pub use chat_inbound::{ @@ -114,6 +116,10 @@ pub fn apply_host_multi_agent_setting( } pub use runtime::{ServerRuntime, set_extra_browser_origins, set_published_reachability}; pub use token_store::{ProvisionedToken, SqliteTokenHashStore}; +pub use transport_session::{ + IDEMPOTENCY_TTL_SECONDS, RtcPeerEngine, SqliteIdempotencyLedger, TransportSession, + TransportSessionTelemetry, +}; pub use update::{HostUpgradeError, HostUpgradePlan, apply_host_upgrade, plan_host_upgrade}; pub use weixin_ilink::{ WeixinQrcodeInfo, WeixinQrcodeStatus, weixin_check_qrcode, weixin_get_qrcode, diff --git a/crates/server/src/runtime.rs b/crates/server/src/runtime.rs index 33402545c..86c98f961 100644 --- a/crates/server/src/runtime.rs +++ b/crates/server/src/runtime.rs @@ -17,9 +17,10 @@ use axum::{ }; use local_deployment::pty::PtyService; use remote_protocol::{ - CapabilityId, CommandRequest, ConversationId, CreatePairingRequest, DeviceId, - DevicePermissionPreset, ErrorCode, ErrorEnvelope, IssuedPairingInvitation, OperationId, - PairingInvitationPayload, ReachabilityOrigin, RedeemPairingRequest, ServerCapabilities, + CapabilityId, CommandRequest, ConversationId, CreateDeviceConnectRequest, CreatePairingRequest, + DeviceId, DevicePermissionPreset, ErrorCode, ErrorEnvelope, IssuedPairingInvitation, + OperationId, PairingId, PairingInvitationPayload, ReachabilityOrigin, RedeemPairingRequest, + ServerCapabilities, }; use serde::Deserialize; use serde_json::json; @@ -40,6 +41,7 @@ pub(crate) struct ServerState { pub(crate) pty: PtyService, pub(crate) events: Arc, pub(crate) plugin_control_plane: Option>, + pub(crate) idempotency_ledger: Option, } pub struct ServerRuntime { @@ -90,11 +92,12 @@ where ) -> Self { Self::from_auth_with_preview_proxy_inner( config, - Arc::new(SqliteServerAuth::new(pool)), + Arc::new(SqliteServerAuth::new(pool.clone())), core, crate::PreviewProxyRegistry::default(), PtyService::new(), ) + .with_idempotency_ledger(crate::SqliteIdempotencyLedger::new(pool)) } pub fn from_sqlite_auth_with_preview_proxy_and_pty( @@ -106,11 +109,19 @@ where ) -> Self { Self::from_auth_with_preview_proxy_inner( config, - Arc::new(SqliteServerAuth::new(pool)), + Arc::new(SqliteServerAuth::new(pool.clone())), core, preview_proxy, pty, ) + .with_idempotency_ledger(crate::SqliteIdempotencyLedger::new(pool)) + } + + pub fn with_idempotency_ledger(mut self, ledger: crate::SqliteIdempotencyLedger) -> Self { + if let Some(state) = Arc::get_mut(&mut self.state) { + state.idempotency_ledger = Some(ledger); + } + self } pub fn from_auth_with_preview_proxy( @@ -182,6 +193,7 @@ where pty, events, plugin_control_plane: None, + idempotency_ledger: None, }), } } @@ -221,6 +233,7 @@ impl ServerRuntime { pty, events: host.events.clone(), plugin_control_plane: Some(host.plugin_control_plane.clone()), + idempotency_ledger: None, }), } } @@ -240,6 +253,18 @@ where .route("/ws", get(crate::ws::ws_handler::)) .route("/call/{command}", post(application_call::)) .route("/auth/pairings", post(create_pairing::)) + .route( + "/auth/connect-requests/pending", + get(list_connect_requests::), + ) + .route( + "/auth/connect-requests/{request_id}/approve", + post(approve_connect_request::), + ) + .route( + "/auth/connect-requests/{request_id}/reject", + post(reject_connect_request::), + ) .route("/auth/devices/{device_id}", delete(revoke_device::)) .route( "/conversations/{conversation_id}/offline", @@ -256,7 +281,16 @@ where )); Router::new() .route("/health", get(health::)) + .route("/api/v1/e2ee/handshake", get(health::)) .route("/api/v1/auth/pairings/redeem", post(redeem_pairing::)) + .route( + "/api/v1/auth/connect-requests", + post(create_connect_request::), + ) + .route( + "/api/v1/auth/connect-requests/{request_id}", + get(poll_connect_request::), + ) .route( "/api/v1/plugin-artifacts/{plugin_id}/{*path}", get(crate::plugin_artifact::serve_runtime_plugin_artifact::), @@ -272,6 +306,7 @@ where .nest("/api/v1", protected) .fallback(get(static_asset::)) .with_state(Arc::clone(&self.state)) + .layer(middleware::from_fn(crate::e2ee::e2ee_middleware)) .layer(middleware::from_fn_with_state( Arc::clone(&self.state), enforce_origin::, @@ -598,7 +633,13 @@ fn apply_cors_headers(headers: &mut HeaderMap, origin: &str) { ); headers.insert( header::ACCESS_CONTROL_ALLOW_HEADERS, - HeaderValue::from_static("authorization, content-type, x-vibex-protocol-version"), + HeaderValue::from_static( + "authorization, content-type, x-vibex-protocol-version, x-vibex-e2ee, x-vibex-e2ee-client-pub, x-vibex-e2ee-server-pub, x-vibex-e2ee-session, x-vibex-e2ee-auth", + ), + ); + headers.insert( + header::ACCESS_CONTROL_EXPOSE_HEADERS, + HeaderValue::from_static("x-vibex-e2ee, x-vibex-e2ee-server-pub, x-vibex-e2ee-session"), ); headers.insert(header::VARY, HeaderValue::from_static("Origin")); } @@ -612,13 +653,36 @@ async fn application_call( where R: ConversationRepository + Send + Sync + 'static, { + if crate::SqliteIdempotencyLedger::is_write_command(&command) + && let Some(ledger) = state.idempotency_ledger.as_ref() + && let Ok(Some(cached)) = ledger + .lookup(&credential.credential_id, request.operation_id, &command) + .await + { + return Json(cached).into_response(); + } + let principal = credential.principal(); match state .commands .execute_name(&principal, &command, request.operation_id, request.args) .await { - Ok(response) => Json(response).into_response(), + Ok(response) => { + if crate::SqliteIdempotencyLedger::is_write_command(&command) + && let Some(ledger) = state.idempotency_ledger.as_ref() + { + let _ = ledger + .record( + &credential.credential_id, + request.operation_id, + &command, + &response, + ) + .await; + } + Json(response).into_response() + } Err(error) => application_error_response(error), } } @@ -631,6 +695,7 @@ where "status": "ok", "version": state.config.server_version, "release": !cfg!(debug_assertions), + "e2ee": true, }); if !state.config.host_id.is_empty() { body["host_id"] = json!(state.config.host_id); @@ -718,6 +783,27 @@ fn extract_client_ip(headers: &HeaderMap, listen_addr: std::net::SocketAddr) -> None } +static RECENT_DEVICE_CONN_RECORD: OnceLock< + RwLock), std::time::Instant>>, +> = OnceLock::new(); + +fn should_record_device_connection(device_id: DeviceId, ip: Option<&str>) -> bool { + let map_lock = + RECENT_DEVICE_CONN_RECORD.get_or_init(|| RwLock::new(std::collections::HashMap::new())); + let key = (device_id, ip.map(ToOwned::to_owned)); + let now = std::time::Instant::now(); + if let Ok(guard) = map_lock.read() + && let Some(last) = guard.get(&key) + && now.duration_since(*last) < std::time::Duration::from_secs(60) + { + return false; + } + if let Ok(mut guard) = map_lock.write() { + guard.insert(key, now); + } + true +} + async fn require_token( State(state): State>>, mut request: Request, @@ -740,10 +826,12 @@ async fn require_token( Ok(Some(credential)) => { if let Some(device_id) = credential.device_id { let ip_address = extract_client_ip(request.headers(), state.config.listen_addr); - let _ = state - .auth - .record_device_connection(device_id, None, ip_address.as_deref()) - .await; + if should_record_device_connection(device_id, ip_address.as_deref()) { + let _ = state + .auth + .record_device_connection(device_id, None, ip_address.as_deref()) + .await; + } } request.extensions_mut().insert(credential); return next.run(request).await; @@ -847,6 +935,88 @@ async fn revoke_device( } } +async fn create_connect_request( + State(state): State>>, + headers: HeaderMap, + Json(request): Json, +) -> Response { + let ip_address = extract_client_ip(&headers, state.config.listen_addr); + match state + .auth + .create_connect_request(&state.config.host_id, request, ip_address.as_deref()) + .await + { + Ok(response) => (StatusCode::CREATED, Json(response)).into_response(), + Err(error) => auth_error_response(error), + } +} + +async fn poll_connect_request( + State(state): State>>, + Path(request_id): Path, +) -> Response { + let Ok(request_id) = request_id.parse::() else { + return bad_request("connect request id is invalid"); + }; + match state + .auth + .poll_connect_request(&state.config.host_id, request_id) + .await + { + Ok(response) => Json(response).into_response(), + Err(error) => auth_error_response(error), + } +} + +async fn list_connect_requests( + State(state): State>>, + Extension(credential): Extension, +) -> Response { + match state.auth.list_connect_requests(&credential).await { + Ok(items) => Json(items).into_response(), + Err(error) => auth_error_response(error), + } +} + +async fn approve_connect_request( + State(state): State>>, + Extension(credential): Extension, + Path(request_id): Path, +) -> Response { + respond_connect_request_inner(&state, &credential, &request_id, true).await +} + +async fn reject_connect_request( + State(state): State>>, + Extension(credential): Extension, + Path(request_id): Path, +) -> Response { + respond_connect_request_inner(&state, &credential, &request_id, false).await +} + +async fn respond_connect_request_inner( + state: &ServerState, + credential: &AuthenticatedCredential, + raw_request_id: &str, + approve: bool, +) -> Response { + let Ok(request_id) = raw_request_id.parse::() else { + return bad_request("connect request id is invalid"); + }; + match state + .auth + .respond_connect_request(credential, request_id, approve) + .await + { + Ok(()) => Json(json!({ + "request_id": request_id, + "approved": approve, + })) + .into_response(), + Err(error) => auth_error_response(error), + } +} + #[derive(Clone, Copy, Debug, Default, Deserialize)] struct OfflineQuery { #[serde(default)] @@ -988,29 +1158,53 @@ fn status_for_error_code(code: ErrorCode) -> StatusCode { } fn auth_error_response(error: AuthStoreError) -> Response { + let mut existing_mobile_device: Option<(String, String)> = None; let reason = match &error { AuthStoreError::InvalidScope => Some("invalid_device_scope"), AuthStoreError::InvalidPairing => Some("invalid_pairing"), AuthStoreError::PairingExpired => Some("pairing_expired"), AuthStoreError::PairingRedeemed => Some("pairing_redeemed"), AuthStoreError::InvalidDeviceName => Some("invalid_device_name"), + AuthStoreError::InvalidPublicKey => Some("invalid_public_key"), + AuthStoreError::InvalidChannelBindingSignature => Some("invalid_channel_binding_signature"), + AuthStoreError::ChannelBindingRecipientMismatch => { + Some("channel_binding_recipient_mismatch") + } + AuthStoreError::ChannelBindingTimestampSkew => Some("channel_binding_timestamp_skew"), + AuthStoreError::ChannelBindingReplay => Some("channel_binding_replay"), AuthStoreError::DeviceNotFound => Some("device_not_found"), AuthStoreError::Forbidden => Some("credential_scope_forbidden"), AuthStoreError::PairingUnavailable => Some("pairing_unavailable"), + AuthStoreError::MobileDeviceConflict { + existing_device_id, + existing_device_name, + } => { + existing_mobile_device = + Some((existing_device_id.to_string(), existing_device_name.clone())); + Some("mobile_device_conflict") + } AuthStoreError::Database(_) => None, }; let (status, code, message) = match error { - AuthStoreError::InvalidScope | AuthStoreError::InvalidDeviceName => ( + AuthStoreError::InvalidScope + | AuthStoreError::InvalidDeviceName + | AuthStoreError::InvalidPublicKey => ( StatusCode::BAD_REQUEST, ErrorCode::BadRequest, error.to_string(), ), - AuthStoreError::InvalidPairing => ( + AuthStoreError::InvalidPairing + | AuthStoreError::InvalidChannelBindingSignature + | AuthStoreError::ChannelBindingRecipientMismatch + | AuthStoreError::ChannelBindingTimestampSkew => ( StatusCode::UNAUTHORIZED, ErrorCode::Unauthorized, error.to_string(), ), - AuthStoreError::PairingExpired | AuthStoreError::PairingRedeemed => { + AuthStoreError::PairingExpired + | AuthStoreError::PairingRedeemed + | AuthStoreError::ChannelBindingReplay + | AuthStoreError::MobileDeviceConflict { .. } => { (StatusCode::CONFLICT, ErrorCode::Conflict, error.to_string()) } AuthStoreError::DeviceNotFound => ( @@ -1035,7 +1229,13 @@ fn auth_error_response(error: AuthStoreError) -> Response { ), }; let mut envelope = ErrorEnvelope::new(code, message, false, OperationId::new()); - if let Some(reason) = reason { + if let Some((existing_id, existing_name)) = existing_mobile_device { + envelope = envelope.with_details(json!({ + "reason": "mobile_device_conflict", + "existing_device_id": existing_id, + "existing_device_name": existing_name, + })); + } else if let Some(reason) = reason { envelope = envelope.with_details(json!({ "reason": reason })); } (status, Json(envelope)).into_response() diff --git a/crates/server/src/transport_session.rs b/crates/server/src/transport_session.rs new file mode 100644 index 000000000..f43c32dad --- /dev/null +++ b/crates/server/src/transport_session.rs @@ -0,0 +1,529 @@ +use std::{ + collections::{HashMap, VecDeque}, + sync::Arc, +}; + +use application::{ + ApplicationCore, ApplicationError, CommandRegistry, ConversationRepository, + ConversationSubscriptionRegistrar, RegisteredCommand, +}; +use async_trait::async_trait; +use remote_protocol::{ + BULK_BUFFERED_HIGH_WATER_BYTES, BULK_CHUNK_MAX_BYTES, BulkChannelFrame, CommandResponse, + ControlChannelFrame, ConversationId, ErrorCode, ErrorEnvelope, OperationId, + SIGNALING_PIGGYBACK_MAX_BYTES, SignalingPiggybackEvents, SignalingResumeCursor, + SubscriptionBootstrap, SubscriptionClientMessage, SubscriptionId, SubscriptionRequest, + SubscriptionResource, SubscriptionServerMessage, +}; +use serde_json::Value; +use sqlx::{Row, SqlitePool}; + +use crate::{AuthClock, AuthStoreError, AuthenticatedCredential, ServerAuth, SystemAuthClock}; + +pub const IDEMPOTENCY_TTL_SECONDS: i64 = 24 * 60 * 60; + +#[derive(Clone)] +pub struct SqliteIdempotencyLedger { + pool: SqlitePool, + clock: Arc, + ttl_seconds: i64, +} + +impl SqliteIdempotencyLedger { + pub fn new(pool: SqlitePool) -> Self { + Self::with_clock(pool, Arc::new(SystemAuthClock)) + } + + pub fn with_clock(pool: SqlitePool, clock: Arc) -> Self { + Self { + pool, + clock, + ttl_seconds: IDEMPOTENCY_TTL_SECONDS, + } + } + + pub fn is_write_command(command: &str) -> bool { + let Ok(registered) = command.parse::() else { + return false; + }; + let scope = registered.required_scope(); + matches!( + scope, + "conversation.write" + | "conversation.permission" + | "conversation.question" + | "conversation.cancel" + | "conversation.steer" + | "workflow.write" + | "workflow.run" + | "workflow.approve" + | "automation.write" + | "delegation.cancel" + | "plugin.write" + ) + } + + pub async fn lookup( + &self, + credential_id: &str, + operation_id: OperationId, + command: &str, + ) -> Result>, sqlx::Error> { + let now = self.clock.unix_seconds(); + let Some(row) = sqlx::query( + "SELECT response_json + FROM companion_idempotency_ledger + WHERE credential_id = ? AND operation_id = ? AND command = ? AND expires_at_unix > ? + LIMIT 1", + ) + .bind(credential_id) + .bind(operation_id.to_string()) + .bind(command) + .bind(now) + .fetch_optional(&self.pool) + .await? + else { + return Ok(None); + }; + let response_json: String = row.try_get("response_json")?; + let response: CommandResponse = serde_json::from_str(&response_json) + .map_err(|err| sqlx::Error::Protocol(format!("invalid idempotency response: {err}")))?; + Ok(Some(response)) + } + + pub async fn record( + &self, + credential_id: &str, + operation_id: OperationId, + command: &str, + response: &CommandResponse, + ) -> Result<(), sqlx::Error> { + let now = self.clock.unix_seconds(); + let expires_at = now.saturating_add(self.ttl_seconds); + let serialized = serde_json::to_string(response) + .map_err(|err| sqlx::Error::Protocol(format!("serialize idempotency: {err}")))?; + let mut tx = self.pool.begin().await?; + sqlx::query("DELETE FROM companion_idempotency_ledger WHERE expires_at_unix <= ?") + .bind(now) + .execute(&mut *tx) + .await?; + sqlx::query( + "INSERT OR REPLACE INTO companion_idempotency_ledger + (credential_id, operation_id, command, response_json, created_at_unix, expires_at_unix) + VALUES (?, ?, ?, ?, ?, ?)", + ) + .bind(credential_id) + .bind(operation_id.to_string()) + .bind(command) + .bind(serialized) + .bind(now) + .bind(expires_at) + .execute(&mut *tx) + .await?; + tx.commit().await?; + Ok(()) + } +} + +#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)] +pub struct TransportSessionTelemetry { + pub replayed_events_count: u64, + pub idempotency_hit_count: u64, + pub last_rtt_ms: Option, +} + +/// Abstract WebRTC PeerConnection engine trait (Section 3.1 & 7.1) decoupling +/// Host business logic from the underlying ICE/DTLS/SCTP implementation +/// (`libdatachannel` / `str0m`). +#[async_trait] +pub trait RtcPeerEngine: Send + Sync { + async fn create_answer(&self, offer_sdp: &str) -> Result<(String, String), ErrorEnvelope>; + + async fn add_ice_candidate(&self, candidate_sdp: &str) -> Result<(), ErrorEnvelope>; + + async fn close(&self); +} + +struct SessionPollingRegistrar; + +#[async_trait] +impl ConversationSubscriptionRegistrar for SessionPollingRegistrar { + async fn register( + &self, + _subscription_id: SubscriptionId, + _conversation_id: ConversationId, + ) -> Result<(), ApplicationError> { + Ok(()) + } +} + +#[derive(Clone, Debug, Eq, PartialEq)] +pub enum SessionSubscription { + Conversation { + conversation_id: ConversationId, + after_sequence: i64, + }, + WorkflowRun { + run_id: uuid::Uuid, + after_sequence: i64, + }, +} + +/// Unified transport session shared by WebRTC DataChannels (`vibex.control.v1` +/// + `vibex.bulk.v1`) and local adapters. +pub struct TransportSession { + credential: AuthenticatedCredential, + auth: Arc, + core: Arc>, + commands: CommandRegistry, + ledger: SqliteIdempotencyLedger, + subscriptions: HashMap, + bulk_queue: VecDeque, + suspended: bool, + telemetry: TransportSessionTelemetry, +} + +impl TransportSession +where + R: ConversationRepository + Send + Sync + 'static, +{ + pub fn new( + credential: AuthenticatedCredential, + auth: Arc, + core: Arc>, + ledger: SqliteIdempotencyLedger, + ) -> Self { + let commands = CommandRegistry::from_core(Arc::clone(&core)); + Self { + credential, + auth, + core, + commands, + ledger, + subscriptions: HashMap::new(), + bulk_queue: VecDeque::new(), + suspended: false, + telemetry: TransportSessionTelemetry::default(), + } + } + + pub const fn telemetry(&self) -> TransportSessionTelemetry { + self.telemetry + } + + pub const fn is_suspended(&self) -> bool { + self.suspended + } + + pub async fn handle_control_frame( + &mut self, + frame: ControlChannelFrame, + ) -> Result, AuthStoreError> { + if !self.auth.is_active(&self.credential).await? { + let op_id = match &frame { + ControlChannelFrame::RpcRequest { operation_id, .. } => *operation_id, + _ => OperationId::new(), + }; + return Ok(vec![ControlChannelFrame::RpcError { + operation_id: op_id, + status: 401, + error: ErrorEnvelope::new( + ErrorCode::Unauthorized, + "credential has been revoked", + false, + op_id, + ), + }]); + } + + self.suspended = false; + match frame { + ControlChannelFrame::RpcRequest { + operation_id, + command, + args, + } => { + if SqliteIdempotencyLedger::is_write_command(&command) + && let Some(cached) = self + .ledger + .lookup(&self.credential.credential_id, operation_id, &command) + .await? + { + self.telemetry.idempotency_hit_count += 1; + return Ok(vec![ControlChannelFrame::from_command_response( + 200, cached, + )]); + } + + let principal = self.credential.principal(); + match self + .commands + .execute_name(&principal, &command, operation_id, args) + .await + { + Ok(response) => { + if SqliteIdempotencyLedger::is_write_command(&command) { + self.ledger + .record( + &self.credential.credential_id, + operation_id, + &command, + &response, + ) + .await?; + } + Ok(vec![ControlChannelFrame::from_command_response( + 200, response, + )]) + } + Err(error) => Ok(vec![ControlChannelFrame::RpcError { + operation_id, + status: status_code_for_error(error.code), + error, + }]), + } + } + ControlChannelFrame::SubClient { payload } => { + Ok(self.handle_subscription_message(payload).await) + } + ControlChannelFrame::Ping { timestamp_ms } => { + Ok(vec![ControlChannelFrame::Pong { timestamp_ms }]) + } + ControlChannelFrame::Pong { timestamp_ms } => { + self.telemetry.last_rtt_ms = Some(timestamp_ms.max(0)); + Ok(Vec::new()) + } + ControlChannelFrame::Suspend => { + self.subscriptions.clear(); + self.suspended = true; + Ok(Vec::new()) + } + ControlChannelFrame::RpcResponse { .. } + | ControlChannelFrame::RpcError { .. } + | ControlChannelFrame::SubServer { .. } => Ok(Vec::new()), + } + } + + async fn handle_subscription_message( + &mut self, + message: SubscriptionClientMessage, + ) -> Vec { + let principal = self.credential.principal(); + match message { + SubscriptionClientMessage::Ping => vec![ControlChannelFrame::SubServer { + payload: SubscriptionServerMessage::Pong, + }], + SubscriptionClientMessage::Detach { subscription_id } => { + self.subscriptions.remove(&subscription_id); + vec![ControlChannelFrame::SubServer { + payload: SubscriptionServerMessage::Detached { + subscription_id, + reason: "client_detached".to_owned(), + }, + }] + } + SubscriptionClientMessage::Attach { + request: + SubscriptionRequest { + subscription_id, + resource, + }, + } => match resource { + SubscriptionResource::Conversation { + conversation_id, + after_sequence, + } => match self + .core + .attach_conversation( + &principal, + subscription_id, + conversation_id, + after_sequence, + &SessionPollingRegistrar, + ) + .await + { + Ok(bootstrap) => { + self.telemetry.replayed_events_count += bootstrap.replay.len() as u64; + self.subscriptions.insert( + subscription_id, + SessionSubscription::Conversation { + conversation_id, + after_sequence: bootstrap.high_water_mark, + }, + ); + bootstrap_to_control_frames(bootstrap) + } + Err(error) => vec![ControlChannelFrame::SubServer { + payload: SubscriptionServerMessage::Error { + error: error.into_envelope(), + subscription_id: Some(subscription_id), + }, + }], + }, + SubscriptionResource::WorkflowRun { + run_id, + after_sequence, + } => match self + .core + .attach_workflow_run(&principal, subscription_id, run_id, after_sequence) + .await + { + Ok(bootstrap) => { + self.telemetry.replayed_events_count += bootstrap.replay.len() as u64; + self.subscriptions.insert( + subscription_id, + SessionSubscription::WorkflowRun { + run_id, + after_sequence: bootstrap.high_water_mark, + }, + ); + bootstrap_to_control_frames(bootstrap) + } + Err(error) => vec![ControlChannelFrame::SubServer { + payload: SubscriptionServerMessage::Error { + error: error.into_envelope(), + subscription_id: Some(subscription_id), + }, + }], + }, + SubscriptionResource::HostEvent { .. } + | SubscriptionResource::PatchStream { .. } => { + vec![ControlChannelFrame::SubServer { + payload: SubscriptionServerMessage::Ready { subscription_id }, + }] + } + }, + } + } + + /// Builds an optional Signaling Piggyback payload (`<= 32KB`) for a mobile + /// client resuming from background (Section 6.3 Scenario 4). + pub async fn build_signaling_piggyback( + &mut self, + cursor: &SignalingResumeCursor, + ) -> Result, ApplicationError> { + let principal = self.credential.principal(); + let bootstrap = self + .core + .attach_conversation( + &principal, + SubscriptionId::new(), + cursor.conversation_id, + cursor.after_sequence, + &SessionPollingRegistrar, + ) + .await?; + let candidate = SignalingPiggybackEvents { + conversation_id: cursor.conversation_id, + events: bootstrap.replay, + high_water_mark: bootstrap.high_water_mark, + }; + let encoded = serde_json::to_vec(&candidate) + .map_err(|err| ApplicationError::internal(err.to_string()))?; + if encoded.len() <= SIGNALING_PIGGYBACK_MAX_BYTES { + self.telemetry.replayed_events_count += candidate.events.len() as u64; + Ok(Some(candidate)) + } else { + Ok(None) + } + } + + /// Enqueues a large payload onto the `vibex.bulk.v1` outbox split into `32KB` chunks. + pub fn enqueue_bulk_payload( + &mut self, + operation_id: OperationId, + content_type: impl Into, + payload: &[u8], + ) { + let frames = BulkChannelFrame::chunk_payload( + operation_id, + content_type, + payload, + BULK_CHUNK_MAX_BYTES, + ); + self.bulk_queue.extend(frames); + } + + /// Drains queued `vibex.bulk.v1` frames while enforcing the `128KB` + /// (`BULK_BUFFERED_HIGH_WATER_BYTES`) SCTP bufferedAmount backpressure ceiling. + pub fn drain_bulk_frames( + &mut self, + buffered_amount_bytes: &mut usize, + ) -> Vec { + let mut out = Vec::new(); + while *buffered_amount_bytes <= BULK_BUFFERED_HIGH_WATER_BYTES { + let Some(frame) = self.bulk_queue.pop_front() else { + break; + }; + let approx_bytes = match &frame { + BulkChannelFrame::BulkChunk { data_base64, .. } => data_base64.len(), + _ => 128, + }; + *buffered_amount_bytes = buffered_amount_bytes.saturating_add(approx_bytes); + out.push(frame); + } + out + } + + /// Processes an inbound `vibex.bulk.v1` control frame such as `bulk_cancel`. + pub fn handle_bulk_frame(&mut self, frame: BulkChannelFrame) { + if let BulkChannelFrame::BulkCancel { operation_id } = frame { + self.bulk_queue.retain(|queued| match queued { + BulkChannelFrame::BulkStart { + operation_id: id, .. + } + | BulkChannelFrame::BulkChunk { + operation_id: id, .. + } + | BulkChannelFrame::BulkEnd { operation_id: id } + | BulkChannelFrame::BulkCancel { operation_id: id } => *id != operation_id, + }); + } + } +} + +fn bootstrap_to_control_frames(bootstrap: SubscriptionBootstrap) -> Vec { + let mut frames = Vec::with_capacity(bootstrap.replay.len() + 3); + frames.push(ControlChannelFrame::SubServer { + payload: SubscriptionServerMessage::Ready { + subscription_id: bootstrap.subscription_id, + }, + }); + if let Some(snapshot) = bootstrap.snapshot { + frames.push(ControlChannelFrame::SubServer { + payload: SubscriptionServerMessage::Snapshot { + subscription_id: bootstrap.subscription_id, + snapshot, + }, + }); + } + for event in bootstrap.replay { + frames.push(ControlChannelFrame::SubServer { + payload: SubscriptionServerMessage::Event { + subscription_id: bootstrap.subscription_id, + event, + }, + }); + } + frames.push(ControlChannelFrame::SubServer { + payload: SubscriptionServerMessage::Live { + subscription_id: bootstrap.subscription_id, + high_water_mark: bootstrap.high_water_mark, + }, + }); + frames +} + +fn status_code_for_error(code: ErrorCode) -> u16 { + match code { + ErrorCode::BadRequest => 400, + ErrorCode::Unauthorized => 401, + ErrorCode::Forbidden => 403, + ErrorCode::NotFound => 404, + ErrorCode::Conflict => 409, + ErrorCode::CapabilityUnavailable => 501, + ErrorCode::Internal => 500, + _ => 500, + } +} diff --git a/crates/server/src/ws.rs b/crates/server/src/ws.rs index d9f303f17..f93486b3a 100644 --- a/crates/server/src/ws.rs +++ b/crates/server/src/ws.rs @@ -19,8 +19,8 @@ use remote_protocol::{ use crate::{AuthenticatedCredential, runtime::ServerState}; -const LIVE_POLL_INTERVAL: Duration = Duration::from_millis(50); -const REVOCATION_POLL_INTERVAL: Duration = Duration::from_secs(1); +const LIVE_POLL_INTERVAL: Duration = Duration::from_millis(12); +const REVOCATION_POLL_INTERVAL: Duration = Duration::from_millis(250); const KEEP_ALIVE_INTERVAL: Duration = Duration::from_secs(15); const MAX_CLIENT_FRAME_BYTES: usize = 1024 * 1024; @@ -74,26 +74,33 @@ impl ActiveSubscription { pub(crate) async fn ws_handler( State(state): State>>, Extension(credential): Extension, + e2ee_session: Option>, upgrade: WebSocketUpgrade, ) -> Response where R: ConversationRepository + Send + Sync + 'static, { + let e2ee = e2ee_session.map(|ext| ext.0); upgrade .max_frame_size(MAX_CLIENT_FRAME_BYTES) .max_message_size(MAX_CLIENT_FRAME_BYTES) .protocols(["vibex.v1"]) - .on_upgrade(move |socket| handle_socket(socket, state, credential)) + .on_upgrade(move |socket| handle_socket(socket, state, credential, e2ee)) } async fn handle_socket( socket: WebSocket, state: Arc>, credential: AuthenticatedCredential, + e2ee_session: Option, ) where R: ConversationRepository + Send + Sync + 'static, { let (mut sender, mut receiver) = socket.split(); + let mut ws_e2ee_key: Option<[u8; 32]> = e2ee_session + .as_ref() + .filter(|s| s.active_e2ee) + .map(|s| s.key); let mut subscriptions = HashMap::::new(); let mut live_ticker = tokio::time::interval(LIVE_POLL_INTERVAL); live_ticker.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip); @@ -125,7 +132,29 @@ async fn handle_socket( Message::Text(text) => text, Message::Binary(_) => continue, }; - let message = match serde_json::from_str::(&text) { + let decoded_text: String = if let Some(ref session) = e2ee_session + && let Ok(wrapper) = serde_json::from_str::(&text) + && wrapper.get("type").and_then(|v| v.as_str()) == Some("e2ee") + { + let Some(cipher_b64) = wrapper.get("d").and_then(|v| v.as_str()) else { + break; + }; + let Ok(plain_bytes) = crate::e2ee::decrypt_payload( + &session.key, + crate::e2ee::AAD_WS, + cipher_b64, + ) else { + break; + }; + let Ok(plain_str) = String::from_utf8(plain_bytes) else { + break; + }; + ws_e2ee_key = Some(session.key); + plain_str + } else { + text.to_string() + }; + let message = match serde_json::from_str::(&decoded_text) { Ok(message) => message, Err(error) => { if send_message( @@ -139,6 +168,7 @@ async fn handle_socket( ), subscription_id: None, }, + ws_e2ee_key.as_ref(), ) .await .is_err() @@ -154,6 +184,7 @@ async fn handle_socket( message, &mut subscriptions, &mut sender, + ws_e2ee_key.as_ref(), ) .await .is_err() @@ -176,6 +207,7 @@ async fn handle_socket( ), subscription_id: None, }, + ws_e2ee_key.as_ref(), ) .await; break; @@ -214,6 +246,7 @@ async fn handle_socket( payload: event.payload.clone(), }, }, + ws_e2ee_key.as_ref(), ) .await .is_err() @@ -274,6 +307,7 @@ async fn handle_socket( subscription_id, event, }, + ws_e2ee_key.as_ref(), ) .await .is_err() @@ -296,6 +330,7 @@ async fn handle_client_message( message: SubscriptionClientMessage, subscriptions: &mut HashMap, sender: &mut S, + e2ee_key: Option<&[u8; 32]>, ) -> Result<(), ()> where R: ConversationRepository + Send + Sync + 'static, @@ -314,12 +349,18 @@ where error, subscription_id: Some(subscription_id), }, + e2ee_key, ) .await?; return Ok(()); } }; - send_message(sender, SubscriptionServerMessage::Ready { subscription_id }).await?; + send_message( + sender, + SubscriptionServerMessage::Ready { subscription_id }, + e2ee_key, + ) + .await?; let mut cursor = active.after_sequence(); if let Some(snapshot) = bootstrap.snapshot { cursor = cursor.max(snapshot.through_sequence); @@ -329,6 +370,7 @@ where subscription_id, snapshot, }, + e2ee_key, ) .await?; } @@ -340,6 +382,7 @@ where subscription_id, event, }, + e2ee_key, ) .await?; } @@ -349,6 +392,7 @@ where subscription_id, high_water_mark: bootstrap.high_water_mark, }, + e2ee_key, ) .await?; subscriptions.insert(subscription_id, { @@ -361,7 +405,7 @@ where subscriptions.remove(&subscription_id); } SubscriptionClientMessage::Ping => { - send_message(sender, SubscriptionServerMessage::Pong).await?; + send_message(sender, SubscriptionServerMessage::Pong, e2ee_key).await?; } } Ok(()) @@ -503,13 +547,29 @@ fn authorize_host_channel(principal: &Principal, channel: &str) -> Result<(), Er Ok(()) } -async fn send_message(sender: &mut S, message: SubscriptionServerMessage) -> Result<(), ()> +async fn send_message( + sender: &mut S, + message: SubscriptionServerMessage, + e2ee_key: Option<&[u8; 32]>, +) -> Result<(), ()> where S: futures::Sink + Unpin, { let text = serde_json::to_string(&message).map_err(|_| ())?; + let wire_text = if let Some(key) = e2ee_key + && let Ok(encrypted) = + crate::e2ee::encrypt_payload(key, crate::e2ee::AAD_WS, text.as_bytes()) + { + serde_json::json!({ + "type": "e2ee", + "d": encrypted, + }) + .to_string() + } else { + text + }; sender - .send(Message::Text(text.into())) + .send(Message::Text(wire_text.into())) .await .map_err(|_| ()) } diff --git a/crates/server/tests/device_pairing.rs b/crates/server/tests/device_pairing.rs index b97e81ce6..d2d383da6 100644 --- a/crates/server/tests/device_pairing.rs +++ b/crates/server/tests/device_pairing.rs @@ -116,6 +116,9 @@ async fn expired_pairing_returns_a_stable_reason() { serde_json::to_vec(&RedeemPairingRequest { pairing_token: challenge.pairing_token, device_name: "expired-device".to_owned(), + public_key_ed25519: None, + client_kind: None, + replace_existing_mobile: false, }) .expect("redeem request"), )) @@ -171,6 +174,9 @@ async fn revoking_a_device_invalidates_http_and_an_existing_websocket() { serde_json::to_vec(&RedeemPairingRequest { pairing_token: challenge.pairing_token, device_name: "revoked-device".to_owned(), + public_key_ed25519: None, + client_kind: None, + replace_existing_mobile: false, }) .expect("redeem request"), )) @@ -317,6 +323,9 @@ async fn pairing_token_can_be_redeemed_exactly_once() { let redeem_request = RedeemPairingRequest { pairing_token: challenge.pairing_token, device_name: "release-smoke-device".to_owned(), + public_key_ed25519: None, + client_kind: None, + replace_existing_mobile: false, }; let redeemed = app .clone() @@ -402,6 +411,9 @@ async fn concurrent_pairing_redemption_has_one_winner() { let redeem = RedeemPairingRequest { pairing_token: challenge.pairing_token, device_name: "concurrent-device".to_owned(), + public_key_ed25519: None, + client_kind: None, + replace_existing_mobile: false, }; let request = || { Request::post("/api/v1/auth/pairings/redeem") diff --git a/crates/server/tests/webrtc_security_and_session.rs b/crates/server/tests/webrtc_security_and_session.rs new file mode 100644 index 000000000..8f54d65ec --- /dev/null +++ b/crates/server/tests/webrtc_security_and_session.rs @@ -0,0 +1,653 @@ +use std::sync::{ + Arc, + atomic::{AtomicI64, Ordering}, +}; + +use base64::{Engine as _, engine::general_purpose::STANDARD as BASE64}; +use remote_protocol::{ + BULK_BUFFERED_HIGH_WATER_BYTES, BULK_BUFFERED_LOW_THRESHOLD_BYTES, BulkChannelFrame, + ChannelBindingClaims, CommandRequest, CommandResponse, ControlChannelFrame, + CreatePairingRequest, DeviceCredential, DeviceId, DevicePermissionPreset, OperationId, + RedeemPairingRequest, SignalingResumeCursor, SubscriptionClientMessage, SubscriptionId, + SubscriptionRequest, SubscriptionResource, SubscriptionServerMessage, +}; +use ring::{ + rand::SystemRandom, + signature::{Ed25519KeyPair, KeyPair}, +}; +use serde_json::json; +use server::{ + AuthClock, AuthStoreError, AuthenticatedCredential, ServerAuth, ServerConfig, ServerRuntime, + SqliteIdempotencyLedger, SqliteServerAuth, TransportSession, TrustWebRtcDeviceRequest, + compute_sas_code, verify_peer_dtls_fingerprint, +}; +use sqlx::sqlite::{SqliteConnectOptions, SqlitePoolOptions}; + +#[derive(Clone, Default)] +struct ManualClock { + now: Arc, +} + +impl ManualClock { + fn new(initial: i64) -> Self { + Self { + now: Arc::new(AtomicI64::new(initial)), + } + } + + fn set(&self, unix_seconds: i64) { + self.now.store(unix_seconds, Ordering::SeqCst); + } +} + +impl AuthClock for ManualClock { + fn unix_seconds(&self) -> i64 { + self.now.load(Ordering::SeqCst) + } +} + +async fn test_auth_with_clock(clock: ManualClock) -> SqliteServerAuth { + let options = SqliteConnectOptions::new() + .filename(":memory:") + .create_if_missing(true) + .foreign_keys(false); + let pool = SqlitePoolOptions::new() + .max_connections(1) + .connect_with(options) + .await + .expect("sqlite memory pool"); + sqlx::migrate!("../db/migrations") + .run(&pool) + .await + .expect("migrations"); + sqlx::query("PRAGMA foreign_keys = OFF") + .execute(&pool) + .await + .expect("disable foreign keys after migrations"); + SqliteServerAuth::with_clock(pool, Arc::new(clock)) +} + +fn generate_ed25519_keypair() -> (Ed25519KeyPair, [u8; 32], String) { + let rng = SystemRandom::new(); + let pkcs8 = Ed25519KeyPair::generate_pkcs8(&rng).expect("generate ed25519 pkcs8"); + let keypair = Ed25519KeyPair::from_pkcs8(pkcs8.as_ref()).expect("parse ed25519 keypair"); + let mut pub_bytes = [0u8; 32]; + pub_bytes.copy_from_slice(keypair.public_key().as_ref()); + let pub_b64 = BASE64.encode(pub_bytes); + (keypair, pub_bytes, pub_b64) +} + +#[tokio::test] +async fn ed25519_channel_binding_verifies_signature_and_blocks_replay_skew_and_fingerprint_mismatch() + { + let clock = ManualClock::new(1_762_660_000); + let auth = test_auth_with_clock(clock.clone()).await; + let owner = AuthenticatedCredential::host_console_owner(); + + let (phone_kp, _phone_pub_bytes, phone_pub_b64) = generate_ed25519_keypair(); + let device_id = DeviceId::new(); + + let record = auth + .trust_webrtc_device( + &owner, + TrustWebRtcDeviceRequest { + device_id, + device_name: "Honor DIO-AN00".to_owned(), + public_key_ed25519: phone_pub_b64.clone(), + preset: DevicePermissionPreset::Companion, + }, + ) + .await + .expect("trust webrtc device"); + assert_eq!(record.device_id, device_id); + assert_eq!( + record.public_key_ed25519.as_deref(), + Some(phone_pub_b64.as_str()) + ); + + let claims = ChannelBindingClaims { + session_nonce: "nonce-001".to_owned(), + sender_device_id: device_id.to_string(), + recipient_device_id: "host-macbook-pro".to_owned(), + unix_timestamp: 1_762_660_010, + dtls_fingerprint: + "AA:BB:CC:DD:EE:FF:00:11:22:33:44:55:66:77:88:99:AA:BB:CC:DD:EE:FF:00:11:22:33:44:55:66:77:88:99" + .to_owned(), + }; + let sig = phone_kp.sign(claims.signing_input().as_bytes()); + let sig_b64 = BASE64.encode(sig.as_ref()); + + // 1. Valid signature & fresh nonce succeeds + let credential = auth + .authenticate_channel_binding("host-macbook-pro", &claims, &sig_b64) + .await + .expect("channel binding auth succeeds"); + assert_eq!(credential.device_id, Some(device_id)); + assert!(credential.allows("conversation.read")); + assert!(credential.allows("conversation.write")); + assert!(!credential.allows("plugin.write")); + + // 2. Replaying the exact same session_nonce is rejected + let replay_err = auth + .authenticate_channel_binding("host-macbook-pro", &claims, &sig_b64) + .await + .expect_err("replay must be rejected"); + assert!(matches!(replay_err, AuthStoreError::ChannelBindingReplay)); + + // 3. Timestamp outside ±60s window is rejected + let stale_claims = ChannelBindingClaims { + session_nonce: "nonce-002".to_owned(), + unix_timestamp: 1_762_660_000 - 65, + ..claims.clone() + }; + let stale_sig = BASE64.encode( + phone_kp + .sign(stale_claims.signing_input().as_bytes()) + .as_ref(), + ); + let skew_err = auth + .authenticate_channel_binding("host-macbook-pro", &stale_claims, &stale_sig) + .await + .expect_err("stale timestamp must be rejected"); + assert!(matches!( + skew_err, + AuthStoreError::ChannelBindingTimestampSkew + )); + + // 4. Wrong recipient host_id is rejected + let wrong_host_claims = ChannelBindingClaims { + session_nonce: "nonce-003".to_owned(), + ..claims.clone() + }; + let wrong_host_sig = BASE64.encode( + phone_kp + .sign(wrong_host_claims.signing_input().as_bytes()) + .as_ref(), + ); + let recipient_err = auth + .authenticate_channel_binding("other-host", &wrong_host_claims, &wrong_host_sig) + .await + .expect_err("wrong recipient must be rejected"); + assert!(matches!( + recipient_err, + AuthStoreError::ChannelBindingRecipientMismatch + )); + + // 5. DTLS peer certificate fingerprint check binds the data channel to the signed SDP fingerprint + assert!(verify_peer_dtls_fingerprint( + &claims.dtls_fingerprint, + "aa:bb:cc:dd:ee:ff:00:11:22:33:44:55:66:77:88:99:aa:bb:cc:dd:ee:ff:00:11:22:33:44:55:66:77:88:99" + )); + assert!(!verify_peer_dtls_fingerprint( + &claims.dtls_fingerprint, + "FF:BB:CC:DD:EE:FF:00:11:22:33:44:55:66:77:88:99:AA:BB:CC:DD:EE:FF:00:11:22:33:44:55:66:77:88:99" + )); +} + +#[tokio::test] +async fn sas_verification_code_and_offline_revocation_sync_close_trust_loop() { + let clock = ManualClock::new(1_762_660_000); + let auth = test_auth_with_clock(clock).await; + let owner = AuthenticatedCredential::host_console_owner(); + + let (_host_kp, host_pub_bytes, _host_pub_b64) = generate_ed25519_keypair(); + let (phone_kp, phone_pub_bytes, phone_pub_b64) = generate_ed25519_keypair(); + + // SAS code is deterministic 4-digit decimal string + let sas_host = compute_sas_code(&host_pub_bytes, &phone_pub_bytes, "nonce-sas-42"); + let sas_phone = compute_sas_code(&host_pub_bytes, &phone_pub_bytes, "nonce-sas-42"); + let sas_diff = compute_sas_code(&host_pub_bytes, &phone_pub_bytes, "nonce-sas-43"); + assert_eq!(sas_host.len(), 4); + assert!(sas_host.chars().all(|c| c.is_ascii_digit())); + assert_eq!(sas_host, sas_phone); + assert_ne!(sas_host, sas_diff); + + // Redeem a LAN/QR pairing that also supplies an Ed25519 public key + let challenge = auth + .create_pairing( + &owner, + CreatePairingRequest { + preset: Some(DevicePermissionPreset::Companion), + requested_scopes: Vec::new(), + ttl_seconds: None, + }, + ) + .await + .expect("create pairing"); + let credential = auth + .redeem_pairing(RedeemPairingRequest { + pairing_token: challenge.pairing_token, + device_name: "iPhone 17 Pro".to_owned(), + public_key_ed25519: Some(phone_pub_b64), + client_kind: None, + replace_existing_mobile: false, + }) + .await + .expect("redeem pairing with ed25519 key"); + + // Offline revocation sync revokes the device before accepting inbound requests + let synced = auth + .sync_revoked_devices(&owner, &[credential.device_id]) + .await + .expect("sync revoked devices"); + assert_eq!(synced, 1); + + // Both bearer token and WebRTC channel binding are now rejected + assert!( + auth.authenticate(&credential.access_token) + .await + .expect("authenticate bearer") + .is_none() + ); + + let claims = ChannelBindingClaims { + session_nonce: "nonce-after-revoke".to_owned(), + sender_device_id: credential.device_id.to_string(), + recipient_device_id: "host-1".to_owned(), + unix_timestamp: 1_762_660_005, + dtls_fingerprint: "AA:BB".to_owned(), + }; + let sig_b64 = BASE64.encode(phone_kp.sign(claims.signing_input().as_bytes()).as_ref()); + let err = auth + .authenticate_channel_binding("host-1", &claims, &sig_b64) + .await + .expect_err("revoked device must fail channel binding"); + assert!(matches!(err, AuthStoreError::DeviceNotFound)); +} + +#[tokio::test] +async fn idempotency_ledger_and_transport_session_deduplicate_retries_replay_events_and_enforce_bulk_backpressure() + { + use application::{ApplicationCore, SqliteConversationRepository}; + use axum::{ + body::{Body, to_bytes}, + http::{Request, StatusCode}, + }; + use tower::ServiceExt; + + let clock = ManualClock::new(1_762_660_000); + let options = SqliteConnectOptions::new() + .filename(":memory:") + .create_if_missing(true) + .foreign_keys(false); + let pool = SqlitePoolOptions::new() + .max_connections(1) + .connect_with(options) + .await + .expect("sqlite memory pool"); + sqlx::migrate!("../db/migrations") + .run(&pool) + .await + .expect("migrations"); + sqlx::query("PRAGMA foreign_keys = OFF") + .execute(&pool) + .await + .expect("disable foreign keys after migrations"); + + let auth = Arc::new(SqliteServerAuth::with_clock( + pool.clone(), + Arc::new(clock.clone()), + )); + let owner = AuthenticatedCredential::host_console_owner(); + let challenge = auth + .create_pairing( + &owner, + CreatePairingRequest { + preset: Some(DevicePermissionPreset::Companion), + requested_scopes: Vec::new(), + ttl_seconds: None, + }, + ) + .await + .expect("issue pairing"); + let device: DeviceCredential = auth + .redeem_pairing(RedeemPairingRequest { + pairing_token: challenge.pairing_token, + device_name: "Pixel 9 Pro".to_owned(), + public_key_ed25519: None, + client_kind: None, + replace_existing_mobile: false, + }) + .await + .expect("redeem pairing"); + let credential = auth + .authenticate(&device.access_token) + .await + .expect("auth") + .expect("active device credential"); + + let core = Arc::new(ApplicationCore::new(SqliteConversationRepository::new( + pool.clone(), + ))); + let ledger = SqliteIdempotencyLedger::with_clock(pool.clone(), Arc::new(clock.clone())); + let mut session = TransportSession::new( + credential.clone(), + Arc::clone(&auth) as Arc, + Arc::clone(&core), + ledger.clone(), + ); + + // 1. Scenario S7: Send `conversation_create` with same `operation_id` twice over WebRTC control channel + let workspace_id = uuid::Uuid::new_v4(); + let create_op = OperationId::new(); + let create_args = json!({ + "workspaceId": workspace_id, + "agentId": "claude-code", + "title": "WebRTC Retry Test" + }); + let create_frame = ControlChannelFrame::RpcRequest { + operation_id: create_op, + command: "conversation_create".to_owned(), + args: create_args.clone(), + }; + let first_frames = session + .handle_control_frame(create_frame.clone()) + .await + .expect("first create call"); + let first_id = match &first_frames[0] { + ControlChannelFrame::RpcResponse { + operation_id, + status: 200, + data, + } => { + assert_eq!(*operation_id, create_op); + data["id"].as_str().expect("conversation id").to_owned() + } + other => panic!("unexpected frame: {other:?}"), + }; + + // Retry the exact same operation_id (simulating reconnect after packet loss) + let retry_frames = session + .handle_control_frame(create_frame) + .await + .expect("retry create call"); + let retry_id = match &retry_frames[0] { + ControlChannelFrame::RpcResponse { + operation_id, + status: 200, + data, + } => { + assert_eq!(*operation_id, create_op); + data["id"].as_str().expect("conversation id").to_owned() + } + other => panic!("unexpected retry frame: {other:?}"), + }; + assert_eq!( + first_id, retry_id, + "idempotency ledger must replay the exact same created conversation without creating a duplicate" + ); + assert_eq!(session.telemetry().idempotency_hit_count, 1); + + // Also verify HTTP `/api/v1/call/conversation_create` shares the same idempotency ledger + let runtime = ServerRuntime::from_auth_with_preview_proxy( + ServerConfig::default(), + Arc::clone(&auth) as Arc, + ApplicationCore::new(SqliteConversationRepository::new(pool.clone())), + server::PreviewProxyRegistry::default(), + ) + .with_idempotency_ledger(ledger.clone()); + let app = runtime.router(); + let http_retry = app + .oneshot( + Request::post("/api/v1/call/conversation_create") + .header("authorization", format!("Bearer {}", device.access_token)) + .header("content-type", "application/json") + .body(Body::from( + serde_json::to_vec(&CommandRequest { + operation_id: create_op, + args: create_args, + }) + .expect("serialize request"), + )) + .expect("http request"), + ) + .await + .expect("http response"); + assert_eq!(http_retry.status(), StatusCode::OK); + let http_body: CommandResponse = serde_json::from_slice( + &to_bytes(http_retry.into_body(), 64 * 1024) + .await + .expect("body"), + ) + .expect("json response"); + assert_eq!(http_body.data["id"].as_str(), Some(first_id.as_str())); + + // 2. Scenario S6 & S8: Subscribe via `sub_client` (`attach`) and verify Signaling Piggyback + let conv_id = remote_protocol::ConversationId::parse(&first_id).expect("parse conv id"); + let sub_id = SubscriptionId::new(); + let attach_frames = session + .handle_control_frame(ControlChannelFrame::SubClient { + payload: SubscriptionClientMessage::Attach { + request: SubscriptionRequest { + subscription_id: sub_id, + resource: SubscriptionResource::Conversation { + conversation_id: conv_id, + after_sequence: 0, + }, + }, + }, + }) + .await + .expect("attach conversation"); + assert!(attach_frames.iter().any(|frame| matches!( + frame, + ControlChannelFrame::SubServer { + payload: SubscriptionServerMessage::Ready { subscription_id } + } if *subscription_id == sub_id + ))); + assert!(attach_frames.iter().any(|frame| matches!( + frame, + ControlChannelFrame::SubServer { + payload: SubscriptionServerMessage::Live { subscription_id, .. } + } if *subscription_id == sub_id + ))); + + // Signaling Piggyback for foreground resume returns events when <= 32KB + let piggyback = session + .build_signaling_piggyback(&SignalingResumeCursor { + conversation_id: conv_id, + after_sequence: 0, + }) + .await + .expect("build piggyback") + .expect("piggyback fits in 32KB"); + assert_eq!(piggyback.conversation_id, conv_id); + + // 3. Scenario S9: Bulk channel chunking + 128KB high-water backpressure + mid-flight `bulk_cancel` + let bulk_op = OperationId::new(); + let large_diff = vec![b'+'; 100 * 1024]; // 100 KB payload -> 4 chunks of 32KB/32KB/32KB/4KB + session.enqueue_bulk_payload(bulk_op, "text/x-patch", &large_diff); + + // Simulate bufferedAmount = 120KB: draining one 32KB chunk pushes bufferedAmount > 128KB high-water mark, pausing further chunks + let mut simulated_buffered = 120 * 1024; + let drained_before_pause = session.drain_bulk_frames(&mut simulated_buffered); + assert_eq!( + drained_before_pause.len(), + 2, // BulkStart + first BulkChunk, then paused because simulated_buffered > BULK_BUFFERED_HIGH_WATER_BYTES + "must pause bulk writes as soon as buffered_amount exceeds 128KB" + ); + assert!(simulated_buffered > BULK_BUFFERED_HIGH_WATER_BYTES); + + // Control channel Ping still executes with zero head-of-line delay while bulk channel is paused + let pong = session + .handle_control_frame(ControlChannelFrame::Ping { + timestamp_ms: 123_456, + }) + .await + .expect("control ping during bulk backpressure"); + assert_eq!( + pong, + vec![ControlChannelFrame::Pong { + timestamp_ms: 123_456 + }] + ); + + // Cancel the remaining bulk transfer mid-flight (`bulk_cancel`) + session.handle_bulk_frame(BulkChannelFrame::BulkCancel { + operation_id: bulk_op, + }); + simulated_buffered = BULK_BUFFERED_LOW_THRESHOLD_BYTES / 2; + let drained_after_cancel = session.drain_bulk_frames(&mut simulated_buffered); + assert!( + drained_after_cancel.is_empty(), + "bulk_cancel must drop remaining queued chunks for that operation_id" + ); + + // 4. Scenario S10: Revoking the device immediately rejects subsequent control frames + clock.set(1_762_660_100); + auth.revoke_device(&owner, device.device_id) + .await + .expect("revoke device"); + let revoked_resp = session + .handle_control_frame(ControlChannelFrame::RpcRequest { + operation_id: OperationId::new(), + command: "conversation_list".to_owned(), + args: json!({}), + }) + .await + .expect("revoked device returns error frame"); + assert!(matches!( + &revoked_resp[0], + ControlChannelFrame::RpcError { status: 401, .. } + )); +} + +#[tokio::test] +async fn mobile_zero_config_connect_request_triggers_host_prompt_and_approves_with_ed25519_key() { + use application::{ApplicationCore, SqliteConversationRepository}; + use axum::{ + body::{Body, to_bytes}, + http::{Request, StatusCode}, + }; + use remote_protocol::{ + CreateDeviceConnectRequest, DeviceConnectRequestStatus, PendingDeviceConnectRequest, + PollDeviceConnectResponse, + }; + use tower::ServiceExt; + + let clock = ManualClock::new(1_762_660_000); + let auth = Arc::new(test_auth_with_clock(clock.clone()).await); + let options = SqliteConnectOptions::new() + .filename(":memory:") + .create_if_missing(true) + .foreign_keys(false); + let pool = SqlitePoolOptions::new() + .max_connections(1) + .connect_with(options) + .await + .expect("sqlite memory pool"); + sqlx::migrate!("../db/migrations") + .run(&pool) + .await + .expect("migrations"); + let runtime = ServerRuntime::from_auth_with_preview_proxy( + ServerConfig::default().with_host_identity("host-desktop-1", Vec::new()), + Arc::clone(&auth) as Arc, + ApplicationCore::new(SqliteConversationRepository::new(pool)), + server::PreviewProxyRegistry::default(), + ); + + let rng = SystemRandom::new(); + let pkcs8 = Ed25519KeyPair::generate_pkcs8(&rng).expect("ed25519 keygen"); + let keypair = Ed25519KeyPair::from_pkcs8(pkcs8.as_ref()).expect("parse keypair"); + let pubkey_b64 = BASE64.encode(keypair.public_key().as_ref()); + + // 1. Mobile sends POST /api/v1/auth/connect-requests on first-time launch + let create_resp = runtime + .router() + .oneshot( + Request::post("/api/v1/auth/connect-requests") + .header("content-type", "application/json") + .header("x-forwarded-for", "192.168.1.88") + .body(Body::from( + serde_json::to_vec(&CreateDeviceConnectRequest { + device_name: "iPhone 16 Pro".to_owned(), + client_kind: Some("mobile".to_owned()), + public_key_ed25519: Some(pubkey_b64.clone()), + session_nonce: Some("first-connect-nonce".to_owned()), + replace_existing_mobile: false, + }) + .expect("serialize"), + )) + .expect("request"), + ) + .await + .expect("response"); + assert_eq!(create_resp.status(), StatusCode::CREATED); + let created: PollDeviceConnectResponse = serde_json::from_slice( + &to_bytes(create_resp.into_body(), 16 * 1024) + .await + .expect("body"), + ) + .expect("json"); + assert_eq!(created.status, DeviceConnectRequestStatus::Pending); + assert_eq!(created.sas_code.len(), 4); + assert!(created.credential.is_none()); + + // 2. Desktop Host lists pending connect requests (for red-box banner prompt) + let owner = AuthenticatedCredential::host_console_owner(); + let pending: Vec = auth + .list_connect_requests(&owner) + .await + .expect("list pending requests"); + assert_eq!(pending.len(), 1); + assert_eq!(pending[0].request_id, created.request_id); + assert_eq!(pending[0].device_name, "iPhone 16 Pro"); + assert_eq!(pending[0].ip_address.as_deref(), Some("192.168.1.88")); + assert_eq!(pending[0].sas_code, created.sas_code); + + // 3. User clicks "连接" on Desktop red-box banner -> approves request + auth.respond_connect_request(&owner, created.request_id, true) + .await + .expect("approve connect request"); + assert!( + auth.list_connect_requests(&owner) + .await + .expect("list after approve") + .is_empty(), + "approved request must no longer appear in pending banner list" + ); + + // 4. Mobile polls GET /api/v1/auth/connect-requests/{id} and receives one-time DeviceCredential + let poll_resp = runtime + .router() + .oneshot( + Request::get(format!( + "/api/v1/auth/connect-requests/{}", + created.request_id + )) + .body(Body::empty()) + .expect("poll request"), + ) + .await + .expect("poll response"); + assert_eq!(poll_resp.status(), StatusCode::OK); + let approved: PollDeviceConnectResponse = serde_json::from_slice( + &to_bytes(poll_resp.into_body(), 16 * 1024) + .await + .expect("body"), + ) + .expect("json"); + assert_eq!(approved.status, DeviceConnectRequestStatus::Approved); + let credential = approved + .credential + .expect("one-time credential must be returned"); + assert!(credential.access_token.starts_with("vbx_device_")); + + // Subsequent poll sees Approved but credential is None (one-time delivery) + let second_poll = auth + .poll_connect_request("host-desktop-1", created.request_id) + .await + .expect("second poll"); + assert_eq!(second_poll.status, DeviceConnectRequestStatus::Approved); + assert!(second_poll.credential.is_none()); + + // And the device is registered with its Ed25519 key in paired devices list + let paired = auth.list_devices(&owner).await.expect("paired devices"); + assert_eq!(paired.len(), 1); + assert_eq!(paired[0].device_id, credential.device_id); + assert_eq!( + paired[0].public_key_ed25519.as_deref(), + Some(pubkey_b64.as_str()) + ); +} diff --git a/crates/utils/src/net.rs b/crates/utils/src/net.rs index bfbc3842b..393c7fe27 100644 --- a/crates/utils/src/net.rs +++ b/crates/utils/src/net.rs @@ -23,7 +23,14 @@ pub struct AdvertisedListenAddress { } pub fn is_advertisable_ipv4(ip: Ipv4Addr) -> bool { - !ip.is_loopback() && !ip.is_unspecified() && !ip.is_link_local() && !ip.is_multicast() + let [a, b, _, _] = ip.octets(); + let is_benchmarking = a == 198 && (b == 18 || b == 19); + !ip.is_loopback() + && !ip.is_unspecified() + && !ip.is_link_local() + && !ip.is_multicast() + && !ip.is_broadcast() + && !is_benchmarking } pub fn is_advertisable_ip(ip: IpAddr) -> bool { @@ -39,6 +46,430 @@ pub fn is_advertisable_ip(ip: IpAddr) -> bool { } } +/// Returns true when `ip` belongs to Tailscale's CGNAT range (`100.64.0.0/10`) +/// or Tailscale's ULA prefix (`fd7a:115c:a1e0::/48`). +pub fn is_tailscale_ip(ip: IpAddr) -> bool { + match ip { + IpAddr::V4(ip) => { + let [a, b, _, _] = ip.octets(); + a == 100 && (64..=127).contains(&b) + } + IpAddr::V6(ip) => { + let segments = ip.segments(); + segments[0] == 0xfd7a && segments[1] == 0x115c && segments[2] == 0xa1e0 + } + } +} + +fn is_virtual_tunnel_interface_name(interface_name: &str) -> bool { + let lower = interface_name.trim().to_ascii_lowercase(); + const BLACKLIST_PREFIXES: &[&str] = &[ + "utun", "tun", "tap", "veth", "docker", "br-", "vmnet", "vboxnet", "virbr", "wg", "mihomo", + "clash", "surge", "singbox", + ]; + BLACKLIST_PREFIXES + .iter() + .any(|prefix| lower.starts_with(prefix)) +} + +/// Checks whether a local `(interface_name, ip)` pair is eligible as a WebRTC +/// Host Candidate or physical LAN reachability address (filtering proxy TUN +/// adapters and Fake-IP ranges while preserving Tailscale). +pub fn is_webrtc_host_candidate_eligible(interface_name: &str, ip: IpAddr) -> bool { + if !is_advertisable_ip(ip) { + return false; + } + if is_tailscale_ip(ip) { + return true; + } + !is_virtual_tunnel_interface_name(interface_name) +} + +/// Bind a UDP socket (used for STUN / TURN / WebRTC transport) directly to a +/// named physical network interface (`IP_BOUND_IF` on macOS, `SO_BINDTODEVICE` +/// on Linux) so proxy TUN default routes cannot hijack the socket. +pub fn bind_udp_socket_to_interface( + socket: &UdpSocket, + interface_name: &str, +) -> std::io::Result<()> { + let trimmed = interface_name.trim(); + if trimmed.is_empty() || trimmed.contains('\0') { + return Err(std::io::Error::new( + std::io::ErrorKind::InvalidInput, + "interface name must be non-empty and not contain NUL", + )); + } + + #[cfg(target_os = "macos")] + { + use std::{ffi::CString, os::fd::AsRawFd}; + + let c_name = CString::new(trimmed).map_err(|_| { + std::io::Error::new(std::io::ErrorKind::InvalidInput, "invalid interface name") + })?; + let index = unsafe { libc::if_nametoindex(c_name.as_ptr()) }; + if index == 0 { + return Err(std::io::Error::new( + std::io::ErrorKind::NotFound, + format!("network interface '{trimmed}' not found"), + )); + } + let raw_fd = socket.as_raw_fd(); + let rc = unsafe { + libc::setsockopt( + raw_fd, + libc::IPPROTO_IP, + libc::IP_BOUND_IF, + (&raw const index).cast::(), + std::mem::size_of::() as libc::socklen_t, + ) + }; + if rc != 0 { + return Err(std::io::Error::last_os_error()); + } + Ok(()) + } + + #[cfg(target_os = "linux")] + { + use std::{ffi::CString, os::fd::AsRawFd}; + + let c_name = CString::new(trimmed).map_err(|_| { + std::io::Error::new(std::io::ErrorKind::InvalidInput, "invalid interface name") + })?; + let index = unsafe { libc::if_nametoindex(c_name.as_ptr()) }; + if index == 0 { + return Err(std::io::Error::new( + std::io::ErrorKind::NotFound, + format!("network interface '{trimmed}' not found"), + )); + } + let bytes = c_name.as_bytes_with_nul(); + let rc = unsafe { + libc::setsockopt( + socket.as_raw_fd(), + libc::SOL_SOCKET, + libc::SO_BINDTODEVICE, + bytes.as_ptr().cast::(), + bytes.len() as libc::socklen_t, + ) + }; + if rc != 0 { + return Err(std::io::Error::last_os_error()); + } + Ok(()) + } + + #[cfg(not(any(target_os = "macos", target_os = "linux")))] + { + let exists = host_interface_addresses() + .iter() + .any(|addr| addr.name.eq_ignore_ascii_case(trimmed)); + let _ = socket; + if !exists { + return Err(std::io::Error::new( + std::io::ErrorKind::NotFound, + format!("network interface '{trimmed}' not found"), + )); + } + Ok(()) + } +} + +/// Returns the OS name of the primary active physical IPv4 network interface +/// (e.g. `"en0"` on macOS or `"eth0"` / `"wlan0"` on Linux), excluding loopback, +/// proxy TUN adapters (`utun*`, `tun*`), and Tailscale interfaces. +pub fn primary_physical_interface_name() -> Option { + host_interface_addresses() + .into_iter() + .find(|addr| { + addr.family == "ipv4" + && !addr.name.trim().is_empty() + && !is_virtual_tunnel_interface_name(&addr.name) + && addr + .ip + .parse::() + .is_ok_and(|ip| is_advertisable_ip(ip) && !is_tailscale_ip(ip)) + }) + .map(|addr| addr.name) +} + +/// Bind a `tokio::net::TcpSocket` directly to a named physical network interface +/// (`IP_BOUND_IF` on macOS, `SO_BINDTODEVICE` on Linux) so proxy TUN routes +/// cannot hijack domestic relay connections. +pub fn bind_tcp_socket_to_interface( + socket: &tokio::net::TcpSocket, + interface_name: &str, +) -> std::io::Result<()> { + let trimmed = interface_name.trim(); + if trimmed.is_empty() || trimmed.contains('\0') { + return Err(std::io::Error::new( + std::io::ErrorKind::InvalidInput, + "interface name must be non-empty and not contain NUL", + )); + } + + #[cfg(target_os = "macos")] + { + use std::{ffi::CString, os::fd::AsRawFd}; + + let c_name = CString::new(trimmed).map_err(|_| { + std::io::Error::new(std::io::ErrorKind::InvalidInput, "invalid interface name") + })?; + let index = unsafe { libc::if_nametoindex(c_name.as_ptr()) }; + if index == 0 { + return Err(std::io::Error::new( + std::io::ErrorKind::NotFound, + format!("network interface '{trimmed}' not found"), + )); + } + let rc = unsafe { + libc::setsockopt( + socket.as_raw_fd(), + libc::IPPROTO_IP, + libc::IP_BOUND_IF, + (&raw const index).cast::(), + std::mem::size_of::() as libc::socklen_t, + ) + }; + if rc != 0 { + return Err(std::io::Error::last_os_error()); + } + Ok(()) + } + + #[cfg(target_os = "linux")] + { + use std::{ffi::CString, os::fd::AsRawFd}; + + let c_name = CString::new(trimmed).map_err(|_| { + std::io::Error::new(std::io::ErrorKind::InvalidInput, "invalid interface name") + })?; + let index = unsafe { libc::if_nametoindex(c_name.as_ptr()) }; + if index == 0 { + return Err(std::io::Error::new( + std::io::ErrorKind::NotFound, + format!("network interface '{trimmed}' not found"), + )); + } + let bytes = c_name.as_bytes_with_nul(); + let rc = unsafe { + libc::setsockopt( + socket.as_raw_fd(), + libc::SOL_SOCKET, + libc::SO_BINDTODEVICE, + bytes.as_ptr().cast::(), + bytes.len() as libc::socklen_t, + ) + }; + if rc != 0 { + return Err(std::io::Error::last_os_error()); + } + Ok(()) + } + + #[cfg(not(any(target_os = "macos", target_os = "linux")))] + { + let _ = socket; + let _ = trimmed; + Ok(()) + } +} + +/// Connect a TCP stream to `addr` with `TCP_NODELAY = true`, preferring the +/// primary physical network interface (`IP_BOUND_IF` / `SO_BINDTODEVICE`) for +/// non-loopback IPv4 targets so Clash/Mihomo TUN routes are bypassed. +pub async fn connect_tcp_bypassing_tun(addr: SocketAddr) -> std::io::Result { + if let SocketAddr::V4(v4_addr) = addr + && !v4_addr.ip().is_loopback() + && let Some(iface) = primary_physical_interface_name() + && let Ok(socket) = tokio::net::TcpSocket::new_v4() + { + let _ = socket.set_nodelay(true); + if bind_tcp_socket_to_interface(&socket, &iface).is_ok() + && let Ok(Ok(stream)) = + tokio::time::timeout(std::time::Duration::from_secs(4), socket.connect(addr)).await + { + let _ = stream.set_nodelay(true); + return Ok(stream); + } + } + + let stream = tokio::net::TcpStream::connect(addr).await?; + let _ = stream.set_nodelay(true); + Ok(stream) +} + +static DIRECT_DNS_CACHE: std::sync::LazyLock< + std::sync::Mutex>, +> = std::sync::LazyLock::new(|| std::sync::Mutex::new(std::collections::HashMap::new())); + +/// Resolve `host:port` to a real IPv4 `SocketAddr`, bypassing Clash Fake-IP DNS +/// (`198.18.0.0/15`) by querying `223.5.5.5:53` / `119.29.29.29:53` over the +/// physical interface when `host` is a domain name, with a 5-minute TTL cache. +pub fn resolve_host_ipv4_direct(host: &str, port: u16) -> Option { + let trimmed = host.trim().trim_matches(|ch| ch == '[' || ch == ']'); + if trimmed.is_empty() { + return None; + } + if trimmed.eq_ignore_ascii_case("localhost") { + return Some(SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), port)); + } + if let Ok(ip) = trimmed.parse::() { + return Some(SocketAddr::new(ip, port)); + } + + let cache_key = trimmed.to_ascii_lowercase(); + if let Ok(guard) = DIRECT_DNS_CACHE.lock() + && let Some((cached_ip, ts)) = guard.get(&cache_key) + && ts.elapsed() < std::time::Duration::from_secs(300) + { + return Some(SocketAddr::new(IpAddr::V4(*cached_ip), port)); + } + + // 1. Try direct UDP or TCP DNS A-record query to 223.5.5.5:53 / 119.29.29.29:53 bound to physical interface + if let Some(ip) = query_dns_a_record_direct(trimmed, Ipv4Addr::new(223, 5, 5, 5)) + .or_else(|| query_dns_a_record_direct(trimmed, Ipv4Addr::new(119, 29, 29, 29))) + .or_else(|| query_dns_a_record_tcp_direct(trimmed, Ipv4Addr::new(223, 5, 5, 5))) + .or_else(|| query_dns_a_record_tcp_direct(trimmed, Ipv4Addr::new(119, 29, 29, 29))) + { + if let Ok(mut guard) = DIRECT_DNS_CACHE.lock() { + guard.insert(cache_key, (ip, std::time::Instant::now())); + } + return Some(SocketAddr::new(IpAddr::V4(ip), port)); + } + + // 2. Fallback to system resolver, rejecting Fake-IP (198.18.0.0/15) + let resolved = (trimmed, port) + .to_socket_addrs() + .ok()? + .find(|addr| match addr.ip() { + IpAddr::V4(v4) => { + let [a, b, _, _] = v4.octets(); + !(a == 198 && (b == 18 || b == 19)) + } + IpAddr::V6(_) => true, + })?; + if let IpAddr::V4(v4) = resolved.ip() + && let Ok(mut guard) = DIRECT_DNS_CACHE.lock() + { + guard.insert(cache_key, (v4, std::time::Instant::now())); + } + Some(resolved) +} + +fn build_dns_a_query_packet(domain: &str) -> Option> { + let mut packet = Vec::with_capacity(64); + packet.extend_from_slice(&[ + 0x56, 0x58, 0x01, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + ]); + for label in domain.split('.') { + let bytes = label.as_bytes(); + if bytes.is_empty() || bytes.len() > 63 { + return None; + } + packet.push(bytes.len() as u8); + packet.extend_from_slice(bytes); + } + packet.push(0x00); + packet.extend_from_slice(&[0x00, 0x01, 0x00, 0x01]); + Some(packet) +} + +fn parse_dns_a_response_packet(buf: &[u8]) -> Option { + let n = buf.len(); + if n < 12 || buf[0] != 0x56 || buf[1] != 0x58 { + return None; + } + let ancount = u16::from_be_bytes([buf[6], buf[7]]) as usize; + if ancount == 0 { + return None; + } + + let mut idx = 12; + while idx < n && buf[idx] != 0 { + let len = buf[idx] as usize; + idx += 1 + len; + } + idx += 5; + + for _ in 0..ancount { + if idx + 10 > n { + break; + } + if buf[idx] & 0xC0 == 0xC0 { + idx += 2; + } else { + while idx < n && buf[idx] != 0 { + idx += 1 + (buf[idx] as usize); + } + idx += 1; + } + if idx + 10 > n { + break; + } + let rtype = u16::from_be_bytes([buf[idx], buf[idx + 1]]); + let rdlen = u16::from_be_bytes([buf[idx + 8], buf[idx + 9]]) as usize; + idx += 10; + if idx + rdlen > n { + break; + } + if rtype == 1 && rdlen == 4 { + let ip = Ipv4Addr::new(buf[idx], buf[idx + 1], buf[idx + 2], buf[idx + 3]); + let [a, b, _, _] = ip.octets(); + if !(a == 198 && (b == 18 || b == 19)) && !ip.is_unspecified() { + return Some(ip); + } + } + idx += rdlen; + } + None +} + +fn query_dns_a_record_direct(domain: &str, dns_server: Ipv4Addr) -> Option { + use std::time::Duration; + + let socket = UdpSocket::bind((Ipv4Addr::UNSPECIFIED, 0)).ok()?; + if let Some(iface) = primary_physical_interface_name() { + let _ = bind_udp_socket_to_interface(&socket, &iface); + } + let _ = socket.set_read_timeout(Some(Duration::from_millis(1200))); + let _ = socket.set_write_timeout(Some(Duration::from_millis(1200))); + + let packet = build_dns_a_query_packet(domain)?; + socket + .send_to(&packet, SocketAddr::new(IpAddr::V4(dns_server), 53)) + .ok()?; + let mut buf = [0u8; 512]; + let (n, _) = socket.recv_from(&mut buf).ok()?; + parse_dns_a_response_packet(&buf[..n]) +} + +fn query_dns_a_record_tcp_direct(domain: &str, dns_server: Ipv4Addr) -> Option { + use std::{ + io::{Read, Write}, + time::Duration, + }; + + let packet = build_dns_a_query_packet(domain)?; + let target = SocketAddr::new(IpAddr::V4(dns_server), 53); + let mut stream = TcpStream::connect_timeout(&target, Duration::from_millis(1500)).ok()?; + let _ = stream.set_read_timeout(Some(Duration::from_millis(1500))); + let _ = stream.set_write_timeout(Some(Duration::from_millis(1500))); + let len_prefix = (packet.len() as u16).to_be_bytes(); + stream.write_all(&len_prefix).ok()?; + stream.write_all(&packet).ok()?; + let mut resp_len_bytes = [0u8; 2]; + stream.read_exact(&mut resp_len_bytes).ok()?; + let resp_len = u16::from_be_bytes(resp_len_bytes) as usize; + if resp_len < 12 || resp_len > 2048 { + return None; + } + let mut buf = vec![0u8; resp_len]; + stream.read_exact(&mut buf).ok()?; + parse_dns_a_response_packet(&buf) +} + pub fn http_origin(ip: IpAddr, port: u16) -> String { match ip { IpAddr::V4(ip) => format!("http://{ip}:{port}"), @@ -76,8 +507,10 @@ pub fn host_interface_addresses() -> Vec { .iter() .find(|address| address.ip == ip.to_string()) { - push(address.clone()); - } else { + if is_webrtc_host_candidate_eligible(&address.name, IpAddr::V4(ip)) { + push(address.clone()); + } + } else if is_webrtc_host_candidate_eligible("", IpAddr::V4(ip)) { push(HostInterfaceAddress { name: String::new(), ip: ip.to_string(), @@ -88,7 +521,7 @@ pub fn host_interface_addresses() -> Vec { for address in enumerated { if let Ok(ip) = address.ip.parse::() - && is_advertisable_ip(ip) + && is_webrtc_host_candidate_eligible(&address.name, ip) { push(address); } @@ -491,4 +924,75 @@ mod tests { ); } } + + #[test] + fn webrtc_candidate_filter_rejects_proxy_tun_and_fake_ip_but_keeps_tailscale_and_physical_lan() + { + use std::net::Ipv4Addr; + + use super::{is_tailscale_ip, is_webrtc_host_candidate_eligible}; + + // Physical Wi-Fi / Ethernet LAN + assert!(is_webrtc_host_candidate_eligible( + "en0", + IpAddr::V4(Ipv4Addr::new(192, 168, 1, 25)) + )); + assert!(is_webrtc_host_candidate_eligible( + "eth0", + IpAddr::V4(Ipv4Addr::new(10, 0, 1, 15)) + )); + + // Clash / Surge / Mihomo Fake-IP benchmark range 198.18.0.0/15 on any interface + assert!(!is_webrtc_host_candidate_eligible( + "en0", + IpAddr::V4(Ipv4Addr::new(198, 18, 0, 1)) + )); + assert!(!is_webrtc_host_candidate_eligible( + "utun3", + IpAddr::V4(Ipv4Addr::new(198, 19, 255, 254)) + )); + + // Non-Tailscale proxy TUN / container / virtual interfaces using private subnets + assert!(!is_webrtc_host_candidate_eligible( + "utun4", + IpAddr::V4(Ipv4Addr::new(172, 19, 0, 1)) + )); + assert!(!is_webrtc_host_candidate_eligible( + "tun0", + IpAddr::V4(Ipv4Addr::new(10, 8, 0, 2)) + )); + assert!(!is_webrtc_host_candidate_eligible( + "tap0", + IpAddr::V4(Ipv4Addr::new(10, 9, 0, 2)) + )); + assert!(!is_webrtc_host_candidate_eligible( + "docker0", + IpAddr::V4(Ipv4Addr::new(172, 17, 0, 1)) + )); + assert!(!is_webrtc_host_candidate_eligible( + "veth1a2b3c", + IpAddr::V4(Ipv4Addr::new(172, 18, 0, 2)) + )); + + // Tailscale CGNAT (100.64.0.0/10) and Tailscale ULA (fd7a:115c:a1e0::/48) on utun / tailscale0 are allowed + let ts_v4 = IpAddr::V4(Ipv4Addr::new(100, 101, 102, 103)); + let ts_v6 = IpAddr::V6(Ipv6Addr::new(0xfd7a, 0x115c, 0xa1e0, 0, 0, 0, 0, 1)); + assert!(is_tailscale_ip(ts_v4)); + assert!(is_tailscale_ip(ts_v6)); + assert!(is_webrtc_host_candidate_eligible("utun2", ts_v4)); + assert!(is_webrtc_host_candidate_eligible("tailscale0", ts_v4)); + assert!(is_webrtc_host_candidate_eligible("utun2", ts_v6)); + } + + #[test] + fn bind_udp_socket_to_interface_rejects_nonexistent_interface() { + use std::net::{Ipv4Addr, UdpSocket}; + + use super::bind_udp_socket_to_interface; + + let socket = UdpSocket::bind((Ipv4Addr::UNSPECIFIED, 0)).expect("bind udp"); + let err = bind_udp_socket_to_interface(&socket, "vibex_nonexistent_if99") + .expect_err("nonexistent interface must fail"); + assert_eq!(err.kind(), std::io::ErrorKind::NotFound); + } } diff --git a/crates/utils/src/tunnel.rs b/crates/utils/src/tunnel.rs index e4dfb92d0..5112a4b9f 100644 --- a/crates/utils/src/tunnel.rs +++ b/crates/utils/src/tunnel.rs @@ -3,6 +3,41 @@ use std::net::IpAddr; pub const DEFAULT_TUNNEL_PORT: u16 = 17891; +pub const DEFAULT_OFFICIAL_RELAY_HOST: &str = ""; +pub const DEFAULT_OFFICIAL_RELAY_PORT: u16 = 443; +pub const RELAY_HEARTBEAT_INTERVAL_MS: u64 = 15_000; +pub const RELAY_CONTROL_TIMEOUT_MS: u64 = 45_000; +pub const HAPPY_EYEBALLS_LAN_WINDOW_MS: u64 = 250; + +/// Returns the configured official multi-tenant domestic relay endpoint. +/// Precedence: `VIBEX_RELAY_URL` / `VIBEX_RELAY_HOST` env var -> `fallback_host` -> `DEFAULT_OFFICIAL_RELAY_HOST`. +pub fn official_relay_endpoint(fallback_host: Option<&str>) -> Option { + if let Ok(raw) = std::env::var("VIBEX_RELAY_URL").or_else(|_| std::env::var("VIBEX_RELAY_HOST")) + && let Ok(ep) = parse_tunnel_endpoint(&raw, DEFAULT_OFFICIAL_RELAY_PORT) + { + return Some(ep); + } + if let Some(host) = fallback_host + && let Ok(ep) = parse_tunnel_endpoint(host, DEFAULT_OFFICIAL_RELAY_PORT) + { + return Some(ep); + } + parse_tunnel_endpoint(DEFAULT_OFFICIAL_RELAY_HOST, DEFAULT_OFFICIAL_RELAY_PORT).ok() +} + +pub fn format_tenant_origin(scheme: &str, endpoint: &TunnelEndpoint, host_id: &str) -> String { + let is_domain = endpoint.host.parse::().is_err() + && !endpoint.host.eq_ignore_ascii_case("localhost"); + if is_domain && (endpoint.port == 80 || endpoint.port == 443) { + return format!( + "https://{}/t/{}", + endpoint.host.trim_end_matches('/'), + host_id.trim() + ); + } + let base = format_origin(scheme, endpoint); + format!("{}/t/{}", base.trim_end_matches('/'), host_id.trim()) +} pub fn tunnel_install_url() -> String { format!("{}/tunnel.sh", crate::site_origin()) @@ -240,12 +275,12 @@ mod tests { fn extract_relay_token_from_install_command() { assert_eq!( extract_relay_token( - "curl -fsSL https://vibex.xforever.xin/tunnel.sh | sh -s -- -t vbx_tun_e22cd3763db1436f847e709d79b3f9f9 -p 17891 -h 103.236.98.173" + "curl -fsSL https://site.example.com/tunnel.sh | sh -s -- -t vbx_tun_e22cd3763db1436f847e709d79b3f9f9 -p 17891 -h 203.0.113.10" ) .as_deref(), Some("vbx_tun_e22cd3763db1436f847e709d79b3f9f9") ); - assert_eq!(extract_relay_token("47.109.140.92:13630"), None); + assert_eq!(extract_relay_token("203.0.113.10:13630"), None); } static ENV_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(()); @@ -253,28 +288,37 @@ mod tests { #[test] fn install_command_includes_the_public_host() { let _lock = ENV_LOCK.lock().expect("env lock"); + unsafe { + std::env::set_var("VIBEX_SITE_URL", "https://site.example.com"); + } + let cmd = install_command("tok_abc", 17891, "203.0.113.10"); unsafe { std::env::remove_var("VIBEX_SITE_URL"); } assert_eq!( - install_command("tok_abc", 17891, "103.236.98.173"), - "curl -fsSL https://vibex.xforever.xin/tunnel.sh | sh -s -- -t tok_abc -p 17891 -h 103.236.98.173" + cmd, + "curl -fsSL https://site.example.com/tunnel.sh | sh -s -- -t tok_abc -p 17891 -h 203.0.113.10" ); } #[test] fn install_command_uses_sudo_for_privileged_ports() { let _lock = ENV_LOCK.lock().expect("env lock"); + unsafe { + std::env::set_var("VIBEX_SITE_URL", "https://site.example.com"); + } + let cmd_443 = install_command("tok_abc", 443, "203.0.113.10"); + let cmd_8443 = install_command("tok_abc", 8443, "203.0.113.10"); unsafe { std::env::remove_var("VIBEX_SITE_URL"); } assert_eq!( - install_command("tok_abc", 443, "203.0.113.10"), - "curl -fsSL https://vibex.xforever.xin/tunnel.sh | sudo sh -s -- -t tok_abc -p 443 -h 203.0.113.10" + cmd_443, + "curl -fsSL https://site.example.com/tunnel.sh | sudo sh -s -- -t tok_abc -p 443 -h 203.0.113.10" ); assert_eq!( - install_command("tok_abc", 8443, "203.0.113.10"), - "curl -fsSL https://vibex.xforever.xin/tunnel.sh | sh -s -- -t tok_abc -p 8443 -h 203.0.113.10" + cmd_8443, + "curl -fsSL https://site.example.com/tunnel.sh | sh -s -- -t tok_abc -p 8443 -h 203.0.113.10" ); } @@ -284,13 +328,13 @@ mod tests { unsafe { std::env::set_var("VIBEX_SITE_URL", "https://site.example.com/"); } - let cmd = install_command("tok_abc", 17891, "103.236.98.173"); + let cmd = install_command("tok_abc", 17891, "relay.example.com"); unsafe { std::env::remove_var("VIBEX_SITE_URL"); } assert_eq!( cmd, - "curl -fsSL https://site.example.com/tunnel.sh | sh -s -- -t tok_abc -p 17891 -h 103.236.98.173" + "curl -fsSL https://site.example.com/tunnel.sh | sh -s -- -t tok_abc -p 17891 -h relay.example.com" ); } } diff --git a/frontend/src/components/layout/IDELayout.tsx b/frontend/src/components/layout/IDELayout.tsx index 1c9af8b1c..4063972e4 100644 --- a/frontend/src/components/layout/IDELayout.tsx +++ b/frontend/src/components/layout/IDELayout.tsx @@ -38,6 +38,7 @@ import { parsePluginSurfaceId, } from '@/lib/hostSurfaceIds'; import { RightPanelSidebar } from '@/components/layout/RightPanelSidebar'; +import { MobileDeviceConnectBanner } from '@/components/layout/MobileDeviceConnectBanner'; import { StatusBar } from '@/components/layout/StatusBar'; import { ProjectLayoutScope, useProject } from '@/contexts/ProjectContext'; import { @@ -1381,6 +1382,7 @@ export function IDELayout({
+ {isDockviewMounted ? (
({ + isLocalDesktopHost: () => true, +})); + +vi.mock('@/lib/api/config', () => ({ + webServiceApi: { + listConnectRequests: (...args: unknown[]) => + listConnectRequestsMock(...args), + respondConnectRequest: (...args: unknown[]) => + respondConnectRequestMock(...args), + listDevices: (...args: unknown[]) => listDevicesMock(...args), + }, +})); + +describe('MobileDeviceConnectBanner', () => { + beforeEach(() => { + listConnectRequestsMock.mockReset(); + respondConnectRequestMock.mockReset(); + listDevicesMock.mockReset(); + listDevicesMock.mockResolvedValue([]); + }); + + it('renders nothing when there are no pending mobile connection requests', async () => { + listConnectRequestsMock.mockResolvedValue([]); + render(); + await waitFor(() => { + expect(listConnectRequestsMock).toHaveBeenCalled(); + }); + expect( + screen.queryByTestId('mobile-device-connect-banner') + ).not.toBeInTheDocument(); + }); + + it('displays available mobile device with 4-digit SAS code and approves connection on click', async () => { + listConnectRequestsMock.mockResolvedValue([ + { + request_id: 'req-123', + device_name: 'Pixel 9 Pro', + client_kind: 'mobile', + ip_address: '192.168.1.88', + sas_code: '8392', + created_at: '2026-11-09T05:00:00Z', + expires_at: '2026-11-09T05:03:00Z', + }, + ]); + respondConnectRequestMock.mockResolvedValue(undefined); + + render(); + + expect( + await screen.findByText(/发现可用移动设备「Pixel 9 Pro」/) + ).toBeInTheDocument(); + expect(screen.getByText('核对码 8392')).toBeInTheDocument(); + + fireEvent.click(screen.getByRole('button', { name: '连接' })); + + await waitFor(() => { + expect(respondConnectRequestMock).toHaveBeenCalledWith('req-123', true); + }); + expect( + await screen.findByText(/已连接移动设备「Pixel 9 Pro」/) + ).toBeInTheDocument(); + }); +}); diff --git a/frontend/src/components/layout/MobileDeviceConnectBanner.tsx b/frontend/src/components/layout/MobileDeviceConnectBanner.tsx new file mode 100644 index 000000000..8ad92a68a --- /dev/null +++ b/frontend/src/components/layout/MobileDeviceConnectBanner.tsx @@ -0,0 +1,301 @@ +import { Check, Smartphone, X } from 'lucide-react'; +import { useCallback, useEffect, useRef, useState } from 'react'; + +import { settingsWindowApi } from '@/lib/api/settingsWindow'; +import { + type HostPairedDevice, + type PendingDeviceConnectRequest, + webServiceApi, +} from '@/lib/api/config'; +import { isLocalDesktopHost } from '@/lib/desktopShell'; + +const POLL_INTERVAL_MS = 2500; +export const CONNECT_REQUESTS_CHANGED_EVENT = 'vibex:connect-requests-changed'; +export const REMOTE_AUTO_CONNECT_KEY = 'vibex:remote-auto-connect'; + +export function getRemoteAutoConnect(): boolean { + if (typeof window === 'undefined') return false; + try { + return window.localStorage.getItem(REMOTE_AUTO_CONNECT_KEY) === 'true'; + } catch { + return false; + } +} + +export function setRemoteAutoConnect(enabled: boolean): void { + if (typeof window === 'undefined') return; + try { + window.localStorage.setItem( + REMOTE_AUTO_CONNECT_KEY, + enabled ? 'true' : 'false' + ); + notifyConnectRequestsChanged(); + } catch { + // Ignore storage errors + } +} + +export function notifyConnectRequestsChanged(): void { + if (typeof window !== 'undefined') { + window.dispatchEvent(new CustomEvent(CONNECT_REQUESTS_CHANGED_EVENT)); + } +} + +function isMobilePairedDevice(device: HostPairedDevice): boolean { + const kind = device.client_kind?.toLowerCase(); + if (kind === 'mobile') return true; + if (kind === 'web') return false; + const name = (device.device_name || '').toLowerCase(); + if ( + /\b(iphone|ipad|android|pixel|mobile|ios|honor|huawei|xiaomi|redmi|oppo|vivo|oneplus|samsung|galaxy)\b/i.test( + name + ) || + name.includes('an00') || + name.includes('al00') || + name.startsWith('dio-') || + device.preset === 'companion' + ) { + return true; + } + return false; +} + +function isActivelyConnectedRecently( + device: HostPairedDevice, + sessionStartMs: number +): boolean { + const raw = device.last_connected_at; + if (!raw) return false; + const ts = Date.parse(raw); + if (Number.isNaN(ts)) return false; + return ts >= sessionStartMs || Date.now() - ts < 90_000; +} + +export function MobileDeviceConnectBanner() { + const [requests, setRequests] = useState([]); + const [pairedMobileDevices, setPairedMobileDevices] = useState< + HostPairedDevice[] + >([]); + const [busyId, setBusyId] = useState(null); + const [connectedDeviceName, setConnectedDeviceName] = useState( + null + ); + const [idleReminderDismissed, setIdleReminderDismissed] = useState(false); + const sessionStartMsRef = useRef(Date.now()); + const clearFeedbackTimerRef = useRef(null); + const respondedIdsRef = useRef>(new Set()); + + const handleRespond = useCallback( + async (item: PendingDeviceConnectRequest, approve: boolean) => { + setBusyId(item.request_id); + try { + await webServiceApi.respondConnectRequest(item.request_id, approve); + respondedIdsRef.current.add(item.request_id); + setRequests((prev) => + prev.filter((entry) => entry.request_id !== item.request_id) + ); + notifyConnectRequestsChanged(); + if (approve) { + setIdleReminderDismissed(true); + setConnectedDeviceName(item.device_name); + if (clearFeedbackTimerRef.current !== null) { + window.clearTimeout(clearFeedbackTimerRef.current); + } + clearFeedbackTimerRef.current = window.setTimeout(() => { + setConnectedDeviceName(null); + clearFeedbackTimerRef.current = null; + }, 2400); + } + } catch (err) { + console.warn('Failed to respond to mobile connect request:', err); + } finally { + setBusyId(null); + } + }, + [] + ); + + const refreshRequests = useCallback(async () => { + if (!isLocalDesktopHost()) { + return; + } + try { + const [nextRequests, devices] = await Promise.all([ + webServiceApi.listConnectRequests(), + webServiceApi.listDevices().catch(() => [] as HostPairedDevice[]), + ]); + const mobileDevices = Array.isArray(devices) + ? devices.filter(isMobilePairedDevice) + : []; + setPairedMobileDevices(mobileDevices); + + const filtered = Array.isArray(nextRequests) + ? nextRequests.filter( + (entry) => !respondedIdsRef.current.has(entry.request_id) + ) + : []; + + // If auto-connect is enabled and an already-paired mobile device is requesting connection, auto-approve + if ( + mobileDevices.length > 0 && + getRemoteAutoConnect() && + filtered.length > 0 + ) { + const matched = filtered.find((req) => + mobileDevices.some( + (dev) => + dev.device_name.trim().toLowerCase() === + req.device_name.trim().toLowerCase() + ) + ); + if (matched && !respondedIdsRef.current.has(matched.request_id)) { + respondedIdsRef.current.add(matched.request_id); + void handleRespond(matched, true); + return; + } + } + + setRequests(filtered); + } catch { + // Ignore in non-host windows or before backend is ready + } + }, [handleRespond]); + + useEffect(() => { + void refreshRequests(); + const intervalId = window.setInterval(() => { + void refreshRequests(); + }, POLL_INTERVAL_MS); + const handleChanged = () => { + void refreshRequests(); + }; + window.addEventListener(CONNECT_REQUESTS_CHANGED_EVENT, handleChanged); + return () => { + window.clearInterval(intervalId); + window.removeEventListener(CONNECT_REQUESTS_CHANGED_EVENT, handleChanged); + if (clearFeedbackTimerRef.current !== null) { + window.clearTimeout(clearFeedbackTimerRef.current); + } + }; + }, [refreshRequests]); + + // First-time connection reminders belong ONLY inside the Remote Connection settings page. + // Only show workspace banner after at least one mobile device has been paired, or when an + // active 1-click connection approval request arrives. + const active = requests[0] ?? null; + const hasPairedMobile = pairedMobileDevices.length > 0; + if (!active && !hasPairedMobile && !connectedDeviceName) { + return null; + } + + const primaryPairedMobile = pairedMobileDevices[0] ?? null; + const isPairedMobileIdle = + primaryPairedMobile !== null && + !isActivelyConnectedRecently( + primaryPairedMobile, + sessionStartMsRef.current + ) && + !idleReminderDismissed; + + if (!active && !connectedDeviceName && !isPairedMobileIdle) { + return null; + } + + return ( +
+
+ {connectedDeviceName && !active ? ( + <> + + + + + 已连接移动设备「{connectedDeviceName}」 + + + ) : active ? ( + <> + + + + + + + + + 发现可用移动设备「{active.device_name}」 + + + 核对码 {active.sas_code} + + {requests.length > 1 ? ( + + +{requests.length - 1} + + ) : null} +
+ + +
+ + ) : primaryPairedMobile ? ( + <> + + + + + 已配对手机「{primaryPairedMobile.device_name}」尚未连接 + +
+ + +
+ + ) : null} +
+
+ ); +} diff --git a/frontend/src/i18n/locales/en/settings.json b/frontend/src/i18n/locales/en/settings.json index 5e96d344d..55f00152f 100644 --- a/frontend/src/i18n/locales/en/settings.json +++ b/frontend/src/i18n/locales/en/settings.json @@ -1144,29 +1144,30 @@ "webSectionTitle": "Web access", "webSectionDescription": "Token and addresses for opening the Web UI in a browser.", "enableServiceFirst": "Turn on the remote connection service first", - "tunnelLabel": "Public tunnel", - "tunnelDescription": "Use an existing public origin, or set one up on a VPS.", + "tunnelLabel": "Cloud service", + "tunnelDescription": "Connect across networks via official cloud service or add a self-hosted node.", "tunnelMode": "Mode", "tunnelModeExisting": "Existing", - "tunnelModeCreate": "New tunnel", - "tunnelSavedList": "Saved tunnels", - "tunnelSavedEmpty": "No saved tunnels yet", + "tunnelModeCreate": "New cloud node", + "tunnelSavedList": "Cloud nodes", + "tunnelSavedEmpty": "No cloud nodes yet", + "tunnelOfficialNode": "Official Cloud", "tunnelRemove": "Remove", - "tunnelRemoveTitle": "Remove this tunnel?", + "tunnelRemoveTitle": "Remove this cloud node?", "tunnelRemoveMessage": "After removal, {{name}} has to be checked or created again before it can be used.", "tunnelInUse": "In use", "tunnelNotInUse": "Unused", "tunnelEnable": "Enable", "tunnelDisable": "Disable", "tunnelAddress": "IP / domain", - "tunnelAddressHint": "Enter the tunnel IP or domain. Click 'Generate command' and run it on your cloud server, or click 'Test connectivity' if already running or self-hosted.", + "tunnelAddressHint": "Enter your node IP or domain. Click 'Generate command' and run it on your server, or click 'Test connectivity' if already deployed.", "tunnelCheck": "Test connectivity", "tunnelCreateAddress": "Public IP / domain", - "tunnelCreateHint": "Enter the tunnel IP or domain. Click 'Generate command' and run it on your cloud server, or click 'Test connectivity' if already running or self-hosted.", - "tunnelNeedCommand": "Generate a setup command and run it on the VPS before testing connectivity.", - "tunnelHostUnreachable": "Could not reach a VibeX Host at that address. For a new VPS tunnel, generate a setup command first and run it on the server.", - "tunnelRelayWait": "The public tunnel is waiting for this Host. Confirm the VPS command is still running, then try again.", - "tunnelHealthFailed": "Reached the tunnel, but this Host did not answer. Confirm the remote connection service is running.", + "tunnelCreateHint": "Enter your node IP or domain. Click 'Generate command' and run it on your server, or click 'Test connectivity' if already deployed.", + "tunnelNeedCommand": "Generate a setup command and run it on the server before testing connectivity.", + "tunnelHostUnreachable": "Could not reach a VibeX Host at that address. For a new node, generate a setup command first and run it on the server.", + "tunnelRelayWait": "The cloud node is waiting for this Host. Confirm the server command is still running, then try again.", + "tunnelHealthFailed": "Reached the cloud node, but this Host did not answer. Confirm the remote connection service is running.", "tunnelGenerateCommand": "Generate command", "tunnelTestConnectivity": "Test connectivity", "tunnelTestConnected": "Connected", @@ -1175,12 +1176,12 @@ "tunnelCommand": "Install command", "tunnelConfirm": "Setup complete", "tunnelPolling": "Connecting", - "tunnelConnected": "Tunnel connected", - "tunnelSaved": "Saved remote tunnel address", - "tunnelSavedHttp": "Saved remote tunnel address", + "tunnelConnected": "Cloud service connected", + "tunnelSaved": "Saved cloud node", + "tunnelSavedHttp": "Saved cloud node", "tunnelCheckFailed": "Could not reach that address", - "tunnelSaveFailed": "Could not save tunnel settings", - "tunnelAddressRequired": "Enter a tunnel address", + "tunnelSaveFailed": "Could not save cloud service settings", + "tunnelAddressRequired": "Enter a node address", "statusSectionTitle": "Service Status", "statusSectionDescription": "One listen port serves the Web UI and Remote Protocol. Loopback by default; LAN needs the switch below.", "currentStatusLabel": "Current status", @@ -1194,8 +1195,8 @@ "hostAddressDescription": "The Web UI and paired devices connect here.", "lanAddressLabel": "LAN", "lanAddressDescription": "Phones and other computers on this network.", - "publishedAddressLabel": "Tunnel", - "publishedAddressDescription": "A checked remote origin for this Host.", + "publishedAddressLabel": "Cloud", + "publishedAddressDescription": "A verified cloud origin for this Host.", "copyOrigin": "Copy address", "openOrigin": "Open", "refreshStatus": "Refresh status", @@ -1214,7 +1215,7 @@ "autoStartLabel": "Auto start", "autoStartDescription": "Start Remote Protocol when the app launches.", "allowLanLabel": "Allow LAN", - "allowLanDescription": "Bind every interface. Put TLS in front of this Host.", + "allowLanDescription": "Bind LAN interfaces for direct local network connections.", "tokenLabel": "Access Token", "tokenDescription": "The token is displayed masked; you can regenerate or copy it.", "tokenPlaceholder": "Not generated yet", @@ -1223,7 +1224,7 @@ "pairingTitle": "Device pairing", "pairingDescription": "Create a connection code. Scan the QR or type the code on the phone.", "copyAddress": "Copy address", - "pairingNeedsReachability": "Turn on Allow LAN, or connect a public tunnel.", + "pairingNeedsReachability": "Turn on Allow LAN, or enable Cloud service.", "stalePortOccupied": "Port {{port}} is already in use.", "stalePortUnknown": "Could not confirm port {{port}}.", "stalePortHint": "Stop the other listener or pick a different port.", diff --git a/frontend/src/i18n/locales/zh-CN/settings.json b/frontend/src/i18n/locales/zh-CN/settings.json index 67f9e288d..429a9b067 100644 --- a/frontend/src/i18n/locales/zh-CN/settings.json +++ b/frontend/src/i18n/locales/zh-CN/settings.json @@ -1144,29 +1144,30 @@ "webSectionTitle": "Web 访问", "webSectionDescription": "浏览器打开 Web UI 时使用的 Token 与地址。", "enableServiceFirst": "请先开启远程连接服务", - "tunnelLabel": "远程穿透", - "tunnelDescription": "用已有公网入口,或在 VPS 上一键配置。", + "tunnelLabel": "云服务", + "tunnelDescription": "使用官方云服务跨网连接,或添加自建云节点。", "tunnelMode": "方式", - "tunnelModeExisting": "已建穿透", - "tunnelModeCreate": "新建穿透", - "tunnelSavedList": "已保存穿透列表", - "tunnelSavedEmpty": "还没有已保存穿透", + "tunnelModeExisting": "已有节点", + "tunnelModeCreate": "新建云节点", + "tunnelSavedList": "云服务节点", + "tunnelSavedEmpty": "暂无云服务节点", + "tunnelOfficialNode": "官方云服务", "tunnelRemove": "移除", - "tunnelRemoveTitle": "移除这个穿透?", + "tunnelRemoveTitle": "移除该云服务节点?", "tunnelRemoveMessage": "移除后,{{name}} 需要重新检查或新建才能使用。", "tunnelInUse": "使用中", "tunnelNotInUse": "未使用", "tunnelEnable": "启用", "tunnelDisable": "停用", "tunnelAddress": "IP / 域名", - "tunnelAddressHint": "请输入穿透地址IP/域名,点击‘生成命令’后,在对应云服务器上运行命令即可,若已运行命令或自建穿透,则点击“测试连通”进行检查", + "tunnelAddressHint": "请输入自建节点 IP/域名,点击“生成命令”并在云服务器执行;若已部署则点击“测试连通”验证。", "tunnelCheck": "测试连通", "tunnelCreateAddress": "公网 IP / 域名", - "tunnelCreateHint": "请输入穿透地址IP/域名,点击‘生成命令’后,在对应云服务器上运行命令即可,若已运行命令或自建穿透,则点击“测试连通”进行检查", + "tunnelCreateHint": "请输入自建节点 IP/域名,点击“生成命令”并在云服务器执行;若已部署则点击“测试连通”验证。", "tunnelNeedCommand": "请先生成命令,并在云服务器运行后再点测试连通。", - "tunnelHostUnreachable": "连不上该地址的 VibeX Host。若这是新建穿透,请先生成命令并在云服务器运行。", - "tunnelRelayWait": "公网入口在等待本机 Host。确认云服务器命令仍在运行后重试。", - "tunnelHealthFailed": "已连上穿透,但本机 Host 没有应答。请确认已开启远程连接服务。", + "tunnelHostUnreachable": "连不上该地址的 VibeX Host。若这是新建节点,请先生成命令并在云服务器运行。", + "tunnelRelayWait": "云节点正在等待本机 Host。确认云服务器命令仍在运行后重试。", + "tunnelHealthFailed": "已连上云节点,但本机 Host 没有应答。请确认已开启远程连接服务。", "tunnelGenerateCommand": "生成命令", "tunnelTestConnectivity": "测试连通", "tunnelTestConnected": "已连通", @@ -1175,12 +1176,12 @@ "tunnelCommand": "安装命令", "tunnelConfirm": "已完成配置", "tunnelPolling": "正在连接", - "tunnelConnected": "穿透已连通", - "tunnelSaved": "已保存远程穿透地址", - "tunnelSavedHttp": "已保存远程穿透地址", + "tunnelConnected": "云服务已连通", + "tunnelSaved": "已保存云服务节点", + "tunnelSavedHttp": "已保存云服务节点", "tunnelCheckFailed": "无法连上该地址", - "tunnelSaveFailed": "穿透设置保存失败", - "tunnelAddressRequired": "填写穿透地址", + "tunnelSaveFailed": "云服务设置保存失败", + "tunnelAddressRequired": "填写节点地址", "statusSectionTitle": "服务状态", "statusSectionDescription": "一个监听端口同时提供 Web UI 和远程协议。默认只听本机;局域网需要打开下面的开关。", "currentStatusLabel": "当前状态", @@ -1194,8 +1195,8 @@ "hostAddressDescription": "Web UI 和已配对设备都连这里。", "lanAddressLabel": "局域网", "lanAddressDescription": "同一网络中的手机和其他电脑。", - "publishedAddressLabel": "穿透", - "publishedAddressDescription": "已通过检查的远程可达地址。", + "publishedAddressLabel": "云服务", + "publishedAddressDescription": "已通过验证的云端跨网地址。", "copyOrigin": "复制地址", "openOrigin": "打开", "refreshStatus": "刷新状态", @@ -1214,7 +1215,7 @@ "autoStartLabel": "自动启动", "autoStartDescription": "应用启动时打开 Remote Protocol。", "allowLanLabel": "允许局域网", - "allowLanDescription": "监听全部网卡。公网访问必须经过 TLS 反代。", + "allowLanDescription": "监听局域网网卡,供同一网络设备直连。", "tokenLabel": "访问 Token", "tokenDescription": "Token 会被遮罩显示,可重新生成或复制。", "tokenPlaceholder": "尚未生成", @@ -1223,7 +1224,7 @@ "pairingTitle": "设备配对", "pairingDescription": "生成连接码。手机扫二维码或输入连接码。", "copyAddress": "复制地址", - "pairingNeedsReachability": "先打开允许局域网,或连通远程穿透。", + "pairingNeedsReachability": "请先打开允许局域网,或启用云服务。", "stalePortOccupied": "端口 {{port}} 已被占用。", "stalePortUnknown": "无法确认端口 {{port}}。", "stalePortHint": "先停掉占用进程,或换一个端口。", @@ -1256,7 +1257,7 @@ "pairingCredentialLabel": "连接凭证", "pairingAddressesExpand": "显示全部地址", "pairingAddressesCollapse": "收起地址", - "pairingOneTime": "仅显示一次,将于 {{expiresAt}} 过期;其中不包含 Server 主访问 Token。", + "pairingOneTime": "仅显示一次,将于 {{expiresAt}} 过期。", "copyPairingCode": "复制连接码", "pairedDevicesTitle": "已连接列表", "pairedDevicesEmpty": "暂无已连接设备", diff --git a/frontend/src/lib/api/config.ts b/frontend/src/lib/api/config.ts index 0ff88cb60..488c2d0fe 100644 --- a/frontend/src/lib/api/config.ts +++ b/frontend/src/lib/api/config.ts @@ -455,6 +455,17 @@ export interface HostPairedDevice { client_kind?: 'mobile' | 'desktop' | 'web' | string | null; ip_address?: string | null; last_connected_at?: string | null; + public_key_ed25519?: string | null; +} + +export interface PendingDeviceConnectRequest { + request_id: string; + device_name: string; + client_kind: 'mobile' | 'desktop' | 'web' | string; + ip_address?: string | null; + sas_code: string; + created_at: string; + expires_at: string; } export interface PortProbeResult { @@ -651,6 +662,19 @@ export const webServiceApi = { listDevices: async (): Promise => { return desktopShellCall('list_host_devices'); }, + listConnectRequests: async (): Promise => { + return desktopShellCall( + 'list_host_connect_requests' + ); + }, + respondConnectRequest: async ( + requestId: string, + approve: boolean + ): Promise => { + await desktopShellCall('respond_host_connect_request', { + request: { request_id: requestId, approve }, + }); + }, revokeDevice: async (deviceId: string): Promise => { await desktopShellCall('revoke_host_device', { request: { device_id: deviceId }, diff --git a/frontend/src/lib/api/index.ts b/frontend/src/lib/api/index.ts index 320542dfe..e6033b397 100644 --- a/frontend/src/lib/api/index.ts +++ b/frontend/src/lib/api/index.ts @@ -86,6 +86,7 @@ export type { TunnelCheckResult, HostPairingChallenge, HostPairedDevice, + PendingDeviceConnectRequest, HostClientProfile, LocalSshTarget, DiscoveredHost, diff --git a/frontend/src/pages/settings/DevicePairingPanel.test.tsx b/frontend/src/pages/settings/DevicePairingPanel.test.tsx index 8aad2a4bb..0689c0da9 100644 --- a/frontend/src/pages/settings/DevicePairingPanel.test.tsx +++ b/frontend/src/pages/settings/DevicePairingPanel.test.tsx @@ -197,10 +197,10 @@ describe('DevicePairingPanel', () => { expect(screen.getByText('loopback')).toHaveClass('rounded-full'); expect(screen.getByText('en0')).toHaveClass('rounded-full'); - expect(screen.getByText('tunnel')).toHaveClass('rounded-full'); + expect(screen.getByText('cloud')).toHaveClass('rounded-full'); expect(screen.getByText('本地')).toHaveClass('font-semibold'); expect(screen.getByText('局域网')).toHaveClass('font-semibold'); - expect(screen.getByText('穿透')).toHaveClass('font-semibold'); + expect(screen.getByText('云服务')).toHaveClass('font-semibold'); expect(screen.getByText('http://192.168.1.20:17891')).toBeVisible(); expect(screen.getByText('https://host.example.ts.net')).toBeVisible(); expect(screen.getByText('http://127.0.0.1:17891')).toBeVisible(); diff --git a/frontend/src/pages/settings/DevicePairingPanel.tsx b/frontend/src/pages/settings/DevicePairingPanel.tsx index 4ac3544d2..8306f6e78 100644 --- a/frontend/src/pages/settings/DevicePairingPanel.tsx +++ b/frontend/src/pages/settings/DevicePairingPanel.tsx @@ -1,16 +1,23 @@ import { useCallback, useEffect, useId, useMemo, useState } from 'react'; import { + Check, ChevronDown, Copy, ExternalLink, Loader2, QrCode, ShieldCheck, + Smartphone, + X, } from 'lucide-react'; import QRCode from 'qrcode'; import { useTranslation } from 'react-i18next'; import { ConfirmDialog } from '@/components/dialogs/shared/ConfirmDialog'; +import { + CONNECT_REQUESTS_CHANGED_EVENT, + notifyConnectRequestsChanged, +} from '@/components/layout/MobileDeviceConnectBanner'; import { Button } from '@/components/ui/button'; import { Label } from '@/components/ui/label'; import { @@ -22,7 +29,11 @@ import { } from '@/components/ui/select'; import { toast } from '@/components/ui/toast'; import { openInSystemBrowser } from '@/hooks/useOpenLink'; -import { webServiceApi, type HostPairedDevice } from '@/lib/api'; +import { + webServiceApi, + type HostPairedDevice, + type PendingDeviceConnectRequest, +} from '@/lib/api'; import { getErrorMessage } from '@/lib/modals'; import type { BackendTransport, @@ -109,7 +120,7 @@ export function DevicePairingPanel({ onEnsureListening?: () => Promise; }) { const { t } = useTranslation(['settings', 'common']); - const [preset, setPreset] = useState('workstation'); + const preset: PairingPreset = 'workstation'; const [challenge, setChallenge] = useState( null ); @@ -118,6 +129,12 @@ export function DevicePairingPanel({ const [autoIssued, setAutoIssued] = useState(false); const [startedUrls, setStartedUrls] = useState(null); const [devices, setDevices] = useState([]); + const [pendingRequests, setPendingRequests] = useState< + PendingDeviceConnectRequest[] + >([]); + const [respondingRequestId, setRespondingRequestId] = useState( + null + ); const [revokingId, setRevokingId] = useState(null); const [ttlSeconds, setTtlSeconds] = useState( DEFAULT_PAIRING_TTL_SECONDS @@ -157,16 +174,56 @@ export function DevicePairingPanel({ } catch { setDevices([]); } + try { + const requests = await webServiceApi.listConnectRequests(); + setPendingRequests(Array.isArray(requests) ? requests : []); + } catch { + setPendingRequests([]); + } }, []); useEffect(() => { void loadDevices(); const timer = window.setInterval(() => { void loadDevices(); - }, 5000); - return () => window.clearInterval(timer); + }, 3000); + const handleChanged = () => { + void loadDevices(); + }; + window.addEventListener(CONNECT_REQUESTS_CHANGED_EVENT, handleChanged); + return () => { + window.clearInterval(timer); + window.removeEventListener(CONNECT_REQUESTS_CHANGED_EVENT, handleChanged); + }; }, [loadDevices]); + const respondConnectRequest = useCallback( + async (request: PendingDeviceConnectRequest, approve: boolean) => { + setRespondingRequestId(request.request_id); + try { + await webServiceApi.respondConnectRequest(request.request_id, approve); + setPendingRequests((current) => + current.filter((item) => item.request_id !== request.request_id) + ); + notifyConnectRequestsChanged(); + void loadDevices(); + if (approve) { + toast.success(`已允许移动设备「${request.device_name}」连接`); + } + } catch (error) { + const message = getErrorMessage(error); + toast.error( + message && message !== 'An unknown error occurred' + ? message + : t('webService.pairingFailed') + ); + } finally { + setRespondingRequestId(null); + } + }, + [loadDevices, t] + ); + useEffect(() => { if (!challenge) return; const timer = window.setInterval(() => { @@ -352,12 +409,15 @@ export function DevicePairingPanel({ data-testid="pairing-addresses-scroll-box" > {visibleOrigins.map((item) => { + const isCloudServiceUrl = item.origin.includes('/t/'); const ifaceLabel = item.interface ?? (item.kind === 'loopback' ? 'loopback' : item.kind === 'published' - ? 'tunnel' + ? isCloudServiceUrl + ? 'Beta' + : 'cloud' : null); return (
- + {addressKindLabel(item.kind)} {ifaceLabel ? ( - + {ifaceLabel} ) : null} - + {isCloudServiceUrl ? ( + + {t('webService.tunnelOfficialNode', { + defaultValue: '官方云服务', + })} + + ) : ( + + )}
- + {!isCloudServiceUrl ? ( + + ) : null}
); @@ -427,6 +504,68 @@ export function DevicePairingPanel({

) : null} + {pendingRequests.length > 0 ? ( +
+
+ + 待确认连接请求 + + + {pendingRequests.length} + +
+
+
+ {pendingRequests.map((req) => ( +
+
+ + + {req.device_name} + + + 核对码 {req.sas_code} + + {req.ip_address ? ( + + {req.ip_address} + + ) : null} +
+
+ + +
+
+ ))} +
+
+
+ ) : null} + {challenge ? (
-
- - -
); - await user.click(await screen.findByRole('switch', { name: '远程穿透' })); + await user.click(await screen.findByRole('switch', { name: '云服务' })); await waitFor(() => expect(hostTunnelApi.setEnabled).toHaveBeenCalledWith(true) ); const toggle = await screen.findByRole('button', { - name: /已保存穿透列表/, + name: /云服务节点/, }); expect(toggle).toHaveAttribute('aria-expanded', 'true'); - expect(screen.getByText('还没有已保存穿透')).toBeVisible(); + expect(screen.getByText('暂无云服务节点')).toBeVisible(); - await user.click(screen.getByRole('button', { name: '新建穿透' })); + await user.click(screen.getByRole('button', { name: '新建云节点' })); expect(screen.getByTestId('host-tunnel-modal-overlay')).toBeInTheDocument(); expect(document.querySelector('.settings-page')).toHaveClass( 'collaboration-settings-window-blurred' ); expect( screen.getByText( - '请输入穿透地址IP/域名,点击‘生成命令’后,在对应云服务器上运行命令即可,若已运行命令或自建穿透,则点击“测试连通”进行检查' + '请输入自建节点 IP/域名,点击“生成命令”并在云服务器执行;若已部署则点击“测试连通”验证。' ) ).toBeVisible(); expect(screen.getByRole('button', { name: '保存' })).toBeDisabled(); @@ -129,8 +129,8 @@ describe('HostTunnelPanel', () => { /> ); - await user.click(await screen.findByRole('switch', { name: '远程穿透' })); - await user.click(await screen.findByRole('button', { name: '新建穿透' })); + await user.click(await screen.findByRole('switch', { name: '云服务' })); + await user.click(await screen.findByRole('button', { name: '新建云节点' })); const saveButton = screen.getByRole('button', { name: '保存' }); expect(saveButton).toBeDisabled(); @@ -160,7 +160,7 @@ describe('HostTunnelPanel', () => { expect(onReachabilityChange).toHaveBeenCalled(); const { toast } = await import('@/components/ui/toast'); - expect(toast.success).toHaveBeenCalledWith('已保存远程穿透地址'); + expect(toast.success).toHaveBeenCalledWith('已保存云服务节点'); }); it('generates a short install command in the modal and keeps save disabled when connectivity fails', async () => { @@ -180,8 +180,8 @@ describe('HostTunnelPanel', () => { undefined} /> ); - await user.click(await screen.findByRole('switch', { name: '远程穿透' })); - await user.click(await screen.findByRole('button', { name: '新建穿透' })); + await user.click(await screen.findByRole('switch', { name: '云服务' })); + await user.click(await screen.findByRole('button', { name: '新建云节点' })); await user.type( screen.getByPlaceholderText('203.0.113.10'), '203.0.113.10' @@ -256,7 +256,7 @@ describe('HostTunnelPanel', () => { ); const toggle = await screen.findByRole('button', { - name: /已保存穿透列表/, + name: /云服务节点/, }); expect(toggle).toHaveAttribute('aria-expanded', 'true'); const listContainer = screen.getByTestId('saved-tunnels-list-container'); diff --git a/frontend/src/pages/settings/HostTunnelPanel.tsx b/frontend/src/pages/settings/HostTunnelPanel.tsx index be5d07ae8..d20a25888 100644 --- a/frontend/src/pages/settings/HostTunnelPanel.tsx +++ b/frontend/src/pages/settings/HostTunnelPanel.tsx @@ -200,6 +200,12 @@ export function HostTunnelPanel({ useEffect(() => { void refresh().catch(() => undefined); + const handleSync = () => { + void refresh().catch(() => undefined); + }; + window.addEventListener('vibex:host-tunnel-updated', handleSync); + return () => + window.removeEventListener('vibex:host-tunnel-updated', handleSync); }, [refresh]); useEffect(() => { @@ -449,9 +455,14 @@ export function HostTunnelPanel({ <>
- +
+ + + Beta + +

{t('webService.tunnelDescription')}

@@ -465,108 +476,134 @@ export function HostTunnelPanel({ />
- {status.enabled ? ( -
-
- - -
+
+
+ + +
- {listExpanded ? ( + {listExpanded ? ( +
-
- {status.saved.length === 0 ? ( -

- {t('webService.tunnelSavedEmpty')} -

- ) : ( - status.saved.map((item) => { - const active = item.id === status.active_id; - const isRelayPolling = - active && - item.kind === 'relay' && - status.relay_state !== 'connected'; - return ( -
-
-
- - {item.origin} + {status.saved.length === 0 ? ( +

+ {t('webService.tunnelSavedEmpty')} +

+ ) : ( + status.saved.map((item) => { + const active = status.enabled && item.id === status.active_id; + const isOfficialCloud = + item.id === 'auto-quick-tunnel' || + item.origin.includes('/t/'); + const isRelayPolling = + active && + item.kind === 'relay' && + status.relay_state !== 'connected'; + return ( +
+
+
+ + {isOfficialCloud + ? `VibeX ${t('webService.tunnelOfficialNode', { + defaultValue: '官方云服务', + })}` + : item.origin} + + +
+
+ {isOfficialCloud ? ( + + {t('webService.tunnelOfficialNode', { + defaultValue: '官方云服务', + })} - -
-
+ ) : ( {item.host}:{item.port} -
- - {formatTunnelCreatedAt(item.created_at)} - + )}
-
- + + {isOfficialCloud + ? 'Beta' + : formatTunnelCreatedAt(item.created_at)} + +
+
+ + {!isOfficialCloud ? (
+ ) : null}
- ); - }) - )} -
+
+ ); + }) + )}
- ) : null} +
+ ) : null} - {polling && status.last_error ? ( -

{status.last_error}

- ) : null} -
- ) : null} + {polling && status.last_error ? ( +

{status.last_error}

+ ) : null} +
{modalOpen ? createPortal( diff --git a/frontend/src/pages/settings/WebServiceSettings.test.tsx b/frontend/src/pages/settings/WebServiceSettings.test.tsx index 43fc38930..73d6bfdd9 100644 --- a/frontend/src/pages/settings/WebServiceSettings.test.tsx +++ b/frontend/src/pages/settings/WebServiceSettings.test.tsx @@ -384,7 +384,7 @@ describe('WebServiceSettings', () => { within(externalAccess!).getByText('http://192.168.1.20:17891') ).toBeVisible(); expect( - within(externalAccess!).getByRole('switch', { name: '远程穿透' }) + within(externalAccess!).getByRole('switch', { name: '云服务' }) ).toBeVisible(); }); @@ -510,11 +510,11 @@ describe('WebServiceSettings', () => { webServiceApiMock.getStatus.mockResolvedValue(runningStatus); renderSettings(); - const tunnel = await screen.findByRole('switch', { name: '远程穿透' }); + const tunnel = await screen.findByRole('switch', { name: '云服务' }); expect(tunnel).toBeVisible(); webServiceApiMock.getConfig.mockClear(); window.dispatchEvent(new Event('vibex://settings-file-changed')); await waitFor(() => expect(webServiceApiMock.getConfig).toHaveBeenCalled()); - expect(screen.getByRole('switch', { name: '远程穿透' })).toBe(tunnel); + expect(screen.getByRole('switch', { name: '云服务' })).toBe(tunnel); }); }); diff --git a/frontend/src/pages/settings/WebServiceSettings.tsx b/frontend/src/pages/settings/WebServiceSettings.tsx index 6f55efa69..38fd12eab 100644 --- a/frontend/src/pages/settings/WebServiceSettings.tsx +++ b/frontend/src/pages/settings/WebServiceSettings.tsx @@ -10,8 +10,14 @@ import { Laptop, Loader2, Server, + Wifi, } from 'lucide-react'; import { useTranslation } from 'react-i18next'; +import { + getRemoteAutoConnect, + setRemoteAutoConnect, +} from '@/components/layout/MobileDeviceConnectBanner'; +import { Button } from '@/components/ui/button'; import { toast } from '@/components/ui/toast'; import type { BackendTransport } from '@/lib/backendTransport'; import { isTauriClient } from '@/lib/desktopShell'; @@ -22,6 +28,7 @@ import { Input } from '@/components/ui/input'; import { Label } from '@/components/ui/label'; import { Switch } from '@/components/ui/switch'; import { + hostTunnelApi, type PortProbeResult, type WebServerStatus, type WebServiceConfig, @@ -41,8 +48,8 @@ type RemoteRoleTab = 'server' | 'client'; const DEFAULT_CONFIG: WebServiceConfig = { port: 17891, token: null, - auto_start: false, - allow_lan: false, + auto_start: true, + allow_lan: true, }; function sameConfig(a: WebServiceConfig, b: WebServiceConfig): boolean { @@ -69,6 +76,11 @@ export function WebServiceSettings({ const [loading, setLoading] = useState(true); const [statusBusy, setStatusBusy] = useState(false); const [probing, setProbing] = useState(false); + const [tunnelEnabled, setTunnelEnabled] = useState(false); + const [showModePrompt, setShowModePrompt] = useState(false); + const [autoConnect, setAutoConnectState] = useState(() => + getRemoteAutoConnect() + ); const hostConsole = isTauriClient(transport.environment); const boundToRemote = transport.environment === 'remote-desktop'; const [role, setRole] = useState(() => @@ -124,10 +136,14 @@ export function WebServiceSettings({ } if (showSpinner) setLoading(true); try { - const [savedConfig, currentStatus] = await Promise.all([ + const [savedConfig, currentStatus, tunnelStatus] = await Promise.all([ webServiceApi.getConfig(), webServiceApi.getStatus(), + Promise.resolve(hostTunnelApi.get?.()).catch(() => null), ]); + if (tunnelStatus) { + setTunnelEnabled(Boolean(tunnelStatus.enabled)); + } if (!holdingRef.current) { draftRef.current = savedConfig; setDraft(savedConfig); @@ -173,7 +189,14 @@ export function WebServiceSettings({ const refreshStatus = useCallback(async () => { setStatusBusy(true); try { - setStatus(await webServiceApi.getStatus()); + const [nextStatus, tunnelStatus] = await Promise.all([ + webServiceApi.getStatus(), + hostTunnelApi.get().catch(() => null), + ]); + setStatus(nextStatus); + if (tunnelStatus) { + setTunnelEnabled(Boolean(tunnelStatus.enabled)); + } } catch (error) { toast.error( error instanceof Error @@ -185,6 +208,29 @@ export function WebServiceSettings({ } }, [t]); + const selectConnectionMode = useCallback( + async (useCloud: boolean) => { + setShowModePrompt(false); + setStatusBusy(true); + try { + const updatedTunnel = await hostTunnelApi.setEnabled(useCloud); + setTunnelEnabled(Boolean(updatedTunnel.enabled)); + window.dispatchEvent(new CustomEvent('vibex:host-tunnel-updated')); + if (!useCloud && !draftRef.current.allow_lan) { + commitDraft({ ...draftRef.current, allow_lan: true }); + } + setStatus(await webServiceApi.getStatus()); + } catch { + setTunnelEnabled(useCloud); + window.dispatchEvent(new CustomEvent('vibex:host-tunnel-updated')); + } finally { + setStatusBusy(false); + } + }, + // eslint-disable-next-line react-hooks/exhaustive-deps + [] + ); + const startServer = useCallback(async () => { await flush(); @@ -264,6 +310,12 @@ export function WebServiceSettings({

{hostConsole && !boundToRemote ? ( @@ -363,8 +415,23 @@ export function WebServiceSettings({ checked={serviceRunning} onCheckedChange={(checked: boolean) => { if (checked) { + setShowModePrompt(true); + void Promise.resolve(hostTunnelApi.setEnabled?.(false)) + .then((next) => { + setTunnelEnabled(Boolean(next?.enabled)); + window.dispatchEvent( + new CustomEvent('vibex:host-tunnel-updated') + ); + }) + .catch(() => { + setTunnelEnabled(false); + window.dispatchEvent( + new CustomEvent('vibex:host-tunnel-updated') + ); + }); void startServer(); } else { + setShowModePrompt(false); void stopServer(); } }} @@ -378,8 +445,81 @@ export function WebServiceSettings({
+ {serviceRunning && showModePrompt ? ( +
+
+ + 是否使用「云服务 Beta」进行远程连接? + + + 开启云服务可跨网络连接;若不使用云服务则采用局域网直连,请确保手机和电脑处于同一个局域网下。 + +
+
+ + +
+
+ ) : null} + + {serviceRunning && !tunnelEnabled ? ( +
+
+ ) : null} + {serviceRunning ? ( <> +
+
+ +

+ 首次连接成功后,已配对的手机再次发起连接时自动允许接入 +

+
+ { + setAutoConnectState(checked); + setRemoteAutoConnect(checked); + }} + /> +
+