Skip to content

Feat/room dos protection 198 - #215

Open
queentiffany1111-cloud wants to merge 2 commits into
RiftCore00:devfrom
queentiffany1111-cloud:feat/room-dos-protection-198
Open

Feat/room dos protection 198#215
queentiffany1111-cloud wants to merge 2 commits into
RiftCore00:devfrom
queentiffany1111-cloud:feat/room-dos-protection-198

Conversation

@queentiffany1111-cloud

Copy link
Copy Markdown

Title

feat(room-manager): implement room membership DoS protection & circuit breaker (#198)                                                              
                                                                                                                                                   
## Summary & Context                                                                                                                               
In `RoomManager.join()`, room membership previously allowed unlimited joins per client and unlimited members per room. This exposed the gateway to 

resource exhaustion attacks:
- A single misbehaving client could join 100,000 distinct room IDs, accumulating ~10MB+ of pure internal Map/Set overhead.
- A single room could accumulate 50,000+ clients, causing broadcast() calls to block the V8 event loop for ~50ms per broadcast.

This PR implements multi-layered resource accounting, configurable room/client capacity caps, total room ceilings, a memory-pressure circuit       

breaker, and real-time metrics exposure for RoomManager.

---                                                                                                                                                
                                                                                                                                                   
## Key Changes Implemented                                                                                                                         
                                                                                                                                                   
### 1. Configurable Capacity Limits & Sane Defaults                                                                                                
`RoomManager` constructor options now accept:                                                                                                      
- `maxRoomsPerClient` (default: `50`): Maximum active rooms a single client ID can join.                                                           
- `maxMembersPerRoom` (default: `10000`): Maximum clients allowed in a single room.                                                                
- `maxRooms` (default: `10000`): Maximum total active room ceiling across the gateway.                                                             
                                                                                                                                                   
### 2. Resource-Pressure Circuit Breaker                                                                                                           
- Evaluates `process.memoryUsage().heapUsed` on `join()` calls with negligible overhead (~1μs).                                                    
- **OPEN State**: When memory exceeds `memoryThresholdBytes` (default: 512MB), the breaker opens and rejects all `join()` calls with `{ type:      

"error", payload: { code: "CIRCUIT_BREAKER_OPEN", message: "..." } }. - **CLOSED State**: Automatically closes when memory drops below recoveryThresholdBytes` (default: 384MB or 75% of threshold).

### 3. Structured Error Protocol                                                                                                                   
Limit violations do not crash or alter signature assumptions, returning structured JSON error objects:                                             
- `ROOM_LIMIT_EXCEEDED` — Client reached max room limit.                                                                                           
- `ROOM_FULL` — Room reached max capacity limit.                                                                                                   
- `MAX_ROOMS_REACHED` — Global room ceiling reached for new room creation.                                                                         
- `CIRCUIT_BREAKER_OPEN` — Memory-pressure circuit breaker open.                                                                                   
                                                                                                                                                   
*Note*: Missing required parameters (`clientId`, `roomId`, `ws`) continue to throw standard `TypeError` exceptions.                                
                                                                                                                                                   
### 4. Edge-Case Resilience & Atomic Enforcement                                                                                                   
- Existing room joins and socket object updates (`ws` reference refresh for a client already in a room) remain allowed even when capacity limits or

total room ceilings are hit.
- Enforced synchronously without yielding execution to avoid TOCTOU (Time-of-Check to Time-of-Use) race conditions.
- Disconnection cleanup and room departure (leave(), disconnect()) bypass limit checks to guarantee clients can always unsubscribe or
disconnect cleanly.

### 5. Metrics & Stats Exposure
- Added `stats` getter returning:
  ```json
  {
    "roomCount": 0,
    "clientCount": 0,
    "totalMembers": 0,
    "circuitBreakerState": "CLOSED"
  }

• totalMembers is tracked in O(1) time on join, leave, and disconnect operations.
──────

Test Coverage

• Added tests/room-manager-dos.test.js covering:
• Limits enforcement (maxRoomsPerClient, maxMembersPerRoom, maxRooms).
• Re-joining an existing room while at maximum capacity limits.
• Circuit breaker state transitions (CLOSED ➔ OPEN ➔ CLOSED).
• Hysteresis behavior between recovery and memory thresholds.
• Metrics tracking (roomCount, clientCount, totalMembers, circuitBreakerState).
• All 23 test suites (187 unit tests) pass cleanly.
• npm run lint passes with zero ESLint errors or warnings.
──────

Verification Commands

npm test
npm run lint

closes #198

…refresh (RiftCore00#197)

- Validate iss and aud claims against AUTH_ISSUER/AUTH_AUDIENCE env vars
- Add clock-skew tolerance (±30s, configurable via AUTH_CLOCK_SKEW_MS)
- Add JWKS endpoint support (http+https) with TTL caching and RSA/EC key support
- Explicitly reject alg:none tokens before jwt.verify
- Pre-validate iss claim to ensure correct error ordering over aud check
- Restrict allowed algorithms to HS256, RS256, ES256
- Add token_refresh message handler in server.js; updates client identity on success
- Make wss connection callback async to support await verifyConnection
- Add auth-hardening.test.js and refresh.test.js test suites
- All 173 tests pass, lint clean
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

1 participant