Skip to content

A tiny friend in your Mac's notch and on your iPhone that keeps an eye on your AI coding agents: Claude Code, Codex, Cursor, Gemini CLI, Antigravity and more. Approve from the notch or your Lock Screen.

12.9 KB
Raw Blame

Relay link (protocol v1 over the internet)

How Coucou for Android and a desktop Coucou talk through a relay when they are not on the same network. This is the wire specification; the reasoning, threats and stages are in android/RELAY_PLAN.md. The direct LAN link (docs/ANDROID_LINK.md) is unchanged and stays the fast path. Status: the computer side is built (stage R3, windows/src-tauri/src/phone_link/relay_client.rs); the phone side is built too (stage R4, android/app/.../link/WebSocket.kt, RelayLink.kt, Transport.kt). Fixed test vectors for everything below are in android/relay/test-vectors.json (generated by android/relay/tools/gen-vectors.mjs).

The relay is a small stateless forwarder that the user deploys on their own Cloudflare account. It forwards opaque frames between exactly two peers, a computer (role pc) and a phone (role phone), and never sees a content key. Every protocol v1 message (hello, welcome, sessions, approval, decision, chat*, …) travels inside an end-to-end encrypted channel exactly as it travels over TLS on the LAN.

1. Secrets, and who holds what

secret size made by held by relay sees it?
K, the pairing key 256 bits the computer, at pairing computer (OS keystore), phone (Keystore-encrypted) never
access key 256 bits the user, once, at deploy time the relay (a Worker secret), the computer (OS keystore), the phone (Keystore-encrypted) yes: it only lets a request create or join rooms
room id 128 bits the computer, at pairing all three yes (it is the address)
K_join (derived from K) 256 bits both sides both sides; the relay sees only that value in the join header yes, but it is a one-way derivation and cannot decrypt anything

The access key gates use of the relay (and of the user's free quota). It protects no content. K protects content.

2. Pairing link

The existing link gains optional fields (an older phone ignores unknown keys and pairs over the LAN only):

coucou://pair?v=1&host=…&port=…&fp=…&token=…&name=…&relay=<wss URL, percent-encoded>&room=<22 chars>&key=<43 chars>&access=<43 chars>
  • relay: wss:// URL of the relay, no path, no query, no credentials. The phone shows its host in the confirmation.
  • room: 16 random bytes, base64url without padding (22 characters).
  • key: K, 32 random bytes, base64url without padding (43 characters).
  • access: the access key, 32 bytes, base64url without padding (43 characters).
  • All of relay, room, key, access are present together or not at all.

3. Connecting to the relay

GET wss://<relay>/v1/room/<room>?role=pc|phone
Authorization: Bearer <access key, base64url>
Sec-WebSocket-Protocol: coucou.v1, coucou.join.<K_join, base64url>
  • The relay refuses, before it creates or contacts any room, a request whose path is not /v1/room/ plus exactly 22 base64url characters, whose role is not pc or phone, or whose Authorization does not carry the access key. The check is a constant-time comparison of SHA-256 digests. If the relay has no access key configured it refuses every room request (fail closed). Refusals are 404 (bad path), 401 (access key) or 429 (rate limit); the body is empty.
  • GET / answers 200 with the text Coucou link relay and needs no key.
  • The client offers both sub-protocols (a strict client requires the server to choose one it offered); the relay accepts the upgrade and answers with Sec-WebSocket-Protocol: coucou.v1. A request whose coucou.join. value is missing or is not 43 base64url characters is refused with 400 before any room is touched.
  • Join proof, in memory only. The first live socket of a room records SHA-256(K_join) in its WebSocket attachment (hibernation state, not storage). Later sockets of that room must present a K_join that hashes to the same value or are closed with 1008 join proof. When the room is empty the record is gone.
  • Slots. One live socket per role. A new socket for a role that already has one (with a valid join proof) replaces the old one, which is closed with 1000 replaced. One phone per room.
  • Limits. A frame is at most 66,000 bytes (larger: close 1009). Per room, a token bucket of 30 messages/s sustained, burst 60 (over: close 1008 rate). Per source address, a limit on new connections at the Worker (429).
  • No buffering. A frame for an absent peer is dropped and the sender receives the text message {"peer":"offline"}.
  • Hints. When the other role joins or leaves, the relay sends the remaining socket a text message {"peer":"online"} or {"peer":"offline"}. Hints are for the status line and the phone's retry; they are never trusted for anything else (they are not authenticated).
  • Keep-alive. A client may send the text message ping; the platform answers pong itself (setWebSocketAutoResponse), without waking the room, so heartbeats cost almost nothing. These are the only text messages a client may send; any other text message closes the socket with 1003. The relay has no idle timer (a timer would wake the room): liveness is judged by the clients, from the encrypted v1 ping/pong and from these pongs.
  • Access key rotation takes effect on live rooms. Each socket's attachment keeps the first 8 bytes of SHA-256(access key) it was admitted with; when the next frame arrives and the current key's digest differs, the relay closes the socket with 1008 access key changed.
  • The relay logs nothing (observability off), stores nothing (no storage API is used) and holds no key for any content.

4. Derived values

HKDF-SHA-256 (RFC 5869), empty salt unless stated, L = output length. LABEL = "coucou-relay/v1".

K_auth     = HKDF(ikm=K, salt="",                    info=LABEL + " auth",    L=32)
K_join     = HKDF(ikm=K, salt="",                    info=LABEL + " join",    L=32)
session    = HKDF(ikm=K, salt=N_phone ‖ N_pc,        info=LABEL + " session", L=64)
k_p2h      = session[0..32]      key for frames phone → computer
k_h2p      = session[32..64]     key for frames computer → phone

N_phone and N_pc are 16 random bytes each, fresh for every connection. ‖ is concatenation. Strings are UTF-8, the room is the 22 ASCII characters of the URL.

5. Frames

Every WebSocket binary message is one frame:

ver (1 byte = 1) ‖ type (1 byte) ‖ counter (8 bytes, big endian) ‖ body
type name sent by body counter
1 init phone N_phone (16) ‖ HMAC-SHA256(K_auth, "init" ‖ room ‖ N_phone) (32) 0
2 accept computer N_pc (16) ‖ HMAC-SHA256(K_auth, "accept" ‖ room ‖ N_phone ‖ N_pc) (32) 0
3 data either AES-256-GCM(key, nonce, aad, padded line) = ciphertext ‖ 16-byte tag 0, 1, 2, … per direction

Handshake

  1. The phone connects and, on every (re)connection and whenever it hears {"peer":"online"} without an open session, sends init.
  2. The computer checks the MAC with K_auth, creates a fresh N_pc, derives the session keys and answers accept. Only the newest init is answered; a computer that gets a new init drops its previous session.
  3. The phone checks that the accept MAC covers its current N_phone (so a recorded accept is useless), derives the same keys and may send data frames. The first valid data frame from the phone proves to the computer that the phone holds K.
  4. Inside the channel the ordinary v1 hello/welcome follow (token, protocol version, caps).
  5. A wrong MAC, a malformed frame or an unexpected type before the handshake ends is ignored; after 3 bad handshake frames the computer stops answering init for 10 s.

Data frames

  • Plaintext = u32 big-endian length ‖ the v1 line (UTF-8 JSON, without the newline, at most 65,536 bytes) ‖ zero bytes, so that the plaintext length is a multiple of 128 and at least 128. The receiver reads the length, takes that many bytes, and requires the rest to be zeros. (The padding hides whether a frame is a ping or an approval.)
  • Nonce (12 bytes) = direction (1 byte) ‖ 0x00 0x00 0x00 ‖ counter (8 bytes, big endian), with direction 1 for phone → computer and 2 for computer → phone.
  • AAD = LABEL ‖ room ‖ direction (1 byte) ‖ ver ‖ type ‖ counter (8 bytes).
  • Counters start at 0 in each direction of each session. The receiver accepts a data frame only if its counter is exactly the previous accepted counter plus 1 (0 for the first). A repeat, a gap, a jump back or a jump forward is a fault.
  • Faults (bad tag, bad header, wrong counter, bad padding, oversize): the receiver closes the session, discards the keys, and the phone starts again from step 1. No error text is sent to the peer.
  • A session ends at counter 2^32 − 1 (the frame with that counter is the last one); the sender re-handshakes before sending more.

Why a (key, nonce) pair never repeats

  1. The two directions use different keys (k_p2h, k_h2p) and different direction bytes in the nonce, so even a bug that made them share a key could not make a nonce collide across directions.
  2. Within a direction the counter strictly increases by 1, and the sender refuses to wrap (the session ends first).
  3. Every connection derives new keys from fresh random nonces, so a restart or reconnect (counter back to 0) is a new key. Random 128-bit nonces are used for this; a collision would need ~2^64 sessions.

Required tests (R2, both Rust and Kotlin; done in phone_link/relay_crypto.rs and link/RelayCryptoTest.kt): mustRefuse, mustRefuseInOrder and data vectors of test-vectors.json; a property test that enumerates (key, nonce) over thousands of frames in both directions and two sessions and finds no duplicate; a test that a sender at counter 2^32 − 1 refuses to send; a test that two sessions with different nonces have different keys.

6. Where protocol v1 plugs in

The computer feeds decrypted lines (adding \n) to the same server code that handles a LAN connection, and sends the lines it produces back through data frames. The phone's LinkClient reads and writes the same lines. Nothing in v1 changes: fingerprints, 120 s offers, decide-once, per-feature switches and the biometric gate behave as on the LAN.

One additive v1 message is defined for rotation (section 7), offered as the capability relay:

direction type fields meaning
computer → phone relayAccess access (43 base64url characters) the new access key, sent inside the authenticated channel (over the LAN or the relay)

The phone replaces its stored access key (Keystore-encrypted) and reconnects. A phone that did not negotiate relay is never sent it.

7. Rotation and revocation

what how effect
Access key openssl rand -base64 32 | tr '+/' '-_' | tr -d '=' → npx wrangler secret put ACCESS_KEY, then paste the same value into the computer's setting New connections with the old key are refused (401); live sockets are closed at their next frame (section 3). The computer sends relayAccess to paired phones so they follow without scanning again; a phone that was offline at that time re-scans or is sent it when it next connects over the LAN.
K and the room (“Pair again”) the computer makes a new K and room id The old room stays empty forever; the old phone cannot read or write anything new. A stolen or lost phone is cut off this way.
A phone leaving (“Disconnect this computer”) the phone deletes K, access key and token The pairing is gone on the phone; the computer can “Pair again”.

The access key can be rotated as often as the user likes: it protects the quota, not the content.

8. What each party can learn

party can see cannot see
relay (user's account) and Cloudflare IP addresses, that a pairing exists (stable room id), when each side is online, frame sizes (padded to 128) and timing any content, K, tokens, sessions, commands, paths, approvals, chat
someone with the access key only nothing about any room; can use the user's quota any content
someone with the room id only nothing any content; cannot join a live room without K_join
someone with K and the room id everything of that pairing, until “Pair again” other pairings

9. Known limits

  • No forward secrecy: session keys come from K and the nonces only (decision D3 of the plan). A later leak of K would let someone decrypt traffic they had recorded.
  • The relay can delay, drop or cut frames. It can never forge one. Dropping a decision leaves the approval to expire on the computer, which is not an allow.
  • An attacker who knows both the access key and a room id could occupy an empty room before its owner connects (the join proof is not stored); the owner sees “room is taken” and does “Pair again”.
  • Free-tier quota can be exhausted by anyone who holds the access key.