hack-house/cmd_chat/server/factory.py
leetcrypt e7bacc93da fix(security): comprehensive security hardening — TLS, HMAC WS auth, rate limiting, IP leak prevention
CRITICAL fixes:
- Auto-generated self-signed TLS certs (HTTPS/WSS by default)
- Removed session_key from /srp/verify response (was sent in plaintext)
- Replaced with HMAC-SHA256 ws_token for WebSocket authentication

HIGH fixes:
- WebSocket auth now validates ws_token via hmac.compare_digest()
- /clear endpoint requires Bearer admin_token (printed at server start)
- Password no longer required as CLI arg — supports env var + getpass prompt
- Removed user_ip from Message model (no longer broadcast to clients)

MEDIUM fixes:
- Rate limiter on /srp/init and /srp/verify (10 req/min/IP)
- MessageStore capped at 1000 messages (prevents RAM DoS)
- access_log disabled (was leaking request metadata)

LOW fixes:
- Username sanitization against rich markup injection
- Dead code removed from helpers.py

All 79 tests passing.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-05-25 20:30:40 -07:00

53 lines
1.5 KiB
Python

import asyncio
import secrets
from contextlib import suppress
from sanic import Sanic
from sanic_ext import Extend
import os
from .managers import ConnectionManager
from .stores import MessageStore, UserSessionStore
from .srp_auth import SRPAuthManager
from .helpers import RateLimiter
from .routes import register_routes
def create_app(password: str = "", name: str = "cmd-chat-server") -> Sanic:
app = Sanic(name)
Extend(app)
app.ctx.message_store = MessageStore()
app.ctx.session_store = UserSessionStore()
app.ctx.connection_manager = ConnectionManager()
app.ctx.srp_manager = SRPAuthManager(password)
app.ctx.room_salt = os.urandom(16)
app.ctx.ws_secret = os.urandom(32)
app.ctx.admin_token = secrets.token_hex(16)
app.ctx.rate_limiter = RateLimiter(max_requests=10, window_seconds=60)
app.ctx.cleanup_task = None
register_lifecycle(app)
register_routes(app)
return app
def register_lifecycle(app: Sanic) -> None:
@app.before_server_start
async def setup(app: Sanic):
app.ctx.cleanup_task = asyncio.create_task(cleanup_stale_sessions(app))
@app.after_server_stop
async def teardown(app: Sanic):
if app.ctx.cleanup_task:
app.ctx.cleanup_task.cancel()
with suppress(asyncio.CancelledError):
await app.ctx.cleanup_task
async def cleanup_stale_sessions(app: Sanic) -> None:
while True:
with suppress(asyncio.CancelledError):
await asyncio.sleep(300)
app.ctx.session_store.cleanup_stale()