# CybSin end-to-end recipe (cybsin-v1) — byte-exact

Three implementations ship today (Swift CryptoKit, Rust, Python) and they
interoperate. Yours must produce identical bytes.

## Handshake

1. Wait for the relay text frame `{"t":"joined"}`.
2. Generate an ephemeral X25519 key pair. Send **your 32-byte raw public key as
   one binary frame**. Receive the peer's 32-byte key (first binary frame).
3. `shared = X25519(our_priv, their_pub)` (32 bytes).
4. `key = HKDF-SHA256(ikm=shared, salt=ASCII bytes of the 6-digit pairing code, info=b"cybsin-v1", length=32)`
5. SAS: `fp = SHA256(host_pub || guest_pub)` (host first on both sides);
   display `"%02X%02X · %02X%02X" % (fp[0], fp[1], fp[2], fp[3])`, e.g. `A7F3 · 9C21`.

## Frames

- Cipher: ChaCha20-Poly1305, IETF variant (12-byte nonce, 16-byte tag), no associated data.
- Nonce (never transmitted): `direction (1 byte) || 0x00 0x00 0x00 || counter (u64 big-endian)`.
  - direction: host sends with `0x01`, guest sends with `0x02`.
  - counter: starts at 0 for the first encrypted frame in that direction, +1 per frame sent.
  - Receiver keeps its own expected counter for the peer's direction.
- Wire format of a data frame: `ciphertext || tag` (exactly what the IETF AEAD outputs).
- Max frame 4 MiB after encryption; chunk payloads at ≤ 1 MiB for comfort.
- Decryption failure ⇒ fatal: close the socket, show an error, never re-sync counters.

## Test vector

```
pairing code      = "429183"
host_priv (hex)   = 77076d0a7318a57d3c16c17251b26645df4c2f87ebc0992ab177fba51db92c2a
guest_priv (hex)  = 5dab087e624a8a4b79e17f8b83800ee66f3bb1292618b6fd1c2f8b27ff88e0eb
host_pub          = 8520f0098930a754748b7ddcb43ef75a0dbf3a0d26381af4eba4a98eaa9b4e6a
guest_pub         = de9edb7d7b7dc1b4d35b61c2ece435373f8343c85b78674dadfc7e146f882b4f
shared            = 4a5d9d5ba4ce2de1728e3bf480350f25e07e21c947d19e3376f09b3c1e161742
key               = HKDF-SHA256(shared, salt=b"429183", info=b"cybsin-v1", 32)
host frame #0 of b"hello" = ChaCha20Poly1305(key).encrypt(nonce=01 000000 0000000000000000, b"hello")
```
Compute `key` and the frame with the Python reference below and compare with
your implementation before testing on devices. (The X25519 pair above is RFC 7748 §6.1.)

## Python reference (cryptography ≥ 42, websockets ≥ 12)

```python
import asyncio, hashlib, json, struct, websockets
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.asymmetric.x25519 import X25519PrivateKey, X25519PublicKey
from cryptography.hazmat.primitives.ciphers.aead import ChaCha20Poly1305
from cryptography.hazmat.primitives.kdf.hkdf import HKDF

def nonce(direction: int, counter: int) -> bytes:
    return bytes([direction, 0, 0, 0]) + struct.pack(">Q", counter)

class Tunnel:
    def __init__(self, ws, role: str, code: str):
        self.ws, self.code = ws, code
        self.me = 1 if role == "host" else 2
        self.them = 2 if role == "host" else 1
        self.tx = self.rx = 0
        self.aead = None; self.sas = None

    async def handshake(self):
        priv = X25519PrivateKey.generate()
        mine = priv.public_key().public_bytes_raw()
        await self.ws.send(mine)
        theirs = await self.ws.recv()
        while isinstance(theirs, str):            # skip stray text control frames
            theirs = await self.ws.recv()
        shared = priv.exchange(X25519PublicKey.from_public_bytes(theirs))
        key = HKDF(hashes.SHA256(), 32, salt=self.code.encode(), info=b"cybsin-v1").derive(shared)
        self.aead = ChaCha20Poly1305(key)
        host_pub, guest_pub = (mine, theirs) if self.me == 1 else (theirs, mine)
        fp = hashlib.sha256(host_pub + guest_pub).digest()
        self.sas = f"{fp[0]:02X}{fp[1]:02X} · {fp[2]:02X}{fp[3]:02X}"

    async def send(self, data: bytes):
        await self.ws.send(self.aead.encrypt(nonce(self.me, self.tx), data, None)); self.tx += 1

    async def recv(self) -> bytes | dict:
        m = await self.ws.recv()
        if isinstance(m, str):
            return json.loads(m)                   # {"t":"peer_left"} etc.
        out = self.aead.decrypt(nonce(self.them, self.rx), m, None); self.rx += 1
        return out
```
