feat: докачиваемая загрузка файлов до 3 ГБ (tus 1.0.0)

Бэкенд (tus_upload.py): самодостаточное ядро tus — потоковая запись
кусков на диск (память не растёт), докачка с серверного offset,
изоляция по владельцу, перенос готового файла в work_dir как у legacy
/api/upload, лимит 3 ГБ + guard по свободному диску, авто-чистка
брошенных загрузок старше суток.

Фронт: tus-js-client (с SRI) — прогресс, авто-ретраи, обновление
токена перед истечением, докачка после обрыва/перезагрузки; мягкий
fallback на /api/upload если CDN недоступен.

Аудит: tus-куски не логируются по PATCH, только финализация (action=upload).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
anor
2026-06-02 15:43:56 +10:00
co-authored by Claude Opus 4.8
parent ac17dec3ce
commit 522b157acc
3 changed files with 290 additions and 10 deletions
+18 -1
View File
@@ -12,6 +12,7 @@ from fastapi.staticfiles import StaticFiles
from auth import authenticate, verify_token
from db import get_audit_log, get_history, get_history_any_user, init_db, list_sessions, log_action, save_message
from tus_upload import register_tus
# Backend: "claude" (Docker sandbox), "glm" (GLM-5 + CAG), "auto" (route by task)
AI_BACKEND = os.environ.get("AI_BACKEND", "claude")
@@ -187,7 +188,7 @@ _AUDIT_MAP = [
("POST", "/api/admin/", "admin"),
]
_SKIP_PREFIXES = ("/static/", "/favicon")
_SKIP_PREFIXES = ("/static/", "/favicon", "/api/tus") # tus chunks are logged on completion, not per-PATCH
def _resolve_action(method: str, path: str) -> str | None:
@@ -286,6 +287,22 @@ async def index():
return Path("static/chat.html").read_text(encoding="utf-8")
# Resumable uploads (tus 1.0.0). Same-process, reuses auth + per-user work dir;
# the finished file lands in the work dir exactly like legacy /api/upload.
TUS_MAX_SIZE = 3 * 1024 * 1024 * 1024 # 3 GB
register_tus(
app,
get_user=_get_user,
get_work_dir=get_work_dir,
is_allowed_file=is_allowed_file,
log_action=log_action,
save_message=save_message,
max_size=TUS_MAX_SIZE,
staging_root=Path(os.environ.get("DATA_DIR", "./smeta-web-data")) / "_tus",
allowed_hint="xlsx, xls, docx, pdf, csv, txt, xml, json, yaml, gge, esw, zip",
)
@app.post("/api/login")
async def login(request: Request):
body = await request.json()
+77 -9
View File
@@ -154,6 +154,7 @@ body { font-family: 'Inter', -apple-system, BlinkMacSystemFont, "Segoe UI", Robo
</div>
<script src="https://cdn.jsdelivr.net/npm/marked/marked.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/tus-js-client@4.3.1/dist/tus.min.js" integrity="sha384-UlHjK3F7TCQCEUpnoa1ohMbP2oaWB3Aypv4gMo511vaZ86uUZ0Zv7UzZ0J1zRUT1" crossorigin="anonymous"></script>
<script>
// Configure marked for safe rendering
if (typeof marked !== 'undefined') {
@@ -356,20 +357,87 @@ function renderFileList() {
}
function removeFile(i) { pendingFiles.splice(i, 1); renderFileList(); }
// Access token (24h) can expire mid-upload of a multi-GB file; refresh just
// before it lapses so long uploads don't 401 halfway through.
function jwtExpSoon() {
try {
const p = JSON.parse(atob(token.split('.')[1]));
return (p.exp * 1000) < (Date.now() + 120000);
} catch { return false; }
}
// Resumable upload of one file via the tus protocol. Survives network drops and
// page reloads (tus-js-client stores the upload URL and resumes from the offset
// the server already has). Resolves {name, ok, status}.
function uploadOne(file, onPct) {
return new Promise((resolve) => {
const upload = new tus.Upload(file, {
endpoint: API + '/api/tus',
chunkSize: 32 * 1024 * 1024,
retryDelays: [0, 3000, 5000, 10000, 20000],
removeFingerprintOnSuccess: true,
metadata: { filename: file.name, tab_id: tabId },
async onBeforeRequest(req) {
if (jwtExpSoon()) await tryRefreshToken();
req.setHeader('Authorization', 'Bearer ' + token);
req.setHeader('X-Tab-Id', tabId);
},
onShouldRetry(err) {
const s = err.originalResponse ? err.originalResponse.getStatus() : 0;
if (s === 401) return !!localStorage.getItem('refresh_token');
return s === 0 || s === 429 || s >= 500;
},
onProgress(sent, total) { onPct(Math.floor(sent / total * 100)); },
onSuccess() { resolve({ name: file.name, ok: true }); },
onError(error) {
const s = error.originalResponse ? error.originalResponse.getStatus() : 0;
if (s === 401) logout();
resolve({ name: file.name, ok: false, status: s });
},
});
upload.findPreviousUploads().then((prev) => {
if (prev.length) upload.resumeFromPreviousUpload(prev[0]);
upload.start();
});
});
}
async function uploadFiles() {
if (typeof tus === 'undefined') return uploadFilesLegacy(); // CDN blocked → degrade
const files = pendingFiles.slice();
const prog = files.map(f => ({ name: f.name, pct: 0 }));
const fl = document.getElementById('file-list');
const render = () => {
fl.innerHTML = '';
prog.forEach(p => {
const b = document.createElement('span');
b.className = 'file-badge';
b.textContent = `${p.name} — ${p.pct}%`;
fl.appendChild(b);
});
};
render();
const results = [];
for (let i = 0; i < files.length; i++) {
results.push(await uploadOne(files[i], (pct) => { prog[i].pct = pct; render(); }));
}
pendingFiles = [];
renderFileList();
const failed = results.filter(r => !r.ok);
if (failed.length && !failed.some(r => r.status === 401)) {
addMsg('error', 'Не загружены: ' + failed.map(r => r.name).join(', '));
}
return results.filter(r => r.ok).map(r => r.name);
}
// Fallback for when the tus client isn't available (e.g. CDN unreachable).
async function uploadFilesLegacy() {
const uploaded = [];
for (const f of pendingFiles) {
const fd = new FormData();
fd.append('file', f);
const r = await fetch(API + '/api/upload', {
method: 'POST',
headers: authHeaders(),
body: fd,
});
if (r.ok) {
const data = await r.json();
uploaded.push(data.filename);
}
const r = await authFetch(API + '/api/upload', { method: 'POST', body: fd });
if (r.ok) uploaded.push((await r.json()).filename);
}
pendingFiles = [];
renderFileList();
+195
View File
@@ -0,0 +1,195 @@
"""Resumable file uploads via the tus 1.0.0 protocol (self-contained core).
Streams chunks straight to disk (memory stays flat regardless of file size),
survives interruption and resumes from the server-known offset, isolates each
upload to its authenticated owner, and on completion moves the finished file
into the user's work dir — the same place the legacy /api/upload writes — so
the rest of the app keeps working unchanged.
Wired up from main.py via register_tus(); kept dependency-free (deps are passed
in) to avoid import cycles and stay unit-testable.
"""
import base64
import json
import os
import re
import secrets
import shutil
import time
from pathlib import Path
from fastapi import HTTPException, Request, Response
from starlette.requests import ClientDisconnect
TUS_VERSION = "1.0.0"
TUS_EXTENSIONS = "creation,termination"
_ID_RE = re.compile(r"^[A-Za-z0-9_-]{8,64}$")
_DISK_MARGIN = 1024 * 1024 * 1024 # refuse if it would leave < 1 GB free
_STALE_AGE = 24 * 3600 # sweep abandoned partial uploads untouched for this long
def _sweep_stale(staging: Path):
"""Drop partial uploads (data + sidecar) idle past _STALE_AGE. An in-flight
upload keeps writing, so its mtime stays fresh and it is never swept."""
cutoff = time.time() - _STALE_AGE
try:
entries = list(staging.iterdir())
except OSError:
return
for p in entries:
try:
if p.stat().st_mtime < cutoff:
p.unlink()
except OSError:
pass
def _parse_metadata(header: str) -> dict:
"""tus Upload-Metadata: comma-separated `key <base64value>` pairs."""
out = {}
for pair in (header or "").split(","):
pair = pair.strip()
if not pair:
continue
parts = pair.split(" ", 1)
if len(parts) == 2:
try:
out[parts[0]] = base64.b64decode(parts[1]).decode("utf-8")
except Exception:
out[parts[0]] = ""
else:
out[parts[0]] = ""
return out
def _safe_tab(tab_id: str) -> str:
"""Block path traversal via attacker-controlled tab_id metadata."""
tab_id = (tab_id or "").strip() or "default"
tab_id = re.sub(r"[^A-Za-z0-9_.-]", "_", tab_id)
return tab_id if tab_id.strip(".") else "default"
def register_tus(app, *, get_user, get_work_dir, is_allowed_file,
log_action, save_message, max_size, staging_root, allowed_hint):
staging = Path(staging_root)
staging.mkdir(parents=True, exist_ok=True)
def _data(uid): return staging / uid
def _meta(uid): return staging / f"{uid}.json"
def _headers(extra=None):
h = {"Tus-Resumable": TUS_VERSION}
if extra:
h.update(extra)
return h
def _load(uid: str, user: str) -> dict:
# Unknown id, bad id, or someone else's upload all look the same: 404.
if not _ID_RE.match(uid) or not _meta(uid).exists():
raise HTTPException(404, "Upload not found")
meta = json.loads(_meta(uid).read_text("utf-8"))
if meta.get("owner") != user:
raise HTTPException(404, "Upload not found")
return meta
async def options_collection(request: Request):
return Response(status_code=204, headers=_headers({
"Tus-Version": TUS_VERSION,
"Tus-Extension": TUS_EXTENSIONS,
"Tus-Max-Size": str(max_size),
}))
async def create(request: Request):
user = get_user(request)
_sweep_stale(staging)
raw_len = request.headers.get("upload-length")
if raw_len is None or not raw_len.isdigit() or int(raw_len) <= 0:
raise HTTPException(400, "Upload-Length required")
length = int(raw_len)
if length > max_size:
raise HTTPException(413, f"File too large (max {max_size // (1024 * 1024)}MB)")
if shutil.disk_usage(str(staging)).free < length + _DISK_MARGIN:
raise HTTPException(507, "Insufficient storage on server")
meta = _parse_metadata(request.headers.get("upload-metadata", ""))
filename = Path(meta.get("filename", "")).name
if not filename or filename.startswith("."):
raise HTTPException(400, "Invalid or missing filename metadata")
if not is_allowed_file(filename):
raise HTTPException(400, f"File type not allowed. Allowed: {allowed_hint}")
uid = secrets.token_urlsafe(16)
_data(uid).write_bytes(b"")
_meta(uid).write_text(json.dumps({
"owner": user,
"filename": filename,
"tab_id": _safe_tab(meta.get("tab_id")),
"length": length,
}), "utf-8")
return Response(status_code=201, headers=_headers({"Location": f"/api/tus/{uid}"}))
async def head(request: Request, uid: str):
user = get_user(request)
meta = _load(uid, user)
return Response(status_code=200, headers=_headers({
"Upload-Offset": str(_data(uid).stat().st_size),
"Upload-Length": str(meta["length"]),
"Cache-Control": "no-store",
}))
async def patch(request: Request, uid: str):
user = get_user(request)
meta = _load(uid, user)
if request.headers.get("content-type") != "application/offset+octet-stream":
raise HTTPException(415, "Content-Type must be application/offset+octet-stream")
raw_off = request.headers.get("upload-offset")
if raw_off is None or not raw_off.isdigit():
raise HTTPException(400, "Upload-Offset required")
dp = _data(uid)
offset = dp.stat().st_size
if int(raw_off) != offset:
raise HTTPException(409, "Offset conflict")
length = meta["length"]
try:
with open(dp, "ab") as f:
async for chunk in request.stream():
if not chunk:
continue
if offset + len(chunk) > length:
raise HTTPException(400, "Upload exceeds declared length")
f.write(chunk)
offset += len(chunk)
f.flush()
os.fsync(f.fileno())
except ClientDisconnect:
# Normal interruption: bytes flushed so far persist; next HEAD
# reports the real on-disk offset and the client resumes from there.
return Response(status_code=204, headers=_headers({
"Upload-Offset": str(dp.stat().st_size),
}))
if offset >= length:
_finalize(uid, meta, request)
return Response(status_code=204, headers=_headers({"Upload-Offset": str(offset)}))
def _finalize(uid: str, meta: dict, request: Request):
dest = Path(get_work_dir(meta["owner"], meta["tab_id"])) / meta["filename"]
shutil.move(str(_data(uid)), str(dest))
_meta(uid).unlink(missing_ok=True)
size = dest.stat().st_size
save_message(meta["owner"], meta["tab_id"], "system",
f"Загружен файл: {meta['filename']} ({size} байт)")
ip = request.client.host if request.client else None
log_action(meta["owner"], "upload", "POST", "/api/tus",
f"{meta['filename']} ({size}B) tab={meta['tab_id']}", ip, 200)
async def terminate(request: Request, uid: str):
user = get_user(request)
_load(uid, user) # owner check
_data(uid).unlink(missing_ok=True)
_meta(uid).unlink(missing_ok=True)
return Response(status_code=204, headers=_headers())
app.add_api_route("/api/tus", options_collection, methods=["OPTIONS"])
app.add_api_route("/api/tus", create, methods=["POST"])
app.add_api_route("/api/tus/{uid}", head, methods=["HEAD"])
app.add_api_route("/api/tus/{uid}", patch, methods=["PATCH"])
app.add_api_route("/api/tus/{uid}", terminate, methods=["DELETE"])