Skip to content

Wire Protocol Specification (CK v1) ​

This document is the single source of truth for the Connekt binary wire protocol shared by Rust (connekt-core), Android (dev.mobra.connekt), iOS (Connekt), and Browser/H5 (@connekt/client/peer). Any client or server implementing this specification interoperates seamlessly.


1. Design Goals ​

  1. Transport-agnostic: The exact same binary framing runs over ADB reverse TCP sockets, usbmuxd loopback TCP sockets, LAN WebSocket binary messages, and future WAN WSS relays.
  2. Payload-agnostic: Payloads are always opaque raw byte arrays (bytes). Business modules are demultiplexed by ch (channel name) without coupling the wire layer to any application schema.
  3. Three first-class primitives: Unidirectional messages (DATA, supporting unicast, subset multicast, and * broadcast), correlated RPC (REQ / RESP with req_id and timeouts), and zero-copy multiplexed streams (STREAM_OPEN / STREAM_CHUNK / STREAM_CLOSE).
  4. Multi-device, multi-app, multi-link merge: Supports multiple apps on one unrooted phone and automatically merges simultaneous USB + LAN transports under a single peer_id with instant failover.

2. Binary Framing ​

All multi-byte integers are encoded in Big-Endian (Network Byte Order).

2.1 Frame Layout ​

text
 0      2      3      4      5           9          13          15          19
+------+------+------+------+-----------+-----------+-----------+-----------+--------------------+---------------------+
|Magic | Ver  | Type |Flags |   ReqID   | StreamID  | HeaderLen |PayloadLen | Header (UTF-8 JSON)|  Payload (raw bytes)|
| (2B) | (1B) | (1B) | (1B) |   (4B)    |   (4B)    |   (2B)    |   (4B)    |   (HeaderLen B)    |   (PayloadLen B)    |
+------+------+------+------+-----------+-----------+-----------+-----------+--------------------+---------------------+
  • Fixed header size: 19 bytes.
  • Field definitions:
OffsetSizeTypeFieldDescription
0..22B[u8; 2]magicFixed magic 0x43 0x4B (ASCII "CK"). Disconnect immediately on mismatch.
21Bu8versionProtocol version, fixed at 0x01.
31Bu8frame_typeFrame type enum (see 2.2 Frame Types).
41Bu8flagsBit flags, default 0x00. Bit 0x01 = IS_ERROR (valid on RESP and STREAM_CLOSE); remaining bits reserved.
5..94Bu32req_idRequest correlation ID. Monotonically incremented per connection starting at 1 (skipping 0) on REQ, echoed verbatim on RESP; 0 on all other frames.
9..134Bu32stream_idStream identifier. 0 for non-stream frames; non-zero u32 for STREAM_* frames enabling frame-level multiplexing.
13..152Bu16header_lenByte length of header (0..=65535). 0 indicates no JSON header.
15..194Bu32payload_lenByte length of payload. Default max frame payload is 16 MiB (16_777_216 bytes); oversized frames are rejected and disconnected.
19..varUTF-8headerUTF-8 encoded JSON object (present when header_len > 0).
followingvar[u8]payloadRaw opaque payload bytes (present when payload_len > 0).

WebSocket transport rule: Over WebSocket (LAN / Relay), every WebSocket Binary Message carries one complete frame (19 + header_len + payload_len bytes), reusing the exact same encoder/decoder as raw TCP streams.

2.2 Frame Types (frame_type) ​

ValueNameDirectionDescription
0x01HELLOClient → PCFirst frame after connect; reports peer identity and device metadata.
0x02HELLO_ACKPC → ClientHandshake acknowledgement returning Hub info, accepted peer_id, and heartbeat interval.
0x03PINGBidirectionalHeartbeat probe (header_len = 0, payload_len = 0 or optional timestamp).
0x04PONGBidirectionalHeartbeat acknowledgement.
0x05PEER_LISTPC → ClientFull snapshot of online peers pushed whenever topology or active transport changes.
0x10DATABidirectional / RelayedUnidirectional message (unicast, dsts subset multicast, or "*" broadcast).
0x11REQBidirectional / RelayedRequest frame expecting a correlated RESP with the same req_id.
0x12RESPBidirectional / RelayedResponse frame carrying the matching req_id.
0x20STREAM_OPENBidirectional / Relayed0-RTT stream open carrying stream_id, RouteHeader, and optional meta (unicast, subset multicast, or broadcast).
0x21STREAM_CHUNKBidirectional / RelayedStream data chunk (header_len = 0, zero JSON overhead), routed solely by stream_id.
0x22STREAM_CLOSEBidirectional / RelayedStream termination: clean EOF (flags = 0, header_len = 0) or abort / receiver reject / cancel (flags = 0x01).

2.3 Golden Test Vector ​

All SDKs validate byte-for-byte encoding parity against this vector:

  • Input:
    • version = 1, frame_type = 0x10 (DATA), flags = 0x00, req_id = 0, stream_id = 0
    • header = {"src":"pc","dst":"dev1/appA","ch":"ping"} (42 bytes = 0x002A)
    • payload = b"hello" (5 bytes = 0x00000005)
  • Expected output (19 + 42 + 5 = 66 bytes, hex):
text
43 4b                                           # magic: "CK"
01                                              # version: 1
10                                              # type: DATA (0x10)
00                                              # flags: 0
00 00 00 00                                     # req_id: 0
00 00 00 00                                     # stream_id: 0
00 2a                                           # header_len: 42
00 00 00 05                                     # payload_len: 5
7b 22 73 72 63 22 3a 22 70 63 22 2c 22 64 73 74 # {"src":"pc","dst
22 3a 22 64 65 76 31 2f 61 70 70 41 22 2c 22 63 # ":"dev1/appA","c
68 22 3a 22 70 69 6e 67 22 7d                   # h":"ping"}
68 65 6c 6c 6f                                  # "hello"

3. Identity & Routing ​

3.1 Device & Peer Identity ​

To support multiple apps per device and multi-link merge (USB + LAN) simultaneously:

  • peer_id (global routing key, generated by the peer SDK and identical across every transport):
    • Format: <client_id>/<package_or_bundle_id> (optional :<process_suffix> for multi-process apps).
    • client_id is a persistent 8–12 character random ID stored locally (SharedPreferences / UserDefaults / localStorage).
    • Because the same app instance reports the exact same peer_id over both USB and LAN, the PC Hub merges both links automatically.
  • Reserved addresses:
    • "pc" — The PC Hub itself.
    • "*" — Broadcast to all online peers except the sender (valid for DATA and STREAM_OPEN, invalid for REQ).
  • Physical device grouping:
    • Over ADB or usbmuxd, the Hub captures the hardware USB serial / UDID and caches peer_id → serial so device grouping survives unplug failover onto Wi-Fi.
    • Over LAN-only, peers group by their reported device_id.

3.2 JSON Header Schemas ​

1) HELLO (0x01, Client → PC) ​

payload_len = 0:

json
{
  "peer_id": "a1b2c3d4/com.demo.shop",
  "device_id": "dev-9f8e7d6c",
  "package_name": "com.demo.shop",
  "app_name": "Demo Shop",
  "process_name": "com.demo.shop",
  "pid": 14820,
  "platform": "android",
  "model": "Pixel 9",
  "manufacturer": "Google",
  "os_version": "15",
  "transport": "adb",
  "sdk_version": "0.1.0"
}

2) HELLO_ACK (0x02, PC → Client) ​

payload_len = 0:

json
{
  "hub_id": "pc",
  "hub_version": "0.1.0",
  "accepted_peer_id": "a1b2c3d4/com.demo.shop",
  "heartbeat_interval_ms": 10000
}

3) PEER_LIST (0x05, PC → Client) ​

Full online snapshot pushed on peer connect, disconnect, or active transport change (payload_len = 0):

json
{
  "peers": [
    {
      "peer_id": "a1b2c3d4/com.demo.shop",
      "device_id": "dev-9f8e7d6c",
      "serial": "DEVICE_SERIAL",
      "package_name": "com.demo.shop",
      "app_name": "Demo Shop",
      "model": "Pixel 9",
      "os_version": "15",
      "transports": ["adb", "lan"],
      "active_transport": "adb"
    }
  ]
}

4) DATA (0x10) & REQ (0x11) ​

json
{
  "src": "pc",
  "dst": "a1b2c3d4/com.demo.shop",
  "ch": "network"
}
  • Subset multicast (DATA and STREAM_OPEN only): Include optional dsts array (omitted when empty so unicast/broadcast pay zero overhead):
    json
    {
      "src": "dev1/com.appA",
      "dst": "",
      "dsts": ["pc", "dev2/com.appB"],
      "ch": "notice"
    }
  • Anti-spoofing: On inbound client frames, the Hub always overwrites src with the authenticated peer_id of that connection.
  • Routing rules:
    • dst == "pc": Delivered to PC Hub handlers and subscribed Control API clients.
    • dst == "*": Broadcast to every online peer except src, plus PC listeners.
    • Non-empty dsts: Deduplicated once in PeerRegistry, excluding src, and fanned out zero-copy via Bytes::clone().
    • Unicast peer_id: Routed via the target peer's highest-priority active transport. For REQ to an offline peer, the Hub immediately replies with RESP (flags = 0x01, err_code = "PEER_OFFLINE").

5) RESP (0x12) ​

Must carry the exact req_id of the originating REQ:

  • Success (flags = 0x00): Raw response bytes in payload, header = { "src", "dst", "ch" }.
  • Error (flags = 0x01): payload_len = 0:
    json
    {
      "src": "a1b2c3d4/com.demo.shop",
      "dst": "pc",
      "ch": "layout",
      "err_code": "PEER_OFFLINE",
      "err_msg": "Target peer is not connected"
    }

6) Multiplexed Streams: STREAM_OPEN (0x20) / STREAM_CHUNK (0x21) / STREAM_CLOSE (0x22) ​

  • STREAM_OPEN: 0-RTT stream open with non-zero stream_id, payload_len = 0, standard RouteHeader plus optional meta (Map<String, String>):
    json
    {
      "src": "pc",
      "dst": "a1b2c3d4/com.demo.shop",
      "ch": "files",
      "meta": { "name": "dump.hprof", "mime": "application/octet-stream" }
    }
    • Collision-free remapping: The Hub keys streams by (src_peer_id, upstream_stream_id) and allocates an independent downstream_stream_id per downstream link so concurrent senders never collide.
  • STREAM_CHUNK: Hot-path chunk with header_len = 0. SDKs auto-chunk payloads at 64 KiB by default to prevent head-of-line blocking, and the Hub fans chunks out zero-copy via Bytes::clone().
  • STREAM_CLOSE:
    • Clean EOF: flags = 0x00, header_len = 0, payload_len = 0.
    • Abort / reject / cancel: flags = 0x01 with JSON err_code and err_msg.
    • Partial multicast reject: If one receiver rejects or disconnects from a multicast stream, the Hub removes only that receiver; the upstream sender is cancelled only when the last receiver exits.
    • Bounded queues: Default 32 chunks per stream and 64 concurrent active streams per Hub; abrupt disconnect sends STREAM_CLOSE(PEER_OFFLINE) to all counterparties and frees routing entries immediately.

3.3 Standard Error Codes (err_code) ​

CodeMeaning
PEER_OFFLINETarget peer is offline or disconnected mid-flight
TIMEOUTLocal caller timed out waiting for RESP
NO_HANDLERRemote peer has no registered request or stream handler for ch
HANDLER_ERRORRemote handler threw an error or sender called abort()
INVALID_REQUESTMalformed request (e.g. REQ with "*", empty target list, or stream limit exceeded)
INTERNAL_ERRORInternal routing or transport failure
STREAM_REJECTEDReceiver rejected stream via stream.reject(reason) after inspecting meta
STREAM_CANCELLEDReceiver cancelled or dropped the stream before EOF

4. Connection Lifecycle, Heartbeat & Failover ​

  1. Handshake timeout: Clients must send HELLO within 5s of opening a TCP/WebSocket connection. The Hub replies with HELLO_ACK followed by PEER_LIST.
  2. Heartbeat:
    • Clients send PING every 10s (as advertised in HELLO_ACK); the Hub replies immediately with PONG.
    • Either side closes the connection if no frame arrives for 30s.
  3. Reconnect backoff: Exponential backoff 500ms → 1s → 2s → 4s → 5s (cap), resetting on successful handshake.
  4. Multi-link priority: adb (100) / usbmux (100) > lan (50) > custom (25) > relay (10). Reconnecting on the same (peer_id, transport) smoothly replaces the previous socket.

5. Transport Details ​

5.1 ADB USB Transport (Android) ​

  • Connects to local ADB server at 127.0.0.1:${ANDROID_ADB_SERVER_PORT:-5037} (spawns adb start-server once if refused).
  • Streams host:track-devices-l (falling back to host:track-devices).
  • For each online device <serial>:
    1. Binds an ephemeral local loopback listener 127.0.0.1:0 → <local_port>.
    2. Issues host:transport:<serial> + reverse:forward:tcp:19527;tcp:<local_port>.
    3. Tags all accepted sockets with transport = "adb" and serial = "<serial>".
  • On device unplug or graceful Hub shutdown, tears down listeners and cleans up reverse:killforward:tcp:19527.
  • On Android, AdbTransportClient connects as a plain TCP client to 127.0.0.1:19527 (only standard INTERNET permission; 100% zero-root Android 5–15).

5.2 usbmuxd USB Transport (iOS) ​

  • Connects to /var/run/usbmuxd (macOS/Linux) or 127.0.0.1:27015 (Windows) using native binary/XML plist framing.
  • Listens for iOS device attach/detach events and connects into the iOS SDK's local USB loopback listener without requiring Xcode or iproxy.

5.3 LAN WebSocket & Discovery ​

  • Hub listens on 0.0.0.0:9527 (configurable), serving device WebSockets at /ws.
  • Broadcasts UDP discovery beacons every 2s to port 19528 (and directed subnet broadcasts) plus Bonjour/mDNS _connekt._tcp:
    json
    {
      "magic": "connekt",
      "version": 1,
      "ws_port": 9527,
      "hub_name": "MacBook-Pro"
    }
  • Peers can also connect via an explicit URL (ws://<pc_ip>:9527/ws) or QR code when UDP broadcast is restricted by corporate Wi-Fi.

Released under the MIT License.