# KoalaSync Architecture This document describes the communication flows and internal logic of the KoalaSync system. ## 1. Extension Connection (Lazy Connect) - **Initialization**: On startup, `background.js` reads settings (Server URL, Username, Last Room) from `chrome.storage.sync`. No WebSocket connection is established at this point. - **On-Demand Connection**: The extension only connects when needed — either the user opens the popup with saved room credentials, or when actively in a room. When not in a room, no connection exists. This improves privacy (IP not exposed while idle) and reduces battery/network usage. - **WebSocket Handshake (when connecting)**: 1. Background creates a `new WebSocket` to `/socket.io/?EIO=4&transport=websocket&version=1.0.0`. 2. Server performs security checks: - **IP Rate Limit**: Checks if the IP has exceeded connection limits. - **Protocol Version**: Client must match the server's protocol (currently `1.0.0`). 3. Server responds with Engine.IO handshake (`0`) and the client joins the namespace (`40`). - **Room Join**: Background emits `JOIN_ROOM` containing `roomId`, `password`, `peerId`, and `username`. - **Deduplication**: If a user joins with a `peerId` that already has an active socket, the server kills the old socket to prevent "Ghost Peers". Deduplication re-validates after acquiring the room creation lock to avoid kicking the wrong socket during concurrent joins. ## 2. Media Event Synchronization When a user interacts with a video: 1. **Detection**: `content.js` listens to native events (`play`, `pause`, `seeked`) on the `