""" Session management with AES encryption. Each session is encrypted with the user's password. Session ID is derived from password — only the right password unlocks the right session. File contents are persisted to disk so map works after refresh. """ import json import os from datetime import datetime from app.config import SESSION_STORE_PATH from app.utils.crypto import encrypt, decrypt, derive_session_id def _load_all() -> dict: if os.path.exists(SESSION_STORE_PATH): try: with open(SESSION_STORE_PATH, "r") as f: return json.load(f) except Exception: return {} return {} def _save_all(data: dict): try: with open(SESSION_STORE_PATH, "w") as f: json.dump(data, f) except Exception as e: print(f"[SESSION] Save failed: {e}") def get_session(session_id: str, password: str) -> dict: """ Load and decrypt a session. Returns empty session if not found. Raises ValueError if password is wrong. """ all_sessions = _load_all() if session_id not in all_sessions: return { "messages": [], "linked_files": [], "file_contents": {}, "map_data": None, "label": "untitled session", "created_at": datetime.now().isoformat(), "last_active": datetime.now().isoformat(), } token = all_sessions[session_id] # decrypt raises ValueError on wrong password return decrypt(token, password) def save_session( session_id: str, password: str, messages: list, linked_files: list, file_contents: dict, label: str = "", map_data: dict = None, ): """Encrypt and persist session data.""" all_sessions = _load_all() # Reconstruct existing metadata if available existing = {} try: if session_id in all_sessions: existing = decrypt(all_sessions[session_id], password) except Exception: pass data = { "messages": messages, "linked_files": linked_files, "file_contents": file_contents, # {filename: [text, language]} "map_data": map_data, "label": label or existing.get("label", "untitled session"), "created_at": existing.get("created_at", datetime.now().isoformat()), "last_active": datetime.now().isoformat(), "preview": next( (m["content"][:60] for m in messages if m["role"] == "user"), "no messages yet" ), } all_sessions[session_id] = encrypt(data, password) _save_all(all_sessions) def session_exists(session_id: str) -> bool: return session_id in _load_all() def delete_session(session_id: str): all_sessions = _load_all() all_sessions.pop(session_id, None) _save_all(all_sessions) def rename_session(session_id: str, password: str, new_label: str): try: data = get_session(session_id, password) data["label"] = new_label save_session( session_id, password, data["messages"], data["linked_files"], data.get("file_contents", {}), new_label, data.get("map_data"), ) except Exception: pass def list_sessions() -> list: """ Returns only session IDs and last_active timestamps. Cannot read labels/previews without password — by design. """ all_sessions = _load_all() return [ {"id": sid, "last_active": "encrypted"} for sid in all_sessions.keys() ]