Compare commits

..
Author SHA1 Message Date
Lan cdaf3638b8 feat: add first-run setup security flow 2026-06-16 00:49:43 +08:00
Lan 1b6d8e7277 fix: harden share rate limit and code generation (#479) 2026-06-09 00:53:11 +08:00
31 changed files with 1215 additions and 1604 deletions

No files matched your search

+9 -4
View File
@@ -12,6 +12,13 @@ from core.settings import settings
from apps.admin.services import FileService, ConfigService, LocalFileService
def _get_jwt_secret() -> bytes:
secret = getattr(settings, "jwt_secret", "")
if not secret:
raise RuntimeError("JWT签名密钥未初始化")
return secret.encode()
def create_token(data: dict, expires_in: int = 3600 * 24 * 30) -> str:
"""
创建JWT token
@@ -25,9 +32,7 @@ def create_token(data: dict, expires_in: int = 3600 * 24 * 30) -> str:
json.dumps({**data, "exp": int(time.time()) + expires_in}).encode()
).decode()
signature = hmac.new(
settings.admin_token.encode(), f"{header}.{payload}".encode(), "sha256"
).digest()
signature = hmac.new(_get_jwt_secret(), f"{header}.{payload}".encode(), "sha256").digest()
signature = base64.b64encode(signature).decode()
return f"{header}.{payload}.{signature}"
@@ -44,7 +49,7 @@ def verify_token(token: str) -> dict:
# 验证签名
expected_signature = hmac.new(
settings.admin_token.encode(),
_get_jwt_secret(),
f"{header_b64}.{payload_b64}".encode(),
"sha256",
).digest()
+16 -2
View File
@@ -8,6 +8,7 @@ from core.response import APIResponse
from core.storage import FileStorageInterface, storages
from core.settings import settings
from core.config import refresh_settings
from core.security import INTERNAL_CONFIG_KEYS, generate_jwt_secret
from apps.base.models import FileCodes, KeyValue
from apps.base.utils import get_expire_info, get_file_path_name
from fastapi import HTTPException
@@ -1514,20 +1515,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:
@@ -1543,6 +1554,9 @@ class ConfigService:
except (TypeError, ValueError):
raise HTTPException(status_code=400, detail=f"{key} 配置值格式错误")
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()
+64 -6
View File
@@ -1,7 +1,69 @@
from typing import Dict, Union
from ipaddress import ip_address, ip_network
from typing import Dict, Iterable, Union
from datetime import datetime, timedelta
from fastapi import HTTPException, Request
from core.settings import settings
def _iter_trusted_proxies() -> Iterable[str]:
trusted_proxies = getattr(settings, "trustedProxies", [])
if isinstance(trusted_proxies, str):
trusted_proxies = [item.strip() for item in trusted_proxies.split(",")]
return [item for item in trusted_proxies if item]
def _is_trusted_proxy(host: str) -> bool:
try:
remote_addr = ip_address(host)
except ValueError:
return False
for proxy in _iter_trusted_proxies():
try:
if remote_addr in ip_network(proxy, strict=False):
return True
except ValueError:
continue
return False
def _get_forwarded_for_ip(header_value: str, fallback_ip: str) -> str:
forwarded_chain = [
item.strip() for item in header_value.split(",") if item.strip()
]
if not forwarded_chain:
return fallback_ip
for candidate in reversed(forwarded_chain):
try:
ip_address(candidate)
except ValueError:
return fallback_ip
if not _is_trusted_proxy(candidate):
return candidate
return forwarded_chain[0]
def get_client_ip(request: Request) -> str:
client_host = request.client.host if request.client else "unknown"
if not _is_trusted_proxy(client_host):
return client_host
forwarded_for = request.headers.get("X-Forwarded-For")
if forwarded_for:
return _get_forwarded_for_ip(forwarded_for, client_host)
real_ip = request.headers.get("X-Real-IP")
if real_ip:
try:
ip_address(real_ip)
except ValueError:
return client_host
return real_ip
return client_host
class IPRateLimit:
def __init__(self, count: int, minutes: int):
@@ -35,11 +97,7 @@ class IPRateLimit:
}
def __call__(self, request: Request) -> str:
ip = (
request.headers.get("X-Real-IP")
or request.headers.get("X-Forwarded-For")
or request.client.host
)
ip = get_client_ip(request)
if not self.check_ip(ip):
raise HTTPException(status_code=423, detail="请求次数过多,请稍后再试")
return ip
+19 -4
View File
@@ -76,8 +76,6 @@ async def get_expire_info(
expired_at, extra = result
if expire_style == "count":
expired_count = extra
elif expire_style == "forever":
code = await get_random_code(style="string")
else:
expired_at = result
if expired_at and expired_at - now > max_timedelta:
@@ -91,9 +89,26 @@ async def get_expire_info(
return expired_at, expired_count, used_count, code
async def get_random_code(style: str = "num") -> str:
def get_code_generate_type() -> str:
code_generate_type = getattr(settings, "code_generate_type", "number")
if code_generate_type in {"secret", "string"}:
return "secret"
return "number"
async def get_random_code(style: str | None = None) -> str:
code_style = style or get_code_generate_type()
if code_style == "num":
code_style = "number"
if code_style == "string":
code_style = "secret"
while True:
code = await get_random_num() if style == "num" else await get_random_string()
code = (
await get_random_num()
if code_style == "number"
else await get_random_string()
)
if not await FileCodes.filter(code=code).exists():
return str(code)
+94 -1
View File
@@ -1,10 +1,64 @@
from apps.base.models import KeyValue
from apps.base.utils import ip_limit
from core.database import db_startup_lock
from core.logger import logger
from core.security import (
generate_jwt_secret,
is_config_initialized,
is_valid_jwt_secret,
prepare_security_config,
)
from core.settings import DEFAULT_CONFIG, settings
from core.utils import hash_password
MIN_ADMIN_PASSWORD_LENGTH = 8
SETUP_CONFIG_FIELDS = {
"allowed_file_types",
"code_generate_type",
"enableChunk",
"errorCount",
"errorMinute",
"expireStyle",
"max_save_seconds",
"name",
"openUpload",
"uploadCount",
"uploadMinute",
"uploadSize",
}
async def ensure_settings_row() -> None:
await KeyValue.get_or_create(key="settings", defaults={"value": DEFAULT_CONFIG})
initial_security = prepare_security_config(DEFAULT_CONFIG)
_, created = await KeyValue.get_or_create(
key="settings", defaults={"value": initial_security.config}
)
if created:
logger.warning(
"系统尚未初始化,请在浏览器中打开站点并完成管理员密码设置"
)
async def ensure_security_settings() -> None:
config_record = await KeyValue.filter(key="settings").first()
if not config_record:
return
current_config = {**DEFAULT_CONFIG, **(config_record.value or {})}
security_config = prepare_security_config(current_config)
if not security_config.changed:
return
config_record.value = security_config.config
await config_record.save()
if security_config.setup_required:
logger.warning("检测到空密码或旧版默认管理员密码,请通过初始化页面重新设置")
elif security_config.password_hashed:
logger.info("已将管理员密码迁移为哈希存储")
if security_config.jwt_secret_rotated:
logger.info("已生成独立 JWT 签名密钥")
await refresh_settings()
def _sync_ip_limits() -> None:
@@ -19,3 +73,42 @@ async def refresh_settings() -> None:
config_record = await KeyValue.filter(key="settings").first()
settings.user_config = config_record.value if config_record and config_record.value else {}
_sync_ip_limits()
def is_runtime_initialized() -> bool:
return is_config_initialized(dict(settings.items()))
async def initialize_system(
admin_password: str,
site_name: str | None = None,
setup_options: dict | None = None,
) -> None:
password = str(admin_password or "").strip()
if len(password) < MIN_ADMIN_PASSWORD_LENGTH:
raise ValueError(f"管理员密码至少需要 {MIN_ADMIN_PASSWORD_LENGTH} 位")
async with db_startup_lock():
config_record = await KeyValue.filter(key="settings").first()
current_config = {
**DEFAULT_CONFIG,
**(config_record.value if config_record and config_record.value else {}),
}
if is_config_initialized(current_config):
raise ValueError("系统已经初始化,请直接登录后台")
next_config = dict(current_config)
for key, value in (setup_options or {}).items():
if key in SETUP_CONFIG_FIELDS:
next_config[key] = value
normalized_site_name = str(site_name or "").strip()
if normalized_site_name:
next_config["name"] = normalized_site_name[:80]
next_config["admin_token"] = hash_password(password)
if not is_valid_jwt_secret(next_config.get("jwt_secret")):
next_config["jwt_secret"] = generate_jwt_secret()
await KeyValue.update_or_create(key="settings", defaults={"value": next_config})
await refresh_settings()
+60
View File
@@ -0,0 +1,60 @@
import copy
import secrets
from dataclasses import dataclass
from typing import Any
from core.utils import hash_password, is_password_hashed, verify_password
JWT_SECRET_MIN_LENGTH = 32
INTERNAL_CONFIG_KEYS = {"jwt_secret"}
LEGACY_DEFAULT_ADMIN_TOKEN = "FileCodeBox" + "2023"
@dataclass
class SecurityConfigResult:
config: dict[str, Any]
changed: bool = False
password_hashed: bool = False
jwt_secret_rotated: bool = False
setup_required: bool = False
def generate_jwt_secret() -> str:
return secrets.token_urlsafe(48)
def is_valid_jwt_secret(secret: Any) -> bool:
return isinstance(secret, str) and len(secret) >= JWT_SECRET_MIN_LENGTH
def is_config_initialized(config: dict[str, Any]) -> bool:
admin_token = str(config.get("admin_token") or "")
if not admin_token:
return False
return not verify_password(LEGACY_DEFAULT_ADMIN_TOKEN, admin_token)
def prepare_security_config(config: dict[str, Any]) -> SecurityConfigResult:
next_config = copy.deepcopy(config)
result = SecurityConfigResult(config=next_config)
admin_token = str(next_config.get("admin_token") or "")
if not admin_token:
result.setup_required = True
elif verify_password(LEGACY_DEFAULT_ADMIN_TOKEN, admin_token):
next_config["admin_token"] = ""
result.setup_required = True
result.changed = True
elif not is_password_hashed(admin_token):
next_config["admin_token"] = hash_password(admin_token)
result.password_hashed = True
result.changed = True
jwt_secret = next_config.get("jwt_secret")
if not is_valid_jwt_secret(jwt_secret):
next_config["jwt_secret"] = generate_jwt_secret()
result.jwt_secret_rotated = True
result.changed = True
return result
+4 -1
View File
@@ -38,11 +38,13 @@ DEFAULT_CONFIG = {
"onedrive_proxy": 0,
"webdav_root_path": "filebox_storage",
"webdav_proxy": 0,
"admin_token": "FileCodeBox2023",
"admin_token": "",
"jwt_secret": "",
"openUpload": 1,
"uploadSize": 1024 * 1024 * 10,
"allowed_file_types": ["*"],
"expireStyle": ["day", "hour", "minute", "forever", "count"],
"code_generate_type": "number",
"uploadMinute": 1,
"enableChunk": 0,
"webdav_url": "",
@@ -73,6 +75,7 @@ DEFAULT_CONFIG = {
"serverPort": 12345,
"showAdminAddr": 0,
"robotsText": "User-agent: *\nDisallow: /",
"trustedProxies": [],
}
+6 -4
View File
@@ -5,8 +5,8 @@
import datetime
import hashlib
import os
import random
import re
import secrets
import string
import time
@@ -18,7 +18,7 @@ async def get_random_num():
获取随机数
:return:
"""
return random.randint(10000, 99999)
return secrets.randbelow(90000) + 10000
r_s = string.ascii_uppercase + string.digits
@@ -29,7 +29,7 @@ async def get_random_string():
获取随机字符串
:return:
"""
return "".join(random.choice(r_s) for _ in range(5))
return "".join(secrets.choice(r_s) for _ in range(5))
async def get_now():
@@ -46,7 +46,9 @@ async def get_select_token(code: str):
:param code:
:return:
"""
token = settings.admin_token
token = getattr(settings, "jwt_secret", "")
if not token:
raise RuntimeError("应用签名密钥未初始化")
return hashlib.sha256(
f"{code}{int(time.time() / 1000)}000{token}".encode()
).hexdigest()
+1 -1
View File
@@ -1 +1 @@
APP_VERSION = "2.0.0-dev"
APP_VERSION = "2.4.0"
+2 -2
View File
@@ -22,7 +22,7 @@ Authorization: Bearer <token>
```bash
curl -X POST "http://localhost:12345/admin/login" \
-H "Content-Type: application/json" \
-d '{"password": "FileCodeBox2023"}'
-d '{"password": "<初始化时设置的管理员密码>"}'
```
**响应示例:**
@@ -329,4 +329,4 @@ curl -L "http://localhost:12345/share/select/?code=abc123" -o downloaded_file
- 403: 禁止访问
- 404: 资源不存在
- 422: 请求参数验证错误
- 500: 服务器内部错误
- 500: 服务器内部错误
-196
View File
@@ -1,196 +0,0 @@
# 本轮开发交付报告
生成日期:2026-06-06
本文档记录 `feature/development-plan` 分支本轮开发完成情况、验证结果和后续处理建议。
## 分支状态
当前工作区包含两个独立 Git 仓库,均已切换到本轮开发分支:
- 后端仓库:`FileCodeBox`
- 前端仓库:`FileCodeBoxFronted`
- 当前分支:`feature/development-plan`
本轮变更尚未提交。
## 开发目标
本轮目标是根据 `docs/development-plan.md` 完成下一阶段的优先开发项:
1. 补齐取件文件预览链路。
2. 建立前端最小测试体系。
3. 加固后端预签名上传回归测试。
4. 区分前端检查脚本和自动修复脚本。
5. 拆分管理文件模块的部分纯函数、状态逻辑和批量操作 UI。
## 完成范围
### P0:取件文件预览链路
已在取件页完成文件预览接线:
- `RetrievewFileView.vue` 绑定文件详情弹窗的 `preview-file` 事件。
- 取件页渲染并控制 `MediaPreviewModal`。
- 取件详情中的可预览文件现在可以打开媒体预览弹窗。
### P0:前端最小测试体系
已建立 Vitest 测试基础:
- 新增 `vitest.config.ts`。
- 新增 `package.json` 的 `test` 脚本。
- 引入 `vitest`、`@vue/test-utils`、`jsdom` 等测试依赖。
- 更新 `pnpm-lock.yaml`。
首批测试覆盖:
- 文件类型规则。
- 下载动作解析。
- 内容预览处理。
- 发送记录工具逻辑。
- 预签名上传相关流程。
- 上传策略分支。
- 管理文件摘要、视图预设和批量选择逻辑。
### P1:后端上传回归加固
已补充后端预签名上传流程测试:
- 新增 `tests/conftest.py`,固定测试导入路径。
- 新增 `tests/test_presign_upload_flow.py`。
覆盖场景包括:
- `init` 直传模式。
- `init` 代理上传模式。
- `confirm` 成功创建文件记录。
- `confirm` 拒绝缺失的直传文件。
- `proxy` 上传大小不一致校验。
- `cancel` 取消并清理已上传对象。
- 过期上传会话自动删除并拒绝继续操作。
### P1:质量脚本调整
已区分自动修复和只检查命令:
```json
{
"lint": "eslint . --fix",
"lint:check": "eslint ."
}
```
同时,架构检查脚本已忽略测试文件,避免测试代码影响前端分层规则检查。
### P2:管理文件模块拆分
已完成第一轮低风险拆分:
- 新增 `admin-file-view-preset.ts`,承载管理文件视图预设规则。
- 新增 `admin-file-summary.ts`,承载管理文件摘要计算逻辑。
- 新增 `useAdminFileSelection.ts`,承载批量选择状态逻辑。
- 新增 `AdminBatchActionBar.vue`,承载管理页批量操作栏 UI。
- `FileManageView.vue` 已接入新的批量操作栏组件。
本轮拆分优先处理纯函数和单一职责状态逻辑,避免一次性重构整个管理页。
## 关键设计决策
1. 优先补用户可见断点,再推进模块拆分。
2. 先给工具函数和 composable 补测试,再扩大重构范围。
3. `lint` 保留自动修复语义,新增 `lint:check` 用于 CI 和人工验证。
4. 管理文件页拆分采用渐进方式,每次只抽离职责清晰、影响边界可控的模块。
5. 后端上传测试使用替身对象和临时状态,避免依赖真实网络、真实 S3 或污染运行数据目录。
## 验证记录
本轮已完成以下验证:
```bash
cd FileCodeBoxFronted
pnpm test
pnpm check:architecture
pnpm type-check
pnpm lint:check
pnpm build
cd ../FileCodeBox
pytest
git diff --check
```
验证结果:
- 前端 `pnpm test`:9 files / 27 tests passed。
- 前端 `pnpm check:architecture`:通过。
- 前端 `pnpm type-check`:通过。
- 前端 `pnpm lint:check`:通过。
- 前端 `pnpm build`:通过。
- 后端 `pytest`:21 passed,仅存在 Tortoise ORM deprecation warnings。
- 前后端 `git diff --check`:通过。
## 当前未提交文件
### 后端仓库
新增文件:
- `docs/development-plan.md`
- `docs/development-delivery-report.md`
- `tests/conftest.py`
- `tests/test_presign_upload_flow.py`
### 前端仓库
修改文件:
- `package.json`
- `pnpm-lock.yaml`
- `scripts/check-architecture.mjs`
- `src/composables/useAdminFiles.ts`
- `src/composables/useSendFlow.ts`
- `src/utils/download-action.ts`
- `src/views/RetrievewFileView.vue`
- `src/views/manage/FileManageView.vue`
- `tsconfig.app.json`
新增文件:
- `src/components/common/AdminBatchActionBar.vue`
- `src/composables/useAdminFileSelection.ts`
- `src/composables/useAdminFileSelection.test.ts`
- `src/composables/usePresignedUpload.test.ts`
- `src/services/upload-strategy.test.ts`
- `src/utils/admin-file-summary.ts`
- `src/utils/admin-file-summary.test.ts`
- `src/utils/admin-file-view-preset.ts`
- `src/utils/admin-file-view-preset.test.ts`
- `src/utils/content-preview.test.ts`
- `src/utils/download-action.test.ts`
- `src/utils/file-type.ts`
- `src/utils/file-type.test.ts`
- `src/utils/send-record.test.ts`
- `vitest.config.ts`
## 后续建议
1. 提交前再次执行前后端验证命令,确保工作区未被其他改动影响。
2. 分别在两个仓库创建提交,避免跨仓库状态混淆。
3. 下一轮继续拆分管理文件模块时,优先处理筛选栏、详情侧栏和元数据编辑逻辑。
4. 后端可继续补充 `allowed_file_types`、S3 `file_exists` 降级、主题资源路径穿越保护等测试。
## 推荐提交信息
后端仓库:
```bash
git commit -m "test: add presign upload flow coverage"
```
前端仓库:
```bash
git commit -m "feat: add retrieve preview and frontend tests"
```
-211
View File
@@ -1,211 +0,0 @@
# 下一步开发计划
本文档记录 FileCodeBox 下一阶段开发优先级、并行拆分方式、验收标准和质量门禁。
## 背景
当前工作区包含两个独立仓库:
- `FileCodeBox`:FastAPI 后端,包含接口、存储、管理后台 API、文档和后端测试。
- `FileCodeBoxFronted`:Vue 3 + Vite 前端,包含公开取件/发件页和管理后台界面。
近期提交主要集中在 S3 存储、取件码归一化、文件类型限制、主题资源加载、前端管理页和上传下载体验。
下一阶段应优先处理用户可见断点和自动化回归保护,再推进大模块拆分。
## 优先级总览
### P0:补齐取件文件预览链路
目标:打通前端已存在但尚未完整接线的文件预览能力。
涉及模块:
- `RetrievewFileView.vue`
- `FileDetailModal.vue`
- `MediaPreviewModal.vue`
- `useRetrieveFlow.ts`
主要工作:
1. 在取件详情弹窗中绑定文件预览事件。
2. 在取件页渲染媒体预览弹窗。
3. 确认图片、视频、音频、PDF 等可预览文件能正常打开。
4. 保持关闭、下载、错误提示等状态行为一致。
验收标准:
```bash
pnpm check:architecture
pnpm build
```
手工验收:
1. 上传非文本文件并获取取件码。
2. 取件后打开详情弹窗。
3. 点击预览,确认弹窗可打开。
4. 确认关闭和下载动作正常。
### P0:建立最小前端测试体系
目标:为核心前端流程建立可持续的自动化回归保护。
现状:
- 前端暂无测试目录。
- `package.json` 中暂无 `test` 脚本。
- 最近改动涉及上传、下载、Markdown 预览、配置表单等高风险路径。
建议引入:
```bash
vitest
@vue/test-utils
jsdom
```
首批测试范围:
- 文件类型限制规则。
- 过期时间限制校验。
- Markdown 渲染和 HTML 清洗。
- 下载动作解析。
- 预签名上传与分片上传提交分支。
验收标准:
```bash
pnpm test
```
要求:
- 测试能在 60 秒内完成。
- 核心工具函数至少具备首批单元测试。
- 测试脚本不修改源码文件。
### P1:后端上传与存储回归加固
目标:把近期修复沉淀为后端测试,降低存储和上传链路回归风险。
涉及模块:
- `apps/base/views.py`
- `core/storage.py`
- `main.py`
- `tests/`
优先测试场景:
1. 预签名上传 `init` / `confirm` / `cancel`。
2. 代理上传文件大小校验。
3. `allowed_file_types` 的扩展名、MIME、通配规则。
4. S3 `file_exists` 的 `head_object` 失败降级逻辑。
5. 主题资源路径穿越保护。
验收标准:
```bash
pytest
```
要求:
- 测试使用临时目录和替身对象,避免污染 `data/`。
- 外部存储相关测试不依赖真实网络或真实 S3。
- 异常路径和边界值必须覆盖。
### P1:调整质量脚本
目标:区分“检查”和“自动修复”,避免 CI 或验证命令改写源码。
当前问题:
```json
"lint": "eslint . --fix"
```
建议调整:
```json
{
"lint": "eslint . --fix",
"lint:check": "eslint ."
}
```
推荐前端验证顺序:
```bash
pnpm check:architecture
pnpm type-check
pnpm lint:check
pnpm test
pnpm build
```
### P2:拆分管理文件模块
目标:降低管理文件页面和业务 composable 的维护复杂度。
现状:
- `FileManageView.vue` 体量较大。
- `useAdminFiles.ts` 同时承载列表、筛选、视图预设、批量操作、详情、元数据、下载和预览等职责。
拆分顺序:
1. 抽纯函数:筛选参数归一化、视图预设归一化、摘要计算、详情视图模型转换。
2. 抽 composable:批量操作、详情弹窗、元数据编辑、视图预设。
3. 抽 UI 子组件:批量工具栏、筛选栏、详情侧栏、预设选择器。
约束:
- 每次只拆一块。
- 拆分前后行为保持一致。
- 先给纯函数补测试,再推进 UI 拆分。
## 并行开发安排
第一轮可并行拆分为四个互不冲突的任务:
1. 前端 A:接线取件文件预览。
2. 前端 B:搭建 Vitest 与首批工具函数测试。
3. 后端 C:补充上传和存储回归测试。
4. 工程 D:新增 `lint:check` 并整理验证命令。
合并前统一验证:
```bash
cd FileCodeBoxFronted
pnpm check:architecture
pnpm type-check
pnpm lint:check
pnpm test
pnpm build
cd ../FileCodeBox
pytest
```
## 质量门禁
每个开发任务完成时必须记录:
- 改动范围。
- 关键设计决策。
- 执行过的验证命令。
- 未覆盖风险和后续事项。
涉及上传、删除、存储、认证、配置等功能时,必须补充异常路径测试。
## 推荐执行顺序
1. 先完成 P0 的取件预览接线。
2. 同步建立前端最小测试体系。
3. 补齐后端上传和存储回归测试。
4. 调整前端质量脚本。
5. 等测试保护到位后,再拆分管理文件模块。
结论:下一阶段以“取件预览接线 + 测试体系建设”为主线,先修用户可见断点,再提升长期维护质量。
+2 -2
View File
@@ -22,7 +22,7 @@ When guest upload is disabled in admin panel (`openUpload=0`), you need to login
```bash
curl -X POST "http://localhost:12345/admin/login" \
-H "Content-Type: application/json" \
-d '{"password": "FileCodeBox2023"}'
-d '{"password": "<admin-password-set-during-setup>"}'
```
**Response Example:**
@@ -329,4 +329,4 @@ When an error occurs, the API will return corresponding error message:
- 403: Forbidden
- 404: Not Found
- 422: Validation Error
- 500: Internal Server Error
- 500: Internal Server Error
+2 -2
View File
@@ -109,11 +109,11 @@ Default available themes:
| Setting | Type | Default | Description |
|---------|------|---------|-------------|
| `admin_token` | string | `FileCodeBox2023` | Admin login password |
| `admin_token` | string | Set during setup | Admin login password |
| `showAdminAddr` | int | `0` | Show admin panel entry on homepage (1=show, 0=hide) |
::: danger Security Warning
Always change the default `admin_token` in production environments! Using the default password poses serious security risks.
The setup page is shown automatically while the system is uninitialized. Complete setup before exposing a production service to the public internet.
:::
## Security Settings
+3 -2
View File
@@ -55,8 +55,9 @@ python main.py
- Download file
4. Admin Panel
- Open `http://localhost:12345` on first run and complete setup
- Visit `http://localhost:12345/#/admin`
- Enter admin password: `FileCodeBox2023`
- Enter the admin password set during setup
- Enter admin panel
- View system information, file list, user management, etc.
@@ -64,4 +65,4 @@ python main.py
- [Storage Configuration](/en/guide/storage) - Learn how to configure different storage methods
- [Security Settings](/en/guide/security) - Learn how to enhance system security
- [API Documentation](/en/api/) - Learn how to integrate through API
- [API Documentation](/en/api/) - Learn how to integrate through API
+5 -4
View File
@@ -8,12 +8,13 @@ FileCodeBox provides a fully-featured admin panel that allows administrators to
The admin panel is located at the `/admin` path. Access method:
1. Visit `http://your-domain.com/admin` in your browser
2. Enter the admin password (the value of the `admin_token` configuration)
3. Click the login button
1. On first run, set the admin password on the setup page
2. Visit `http://your-domain.com/admin` in your browser
3. Enter the admin password (the value of the `admin_token` configuration)
4. Click the login button
::: tip Tip
The default admin password is `FileCodeBox2023`. Be sure to change this password in production environments. See [Security Settings](/en/guide/security) for details.
The setup page is shown automatically while the system is uninitialized. Complete setup before exposing a production service to the public internet.
:::
### Show Admin Entry
+3 -3
View File
@@ -4,10 +4,10 @@ FileCodeBox provides multiple layers of security mechanisms to protect your file
## Admin Password
### Change Default Password
### First-Run Setup
::: danger Important Security Warning
FileCodeBox's default admin password is `FileCodeBox2023`. **You must change this password immediately in production environments!** Using the default password allows anyone to access your admin panel.
FileCodeBox does not ship with a default admin password. Open the site in your browser on first run and set the admin password on the setup page.
:::
There are two ways to change the admin password:
@@ -272,7 +272,7 @@ your-domain.com {
Before deploying FileCodeBox, confirm the following security configurations:
- [ ] Changed default admin password `admin_token`
- [ ] Completed first-run setup and set the admin password `admin_token`
- [ ] Hidden admin entry `showAdminAddr: 0`
- [ ] Configured appropriate upload rate limiting
- [ ] Configured error rate limiting to prevent brute-force attacks
+1 -1
View File
@@ -149,7 +149,7 @@ If guest upload is disabled in admin panel (`openUpload=0`), you need to login f
# 1. Login to get token
curl -X POST "http://localhost:12345/admin/login" \
-H "Content-Type: application/json" \
-d '{"password": "FileCodeBox2023"}'
-d '{"password": "<admin-password-set-during-setup>"}'
# Returns: {"code":200,"msg":"success","detail":{"token":"xxx.xxx.xxx","token_type":"Bearer"}}
+2 -2
View File
@@ -108,11 +108,11 @@ FileCodeBox 支持两种配置方式:
| 配置项 | 类型 | 默认值 | 说明 |
|--------|------|--------|------|
| `admin_token` | string | `FileCodeBox2023` | 管理员登录密码 |
| `admin_token` | string | 初始化页面设置 | 管理员登录密码(哈希存储) |
| `showAdminAddr` | int | `0` | 是否在首页显示管理入口(1=显示,0=隐藏) |
::: danger 安全警告
请务必在生产环境中修改默认的 `admin_token`!使用默认密码会导致严重的安全风险。
未初始化时会自动显示初始化页面。生产环境请在服务对外开放前完成初始化。
:::
## 安全设置
+3 -2
View File
@@ -109,8 +109,9 @@ python main.py
- 下载文件
4. 后台管理
- 首次访问 `http://localhost:12345` 完成初始化
- 访问 `http://localhost:12345/#/admin`
- 输入管理员密码:`FileCodeBox2023`
- 输入初始化时设置的管理员密码
- 进入后台管理页面
- 查看系统信息、文件列表、用户管理等
@@ -118,4 +119,4 @@ python main.py
- [存储配置](/guide/storage) - 了解如何配置不同的存储方式
- [安全设置](/guide/security) - 了解如何增强系统安全性
- [API 文档](/api/) - 了解如何通过 API 集成
- [API 文档](/api/) - 了解如何通过 API 集成
+6 -5
View File
@@ -8,12 +8,13 @@ FileCodeBox 提供了功能完善的管理面板,让管理员可以方便地
管理面板位于 `/admin` 路径。访问方式:
1. 在浏览器中访问 `http://your-domain.com/admin`
2. 输入管理员密码(`admin_token` 配置项的值)
3. 点击登录按钮
1. 首次访问站点时,按初始化页面设置管理员密码
2. 在浏览器中访问 `http://your-domain.com/admin`
3. 输入管理员密码(`admin_token` 配置项的值)
4. 点击登录按钮
::: tip 提示
默认管理员密码是 `FileCodeBox2023`。请务必在生产环境中修改此密码,详见 [安全设置](/guide/security)。
未初始化时会自动进入初始化页面。生产环境请先完成初始化,再开放公网访问。
:::
### 显示管理入口
@@ -384,7 +385,7 @@ Content-Type: application/json
-- 查看当前配置
SELECT * FROM keyvalue WHERE key = 'settings';
-- 或者删除配置,恢复默认密码
-- 或者删除配置,重启后重新进入初始化流程
DELETE FROM keyvalue WHERE key = 'settings';
```
+3 -3
View File
@@ -4,10 +4,10 @@ FileCodeBox 提供了多层安全机制来保护您的文件分享服务。本
## 管理员密码
### 修改默认密码
### 首次初始化
::: danger 重要安全警告
FileCodeBox 的默认管理员密码是 `FileCodeBox2023`。**在生产环境中必须立即修改此密码!**使用默认密码会导致任何人都可以访问您的管理面板。
FileCodeBox 首次启动时不会生成默认管理员密码。请在浏览器中打开站点,按初始化页面设置管理员密码,并妥善保存。
:::
修改管理员密码有两种方式:
@@ -271,7 +271,7 @@ your-domain.com {
部署 FileCodeBox 前,请确认以下安全配置:
- [ ] 已修改默认管理员密码 `admin_token`
- [ ] 已完成首次初始化并设置管理员密码 `admin_token`
- [ ] 已隐藏管理入口 `showAdminAddr: 0`
- [ ] 已配置合适的上传频率限制
- [ ] 已配置错误次数限制防止暴力破解
+1 -1
View File
@@ -149,7 +149,7 @@ curl -L "http://localhost:12345/share/select/?code=取件码" -o downloaded_file
# 1. 登录获取 token
curl -X POST "http://localhost:12345/admin/login" \
-H "Content-Type: application/json" \
-d '{"password": "FileCodeBox2023"}'
-d '{"password": "<初始化时设置的管理员密码>"}'
# 返回: {"code":200,"msg":"success","detail":{"token":"xxx.xxx.xxx","token_type":"Bearer"}}
-843
View File
@@ -1,843 +0,0 @@
# 功能与用户体验提升规划
生成日期:2026-06-06
本文档承接 `development-plan.md` 和 `development-delivery-report.md`,用于规划下一轮“功能增强 + 用户体验提升”开发。重点不是重做界面,而是让发送、取件和管理流程更清楚、更可恢复、更适合反复使用。
## 当前基线
当前工作区包含两个独立仓库:
- `FileCodeBox`:FastAPI 后端,提供分享、取件、分片上传、预签名上传、管理后台、配置和本地文件管理接口。
- `FileCodeBoxFronted`:Vue 3 + Vite 前端,提供公开取件页、发件页、登录页、管理仪表盘、文件管理和系统设置。
本轮已完成的基础能力:
- 取件文件预览链路已接通。
- 前端 Vitest 测试体系已建立。
- 后端预签名上传流程已有回归测试。
- 管理文件页已抽出部分纯函数、批量选择逻辑和批量操作栏。
下一轮应把重点从“能用”推进到“好用、稳定、可解释”。
## 体验目标
1. 发送流程要让用户明确知道当前文件是否可发、发到哪一步、失败后如何继续。
2. 取件流程要避免误消耗取件次数,先展示文件摘要,再由用户确认下载或预览。
3. 管理后台要提高高频操作效率,减少大页面内工具堆叠和重复确认成本。
4. 所有危险操作要有清晰影响范围,避免误删、误批量修改和不可逆操作。
5. 错误提示要从“发生错误”升级为“原因 + 可执行下一步”。
## 规划依据
本轮规划基于前后端只读审阅结果:
- 前端主流程已完整,但取件前确认、上传取消/重试、发送成功结果区和后台强确认仍不足。
- 后端接口能力较全,但取件扣次数、下载票据、预签名直传确认、错误响应和审计追踪仍需要加固。
- 下一轮应优先处理“安全边界 + 关键路径体验”,再扩展管理效率和长期产品能力。
## P0:取件扣次数与下载票据一致性
目标:确保取件次数只在真实授权动作中消耗,并且旧下载地址不能绕过过期或次数限制。
### 现状问题
- `/share/select/` 当前会调用 `update_file_usage()`,取件前缺少确认时容易误消耗次数。
- `/share/download` 使用 `check=False` 获取文件记录,已生成的下载地址存在被继续复用的窗口。
- 下载票据由 `get_select_token()` 生成,缺少明确的短期过期语义和服务端状态绑定。
### 建议实现
1. 将“查看元数据”和“确认取件授权”严格分离。
2. 为确认取件生成短期下载票据:
- 票据绑定取件码。
- 票据包含过期时间。
- 票据校验时重新检查文件是否过期、次数是否耗尽。
3. 并发场景下保证 `expired_count=1` 只能成功一次。
4. 下载接口拒绝已过期、次数耗尽或票据失效的请求。
5. 响应中明确返回剩余次数和下一步动作。
### 涉及模块
- `apps/base/views.py`
- `core/utils.py`
- `apps/base/models.py`
- `tests/`
### 数据模型影响
第一阶段可先使用签名票据,不强制新增表。
如果要做更完整审计,后续新增:
- `DownloadTicket`
- `FileAccessLog`
### 验收标准
1. 元数据查询不消耗下载次数。
2. 确认取件后才消耗次数并返回下载票据。
3. `expired_count=1` 并发取件时只能成功一次。
4. 旧下载地址在文件过期或次数耗尽后不可继续下载。
5. 后端测试覆盖票据过期、次数耗尽和并发边界。
## P0:公开取件体验升级
目标:取件码输入后先确认内容,再执行会消耗次数的取件动作。
### 现状问题
- `RetrievewFileView.vue` 在取件码长度达到 5 位时直接调用 `handleSubmit()`。
- `handleSubmit()` 调用 `/share/select/`,会执行 `update_file_usage()`,可能消耗下载次数。
- `useRetrieveFlow.ts` 已有 `inspectCode()` 和 `inspectedFile`,但页面当前未形成完整的“预检查确认”体验。
### 建议实现
1. 输入 5 位取件码后调用 `inspectCode()`,请求 `/share/metadata/`。
2. 页面展示文件摘要卡片:
- 文件名或文本类型。
- 文件大小。
- 过期时间。
- 剩余下载次数。
- 是否可预览。
3. 用户点击“取件”后再调用 `handleSubmit()`。
4. 如果文件已过期或次数耗尽,直接展示不可取原因,不再进入下载动作。
5. 查询参数 `?code=xxxxx` 进入页面时,也走同样的预检查流程。
6. 与服务端下载票据机制配合,确认取件后再获得可下载地址。
### 涉及模块
- `RetrievewFileView.vue`
- `RetrieveForm.vue`
- `useRetrieveFlow.ts`
- `FileDetailModal.vue`
- `download-action.ts`
- `src/i18n/locales/zh-CN.ts`
- `src/i18n/locales/en-US.ts`
### 验收标准
```bash
cd FileCodeBoxFronted
pnpm test
pnpm check:architecture
pnpm type-check
pnpm lint:check
pnpm build
```
手工验收:
1. 输入有效取件码,只展示摘要,不立即消耗下载次数。
2. 点击确认取件后,才新增取件记录并打开详情或预览。
3. 输入过期取件码时展示明确原因。
4. 从 `?code=xxxxx` 访问时能自动展示摘要。
## P0:发送结果页增强
目标:发送成功后让用户更快完成复制、分享、复查和再次发送。
### 现状问题
- `useSendFlow.ts` 发送成功后会自动复制链接并打开记录详情。
- 用户能看到结果,但结果区域更像历史详情,不像一次明确的“发送完成”状态。
- 多文件、文本、单文件的结果反馈可以更聚焦。
### 建议实现
1. 新增发送成功结果面板,替代只依赖记录详情弹窗:
- 取件码大号展示。
- 一键复制取件码。
- 一键复制链接。
- 二维码展示入口。
- 重新发送按钮。
2. 明确自动复制结果:
- 复制成功展示“链接已复制”。
- 复制失败展示“请手动复制”。
3. 多文件上传成功后展示文件数量和压缩包/批量记录说明。
4. 文本发送成功后提供“预览文本”和“复制原文”。
### 涉及模块
- `SendFileView.vue`
- `SentRecordDetailModal.vue`
- `SentRecordList.vue`
- `useSendFlow.ts`
- `sent-record-actions.ts`
- `send-record.ts`
### 验收标准
1. 单文件、文本、多文件发送成功后都有明确完成态。
2. 复制取件码、复制链接、二维码入口可用。
3. 发送成功后再次选择文件或文本不会残留上一次进度。
4. 自动复制失败时有人工复制路径。
## P0:上传失败恢复与取消
目标:上传过程可中断、可重试、可解释。
### 现状问题
- 前端已有上传进度、速度和预签名上传封装。
- 用户在上传中无法主动取消。
- 失败后缺少保留文件并重试的明确路径。
- 预签名上传会话存在后端取消接口,但前端体验还可以更完整。
### 建议实现
1. 上传中展示取消按钮。
2. 取消时调用对应取消逻辑:
- 预签名上传:`DELETE /presign/upload/{upload_id}`。
- 分片上传:`DELETE /chunk/upload/{upload_id}`。
3. 失败后保留已选择文件,提供“重试”按钮。
4. 错误提示按类型分层:
- 文件过大。
- 文件类型不允许。
- 网络中断。
- 服务端拒绝。
- 上传会话过期。
5. 上传过程中离开页面时提示用户确认。
### 涉及模块
- `FileUploadArea.vue`
- `SendFileView.vue`
- `useSendFlow.ts`
- `useSendSubmit.ts`
- `usePresignedUpload.ts`
- `upload-strategy.ts`
- `FileService`
### 验收标准
1. 上传中可以取消,后端临时会话或分片状态被清理。
2. 网络失败后可以直接重试,不需要重新选择文件。
3. 取消上传后进度归零,按钮状态恢复。
4. 页面跳转或关闭前有上传中提示。
## P0:预签名直传确认加固
目标:直传文件确认不只检查“对象存在”,还要确认大小、状态和失败原因。
### 现状问题
- `presign_upload_confirm()` 当前主要依赖 `file_exists()`。
- 直传对象大小不符、上传中断、对象异常时,服务端难以给出准确原因。
- `PresignUploadSession` 当前缺少状态字段,前端只能通过接口错误推断上传阶段。
### 建议实现
1. 存储接口增加对象元信息读取能力:
- `stat_file(save_path)`
- 返回是否存在、实际大小、更新时间和存储后端错误。
2. `presign_upload_confirm()` 校验实际大小与声明大小一致。
3. 上传会话状态响应补充原因:
- `pending`
- `uploading`
- `uploaded`
- `confirmed`
- `expired`
- `cancelled`
- `failed`
4. 失败时返回明确错误码和可展示文案。
5. 取消或失败后清理可清理的临时对象。
### 涉及模块
- `apps/base/views.py`
- `apps/base/models.py`
- `core/storage.py`
- `src/composables/usePresignedUpload.ts`
- `src/services/presign-upload.ts`
- `tests/test_presign_upload_flow.py`
### 数据模型影响
建议为 `PresignUploadSession` 增加:
- `status`
- `actual_size`
- `error_message`
第一阶段如果不做迁移,也可以先在状态接口中计算并返回原因。
### 验收标准
1. 直传对象不存在时返回明确错误。
2. 直传对象大小不符时拒绝创建分享记录。
3. 会话过期、取消、确认成功均有稳定状态。
4. 前端能展示初始化、上传中、确认中、失败、成功状态。
5. 后端测试覆盖对象不存在、大小不符、取消清理和会话过期。
## P0:统一错误响应与请求追踪
目标:让前端能稳定识别业务错误、网络错误和权限错误,并展示可执行下一步。
### 现状问题
- 部分接口抛出 `HTTPException`,部分接口返回 `APIResponse(code=404)`。
- 客户端难以稳定区分上传超限、类型不允许、取件码不存在、会话过期等业务失败。
- 缺少请求 ID,线上排查问题时难以关联日志和用户反馈。
### 建议实现
1. 统一错误响应结构:
- `code`
- `message`
- `error_code`
- `request_id`
- `detail`
2. 增加全局异常处理中间件或异常处理器。
3. 上传、取件、登录、配置保存等关键接口返回稳定错误码。
4. 前端错误提示按 `error_code` 映射文案和建议动作。
### 涉及模块
- `core/response.py`
- `main.py`
- `apps/base/views.py`
- `apps/admin/views.py`
- `src/utils/common.ts`
- `src/services/client.ts`
### 验收标准
1. 上传超限、类型不允许、取件码不存在、登录失败返回统一结构。
2. 前端提示包含原因和下一步动作。
3. 日志中可按 `request_id` 定位请求。
4. 后端测试覆盖全局错误响应格式。
## P0:管理高风险操作确认升级
目标:删除、批量修改、批量策略等不可逆操作必须让管理员清楚知道影响范围。
### 现状问题
- `useAdminFiles.ts` 中多处仍使用 `window.confirm()`。
- 批量删除、批量更新和批量策略操作缺少文件样例、影响数量和不可逆提示。
- 视图预设删除、单文件删除和批量删除的确认体验不统一。
### 建议实现
1. 替换 `window.confirm()` 为统一确认弹窗。
2. 确认弹窗展示:
- 操作类型。
- 影响文件数量。
- 文件样例。
- 是否不可逆。
- 操作执行后可能的结果。
3. 操作执行中禁用确认按钮和相关批量按钮。
4. 操作完成后展示成功数量、失败数量和失败原因。
5. 删除本地浏览器记录时明确提示“不删除服务器文件”。
### 涉及模块
- `FileManageView.vue`
- `AdminBatchActionBar.vue`
- `BaseModal.vue`
- `useAdminFiles.ts`
- `SentRecordList.vue`
- `FileRecordList.vue`
### 验收标准
1. 单文件删除、批量删除、批量更新、批量策略动作均使用统一确认弹窗。
2. 批量删除前可看到选中数量和至少 3 个文件样例。
3. 操作中按钮禁用,避免重复提交。
4. 取消操作不会改变选中状态。
5. 操作结果能区分全部成功、部分成功和全部失败。
## P0:配置保存强校验
目标:把配置错误拦在保存阶段,而不是等用户上传或下载时才暴露。
### 现状问题
- 配置存储在 `KeyValue` 中,更新入口需要更强字段校验。
- 存储后端切换、上传限制、过期策略、文件类型规则等配置一旦错误,会直接影响公开流程。
- 前端设置页有未保存状态,但配置变更风险没有形成统一摘要。
### 建议实现
1. 后端保存配置前做字段级校验:
- `file_storage` 必须是支持的存储后端。
- 上传大小、限流和保存时长不能为负数。
- `expireStyle` 必须属于允许枚举。
- S3、WebDAV、OpenDAL、OneDrive 的必填项按存储类型校验。
2. 前端保存前展示变更摘要:
- 已变更字段。
- 是否影响现有上传。
- 是否需要管理员复查。
3. 高风险配置显示明确提示:
- 公开上传。
- 允许全部文件类型。
- 永久保存。
- 默认管理员口令。
4. 设置页离开、刷新、切换后台页面时提示保存或放弃。
### 涉及模块
前端:
- `SystemSettingsView.vue`
- `useSystemConfig.ts`
- `router/index.ts`
- `config-storage.ts`
后端:
- `apps/admin/services.py`
- `apps/admin/views.py`
- `core/settings.py`
### 验收标准
1. 非法配置会被后端拒绝,并返回具体字段原因。
2. 前端保存前展示变更摘要。
3. 未保存配置离开页面会触发确认。
4. 默认管理员口令、公开上传、允许所有文件类型会有高风险提示。
## P1:管理文件页信息架构优化
目标:把管理页从“功能堆在一个表格上”调整为更适合高频扫描和批量处理的工作台。
### 现状问题
- `FileManageView.vue` 仍承担较多职责。
- 筛选、预设、批量操作、表格、详情、编辑弹窗集中在同一个页面。
- 单行操作按钮较多,在窄屏或大量数据时容易拥挤。
### 建议实现
1. 拆分筛选区组件:
- `AdminFileFilterBar.vue`
- 负责关键词、状态、健康度、类型、排序和预设入口。
2. 拆分详情侧栏:
- `AdminFileDetailDrawer.vue`
- 替代过重弹窗,保留复制、下载、编辑、预览入口。
3. 表格行操作收敛为主操作 + 更多菜单:
- 详情作为主操作。
- 下载、编辑、删除进入更多菜单。
4. 增加快捷筛选:
- 即将过期。
- 从未取件。
- 已耗尽次数。
- 存储异常。
5. 表格空状态提供可执行动作:
- 清空筛选。
- 创建视图预设。
- 返回全部文件。
### 涉及模块
- `FileManageView.vue`
- `AdminBatchActionBar.vue`
- `useAdminFiles.ts`
- `admin-file-summary.ts`
- `admin-file-view-preset.ts`
- `src/i18n/locales/zh-CN.ts`
- `src/i18n/locales/en-US.ts`
### 验收标准
1. 筛选区、批量操作区、表格区职责清晰。
2. 窄屏下表格行操作不溢出。
3. 快捷筛选能正确改变请求参数并刷新数据。
4. 已有批量选择、批量删除、批量策略动作不回归。
## P1:管理后台操作反馈增强
目标:让管理员明确知道批量操作影响了哪些文件、哪些成功、哪些失败。
### 现状能力
- 后端已有批量删除、批量更新、策略动作和活动记录。
- 前端已有批量操作栏。
- 后端 `FileService` 已具备管理活动记录能力。
### 建议实现
1. 批量操作执行前展示影响摘要:
- 选中文件数。
- 即将修改的字段。
- 不可逆风险。
2. 批量操作完成后展示结果摘要:
- 成功数量。
- 失败数量。
- 跳过原因。
3. 活动记录支持从文件详情进入:
- 展示该文件最近操作。
- 展示操作者、动作和时间。
4. 危险操作确认文案包含文件名或数量,而不是只问“是否删除”。
### 涉及模块
前端:
- `AdminBatchActionBar.vue`
- `FileManageView.vue`
- `useAdminFiles.ts`
- `DashboardView.vue`
后端:
- `apps/admin/views.py`
- `apps/admin/services.py`
### 验收标准
1. 批量删除和批量更新前有明确影响摘要。
2. 批量操作结果能展示部分失败,不只显示统一成功或失败。
3. 操作记录能按文件或关键词过滤。
4. 后端测试覆盖活动记录过滤和批量操作结果结构。
## P1:下载与预览体验统一
目标:用户在公开页和管理页面对“文本、图片、视频、音频、PDF、未知文件”时,操作路径一致。
### 建议实现
1. 抽统一文件能力判断工具:
- 是否可文本预览。
- 是否可媒体预览。
- 是否建议下载。
- 是否可复制内容。
2. 统一公开取件和管理页的预览入口文案。
3. PDF、图片、音视频预览失败时提供下载兜底。
4. 文本预览支持复制、下载为 `.txt`、查看原始内容。
### 涉及模块
- `MediaPreviewModal.vue`
- `ContentPreviewModal.vue`
- `FileDetailModal.vue`
- `FileManageView.vue`
- `content-preview.ts`
- `download-action.ts`
- `file-type.ts`
### 验收标准
1. 同一文件类型在公开页和管理页展示一致。
2. 预览失败时始终能回退到下载。
3. 文本内容复制和导出行为一致。
4. 文件类型判断工具具备单元测试。
## P1:上传前文件清单与限制提示
目标:多文件或大文件上传前,让用户提前知道会发生什么,减少上传中途失败。
### 现状问题
- 多文件上传会先打包为 zip,但用户只看到“正在打包文件”。
- 文件清单、总大小、超限原因和打包后行为没有在提交前集中展示。
- `FileUploadArea.vue` 已支持更多上传状态,但页面当前只传入 `uploading` 和 `idle`。
### 建议实现
1. 多文件选择后展示文件清单:
- 文件数量。
- 总大小。
- 最大文件。
- 不允许类型或超限文件。
2. 明确提示多文件将被打包为 zip。
3. 打包阶段展示独立状态,避免和上传阶段混淆。
4. 提交前对所有文件逐项校验,并返回具体失败原因。
### 涉及模块
- `FileUploadArea.vue`
- `SendFileView.vue`
- `useSendFlow.ts`
- `useSendSubmit.ts`
- `ExpirationSelector.vue`
- `file-type.ts`
### 验收标准
1. 多文件选择后可看到数量、总大小和打包提示。
2. 超限文件能逐项展示原因。
3. 打包中、上传中、确认中三个阶段状态不同。
4. 文件清单在取消或重新选择后正确重置。
## P1:服务端状态字段与可操作能力
目标:为前端展示更清楚的状态和主操作提供稳定数据,减少前端重复推断。
### 建议实现
1. 分享记录增加明确状态字段:
- `active`
- `expired`
- `download_limit_exhausted`
- `storage_missing`
2. 公开元数据接口补充可操作能力:
- `canPreview`
- `canDownload`
- `canCopy`
- `primaryAction`
3. 管理列表支持快捷筛选参数:
- `expiringSoon`
- `neverUsed`
- `exhausted`
- `storageIssue`
4. 后端响应保留必要的 snake_case 和 camelCase 兼容。
### 涉及模块
- `apps/base/views.py`
- `apps/base/schemas.py`
- `apps/admin/views.py`
- `apps/admin/services.py`
- `src/types/file.ts`
- `src/services/file.ts`
- `tests/`
### 验收标准
1. 元数据接口能直接告诉前端主操作是什么。
2. 管理文件列表能按快捷状态筛选。
3. 状态字段有后端测试覆盖。
4. 前端不再依赖 `filename === 'Text'` 这类脆弱判断。
## P1:审计日志表化
目标:让上传、下载、删除、配置变更等关键动作可追踪、可过滤、可定位。
### 现状问题
- 管理活动当前主要保存在 `KeyValue` 中,容量和查询能力有限。
- 活动记录缺少 IP、User-Agent、请求 ID、结果状态等排障信息。
- 批量操作失败时,缺少逐项结果追踪。
### 建议实现
1. 新增审计日志模型,记录:
- 动作类型。
- 操作者。
- IP。
- User-Agent。
- 请求 ID。
- 目标类型和目标 ID。
- 执行结果。
- 元数据。
- 创建时间。
2. `/admin/activities` 支持分页和筛选:
- 动作。
- 对象类型。
- 关键词。
- 时间范围。
- 结果状态。
3. 文件详情中展示该文件最近操作。
4. 配置变更记录变更摘要,不记录密钥明文。
### 涉及模块
- `apps/admin/services.py`
- `apps/admin/views.py`
- `apps/base/models.py`
- `tests/`
### 数据模型影响
建议新增:
- `AuditLog`
### 验收标准
1. 删除、批量更新、配置变更会写入审计日志。
2. 审计列表支持分页和筛选。
3. 日志不泄露 Token、密码、密钥。
4. 后端测试覆盖写入、过滤和敏感字段脱敏。
## P1:管理查询性能优化
目标:让后台在千级、万级文件记录下仍能稳定分页、筛选和统计。
### 现状问题
- 文件列表和仪表盘部分统计、过滤、排序在 Python 内存中完成。
- 数据量增加后,后台打开、筛选和统计会逐渐变慢。
### 建议实现
1. 文件列表筛选和排序尽量下推到数据库。
2. 仪表盘统计改为聚合查询。
3. 为高频字段补索引:
- `created_at`
- `expired_at`
- `suffix`
- `is_chunked`
- `used_count`
- `file_hash`
4. 大量记录下避免一次性加载所有文件再过滤。
### 涉及模块
- `apps/admin/views.py`
- `apps/admin/services.py`
- `apps/base/models.py`
- `tests/`
### 验收标准
1. 千级和万级记录下分页耗时稳定。
2. 仪表盘统计结果与现有结果一致。
3. 筛选、排序、分页返回结构保持兼容。
4. 后端测试覆盖主要过滤组合。
## P2:取件与发送记录体验增强
目标:让浏览器本地记录更适合长期使用。
### 建议实现
1. 记录支持搜索:
- 取件码。
- 文件名。
- 类型。
2. 记录支持分组:
- 今天。
- 最近 7 天。
- 更早。
3. 记录详情展示来源:
- 手动输入。
- 链接打开。
- 历史记录。
4. 支持清空记录前二次确认,并说明只清理本地记录,不删除服务器文件。
5. 支持导出发送记录为 JSON。
### 涉及模块
- `SideDrawer.vue`
- `SentRecordList.vue`
- `FileRecordList.vue`
- `fileData` store
- `send-record.ts`
- `download-action.ts`
### 验收标准
1. 本地记录超过 20 条时仍易于查找。
2. 清空记录不会误导用户以为删除了服务器文件。
3. 导出的记录可重新导入或至少可人工读取。
## P2:系统设置体验增强
目标:在强校验之外,给管理员提供配置自检、连接测试和修复建议。
### 建议实现
1. 设置页增加配置自检:
- 当前存储后端是否可用。
- 上传大小限制是否合理。
- 允许文件类型是否能被正确解析。
- 管理地址是否公开。
2. 存储配置增加测试连接按钮:
- S3。
- WebDAV。
- OpenDAL。
- OneDrive。
3. 自检结果返回修复建议:
- 缺少必填项。
- 存储连接失败。
- 上传限制过宽。
- 管理地址暴露。
4. 支持导出当前非敏感配置快照,便于排障。
### 涉及模块
前端:
- `SystemSettingsView.vue`
- `config-storage.ts`
- `config` types
后端:
- `apps/admin/views.py`
- `apps/admin/services.py`
- `core/storage.py`
- `core/settings.py`
### 验收标准
1. 保存设置前能看到变更摘要。
2. 错误配置不会只在上传时暴露。
3. 存储连接失败能返回可理解原因。
4. 配置自检接口有后端测试覆盖。
## 并行开发拆分
第一轮建议拆成四个互不冲突任务,先处理会影响安全边界和关键体验的事项:
1. 后端 A:取件扣次数与下载票据一致性。
2. 前端 B:取件前确认卡片和查询参数自动预检查。
3. 后端 C:统一错误响应和请求追踪。
4. 前端 D:发送成功结果面板和复制反馈。
第二轮在第一轮稳定后推进:
1. 后端 E:预签名直传确认加固和上传会话状态原因。
2. 前端 F:上传取消、失败重试和离页确认。
3. 前端 G:管理高风险操作确认弹窗。
4. 后端 H:配置保存强校验。
第三轮推进管理效率和长期维护:
1. 前端 I:管理文件筛选区、详情侧栏和行操作收敛。
2. 后端 J:服务端状态字段、快捷筛选和管理查询性能优化。
3. 后端 K:审计日志表化。
4. 前端 L:记录搜索、分组、导出和国际化补齐。
## 推荐执行顺序
1. 先做 P0 取件票据和扣次数一致性,修正服务端安全边界。
2. 接着做 P0 取件前确认卡片,避免用户误消耗次数。
3. 同步推进统一错误响应,让前端能展示稳定错误文案。
4. 再做发送成功结果区,提升公开用户最常见路径。
5. 然后做上传取消/重试和预签名直传确认加固。
6. 管理页按强确认、筛选拆分、详情侧栏的顺序渐进推进。
## 质量门禁
前端每轮合并前执行:
```bash
cd FileCodeBoxFronted
pnpm test
pnpm check:architecture
pnpm type-check
pnpm lint:check
pnpm build
```
后端每轮合并前执行:
```bash
cd FileCodeBox
pytest
```
涉及上传、删除、配置、权限和批量操作时,必须补充异常路径测试。
## 风险与注意事项
1. 取件预检查不能调用会消耗次数的接口。
2. 上传取消需要确认不同上传策略的清理路径一致。
3. 管理页组件拆分必须保持现有批量操作行为不变。
4. 配置自检不能泄露密钥、Token 或内部路径。
5. 本地记录增强只影响浏览器存储,不应让用户误解为服务端记录。
## 下一步建议
下一轮优先实现:
1. `P0:取件扣次数与下载票据一致性`
2. `P0:公开取件体验升级`
3. `P0:统一错误响应与请求追踪`
4. `P0:发送结果页增强`
这四项组合能同时修正服务端边界和公开用户体验,为后续上传恢复、管理工作台优化打基础。
+672 -18
View File
@@ -3,12 +3,14 @@
# @File : main.py
# @Software: PyCharm
import asyncio
import html
import time
from contextlib import asynccontextmanager
from urllib.parse import parse_qs
from fastapi import FastAPI, HTTPException
from fastapi import FastAPI, HTTPException, Request
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import FileResponse, HTMLResponse
from fastapi.responses import FileResponse, HTMLResponse, JSONResponse, RedirectResponse
from tortoise import Tortoise
from tortoise.contrib.fastapi import register_tortoise
@@ -16,13 +18,18 @@ from apps.admin.views import admin_api
from apps.base.models import KeyValue
from apps.base.utils import ip_limit
from apps.base.views import share_api, chunk_api, presign_api
from core.config import ensure_settings_row, refresh_settings
from core.config import (
ensure_security_settings,
ensure_settings_row,
initialize_system,
is_runtime_initialized,
refresh_settings,
)
from core.database import db_startup_lock, get_db_config, init_db
from core.logger import logger
from core.response import APIResponse
from core.settings import settings, BASE_DIR, DEFAULT_CONFIG
from core.tasks import delete_expire_files, clean_incomplete_uploads
from core.utils import hash_password, is_password_hashed
from core.version import APP_VERSION
@@ -67,6 +74,617 @@ def build_public_meta() -> dict:
}
FILE_SIZE_UNITS = {"KB": 1024, "MB": 1024**2, "GB": 1024**3}
SAVE_TIME_UNITS = {"second": 1, "minute": 60, "hour": 3600, "day": 86400}
EXPIRE_STYLE_OPTIONS = [
("day", "按天"),
("hour", "按小时"),
("minute", "按分钟"),
("forever", "永久"),
("count", "按取件次数"),
]
def get_form_value(data: dict, key: str, default: str = "") -> str:
value = data.get(key, default)
if isinstance(value, list):
value = value[-1] if value else default
return str(value if value is not None else default)
def get_form_list(data: dict, key: str) -> list[str]:
value = data.get(key, [])
if isinstance(value, list):
return [str(item) for item in value if str(item)]
if value:
return [str(value)]
return []
def normalize_bool_field(data: dict, key: str, default: bool) -> bool:
if key not in data:
return default
return get_form_value(data, key).lower() in {"1", "true", "on", "yes"}
def parse_int_field(
data: dict,
key: str,
default: int,
label: str,
min_value: int = 0,
max_value: int | None = None,
) -> int:
raw_value = get_form_value(data, key, str(default)).strip()
try:
value = int(raw_value)
except ValueError:
raise ValueError(f"{label} 必须是整数")
if value < min_value:
raise ValueError(f"{label} 不能小于 {min_value}")
if max_value is not None and value > max_value:
raise ValueError(f"{label} 不能大于 {max_value}")
return value
def parse_allowed_file_types(value: str) -> list[str]:
items = [item.strip() for item in value.split(",") if item.strip()]
return items or ["*"]
def parse_setup_options(data: dict) -> dict:
upload_size_unit = get_form_value(data, "upload_size_unit", "MB").upper()
if upload_size_unit not in FILE_SIZE_UNITS:
raise ValueError("文件大小单位不正确")
upload_size_value = parse_int_field(
data, "upload_size_value", 10, "文件大小限制", min_value=1
)
save_time_unit = get_form_value(data, "save_time_unit", "day")
if save_time_unit not in SAVE_TIME_UNITS:
raise ValueError("最长保存时间单位不正确")
save_time_value = parse_int_field(
data, "save_time_value", 0, "最长保存时间", min_value=0
)
expire_styles = get_form_list(data, "expireStyle")
valid_expire_styles = {style for style, _label in EXPIRE_STYLE_OPTIONS}
expire_styles = [style for style in expire_styles if style in valid_expire_styles]
if not expire_styles:
raise ValueError("至少需要选择一种过期方式")
code_generate_type = get_form_value(data, "code_generate_type", "number")
if code_generate_type not in {"number", "secret"}:
raise ValueError("提取码类型不正确")
return {
"allowed_file_types": parse_allowed_file_types(
get_form_value(data, "allowed_file_types", "*")
),
"code_generate_type": code_generate_type,
"enableChunk": int(normalize_bool_field(data, "enableChunk", False)),
"errorCount": parse_int_field(
data, "errorCount", DEFAULT_CONFIG["errorCount"], "取件错误次数限制", 1
),
"errorMinute": parse_int_field(
data, "errorMinute", DEFAULT_CONFIG["errorMinute"], "取件错误检测窗口", 1
),
"expireStyle": expire_styles,
"max_save_seconds": save_time_value * SAVE_TIME_UNITS[save_time_unit],
"openUpload": int(normalize_bool_field(data, "openUpload", True)),
"uploadCount": parse_int_field(
data, "uploadCount", DEFAULT_CONFIG["uploadCount"], "上传次数限制", 1
),
"uploadMinute": parse_int_field(
data, "uploadMinute", DEFAULT_CONFIG["uploadMinute"], "上传检测窗口", 1
),
"uploadSize": upload_size_value * FILE_SIZE_UNITS[upload_size_unit],
}
def build_expire_style_inputs(selected_styles: list[str]) -> str:
inputs = []
selected = set(selected_styles)
for style, label in EXPIRE_STYLE_OPTIONS:
checked = " checked" if style in selected else ""
inputs.append(
f'<label class="check"><input type="checkbox" name="expireStyle" value="{style}"{checked}> {label}</label>'
)
return "\n ".join(inputs)
def build_setup_page(error: str = "", form: dict | None = None) -> str:
form = form or {}
escaped_error = html.escape(error)
escaped_site_name = html.escape(
get_form_value(form, "site_name", DEFAULT_CONFIG["name"])
)
escaped_allowed_types = html.escape(get_form_value(form, "allowed_file_types", "*"))
upload_size_value = html.escape(get_form_value(form, "upload_size_value", "10"))
upload_size_unit = get_form_value(form, "upload_size_unit", "MB").upper()
save_time_value = html.escape(get_form_value(form, "save_time_value", "0"))
save_time_unit = get_form_value(form, "save_time_unit", "day")
upload_minute = html.escape(
get_form_value(form, "uploadMinute", str(DEFAULT_CONFIG["uploadMinute"]))
)
upload_count = html.escape(
get_form_value(form, "uploadCount", str(DEFAULT_CONFIG["uploadCount"]))
)
error_minute = html.escape(
get_form_value(form, "errorMinute", str(DEFAULT_CONFIG["errorMinute"]))
)
error_count = html.escape(
get_form_value(form, "errorCount", str(DEFAULT_CONFIG["errorCount"]))
)
open_upload_checked = (
" checked" if normalize_bool_field(form, "openUpload", True) else ""
)
chunk_checked = (
" checked" if normalize_bool_field(form, "enableChunk", False) else ""
)
code_generate_type = get_form_value(form, "code_generate_type", "number")
selected_expire_styles = get_form_list(form, "expireStyle") or list(
DEFAULT_CONFIG["expireStyle"]
)
expire_style_inputs = build_expire_style_inputs(selected_expire_styles)
size_unit_options = "\n".join(
f'<option value="{unit}"{" selected" if unit == upload_size_unit else ""}>{unit}</option>'
for unit in FILE_SIZE_UNITS
)
save_time_unit_options = "\n".join(
f'<option value="{unit}"{" selected" if unit == save_time_unit else ""}>{label}</option>'
for unit, label in [
("second", "秒"),
("minute", "分钟"),
("hour", "小时"),
("day", "天"),
]
)
code_type_options = "\n".join(
f'<option value="{value}"{" selected" if value == code_generate_type else ""}>{label}</option>'
for value, label in [("number", "数字"), ("secret", "随机字符")]
)
error_block = (
f'<div class="alert" role="alert">{escaped_error}</div>' if escaped_error else ""
)
return f"""<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>初始化 FileCodeBox</title>
<style>
:root {{
color-scheme: light;
--bg: #f5f5f7;
--panel: rgba(255, 255, 255, .86);
--panel-strong: rgba(255, 255, 255, .96);
--text: #18181b;
--muted: #71717a;
--line: rgba(228, 228, 231, .9);
--line-strong: rgba(212, 212, 216, .95);
--primary: #18181b;
--primary-soft: #f4f4f5;
--danger-bg: #fef2f2;
--danger: #b91c1c;
}}
* {{ box-sizing: border-box; }}
body {{
margin: 0;
min-height: 100vh;
display: grid;
place-items: center;
padding: 14px;
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
background: var(--bg);
color: var(--text);
}}
main {{
width: min(100%, 1040px);
padding: 14px;
border: 1px solid rgba(255, 255, 255, .8);
border-radius: 20px;
background: rgba(255, 255, 255, .62);
box-shadow: 0 22px 70px -34px rgba(24, 24, 27, .32);
backdrop-filter: blur(22px);
}}
.setup-header {{
display: flex;
align-items: center;
justify-content: space-between;
gap: 16px;
padding: 10px 10px 12px;
}}
.brand-mark {{
flex: 0 0 auto;
width: 40px;
height: 40px;
display: grid;
place-items: center;
border-radius: 14px;
background: #18181b;
color: #fff;
font-weight: 800;
letter-spacing: 0;
box-shadow: 0 16px 34px -14px rgba(24, 24, 27, .42);
}}
.title-wrap {{
min-width: 0;
display: flex;
align-items: center;
gap: 12px;
}}
h1 {{
margin: 0;
font-size: 21px;
line-height: 1.25;
letter-spacing: 0;
font-weight: 750;
}}
p {{
margin: 2px 0 0;
color: var(--muted);
line-height: 1.35;
font-size: 13px;
}}
form {{
margin: 0;
padding: 12px;
border: 1px solid var(--line);
border-radius: 16px;
background: var(--panel);
}}
.panel-grid {{
display: grid;
grid-template-columns: 1.05fr 1fr 1fr;
gap: 10px;
}}
.panel {{
min-width: 0;
padding: 10px;
border: 1px solid var(--line);
border-radius: 14px;
background: rgba(255, 255, 255, .68);
}}
.panel-wide {{
grid-column: 1 / -1;
display: grid;
grid-template-columns: minmax(0, 1.3fr) minmax(0, .9fr);
gap: 12px;
align-items: end;
}}
.panel-title {{
margin: 0 0 2px;
color: #18181b;
font-size: 13px;
font-weight: 760;
}}
label {{
display: block;
margin: 8px 0 5px;
font-weight: 650;
font-size: 12px;
color: #3f3f46;
}}
input, select {{
width: 100%;
height: 34px;
border: 1px solid var(--line);
border-radius: 10px;
padding: 0 10px;
font: inherit;
color: var(--text);
outline: none;
background: rgba(255, 255, 255, .84);
transition: border-color .2s ease, box-shadow .2s ease, background-color .2s ease;
}}
input:focus, select:focus {{
border-color: #a1a1aa;
background: #fff;
box-shadow: 0 10px 22px -12px rgba(24, 24, 27, .2), 0 0 0 3px rgba(24, 24, 27, .06);
}}
.grid {{
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 6px 12px;
}}
.full {{ grid-column: 1 / -1; }}
.span-2 {{ grid-column: span 2; }}
.row {{
display: grid;
grid-template-columns: minmax(0, 1fr) 88px;
gap: 8px;
}}
.checks {{
display: flex;
flex-wrap: wrap;
gap: 8px;
margin-top: 5px;
}}
.check {{
display: flex;
align-items: center;
gap: 8px;
min-height: 36px;
margin: 0;
padding: 0 9px;
border: 1px solid var(--line);
border-radius: 10px;
font-weight: 550;
font-size: 13px;
color: var(--text);
white-space: nowrap;
background: rgba(255, 255, 255, .72);
transition: border-color .2s ease, background-color .2s ease, box-shadow .2s ease;
}}
.check:hover {{
border-color: var(--line-strong);
background: #fff;
box-shadow: 0 8px 20px -8px rgba(0, 0, 0, .1);
}}
.check input {{
width: 16px;
height: 16px;
padding: 0;
box-shadow: none;
}}
.section-title {{
display: none;
}}
.help {{
margin: 4px 0 0;
font-size: 12px;
color: var(--muted);
}}
.alert {{
margin-bottom: 8px;
padding: 9px 12px;
border-radius: 12px;
background: var(--danger-bg);
color: var(--danger);
font-size: 13px;
}}
button {{
width: 100%;
height: 38px;
margin-top: 12px;
border: 0;
border-radius: 12px;
background: var(--primary);
color: white;
font: inherit;
font-weight: 700;
cursor: pointer;
box-shadow: 0 16px 34px -14px rgba(24, 24, 27, .42);
transition: background-color .2s ease, box-shadow .2s ease;
}}
button:hover {{
background: #27272a;
box-shadow: 0 16px 34px -14px rgba(24, 24, 27, .56);
}}
.hint {{
margin-top: 8px;
margin-bottom: 0;
font-size: 12px;
}}
.compact-help {{
display: inline;
margin-left: 6px;
color: var(--muted);
font-weight: 500;
font-size: 12px;
}}
.topline {{
display: none;
}}
.badge {{
min-height: 26px;
display: inline-flex;
align-items: center;
padding: 0 10px;
border: 1px solid var(--line);
border-radius: 999px;
background: rgba(255, 255, 255, .76);
color: #52525b;
font-size: 12px;
font-weight: 650;
white-space: nowrap;
}}
@media (max-width: 640px) {{
body {{ padding: 10px; }}
main {{ padding: 10px; }}
.setup-header {{ align-items: flex-start; padding: 6px 4px 10px; }}
.title-wrap {{ align-items: flex-start; }}
.panel-grid, .panel-wide {{ grid-template-columns: 1fr; }}
.grid, .checks {{ grid-template-columns: 1fr; }}
.span-2 {{ grid-column: auto; }}
.row {{ grid-template-columns: 1fr; }}
.badge {{ display: none; }}
}}
</style>
</head>
<body>
<main>
<div class="setup-header">
<div class="title-wrap">
<div class="brand-mark">FCB</div>
<div>
<h1>初始化 FileCodeBox</h1>
<p>首次配置管理员密码、上传限制和取件策略,后续可在后台调整。</p>
</div>
</div>
<span class="badge">首次配置向导</span>
</div>
<form method="post" action="/setup" autocomplete="off">
{error_block}
<div class="panel-grid">
<section class="panel">
<div class="panel-title">基础设置</div>
<label for="site_name">站点名称</label>
<input id="site_name" name="site_name" maxlength="80" value="{escaped_site_name}" placeholder="文件快递柜 - FileCodeBox">
<label for="admin_password">管理员密码</label>
<input id="admin_password" name="admin_password" type="password" minlength="8" required autofocus>
<label for="confirm_password">确认管理员密码</label>
<input id="confirm_password" name="confirm_password" type="password" minlength="8" required>
</section>
<section class="panel">
<div class="panel-title">上传设置</div>
<label for="upload_size_value">单文件大小限制</label>
<div class="row">
<input id="upload_size_value" name="upload_size_value" type="number" min="1" value="{upload_size_value}" required>
<select name="upload_size_unit" aria-label="文件大小单位">
{size_unit_options}
</select>
</div>
<label for="uploadCount">上传频率 <span class="compact-help">次数 / 分钟</span></label>
<div class="row">
<input id="uploadCount" name="uploadCount" type="number" min="1" value="{upload_count}" required>
<input name="uploadMinute" type="number" min="1" value="{upload_minute}" aria-label="上传检测窗口分钟" required>
</div>
<div class="grid">
<input type="hidden" name="openUpload" value="0">
<label class="check"><input type="checkbox" name="openUpload" value="1"{open_upload_checked}> 允许游客上传</label>
<input type="hidden" name="enableChunk" value="0">
<label class="check"><input type="checkbox" name="enableChunk" value="1"{chunk_checked}> 启用切片上传</label>
</div>
</section>
<section class="panel">
<div class="panel-title">取件与保存</div>
<label for="errorCount">取件错误频率 <span class="compact-help">次数 / 分钟</span></label>
<div class="row">
<input id="errorCount" name="errorCount" type="number" min="1" value="{error_count}" required>
<input name="errorMinute" type="number" min="1" value="{error_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>
<select name="save_time_unit" aria-label="最长保存时间单位">
{save_time_unit_options}
</select>
</div>
<label for="code_generate_type">提取码类型</label>
<select id="code_generate_type" name="code_generate_type">
{code_type_options}
</select>
</section>
<section class="panel panel-wide">
<div>
<div class="panel-title">可用策略</div>
<label>允许的过期方式</label>
<div class="checks">
{expire_style_inputs}
</div>
</div>
<div>
<label for="allowed_file_types">允许文件类型 <span class="compact-help">逗号分隔,* 表示不限制</span></label>
<input id="allowed_file_types" name="allowed_file_types" value="{escaped_allowed_types}" placeholder="* 或 .zip, image/*">
</div>
</section>
</div>
<button type="submit">完成初始化</button>
</form>
</main>
</body>
</html>"""
def build_setup_success_page() -> str:
return """<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="refresh" content="2;url=/#/admin">
<title>初始化完成</title>
<style>
body {
margin: 0;
min-height: 100vh;
display: grid;
place-items: center;
padding: 24px;
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
background: #f6f8fb;
color: #172033;
}
main {
width: min(100%, 420px);
padding: 28px;
border: 1px solid #d9e1ec;
border-radius: 8px;
background: #fff;
text-align: center;
box-shadow: 0 18px 50px rgba(23, 32, 51, .08);
}
h1 { margin: 0 0 10px; font-size: 24px; letter-spacing: 0; }
p { margin: 0 0 22px; color: #60708a; line-height: 1.65; }
a {
display: inline-flex;
align-items: center;
justify-content: center;
min-height: 42px;
padding: 0 18px;
border-radius: 6px;
background: #2563eb;
color: white;
text-decoration: none;
font-weight: 700;
}
</style>
</head>
<body>
<main>
<h1>初始化完成</h1>
<p>管理员密码已设置,请使用刚才的密码登录后台。</p>
<a href="/#/admin">进入后台</a>
</main>
</body>
</html>"""
def setup_response(content: str, status_code: int = 200) -> HTMLResponse:
return HTMLResponse(
content=content,
status_code=status_code,
media_type="text/html",
headers={"Cache-Control": "no-store"},
)
def is_setup_path(path: str) -> bool:
return path.rstrip("/") == "/setup"
def wants_html_response(request: Request) -> bool:
if request.method not in {"GET", "HEAD"}:
return False
accept = request.headers.get("accept", "")
return not accept or "text/html" in accept or "*/*" in accept
async def read_setup_payload(request: Request) -> dict:
content_type = request.headers.get("content-type", "")
if "application/json" in content_type:
data = await request.json()
return data if isinstance(data, dict) else {}
body = (await request.body()).decode("utf-8")
return {
key: values if len(values) > 1 else values[-1]
for key, values in parse_qs(body).items()
}
@asynccontextmanager
async def lifespan(app: FastAPI):
logger.info("正在初始化应用...")
@@ -99,31 +717,30 @@ async def load_config():
key="sys_start", defaults={"value": int(time.time() * 1000)}
)
await refresh_settings()
await migrate_password_to_hash()
await ensure_security_settings()
ip_limit["error"].minutes = settings.errorMinute
ip_limit["error"].count = settings.errorCount
ip_limit["upload"].minutes = settings.uploadMinute
ip_limit["upload"].count = settings.uploadCount
async def migrate_password_to_hash():
if not is_password_hashed(settings.admin_token):
hashed = hash_password(settings.admin_token)
settings.admin_token = hashed
config_record = await KeyValue.filter(key="settings").first()
if config_record and config_record.value:
config_record.value["admin_token"] = hashed
await config_record.save()
logger.info("已将管理员密码迁移为哈希存储")
app = FastAPI(lifespan=lifespan)
@app.middleware("http")
async def refresh_settings_middleware(request, call_next):
await refresh_settings()
if not is_runtime_initialized() and not is_setup_path(request.url.path):
if wants_html_response(request):
return setup_response(build_setup_page())
return JSONResponse(
status_code=428,
content={
"code": 428,
"message": "系统未初始化,请先完成初始化",
"msg": "系统未初始化,请先完成初始化",
"detail": {"setup": "/setup"},
},
)
return await call_next(request)
app.add_middleware(
@@ -149,6 +766,43 @@ app.include_router(presign_api, prefix="/api")
app.include_router(admin_api)
@app.get("/setup", include_in_schema=False)
@app.get("/setup/", include_in_schema=False)
async def setup_page():
if is_runtime_initialized():
return RedirectResponse(url="/", status_code=303)
return setup_response(build_setup_page())
@app.post("/setup", include_in_schema=False)
@app.post("/setup/", include_in_schema=False)
async def setup_submit(request: Request):
if is_runtime_initialized():
return RedirectResponse(url="/", status_code=303)
data = await read_setup_payload(request)
admin_password = str(data.get("admin_password") or "")
confirm_password = str(data.get("confirm_password") or "")
site_name = str(data.get("site_name") or "")
if admin_password != confirm_password:
return setup_response(build_setup_page("两次输入的管理员密码不一致", data), 400)
try:
setup_options = parse_setup_options(data)
await initialize_system(
admin_password=admin_password,
site_name=site_name,
setup_options=setup_options,
)
except ValueError as exc:
return setup_response(build_setup_page(str(exc), data), 400)
if "application/json" in request.headers.get("accept", ""):
return APIResponse(detail={"ok": True, "admin": "/#/admin"})
return setup_response(build_setup_success_page())
def resolve_theme_root():
themes_root = (BASE_DIR / "themes").resolve()
theme_root = (BASE_DIR / str(settings.themesSelect)).resolve()
+2 -2
View File
@@ -254,7 +254,7 @@ python main.py
|------|------|
| **分享文件** | 打开网页 → 选择/拖拽文件 → 设置有效期 → 获取提取码 |
| **获取文件** | 打开网页 → 输入提取码 → 下载文件或查看文本 |
| **管理后台** | 访问 `/#/admin` → 输入密码 `FileCodeBox2023` |
| **管理后台** | 首次访问站点完成初始化 → 访问 `/#/admin` → 输入初始化时设置的密码 |
### 命令行使用(curl)
@@ -323,7 +323,7 @@ curl -L "http://localhost:12345/share/select/?code=提取码" -o filename
# 1. 获取 token
curl -X POST "http://localhost:12345/admin/login" \
-H "Content-Type: application/json" \
-d '{"password": "FileCodeBox2023"}'
-d '{"password": "<初始化时设置的管理员密码>"}'
# 2. 携带 token 上传
curl -X POST "http://localhost:12345/share/file/" \
+2 -2
View File
@@ -254,7 +254,7 @@ python main.py
|-----------|-------|
| **Share File** | Open website → Select/drag files → Set expiration → Get passcode |
| **Retrieve File** | Open website → Enter passcode → Download file or view text |
| **Admin Panel** | Visit `/#/admin` → Enter password `FileCodeBox2023` |
| **Admin Panel** | Complete first-run setup → Visit `/#/admin` → Enter the password set during setup |
### Command Line Usage (curl)
@@ -323,7 +323,7 @@ curl -L "http://localhost:12345/share/select/?code=PASSCODE" -o filename
# 1. Get token
curl -X POST "http://localhost:12345/admin/login" \
-H "Content-Type: application/json" \
-d '{"password": "FileCodeBox2023"}'
-d '{"password": "<admin-password-set-during-setup>"}'
# 2. Upload with token
curl -X POST "http://localhost:12345/share/file/" \
-6
View File
@@ -1,6 +0,0 @@
import sys
from pathlib import Path
PROJECT_ROOT = Path(__file__).resolve().parents[1]
if str(PROJECT_ROOT) not in sys.path:
sys.path.insert(0, str(PROJECT_ROOT))
+221
View File
@@ -0,0 +1,221 @@
import asyncio
import copy
import unittest
import apps.admin.services as admin_services
import core.config as core_config
from apps.admin.dependencies import create_token, verify_token
from apps.admin.services import ConfigService
from main import parse_setup_options
from core.security import (
LEGACY_DEFAULT_ADMIN_TOKEN,
is_config_initialized,
prepare_security_config,
)
from core.settings import DEFAULT_CONFIG, settings
from core.utils import hash_password, verify_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 SecurityConfigTests(unittest.TestCase):
def test_initial_security_config_requires_setup_and_generates_jwt_secret(self):
result = prepare_security_config(DEFAULT_CONFIG)
self.assertTrue(result.changed)
self.assertTrue(result.setup_required)
self.assertEqual(result.config["admin_token"], "")
self.assertFalse(is_config_initialized(result.config))
self.assertGreaterEqual(len(result.config["jwt_secret"]), 32)
def test_legacy_default_password_requires_setup(self):
config = copy.deepcopy(DEFAULT_CONFIG)
config["admin_token"] = hash_password(LEGACY_DEFAULT_ADMIN_TOKEN)
config["jwt_secret"] = "j" * 48
result = prepare_security_config(config)
self.assertTrue(result.setup_required)
self.assertEqual(result.config["admin_token"], "")
self.assertEqual(result.config["jwt_secret"], "j" * 48)
def test_custom_plaintext_password_is_hashed_and_initialized(self):
config = copy.deepcopy(DEFAULT_CONFIG)
config["admin_token"] = "custom-password"
config["jwt_secret"] = "j" * 48
result = prepare_security_config(config)
self.assertTrue(result.password_hashed)
self.assertTrue(is_config_initialized(result.config))
self.assertTrue(verify_password("custom-password", result.config["admin_token"]))
class SetupOptionTests(unittest.TestCase):
def test_parse_setup_options_converts_common_fields(self):
options = parse_setup_options(
{
"upload_size_value": "20",
"upload_size_unit": "MB",
"save_time_value": "7",
"save_time_unit": "day",
"uploadCount": "30",
"uploadMinute": "2",
"errorCount": "5",
"errorMinute": "1",
"openUpload": ["0", "1"],
"enableChunk": "0",
"code_generate_type": "secret",
"expireStyle": ["day", "count"],
"allowed_file_types": ".zip, image/*",
}
)
self.assertEqual(options["uploadSize"], 20 * 1024 * 1024)
self.assertEqual(options["max_save_seconds"], 7 * 86400)
self.assertEqual(options["uploadCount"], 30)
self.assertEqual(options["uploadMinute"], 2)
self.assertEqual(options["errorCount"], 5)
self.assertEqual(options["errorMinute"], 1)
self.assertEqual(options["openUpload"], 1)
self.assertEqual(options["enableChunk"], 0)
self.assertEqual(options["code_generate_type"], "secret")
self.assertEqual(options["expireStyle"], ["day", "count"])
self.assertEqual(options["allowed_file_types"], [".zip", "image/*"])
def test_parse_setup_options_allows_turning_guest_upload_off(self):
options = parse_setup_options(
{
"openUpload": "0",
"expireStyle": ["day"],
}
)
self.assertEqual(options["openUpload"], 0)
def test_parse_setup_options_requires_expire_style(self):
with self.assertRaises(ValueError):
parse_setup_options({"expireStyle": []})
class AdminJwtTests(SettingsOverrideMixin, unittest.TestCase):
def test_admin_jwt_signature_uses_independent_secret(self):
settings.admin_token = hash_password("old-admin-password")
settings.jwt_secret = "j" * 48
token = create_token({"is_admin": True}, expires_in=60)
self.assertTrue(verify_token(token)["is_admin"])
settings.admin_token = hash_password("new-admin-password")
self.assertTrue(verify_token(token)["is_admin"])
settings.jwt_secret = "k" * 48
with self.assertRaises(ValueError):
verify_token(token)
class FakeKeyValue:
saved_value = None
@classmethod
async def update_or_create(cls, key, defaults):
cls.saved_value = defaults["value"]
return None, True
async def fake_refresh_settings():
return None
class FakeConfigRecord:
def __init__(self, value):
self.value = value
class FakeConfigQuery:
async def first(self):
return FakeConfigKeyValue.record
class FakeConfigKeyValue:
record = None
saved_value = None
@classmethod
def filter(cls, key):
return FakeConfigQuery()
@classmethod
async def update_or_create(cls, key, defaults):
cls.saved_value = defaults["value"]
return None, True
class ConfigServiceSecurityTests(SettingsOverrideMixin, unittest.TestCase):
def test_admin_password_update_rotates_jwt_secret(self):
old_secret = "j" * 48
settings.user_config = {
**copy.deepcopy(DEFAULT_CONFIG),
"admin_token": hash_password("old-admin-password"),
"jwt_secret": old_secret,
}
original_key_value = admin_services.KeyValue
original_refresh_settings = admin_services.refresh_settings
admin_services.KeyValue = FakeKeyValue
admin_services.refresh_settings = fake_refresh_settings
FakeKeyValue.saved_value = None
try:
asyncio.run(ConfigService().update_config({"admin_token": "new-admin-password"}))
finally:
admin_services.KeyValue = original_key_value
admin_services.refresh_settings = original_refresh_settings
self.assertIsNotNone(FakeKeyValue.saved_value)
self.assertTrue(verify_password("new-admin-password", FakeKeyValue.saved_value["admin_token"]))
self.assertNotEqual(FakeKeyValue.saved_value["jwt_secret"], old_secret)
self.assertGreaterEqual(len(FakeKeyValue.saved_value["jwt_secret"]), 32)
def test_initialize_system_sets_admin_password_and_jwt_secret(self):
original_key_value = core_config.KeyValue
original_refresh_settings = core_config.refresh_settings
FakeConfigKeyValue.record = FakeConfigRecord(
{
**copy.deepcopy(DEFAULT_CONFIG),
"admin_token": "",
"jwt_secret": "",
}
)
FakeConfigKeyValue.saved_value = None
core_config.KeyValue = FakeConfigKeyValue
core_config.refresh_settings = fake_refresh_settings
try:
asyncio.run(
core_config.initialize_system(
admin_password="new-admin-password",
site_name="我的文件快递柜",
setup_options={
"uploadSize": 50 * 1024 * 1024,
"errorCount": 6,
"expireStyle": ["day", "count"],
},
)
)
finally:
core_config.KeyValue = original_key_value
core_config.refresh_settings = original_refresh_settings
self.assertIsNotNone(FakeConfigKeyValue.saved_value)
self.assertTrue(
verify_password("new-admin-password", FakeConfigKeyValue.saved_value["admin_token"])
)
self.assertGreaterEqual(len(FakeConfigKeyValue.saved_value["jwt_secret"]), 32)
self.assertEqual(FakeConfigKeyValue.saved_value["name"], "我的文件快递柜")
self.assertEqual(FakeConfigKeyValue.saved_value["uploadSize"], 50 * 1024 * 1024)
self.assertEqual(FakeConfigKeyValue.saved_value["errorCount"], 6)
self.assertEqual(FakeConfigKeyValue.saved_value["expireStyle"], ["day", "count"])
+12 -3
View File
@@ -3,7 +3,7 @@ import unittest
from fastapi import HTTPException
from core.settings import settings
from core.settings import BASE_DIR, settings
from main import index, resolve_theme_file
@@ -16,12 +16,21 @@ class SettingsOverrideMixin:
class ThemeAssetTests(SettingsOverrideMixin, unittest.TestCase):
def get_theme_index_asset(self, theme: str) -> str:
assets = sorted((BASE_DIR / theme / "assets").glob("index-*.js"))
self.assertTrue(assets, f"{theme} 缺少 index JS 资源")
return assets[0].name
def test_resolves_assets_from_current_theme(self):
settings.themesSelect = "themes/2023"
theme_2023_asset = resolve_theme_file("assets", "index-CxMsK_Ni.js")
theme_2023_asset = resolve_theme_file(
"assets", self.get_theme_index_asset("themes/2023")
)
settings.themesSelect = "themes/2024"
theme_2024_asset = resolve_theme_file("assets", "index-DjzJA_Oj.js")
theme_2024_asset = resolve_theme_file(
"assets", self.get_theme_index_asset("themes/2024")
)
self.assertIn("themes/2023/assets", str(theme_2023_asset))
self.assertIn("themes/2024/assets", str(theme_2024_asset))
-271
View File
@@ -1,271 +0,0 @@
import asyncio
import unittest
from datetime import timedelta
from types import SimpleNamespace
from fastapi import HTTPException
import apps.base.views as views
from apps.base.schemas import PresignUploadInitRequest
from core.settings import settings
from core.utils import get_now
class SettingsOverrideMixin:
def setUp(self):
self._original_user_config = dict(settings.user_config)
def tearDown(self):
settings.user_config = self._original_user_config
class FakeUploadLimiter:
def __init__(self):
self.added_ips = []
def add_ip(self, ip):
self.added_ips.append(ip)
class FakeUploadFile:
def __init__(self, size):
self.size = size
self.filename = "upload.txt"
self.content_type = "text/plain"
class FakeStorage:
def __init__(self, presigned_url=None, exists=True):
self.presigned_url = presigned_url
self.exists = exists
self.saved = []
self.deleted = []
async def generate_presigned_upload_url(self, save_path, expires_in):
self.last_presign_request = (save_path, expires_in)
return self.presigned_url
async def save_file(self, file, save_path):
self.saved.append((file, save_path))
async def file_exists(self, save_path):
self.last_exists_path = save_path
return self.exists
async def delete_file(self, file_code):
self.deleted.append(file_code)
class FakeSession:
def __init__(self, mode="direct", file_size=12, expired=False):
self.upload_id = "upload-1"
self.file_name = "upload.txt"
self.file_size = file_size
self.save_path = "share/data/2026/06/06/upload-1/upload.txt"
self.mode = mode
self.expire_value = 2
self.expire_style = "day"
self.created_at = None
self.expires_at = None
self.expired = expired
self.deleted = False
async def is_expired(self):
return self.expired
async def delete(self):
self.deleted = True
class FakeSessionQuery:
def __init__(self, session):
self.session = session
async def first(self):
return self.session
class FakePresignUploadSession:
created_payload = None
session = None
@classmethod
async def create(cls, **kwargs):
cls.created_payload = kwargs
return SimpleNamespace(**kwargs)
@classmethod
def filter(cls, **kwargs):
cls.filter_kwargs = kwargs
return FakeSessionQuery(cls.session)
class FakeFileUploadService:
created_records = []
@staticmethod
async def generate_file_path(file_name, upload_id=None):
filename = file_name.strip()
return (
f"share/data/2026/06/06/{upload_id}",
".txt",
"upload",
filename,
f"share/data/2026/06/06/{upload_id}/{filename}",
)
@classmethod
async def create_file_record(
cls, file_name, file_size, file_path, expire_value, expire_style, **extra_fields
):
cls.created_records.append(
{
"file_name": file_name,
"file_size": file_size,
"file_path": file_path,
"expire_value": expire_value,
"expire_style": expire_style,
**extra_fields,
}
)
return "12345"
class PresignUploadFlowTests(SettingsOverrideMixin, unittest.TestCase):
def setUp(self):
super().setUp()
self._original_storages = dict(views.storages)
self._original_session_model = views.PresignUploadSession
self._original_file_upload_service = views.FileUploadService
self._original_upload_limiter = views.ip_limit["upload"]
self.storage = FakeStorage()
views.storages = {"local": lambda: self.storage}
views.PresignUploadSession = FakePresignUploadSession
views.FileUploadService = FakeFileUploadService
views.ip_limit["upload"] = FakeUploadLimiter()
FakePresignUploadSession.created_payload = None
FakePresignUploadSession.session = None
FakeFileUploadService.created_records = []
settings.file_storage = "local"
settings.uploadSize = 1024
settings.allowed_file_types = ["*"]
settings.expireStyle = ["day", "hour", "minute", "forever", "count"]
def tearDown(self):
views.storages = self._original_storages
views.PresignUploadSession = self._original_session_model
views.FileUploadService = self._original_file_upload_service
views.ip_limit["upload"] = self._original_upload_limiter
super().tearDown()
def test_init_returns_proxy_urls_when_storage_has_no_presigned_url(self):
response = asyncio.run(
views.presign_upload_init(
PresignUploadInitRequest(
file_name="upload.txt",
file_size=12,
expire_value=2,
expire_style="day",
),
ip="127.0.0.1",
)
)
detail = response.detail
self.assertEqual(detail["mode"], "proxy")
self.assertEqual(detail["upload_url"], detail["proxy_upload_url"])
self.assertEqual(detail["legacy_proxy_upload_url"], f"/api{detail['proxy_upload_url']}")
self.assertEqual(FakePresignUploadSession.created_payload["file_name"], "upload.txt")
self.assertEqual(FakePresignUploadSession.created_payload["file_size"], 12)
self.assertEqual(views.ip_limit["upload"].added_ips, ["127.0.0.1"])
def test_init_returns_direct_url_when_storage_supports_presigned_upload(self):
self.storage.presigned_url = "https://storage.example/upload"
response = asyncio.run(
views.presign_upload_init(
PresignUploadInitRequest(file_name="upload.txt", file_size=12),
ip="127.0.0.1",
)
)
self.assertEqual(response.detail["mode"], "direct")
self.assertEqual(response.detail["upload_url"], "https://storage.example/upload")
self.assertNotIn("proxy_upload_url", response.detail)
def test_init_rejects_disallowed_expiration_style(self):
with self.assertRaises(HTTPException) as error:
asyncio.run(
views.presign_upload_init(
PresignUploadInitRequest(
file_name="upload.txt",
file_size=12,
expire_style="week",
),
ip="127.0.0.1",
)
)
self.assertEqual(error.exception.status_code, 400)
def test_confirm_requires_uploaded_direct_file_before_creating_record(self):
FakePresignUploadSession.session = FakeSession(mode="direct")
self.storage.exists = True
response = asyncio.run(views.presign_upload_confirm("upload-1", ip="127.0.0.1"))
self.assertEqual(response.detail, {"code": "12345", "name": "upload.txt"})
self.assertTrue(FakePresignUploadSession.session.deleted)
self.assertEqual(FakeFileUploadService.created_records[0]["file_size"], 12)
self.assertEqual(
FakeFileUploadService.created_records[0]["file_path"],
"share/data/2026/06/06/upload-1",
)
def test_confirm_rejects_missing_uploaded_direct_file(self):
FakePresignUploadSession.session = FakeSession(mode="direct")
self.storage.exists = False
with self.assertRaises(HTTPException) as error:
asyncio.run(views.presign_upload_confirm("upload-1", ip="127.0.0.1"))
self.assertEqual(error.exception.status_code, 404)
self.assertFalse(FakePresignUploadSession.session.deleted)
self.assertEqual(FakeFileUploadService.created_records, [])
def test_proxy_upload_rejects_size_mismatch_before_saving_file(self):
FakePresignUploadSession.session = FakeSession(mode="proxy", file_size=10)
with self.assertRaises(HTTPException) as error:
asyncio.run(
views.presign_upload_proxy(
"upload-1",
file=FakeUploadFile(size=2048),
ip="127.0.0.1",
)
)
self.assertEqual(error.exception.status_code, 403)
self.assertEqual(self.storage.saved, [])
def test_cancel_direct_session_removes_uploaded_object_when_present(self):
FakePresignUploadSession.session = FakeSession(mode="direct")
self.storage.exists = True
response = asyncio.run(views.presign_upload_cancel("upload-1"))
self.assertEqual(response.detail, {"message": "上传会话已取消"})
self.assertTrue(FakePresignUploadSession.session.deleted)
self.assertEqual(len(self.storage.deleted), 1)
self.assertEqual(self.storage.deleted[0].file_path, "share/data/2026/06/06/upload-1")
self.assertEqual(self.storage.deleted[0].uuid_file_name, "upload.txt")
def test_expired_session_is_deleted_and_rejected(self):
FakePresignUploadSession.session = FakeSession(mode="direct", expired=True)
FakePresignUploadSession.session.expires_at = asyncio.run(get_now()) - timedelta(seconds=1)
with self.assertRaises(HTTPException) as error:
asyncio.run(views.presign_upload_confirm("upload-1", ip="127.0.0.1"))
self.assertEqual(error.exception.status_code, 404)
self.assertTrue(FakePresignUploadSession.session.deleted)