Overview
The WebSocket Service is the central hub for all real-time communication in MentraOS Cloud. It manages two separate WebSocket servers - one for smart glasses connections and another for third-party app connections. File:packages/cloud/src/services/websocket/websocket.service.ts
Architecture
Key Components
Singleton Pattern
The service implements a singleton pattern to ensure only one instance manages all WebSocket connections:Connection Routing
The service handles HTTP upgrade requests and routes them based on the URL path:/glasses-ws- Routes to glasses WebSocket handler/app-ws- Routes to app WebSocket handler- Unknown paths - Rejects connection
Authentication Flow
Glasses Authentication
For glasses connections (/glasses-ws):
- Token Extraction: JWT token from Authorization header
- Token Verification: Using
AUGMENTOS_AUTH_JWT_SECRET - User ID Extraction: From JWT payload (
userData.email) - Request Enhancement: Attaches
userIdto request object
App Authentication
For app connections (/app-ws):
-
JWT Authentication (preferred):
- Bearer token in Authorization header
- Headers:
x-user-idandx-session-idrequired - JWT payload contains
packageNameandapiKey
-
Request Enhancement: Attaches to request:
userId- From x-user-id headersessionId- From x-session-id headerappJwtPayload- Decoded JWT payload
Connection Handlers
Glasses Connection Handler
App Connection Handler
App Lifecycle Messages
The service provides methods to notify glasses when apps start or stop:sendAppStarted
Notifies glasses when an app begins running:sendAppStopped
Notifies glasses when an app stops:Error Handling
Authentication Errors
For glasses connections:HTTP Response Codes
- 401 Unauthorized: Invalid or missing authentication
- Connection closed: Unknown WebSocket path
Server Setup
The service attaches to an HTTP server using thesetupWebSocketServers method:
Logging
Comprehensive logging includes:- Connection attempts with headers and paths
- Authentication success/failure
- Connection establishment
- Message sending status
- Error details with stack traces
Environment Variables
AUGMENTOS_AUTH_JWT_SECRET: Secret key for JWT token verification (required)
Best Practices
- Connection State Checks: Always verify WebSocket readyState before sending
- Error Handling: Catch and log all handler errors
- Token Security: Never log full tokens, only first 10 characters
- Request Enhancement: Attach authentication data to request for downstream handlers
Related Services
- GlassesWebSocketService: Handles glasses-specific logic
- AppWebSocketService: Handles app-specific logic
- SessionService: Manages user sessions
- UserSession: Core session object