# CybSin in Rust — ureq + tungstenite + x25519-dalek + chacha20poly1305 + hkdf

Reference implementation ships in the EMPTY desktop receiver (`relay.rs`).

```toml
[dependencies]
ureq = { version = "2", features = ["json"] }
tungstenite = { version = "0.24", features = ["native-tls"] }
x25519-dalek = { version = "2", features = ["getrandom"] }
chacha20poly1305 = "0.10"
hkdf = "0.12"
sha2 = "0.10"
rand = "0.8"
serde = { version = "1", features = ["derive"] }
serde_json = "1"
hostname = "0.4"
mac_address = "1"          # desktop MAC for device identity
anyhow = "1"
```

```rust
use anyhow::{anyhow, bail, Result};
use chacha20poly1305::{aead::Aead, ChaCha20Poly1305, KeyInit, Nonce};
use hkdf::Hkdf;
use serde_json::{json, Value};
use sha2::{Digest, Sha256};
use tungstenite::{connect, Message, WebSocket, stream::MaybeTlsStream};
use std::net::TcpStream;

pub const APP_KEY: &str = "cs_app_REPLACE_ME";
pub const BUNDLE_ID: &str = "com.example.notedrop.desktop";

pub struct Client { pub server: String, pub token: Option<String>, pub device_id: Option<i64> }

fn device_identity() -> Value {
    json!({
        "name": hostname::get().map(|h| h.to_string_lossy().into_owned()).unwrap_or("Desktop".into()),
        "platform": std::env::consts::OS,           // "windows" | "macos" | "linux"
        "os_version": "", "model": std::env::consts::ARCH,
        "hostname": hostname::get().map(|h| h.to_string_lossy().into_owned()).unwrap_or_default(),
        "os_user": std::env::var("USERNAME").or_else(|_| std::env::var("USER")).unwrap_or_default(),
        "mac": mac_address::get_mac_address().ok().flatten().map(|m| m.to_string()).unwrap_or_default(),
        "bundle_id": BUNDLE_ID, "app_version": env!("CARGO_PKG_VERSION"),
    })
}

impl Client {
    fn post(&self, path: &str, body: Value, auth: bool) -> Result<Value> {
        let mut req = ureq::post(&format!("{}{}", self.server, path)).set("X-App-Key", APP_KEY);
        if auth { req = req.set("Authorization", &format!("Bearer {}", self.token.clone().unwrap_or_default())); }
        match req.send_json(body) {
            Ok(r) => Ok(r.into_json()?),
            Err(ureq::Error::Status(402, r)) => bail!("payment_required: {}", r.into_string().unwrap_or_default()),
            Err(ureq::Error::Status(c, r)) => bail!("HTTP {c}: {}", r.into_string().unwrap_or_default()),
            Err(e) => Err(e.into()),
        }
    }
    pub fn sign_in(&mut self, email: &str, password: &str, register: bool) -> Result<()> {
        let r = self.post(if register { "/api/v1/register" } else { "/api/v1/login" },
                          json!({"email": email, "password": password, "device": device_identity()}), false)?;
        self.token = r["token"].as_str().map(String::from);
        self.device_id = r["device_id"].as_i64();
        Ok(())
    }
    pub fn pair_new(&self) -> Result<(String, String)> {
        let r = self.post("/api/v1/pair/new", json!({"device_id": self.device_id}), true)?;
        Ok((r["code"].as_str().unwrap().into(), r["session_id"].as_str().unwrap().into()))
    }
    pub fn pair_join(&self, code: &str) -> Result<String> {
        let r = self.post("/api/v1/pair/join", json!({"code": code, "device_id": self.device_id}), true)?;
        Ok(r["session_id"].as_str().unwrap().into())
    }
    pub fn connect(&self, session: &str, host: bool, code: &str) -> Result<Tunnel> {
        let ws_base = self.server.replacen("https://", "wss://", 1).replacen("http://", "ws://", 1);
        let url = format!("{ws_base}/ws/relay/{session}?token={}&role={}&app_key={APP_KEY}&device_id={}",
                          self.token.clone().unwrap_or_default(), if host { "host" } else { "guest" }, self.device_id.unwrap_or(0));
        let (mut ws, _) = connect(url)?;
        loop {                                                   // wait for {"t":"joined"}
            match ws.read()? {
                Message::Text(t) => {
                    let v: Value = serde_json::from_str(&t)?;
                    match v["t"].as_str() { Some("joined") => break, Some("expired") => bail!("pairing expired"),
                                            Some("error") => bail!("{}", v["code"]), _ => {} }
                }
                Message::Close(_) => bail!("relay closed before peer joined"),
                _ => {}
            }
        }
        Tunnel::handshake(ws, host, code)
    }
}

pub struct Tunnel {
    ws: WebSocket<MaybeTlsStream<TcpStream>>,
    aead: ChaCha20Poly1305, dir_me: u8, dir_them: u8, tx: u64, rx: u64,
    pub sas: String,
}

fn nonce(dir: u8, counter: u64) -> Nonce {
    let mut n = [0u8; 12]; n[0] = dir; n[4..].copy_from_slice(&counter.to_be_bytes()); Nonce::from(n)
}

impl Tunnel {
    fn handshake(mut ws: WebSocket<MaybeTlsStream<TcpStream>>, host: bool, code: &str) -> Result<Self> {
        let secret = x25519_dalek::EphemeralSecret::random_from_rng(rand::thread_rng());
        let mine = x25519_dalek::PublicKey::from(&secret);
        ws.send(Message::Binary(mine.as_bytes().to_vec()))?;
        let theirs: [u8; 32] = loop {
            if let Message::Binary(b) = ws.read()? { if b.len() == 32 { break b.try_into().unwrap(); } }
        };
        let shared = secret.diffie_hellman(&x25519_dalek::PublicKey::from(theirs));
        let mut key = [0u8; 32];
        Hkdf::<Sha256>::new(Some(code.as_bytes()), shared.as_bytes()).expand(b"cybsin-v1", &mut key).map_err(|_| anyhow!("hkdf"))?;
        let (hp, gp) = if host { (mine.as_bytes(), &theirs) } else { (&theirs, mine.as_bytes()) };
        let fp = Sha256::digest([hp.as_slice(), gp.as_slice()].concat());
        Ok(Self { ws, aead: ChaCha20Poly1305::new(&key.into()), dir_me: if host {1} else {2}, dir_them: if host {2} else {1},
                  tx: 0, rx: 0, sas: format!("{:02X}{:02X} · {:02X}{:02X}", fp[0], fp[1], fp[2], fp[3]) })
    }
    pub fn send(&mut self, plaintext: &[u8]) -> Result<()> {
        let ct = self.aead.encrypt(&nonce(self.dir_me, self.tx), plaintext).map_err(|_| anyhow!("encrypt"))?;
        self.tx += 1;
        Ok(self.ws.send(Message::Binary(ct))?)                      // wire = ciphertext || tag
    }
    /// Ok(Some(bytes)) payload · Ok(None) peer left / closed · Err fatal
    pub fn recv(&mut self) -> Result<Option<Vec<u8>>> {
        loop {
            match self.ws.read()? {
                Message::Binary(ct) => {
                    let pt = self.aead.decrypt(&nonce(self.dir_them, self.rx), ct.as_ref()).map_err(|_| anyhow!("decrypt failed — fatal"))?;
                    self.rx += 1; return Ok(Some(pt));
                }
                Message::Text(t) => { if t.contains("peer_left") || t.contains("expired") { return Ok(None); } }
                Message::Close(_) => return Ok(None),
                _ => {}
            }
        }
    }
}
```

Notes
- Show the pairing code **and** a QR of `cybsin://pair?server=<url>&code=<code>&app=<key>` (crate `qrcode`).
- Frames ≤ 4 MiB: chunk files at 1 MiB and run your own framing inside.
- Keep `token` in the OS credential store (`keyring` crate) or a 0600 file.
