""" WebSocket endpoints for real-time ticket updates. """ from fastapi import APIRouter, WebSocket, WebSocketDisconnect, Query from uuid import UUID from core.websockets import manager from core.security import decode_access_token router = APIRouter() @router.websocket("/ws/{workspace_id}") async def ticket_events( websocket: WebSocket, workspace_id: UUID, token: str = Query(...) ): """ WebSocket endpoint for a specific workspace. Authenticates via token in query string (since WS headers are limited). """ # 1. Authenticate try: payload = decode_access_token(token) user_id = payload.get("sub") token_workspace_id = payload.get("workspace_id") role = payload.get("role", "").lower() # Security Guard: Customers are strictly isolated to their own workspace. # Staff (non-customer prefix) are allowed to monitor any workspace they jump into. is_customer = role.startswith("customer") or role == "customer" if is_customer and str(token_workspace_id) != str(workspace_id): await websocket.close(code=1008) # Policy Violation return except Exception: await websocket.close(code=1008) # Policy Violation return user_uuid = UUID(user_id) if isinstance(user_id, str) else user_id await manager.connect(websocket, workspace_id, user_uuid, role=role) try: # Keep alive - wait for messages (though we mainly broadcast) while True: data = await websocket.receive_text() # Handle client-to-server messages if needed except WebSocketDisconnect: manager.disconnect(websocket, workspace_id, user_uuid, role=role) @router.websocket("/ws/tickets/{ticket_id}") async def ticket_thread_events( websocket: WebSocket, ticket_id: UUID, token: str = Query(...) ): """ WebSocket endpoint for a specific ticket thread. Allows real-time message updates within the thread. """ try: payload = decode_access_token(token) user_id = payload.get("sub") # In a real app, we'd verify the user has access to this ticket except Exception: await websocket.close(code=1008) return await manager.connect_ticket(websocket, ticket_id) try: while True: await websocket.receive_text() except WebSocketDisconnect: manager.disconnect_ticket(websocket, ticket_id)