|
| 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