Spaces:
Running
Running
Update app.py
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748493 unmodified lines5354555657585960616 unmodified lines68697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381392 unmodified lines142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588# app.pyimport osimport jsonimport timeimport uuidimport base64from typing import Optional, Dict, Setimport asyncioimport aiosqliteimport tempfileimport ioimport loggingfrom contextlib import asynccontextmanagerfrom fastapi import FastAPI, HTTPException, WebSocket, WebSocketDisconnect, Header, Query, Request, UploadFile, Filefrom fastapi.staticfiles import StaticFilesfrom fastapi.responses import Response, JSONResponse, FileResponsefrom cryptography.hazmat.primitives.ciphers.aead import AESGCMfrom cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMACfrom cryptography.hazmat.primitives import hashesfrom cryptography.hazmat.backends import default_backendfrom storage_handler import store_file, retrieve_file, delete_file, store_file_stream# --------------------------- Configuration ---------------------------DATABASE_URL = os.environ.get("DATABASE_URL", "/data/infinitychat.db")MESSAGE_KEY_B64 = os.environ.get("SECRET_KEY", None)if MESSAGE_KEY_B64 is None:# Auto-generate (set permanently in production!)MESSAGE_KEY_B64 = base64.urlsafe_b64encode(os.urandom(32)).decode()print("WARNING: SECRET_KEY not set – generated random key.")MESSAGE_KEY = base64.urlsafe_b64decode(MESSAGE_KEY_B64)assert len(MESSAGE_KEY) == 32logging.basicConfig(level=logging.INFO)logger = logging.getLogger("InfinityChat")# --------------------------- Database initialization ---------------------------async def init_database():"""Initialize the SQLite database with proper async context."""async with aiosqlite.connect(DATABASE_URL) as db:db.row_factory = aiosqlite.Rowawait db.execute("PRAGMA journal_mode=WAL;")await db.execute("PRAGMA foreign_keys=ON;")await db.execute("""CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY AUTOINCREMENT,3 unmodified linessalt TEXT NOT NULL,avatar_path TEXT,token TEXT UNIQUE,created_at INTEGER DEFAULT (strftime('%s','now')))""")await db.execute("""CREATE TABLE IF NOT EXISTS messages (id INTEGER PRIMARY KEY AUTOINCREMENT,6 unmodified linesfile_path TEXT,file_type TEXT,file_name TEXT,FOREIGN KEY(sender_id) REFERENCES users(id))""")await db.execute("""CREATE TABLE IF NOT EXISTS read_receipts (user_id INTEGER NOT NULL,message_id INTEGER NOT NULL,PRIMARY KEY (user_id, message_id))""")await db.execute("CREATE INDEX IF NOT EXISTS idx_msg_time ON messages(timestamp_ms)")await db.commit()logger.info("✅ Database initialized successfully")# --------------------------- Lifespan handler (proper async startup) ---------------------------@asynccontextmanagerasync def lifespan(app: FastAPI):"""Handle startup and shutdown events properly."""# Startupawait init_database()yield# Shutdown# Cleanup if needed# --------------------------- FastAPI app with lifespan ---------------------------app = FastAPI(title="InfinityChat", lifespan=lifespan)app.mount("/static", StaticFiles(directory="static"), name="static")# --------------------------- Database helpers ---------------------------async def get_db():"""Get a database connection with proper async context."""db = await aiosqlite.connect(DATABASE_URL)db.row_factory = aiosqlite.Rowawait db.execute("PRAGMA journal_mode=WAL")await db.execute("PRAGMA foreign_keys=ON")return db# --------------------------- Encryption helpers ---------------------------def encrypt_message(plain: str) -> str:"""Encrypt message content with AES-256-GCM."""aesgcm = AESGCM(MESSAGE_KEY)nonce = os.urandom(12)ct = aesgcm.encrypt(nonce, plain.encode(), None)return base64.urlsafe_b64encode(nonce + ct).decode()def decrypt_message(encrypted_b64: str) -> str:"""Decrypt message content."""raw = base64.urlsafe_b64decode(encrypted_b64)nonce, ct = raw[:12], raw[12:]aesgcm = AESGCM(MESSAGE_KEY)return aesgcm.decrypt(nonce, ct, None).decode()# --------------------------- Password handling ---------------------------def hash_password(password: str, salt: Optional[str] = None) -> tuple[str, str]:"""Hash password with PBKDF2."""if salt is None:salt = os.urandom(16).hex()kdf = PBKDF2HMAC(algorithm=hashes.SHA256(),length=32,salt=salt.encode(),iterations=600000,backend=default_backend())return base64.urlsafe_b64encode(kdf.derive(password.encode())).decode(), saltdef verify_password(password: str, salt: str, stored_hash: str) -> bool:"""Verify password against stored hash."""2 unmodified linesdef generate_token() -> str:"""Generate a secure random token."""return base64.urlsafe_b64encode(os.urandom(32)).decode()# --------------------------- User lookup ---------------------------async def get_user_by_token(token: str):"""Get user by token with proper async context."""db = await get_db()try:async with db.execute("SELECT * FROM users WHERE token = ?", (token,)) as cur:return await cur.fetchone()finally:await db.close()async def get_user_by_username(username: str):"""Get user by username."""db = await get_db()try:async with db.execute("SELECT * FROM users WHERE username = ?", (username,)) as cur:return await cur.fetchone()finally:await db.close()# --------------------------- HTTP endpoints ---------------------------@app.post("/signup")async def signup(username: str, password: str, display_name: str = ""):"""Create a new user account."""db = await get_db()try:existing = await get_user_by_username(username)if existing:raise HTTPException(400, "Username already taken")pwd_hash, salt = hash_password(password)token = generate_token()await db.execute("INSERT INTO users (username, display_name, password_hash, salt, token) VALUES (?, ?, ?, ?, ?)",(username, display_name, pwd_hash, salt, token))await db.commit()return {"token": token, "username": username, "display_name": display_name}finally:await db.close()@app.post("/login")async def login(username: str, password: str):"""Authenticate user and return token."""db = await get_db()try:user = await get_user_by_username(username)if not user or not verify_password(password, user["salt"], user["password_hash"]):raise HTTPException(400, "Invalid credentials")token = generate_token()await db.execute("UPDATE users SET token = ? WHERE id = ?", (token, user["id"]))await db.commit()return {"token": token,"username": user["username"],"display_name": user["display_name"],"avatar_path": user["avatar_path"]}finally:await db.close()@app.get("/me")async def me(token: str = Header(...)):"""Get current user info."""user = await get_user_by_token(token)if not user:raise HTTPException(401, "Invalid token")return {"id": user["id"],"username": user["username"],"display_name": user["display_name"],"avatar_path": user["avatar_path"]}@app.post("/update_profile")async def update_profile(display_name: str = None, token: str = Header(...)):"""Update user profile."""user = await get_user_by_token(token)if not user:raise HTTPException(401)if display_name is not None:db = await get_db()try:await db.execute("UPDATE users SET display_name = ? WHERE id = ?", (display_name, user["id"]))await db.commit()finally:await db.close()return {"status": "ok"}@app.post("/upload_avatar")async def upload_avatar(file: UploadFile = File(...), token: str = Header(...)):"""Upload user avatar."""user = await get_user_by_token(token)if not user:raise HTTPException(401)data = await file.read()ext = os.path.splitext(file.filename)[1] if file.filename else ".jpg"remote_path = f"avatars/{user['username']}_{uuid.uuid4().hex}{ext}"store_file(remote_path, data)db = await get_db()try:await db.execute("UPDATE users SET avatar_path = ? WHERE id = ?", (remote_path, user["id"]))await db.commit()finally:await db.close()return {"avatar_path": remote_path}# --------------------------- Chunked upload ---------------------------upload_sessions: Dict[str, dict] = {}@app.post("/upload_chunk")async def upload_chunk(file: UploadFile = File(...),chunk_index: int = Query(...),total_chunks: int = Query(...),file_name: str = Query(...),file_type: str = Query(...),upload_id: str = Query(...),token: str = Header(...)):"""Handle chunked file upload."""user = await get_user_by_token(token)if not user:raise HTTPException(401)if upload_id not in upload_sessions:upload_sessions[upload_id] = {"chunks": {},"filename": file_name,"file_type": file_type,"total_chunks": total_chunks,"user_id": user["id"],"received": 0}ses = upload_sessions[upload_id]if chunk_index in ses["chunks"]:return {"status": "duplicate"}ses["chunks"][chunk_index] = await file.read()ses["received"] += 1if ses["received"] == ses["total_chunks"]:# All chunks received, reassemblefull_data = b"".join(ses["chunks"][i] for i in sorted(ses["chunks"]))remote_path = f"uploads/{user['username']}_{uuid.uuid4().hex}/{file_name}"try:store_file(remote_path, full_data)except Exception as e:logger.error(f"Failed to store file: {e}")del upload_sessions[upload_id]raise HTTPException(500, "Storage error")del upload_sessions[upload_id]return {"status": "complete","file_path": remote_path,"file_name": file_name,"file_type": file_type}return {"status": "chunk_ok", "received": ses["received"], "total": ses["total_chunks"]}# --------------------------- File download ---------------------------@app.get("/download/{file_path:path}")async def download(file_path: str, token: str = Header(...)):"""Download a file (authenticated proxy)."""user = await get_user_by_token(token)if not user:raise HTTPException(401)try:data = retrieve_file(file_path)except Exception as e:raise HTTPException(404, "File not found or decryption failed")import mimetypesmedia_type = mimetypes.guess_type(file_path)[0] or "application/octet-stream"return Response(content=data, media_type=media_type)@app.get("/")async def root():"""Serve the main page."""return FileResponse("static/index.html")# --------------------------- WebSocket Manager ---------------------------class ConnectionManager:def __init__(self):self.active: Dict[str, Set[WebSocket]] = {}async def connect(self, ws: WebSocket, username: str):await ws.accept()self.active.setdefault(username, set()).add(ws)def disconnect(self, ws: WebSocket, username: str):if username in self.active:self.active[username].discard(ws)if not self.active[username]:del self.active[username]async def broadcast(self, msg: dict, exclude: WebSocket = None):for uname, ws_set in self.active.items():for w in list(ws_set):if w == exclude:continuetry:await w.send_json(msg)except Exception:self.disconnect(w, uname)def online_users(self) -> list:return list(self.active.keys())manager = ConnectionManager()# --------------------------- WebSocket endpoint ---------------------------@app.websocket("/ws")async def ws_endpoint(ws: WebSocket, token: str = Query(...)):"""WebSocket endpoint for real-time communication."""if not token:await ws.close(code=4001)returnuser = await get_user_by_token(token)if not user:await ws.close(code=4001, reason="Invalid token")returnusername = user["username"]uid = user["id"]await manager.connect(ws, username)# Send online usersonline = manager.online_users()await ws.send_json({"type": "online_users", "users": online})await manager.broadcast({"type": "user_online", "username": username}, exclude=ws)try:while True:data = await ws.receive_json()mtype = data.get("type")if mtype == "chat_message":# Handle new messagecontent = data.get("content", "")reply_to = data.get("reply_to_id")client_id = data.get("client_id")file_path = data.get("file_path")file_type = data.get("file_type")file_name = data.get("file_name")ts = int(time.time() * 1000)encrypted = encrypt_message(content)db = await get_db()try:cur = await db.execute("""INSERT INTO messages (sender_id, encrypted_content, timestamp_ms, reply_to_id, file_path, file_type, file_name)VALUES (?, ?, ?, ?, ?, ?, ?)""",(uid, encrypted, ts, reply_to, file_path, file_type, file_name))mid = cur.lastrowidawait db.commit()finally:await db.close()msg_out = {"type": "new_message","id": mid,"sender_id": uid,"username": username,"display_name": user["display_name"],"avatar_path": user["avatar_path"],"content": content,"timestamp_ms": ts,"reply_to_id": reply_to,"file_path": file_path,"file_type": file_type,"file_name": file_name,"is_edited": False,"is_deleted": False,"client_id": client_id,"status": "sent"}# Send confirmation to senderawait ws.send_json({**msg_out, "status": "delivered"})# Broadcast to othersawait manager.broadcast(msg_out, exclude=ws)elif mtype == "load_messages":# Handle message loading with cursor-based paginationbefore_id = data.get("before_id")limit = min(data.get("limit", 50), 100)db = await get_db()try:q = "SELECT * FROM messages WHERE is_deleted = 0"params = []if before_id is not None:q += " AND id < ?"params.append(before_id)q += " ORDER BY id DESC LIMIT ?"params.append(limit)rows = await (await db.execute(q, tuple(params))).fetchall()rows = list(reversed(rows))msgs = []for row in rows:try:plain = decrypt_message(row["encrypted_content"])except Exception:plain = "[decryption error]"s = await db.execute("SELECT id, username, display_name, avatar_path FROM users WHERE id = ?",(row["sender_id"],))s = await s.fetchone()msgs.append({"id": row["id"],"sender_id": row["sender_id"],"username": s["username"] if s else "unknown","display_name": s["display_name"] if s else "","avatar_path": s["avatar_path"] if s else "","content": plain,"timestamp_ms": row["timestamp_ms"],"reply_to_id": row["reply_to_id"],"file_path": row["file_path"],"file_type": row["file_type"],"file_name": row["file_name"],"is_edited": bool(row["is_edited"]),"is_deleted": bool(row["is_deleted"])})await ws.send_json({"type": "messages_batch", "messages": msgs, "before_id": before_id})finally:await db.close()elif mtype == "edit_message":# Handle message editmid, new_text = data.get("message_id"), data.get("content")db = await get_db()try:row = await db.execute("SELECT * FROM messages WHERE id = ? AND sender_id = ? AND is_deleted = 0",(mid, uid))if await row.fetchone():new_enc = encrypt_message(new_text)await db.execute("UPDATE messages SET encrypted_content = ?, is_edited = 1 WHERE id = ?",(new_enc, mid))await db.commit()await manager.broadcast({"type": "edit_message", "message_id": mid, "content": new_text})finally:await db.close()elif mtype == "delete_message":# Handle permanent message deletionmid = data.get("message_id")db = await get_db()try:row = await db.execute("SELECT * FROM messages WHERE id = ? AND sender_id = ?", (mid, uid))msg = await row.fetchone()if msg:if msg["file_path"]:try:delete_file(msg["file_path"])except Exception:passawait db.execute("DELETE FROM messages WHERE id = ?", (mid,))await db.execute("DELETE FROM read_receipts WHERE message_id = ?", (mid,))await db.commit()await manager.broadcast({"type": "delete_message", "message_id": mid})finally:await db.close()elif mtype == "typing":# Handle typing indicatorawait manager.broadcast({"type": "typing_update", "username": username, "is_typing": data.get("is_typing", False)},exclude=ws)elif mtype == "mark_read":# Handle read receiptsup_to = data.get("up_to_message_id")if up_to:db = await get_db()try:rows = await db.execute("""SELECT id, sender_id FROM messagesWHERE id <= ? AND sender_id != ? AND is_deleted = 0EXCEPT SELECT message_id FROM read_receipts WHERE user_id = ?""",(up_to, uid, uid))receipts = []async for r in rows:await db.execute("INSERT OR IGNORE INTO read_receipts (user_id, message_id) VALUES (?, ?)",(uid, r["id"]))receipts.append(r["id"])await db.commit()for mid in receipts:await manager.broadcast({"type": "read_receipt","message_id": mid,"reader_username": username})finally:await db.close()except WebSocketDisconnect:passexcept Exception as e:logger.error(f"WebSocket error for {username}: {e}")finally:manager.disconnect(ws, username)if username not in manager.active:await manager.broadcast({"type": "user_offline", "username": username})1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556573 unmodified lines616263646566676869707172736 unmodified lines80818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192 unmodified lines222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095import osimport jsonimport timeimport uuidimport base64from typing import Optional, Dict, Set, List, Anyimport asyncioimport aiosqliteimport loggingfrom contextlib import asynccontextmanagerfrom datetime import datetimefrom urllib.parse import unquotefrom fastapi import FastAPI, HTTPException, WebSocket, WebSocketDisconnect, Header, Query, Request, UploadFile, Filefrom fastapi.staticfiles import StaticFilesfrom fastapi.responses import Response, JSONResponse, FileResponsefrom fastapi.middleware.cors import CORSMiddlewarefrom fastapi.middleware.trustedhost import TrustedHostMiddlewarefrom cryptography.hazmat.primitives.ciphers.aead import AESGCMfrom cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMACfrom cryptography.hazmat.primitives import hashesfrom cryptography.hazmat.backends import default_backendfrom storage_handler import store_file, retrieve_file, delete_file, get_bucket_info, file_exists# ------------------------------------------------------------------------# Configuration# ------------------------------------------------------------------------DATABASE_URL = os.environ.get("DATABASE_URL", "/data/infinitychat.db")MESSAGE_KEY_B64 = os.environ.get("SECRET_KEY", None)if MESSAGE_KEY_B64 is None:MESSAGE_KEY_B64 = base64.urlsafe_b64encode(os.urandom(32)).decode()print("WARNING: SECRET_KEY not set – generated random key. Set it permanently in production!")MESSAGE_KEY = base64.urlsafe_b64decode(MESSAGE_KEY_B64)assert len(MESSAGE_KEY) == 32, "SECRET_KEY must decode to exactly 32 bytes"logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')logger = logging.getLogger("InfinityChat")# ------------------------------------------------------------------------# Database initialization# ------------------------------------------------------------------------async def init_database():"""Initialize SQLite database with all required tables and indexes."""async with aiosqlite.connect(DATABASE_URL) as db:db.row_factory = aiosqlite.Rowawait db.execute("PRAGMA journal_mode=WAL;")await db.execute("PRAGMA foreign_keys=ON;")await db.execute("PRAGMA synchronous=NORMAL;")await db.execute("PRAGMA cache_size=-20000;") # 20MB cacheawait db.execute("PRAGMA busy_timeout=5000;")# Users tableawait db.execute("""CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY AUTOINCREMENT,3 unmodified linessalt TEXT NOT NULL,avatar_path TEXT,token TEXT UNIQUE,created_at INTEGER DEFAULT (strftime('%s','now')),last_seen INTEGER DEFAULT (strftime('%s','now')),status TEXT DEFAULT 'offline')""")# Messages table with optimized indexesawait db.execute("""CREATE TABLE IF NOT EXISTS messages (id INTEGER PRIMARY KEY AUTOINCREMENT,6 unmodified linesfile_path TEXT,file_type TEXT,file_name TEXT,file_size INTEGER DEFAULT 0,FOREIGN KEY(sender_id) REFERENCES users(id))""")# Read receiptsawait db.execute("""CREATE TABLE IF NOT EXISTS read_receipts (user_id INTEGER NOT NULL,message_id INTEGER NOT NULL,read_at INTEGER DEFAULT (strftime('%s','now')),PRIMARY KEY (user_id, message_id),FOREIGN KEY(user_id) REFERENCES users(id),FOREIGN KEY(message_id) REFERENCES messages(id))""")# Conversation index for faster queriesawait db.execute("""CREATE INDEX IF NOT EXISTS idx_messages_sender_timeON messages(sender_id, timestamp_ms)""")await db.execute("""CREATE INDEX IF NOT EXISTS idx_messages_time_idON messages(timestamp_ms, id)""")await db.execute("""CREATE INDEX IF NOT EXISTS idx_messages_not_deletedON messages(is_deleted, id)""")await db.execute("""CREATE INDEX IF NOT EXISTS idx_receipts_user_msgON read_receipts(user_id, message_id)""")await db.commit()logger.info("✅ Database initialized successfully")# ------------------------------------------------------------------------# FastAPI app with lifespan# ------------------------------------------------------------------------@asynccontextmanagerasync def lifespan(app: FastAPI):"""Handle startup and shutdown events."""await init_database()yieldapp = FastAPI(title="InfinityChat",version="1.0.0",lifespan=lifespan,docs_url=None,redoc_url=None)# Middlewareapp.add_middleware(CORSMiddleware,allow_origins=["*"],allow_credentials=True,allow_methods=["*"],allow_headers=["*"],)# Static filesapp.mount("/static", StaticFiles(directory="static"), name="static")# ------------------------------------------------------------------------# Database connection pool# ------------------------------------------------------------------------class DatabasePool:"""Simple database connection management."""def __init__(self):self._conn = Noneasync def get_connection(self) -> aiosqlite.Connection:if self._conn is None:self._conn = await aiosqlite.connect(DATABASE_URL)self._conn.row_factory = aiosqlite.Rowawait self._conn.execute("PRAGMA journal_mode=WAL")await self._conn.execute("PRAGMA foreign_keys=ON")await self._conn.execute("PRAGMA synchronous=NORMAL")return self._connasync def close(self):if self._conn:await self._conn.close()self._conn = Nonedb_pool = DatabasePool()async def get_db() -> aiosqlite.Connection:"""Get or create a database connection."""return await db_pool.get_connection()# ------------------------------------------------------------------------# Encryption (AES-256-GCM)# ------------------------------------------------------------------------def encrypt_message(plaintext: str) -> str:"""Encrypt message content with AES-256-GCM."""aesgcm = AESGCM(MESSAGE_KEY)nonce = os.urandom(12)ciphertext = aesgcm.encrypt(nonce, plaintext.encode('utf-8'), None)return base64.urlsafe_b64encode(nonce + ciphertext).decode('utf-8')def decrypt_message(encrypted_b64: str) -> str:"""Decrypt message content."""try:raw = base64.urlsafe_b64decode(encrypted_b64)nonce, ciphertext = raw[:12], raw[12:]aesgcm = AESGCM(MESSAGE_KEY)return aesgcm.decrypt(nonce, ciphertext, None).decode('utf-8')except Exception as e:logger.error(f"Decryption failed: {e}")return "[Decryption Error]"# ------------------------------------------------------------------------# Password hashing (PBKDF2)# ------------------------------------------------------------------------def hash_password(password: str, salt: Optional[str] = None) -> tuple[str, str]:"""Hash password with PBKDF2-SHA256."""if salt is None:salt = os.urandom(32).hex()kdf = PBKDF2HMAC(algorithm=hashes.SHA256(),length=32,salt=salt.encode('utf-8'),iterations=600000,backend=default_backend())key = base64.urlsafe_b64encode(kdf.derive(password.encode('utf-8'))).decode('utf-8')return key, saltdef verify_password(password: str, salt: str, stored_hash: str) -> bool:"""Verify password against stored hash."""2 unmodified linesdef generate_token() -> str:"""Generate a secure random token."""return base64.urlsafe_b64encode(os.urandom(32)).decode('utf-8')# ------------------------------------------------------------------------# Authentication helpers# ------------------------------------------------------------------------async def authenticate_user(token: str) -> Optional[dict]:"""Validate token and return user data."""if not token or token in ('null', 'undefined'):return Nonedb = await get_db()try:async with db.execute("SELECT id, username, display_name, avatar_path, status FROM users WHERE token = ?",(token,)) as cursor:user = await cursor.fetchone()if user:# Update last_seenawait db.execute("UPDATE users SET last_seen = ? WHERE id = ?",(int(time.time()), user['id']))await db.commit()return dict(user)return Noneexcept Exception as e:logger.error(f"Authentication error: {e}")return None# ------------------------------------------------------------------------# HTTP Endpoints# ------------------------------------------------------------------------@app.get("/api/health")async def health_check():"""Health check endpoint."""return {"status": "healthy","timestamp": int(time.time()),"version": "1.0.0"}@app.post("/api/auth/signup")async def signup(username: str = Query(..., min_length=3, max_length=30),password: str = Query(..., min_length=6),display_name: Optional[str] = Query(None, max_length=50)):"""Create a new user account."""# Validate username formatif not username.isalnum() and '_' not in username:raise HTTPException(400, "Username can only contain letters, numbers, and underscores")db = await get_db()try:# Check if username existsasync with db.execute("SELECT id FROM users WHERE username = ?", (username.lower(),)) as cursor:if await cursor.fetchone():raise HTTPException(409, "Username is already taken")# Create userpwd_hash, salt = hash_password(password)token = generate_token()display = display_name or usernamecursor = await db.execute("""INSERT INTO users (username, display_name, password_hash, salt, token, status)VALUES (?, ?, ?, ?, ?, 'online')""",(username.lower(), display, pwd_hash, salt, token))await db.commit()user_id = cursor.lastrowidlogger.info(f"New user registered: {username} (ID: {user_id})")return {"token": token,"user": {"id": user_id,"username": username,"display_name": display,"avatar_path": None,"status": "online"}}except HTTPException:raiseexcept Exception as e:logger.error(f"Signup error: {e}")raise HTTPException(500, "Internal server error")finally:await db.close()@app.post("/api/auth/login")async def login(username: str = Query(...),password: str = Query(...)):"""Authenticate user and return token."""db = await get_db()try:async with db.execute("SELECT * FROM users WHERE username = ?", (username.lower(),)) as cursor:user = await cursor.fetchone()if not user:# Use constant-time comparison to prevent timing attacksverify_password("dummy", os.urandom(32).hex(),base64.urlsafe_b64encode(os.urandom(32)).decode())raise HTTPException(401, "Invalid username or password")if not verify_password(password, user['salt'], user['password_hash']):raise HTTPException(401, "Invalid username or password")# Generate new tokentoken = generate_token()await db.execute("UPDATE users SET token = ?, last_seen = ?, status = 'online' WHERE id = ?",(token, int(time.time()), user['id']))await db.commit()logger.info(f"User logged in: {user['username']}")return {"token": token,"user": {"id": user['id'],"username": user['username'],"display_name": user['display_name'],"avatar_path": user['avatar_path'],"status": "online"}}except HTTPException:raiseexcept Exception as e:logger.error(f"Login error: {e}")raise HTTPException(500, "Internal server error")finally:await db.close()@app.get("/api/auth/verify")async def verify_token(token: str = Header(..., alias="X-Auth-Token")):"""Verify authentication token."""user = await authenticate_user(token)if not user:raise HTTPException(401, "Invalid or expired token")return {"user": user}@app.post("/api/auth/logout")async def logout(token: str = Header(..., alias="X-Auth-Token")):"""Logout user by invalidating token."""db = await get_db()try:await db.execute("UPDATE users SET token = NULL, status = 'offline', last_seen = ? WHERE token = ?",(int(time.time()), token))await db.commit()return {"status": "logged_out"}finally:await db.close()# ------------------------------------------------------------------------# Profile Endpoints# ------------------------------------------------------------------------@app.get("/api/profile")async def get_profile(token: str = Header(..., alias="X-Auth-Token")):"""Get current user profile."""user = await authenticate_user(token)if not user:raise HTTPException(401)return {"user": user}@app.patch("/api/profile")async def update_profile(display_name: Optional[str] = Query(None, max_length=50),token: str = Header(..., alias="X-Auth-Token")):"""Update user profile."""user = await authenticate_user(token)if not user:raise HTTPException(401)db = await get_db()try:if display_name:await db.execute("UPDATE users SET display_name = ? WHERE id = ?",(display_name, user['id']))await db.commit()user['display_name'] = display_namereturn {"user": user}finally:await db.close()@app.post("/api/profile/avatar")async def upload_avatar(file: UploadFile = File(...),token: str = Header(..., alias="X-Auth-Token")):"""Upload user avatar."""user = await authenticate_user(token)if not user:raise HTTPException(401)# Validate file typeallowed_types = {'image/jpeg', 'image/png', 'image/gif', 'image/webp'}if file.content_type not in allowed_types:raise HTTPException(400, "Only JPEG, PNG, GIF, and WebP images are allowed")# Validate file size (max 5MB)data = await file.read()if len(data) > 5 * 1024 * 1024:raise HTTPException(400, "Image must be less than 5MB")# Generate unique pathext = os.path.splitext(file.filename)[1] if file.filename else '.jpg'remote_path = f"avatars/{user['username']}_{uuid.uuid4().hex}{ext}"try:store_file(remote_path, data)except Exception as e:logger.error(f"Avatar upload failed: {e}")raise HTTPException(500, "Failed to upload avatar")db = await get_db()try:await db.execute("UPDATE users SET avatar_path = ? WHERE id = ?",(remote_path, user['id']))await db.commit()user['avatar_path'] = remote_pathfinally:await db.close()return {"avatar_path": remote_path}# ------------------------------------------------------------------------# File Upload (Chunked)# ------------------------------------------------------------------------upload_sessions: Dict[str, Dict] = {}@app.post("/api/upload/chunk")async def upload_chunk(file: UploadFile = File(...),chunk_index: int = Query(..., ge=0),total_chunks: int = Query(..., ge=1),file_name: str = Query(..., max_length=255),file_type: str = Query(..., max_length=100),file_size: int = Query(..., ge=0),upload_id: str = Query(..., min_length=8),token: str = Header(..., alias="X-Auth-Token")):"""Handle chunked file upload."""user = await authenticate_user(token)if not user:raise HTTPException(401)# Validate file size (max 100MB total)if file_size > 100 * 1024 * 1024:raise HTTPException(400, "File must be less than 100MB")# Initialize upload session if newif upload_id not in upload_sessions:upload_sessions[upload_id] = {"chunks": {},"filename": file_name,"file_type": file_type,"file_size": file_size,"total_chunks": total_chunks,"received": 0,"user_id": user['id'],"created_at": time.time()}session = upload_sessions[upload_id]# Verify ownershipif session['user_id'] != user['id']:raise HTTPException(403, "Upload session belongs to another user")# Store chunkchunk_data = await file.read()if chunk_index in session['chunks']:return {"status": "duplicate", "received": session['received'], "total": total_chunks}session['chunks'][chunk_index] = chunk_datasession['received'] += 1# Check if upload completeif session['received'] == total_chunks:# Reassemble filefull_data = b"".join(session['chunks'][i] for i in sorted(session['chunks'].keys()))# Generate storage pathremote_path = f"uploads/{user['username']}/{uuid.uuid4().hex}/{file_name}"try:store_file(remote_path, full_data)except Exception as e:logger.error(f"Failed to store uploaded file: {e}")del upload_sessions[upload_id]raise HTTPException(500, "Failed to store file")# Cleanupdel upload_sessions[upload_id]# Cleanup old sessions (older than 30 minutes)current_time = time.time()expired = [uid for uid, s in upload_sessions.items()if current_time - s['created_at'] > 1800]for uid in expired:del upload_sessions[uid]return {"status": "complete","file_path": remote_path,"file_name": file_name,"file_type": file_type,"file_size": file_size}return {"status": "in_progress","received": session['received'],"total": total_chunks}# ------------------------------------------------------------------------# File Download# ------------------------------------------------------------------------@app.get("/api/download/{file_path:path}")async def download_file(file_path: str,token: str = Header(..., alias="X-Auth-Token")):"""Download a file with authentication."""user = await authenticate_user(token)if not user:raise HTTPException(401)# Security: prevent path traversalif '..' in file_path or file_path.startswith('/'):raise HTTPException(400, "Invalid file path")try:data = retrieve_file(file_path)except FileNotFoundError:raise HTTPException(404, "File not found")except Exception as e:logger.error(f"File download failed: {file_path} - {e}")raise HTTPException(500, "Failed to retrieve file")import mimetypesmedia_type = mimetypes.guess_type(file_path)[0] or "application/octet-stream"filename = os.path.basename(file_path)return Response(content=data,media_type=media_type,headers={"Content-Disposition": f'inline; filename="{filename}"',"Cache-Control": "private, max-age=3600"})# ------------------------------------------------------------------------# WebSocket Connection Manager# ------------------------------------------------------------------------class ConnectionManager:"""Manage WebSocket connections with per-user tracking."""def __init__(self):self.active_connections: Dict[int, Dict[str, Any]] = {} # user_id -> {username, connections: set}async def connect(self, websocket: WebSocket, user_id: int, username: str):"""Add a new connection."""await websocket.accept()if user_id not in self.active_connections:self.active_connections[user_id] = {"username": username,"connections": set()}self.active_connections[user_id]["connections"].add(websocket)def disconnect(self, websocket: WebSocket, user_id: int):"""Remove a connection."""if user_id in self.active_connections:self.active_connections[user_id]["connections"].discard(websocket)if not self.active_connections[user_id]["connections"]:del self.active_connections[user_id]async def broadcast(self, message: dict, exclude_user_id: Optional[int] = None):"""Broadcast message to all connected users."""for uid, info in self.active_connections.items():if uid == exclude_user_id:continuefor ws in list(info["connections"]):try:await ws.send_json(message)except Exception:self.disconnect(ws, uid)async def send_to_user(self, user_id: int, message: dict):"""Send message to a specific user."""if user_id in self.active_connections:for ws in list(self.active_connections[user_id]["connections"]):try:await ws.send_json(message)except Exception:self.disconnect(ws, user_id)def get_online_users(self) -> List[Dict]:"""Get list of online users with their info."""users = []for uid, info in self.active_connections.items():users.append({"id": uid,"username": info["username"]})return usersdef is_online(self, user_id: int) -> bool:"""Check if a user is online."""return user_id in self.active_connectionsmanager = ConnectionManager()# ------------------------------------------------------------------------# WebSocket Endpoint# ------------------------------------------------------------------------@app.websocket("/ws")async def websocket_endpoint(websocket: WebSocket, token: str = Query(...)):"""WebSocket endpoint for real-time messaging."""# Authenticateuser = await authenticate_user(token)if not user:await websocket.close(code=4001, reason="Authentication failed")returnuser_id = user['id']username = user['username']display_name = user['display_name']avatar_path = user['avatar_path']# Connectawait manager.connect(websocket, user_id, username)# Send initial dataonline_users = manager.get_online_users()await websocket.send_json({"type": "connection_established","user_id": user_id,"username": username,"display_name": display_name,"avatar_path": avatar_path,"online_users": online_users})# Broadcast user online statusawait manager.broadcast({"type": "user_status","user_id": user_id,"username": username,"display_name": display_name,"avatar_path": avatar_path,"status": "online"}, exclude_user_id=user_id)try:while True:data = await websocket.receive_json()message_type = data.get("type")# --------------------------------------------------------------------# Send Message# --------------------------------------------------------------------if message_type == "send_message":content = data.get("content", "").strip()reply_to_id = data.get("reply_to_id")file_path = data.get("file_path")file_type = data.get("file_type")file_name = data.get("file_name")file_size = data.get("file_size", 0)client_id = data.get("client_id")# Validate contentif not content and not file_path:await websocket.send_json({"type": "error","code": "INVALID_MESSAGE","message": "Message must contain text or a file"})continue# Validate content lengthif len(content) > 10000:await websocket.send_json({"type": "error","code": "MESSAGE_TOO_LONG","message": "Message must be less than 10,000 characters"})continue# Validate reply existsif reply_to_id:db = await get_db()try:async with db.execute("SELECT id FROM messages WHERE id = ? AND is_deleted = 0",(reply_to_id,)) as cursor:if not await cursor.fetchone():reply_to_id = Nonefinally:await db.close()timestamp_ms = int(time.time() * 1000)# Encrypt contentencrypted = encrypt_message(content)# Store in databasedb = await get_db()try:cursor = await db.execute("""INSERT INTO messages(sender_id, encrypted_content, timestamp_ms, reply_to_id,file_path, file_type, file_name, file_size)VALUES (?, ?, ?, ?, ?, ?, ?, ?)""",(user_id, encrypted, timestamp_ms, reply_to_id,file_path, file_type, file_name, file_size))message_id = cursor.lastrowidawait db.commit()finally:await db.close()# Build message objectmessage_obj = {"type": "new_message","message": {"id": message_id,"sender_id": user_id,"sender_username": username,"sender_display_name": display_name,"sender_avatar_path": avatar_path,"content": content,"timestamp_ms": timestamp_ms,"reply_to_id": reply_to_id,"file_path": file_path,"file_type": file_type,"file_name": file_name,"file_size": file_size,"is_edited": False,"is_deleted": False,"status": "sent"}}# Send to sender with delivered statusawait websocket.send_json({**message_obj,"message": {**message_obj["message"], "status": "delivered"},"client_id": client_id})# Broadcast to other usersawait manager.broadcast(message_obj, exclude_user_id=user_id)# --------------------------------------------------------------------# Load Messages (Cursor-based Pagination)# --------------------------------------------------------------------elif message_type == "load_messages":cursor_id = data.get("cursor") # Message ID to load beforelimit = min(int(data.get("limit", 50)), 100)db = await get_db()try:if cursor_id:query = """SELECT m.*, u.username, u.display_name, u.avatar_pathFROM messages mJOIN users u ON m.sender_id = u.idWHERE m.is_deleted = 0 AND m.id < ?ORDER BY m.id DESCLIMIT ?"""params = (cursor_id, limit)else:query = """SELECT m.*, u.username, u.display_name, u.avatar_pathFROM messages mJOIN users u ON m.sender_id = u.idWHERE m.is_deleted = 0ORDER BY m.id DESCLIMIT ?"""params = (limit,)rows = await (await db.execute(query, params)).fetchall()messages = []for row in reversed(rows): # Reverse to get chronological ordertry:decrypted = decrypt_message(row['encrypted_content'])except Exception:decrypted = "[Decryption Error]"# Check read statusread_status = "sent"async with db.execute("SELECT COUNT(*) as count FROM read_receipts WHERE message_id = ?",(row['id'],)) as read_cursor:read_result = await read_cursor.fetchone()if read_result and read_result['count'] > 0:read_status = "read"messages.append({"id": row['id'],"sender_id": row['sender_id'],"sender_username": row['username'],"sender_display_name": row['display_name'],"sender_avatar_path": row['avatar_path'],"content": decrypted,"timestamp_ms": row['timestamp_ms'],"reply_to_id": row['reply_to_id'],"file_path": row['file_path'],"file_type": row['file_type'],"file_name": row['file_name'],"file_size": row['file_size'],"is_edited": bool(row['is_edited']),"is_deleted": False,"status": read_status})# Get the oldest message ID for next pagenext_cursor = Noneif len(messages) > 0:next_cursor = messages[0]['id']await websocket.send_json({"type": "messages_loaded","messages": messages,"next_cursor": next_cursor,"has_more": len(messages) == limit})finally:await db.close()# --------------------------------------------------------------------# Edit Message# --------------------------------------------------------------------elif message_type == "edit_message":message_id = data.get("message_id")new_content = data.get("content", "").strip()if not message_id or not new_content:await websocket.send_json({"type": "error","code": "INVALID_EDIT","message": "Message ID and new content are required"})continueif len(new_content) > 10000:await websocket.send_json({"type": "error","code": "MESSAGE_TOO_LONG","message": "Message must be less than 10,000 characters"})continuedb = await get_db()try:# Verify ownershipasync with db.execute("SELECT * FROM messages WHERE id = ? AND sender_id = ? AND is_deleted = 0",(message_id, user_id)) as cursor:if not await cursor.fetchone():await websocket.send_json({"type": "error","code": "NOT_FOUND","message": "Message not found or you don't have permission to edit it"})continuenew_encrypted = encrypt_message(new_content)await db.execute("UPDATE messages SET encrypted_content = ?, is_edited = 1 WHERE id = ?",(new_encrypted, message_id))await db.commit()# Broadcast editawait manager.broadcast({"type": "message_edited","message_id": message_id,"content": new_content,"editor_id": user_id})finally:await db.close()# --------------------------------------------------------------------# Delete Message# --------------------------------------------------------------------elif message_type == "delete_message":message_id = data.get("message_id")if not message_id:continuedb = await get_db()try:# Verify ownershipasync with db.execute("SELECT * FROM messages WHERE id = ? AND sender_id = ?",(message_id, user_id)) as cursor:message = await cursor.fetchone()if not message:await websocket.send_json({"type": "error","code": "NOT_FOUND","message": "Message not found or you don't have permission to delete it"})continue# Delete associated file if existsif message['file_path']:try:delete_file(message['file_path'])except Exception:pass# Remove message and read receiptsawait db.execute("DELETE FROM messages WHERE id = ?", (message_id,))await db.execute("DELETE FROM read_receipts WHERE message_id = ?", (message_id,))await db.commit()# Broadcast deletionawait manager.broadcast({"type": "message_deleted","message_id": message_id})finally:await db.close()# --------------------------------------------------------------------# Typing Indicator# --------------------------------------------------------------------elif message_type == "typing":is_typing = bool(data.get("is_typing", False))await manager.broadcast({"type": "typing_indicator","user_id": user_id,"username": username,"display_name": display_name,"is_typing": is_typing}, exclude_user_id=user_id)# --------------------------------------------------------------------# Mark as Read# --------------------------------------------------------------------elif message_type == "mark_read":up_to_message_id = data.get("up_to_message_id")if not up_to_message_id:continuedb = await get_db()try:# Get messages that haven't been read by this userrows = await db.execute("""SELECT m.id, m.sender_idFROM messages mWHERE m.id <= ?AND m.sender_id != ?AND m.is_deleted = 0AND m.id > (SELECT COALESCE(MAX(message_id), 0)FROM read_receiptsWHERE user_id = ?)""",(up_to_message_id, user_id, user_id))new_reads = []async for row in rows:await db.execute("INSERT OR IGNORE INTO read_receipts (user_id, message_id, read_at) VALUES (?, ?, ?)",(user_id, row['id'], int(time.time())))new_reads.append({"message_id": row['id'],"sender_id": row['sender_id']})await db.commit()# Notify message sendersfor read_info in new_reads:await manager.send_to_user(read_info['sender_id'], {"type": "message_read","message_id": read_info['message_id'],"reader_id": user_id,"reader_username": username})finally:await db.close()# --------------------------------------------------------------------# Get Online Users# --------------------------------------------------------------------elif message_type == "get_online_users":await websocket.send_json({"type": "online_users","users": manager.get_online_users()})except WebSocketDisconnect:passexcept Exception as e:logger.error(f"WebSocket error for {username}: {e}")finally:# Disconnectmanager.disconnect(websocket, user_id)# Update status in databasedb = await get_db()try:await db.execute("UPDATE users SET status = 'offline', last_seen = ? WHERE id = ?",(int(time.time()), user_id))await db.commit()finally:await db.close()# Broadcast offline statusawait manager.broadcast({"type": "user_status","user_id": user_id,"username": username,"display_name": display_name,"avatar_path": avatar_path,"status": "offline"})# ------------------------------------------------------------------------# Root endpoint# ------------------------------------------------------------------------@app.get("/")async def root():"""Serve the main application."""return FileResponse("static/index.html")
app.py+827-320