diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md index a8eca8b..c4e1ef9 100644 --- a/ARCHITECTURE.md +++ b/ARCHITECTURE.md @@ -102,7 +102,7 @@ ## Деплой ``` -Сервер: 192.168.87.76 (git.kazin.ru = smeta.kazin.ru) +Сервер: 192.168.87.76 (git.kazin.ru = infosmeta.ru) OS: Ubuntu, 32GB RAM, 8 CPU Пользователь: mcp-user Сервис: smeta-web.service (uvicorn:8101) diff --git a/README.md b/README.md index ec93a8e..bb2ec48 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # Сметный ИИ-ассистент -**URL:** https://smeta.kazin.ru +**URL:** https://infosmeta.ru ## Чат с ИИ @@ -67,7 +67,7 @@ ### Сервер ``` -IP: 192.168.87.76 (git.kazin.ru / smeta.kazin.ru) +IP: 192.168.87.76 (git.kazin.ru / infosmeta.ru) SSH: ssh server-mcp-user App: /home/mcp-user/smeta-web/ Data: /home/mcp-user/smeta-web-data/ diff --git a/batch.py b/batch.py index 6c55624..ff558e2 100644 --- a/batch.py +++ b/batch.py @@ -25,7 +25,7 @@ import httpx ZAI_API_KEY = os.environ.get("ZAI_API_KEY", "") ZAI_BASE_URL = os.environ.get("ZAI_BASE_URL", "https://open.bigmodel.cn/api/coding/paas/v4") -ZAI_MODEL = os.environ.get("ZAI_MODEL", "glm-5") +ZAI_MODEL = os.environ.get("ZAI_MODEL", "glm-5.1") # Batch jobs storage _jobs: dict[str, dict] = {} @@ -231,6 +231,7 @@ async def analyze_structure(sample_files: list[str], target_file: str, task_desc "temperature": 0.1, "max_tokens": 4000, "response_format": {"type": "json_object"}, + "thinking": {"type": "disabled"}, }, ) resp.raise_for_status() diff --git a/claude_bridge_glm.py b/claude_bridge_glm.py index 673605f..553fa0a 100644 --- a/claude_bridge_glm.py +++ b/claude_bridge_glm.py @@ -16,7 +16,7 @@ import httpx SMETA_DIR = Path(os.environ.get("SMETA_PROJECT_DIR", os.path.expanduser("~/smeta-railway"))) ZAI_API_KEY = os.environ.get("ZAI_API_KEY", "") ZAI_BASE_URL = os.environ.get("ZAI_BASE_URL", "https://open.bigmodel.cn/api/coding/paas/v4") -ZAI_MODEL = os.environ.get("ZAI_MODEL", "glm-5") +ZAI_MODEL = os.environ.get("ZAI_MODEL", "glm-5.1") DATA_DIR = Path(os.environ.get("DATA_DIR", "./smeta-web-data")) # Session tracking: (username, tab_id) -> conversation history @@ -341,7 +341,7 @@ async def stream_claude( full_response = "" proxy = os.environ.get("HTTPS_PROXY") or os.environ.get("HTTP_PROXY") try: - async with httpx.AsyncClient(timeout=60, proxy=proxy) as client: + async with httpx.AsyncClient(timeout=120, proxy=proxy) as client: resp = await client.post( f"{ZAI_BASE_URL}/chat/completions", headers={"Authorization": f"Bearer {ZAI_API_KEY}"}, @@ -350,7 +350,8 @@ async def stream_claude( "messages": messages, "stream": True, "temperature": 0.1, - "max_tokens": 2000, + "max_tokens": 4096, + "thinking": {"type": "disabled"}, }, ) resp.raise_for_status() @@ -364,6 +365,7 @@ async def stream_claude( try: chunk = json.loads(data_str) delta = chunk["choices"][0].get("delta", {}) + # GLM-5.1: skip reasoning_content (internal thinking), use only content text = delta.get("content", "") if text: full_response += text diff --git a/db.py b/db.py index d4e4d13..6fcb383 100644 --- a/db.py +++ b/db.py @@ -40,6 +40,20 @@ CREATE TABLE IF NOT EXISTS invites ( created_at REAL NOT NULL, expires_at REAL NOT NULL ); + +CREATE TABLE IF NOT EXISTS audit_log ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + timestamp REAL NOT NULL, + username TEXT, + action TEXT NOT NULL, + method TEXT NOT NULL, + path TEXT NOT NULL, + detail TEXT, + ip TEXT, + status_code INTEGER +); +CREATE INDEX IF NOT EXISTS idx_audit_ts ON audit_log(timestamp); +CREATE INDEX IF NOT EXISTS idx_audit_user ON audit_log(username); """ @@ -201,6 +215,39 @@ def get_history_any_user(tab_id: str, limit: int = 100) -> list[dict]: return [dict(r) for r in reversed(rows)] +# === Audit Log === + +def log_action(username: str | None, action: str, method: str, path: str, + detail: str | None = None, ip: str | None = None, + status_code: int | None = None): + with _conn() as conn: + conn.execute( + "INSERT INTO audit_log (timestamp, username, action, method, path, detail, ip, status_code) " + "VALUES (?, ?, ?, ?, ?, ?, ?, ?)", + (time.time(), username, action, method, path, detail, ip, status_code), + ) + + +def get_audit_log(limit: int = 100, offset: int = 0, + username: str | None = None, + action: str | None = None) -> list[dict]: + where, params = [], [] + if username: + where.append("username = ?") + params.append(username) + if action: + where.append("action = ?") + params.append(action) + clause = ("WHERE " + " AND ".join(where)) if where else "" + params += [limit, offset] + with _conn() as conn: + rows = conn.execute( + f"SELECT * FROM audit_log {clause} ORDER BY id DESC LIMIT ? OFFSET ?", + params, + ).fetchall() + return [dict(r) for r in rows] + + def list_sessions(username: str) -> list[dict]: """List all chat sessions for a user with last message preview.""" with _conn() as conn: diff --git a/main.py b/main.py index 9466c0e..e4730a0 100644 --- a/main.py +++ b/main.py @@ -11,7 +11,7 @@ from fastapi.responses import FileResponse, HTMLResponse, StreamingResponse from fastapi.staticfiles import StaticFiles from auth import authenticate, verify_token -from db import get_history, get_history_any_user, init_db, list_sessions, save_message +from db import get_audit_log, get_history, get_history_any_user, init_db, list_sessions, log_action, save_message # Backend: "claude" (Docker sandbox), "glm" (GLM-5 + CAG), "auto" (route by task) AI_BACKEND = os.environ.get("AI_BACKEND", "claude") @@ -101,12 +101,97 @@ app.mount("/static", StaticFiles(directory="static"), name="static") MAX_UPLOAD_SIZE = 50 * 1024 * 1024 # 50 MB MAX_MESSAGE_LEN = 10_000 +# Audit: path → action name mapping +_AUDIT_MAP = [ + ("POST", "/api/login", "login"), + ("POST", "/api/register", "register"), + ("POST", "/api/verify-email", "verify_email"), + ("POST", "/api/refresh", "refresh"), + ("POST", "/api/chat", "chat"), + ("POST", "/api/upload", "upload"), + ("GET", "/api/files/", "download"), + ("GET", "/api/files", "list_files"), + ("POST", "/api/clear-files", "clear_files"), + ("POST", "/api/reset", "reset_session"), + ("POST", "/api/batch-v2/", "batch_v2"), + ("GET", "/api/batch-v2/", "batch_v2"), + ("POST", "/api/batch-v3/", "batch_v3"), + ("GET", "/api/batch-v3/", "batch_v3"), + ("POST", "/api/ssr/", "ssr"), + ("GET", "/api/ssr/", "ssr"), + ("POST", "/api/check/", "check"), + ("POST", "/api/gen/", "generate"), + ("GET", "/api/gen/", "generate"), + ("POST", "/api/wizard/", "wizard"), + ("GET", "/api/wizard/", "wizard"), + ("GET", "/api/ref/", "reference"), + ("GET", "/api/history", "history"), + ("GET", "/api/sessions", "sessions"), + ("GET", "/api/admin/", "admin"), + ("POST", "/api/admin/", "admin"), +] + +_SKIP_PREFIXES = ("/static/", "/favicon") + + +def _resolve_action(method: str, path: str) -> str | None: + if any(path.startswith(p) for p in _SKIP_PREFIXES): + return None + for m, prefix, action in _AUDIT_MAP: + if method == m and path.startswith(prefix): + # For admin sub-actions: admin.invite, admin.block, etc. + if action == "admin": + sub = path.removeprefix("/api/admin/").split("/")[0].split("?")[0] + return f"admin.{sub}" if sub else "admin" + return action + # Pages (GET /, /batch2, /admin, etc.) — skip + if not path.startswith("/api/"): + return None + return method.lower() + ":" + path + @app.on_event("startup") async def startup(): init_db() +# Actions logged manually in handlers (with richer detail) +_MANUAL_ACTIONS = {"login", "login_fail", "chat", "upload", "register", "register_fail"} + + +@app.middleware("http") +async def audit_middleware(request: Request, call_next): + method = request.method + path = request.url.path + action = _resolve_action(method, path) + response = await call_next(request) + if action is None or action in _MANUAL_ACTIONS: + return response + # Extract username from JWT (best-effort, don't fail) + username = None + try: + auth_header = request.headers.get("authorization", "") + tok = auth_header.removeprefix("Bearer ").strip() + if tok: + username = verify_token(tok) + except Exception: + pass + # Extract detail based on action + detail = None + if action == "download": + parts = path.split("/api/files/") + detail = parts[1] if len(parts) > 1 else None + elif action in ("batch_v2", "batch_v3", "ssr", "generate"): + sub = path.split("/")[-1] if "/" in path else None + detail = sub + ip = request.client.host if request.client else None + try: + log_action(username, action, method, path, detail, ip, response.status_code) + except Exception: + pass + return response + + # Rate limiting for chat API (10 requests/minute per user) _chat_rate: dict[str, list[float]] = {} CHAT_RATE_LIMIT = 10 @@ -153,10 +238,12 @@ async def login(request: Request): client_ip = request.client.host if request.client else "" token = authenticate(username, password, client_ip) if not token: + log_action(username, "login_fail", "POST", "/api/login", None, client_ip, 401) raise HTTPException(401, "Wrong credentials") from auth import _make_refresh_token, get_token_role role = get_token_role(token) refresh = _make_refresh_token(username, role) + log_action(username, "login", "POST", "/api/login", f"role={role}", client_ip, 200) return {"token": token, "refresh_token": refresh, "username": username} @@ -183,9 +270,13 @@ async def register(request: Request): from auth import register_user result = register_user(email, password, invite) + client_ip = request.client.host if request.client else "" if not result["ok"]: + log_action(email, "register_fail", "POST", "/api/register", result["error"], client_ip, 400) raise HTTPException(400, result["error"]) + log_action(email, "register", "POST", "/api/register", None, client_ip, 200) + # Send verification code via email code = result.get("code", "") if code: @@ -256,6 +347,8 @@ async def chat(request: Request): raise HTTPException(400, "Empty message") if len(message) > MAX_MESSAGE_LEN: raise HTTPException(400, f"Message too long (max {MAX_MESSAGE_LEN} chars)") + ip = request.client.host if request.client else None + log_action(user, "chat", "POST", "/api/chat", f"tab={tab_id} | {message[:120]}", ip, 200) return StreamingResponse( _stream_and_save(message, user, tab_id), @@ -317,6 +410,8 @@ async def upload(request: Request, file: UploadFile): dest = work_dir / safe_name dest.write_bytes(b"".join(chunks)) save_message(user, tab_id, "system", f"Загружен файл: {safe_name} ({total} байт)") + ip = request.client.host if request.client else None + log_action(user, "upload", "POST", "/api/upload", f"{safe_name} ({total}B) tab={tab_id}", ip, 200) return {"filename": safe_name, "size": total} @@ -572,6 +667,17 @@ async def admin_sessions(request: Request): return [dict(r) for r in rows] +@app.get("/api/admin/audit") +async def admin_audit(request: Request): + """Full audit log — admin only.""" + _require_admin(request) + limit = int(request.query_params.get("limit", "200")) + offset = int(request.query_params.get("offset", "0")) + username = request.query_params.get("username") or None + action = request.query_params.get("action") or None + return get_audit_log(limit, offset, username, action) + + @app.get("/api/admin/stats") async def admin_stats(request: Request): """Dashboard stats: messages per day, total sessions, etc.""" @@ -608,7 +714,7 @@ async def create_invite_endpoint(request: Request): from db import create_invite invite_token = secrets.token_urlsafe(24) create_invite(invite_token, user) - return {"invite_token": invite_token, "url": f"https://smeta.kazin.ru/register?invite={invite_token}"} + return {"invite_token": invite_token, "url": f"https://infosmeta.ru/register?invite={invite_token}"} @app.get("/api/admin/invites") diff --git a/static/admin.html b/static/admin.html index c513189..137cadc 100644 --- a/static/admin.html +++ b/static/admin.html @@ -45,6 +45,7 @@ a { color: var(--accent); text-decoration: none; } Пользователи Приглашения Сессии + Журнал ← Вернуться в чат @@ -83,6 +84,24 @@ a { color: var(--accent); text-decoration: none; } + +
+

Журнал действий

+
+ + + +
+ + +
ВремяПользовательДействиеПутьДеталиIPКод
+ +
+