# KoalaSync Architecture This document describes the communication flows and internal logic of the KoalaSync system. ## 1. Extension Startup & Connection - **Initialization**: On startup, `background.js` reads settings (Server URL, Username, Last Room) from `chrome.storage.sync`. - **WebSocket Handshake**: 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 `