v0.166.0
 1"""E2E encryption for portal sessions using SPAKE2 + NaCl.
 2
 3Both sides derive a shared secret from the human-readable portal code
 4via SPAKE2 (a password-authenticated key exchange). An eavesdropper
 5observing the relay traffic cannot brute-force the code offline.
 6
 7All messages after the key exchange are encrypted with NaCl SecretBox
 8(XSalsa20-Poly1305).
 9
10The portal code is never sent to the relay. Instead, a SHA-256 hash
11of the code is used as the channel ID for pairing. The raw code is
12only used locally for the SPAKE2 exchange.
13"""
14
15import base64
16import hashlib
17import json
18
19import nacl.secret
20import spake2
21from websockets.asyncio.client import ClientConnection
22
23
24def channel_id(code: str) -> str:
25    """Derive a relay channel ID from the portal code.
26
27    Uses SHA-256 so the relay never learns the raw code and cannot
28    perform SPAKE2 to impersonate either side.
29    """
30    return hashlib.sha256(code.encode("utf-8")).hexdigest()
31
32
33async def perform_key_exchange(
34    ws: ClientConnection, code: str, *, side: str
35) -> PortalEncryptor:
36    """Run the SPAKE2 handshake over a WebSocket and return an encryptor.
37
38    `side` must be "start" (SPAKE2_A / initiator) or "connect" (SPAKE2_B / joiner).
39    """
40    spake_cls = spake2.SPAKE2_A if side == "start" else spake2.SPAKE2_B
41    spake_instance = spake_cls(code.encode("utf-8"))
42    spake_msg = spake_instance.start()
43
44    await ws.send(base64.b64encode(spake_msg).decode("ascii"))
45    peer_msg = base64.b64decode(await ws.recv())
46    key = spake_instance.finish(peer_msg)
47    return PortalEncryptor(key)
48
49
50class PortalEncryptor:
51    """Encrypts and decrypts portal messages using a shared key."""
52
53    def __init__(self, key: bytes) -> None:
54        # SPAKE2 produces a 32-byte key, which is exactly what SecretBox wants.
55        self._box = nacl.secret.SecretBox(key)
56
57    def encrypt(self, data: bytes) -> bytes:
58        """Encrypt data. Returns nonce + ciphertext."""
59        return self._box.encrypt(data)
60
61    def decrypt(self, data: bytes) -> bytes:
62        """Decrypt data. Expects nonce + ciphertext."""
63        return self._box.decrypt(data)
64
65    def encrypt_message(self, msg: dict) -> bytes:
66        """Encrypt a JSON-serializable message dict."""
67        plaintext = json.dumps(msg).encode("utf-8")
68        return self.encrypt(plaintext)
69
70    def decrypt_message(self, data: bytes) -> dict:
71        """Decrypt and parse a JSON message dict."""
72        plaintext = self.decrypt(data)
73        return json.loads(plaintext.decode("utf-8"))