FEAT: thêm nút bypass cho track strip để bypass không qua mastering panel

This commit is contained in:
2026-08-03 15:47:10 +07:00
parent 6f55d36085
commit a9da813cb1
28 changed files with 2076 additions and 233 deletions
+112 -10
View File
@@ -1,7 +1,16 @@
import asyncio
import ipaddress
import json
import socket
from urllib.parse import urlparse
import httpx
from fastapi import APIRouter, HTTPException
from fastapi import APIRouter, Depends, HTTPException
from pydantic import BaseModel
from typing import Optional, Any, Dict, List
from typing import Any, Dict
from app.api.v1.auth import get_current_user
from app.api.v1.user_config import _load_ai_configs, _get_default_providers
router = APIRouter()
@@ -10,17 +19,108 @@ class ProxyRequest(BaseModel):
headers: Dict[str, str] = {}
body: Dict[str, Any] = {}
import json
# Ranges that are never legitimate AI endpoints: cloud metadata + this host.
_BLOCKED_NETWORKS = [
ipaddress.ip_network("169.254.0.0/16"), # link-local / cloud metadata
ipaddress.ip_network("0.0.0.0/8"),
]
# Private ranges: only reachable when the target host is one the user has
# explicitly configured as an AI provider (e.g. local Ollama/LM Studio).
_PRIVATE_NETWORKS = [
ipaddress.ip_network("10.0.0.0/8"),
ipaddress.ip_network("172.16.0.0/12"),
ipaddress.ip_network("192.168.0.0/16"),
ipaddress.ip_network("127.0.0.0/8"),
ipaddress.ip_network("::1/128"),
ipaddress.ip_network("fc00::/7"), # ULA
]
_LOOPBACK_HOSTS = {"localhost", "127.0.0.1", "::1", "0.0.0.0"}
def _configured_ai_hosts(user_id: str) -> set:
"""Hosts the user has configured as AI providers (from saved config + defaults)."""
hosts = set()
configs = _load_ai_configs()
providers = configs.get(user_id) or _get_default_providers()
for p in providers:
base = (p.get("api_base_url") or "").strip()
if not base:
continue
try:
host = urlparse(base).hostname
if host:
hosts.add(host.lower())
except Exception:
continue
return hosts
async def _resolve_host_ips(hostname: str):
"""Resolve hostname to IPs (non-blocking). Returns list of ipaddress objects."""
loop = asyncio.get_event_loop()
try:
infos = await loop.run_in_executor(None, socket.getaddrinfo, hostname, None)
ips = []
for info in infos:
try:
ips.append(ipaddress.ip_address(info[4][0]))
except ValueError:
continue
return ips
except Exception:
return []
async def _validate_target_url(url: str, user_id: str):
parsed = urlparse(url)
if parsed.scheme not in ("http", "https"):
raise HTTPException(status_code=400, detail="URL chỉ hỗ trợ giao thức http/https")
if parsed.username or parsed.password:
raise HTTPException(status_code=400, detail="URL không được chứa thông tin đăng nhập")
hostname = (parsed.hostname or "").lower()
if not hostname:
raise HTTPException(status_code=400, detail="URL không hợp lệ")
allowed_hosts = _configured_ai_hosts(user_id)
# Hostname-level fast path for loopback hosts
if hostname in _LOOPBACK_HOSTS:
if hostname in allowed_hosts:
return
raise HTTPException(status_code=403, detail="Target nội bộ không nằm trong danh sách AI provider đã cấu hình")
# Try direct IP parse (hostname may itself be an IP)
try:
ip = ipaddress.ip_address(hostname)
ips = [ip]
except ValueError:
ips = await _resolve_host_ips(hostname)
if not ips:
raise HTTPException(status_code=502, detail="Không phân giải được hostname")
for ip in ips:
if any(ip in net for net in _BLOCKED_NETWORKS):
raise HTTPException(status_code=403, detail="Target bị chặn (metadata/link-local không được phép)")
if any(ip in net for net in _PRIVATE_NETWORKS):
if hostname in allowed_hosts:
continue
raise HTTPException(status_code=403, detail="Target IP nội bộ không nằm trong danh sách AI provider đã cấu hình")
@router.post("/proxy")
async def proxy_llm(req: ProxyRequest):
async def proxy_llm(req: ProxyRequest, current_user: dict = Depends(get_current_user)):
await _validate_target_url(req.url, current_user["user_id"])
# Never forward the app's own auth token upstream.
headers = {
k: v for k, v in req.headers.items()
if k.lower() not in ("host", "origin", "referer", "x-auth-token")
}
try:
async with httpx.AsyncClient(timeout=180.0) as client:
resp = await client.post(
req.url,
headers={k: v for k, v in req.headers.items() if k.lower() not in ('host', 'origin', 'referer')},
json=req.body
)
async with httpx.AsyncClient(timeout=180.0, follow_redirects=False) as client:
resp = await client.post(req.url, headers=headers, json=req.body)
raw = resp.text
try:
return resp.json()
@@ -36,5 +136,7 @@ async def proxy_llm(req: ProxyRequest):
if 'localhost' in req.url or '127.0.0.1' in req.url:
msg += "\nNếu app chạy trong Docker, localhost trỏ vào container, không ra host.\nHãy thay localhost bằng host.docker.internal hoặc IP bridge Docker (172.17.0.1)."
raise HTTPException(status_code=502, detail=msg)
except HTTPException:
raise
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
+69 -73
View File
@@ -8,12 +8,32 @@ from pydantic import BaseModel
from typing import Optional, List
import json
from app.config import settings
from app.api.v1.auth import get_current_user
from app.api.v1.auth import get_current_user, enforce_password_changed
from app.api.v1.projects import get_optional_user
from app.models.user import get_db_connection
router = APIRouter()
MAX_AUDIO_UPLOAD_BYTES = 1024 * 1024 * 1024 # 1 GB
def _safe_file_id(file_id: str) -> str:
"""Strip any path components from a client-supplied file id."""
if not file_id:
return ""
return os.path.basename(file_id.replace("\\", "/"))
def _resolve_storage_path(file_id: str) -> str:
"""Return the existing file path (processed first, then uploads) for a
sanitized file id, or '' when not found."""
fid = _safe_file_id(file_id)
if not fid:
return ""
for d in (settings.PROCESSED_DIR, settings.UPLOADS_DIR):
p = os.path.join(d, fid)
if os.path.isfile(p):
return p
return ""
class EditRequest(BaseModel):
file_id: str
cut_start_ms: Optional[float] = None
@@ -58,16 +78,32 @@ class PythonToolRequest(BaseModel):
@router.post("/upload")
async def upload_audio(file: UploadFile = File(...), current_user: Optional[dict] = Depends(get_optional_user)):
if current_user:
enforce_password_changed(current_user)
user_id = current_user["user_id"] if current_user else "anonymous"
ext = os.path.splitext(file.filename)[1]
ext = os.path.splitext(file.filename or "")[1]
if not ext:
ext = ".wav"
file_id = f"user_{user_id}_{uuid.uuid4()}{ext}"
file_path = os.path.join(settings.UPLOADS_DIR, file_id)
# Stream upload in chunks with a hard size cap (avoids loading a multi-GB
# WAV into RAM and bounds disk usage).
with open(file_path, "wb") as f:
content = await file.read()
f.write(content)
size = 0
while True:
chunk = await file.read(1024 * 1024)
if not chunk:
break
size += len(chunk)
if size > MAX_AUDIO_UPLOAD_BYTES:
f.close()
try:
os.remove(file_path)
except OSError:
pass
raise HTTPException(status_code=413, detail="File âm thanh quá lớn (giới hạn 1GB)")
f.write(chunk)
# Save original filename as sidecar metadata
import json
@@ -90,15 +126,12 @@ async def upload_audio(file: UploadFile = File(...), current_user: Optional[dict
@router.post("/edit")
async def edit_audio(req: EditRequest):
upload_path = os.path.join(settings.UPLOADS_DIR, req.file_id)
processed_path = os.path.join(settings.PROCESSED_DIR, req.file_id)
# Use uploaded file if it exists, or look in processed if it was already edited
if not os.path.exists(upload_path) and not os.path.exists(processed_path):
if not _resolve_storage_path(req.file_id):
raise HTTPException(status_code=404, detail="File not found")
from app.tasks.worker import edit_audio_task
task = edit_audio_task.delay(req.dict())
task = edit_audio_task.delay(req.model_dump())
return {
"task_id": task.id
@@ -106,15 +139,10 @@ async def edit_audio(req: EditRequest):
@router.get("/download/{file_id}")
async def download_audio(file_id: str):
processed_path = os.path.join(settings.PROCESSED_DIR, file_id)
upload_path = os.path.join(settings.UPLOADS_DIR, file_id)
if os.path.exists(processed_path):
return FileResponse(processed_path, media_type="audio/wav", filename=file_id)
elif os.path.exists(upload_path):
return FileResponse(upload_path, media_type="audio/wav", filename=file_id)
raise HTTPException(status_code=404, detail="File not found")
path = _resolve_storage_path(file_id)
if not path:
raise HTTPException(status_code=404, detail="File not found")
return FileResponse(path, media_type="audio/wav", filename=os.path.basename(path))
@router.get("/waveform/{file_id}")
async def get_waveform(file_id: str, num_peaks: int = Query(default=800, ge=50, le=4000)):
@@ -122,14 +150,8 @@ async def get_waveform(file_id: str, num_peaks: int = Query(default=800, ge=50,
API endpoint vẽ Peak Waveform đồng bộ (Week 2).
Trả về dữ liệu peak waveform cho hiển thị đồ thị sóng âm trên Frontend.
"""
upload_path = os.path.join(settings.UPLOADS_DIR, file_id)
processed_path = os.path.join(settings.PROCESSED_DIR, file_id)
if os.path.exists(processed_path):
file_path = processed_path
elif os.path.exists(upload_path):
file_path = upload_path
else:
file_path = _resolve_storage_path(file_id)
if not file_path:
raise HTTPException(status_code=404, detail="File not found")
from app.core.dsp_utils import generate_peak_waveform
@@ -140,14 +162,8 @@ async def get_waveform_rms(file_id: str, num_points: int = Query(default=800, ge
"""
API endpoint vẽ RMS Waveform (mượt hơn peak).
"""
upload_path = os.path.join(settings.UPLOADS_DIR, file_id)
processed_path = os.path.join(settings.PROCESSED_DIR, file_id)
if os.path.exists(processed_path):
file_path = processed_path
elif os.path.exists(upload_path):
file_path = upload_path
else:
file_path = _resolve_storage_path(file_id)
if not file_path:
raise HTTPException(status_code=404, detail="File not found")
from app.core.dsp_utils import generate_rms_waveform
@@ -159,26 +175,20 @@ async def analyze_audio_with_ai(req: AIAnalysisRequest):
API endpoint phân tích cấu trúc khuôn nhạc bằng AI (Week 4).
Gọi OpenAI Compatible API (DeepSeek/Ollama) để phân đoạn bố cục.
"""
upload_path = os.path.join(settings.UPLOADS_DIR, req.file_id)
processed_path = os.path.join(settings.PROCESSED_DIR, req.file_id)
if os.path.exists(processed_path):
file_path = processed_path
elif os.path.exists(upload_path):
file_path = upload_path
else:
file_path = _resolve_storage_path(req.file_id)
if not file_path:
raise HTTPException(status_code=404, detail="File not found")
from app.tasks.worker import analyze_ai_task
task = analyze_ai_task.delay(
file_id=req.file_id,
file_id=_safe_file_id(req.file_id),
api_base_url=req.api_base_url,
model=req.model
)
return {
"task_id": task.id,
"file_id": req.file_id
"file_id": _safe_file_id(req.file_id)
}
@router.post("/export")
@@ -186,19 +196,13 @@ async def export_audio(req: ExportRequest):
"""
API endpoint xuất tệp âm thanh sang nhiều định dạng (WAV/MP3/OGG).
"""
upload_path = os.path.join(settings.UPLOADS_DIR, req.file_id)
processed_path = os.path.join(settings.PROCESSED_DIR, req.file_id)
if os.path.exists(processed_path):
source_path = processed_path
elif os.path.exists(upload_path):
source_path = upload_path
else:
source_path = _resolve_storage_path(req.file_id)
if not source_path:
raise HTTPException(status_code=404, detail="File not found")
from app.tasks.worker import export_audio_task
task = export_audio_task.delay(
file_id=req.file_id,
file_id=_safe_file_id(req.file_id),
format=req.format,
sample_rate=req.sample_rate,
bit_depth=req.bit_depth
@@ -206,29 +210,24 @@ async def export_audio(req: ExportRequest):
return {
"task_id": task.id,
"file_id": req.file_id
"file_id": _safe_file_id(req.file_id)
}
@router.post("/ai-scan")
async def ai_scan_audio(req: AIScanRequest):
async def ai_scan_audio(req: AIScanRequest, current_user: Optional[dict] = Depends(get_optional_user)):
"""
17_AI_SCAN.md Feature 1: AI Loop Scan & Automated Marker Labeling.
Uses AIDSPEngine to find optimal recurring loop region with zero-crossing alignment.
"""
if current_user:
enforce_password_changed(current_user)
from app.core.ai_dsp_engine import AIDSPEngine
import soundfile as sf
import numpy as np
file_path = None
if req.file_id:
upload_path = os.path.join(settings.UPLOADS_DIR, req.file_id)
processed_path = os.path.join(settings.PROCESSED_DIR, req.file_id)
if os.path.exists(processed_path):
file_path = processed_path
elif os.path.exists(upload_path):
file_path = upload_path
file_path = _resolve_storage_path(req.file_id) if req.file_id else ""
if file_path and os.path.exists(file_path):
if file_path:
data, sr = sf.read(file_path)
if data.ndim > 1:
data = data.T
@@ -252,6 +251,8 @@ async def ai_cut_audio(req: AICutRequest, current_user: Optional[dict] = Depends
Executes raw binary sample slice at exact zero-crossing coordinates.
"""
user_id = current_user["user_id"] if current_user else "anonymous"
if current_user:
enforce_password_changed(current_user)
from app.core.ai_dsp_engine import AIDSPEngine
import soundfile as sf
import numpy as np
@@ -259,16 +260,9 @@ async def ai_cut_audio(req: AICutRequest, current_user: Optional[dict] = Depends
output_file_id = f"user_{user_id}_ai_cut_{uuid.uuid4().hex[:8]}.wav"
out_path = os.path.join(settings.PROCESSED_DIR, output_file_id)
file_path = None
if req.file_id:
upload_path = os.path.join(settings.UPLOADS_DIR, req.file_id)
processed_path = os.path.join(settings.PROCESSED_DIR, req.file_id)
if os.path.exists(processed_path):
file_path = processed_path
elif os.path.exists(upload_path):
file_path = upload_path
file_path = _resolve_storage_path(req.file_id) if req.file_id else ""
if file_path and os.path.exists(file_path):
if file_path:
data, sr = sf.read(file_path)
if data.ndim > 1:
data = data.T
@@ -295,6 +289,8 @@ async def run_python_dsp_tool(req: PythonToolRequest, current_user: Optional[dic
Handles normalize peak, invert phase, swap channels, zero-crossing align, and synth wave generation.
"""
user_id = current_user["user_id"] if current_user else "anonymous"
if current_user:
enforce_password_changed(current_user)
from app.core.python_tools_engine import PythonToolsEngine
from app.core.ai_dsp_engine import AIDSPEngine
import soundfile as sf
+79 -14
View File
@@ -1,10 +1,15 @@
import uuid
import time
from fastapi import APIRouter, HTTPException, Header, Depends
import threading
from fastapi import APIRouter, HTTPException, Header, Depends, Request, Response
from fastapi.responses import JSONResponse
from pydantic import BaseModel, EmailStr
from typing import Optional
from app.models.user import get_db_connection
from app.core.auth import hash_password, verify_password, create_token, decode_token, seed_admin
from app.core.auth import (
hash_password, verify_password, create_token, decode_token, seed_admin,
COOKIE_NAME, X_AUTH_HEADER,
)
router = APIRouter()
@@ -21,10 +26,49 @@ class ChangePasswordRequest(BaseModel):
old_password: str
new_password: str
def get_current_user(authorization: Optional[str] = Header(None)):
if not authorization or not authorization.startswith("Bearer "):
# ── Brute-force guard: in-memory per-IP failed-login limiter ──
_LOGIN_FAILURES = {} # ip -> [timestamps]
_LOGIN_LOCK = threading.Lock()
MAX_LOGIN_ATTEMPTS = 10
LOGIN_WINDOW_SEC = 900 # 15 min
LOGIN_BLOCK_SEC = 900
def _check_login_ratelimit(ip: str):
now = time.time()
with _LOGIN_LOCK:
stamps = [t for t in _LOGIN_FAILURES.get(ip, []) if now - t < LOGIN_WINDOW_SEC]
if len(stamps) >= MAX_LOGIN_ATTEMPTS:
raise HTTPException(status_code=429, detail="Quá nhiều lần đăng nhập thất bại. Vui lòng thử lại sau 15 phút.")
_LOGIN_FAILURES[ip] = stamps
def _record_login_failure(ip: str):
now = time.time()
with _LOGIN_LOCK:
stamps = _LOGIN_FAILURES.setdefault(ip, [])
stamps.append(now)
_LOGIN_FAILURES[ip] = [t for t in stamps if now - t < LOGIN_WINDOW_SEC]
def _record_login_success(ip: str):
with _LOGIN_LOCK:
_LOGIN_FAILURES.pop(ip, None)
def _set_auth_cookie(response: Response, token: str):
response.set_cookie(
COOKIE_NAME, token,
max_age=7 * 24 * 3600, httponly=True, samesite="lax",
# path="/" (default); secure flag set by proxy when behind TLS
)
def get_current_user(request: Request, authorization: Optional[str] = Header(None), x_auth_token: Optional[str] = Header(None)):
token = None
if authorization and authorization.startswith("Bearer "):
token = authorization.split(" ")[1]
elif x_auth_token:
token = x_auth_token
elif request.cookies.get(COOKIE_NAME):
token = request.cookies.get(COOKIE_NAME)
if not token:
raise HTTPException(status_code=401, detail="Thiếu Token xác thực hoặc Token không hợp lệ")
token = authorization.split(" ")[1]
payload = decode_token(token)
if not payload:
raise HTTPException(status_code=401, detail="Token đã hết hạn hoặc không hợp lệ")
@@ -39,7 +83,10 @@ def enforce_password_changed(user: dict):
)
@router.post("/login")
async def login(req: LoginRequest):
async def login(req: LoginRequest, request: Request):
client_ip = request.client.host if request.client else "unknown"
_check_login_ratelimit(client_ip)
conn = get_db_connection()
cursor = conn.cursor()
@@ -65,14 +112,17 @@ async def login(req: LoginRequest):
conn.close()
if not user or not user["is_active"]:
_record_login_failure(client_ip)
raise HTTPException(status_code=400, detail="Tài khoản hoặc mật khẩu không chính xác")
if not verify_password(password, user["hashed_password"]):
_record_login_failure(client_ip)
raise HTTPException(status_code=400, detail="Tài khoản hoặc mật khẩu không chính xác")
token = create_token(user["id"], user["username"], user["role"], user["must_change_password"])
return {
_record_login_success(client_ip)
resp = JSONResponse({
"access_token": token,
"user": {
"id": user["id"],
@@ -81,13 +131,24 @@ async def login(req: LoginRequest):
"role": user["role"],
"must_change_password": bool(user["must_change_password"])
}
}
})
_set_auth_cookie(resp, token)
return resp
def _validate_password_strength(password: str):
"""Minimal strength policy: >= 8 chars and not trivially common."""
if len(password) < 8:
raise HTTPException(status_code=400, detail="Mật khẩu phải có ít nhất 8 ký tự")
lowered = password.lower()
if lowered in ("admin123", "password", "12345678", "123456789", "qwerty123"):
raise HTTPException(status_code=400, detail="Mật khẩu quá dễ đoán, vui lòng chọn mật khẩu khác")
@router.post("/register")
async def register(req: RegisterRequest):
async def register(req: RegisterRequest, request: Request):
username = req.username.strip()
email = req.email.strip()
password = req.password.strip()
_validate_password_strength(password)
conn = get_db_connection()
cursor = conn.cursor()
@@ -115,7 +176,7 @@ async def register(req: RegisterRequest):
conn.close()
token = create_token(user_id, username, "standard", False)
return {
resp = JSONResponse({
"access_token": token,
"user": {
"id": user_id,
@@ -124,7 +185,9 @@ async def register(req: RegisterRequest):
"role": "standard",
"must_change_password": False
}
}
})
_set_auth_cookie(resp, token)
return resp
@router.post("/change-password")
async def change_password(req: ChangePasswordRequest, current_user: dict = Depends(get_current_user)):
@@ -153,10 +216,12 @@ async def change_password(req: ChangePasswordRequest, current_user: dict = Depen
conn.close()
new_token = create_token(updated_user["id"], updated_user["username"], updated_user["role"], False)
return {
resp = JSONResponse({
"message": "Đổi mật khẩu thành công!",
"access_token": new_token
}
})
_set_auth_cookie(resp, new_token)
return resp
@router.get("/profile")
async def get_profile(current_user: dict = Depends(get_current_user)):
+6 -4
View File
@@ -2,9 +2,11 @@ import os
import platform
from typing import List, Optional
from fastapi import APIRouter, HTTPException, Query
from fastapi import APIRouter, Depends, HTTPException, Query
from fastapi.responses import FileResponse
from app.api.v1.auth import get_current_user
router = APIRouter()
MEDIA_EXTS = {
@@ -39,7 +41,7 @@ PSEUDO_FS_TYPES = {
@router.get("/computer")
async def list_computer_roots():
async def list_computer_roots(current_user: dict = Depends(get_current_user)):
"""Liệt kê các ổ đĩa / mount point thật của máy (My Computer)."""
system = platform.system()
roots = []
@@ -97,7 +99,7 @@ async def list_computer_roots():
@router.get("/browse")
async def browse_directory(path: str = Query(...)):
async def browse_directory(path: str = Query(...), current_user: dict = Depends(get_current_user)):
"""Liệt kê nội dung một thư mục trên máy: thư mục con + file audio/MIDI."""
resolved = _safe_path(path)
if not os.path.isdir(resolved):
@@ -146,7 +148,7 @@ async def browse_directory(path: str = Query(...)):
@router.get("/file")
async def serve_local_file(path: str = Query(...)):
async def serve_local_file(path: str = Query(...), current_user: dict = Depends(get_current_user)):
"""Phục vụ file audio/MIDI cục bộ để preview."""
resolved = _safe_path(path)
if not os.path.isfile(resolved):
+2 -2
View File
@@ -54,7 +54,7 @@ async def mix_multitrack_session(req: MultitrackSessionRequest):
# Gửi task xuống Celery Worker
from app.tasks.worker import mix_multitrack_task
task = mix_multitrack_task.delay(req.dict())
task = mix_multitrack_task.delay(req.model_dump())
return {
"task_id": task.id,
@@ -69,7 +69,7 @@ async def process_session(req: MultitrackSessionRequest):
Xử lý từng clip, sau đó hòa âm tất cả tracks lại với nhau.
"""
from app.tasks.worker import process_multitrack_session_task
task = process_multitrack_session_task.delay(req.dict())
task = process_multitrack_session_task.delay(req.model_dump())
return {
"task_id": task.id,
+21 -4
View File
@@ -9,7 +9,7 @@ from app.core.render_engine import PythonRenderEngine
from app.core.soundfont_inspector import SoundFontInspector
from app.core.soundfont_converter import SoundFontConverter
from app.core.soundfont_scanner import SoundFontAutoScanner
from app.api.v1.auth import get_current_user
from app.api.v1.auth import get_current_user, enforce_password_changed
router = APIRouter()
@@ -79,11 +79,23 @@ async def upload_soundfont(
background_tasks: BackgroundTasks = None,
current_user: dict = Depends(get_current_user)
):
enforce_password_changed(current_user)
if not (file.filename and (file.filename.endswith(".sf2") or file.filename.endswith(".sf3"))):
raise HTTPException(status_code=400, detail="Only .sf2 / .sf3 files are allowed")
contents = await file.read()
if not PluginManager.validate_sf2_header(contents):
# Stream upload in chunks with a hard size cap (SGM-class fonts can exceed
# 500MB; reading the whole body into RAM would OOM the server).
MAX_SF_UPLOAD_BYTES = 2 * 1024 * 1024 * 1024 # 2 GB
contents = bytearray()
while True:
chunk = await file.read(1024 * 1024)
if not chunk:
break
contents.extend(chunk)
if len(contents) > MAX_SF_UPLOAD_BYTES:
raise HTTPException(status_code=413, detail="SoundFont quá lớn (giới hạn 2GB)")
if not PluginManager.validate_sf2_header(bytes(contents[:4096])):
raise HTTPException(status_code=400, detail="Invalid SoundFont file: missing RIFF/sfbk header")
file_ext = os.path.splitext(file.filename)[1]
@@ -178,8 +190,13 @@ async def render_project(
req: RenderRequest,
current_user: dict = Depends(get_current_user)
):
enforce_password_changed(current_user)
engine = PythonRenderEngine()
output_path = os.path.join(settings.PROCESSED_DIR, req.output_filename or "render_output.wav")
# Prevent path traversal: strip any directory components and force .wav.
safe_name = os.path.basename((req.output_filename or "render_output.wav").replace("\\", "/"))
if not safe_name.lower().endswith(".wav"):
safe_name += ".wav"
output_path = os.path.join(settings.PROCESSED_DIR, safe_name)
try:
result_path = engine.render_project(req.project_json, output_path)
return {"url": f"/static/audio/processed/{os.path.basename(result_path)}", "path": result_path}
+21 -4
View File
@@ -283,13 +283,30 @@ async def update_cloud_project(project_id: str, req: SaveProjectRequest, current
conn = get_db_connection()
cursor = conn.cursor()
cursor.execute("SELECT id FROM projects WHERE id = ? AND user_id = ? AND is_temp = 0", (project_id, user_id))
exists = cursor.fetchone()
if not exists:
cursor.execute("SELECT id, size_bytes FROM projects WHERE id = ? AND user_id = ? AND is_temp = 0", (project_id, user_id))
existing = cursor.fetchone()
if not existing:
conn.close()
raise HTTPException(status_code=404, detail="Không tìm thấy dự án để cập nhật")
new_size_bytes = len(validated_data_json.encode("utf-8"))
# Enforce storage quota (same rule as save_cloud_project — previously
# update bypassed the quota entirely).
cursor.execute("SELECT storage_limit_mb FROM user_quotas WHERE user_id = ?", (user_id,))
quota_row = cursor.fetchone()
storage_limit_mb = quota_row["storage_limit_mb"] if quota_row else 500
cursor.execute("SELECT SUM(size_bytes) as total_used FROM projects WHERE user_id = ? AND is_temp = 0", (user_id,))
used_row = cursor.fetchone()
used_bytes = (used_row["total_used"] if used_row and used_row["total_used"] else 0) - (existing["size_bytes"] or 0)
max_bytes = storage_limit_mb * 1024 * 1024
if used_bytes + new_size_bytes > max_bytes:
conn.close()
raise HTTPException(
status_code=400,
detail=f"Dung lượng dự án vượt quá hạn mức Quota ({storage_limit_mb}MB). Vui lòng dọn dẹp hoặc nâng cấp tài khoản."
)
now = time.time()
cursor.execute("""
+1 -1
View File
@@ -96,7 +96,7 @@ async def get_user_ai_config(authorization: Optional[str] = Header(None)):
async def save_user_ai_config(req: SaveAIConfigRequest, authorization: Optional[str] = Header(None)):
uid = _get_user_id(authorization)
configs = _load_ai_configs()
configs[uid] = [p.dict() for p in req.providers]
configs[uid] = [p.model_dump() for p in req.providers]
_save_all(ai_configs=configs)
return {
"success": True,