Compare commits

..
Author SHA1 Message Date
Lan 1ec397af0c test: add presigned upload flow coverage 2026-06-07 14:43:04 +08:00
99 changed files with 36198 additions and 4803 deletions

No files matched your search

Binary file not shown.

Before

Width:  |  Height:  |  Size: 84 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 76 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 133 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 130 KiB

-134
View File
@@ -1,134 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" width="1024" height="1024" viewBox="420 360 1208 1208">
<defs>
<linearGradient id="blue" x1="0" y1="0" x2="1" y2="1">
<stop offset="0" stop-color="#75A7FF"/>
<stop offset="0.52" stop-color="#4E86F7"/>
<stop offset="1" stop-color="#3769D8"/>
</linearGradient>
<linearGradient id="blueSoft" x1="0" y1="0" x2="1" y2="1">
<stop offset="0" stop-color="#EDF4FF"/>
<stop offset="1" stop-color="#C9DCFF"/>
</linearGradient>
<linearGradient id="ear" x1="0" y1="0" x2="0" y2="1">
<stop offset="0" stop-color="#F8FBFF"/>
<stop offset="1" stop-color="#DDE9FF"/>
</linearGradient>
<linearGradient id="earInner" x1="0" y1="0" x2="0" y2="1">
<stop offset="0" stop-color="#FFD8A8"/>
<stop offset="1" stop-color="#F3A76E"/>
</linearGradient>
<linearGradient id="tail" x1="0" y1="0" x2="1" y2="1">
<stop offset="0" stop-color="#6EA2FF"/>
<stop offset="1" stop-color="#315FC8"/>
</linearGradient>
<filter id="softShadow" x="-30%" y="-30%" width="160%" height="180%">
<feDropShadow dx="0" dy="24" stdDeviation="26" flood-color="#1D376C" flood-opacity="0.18"/>
</filter>
<filter id="tinyShadow" x="-50%" y="-50%" width="200%" height="200%">
<feDropShadow dx="0" dy="10" stdDeviation="10" flood-color="#243E72" flood-opacity="0.18"/>
</filter>
</defs>
<!-- 透明底:已去除外围白底 / 圆角框 / 光晕 -->
<!-- Floating audio particles -->
<g fill="#6A9BFA" opacity="0.9">
<circle cx="529" cy="777" r="20"/>
<circle cx="1561" cy="728" r="16"/>
<circle cx="1516" cy="1302" r="14"/>
</g>
<g fill="none" stroke="#8EB4FF" stroke-width="20" stroke-linecap="round" opacity="0.72">
<path d="M440 942c-36 36-36 94 0 130"/>
<path d="M1608 940c36 36 36 94 0 130"/>
</g>
<!-- Tail: a listening loop that wraps the box -->
<path d="M1351 1309c176 27 249 166 165 287-65 93-226 95-337 12"
fill="none" stroke="url(#tail)" stroke-width="114" stroke-linecap="round"
filter="url(#softShadow)"/>
<path d="M1418 1460c57 29 71 80 35 116-38 38-100 25-136-8"
fill="none" stroke="#DDE9FF" stroke-width="54" stroke-linecap="round"/>
<!-- Headphones behind the mascot -->
<path d="M702 1048c0-318 145-507 322-507s322 189 322 507"
fill="none" stroke="#18264A" stroke-width="86" stroke-linecap="round"
filter="url(#tinyShadow)"/>
<path d="M706 834c41-189 160-293 318-293 157 0 278 104 318 293"
fill="none" stroke="#4F86F7" stroke-width="34" stroke-linecap="round"/>
<rect x="625" y="972" width="160" height="300" rx="76" fill="#18264A"/>
<rect x="1263" y="972" width="160" height="300" rx="76" fill="#18264A"/>
<rect x="655" y="1010" width="98" height="225" rx="49" fill="url(#blue)"/>
<rect x="1295" y="1010" width="98" height="225" rx="49" fill="url(#blue)"/>
<!-- Open audio box -->
<g filter="url(#softShadow)">
<path d="M594 1191c0-49 40-89 89-89h682c49 0 89 40 89 89v331c0 77-62 139-139 139H733c-77 0-139-62-139-139z"
fill="url(#blue)"/>
<ellipse cx="1024" cy="1122" rx="430" ry="126" fill="#24345E"/>
<ellipse cx="1024" cy="1118" rx="365" ry="89" fill="#111B37"/>
<path d="M594 1216c189 62 671 62 860 0v311c0 74-60 134-134 134H728c-74 0-134-60-134-134z"
fill="url(#blue)"/>
<path d="M633 1287c181 50 601 55 782 4" fill="none" stroke="#9BC0FF" stroke-width="18" opacity="0.54"/>
</g>
<!-- Fox ears -->
<g filter="url(#softShadow)">
<path d="M719 854C664 713 683 520 751 397c26-47 91-42 115 5l170 331z"
fill="url(#ear)" stroke="#20335F" stroke-width="24" stroke-linejoin="round"/>
<path d="M1329 854c55-141 36-334-32-457-26-47-91-42-115 5l-170 331z"
fill="url(#ear)" stroke="#20335F" stroke-width="24" stroke-linejoin="round"/>
<path d="M758 726c-25-93-16-200 18-271 12-24 44-20 56 4l111 235z"
fill="url(#earInner)"/>
<path d="M1290 726c25-93 16-200-18-271-12-24-44-20-56 4l-111 235z"
fill="url(#earInner)"/>
</g>
<!-- Fox head -->
<g filter="url(#softShadow)">
<path d="M741 788c52-125 160-205 283-205s231 80 283 205c38 92 48 232 3 338-45 105-154 170-286 170s-241-65-286-170c-45-106-35-246 3-338z"
fill="#F9FBFF" stroke="#20335F" stroke-width="26"/>
<path d="M824 1068c52-35 119-51 200-51s148 16 200 51c-20 110-91 179-200 179s-180-69-200-179z"
fill="#E8F0FF"/>
<path d="M780 856c54-30 102-37 156-16" fill="none" stroke="#D1E0FF" stroke-width="26" stroke-linecap="round"/>
<path d="M1268 856c-54-30-102-37-156-16" fill="none" stroke="#D1E0FF" stroke-width="26" stroke-linecap="round"/>
</g>
<!-- Face -->
<g fill="none" stroke="#1E2E56" stroke-width="26" stroke-linecap="round">
<path d="M862 946c26 27 60 27 86 0"/>
<path d="M1100 946c26 27 60 27 86 0"/>
</g>
<path d="M972 1027c0-30 24-54 54-54s54 24 54 54c0 22-14 39-30 51-15 11-33 11-48 0-16-12-30-29-30-51z"
fill="#192544"/>
<circle cx="1045" cy="1005" r="10" fill="#FFFFFF" opacity="0.9"/>
<path d="M1026 1079c-2 46-30 73-72 77" fill="none" stroke="#1E2E56" stroke-width="20" stroke-linecap="round"/>
<path d="M1026 1079c2 46 30 73 72 77" fill="none" stroke="#1E2E56" stroke-width="20" stroke-linecap="round"/>
<circle cx="824" cy="1041" r="34" fill="#F4B18B" opacity="0.62"/>
<circle cx="1224" cy="1041" r="34" fill="#F4B18B" opacity="0.62"/>
<!-- Paws resting on the box -->
<g filter="url(#tinyShadow)">
<ellipse cx="790" cy="1190" rx="116" ry="78" fill="#F9FBFF" stroke="#20335F" stroke-width="22"/>
<ellipse cx="1258" cy="1190" rx="116" ry="78" fill="#F9FBFF" stroke="#20335F" stroke-width="22"/>
<path d="M756 1189c18 22 46 31 72 20M1224 1189c18 22 46 31 72 20"
fill="none" stroke="#CADBFA" stroke-width="15" stroke-linecap="round"/>
</g>
<!-- Audio waveform badge -->
<g transform="translate(1024 1442)" filter="url(#tinyShadow)">
<circle cx="0" cy="0" r="116" fill="#FFFFFF" opacity="0.96"/>
<circle cx="0" cy="0" r="98" fill="#EAF2FF"/>
<g stroke="#4D83F2" stroke-width="24" stroke-linecap="round">
<line x1="-50" y1="-18" x2="-50" y2="18"/>
<line x1="-17" y1="-49" x2="-17" y2="49"/>
<line x1="17" y1="-70" x2="17" y2="70"/>
<line x1="50" y1="-35" x2="50" y2="35"/>
</g>
</g>
<!-- Tiny AI spark -->
<g transform="translate(1437 520)" fill="#5E91F6">
<path d="M0-66c12 42 24 54 66 66-42 12-54 24-66 66-12-42-24-54-66-66 42-12 54-24 66-66z"/>
<circle cx="-91" cy="91" r="15" opacity="0.55"/>
</g>
</svg>

Before

Width:  |  Height:  |  Size: 6.4 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 240 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 192 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 233 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 78 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 54 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 94 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 78 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 138 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 171 KiB

+6 -66
View File
@@ -2,11 +2,6 @@ name: Build and push Docker image
on:
workflow_dispatch:
inputs:
release_tag:
description: Optional release tag created by Release Please
required: false
type: string
push:
branches:
- master
@@ -25,7 +20,6 @@ jobs:
- name: Checkout
uses: actions/checkout@v4
with:
ref: ${{ inputs.release_tag || github.ref }}
submodules: true
- name: Extract metadata
@@ -33,63 +27,14 @@ jobs:
uses: docker/metadata-action@v5
with:
images: ${{ env.REGISTRY_IMAGE }}
flavor: |
latest=false
tags: |
type=ref,event=branch,enable=${{ inputs.release_tag == '' }}
type=ref,event=pr,enable=${{ inputs.release_tag == '' }}
type=semver,pattern={{version}},enable=${{ inputs.release_tag == '' }}
type=semver,pattern={{major}}.{{minor}},enable=${{ inputs.release_tag == '' }}
type=semver,value=${{ inputs.release_tag }},pattern={{version}},enable=${{ inputs.release_tag != '' }}
type=semver,value=${{ inputs.release_tag }},pattern={{major}}.{{minor}},enable=${{ inputs.release_tag != '' }}
type=ref,event=branch
type=ref,event=pr
type=semver,pattern={{version}}
type=semver,pattern={{major}}.{{minor}}
type=raw,value=dev,enable=${{ github.ref == 'refs/heads/dev' }}
type=sha,prefix=edge-,enable=${{ github.ref == 'refs/heads/master' && inputs.release_tag == '' }}
type=raw,value=latest,enable=${{ startsWith(github.ref, 'refs/tags/v') || inputs.release_tag != '' }}
- name: Verify release version
if: ${{ startsWith(github.ref, 'refs/tags/v') || inputs.release_tag != '' }}
shell: bash
env:
RELEASE_TAG: ${{ inputs.release_tag || github.ref_name }}
run: |
source_version="$(tr -d '[:space:]' < VERSION)"
tag_version="${RELEASE_TAG#v}"
test "$source_version" = "$tag_version" || {
echo "Version mismatch: VERSION=$source_version, tag=$tag_version" >&2
exit 1
}
- name: Resolve source revision
id: source-revision
shell: bash
run: |
revision="$(git rev-parse HEAD)"
echo "value=$revision" >> "$GITHUB_OUTPUT"
echo "short=${revision::12}" >> "$GITHUB_OUTPUT"
- name: Resolve latest frontend revisions
id: frontend-revisions
shell: bash
run: |
frontend_2024_ref="$(git ls-remote https://github.com/vastsa/FileCodeBoxFronted.git HEAD | cut -f1)"
frontend_2023_ref="$(git ls-remote https://github.com/vastsa/FileCodeBoxFronted2023.git HEAD | cut -f1)"
test -n "$frontend_2024_ref"
test -n "$frontend_2023_ref"
echo "frontend_2024=$frontend_2024_ref" >> "$GITHUB_OUTPUT"
echo "frontend_2023=$frontend_2023_ref" >> "$GITHUB_OUTPUT"
- name: Resolve application version
id: app-version
shell: bash
env:
RELEASE_TAG: ${{ inputs.release_tag }}
run: |
source_version="$(tr -d '[:space:]' < VERSION)"
if [[ "$GITHUB_REF" == refs/tags/v* || -n "$RELEASE_TAG" ]]; then
echo "value=$source_version" >> "$GITHUB_OUTPUT"
else
echo "value=${source_version}-dev+${{ steps.source-revision.outputs.short }}" >> "$GITHUB_OUTPUT"
fi
type=raw,value=beta,enable={{is_default_branch}}
type=raw,value=latest,enable={{is_default_branch}}
- name: Set up QEMU
uses: docker/setup-qemu-action@v3
@@ -115,11 +60,6 @@ jobs:
push: true
tags: ${{ steps.meta.outputs.tags }}
labels: ${{ steps.meta.outputs.labels }}
build-args: |
APP_VERSION=${{ steps.app-version.outputs.value }}
VCS_REF=${{ steps.source-revision.outputs.value }}
FRONTEND_2024_REF=${{ steps.frontend-revisions.outputs.frontend_2024 }}
FRONTEND_2023_REF=${{ steps.frontend-revisions.outputs.frontend_2023 }}
cache-from: type=gha
cache-to: type=gha,mode=max
provenance: false
-57
View File
@@ -1,57 +0,0 @@
name: Create release
on:
push:
branches:
- master
workflow_dispatch:
permissions:
actions: write
contents: write
issues: write
pull-requests: write
concurrency:
group: release-${{ github.ref }}
cancel-in-progress: false
jobs:
release-please:
runs-on: ubuntu-latest
timeout-minutes: 30
steps:
- name: Create or update release
id: release
uses: googleapis/release-please-action@v4
with:
config-file: release-please-config.json
manifest-file: .release-please-manifest.json
- name: Merge release pull request
if: ${{ steps.release.outputs.prs_created == 'true' }}
env:
GH_TOKEN: ${{ github.token }}
GH_REPO: ${{ github.repository }}
RELEASE_PR_JSON: ${{ steps.release.outputs.pr }}
run: |
RELEASE_PR="$(jq -r '.number' <<< "$RELEASE_PR_JSON")"
for attempt in {1..120}; do
if gh pr merge "$RELEASE_PR" --squash --delete-branch; then
break
fi
if [[ "$attempt" -eq 120 ]]; then
echo "Timed out waiting for release PR #$RELEASE_PR to merge" >&2
exit 1
fi
sleep 10
done
gh workflow run release.yml --ref master
- name: Publish release image
if: ${{ steps.release.outputs.release_created == 'true' }}
env:
GH_TOKEN: ${{ github.token }}
GH_REPO: ${{ github.repository }}
RELEASE_TAG: ${{ steps.release.outputs.tag_name }}
run: gh workflow run docker-image.yml --ref master -f release_tag="$RELEASE_TAG"
+1 -2
View File
@@ -157,10 +157,9 @@ data/.env
# Ignore node_modules
node_modules/
docs/.vitepress/cache/
AGENTS.md
dist/
# Frontend themes (built from GitHub during Docker build)
themes/
themes/
-3
View File
@@ -1,3 +0,0 @@
{
".": "2.5.3"
}
+10 -44
View File
@@ -1,9 +1,5 @@
# 第一阶段:构建前端主题
# 前端产物与 CPU 架构无关,使用原生构建平台避免在 QEMU 中运行 Node/pnpm。
FROM --platform=$BUILDPLATFORM node:20-alpine AS frontend-builder
ARG FRONTEND_2024_REF=main
ARG FRONTEND_2023_REF=main
FROM node:20-alpine AS frontend-builder
RUN apk add --no-cache git python3 make g++
@@ -12,43 +8,28 @@ RUN corepack enable && \
WORKDIR /build
# 克隆并构建固定版本的 2024 主题
RUN git clone --filter=blob:none --no-checkout https://github.com/vastsa/FileCodeBoxFronted.git /build/fronted-2024 && \
# 克隆并构建 2024 主题
RUN git clone --depth 1 https://github.com/vastsa/FileCodeBoxFronted.git /build/fronted-2024 && \
cd /build/fronted-2024 && \
git fetch --depth 1 origin "${FRONTEND_2024_REF}" && \
git checkout --detach FETCH_HEAD && \
pnpm install --frozen-lockfile --prod=false && \
VITE_GIT_COMMIT="$(git rev-parse HEAD)" pnpm run build
pnpm run build
# 克隆并构建固定版本的 2023 主题
RUN git clone --filter=blob:none --no-checkout https://github.com/vastsa/FileCodeBoxFronted2023.git /build/fronted-2023 && \
# 克隆并构建 2023 主题
RUN git clone --depth 1 https://github.com/vastsa/FileCodeBoxFronted2023.git /build/fronted-2023 && \
cd /build/fronted-2023 && \
git fetch --depth 1 origin "${FRONTEND_2023_REF}" && \
git checkout --detach FETCH_HEAD && \
npm install --legacy-peer-deps && \
npm run build
# 第二阶段:构建最终镜像
FROM python:3.12-slim-bookworm
ARG APP_VERSION
ARG VCS_REF=unknown
ARG FRONTEND_2024_REF=main
ARG FRONTEND_2023_REF=main
LABEL author="Lan"
LABEL email="xzu@live.com"
LABEL org.opencontainers.image.version="${APP_VERSION}"
LABEL org.opencontainers.image.revision="${VCS_REF}"
LABEL org.opencontainers.image.filecodebox.frontend-2024-revision="${FRONTEND_2024_REF}"
LABEL org.opencontainers.image.filecodebox.frontend-2023-revision="${FRONTEND_2023_REF}"
WORKDIR /app
# 复制项目文件(通过 .dockerignore 排除不必要的文件)
COPY . .
# 分支镜像使用带提交号的开发版本;正式镜像使用 VERSION 中的版本。
ENV APP_VERSION="${APP_VERSION}"
# 设置时区
RUN ln -sf /usr/share/zoneinfo/Asia/Shanghai /etc/localtime && \
echo 'Asia/Shanghai' > /etc/timezone
@@ -57,31 +38,16 @@ RUN ln -sf /usr/share/zoneinfo/Asia/Shanghai /etc/localtime && \
COPY --from=frontend-builder /build/fronted-2024/dist ./themes/2024
COPY --from=frontend-builder /build/fronted-2023/dist ./themes/2023
# 安装系统安全更新 + Python 依赖
# 清理 apt 缓存,降低镜像噪音与扫描面
RUN apt-get update \
&& apt-get upgrade -y --no-install-recommends \
&& rm -rf /var/lib/apt/lists/* \
&& pip install --no-cache-dir -r requirements.txt \
&& pip cache purge || true \
&& groupadd --system --gid 1000 appuser \
&& useradd --system --uid 1000 --gid appuser --create-home --home-dir /home/appuser --shell /usr/sbin/nologin appuser \
&& mkdir -p /app/data \
&& chown -R appuser:appuser /app
# 非 root 运行,降低容器逃逸后的主机影响面
USER appuser
# 安装 Python 依赖
RUN pip install --no-cache-dir -r requirements.txt
# 环境变量配置
ENV HOST="0.0.0.0" \
PORT=12345 \
WORKERS=1 \
LOG_LEVEL="info" \
FORWARDED_ALLOW_IPS=""
LOG_LEVEL="info"
EXPOSE 12345
# 生产环境启动命令
# FORWARDED_ALLOW_IPS 默认为空:仅信任直连 IP,避免任意客户端伪造 X-Forwarded-*。
# 若前面有反向代理,请显式设置为代理网段,例如 "10.0.0.0/8,172.16.0.0/12"。
CMD ["sh", "-c", "exec uvicorn main:app --host \"$HOST\" --port \"$PORT\" --workers \"$WORKERS\" --log-level \"$LOG_LEVEL\" --proxy-headers --forwarded-allow-ips \"${FORWARDED_ALLOW_IPS:-}\""]
CMD ["sh", "-c", "exec uvicorn main:app --host \"$HOST\" --port \"$PORT\" --workers \"$WORKERS\" --log-level \"$LOG_LEVEL\" --proxy-headers --forwarded-allow-ips '*'"]
-1
View File
@@ -1 +0,0 @@
2.5.3
+14 -54
View File
@@ -8,60 +8,27 @@ import base64
import hmac
import json
import time
from core.settings import (
ADMIN_SESSION_EXPIRE_DEFAULT,
ADMIN_SESSION_EXPIRE_MAX,
ADMIN_SESSION_EXPIRE_MIN,
settings,
)
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 get_admin_session_expire_seconds() -> int:
try:
expires_in = int(
getattr(settings, "adminSessionExpire", ADMIN_SESSION_EXPIRE_DEFAULT)
)
except (TypeError, ValueError):
return ADMIN_SESSION_EXPIRE_DEFAULT
if (
not ADMIN_SESSION_EXPIRE_MIN <= expires_in <= ADMIN_SESSION_EXPIRE_MAX
or expires_in % ADMIN_SESSION_EXPIRE_MIN != 0
):
return ADMIN_SESSION_EXPIRE_DEFAULT
return expires_in
def create_token(data: dict, expires_in: int | None = None) -> str:
def create_token(data: dict, expires_in: int = 3600 * 24 * 30) -> str:
"""
创建JWT token
:param data: 数据负载
:param expires_in: 过期时间(秒)
"""
token_lifetime = (
get_admin_session_expire_seconds() if expires_in is None else expires_in
)
header = base64.urlsafe_b64encode(
json.dumps({"alg": "HS256", "typ": "JWT"}, separators=(",", ":")).encode()
).decode().rstrip("=")
payload = base64.urlsafe_b64encode(
json.dumps(
{**data, "exp": int(time.time()) + token_lifetime},
separators=(",", ":"),
).encode()
).decode().rstrip("=")
header = base64.b64encode(
json.dumps({"alg": "HS256", "typ": "JWT"}).encode()
).decode()
payload = base64.b64encode(
json.dumps({**data, "exp": int(time.time()) + expires_in}).encode()
).decode()
signature = hmac.new(
_get_jwt_secret(), f"{header}.{payload}".encode(), "sha256"
settings.admin_token.encode(), f"{header}.{payload}".encode(), "sha256"
).digest()
signature = base64.urlsafe_b64encode(signature).decode().rstrip("=")
signature = base64.b64encode(signature).decode()
return f"{header}.{payload}.{signature}"
@@ -77,24 +44,17 @@ def verify_token(token: str) -> dict:
# 验证签名
expected_signature = hmac.new(
_get_jwt_secret(),
settings.admin_token.encode(),
f"{header_b64}.{payload_b64}".encode(),
"sha256",
).digest()
expected_signature_b64 = (
base64.urlsafe_b64encode(expected_signature).decode().rstrip("=")
)
expected_signature_b64 = base64.b64encode(expected_signature).decode()
if not hmac.compare_digest(signature_b64, expected_signature_b64):
raise ValueError("无效的签名")
# 解码payload(兼容历史标准 base64 与 urlsafe base64)
padded = payload_b64 + "=" * (-len(payload_b64) % 4)
try:
payload_bytes = base64.urlsafe_b64decode(padded)
except Exception:
payload_bytes = base64.b64decode(padded)
payload = json.loads(payload_bytes)
# 解码payload
payload = json.loads(base64.b64decode(payload_b64))
# 检查是否过期
if payload.get("exp", 0) < time.time():
+26 -111
View File
@@ -1,23 +1,15 @@
import hashlib
from pathlib import Path
import os
import time
import uuid
from datetime import datetime, timedelta
from typing import Any, Optional
from core.response import APIResponse
from core.storage import FileStorageInterface, storages
from core.settings import (
ADMIN_SESSION_EXPIRE_MAX,
ADMIN_SESSION_EXPIRE_MIN,
settings,
)
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 apps.base.quota import release_storage, reserve_storage
from fastapi import HTTPException
from core.settings import data_root
from core.utils import get_now, hash_password, is_password_hashed
@@ -1475,36 +1467,25 @@ class FileService:
if not await local_file.exists():
raise HTTPException(status_code=404, detail="文件不存在")
reservation_token = f"local:{uuid.uuid4().hex}"
await reserve_storage(reservation_token, local_file.size, ttl_seconds=3600)
try:
text = await local_file.read()
expired_at, expired_count, used_count, code = await get_expire_info(
item.expire_value, item.expire_style
)
path, suffix, prefix, uuid_file_name, save_path = await get_file_path_name(
item
)
await self.file_storage.save_file(text, save_path)
try:
await FileCodes.create(
code=code,
prefix=prefix,
suffix=suffix,
uuid_file_name=uuid_file_name,
file_path=path,
size=local_file.size,
expired_at=expired_at,
expired_count=expired_count,
used_count=used_count,
)
except Exception:
await self.file_storage.delete_file(
FileCodes(file_path=path, uuid_file_name=uuid_file_name)
)
raise
finally:
await release_storage(reservation_token)
text = await local_file.read()
expired_at, expired_count, used_count, code = await get_expire_info(
item.expire_value, item.expire_style
)
path, suffix, prefix, uuid_file_name, save_path = await get_file_path_name(item)
await self.file_storage.save_file(text, save_path)
await FileCodes.create(
code=code,
prefix=prefix,
suffix=suffix,
uuid_file_name=uuid_file_name,
file_path=path,
size=local_file.size,
expired_at=expired_at,
expired_count=expired_count,
used_count=used_count,
)
return {
"code": code,
@@ -1514,12 +1495,9 @@ class FileService:
class ConfigService:
INT_FIELDS = {
"adminSessionExpire",
"enableChunk",
"errorCount",
"errorMinute",
"loginCount",
"loginMinute",
"max_save_seconds",
"onedrive_proxy",
"openUpload",
@@ -1528,7 +1506,6 @@ class ConfigService:
"serverPort",
"serverWorkers",
"showAdminAddr",
"storageLimit",
"uploadCount",
"uploadMinute",
"uploadSize",
@@ -1537,30 +1514,20 @@ class ConfigService:
FLOAT_FIELDS = {"opacity"}
def get_config(self):
config = dict(settings.items())
config["admin_token"] = ""
for key in INTERNAL_CONFIG_KEYS:
config.pop(key, None)
return config
return dict(settings.items())
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 and key not in INTERNAL_CONFIG_KEYS
key: value for key, value in data.items() if key in settings.default_config
}
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:
@@ -1576,32 +1543,6 @@ class ConfigService:
except (TypeError, ValueError):
raise HTTPException(status_code=400, detail=f"{key} 配置值格式错误")
try:
session_expire = int(next_config.get("adminSessionExpire"))
except (TypeError, ValueError):
raise HTTPException(
status_code=400,
detail="adminSessionExpire 配置值格式错误",
)
if (
not ADMIN_SESSION_EXPIRE_MIN <= session_expire <= ADMIN_SESSION_EXPIRE_MAX
or session_expire % ADMIN_SESSION_EXPIRE_MIN != 0
):
raise HTTPException(
status_code=400,
detail="adminSessionExpire 必须是 1 到 365 个整天",
)
next_config["adminSessionExpire"] = session_expire
if int(next_config.get("storageLimit", 0)) < 0:
raise HTTPException(
status_code=400,
detail="storageLimit 不能小于 0",
)
if admin_password_changed:
next_config["jwt_secret"] = generate_jwt_secret()
await KeyValue.update_or_create(key="settings", defaults={"value": next_config})
await refresh_settings()
@@ -1630,35 +1571,9 @@ class LocalFileService:
class LocalFileClass:
def __init__(self, file):
# 仅允许 data/local 目录下的单层文件名,阻断路径穿越与绝对路径访问。
raw_name = str(file or "")
normalized = Path(raw_name).as_posix()
# 输入本身不得包含路径分隔符或绝对路径形态。
if (
not raw_name
or raw_name in {".", ".."}
or normalized in {".", ".."}
or "/" in normalized
or normalized.startswith("~")
or Path(raw_name).is_absolute()
or Path(raw_name).name != raw_name
):
raise HTTPException(status_code=400, detail="非法文件名")
safe_name = Path(raw_name).name
if not safe_name or safe_name in {".", ".."}:
raise HTTPException(status_code=400, detail="非法文件名")
local_root = (data_root / "local").resolve()
candidate = (local_root / safe_name).resolve()
try:
candidate.relative_to(local_root)
except ValueError:
raise HTTPException(status_code=400, detail="非法文件路径")
self.file = safe_name
self.path = candidate
if self.path.is_file():
self.file = file
self.path = data_root / "local" / file
if os.path.exists(self.path):
self.ctime = time.strftime(
"%Y-%m-%d %H:%M:%S", time.localtime(os.path.getctime(self.path))
)
@@ -1678,4 +1593,4 @@ class LocalFileClass:
os.remove(self.path)
async def exists(self):
return self.path.is_file()
return os.path.exists(self.path)
+4 -21
View File
@@ -31,14 +31,9 @@ from apps.admin.schemas import (
)
from core.response import APIResponse
from apps.base.models import FileCodes, KeyValue
from apps.admin.dependencies import (
create_token,
get_admin_session_expire_seconds,
verify_token,
)
from apps.admin.dependencies import create_token
from core.settings import settings
from core.utils import get_now, verify_password
from apps.base.utils import ip_limit
admin_api = APIRouter(
prefix="/admin", tags=["管理"], dependencies=[Depends(admin_required)]
@@ -54,24 +49,12 @@ def _pick_query_text(*values: Optional[str]) -> Optional[str]:
@admin_api.post("/login")
async def login(data: LoginData, ip: str = Depends(ip_limit["login"])):
# 登录失败计入 IP 频率限制,超过 loginCount/loginMinute 后暂时锁定
async def login(data: LoginData):
if not verify_password(data.password, settings.admin_token):
ip_limit["login"].add_ip(ip)
raise HTTPException(status_code=401, detail="密码错误")
expires_in = get_admin_session_expire_seconds()
token = create_token({"is_admin": True}, expires_in=expires_in)
return APIResponse(
detail={
"id": "admin",
"username": "admin",
"token": token,
"token_type": "Bearer",
"expires_at": verify_token(token)["exp"],
"expires_in": expires_in,
}
)
token = create_token({"is_admin": True})
return APIResponse(detail={"token": token, "token_type": "Bearer"})
@admin_api.get("/verify")
+6 -64
View File
@@ -1,69 +1,7 @@
from ipaddress import ip_address, ip_network
from typing import Dict, Iterable, Union
from typing import Dict, 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):
@@ -97,7 +35,11 @@ class IPRateLimit:
}
def __call__(self, request: Request) -> str:
ip = get_client_ip(request)
ip = (
request.headers.get("X-Real-IP")
or request.headers.get("X-Forwarded-For")
or request.client.host
)
if not self.check_ip(ip):
raise HTTPException(status_code=423, detail="请求次数过多,请稍后再试")
return ip
-196
View File
@@ -1,196 +0,0 @@
"""文件类型校验:扩展名 / MIME 白名单 + magic bytes 防伪造。"""
from __future__ import annotations
from dataclasses import dataclass
from pathlib import Path
from typing import Optional
from fastapi import HTTPException, UploadFile
from fnmatch import fnmatchcase
from core.settings import settings
@dataclass(frozen=True)
class FileKind:
name: str
extensions: tuple[str, ...]
mimes: tuple[str, ...]
signatures: tuple[bytes, ...]
FILE_KINDS: tuple[FileKind, ...] = (
FileKind("png", (".png",), ("image/png",), (b"\x89PNG\r\n\x1a\n",)),
FileKind("jpg", (".jpg", ".jpeg"), ("image/jpeg",), (b"\xff\xd8\xff",)),
FileKind("gif", (".gif",), ("image/gif",), (b"GIF87a", b"GIF89a")),
FileKind("webp", (".webp",), ("image/webp",), ()),
FileKind("bmp", (".bmp",), ("image/bmp", "image/x-ms-bmp"), (b"BM",)),
FileKind("pdf", (".pdf",), ("application/pdf",), (b"%PDF",)),
FileKind(
"zip",
(".zip", ".docx", ".xlsx", ".pptx", ".apk", ".jar"),
(
"application/zip",
"application/x-zip-compressed",
"application/vnd.openxmlformats-officedocument.wordprocessingml.document",
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
"application/vnd.openxmlformats-officedocument.presentationml.presentation",
"application/java-archive",
"application/vnd.android.package-archive",
),
(b"PK\x03\x04", b"PK\x05\x06", b"PK\x07\x08"),
),
FileKind(
"rar",
(".rar",),
("application/x-rar-compressed", "application/vnd.rar"),
(b"Rar!\x1a\x07\x00", b"Rar!\x1a\x07\x01\x00"),
),
FileKind("7z", (".7z",), ("application/x-7z-compressed",), (b"7z\xbc\xaf'\x1c",)),
FileKind("gz", (".gz", ".tgz"), ("application/gzip", "application/x-gzip"), (b"\x1f\x8b",)),
FileKind(
"mp3",
(".mp3",),
("audio/mpeg",),
(b"ID3", b"\xff\xfb", b"\xff\xf3", b"\xff\xf2"),
),
FileKind("mp4", (".mp4", ".m4a", ".mov"), ("video/mp4", "audio/mp4", "video/quicktime"), ()),
FileKind(
"exe",
(".exe", ".dll", ".sys"),
("application/x-msdownload", "application/x-dosexec"),
(b"MZ",),
),
FileKind("elf", (".elf", ".so", ".o"), ("application/x-executable",), (b"\x7fELF",)),
)
KNOWN_EXTENSIONS = {ext for kind in FILE_KINDS for ext in kind.extensions}
def normalize_allowed_file_types() -> list[str]:
raw_value = settings.allowed_file_types
if isinstance(raw_value, str):
values = [item.strip() for item in raw_value.split(",")]
elif isinstance(raw_value, (list, tuple, set)):
values = [str(item).strip() for item in raw_value]
else:
values = []
normalized = [item.lower() for item in values if item]
return normalized or ["*"]
def _extension_of(file_name: str) -> str:
return Path(file_name or "").suffix.lower()
def _match_allow_rule(rule: str, file_name: str, content_type: str) -> bool:
if rule in {"*", "*/*"}:
return True
if "/" in rule:
return fnmatchcase(content_type, rule)
extension = rule if rule.startswith(".") else f".{rule}"
return file_name.endswith(extension)
def is_type_allowed(file_name: str, content_type: Optional[str] = None) -> bool:
allowed = normalize_allowed_file_types()
if any(rule in {"*", "*/*"} for rule in allowed):
return True
normalized_name = (file_name or "").strip().lower()
normalized_content_type = (content_type or "").strip().lower()
return any(
_match_allow_rule(rule, normalized_name, normalized_content_type)
for rule in allowed
)
def detect_file_kind(header: bytes) -> Optional[FileKind]:
if not header:
return None
if len(header) >= 12 and header.startswith(b"RIFF") and header[8:12] == b"WEBP":
return next(kind for kind in FILE_KINDS if kind.name == "webp")
if len(header) >= 12 and header[4:8] == b"ftyp":
return next(kind for kind in FILE_KINDS if kind.name == "mp4")
candidates: list[tuple[int, FileKind]] = []
for kind in FILE_KINDS:
for signature in kind.signatures:
if signature and header.startswith(signature):
candidates.append((len(signature), kind))
if not candidates:
return None
candidates.sort(key=lambda item: item[0], reverse=True)
return candidates[0][1]
def validate_file_type(file_name: str, content_type: Optional[str] = None) -> None:
if not is_type_allowed(file_name, content_type):
raise HTTPException(status_code=403, detail="不允许上传该类型文件")
def _kind_matches_ext(kind: FileKind, extension: str) -> bool:
return extension in kind.extensions
def _kind_matches_mime(kind: FileKind, mime: str) -> bool:
return mime in kind.mimes
def validate_file_magic(
file_name: str,
content_type: Optional[str],
header: Optional[bytes],
) -> None:
"""白名单通过后,用 magic bytes 防止扩展名 / MIME 伪造。"""
validate_file_type(file_name, content_type)
if not header:
return
claimed_ext = _extension_of(file_name)
claimed_mime = (content_type or "").strip().lower()
detected = detect_file_kind(header)
if claimed_ext in KNOWN_EXTENSIONS:
if detected is None or not _kind_matches_ext(detected, claimed_ext):
raise HTTPException(
status_code=403,
detail="文件内容与扩展名不匹配,疑似伪造类型",
)
if claimed_mime and any(claimed_mime in kind.mimes for kind in FILE_KINDS):
if detected is None or not _kind_matches_mime(detected, claimed_mime):
raise HTTPException(
status_code=403,
detail="文件内容与 Content-Type 不匹配,疑似伪造类型",
)
allowed = normalize_allowed_file_types()
if detected and not any(rule in {"*", "*/*"} for rule in allowed):
allowed_by_detected = any(
is_type_allowed(f"file{ext}", mime)
for ext in detected.extensions
for mime in (detected.mimes or (None,))
)
if not allowed_by_detected:
raise HTTPException(status_code=403, detail="不允许上传该类型文件")
async def read_upload_header(file: UploadFile, size: int = 64) -> bytes:
await file.seek(0)
header = await file.read(size)
await file.seek(0)
return header or b""
async def validate_upload_file(file: UploadFile) -> None:
header = await read_upload_header(file)
validate_file_magic(file.filename or "", file.content_type, header)
def validate_header_bytes(
file_name: str, content_type: Optional[str], header: bytes
) -> None:
validate_file_magic(file_name, content_type, header)
-19
View File
@@ -1,19 +0,0 @@
from tortoise import connections
async def migrate():
conn = connections.get("default")
await conn.execute_script(
"""
CREATE TABLE IF NOT EXISTS storagereservation (
id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
token VARCHAR(64) NOT NULL UNIQUE,
size BIGINT NOT NULL,
expires_at TIMESTAMP NOT NULL
);
CREATE UNIQUE INDEX IF NOT EXISTS idx_storagereservation_token
ON storagereservation (token);
CREATE INDEX IF NOT EXISTS idx_storagereservation_expires_at
ON storagereservation (expires_at);
"""
)
-9
View File
@@ -84,15 +84,6 @@ class PresignUploadSession(models.Model):
return self.expires_at < await get_now()
class StorageReservation(models.Model):
"""尚未写入 FileCodes 的上传容量预留。"""
id = fields.IntField(pk=True)
token = fields.CharField(max_length=64, unique=True, index=True)
size = fields.BigIntField()
expires_at = fields.DatetimeField(index=True)
file_codes_pydantic = pydantic_model_creator(FileCodes, name="FileCodes")
upload_chunk_pydantic = pydantic_model_creator(UploadChunk, name="UploadChunk")
key_value_pydantic = pydantic_model_creator(KeyValue, name="KeyValue")
-119
View File
@@ -1,119 +0,0 @@
import datetime
from fastapi import HTTPException
from tortoise import connections
from apps.base.models import FileCodes, StorageReservation
from core.settings import settings
from core.utils import get_now
def _detect_sql_dialect() -> str:
"""识别当前默认连接的 SQL 方言。
优先使用 Tortoise capabilities.dialect;
回退到 db_config 中的 engine 路径字符串。
"""
conn = connections.get("default")
dialect = getattr(getattr(conn, "capabilities", None), "dialect", "") or ""
if dialect:
return dialect.lower()
try:
engine = str(connections.db_config.get("default", {}).get("engine", "")).lower()
except Exception:
engine = ""
if "postgres" in engine or "asyncpg" in engine or "psycopg" in engine:
return "postgres"
if "mysql" in engine:
return "mysql"
if "sqlite" in engine:
return "sqlite"
return "sqlite"
def _sql_placeholders(count: int) -> list[str]:
"""根据数据库方言生成参数占位符(多数据库兼容)。
SQLite 用 ?,PostgreSQL 用 $1/$2/...,MySQL 用 %s。
"""
dialect = _detect_sql_dialect()
if dialect in {"postgres", "postgresql"}:
return [f"${i}" for i in range(1, count + 1)]
if dialect == "mysql":
return ["%s"] * count
return ["?"] * count
def get_storage_limit() -> int:
try:
return max(0, int(getattr(settings, "storageLimit", 0)))
except (TypeError, ValueError):
return 0
async def get_storage_usage() -> dict[str, int | None]:
now = await get_now()
used = await FileCodes.all().values_list("size", flat=True)
reserved = await StorageReservation.filter(expires_at__gt=now).values_list(
"size", flat=True
)
limit = get_storage_limit()
used_bytes = sum(used)
reserved_bytes = sum(reserved)
return {
"limit": limit,
"used": used_bytes,
"reserved": reserved_bytes,
"available": max(0, limit - used_bytes - reserved_bytes) if limit else None,
}
async def reserve_storage(token: str, size: int, ttl_seconds: int) -> None:
requested_size = max(0, int(size))
limit = get_storage_limit()
if not limit or requested_size == 0:
return
now = await get_now()
expires_at = now + datetime.timedelta(seconds=ttl_seconds)
conn = connections.get("default")
await StorageReservation.filter(token=token, expires_at__lte=now).delete()
existing = await StorageReservation.filter(token=token, expires_at__gt=now).first()
if existing:
if existing.size == requested_size:
return
raise HTTPException(status_code=409, detail="上传容量预留信息不一致")
try:
ph = _sql_placeholders(6)
affected, _ = await conn.execute_query(
f"""
INSERT INTO storagereservation (token, size, expires_at)
SELECT {ph[0]}, {ph[1]}, {ph[2]}
WHERE (
COALESCE((SELECT SUM(size) FROM filecodes), 0)
+ COALESCE((SELECT SUM(size) FROM storagereservation WHERE expires_at > {ph[3]}), 0)
+ {ph[4]}
) <= {ph[5]}
""",
[token, requested_size, expires_at, now, requested_size, limit],
)
except Exception:
concurrent = await StorageReservation.filter(
token=token, size=requested_size, expires_at__gt=now
).exists()
if concurrent:
return
raise
if affected != 1:
concurrent = await StorageReservation.filter(
token=token, size=requested_size, expires_at__gt=now
).exists()
if concurrent:
return
raise HTTPException(status_code=507, detail="存储空间已达到管理员设置的容量上限")
async def release_storage(token: str) -> None:
await StorageReservation.filter(token=token).delete()
+4 -28
View File
@@ -19,13 +19,6 @@ from core.utils import (
)
def validate_expire_style(expire_style: str) -> str:
"""校验过期方式是否在管理员配置的白名单内。"""
if expire_style not in settings.expireStyle:
raise HTTPException(status_code=400, detail="过期时间类型错误")
return expire_style
async def get_file_path_name(file: UploadFile) -> Tuple[str, str, str, str, str]:
today = await get_now()
storage_path = settings.storage_path.strip("/")
@@ -83,6 +76,8 @@ 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:
@@ -96,26 +91,9 @@ async def get_expire_info(
return expired_at, expired_count, used_count, code
def get_code_generate_type() -> str:
code_generate_type = getattr(settings, "code_generate_type", "secret")
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"
async def get_random_code(style: str = "num") -> str:
while True:
code = (
await get_random_num()
if code_style == "number"
else await get_random_string()
)
code = await get_random_num() if style == "num" else await get_random_string()
if not await FileCodes.filter(code=code).exists():
return str(code)
@@ -134,7 +112,5 @@ async def calculate_file_hash(file: UploadFile, chunk_size=1024 * 1024) -> str:
ip_limit = {
"error": IPRateLimit(count=settings.errorCount, minutes=settings.errorMinute),
"metadata": IPRateLimit(count=settings.errorCount, minutes=settings.errorMinute),
"upload": IPRateLimit(count=settings.uploadCount, minutes=settings.uploadMinute),
"login": IPRateLimit(count=settings.loginCount, minutes=settings.loginMinute),
}
+129 -267
View File
@@ -1,44 +1,35 @@
import datetime
from fnmatch import fnmatchcase
import hashlib
import os
import uuid
from datetime import timedelta
from urllib.parse import quote, unquote
from urllib.parse import unquote
from typing import Optional, Tuple, Union
from fastapi import APIRouter, Form, Request, UploadFile, File, Depends, HTTPException
from pydantic import BaseModel, ValidationError
from starlette import status
from starlette.responses import Response
from tortoise.expressions import Case, F, Q, When
from apps.admin.dependencies import share_required_login
from apps.base.models import FileCodes, UploadChunk, PresignUploadSession
from apps.base.quota import release_storage, reserve_storage
from apps.base.schemas import (
SelectFileModel,
InitChunkUploadModel,
CompleteUploadModel,
PresignUploadInitRequest,
)
from apps.base.file_validation import validate_file_type, validate_upload_file, validate_header_bytes
from apps.base.utils import (
get_expire_info,
get_file_path_name,
ip_limit,
get_chunk_file_path_name,
validate_expire_style,
)
from core.response import APIResponse
from core.settings import settings
from core.storage import storages, FileStorageInterface
from core.utils import (
get_file_url as get_proxy_file_url,
get_select_token,
get_now,
sanitize_filename,
)
from core.utils import get_select_token, get_now, sanitize_filename
share_api = APIRouter(prefix="/share", tags=["分享"])
@@ -106,6 +97,36 @@ async def validate_file_size(file: UploadFile, max_size: int) -> int:
return size
def normalize_allowed_file_types() -> list[str]:
raw_value = settings.allowed_file_types
if isinstance(raw_value, str):
values = raw_value.replace(";", ",").split(",")
elif isinstance(raw_value, (list, tuple, set)):
values = raw_value
else:
values = []
allowed = [str(item).strip().lower() for item in values if str(item).strip()]
return allowed or ["*"]
def validate_file_type(file_name: str, content_type: Optional[str] = None) -> None:
allowed = normalize_allowed_file_types()
if "*" in allowed or "*/*" in allowed:
return
normalized_name = file_name.strip().lower()
normalized_content_type = (content_type or "").strip().lower()
for rule in allowed:
if "/" in rule and fnmatchcase(normalized_content_type, rule):
return
extension = rule if rule.startswith(".") else f".{rule}"
if normalized_name.endswith(extension):
return
raise HTTPException(status_code=403, detail="不允许上传该类型文件")
async def create_file_code(code, **kwargs):
@@ -123,29 +144,23 @@ async def share_text(
expire_style: str = Form(default="day"),
ip: str = Depends(ip_limit["upload"]),
):
validate_expire_style(expire_style)
text_size = len(text.encode("utf-8"))
max_txt_size = 222 * 1024
if text_size > max_txt_size:
raise HTTPException(status_code=403, detail="内容过多,建议采用文件形式")
reservation_token = f"text:{uuid.uuid4().hex}"
await reserve_storage(reservation_token, text_size, ttl_seconds=300)
try:
expired_at, expired_count, used_count, code = await get_expire_info(
expire_value, expire_style
)
await create_file_code(
code=code,
text=text,
expired_at=expired_at,
expired_count=expired_count,
used_count=used_count,
size=text_size,
prefix="Text",
)
finally:
await release_storage(reservation_token)
expired_at, expired_count, used_count, code = await get_expire_info(
expire_value, expire_style
)
await create_file_code(
code=code,
text=text,
expired_at=expired_at,
expired_count=expired_count,
used_count=used_count,
size=len(text),
prefix="Text",
)
ip_limit["upload"].add_ip(ip)
return APIResponse(detail={"code": code})
@@ -158,38 +173,26 @@ async def share_file(
ip: str = Depends(ip_limit["upload"]),
):
file_size = await validate_file_size(file, settings.uploadSize)
await validate_upload_file(file)
validate_expire_style(expire_style)
validate_file_type(file.filename or "", file.content_type)
if expire_style not in settings.expireStyle:
raise HTTPException(status_code=400, detail="过期时间类型错误")
expired_at, expired_count, used_count, code = await get_expire_info(
expire_value, expire_style
)
path, suffix, prefix, uuid_file_name, save_path = await get_file_path_name(file)
reservation_token = f"file:{uuid.uuid4().hex}"
await reserve_storage(reservation_token, file_size, ttl_seconds=3600)
file_storage: FileStorageInterface = storages[settings.file_storage]()
try:
expired_at, expired_count, used_count, code = await get_expire_info(
expire_value, expire_style
)
await file_storage.save_file(file, save_path)
await create_file_code(
code=code,
prefix=prefix,
suffix=suffix,
uuid_file_name=uuid_file_name,
file_path=path,
size=file_size,
expired_at=expired_at,
expired_count=expired_count,
used_count=used_count,
)
except Exception:
try:
await file_storage.delete_file(
FileCodes(file_path=path, uuid_file_name=uuid_file_name)
)
except Exception:
pass
raise
finally:
await release_storage(reservation_token)
await file_storage.save_file(file, save_path)
await create_file_code(
code=code,
prefix=prefix,
suffix=suffix,
uuid_file_name=uuid_file_name,
file_path=path,
size=file_size,
expired_at=expired_at,
expired_count=expired_count,
used_count=used_count,
)
ip_limit["upload"].add_ip(ip)
return APIResponse(detail={"code": code, "name": file.filename})
@@ -208,25 +211,11 @@ async def get_code_file_by_code(
return True, file_code
async def consume_file_usage(file_code: FileCodes) -> bool:
"""原子校验分享状态并记录一次实际领取。"""
now = await get_now()
eligible = (
Q(expired_count__gt=0)
| Q(expired_count__lt=0, expired_at__gt=now)
| Q(expired_count__lt=0, expired_at=None)
)
updated = await FileCodes.filter(Q(id=file_code.id) & eligible).update(
expired_count=Case(
When(expired_count__gt=0, then=F("expired_count") - 1),
default=F("expired_count"),
),
used_count=F("used_count") + 1,
)
if not updated:
return False
await file_code.refresh_from_db()
return True
async def update_file_usage(file_code: FileCodes) -> None:
file_code.used_count += 1
if file_code.expired_count > 0:
file_code.expired_count -= 1
await file_code.save()
def build_file_metadata(file_code: FileCodes) -> dict:
@@ -253,13 +242,9 @@ async def build_select_detail(
file_code: FileCodes, file_storage: FileStorageInterface
) -> dict:
metadata = build_file_metadata(file_code)
if file_code.text is not None:
download_url = None
elif file_code.expired_count >= 0:
# 有次数限制的文件必须经过下载接口,第三方直链无法阻止重复使用。
download_url = await get_proxy_file_url(file_code.code)
else:
download_url = await file_storage.get_file_url(file_code)
download_url = (
None if file_code.text is not None else await file_storage.get_file_url(file_code)
)
content = file_code.text if file_code.text is not None else None
return {
**metadata,
@@ -270,28 +255,24 @@ async def build_select_detail(
@share_api.get("/metadata/")
async def get_file_metadata(code: str, ip: str = Depends(ip_limit["metadata"])):
async def get_file_metadata(code: str, ip: str = Depends(ip_limit["error"])):
has, file_code = await get_code_file_by_code(code)
if not has:
ip_limit["metadata"].add_ip(ip)
ip_limit["error"].add_ip(ip)
return APIResponse(code=404, detail=file_code)
assert isinstance(file_code, FileCodes)
ip_limit["metadata"].add_ip(ip)
return APIResponse(detail=build_file_metadata(file_code))
@share_api.post("/metadata/")
async def post_file_metadata(
data: SelectFileModel, ip: str = Depends(ip_limit["metadata"])
):
async def post_file_metadata(data: SelectFileModel, ip: str = Depends(ip_limit["error"])):
has, file_code = await get_code_file_by_code(data.code)
if not has:
ip_limit["metadata"].add_ip(ip)
ip_limit["error"].add_ip(ip)
return APIResponse(code=404, detail=file_code)
assert isinstance(file_code, FileCodes)
ip_limit["metadata"].add_ip(ip)
return APIResponse(detail=build_file_metadata(file_code))
@@ -304,19 +285,7 @@ async def get_code_file(code: str, ip: str = Depends(ip_limit["error"])):
return APIResponse(code=404, detail=file_code)
assert isinstance(file_code, FileCodes)
if not await consume_file_usage(file_code):
return APIResponse(code=404, detail="文件已过期")
if file_code.text is not None:
filename = f"{file_code.prefix or 'Text'}{file_code.suffix or '.txt'}"
return Response(
content=file_code.text,
media_type="text/plain",
headers={
"Content-Disposition": (
f"attachment; filename*=UTF-8''{quote(filename, safe='')}"
)
},
)
await update_file_usage(file_code)
return await file_storage.get_file_response(file_code)
@@ -329,36 +298,21 @@ async def select_file(data: SelectFileModel, ip: str = Depends(ip_limit["error"]
return APIResponse(code=404, detail=file_code)
assert isinstance(file_code, FileCodes)
detail = await build_select_detail(file_code, file_storage)
download_url = detail.get("download_url")
consumes_on_download = isinstance(download_url, str) and download_url.startswith(
"/share/download?"
)
if not consumes_on_download and not await consume_file_usage(file_code):
return APIResponse(code=404, detail="文件已过期")
if not consumes_on_download:
detail.update(build_file_metadata(file_code))
return APIResponse(detail=detail)
await update_file_usage(file_code)
return APIResponse(detail=await build_select_detail(file_code, file_storage))
@share_api.get("/download")
async def download_file(key: str, code: str, ip: str = Depends(ip_limit["error"])):
file_storage: FileStorageInterface = storages[settings.file_storage]()
normalized_code = normalize_share_code(code)
# 同时接受当前窗口与上一窗口 token,避免时间窗边界竞态导致偶发 403
valid_keys = {
await get_select_token(normalized_code, offset=0),
await get_select_token(normalized_code, offset=1),
}
if key not in valid_keys:
if await get_select_token(normalized_code) != key:
ip_limit["error"].add_ip(ip)
raise HTTPException(status_code=403, detail="下载鉴权失败")
has, file_code = await get_code_file_by_code(normalized_code)
has, file_code = await get_code_file_by_code(normalized_code, False)
if not has:
return APIResponse(code=404, detail=file_code)
return APIResponse(code=404, detail="文件不存在")
assert isinstance(file_code, FileCodes)
if not await consume_file_usage(file_code):
return APIResponse(code=404, detail="文件已过期")
return (
APIResponse(detail=file_code.text)
if file_code.text
@@ -429,16 +383,7 @@ async def init_chunk_upload(data: InitChunkUploadModel = Depends(parse_init_chun
if existing_session:
if not existing_session.save_path:
await UploadChunk.filter(upload_id=existing_session.upload_id).delete()
await release_storage(f"chunk:{existing_session.upload_id}")
else:
await reserve_storage(
f"chunk:{existing_session.upload_id}",
existing_session.file_size,
ttl_seconds=max(
1, int(getattr(settings, "chunk_expire_hours", 24))
)
* 3600,
)
uploaded_chunks = await UploadChunk.filter(
upload_id=existing_session.upload_id, completed=True
).values_list("chunk_index", flat=True)
@@ -454,26 +399,17 @@ async def init_chunk_upload(data: InitChunkUploadModel = Depends(parse_init_chun
# 创建新的上传会话
upload_id = uuid.uuid4().hex
reservation_token = f"chunk:{upload_id}"
chunk_expire_seconds = max(1, int(getattr(settings, "chunk_expire_hours", 24))) * 3600
await reserve_storage(
reservation_token, data.file_size, ttl_seconds=chunk_expire_seconds
)
_, _, _, _, save_path = await get_chunk_file_path_name(data.file_name, upload_id)
try:
await UploadChunk.create(
upload_id=upload_id,
chunk_index=-1,
total_chunks=total_chunks,
file_size=data.file_size,
chunk_size=data.chunk_size,
chunk_hash=data.file_hash,
file_name=data.file_name,
save_path=save_path,
)
except Exception:
await release_storage(reservation_token)
raise
await UploadChunk.create(
upload_id=upload_id,
chunk_index=-1,
total_chunks=total_chunks,
file_size=data.file_size,
chunk_size=data.chunk_size,
chunk_hash=data.file_hash,
file_name=data.file_name,
save_path=save_path,
)
return APIResponse(
detail={
"existed": False,
@@ -498,11 +434,6 @@ async def upload_chunk(
chunk_info = await UploadChunk.filter(upload_id=upload_id, chunk_index=-1).first()
if not chunk_info:
raise HTTPException(status.HTTP_404_NOT_FOUND, detail="上传会话不存在")
await reserve_storage(
f"chunk:{upload_id}",
chunk_info.file_size,
ttl_seconds=max(1, int(getattr(settings, "chunk_expire_hours", 24))) * 3600,
)
# 检查分片索引有效性
if chunk_index < 0 or chunk_index >= chunk_info.total_chunks:
@@ -519,8 +450,6 @@ async def upload_chunk(
# 读取分片数据并计算哈希
chunk_data = await chunk.read()
if chunk_index == 0:
validate_header_bytes(chunk_info.file_name, None, chunk_data[:64])
chunk_size = len(chunk_data)
# 校验分片大小不超过声明的 chunk_size
@@ -593,7 +522,6 @@ async def cancel_upload(upload_id: str):
# 清理数据库记录
await UploadChunk.filter(upload_id=upload_id).delete()
await release_storage(f"chunk:{upload_id}")
return APIResponse(detail={"message": "上传已取消"})
@@ -637,12 +565,6 @@ async def complete_upload(
chunk_info = await UploadChunk.filter(upload_id=upload_id, chunk_index=-1).first()
if not chunk_info:
raise HTTPException(status.HTTP_404_NOT_FOUND, detail="上传会话不存在")
validate_expire_style(data.expire_style)
await reserve_storage(
f"chunk:{upload_id}",
chunk_info.file_size,
ttl_seconds=max(1, int(getattr(settings, "chunk_expire_hours", 24))) * 3600,
)
storage = storages[settings.file_storage]()
# 验证所有分片
@@ -662,7 +584,6 @@ async def complete_upload(
except Exception:
pass
await UploadChunk.filter(upload_id=upload_id).delete()
await release_storage(f"chunk:{upload_id}")
max_size_mb = settings.uploadSize / (1024 * 1024)
raise HTTPException(
status_code=403, detail=f"实际上传大小超过限制,最大为 {max_size_mb:.2f} MB"
@@ -697,7 +618,6 @@ async def complete_upload(
await storage.clean_chunks(upload_id, save_path)
# 清理数据库中的分片记录
await UploadChunk.filter(upload_id=upload_id).delete()
await release_storage(f"chunk:{upload_id}")
ip_limit["upload"].add_ip(ip)
return APIResponse(detail={"code": code, "name": chunk_info.file_name})
except ValueError as e:
@@ -736,7 +656,6 @@ async def _get_valid_session(
raise HTTPException(404, "上传会话不存在")
if await session.is_expired():
await session.delete()
await release_storage(f"presign:{upload_id}")
raise HTTPException(404, "上传会话已过期")
if expected_mode and session.mode != expected_mode:
raise HTTPException(400, f"此会话不支持{expected_mode}模式")
@@ -754,37 +673,33 @@ async def presign_upload_init(
403,
f"文件大小超过限制,最大为 {settings.uploadSize / (1024 * 1024):.2f} MB",
)
validate_expire_style(data.expire_style)
if data.expire_style not in settings.expireStyle:
raise HTTPException(400, "过期时间类型错误")
upload_id = uuid.uuid4().hex
reservation_token = f"presign:{upload_id}"
await reserve_storage(
reservation_token, data.file_size, ttl_seconds=PRESIGN_SESSION_EXPIRES
path, _, _, filename, save_path = await FileUploadService.generate_file_path(
data.file_name, upload_id
)
storage: FileStorageInterface = storages[settings.file_storage]()
presigned_url = await storage.generate_presigned_upload_url(
save_path, PRESIGN_SESSION_EXPIRES
)
mode = "direct" if presigned_url else "proxy"
proxy_urls = build_proxy_upload_urls(upload_id)
upload_url = presigned_url or proxy_urls["proxy_upload_url"]
await PresignUploadSession.create(
upload_id=upload_id,
file_name=filename,
file_size=data.file_size,
save_path=save_path,
mode=mode,
expire_value=data.expire_value,
expire_style=data.expire_style,
expires_at=await get_now() + timedelta(seconds=PRESIGN_SESSION_EXPIRES),
)
try:
path, _, _, filename, save_path = await FileUploadService.generate_file_path(
data.file_name, upload_id
)
storage: FileStorageInterface = storages[settings.file_storage]()
presigned_url = await storage.generate_presigned_upload_url(
save_path, PRESIGN_SESSION_EXPIRES
)
mode = "direct" if presigned_url else "proxy"
proxy_urls = build_proxy_upload_urls(upload_id)
upload_url = presigned_url or proxy_urls["proxy_upload_url"]
await PresignUploadSession.create(
upload_id=upload_id,
file_name=filename,
file_size=data.file_size,
save_path=save_path,
mode=mode,
expire_value=data.expire_value,
expire_style=data.expire_style,
expires_at=await get_now() + timedelta(seconds=PRESIGN_SESSION_EXPIRES),
)
except Exception:
await release_storage(reservation_token)
raise
ip_limit["upload"].add_ip(ip)
detail = {
@@ -809,14 +724,8 @@ async def presign_upload_proxy(
):
"""代理模式上传,服务器转存到存储后端"""
session = await _get_valid_session(upload_id, expected_mode="proxy")
await reserve_storage(
f"presign:{upload_id}",
session.file_size,
ttl_seconds=PRESIGN_SESSION_EXPIRES,
)
file_size = await validate_file_size(file, settings.uploadSize)
await validate_upload_file(file)
if abs(file_size - session.file_size) > 1024:
raise HTTPException(400, "文件大小与声明不符")
@@ -826,28 +735,15 @@ async def presign_upload_proxy(
except Exception as e:
raise HTTPException(500, f"文件保存失败: {str(e)}")
try:
code = await FileUploadService.create_file_record(
session.file_name,
file_size,
os.path.dirname(session.save_path),
session.expire_value,
session.expire_style,
)
except Exception:
try:
await storage.delete_file(
FileCodes(
file_path=os.path.dirname(session.save_path),
uuid_file_name=os.path.basename(session.save_path),
)
)
except Exception:
pass
raise
code = await FileUploadService.create_file_record(
session.file_name,
file_size,
os.path.dirname(session.save_path),
session.expire_value,
session.expire_style,
)
await session.delete()
await release_storage(f"presign:{upload_id}")
ip_limit["upload"].add_ip(ip)
return APIResponse(detail={"code": code, "name": session.file_name})
@@ -858,53 +754,20 @@ async def presign_upload_proxy(
async def presign_upload_confirm(upload_id: str, ip: str = Depends(ip_limit["upload"])):
"""直传确认,客户端完成S3直传后调用获取分享码"""
session = await _get_valid_session(upload_id, expected_mode="direct")
try:
await reserve_storage(
f"presign:{upload_id}",
session.file_size,
ttl_seconds=PRESIGN_SESSION_EXPIRES,
)
except HTTPException:
storage: FileStorageInterface = storages[settings.file_storage]()
try:
if await storage.file_exists(session.save_path):
await storage.delete_file(
FileCodes(
file_path=os.path.dirname(session.save_path),
uuid_file_name=os.path.basename(session.save_path),
)
)
finally:
await session.delete()
await release_storage(f"presign:{upload_id}")
raise
storage: FileStorageInterface = storages[settings.file_storage]()
if not await storage.file_exists(session.save_path):
raise HTTPException(404, "文件未上传或上传失败")
try:
code = await FileUploadService.create_file_record(
session.file_name,
session.file_size,
os.path.dirname(session.save_path),
session.expire_value,
session.expire_style,
)
except Exception:
try:
await storage.delete_file(
FileCodes(
file_path=os.path.dirname(session.save_path),
uuid_file_name=os.path.basename(session.save_path),
)
)
except Exception:
pass
raise
code = await FileUploadService.create_file_record(
session.file_name,
session.file_size,
os.path.dirname(session.save_path),
session.expire_value,
session.expire_style,
)
await session.delete()
await release_storage(f"presign:{upload_id}")
ip_limit["upload"].add_ip(ip)
return APIResponse(detail={"code": code, "name": session.file_name})
@@ -951,5 +814,4 @@ async def presign_upload_cancel(upload_id: str):
pass
await session.delete()
await release_storage(f"presign:{upload_id}")
return APIResponse(detail={"message": "上传会话已取消"})
+1 -100
View File
@@ -1,77 +1,17 @@
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",
"loginCount",
"loginMinute",
"expireStyle",
"max_save_seconds",
"name",
"openUpload",
"uploadCount",
"uploadMinute",
"uploadSize",
}
async def ensure_settings_row() -> None:
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()
await KeyValue.get_or_create(key="settings", defaults={"value": DEFAULT_CONFIG})
def _sync_ip_limits() -> None:
ip_limit["error"].minutes = settings.errorMinute
ip_limit["error"].count = settings.errorCount
ip_limit["metadata"].minutes = settings.errorMinute
ip_limit["metadata"].count = settings.errorCount
ip_limit["upload"].minutes = settings.uploadMinute
ip_limit["upload"].count = settings.uploadCount
ip_limit["login"].minutes = settings.loginMinute
ip_limit["login"].count = settings.loginCount
async def refresh_settings() -> None:
@@ -79,42 +19,3 @@ 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
@@ -1,60 +0,0 @@
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
+1 -12
View File
@@ -4,10 +4,6 @@
# @Software: PyCharm
from pathlib import Path
ADMIN_SESSION_EXPIRE_DEFAULT = 30 * 24 * 60 * 60
ADMIN_SESSION_EXPIRE_MIN = 24 * 60 * 60
ADMIN_SESSION_EXPIRE_MAX = 365 * 24 * 60 * 60
BASE_DIR = Path(__file__).resolve().parent.parent
data_root = BASE_DIR / "data"
@@ -17,7 +13,6 @@ if not data_root.exists():
DEFAULT_CONFIG = {
"file_storage": "local",
"storage_path": "",
"storageLimit": 0,
"name": "文件快递柜 - FileCodeBox",
"description": "开箱即用的文件快传系统",
"notify_title": "系统通知",
@@ -43,14 +38,11 @@ DEFAULT_CONFIG = {
"onedrive_proxy": 0,
"webdav_root_path": "filebox_storage",
"webdav_proxy": 0,
"admin_token": "",
"jwt_secret": "",
"adminSessionExpire": ADMIN_SESSION_EXPIRE_DEFAULT,
"admin_token": "FileCodeBox2023",
"openUpload": 1,
"uploadSize": 1024 * 1024 * 10,
"allowed_file_types": ["*"],
"expireStyle": ["day", "hour", "minute", "forever", "count"],
"code_generate_type": "secret",
"uploadMinute": 1,
"enableChunk": 0,
"webdav_url": "",
@@ -76,14 +68,11 @@ DEFAULT_CONFIG = {
"themesSelect": "themes/2024",
"errorMinute": 1,
"errorCount": 10,
"loginCount": 5,
"loginMinute": 15,
"serverWorkers": 1,
"serverHost": "0.0.0.0",
"serverPort": 12345,
"showAdminAddr": 0,
"robotsText": "User-agent: *\nDisallow: /",
"trustedProxies": [],
}
+14 -42
View File
@@ -25,7 +25,6 @@ from core.settings import data_root, settings
from apps.base.models import FileCodes, UploadChunk
from core.utils import get_file_url, sanitize_filename
from fastapi.responses import FileResponse, StreamingResponse
from starlette.background import BackgroundTask
class FileStorageInterface:
@@ -112,17 +111,6 @@ class SystemFileStorage(FileStorageInterface):
self.chunk_size = 256 * 1024
self.root_path = data_root
def _resolve_safe_path(self, relative_path: str) -> Path:
"""将相对路径解析到数据根目录内,阻止路径穿越。"""
root = self.root_path.resolve()
raw = str(relative_path or "").replace("\\", "/").lstrip("/")
candidate = (root / raw).resolve()
try:
candidate.relative_to(root)
except ValueError as exc:
raise ValueError("非法文件路径") from exc
return candidate
def _save(self, file, save_path):
with open(save_path, "wb") as f:
chunk = file.read(self.chunk_size)
@@ -131,19 +119,19 @@ class SystemFileStorage(FileStorageInterface):
chunk = file.read(self.chunk_size)
async def save_file(self, file: UploadFile, save_path: str):
path_obj = Path(str(save_path).replace("\\", "/"))
directory = str(path_obj.parent).replace("\\", "/").lstrip("/")
path_obj = Path(save_path)
directory = str(path_obj.parent)
# 提取原始文件名并进行清理
filename = await sanitize_filename(path_obj.name)
# 构建安全的完整保存路径
safe_save_path = self._resolve_safe_path(f"{directory}/{filename}" if directory not in {"", "."} else filename)
safe_save_path = self.root_path / directory / filename
# 确保目录存在
if not safe_save_path.parent.exists():
safe_save_path.parent.mkdir(parents=True)
await asyncio.to_thread(self._save, file.file, safe_save_path)
async def delete_file(self, file_code: FileCodes):
save_path = self._resolve_safe_path(await file_code.get_file_path())
save_path = self.root_path / await file_code.get_file_path()
if save_path.exists():
save_path.unlink()
@@ -151,7 +139,7 @@ class SystemFileStorage(FileStorageInterface):
return await get_file_url(file_code.code)
async def get_file_response(self, file_code: FileCodes):
file_path = self._resolve_safe_path(await file_code.get_file_path())
file_path = self.root_path / await file_code.get_file_path()
if not file_path.exists():
return APIResponse(code=404, detail="文件已过期删除")
filename = f"{file_code.prefix}{file_code.suffix}"
@@ -183,11 +171,8 @@ class SystemFileStorage(FileStorageInterface):
:param chunk_hash: 分片哈希值
:param save_path: 文件保存路径
"""
# 先校验目标文件路径合法,再将分片落到同级 chunks 目录。
self._resolve_safe_path(save_path)
chunk_path = self._resolve_safe_path(
str(Path(save_path).parent / "chunks" / upload_id / f"{chunk_index}.part")
)
chunk_dir = self.root_path / save_path
chunk_path = chunk_dir.parent / 'chunks' / upload_id / f"{chunk_index}.part"
if not chunk_path.parent.exists():
chunk_path.parent.mkdir(parents=True, exist_ok=True)
# 使用临时文件写入,确保原子性
@@ -210,11 +195,9 @@ class SystemFileStorage(FileStorageInterface):
:param save_path: 文件保存路径
:return: (文件路径, 文件哈希值)
"""
output_path = self._resolve_safe_path(save_path)
output_path = self.root_path / save_path
output_path.parent.mkdir(parents=True, exist_ok=True)
chunk_base_dir = self._resolve_safe_path(
str(Path(save_path).parent / "chunks" / upload_id)
)
chunk_base_dir = output_path.parent / 'chunks' / upload_id
file_sha256 = hashlib.sha256()
# 使用临时文件写入,确保原子性
@@ -250,9 +233,7 @@ class SystemFileStorage(FileStorageInterface):
:param upload_id: 上传会话ID
:param save_path: 文件保存路径
"""
chunk_dir = self._resolve_safe_path(
str(Path(save_path).parent / "chunks" / upload_id)
)
chunk_dir = (self.root_path / save_path).parent / 'chunks' / upload_id
if chunk_dir.exists():
try:
shutil.rmtree(chunk_dir)
@@ -272,10 +253,7 @@ class SystemFileStorage(FileStorageInterface):
:param save_path: 文件路径
:return: 文件是否存在
"""
try:
file_path = self._resolve_safe_path(save_path)
except ValueError:
return False
file_path = self.root_path / save_path
return file_path.exists()
@@ -396,9 +374,7 @@ class S3FileStorage(FileStorageInterface):
return StreamingResponse(
stream_generator(),
media_type="application/octet-stream",
headers=headers,
# 兜底关闭会话:客户端中断时与 generator finally 双保险
background=BackgroundTask(session.close),
headers=headers
)
except HTTPException:
raise
@@ -736,9 +712,7 @@ class OneDriveFileStorage(FileStorageInterface):
return StreamingResponse(
stream_generator(),
media_type="application/octet-stream",
headers=headers,
# 兜底关闭会话:客户端中断时与 generator finally 双保险
background=BackgroundTask(session.close),
headers=headers
)
except HTTPException:
raise
@@ -1214,9 +1188,7 @@ class WebDAVFileStorage(FileStorageInterface):
return StreamingResponse(
stream_generator(),
media_type="application/octet-stream",
headers=headers,
# 兜底关闭会话:客户端中断时与 generator finally 双保险
background=BackgroundTask(session.close),
headers=headers
)
except aiohttp.ClientError as e:
raise HTTPException(
+1 -45
View File
@@ -9,12 +9,7 @@ import os
from tortoise.expressions import Q
from apps.base.models import (
FileCodes,
PresignUploadSession,
StorageReservation,
UploadChunk,
)
from apps.base.models import FileCodes, UploadChunk
from apps.base.utils import ip_limit, get_chunk_file_path_name
from core.config import refresh_settings
from core.settings import settings, data_root
@@ -33,9 +28,7 @@ async def delete_expire_files():
if not dirs and not files:
os.rmdir(root)
await ip_limit["error"].remove_expired_ip()
await ip_limit["metadata"].remove_expired_ip()
await ip_limit["upload"].remove_expired_ip()
await StorageReservation.filter(expires_at__lte=await get_now()).delete()
expire_data = await FileCodes.filter(
Q(expired_at__lt=await get_now()) | Q(expired_count=0)
).all()
@@ -81,9 +74,6 @@ async def clean_incomplete_uploads():
try:
await UploadChunk.filter(upload_id=session.upload_id).delete()
await StorageReservation.filter(
token=f"chunk:{session.upload_id}"
).delete()
logging.info(f"已清理过期上传会话 upload_id={session.upload_id}")
except Exception as e:
logging.error(
@@ -94,37 +84,3 @@ async def clean_incomplete_uploads():
logging.error(f"清理未完成上传任务异常: {e}")
finally:
await asyncio.sleep(3600)
async def clean_expired_presign_sessions():
while True:
try:
await refresh_settings()
storage: FileStorageInterface = storages[settings.file_storage]()
now = await get_now()
expired_sessions = await PresignUploadSession.filter(
expires_at__lt=now
).all()
for session in expired_sessions:
if session.mode == "direct":
try:
if await storage.file_exists(session.save_path):
await storage.delete_file(
FileCodes(
file_path=os.path.dirname(session.save_path),
uuid_file_name=os.path.basename(session.save_path),
)
)
except Exception as e:
logging.error(
"清理过期直传文件失败 "
f"upload_id={session.upload_id}: {e}"
)
await StorageReservation.filter(
token=f"presign:{session.upload_id}"
).delete()
await session.delete()
except Exception as e:
logging.error(f"清理过期预签名会话异常: {e}")
finally:
await asyncio.sleep(900)
+9 -17
View File
@@ -4,10 +4,9 @@
# @Software: PyCharm
import datetime
import hashlib
import hmac
import os
import random
import re
import secrets
import string
import time
@@ -19,7 +18,7 @@ async def get_random_num():
获取随机数
:return:
"""
return secrets.randbelow(90000) + 10000
return random.randint(10000, 99999)
r_s = string.ascii_uppercase + string.digits
@@ -30,7 +29,7 @@ async def get_random_string():
获取随机字符串
:return:
"""
return "".join(secrets.choice(r_s) for _ in range(5))
return "".join(random.choice(r_s) for _ in range(5))
async def get_now():
@@ -41,22 +40,15 @@ async def get_now():
return datetime.datetime.now(datetime.timezone(datetime.timedelta(hours=8)))
async def get_select_token(code: str, offset: int = 0):
async def get_select_token(code: str):
"""
获取下载token
:param code: 取件码
:param offset: 时间窗口偏移(0=当前窗口,1=上一个窗口)。
用于兼容窗口边界竞态:用户在某窗口末尾获取的 token,
请求到达服务器时可能已进入下一窗口。
:param code:
:return:
"""
token = getattr(settings, "jwt_secret", "")
if not token:
raise RuntimeError("应用签名密钥未初始化")
# 每个窗口约 1000 秒;offset 允许校验上一窗口,避免边界竞态
time_factor = int(time.time() / 1000) - max(0, int(offset))
token = settings.admin_token
return hashlib.sha256(
f"{code}{time_factor}000{token}".encode()
f"{code}{int(time.time() / 1000)}000{token}".encode()
).hexdigest()
@@ -130,10 +122,10 @@ def verify_password(password: str, hashed: str) -> bool:
return False
_, salt, stored_hash = parts
password_hash = hashlib.sha256(f"{salt}{password}".encode()).hexdigest()
return hmac.compare_digest(password_hash, stored_hash)
return password_hash == stored_hash
# 旧格式: 明文比较 (兼容迁移前的数据)
return hmac.compare_digest(str(password), str(hashed))
return password == hashed
def is_password_hashed(password: str) -> bool:
+1 -20
View File
@@ -1,20 +1 @@
import os
import re
from pathlib import Path
VERSION_FILE = Path(__file__).resolve().parents[1] / "VERSION"
VERSION_PATTERN = re.compile(
r"^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$"
)
def load_app_version() -> str:
version = os.getenv("APP_VERSION") or VERSION_FILE.read_text(encoding="utf-8")
version = version.strip()
if not VERSION_PATTERN.fullmatch(version):
raise RuntimeError(f"无效的应用版本号: {version!r}")
return version
APP_VERSION = load_app_version()
APP_VERSION = "2.0.0-dev"
+2 -3
View File
@@ -1,8 +1,7 @@
version: "3"
services:
file-code-box:
image: lanol/filecodebox:2.5.3 # x-release-please-version
user: "1000:1000"
image: lanol/filecodebox:latest
volumes:
- fcb-data:/app/data:rw
restart: unless-stopped
@@ -10,4 +9,4 @@ services:
- "12345:12345"
volumes:
fcb-data:
external: false
external: false
+52
View File
@@ -0,0 +1,52 @@
{
"hash": "8f855eaf",
"configHash": "1b3ca22f",
"lockfileHash": "bd28b2c2",
"browserHash": "29e84937",
"optimized": {
"vue": {
"src": "../../../node_modules/.pnpm/vue@3.5.13/node_modules/vue/dist/vue.runtime.esm-bundler.js",
"file": "vue.js",
"fileHash": "3215885f",
"needsInterop": false
},
"vitepress > @vue/devtools-api": {
"src": "../../../node_modules/.pnpm/@vue+devtools-api@7.7.1/node_modules/@vue/devtools-api/dist/index.js",
"file": "vitepress___@vue_devtools-api.js",
"fileHash": "5a5f95ef",
"needsInterop": false
},
"vitepress > @vueuse/core": {
"src": "../../../node_modules/.pnpm/@vueuse+core@12.5.0/node_modules/@vueuse/core/index.mjs",
"file": "vitepress___@vueuse_core.js",
"fileHash": "0fbf66f0",
"needsInterop": false
},
"vitepress > @vueuse/integrations/useFocusTrap": {
"src": "../../../node_modules/.pnpm/@vueuse+integrations@12.5.0_focus-trap@7.6.4/node_modules/@vueuse/integrations/useFocusTrap.mjs",
"file": "vitepress___@vueuse_integrations_useFocusTrap.js",
"fileHash": "91b03896",
"needsInterop": false
},
"vitepress > mark.js/src/vanilla.js": {
"src": "../../../node_modules/.pnpm/mark.js@8.11.1/node_modules/mark.js/src/vanilla.js",
"file": "vitepress___mark__js_src_vanilla__js.js",
"fileHash": "99e4f81c",
"needsInterop": false
},
"vitepress > minisearch": {
"src": "../../../node_modules/.pnpm/minisearch@7.1.1/node_modules/minisearch/dist/es/index.js",
"file": "vitepress___minisearch.js",
"fileHash": "cc176c9c",
"needsInterop": false
}
},
"chunks": {
"chunk-KT7LHMJ2": {
"file": "chunk-KT7LHMJ2.js"
},
"chunk-CQOUZRMK": {
"file": "chunk-CQOUZRMK.js"
}
}
}
File diff suppressed because it is too large. Load diff
+7
View File
@@ -0,0 +1,7 @@
{
"version": 3,
"sources": ["../../../node_modules/.pnpm/@vue+shared@3.5.13/node_modules/@vue/shared/dist/shared.esm-bundler.js", "../../../node_modules/.pnpm/@vue+reactivity@3.5.13/node_modules/@vue/reactivity/dist/reactivity.esm-bundler.js", "../../../node_modules/.pnpm/@vue+runtime-core@3.5.13/node_modules/@vue/runtime-core/dist/runtime-core.esm-bundler.js", "../../../node_modules/.pnpm/@vue+runtime-dom@3.5.13/node_modules/@vue/runtime-dom/dist/runtime-dom.esm-bundler.js", "../../../node_modules/.pnpm/vue@3.5.13/node_modules/vue/dist/vue.runtime.esm-bundler.js"],
"sourcesContent": ["/**\n* @vue/shared v3.5.13\n* (c) 2018-present Yuxi (Evan) You and Vue contributors\n* @license MIT\n**/\n/*! #__NO_SIDE_EFFECTS__ */\n// @__NO_SIDE_EFFECTS__\nfunction makeMap(str) {\n const map = /* @__PURE__ */ Object.create(null);\n for (const key of str.split(\",\")) map[key] = 1;\n return (val) => val in map;\n}\n\nconst EMPTY_OBJ = !!(process.env.NODE_ENV !== \"production\") ? Object.freeze({}) : {};\nconst EMPTY_ARR = !!(process.env.NODE_ENV !== \"production\") ? Object.freeze([]) : [];\nconst NOOP = () => {\n};\nconst NO = () => false;\nconst isOn = (key) => key.charCodeAt(0) === 111 && key.charCodeAt(1) === 110 && // uppercase letter\n(key.charCodeAt(2) > 122 || key.charCodeAt(2) < 97);\nconst isModelListener = (key) => key.startsWith(\"onUpdate:\");\nconst extend = Object.assign;\nconst remove = (arr, el) => {\n const i = arr.indexOf(el);\n if (i > -1) {\n arr.splice(i, 1);\n }\n};\nconst hasOwnProperty = Object.prototype.hasOwnProperty;\nconst hasOwn = (val, key) => hasOwnProperty.call(val, key);\nconst isArray = Array.isArray;\nconst isMap = (val) => toTypeString(val) === \"[object Map]\";\nconst isSet = (val) => toTypeString(val) === \"[object Set]\";\nconst isDate = (val) => toTypeString(val) === \"[object Date]\";\nconst isRegExp = (val) => toTypeString(val) === \"[object RegExp]\";\nconst isFunction = (val) => typeof val === \"function\";\nconst isString = (val) => typeof val === \"string\";\nconst isSymbol = (val) => typeof val === \"symbol\";\nconst isObject = (val) => val !== null && typeof val === \"object\";\nconst isPromise = (val) => {\n return (isObject(val) || isFunction(val)) && isFunction(val.then) && isFunction(val.catch);\n};\nconst objectToString = Object.prototype.toString;\nconst toTypeString = (value) => objectToString.call(value);\nconst toRawType = (value) => {\n return toTypeString(value).slice(8, -1);\n};\nconst isPlainObject = (val) => toTypeString(val) === \"[object Object]\";\nconst isIntegerKey = (key) => isString(key) && key !== \"NaN\" && key[0] !== \"-\" && \"\" + parseInt(key, 10) === key;\nconst isReservedProp = /* @__PURE__ */ makeMap(\n // the leading comma is intentional so empty string \"\" is also included\n \",key,ref,ref_for,ref_key,onVnodeBeforeMount,onVnodeMounted,onVnodeBeforeUpdate,onVnodeUpdated,onVnodeBeforeUnmount,onVnodeUnmounted\"\n);\nconst isBuiltInDirective = /* @__PURE__ */ makeMap(\n \"bind,cloak,else-if,else,for,html,if,model,on,once,pre,show,slot,text,memo\"\n);\nconst cacheStringFunction = (fn) => {\n const cache = /* @__PURE__ */ Object.create(null);\n return (str) => {\n const hit = cache[str];\n return hit || (cache[str] = fn(str));\n };\n};\nconst camelizeRE = /-(\\w)/g;\nconst camelize = cacheStringFunction(\n (str) => {\n return str.replace(camelizeRE, (_, c) => c ? c.toUpperCase() : \"\");\n }\n);\nconst hyphenateRE = /\\B([A-Z])/g;\nconst hyphenate = cacheStringFunction(\n (str) => str.replace(hyphenateRE, \"-$1\").toLowerCase()\n);\nconst capitalize = cacheStringFunction((str) => {\n return str.charAt(0).toUpperCase() + str.slice(1);\n});\nconst toHandlerKey = cacheStringFunction(\n (str) => {\n const s = str ? `on${capitalize(str)}` : ``;\n return s;\n }\n);\nconst hasChanged = (value, oldValue) => !Object.is(value, oldValue);\nconst invokeArrayFns = (fns, ...arg) => {\n for (let i = 0; i < fns.length; i++) {\n fns[i](...arg);\n }\n};\nconst def = (obj, key, value, writable = false) => {\n Object.defineProperty(obj, key, {\n configurable: true,\n enumerable: false,\n writable,\n value\n });\n};\nconst looseToNumber = (val) => {\n const n = parseFloat(val);\n return isNaN(n) ? val : n;\n};\nconst toNumber = (val) => {\n const n = isString(val) ? Number(val) : NaN;\n return isNaN(n) ? val : n;\n};\nlet _globalThis;\nconst getGlobalThis = () => {\n return _globalThis || (_globalThis = typeof globalThis !== \"undefined\" ? globalThis : typeof self !== \"undefined\" ? self : typeof window !== \"undefined\" ? window : typeof global !== \"undefined\" ? global : {});\n};\nconst identRE = /^[_$a-zA-Z\\xA0-\\uFFFF][_$a-zA-Z0-9\\xA0-\\uFFFF]*$/;\nfunction genPropsAccessExp(name) {\n return identRE.test(name) ? `__props.${name}` : `__props[${JSON.stringify(name)}]`;\n}\nfunction genCacheKey(source, options) {\n return source + JSON.stringify(\n options,\n (_, val) => typeof val === \"function\" ? val.toString() : val\n );\n}\n\nconst PatchFlags = {\n \"TEXT\": 1,\n \"1\": \"TEXT\",\n \"CLASS\": 2,\n \"2\": \"CLASS\",\n \"STYLE\": 4,\n \"4\": \"STYLE\",\n \"PROPS\": 8,\n \"8\": \"PROPS\",\n \"FULL_PROPS\": 16,\n \"16\": \"FULL_PROPS\",\n \"NEED_HYDRATION\": 32,\n \"32\": \"NEED_HYDRATION\",\n \"STABLE_FRAGMENT\": 64,\n \"64\": \"STABLE_FRAGMENT\",\n \"KEYED_FRAGMENT\": 128,\n \"128\": \"KEYED_FRAGMENT\",\n \"UNKEYED_FRAGMENT\": 256,\n \"256\": \"UNKEYED_FRAGMENT\",\n \"NEED_PATCH\": 512,\n \"512\": \"NEED_PATCH\",\n \"DYNAMIC_SLine truncated
"mappings": ";AAOA,SAAS,QAAQ,KAAK;AACpB,QAAMA,OAAsB,uBAAO,OAAO,IAAI;AAC9C,aAAW,OAAO,IAAI,MAAM,GAAG,EAAG,CAAAA,KAAI,GAAG,IAAI;AAC7C,SAAO,CAAC,QAAQ,OAAOA;AACzB;AAEA,IAAM,YAAY,OAA4C,OAAO,OAAO,CAAC,CAAC,IAAI,CAAC;AACnF,IAAM,YAAY,OAA4C,OAAO,OAAO,CAAC,CAAC,IAAI,CAAC;AACnF,IAAM,OAAO,MAAM;AACnB;AACA,IAAM,KAAK,MAAM;AACjB,IAAM,OAAO,CAAC,QAAQ,IAAI,WAAW,CAAC,MAAM,OAAO,IAAI,WAAW,CAAC,MAAM;AAAA,CACxE,IAAI,WAAW,CAAC,IAAI,OAAO,IAAI,WAAW,CAAC,IAAI;AAChD,IAAM,kBAAkB,CAAC,QAAQ,IAAI,WAAW,WAAW;AAC3D,IAAM,SAAS,OAAO;AACtB,IAAM,SAAS,CAAC,KAA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S,UAAU;AAC9B;AAmBA,IAAM,kBAAkC;AAAA,EACtC;AACF;AACA,IAAM,iBAAiC;AAAA,EACrC;AACF;AACA,IAAM,oBAAoC;AAAA,EACxC;AACF;AACA,SAAS,sBAAsB,OAAO;AACpC,MAAI,SAAS,MAAM;AACjB,WAAO;AAAA,EACT;AACA,QAAM,OAAO,OAAO;AACpB,SAAO,SAAS,YAAY,SAAS,YAAY,SAAS;AAC5D;AA6CA,IAAM,4BAA4B;AAClC,SAAS,qBAAqB,KAAK,cAAc;AAC/C,SAAO,ILine truncated
"names": ["map", "computed", "computed", "self", "hasOwnProperty", "isRef", "readonly", "effect", "isRef", "isRef", "p", "version", "callHook", "remove", "ref", "patchProp", "hydrate", "hasWarned", "resolve", "watch", "render", "computed", "h", "createApp", "effect", "remove2", "track", "trigger", "isModelListener", "emit", "render2", "warn", "warn", "callHook", "resolve", "watch", "isBoolean", "def", "enterCbKey", "compile", "warn"]
}
File diff suppressed because it is too large. Load diff
+7
View File
@@ -0,0 +1,7 @@
{
"version": 3,
"sources": ["../../../node_modules/.pnpm/@vueuse+shared@12.5.0/node_modules/@vueuse/shared/index.mjs", "../../../node_modules/.pnpm/@vueuse+core@12.5.0/node_modules/@vueuse/core/index.mjs"],
"sourcesContent": ["import { shallowRef, watchEffect, readonly, ref, watch, customRef, getCurrentScope, onScopeDispose, effectScope, getCurrentInstance, hasInjectionContext, inject, provide, isRef, unref, toValue as toValue$1, computed, reactive, toRefs as toRefs$1, toRef as toRef$1, onBeforeMount, nextTick, onBeforeUnmount, onMounted, onUnmounted, isReactive } from 'vue';\n\nfunction computedEager(fn, options) {\n var _a;\n const result = shallowRef();\n watchEffect(() => {\n result.value = fn();\n }, {\n ...options,\n flush: (_a = options == null ? undefined : options.flush) != null ? _a : \"sync\"\n });\n return readonly(result);\n}\n\nfunction computedWithControl(source, fn) {\n let v = undefined;\n let track;\n let trigger;\n const dirty = ref(true);\n const update = () => {\n dirty.value = true;\n trigger();\n };\n watch(source, update, { flush: \"sync\" });\n const get = typeof fn === \"function\" ? fn : fn.get;\n const set = typeof fn === \"function\" ? undefined : fn.set;\n const result = customRef((_track, _trigger) => {\n track = _track;\n trigger = _trigger;\n return {\n get() {\n if (dirty.value) {\n v = get(v);\n dirty.value = false;\n }\n track();\n return v;\n },\n set(v2) {\n set == null ? undefined : set(v2);\n }\n };\n });\n if (Object.isExtensible(result))\n result.trigger = update;\n return result;\n}\n\nfunction tryOnScopeDispose(fn) {\n if (getCurrentScope()) {\n onScopeDispose(fn);\n return true;\n }\n return false;\n}\n\nfunction createEventHook() {\n const fns = /* @__PURE__ */ new Set();\n const off = (fn) => {\n fns.delete(fn);\n };\n const clear = () => {\n fns.clear();\n };\n const on = (fn) => {\n fns.add(fn);\n const offFn = () => off(fn);\n tryOnScopeDispose(offFn);\n return {\n off: offFn\n };\n };\n const trigger = (...args) => {\n return Promise.all(Array.from(fns).map((fn) => fn(...args)));\n };\n return {\n on,\n off,\n trigger,\n clear\n };\n}\n\nfunction createGlobalState(stateFactory) {\n let initialized = false;\n let state;\n const scope = effectScope(true);\n return (...args) => {\n if (!initialized) {\n state = scope.run(() => stateFactory(...args));\n initialized = true;\n }\n return state;\n };\n}\n\nconst localProvidedStateMap = /* @__PURE__ */ new WeakMap();\n\nconst injectLocal = (...args) => {\n var _a;\n const key = args[0];\n const instance = (_a = getCurrentInstance()) == null ? undefined : _a.proxy;\n if (instance == null && !hasInjectionContext())\n throw new Error(\"injectLocal must be called in setup\");\n if (instance && localProvidedStateMap.has(instance) && key in localProvidedStateMap.get(instance))\n return localProvidedStateMap.get(instance)[key];\n return inject(...args);\n};\n\nconst provideLocal = (key, value) => {\n var _a;\n const instance = (_a = getCurrentInstance()) == null ? undefined : _a.proxy;\n if (instance == null)\n throw new Error(\"provideLocal must be called in setup\");\n if (!localProvidedStateMap.has(instance))\n localProvidedStateMap.set(instance, /* @__PURE__ */ Object.create(null));\n const localProvidedState = localProvidedStateMap.get(instance);\n localProvidedState[key] = value;\n provide(key, value);\n};\n\nfunction createInjectionState(composable, options) {\n const key = (options == null ? undefined : options.injectionKey) || Symbol(composable.name || \"InjectionState\");\n const defaultValue = options == null ? undefined : options.defaultValue;\n const useProvidingState = (...args) => {\n const state = composable(...args);\n provideLocal(key, state);\n return state;\n };\n const useInjectedState = () => injectLocal(key, defaultValue);\n return [useProvidingState, useInjectedState];\n}\n\nfunction createSharedComposable(composable) {\n let subscribers = 0;\n let state;\n let scope;\n const dispose = () => {\n subscribers -= 1;\n if (scope && subscribers <= 0) {\n scope.stop();\n state = undefined;\n scope = undefined;\n }\n };\n return (...args) => {\n subscribers += 1;\n if (!scope) {\n scope = effectScope(true);\n state = scope.run(() => composable(...args));\n }\n tryOnScopeDispose(dispose);\n return state;\n };\n}\n\nfunction extendRef(ref, extend, { enumerable = false, unwrap = true } = {}) {\n for (const [key, value] of Object.entries(extend)) {\n if (key === \"value\")\n continue;\n if (isRef(value) && unwrap) {\n Object.defineProperty(ref, key, {\n get() {\n return value.value;\n },\n set(v) {\n value.value = v;\n },\n enumerable\n });\n } else {\n Object.defineProperty(ref, key, { value, enumerable });\n }\n }\n return ref;\n}\n\nfunction get(obj, key) {\n if (key == null)\n return unref(obj);\n return unref(obj)[kLine truncated
"mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAEA,SAAS,cAAc,IAAI,SAAS;AAClC,MAAI;AACJ,QAAM,SAAS,WAAW;AAC1B,cAAY,MAAM;AAChB,WAAO,QAAQ,GAAG;AAAA,EACpB,GAAG;AAAA,IACD,GAAG;AAAA,IACH,QAAQ,KAAK,WAAW,OAAO,SAAY,QAAQ,UAAU,OAAO,KAAK;AAAA,EAC3E,CAAC;AACD,SAAO,SAAS,MAAM;AACxB;AAEA,SAAS,oBAAoB,QAAQ,IAAI;AACvC,MAAI,IAAI;AACR,MAAI;AACJ,MAAI;AACJ,QAAM,QAAQ,IAAI,IAAI;AACtB,QAAM,SAAS,MAAM;AACnB,UAAM,QAAQ;AACd,YA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AM,QAAQ,IAAI,MAAM,CAAC,GAAG;AAAA,IAC1B,IAAI,GAAG,GAAG,UAAU;AAClB,aAAO,MAAM,QAAQ,IAAI,UAAU,OAAO,GAAG,QAAQ,CAAC;AAAA,IACxD;AAAA,IACA,IAAI,GAAG,GAAG,OAAO;AACf,UAAI,MAAM,UAAU,MAAM,CAAC,CAAC,KAAK,CAAC,MAAM,KAAK;AAC3C,kBAAU,MAAM,CAAC,EAAE,QAAQ;AAAA;AAE3B,kBAAU,MAAM,CAAC,IAAI;AACvB,aAAO;AAAA,IACT;AAAA,IACA,eAAe,GAAG,GAAG;AACnB,aAAO,QAAQ,eAAe,UAAU,OAAO,CAAC;AAAA,IAClD;AAAA,IACA,IAAI,GAAG,GAAG;AALine truncated
"names": ["get", "set", "ref", "keys", "invoke", "toRef", "toRefs", "toValue", "window", "document", "timestamp", "navigator", "events", "getValue", "defaults", "toRef", "set", "onUpdated", "preventDefault", "toRefs", "now", "keys", "get", "isReadonly"]
}
+3
View File
@@ -0,0 +1,3 @@
{
"type": "module"
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,7 @@
{
"version": 3,
"sources": ["../../../node_modules/.pnpm/@vue+devtools-shared@7.7.1/node_modules/@vue/devtools-shared/dist/index.js", "../../../node_modules/.pnpm/perfect-debounce@1.0.0/node_modules/perfect-debounce/dist/index.mjs", "../../../node_modules/.pnpm/hookable@5.5.3/node_modules/hookable/dist/index.mjs", "../../../node_modules/.pnpm/birpc@0.2.19/node_modules/birpc/dist/index.mjs", "../../../node_modules/.pnpm/@vue+devtools-kit@7.7.1/node_modules/@vue/devtools-kit/dist/index.js"],
"sourcesContent": ["var __create = Object.create;\nvar __defProp = Object.defineProperty;\nvar __getOwnPropDesc = Object.getOwnPropertyDescriptor;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __getProtoOf = Object.getPrototypeOf;\nvar __hasOwnProp = Object.prototype.hasOwnProperty;\nvar __esm = (fn, res) => function __init() {\n return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;\n};\nvar __commonJS = (cb, mod) => function __require() {\n return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;\n};\nvar __copyProps = (to, from, except, desc) => {\n if (from && typeof from === \"object\" || typeof from === \"function\") {\n for (let key of __getOwnPropNames(from))\n if (!__hasOwnProp.call(to, key) && key !== except)\n __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });\n }\n return to;\n};\nvar __toESM = (mod, isNodeMode, target2) => (target2 = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(\n // If the importer is in node compatibility mode or this is not an ESM\n // file that has been converted to a CommonJS file using a Babel-\n // compatible transform (i.e. \"__esModule\" has not been set), then set\n // \"default\" to the CommonJS \"module.exports\" for node compatibility.\n isNodeMode || !mod || !mod.__esModule ? __defProp(target2, \"default\", { value: mod, enumerable: true }) : target2,\n mod\n));\n\n// ../../node_modules/.pnpm/tsup@8.3.5_@microsoft+api-extractor@7.48.1_@types+node@22.10.5__jiti@2.4.2_postcss@8.4.49_tsx_s7k37zks4wtn7x2grzma6lrsfa/node_modules/tsup/assets/esm_shims.js\nvar init_esm_shims = __esm({\n \"../../node_modules/.pnpm/tsup@8.3.5_@microsoft+api-extractor@7.48.1_@types+node@22.10.5__jiti@2.4.2_postcss@8.4.49_tsx_s7k37zks4wtn7x2grzma6lrsfa/node_modules/tsup/assets/esm_shims.js\"() {\n \"use strict\";\n }\n});\n\n// ../../node_modules/.pnpm/rfdc@1.4.1/node_modules/rfdc/index.js\nvar require_rfdc = __commonJS({\n \"../../node_modules/.pnpm/rfdc@1.4.1/node_modules/rfdc/index.js\"(exports, module) {\n \"use strict\";\n init_esm_shims();\n module.exports = rfdc2;\n function copyBuffer(cur) {\n if (cur instanceof Buffer) {\n return Buffer.from(cur);\n }\n return new cur.constructor(cur.buffer.slice(), cur.byteOffset, cur.length);\n }\n function rfdc2(opts) {\n opts = opts || {};\n if (opts.circles) return rfdcCircles(opts);\n const constructorHandlers = /* @__PURE__ */ new Map();\n constructorHandlers.set(Date, (o) => new Date(o));\n constructorHandlers.set(Map, (o, fn) => new Map(cloneArray(Array.from(o), fn)));\n constructorHandlers.set(Set, (o, fn) => new Set(cloneArray(Array.from(o), fn)));\n if (opts.constructorHandlers) {\n for (const handler2 of opts.constructorHandlers) {\n constructorHandlers.set(handler2[0], handler2[1]);\n }\n }\n let handler = null;\n return opts.proto ? cloneProto : clone;\n function cloneArray(a, fn) {\n const keys = Object.keys(a);\n const a2 = new Array(keys.length);\n for (let i = 0; i < keys.length; i++) {\n const k = keys[i];\n const cur = a[k];\n if (typeof cur !== \"object\" || cur === null) {\n a2[k] = cur;\n } else if (cur.constructor !== Object && (handler = constructorHandlers.get(cur.constructor))) {\n a2[k] = handler(cur, fn);\n } else if (ArrayBuffer.isView(cur)) {\n a2[k] = copyBuffer(cur);\n } else {\n a2[k] = fn(cur);\n }\n }\n return a2;\n }\n function clone(o) {\n if (typeof o !== \"object\" || o === null) return o;\n if (Array.isArray(o)) return cloneArray(o, clone);\n if (o.constructor !== Object && (handler = constructorHandlers.get(o.constructor))) {\n return handler(o, clone);\n }\n const o2 = {};\n for (const k in o) {\n if (Object.hasOwnProperty.call(o, k) === false) continue;\n const cur = o[k];\n if (typeof cur !== \"object\" || cur === null) {\n o2[k] = cur;\n } else if (cur.constructor !== Object && (handler = constructorHandlers.get(cur.constructor))) {\n o2[k] = handler(cur, clone);\n } else if (ArrayBuffer.isView(cur)) {\n o2[k] = copyBuffer(cur);\n } else {\n o2[k] = clone(cur);\n }\n }\n return o2;\n }\n function cloneProto(o) {\n if (typeof o !== \"object\" || o === null) return o;\n if (Array.isArray(o)) return cloneArray(o, cloneProto);\n if (o.constructor !== Object && (handler = constructorHandlers.get(o.constructor))) {\n return handler(o, cloneProto);\n }\n const o2 = {};\n for (const k in o) {\n const cur = o[k];\n if (tLine truncated
"mappings": ";AAAA,IAAI,WAAW,OAAO;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gB,WAAW,UAAU,oBAAoB,IAAI,IAAI,WAAW,IAAI;AAC7F,eAAG,CAAC,IAAI,QAAQ,KAAK,EAAE;AAAA,UACzB,WAAW,YAAY,OAAO,GAAG,GAAG;AAClC,eAAG,CAAC,IAAI,WAAW,GAAG;AAAA,UACxB,OAAO;AACL,kBAAM,QAAQ,KAAK,QAAQ,GAAG;AAC9B,gBAAI,UAAU,IAAI;AAChB,iBAAG,CAAC,IAAI,QAAQ,KAAK;AAAA,YACvB,OAAO;AACL,iBAAG,CAAC,IAAI,GAAG,GAAG;AAAA,YAChB;AAAA,UACF;AAAA,QACF;AACA,eAAO;AAAA,MACT;AACA,eAAS,MAAM,GAAG;AAChB,YAAI,OAAO,MAAM,YAAY,MAAM,KAAM,QAAO;AAChD,YAAI,MAAM,QAAQ,CAAC,EAAG,QAAO,WAAW,GAAG,KAAK;AAChD,YAAI,EAAE,gBAAgB,WAAW,UAAU,oBAAoB,IAAI,EAAE,WAAW,IAAI;AAClF,iBAAO,QAAQ,GAAG,KAAK;AAAA,QACzB;AACA,cAAM,KAAK,CAAC;AACZ,aAAK,KAAK,CAAC;AACX,gBAAQ,KAAK,EAAE;AACf,mBAAW,KAAK,GAAG;AACjB,cAAI,OAAO,eAAe,KAAK,GAAG,CAAC,MAAM,MAAO;AAChD,gBAAM,MAAM,EAAE,CAAC;AACf,cAAI,OAAO,QAAQ,YAAY,QAAQ,MAAM;AAC3C,eAAG,CAAC,IAAI;AAAA,UACV,WAAW,IAAI,gBAAgB,WLine truncated
"names": ["hooks", "hooks", "hook", "hook", "hooks", "clearTimeout", "setTimeout", "__create", "__defProp", "__getOwnPropDesc", "__getOwnPropNames", "__getProtoOf", "__hasOwnProp", "__esm", "__commonJS", "__copyProps", "__toESM", "init_esm_shims", "init_esm_shims", "init_esm_shims", "_a", "init_esm_shims", "init_esm_shims", "init_esm_shims", "_a2", "init_esm_shims", "init_esm_shims", "init_esm_shims", "init_esm_shims", "init_esm_shims", "init_esm_shims", "init_esm_shims", "init_esm_shims", "init_esm_shims", "__toESM", "init_esm_shims", "init_esm_shims", "init_esm_shims", "init_esm_shims", "init_esm_shims", "init_esm_shims", "init_esm_shims", "init_esm_shims", "init_esm_shims", "init_esm_shims", "init_esm_shims", "init_esm_shims", "init_esm_shims", "_a22", "init_esm_shims", "init_esm_shims"]
}
+581
View File
@@ -0,0 +1,581 @@
import {
DefaultMagicKeysAliasMap,
StorageSerializers,
TransitionPresets,
assert,
breakpointsAntDesign,
breakpointsBootstrapV5,
breakpointsElement,
breakpointsMasterCss,
breakpointsPrimeFlex,
breakpointsQuasar,
breakpointsSematic,
breakpointsTailwind,
breakpointsVuetify,
breakpointsVuetifyV2,
breakpointsVuetifyV3,
bypassFilter,
camelize,
clamp,
cloneFnJSON,
computedAsync,
computedEager,
computedInject,
computedWithControl,
containsProp,
controlledRef,
createEventHook,
createFetch,
createFilterWrapper,
createGlobalState,
createInjectionState,
createReusableTemplate,
createSharedComposable,
createSingletonPromise,
createTemplatePromise,
createUnrefFn,
customStorageEventName,
debounceFilter,
defaultDocument,
defaultLocation,
defaultNavigator,
defaultWindow,
executeTransition,
extendRef,
formatDate,
formatTimeAgo,
get,
getLifeCycleTarget,
getSSRHandler,
hasOwn,
hyphenate,
identity,
increaseWithUnit,
injectLocal,
invoke,
isClient,
isDef,
isDefined,
isIOS,
isObject,
isWorker,
makeDestructurable,
mapGamepadToXbox360Controller,
noop,
normalizeDate,
notNullish,
now,
objectEntries,
objectOmit,
objectPick,
onClickOutside,
onElementRemoval,
onKeyDown,
onKeyPressed,
onKeyStroke,
onKeyUp,
onLongPress,
onStartTyping,
pausableFilter,
promiseTimeout,
provideLocal,
provideSSRWidth,
pxValue,
rand,
reactify,
reactifyObject,
reactiveComputed,
reactiveOmit,
reactivePick,
refAutoReset,
refDebounced,
refDefault,
refThrottled,
refWithControl,
resolveRef,
resolveUnref,
set,
setSSRHandler,
syncRef,
syncRefs,
templateRef,
throttleFilter,
timestamp,
toArray,
toReactive,
toRef,
toRefs,
toValue,
tryOnBeforeMount,
tryOnBeforeUnmount,
tryOnMounted,
tryOnScopeDispose,
tryOnUnmounted,
unrefElement,
until,
useActiveElement,
useAnimate,
useArrayDifference,
useArrayEvery,
useArrayFilter,
useArrayFind,
useArrayFindIndex,
useArrayFindLast,
useArrayIncludes,
useArrayJoin,
useArrayMap,
useArrayReduce,
useArraySome,
useArrayUnique,
useAsyncQueue,
useAsyncState,
useBase64,
useBattery,
useBluetooth,
useBreakpoints,
useBroadcastChannel,
useBrowserLocation,
useCached,
useClipboard,
useClipboardItems,
useCloned,
useColorMode,
useConfirmDialog,
useCountdown,
useCounter,
useCssVar,
useCurrentElement,
useCycleList,
useDark,
useDateFormat,
useDebounceFn,
useDebouncedRefHistory,
useDeviceMotion,
useDeviceOrientation,
useDevicePixelRatio,
useDevicesList,
useDisplayMedia,
useDocumentVisibility,
useDraggable,
useDropZone,
useElementBounding,
useElementByPoint,
useElementHover,
useElementSize,
useElementVisibility,
useEventBus,
useEventListener,
useEventSource,
useEyeDropper,
useFavicon,
useFetch,
useFileDialog,
useFileSystemAccess,
useFocus,
useFocusWithin,
useFps,
useFullscreen,
useGamepad,
useGeolocation,
useIdle,
useImage,
useInfiniteScroll,
useIntersectionObserver,
useInterval,
useIntervalFn,
useKeyModifier,
useLastChanged,
useLocalStorage,
useMagicKeys,
useManualRefHistory,
useMediaControls,
useMediaQuery,
useMemoize,
useMemory,
useMounted,
useMouse,
useMouseInElement,
useMousePressed,
useMutationObserver,
useNavigatorLanguage,
useNetwork,
useNow,
useObjectUrl,
useOffsetPagination,
useOnline,
usePageLeave,
useParallax,
useParentElement,
usePerformanceObserver,
usePermission,
usePointer,
usePointerLock,
usePointerSwipe,
usePreferredColorScheme,
usePreferredContrast,
usePreferredDark,
usePreferredLanguages,
usePreferredReducedMotion,
usePreferredReducedTransparency,
usePrevious,
useRafFn,
useRefHistory,
useResizeObserver,
useSSRWidth,
useScreenOrientation,
useScreenSafeArea,
useScriptTag,
useScroll,
useScrollLock,
useSessionStorage,
useShare,
useSorted,
useSpeechRecognition,
useSpeechSynthesis,
useStepper,
useStorage,
useStorageAsync,
useStyleTag,
useSupported,
useSwipe,
useTemplateRefsList,
useTextDirection,
useTextSelection,
useTextareaAutosize,
useThrottleFn,
useThrottledRefHistory,
useTimeAgo,
useTimeout,
useTimeoutFn,
useTimeoutPoll,
useTimestamp,
useTitle,
useToNumber,
useToString,
useToggle,
useTransition,
useUrlSearchParams,
useUserMedia,
useVModel,
useVModels,
useVibrate,
useVirtualList,
useWakeLock,
useWebNotification,
useWebSocket,
useWebWorker,
useWebWorkerFn,
useWindowFocus,
useWindowScroll,
useWindowSize,
watchArray,
watchAtMost,
watchDebounced,
watchDeep,
watchIgnorable,
watchImmediate,
watchOnce,
watchPausable,
watchThrottled,
watchTriggerable,
watchWithFilter,
whenever
} from "./chunk-KT7LHMJ2.js";
import "./chunk-CQOUZRMK.js";
export {
DefaultMagicKeysAliasMap,
StorageSerializers,
TransitionPresets,
assert,
computedAsync as asyncComputed,
refAutoReset as autoResetRef,
breakpointsAntDesign,
breakpointsBootstrapV5,
breakpointsElement,
breakpointsMasterCss,
breakpointsPrimeFlex,
breakpointsQuasar,
breakpointsSematic,
breakpointsTailwind,
breakpointsVuetify,
breakpointsVuetifyV2,
breakpointsVuetifyV3,
bypassFilter,
camelize,
clamp,
cloneFnJSON,
computedAsync,
computedEager,
computedInject,
computedWithControl,
containsProp,
computedWithControl as controlledComputed,
controlledRef,
createEventHook,
createFetch,
createFilterWrapper,
createGlobalState,
createInjectionState,
reactify as createReactiveFn,
createReusableTemplate,
createSharedComposable,
createSingletonPromise,
createTemplatePromise,
createUnrefFn,
customStorageEventName,
debounceFilter,
refDebounced as debouncedRef,
watchDebounced as debouncedWatch,
defaultDocument,
defaultLocation,
defaultNavigator,
defaultWindow,
computedEager as eagerComputed,
executeTransition,
extendRef,
formatDate,
formatTimeAgo,
get,
getLifeCycleTarget,
getSSRHandler,
hasOwn,
hyphenate,
identity,
watchIgnorable as ignorableWatch,
increaseWithUnit,
injectLocal,
invoke,
isClient,
isDef,
isDefined,
isIOS,
isObject,
isWorker,
makeDestructurable,
mapGamepadToXbox360Controller,
noop,
normalizeDate,
notNullish,
now,
objectEntries,
objectOmit,
objectPick,
onClickOutside,
onElementRemoval,
onKeyDown,
onKeyPressed,
onKeyStroke,
onKeyUp,
onLongPress,
onStartTyping,
pausableFilter,
watchPausable as pausableWatch,
promiseTimeout,
provideLocal,
provideSSRWidth,
pxValue,
rand,
reactify,
reactifyObject,
reactiveComputed,
reactiveOmit,
reactivePick,
refAutoReset,
refDebounced,
refDefault,
refThrottled,
refWithControl,
resolveRef,
resolveUnref,
set,
setSSRHandler,
syncRef,
syncRefs,
templateRef,
throttleFilter,
refThrottled as throttledRef,
watchThrottled as throttledWatch,
timestamp,
toArray,
toReactive,
toRef,
toRefs,
toValue,
tryOnBeforeMount,
tryOnBeforeUnmount,
tryOnMounted,
tryOnScopeDispose,
tryOnUnmounted,
unrefElement,
until,
useActiveElement,
useAnimate,
useArrayDifference,
useArrayEvery,
useArrayFilter,
useArrayFind,
useArrayFindIndex,
useArrayFindLast,
useArrayIncludes,
useArrayJoin,
useArrayMap,
useArrayReduce,
useArraySome,
useArrayUnique,
useAsyncQueue,
useAsyncState,
useBase64,
useBattery,
useBluetooth,
useBreakpoints,
useBroadcastChannel,
useBrowserLocation,
useCached,
useClipboard,
useClipboardItems,
useCloned,
useColorMode,
useConfirmDialog,
useCountdown,
useCounter,
useCssVar,
useCurrentElement,
useCycleList,
useDark,
useDateFormat,
refDebounced as useDebounce,
useDebounceFn,
useDebouncedRefHistory,
useDeviceMotion,
useDeviceOrientation,
useDevicePixelRatio,
useDevicesList,
useDisplayMedia,
useDocumentVisibility,
useDraggable,
useDropZone,
useElementBounding,
useElementByPoint,
useElementHover,
useElementSize,
useElementVisibility,
useEventBus,
useEventListener,
useEventSource,
useEyeDropper,
useFavicon,
useFetch,
useFileDialog,
useFileSystemAccess,
useFocus,
useFocusWithin,
useFps,
useFullscreen,
useGamepad,
useGeolocation,
useIdle,
useImage,
useInfiniteScroll,
useIntersectionObserver,
useInterval,
useIntervalFn,
useKeyModifier,
useLastChanged,
useLocalStorage,
useMagicKeys,
useManualRefHistory,
useMediaControls,
useMediaQuery,
useMemoize,
useMemory,
useMounted,
useMouse,
useMouseInElement,
useMousePressed,
useMutationObserver,
useNavigatorLanguage,
useNetwork,
useNow,
useObjectUrl,
useOffsetPagination,
useOnline,
usePageLeave,
useParallax,
useParentElement,
usePerformanceObserver,
usePermission,
usePointer,
usePointerLock,
usePointerSwipe,
usePreferredColorScheme,
usePreferredContrast,
usePreferredDark,
usePreferredLanguages,
usePreferredReducedMotion,
usePreferredReducedTransparency,
usePrevious,
useRafFn,
useRefHistory,
useResizeObserver,
useSSRWidth,
useScreenOrientation,
useScreenSafeArea,
useScriptTag,
useScroll,
useScrollLock,
useSessionStorage,
useShare,
useSorted,
useSpeechRecognition,
useSpeechSynthesis,
useStepper,
useStorage,
useStorageAsync,
useStyleTag,
useSupported,
useSwipe,
useTemplateRefsList,
useTextDirection,
useTextSelection,
useTextareaAutosize,
refThrottled as useThrottle,
useThrottleFn,
useThrottledRefHistory,
useTimeAgo,
useTimeout,
useTimeoutFn,
useTimeoutPoll,
useTimestamp,
useTitle,
useToNumber,
useToString,
useToggle,
useTransition,
useUrlSearchParams,
useUserMedia,
useVModel,
useVModels,
useVibrate,
useVirtualList,
useWakeLock,
useWebNotification,
useWebSocket,
useWebWorker,
useWebWorkerFn,
useWindowFocus,
useWindowScroll,
useWindowSize,
watchArray,
watchAtMost,
watchDebounced,
watchDeep,
watchIgnorable,
watchImmediate,
watchOnce,
watchPausable,
watchThrottled,
watchTriggerable,
watchWithFilter,
whenever
};
//# sourceMappingURL=vitepress___@vueuse_core.js.map
@@ -0,0 +1,7 @@
{
"version": 3,
"sources": [],
"sourcesContent": [],
"mappings": "",
"names": []
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,7 @@
{
"version": 3,
"sources": ["../../../node_modules/.pnpm/tabbable@6.2.0/node_modules/tabbable/src/index.js", "../../../node_modules/.pnpm/focus-trap@7.6.4/node_modules/focus-trap/index.js", "../../../node_modules/.pnpm/@vueuse+integrations@12.5.0_focus-trap@7.6.4/node_modules/@vueuse/integrations/useFocusTrap.mjs"],
"sourcesContent": ["// NOTE: separate `:not()` selectors has broader browser support than the newer\n// `:not([inert], [inert] *)` (Feb 2023)\n// CAREFUL: JSDom does not support `:not([inert] *)` as a selector; using it causes\n// the entire query to fail, resulting in no nodes found, which will break a lot\n// of things... so we have to rely on JS to identify nodes inside an inert container\nconst candidateSelectors = [\n 'input:not([inert])',\n 'select:not([inert])',\n 'textarea:not([inert])',\n 'a[href]:not([inert])',\n 'button:not([inert])',\n '[tabindex]:not(slot):not([inert])',\n 'audio[controls]:not([inert])',\n 'video[controls]:not([inert])',\n '[contenteditable]:not([contenteditable=\"false\"]):not([inert])',\n 'details>summary:first-of-type:not([inert])',\n 'details:not([inert])',\n];\nconst candidateSelector = /* #__PURE__ */ candidateSelectors.join(',');\n\nconst NoElement = typeof Element === 'undefined';\n\nconst matches = NoElement\n ? function () {}\n : Element.prototype.matches ||\n Element.prototype.msMatchesSelector ||\n Element.prototype.webkitMatchesSelector;\n\nconst getRootNode =\n !NoElement && Element.prototype.getRootNode\n ? (element) => element?.getRootNode?.()\n : (element) => element?.ownerDocument;\n\n/**\n * Determines if a node is inert or in an inert ancestor.\n * @param {Element} [node]\n * @param {boolean} [lookUp] If true and `node` is not inert, looks up at ancestors to\n * see if any of them are inert. If false, only `node` itself is considered.\n * @returns {boolean} True if inert itself or by way of being in an inert ancestor.\n * False if `node` is falsy.\n */\nconst isInert = function (node, lookUp = true) {\n // CAREFUL: JSDom does not support inert at all, so we can't use the `HTMLElement.inert`\n // JS API property; we have to check the attribute, which can either be empty or 'true';\n // if it's `null` (not specified) or 'false', it's an active element\n const inertAtt = node?.getAttribute?.('inert');\n const inert = inertAtt === '' || inertAtt === 'true';\n\n // NOTE: this could also be handled with `node.matches('[inert], :is([inert] *)')`\n // if it weren't for `matches()` not being a function on shadow roots; the following\n // code works for any kind of node\n // CAREFUL: JSDom does not appear to support certain selectors like `:not([inert] *)`\n // so it likely would not support `:is([inert] *)` either...\n const result = inert || (lookUp && node && isInert(node.parentNode)); // recursive\n\n return result;\n};\n\n/**\n * Determines if a node's content is editable.\n * @param {Element} [node]\n * @returns True if it's content-editable; false if it's not or `node` is falsy.\n */\nconst isContentEditable = function (node) {\n // CAREFUL: JSDom does not support the `HTMLElement.isContentEditable` API so we have\n // to use the attribute directly to check for this, which can either be empty or 'true';\n // if it's `null` (not specified) or 'false', it's a non-editable element\n const attValue = node?.getAttribute?.('contenteditable');\n return attValue === '' || attValue === 'true';\n};\n\n/**\n * @param {Element} el container to check in\n * @param {boolean} includeContainer add container to check\n * @param {(node: Element) => boolean} filter filter candidates\n * @returns {Element[]}\n */\nconst getCandidates = function (el, includeContainer, filter) {\n // even if `includeContainer=false`, we still have to check it for inertness because\n // if it's inert, all its children are inert\n if (isInert(el)) {\n return [];\n }\n\n let candidates = Array.prototype.slice.apply(\n el.querySelectorAll(candidateSelector)\n );\n if (includeContainer && matches.call(el, candidateSelector)) {\n candidates.unshift(el);\n }\n candidates = candidates.filter(filter);\n return candidates;\n};\n\n/**\n * @callback GetShadowRoot\n * @param {Element} element to check for shadow root\n * @returns {ShadowRoot|boolean} ShadowRoot if available or boolean indicating if a shadowRoot is attached but not available.\n */\n\n/**\n * @callback ShadowRootFilter\n * @param {Element} shadowHostNode the element which contains shadow content\n * @returns {boolean} true if a shadow root could potentially contain valid candidates.\n */\n\n/**\n * @typedef {Object} CandidateScope\n * @property {Element} scopeParent contains inner candidates\n * @property {Element[]} candidates list of candidates found in the scope parent\n */\n\n/**\n * @typedef {Object} IterativeOptions\n * @property {GetShadowRoot|boolean} getShadowRoot true if shadow support is enabled; falsy if not;\n * if a function, implies shadow support is enabled and either returns the shadow root of an element\n * or a boolean stating if it has an undisclosed shadow root\n * @property {(node: Element) => boolean} filter filter candidates\n * @property {boolean} flatten if true then result will flatten any CandidateScope into the returned list\n * @property {Line truncated
"mappings": ";;;;;;;;;;;;;;AAKA,IAAMA,qBAAqB,CACzB,sBACA,uBACA,yBACA,wBACA,uBACA,qCACA,gCACA,gCACA,iEACA,8CACA,sBAAsB;AAExB,IAAMC,oBAAoCD,mBAAmBE,KAAK,GAAG;AAErE,IAAMC,YAAY,OAAOC,YAAY;AAErC,IAAMC,UAAUF,YACZ,WAAY;AAAA,IACZC,QAAQE,UAAUD,WAClBD,QAAQE,UAAUC,qBAClBH,QAAQE,UAAUE;AAEtB,IAAMC,cACJ,CAACN,aAAaC,QAAQE,UAAUG,cAC5B,SAACC,SAAO;AAAA,MAAAC;AAAA,SAAKD,YAAAA,QAAAA,YAAOC,SAAAA,UAAAA,uBAAPD,QAASD,iBAAW,QAAAE,yBAApBA,SAAAA,SAAAA,qBAAAC,KAAAF,OAAuB;AAAC,IACrC,SAACA,SAAO;AAAA,SAAKA,YAAAA,QAAAA,YAAAA,SAAAA,SAAAA,QAASG;AAAa;AAUzC,IAAMC,UAAU,SAAVA,SAAoBC,MAAMC,QAAe;AAAA,MAAAC;AAAA,MAAfD,WAAM,QAAA;AAANA,aAAS;EAAI;AAI3C,MAAME,WAAWH,SAAI,QAAJA,SAAIE,SAAAA,UAAAA,qBAAJF,KAAMI,kBAAYF,QAAAA,uBAAA,SAAA,SAAlBA,mBAAAL,KAAAG,MAAqB,OAAO;AAC7C,MAAMK,QAAQF,aAAa,MAAMA,aAAa;AAO9C,MAAMG,SAASD,SAAUJ,UAAUD,QAAQD,SAAQC,KAAKO,UAAU;AAElE,SAAOD;AACT;AAOA,IAAME,oBAAoB,SAApBA,mBAA8BR,MAAM;AAAA,MAAAS;AAIxC,MAAMC,WAAWV,SAAI,QAAJA,SAAIS,SAAAA,UAAAA,sBAAJT,KAAMI,kBAAYK,QAAAA,wBAAA,SAAA,SAAlBA,oBAAAZ,KAAAG,MAAqB,iBAAiB;AAC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J,gBAAgBS,UAAUxE,KAAKiE,IAAI;AACnD,SAAO,CAACE,WAAWA,YAAYnE;AACjC;AAEA,IAAMgF,UAAU,SAAVA,SAAoBhF,MAAM;AAC9B,SAAOwD,QAAQxD,IAAI,KAAKA,KAAK0D,SAAS;AACxC;AAEA,IAAMuB,qBAAqB,SAArBA,oBAA+BjF,MAAM;AACzC,SAAOgF,QAAQhF,IAAI,KAAK,CAACoE,gBAAgBpE,IAAI;AAC/C;AAGA,IAAMkF,iBAAiB,SAAjBA,gBAA2BlF,MAAM;AAAA,MAAAmF;AAwBrC,MAAIC,WAAWpF,QAAQN,YAAYM,IAAI;AACvC,MAAIqF,gBAAYF,YAAGC,cAAQ,QAAAD,cAAA,SAAA,SAARA,UAAUG;AAI7B,MAAIC,WAAW;AACf,MAAIH,YAAYA,aAAapF,MAAM;AAAA,QAAAwF,eAAAC,uBAAAC;AACjCH,eAAW,CAAC,GACVC,gBAAAH,kBAAYG,QAAAA,kBAAA,WAAAC,wBAAZD,cAAc1F,mBAAa,QAAA2F,0BAAA,UAA3BA,sBAA6BE,SAASN,YAAY,KAClDrF,SAAI,QAAJA,SAAI0F,WAAAA,sBAAJ1F,KAAMF,mBAAa4F,QAAAA,wBAAA,UAAnBA,oBAAqBC,SAAS3F,IAAI;AAGpC,WAAO,CAACuF,YAAYF,cAAc;AAAA,UAAAO,YAAAC,gBAAAC;AAIhCV,iBAAW1F,YAAY2F,YAAY;AACnCA,sBAAYO,aAAGR,cAAQ,QAAAQ,eAAA,SAAA,SAARA,WAAUN;AACzBC,iLine truncated
"names": ["candidateSelectors", "candidateSelector", "join", "NoElement", "Element", "matches", "prototype", "msMatchesSelector", "webkitMatchesSelector", "getRootNode", "element", "_element$getRootNode", "call", "ownerDocument", "isInert", "node", "lookUp", "_node$getAttribute", "inertAtt", "getAttribute", "inert", "result", "parentNode", "isContentEditable", "_node$getAttribute2", "attValue", "getCandidates", "el", "includeContainer", "filter", "candidates", "Array", "slice", "apply", "querySelectorAll", "unshift", "getCandidatesIteratively", "elements", "options", "elementsToCheck", "from", "length", "shift", "tagName", "assigned", "assignedElements", "content", "children", "nestedCandidates", "flatten", "push", "scopeParent", "validCandidate", "includes", "shadowRoot", "getShadowRoot", "validShadowRoot", "shadowRootFilter", "hasTabIndex", "isNaN", "parseInt", "getTabIndex", "Error", "tabIndex", "test", "getSortOrderTabIndex", "isScope", "sortOrderedTabbables", "a", "b", "documentOrder", "isInput", "isHiddenInput", "type", "isDetailsWithSummary", "r", "some", "child", "getCheckedRadio", "nodes", "form", "i", "checked", "isTabbableRadio", "name", "radioScope", "queryRadios", "radioSet", "window", "CSS", "escape", "err", "console", "error", "message", "isRadio", "isNonTabbableRadio", "isNodeAttached", "_nodeRoot", "nodeRoot", "nodeRootHost", "host", "attached", "_nodeRootHost", "_nodeRootHost$ownerDo", "_node$ownerDocument", "contains", "_nodeRoot2", "_nodeRootHost2", "_nodeRootHost2$ownerD", "isZeroArea", "_node$getBoundingClie", "getBoundingClientRect", "width", "height", "isHidden", "_ref", "displayCheck", "getComputedStyle", "visibility", "isDirectSummary", "nodeUnderDetails", "parentElement", "originalNode", "rootNode", "assignedSlot", "getClientRects", "isDisabledFromFieldset", "disabled", "item", "isNodeMatchingSelectorFocusable", "isNodeMatchingSelectorTabbable", "isValidShadowRootTabbable", "shadowHostNode", "sortByOrder", "regularTabbables", "orderedTabbables", "forEach", "candidateTabindex", "sort", "reduce", "acc", "sortable", "concat", "tabbable", "container", "bind", "focusable", "isTabbable", "focusableCandidateSelector", "isFocusable", "activeFocusTraps", "activateTrap", "trapStack", "trap", "length", "activeTrap", "_setPausedState", "trapIndex", "indexOf", "push", "splice", "deactivateTrap", "_isManuallyPaused", "isSelectableInput", "node", "tagName", "toLowerCase", "select", "isEscapeEvent", "e", "key", "keyCode", "isTabEvent", "isKeyForward", "shiftKey", "isKeyBackward", "delay", "fn", "setTimeout", "valueOrHandler", "value", "_len", "arguments", "params", "Array", "_key", "apply", "getActualTarget", "event", "target", "shadowRoot", "composedPath", "internalTrapStack", "createFocusTrap", "elements", "userOptions", "doc", "document", "config", "_objectSpread", "returnFocusOnDeactivate", "escapeDeactivates", "delayInitialFocus", "state", "containers", "containerGroups", "tabbableGroups", "nodeFocusedBeforeActivation", "mostRecentlyFocusedNode", "active", "paused", "manuallyPaused", "delayInitialFocusTimer", "undefined", "recentNavEvent", "getOption", "configOverrideOptions", "optionName", "configOptionName", "findContainerIndex", "element", "findIndex", "_ref", "container", "tabbableNodes", "contains", "includes", "find", "getNodeForOption", "_ref2", "_ref2$hasFallback", "hasFallback", "_ref2$params", "optionValue", "_toConsumableArray", "Error", "concat", "querySelector", "err", "message", "getInitialFocusNode", "isFocusable", "tabbableOptions", "activeElement", "firstTabbableGroup", "firstTabbableNode", "updateTabbableNodes", "map", "tabbable", "focusableNodes", "focusable", "lastTabbableNode", "firstDomTabbableNode", "isTabbable", "lastDomTabbableNode", "slice", "reverse", "posTabIndexesFound", "getTabIndex", "nextTabbableNode", "forward", "nodeIdx", "el", "filter", "group", "g", "getActiveElement", "tryFocus", "focus", "preventScroll", "getReturnFocusNode", "previousActiveElement", "findNextNavNode", "_ref3", "_ref3$isBackward", "isBackward", "destinationNode", "containerIndex", "containerGroup", "startOfGroupIndex", "_ref4", "destinationGroupIndex", "destinationGroup", "lastOfGroupIndex", "_ref5", "checkPointerDown", "clickOutsideDeactivates", "deactivate", "returnFocus", "allowOutsideClick", "preventDefault", "checkFocusIn", "targetContained", "Document", "stopImmediatePropagation", "nextNode", "navAcrossContainers", "mruContainerIdx", "mruTabIdx", "some", "n", "checkKeyNav", "checkTabKey", "checkEscapeKey", "checkClick", "addListeners", "addEventListener", "capture", "passive", "removeListeners", "removeEventListener", "checkDomRemoval", "mutations", "isFocusedNodeRemoved", "mutation", "removedNodes", "from", "mutationObserver", "window", "MutationObserver", "updateObservedNodes", "disconnect", "observe", "subtree", "childList", "activate", "activateOptions", "onActivate", "onPostActivate", "checkCanFocusTrap", "finishActivation", "then", "deactivateOptions", "options", "onDeactiLine truncated
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,7 @@
{
"version": 3,
"sources": ["../../../node_modules/.pnpm/mark.js@8.11.1/node_modules/mark.js/src/lib/domiterator.js", "../../../node_modules/.pnpm/mark.js@8.11.1/node_modules/mark.js/src/lib/mark.js", "../../../node_modules/.pnpm/mark.js@8.11.1/node_modules/mark.js/src/vanilla.js"],
"sourcesContent": ["/**\n * A NodeIterator with iframes support and a method to check if an element is\n * matching a specified selector\n * @example\n * const iterator = new DOMIterator(\n * document.querySelector(\"#context\"), true\n * );\n * iterator.forEachNode(NodeFilter.SHOW_TEXT, node => {\n * console.log(node);\n * }, node => {\n * if(DOMIterator.matches(node.parentNode, \".ignore\")){\n * return NodeFilter.FILTER_REJECT;\n * } else {\n * return NodeFilter.FILTER_ACCEPT;\n * }\n * }, () => {\n * console.log(\"DONE\");\n * });\n * @todo Outsource into separate repository\n */\nexport default class DOMIterator {\n\n /**\n * @param {HTMLElement|HTMLElement[]|NodeList|string} ctx - The context DOM\n * element, an array of DOM elements, a NodeList or a selector\n * @param {boolean} [iframes=true] - A boolean indicating if iframes should\n * be handled\n * @param {string[]} [exclude=[]] - An array containing exclusion selectors\n * for iframes\n * @param {number} [iframesTimeout=5000] - A number indicating the ms to\n * wait before an iframe should be skipped, in case the load event isn't\n * fired. This also applies if the user is offline and the resource of the\n * iframe is online (either by the browsers \"offline\" mode or because\n * there's no internet connection)\n */\n constructor(ctx, iframes = true, exclude = [], iframesTimeout = 5000) {\n /**\n * The context of the instance. Either a DOM element, an array of DOM\n * elements, a NodeList or a selector\n * @type {HTMLElement|HTMLElement[]|NodeList|string}\n * @access protected\n */\n this.ctx = ctx;\n /**\n * Boolean indicating if iframe support is enabled\n * @type {boolean}\n * @access protected\n */\n this.iframes = iframes;\n /**\n * An array containing exclusion selectors for iframes\n * @type {string[]}\n */\n this.exclude = exclude;\n /**\n * The maximum ms to wait for a load event before skipping an iframe\n * @type {number}\n */\n this.iframesTimeout = iframesTimeout;\n }\n\n /**\n * Checks if the specified DOM element matches the selector\n * @param {HTMLElement} element - The DOM element\n * @param {string|string[]} selector - The selector or an array with\n * selectors\n * @return {boolean}\n * @access public\n */\n static matches(element, selector) {\n const selectors = typeof selector === 'string' ? [selector] : selector,\n fn = (\n element.matches ||\n element.matchesSelector ||\n element.msMatchesSelector ||\n element.mozMatchesSelector ||\n element.oMatchesSelector ||\n element.webkitMatchesSelector\n );\n if (fn) {\n let match = false;\n selectors.every(sel => {\n if (fn.call(element, sel)) {\n match = true;\n return false;\n }\n return true;\n });\n return match;\n } else { // may be false e.g. when el is a textNode\n return false;\n }\n }\n\n /**\n * Returns all contexts filtered by duplicates (even nested)\n * @return {HTMLElement[]} - An array containing DOM contexts\n * @access protected\n */\n getContexts() {\n let ctx,\n filteredCtx = [];\n if (typeof this.ctx === 'undefined' || !this.ctx) { // e.g. null\n ctx = [];\n } else if (NodeList.prototype.isPrototypeOf(this.ctx)) {\n ctx = Array.prototype.slice.call(this.ctx);\n } else if (Array.isArray(this.ctx)) {\n ctx = this.ctx;\n } else if (typeof this.ctx === 'string') {\n ctx = Array.prototype.slice.call(\n document.querySelectorAll(this.ctx)\n );\n } else { // e.g. HTMLElement or element inside iframe\n ctx = [this.ctx];\n }\n // filter duplicate text nodes\n ctx.forEach(ctx => {\n const isDescendant = filteredCtx.filter(contexts => {\n return contexts.contains(ctx);\n }).length > 0;\n if (filteredCtx.indexOf(ctx) === -1 && !isDescendant) {\n filteredCtx.push(ctx);\n }\n });\n return filteredCtx;\n }\n\n /**\n * @callback DOMIterator~getIframeContentsSuccessCallback\n * @param {HTMLDocument} contents - The contentDocument of the iframe\n */\n /**\n * Calls the success callback function with the iframe document. If it can't\n * be accessed it calls the error callback function\n * @param {HTMLElement} ifr - The iframe DOM element\n * @param {DOMIterator~getIframeContentsSuccessCallback} successFn\n * @param {function} [errorFn]\n * @access protected\n */\n getIframeContents(ifr, successFn, errorFn = () => {}) {\n let doc;\n try {\n const ifrWin = ifr.contentWindow;\n doc = ifrWin.document;\n if (!ifrWin || !doc) { // no permission = null. Undefined in Phantom\n throw new Error('iframe inaccessible');\n }\n } catch (e) {\n errorFn();\n }\n if (doc) {\n successFn(doc);\n }\n }\n\n /Line truncated
"mappings": ";AAoBA,IAAqB,cAArB,MAAqB,aAAY;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAe/B,YAAY,KAAK,UAAU,MAAM,UAAU,CAAC,GAAG,iBAAiB,KAAM;AAOpE,SAAK,MAAM;AAMX,SAAK,UAAU;AAKf,SAAK,UAAU;AAKf,SAAK,iBAAiB;AAAA,EACxB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAUA,OAAO,QAAQ,SAAS,UAAU;AAChC,UAAM,YAAY,OAAO,aAAa,WAAW,CAAC,QAAQ,IAAI,UAC5D,KACE,QAAQ,WACR,QAAQ,mBACR,QAAQ,qBACR,QAAQ,sBACR,QAAQ,oBACR,QAAQ;AAEZ,QAAI,IAAI;AACN,UAAI,QAAQ;AACZ,gBAAU,MAAM,SAAO;AACrB,YAAI,GAAG,KAAK,SAAS,GAAG,GAAG;AACzB,kBAAQ;AACR,iBAAO;AAAA,QACT;AACA,eAAO;AAAA,MACT,CAAC;AACD,aAAO;AAAA,IACT,OAAO;AACL,aAAO;AAAA,IACT;AAAA,EACF;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOA,cAAc;AACZ,QAAI,KACF,cAAc,CAAC;AACjB,QAAI,OAAO,KAAK,QAAQ,eAAe,CAAC,KAAK,KAAK;AAChD,YAAM,CAAC;AAAA,IACT,WAAW,SAAS,UAAU,cAAc,KAAK,GAAG,GAAG;AACrD,YAAM,MAAM,UAAU,MAAM,KAAK,KAAK,GAAG;AAAA,IAC3C,WAAW,MAAM,QAAQ,KAAK,GAAG,GAAG;AAClC,YAAM,KAAK;AAAA,IACb,WAAW,OAAO,KAAK,Q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,MACF,OAAO;AACL,eAAO;AAAA,MACT;AAAA,IACF;AACA,WAAO;AAAA,EACT;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAeA,gBAAgB,KAAK;AACnB,UAAM,WAAW,IAAI,aAAa;AAClC,QAAI;AACJ,QAAI,aAAa,MAAM;AACrB,aAAO,IAAI,SAAS;AAAA,IACtB,OAAO;AACL,aAAO,IAAI,SAAS,KAAK,IAAI,SAAS;AAAA,IACxC;AACA,WAAO;AAAA,MACL;AAAA,MACA;AAAA,IACF;AAAA,EACF;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EA4BA,kBAAkB,MAAM,UAAU,SAAS,KAAK;AAC9C,QAAI,MAAM,OACR,UAAU;AACZ,QAAI,QAAQ,CAAC,SAAS,MAAM;AAC1B,UAAI,QAAQ,QAAQ,SAAS;AAC3B,cAAM;AACN,kBAAU,QAAQ;AAAA,MACpB;AAAA,IACF,CAAC;AACD,QAAI,KAAK,kBAAkB,MAAM,UAAU,OAAO,GAAG;AACnD,UAAI,QAAQ,SAAS,CAAC,SAAS;AAC7B,YAAI,KAAK;AAAA,UACP,KAAK;AAAA,UACL,SAAS;AAAA,QACX,CAAC;AAAA,MACH,WAAW,QAAQ,SAAS,CAAC,SAAS;AACpC,YAAI,GAAG,EAAE,UAAU;AAAA,MACrB;AACA,aAAO;AAAA,IACT;AACA,QAAI,QAAQ,OAAO;AACjB,UAAI,KAAK;AAAA,QACP,KLine truncated
"names": ["ctx", "ifr", "node", "dct", "Mark"]
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,7 @@
{
"version": 3,
"sources": ["../../../node_modules/.pnpm/minisearch@7.1.1/node_modules/minisearch/node_modules/tslib/tslib.es6.js", "../../../node_modules/.pnpm/minisearch@7.1.1/node_modules/minisearch/src/SearchableMap/TreeIterator.ts", "../../../node_modules/.pnpm/minisearch@7.1.1/node_modules/minisearch/src/SearchableMap/fuzzySearch.ts", "../../../node_modules/.pnpm/minisearch@7.1.1/node_modules/minisearch/src/SearchableMap/SearchableMap.ts", "../../../node_modules/.pnpm/minisearch@7.1.1/node_modules/minisearch/src/MiniSearch.ts"],
"sourcesContent": ["/******************************************************************************\r\nCopyright (c) Microsoft Corporation.\r\n\r\nPermission to use, copy, modify, and/or distribute this software for any\r\npurpose with or without fee is hereby granted.\r\n\r\nTHE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\r\nREGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY\r\nAND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\r\nINDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM\r\nLOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR\r\nOTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\r\nPERFORMANCE OF THIS SOFTWARE.\r\n***************************************************************************** */\r\n/* global Reflect, Promise, SuppressedError, Symbol */\r\n\r\nvar extendStatics = function(d, b) {\r\n extendStatics = Object.setPrototypeOf ||\r\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\r\n function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };\r\n return extendStatics(d, b);\r\n};\r\n\r\nexport function __extends(d, b) {\r\n if (typeof b !== \"function\" && b !== null)\r\n throw new TypeError(\"Class extends value \" + String(b) + \" is not a constructor or null\");\r\n extendStatics(d, b);\r\n function __() { this.constructor = d; }\r\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\r\n}\r\n\r\nexport var __assign = function() {\r\n __assign = Object.assign || function __assign(t) {\r\n for (var s, i = 1, n = arguments.length; i < n; i++) {\r\n s = arguments[i];\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];\r\n }\r\n return t;\r\n }\r\n return __assign.apply(this, arguments);\r\n}\r\n\r\nexport function __rest(s, e) {\r\n var t = {};\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\r\n t[p] = s[p];\r\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\r\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\r\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\r\n t[p[i]] = s[p[i]];\r\n }\r\n return t;\r\n}\r\n\r\nexport function __decorate(decorators, target, key, desc) {\r\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\r\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\r\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\r\n return c > 3 && r && Object.defineProperty(target, key, r), r;\r\n}\r\n\r\nexport function __param(paramIndex, decorator) {\r\n return function (target, key) { decorator(target, key, paramIndex); }\r\n}\r\n\r\nexport function __esDecorate(ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {\r\n function accept(f) { if (f !== void 0 && typeof f !== \"function\") throw new TypeError(\"Function expected\"); return f; }\r\n var kind = contextIn.kind, key = kind === \"getter\" ? \"get\" : kind === \"setter\" ? \"set\" : \"value\";\r\n var target = !descriptorIn && ctor ? contextIn[\"static\"] ? ctor : ctor.prototype : null;\r\n var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});\r\n var _, done = false;\r\n for (var i = decorators.length - 1; i >= 0; i--) {\r\n var context = {};\r\n for (var p in contextIn) context[p] = p === \"access\" ? {} : contextIn[p];\r\n for (var p in contextIn.access) context.access[p] = contextIn.access[p];\r\n context.addInitializer = function (f) { if (done) throw new TypeError(\"Cannot add initializers after decoration has completed\"); extraInitializers.push(accept(f || null)); };\r\n var result = (0, decorators[i])(kind === \"accessor\" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context);\r\n if (kind === \"accessor\") {\r\n if (result === void 0) continue;\r\n if (result === null || typeof result !== \"object\") throw new TypeError(\"Object expected\");\r\n if (_ = accept(result.get)) descriptor.get = _;\r\n if (_ = accept(result.set)) descriptor.set = _;\r\n if (_ = accept(result.init)) initializers.unshift(_);\r\n }\r\n else if (_ = accept(result)) {\r\n if (kind === \"field\") initializers.unshift(_);\r\n else descriptor[key] = _;\r\n }\r\n }\r\n iLine truncated
"mappings": ";AAkHO,SAAS,UAAU,SAAS,YAAY,GAAG,WAAW;AACzD,WAAS,MAAM,OAAO;AAAE,WAAO,iBAAiB,IAAI,QAAQ,IAAI,EAAE,SAAU,SAAS;AAAE,cAAQ,KAAK;IAAE,CAAE;EAAE;AAC1G,SAAO,KAAK,MAAM,IAAI,UAAU,SAAU,SAAS,QAAQ;AACvD,aAAS,UAAU,OAAO;AAAE,UAAI;AAAE,aAAK,UAAU,KAAK,KAAK,CAAC;MAAE,SAAU,GAAG;AAAE,eAAO,CAAC;MAAE;IAAE;AACzF,aAAS,SAAS,OAAO;AAAE,UAAI;AAAE,aAAK,UAAU,OAAO,EAAE,KAAK,CAAC;MAAE,SAAU,GAAG;AAAE,eAAO,CAAC;MAAE;IAAE;AAC5F,aAAS,KAAK,QAAQ;AAAE,aAAO,OAAO,QAAQ,OAAO,KAAK,IAAI,MAAM,OAAO,KAAK,EAAE,KAAK,WAAW,QAAQ;IAAE;AAC5G,UAAM,YAAY,UAAU,MAAM,SAAS,cAAc,CAAA,CAAE,GAAG,KAAI,CAAE;EAC5E,CAAK;AACL;ACvHA,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AAO,QAAQ,UAAU;AAAE,YAAM,IAAI,MAAM,sBAAsB;;AACrE,SAAK,QAAQ;AACb,UAAM,OAAO,WAAW,KAAK,OAAO,GAAG;AACvC,SAAK,IAAI,MAAM,GAAG,KAAK,IAAI,IAAI,CAAC,CAAC;AACjC,WAAO;;;;;;;;;;;;;;;;;;EAmBT,MAAO,KAAa,SAAgB;AAClC,QAAI,OAAO,QAAQ,UAAU;AAAE,YAAM,IAAI,MAAM,sBAAsB;;AACrE,SAAK,QAAQ;Line truncated
"names": ["last", "node", "child", "key", "chunk", "promise", "conditions", "options", "results", "query", "boosts", "data"]
}
+343
View File
@@ -0,0 +1,343 @@
import {
BaseTransition,
BaseTransitionPropsValidators,
Comment,
DeprecationTypes,
EffectScope,
ErrorCodes,
ErrorTypeStrings,
Fragment,
KeepAlive,
ReactiveEffect,
Static,
Suspense,
Teleport,
Text,
TrackOpTypes,
Transition,
TransitionGroup,
TriggerOpTypes,
VueElement,
assertNumber,
callWithAsyncErrorHandling,
callWithErrorHandling,
camelize,
capitalize,
cloneVNode,
compatUtils,
compile,
computed,
createApp,
createBaseVNode,
createBlock,
createCommentVNode,
createElementBlock,
createHydrationRenderer,
createPropsRestProxy,
createRenderer,
createSSRApp,
createSlots,
createStaticVNode,
createTextVNode,
createVNode,
customRef,
defineAsyncComponent,
defineComponent,
defineCustomElement,
defineEmits,
defineExpose,
defineModel,
defineOptions,
defineProps,
defineSSRCustomElement,
defineSlots,
devtools,
effect,
effectScope,
getCurrentInstance,
getCurrentScope,
getCurrentWatcher,
getTransitionRawChildren,
guardReactiveProps,
h,
handleError,
hasInjectionContext,
hydrate,
hydrateOnIdle,
hydrateOnInteraction,
hydrateOnMediaQuery,
hydrateOnVisible,
initCustomFormatter,
initDirectivesForSSR,
inject,
isMemoSame,
isProxy,
isReactive,
isReadonly,
isRef,
isRuntimeOnly,
isShallow,
isVNode,
markRaw,
mergeDefaults,
mergeModels,
mergeProps,
nextTick,
normalizeClass,
normalizeProps,
normalizeStyle,
onActivated,
onBeforeMount,
onBeforeUnmount,
onBeforeUpdate,
onDeactivated,
onErrorCaptured,
onMounted,
onRenderTracked,
onRenderTriggered,
onScopeDispose,
onServerPrefetch,
onUnmounted,
onUpdated,
onWatcherCleanup,
openBlock,
popScopeId,
provide,
proxyRefs,
pushScopeId,
queuePostFlushCb,
reactive,
readonly,
ref,
registerRuntimeCompiler,
render,
renderList,
renderSlot,
resolveComponent,
resolveDirective,
resolveDynamicComponent,
resolveFilter,
resolveTransitionHooks,
setBlockTracking,
setDevtoolsHook,
setTransitionHooks,
shallowReactive,
shallowReadonly,
shallowRef,
ssrContextKey,
ssrUtils,
stop,
toDisplayString,
toHandlerKey,
toHandlers,
toRaw,
toRef,
toRefs,
toValue,
transformVNodeArgs,
triggerRef,
unref,
useAttrs,
useCssModule,
useCssVars,
useHost,
useId,
useModel,
useSSRContext,
useShadowRoot,
useSlots,
useTemplateRef,
useTransitionState,
vModelCheckbox,
vModelDynamic,
vModelRadio,
vModelSelect,
vModelText,
vShow,
version,
warn,
watch,
watchEffect,
watchPostEffect,
watchSyncEffect,
withAsyncContext,
withCtx,
withDefaults,
withDirectives,
withKeys,
withMemo,
withModifiers,
withScopeId
} from "./chunk-CQOUZRMK.js";
export {
BaseTransition,
BaseTransitionPropsValidators,
Comment,
DeprecationTypes,
EffectScope,
ErrorCodes,
ErrorTypeStrings,
Fragment,
KeepAlive,
ReactiveEffect,
Static,
Suspense,
Teleport,
Text,
TrackOpTypes,
Transition,
TransitionGroup,
TriggerOpTypes,
VueElement,
assertNumber,
callWithAsyncErrorHandling,
callWithErrorHandling,
camelize,
capitalize,
cloneVNode,
compatUtils,
compile,
computed,
createApp,
createBlock,
createCommentVNode,
createElementBlock,
createBaseVNode as createElementVNode,
createHydrationRenderer,
createPropsRestProxy,
createRenderer,
createSSRApp,
createSlots,
createStaticVNode,
createTextVNode,
createVNode,
customRef,
defineAsyncComponent,
defineComponent,
defineCustomElement,
defineEmits,
defineExpose,
defineModel,
defineOptions,
defineProps,
defineSSRCustomElement,
defineSlots,
devtools,
effect,
effectScope,
getCurrentInstance,
getCurrentScope,
getCurrentWatcher,
getTransitionRawChildren,
guardReactiveProps,
h,
handleError,
hasInjectionContext,
hydrate,
hydrateOnIdle,
hydrateOnInteraction,
hydrateOnMediaQuery,
hydrateOnVisible,
initCustomFormatter,
initDirectivesForSSR,
inject,
isMemoSame,
isProxy,
isReactive,
isReadonly,
isRef,
isRuntimeOnly,
isShallow,
isVNode,
markRaw,
mergeDefaults,
mergeModels,
mergeProps,
nextTick,
normalizeClass,
normalizeProps,
normalizeStyle,
onActivated,
onBeforeMount,
onBeforeUnmount,
onBeforeUpdate,
onDeactivated,
onErrorCaptured,
onMounted,
onRenderTracked,
onRenderTriggered,
onScopeDispose,
onServerPrefetch,
onUnmounted,
onUpdated,
onWatcherCleanup,
openBlock,
popScopeId,
provide,
proxyRefs,
pushScopeId,
queuePostFlushCb,
reactive,
readonly,
ref,
registerRuntimeCompiler,
render,
renderList,
renderSlot,
resolveComponent,
resolveDirective,
resolveDynamicComponent,
resolveFilter,
resolveTransitionHooks,
setBlockTracking,
setDevtoolsHook,
setTransitionHooks,
shallowReactive,
shallowReadonly,
shallowRef,
ssrContextKey,
ssrUtils,
stop,
toDisplayString,
toHandlerKey,
toHandlers,
toRaw,
toRef,
toRefs,
toValue,
transformVNodeArgs,
triggerRef,
unref,
useAttrs,
useCssModule,
useCssVars,
useHost,
useId,
useModel,
useSSRContext,
useShadowRoot,
useSlots,
useTemplateRef,
useTransitionState,
vModelCheckbox,
vModelDynamic,
vModelRadio,
vModelSelect,
vModelText,
vShow,
version,
warn,
watch,
watchEffect,
watchPostEffect,
watchSyncEffect,
withAsyncContext,
withCtx,
withDefaults,
withDirectives,
withKeys,
withMemo,
withModifiers,
withScopeId
};
//# sourceMappingURL=vue.js.map
+7
View File
@@ -0,0 +1,7 @@
{
"version": 3,
"sources": [],
"sourcesContent": [],
"mappings": "",
"names": []
}
+17 -87
View File
@@ -3,17 +3,9 @@ import { defineConfig } from 'vitepress'
// https://vitepress.dev/reference/site-config
export default defineConfig({
title: 'FileCodeBox',
description: 'FileCodeBox 自托管文件与文本分享服务文档',
description: '简单高效的文件分享工具',
lang: 'zh-CN',
lastUpdated: true,
cleanUrls: true,
sitemap: {
hostname: 'https://fcb-docs.aiuo.net',
},
head: [
['meta', { name: 'theme-color', content: '#111111' }],
['link', { rel: 'icon', href: '/logo_small.png' }],
],
locales: {
root: {
label: '简体中文',
@@ -24,24 +16,15 @@ export default defineConfig({
logo: '/logo_small.png',
nav: [
{ text: '首页', link: '/' },
{
text: '使用指南',
items: [
{ text: '快速开始', link: '/guide/getting-started' },
{ text: '上传与分享', link: '/guide/upload' },
{ text: '管理面板', link: '/guide/management' },
{ text: '存储配置', link: '/guide/storage' },
],
},
{ text: '指南', link: '/guide/getting-started' },
{ text: 'API', link: '/api/' },
{ text: '优秀案例', link: '/showcase' },
{ text: 'Demo', link: 'https://share.lanol.cn' },
{
text: '资源',
text: '了解更多',
items: [
{ text: '在线体验', link: 'https://share.lanol.cn' },
{ text: '部署案例', link: '/showcase' },
{ text: '更新日志', link: '/changelog' },
{ text: '贡献指南', link: '/contributing' },
{ text: 'GitHub', link: 'https://github.com/vastsa/FileCodeBox' },
],
},
],
@@ -49,7 +32,7 @@ export default defineConfig({
sidebar: {
'/guide/': [
{
text: '开始',
text: '介绍',
items: [
{
text: '什么是 FileCodeBox',
@@ -59,7 +42,7 @@ export default defineConfig({
],
},
{
text: '使用',
text: '基础功能',
items: [
{ text: '文件上传', link: '/guide/upload' },
{ text: '文件分享', link: '/guide/share' },
@@ -67,12 +50,11 @@ export default defineConfig({
],
},
{
text: '运维',
text: '高级特性',
items: [
{ text: '存储配置', link: '/guide/storage' },
{ text: '安全设置', link: '/guide/security' },
{ text: '系统配置', link: '/guide/configuration' },
{ text: '版本发布', link: '/guide/releasing' },
],
},
],
@@ -80,8 +62,6 @@ export default defineConfig({
{
text: 'API 参考',
items: [
{ text: 'API 概览', link: '/api/' },
{ text: '预签名上传', link: '/api/presign-upload' },
{ text: '分享接口', link: '/api/#分享接口' },
{ text: '管理接口', link: '/api/#管理接口' },
{ text: '错误响应', link: '/api/#错误响应' },
@@ -102,28 +82,9 @@ export default defineConfig({
{ icon: 'github', link: 'https://github.com/vastsa/FileCodeBox' },
],
footer: {
message: '基于 LGPL-3.0 许可证发布',
message: '基于 LGPL-3.0 license 发布',
copyright: 'Copyright © 2022-present FileCodeBox',
},
editLink: {
pattern: 'https://github.com/vastsa/FileCodeBox/edit/master/docs/:path',
text: '在 GitHub 上编辑此页',
},
docFooter: {
prev: '上一篇',
next: '下一篇',
},
lastUpdated: {
text: '最后更新',
},
returnToTopLabel: '返回顶部',
skipToContentLabel: '跳转到正文',
navMenuLabel: '导航菜单',
langMenuLabel: '切换语言',
sidebarMenuLabel: '文档目录',
darkModeSwitchLabel: '外观',
lightModeSwitchTitle: '切换到浅色模式',
darkModeSwitchTitle: '切换到深色模式',
search: {
provider: 'local',
},
@@ -142,24 +103,15 @@ export default defineConfig({
logo: '/logo_small.png',
nav: [
{ text: 'Home', link: '/en/' },
{
text: 'Guides',
items: [
{ text: 'Getting Started', link: '/en/guide/getting-started' },
{ text: 'Upload & Share', link: '/en/guide/upload' },
{ text: 'Admin Panel', link: '/en/guide/management' },
{ text: 'Storage', link: '/en/guide/storage' },
],
},
{ text: 'Guide', link: '/en/guide/getting-started' },
{ text: 'API', link: '/en/api/' },
{ text: 'Showcase', link: '/en/showcase' },
{ text: 'Demo', link: 'https://share.lanol.cn' },
{
text: 'Resources',
text: 'More',
items: [
{ text: 'Live Demo', link: 'https://share.lanol.cn' },
{ text: 'Showcase', link: '/en/showcase' },
{ text: 'Changelog', link: '/en/changelog' },
{ text: 'Contributing', link: '/en/contributing' },
{ text: 'GitHub', link: 'https://github.com/vastsa/FileCodeBox' },
],
},
],
@@ -167,7 +119,7 @@ export default defineConfig({
sidebar: {
'/en/guide/': [
{
text: 'Start',
text: 'Introduction',
items: [
{
text: 'What is FileCodeBox',
@@ -180,7 +132,7 @@ export default defineConfig({
],
},
{
text: 'Use',
text: 'Basic Features',
items: [
{ text: 'File Upload', link: '/en/guide/upload' },
{ text: 'File Sharing', link: '/en/guide/share' },
@@ -188,7 +140,7 @@ export default defineConfig({
],
},
{
text: 'Operate',
text: 'Advanced Features',
items: [
{ text: 'Storage Configuration', link: '/en/guide/storage' },
{ text: 'Security Settings', link: '/en/guide/security' },
@@ -196,7 +148,6 @@ export default defineConfig({
text: 'System Configuration',
link: '/en/guide/configuration',
},
{ text: 'Releasing', link: '/en/guide/releasing' },
],
},
],
@@ -204,7 +155,6 @@ export default defineConfig({
{
text: 'API Reference',
items: [
{ text: 'API Overview', link: '/en/api/' },
{ text: 'Share API', link: '/en/api/#share-api' },
{ text: 'Admin API', link: '/en/api/#admin-api' },
{ text: 'Error Response', link: '/en/api/#error-response' },
@@ -228,31 +178,12 @@ export default defineConfig({
message: 'Released under the LGPL-3.0 license',
copyright: 'Copyright © 2022-present FileCodeBox',
},
editLink: {
pattern: 'https://github.com/vastsa/FileCodeBox/edit/master/docs/:path',
text: 'Edit this page on GitHub',
},
docFooter: {
prev: 'Previous',
next: 'Next',
},
lastUpdated: {
text: 'Last updated',
},
returnToTopLabel: 'Return to top',
skipToContentLabel: 'Skip to content',
navMenuLabel: 'Navigation',
langMenuLabel: 'Change language',
sidebarMenuLabel: 'Documentation',
darkModeSwitchLabel: 'Appearance',
lightModeSwitchTitle: 'Switch to light theme',
darkModeSwitchTitle: 'Switch to dark theme',
search: {
provider: 'local',
},
outline: {
level: [2, 3],
label: 'On this page',
label: '目录',
},
},
},
@@ -318,6 +249,5 @@ export default defineConfig({
level: [2, 3],
label: '目录',
},
externalLinkIcon: true,
},
})
+441 -285
View File
@@ -1,317 +1,473 @@
:root {
--vp-c-brand-1: #6d5dfc;
--vp-c-brand-2: #5848e8;
--vp-c-brand-3: #4938ce;
--vp-c-brand-soft: rgba(109, 93, 252, 0.12);
--vp-c-bg: #ffffff;
--vp-c-bg-alt: #f7f7f8;
--vp-c-bg-soft: #f2f2f3;
--vp-c-divider: #e8e8eb;
--vp-c-gutter: #eeeeef;
--vp-c-text-1: #18181b;
--vp-c-text-2: #52525b;
--vp-c-text-3: #71717a;
--vp-button-brand-bg: #18181b;
--vp-button-brand-hover-bg: #2f2f33;
--vp-button-brand-active-bg: #09090b;
--vp-button-brand-text: #ffffff;
--vp-home-hero-name-color: transparent;
--vp-home-hero-name-background: linear-gradient(120deg, #18181b 15%, #6d5dfc 85%);
--vp-home-hero-image-background-image: radial-gradient(circle, rgba(109, 93, 252, 0.24), transparent 66%);
--vp-home-hero-image-filter: blur(48px);
--vp-font-family-base: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", "Noto Sans SC", sans-serif;
--vp-font-family-mono: "SFMono-Regular", Consolas, "Liberation Mono", monospace;
}
.dark {
--vp-c-brand-1: #a99fff;
--vp-c-brand-2: #8d80ff;
--vp-c-brand-3: #7565ff;
--vp-c-brand-soft: rgba(169, 159, 255, 0.14);
--vp-c-bg: #0b0b0d;
--vp-c-bg-alt: #111114;
--vp-c-bg-soft: #18181c;
--vp-c-divider: #27272c;
--vp-c-gutter: #18181c;
--vp-c-text-1: #fafafa;
--vp-c-text-2: #c4c4ca;
--vp-c-text-3: #92929b;
--vp-button-brand-bg: #f4f4f5;
--vp-button-brand-hover-bg: #ffffff;
--vp-button-brand-active-bg: #e4e4e7;
--vp-button-brand-text: #18181b;
--vp-home-hero-name-background: linear-gradient(120deg, #ffffff 12%, #a99fff 88%);
}
:root {
/* --- 核心色板:清晨薄雾 (Teal -> Sky) --- */
--vp-c-brand-1: #14b8a6; /* Teal 500 */
--vp-c-brand-2: #0ea5e9; /* Sky 500 */
--vp-c-brand-3: #0f766e; /* Teal 700 */
--vp-c-brand-soft: rgba(20, 184, 166, 0.14);
html {
scroll-behavior: smooth;
}
/* --- 背景色:极简与通透 --- */
--vp-c-bg: #ffffff;
--vp-c-bg-alt: #f8fafc; /* Slate 50 */
--vp-c-bg-elv: #ffffff;
/* --- 文字颜色:柔和的深灰,而非纯黑 --- */
--vp-c-text-1: #334155; /* Slate 700 */
--vp-c-text-2: #64748b; /* Slate 500 */
--vp-c-text-3: #94a3b8; /* Slate 400 */
body {
letter-spacing: -0.01em;
}
/* --- 边框与分隔 --- */
--vp-c-border: #e2e8f0;
--vp-c-divider: #f1f5f9;
.VPNavBar {
border-bottom: 1px solid color-mix(in srgb, var(--vp-c-divider) 76%, transparent);
background: color-mix(in srgb, var(--vp-c-bg) 86%, transparent) !important;
backdrop-filter: blur(18px) saturate(160%);
}
/* --- 阴影:扩散柔光 --- */
--vp-shadow-1: 0 4px 6px -1px rgba(0, 0, 0, 0.05), 0 2px 4px -1px rgba(0, 0, 0, 0.03);
--vp-shadow-2: 0 10px 15px -3px rgba(0, 0, 0, 0.05), 0 4px 6px -2px rgba(0, 0, 0, 0.025);
--vp-shadow-brand: 0 4px 14px 0 rgba(20, 184, 166, 0.3);
.VPNavBarTitle .logo {
width: 28px;
height: 28px;
}
/* --- 布局参数 --- */
--vp-nav-height: 64px;
--vp-sidebar-width: 280px;
--vp-radius-default: 12px;
--vp-radius-small: 6px;
}
.VPNavBarTitle .title {
font-weight: 750;
letter-spacing: -0.03em;
}
/* * ==========================================
* 暗黑模式重构 (Deep Ocean Theme)
* ==========================================
*/
.dark {
/* 背景:更深邃的蓝黑色,更有沉浸感 */
--vp-c-bg: #020617; /* Slate 950 */
--vp-c-bg-alt: #0f172a; /* Slate 900 */
--vp-c-bg-elv: #1e293b; /* Slate 800 */
/* 文字:降低纯白刺眼感,提高舒适度 */
--vp-c-text-1: #f8fafc; /* Slate 50 */
--vp-c-text-2: #94a3b8; /* Slate 400 */
--vp-c-text-3: #64748b; /* Slate 500 */
.VPNavBarMenuLink,
.VPNavBarMenuGroup .text {
font-size: 14px;
font-weight: 550;
}
/* 边框:更细腻的深色线条 */
--vp-c-border: #1e293b;
--vp-c-divider: #0f172a;
.VPSidebar {
border-right: 1px solid var(--vp-c-divider);
background: color-mix(in srgb, var(--vp-c-bg) 96%, var(--vp-c-bg-alt));
}
/* 品牌色:调亮,产生荧光感 */
--vp-c-brand-1: #2dd4bf; /* Teal 400 */
--vp-c-brand-2: #38bdf8; /* Sky 400 */
--vp-c-brand-3: #14b8a6; /* Teal 500 */
--vp-c-brand-soft: rgba(45, 212, 191, 0.15); /* 淡淡的荧光底色 */
.VPSidebarItem.level-0 > .item > .text {
font-size: 12px;
font-weight: 700;
letter-spacing: 0.08em;
text-transform: uppercase;
color: var(--vp-c-text-3);
}
/* 阴影:暗色环境下的微光 */
--vp-shadow-1: 0 4px 6px -1px rgba(0, 0, 0, 0.5);
--vp-shadow-2: 0 10px 15px -3px rgba(0, 0, 0, 0.5);
--vp-shadow-brand: 0 0 20px rgba(45, 212, 191, 0.3); /* 品牌色发光 */
}
.VPSidebarItem.level-1 .link {
margin: 2px 0;
padding: 5px 10px;
border-radius: 8px;
transition: color 0.18s ease, background-color 0.18s ease;
}
/* 全局基础设置 */
body {
font-family: 'Noto Sans SC', sans-serif;
background-color: var(--vp-c-bg-alt);
color: var(--vp-c-text-1);
margin: 0;
transition: background-color 0.3s, color 0.3s;
overflow-x: hidden;
}
.VPSidebarItem.level-1 .link:hover,
.VPSidebarItem.level-1.is-active > .item .link {
background: var(--vp-c-brand-soft);
}
a { text-decoration: none; color: inherit; transition: color 0.2s; }
.vp-doc {
font-size: 16px;
}
/* -------------------------------------------
布局结构 (模拟 VitePress 布局)
------------------------------------------- */
.app-container {
display: flex;
flex-direction: column;
min-height: 100vh;
}
.vp-doc h1 {
margin-bottom: 18px;
font-size: clamp(32px, 5vw, 44px);
line-height: 1.12;
letter-spacing: -0.045em;
}
/* 1. 导航栏:毛玻璃 + 悬浮感 */
.VPNavBar {
position: fixed;
top: 0;
left: 0;
right: 0;
height: var(--vp-nav-height);
background-color: rgba(255, 255, 255, 0.85); /* 稍微增加不透明度 */
backdrop-filter: blur(20px) saturate(180%);
-webkit-backdrop-filter: blur(20px) saturate(180%);
border-bottom: 1px solid rgba(226, 232, 240, 0.6);
z-index: 50;
display: flex;
align-items: center;
padding: 0 24px;
justify-content: space-between;
}
.dark .VPNavBar {
background-color: rgba(2, 6, 23, 0.85); /* 深色背景半透 */
border-bottom: 1px solid rgba(30, 41, 59, 0.7);
}
.vp-doc h2 {
margin-top: 48px;
padding-top: 12px;
border-top: 1px solid var(--vp-c-divider);
letter-spacing: -0.025em;
}
.nav-logo {
font-weight: 700;
font-size: 1.2rem;
background: linear-gradient(120deg, var(--vp-c-brand-1), var(--vp-c-brand-2));
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
display: flex;
align-items: center;
gap: 8px;
}
.vp-doc h3 {
letter-spacing: -0.02em;
}
.nav-links {
display: flex;
gap: 24px;
font-size: 0.9rem;
font-weight: 500;
color: var(--vp-c-text-2);
}
.vp-doc p,
.vp-doc li {
line-height: 1.8;
}
.nav-link:hover {
color: var(--vp-c-brand-1);
}
.nav-link.active {
color: var(--vp-c-brand-1);
position: relative;
}
.nav-link.active::after {
content: '';
position: absolute;
bottom: -22px;
left: 0;
width: 100%;
height: 2px;
background: var(--vp-c-brand-1);
border-radius: 2px 2px 0 0;
box-shadow: 0 -2px 10px var(--vp-c-brand-1); /* 激活状态发光 */
}
.vp-doc a {
text-underline-offset: 3px;
}
/* 2. 侧边栏:极简卡片式 */
.VPSidebar {
position: fixed;
top: var(--vp-nav-height);
left: 0;
bottom: 0;
width: var(--vp-sidebar-width);
background-color: var(--vp-c-bg); /* 实色背景 */
border-right: 1px solid var(--vp-c-border);
padding: 32px 24px;
overflow-y: auto;
transform: translateX(0);
transition: transform 0.3s ease;
z-index: 40;
}
.dark .VPSidebar {
background-color: var(--vp-c-bg-alt); /* 侧边栏比内容区稍微亮一点点/或者暗一点 */
}
@media (max-width: 960px) {
.VPSidebar { transform: translateX(-100%); }
.VPSidebar.open { transform: translateX(0); }
}
.vp-doc div[class*="language-"] {
margin: 22px 0;
border: 1px solid var(--vp-c-divider);
border-radius: 14px;
box-shadow: 0 14px 36px rgba(24, 24, 27, 0.06);
}
.sidebar-group-title {
font-weight: 700;
color: var(--vp-c-text-1);
margin-bottom: 12px;
margin-top: 24px;
font-size: 1rem;
}
.sidebar-group-title:first-child { margin-top: 0; }
.dark .vp-doc div[class*="language-"] {
box-shadow: 0 14px 38px rgba(0, 0, 0, 0.24);
}
.sidebar-link {
display: block;
padding: 8px 12px;
margin: 4px 0;
border-radius: var(--vp-radius-small);
color: var(--vp-c-text-2);
font-size: 0.95rem;
transition: all 0.2s;
}
.vp-doc table {
display: table;
width: 100%;
font-size: 14px;
}
.sidebar-link:hover {
background-color: var(--vp-c-bg-alt);
color: var(--vp-c-brand-1);
}
.dark .sidebar-link:hover {
background-color: var(--vp-c-bg-elv);
}
.vp-doc th {
background: var(--vp-c-bg-soft);
}
.sidebar-link.active {
background-color: var(--vp-c-brand-soft);
color: var(--vp-c-brand-3);
font-weight: 600;
}
.dark .sidebar-link.active {
color: var(--vp-c-brand-1);
background-color: rgba(45, 212, 191, 0.1); /* 暗色模式下更通透 */
box-shadow: inset 2px 0 0 0 var(--vp-c-brand-1); /* 左侧高亮条 */
}
.custom-block {
border-radius: 12px;
}
/* 3. 主内容区:居中与留白 */
.VPContent {
margin-top: var(--vp-nav-height);
margin-left: var(--vp-sidebar-width);
padding: 48px 64px;
min-height: calc(100vh - var(--vp-nav-height));
background-color: var(--vp-c-bg);
transition: margin-left 0.3s ease;
}
@media (max-width: 960px) {
.VPContent { margin-left: 0; padding: 32px 24px; }
}
.VPHome {
padding-bottom: 72px !important;
}
/* 内容排版 (Typography) */
.vp-doc h1 {
font-size: 2.5rem;
font-weight: 800;
margin-bottom: 1.5rem;
line-height: 1.2;
background: linear-gradient(120deg, var(--vp-c-brand-1), var(--vp-c-brand-2));
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
display: inline-block;
/* 暗色模式下加一点文字阴影增强可读性 */
filter: drop-shadow(0 0 2em rgba(20, 184, 166, 0.2));
}
.dark .vp-doc h1 {
filter: drop-shadow(0 0 25px rgba(45, 212, 191, 0.2));
}
.VPHero {
padding-top: 80px !important;
}
.vp-doc h2 {
font-size: 1.8rem;
margin-top: 3rem;
margin-bottom: 1rem;
padding-bottom: 0.5rem;
border-bottom: 1px solid var(--vp-c-border);
color: var(--vp-c-text-1);
}
.vp-doc h3 {
font-size: 1.4rem;
margin-top: 2rem;
margin-bottom: 0.8rem;
color: var(--vp-c-text-1);
}
.VPHero .name,
.VPHero .text {
letter-spacing: -0.055em;
}
.vp-doc p {
line-height: 1.8;
margin-bottom: 1.2rem;
color: var(--vp-c-text-2);
font-size: 1.05rem;
}
.VPHero .tagline {
max-width: 620px;
line-height: 1.65;
}
/* 代码块美化 */
.vp-doc pre {
background-color: #1e293b; /* Dark Slate */
border-radius: var(--vp-radius-default);
padding: 20px;
overflow-x: auto;
color: #f8fafc;
margin: 24px 0;
border: 1px solid rgba(0,0,0,0.1);
box-shadow: var(--vp-shadow-1);
}
.dark .vp-doc pre {
background-color: #0f172a; /* 更深一层的背景 */
border: 1px solid #1e293b;
}
.vp-doc code {
font-family: 'Menlo', 'Monaco', 'Courier New', monospace;
font-size: 0.9em;
}
.vp-doc p code {
background-color: var(--vp-c-brand-soft);
color: var(--vp-c-brand-3);
padding: 2px 6px;
border-radius: 4px;
font-size: 0.9em;
}
.dark .vp-doc p code {
color: var(--vp-c-brand-1);
background-color: rgba(45, 212, 191, 0.1);
}
.VPHero .image-bg {
opacity: 0.7;
}
/* 引用块 (Blockquote) */
.vp-doc blockquote {
margin: 1.5rem 0;
padding: 16px 24px;
background-color: var(--vp-c-bg-alt);
border-left: 4px solid var(--vp-c-brand-1);
border-radius: 0 var(--vp-radius-default) var(--vp-radius-default) 0;
color: var(--vp-c-text-2);
}
.dark .vp-doc blockquote {
background-color: rgba(30, 41, 59, 0.5);
}
.VPHero .image-src {
max-width: 250px;
max-height: 250px;
}
/* 按钮与卡片 (Features) */
.vp-button {
display: inline-block;
padding: 0 24px;
height: 48px;
line-height: 48px;
border-radius: 24px; /* Pill shape */
font-weight: 600;
font-size: 1rem;
transition: all 0.3s cubic-bezier(0.25, 0.8, 0.25, 1);
cursor: pointer;
border: none;
}
.VPButton {
border-radius: 10px !important;
font-weight: 650 !important;
}
.vp-button.brand {
background: linear-gradient(135deg, var(--vp-c-brand-1), var(--vp-c-brand-2));
color: white;
box-shadow: var(--vp-shadow-brand);
}
.dark .vp-button.brand {
color: #020617; /* 暗色模式下按钮文字用深色,因为背景亮 */
}
.VPFeature {
border: 1px solid var(--vp-c-divider) !important;
border-radius: 16px !important;
background: color-mix(in srgb, var(--vp-c-bg) 94%, var(--vp-c-bg-soft)) !important;
transition: transform 0.2s ease, border-color 0.2s ease, box-shadow 0.2s ease;
}
.vp-button.brand:hover {
transform: translateY(-2px);
box-shadow: 0 8px 25px -4px rgba(20, 184, 166, 0.5);
}
.dark .vp-button.brand:hover {
box-shadow: 0 0 30px -4px rgba(45, 212, 191, 0.6); /* 发光增强 */
}
.VPFeature:hover {
transform: translateY(-3px);
border-color: var(--vp-c-brand-1) !important;
box-shadow: 0 18px 42px rgba(24, 24, 27, 0.08);
}
.vp-button.alt {
background-color: var(--vp-c-bg-alt);
color: var(--vp-c-text-1);
border: 1px solid var(--vp-c-border);
}
.dark .vp-button.alt {
background-color: transparent;
border-color: var(--vp-c-text-2);
color: var(--vp-c-text-1);
}
.vp-button.alt:hover {
border-color: var(--vp-c-brand-1);
color: var(--vp-c-brand-1);
}
.VPFeature .icon {
display: inline-flex;
align-items: center;
justify-content: center;
width: 38px;
height: 38px;
border-radius: 10px;
background: var(--vp-c-brand-soft);
color: var(--vp-c-brand-1);
font-family: var(--vp-font-family-mono);
font-size: 12px;
font-weight: 700;
}
.VPFeature .title {
letter-spacing: -0.02em;
}
.VPHome .vp-doc {
max-width: 1152px;
margin: 36px auto 0;
padding: 0 24px;
}
.doc-paths {
display: grid;
grid-template-columns: repeat(3, minmax(0, 1fr));
gap: 14px;
margin: 28px 0 34px;
}
.doc-path {
display: flex;
min-height: 154px;
flex-direction: column;
padding: 20px;
border: 1px solid var(--vp-c-divider);
border-radius: 14px;
background: var(--vp-c-bg);
color: var(--vp-c-text-1) !important;
text-decoration: none !important;
transition: transform 0.2s ease, border-color 0.2s ease, box-shadow 0.2s ease;
}
.doc-path:hover {
transform: translateY(-3px);
border-color: var(--vp-c-brand-1);
box-shadow: 0 16px 36px rgba(24, 24, 27, 0.08);
}
.doc-path:focus-visible {
outline: 3px solid var(--vp-c-brand-soft);
outline-offset: 3px;
border-color: var(--vp-c-brand-1);
}
.doc-path span {
margin-bottom: 16px;
color: var(--vp-c-brand-1);
font-size: 12px;
font-weight: 700;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.doc-path strong {
margin-bottom: 8px;
font-size: 17px;
letter-spacing: -0.02em;
}
.doc-path small {
margin-top: auto;
color: var(--vp-c-text-2);
line-height: 1.55;
}
@media (max-width: 767px) {
.VPHero {
padding-top: 42px !important;
}
.VPHero .image-src {
max-width: 180px;
max-height: 180px;
}
.VPHome .vp-doc {
margin-top: 20px;
padding: 0 20px;
}
.doc-paths {
grid-template-columns: 1fr;
}
.doc-path {
min-height: 132px;
}
.vp-doc table {
display: block;
}
}
@media (prefers-reduced-motion: reduce) {
html {
scroll-behavior: auto;
}
*,
*::before,
*::after {
transition-duration: 0.01ms !important;
}
}
/* 工具类 */
.theme-toggle {
background: none;
border: none;
cursor: pointer;
font-size: 1.5rem;
color: var(--vp-c-text-2);
display: flex;
align-items: center;
justify-content: center;
padding: 8px;
border-radius: 50%;
transition: background 0.2s;
}
.theme-toggle:hover {
background-color: var(--vp-c-bg-alt);
color: var(--vp-c-brand-1);
}
.dark .theme-toggle:hover {
background-color: var(--vp-c-bg-elv);
}
.mobile-menu-btn {
display: none;
background: none;
border: none;
font-size: 1.5rem;
color: var(--vp-c-text-1);
cursor: pointer;
}
@media (max-width: 960px) {
.mobile-menu-btn { display: block; }
.nav-links { display: none; }
}
/* 首页 Hero 样式模拟 */
.hero-section {
text-align: center;
padding: 80px 20px;
max-width: 800px;
margin: 0 auto;
}
.hero-title {
font-size: 3.5rem;
font-weight: 900;
line-height: 1.1;
margin-bottom: 24px;
}
.hero-title span {
background: linear-gradient(120deg, var(--vp-c-brand-1), var(--vp-c-brand-2));
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
}
.hero-desc {
font-size: 1.5rem;
color: var(--vp-c-text-2);
margin-bottom: 40px;
}
.hero-actions {
display: flex;
gap: 16px;
justify-content: center;
}
/* Features Grid */
.features-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
gap: 24px;
margin-top: 64px;
}
.feature-card {
background-color: var(--vp-c-bg-alt);
padding: 24px;
border-radius: var(--vp-radius-default);
transition: transform 0.3s, box-shadow 0.3s;
border: 1px solid transparent;
}
.dark .feature-card {
background-color: rgba(30, 41, 59, 0.3); /* 微微透明 */
border: 1px solid rgba(255,255,255,0.05);
}
.feature-card:hover {
background-color: var(--vp-c-bg);
transform: translateY(-4px);
box-shadow: var(--vp-shadow-2);
border-color: var(--vp-c-brand-soft);
}
.dark .feature-card:hover {
background-color: var(--vp-c-bg-elv);
border-color: var(--vp-c-brand-1);
box-shadow: 0 0 15px rgba(45, 212, 191, 0.1);
}
.feature-icon {
font-size: 2rem;
margin-bottom: 16px;
color: var(--vp-c-brand-1);
background-color: var(--vp-c-brand-soft);
width: 48px;
height: 48px;
display: flex;
align-items: center;
justify-content: center;
border-radius: 12px;
}
.feature-title {
font-weight: 700;
margin-bottom: 8px;
color: var(--vp-c-text-1);
}
.feature-details {
color: var(--vp-c-text-2);
font-size: 0.95rem;
line-height: 1.6;
}
+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": "<初始化时设置的管理员密码>"}'
-d '{"password": "FileCodeBox2023"}'
```
**响应示例:**
@@ -329,4 +329,4 @@ curl -L "http://localhost:12345/share/select/?code=abc123" -o downloaded_file
- 403: 禁止访问
- 404: 资源不存在
- 422: 请求参数验证错误
- 500: 服务器内部错误
- 500: 服务器内部错误
-48
View File
@@ -1,48 +0,0 @@
# Changelog
## [2.5.3](https://github.com/vastsa/FileCodeBox/compare/v2.5.2...v2.5.3) (2026-07-23)
### Bug Fixes
* add magic-byte checks, login rate limits, and non-root Docker ([eda0a31](https://github.com/vastsa/FileCodeBox/commit/eda0a3127ab562b6a2cf828c0df4a93933c44526))
* magic-byte file checks, admin login rate limit, non-root Docker ([0ee2f04](https://github.com/vastsa/FileCodeBox/commit/0ee2f046dd057fecceaee1059d72d67de3038f19))
## [2.5.2](https://github.com/vastsa/FileCodeBox/compare/v2.5.1...v2.5.2) (2026-07-23)
### Bug Fixes
* harden share expiry, download token, quota SQL, and CORS ([ae77026](https://github.com/vastsa/FileCodeBox/commit/ae7702603a99dc77b9b48e78746058b2a74b0bf5))
* harden share expiry, download token, quota SQL, and CORS ([a41693f](https://github.com/vastsa/FileCodeBox/commit/a41693f90ded0234e0883c399254319bef04924a))
## [2.5.1](https://github.com/vastsa/FileCodeBox/compare/v2.5.0...v2.5.1) (2026-07-21)
### Bug Fixes
* patch CVE dependencies and path traversal risks ([00f3abd](https://github.com/vastsa/FileCodeBox/commit/00f3abd3b20fe2344e4dbf8d53714773e23a1050))
## [2.5.0](https://github.com/vastsa/FileCodeBox/compare/v2.4.0...v2.5.0) (2026-07-11)
### Features
* add global storage capacity limit ([818dd47](https://github.com/vastsa/FileCodeBox/commit/818dd47b2a4136d4b0d68b2484ac2d01a7ae6a3c))
* automate version releases ([ee8f908](https://github.com/vastsa/FileCodeBox/commit/ee8f9082ab59418a4a7721a05fc358215230981f))
* configure admin session lifetime ([#484](https://github.com/vastsa/FileCodeBox/issues/484)) ([93ff291](https://github.com/vastsa/FileCodeBox/commit/93ff291366aaac9d04c5259d3ecf01b20aed3fd0))
### Bug Fixes
* build frontend on native Docker platform ([2c51384](https://github.com/vastsa/FileCodeBox/commit/2c51384c80a9ff3f4eb98eb876759b8949dfae89))
* harden automated release workflow ([46883c9](https://github.com/vastsa/FileCodeBox/commit/46883c90ff52894631fe53bbd9b9c4100a7b27f1))
* harden share retrieval and admin visibility ([#482](https://github.com/vastsa/FileCodeBox/issues/482), [#480](https://github.com/vastsa/FileCodeBox/issues/480)) ([8d7d856](https://github.com/vastsa/FileCodeBox/commit/8d7d856c62d73badd0797eb4daec8d2ff10a403a))
* resolve docs dependency audit warnings ([36300ef](https://github.com/vastsa/FileCodeBox/commit/36300ef54ee09081a6cf6a5fe4e69cee7aad0162))
## [Unreleased]
### Added
- 增加全局存储容量上限配置,并对普通上传、分片上传、预签名直传和后台文件分享统一执行并发安全的容量预留。
- 增加存储预留迁移及过期上传清理,失败、取消或过期的上传会释放预留容量。
+196
View File
@@ -0,0 +1,196 @@
# 本轮开发交付报告
生成日期: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
@@ -0,0 +1,211 @@
# 下一步开发计划
本文档记录 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": "<admin-password-set-during-setup>"}'
-d '{"password": "FileCodeBox2023"}'
```
**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
-8
View File
@@ -1,8 +0,0 @@
## [Unreleased]
<!-- Current release: 2.5.3 x-release-please-version -->
### Added
- Added a global storage capacity limit with concurrency-safe reservations for regular, chunked, presigned, and admin file uploads.
- Added the storage reservation migration and stale upload cleanup so failed, cancelled, or expired uploads release reserved capacity.
+8 -15
View File
@@ -1,6 +1,6 @@
# Configuration Guide
FileCodeBox provides rich configuration options. Prefer the admin panel; directly editing the database can introduce invalid types or break security settings.
FileCodeBox provides rich configuration options that can be customized through the admin panel or by directly modifying the configuration. This document details all available configuration options.
## Configuration Methods
@@ -22,9 +22,7 @@ On first startup, the system uses default configuration from `core/settings.py`.
| `name` | string | `文件快递柜 - FileCodeBox` | Site name, displayed in page title and navigation bar |
| `description` | string | `开箱即用的文件快传系统` | Site description, used for SEO |
| `keywords` | string | `FileCodeBox, 文件快递柜...` | Site keywords, used for SEO |
| `serverHost` | string | `0.0.0.0` | Service listening address |
| `serverPort` | int | `12345` | Service listening port |
| `serverWorkers` | int | `1` | Worker count; keep one worker for SQLite deployments |
| `port` | int | `12345` | Service listening port |
### Notification Settings
@@ -44,7 +42,6 @@ On first startup, the system uses default configuration from `core/settings.py`.
| `openUpload` | int | `1` | Enable upload functionality (1=enabled, 0=disabled) |
| `uploadSize` | int | `10485760` | Maximum single file upload size (bytes), default 10MB |
| `enableChunk` | int | `0` | Enable chunked upload (1=enabled, 0=disabled) |
| `allowed_file_types` | list | `["*"]` | Allowed extensions; `*` allows every file type |
::: warning Note
`uploadSize` is in bytes. 10MB = 10 * 1024 * 1024 = 10485760 bytes
@@ -112,12 +109,11 @@ Default available themes:
| Setting | Type | Default | Description |
|---------|------|---------|-------------|
| `admin_token` | string | Set during setup | Admin login password |
| `admin_token` | string | `FileCodeBox2023` | Admin login password |
| `showAdminAddr` | int | `0` | Show admin panel entry on homepage (1=show, 0=hide) |
| `adminSessionExpire` | int | `2592000` | Admin session lifetime in seconds (30 days) |
::: danger Security Warning
The setup page is shown automatically while the system is uninitialized. Complete setup before exposing a production service to the public internet.
Always change the default `admin_token` in production environments! Using the default password poses serious security risks.
:::
## Security Settings
@@ -127,8 +123,7 @@ The setup page is shown automatically while the system is uninitialized. Complet
| Setting | Type | Default | Description |
|---------|------|---------|-------------|
| `errorMinute` | int | `1` | Error limit time window (minutes) |
| `errorCount` | int | `10` | Maximum errors allowed within the time window |
| `trustedProxies` | list | `[]` | Trusted reverse-proxy IPs used to resolve client addresses |
| `errorCount` | int | `1` | Maximum errors allowed within the time window |
This setting prevents brute-force attacks on extraction codes.
@@ -140,7 +135,6 @@ This setting prevents brute-force attacks on extraction codes.
|---------|------|---------|-------------|
| `file_storage` | string | `local` | Storage backend type |
| `storage_path` | string | `""` | Custom storage path |
| `storageLimit` | int | `0` | Total storage quota in bytes; 0 means unlimited |
Supported storage types:
- `local` - Local storage
@@ -164,6 +158,7 @@ Suitable for personal or small team use with relaxed limits:
"uploadMinute": 5, # 5 minutes
"uploadCount": 20, # Max 20 uploads
"expireStyle": ["day", "hour", "forever"],
"admin_token": "your-secure-password",
"showAdminAddr": 1
}
```
@@ -182,6 +177,7 @@ Suitable for public services requiring stricter limits:
"errorCount": 3, # Max 3 errors
"expireStyle": ["hour", "minute", "count"],
"max_save_seconds": 86400, # Max retention 1 day
"admin_token": "very-secure-password-123",
"showAdminAddr": 0
}
```
@@ -199,14 +195,11 @@ Suitable for enterprise internal use with large file and chunked upload support:
"uploadCount": 100, # Max 100 uploads
"expireStyle": ["day", "forever"],
"file_storage": "s3", # Use S3 storage
"admin_token": "enterprise-secure-token",
"showAdminAddr": 1
}
```
::: warning Configuration examples
These dictionaries illustrate combinations of values; they are not editable configuration files. Set the admin password through first-run setup or the admin panel.
:::
## Next Steps
- [Storage Configuration](/en/guide/storage) - Learn how to configure different storage backends
+5 -19
View File
@@ -15,25 +15,12 @@ FileCodeBox is a simple and efficient file sharing tool that supports temporary
## Deployment Methods
### Docker Deployment (Recommended)
### Docker Deployment
```bash
docker run -d --restart unless-stopped \
-p 12345:12345 \
-v fcb-data:/app/data \
--name filecodebox \
lanol/filecodebox:latest
docker run -d --restart=always -p 12345:12345 -v /opt/FileCodeBox/:/app/data --name filecodebox lanol/filecodebox:beta
```
The named volume persists configuration and uploaded files across container upgrades.
| Variable | Default | Description |
|----------|---------|-------------|
| `HOST` | `0.0.0.0` | Service listening address |
| `PORT` | `12345` | Service port |
| `WORKERS` | `1` | Worker count; keep one worker for SQLite deployments |
| `LOG_LEVEL` | `info` | `debug`, `info`, `warning`, or `error` |
### Manual Deployment
1. Clone the repository
@@ -68,14 +55,13 @@ python main.py
- Download file
4. Admin Panel
- Open `http://localhost:12345` on first run and complete setup
- Visit `http://localhost:12345/#/admin`
- Enter the admin password set during setup
- Enter admin password: `FileCodeBox2023`
- Enter admin panel
- View system information, files, activity records, and configuration
- View system information, file list, user management, etc.
## Next Steps
- [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
+2 -2
View File
@@ -136,7 +136,7 @@ Command-line download
### Docker Deployment
```bash
docker run -d --restart unless-stopped -p 12345:12345 -v fcb-data:/app/data --name filecodebox lanol/filecodebox:latest
docker run -d --restart=always -p 12345:12345 -v /opt/FileCodeBox/:/app/data --name filecodebox lanol/filecodebox:beta
```
### Manual Deployment
@@ -240,4 +240,4 @@ For more questions, visit [Wiki](https://github.com/vastsa/FileCodeBox/wiki/常
## 📜 Disclaimer
This project is open-source for learning purposes only. It should not be used for any illegal purposes. The author is not responsible for any consequences. Please retain the project address and copyright information when using it.
This project is open-source for learning purposes only. It should not be used for any illegal purposes. The author is not responsible for any consequences. Please retain the project address and copyright information when using it.
+4 -5
View File
@@ -8,13 +8,12 @@ FileCodeBox provides a fully-featured admin panel that allows administrators to
The admin panel is located at the `/admin` path. Access method:
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
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
::: tip Tip
The setup page is shown automatically while the system is uninitialized. Complete setup before exposing a production service to the public internet.
The default admin password is `FileCodeBox2023`. Be sure to change this password in production environments. See [Security Settings](/en/guide/security) for details.
:::
### Show Admin Entry
-26
View File
@@ -1,26 +0,0 @@
# Releasing
The project uses Semantic Versioning and Conventional Commits.
Complete these settings once in the backend GitHub repository:
- In `Settings → Actions → General → Workflow permissions`, grant read/write
access and allow GitHub Actions to create pull requests. The frontend repository
only needs the default read-only Actions permission.
- Keep squash merging enabled. The release workflow waits for required checks
before merging the release pull request.
- Add `DOCKER_USERNAME` and `DOCKER_PASSWORD` Actions secrets to the backend repository.
1. Merge commits using Conventional Commit types such as `feat:` and `fix:` into the default branch.
2. Release Please creates and merges the release pull request and updates `VERSION` and the changelog.
3. The workflow then creates `vX.Y.Z`, a GitHub Release, and dispatches the production image build.
4. Releases publish `X.Y.Z`, `X.Y`, and `latest`; branches publish `dev` or `edge-*` images.
5. Each image build resolves the latest commit from both frontend default branches automatically.
Every `fix:`, `feat:`, or breaking change merged into the default branch therefore
creates a Patch, Minor, or Major release automatically. Non-release commits such
as `docs:` and `chore:` do not publish a release on their own.
The backend runtime version comes from `VERSION`. Container branch builds inject a
commit-qualified development version through `APP_VERSION`; release tags must exactly
match `VERSION`. OCI image labels record the resolved backend and frontend commits for traceability.
+11 -7
View File
@@ -4,13 +4,15 @@ FileCodeBox provides multiple layers of security mechanisms to protect your file
## Admin Password
### First-Run Setup
### Change Default Password
::: danger Important Security Warning
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.
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.
:::
Change the admin password through the admin panel:
There are two ways to change the admin password:
**Method 1: Via Admin Panel (Recommended)**
1. Access `/admin` to enter the admin panel
2. Log in with the current password
@@ -18,7 +20,9 @@ Change the admin password through the admin panel:
4. Find the `admin_token` configuration item
5. Enter a new secure password and save
`admin_token` is stored as a password hash. Do not write a plaintext password to the database, or admin login will stop working.
**Method 2: Via Database**
Configuration is stored in the `keyvalue` table of the `data/filecodebox.db` database. You can directly modify the `admin_token` value.
### Password Security Recommendations
@@ -87,7 +91,7 @@ Limit the number of error attempts from a single IP to prevent brute-force attac
| Setting | Type | Default | Description |
|---------|------|---------|-------------|
| `errorMinute` | int | `1` | Error limit time window (minutes) |
| `errorCount` | int | `10` | Maximum errors allowed within the time window |
| `errorCount` | int | `1` | Maximum errors allowed within the time window |
**How it works:**
- When a user enters an incorrect extraction code, the system records the error count for that IP
@@ -106,7 +110,7 @@ Limit the number of error attempts from a single IP to prevent brute-force attac
```
::: warning Note
The default allows up to 10 errors per IP each minute. Public services can tighten this limit while accounting for users behind shared network addresses.
The default configuration `errorMinute=1, errorCount=1` is very strict, meaning you need to wait 1 minute after entering one incorrect extraction code before retrying. Adjust this configuration based on actual needs.
:::
## Upload Restrictions
@@ -268,7 +272,7 @@ your-domain.com {
Before deploying FileCodeBox, confirm the following security configurations:
- [ ] Completed first-run setup and set the admin password `admin_token`
- [ ] Changed default 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": "<admin-password-set-during-setup>"}'
-d '{"password": "FileCodeBox2023"}'
# Returns: {"code":200,"msg":"success","detail":{"token":"xxx.xxx.xxx","token_type":"Bearer"}}
+23 -48
View File
@@ -3,8 +3,8 @@ layout: home
hero:
name: "FileCodeBox"
text: "Share files like picking up a package"
tagline: A lightweight, modern, self-hosted service for files and text
text: "File Express Box"
tagline: Share text and files anonymously with access codes, just like picking up a package
image:
src: /logo_small.png
alt: FileCodeBox
@@ -16,51 +16,26 @@ hero:
text: Live Demo
link: https://share.lanol.cn
- theme: alt
text: Deployment Guide
link: /en/guide/getting-started#docker-deployment-recommended
text: View on GitHub
link: https://github.com/vastsa/FileCodeBox
features:
- icon: 01
title: Share instantly
details: Files and text in one flow, with batch, chunked, and resumable uploads
- icon: 02
title: Flexible expiry
details: Expire by time or retrieval count, or keep content permanently
- icon: 03
title: Own your data
details: Local, S3, OneDrive, WebDAV, and OpenDAL storage
---
## Start in 30 seconds
```bash
docker run -d --restart unless-stopped \
-p 12345:12345 \
-v ./data:/app/data \
--name filecodebox \
lanol/filecodebox:2.5.3 # x-release-please-version
```
Open `http://localhost:12345` and complete the first-run setup.
<div class="doc-paths">
<a class="doc-path" href="/en/guide/getting-started">
<span>Get started</span>
<strong>Deploy, initialize, and upgrade</strong>
<small>Run FileCodeBox from a clean server →</small>
</a>
<a class="doc-path" href="/en/guide/storage">
<span>Operate</span>
<strong>Storage, configuration, and security</strong>
<small>Choose production-ready storage and protection →</small>
</a>
<a class="doc-path" href="/en/api/">
<span>Integrate</span>
<strong>API and upload workflows</strong>
<small>Build on sharing, chunked uploads, and administration →</small>
</a>
</div>
::: warning Responsible use
Use FileCodeBox only for lawful file and text sharing. Operators are responsible for deployment security, data compliance, and content moderation.
:::
- icon: 🚀
title: Quick Deployment
details: Supports one-click Docker deployment, simple and fast, no complex configuration needed
- icon: 🔒
title: Secure & Reliable
details: File access requires an access code, supports expiration time and download limit settings
- icon: 💻
title: Clean Interface
details: Clean user interface with drag-and-drop upload support for excellent user experience
- icon: 🛠️
title: Feature Rich
details: Supports file preview, online playback, image processing, and many other features
- icon: 📦
title: Storage Extensions
details: Supports various storage methods including local storage and object storage
- icon: 🔌
title: API Support
details: Provides complete REST API for easy integration with other systems
---
+8 -15
View File
@@ -1,6 +1,6 @@
# 配置说明
FileCodeBox 提供了丰富的配置选项。请优先通过管理面板修改,避免直接编辑数据库造成类型错误或安全配置失效。
FileCodeBox 提供了丰富的配置选项,可以通过管理面板或直接修改配置来自定义系统行为。本文档详细介绍所有可用的配置项。
## 配置方式
@@ -22,9 +22,7 @@ FileCodeBox 支持两种配置方式:
| `name` | string | `文件快递柜 - FileCodeBox` | 站点名称,显示在页面标题和导航栏 |
| `description` | string | `开箱即用的文件快传系统` | 站点描述,用于 SEO |
| `keywords` | string | `FileCodeBox, 文件快递柜...` | 站点关键词,用于 SEO |
| `serverHost` | string | `0.0.0.0` | 服务监听地址 |
| `serverPort` | int | `12345` | 服务监听端口 |
| `serverWorkers` | int | `1` | 工作进程数;SQLite 部署建议保持单进程 |
| `port` | int | `12345` | 服务监听端口 |
### 通知设置
@@ -44,7 +42,6 @@ FileCodeBox 支持两种配置方式:
| `openUpload` | int | `1` | 是否开启上传功能(1=开启,0=关闭) |
| `uploadSize` | int | `10485760` | 单文件最大上传大小(字节),默认 10MB |
| `enableChunk` | int | `0` | 是否启用分片上传(1=启用,0=禁用) |
| `allowed_file_types` | list | `["*"]` | 允许上传的扩展名;`*` 表示不限制 |
::: warning 注意
`uploadSize` 的单位是字节。10MB = 10 * 1024 * 1024 = 10485760 字节
@@ -111,12 +108,11 @@ FileCodeBox 支持两种配置方式:
| 配置项 | 类型 | 默认值 | 说明 |
|--------|------|--------|------|
| `admin_token` | string | 初始化页面设置 | 管理员登录密码(哈希存储) |
| `admin_token` | string | `FileCodeBox2023` | 管理员登录密码 |
| `showAdminAddr` | int | `0` | 是否在首页显示管理入口(1=显示,0=隐藏) |
| `adminSessionExpire` | int | `2592000` | 管理会话有效期(秒),默认 30 天 |
::: danger 安全警告
未初始化时会自动显示初始化页面。生产环境请在服务对外开放前完成初始化。
请务必在生产环境中修改默认的 `admin_token`!使用默认密码会导致严重的安全风险。
:::
## 安全设置
@@ -126,8 +122,7 @@ FileCodeBox 支持两种配置方式:
| 配置项 | 类型 | 默认值 | 说明 |
|--------|------|--------|------|
| `errorMinute` | int | `1` | 错误限制的时间窗口(分钟) |
| `errorCount` | int | `10` | 在时间窗口内允许的最大错误次数 |
| `trustedProxies` | list | `[]` | 可信反向代理 IP;用于安全解析客户端地址 |
| `errorCount` | int | `1` | 在时间窗口内允许的最大错误次数 |
此设置用于防止暴力破解提取码。
@@ -139,7 +134,6 @@ FileCodeBox 支持两种配置方式:
|--------|------|--------|------|
| `file_storage` | string | `local` | 存储后端类型 |
| `storage_path` | string | `""` | 自定义存储路径 |
| `storageLimit` | int | `0` | 总存储配额(字节),0 表示不限制 |
支持的存储类型:
- `local` - 本地存储
@@ -163,6 +157,7 @@ FileCodeBox 支持两种配置方式:
"uploadMinute": 5, # 5分钟
"uploadCount": 20, # 最多20次
"expireStyle": ["day", "hour", "forever"],
"admin_token": "your-secure-password",
"showAdminAddr": 1
}
```
@@ -181,6 +176,7 @@ FileCodeBox 支持两种配置方式:
"errorCount": 3, # 最多3次错误
"expireStyle": ["hour", "minute", "count"],
"max_save_seconds": 86400, # 最长保存1天
"admin_token": "very-secure-password-123",
"showAdminAddr": 0
}
```
@@ -198,14 +194,11 @@ FileCodeBox 支持两种配置方式:
"uploadCount": 100, # 最多100次
"expireStyle": ["day", "forever"],
"file_storage": "s3", # 使用S3存储
"admin_token": "enterprise-secure-token",
"showAdminAddr": 1
}
```
::: warning 配置示例
以上字典仅用于展示配置值组合,不是可直接编辑的配置文件。管理员密码请在初始化页面或管理面板中设置。
:::
## 下一步
- [存储配置](/guide/storage) - 了解如何配置不同的存储后端
+9 -14
View File
@@ -20,11 +20,7 @@ FileCodeBox 是一个简单高效的文件分享工具,支持文件临时中
#### 快速启动
```bash
docker run -d --restart unless-stopped \
-p 12345:12345 \
-v fcb-data:/app/data \
--name filecodebox \
lanol/filecodebox:latest
docker run -d --restart=always -p 12345:12345 -v /opt/FileCodeBox/:/app/data --name filecodebox lanol/filecodebox:latest
```
#### Docker Compose
@@ -40,7 +36,7 @@ services:
ports:
- "12345:12345"
environment:
- WORKERS=1
- WORKERS=4
- LOG_LEVEL=info
volumes:
fcb-data:
@@ -51,9 +47,9 @@ volumes:
| 变量 | 默认值 | 说明 |
|------|--------|------|
| `HOST` | `0.0.0.0` | 服务监听地址 |
| `HOST` | `::` | 监听地址,支持 IPv4/IPv6 双栈 |
| `PORT` | `12345` | 服务端口 |
| `WORKERS` | `1` | 工作进程数;SQLite 部署建议保持单进程 |
| `WORKERS` | `4` | 工作进程数,建议设置为 CPU 核心数 |
| `LOG_LEVEL` | `info` | 日志级别:debug/info/warning/error |
#### 自定义配置示例
@@ -61,8 +57,8 @@ volumes:
```bash
docker run -d --restart=always \
-p 12345:12345 \
-v fcb-data:/app/data \
-e WORKERS=1 \
-v /opt/FileCodeBox/:/app/data \
-e WORKERS=8 \
-e LOG_LEVEL=warning \
--name filecodebox \
lanol/filecodebox:latest
@@ -113,14 +109,13 @@ python main.py
- 下载文件
4. 后台管理
- 首次访问 `http://localhost:12345` 完成初始化
- 访问 `http://localhost:12345/#/admin`
- 输入初始化时设置的管理员密码
- 输入管理员密码:`FileCodeBox2023`
- 进入后台管理页面
- 查看系统信息、文件列表、活动记录和系统配置
- 查看系统信息、文件列表、用户管理等
## 下一步
- [存储配置](/guide/storage) - 了解如何配置不同的存储方式
- [安全设置](/guide/security) - 了解如何增强系统安全性
- [API 文档](/api/) - 了解如何通过 API 集成
- [API 文档](/api/) - 了解如何通过 API 集成
+1 -1
View File
@@ -128,7 +128,7 @@ FileCodeBox 是一个基于 FastAPI + Vue3 开发的轻量级文件分享工具
### Docker 部署
```bash
docker run -d --restart unless-stopped -p 12345:12345 -v fcb-data:/app/data --name filecodebox lanol/filecodebox:latest
docker run -d --restart=always -p 12345:12345 -v /opt/FileCodeBox/:/app/data --name filecodebox lanol/filecodebox:beta
```
### 手动部署
+5 -6
View File
@@ -8,13 +8,12 @@ FileCodeBox 提供了功能完善的管理面板,让管理员可以方便地
管理面板位于 `/admin` 路径。访问方式:
1. 首次访问站点时,按初始化页面设置管理员密码
2. 在浏览器中访问 `http://your-domain.com/admin`
3. 输入管理员密码(`admin_token` 配置项的值)
4. 点击登录按钮
1. 在浏览器中访问 `http://your-domain.com/admin`
2. 输入管理员密码(`admin_token` 配置项的值)
3. 点击登录按钮
::: tip 提示
未初始化时会自动进入初始化页面。生产环境请先完成初始化,再开放公网访问。
默认管理员密码是 `FileCodeBox2023`。请务必在生产环境中修改此密码,详见 [安全设置](/guide/security)。
:::
### 显示管理入口
@@ -385,7 +384,7 @@ Content-Type: application/json
-- 查看当前配置
SELECT * FROM keyvalue WHERE key = 'settings';
-- 或者删除配置,重启后重新进入初始化流程
-- 或者删除配置,恢复默认密码
DELETE FROM keyvalue WHERE key = 'settings';
```
-23
View File
@@ -1,23 +0,0 @@
# 版本发布
项目采用 Semantic Versioning 和 Conventional Commits 管理版本。
首次启用时,需要在后端 GitHub 仓库完成以下设置:
- `Settings → Actions → General → Workflow permissions` 选择读写权限,并允许
GitHub Actions 创建 Pull Request。前端仓库只需要默认的 Actions 读取权限。
- 保持 Squash merge 可用;自动发布工作流会等待必需检查通过后合并发布 PR。
- 后端仓库配置 `DOCKER_USERNAME` 和 `DOCKER_PASSWORD` Actions Secrets。
1. 日常提交使用 `feat:`、`fix:` 等 Conventional Commits 前缀并合入主分支。
2. Release Please 自动创建并合并发布 PR,更新 `VERSION` 和更新日志。
3. 工作流随后自动创建 `vX.Y.Z`、GitHub Release 并触发正式镜像构建。
4. 正式镜像发布 `X.Y.Z`、`X.Y` 和 `latest`;分支镜像使用 `dev` 或 `edge-*`。
5. 镜像构建时自动读取两个前端仓库默认分支的最新提交,无需手工同步版本。
因此每次合入主分支的 `fix:`、`feat:` 或破坏性变更都会自动产生对应的
Patch、Minor 或 Major 版本。`docs:`、`chore:` 等不影响版本的提交不会单独发版。
后端运行版本来自 `VERSION`。容器分支构建通过 `APP_VERSION` 注入带提交号的
开发版本;正式标签必须与 `VERSION` 完全一致。Docker 镜像的 OCI 标签还记录
后端和两个前端仓库当次解析到的精确提交,便于定位构建内容。
+11 -7
View File
@@ -4,13 +4,15 @@ FileCodeBox 提供了多层安全机制来保护您的文件分享服务。本
## 管理员密码
### 首次初始化
### 修改默认密码
::: danger 重要安全警告
FileCodeBox 首次启动时不会生成默认管理员密码。请在浏览器中打开站点,按初始化页面设置管理员密码,并妥善保存。
FileCodeBox 的默认管理员密码是 `FileCodeBox2023`。**在生产环境中必须立即修改此密码!**使用默认密码会导致任何人都可以访问您的管理面板。
:::
请通过管理面板修改管理员密码:
修改管理员密码有两种方式:
**方式一:通过管理面板修改(推荐)**
1. 访问 `/admin` 进入管理面板
2. 使用当前密码登录
@@ -18,7 +20,9 @@ FileCodeBox 首次启动时不会生成默认管理员密码。请在浏览器
4. 找到 `admin_token` 配置项
5. 输入新的安全密码并保存
`admin_token` 使用密码哈希存储。不要向数据库写入明文密码,否则管理员登录将失效。
**方式二:通过数据库修改**
配置存储在 `data/filecodebox.db` 数据库的 `keyvalue` 表中,可以直接修改 `admin_token` 的值。
### 密码安全建议
@@ -86,7 +90,7 @@ FileCodeBox 内置了基于 IP 的速率限制机制,可以有效防止滥用
| 配置项 | 类型 | 默认值 | 说明 |
|--------|------|--------|------|
| `errorMinute` | int | `1` | 错误限制的时间窗口(分钟) |
| `errorCount` | int | `10` | 在时间窗口内允许的最大错误次数 |
| `errorCount` | int | `1` | 在时间窗口内允许的最大错误次数 |
**工作原理:**
- 当用户输入错误的提取码时,系统记录该 IP 的错误次数
@@ -105,7 +109,7 @@ FileCodeBox 内置了基于 IP 的速率限制机制,可以有效防止滥用
```
::: warning 注意
默认配置允许每个 IP 在 1 分钟内最多出现 10 次错误。公开服务可根据访问规模适当收紧,并避免误伤共享出口用户。
默认配置 `errorMinute=1, errorCount=1` 非常严格,意味着输入一次错误的提取码后需要等待1分钟才能重试。根据实际需求调整此配置。
:::
## 上传限制
@@ -267,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": "<初始化时设置的管理员密码>"}'
-d '{"password": "FileCodeBox2023"}'
# 返回: {"code":200,"msg":"success","detail":{"token":"xxx.xxx.xxx","token_type":"Bearer"}}
+22 -46
View File
@@ -3,8 +3,8 @@ layout: home
hero:
name: "FileCodeBox"
text: "像取快递一样取文件"
tagline: 轻量、现代的自托管文件与文本分享服务
text: "文件快递柜"
tagline: 匿名口令分享文本,文件,像拿快递一样取文件
image:
src: /logo_small.png
alt: FileCodeBox
@@ -16,51 +16,27 @@ hero:
text: 在线体验
link: https://share.lanol.cn
- theme: alt
text: 部署指南
link: /guide/getting-started#docker-部署推荐
text: 在 GitHub 上查看
link: https://github.com/vastsa/FileCodeBox
features:
- icon: 01
title: 即传即取
details: 文件与文本统一分享,支持批量、分片和断点续传
- icon: 02
title: 灵活失效
details: 按时间或取件次数失效,也可以永久保留
- icon: 03
title: 数据自主
details: 支持本地、S3、OneDrive、WebDAV 与 OpenDAL
- icon: 🚀
title: 快速部署
details: 支持 Docker 一键部署,简单快捷,无需复杂配置
- icon: 🔒
title: 安全可靠
details: 文件访问需要提取码,支持设置有效期和下载次数限制
- icon: 💻
title: 简洁界面
details: 清爽的用户界面,支持拖拽上传,使用体验极佳
- icon: 🛠️
title: 功能丰富
details: 支持文件预览、在线播放、图片处理等多种功能
- icon: 📦
title: 存储扩展
details: 支持本地存储、对象存储等多种存储方式
- icon: 🔌
title: API 支持
details: 提供完整的 REST API,方便与其他系统集成
---
## 30 秒启动
```bash
docker run -d --restart unless-stopped \
-p 12345:12345 \
-v ./data:/app/data \
--name filecodebox \
lanol/filecodebox:2.5.3 # x-release-please-version
```
打开 `http://localhost:12345`,按引导完成首次初始化。
<div class="doc-paths">
<a class="doc-path" href="/guide/getting-started">
<span>开始使用</span>
<strong>部署、初始化与升级</strong>
<small>从一台空服务器开始运行 FileCodeBox →</small>
</a>
<a class="doc-path" href="/guide/storage">
<span>管理服务</span>
<strong>存储、配置与安全</strong>
<small>为生产环境选择合适的存储和保护策略 →</small>
</a>
<a class="doc-path" href="/api/">
<span>集成开发</span>
<strong>API 与上传流程</strong>
<small>接入分享、分片上传和管理能力 →</small>
</a>
</div>
::: warning 使用须知
请仅将 FileCodeBox 用于合法的文件与文本分享。服务运营者应自行负责部署安全、数据合规和内容管理。
:::
+2 -7
View File
@@ -1,15 +1,10 @@
{
"devDependencies": {
"vitepress": "^1.6.4"
},
"pnpm": {
"overrides": {
"vite": "6.4.3"
}
"vitepress": "^1.6.3"
},
"scripts": {
"docs:dev": "vitepress dev",
"docs:build": "vitepress build",
"docs:preview": "vitepress preview"
}
}
}
+607 -752
View File
File diff suppressed because it is too large. Load diff
+843
View File
@@ -0,0 +1,843 @@
# 功能与用户体验提升规划
生成日期: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:发送结果页增强`
这四项组合能同时修正服务端边界和公开用户体验,为后续上传恢复、管理工作台优化打基础。
+24 -721
View File
@@ -3,14 +3,12 @@
# @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, HTTPException
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import FileResponse, HTMLResponse, JSONResponse, RedirectResponse
from fastapi.responses import FileResponse, HTMLResponse
from tortoise import Tortoise
from tortoise.contrib.fastapi import register_tortoise
@@ -18,31 +16,16 @@ 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_security_settings,
ensure_settings_row,
initialize_system,
is_runtime_initialized,
refresh_settings,
)
from core.config import ensure_settings_row, 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 (
clean_expired_presign_sessions,
clean_incomplete_uploads,
delete_expire_files,
)
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
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,
@@ -55,7 +38,7 @@ def build_public_config() -> dict:
"openUpload": settings.openUpload,
"notify_title": settings.notify_title,
"notify_content": settings.notify_content,
"show_admin_address": normalize_public_flag(settings.showAdminAddr),
"show_admin_address": settings.showAdminAddr,
"max_save_seconds": settings.max_save_seconds,
}
@@ -71,7 +54,7 @@ def build_public_meta() -> dict:
"features": {
"chunkUpload": bool(settings.enableChunk),
"guestUpload": bool(settings.openUpload),
"adminAddressVisible": bool(normalize_public_flag(settings.showAdminAddr)),
"adminAddressVisible": bool(settings.showAdminAddr),
"expirationModes": settings.expireStyle,
},
"limits": {
@@ -84,639 +67,6 @@ 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", 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'<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"]))
)
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'<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="loginCount">管理员登录失败频率 <span class="compact-help">次数 / 分钟</span></label>
<div class="row">
<input id="loginCount" name="loginCount" type="number" min="1" value="{login_count}" required>
<input name="loginMinute" type="number" min="1" value="{login_minute}" aria-label="登录失败检测窗口分钟" required>
</div>
<label for="save_time_value">最长保存时间</label>
<div class="row">
<input id="save_time_value" name="save_time_value" type="number" min="0" value="{save_time_value}" required>
<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("正在初始化应用...")
@@ -729,7 +79,6 @@ async def lifespan(app: FastAPI):
# 启动后台任务
task = asyncio.create_task(delete_expire_files())
chunk_cleanup_task = asyncio.create_task(clean_incomplete_uploads())
presign_cleanup_task = asyncio.create_task(clean_expired_presign_sessions())
logger.info("应用初始化完成")
try:
@@ -739,13 +88,7 @@ async def lifespan(app: FastAPI):
logger.info("正在关闭应用...")
task.cancel()
chunk_cleanup_task.cancel()
presign_cleanup_task.cancel()
await asyncio.gather(
task,
chunk_cleanup_task,
presign_cleanup_task,
return_exceptions=True,
)
await asyncio.gather(task, chunk_cleanup_task, return_exceptions=True)
await Tortoise.close_connections()
logger.info("应用已关闭")
@@ -756,40 +99,37 @@ async def load_config():
key="sys_start", defaults={"value": int(time.time() * 1000)}
)
await refresh_settings()
await ensure_security_settings()
await migrate_password_to_hash()
ip_limit["error"].minutes = settings.errorMinute
ip_limit["error"].count = settings.errorCount
ip_limit["upload"].minutes = settings.uploadMinute
ip_limit["upload"].count = settings.uploadCount
ip_limit["login"].minutes = settings.loginMinute
ip_limit["login"].count = settings.loginCount
app = FastAPI(lifespan=lifespan, version=APP_VERSION)
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(
CORSMiddleware,
allow_origins=["*"],
# 前端使用 Bearer Token,不依赖 Cookie credentials。
# allow_origins=["*"] 与 allow_credentials=True 组合不符合 CORS 规范。
allow_credentials=False,
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
@@ -809,43 +149,6 @@ 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()
+429 -62
View File
@@ -1,105 +1,472 @@
<div align="center">
<img src="./docs/public/logo_small.png" alt="FileCodeBox" width="96" />
# FileCodeBox
### 像取快递一样取文件
### 文件快递柜 - 匿名口令分享文本和文件
一个轻量、现代的自托管文件分享工具。无需注册,上传后获得口令,对方输入即可取件。
<img src="https://fastly.jsdelivr.net/gh/vastsa/FileCodeBox@V1.6/static/banners/img_1.png" alt="FileCodeBox Logo" width="400">
[在线演示](https://share.lanol.cn) · [使用文档](https://fcb-docs.aiuo.net/) · [English](./readme_en.md)
像拿快递一样取文件,无需注册,输入口令即可获取
[![Release](https://img.shields.io/github/v/release/vastsa/FileCodeBox?style=flat-square&color=111111)](https://github.com/vastsa/FileCodeBox/releases/latest)
[![Docker Pulls](https://img.shields.io/docker/pulls/lanol/filecodebox?style=flat-square&logo=docker&color=111111)](https://hub.docker.com/r/lanol/filecodebox)
[![Stars](https://img.shields.io/github/stars/vastsa/FileCodeBox?style=flat-square&logo=github&color=111111)](https://github.com/vastsa/FileCodeBox/stargazers)
[![License](https://img.shields.io/github/license/vastsa/FileCodeBox?style=flat-square&color=111111)](./LICENSE)
[![GitHub stars](https://img.shields.io/github/stars/vastsa/FileCodeBox?style=flat-square&logo=github)](https://github.com/vastsa/FileCodeBox/stargazers)
[![GitHub forks](https://img.shields.io/github/forks/vastsa/FileCodeBox?style=flat-square&logo=github)](https://github.com/vastsa/FileCodeBox/network)
[![GitHub issues](https://img.shields.io/github/issues/vastsa/FileCodeBox?style=flat-square&logo=github)](https://github.com/vastsa/FileCodeBox/issues)
[![GitHub license](https://img.shields.io/github/license/vastsa/FileCodeBox?style=flat-square)](https://github.com/vastsa/FileCodeBox/blob/master/LICENSE)
[![Docker Pulls](https://img.shields.io/docker/pulls/lanol/filecodebox?style=flat-square&logo=docker)](https://hub.docker.com/r/lanol/filecodebox)
<br />
[![Python](https://img.shields.io/badge/Python-3.8+-3776AB?style=flat-square&logo=python&logoColor=white)](https://www.python.org)
[![FastAPI](https://img.shields.io/badge/FastAPI-0.68+-009688?style=flat-square&logo=fastapi&logoColor=white)](https://fastapi.tiangolo.com)
[![Vue.js](https://img.shields.io/badge/Vue.js-3.x-4FC08D?style=flat-square&logo=vue.js&logoColor=white)](https://vuejs.org)
<img src="./.github/images/readme/retrieve-dark.png" alt="FileCodeBox 取件页面" width="860" />
</div>
## 一条命令开始
[English](./readme_en.md) | [在线演示](https://share.lanol.cn) | [部署教程](https://github.com/vastsa/FileCodeBox/wiki/部署教程) | [常见问题](https://github.com/vastsa/FileCodeBox/wiki/常见问题) | [QQ群: 739673698](https://qm.qq.com/q/PemPzhdEIM)
```bash
docker run -d --restart unless-stopped -p 12345:12345 -v ./data:/app/data --name filecodebox lanol/filecodebox:2.5.3 # x-release-please-version
# 🚀 一键部署
docker run -d -p 12345:12345 -v /opt/FileCodeBox:/app/data --name filecodebox lanol/filecodebox:latest
# 国内镜像(如果上面拉取缓慢): docker.cnb.cool/aixk/filecodebox
```
访问 `http://localhost:12345`,完成首次初始化。生产环境建议固定版本号;`latest` 指向最新正式版。
</div>
## 简单,但足够强大
---
## 目录
- [项目简介](#-项目简介)
- [功能特性](#-功能特性)
- [界面预览](#-界面预览)
- [快速开始](#-快速开始)
- [使用指南](#-使用指南)
- [开发指南](#-开发指南)
- [常见问题](#-常见问题)
- [贡献指南](#-贡献指南)
- [项目统计](#-项目统计)
- [免责声明](#-免责声明)
---
## 📝 项目简介
FileCodeBox 是一个轻量级的文件分享工具,基于 **FastAPI + Vue3** 开发。用户可以通过简单的方式匿名分享文本和文件,接收者只需输入提取码即可获取内容——就像从快递柜取出快递一样简单。
### 应用场景
| 场景 | 描述 |
|------|------|
| 📁 **临时文件分享** | 快速分享文件,无需注册登录 |
| 📝 **代码片段分享** | 分享代码、配置文件等文本内容 |
| 🕶️ **匿名文件传输** | 保护隐私的点对点传输 |
| 🔄 **跨设备传输** | 在不同设备间快速同步文件 |
| 💾 **临时存储** | 支持自定义过期时间的云存储 |
| 🌐 **私有服务** | 搭建企业或个人专属分享服务 |
---
## ✨ 功能特性
<table>
<tr>
<td width="33%" valign="top"><b>即传即取</b><br /><sub>文件与文本统一分享,支持拖拽、粘贴、批量与分片上传。</sub></td>
<td width="33%" valign="top"><b>按需失效</b><br /><sub>按时间、取件次数或永久保存,自动清理过期内容。</sub></td>
<td width="33%" valign="top"><b>数据自主</b><br /><sub>本地、S3、OneDrive、WebDAV 与 OpenDAL,数据留在自己的基础设施。</sub></td>
<td width="33%" valign="top">
### 🚀 轻量高效
- FastAPI + SQLite3 后端
- Vue3 + Element Plus 前端
- Docker 一键部署
- 资源占用极低
</td>
<td width="33%" valign="top">
### 🔒 安全可靠
- IP 上传频率限制
- 提取码错误次数限制
- 文件自动过期清理
- 支持管理员认证
</td>
<td width="33%" valign="top">
### 📤 便捷上传
- 拖拽上传
- 复制粘贴上传
- 命令行 curl 上传
- 批量文件上传
</td>
</tr>
<tr>
<td width="33%" valign="top">
### 🎫 灵活分享
- 随机/自定义提取码
- 可设置有效期(时间/次数)
- 支持永久有效
- 文本和文件统一管理
</td>
<td width="33%" valign="top">
### 💾 多存储支持
- 本地文件系统
- S3 兼容存储
- [OneDrive](./docs/guide/storage-onedrive.md)
- [OpenDAL](./docs/guide/storage-opendal.md)
</td>
<td width="33%" valign="top">
### 🌍 国际化
- 简体中文
- 繁体中文
- English
- 响应式设计 / 深色模式
</td>
</tr>
</table>
## 从分享,到管理
---
## 🖼️ 界面预览
> 前端源码仓库:[2024主题](https://github.com/vastsa/FileCodeBoxFronted) | [2023主题](https://github.com/vastsa/FileCodeBoxFronted2023)
<details open>
<summary><b>🎨 新版界面 (2024)</b></summary>
<br>
<div align="center">
<table>
<tr>
<td width="50%"><img src="./.github/images/readme/send.png" alt="文件发送页面" /></td>
<td width="50%"><img src="./.github/images/readme/dashboard.png" alt="管理仪表盘" /></td>
<td><img src="./.github/images/img_7.png" alt="文件上传"></td>
<td><img src="./.github/images/img_8.png" alt="文本分享"></td>
</tr>
<tr>
<td><img src="./.github/images/img_10.png" alt="文件管理"></td>
<td><img src="./.github/images/img_9.png" alt="系统设置"></td>
</tr>
<tr>
<td><img src="./.github/images/img_11.png" alt="移动端"></td>
<td><img src="./.github/images/img_12.png" alt="深色模式"></td>
</tr>
</table>
</div>
</details>
<p align="center">
<img src="./.github/images/readme/mobile-retrieve.png" alt="移动端取件" width="29%" />
&nbsp;&nbsp;
<img src="./.github/images/readme/mobile-send.png" alt="移动端发送" width="29%" />
&nbsp;&nbsp;
<img src="./.github/images/readme/mobile-files.png" alt="移动端管理" width="29%" />
</p>
<details>
<summary><b>📦 经典界面 (2023)</b></summary>
<br>
<div align="center">
<table>
<tr>
<td><img src="./.github/images/img.png" alt="首页"></td>
<td><img src="./.github/images/img_1.png" alt="上传"></td>
</tr>
<tr>
<td><img src="./.github/images/img_2.png" alt="管理"></td>
<td><img src="./.github/images/img_3.png" alt="设置"></td>
</tr>
</table>
</div>
</details>
---
## 🚀 快速开始
### Docker 部署(推荐)
**方式一:Docker CLI**
```bash
# Docker Hub(推荐)
docker run -d --restart always -p 12345:12345 -v /opt/FileCodeBox:/app/data --name filecodebox lanol/filecodebox:latest
# 国内镜像(如果 Docker Hub 拉取缓慢)
docker run -d --restart always -p 12345:12345 -v /opt/FileCodeBox:/app/data --name filecodebox docker.cnb.cool/aixk/filecodebox
```
**方式二:Docker Compose**
```yaml
services:
filecodebox:
image: lanol/filecodebox:latest
container_name: filecodebox
restart: unless-stopped
ports:
- "12345:12345"
volumes:
- ./data:/app/data
environment:
- WORKERS=4
- LOG_LEVEL=info
```
```bash
docker compose up -d
```
**环境变量说明**
| 变量 | 默认值 | 说明 |
|------|--------|------|
| `HOST` | `::` | 监听地址(支持 IPv4/IPv6 双栈) |
| `PORT` | `12345` | 服务端口 |
| `WORKERS` | `4` | 工作进程数(建议设为 CPU 核心数) |
| `LOG_LEVEL` | `info` | 日志级别:`debug` / `info` / `warning` / `error` |
### 反向代理配置
使用 Nginx 时,请添加以下配置以正确获取客户端 IP:
```nginx
location / {
proxy_pass http://127.0.0.1:12345;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
client_max_body_size 100m; # 根据需要调整上传大小限制
}
```
### 手动部署
```bash
# 1. 克隆项目
git clone https://github.com/vastsa/FileCodeBox.git
cd FileCodeBox
# 2. 安装依赖
pip install -r requirements.txt
# 3. 启动服务
python main.py
```
---
## 📖 使用指南
### 基础操作
| 操作 | 步骤 |
|------|------|
| **分享文件** | 打开网页 → 选择/拖拽文件 → 设置有效期 → 获取提取码 |
| **获取文件** | 打开网页 → 输入提取码 → 下载文件或查看文本 |
| **管理后台** | 访问 `/#/admin` → 输入密码 `FileCodeBox2023` |
### 命令行使用(curl)
<details>
<summary><b>点击展开 curl 使用示例</b></summary>
**上传文件**
```bash
# 基础上传(默认 1 天有效期)
curl -X POST "http://localhost:12345/share/file/" \
-F "file=@/path/to/file.txt"
# 指定 1 小时有效期
curl -X POST "http://localhost:12345/share/file/" \
-F "file=@/path/to/file.txt" \
-F "expire_value=1" \
-F "expire_style=hour"
# 指定下载 10 次后过期
curl -X POST "http://localhost:12345/share/file/" \
-F "file=@/path/to/file.txt" \
-F "expire_value=10" \
-F "expire_style=count"
```
**分享文本**
```bash
curl -X POST "http://localhost:12345/share/text/" \
-F "text=要分享的文本内容"
```
**下载文件**
```bash
curl -L "http://localhost:12345/share/select/?code=提取码" -o filename
```
**有效期参数**
| `expire_style` | 说明 |
|----------------|------|
| `day` | 天数 |
| `hour` | 小时 |
| `minute` | 分钟 |
| `count` | 下载次数 |
| `forever` | 永久有效 |
**返回示例**
```json
{
"code": 200,
"msg": "success",
"detail": {
"code": "abcd1234",
"name": "file.txt"
}
}
```
**需要认证时**(管理员关闭游客上传后)
```bash
# 1. 获取 token
curl -X POST "http://localhost:12345/admin/login" \
-H "Content-Type: application/json" \
-d '{"password": "FileCodeBox2023"}'
# 2. 携带 token 上传
curl -X POST "http://localhost:12345/share/file/" \
-H "Authorization: Bearer <token>" \
-F "file=@/path/to/file.txt"
```
</details>
---
## 🛠 开发指南
### 项目结构
```
FileCodeBox/
├── apps/ # 应用模块
│ ├── admin/ # 管理后台
│ └── base/ # 基础功能
├── core/ # 核心模块
├── data/ # 数据目录(运行时生成)
├── docs/ # 文档
└── main.py # 入口文件
```
### 本地开发
**后端**
```bash
pip install -r requirements.txt
python main.py
```
**前端**
```bash
# 前端仓库: https://github.com/vastsa/FileCodeBoxFronted
cd fcb-fronted
npm install
npm run dev
```
### 技术栈
| 类别 | 技术 |
|------|------|
| **后端框架** | FastAPI 0.128+ / Uvicorn |
| **数据库** | SQLite + Tortoise ORM |
| **数据验证** | Pydantic 2.x |
| **异步支持** | aiofiles / aiohttp / aioboto3 |
| **对象存储** | S3 协议 / OneDrive / OpenDAL |
| **前端框架** | Vue 3 + Element Plus + Vite |
| **运行环境** | Python 3.8+ / Node.js 18+ |
| **容器化** | Docker / Docker Compose |
---
## ❓ 常见问题
<details>
<summary><b>如何修改上传大小限制?</b></summary>
在管理面板中修改 `uploadSize` 配置项。如果使用 Nginx 反向代理,还需修改 `client_max_body_size`。
</details>
<details>
<summary><b>如何配置存储引擎?</b></summary>
在管理面板中选择存储引擎类型并配置相应参数。支持本地存储、S3、OneDrive、OpenDAL 等。
</details>
<details>
<summary><b>如何备份数据?</b></summary>
备份 `data` 目录即可,包含数据库和上传的文件。
</details>
<details>
<summary><b>如何修改管理员密码?</b></summary>
登录管理面板后,在系统设置中修改 `adminPassword` 配置项。
</details>
更多问题请访问 [Wiki](https://github.com/vastsa/FileCodeBox/wiki/常见问题) 或加入 [QQ群: 739673698](https://qm.qq.com/q/PemPzhdEIM)
---
## 🤝 贡献指南
欢迎提交 Issue 和 Pull Request!
```bash
# 1. Fork 并克隆
git clone https://github.com/your-username/FileCodeBox.git
# 2. 创建分支
git checkout -b feature/your-feature
# 3. 提交更改
git commit -m "feat: add your feature"
# 4. 推送并创建 PR
git push origin feature/your-feature
```
---
## 📊 项目统计
<div align="center">
`FastAPI` `Vue 3` `SQLite` `Docker` `S3` `WebDAV` `Dark Mode`
<a href="https://hellogithub.com/repository/75ad7ffedd404a6485b4d621ec5b47e6" target="_blank">
<img src="https://api.hellogithub.com/v1/widgets/recommend.svg?rid=75ad7ffedd404a6485b4d621ec5b47e6&claim_uid=beSz6INEkCM4mDH" alt="HelloGitHub" width="200">
</a>
![Repobeats](https://repobeats.axiom.co/api/embed/7a6c92f1d96ee57e6fb67f0df371528397b0c9ac.svg)
[![Star History](https://api.star-history.com/svg?repos=vastsa/FileCodeBox&type=Date)](https://star-history.com/#vastsa/FileCodeBox&Date)
</div>
## 继续了解
---
- [快速开始](https://fcb-docs.aiuo.net/guide/getting-started) · 部署、初始化与升级
- [存储配置](https://fcb-docs.aiuo.net/guide/storage) · 本地与对象存储
- [安全设置](https://fcb-docs.aiuo.net/guide/security) · 限流、会话与访问保护
- [API 文档](https://fcb-docs.aiuo.net/api/) · 上传、取件与管理接口
- [前端源码](https://github.com/vastsa/FileCodeBoxFronted) · 当前 2024 主题
## 🗓 更新计划
## 相关项目
- [ ] 2025 年新皮肤
- [ ] 文件收集功能
如果你也喜欢「盒子」系列的自托管工具,可以看看同作者的:
---
### [BokeBox](https://github.com/vastsa/BokeBox/) · 私人 AI 播客盒
## 📜 免责声明
把视频、链接或文稿丢进去,生成可听完的个人播客,支持自定义主持人设与声音。
本项目开源仅供学习交流使用,不得用于任何违法用途,否则后果自负,与作者无关。使用本项目时请保留项目地址和版权信息。
<p align="center">
<a href="https://github.com/vastsa/BokeBox/">
<img src="./.github/images/readme/bokebox/banner_zh.webp" alt="BokeBox 横幅" width="860" />
</a>
</p>
<p align="center">
<a href="https://github.com/vastsa/BokeBox/">
<img src="./.github/images/readme/bokebox/home_zh.webp" alt="BokeBox 首页" width="860" />
</a>
</p>
## 参与项目
欢迎 [提交 Issue](https://github.com/vastsa/FileCodeBox/issues/new/choose) 或 Pull Request。项目基于 [LGPL-3.0](./LICENSE) 发布。
## 免责声明
本项目仅供合法的文件与文本分享场景使用。请勿上传、存储或传播违法、侵权或未经授权的内容;使用者应自行承担部署、数据合规与内容管理责任。
---
<div align="center">
**如果 FileCodeBox 对你有帮助,欢迎点亮一个 Star。**
**如果觉得项目不错,欢迎 ⭐ Star 支持!**
Made with ❤️ by [vastsa](https://github.com/vastsa)
</div>
+428 -62
View File
@@ -1,105 +1,471 @@
<div align="center">
<img src="./docs/public/logo_small.png" alt="FileCodeBox" width="96" />
# FileCodeBox
### Share files like picking up a package
### Anonymous File & Text Sharing with Passcode
A lightweight, modern, self-hosted file sharing service. No account required—upload, share the passcode, and retrieve.
<img src="https://fastly.jsdelivr.net/gh/vastsa/FileCodeBox@V1.6/static/banners/img_1.png" alt="FileCodeBox Logo" width="400">
[Live Demo](https://share.lanol.cn) · [Documentation](https://fcb-docs.aiuo.net/en/) · [简体中文](./readme.md)
Share files like picking up a package — no registration required, just enter the passcode
[![Release](https://img.shields.io/github/v/release/vastsa/FileCodeBox?style=flat-square&color=111111)](https://github.com/vastsa/FileCodeBox/releases/latest)
[![Docker Pulls](https://img.shields.io/docker/pulls/lanol/filecodebox?style=flat-square&logo=docker&color=111111)](https://hub.docker.com/r/lanol/filecodebox)
[![Stars](https://img.shields.io/github/stars/vastsa/FileCodeBox?style=flat-square&logo=github&color=111111)](https://github.com/vastsa/FileCodeBox/stargazers)
[![License](https://img.shields.io/github/license/vastsa/FileCodeBox?style=flat-square&color=111111)](./LICENSE)
[![GitHub stars](https://img.shields.io/github/stars/vastsa/FileCodeBox?style=flat-square&logo=github)](https://github.com/vastsa/FileCodeBox/stargazers)
[![GitHub forks](https://img.shields.io/github/forks/vastsa/FileCodeBox?style=flat-square&logo=github)](https://github.com/vastsa/FileCodeBox/network)
[![GitHub issues](https://img.shields.io/github/issues/vastsa/FileCodeBox?style=flat-square&logo=github)](https://github.com/vastsa/FileCodeBox/issues)
[![GitHub license](https://img.shields.io/github/license/vastsa/FileCodeBox?style=flat-square)](https://github.com/vastsa/FileCodeBox/blob/master/LICENSE)
[![Docker Pulls](https://img.shields.io/docker/pulls/lanol/filecodebox?style=flat-square&logo=docker)](https://hub.docker.com/r/lanol/filecodebox)
<br />
[![Python](https://img.shields.io/badge/Python-3.8+-3776AB?style=flat-square&logo=python&logoColor=white)](https://www.python.org)
[![FastAPI](https://img.shields.io/badge/FastAPI-0.128+-009688?style=flat-square&logo=fastapi&logoColor=white)](https://fastapi.tiangolo.com)
[![Vue.js](https://img.shields.io/badge/Vue.js-3.x-4FC08D?style=flat-square&logo=vue.js&logoColor=white)](https://vuejs.org)
<img src="./.github/images/readme/retrieve-dark.png" alt="FileCodeBox retrieval screen" width="860" />
</div>
## Start with one command
[简体中文](./README.md) | [Live Demo](https://share.lanol.cn) | [Documentation](https://github.com/vastsa/FileCodeBox/wiki/Deployment-Guide) | [FAQ](https://github.com/vastsa/FileCodeBox/wiki/FAQ)
```bash
docker run -d --restart unless-stopped -p 12345:12345 -v ./data:/app/data --name filecodebox lanol/filecodebox:2.5.3 # x-release-please-version
# 🚀 Quick Deploy
docker run -d -p 12345:12345 -v /opt/FileCodeBox:/app/data --name filecodebox lanol/filecodebox:latest
# China Mirror (if slow): docker.cnb.cool/aixk/filecodebox
```
Open `http://localhost:12345` and complete first-run setup. Pin a version in production; `latest` tracks the newest stable release.
</div>
## Simple, yet capable
---
## Table of Contents
- [Introduction](#-introduction)
- [Features](#-features)
- [Screenshots](#-screenshots)
- [Quick Start](#-quick-start)
- [Usage Guide](#-usage-guide)
- [Development](#-development)
- [FAQ](#-faq)
- [Contributing](#-contributing)
- [Statistics](#-statistics)
- [Disclaimer](#-disclaimer)
---
## 📝 Introduction
FileCodeBox is a lightweight file sharing tool built with **FastAPI + Vue3**. Users can anonymously share text and files, and recipients only need to enter a passcode to retrieve the content — just like picking up a package from a locker.
### Use Cases
| Scenario | Description |
|----------|-------------|
| 📁 **Temporary File Sharing** | Quick file sharing without registration |
| 📝 **Code Snippet Sharing** | Share code, config files, and text content |
| 🕶️ **Anonymous Transfer** | Privacy-protected peer-to-peer transfer |
| 🔄 **Cross-Device Transfer** | Quickly sync files between devices |
| 💾 **Temporary Storage** | Cloud storage with custom expiration |
| 🌐 **Private Service** | Build your own enterprise or personal sharing service |
---
## ✨ Features
<table>
<tr>
<td width="33%" valign="top"><b>Share instantly</b><br /><sub>Files and text in one flow, with drag, paste, batch, and chunked uploads.</sub></td>
<td width="33%" valign="top"><b>Expire on your terms</b><br /><sub>Expire by time or retrieval count, keep forever, and clean up automatically.</sub></td>
<td width="33%" valign="top"><b>Own your data</b><br /><sub>Local, S3, OneDrive, WebDAV, and OpenDAL storage on infrastructure you control.</sub></td>
<td width="33%" valign="top">
### 🚀 Lightweight & Fast
- FastAPI + SQLite3 backend
- Vue3 + Element Plus frontend
- One-click Docker deployment
- Minimal resource usage
</td>
<td width="33%" valign="top">
### 🔒 Secure & Reliable
- IP upload rate limiting
- Passcode attempt limiting
- Auto file expiration cleanup
- Admin authentication support
</td>
<td width="33%" valign="top">
### 📤 Easy Upload
- Drag & drop upload
- Copy & paste upload
- Command line curl upload
- Batch file upload
</td>
</tr>
<tr>
<td width="33%" valign="top">
### 🎫 Flexible Sharing
- Random / custom passcodes
- Set expiration (time/count)
- Permanent validity support
- Unified text & file management
</td>
<td width="33%" valign="top">
### 💾 Multiple Storage
- Local file system
- S3-compatible storage
- [OneDrive](./docs/guide/storage-onedrive.md)
- [OpenDAL](./docs/guide/storage-opendal.md)
</td>
<td width="33%" valign="top">
### 🌍 Internationalization
- Simplified Chinese
- Traditional Chinese
- English
- Responsive design / Dark mode
</td>
</tr>
</table>
## From sharing to administration
---
## 🖼️ Screenshots
> Frontend repositories: [2024 Theme](https://github.com/vastsa/FileCodeBoxFronted) | [2023 Theme](https://github.com/vastsa/FileCodeBoxFronted2023)
<details open>
<summary><b>🎨 New Interface (2024)</b></summary>
<br>
<div align="center">
<table>
<tr>
<td width="50%"><img src="./.github/images/readme/send.png" alt="File sharing screen" /></td>
<td width="50%"><img src="./.github/images/readme/dashboard.png" alt="Admin dashboard" /></td>
<td><img src="./.github/images/img_7.png" alt="File Upload"></td>
<td><img src="./.github/images/img_8.png" alt="Text Share"></td>
</tr>
<tr>
<td><img src="./.github/images/img_10.png" alt="File Management"></td>
<td><img src="./.github/images/img_9.png" alt="System Settings"></td>
</tr>
<tr>
<td><img src="./.github/images/img_11.png" alt="Mobile View"></td>
<td><img src="./.github/images/img_12.png" alt="Dark Mode"></td>
</tr>
</table>
</div>
</details>
<p align="center">
<img src="./.github/images/readme/mobile-retrieve.png" alt="Mobile retrieval" width="29%" />
&nbsp;&nbsp;
<img src="./.github/images/readme/mobile-send.png" alt="Mobile sharing" width="29%" />
&nbsp;&nbsp;
<img src="./.github/images/readme/mobile-files.png" alt="Mobile administration" width="29%" />
</p>
<details>
<summary><b>📦 Classic Interface (2023)</b></summary>
<br>
<div align="center">
<table>
<tr>
<td><img src="./.github/images/img.png" alt="Home"></td>
<td><img src="./.github/images/img_1.png" alt="Upload"></td>
</tr>
<tr>
<td><img src="./.github/images/img_2.png" alt="Management"></td>
<td><img src="./.github/images/img_3.png" alt="Settings"></td>
</tr>
</table>
</div>
</details>
---
## 🚀 Quick Start
### Docker Deployment (Recommended)
**Option 1: Docker CLI**
```bash
# Docker Hub (Recommended)
docker run -d --restart always -p 12345:12345 -v /opt/FileCodeBox:/app/data --name filecodebox lanol/filecodebox:latest
# China Mirror (if Docker Hub is slow)
docker run -d --restart always -p 12345:12345 -v /opt/FileCodeBox:/app/data --name filecodebox docker.cnb.cool/aixk/filecodebox
```
**Option 2: Docker Compose**
```yaml
services:
filecodebox:
image: lanol/filecodebox:latest
container_name: filecodebox
restart: unless-stopped
ports:
- "12345:12345"
volumes:
- ./data:/app/data
environment:
- WORKERS=4
- LOG_LEVEL=info
```
```bash
docker compose up -d
```
**Environment Variables**
| Variable | Default | Description |
|----------|---------|-------------|
| `HOST` | `::` | Listen address (supports IPv4/IPv6 dual-stack) |
| `PORT` | `12345` | Service port |
| `WORKERS` | `4` | Worker processes (recommended: CPU cores) |
| `LOG_LEVEL` | `info` | Log level: `debug` / `info` / `warning` / `error` |
### Reverse Proxy Configuration
When using Nginx, add the following configuration to properly obtain client IP:
```nginx
location / {
proxy_pass http://127.0.0.1:12345;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
client_max_body_size 100m; # Adjust upload size limit as needed
}
```
### Manual Deployment
```bash
# 1. Clone the repository
git clone https://github.com/vastsa/FileCodeBox.git
cd FileCodeBox
# 2. Install dependencies
pip install -r requirements.txt
# 3. Start the service
python main.py
```
---
## 📖 Usage Guide
### Basic Operations
| Operation | Steps |
|-----------|-------|
| **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` |
### Command Line Usage (curl)
<details>
<summary><b>Click to expand curl examples</b></summary>
**Upload File**
```bash
# Basic upload (default 1 day expiration)
curl -X POST "http://localhost:12345/share/file/" \
-F "file=@/path/to/file.txt"
# Set 1 hour expiration
curl -X POST "http://localhost:12345/share/file/" \
-F "file=@/path/to/file.txt" \
-F "expire_value=1" \
-F "expire_style=hour"
# Set expiration after 10 downloads
curl -X POST "http://localhost:12345/share/file/" \
-F "file=@/path/to/file.txt" \
-F "expire_value=10" \
-F "expire_style=count"
```
**Share Text**
```bash
curl -X POST "http://localhost:12345/share/text/" \
-F "text=Text content to share"
```
**Download File**
```bash
curl -L "http://localhost:12345/share/select/?code=PASSCODE" -o filename
```
**Expiration Parameters**
| `expire_style` | Description |
|----------------|-------------|
| `day` | Days |
| `hour` | Hours |
| `minute` | Minutes |
| `count` | Download count |
| `forever` | Never expire |
**Response Example**
```json
{
"code": 200,
"msg": "success",
"detail": {
"code": "abcd1234",
"name": "file.txt"
}
}
```
**When Authentication Required** (after admin disables guest upload)
```bash
# 1. Get token
curl -X POST "http://localhost:12345/admin/login" \
-H "Content-Type: application/json" \
-d '{"password": "FileCodeBox2023"}'
# 2. Upload with token
curl -X POST "http://localhost:12345/share/file/" \
-H "Authorization: Bearer <token>" \
-F "file=@/path/to/file.txt"
```
</details>
---
## 🛠 Development
### Project Structure
```
FileCodeBox/
├── apps/ # Application modules
│ ├── admin/ # Admin backend
│ └── base/ # Base functionality
├── core/ # Core modules
├── data/ # Data directory (generated at runtime)
├── docs/ # Documentation
└── main.py # Entry point
```
### Local Development
**Backend**
```bash
pip install -r requirements.txt
python main.py
```
**Frontend**
```bash
# Frontend repo: https://github.com/vastsa/FileCodeBoxFronted
cd fcb-fronted
npm install
npm run dev
```
### Tech Stack
| Category | Technology |
|----------|------------|
| **Backend Framework** | FastAPI 0.128+ / Uvicorn |
| **Database** | SQLite + Tortoise ORM |
| **Data Validation** | Pydantic 2.x |
| **Async Support** | aiofiles / aiohttp / aioboto3 |
| **Object Storage** | S3 Protocol / OneDrive / OpenDAL |
| **Frontend Framework** | Vue 3 + Element Plus + Vite |
| **Runtime** | Python 3.8+ / Node.js 18+ |
| **Containerization** | Docker / Docker Compose |
---
## ❓ FAQ
<details>
<summary><b>How to modify upload size limit?</b></summary>
Modify the `uploadSize` configuration in the admin panel. If using Nginx reverse proxy, also modify `client_max_body_size`.
</details>
<details>
<summary><b>How to configure storage engine?</b></summary>
Select the storage engine type and configure parameters in the admin panel. Supports local storage, S3, OneDrive, OpenDAL, etc.
</details>
<details>
<summary><b>How to backup data?</b></summary>
Backup the `data` directory, which contains the database and uploaded files.
</details>
<details>
<summary><b>How to change admin password?</b></summary>
After logging into the admin panel, modify the `adminPassword` configuration in system settings.
</details>
For more questions, visit [Wiki](https://github.com/vastsa/FileCodeBox/wiki/FAQ)
---
## 🤝 Contributing
Issues and Pull Requests are welcome!
```bash
# 1. Fork and clone
git clone https://github.com/your-username/FileCodeBox.git
# 2. Create branch
git checkout -b feature/your-feature
# 3. Commit changes
git commit -m "feat: add your feature"
# 4. Push and create PR
git push origin feature/your-feature
```
---
## 📊 Statistics
<div align="center">
`FastAPI` `Vue 3` `SQLite` `Docker` `S3` `WebDAV` `Dark Mode`
<a href="https://hellogithub.com/repository/75ad7ffedd404a6485b4d621ec5b47e6" target="_blank">
<img src="https://api.hellogithub.com/v1/widgets/recommend.svg?rid=75ad7ffedd404a6485b4d621ec5b47e6&claim_uid=beSz6INEkCM4mDH" alt="HelloGitHub" width="200">
</a>
![Repobeats](https://repobeats.axiom.co/api/embed/7a6c92f1d96ee57e6fb67f0df371528397b0c9ac.svg)
[![Star History](https://api.star-history.com/svg?repos=vastsa/FileCodeBox&type=Date)](https://star-history.com/#vastsa/FileCodeBox&Date)
</div>
## Learn more
---
- [Getting started](https://fcb-docs.aiuo.net/en/guide/getting-started) · deployment, setup, and upgrades
- [Storage](https://fcb-docs.aiuo.net/en/guide/storage) · local and object storage
- [Security](https://fcb-docs.aiuo.net/en/guide/security) · rate limits, sessions, and access protection
- [API reference](https://fcb-docs.aiuo.net/en/api/) · upload, retrieval, and administration
- [Frontend source](https://github.com/vastsa/FileCodeBoxFronted) · the active 2024 theme
## 🗓 Roadmap
## Related projects
- [ ] 2025 New Theme
- [ ] File Collection Feature
If you enjoy self-hosted “box” tools, also check out this project from the same author:
---
### [BokeBox](https://github.com/vastsa/BokeBox/) · Private AI Podcast Box
## 📜 Disclaimer
Drop in videos, links, or drafts, and get listen-worthy personal podcasts with custom host persona and voice.
This project is open-source for learning and communication purposes only. It should not be used for any illegal purposes. The author is not responsible for any consequences. Please retain the project address and copyright information when using it.
<p align="center">
<a href="https://github.com/vastsa/BokeBox/">
<img src="./.github/images/readme/bokebox/banner_en.webp" alt="BokeBox banner" width="860" />
</a>
</p>
<p align="center">
<a href="https://github.com/vastsa/BokeBox/">
<img src="./.github/images/readme/bokebox/home_en.webp" alt="BokeBox home" width="860" />
</a>
</p>
## Contributing
[Issues](https://github.com/vastsa/FileCodeBox/issues/new/choose) and pull requests are welcome. FileCodeBox is released under [LGPL-3.0](./LICENSE).
## Disclaimer
Use FileCodeBox only for lawful file and text sharing. Do not upload, store, or distribute illegal, infringing, or unauthorized content. Operators are responsible for deployment security, data compliance, and content moderation.
---
<div align="center">
**If FileCodeBox helps you, consider leaving a Star.**
**If you find this project helpful, please give it a ⭐ Star!**
Made with ❤️ by [vastsa](https://github.com/vastsa)
</div>
-40
View File
@@ -1,40 +0,0 @@
{
"$schema": "https://raw.githubusercontent.com/googleapis/release-please/main/schemas/config.json",
"packages": {
".": {
"release-type": "simple",
"component": "filecodebox",
"package-name": "filecodebox",
"include-v-in-tag": true,
"include-component-in-tag": false,
"version-file": "VERSION",
"changelog-path": "docs/changelog.md",
"extra-files": [
{
"type": "generic",
"path": "docs/en/changelog.md"
},
{
"type": "generic",
"path": "docker-compose.yml"
},
{
"type": "generic",
"path": "readme.md"
},
{
"type": "generic",
"path": "readme_en.md"
},
{
"type": "generic",
"path": "docs/index.md"
},
{
"type": "generic",
"path": "docs/en/index.md"
}
]
}
}
}
+4 -5
View File
@@ -1,9 +1,8 @@
aioboto3==15.5.0
aiohttp==3.14.2
aiohttp==3.13.3
aiofiles==25.1.0
fastapi==0.139.2
starlette==1.3.1
fastapi==0.128.0
pydantic==2.12.5
uvicorn==0.51.0
uvicorn==0.40.0
tortoise-orm==0.25.3
python-multipart==0.0.32
python-multipart==0.0.21
+6
View File
@@ -0,0 +1,6 @@
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))
-268
View File
@@ -1,268 +0,0 @@
import asyncio
import copy
import unittest
import apps.admin.services as admin_services
import apps.admin.views as admin_views
import apps.admin.dependencies as admin_dependencies
import core.config as core_config
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 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",
"loginCount": "4",
"loginMinute": "20",
"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["loginCount"], 4)
self.assertEqual(options["loginMinute"], 20)
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)
def test_configured_session_lifetime_is_returned_by_login(self):
settings.admin_token = hash_password("admin-password")
settings.jwt_secret = "j" * 48
settings.adminSessionExpire = 90 * 24 * 60 * 60
original_time = admin_dependencies.time.time
admin_dependencies.time.time = lambda: 1_800_000_000
try:
response = asyncio.run(
admin_views.login(LoginData(password="admin-password"))
)
payload = verify_token(response.detail["token"])
finally:
admin_dependencies.time.time = original_time
self.assertEqual(response.detail["expires_in"], 90 * 24 * 60 * 60)
self.assertEqual(
response.detail["expires_at"], 1_800_000_000 + 90 * 24 * 60 * 60
)
self.assertEqual(payload["exp"], response.detail["expires_at"])
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_storage_limit_rejects_negative_values(self):
settings.user_config = copy.deepcopy(DEFAULT_CONFIG)
with self.assertRaises(HTTPException) as context:
asyncio.run(ConfigService().update_config({"storageLimit": -1}))
self.assertEqual(context.exception.status_code, 400)
def test_admin_session_lifetime_rejects_out_of_range_values(self):
settings.user_config = copy.deepcopy(DEFAULT_CONFIG)
for invalid_value in (0, 86399, 90000, 365 * 24 * 60 * 60 + 1):
with self.subTest(invalid_value=invalid_value):
with self.assertRaises(HTTPException) as context:
asyncio.run(
ConfigService().update_config(
{"adminSessionExpire": invalid_value}
)
)
self.assertEqual(context.exception.status_code, 400)
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"])
+3 -12
View File
@@ -3,7 +3,7 @@ import unittest
from fastapi import HTTPException
from core.settings import BASE_DIR, settings
from core.settings import settings
from main import index, resolve_theme_file
@@ -16,21 +16,12 @@ 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", self.get_theme_index_asset("themes/2023")
)
theme_2023_asset = resolve_theme_file("assets", "index-CxMsK_Ni.js")
settings.themesSelect = "themes/2024"
theme_2024_asset = resolve_theme_file(
"assets", self.get_theme_index_asset("themes/2024")
)
theme_2024_asset = resolve_theme_file("assets", "index-DjzJA_Oj.js")
self.assertIn("themes/2023/assets", str(theme_2023_asset))
self.assertIn("themes/2024/assets", str(theme_2024_asset))
-26
View File
@@ -1,26 +0,0 @@
import unittest
from core.settings import settings
from main import build_public_config, build_public_meta
class AdminAddressPublicConfigTests(unittest.TestCase):
def setUp(self):
self._original_user_config = dict(settings.user_config)
def tearDown(self):
settings.user_config = self._original_user_config
def test_admin_address_is_exposed_as_strict_binary_flag(self):
cases = ((0, 0), (1, 1), ("0", 0), ("1", 1))
for configured_value, expected_value in cases:
with self.subTest(configured_value=configured_value):
settings.showAdminAddr = configured_value
public_value = build_public_config()["show_admin_address"]
feature_value = build_public_meta()["features"]["adminAddressVisible"]
self.assertIs(type(public_value), int)
self.assertEqual(public_value, expected_value)
self.assertIs(feature_value, bool(expected_value))
-218
View File
@@ -1,218 +0,0 @@
import asyncio
import datetime
import unittest
from unittest.mock import patch
from tortoise import Tortoise
from apps.base.models import FileCodes
from apps.base import views
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
class FakeStorage:
direct_url_calls = 0
async def get_file_url(self, file_code):
self.direct_url_calls += 1
return "https://storage.example/reusable-url"
async def get_file_response(self, file_code):
return {"downloaded": file_code.code}
class FakeRateLimit:
def __init__(self):
self.seen_ips = []
def add_ip(self, ip):
self.seen_ips.append(ip)
class ShareUsageSecurityTests(unittest.TestCase):
def test_new_installations_default_to_secret_codes(self):
self.assertEqual(DEFAULT_CONFIG["code_generate_type"], "secret")
self.assertEqual(
parse_setup_options({"expireStyle": ["day"]})["code_generate_type"],
"secret",
)
self.assertIn('<option value="secret" selected>', build_setup_page())
def test_atomic_usage_download_and_metadata_limits(self):
asyncio.run(self._run_scenario())
async def _run_scenario(self):
original_config = dict(settings.user_config)
original_metadata_limit = views.ip_limit["metadata"]
settings.file_storage = "local"
settings.jwt_secret = "test-download-secret"
await Tortoise.init(
config={
"connections": {
"default": {
"engine": "tortoise.backends.sqlite",
"credentials": {"file_path": ":memory:"},
}
},
"apps": {
"models": {
"models": ["apps.base.models"],
"default_connection": "default",
}
},
"use_tz": False,
"timezone": "Asia/Shanghai",
}
)
await Tortoise.generate_schemas()
try:
await self._assert_count_consumption_is_atomic()
await self._assert_time_expiration_and_usage_are_atomic()
await self._assert_download_url_is_single_use()
await self._assert_text_share_downloads_as_txt()
await self._assert_limited_files_do_not_expose_direct_urls()
await self._assert_metadata_counts_all_attempts()
finally:
views.ip_limit["metadata"] = original_metadata_limit
settings.user_config = original_config
await Tortoise.close_connections()
async def _assert_count_consumption_is_atomic(self):
record = await FileCodes.create(
code="atomic",
prefix="atomic",
suffix=".txt",
expired_count=1,
expired_at=await get_now() + datetime.timedelta(days=1),
)
stale_copies = await asyncio.gather(
*(FileCodes.get(id=record.id) for _ in range(20))
)
consumed = await asyncio.gather(
*(views.consume_file_usage(item) for item in stale_copies)
)
await record.refresh_from_db()
self.assertEqual(sum(consumed), 1)
self.assertEqual(record.expired_count, 0)
self.assertEqual(record.used_count, 1)
async def _assert_time_expiration_and_usage_are_atomic(self):
valid = await FileCodes.create(
code="time-valid",
text="valid",
expired_count=-1,
expired_at=await get_now() + datetime.timedelta(minutes=5),
)
expired = await FileCodes.create(
code="time-expired",
text="expired",
expired_count=-1,
expired_at=await get_now() - datetime.timedelta(seconds=1),
)
valid_copies = await asyncio.gather(
*(FileCodes.get(id=valid.id) for _ in range(20))
)
consumed = await asyncio.gather(
*(views.consume_file_usage(item) for item in valid_copies)
)
self.assertTrue(all(consumed))
self.assertFalse(await views.consume_file_usage(expired))
await valid.refresh_from_db()
await expired.refresh_from_db()
self.assertEqual(valid.expired_count, -1)
self.assertEqual(valid.used_count, 20)
self.assertEqual(expired.used_count, 0)
async def _assert_download_url_is_single_use(self):
record = await FileCodes.create(
code="single-use",
prefix="report",
suffix=".pdf",
expired_count=1,
expired_at=await get_now() + datetime.timedelta(days=1),
)
key = await get_select_token(record.code)
with patch.dict(views.storages, {"local": FakeStorage}):
selected = await views.select_file(
data=views.SelectFileModel(code=record.code), ip="127.0.0.1"
)
await record.refresh_from_db()
self.assertEqual(selected.detail["expired_count"], 1)
self.assertEqual(record.expired_count, 1)
self.assertEqual(record.used_count, 0)
first = await views.download_file(key=key, code=record.code, ip="127.0.0.1")
second = await views.download_file(key=key, code=record.code, ip="127.0.0.1")
self.assertEqual(first, {"downloaded": record.code})
self.assertEqual(second.code, 404)
await record.refresh_from_db()
self.assertEqual(record.expired_count, 0)
self.assertEqual(record.used_count, 1)
async def _assert_text_share_downloads_as_txt(self):
record = await FileCodes.create(
code="text-download",
prefix="TAG",
text="hello, 文本直链",
expired_count=-1,
expired_at=None,
)
with patch.dict(views.storages, {"local": FakeStorage}):
response = await views.get_code_file(
code=record.code, ip="127.0.0.1"
)
self.assertEqual(response.status_code, 200)
self.assertEqual(response.body.decode("utf-8"), record.text)
self.assertEqual(response.media_type, "text/plain")
self.assertEqual(
response.headers["content-disposition"],
"attachment; filename*=UTF-8''TAG.txt",
)
await record.refresh_from_db()
self.assertEqual(record.used_count, 1)
async def _assert_limited_files_do_not_expose_direct_urls(self):
record = await FileCodes.create(
code="proxy-only",
prefix="archive",
suffix=".zip",
expired_count=2,
expired_at=await get_now() + datetime.timedelta(days=1),
)
storage = FakeStorage()
detail = await views.build_select_detail(record, storage)
self.assertTrue(detail["download_url"].startswith("/share/download?"))
self.assertEqual(storage.direct_url_calls, 0)
async def _assert_metadata_counts_all_attempts(self):
await FileCodes.create(
code="metadata",
text="hello",
expired_count=-1,
expired_at=None,
)
limiter = FakeRateLimit()
views.ip_limit["metadata"] = limiter
success = await views.get_file_metadata(code="metadata", ip="192.0.2.1")
missing = await views.get_file_metadata(code="missing", ip="192.0.2.1")
self.assertEqual(success.code, 200)
self.assertEqual(missing.code, 404)
self.assertEqual(limiter.seen_ips, ["192.0.2.1", "192.0.2.1"])
if __name__ == "__main__":
unittest.main()
-91
View File
@@ -1,91 +0,0 @@
import asyncio
import unittest
from fastapi import HTTPException
from tortoise import Tortoise
from apps.base.models import FileCodes, StorageReservation
from apps.base.quota import get_storage_usage, release_storage, reserve_storage
from core.settings import settings
from core.utils import get_now
class StorageQuotaTests(unittest.TestCase):
def test_quota_reservations_are_atomic_and_reusable(self):
asyncio.run(self._run_scenario())
async def _run_scenario(self):
original_config = dict(settings.user_config)
settings.storageLimit = 100
await Tortoise.init(
config={
"connections": {
"default": {
"engine": "tortoise.backends.sqlite",
"credentials": {"file_path": ":memory:"},
}
},
"apps": {
"models": {
"models": ["apps.base.models"],
"default_connection": "default",
}
},
"use_tz": False,
"timezone": "Asia/Shanghai",
}
)
await Tortoise.generate_schemas()
try:
await FileCodes.create(code="existing", size=60, expired_count=-1)
results = await asyncio.gather(
reserve_storage("upload-a", 30, 300),
reserve_storage("upload-b", 30, 300),
return_exceptions=True,
)
self.assertEqual(sum(result is None for result in results), 1)
rejected = [result for result in results if isinstance(result, HTTPException)]
self.assertEqual(len(rejected), 1)
self.assertEqual(rejected[0].status_code, 507)
usage = await get_storage_usage()
self.assertEqual(usage["used"], 60)
self.assertEqual(usage["reserved"], 30)
self.assertEqual(usage["available"], 10)
active = await StorageReservation.first()
await release_storage(active.token)
await reserve_storage("upload-c", 40, 300)
self.assertEqual((await get_storage_usage())["available"], 0)
settings.storageLimit = 0
await reserve_storage("unlimited", 10_000, 300)
self.assertFalse(
await StorageReservation.filter(token="unlimited").exists()
)
settings.storageLimit = 100
expired = await StorageReservation.get(token="upload-c")
expired.expires_at = await get_now()
await expired.save(update_fields=["expires_at"])
await reserve_storage("upload-d", 40, 300)
self.assertEqual((await get_storage_usage())["reserved"], 40)
await release_storage("upload-d")
same_token_results = await asyncio.gather(
*(reserve_storage("same-upload", 40, 300) for _ in range(10)),
return_exceptions=True,
)
self.assertTrue(all(result is None for result in same_token_results))
self.assertEqual(
await StorageReservation.filter(token="same-upload").count(), 1
)
finally:
settings.user_config = original_config
await Tortoise.close_connections()
if __name__ == "__main__":
unittest.main()
-141
View File
@@ -1,141 +0,0 @@
import asyncio
import hashlib
import time
import unittest
from unittest.mock import patch
from fastapi import HTTPException
from tortoise import Tortoise
from apps.base import views
from apps.base.models import FileCodes
from apps.base.quota import _detect_sql_dialect, _sql_placeholders, reserve_storage
from apps.base.utils import validate_expire_style
from core.settings import settings
from core.utils import get_select_token
class FakeStorage:
async def get_file_url(self, file_code):
return f"https://example.invalid/{file_code.code}"
async def get_file_response(self, file_code):
return {"downloaded": file_code.code}
class SecurityPatchTests(unittest.TestCase):
def test_validate_expire_style_rejects_unknown_mode(self):
original = dict(settings.user_config)
try:
settings.expireStyle = ["day", "count"]
self.assertEqual(validate_expire_style("day"), "day")
with self.assertRaises(HTTPException) as ctx:
validate_expire_style("forever")
self.assertEqual(ctx.exception.status_code, 400)
finally:
settings.user_config = original
def test_sql_placeholders_follow_dialect(self):
asyncio.run(self._assert_sql_placeholders())
async def _assert_sql_placeholders(self):
await Tortoise.init(
config={
"connections": {
"default": {
"engine": "tortoise.backends.sqlite",
"credentials": {"file_path": ":memory:"},
}
},
"apps": {
"models": {
"models": ["apps.base.models"],
"default_connection": "default",
}
},
"use_tz": False,
"timezone": "Asia/Shanghai",
}
)
try:
self.assertEqual(_detect_sql_dialect(), "sqlite")
self.assertEqual(_sql_placeholders(3), ["?", "?", "?"])
with patch(
"apps.base.quota._detect_sql_dialect", return_value="postgres"
):
self.assertEqual(_sql_placeholders(3), ["$1", "$2", "$3"])
with patch("apps.base.quota._detect_sql_dialect", return_value="mysql"):
self.assertEqual(_sql_placeholders(2), ["%s", "%s"])
# sqlite 下 reserve_storage 仍可正常工作
settings.storageLimit = 100
await Tortoise.generate_schemas()
await reserve_storage("patch-token", 10, 300)
finally:
settings.storageLimit = 0
await Tortoise.close_connections()
def test_download_token_accepts_previous_window(self):
asyncio.run(self._assert_download_token_window())
async def _assert_download_token_window(self):
original = dict(settings.user_config)
settings.jwt_secret = "test-secret-key-for-token-window"
now = 2_000_500 # 落在窗口 2000 内
code = "ABCDE"
with patch("core.utils.time.time", return_value=now):
current = await get_select_token(code, offset=0)
previous = await get_select_token(code, offset=1)
expected_current = hashlib.sha256(
f"{code}{int(now / 1000)}000{settings.jwt_secret}".encode()
).hexdigest()
expected_previous = hashlib.sha256(
f"{code}{int(now / 1000) - 1}000{settings.jwt_secret}".encode()
).hexdigest()
self.assertEqual(current, expected_current)
self.assertEqual(previous, expected_previous)
await Tortoise.init(
config={
"connections": {
"default": {
"engine": "tortoise.backends.sqlite",
"credentials": {"file_path": ":memory:"},
}
},
"apps": {
"models": {
"models": ["apps.base.models"],
"default_connection": "default",
}
},
"use_tz": False,
"timezone": "Asia/Shanghai",
}
)
await Tortoise.generate_schemas()
try:
await FileCodes.create(
code=code,
prefix="demo",
suffix=".txt",
expired_count=-1,
size=1,
)
# 模拟请求进入下一窗口,但仍携带上一窗口 token
next_window = now + 1000
with patch("core.utils.time.time", return_value=next_window):
with patch.dict(views.storages, {"local": FakeStorage}):
result = await views.download_file(
key=current, code=code, ip="127.0.0.1"
)
self.assertEqual(result, {"downloaded": code})
finally:
settings.user_config = original
await Tortoise.close_connections()
if __name__ == "__main__":
unittest.main()
+271
View File
@@ -0,0 +1,271 @@
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)
-103
View File
@@ -1,103 +0,0 @@
import asyncio
import unittest
from pathlib import Path
from fastapi import HTTPException
from apps.admin import views as admin_views
from apps.admin.schemas import LoginData
from apps.base.dependencies import IPRateLimit
from apps.base.file_validation import detect_file_kind, validate_file_magic, validate_file_type
from apps.base.utils import ip_limit
from core.settings import settings
from core.utils import hash_password
class SettingsOverrideMixin:
def setUp(self):
self._original_user_config = dict(settings.user_config)
def tearDown(self):
settings.user_config = self._original_user_config
class MagicBytesTests(SettingsOverrideMixin, unittest.TestCase):
def test_detects_common_signatures(self):
self.assertEqual(detect_file_kind(b"\x89PNG\r\n\x1a\nxxxx").name, "png")
self.assertEqual(detect_file_kind(b"\xff\xd8\xff\xe0xxxx").name, "jpg")
self.assertEqual(detect_file_kind(b"%PDF-1.7").name, "pdf")
self.assertEqual(detect_file_kind(b"PK\x03\x04xxxx").name, "zip")
self.assertEqual(detect_file_kind(b"RIFF\x00\x00\x00\x00WEBPxxxx").name, "webp")
self.assertEqual(detect_file_kind(b"\x00\x00\x00\x18ftypmp42").name, "mp4")
def test_rejects_extension_spoofing(self):
settings.allowed_file_types = ["*"]
with self.assertRaises(HTTPException) as ctx:
validate_file_magic("photo.png", "image/png", b"MZ" + b"\x00" * 20)
self.assertEqual(ctx.exception.status_code, 403)
self.assertIn("扩展名", ctx.exception.detail)
def test_rejects_content_type_spoofing(self):
settings.allowed_file_types = ["*"]
with self.assertRaises(HTTPException) as ctx:
validate_file_magic("blob.bin", "image/png", b"MZ" + b"\x00" * 20)
self.assertEqual(ctx.exception.status_code, 403)
def test_accepts_matching_png(self):
settings.allowed_file_types = [".png", "image/*"]
validate_file_magic("a.png", "image/png", b"\x89PNG\r\n\x1a\nxxxx")
def test_whitelist_still_enforced(self):
settings.allowed_file_types = [".png"]
with self.assertRaises(HTTPException):
validate_file_type("a.exe", "application/x-msdownload")
class LoginRateLimitTests(SettingsOverrideMixin, unittest.TestCase):
def setUp(self):
super().setUp()
settings.admin_token = hash_password("correct-password-123")
settings.jwt_secret = "j" * 48
settings.loginCount = 3
settings.loginMinute = 15
self._original_login_limiter = ip_limit["login"]
ip_limit["login"] = IPRateLimit(count=3, minutes=15)
def tearDown(self):
ip_limit["login"] = self._original_login_limiter
super().tearDown()
def test_failed_logins_are_rate_limited(self):
async def attempt(password: str):
return await admin_views.login(
data=LoginData(password=password), ip="203.0.113.10"
)
for _ in range(3):
with self.assertRaises(HTTPException) as ctx:
asyncio.run(attempt("wrong-password"))
self.assertEqual(ctx.exception.status_code, 401)
self.assertFalse(ip_limit["login"].check_ip("203.0.113.10"))
def test_successful_login_does_not_consume_failure_quota(self):
result = asyncio.run(
admin_views.login(
data=LoginData(password="correct-password-123"), ip="198.51.100.8"
)
)
self.assertIn("token", result.detail)
self.assertTrue(ip_limit["login"].check_ip("198.51.100.8"))
class DockerNonRootTests(unittest.TestCase):
def test_dockerfile_runs_as_non_root_user(self):
text = Path("Dockerfile").read_text()
self.assertIn("USER appuser", text)
self.assertIn("--uid 1000", text)
compose = Path("docker-compose.yml").read_text()
self.assertIn('user: "1000:1000"', compose)
if __name__ == "__main__":
unittest.main()
-93
View File
@@ -1,93 +0,0 @@
import asyncio
import os
import tempfile
import unittest
from pathlib import Path
from unittest.mock import patch
from fastapi import HTTPException
from apps.admin import dependencies as admin_dependencies
from apps.admin.dependencies import create_token, verify_token
from apps.admin.services import LocalFileClass
from core.settings import data_root, settings
from core.storage import SystemFileStorage
from core.utils import hash_password, verify_password
class PasswordCompareTests(unittest.TestCase):
def test_verify_password_accepts_valid_hash(self):
hashed = hash_password("s3cret-pass")
self.assertTrue(verify_password("s3cret-pass", hashed))
self.assertFalse(verify_password("wrong-pass", hashed))
def test_verify_password_supports_legacy_plaintext(self):
self.assertTrue(verify_password("legacy", "legacy"))
self.assertFalse(verify_password("legacy", "other"))
class LocalFilePathTraversalTests(unittest.TestCase):
def setUp(self):
self._tmpdir = tempfile.TemporaryDirectory()
self.local_root = Path(self._tmpdir.name) / "local"
self.local_root.mkdir(parents=True, exist_ok=True)
(self.local_root / "safe.txt").write_text("ok", encoding="utf-8")
self._data_root_patch = patch(
"apps.admin.services.data_root", Path(self._tmpdir.name)
)
self._data_root_patch.start()
def tearDown(self):
self._data_root_patch.stop()
self._tmpdir.cleanup()
def test_rejects_dotdot_filename(self):
with self.assertRaises(HTTPException) as ctx:
LocalFileClass("../etc/passwd")
self.assertEqual(ctx.exception.status_code, 400)
def test_rejects_absolute_filename(self):
with self.assertRaises(HTTPException) as ctx:
LocalFileClass("/etc/passwd")
self.assertEqual(ctx.exception.status_code, 400)
def test_allows_basename_inside_local(self):
local_file = LocalFileClass("safe.txt")
self.assertTrue(asyncio.run(local_file.exists()))
self.assertEqual(local_file.file, "safe.txt")
self.assertEqual(local_file.path, (self.local_root / "safe.txt").resolve())
class SystemStoragePathTests(unittest.TestCase):
def setUp(self):
self._tmpdir = tempfile.TemporaryDirectory()
self.storage = SystemFileStorage()
self.storage.root_path = Path(self._tmpdir.name)
def tearDown(self):
self._tmpdir.cleanup()
def test_resolve_safe_path_blocks_escape(self):
with self.assertRaises(ValueError):
self.storage._resolve_safe_path("../etc/passwd")
def test_resolve_safe_path_allows_nested(self):
target = self.storage._resolve_safe_path("share/data/a/b.txt")
self.assertTrue(str(target).startswith(str(Path(self._tmpdir.name).resolve())))
class AdminJwtUrlSafeTests(unittest.TestCase):
def setUp(self):
settings.jwt_secret = "j" * 48
def test_create_and_verify_roundtrip(self):
token = create_token({"is_admin": True}, expires_in=60)
# urlsafe token 不应依赖标准 base64 填充字符
self.assertNotIn("+", token)
self.assertNotIn("/", token)
payload = verify_token(token)
self.assertTrue(payload["is_admin"])
if __name__ == "__main__":
unittest.main()
-40
View File
@@ -1,40 +0,0 @@
import json
import os
import unittest
from unittest.mock import patch
from core.version import APP_VERSION, VERSION_FILE, load_app_version
from main import app
class ApplicationVersionTests(unittest.TestCase):
def test_version_file_is_the_runtime_version_source(self):
version = VERSION_FILE.read_text(encoding="utf-8").strip()
self.assertRegex(version, r"^\d+\.\d+\.\d+$")
with patch.dict(os.environ, {}, clear=True):
self.assertEqual(load_app_version(), version)
self.assertEqual(app.version, APP_VERSION)
def test_release_manifest_matches_version_file(self):
manifest_file = VERSION_FILE.parent / ".release-please-manifest.json"
manifest = json.loads(manifest_file.read_text(encoding="utf-8"))
self.assertEqual(manifest["."], VERSION_FILE.read_text(encoding="utf-8").strip())
def test_build_can_override_version_with_environment(self):
for version in ("9.8.7", "9.8.7-dev+abc123"):
with self.subTest(version=version):
with patch.dict(os.environ, {"APP_VERSION": version}):
self.assertEqual(load_app_version(), version)
def test_rejects_non_canonical_versions(self):
for version in ("v2.4.0", "2.4", "2.4.0 beta"):
with self.subTest(version=version):
with patch.dict(os.environ, {"APP_VERSION": version}):
with self.assertRaises(RuntimeError):
load_app_version()
if __name__ == "__main__":
unittest.main()