# CybSin in Python — httpx/requests + websockets + cryptography

`pip install websockets cryptography requests`

```python
import asyncio, hashlib, json, platform, socket, struct, uuid, getpass, requests, 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

SERVER = "https://cybsin.com"
APP_KEY = "cs_app_REPLACE_ME"
BUNDLE_ID = "com.example.notedrop.desktop"

def device_identity() -> dict:
    mac = uuid.getnode()
    return {"name": socket.gethostname(), "platform": {"Windows": "windows", "Darwin": "macos"}.get(platform.system(), "linux"),
            "model": platform.machine(), "os_version": platform.version()[:40], "hostname": socket.gethostname(),
            "os_user": getpass.getuser(), "mac": ":".join(f"{(mac >> s) & 0xff:02x}" for s in range(40, -1, -8)),
            "bundle_id": BUNDLE_ID, "app_version": "1.0.0"}

class Client:
    def __init__(self): self.token = None; self.device_id = None
    def _post(self, path, body=None, auth=False):
        h = {"X-App-Key": APP_KEY}
        if auth: h["Authorization"] = f"Bearer {self.token}"
        r = requests.post(SERVER + path, json=body or {}, headers=h, timeout=20)
        if r.status_code == 402: raise RuntimeError(f"payment_required: {r.json()['detail']}")
        r.raise_for_status(); return r.json()
    def sign_in(self, email, password, register=False):
        r = self._post("/api/v1/register" if register else "/api/v1/login", {"email": email, "password": password, "device": device_identity()})
        self.token, self.device_id = r["token"], r.get("device_id")
    def pair_new(self): r = self._post("/api/v1/pair/new", {"device_id": self.device_id}, True); return r["code"], r["session_id"], r["qr"]
    def pair_join(self, code): return self._post("/api/v1/pair/join", {"code": code, "device_id": self.device_id}, True)["session_id"]

    async def connect(self, session, role, code):
        ws_base = SERVER.replace("https://", "wss://").replace("http://", "ws://")
        ws = await websockets.connect(f"{ws_base}/ws/relay/{session}?token={self.token}&role={role}&app_key={APP_KEY}&device_id={self.device_id or 0}",
                                      max_size=4 * 1024 * 1024 + 64)
        while True:                                   # wait for joined
            m = await ws.recv()
            if isinstance(m, str):
                t = json.loads(m)
                if t.get("t") == "joined": break
                if t.get("t") in ("expired",) or t.get("code"): raise RuntimeError(t)
        tun = Tunnel(ws, role, code); await tun.handshake(); return tun

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

class Tunnel:
    def __init__(self, ws, role, code):
        self.ws, self.code = ws, code
        self.me, self.them = (1, 2) if role == "host" else (2, 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): theirs = await self.ws.recv()
        shared = priv.exchange(X25519PublicKey.from_public_bytes(theirs))
        self.aead = ChaCha20Poly1305(HKDF(hashes.SHA256(), 32, salt=self.code.encode(), info=b"cybsin-v1").derive(shared))
        hp, gp = (mine, theirs) if self.me == 1 else (theirs, mine)
        fp = hashlib.sha256(hp + gp).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 payload, or dict control frame ({"t":"peer_left"}); raises on decryption failure (fatal)."""
        m = await self.ws.recv()
        if isinstance(m, str): return json.loads(m)
        out = self.aead.decrypt(nonce(self.them, self.rx), m, None); self.rx += 1; return out

# --- demo: run `python app.py host` on one machine, `python app.py guest 429183` on the other
async def main():
    import sys
    c = Client(); c.sign_in("you@example.com", "correct horse battery", register=False)
    if sys.argv[1] == "host":
        code, session, qr = c.pair_new(); print("code:", code, "qr:", qr)
        t = await c.connect(session, "host", code); print("SAS", t.sas)
        await t.send(b"hello from host"); print(await t.recv())
    else:
        code = sys.argv[2]; session = c.pair_join(code)
        t = await c.connect(session, "guest", code); print("SAS", t.sas)
        print(await t.recv()); await t.send(b"hello from guest")

if __name__ == "__main__": asyncio.run(main())
```
