From 6587ec86bed9dbec551696269a24ebec546510f5 Mon Sep 17 00:00:00 2001 From: Marrrrrrrrry <34876935+Marrrrrrrrry@users.noreply.github.com> Date: Wed, 9 Sep 2026 17:25:42 +0800 Subject: [PATCH] refactor: extract setup wizard and public pages from main.py (945 -> 148 lines) - apps/base/setup_wizard.py: form parsing rules, setup options, and the two admin-facing HTML pages - apps/base/pages.py: setup/assets/index/robots/public-config routes and theme resolution (404 handler registered on the app in main.py) - tests updated to import from the new modules --- apps/base/pages.py | 137 +++++ apps/base/setup_wizard.py | 692 +++++++++++++++++++++ main.py | 825 +------------------------- tests/test_admin_security.py | 2 +- tests/test_index_template_escaping.py | 10 +- tests/test_issue_476_theme_assets.py | 2 +- tests/test_issue_480_admin_address.py | 2 +- tests/test_issue_482_share_usage.py | 2 +- 8 files changed, 852 insertions(+), 820 deletions(-) create mode 100644 apps/base/pages.py create mode 100644 apps/base/setup_wizard.py diff --git a/apps/base/pages.py b/apps/base/pages.py new file mode 100644 index 0000000..0d7b28b --- /dev/null +++ b/apps/base/pages.py @@ -0,0 +1,137 @@ +"""Public-facing pages and routes: setup wizard, theme assets, index, +robots.txt, and the public config endpoints.""" +import html + +from fastapi import APIRouter, HTTPException, Request +from fastapi.responses import FileResponse, HTMLResponse, RedirectResponse + +from apps.base.config import initialize_system, is_runtime_initialized +from apps.base.setup_wizard import ( + build_public_config, + build_public_meta, + build_setup_page, + build_setup_success_page, + parse_setup_options, + read_setup_payload, + setup_response, +) +from core.response import APIResponse +from core.settings import BASE_DIR, DEFAULT_CONFIG, settings +from core.version import APP_VERSION + +router = APIRouter() + + +@router.get("/setup", include_in_schema=False) +@router.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()) + + +@router.post("/setup", include_in_schema=False) +@router.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() + try: + theme_root.relative_to(themes_root) + except ValueError: + theme_root = (BASE_DIR / DEFAULT_CONFIG["themesSelect"]).resolve() + if not theme_root.exists(): + theme_root = (BASE_DIR / DEFAULT_CONFIG["themesSelect"]).resolve() + return theme_root + + +def resolve_theme_file(*parts: str): + theme_root = resolve_theme_root() + file_path = theme_root.joinpath(*parts).resolve() + # 防止通过 /assets/../ 读取主题目录外的文件。 + try: + file_path.relative_to(theme_root) + except ValueError: + raise HTTPException(status_code=404, detail="资源不存在") + if not file_path.is_file(): + raise HTTPException(status_code=404, detail="资源不存在") + return file_path + + +@router.get("/assets/{asset_path:path}", include_in_schema=False) +async def theme_asset(asset_path: str): + return FileResponse(resolve_theme_file("assets", asset_path)) + + +@router.get("/") +async def index(request=None, exc=None): + # Site config is admin input (and during the setup window anyone can claim it); + # always escape before injecting into the theme template to prevent stored XSS + # (mirrors the setup page). + return HTMLResponse( + content=resolve_theme_file("index.html") + .read_text(encoding="utf-8") + .replace("{{title}}", html.escape(str(settings.name))) + .replace("{{description}}", html.escape(str(settings.description))) + .replace("{{keywords}}", html.escape(str(settings.keywords))) + .replace("{{opacity}}", html.escape(str(settings.opacity))) + .replace("{{background}}", html.escape(str(settings.background))), + media_type="text/html", + headers={"Cache-Control": "no-cache"}, + ) + +@router.get("/robots.txt") +async def robots(): + return HTMLResponse(content=settings.robotsText, media_type="text/plain") + + +@router.post("/") +async def get_config(): + return APIResponse(detail=build_public_config()) + + +@router.get("/api/v1/config") +async def get_public_config(): + return APIResponse( + detail={ + "config": build_public_config(), + "meta": build_public_meta(), + } + ) + + +@router.get("/health") +async def health_check(): + return APIResponse( + detail={ + "status": "ok", + "version": APP_VERSION, + "storage": settings.file_storage, + "theme": settings.themesSelect, + } + ) diff --git a/apps/base/setup_wizard.py b/apps/base/setup_wizard.py new file mode 100644 index 0000000..2f063ba --- /dev/null +++ b/apps/base/setup_wizard.py @@ -0,0 +1,692 @@ +"""Setup wizard: form parsing rules and the two admin-facing HTML pages. + +Pure presentation/logic — no router here; routes live in apps.base.pages. +""" +import html +from urllib.parse import parse_qs + +from fastapi import Request +from fastapi.responses import HTMLResponse + +from core.settings import DEFAULT_CONFIG, settings +from core.version import APP_VERSION + + +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 normalize_public_flag(value) -> int: + if isinstance(value, str): + return int(value.strip().lower() in {"1", "true", "on", "yes"}) + return int(bool(value)) + + +def build_public_config() -> dict: + return { + "name": settings.name, + "description": settings.description, + "explain": settings.page_explain, + "uploadSize": settings.uploadSize, + "allowedFileTypes": settings.allowed_file_types, + "expireStyle": settings.expireStyle, + "enableChunk": settings.enableChunk, + "openUpload": settings.openUpload, + "notify_title": settings.notify_title, + "notify_content": settings.notify_content, + "show_admin_address": normalize_public_flag(settings.showAdminAddr), + "max_save_seconds": settings.max_save_seconds, + } + + +def build_public_meta() -> dict: + return { + "version": APP_VERSION, + "api": { + "legacyConfig": "/", + "publicConfig": "/api/v1/config", + "health": "/health", + }, + "features": { + "chunkUpload": bool(settings.enableChunk), + "guestUpload": bool(settings.openUpload), + "adminAddressVisible": bool(normalize_public_flag(settings.showAdminAddr)), + "expirationModes": settings.expireStyle, + }, + "limits": { + "uploadSize": settings.uploadSize, + "allowedFileTypes": settings.allowed_file_types, + "maxSaveSeconds": settings.max_save_seconds, + "uploadWindowMinutes": settings.uploadMinute, + "uploadWindowCount": settings.uploadCount, + }, + } + + + + + +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", DEFAULT_CONFIG["code_generate_type"] + ) + 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 + ), + "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)), + "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'' + ) + 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"])) + ) + 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 "" + ) + chunk_checked = ( + " checked" if normalize_bool_field(form, "enableChunk", False) else "" + ) + code_generate_type = get_form_value( + form, "code_generate_type", DEFAULT_CONFIG["code_generate_type"] + ) + 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'' + for unit in FILE_SIZE_UNITS + ) + save_time_unit_options = "\n".join( + f'' + for unit, label in [ + ("second", "秒"), + ("minute", "分钟"), + ("hour", "小时"), + ("day", "天"), + ] + ) + code_type_options = "\n".join( + f'' + for value, label in [("number", "数字"), ("secret", "随机字符")] + ) + error_block = ( + f'' if escaped_error else "" + ) + return f""" + + + + + 初始化 FileCodeBox + + + +
+
+
+
FCB
+
+

初始化 FileCodeBox

+

首次配置管理员密码、上传限制和取件策略,后续可在后台调整。

+
+
+ 首次配置向导 +
+
+ {error_block} +
+
+
基础设置
+ + + + + + + + +
+ +
+
上传设置
+ +
+ + +
+ + +
+ + +
+ +
+ + + + +
+
+ +
+
取件与保存
+ +
+ + +
+ + +
+ + +
+ + +
+ + +
+ + + +
+ +
+
+
可用策略
+ +
+ {expire_style_inputs} +
+
+ +
+ + +
+
+
+ +
+
+ +""" + + +def build_setup_success_page() -> str: + return """ + + + + + + 初始化完成 + + + +
+

初始化完成

+

管理员密码已设置,请使用刚才的密码登录后台。

+ 进入后台 +
+ +""" + +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() + } diff --git a/main.py b/main.py index 33ee2f6..f860f0c 100644 --- a/main.py +++ b/main.py @@ -3,720 +3,38 @@ # @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, Request +from fastapi import FastAPI from fastapi.middleware.cors import CORSMiddleware -from fastapi.responses import FileResponse, HTMLResponse, JSONResponse, RedirectResponse +from fastapi.responses import JSONResponse from tortoise import Tortoise from tortoise.contrib.fastapi import register_tortoise from apps.admin.views import admin_api -from apps.base.models import KeyValue -from apps.base.views import share_api, chunk_api, presign_api from apps.base.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.errors import StorageError -from core.logger import get_log_level_name, is_access_log_enabled, logger -from core.response import APIResponse -from core.settings import settings, BASE_DIR, DEFAULT_CONFIG +from apps.base.models import KeyValue +from apps.base.pages import index, router as pages_router +from apps.base.setup_wizard import build_setup_page, is_setup_path, setup_response, wants_html_response from apps.base.tasks import ( clean_expired_presign_sessions, clean_incomplete_uploads, delete_expire_files, ) +from apps.base.views import share_api, chunk_api, presign_api +from core.database import db_startup_lock, get_db_config, init_db +from core.errors import StorageError +from core.logger import get_log_level_name, is_access_log_enabled, logger +from core.settings import settings from core.version import APP_VERSION -def normalize_public_flag(value) -> int: - if isinstance(value, str): - return int(value.strip().lower() in {"1", "true", "on", "yes"}) - return int(bool(value)) - - -def build_public_config() -> dict: - return { - "name": settings.name, - "description": settings.description, - "explain": settings.page_explain, - "uploadSize": settings.uploadSize, - "allowedFileTypes": settings.allowed_file_types, - "expireStyle": settings.expireStyle, - "enableChunk": settings.enableChunk, - "openUpload": settings.openUpload, - "notify_title": settings.notify_title, - "notify_content": settings.notify_content, - "show_admin_address": normalize_public_flag(settings.showAdminAddr), - "max_save_seconds": settings.max_save_seconds, - } - - -def build_public_meta() -> dict: - return { - "version": APP_VERSION, - "api": { - "legacyConfig": "/", - "publicConfig": "/api/v1/config", - "health": "/health", - }, - "features": { - "chunkUpload": bool(settings.enableChunk), - "guestUpload": bool(settings.openUpload), - "adminAddressVisible": bool(normalize_public_flag(settings.showAdminAddr)), - "expirationModes": settings.expireStyle, - }, - "limits": { - "uploadSize": settings.uploadSize, - "allowedFileTypes": settings.allowed_file_types, - "maxSaveSeconds": settings.max_save_seconds, - "uploadWindowMinutes": settings.uploadMinute, - "uploadWindowCount": settings.uploadCount, - }, - } - - -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", DEFAULT_CONFIG["code_generate_type"] - ) - 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 - ), - "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)), - "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'' - ) - 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"])) - ) - 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 "" - ) - chunk_checked = ( - " checked" if normalize_bool_field(form, "enableChunk", False) else "" - ) - code_generate_type = get_form_value( - form, "code_generate_type", DEFAULT_CONFIG["code_generate_type"] - ) - 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'' - for unit in FILE_SIZE_UNITS - ) - save_time_unit_options = "\n".join( - f'' - for unit, label in [ - ("second", "秒"), - ("minute", "分钟"), - ("hour", "小时"), - ("day", "天"), - ] - ) - code_type_options = "\n".join( - f'' - for value, label in [("number", "数字"), ("secret", "随机字符")] - ) - error_block = ( - f'' if escaped_error else "" - ) - return f""" - - - - - 初始化 FileCodeBox - - - -
-
-
-
FCB
-
-

初始化 FileCodeBox

-

首次配置管理员密码、上传限制和取件策略,后续可在后台调整。

-
-
- 首次配置向导 -
-
- {error_block} -
-
-
基础设置
- - - - - - - - -
- -
-
上传设置
- -
- - -
- - -
- - -
- -
- - - - -
-
- -
-
取件与保存
- -
- - -
- - -
- - -
- - -
- - -
- - - -
- -
-
-
可用策略
- -
- {expire_style_inputs} -
-
- -
- - -
-
-
- -
-
- -""" - - -def build_setup_success_page() -> str: - return """ - - - - - - 初始化完成 - - - -
-

初始化完成

-

管理员密码已设置,请使用刚才的密码登录后台。

- 进入后台 -
- -""" - - -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("正在初始化应用...") @@ -735,8 +53,6 @@ async def lifespan(app: FastAPI): try: yield finally: - # 清理操作 - logger.info("正在关闭应用...") task.cancel() chunk_cleanup_task.cancel() presign_cleanup_task.cancel() @@ -761,6 +77,7 @@ async def load_config(): await refresh_settings() await ensure_security_settings() + app = FastAPI(lifespan=lifespan, version=APP_VERSION) @@ -811,124 +128,10 @@ app.include_router(chunk_api) app.include_router(presign_api) app.include_router(presign_api, prefix="/api") app.include_router(admin_api) +app.include_router(pages_router) - -@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() - try: - theme_root.relative_to(themes_root) - except ValueError: - theme_root = (BASE_DIR / DEFAULT_CONFIG["themesSelect"]).resolve() - if not theme_root.exists(): - theme_root = (BASE_DIR / DEFAULT_CONFIG["themesSelect"]).resolve() - return theme_root - - -def resolve_theme_file(*parts: str): - theme_root = resolve_theme_root() - file_path = theme_root.joinpath(*parts).resolve() - # 防止通过 /assets/../ 读取主题目录外的文件。 - try: - file_path.relative_to(theme_root) - except ValueError: - raise HTTPException(status_code=404, detail="资源不存在") - if not file_path.is_file(): - raise HTTPException(status_code=404, detail="资源不存在") - return file_path - - -@app.get("/assets/{asset_path:path}", include_in_schema=False) -async def theme_asset(asset_path: str): - return FileResponse(resolve_theme_file("assets", asset_path)) - - -@app.exception_handler(404) -@app.get("/") -async def index(request=None, exc=None): - # Site config is admin input (and during the setup window anyone can claim it); - # always escape before injecting into the theme template to prevent stored XSS - # (mirrors the setup page). - return HTMLResponse( - content=resolve_theme_file("index.html") - .read_text(encoding="utf-8") - .replace("{{title}}", html.escape(str(settings.name))) - .replace("{{description}}", html.escape(str(settings.description))) - .replace("{{keywords}}", html.escape(str(settings.keywords))) - .replace("{{opacity}}", html.escape(str(settings.opacity))) - .replace("{{background}}", html.escape(str(settings.background))), - media_type="text/html", - headers={"Cache-Control": "no-cache"}, - ) - - -@app.get("/robots.txt") -async def robots(): - return HTMLResponse(content=settings.robotsText, media_type="text/plain") - - -@app.post("/") -async def get_config(): - return APIResponse(detail=build_public_config()) - - -@app.get("/api/v1/config") -async def get_public_config(): - return APIResponse( - detail={ - "config": build_public_config(), - "meta": build_public_meta(), - } - ) - - -@app.get("/health") -async def health_check(): - return APIResponse( - detail={ - "status": "ok", - "version": APP_VERSION, - "storage": settings.file_storage, - "theme": settings.themesSelect, - } - ) +# 404 时返回主题首页(index 兼任 exception handler 与 GET / 路由) +app.add_exception_handler(404, index) if __name__ == "__main__": diff --git a/tests/test_admin_security.py b/tests/test_admin_security.py index 3be32a4..b48094f 100644 --- a/tests/test_admin_security.py +++ b/tests/test_admin_security.py @@ -10,7 +10,7 @@ from apps.admin.dependencies import create_token, verify_token from apps.admin.schemas import LoginData from apps.admin.services import ConfigService from fastapi import HTTPException -from main import parse_setup_options +from apps.base.setup_wizard import parse_setup_options from core.security import ( LEGACY_DEFAULT_ADMIN_TOKEN, is_config_initialized, diff --git a/tests/test_index_template_escaping.py b/tests/test_index_template_escaping.py index b856709..3b6663c 100644 --- a/tests/test_index_template_escaping.py +++ b/tests/test_index_template_escaping.py @@ -3,7 +3,7 @@ import tempfile import unittest from pathlib import Path -import main +import apps.base.pages as pages from core.settings import settings @@ -17,7 +17,7 @@ class IndexTemplateEscapingTests(unittest.TestCase): def setUp(self): self._original_user_config = dict(settings.user_config) - self._original_resolve_theme_file = main.resolve_theme_file + self._original_resolve_theme_file = pages.resolve_theme_file tmp = tempfile.NamedTemporaryFile( "w", suffix=".html", delete=False, encoding="utf-8" ) @@ -31,14 +31,14 @@ class IndexTemplateEscapingTests(unittest.TestCase): def tearDown(self): settings.user_config = self._original_user_config - main.resolve_theme_file = self._original_resolve_theme_file + pages.resolve_theme_file = self._original_resolve_theme_file self._template_path.unlink() def _patch_template(self): - main.resolve_theme_file = lambda *args, **kwargs: self._template_path + pages.resolve_theme_file = lambda *args, **kwargs: self._template_path def _render_index_html(self) -> str: - return asyncio.run(main.index()).body.decode("utf-8") + return asyncio.run(pages.index()).body.decode("utf-8") def test_malicious_site_config_is_escaped(self): self._patch_template() diff --git a/tests/test_issue_476_theme_assets.py b/tests/test_issue_476_theme_assets.py index 4c5c5f7..1c8f0d4 100644 --- a/tests/test_issue_476_theme_assets.py +++ b/tests/test_issue_476_theme_assets.py @@ -4,7 +4,7 @@ import unittest from fastapi import HTTPException from core.settings import BASE_DIR, settings -from main import index, resolve_theme_file +from apps.base.pages import index, resolve_theme_file from tests.helpers import SettingsOverrideMixin # themes/ is produced by the Dockerfile frontend build (see .gitignore); a bare checkout has no such directory diff --git a/tests/test_issue_480_admin_address.py b/tests/test_issue_480_admin_address.py index 8ff9da5..76a75f3 100644 --- a/tests/test_issue_480_admin_address.py +++ b/tests/test_issue_480_admin_address.py @@ -1,7 +1,7 @@ import unittest from core.settings import settings -from main import build_public_config, build_public_meta +from apps.base.pages import build_public_config, build_public_meta class AdminAddressPublicConfigTests(unittest.TestCase): diff --git a/tests/test_issue_482_share_usage.py b/tests/test_issue_482_share_usage.py index d110701..77550ef 100644 --- a/tests/test_issue_482_share_usage.py +++ b/tests/test_issue_482_share_usage.py @@ -10,7 +10,7 @@ from core.storage import StoredDownload from tests.helpers import close_db, init_memory_db from core.settings import DEFAULT_CONFIG, settings from core.utils import get_now, get_select_token -from main import build_setup_page, parse_setup_options +from apps.base.setup_wizard import build_setup_page, parse_setup_options class FakeStorage: