## WebSocket Handshake Logic for Community Hub & Compliance Engine

This document outlines the standard WebSocket handshake process, integrated with JWT-based authentication for secure communication in the Community Hub.

### 1. Client Initiates Connection Request
The client (web browser or mobile app) initiates the WebSocket connection by sending an HTTP GET request to the WebSocket server endpoint (e.g., `wss://api.mysportmanager.ie/chat`). This request *must* include the following specific HTTP headers:
-   `Upgrade: websocket`
-   `Connection: Upgrade`
-   `Sec-WebSocket-Key`: A unique, randomly generated base64-encoded 16-byte value. This key is crucial for establishing the WebSocket connection's integrity.
-   `Sec-WebSocket-Version: 13`: Specifies the WebSocket protocol version (currently the standard).
-   `Authorization: Bearer <JWT_TOKEN>`: A JSON Web Token (JWT) must be included in the Authorization header. This token, obtained from a secure authentication endpoint (e.g., OAuth 2.0 flow), authenticates the user for WebSocket access.

### 2. Server Validation and Authentication
Upon receiving the client's request, the WebSocket server performs a series of validations:
a.  **Header Verification:** The server first validates the `Upgrade`, `Connection`, and `Sec-WebSocket-Version` headers to ensure they comply with the WebSocket protocol specification.
b.  **JWT Authentication:** The server extracts the `<JWT_TOKEN>` from the `Authorization: Bearer` header. It then performs critical security checks:
    -   **Signature Verification:** Ensures the JWT's signature is valid, preventing tampering.
    -   **Expiration Check:** Verifies that the JWT has not expired.
    -   **Claim Validation:** Checks essential claims like `sub` (subject/user ID) and `aud` (audience) to confirm the token's legitimacy and intended use.
    -   **Rejection:** If the JWT is missing, invalid, expired, or tampered with, the server MUST reject the connection attempt by not proceeding with the handshake (e.g., by returning an HTTP 401 Unauthorized status or simply closing the TCP connection).
c.  **Origin Check (Recommended):** The server should check the `Origin` header to ensure the request is coming from an allowed domain, mitigating cross-site WebSocket hijacking attacks.
d.  **`Sec-WebSocket-Key` Processing:** If all preceding validations (headers, JWT, origin) are successful, the server computes the `Sec-WebSocket-Accept` value. This is done by concatenating the client's `Sec-WebSocket-Key` with a fixed GUID ("258EAFA5-E914-47DA-95CA-C5AB0DC85B11"), hashing the result using SHA-1, and then base64-encoding the hash.

### 3. Server Responds and Upgrades Protocol
If all validations and authentication steps are successful, the server responds to the client with an HTTP 101 Switching Protocols status code. This response signifies the successful upgrade of the HTTP connection to a WebSocket protocol. The response headers include:
-   `HTTP/1.1 101 Switching Protocols`
-   `Upgrade: websocket`
-   `Connection: Upgrade`
-   `Sec-WebSocket-Accept`: The value computed in the previous step, confirming the server's acceptance of the WebSocket connection.

### 4. Persistent Connection Established
Upon receiving the 101 response, the client confirms the handshake, and the full-duplex, persistent WebSocket connection is established. Both the client and server can now exchange data using WebSocket frames.

### Security Considerations:
-   **WSS (SSL/TLS):** All WebSocket connections must operate over `wss://` (WebSocket Secure) to ensure all data, including the JWT during handshake and subsequent messages, is encrypted in transit using SSL/TLS.
-   **JWT Expiration & Renewal:** Implement graceful handling for JWT expiration. Clients should ideally refresh tokens without requiring a full reconnection, or be able to reconnect seamlessly with a new valid token.
-   **Rate Limiting:** Protect the WebSocket connection endpoint with rate limiting to prevent Denial-of-Service (DoS) attacks.
-   **Input Validation:** All messages received over the WebSocket connection must be thoroughly validated on the server-side to prevent malicious data injection or unexpected application behavior.
-   **Session Management:** Ensure robust server-side session management tied to the validated JWT to maintain user state and permissions.
