Compare commits

...
12 Commits
Author SHA1 Message Date
github-actions[bot] 287b647da1 chore(master): release 2.5.4 (#501)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2026-07-23 14:35:42 +00:00
Lan fbcd4a5b2b Merge pull request #500 from vastsa/fix/docker-run-as-root
fix: run Docker as root for volume compatibility
2026-07-23 22:35:20 +08:00
vastsa fc0cbeb4f0 fix: run Docker image as root for data volume compatibility
Revert the non-root container user so existing deployments with
root-owned data volumes keep working without a manual chown step.
2026-07-23 22:35:00 +08:00
github-actions[bot] 24bf6e1a81 chore(master): release 2.5.3 (#499)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2026-07-23 14:23:38 +00:00
Lan 0ee2f046dd Merge pull request #498 from vastsa/fix/security-hardening-gaps
fix: magic-byte file checks, admin login rate limit, non-root Docker
2026-07-23 22:23:11 +08:00
vastsa eda0a3127a fix: add magic-byte checks, login rate limits, and non-root Docker
Close the remaining security gaps: validate upload content against
file signatures, rate-limit admin login failures with configurable
thresholds, and run the container as uid 1000 instead of root.
2026-07-23 22:23:04 +08:00
github-actions[bot] c11059b851 chore(master): release 2.5.2 (#497)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2026-07-23 11:42:06 +00:00
Lan ae7702603a Merge pull request #496 from vastsa/fix/pr494-security-patches
fix: harden share expiry, download token, quota SQL, and CORS
2026-07-23 19:41:40 +08:00
vastsa a41693f90d fix: harden share expiry, download token, quota SQL, and CORS
Apply the useful security fixes from PR #494 with review corrections:
validate expire_style through a shared helper, accept previous download
token window, detect SQL dialect via Tortoise capabilities, close remote
download sessions on client abort, and disable invalid CORS credentials.
2026-07-23 19:38:50 +08:00
Lan 59ed733f3a support text direct downloads (#490)
## 合入说明

- 修复 `GET /share/select/` 文本分享直链错误走存储层导致“已删除/过期”的问题
- 文本分享返回 UTF-8 plain text 附件下载
- 补充回归测试,不影响现有文件下载与次数扣减逻辑

## 评估结论

有必要合入:master 仍复现该缺陷,改动小、无冲突、测试通过。
2026-07-21 14:52:36 +08:00
github-actions[bot] cf6d364c2b chore(master): release 2.5.1 (#492)
Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2026-07-21 06:49:57 +00:00
monlor f2277e1649 support text direct downloads 2026-07-15 15:12:24 +08:00
24 changed files with 641 additions and 59 deletions

No files matched your search

+1 -1
View File
@@ -1,3 +1,3 @@
{
".": "2.5.0"
".": "2.5.4"
}
+1 -1
View File
@@ -1 +1 @@
2.5.0
2.5.4
+2
View File
@@ -1518,6 +1518,8 @@ class ConfigService:
"enableChunk",
"errorCount",
"errorMinute",
"loginCount",
"loginMinute",
"max_save_seconds",
"onedrive_proxy",
"openUpload",
+4 -1
View File
@@ -38,6 +38,7 @@ from apps.admin.dependencies import (
)
from core.settings import settings
from core.utils import get_now, verify_password
from apps.base.utils import ip_limit
admin_api = APIRouter(
prefix="/admin", tags=["管理"], dependencies=[Depends(admin_required)]
@@ -53,8 +54,10 @@ def _pick_query_text(*values: Optional[str]) -> Optional[str]:
@admin_api.post("/login")
async def login(data: LoginData):
async def login(data: LoginData, ip: str = Depends(ip_limit["login"])):
# 登录失败计入 IP 频率限制,超过 loginCount/loginMinute 后暂时锁定
if not verify_password(data.password, settings.admin_token):
ip_limit["login"].add_ip(ip)
raise HTTPException(status_code=401, detail="密码错误")
expires_in = get_admin_session_expire_seconds()
+196
View File
@@ -0,0 +1,196 @@
"""文件类型校验:扩展名 / MIME 白名单 + magic bytes 防伪造。"""
from __future__ import annotations
from dataclasses import dataclass
from pathlib import Path
from typing import Optional
from fastapi import HTTPException, UploadFile
from fnmatch import fnmatchcase
from core.settings import settings
@dataclass(frozen=True)
class FileKind:
name: str
extensions: tuple[str, ...]
mimes: tuple[str, ...]
signatures: tuple[bytes, ...]
FILE_KINDS: tuple[FileKind, ...] = (
FileKind("png", (".png",), ("image/png",), (b"\x89PNG\r\n\x1a\n",)),
FileKind("jpg", (".jpg", ".jpeg"), ("image/jpeg",), (b"\xff\xd8\xff",)),
FileKind("gif", (".gif",), ("image/gif",), (b"GIF87a", b"GIF89a")),
FileKind("webp", (".webp",), ("image/webp",), ()),
FileKind("bmp", (".bmp",), ("image/bmp", "image/x-ms-bmp"), (b"BM",)),
FileKind("pdf", (".pdf",), ("application/pdf",), (b"%PDF",)),
FileKind(
"zip",
(".zip", ".docx", ".xlsx", ".pptx", ".apk", ".jar"),
(
"application/zip",
"application/x-zip-compressed",
"application/vnd.openxmlformats-officedocument.wordprocessingml.document",
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
"application/vnd.openxmlformats-officedocument.presentationml.presentation",
"application/java-archive",
"application/vnd.android.package-archive",
),
(b"PK\x03\x04", b"PK\x05\x06", b"PK\x07\x08"),
),
FileKind(
"rar",
(".rar",),
("application/x-rar-compressed", "application/vnd.rar"),
(b"Rar!\x1a\x07\x00", b"Rar!\x1a\x07\x01\x00"),
),
FileKind("7z", (".7z",), ("application/x-7z-compressed",), (b"7z\xbc\xaf'\x1c",)),
FileKind("gz", (".gz", ".tgz"), ("application/gzip", "application/x-gzip"), (b"\x1f\x8b",)),
FileKind(
"mp3",
(".mp3",),
("audio/mpeg",),
(b"ID3", b"\xff\xfb", b"\xff\xf3", b"\xff\xf2"),
),
FileKind("mp4", (".mp4", ".m4a", ".mov"), ("video/mp4", "audio/mp4", "video/quicktime"), ()),
FileKind(
"exe",
(".exe", ".dll", ".sys"),
("application/x-msdownload", "application/x-dosexec"),
(b"MZ",),
),
FileKind("elf", (".elf", ".so", ".o"), ("application/x-executable",), (b"\x7fELF",)),
)
KNOWN_EXTENSIONS = {ext for kind in FILE_KINDS for ext in kind.extensions}
def normalize_allowed_file_types() -> list[str]:
raw_value = settings.allowed_file_types
if isinstance(raw_value, str):
values = [item.strip() for item in raw_value.split(",")]
elif isinstance(raw_value, (list, tuple, set)):
values = [str(item).strip() for item in raw_value]
else:
values = []
normalized = [item.lower() for item in values if item]
return normalized or ["*"]
def _extension_of(file_name: str) -> str:
return Path(file_name or "").suffix.lower()
def _match_allow_rule(rule: str, file_name: str, content_type: str) -> bool:
if rule in {"*", "*/*"}:
return True
if "/" in rule:
return fnmatchcase(content_type, rule)
extension = rule if rule.startswith(".") else f".{rule}"
return file_name.endswith(extension)
def is_type_allowed(file_name: str, content_type: Optional[str] = None) -> bool:
allowed = normalize_allowed_file_types()
if any(rule in {"*", "*/*"} for rule in allowed):
return True
normalized_name = (file_name or "").strip().lower()
normalized_content_type = (content_type or "").strip().lower()
return any(
_match_allow_rule(rule, normalized_name, normalized_content_type)
for rule in allowed
)
def detect_file_kind(header: bytes) -> Optional[FileKind]:
if not header:
return None
if len(header) >= 12 and header.startswith(b"RIFF") and header[8:12] == b"WEBP":
return next(kind for kind in FILE_KINDS if kind.name == "webp")
if len(header) >= 12 and header[4:8] == b"ftyp":
return next(kind for kind in FILE_KINDS if kind.name == "mp4")
candidates: list[tuple[int, FileKind]] = []
for kind in FILE_KINDS:
for signature in kind.signatures:
if signature and header.startswith(signature):
candidates.append((len(signature), kind))
if not candidates:
return None
candidates.sort(key=lambda item: item[0], reverse=True)
return candidates[0][1]
def validate_file_type(file_name: str, content_type: Optional[str] = None) -> None:
if not is_type_allowed(file_name, content_type):
raise HTTPException(status_code=403, detail="不允许上传该类型文件")
def _kind_matches_ext(kind: FileKind, extension: str) -> bool:
return extension in kind.extensions
def _kind_matches_mime(kind: FileKind, mime: str) -> bool:
return mime in kind.mimes
def validate_file_magic(
file_name: str,
content_type: Optional[str],
header: Optional[bytes],
) -> None:
"""白名单通过后,用 magic bytes 防止扩展名 / MIME 伪造。"""
validate_file_type(file_name, content_type)
if not header:
return
claimed_ext = _extension_of(file_name)
claimed_mime = (content_type or "").strip().lower()
detected = detect_file_kind(header)
if claimed_ext in KNOWN_EXTENSIONS:
if detected is None or not _kind_matches_ext(detected, claimed_ext):
raise HTTPException(
status_code=403,
detail="文件内容与扩展名不匹配,疑似伪造类型",
)
if claimed_mime and any(claimed_mime in kind.mimes for kind in FILE_KINDS):
if detected is None or not _kind_matches_mime(detected, claimed_mime):
raise HTTPException(
status_code=403,
detail="文件内容与 Content-Type 不匹配,疑似伪造类型",
)
allowed = normalize_allowed_file_types()
if detected and not any(rule in {"*", "*/*"} for rule in allowed):
allowed_by_detected = any(
is_type_allowed(f"file{ext}", mime)
for ext in detected.extensions
for mime in (detected.mimes or (None,))
)
if not allowed_by_detected:
raise HTTPException(status_code=403, detail="不允许上传该类型文件")
async def read_upload_header(file: UploadFile, size: int = 64) -> bytes:
await file.seek(0)
header = await file.read(size)
await file.seek(0)
return header or b""
async def validate_upload_file(file: UploadFile) -> None:
header = await read_upload_header(file)
validate_file_magic(file.filename or "", file.content_type, header)
def validate_header_bytes(
file_name: str, content_type: Optional[str], header: bytes
) -> None:
validate_file_magic(file_name, content_type, header)
+43 -5
View File
@@ -8,6 +8,43 @@ from core.settings import settings
from core.utils import get_now
def _detect_sql_dialect() -> str:
"""识别当前默认连接的 SQL 方言。
优先使用 Tortoise capabilities.dialect;
回退到 db_config 中的 engine 路径字符串。
"""
conn = connections.get("default")
dialect = getattr(getattr(conn, "capabilities", None), "dialect", "") or ""
if dialect:
return dialect.lower()
try:
engine = str(connections.db_config.get("default", {}).get("engine", "")).lower()
except Exception:
engine = ""
if "postgres" in engine or "asyncpg" in engine or "psycopg" in engine:
return "postgres"
if "mysql" in engine:
return "mysql"
if "sqlite" in engine:
return "sqlite"
return "sqlite"
def _sql_placeholders(count: int) -> list[str]:
"""根据数据库方言生成参数占位符(多数据库兼容)。
SQLite 用 ?,PostgreSQL 用 $1/$2/...,MySQL 用 %s。
"""
dialect = _detect_sql_dialect()
if dialect in {"postgres", "postgresql"}:
return [f"${i}" for i in range(1, count + 1)]
if dialect == "mysql":
return ["%s"] * count
return ["?"] * count
def get_storage_limit() -> int:
try:
return max(0, int(getattr(settings, "storageLimit", 0)))
@@ -49,15 +86,16 @@ async def reserve_storage(token: str, size: int, ttl_seconds: int) -> None:
raise HTTPException(status_code=409, detail="上传容量预留信息不一致")
try:
ph = _sql_placeholders(6)
affected, _ = await conn.execute_query(
"""
f"""
INSERT INTO storagereservation (token, size, expires_at)
SELECT ?, ?, ?
SELECT {ph[0]}, {ph[1]}, {ph[2]}
WHERE (
COALESCE((SELECT SUM(size) FROM filecodes), 0)
+ COALESCE((SELECT SUM(size) FROM storagereservation WHERE expires_at > ?), 0)
+ ?
) <= ?
+ COALESCE((SELECT SUM(size) FROM storagereservation WHERE expires_at > {ph[3]}), 0)
+ {ph[4]}
) <= {ph[5]}
""",
[token, requested_size, expires_at, now, requested_size, limit],
)
+8
View File
@@ -19,6 +19,13 @@ from core.utils import (
)
def validate_expire_style(expire_style: str) -> str:
"""校验过期方式是否在管理员配置的白名单内。"""
if expire_style not in settings.expireStyle:
raise HTTPException(status_code=400, detail="过期时间类型错误")
return expire_style
async def get_file_path_name(file: UploadFile) -> Tuple[str, str, str, str, str]:
today = await get_now()
storage_path = settings.storage_path.strip("/")
@@ -129,4 +136,5 @@ ip_limit = {
"error": IPRateLimit(count=settings.errorCount, minutes=settings.errorMinute),
"metadata": IPRateLimit(count=settings.errorCount, minutes=settings.errorMinute),
"upload": IPRateLimit(count=settings.uploadCount, minutes=settings.uploadMinute),
"login": IPRateLimit(count=settings.loginCount, minutes=settings.loginMinute),
}
+29 -38
View File
@@ -1,16 +1,16 @@
import datetime
from fnmatch import fnmatchcase
import hashlib
import os
import uuid
from datetime import timedelta
from urllib.parse import unquote
from urllib.parse import quote, unquote
from typing import Optional, Tuple, Union
from fastapi import APIRouter, Form, Request, UploadFile, File, Depends, HTTPException
from pydantic import BaseModel, ValidationError
from starlette import status
from starlette.responses import Response
from tortoise.expressions import Case, F, Q, When
from apps.admin.dependencies import share_required_login
@@ -22,11 +22,13 @@ from apps.base.schemas import (
CompleteUploadModel,
PresignUploadInitRequest,
)
from apps.base.file_validation import validate_file_type, validate_upload_file, validate_header_bytes
from apps.base.utils import (
get_expire_info,
get_file_path_name,
ip_limit,
get_chunk_file_path_name,
validate_expire_style,
)
from core.response import APIResponse
from core.settings import settings
@@ -104,36 +106,6 @@ async def validate_file_size(file: UploadFile, max_size: int) -> int:
return size
def normalize_allowed_file_types() -> list[str]:
raw_value = settings.allowed_file_types
if isinstance(raw_value, str):
values = raw_value.replace(";", ",").split(",")
elif isinstance(raw_value, (list, tuple, set)):
values = raw_value
else:
values = []
allowed = [str(item).strip().lower() for item in values if str(item).strip()]
return allowed or ["*"]
def validate_file_type(file_name: str, content_type: Optional[str] = None) -> None:
allowed = normalize_allowed_file_types()
if "*" in allowed or "*/*" in allowed:
return
normalized_name = file_name.strip().lower()
normalized_content_type = (content_type or "").strip().lower()
for rule in allowed:
if "/" in rule and fnmatchcase(normalized_content_type, rule):
return
extension = rule if rule.startswith(".") else f".{rule}"
if normalized_name.endswith(extension):
return
raise HTTPException(status_code=403, detail="不允许上传该类型文件")
async def create_file_code(code, **kwargs):
@@ -151,6 +123,7 @@ async def share_text(
expire_style: str = Form(default="day"),
ip: str = Depends(ip_limit["upload"]),
):
validate_expire_style(expire_style)
text_size = len(text.encode("utf-8"))
max_txt_size = 222 * 1024
if text_size > max_txt_size:
@@ -185,9 +158,8 @@ async def share_file(
ip: str = Depends(ip_limit["upload"]),
):
file_size = await validate_file_size(file, settings.uploadSize)
validate_file_type(file.filename or "", file.content_type)
if expire_style not in settings.expireStyle:
raise HTTPException(status_code=400, detail="过期时间类型错误")
await validate_upload_file(file)
validate_expire_style(expire_style)
path, suffix, prefix, uuid_file_name, save_path = await get_file_path_name(file)
reservation_token = f"file:{uuid.uuid4().hex}"
await reserve_storage(reservation_token, file_size, ttl_seconds=3600)
@@ -334,6 +306,17 @@ async def get_code_file(code: str, ip: str = Depends(ip_limit["error"])):
assert isinstance(file_code, FileCodes)
if not await consume_file_usage(file_code):
return APIResponse(code=404, detail="文件已过期")
if file_code.text is not None:
filename = f"{file_code.prefix or 'Text'}{file_code.suffix or '.txt'}"
return Response(
content=file_code.text,
media_type="text/plain",
headers={
"Content-Disposition": (
f"attachment; filename*=UTF-8''{quote(filename, safe='')}"
)
},
)
return await file_storage.get_file_response(file_code)
@@ -362,7 +345,12 @@ async def select_file(data: SelectFileModel, ip: str = Depends(ip_limit["error"]
async def download_file(key: str, code: str, ip: str = Depends(ip_limit["error"])):
file_storage: FileStorageInterface = storages[settings.file_storage]()
normalized_code = normalize_share_code(code)
if await get_select_token(normalized_code) != key:
# 同时接受当前窗口与上一窗口 token,避免时间窗边界竞态导致偶发 403
valid_keys = {
await get_select_token(normalized_code, offset=0),
await get_select_token(normalized_code, offset=1),
}
if key not in valid_keys:
ip_limit["error"].add_ip(ip)
raise HTTPException(status_code=403, detail="下载鉴权失败")
has, file_code = await get_code_file_by_code(normalized_code)
@@ -531,6 +519,8 @@ async def upload_chunk(
# 读取分片数据并计算哈希
chunk_data = await chunk.read()
if chunk_index == 0:
validate_header_bytes(chunk_info.file_name, None, chunk_data[:64])
chunk_size = len(chunk_data)
# 校验分片大小不超过声明的 chunk_size
@@ -647,6 +637,7 @@ async def complete_upload(
chunk_info = await UploadChunk.filter(upload_id=upload_id, chunk_index=-1).first()
if not chunk_info:
raise HTTPException(status.HTTP_404_NOT_FOUND, detail="上传会话不存在")
validate_expire_style(data.expire_style)
await reserve_storage(
f"chunk:{upload_id}",
chunk_info.file_size,
@@ -763,8 +754,7 @@ async def presign_upload_init(
403,
f"文件大小超过限制,最大为 {settings.uploadSize / (1024 * 1024):.2f} MB",
)
if data.expire_style not in settings.expireStyle:
raise HTTPException(400, "过期时间类型错误")
validate_expire_style(data.expire_style)
upload_id = uuid.uuid4().hex
reservation_token = f"presign:{upload_id}"
@@ -826,6 +816,7 @@ async def presign_upload_proxy(
)
file_size = await validate_file_size(file, settings.uploadSize)
await validate_upload_file(file)
if abs(file_size - session.file_size) > 1024:
raise HTTPException(400, "文件大小与声明不符")
+4
View File
@@ -19,6 +19,8 @@ SETUP_CONFIG_FIELDS = {
"enableChunk",
"errorCount",
"errorMinute",
"loginCount",
"loginMinute",
"expireStyle",
"max_save_seconds",
"name",
@@ -68,6 +70,8 @@ def _sync_ip_limits() -> None:
ip_limit["metadata"].count = settings.errorCount
ip_limit["upload"].minutes = settings.uploadMinute
ip_limit["upload"].count = settings.uploadCount
ip_limit["login"].minutes = settings.loginMinute
ip_limit["login"].count = settings.loginCount
async def refresh_settings() -> None:
+2
View File
@@ -76,6 +76,8 @@ DEFAULT_CONFIG = {
"themesSelect": "themes/2024",
"errorMinute": 1,
"errorCount": 10,
"loginCount": 5,
"loginMinute": 15,
"serverWorkers": 1,
"serverHost": "0.0.0.0",
"serverPort": 12345,
+10 -3
View File
@@ -25,6 +25,7 @@ from core.settings import data_root, settings
from apps.base.models import FileCodes, UploadChunk
from core.utils import get_file_url, sanitize_filename
from fastapi.responses import FileResponse, StreamingResponse
from starlette.background import BackgroundTask
class FileStorageInterface:
@@ -395,7 +396,9 @@ class S3FileStorage(FileStorageInterface):
return StreamingResponse(
stream_generator(),
media_type="application/octet-stream",
headers=headers
headers=headers,
# 兜底关闭会话:客户端中断时与 generator finally 双保险
background=BackgroundTask(session.close),
)
except HTTPException:
raise
@@ -733,7 +736,9 @@ class OneDriveFileStorage(FileStorageInterface):
return StreamingResponse(
stream_generator(),
media_type="application/octet-stream",
headers=headers
headers=headers,
# 兜底关闭会话:客户端中断时与 generator finally 双保险
background=BackgroundTask(session.close),
)
except HTTPException:
raise
@@ -1209,7 +1214,9 @@ class WebDAVFileStorage(FileStorageInterface):
return StreamingResponse(
stream_generator(),
media_type="application/octet-stream",
headers=headers
headers=headers,
# 兜底关闭会话:客户端中断时与 generator finally 双保险
background=BackgroundTask(session.close),
)
except aiohttp.ClientError as e:
raise HTTPException(
+8 -3
View File
@@ -41,17 +41,22 @@ async def get_now():
return datetime.datetime.now(datetime.timezone(datetime.timedelta(hours=8)))
async def get_select_token(code: str):
async def get_select_token(code: str, offset: int = 0):
"""
获取下载token
:param code:
:param code: 取件码
:param offset: 时间窗口偏移(0=当前窗口,1=上一个窗口)。
用于兼容窗口边界竞态:用户在某窗口末尾获取的 token,
请求到达服务器时可能已进入下一窗口。
:return:
"""
token = getattr(settings, "jwt_secret", "")
if not token:
raise RuntimeError("应用签名密钥未初始化")
# 每个窗口约 1000 秒;offset 允许校验上一窗口,避免边界竞态
time_factor = int(time.time() / 1000) - max(0, int(offset))
return hashlib.sha256(
f"{code}{int(time.time() / 1000)}000{token}".encode()
f"{code}{time_factor}000{token}".encode()
).hexdigest()
+1 -1
View File
@@ -1,7 +1,7 @@
version: "3"
services:
file-code-box:
image: lanol/filecodebox:2.5.0 # x-release-please-version
image: lanol/filecodebox:2.5.4 # x-release-please-version
volumes:
- fcb-data:/app/data:rw
restart: unless-stopped
+31
View File
@@ -1,5 +1,36 @@
# Changelog
## [2.5.4](https://github.com/vastsa/FileCodeBox/compare/v2.5.3...v2.5.4) (2026-07-23)
### Bug Fixes
* run Docker as root for volume compatibility ([fbcd4a5](https://github.com/vastsa/FileCodeBox/commit/fbcd4a5b2b788cdfc8e86d920f9c5a7299dc839a))
* run Docker image as root for data volume compatibility ([fc0cbeb](https://github.com/vastsa/FileCodeBox/commit/fc0cbeb4f0c7485d2e7abc0501a5fd9b1456cc22))
## [2.5.3](https://github.com/vastsa/FileCodeBox/compare/v2.5.2...v2.5.3) (2026-07-23)
### Bug Fixes
* add magic-byte checks, login rate limits, and non-root Docker ([eda0a31](https://github.com/vastsa/FileCodeBox/commit/eda0a3127ab562b6a2cf828c0df4a93933c44526))
* magic-byte file checks, admin login rate limit, non-root Docker ([0ee2f04](https://github.com/vastsa/FileCodeBox/commit/0ee2f046dd057fecceaee1059d72d67de3038f19))
## [2.5.2](https://github.com/vastsa/FileCodeBox/compare/v2.5.1...v2.5.2) (2026-07-23)
### Bug Fixes
* harden share expiry, download token, quota SQL, and CORS ([ae77026](https://github.com/vastsa/FileCodeBox/commit/ae7702603a99dc77b9b48e78746058b2a74b0bf5))
* harden share expiry, download token, quota SQL, and CORS ([a41693f](https://github.com/vastsa/FileCodeBox/commit/a41693f90ded0234e0883c399254319bef04924a))
## [2.5.1](https://github.com/vastsa/FileCodeBox/compare/v2.5.0...v2.5.1) (2026-07-21)
### Bug Fixes
* patch CVE dependencies and path traversal risks ([00f3abd](https://github.com/vastsa/FileCodeBox/commit/00f3abd3b20fe2344e4dbf8d53714773e23a1050))
## [2.5.0](https://github.com/vastsa/FileCodeBox/compare/v2.4.0...v2.5.0) (2026-07-11)
+1 -1
View File
@@ -1,6 +1,6 @@
## [Unreleased]
<!-- Current release: 2.5.0 x-release-please-version -->
<!-- Current release: 2.5.4 x-release-please-version -->
### Added
+1 -1
View File
@@ -38,7 +38,7 @@ docker run -d --restart unless-stopped \
-p 12345:12345 \
-v ./data:/app/data \
--name filecodebox \
lanol/filecodebox:2.5.0 # x-release-please-version
lanol/filecodebox:2.5.4 # x-release-please-version
```
Open `http://localhost:12345` and complete the first-run setup.
+1 -1
View File
@@ -38,7 +38,7 @@ docker run -d --restart unless-stopped \
-p 12345:12345 \
-v ./data:/app/data \
--name filecodebox \
lanol/filecodebox:2.5.0 # x-release-please-version
lanol/filecodebox:2.5.4 # x-release-please-version
```
打开 `http://localhost:12345`,按引导完成首次初始化。
+23 -1
View File
@@ -181,6 +181,12 @@ def parse_setup_options(data: dict) -> dict:
"errorMinute": parse_int_field(
data, "errorMinute", DEFAULT_CONFIG["errorMinute"], "取件错误检测窗口", 1
),
"loginCount": parse_int_field(
data, "loginCount", DEFAULT_CONFIG["loginCount"], "登录失败次数限制", 1
),
"loginMinute": parse_int_field(
data, "loginMinute", DEFAULT_CONFIG["loginMinute"], "登录失败检测窗口", 1
),
"expireStyle": expire_styles,
"max_save_seconds": save_time_value * SAVE_TIME_UNITS[save_time_unit],
"openUpload": int(normalize_bool_field(data, "openUpload", True)),
@@ -228,6 +234,12 @@ def build_setup_page(error: str = "", form: dict | None = None) -> str:
error_count = html.escape(
get_form_value(form, "errorCount", str(DEFAULT_CONFIG["errorCount"]))
)
login_minute = html.escape(
get_form_value(form, "loginMinute", str(DEFAULT_CONFIG["loginMinute"]))
)
login_count = html.escape(
get_form_value(form, "loginCount", str(DEFAULT_CONFIG["loginCount"]))
)
open_upload_checked = (
" checked" if normalize_bool_field(form, "openUpload", True) else ""
)
@@ -576,6 +588,12 @@ def build_setup_page(error: str = "", form: dict | None = None) -> str:
<input name="errorMinute" type="number" min="1" value="{error_minute}" aria-label="取件错误检测窗口分钟" required>
</div>
<label for="loginCount">管理员登录失败频率 <span class="compact-help">次数 / 分钟</span></label>
<div class="row">
<input id="loginCount" name="loginCount" type="number" min="1" value="{login_count}" required>
<input name="loginMinute" type="number" min="1" value="{login_minute}" aria-label="登录失败检测窗口分钟" required>
</div>
<label for="save_time_value">最长保存时间</label>
<div class="row">
<input id="save_time_value" name="save_time_value" type="number" min="0" value="{save_time_value}" required>
@@ -744,6 +762,8 @@ async def load_config():
ip_limit["error"].count = settings.errorCount
ip_limit["upload"].minutes = settings.uploadMinute
ip_limit["upload"].count = settings.uploadCount
ip_limit["login"].minutes = settings.loginMinute
ip_limit["login"].count = settings.loginCount
app = FastAPI(lifespan=lifespan, version=APP_VERSION)
@@ -767,7 +787,9 @@ async def refresh_settings_middleware(request, call_next):
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
# 前端使用 Bearer Token,不依赖 Cookie credentials。
# allow_origins=["*"] 与 allow_credentials=True 组合不符合 CORS 规范。
allow_credentials=False,
allow_methods=["*"],
allow_headers=["*"],
)
+1 -1
View File
@@ -24,7 +24,7 @@
## 一条命令开始
```bash
docker run -d --restart unless-stopped -p 12345:12345 -v ./data:/app/data --name filecodebox lanol/filecodebox:2.5.0 # x-release-please-version
docker run -d --restart unless-stopped -p 12345:12345 -v ./data:/app/data --name filecodebox lanol/filecodebox:2.5.4 # x-release-please-version
```
访问 `http://localhost:12345`,完成首次初始化。生产环境建议固定版本号;`latest` 指向最新正式版。
+1 -1
View File
@@ -24,7 +24,7 @@ A lightweight, modern, self-hosted file sharing service. No account required—u
## Start with one command
```bash
docker run -d --restart unless-stopped -p 12345:12345 -v ./data:/app/data --name filecodebox lanol/filecodebox:2.5.0 # x-release-please-version
docker run -d --restart unless-stopped -p 12345:12345 -v ./data:/app/data --name filecodebox lanol/filecodebox:2.5.4 # x-release-please-version
```
Open `http://localhost:12345` and complete first-run setup. Pin a version in production; `latest` tracks the newest stable release.
+4
View File
@@ -73,6 +73,8 @@ class SetupOptionTests(unittest.TestCase):
"uploadMinute": "2",
"errorCount": "5",
"errorMinute": "1",
"loginCount": "4",
"loginMinute": "20",
"openUpload": ["0", "1"],
"enableChunk": "0",
"code_generate_type": "secret",
@@ -87,6 +89,8 @@ class SetupOptionTests(unittest.TestCase):
self.assertEqual(options["uploadMinute"], 2)
self.assertEqual(options["errorCount"], 5)
self.assertEqual(options["errorMinute"], 1)
self.assertEqual(options["loginCount"], 4)
self.assertEqual(options["loginMinute"], 20)
self.assertEqual(options["openUpload"], 1)
self.assertEqual(options["enableChunk"], 0)
self.assertEqual(options["code_generate_type"], "secret")
+25
View File
@@ -71,6 +71,7 @@ class ShareUsageSecurityTests(unittest.TestCase):
await self._assert_count_consumption_is_atomic()
await self._assert_time_expiration_and_usage_are_atomic()
await self._assert_download_url_is_single_use()
await self._assert_text_share_downloads_as_txt()
await self._assert_limited_files_do_not_expose_direct_urls()
await self._assert_metadata_counts_all_attempts()
finally:
@@ -156,6 +157,30 @@ class ShareUsageSecurityTests(unittest.TestCase):
self.assertEqual(record.expired_count, 0)
self.assertEqual(record.used_count, 1)
async def _assert_text_share_downloads_as_txt(self):
record = await FileCodes.create(
code="text-download",
prefix="TAG",
text="hello, 文本直链",
expired_count=-1,
expired_at=None,
)
with patch.dict(views.storages, {"local": FakeStorage}):
response = await views.get_code_file(
code=record.code, ip="127.0.0.1"
)
self.assertEqual(response.status_code, 200)
self.assertEqual(response.body.decode("utf-8"), record.text)
self.assertEqual(response.media_type, "text/plain")
self.assertEqual(
response.headers["content-disposition"],
"attachment; filename*=UTF-8''TAG.txt",
)
await record.refresh_from_db()
self.assertEqual(record.used_count, 1)
async def _assert_limited_files_do_not_expose_direct_urls(self):
record = await FileCodes.create(
code="proxy-only",
+141
View File
@@ -0,0 +1,141 @@
import asyncio
import hashlib
import time
import unittest
from unittest.mock import patch
from fastapi import HTTPException
from tortoise import Tortoise
from apps.base import views
from apps.base.models import FileCodes
from apps.base.quota import _detect_sql_dialect, _sql_placeholders, reserve_storage
from apps.base.utils import validate_expire_style
from core.settings import settings
from core.utils import get_select_token
class FakeStorage:
async def get_file_url(self, file_code):
return f"https://example.invalid/{file_code.code}"
async def get_file_response(self, file_code):
return {"downloaded": file_code.code}
class SecurityPatchTests(unittest.TestCase):
def test_validate_expire_style_rejects_unknown_mode(self):
original = dict(settings.user_config)
try:
settings.expireStyle = ["day", "count"]
self.assertEqual(validate_expire_style("day"), "day")
with self.assertRaises(HTTPException) as ctx:
validate_expire_style("forever")
self.assertEqual(ctx.exception.status_code, 400)
finally:
settings.user_config = original
def test_sql_placeholders_follow_dialect(self):
asyncio.run(self._assert_sql_placeholders())
async def _assert_sql_placeholders(self):
await Tortoise.init(
config={
"connections": {
"default": {
"engine": "tortoise.backends.sqlite",
"credentials": {"file_path": ":memory:"},
}
},
"apps": {
"models": {
"models": ["apps.base.models"],
"default_connection": "default",
}
},
"use_tz": False,
"timezone": "Asia/Shanghai",
}
)
try:
self.assertEqual(_detect_sql_dialect(), "sqlite")
self.assertEqual(_sql_placeholders(3), ["?", "?", "?"])
with patch(
"apps.base.quota._detect_sql_dialect", return_value="postgres"
):
self.assertEqual(_sql_placeholders(3), ["$1", "$2", "$3"])
with patch("apps.base.quota._detect_sql_dialect", return_value="mysql"):
self.assertEqual(_sql_placeholders(2), ["%s", "%s"])
# sqlite 下 reserve_storage 仍可正常工作
settings.storageLimit = 100
await Tortoise.generate_schemas()
await reserve_storage("patch-token", 10, 300)
finally:
settings.storageLimit = 0
await Tortoise.close_connections()
def test_download_token_accepts_previous_window(self):
asyncio.run(self._assert_download_token_window())
async def _assert_download_token_window(self):
original = dict(settings.user_config)
settings.jwt_secret = "test-secret-key-for-token-window"
now = 2_000_500 # 落在窗口 2000 内
code = "ABCDE"
with patch("core.utils.time.time", return_value=now):
current = await get_select_token(code, offset=0)
previous = await get_select_token(code, offset=1)
expected_current = hashlib.sha256(
f"{code}{int(now / 1000)}000{settings.jwt_secret}".encode()
).hexdigest()
expected_previous = hashlib.sha256(
f"{code}{int(now / 1000) - 1}000{settings.jwt_secret}".encode()
).hexdigest()
self.assertEqual(current, expected_current)
self.assertEqual(previous, expected_previous)
await Tortoise.init(
config={
"connections": {
"default": {
"engine": "tortoise.backends.sqlite",
"credentials": {"file_path": ":memory:"},
}
},
"apps": {
"models": {
"models": ["apps.base.models"],
"default_connection": "default",
}
},
"use_tz": False,
"timezone": "Asia/Shanghai",
}
)
await Tortoise.generate_schemas()
try:
await FileCodes.create(
code=code,
prefix="demo",
suffix=".txt",
expired_count=-1,
size=1,
)
# 模拟请求进入下一窗口,但仍携带上一窗口 token
next_window = now + 1000
with patch("core.utils.time.time", return_value=next_window):
with patch.dict(views.storages, {"local": FakeStorage}):
result = await views.download_file(
key=current, code=code, ip="127.0.0.1"
)
self.assertEqual(result, {"downloaded": code})
finally:
settings.user_config = original
await Tortoise.close_connections()
if __name__ == "__main__":
unittest.main()
+103
View File
@@ -0,0 +1,103 @@
import asyncio
import unittest
from pathlib import Path
from fastapi import HTTPException
from apps.admin import views as admin_views
from apps.admin.schemas import LoginData
from apps.base.dependencies import IPRateLimit
from apps.base.file_validation import detect_file_kind, validate_file_magic, validate_file_type
from apps.base.utils import ip_limit
from core.settings import settings
from core.utils import hash_password
class SettingsOverrideMixin:
def setUp(self):
self._original_user_config = dict(settings.user_config)
def tearDown(self):
settings.user_config = self._original_user_config
class MagicBytesTests(SettingsOverrideMixin, unittest.TestCase):
def test_detects_common_signatures(self):
self.assertEqual(detect_file_kind(b"\x89PNG\r\n\x1a\nxxxx").name, "png")
self.assertEqual(detect_file_kind(b"\xff\xd8\xff\xe0xxxx").name, "jpg")
self.assertEqual(detect_file_kind(b"%PDF-1.7").name, "pdf")
self.assertEqual(detect_file_kind(b"PK\x03\x04xxxx").name, "zip")
self.assertEqual(detect_file_kind(b"RIFF\x00\x00\x00\x00WEBPxxxx").name, "webp")
self.assertEqual(detect_file_kind(b"\x00\x00\x00\x18ftypmp42").name, "mp4")
def test_rejects_extension_spoofing(self):
settings.allowed_file_types = ["*"]
with self.assertRaises(HTTPException) as ctx:
validate_file_magic("photo.png", "image/png", b"MZ" + b"\x00" * 20)
self.assertEqual(ctx.exception.status_code, 403)
self.assertIn("扩展名", ctx.exception.detail)
def test_rejects_content_type_spoofing(self):
settings.allowed_file_types = ["*"]
with self.assertRaises(HTTPException) as ctx:
validate_file_magic("blob.bin", "image/png", b"MZ" + b"\x00" * 20)
self.assertEqual(ctx.exception.status_code, 403)
def test_accepts_matching_png(self):
settings.allowed_file_types = [".png", "image/*"]
validate_file_magic("a.png", "image/png", b"\x89PNG\r\n\x1a\nxxxx")
def test_whitelist_still_enforced(self):
settings.allowed_file_types = [".png"]
with self.assertRaises(HTTPException):
validate_file_type("a.exe", "application/x-msdownload")
class LoginRateLimitTests(SettingsOverrideMixin, unittest.TestCase):
def setUp(self):
super().setUp()
settings.admin_token = hash_password("correct-password-123")
settings.jwt_secret = "j" * 48
settings.loginCount = 3
settings.loginMinute = 15
self._original_login_limiter = ip_limit["login"]
ip_limit["login"] = IPRateLimit(count=3, minutes=15)
def tearDown(self):
ip_limit["login"] = self._original_login_limiter
super().tearDown()
def test_failed_logins_are_rate_limited(self):
async def attempt(password: str):
return await admin_views.login(
data=LoginData(password=password), ip="203.0.113.10"
)
for _ in range(3):
with self.assertRaises(HTTPException) as ctx:
asyncio.run(attempt("wrong-password"))
self.assertEqual(ctx.exception.status_code, 401)
self.assertFalse(ip_limit["login"].check_ip("203.0.113.10"))
def test_successful_login_does_not_consume_failure_quota(self):
result = asyncio.run(
admin_views.login(
data=LoginData(password="correct-password-123"), ip="198.51.100.8"
)
)
self.assertIn("token", result.detail)
self.assertTrue(ip_limit["login"].check_ip("198.51.100.8"))
class DockerRuntimeUserTests(unittest.TestCase):
def test_dockerfile_defaults_to_root_for_volume_compatibility(self):
# 默认 root:兼容已有 data 卷权限;如需非 root 可由编排层自行指定 user
text = Path("Dockerfile").read_text()
self.assertNotIn("USER appuser", text)
compose = Path("docker-compose.yml").read_text()
self.assertNotIn('user: "1000:1000"', compose)
if __name__ == "__main__":
unittest.main()