🔀 合并 FileCodeBox 2.5.4 安全更新

同步官方 2.5.4 的初始化、安全、容量控制与上传校验,并保留 2026 主题、动态资源缓存和管理后台统计能力。

- 使用原子领取和容量预留,补齐文件校验、限流、令牌轮换与路径防护
- 保留三主题构建、2026 静态资源隔离及 TransferStats 生命周期记录
- 已通过容器生产镜像构建、23 项安全与分享回归测试、Python 编译检查和 Dockerfile 检查
This commit is contained in:
orion committed 2026-08-07 09:09:42 +08:00
commit 0be5a31a59
121 files changed
+5302 -34718

No files matched your search

+130 -28
View File
@@ -1,16 +1,26 @@
import hashlib
import json
from pathlib import Path
import os
import time
import uuid
from datetime import datetime, timedelta
from typing import Any, Dict, List, Optional, Tuple
from core.response import APIResponse
from core.storage import FileStorageInterface, storages
from core.settings import settings
from core.settings import (
ADMIN_SESSION_EXPIRE_MAX,
ADMIN_SESSION_EXPIRE_MIN,
settings,
)
from core.config import refresh_settings
from core.security import INTERNAL_CONFIG_KEYS, generate_jwt_secret
from apps.base.models import FileCodes, KeyValue, TransferStats, file_codes_pydantic
from apps.base.utils import get_expire_info, get_file_path_name
from apps.base.quota import release_storage, reserve_storage
from fastapi import HTTPException
from core.settings import data_root
from core.utils import get_now, hash_password, is_password_hashed
@@ -594,8 +604,23 @@ class FileService:
remaining_downloads = (
max(file_code.expired_count, 0) if file_code.expired_count >= 0 else None
)
item = await file_codes_pydantic.from_tortoise_orm(file_code)
data = item.model_dump()
data = {
"id": file_code.id,
"code": file_code.code,
"prefix": file_code.prefix,
"suffix": file_code.suffix,
"uuid_file_name": file_code.uuid_file_name,
"file_path": file_code.file_path,
"size": file_code.size or 0,
"text": file_code.text,
"expired_at": file_code.expired_at,
"expired_count": file_code.expired_count,
"used_count": file_code.used_count,
"created_at": file_code.created_at,
"file_hash": file_code.file_hash,
"is_chunked": file_code.is_chunked,
"upload_id": file_code.upload_id,
}
data.update(
{
"name": name,
@@ -1512,25 +1537,36 @@ class FileService:
if not await local_file.exists():
raise HTTPException(status_code=404, detail="文件不存在")
text = await local_file.read()
expired_at, expired_count, used_count, code = await get_expire_info(
item.expire_value, item.expire_style
)
path, suffix, prefix, uuid_file_name, save_path = await get_file_path_name(item)
await self.file_storage.save_file(text, save_path)
await FileCodes.create(
code=code,
prefix=prefix,
suffix=suffix,
uuid_file_name=uuid_file_name,
file_path=path,
size=local_file.size,
expired_at=expired_at,
expired_count=expired_count,
used_count=used_count,
)
reservation_token = f"local:{uuid.uuid4().hex}"
await reserve_storage(reservation_token, local_file.size, ttl_seconds=3600)
try:
text = await local_file.read()
expired_at, expired_count, used_count, code = await get_expire_info(
item.expire_value, item.expire_style
)
path, suffix, prefix, uuid_file_name, save_path = await get_file_path_name(
item
)
await self.file_storage.save_file(text, save_path)
try:
await FileCodes.create(
code=code,
prefix=prefix,
suffix=suffix,
uuid_file_name=uuid_file_name,
file_path=path,
size=local_file.size,
expired_at=expired_at,
expired_count=expired_count,
used_count=used_count,
)
except Exception:
await self.file_storage.delete_file(
FileCodes(file_path=path, uuid_file_name=uuid_file_name)
)
raise
finally:
await release_storage(reservation_token)
return {
"code": code,
@@ -1540,9 +1576,12 @@ class FileService:
class ConfigService:
INT_FIELDS = {
"adminSessionExpire",
"enableChunk",
"errorCount",
"errorMinute",
"loginCount",
"loginMinute",
"max_save_seconds",
"onedrive_proxy",
"openUpload",
@@ -1551,6 +1590,7 @@ class ConfigService:
"serverPort",
"serverWorkers",
"showAdminAddr",
"storageLimit",
"uploadCount",
"uploadMinute",
"uploadSize",
@@ -1559,20 +1599,30 @@ class ConfigService:
FLOAT_FIELDS = {"opacity"}
def get_config(self):
return dict(settings.items())
config = dict(settings.items())
config["admin_token"] = ""
for key in INTERNAL_CONFIG_KEYS:
config.pop(key, None)
return config
async def update_config(self, data: dict):
current_config = dict(settings.items())
next_config = dict(current_config)
update_data = {
key: value for key, value in data.items() if key in settings.default_config
key: value
for key, value in data.items()
if key in settings.default_config and key not in INTERNAL_CONFIG_KEYS
}
admin_token = update_data.get("admin_token")
admin_password_changed = False
if admin_token is None or admin_token == "":
update_data.pop("admin_token", None)
elif not is_password_hashed(admin_token):
update_data["admin_token"] = hash_password(admin_token)
admin_password_changed = True
else:
admin_password_changed = True
for key, value in update_data.items():
if value == "" and key in self.INT_FIELDS | self.FLOAT_FIELDS:
@@ -1588,6 +1638,32 @@ class ConfigService:
except (TypeError, ValueError):
raise HTTPException(status_code=400, detail=f"{key} 配置值格式错误")
try:
session_expire = int(next_config.get("adminSessionExpire"))
except (TypeError, ValueError):
raise HTTPException(
status_code=400,
detail="adminSessionExpire 配置值格式错误",
)
if (
not ADMIN_SESSION_EXPIRE_MIN <= session_expire <= ADMIN_SESSION_EXPIRE_MAX
or session_expire % ADMIN_SESSION_EXPIRE_MIN != 0
):
raise HTTPException(
status_code=400,
detail="adminSessionExpire 必须是 1 到 365 个整天",
)
next_config["adminSessionExpire"] = session_expire
if int(next_config.get("storageLimit", 0)) < 0:
raise HTTPException(
status_code=400,
detail="storageLimit 不能小于 0",
)
if admin_password_changed:
next_config["jwt_secret"] = generate_jwt_secret()
await KeyValue.update_or_create(key="settings", defaults={"value": next_config})
await refresh_settings()
@@ -1616,9 +1692,35 @@ class LocalFileService:
class LocalFileClass:
def __init__(self, file):
self.file = file
self.path = data_root / "local" / file
if os.path.exists(self.path):
# 仅允许 data/local 目录下的单层文件名,阻断路径穿越与绝对路径访问。
raw_name = str(file or "")
normalized = Path(raw_name).as_posix()
# 输入本身不得包含路径分隔符或绝对路径形态。
if (
not raw_name
or raw_name in {".", ".."}
or normalized in {".", ".."}
or "/" in normalized
or normalized.startswith("~")
or Path(raw_name).is_absolute()
or Path(raw_name).name != raw_name
):
raise HTTPException(status_code=400, detail="非法文件名")
safe_name = Path(raw_name).name
if not safe_name or safe_name in {".", ".."}:
raise HTTPException(status_code=400, detail="非法文件名")
local_root = (data_root / "local").resolve()
candidate = (local_root / safe_name).resolve()
try:
candidate.relative_to(local_root)
except ValueError:
raise HTTPException(status_code=400, detail="非法文件路径")
self.file = safe_name
self.path = candidate
if self.path.is_file():
self.ctime = time.strftime(
"%Y-%m-%d %H:%M:%S", time.localtime(os.path.getctime(self.path))
)
@@ -1638,4 +1740,4 @@ class LocalFileClass:
os.remove(self.path)
async def exists(self):
return os.path.exists(self.path)
return self.path.is_file()