import hashlib import hmac import json import os import re import secrets import sqlite3 import time from collections import defaultdict, deque from contextlib import asynccontextmanager from datetime import timedelta from pathlib import Path from typing import Optional from argon2 import PasswordHasher from argon2.exceptions import ( InvalidHashError, VerificationError, VerifyMismatchError, ) from dotenv import load_dotenv from fastapi import ( Cookie, FastAPI, Header, HTTPException, ) from fastapi.responses import FileResponse from fastapi.staticfiles import StaticFiles from livekit import api as livekit_api from livekit.api import AccessToken, VideoGrants from pydantic import ( BaseModel, ConfigDict, Field, ) from accounts import ( SESSION_COOKIE, authenticate_account, configure_accounts, get_session_user, initialize_account_database, managed_room_exists, room_record_for_user, router as accounts_router, ) from chat_files import ( chat_files_router, configure_chat_files, delete_room_chat_files, initialize_chat_file_storage, start_chat_file_cleanup, stop_chat_file_cleanup, ) from giphy_api import router as giphy_router from helper_api import ( configure_helper_api, initialize_helper_database, router as helper_router, ) # --------------------------------------------------------- # Environment and configuration # --------------------------------------------------------- load_dotenv() API_KEY = os.getenv( "LIVEKIT_API_KEY", "", ).strip() API_SECRET = os.getenv( "LIVEKIT_API_SECRET", "", ).strip() if not API_KEY or not API_SECRET: raise RuntimeError( "LIVEKIT_API_KEY and LIVEKIT_API_SECRET " "must be set in the .env file." ) def resolve_livekit_api_url() -> str: configured_api_url = os.getenv( "LIVEKIT_API_URL", "", ).strip() if configured_api_url: return configured_api_url.rstrip("/") configured_client_url = os.getenv( "LIVEKIT_URL", "", ).strip() if configured_client_url.startswith( "wss://" ): return ( "https://" + configured_client_url[6:] ).rstrip("/") if configured_client_url.startswith( "ws://" ): return ( "http://" + configured_client_url[5:] ).rstrip("/") raise RuntimeError( "Set LIVEKIT_API_URL to the HTTP(S) URL " "of your LiveKit server, for example " "https://livkt.kronickrusaders.ca." ) LIVEKIT_API_URL = resolve_livekit_api_url() BASE_DIR = Path(__file__).resolve().parent # Account identities, managed rooms, room ACLs, and media permissions MUST # share the media server's authoritative account database. ROOM_DATABASE_PATH # is a legacy setting and deliberately does not select an account database. # If Chat is started without its Media parent, read the parent config.env. from dotenv import dotenv_values _MEDIA_CONFIG = dotenv_values(BASE_DIR.parent / "config.env") _SHARED_ACCOUNT_DB = ( os.getenv("KRONICK_ACCOUNT_DB") or _MEDIA_CONFIG.get("KRONICK_ACCOUNT_DB") or str(BASE_DIR.parent / "kronick_accounts.sqlite3") ) DATABASE_PATH = Path(_SHARED_ACCOUNT_DB).expanduser() if not DATABASE_PATH.is_absolute(): DATABASE_PATH = BASE_DIR.parent / DATABASE_PATH DATABASE_PATH = DATABASE_PATH.resolve() HELPER_MODULES_DIR = Path( os.getenv( "HELPER_MODULES_DIR", str(BASE_DIR / "helper_modules"), ) ).resolve() HELPER_TOKEN_TTL_DAYS = int( os.getenv( "HELPER_TOKEN_TTL_DAYS", "90", ) ) ROOM_NAME_MIN_LENGTH = 3 ROOM_NAME_MAX_LENGTH = 48 USER_NAME_MIN_LENGTH = 1 USER_NAME_MAX_LENGTH = 64 PASSWORD_MIN_LENGTH = 8 PASSWORD_MAX_LENGTH = 128 AVATAR_URL_MAX_LENGTH = 2048 ROOM_COOLDOWN_SECONDS = 24 * 60 * 60 ALLOW_LEGACY_ROOM_AUTH = os.getenv("ALLOW_LEGACY_ROOM_AUTH", "false").strip().lower() in {"1", "true", "yes", "on"} LIVEKIT_TOKEN_TTL_HOURS = int( os.getenv( "LIVEKIT_TOKEN_TTL_HOURS", "6", ) ) OWNER_TOKEN_SECRET = os.getenv( "ROOM_OWNER_TOKEN_SECRET", API_SECRET, ).encode("utf-8") ROOM_NAME_PATTERN = re.compile( r"^[a-z0-9][a-z0-9_-]{2,47}$" ) password_hasher = PasswordHasher() # --------------------------------------------------------- # Temporary chat history # --------------------------------------------------------- # Chat messages still persist only until server.py restarts. # The room/password registry itself persists in SQLite. chat_history = defaultdict( lambda: deque(maxlen=100) ) # --------------------------------------------------------- # Request models # --------------------------------------------------------- class RoomTokenRequest(BaseModel): model_config = ConfigDict( populate_by_name=True ) room: str user: str password: str avatar: str = "" owner_token: str = Field( default="", alias="ownerToken", ) class AccountRoomTokenRequest(BaseModel): room: str avatar: str = "" class ChatMessage(BaseModel): id: str = Field(min_length=1, max_length=128) room: str sender: str = Field(default="", max_length=64) # ignored: identity comes from session text: str = Field(default="", max_length=8000) gifUrl: Optional[str] = None imageUrl: Optional[str] = None createdAt: Optional[int] = None # --------------------------------------------------------- # Validation helpers # --------------------------------------------------------- def normalize_room_name( value: str, ) -> str: room = str( value or "" ).strip().lower() if not ( ROOM_NAME_MIN_LENGTH <= len(room) <= ROOM_NAME_MAX_LENGTH ): raise HTTPException( status_code=400, detail=( "Room names must be between " f"{ROOM_NAME_MIN_LENGTH} and " f"{ROOM_NAME_MAX_LENGTH} characters." ), ) if not ROOM_NAME_PATTERN.fullmatch( room ): raise HTTPException( status_code=400, detail=( "Room names may contain lowercase " "letters, numbers, underscores, and " "hyphens. They must begin with a " "letter or number." ), ) return room def normalize_user_name( value: str, ) -> str: user = str( value or "" ).strip() if not ( USER_NAME_MIN_LENGTH <= len(user) <= USER_NAME_MAX_LENGTH ): raise HTTPException( status_code=400, detail=( "The chat name must be between " f"{USER_NAME_MIN_LENGTH} and " f"{USER_NAME_MAX_LENGTH} characters." ), ) return user def normalize_avatar_url( value: str, ) -> str: avatar = str( value or "" ).strip() if len(avatar) > AVATAR_URL_MAX_LENGTH: raise HTTPException( status_code=400, detail="The avatar URL is too long.", ) return avatar def validate_room_password( password: str, *, creating_room: bool, ) -> str: supplied_password = str( password or "" ) if not supplied_password: raise HTTPException( status_code=400, detail="A room password is required.", ) if len( supplied_password ) > PASSWORD_MAX_LENGTH: raise HTTPException( status_code=400, detail=( "The room password is too long." ), ) if ( creating_room and len(supplied_password) < PASSWORD_MIN_LENGTH ): raise HTTPException( status_code=400, detail=( "New room passwords must contain " f"at least {PASSWORD_MIN_LENGTH} " "characters." ), ) return supplied_password # --------------------------------------------------------- # Owner-token helpers # --------------------------------------------------------- def generate_owner_token() -> str: return secrets.token_urlsafe(48) def hash_owner_token( owner_token: str, ) -> str: return hmac.new( OWNER_TOKEN_SECRET, owner_token.encode("utf-8"), hashlib.sha256, ).hexdigest() def owner_token_matches( supplied_token: str, stored_hash: str, ) -> bool: if ( not supplied_token or not stored_hash ): return False supplied_hash = hash_owner_token( supplied_token ) return hmac.compare_digest( supplied_hash, stored_hash, ) # --------------------------------------------------------- # Password helpers # --------------------------------------------------------- def hash_room_password( password: str, ) -> str: return password_hasher.hash( password ) def verify_room_password( stored_hash: str, supplied_password: str, ) -> bool: try: valid = password_hasher.verify( stored_hash, supplied_password, ) return bool(valid) except ( VerifyMismatchError, VerificationError, InvalidHashError, ): return False # --------------------------------------------------------- # SQLite helpers # --------------------------------------------------------- def open_database() -> sqlite3.Connection: connection = sqlite3.connect( DATABASE_PATH, timeout=15, ) connection.row_factory = ( sqlite3.Row ) connection.execute( "PRAGMA foreign_keys = ON" ) connection.execute( "PRAGMA busy_timeout = 15000" ) return connection def initialize_database() -> None: DATABASE_PATH.parent.mkdir( parents=True, exist_ok=True, ) with open_database() as connection: connection.execute( "PRAGMA journal_mode = WAL" ) connection.execute( """ CREATE TABLE IF NOT EXISTS rooms ( room_name TEXT PRIMARY KEY COLLATE NOCASE, password_hash TEXT NOT NULL, owner_token_hash TEXT NOT NULL, created_at INTEGER NOT NULL, last_used_at INTEGER NOT NULL ) """ ) connection.execute( """ CREATE TABLE IF NOT EXISTS room_cooldowns ( room_name TEXT PRIMARY KEY COLLATE NOCASE, deleted_at INTEGER NOT NULL, expires_at INTEGER NOT NULL ) """ ) connection.execute( """ CREATE INDEX IF NOT EXISTS idx_room_cooldowns_expires_at ON room_cooldowns ( expires_at ) """ ) connection.commit() def remove_expired_cooldowns( connection: sqlite3.Connection, now: Optional[int] = None, ) -> None: current_time = ( int(time.time()) if now is None else now ) connection.execute( """ DELETE FROM room_cooldowns WHERE expires_at <= ? """, ( current_time, ), ) def get_room_record( connection: sqlite3.Connection, room_name: str, ) -> Optional[sqlite3.Row]: return connection.execute( """ SELECT room_name, password_hash, owner_token_hash, created_at, last_used_at FROM rooms WHERE room_name = ? """, ( room_name, ), ).fetchone() def get_cooldown_record( connection: sqlite3.Connection, room_name: str, ) -> Optional[sqlite3.Row]: return connection.execute( """ SELECT room_name, deleted_at, expires_at FROM room_cooldowns WHERE room_name = ? """, ( room_name, ), ).fetchone() def room_exists( room_name: str, ) -> bool: """ Return True only when the room exists in the persistent room registry. chat_files.py uses this before accepting uploads. """ normalized_room = normalize_room_name( room_name ) if managed_room_exists(normalized_room): return True with open_database() as connection: room_record = get_room_record( connection, normalized_room, ) return room_record is not None # --------------------------------------------------------- # LiveKit token and room helpers # --------------------------------------------------------- def create_livekit_token( *, room_name: str, user_name: str, avatar_url: str, is_owner: bool, ) -> str: metadata = json.dumps( { "avatar": avatar_url, "roomOwner": is_owner, } ) token = ( AccessToken( API_KEY, API_SECRET, ) .with_identity( user_name ) .with_name( user_name ) .with_metadata( metadata ) .with_ttl( timedelta( hours=LIVEKIT_TOKEN_TTL_HOURS ) ) .with_grants( VideoGrants( room_join=True, room=room_name, can_publish=True, can_subscribe=True, can_publish_data=True, can_update_own_metadata=True, ) ) ) return token.to_jwt() async def delete_livekit_room( room_name: str, ) -> tuple[bool, Optional[str]]: """ Delete the active LiveKit room. A room that is not currently active is already effectively deleted, so NOT_FOUND is treated as success. """ try: async with livekit_api.LiveKitAPI( url=LIVEKIT_API_URL, api_key=API_KEY, api_secret=API_SECRET, ) as livekit: await livekit.room.delete_room( livekit_api.DeleteRoomRequest( room=room_name ) ) return True, None except livekit_api.TwirpError as error: if ( getattr( error, "code", None, ) == livekit_api .TwirpErrorCode .NOT_FOUND ): return True, None return ( False, str(error), ) except Exception as error: return ( False, str(error), ) # --------------------------------------------------------- # Application lifecycle # --------------------------------------------------------- @asynccontextmanager async def application_lifespan( application: FastAPI, ): initialize_database() configure_accounts(DATABASE_PATH) initialize_account_database() configure_helper_api( database_path=DATABASE_PATH, modules_dir=HELPER_MODULES_DIR, token_ttl_days=HELPER_TOKEN_TTL_DAYS, authenticate_account=authenticate_account, ) initialize_helper_database() configure_chat_files( database_path= DATABASE_PATH, chat_history= chat_history, normalize_room_name= normalize_room_name, normalize_user_name= normalize_user_name, room_exists= room_exists, ) initialize_chat_file_storage() cleanup_task = ( start_chat_file_cleanup() ) try: yield finally: await stop_chat_file_cleanup( cleanup_task ) app = FastAPI( lifespan=application_lifespan ) app.include_router( chat_files_router ) app.include_router( accounts_router ) app.include_router( helper_router ) app.include_router( giphy_router ) # --------------------------------------------------------- # Static frontend files # --------------------------------------------------------- # Do not mount "." as a public static directory. # Doing so could expose the .env file or SQLite database. app.mount( "/js", StaticFiles( directory=BASE_DIR / "js" ), name="js", ) app.mount( "/css", StaticFiles( directory=BASE_DIR / "css" ), name="css", ) # Serve rnnoise-wasm static assets safely without exposing sensitive root files RNNOISE_DIR = BASE_DIR / "rnnoise-wasm" if RNNOISE_DIR.is_dir(): app.mount( "/rnnoise-wasm", StaticFiles( directory=RNNOISE_DIR ), name="rnnoise-wasm", ) # --------------------------------------------------------- # Room status # --------------------------------------------------------- @app.get( "/api/rooms/{room}/status" ) async def get_room_status( room: str, ): room_name = normalize_room_name( room ) now = int( time.time() ) with open_database() as connection: remove_expired_cooldowns( connection, now, ) room_record = get_room_record( connection, room_name, ) cooldown_record = ( get_cooldown_record( connection, room_name, ) ) connection.commit() if room_record: return { "room": room_name, "exists": True, "available": False, "requiresPassword": True, "cooldown": False, "cooldownUntil": None, "cooldownSecondsRemaining": 0, } if cooldown_record: seconds_remaining = max( 0, int( cooldown_record[ "expires_at" ] ) - now, ) return { "room": room_name, "exists": False, "available": False, "requiresPassword": False, "cooldown": True, "cooldownUntil": cooldown_record[ "expires_at" ], "cooldownSecondsRemaining": seconds_remaining, } return { "room": room_name, "exists": False, "available": True, "requiresPassword": False, "cooldown": False, "cooldownUntil": None, "cooldownSecondsRemaining": 0, } # --------------------------------------------------------- # Approved-account LiveKit token # --------------------------------------------------------- @app.post("/api/account-token") async def get_account_token( request: AccountRoomTokenRequest, kronick_session: Optional[str] = Cookie(default=None), ): user = get_session_user(kronick_session) room_name = normalize_room_name(request.room) avatar_url = normalize_avatar_url(request.avatar) room_record = room_record_for_user(user["id"], room_name) if room_record is None: raise HTTPException( status_code=403, detail="You are not assigned to this room's group.", ) now = int(time.time()) expires_at = room_record["expires_at"] if room_record["group_status"] != "active": raise HTTPException(status_code=403, detail="This group is not active.") if room_record["subscription_status"] not in {"active", "trial", "free"}: raise HTTPException(status_code=403, detail="This group's service is not active.") if expires_at is not None and int(expires_at) <= now: raise HTTPException(status_code=403, detail="This group's access has expired.") permissions = { "owner": ["join_room", "manage_members", "create_room", "delete_room", "manage_media", "manage_group"], "admin": ["join_room", "manage_members", "create_room", "delete_room", "manage_media"], "moderator": ["join_room", "manage_media"], "member": ["join_room"], }.get(room_record["role"], ["join_room"]) token = create_livekit_token( room_name=room_name, user_name=user["username"], avatar_url=avatar_url, is_owner=room_record["role"] == "owner", ) return { "token": token, "room": room_name, "created": False, "isOwner": room_record["role"] == "owner", "role": room_record["role"], "group": room_record["group_name"], "permissions": permissions, "mediaEnabled": bool(room_record["media_enabled"]), } # --------------------------------------------------------- # Create or join a room # --------------------------------------------------------- @app.post("/get-token") async def get_token( request: RoomTokenRequest, ): if not ALLOW_LEGACY_ROOM_AUTH: raise HTTPException( status_code=410, detail="Legacy room-password login is disabled. Sign in with an approved account.", ) room_name = normalize_room_name( request.room ) user_name = normalize_user_name( request.user ) avatar_url = normalize_avatar_url( request.avatar ) supplied_owner_token = str( request.owner_token or "" ).strip() now = int( time.time() ) # ----------------------------------------------------- # Determine whether this is a join or room creation. # ----------------------------------------------------- with open_database() as connection: remove_expired_cooldowns( connection, now, ) room_record = get_room_record( connection, room_name, ) cooldown_record = ( get_cooldown_record( connection, room_name, ) ) connection.commit() # ----------------------------------------------------- # Existing room: verify the established password. # ----------------------------------------------------- if room_record: supplied_password = ( validate_room_password( request.password, creating_room=False, ) ) if not verify_room_password( room_record["password_hash"], supplied_password, ): raise HTTPException( status_code=403, detail=( "Incorrect room password." ), ) is_owner = owner_token_matches( supplied_owner_token, room_record[ "owner_token_hash" ], ) with open_database() as connection: connection.execute( """ UPDATE rooms SET last_used_at = ? WHERE room_name = ? """, ( now, room_name, ), ) connection.commit() token = create_livekit_token( room_name=room_name, user_name=user_name, avatar_url=avatar_url, is_owner=is_owner, ) return { "token": token, "room": room_name, "created": False, "isOwner": is_owner, "ownerToken": None, } # ----------------------------------------------------- # Deleted room still inside the 24-hour cooldown. # ----------------------------------------------------- if cooldown_record: seconds_remaining = max( 0, int( cooldown_record[ "expires_at" ] ) - now, ) raise HTTPException( status_code=423, detail={ "message": ( "This room name is temporarily " "reserved after deletion." ), "room": room_name, "cooldownUntil": cooldown_record[ "expires_at" ], "cooldownSecondsRemaining": seconds_remaining, }, ) # ----------------------------------------------------- # New room: establish password and creator ownership. # ----------------------------------------------------- supplied_password = ( validate_room_password( request.password, creating_room=True, ) ) password_hash = hash_room_password( supplied_password ) owner_token = generate_owner_token() owner_token_hash = hash_owner_token( owner_token ) try: with open_database() as connection: connection.execute( "BEGIN IMMEDIATE" ) remove_expired_cooldowns( connection, now, ) concurrent_room = ( get_room_record( connection, room_name, ) ) concurrent_cooldown = ( get_cooldown_record( connection, room_name, ) ) if concurrent_room: connection.rollback() raise HTTPException( status_code=409, detail=( "The room was created by " "another user. Try joining it." ), ) if concurrent_cooldown: connection.rollback() seconds_remaining = max( 0, int( concurrent_cooldown[ "expires_at" ] ) - now, ) raise HTTPException( status_code=423, detail={ "message": ( "This room name is " "temporarily reserved " "after deletion." ), "room": room_name, "cooldownUntil": concurrent_cooldown[ "expires_at" ], "cooldownSecondsRemaining": seconds_remaining, }, ) connection.execute( """ INSERT INTO rooms ( room_name, password_hash, owner_token_hash, created_at, last_used_at ) VALUES (?, ?, ?, ?, ?) """, ( room_name, password_hash, owner_token_hash, now, now, ), ) connection.commit() except sqlite3.IntegrityError: raise HTTPException( status_code=409, detail=( "The room was created by another " "user. Try joining it." ), ) token = create_livekit_token( room_name=room_name, user_name=user_name, avatar_url=avatar_url, is_owner=True, ) return { "token": token, "room": room_name, "created": True, "isOwner": True, # This is returned only once when the room is # created. The frontend must save it securely # enough for the intended friends/family use. "ownerToken": owner_token, } # --------------------------------------------------------- # Delete a room # --------------------------------------------------------- @app.delete( "/api/rooms/{room}" ) async def delete_room( room: str, authorization: Optional[str] = Header( default=None ), ): room_name = normalize_room_name( room ) if not authorization: raise HTTPException( status_code=401, detail=( "The room owner token is required." ), headers={ "WWW-Authenticate": "Bearer" }, ) auth_scheme, separator, auth_token = ( authorization.partition(" ") ) if ( separator != " " or auth_scheme.lower() != "bearer" or not auth_token.strip() ): raise HTTPException( status_code=401, detail=( "Use Authorization: Bearer " "." ), headers={ "WWW-Authenticate": "Bearer" }, ) supplied_owner_token = ( auth_token.strip() ) now = int( time.time() ) cooldown_until = ( now + ROOM_COOLDOWN_SECONDS ) with open_database() as connection: connection.execute( "BEGIN IMMEDIATE" ) room_record = get_room_record( connection, room_name, ) if not room_record: connection.rollback() raise HTTPException( status_code=404, detail="Room not found.", ) if not owner_token_matches( supplied_owner_token, room_record[ "owner_token_hash" ], ): connection.rollback() raise HTTPException( status_code=403, detail=( "Only the room creator may " "delete this room." ), ) connection.execute( """ DELETE FROM rooms WHERE room_name = ? """, ( room_name, ), ) connection.execute( """ INSERT INTO room_cooldowns ( room_name, deleted_at, expires_at ) VALUES (?, ?, ?) ON CONFLICT(room_name) DO UPDATE SET deleted_at = excluded.deleted_at, expires_at = excluded.expires_at """, ( room_name, now, cooldown_until, ), ) connection.commit() # Remove temporary server-side chat history. chat_history.pop( room_name, None, ) # Remove all uploaded files and file metadata # associated with the deleted room. deleted_file_count = ( delete_room_chat_files( room_name ) ) livekit_deleted, livekit_error = ( await delete_livekit_room( room_name ) ) response = { "ok": True, "deleted": True, "room": room_name, "cooldownUntil": cooldown_until, "cooldownSeconds": ROOM_COOLDOWN_SECONDS, "livekitRoomDeleted": livekit_deleted, "deletedFiles": deleted_file_count, } if livekit_error: response["warning"] = ( "The room registry was deleted and " "new joins are blocked, but the active " "LiveKit room could not be terminated: " + livekit_error ) return response # --------------------------------------------------------- # Chat history # --------------------------------------------------------- @app.get( "/api/chat/history/{room}" ) async def get_chat_history( room: str, kronick_session: Optional[str] = Cookie(default=None), ): user = get_session_user(kronick_session) room_name = normalize_room_name(room) if room_record_for_user(int(user["id"]), room_name) is None: raise HTTPException(status_code=403, detail="Room access denied.") return { "room": room_name, "messages": list(chat_history.get(room_name, ())), } @app.post( "/api/chat/message" ) async def save_chat_message( message: ChatMessage, kronick_session: Optional[str] = Cookie(default=None), ): user = get_session_user(kronick_session) room_name = normalize_room_name(message.room) if room_record_for_user(int(user["id"]), room_name) is None: raise HTTPException(status_code=403, detail="Room access denied.") data = message.model_dump() data["room"] = room_name data["sender"] = str(user["username"]) if not data.get( "createdAt" ): data["createdAt"] = int( time.time() * 1000 ) existing_ids = { stored_message.get("id") for stored_message in chat_history[ room_name ] } if ( data["id"] not in existing_ids ): chat_history[ room_name ].append( data ) return { "ok": True, "room": room_name, "stored": len( chat_history[ room_name ] ), } # --------------------------------------------------------- # Frontend pages # --------------------------------------------------------- @app.get("/") async def serve_login_root(): return FileResponse(BASE_DIR / "login.html") @app.get("/login") async def serve_login(): return FileResponse(BASE_DIR / "login.html") @app.get("/app") async def serve_index(): return FileResponse(BASE_DIR / "index.html") @app.get("/admin") async def serve_admin(): return FileResponse(BASE_DIR / "admin.html") @app.get("/music-browser.html") async def serve_music_browser(): return FileResponse( BASE_DIR / "music-browser.html" ) @app.get("/giphy.html") async def serve_giphy(): return FileResponse( BASE_DIR / "giphy.html" ) @app.get("/chat.html") async def serve_chat(): return FileResponse( BASE_DIR / "chat.html" ) @app.get("/kkicon.png") async def serve_kk_icon(): return FileResponse(BASE_DIR / "kkicon.png") # @app.get("/kklogob.png") # async def serve_kk_logo(): # return FileResponse(BASE_DIR / "kklogob.png")