Skip to content

Commit 0815f6a

Browse files
steipeteSebastian Schubotzsibbl
authored
feat(android): add Wear proxy protocol (#108835)
* feat(android): add Wear proxy protocol Introduce a bounded, versioned phone/watch RPC contract and wire its test, lint, and build gates before either runtime endpoint lands. Co-authored-by: Sebastian Schubotz <[email protected]> * test(android): lock Wear wire names Cover every supported RPC method and event discriminator so phone and watch cannot silently drift. Co-authored-by: Sebastian Schubotz <[email protected]> * fix(android): bound Wear JSON depth Reject excessively nested Data Layer envelopes before kotlinx.serialization can recurse through them. * fix(android): enforce Wear depth on encode Keep outbound messages inside the same JSON nesting contract enforced by the decoder. * fix(android): preflight Wear payload depth Traverse arbitrary JSON payloads iteratively before serialization so deeply nested local trees fail safely. --------- Co-authored-by: Sebastian Schubotz <[email protected]> Co-authored-by: Sebastian Schubotz <[email protected]>
1 parent c11d112 commit 0815f6a

9 files changed

Lines changed: 511 additions & 8 deletions

File tree

‎.github/workflows/ci.yml‎

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2897,7 +2897,9 @@ jobs:
28972897
set -euo pipefail
28982898
case "$TASK" in
28992899
test-play)
2900-
./gradlew --no-daemon --build-cache :app:testPlayDebugUnitTest
2900+
./gradlew --no-daemon --build-cache \
2901+
:app:testPlayDebugUnitTest \
2902+
:wear-shared:testDebugUnitTest
29012903
;;
29022904
test-third-party)
29032905
./gradlew --no-daemon --build-cache :app:testThirdPartyDebugUnitTest
@@ -2908,7 +2910,9 @@ jobs:
29082910
:app:assembleThirdPartyDebug \
29092911
:app:lintPlayDebug \
29102912
:app:lintThirdPartyDebug \
2911-
:benchmark:assembleDebug
2913+
:benchmark:assembleDebug \
2914+
:wear-shared:assembleDebug \
2915+
:wear-shared:lintDebug
29122916
;;
29132917
build-play-compat)
29142918
# Frozen targets keep their target-owned Android build contract. New lint rules
@@ -2917,7 +2921,10 @@ jobs:
29172921
;;
29182922
ktlint)
29192923
# Mirrors `pnpm android:lint`; keeps formatting drift out of main (see PR #100304 sweep).
2920-
./gradlew --no-daemon --build-cache :app:ktlintCheck :benchmark:ktlintCheck
2924+
./gradlew --no-daemon --build-cache \
2925+
:app:ktlintCheck \
2926+
:benchmark:ktlintCheck \
2927+
:wear-shared:ktlintCheck
29212928
;;
29222929
*)
29232930
echo "Unsupported Android task: $TASK" >&2

‎apps/android/build.gradle.kts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
plugins {
22
alias(libs.plugins.android.application) apply false
3+
alias(libs.plugins.android.library) apply false
34
alias(libs.plugins.android.test) apply false
45
alias(libs.plugins.ktlint) apply false
56
alias(libs.plugins.kotlin.compose) apply false

‎apps/android/gradle/libs.versions.toml‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -80,6 +80,7 @@ robolectric = { module = "org.robolectric:robolectric", version.ref = "robolectr
8080

8181
[plugins]
8282
android-application = { id = "com.android.application", version.ref = "agp" }
83+
android-library = { id = "com.android.library", version.ref = "agp" }
8384
android-test = { id = "com.android.test", version.ref = "agp" }
8485
kotlin-compose = { id = "org.jetbrains.kotlin.plugin.compose", version.ref = "kotlin" }
8586
kotlin-serialization = { id = "org.jetbrains.kotlin.plugin.serialization", version.ref = "kotlin" }

‎apps/android/settings.gradle.kts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,3 +17,4 @@ dependencyResolutionManagement {
1717
rootProject.name = "OpenClawNodeAndroid"
1818
include(":app")
1919
include(":benchmark")
20+
include(":wear-shared")
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
plugins {
2+
alias(libs.plugins.android.library)
3+
alias(libs.plugins.ktlint)
4+
alias(libs.plugins.kotlin.serialization)
5+
}
6+
7+
android {
8+
namespace = "ai.openclaw.wear.shared"
9+
compileSdk = 37
10+
11+
defaultConfig {
12+
minSdk = 31
13+
}
14+
15+
compileOptions {
16+
sourceCompatibility = JavaVersion.VERSION_17
17+
targetCompatibility = JavaVersion.VERSION_17
18+
}
19+
20+
lint {
21+
warningsAsErrors = true
22+
}
23+
}
24+
25+
kotlin {
26+
compilerOptions {
27+
jvmTarget.set(org.jetbrains.kotlin.gradle.dsl.JvmTarget.JVM_17)
28+
allWarningsAsErrors.set(true)
29+
}
30+
}
31+
32+
ktlint {
33+
android.set(true)
34+
ignoreFailures.set(false)
35+
filter {
36+
exclude("**/build/**")
37+
}
38+
}
39+
40+
dependencies {
41+
api(libs.kotlinx.serialization.json)
42+
43+
testImplementation(libs.junit)
44+
}
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
<manifest />
Lines changed: 258 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,258 @@
1+
package ai.openclaw.wear.shared
2+
3+
import kotlinx.serialization.SerialName
4+
import kotlinx.serialization.Serializable
5+
import kotlinx.serialization.SerializationException
6+
import kotlinx.serialization.json.Json
7+
import kotlinx.serialization.json.JsonArray
8+
import kotlinx.serialization.json.JsonElement
9+
import kotlinx.serialization.json.JsonObject
10+
import kotlinx.serialization.json.JsonPrimitive
11+
import kotlinx.serialization.json.buildJsonObject
12+
import kotlinx.serialization.json.intOrNull
13+
import kotlinx.serialization.json.jsonObject
14+
import java.nio.charset.CharacterCodingException
15+
16+
object WearProtocol {
17+
const val VERSION = 1
18+
const val REQUEST_PATH = "/openclaw/wear/v1/request"
19+
const val RESPONSE_PATH = "/openclaw/wear/v1/response"
20+
const val EVENT_PATH = "/openclaw/wear/v1/event"
21+
22+
// MessageClient has a 100 KiB ceiling. Keep headroom for transport metadata and
23+
// force transcript pagination instead of depending on an edge-sized message.
24+
const val MAX_MESSAGE_BYTES = 64 * 1024
25+
26+
// Bound recursive JSON parsing at the untrusted Data Layer boundary.
27+
const val MAX_JSON_DEPTH = 32
28+
}
29+
30+
@Serializable
31+
enum class WearRpcMethod {
32+
@SerialName("proxy.status")
33+
ProxyStatus,
34+
35+
@SerialName("sessions.list")
36+
SessionsList,
37+
38+
@SerialName("chat.history")
39+
ChatHistory,
40+
41+
@SerialName("chat.send")
42+
ChatSend,
43+
44+
@SerialName("chat.abort")
45+
ChatAbort,
46+
}
47+
48+
@Serializable
49+
enum class WearEventType {
50+
@SerialName("chat")
51+
Chat,
52+
53+
@SerialName("connection")
54+
Connection,
55+
}
56+
57+
@Serializable
58+
sealed interface WearMessage {
59+
val version: Int
60+
61+
@Serializable
62+
@SerialName("request")
63+
data class Request(
64+
override val version: Int = WearProtocol.VERSION,
65+
val requestId: String,
66+
val method: WearRpcMethod,
67+
val params: JsonObject = buildJsonObject {},
68+
) : WearMessage
69+
70+
@Serializable
71+
@SerialName("response")
72+
data class Response(
73+
override val version: Int = WearProtocol.VERSION,
74+
val requestId: String,
75+
val ok: Boolean,
76+
val result: JsonElement? = null,
77+
val error: WearRpcError? = null,
78+
) : WearMessage
79+
80+
@Serializable
81+
@SerialName("event")
82+
data class Event(
83+
override val version: Int = WearProtocol.VERSION,
84+
val sequence: Long,
85+
val event: WearEventType,
86+
val payload: JsonElement? = null,
87+
) : WearMessage
88+
}
89+
90+
@Serializable
91+
data class WearRpcError(
92+
val code: String,
93+
val message: String,
94+
)
95+
96+
enum class WearDecodeFailureReason {
97+
Empty,
98+
TooLarge,
99+
TooDeep,
100+
Malformed,
101+
UnsupportedVersion,
102+
InvalidEnvelope,
103+
}
104+
105+
sealed interface WearDecodeResult {
106+
data class Success(
107+
val message: WearMessage,
108+
) : WearDecodeResult
109+
110+
data class Failure(
111+
val reason: WearDecodeFailureReason,
112+
) : WearDecodeResult
113+
}
114+
115+
object WearProtocolCodec {
116+
private val json =
117+
Json {
118+
classDiscriminator = "type"
119+
encodeDefaults = true
120+
explicitNulls = false
121+
ignoreUnknownKeys = true
122+
}
123+
124+
fun encode(message: WearMessage): ByteArray {
125+
requireValid(message)
126+
require(hasValidPayloadDepth(message)) {
127+
"Wear message exceeds JSON depth ${WearProtocol.MAX_JSON_DEPTH}"
128+
}
129+
val encoded = json.encodeToString(WearMessage.serializer(), message)
130+
require(!exceedsJsonDepth(encoded)) {
131+
"Wear message exceeds JSON depth ${WearProtocol.MAX_JSON_DEPTH}"
132+
}
133+
val bytes =
134+
encoded.encodeToByteArray(throwOnInvalidSequence = true)
135+
require(bytes.size <= WearProtocol.MAX_MESSAGE_BYTES) {
136+
"Wear message exceeds ${WearProtocol.MAX_MESSAGE_BYTES} bytes"
137+
}
138+
return bytes
139+
}
140+
141+
private fun hasValidPayloadDepth(message: WearMessage): Boolean {
142+
val payloads =
143+
when (message) {
144+
is WearMessage.Request -> listOf(message.params)
145+
is WearMessage.Response -> listOfNotNull(message.result)
146+
is WearMessage.Event -> listOfNotNull(message.payload)
147+
}
148+
return payloads.all { element -> hasValidElementDepth(element, parentDepth = 1) }
149+
}
150+
151+
private fun hasValidElementDepth(
152+
element: JsonElement,
153+
parentDepth: Int,
154+
): Boolean {
155+
val pending = ArrayDeque<Pair<JsonElement, Int>>()
156+
pending.addLast(element to parentDepth)
157+
while (pending.isNotEmpty()) {
158+
val (current, parent) = pending.removeLast()
159+
val children =
160+
when (current) {
161+
is JsonArray -> current
162+
is JsonObject -> current.values
163+
else -> continue
164+
}
165+
val depth = parent + 1
166+
if (depth > WearProtocol.MAX_JSON_DEPTH) return false
167+
children.forEach { child -> pending.addLast(child to depth) }
168+
}
169+
return true
170+
}
171+
172+
fun decode(bytes: ByteArray): WearDecodeResult {
173+
if (bytes.isEmpty()) return WearDecodeResult.Failure(WearDecodeFailureReason.Empty)
174+
if (bytes.size > WearProtocol.MAX_MESSAGE_BYTES) {
175+
return WearDecodeResult.Failure(WearDecodeFailureReason.TooLarge)
176+
}
177+
178+
val text =
179+
try {
180+
bytes.decodeToString(throwOnInvalidSequence = true)
181+
} catch (_: CharacterCodingException) {
182+
return WearDecodeResult.Failure(WearDecodeFailureReason.Malformed)
183+
}
184+
if (exceedsJsonDepth(text)) {
185+
return WearDecodeResult.Failure(WearDecodeFailureReason.TooDeep)
186+
}
187+
val root =
188+
try {
189+
json.parseToJsonElement(text).jsonObject
190+
} catch (_: SerializationException) {
191+
return WearDecodeResult.Failure(WearDecodeFailureReason.Malformed)
192+
} catch (_: IllegalArgumentException) {
193+
return WearDecodeResult.Failure(WearDecodeFailureReason.Malformed)
194+
}
195+
val version =
196+
(root["version"] as? JsonPrimitive)?.intOrNull
197+
?: return WearDecodeResult.Failure(WearDecodeFailureReason.Malformed)
198+
if (version != WearProtocol.VERSION) {
199+
return WearDecodeResult.Failure(WearDecodeFailureReason.UnsupportedVersion)
200+
}
201+
val message =
202+
try {
203+
json.decodeFromJsonElement(WearMessage.serializer(), root)
204+
} catch (_: SerializationException) {
205+
return WearDecodeResult.Failure(WearDecodeFailureReason.Malformed)
206+
} catch (_: IllegalArgumentException) {
207+
return WearDecodeResult.Failure(WearDecodeFailureReason.Malformed)
208+
}
209+
if (!isValid(message)) {
210+
return WearDecodeResult.Failure(WearDecodeFailureReason.InvalidEnvelope)
211+
}
212+
return WearDecodeResult.Success(message)
213+
}
214+
215+
private fun exceedsJsonDepth(text: String): Boolean {
216+
var depth = 0
217+
var inString = false
218+
var escaped = false
219+
for (character in text) {
220+
if (inString) {
221+
when {
222+
escaped -> escaped = false
223+
character == '\\' -> escaped = true
224+
character == '"' -> inString = false
225+
}
226+
continue
227+
}
228+
229+
when (character) {
230+
'"' -> inString = true
231+
'{', '[' -> {
232+
depth += 1
233+
if (depth > WearProtocol.MAX_JSON_DEPTH) return true
234+
}
235+
'}', ']' -> depth -= 1
236+
}
237+
}
238+
return false
239+
}
240+
241+
private fun requireValid(message: WearMessage) {
242+
require(message.version == WearProtocol.VERSION) { "Unsupported Wear protocol version: ${message.version}" }
243+
require(isValid(message)) { "Invalid Wear protocol envelope" }
244+
}
245+
246+
private fun isValid(message: WearMessage): Boolean =
247+
when (message) {
248+
is WearMessage.Request -> message.requestId.isNotBlank()
249+
is WearMessage.Response ->
250+
message.requestId.isNotBlank() &&
251+
if (message.ok) {
252+
message.error == null
253+
} else {
254+
message.error != null && message.result == null && message.error.code.isNotBlank()
255+
}
256+
is WearMessage.Event -> message.sequence >= 0
257+
}
258+
}

0 commit comments

Comments
 (0)