✨ feat: 整合 2.8.5 后端存储、安全与运行优化

* 禁用 OSS 非必需校验尾部,改用精确会话前缀逐对象清理
* 保护上传终态与分享事务,清理失败保留会话并支持安全重试
* 统一下载响应头,兼容旧下载器并防止文件名注入
* 限流改用单调时钟并限制 IP 记录,缓存模板与静态资源策略
* 统一 ORM 初始化与异常处理,新增查询索引及 SQLite 性能参数
* 固定 uvloop/httptools,统一 Docker keep-alive 与内存回收配置
* 同步版本与升级文档,补充 OSS、清理、缓存及数据库回归验证
This commit is contained in:
orion committed 2026-10-29 16:37:14 +08:00
1 parent b2a9aeddb3
commit 41519afb6a
29 files changed
+1033 -132

No files matched your search

+60 -30
View File
@@ -1,3 +1,5 @@
from functools import lru_cache
from pathlib import Path
# @Time : 2023/8/9 23:23
# @Author : Lan
# @File : main.py
@@ -16,7 +18,7 @@ from fastapi.responses import FileResponse, HTMLResponse, JSONResponse, PlainTex
from starlette.middleware.gzip import GZipMiddleware
from tortoise import Tortoise
from tortoise.contrib.fastapi import register_tortoise
from tortoise.contrib.fastapi import tortoise_exception_handlers
from apps.admin.views import admin_api
from apps.base.models import KeyValue
@@ -29,7 +31,7 @@ from core.config import (
is_runtime_initialized,
refresh_settings,
)
from core.database import db_startup_lock, get_db_config, init_db
from core.database import db_startup_lock, init_db
from core.logger import get_log_level_name, is_access_log_enabled, logger
from core.response import APIResponse
from core.settings import settings, BASE_DIR, DEFAULT_CONFIG
@@ -772,7 +774,7 @@ async def load_config():
ip_limit["login"].minutes = settings.loginMinute
ip_limit["login"].count = settings.loginCount
app = FastAPI(lifespan=lifespan, version=APP_VERSION)
app = FastAPI(lifespan=lifespan, version=APP_VERSION, exception_handlers=tortoise_exception_handlers())
app.add_middleware(GZipMiddleware, minimum_size=1024, compresslevel=6)
@@ -803,14 +805,6 @@ app.add_middleware(
allow_headers=["*"],
)
# 使用 register_tortoise 来添加异常处理器
register_tortoise(
app,
config=get_db_config(),
generate_schemas=False,
add_exception_handlers=True,
)
app.include_router(share_api)
app.include_router(chunk_api)
app.include_router(presign_api)
@@ -880,13 +874,60 @@ def resolve_theme_file(*parts: str):
return file_path
_HASHED_ASSET_RE = re.compile(
r"-[A-Za-z0-9_-]{8,}\.(?:js|mjs|css|map|woff2?|ttf|otf|eot|svg|png|jpe?g|gif|webp|avif|ico)$",
re.IGNORECASE,
)
_IMMUTABLE_ASSET_CACHE = "public, max-age=31536000, immutable"
_DEFAULT_ASSET_CACHE = "public, max-age=86400"
def _asset_cache_control(asset_path: str) -> str:
if _HASHED_ASSET_RE.search(asset_path):
return _IMMUTABLE_ASSET_CACHE
return _DEFAULT_ASSET_CACHE
@lru_cache(maxsize=8)
def _render_index_html(
template_path: str,
inode: int,
mtime_ns: int,
size: int,
title: str,
description: str,
keywords: str,
opacity: str,
background: str,
) -> str:
"""Render index.html once per (theme file version, site config) pair.
The stat fields keep the cache honest when a theme is replaced in place;
config values are part of the key so admin edits are visible immediately
without any cross-module invalidation hook.
"""
content = (
Path(template_path)
.read_text(encoding="utf-8")
.replace("{{title}}", html.escape(title))
.replace("{{description}}", html.escape(description))
.replace("{{keywords}}", html.escape(keywords))
.replace("{{opacity}}", html.escape(opacity))
.replace("{{background}}", html.escape(background))
.replace('"/assets/', '"/theme-assets/')
.replace('"assets/', '"/theme-assets/')
)
return re.sub(r'((?:theme-)?assets/[^"\']+\.(?:css|js|json|png))(["\'])', rf"\1?v={mtime_ns}\2", content)
@app.get("/theme-assets/{asset_path:path}", include_in_schema=False)
@app.get("/assets/{asset_path:path}", include_in_schema=False)
async def theme_asset(asset_path: str):
normalized_asset_path = asset_path.removeprefix("assets/")
return FileResponse(
resolve_theme_file("assets", normalized_asset_path),
headers={"Cache-Control": "public, max-age=31536000, immutable"},
headers={"Cache-Control": _asset_cache_control(normalized_asset_path)},
)
@@ -909,25 +950,14 @@ async def not_found_handler(request, exc=None):
async def index(request=None, exc=None):
if request is not None and request.url.path.startswith(("/assets/", "/theme-assets/")):
return PlainTextResponse("Not found", status_code=404)
theme_dir = resolve_theme_root()
index_file = resolve_theme_file("index.html")
asset_version = str(int(index_file.stat().st_mtime))
content = (
index_file.read_text(encoding="utf-8")
.replace("{{title}}", str(settings.name))
.replace("{{description}}", str(settings.description))
.replace("{{keywords}}", str(settings.keywords))
.replace("{{opacity}}", str(settings.opacity))
.replace('"/assets/', '"/theme-assets/')
.replace('"assets/', '"/theme-assets/')
.replace("{{background}}", str(settings.background))
)
content = re.sub(
r'((?:theme-)?assets/[^"\']+\.(?:css|js|json|png))(["\'])',
rf"\1?v={asset_version}\2",
content,
)
try:
stat = index_file.stat()
except OSError:
raise HTTPException(404, "资源不存在")
content = _render_index_html(str(index_file), stat.st_ino, stat.st_mtime_ns, stat.st_size,
str(settings.name), str(settings.description), str(settings.keywords),
str(settings.opacity), str(settings.background))
return HTMLResponse(
content=content,