CRITICAL: - #1 JWT секрет: убран fallback, fail-fast без SESSION_SECRET - #7 env leak: минимальный env для subprocess (не os.environ.copy()) HIGH: - #4 timing attack: hmac.compare_digest вместо == - #5 brute force: rate limiting 5 попыток / 5 мин на IP - #6 upload: whitelist расширений (xlsx, docx, pdf, csv, txt, xml, json, yaml) MEDIUM: - #9 XSS: textContent вместо innerHTML для имён файлов - #10 token expire: 24ч вместо 7 дней - #11 DoS: asyncio.Semaphore(3) на Claude-процессы - #12 session isolation: ключ (username, tab_id) вместо tab_id - #14 DoS: лимит длины сообщения 10000 символов - #15 OOM: чтение upload по чанкам 1MB LOW: - #19 reset endpoint: POST с body Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
163 lines
4.9 KiB
Python
163 lines
4.9 KiB
Python
"""smeta-web: AI assistant for estimators — FastAPI + Claude Code."""
|
|
|
|
import os
|
|
import shutil
|
|
from pathlib import Path
|
|
|
|
from fastapi import FastAPI, HTTPException, Request, UploadFile
|
|
from fastapi.responses import FileResponse, HTMLResponse, StreamingResponse
|
|
from fastapi.staticfiles import StaticFiles
|
|
|
|
from auth import authenticate, verify_token
|
|
from claude_bridge import (
|
|
clear_session,
|
|
get_work_dir,
|
|
is_allowed_file,
|
|
list_user_files,
|
|
stream_claude,
|
|
)
|
|
|
|
app = FastAPI(title="smeta-web")
|
|
app.mount("/static", StaticFiles(directory="static"), name="static")
|
|
|
|
MAX_UPLOAD_SIZE = 50 * 1024 * 1024 # 50 MB
|
|
MAX_MESSAGE_LEN = 10_000 # #14 DoS: limit prompt length
|
|
|
|
|
|
def _get_user(request: Request) -> str:
|
|
"""Extract and verify user from Authorization header."""
|
|
auth = request.headers.get("authorization", "")
|
|
token = auth.removeprefix("Bearer ").strip()
|
|
if not token:
|
|
raise HTTPException(401, "No token")
|
|
user = verify_token(token)
|
|
if not user:
|
|
raise HTTPException(401, "Invalid token")
|
|
return user
|
|
|
|
|
|
def _get_tab(request: Request, body: dict | None = None) -> str:
|
|
"""Extract tab_id from request header or body."""
|
|
if body and "tab_id" in body:
|
|
return body["tab_id"]
|
|
return request.headers.get("x-tab-id", "default")
|
|
|
|
|
|
@app.get("/", response_class=HTMLResponse)
|
|
async def index():
|
|
return Path("static/chat.html").read_text(encoding="utf-8")
|
|
|
|
|
|
@app.post("/api/login")
|
|
async def login(request: Request):
|
|
body = await request.json()
|
|
username = body.get("username", "")
|
|
password = body.get("password", "")
|
|
client_ip = request.client.host if request.client else ""
|
|
token = authenticate(username, password, client_ip)
|
|
if not token:
|
|
raise HTTPException(401, "Wrong credentials")
|
|
return {"token": token, "username": username}
|
|
|
|
|
|
@app.post("/api/chat")
|
|
async def chat(request: Request):
|
|
user = _get_user(request)
|
|
body = await request.json()
|
|
message = body.get("message", "").strip()
|
|
tab_id = _get_tab(request, body)
|
|
if not message:
|
|
raise HTTPException(400, "Empty message")
|
|
if len(message) > MAX_MESSAGE_LEN:
|
|
raise HTTPException(400, f"Message too long (max {MAX_MESSAGE_LEN} chars)")
|
|
|
|
return StreamingResponse(
|
|
stream_claude(message, user, tab_id),
|
|
media_type="text/event-stream",
|
|
headers={
|
|
"Cache-Control": "no-cache",
|
|
"X-Accel-Buffering": "no",
|
|
},
|
|
)
|
|
|
|
|
|
@app.post("/api/upload")
|
|
async def upload(request: Request, file: UploadFile):
|
|
user = _get_user(request)
|
|
tab_id = request.headers.get("x-tab-id", "default")
|
|
work_dir = get_work_dir(user, tab_id)
|
|
|
|
safe_name = Path(file.filename).name
|
|
if not safe_name or safe_name.startswith("."):
|
|
raise HTTPException(400, "Invalid filename")
|
|
|
|
# #6 HIGH: whitelist file extensions
|
|
if not is_allowed_file(safe_name):
|
|
raise HTTPException(
|
|
400,
|
|
f"File type not allowed. Allowed: xlsx, docx, pdf, csv, txt, xml, json, yaml",
|
|
)
|
|
|
|
# #15: read in chunks to avoid OOM on huge files
|
|
chunks = []
|
|
total = 0
|
|
while True:
|
|
chunk = await file.read(1024 * 1024) # 1MB chunks
|
|
if not chunk:
|
|
break
|
|
total += len(chunk)
|
|
if total > MAX_UPLOAD_SIZE:
|
|
raise HTTPException(413, f"File too large (max {MAX_UPLOAD_SIZE // 1024 // 1024}MB)")
|
|
chunks.append(chunk)
|
|
|
|
dest = work_dir / safe_name
|
|
dest.write_bytes(b"".join(chunks))
|
|
return {"filename": safe_name, "size": total}
|
|
|
|
|
|
@app.get("/api/files")
|
|
async def files(request: Request):
|
|
user = _get_user(request)
|
|
tab_id = request.headers.get("x-tab-id", "default")
|
|
return list_user_files(user, tab_id)
|
|
|
|
|
|
@app.get("/api/files/{filename}")
|
|
async def download_file(filename: str, request: Request):
|
|
user = _get_user(request)
|
|
tab_id = request.headers.get("x-tab-id", "default")
|
|
safe_name = Path(filename).name
|
|
fpath = get_work_dir(user, tab_id) / safe_name
|
|
if not fpath.exists() or not fpath.is_file():
|
|
raise HTTPException(404, "File not found")
|
|
return FileResponse(fpath, filename=filename)
|
|
|
|
|
|
@app.post("/api/reset")
|
|
async def reset_session(request: Request):
|
|
user = _get_user(request)
|
|
tab_id = request.headers.get("x-tab-id", "default")
|
|
clear_session(user, tab_id)
|
|
return {"status": "ok"}
|
|
|
|
|
|
@app.post("/api/clear-files")
|
|
async def clear_files(request: Request):
|
|
user = _get_user(request)
|
|
tab_id = request.headers.get("x-tab-id", "default")
|
|
work_dir = get_work_dir(user, tab_id)
|
|
for f in work_dir.iterdir():
|
|
if f.name.startswith("."):
|
|
continue
|
|
if f.is_file():
|
|
f.unlink()
|
|
elif f.is_dir():
|
|
shutil.rmtree(f)
|
|
clear_session(user, tab_id)
|
|
return {"status": "ok"}
|
|
|
|
|
|
if __name__ == "__main__":
|
|
import uvicorn
|
|
uvicorn.run(app, host="0.0.0.0", port=int(os.environ.get("PORT", "8000")))
|