mirror of
https://github.com/vastsa/FileCodeBox.git
synced 2026-11-21 22:47:13 +08:00
Compare commits
10
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f1fee1edff | ||
|
|
65f4929d40 | ||
|
|
40f22de7f8 | ||
|
|
da374b4595 | ||
|
|
d3f9e7902c | ||
|
|
2f5eab18b1 | ||
|
|
6bb1ef06c1 | ||
|
|
63e72c1455 | ||
|
|
648d578d53 | ||
|
|
031d300cae |
No files matched your search
@@ -1,3 +1,3 @@
|
||||
{
|
||||
".": "2.7.0"
|
||||
".": "2.8.3"
|
||||
}
|
||||
+3
-10
@@ -54,22 +54,18 @@ RUN ln -sf /usr/share/zoneinfo/Asia/Shanghai /etc/localtime && \
|
||||
echo 'Asia/Shanghai' > /etc/timezone
|
||||
|
||||
# 从构建阶段复制编译好的前端主题
|
||||
COPY --from=frontend-builder /build/fronted-2024/dist ./themes/2024
|
||||
COPY --from=frontend-builder /build/FileCodeBox/themes/2024 ./themes/2024
|
||||
COPY --from=frontend-builder /build/fronted-2023/dist ./themes/2023
|
||||
|
||||
# 安装系统安全更新 + Python 依赖
|
||||
# 依赖从带哈希的锁定文件安装(--require-hashes),保证构建可复现、防供应链篡改。
|
||||
# gosu 用于入口脚本的数据卷属主修正后降权;清理 apt 缓存,降低镜像噪音与扫描面
|
||||
# 清理 apt 缓存,降低镜像噪音与扫描面
|
||||
RUN apt-get update \
|
||||
&& apt-get upgrade -y --no-install-recommends \
|
||||
&& apt-get install -y --no-install-recommends gosu \
|
||||
&& rm -rf /var/lib/apt/lists/* \
|
||||
&& pip install --no-cache-dir --require-hashes -r requirements.lock.txt \
|
||||
&& pip cache purge || true
|
||||
|
||||
# 非 root 运行用户;数据卷属主由 docker-entrypoint.sh 按需修正(兼容存量 root 卷)
|
||||
RUN useradd --system --uid 10001 --home-dir /app app
|
||||
|
||||
# 环境变量配置
|
||||
ENV HOST="0.0.0.0" \
|
||||
PORT=12345 \
|
||||
@@ -81,11 +77,8 @@ ENV HOST="0.0.0.0" \
|
||||
|
||||
EXPOSE 12345
|
||||
|
||||
COPY docker-entrypoint.sh /usr/local/bin/docker-entrypoint.sh
|
||||
RUN chmod +x /usr/local/bin/docker-entrypoint.sh
|
||||
ENTRYPOINT ["/usr/local/bin/docker-entrypoint.sh"]
|
||||
|
||||
# 生产环境启动命令
|
||||
# FORWARDED_ALLOW_IPS 默认为空:仅信任直连 IP,避免任意客户端伪造 X-Forwarded-*。
|
||||
# 若前面有反向代理,请显式设置为代理网段,例如 "10.0.0.0/8,172.16.0.0/12"。
|
||||
# 容器以 root 运行:兼容存量 root 属主的数据卷,以及 NAS/只读 bind mount。
|
||||
CMD ["sh", "-c", "access_log_arg=--no-access-log; if [ \"${APP_ENV:-development}\" != \"production\" ] || [ \"${ACCESS_LOG:-false}\" = \"true\" ]; then access_log_arg=--access-log; fi; exec uvicorn main:app --host \"$HOST\" --port \"$PORT\" --workers \"$WORKERS\" --log-level \"$LOG_LEVEL\" \"$access_log_arg\" --proxy-headers --forwarded-allow-ips \"${FORWARDED_ALLOW_IPS:-}\""]
|
||||
@@ -40,6 +40,7 @@ class ConfigService:
|
||||
"max_save_seconds",
|
||||
"onedrive_proxy",
|
||||
"open_upload",
|
||||
"mcp_require_token",
|
||||
"port",
|
||||
"s3_proxy",
|
||||
"server_port",
|
||||
|
||||
@@ -0,0 +1,231 @@
|
||||
"""Stateless MCP Streamable HTTP endpoint for quick share uploads."""
|
||||
import base64
|
||||
import binascii
|
||||
import html
|
||||
import io
|
||||
import json
|
||||
from typing import Any
|
||||
from urllib.parse import quote, urlsplit
|
||||
|
||||
from fastapi import APIRouter, HTTPException, Request, UploadFile
|
||||
from starlette.datastructures import Headers
|
||||
from starlette.responses import JSONResponse, Response
|
||||
|
||||
from apps.base.auth import _require_admin_payload
|
||||
from apps.base.file_validation import validate_file_type, validate_upload_file
|
||||
from apps.base.services import FileUploadService, validate_file_size
|
||||
from apps.base.utils import ip_limit, validate_expire_style
|
||||
from core.settings import settings
|
||||
from core.utils import sanitize_filename
|
||||
|
||||
router = APIRouter(tags=["MCP"])
|
||||
|
||||
MCP_PROTOCOL_VERSION = "2025-03-26"
|
||||
TEXT_SHARE_MAX_BYTES = 222 * 1024
|
||||
MAX_MCP_BODY_BYTES = 64 * 1024 * 1024
|
||||
|
||||
|
||||
def _jsonrpc_error(request_id, code: int, message: str) -> dict:
|
||||
return {"jsonrpc": "2.0", "id": request_id, "error": {"code": code, "message": message}}
|
||||
|
||||
|
||||
def _jsonrpc_result(request_id, result: dict) -> dict:
|
||||
return {"jsonrpc": "2.0", "id": request_id, "result": result}
|
||||
|
||||
|
||||
def _validate_origin(request: Request) -> None:
|
||||
"""Reject browser cross-site POSTs before parsing any upload tool."""
|
||||
origin = request.headers.get("origin")
|
||||
fetch_site = request.headers.get("sec-fetch-site", "").lower()
|
||||
if fetch_site == "cross-site":
|
||||
raise HTTPException(status_code=403, detail="跨站请求已拒绝")
|
||||
if not origin:
|
||||
return # Native MCP clients do not send Origin and use no ambient cookies.
|
||||
try:
|
||||
parsed = urlsplit(origin)
|
||||
host = request.headers.get("host", "").lower()
|
||||
if (
|
||||
parsed.scheme not in {"http", "https"}
|
||||
or not parsed.netloc
|
||||
or parsed.netloc.lower() != host
|
||||
or parsed.username is not None
|
||||
or parsed.password is not None
|
||||
or parsed.path not in {"", "/"}
|
||||
or parsed.query
|
||||
or parsed.fragment
|
||||
):
|
||||
raise ValueError("origin mismatch")
|
||||
except (ValueError, TypeError):
|
||||
raise HTTPException(status_code=403, detail="跨站请求已拒绝")
|
||||
|
||||
|
||||
async def _read_limited_body(request: Request) -> bytes:
|
||||
max_size = min(
|
||||
MAX_MCP_BODY_BYTES,
|
||||
max(1024 * 1024, int(settings.upload_size * 4 / 3) + 256 * 1024),
|
||||
)
|
||||
declared_size = request.headers.get("content-length")
|
||||
if declared_size:
|
||||
try:
|
||||
if int(declared_size) > max_size:
|
||||
raise HTTPException(status_code=413, detail="MCP 请求体过大")
|
||||
except ValueError:
|
||||
raise HTTPException(status_code=400, detail="Content-Length 无效")
|
||||
body = bytearray()
|
||||
async for chunk in request.stream():
|
||||
body.extend(chunk)
|
||||
if len(body) > max_size:
|
||||
raise HTTPException(status_code=413, detail="MCP 请求体过大")
|
||||
return bytes(body)
|
||||
|
||||
|
||||
def _tool_definitions() -> list[dict]:
|
||||
return [
|
||||
{
|
||||
"name": "share_text",
|
||||
"description": "将文本快速上传到 FileCodeBox 并创建分享链接。",
|
||||
"inputSchema": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"text": {"type": "string", "description": "要分享的文本"},
|
||||
"expire_value": {"type": "integer", "minimum": 1, "default": 1},
|
||||
"expire_style": {"type": "string", "enum": ["day", "hour", "minute", "forever", "count"], "default": "day"},
|
||||
},
|
||||
"required": ["text"],
|
||||
},
|
||||
},
|
||||
{
|
||||
"name": "share_file",
|
||||
"description": "将 Base64 编码的文件上传到 FileCodeBox 并创建分享链接。",
|
||||
"inputSchema": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"filename": {"type": "string", "description": "文件名"},
|
||||
"content_base64": {"type": "string", "description": "文件内容的标准 Base64 编码"},
|
||||
"content_type": {"type": "string", "default": "application/octet-stream"},
|
||||
"expire_value": {"type": "integer", "minimum": 1, "default": 1},
|
||||
"expire_style": {"type": "string", "enum": ["day", "hour", "minute", "forever", "count"], "default": "day"},
|
||||
},
|
||||
"required": ["filename", "content_base64"],
|
||||
},
|
||||
},
|
||||
]
|
||||
|
||||
|
||||
def _share_result(request: Request, code: str, name: str) -> dict:
|
||||
base_url = str(request.base_url).rstrip("/")
|
||||
share_url = f"{base_url}/#/?code={quote(code, safe='')}"
|
||||
markdown_name = html.escape(name).replace("[", "\\[").replace("]", "\\]")
|
||||
return {
|
||||
"code": code,
|
||||
"name": name,
|
||||
"url": share_url,
|
||||
"markdown": f"[{markdown_name}]({share_url})",
|
||||
}
|
||||
|
||||
|
||||
async def _call_tool(request: Request, tool_name: str, arguments: dict) -> dict:
|
||||
authorization = request.headers.get("authorization", "")
|
||||
if settings.mcp_require_token or not settings.open_upload:
|
||||
_require_admin_payload(authorization)
|
||||
ip = ip_limit["upload"](request)
|
||||
|
||||
if tool_name == "share_text":
|
||||
text = arguments.get("text")
|
||||
if not isinstance(text, str):
|
||||
raise ValueError("text 必须是字符串")
|
||||
if len(text.encode("utf-8")) > TEXT_SHARE_MAX_BYTES:
|
||||
raise ValueError("内容过多,请改用文件分享")
|
||||
expire_value = int(arguments.get("expire_value", 1))
|
||||
expire_style = str(arguments.get("expire_style", "day"))
|
||||
if expire_value < 1:
|
||||
raise ValueError("expire_value 必须大于 0")
|
||||
validate_expire_style(expire_style)
|
||||
code = await FileUploadService.create_text_share(text, expire_value, expire_style)
|
||||
ip_limit["upload"].add_ip(ip)
|
||||
return _share_result(request, code, "Text")
|
||||
|
||||
if tool_name == "share_file":
|
||||
filename = arguments.get("filename")
|
||||
encoded_content = arguments.get("content_base64")
|
||||
content_type = str(arguments.get("content_type", "application/octet-stream"))
|
||||
if not isinstance(filename, str) or not filename.strip():
|
||||
raise ValueError("filename 不能为空")
|
||||
if not isinstance(encoded_content, str):
|
||||
raise ValueError("content_base64 必须是字符串")
|
||||
try:
|
||||
content = base64.b64decode(encoded_content, validate=True)
|
||||
except (ValueError, binascii.Error):
|
||||
raise ValueError("content_base64 不是有效的标准 Base64")
|
||||
safe_name = await sanitize_filename(filename.rsplit("/", 1)[-1].rsplit("\\", 1)[-1])
|
||||
validate_file_type(safe_name, content_type)
|
||||
upload = UploadFile(filename=safe_name, file=io.BytesIO(content), size=len(content), headers=Headers({"content-type": content_type}))
|
||||
size = await validate_file_size(upload, settings.upload_size)
|
||||
await validate_upload_file(upload)
|
||||
expire_value = int(arguments.get("expire_value", 1))
|
||||
expire_style = str(arguments.get("expire_style", "day"))
|
||||
if expire_value < 1:
|
||||
raise ValueError("expire_value 必须大于 0")
|
||||
validate_expire_style(expire_style)
|
||||
share = await FileUploadService.create_file_share(upload, size=size, expire_value=expire_value, expire_style=expire_style)
|
||||
ip_limit["upload"].add_ip(ip)
|
||||
return _share_result(request, share["code"], share["name"])
|
||||
|
||||
raise LookupError(f"未知工具:{tool_name}")
|
||||
|
||||
|
||||
@router.post("/mcp", include_in_schema=False)
|
||||
async def mcp_endpoint(request: Request):
|
||||
_validate_origin(request)
|
||||
media_type = request.headers.get("content-type", "").split(";", 1)[0].strip().lower()
|
||||
if media_type != "application/json":
|
||||
raise HTTPException(status_code=415, detail="MCP 请求必须使用 application/json")
|
||||
try:
|
||||
message = json.loads(await _read_limited_body(request))
|
||||
except (json.JSONDecodeError, UnicodeDecodeError):
|
||||
return JSONResponse(_jsonrpc_error(None, -32700, "Parse error"), status_code=400)
|
||||
if not isinstance(message, dict) or message.get("jsonrpc") != "2.0" or not isinstance(message.get("method"), str):
|
||||
return JSONResponse(_jsonrpc_error(message.get("id") if isinstance(message, dict) else None, -32600, "Invalid Request"), status_code=400)
|
||||
|
||||
request_id = message.get("id")
|
||||
method = message["method"]
|
||||
if request_id is None and method.startswith("notifications/"):
|
||||
return Response(status_code=202)
|
||||
result: dict[str, Any] = {}
|
||||
try:
|
||||
if method == "initialize":
|
||||
result = {
|
||||
"protocolVersion": MCP_PROTOCOL_VERSION,
|
||||
"capabilities": {"tools": {"listChanged": False}},
|
||||
"serverInfo": {"name": "filecodebox", "version": "1.0.0"},
|
||||
}
|
||||
elif method == "ping":
|
||||
result = {}
|
||||
elif method == "tools/list":
|
||||
result = {"tools": _tool_definitions()}
|
||||
elif method == "tools/call":
|
||||
params = message.get("params")
|
||||
if not isinstance(params, dict) or not isinstance(params.get("name"), str):
|
||||
return JSONResponse(_jsonrpc_error(request_id, -32602, "Invalid params"))
|
||||
arguments = params.get("arguments", {})
|
||||
if not isinstance(arguments, dict):
|
||||
return JSONResponse(_jsonrpc_error(request_id, -32602, "Invalid params"))
|
||||
try:
|
||||
tool_value = await _call_tool(request, params["name"], arguments)
|
||||
result = {"content": [{"type": "text", "text": json.dumps(tool_value, ensure_ascii=False)}], "structuredContent": tool_value}
|
||||
except LookupError as exc:
|
||||
return JSONResponse(_jsonrpc_error(request_id, -32602, str(exc)))
|
||||
except HTTPException as exc:
|
||||
if exc.status_code in {401, 403}:
|
||||
raise
|
||||
result = {"content": [{"type": "text", "text": str(exc.detail)}], "isError": True}
|
||||
except (TypeError, ValueError) as exc:
|
||||
result = {"content": [{"type": "text", "text": str(exc)}], "isError": True}
|
||||
else:
|
||||
return JSONResponse(_jsonrpc_error(request_id, -32601, "Method not found"))
|
||||
return JSONResponse(_jsonrpc_result(request_id, result), headers={"MCP-Protocol-Version": MCP_PROTOCOL_VERSION})
|
||||
except HTTPException as exc:
|
||||
return JSONResponse(
|
||||
_jsonrpc_error(request_id, -32001 if exc.status_code == 401 else -32003, str(exc.detail)),
|
||||
status_code=exc.status_code,
|
||||
)
|
||||
+9
-5
@@ -96,14 +96,18 @@ async def not_found_handler(request, exc=None):
|
||||
(负路径测试抓到的存量 bug)。浏览器(Accept 含 text/html)仍拿到
|
||||
主题首页做 SPA 兜底;API 客户端拿到 JSON 404。
|
||||
"""
|
||||
if request is not None and request.method in {"GET", "HEAD"} and "text/html" in (
|
||||
request.headers.get("accept", "")
|
||||
):
|
||||
return await index(request, exc)
|
||||
return JSONResponse(
|
||||
json_404 = JSONResponse(
|
||||
status_code=404,
|
||||
content={"code": 404, "message": "Not Found", "detail": "资源不存在"},
|
||||
)
|
||||
if request is not None and request.method in {"GET", "HEAD"} and "text/html" in (
|
||||
request.headers.get("accept", "")
|
||||
):
|
||||
try:
|
||||
return await index(request, exc)
|
||||
except HTTPException:
|
||||
return json_404
|
||||
return json_404
|
||||
|
||||
|
||||
@router.get("/")
|
||||
|
||||
@@ -194,6 +194,8 @@ async def post_file_metadata(
|
||||
return APIResponse(detail=build_file_metadata(file_code))
|
||||
|
||||
|
||||
|
||||
|
||||
@share_api.get("/select/")
|
||||
async def get_code_file(code: str, ip: str = Depends(ip_limit["error"])):
|
||||
file_storage: FileStorageInterface = storages[settings.file_storage]()
|
||||
|
||||
+2
-2
@@ -155,8 +155,8 @@ def validate_outbound_hostname(value: Any) -> str:
|
||||
if os.environ.get("APP_ENV", "development") != "production":
|
||||
return hostname
|
||||
|
||||
if "://" in hostname or "/" in hostname:
|
||||
raise ValueError(f"s3_hostname 应为裸主机名,不含协议或路径:{hostname}")
|
||||
if "://" in hostname or "/" in hostname or "@" in hostname:
|
||||
raise ValueError(f"s3_hostname 应为裸主机名,不含协议、路径或 userinfo:{hostname}")
|
||||
# 取主机部分:[v6] 形态取括号内;host:port 取冒号前;裸 IPv6(多个冒号)整体
|
||||
if "[" in hostname:
|
||||
host = hostname.split("[", 1)[1].split("]", 1)[0]
|
||||
|
||||
@@ -48,6 +48,7 @@ DEFAULT_CONFIG: dict[str, Any] = {
|
||||
"jwt_secret": "",
|
||||
"admin_session_expire": ADMIN_SESSION_EXPIRE_DEFAULT,
|
||||
"open_upload": 1,
|
||||
"mcp_require_token": 0,
|
||||
"upload_size": 1024 * 1024 * 10,
|
||||
"allowed_file_types": ["*"],
|
||||
"expire_style": ["day", "hour", "minute", "forever", "count"],
|
||||
|
||||
+1
-1
@@ -1,7 +1,7 @@
|
||||
version: "3"
|
||||
services:
|
||||
file-code-box:
|
||||
image: lanol/filecodebox:2.7.0 # x-release-please-version
|
||||
image: lanol/filecodebox:2.8.3 # x-release-please-version
|
||||
volumes:
|
||||
- fcb-data:/app/data:rw
|
||||
# NAS 已有文件:把共享目录挂到 /app/data/local,即可在后台「本地分享」里生成提取码,无需再上传
|
||||
|
||||
@@ -1,20 +0,0 @@
|
||||
#!/bin/sh
|
||||
# FileCodeBox 容器入口:兼容式非 root 降权。
|
||||
#
|
||||
# 默认以 root 进入(兼容存量 root 属主的数据卷),按需修正 data 目录属主后
|
||||
# 用 gosu 降权到 app 用户运行;若部署方显式指定了 user(非 root),则直接运行
|
||||
# 不做任何 chown,保证两种形态都可预期。
|
||||
set -e
|
||||
|
||||
DATA_DIR="${DATA_DIR:-/app/data}"
|
||||
|
||||
if [ "$(id -u)" = "0" ]; then
|
||||
mkdir -p "$DATA_DIR"
|
||||
# 仅当存在非 app 属主的文件时才 chown,避免大卷启动变慢
|
||||
if [ -n "$(find "$DATA_DIR" ! -uid "$(id -u app)" -print -quit 2>/dev/null)" ]; then
|
||||
chown -R app:app "$DATA_DIR"
|
||||
fi
|
||||
exec gosu app "$@"
|
||||
fi
|
||||
|
||||
exec "$@"
|
||||
@@ -1,5 +1,40 @@
|
||||
# Changelog
|
||||
|
||||
## [2.8.3](https://github.com/vastsa/FileCodeBox/compare/v2.8.2...v2.8.3) (2026-10-10)
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* remove HTML preview endpoint ([65f4929](https://github.com/vastsa/FileCodeBox/commit/65f4929d405408e1c9e58127e0097f8b78b1819f))
|
||||
|
||||
## [2.8.2](https://github.com/vastsa/FileCodeBox/compare/v2.8.1...v2.8.2) (2026-10-10)
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* type MCP protocol results ([da374b4](https://github.com/vastsa/FileCodeBox/commit/da374b459537ee079e1d03da121a935c8fb18f0e))
|
||||
|
||||
## [2.8.1](https://github.com/vastsa/FileCodeBox/compare/v2.8.0...v2.8.1) (2026-10-10)
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* restore lint and Docker theme build ([2f5eab1](https://github.com/vastsa/FileCodeBox/commit/2f5eab18b1ab28fcb4f416248076ce574998d718))
|
||||
|
||||
## [2.8.0](https://github.com/vastsa/FileCodeBox/compare/v2.7.1...v2.8.0) (2026-10-10)
|
||||
|
||||
|
||||
### Features
|
||||
|
||||
* add MCP quick share and safe HTML preview ([63e72c1](https://github.com/vastsa/FileCodeBox/commit/63e72c145576d169265e4fa8cf373e33531a06a0))
|
||||
|
||||
## [2.7.1](https://github.com/vastsa/FileCodeBox/compare/v2.7.0...v2.7.1) (2026-09-19)
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* keep Docker as root, close s3_hostname SSRF, unbreak 404 tests ([031d300](https://github.com/vastsa/FileCodeBox/commit/031d300caea99117e82b3bddc3e5d0532cf3efa6))
|
||||
|
||||
## [2.7.0](https://github.com/vastsa/FileCodeBox/compare/v2.6.1...v2.7.0) (2026-09-16)
|
||||
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
## [Unreleased]
|
||||
|
||||
<!-- Current release: 2.7.0 x-release-please-version -->
|
||||
<!-- Current release: 2.8.3 x-release-please-version -->
|
||||
|
||||
### Added
|
||||
|
||||
|
||||
+1
-1
@@ -42,7 +42,7 @@ docker run -d --restart unless-stopped \
|
||||
--log-opt max-size=10m \
|
||||
--log-opt max-file=3 \
|
||||
--name filecodebox \
|
||||
lanol/filecodebox:2.7.0 # x-release-please-version
|
||||
lanol/filecodebox:2.8.3 # x-release-please-version
|
||||
```
|
||||
|
||||
Open `http://localhost:12345` and complete the first-run setup.
|
||||
|
||||
+1
-1
@@ -42,7 +42,7 @@ docker run -d --restart unless-stopped \
|
||||
--log-opt max-size=10m \
|
||||
--log-opt max-file=3 \
|
||||
--name filecodebox \
|
||||
lanol/filecodebox:2.7.0 # x-release-please-version
|
||||
lanol/filecodebox:2.8.3 # x-release-please-version
|
||||
```
|
||||
|
||||
打开 `http://localhost:12345`,按引导完成首次初始化。
|
||||
|
||||
@@ -28,6 +28,7 @@ from apps.base.tasks import (
|
||||
delete_expire_files,
|
||||
)
|
||||
from apps.base.views import share_api, chunk_api, presign_api
|
||||
from apps.base.mcp import router as mcp_router
|
||||
from core.database import db_startup_lock, get_db_config, init_db
|
||||
from core.errors import StorageError
|
||||
from core.logger import get_log_level_name, is_access_log_enabled, logger
|
||||
@@ -139,6 +140,7 @@ app.include_router(presign_api)
|
||||
app.include_router(presign_api, prefix="/api")
|
||||
app.include_router(admin_api)
|
||||
app.include_router(pages_router)
|
||||
app.include_router(mcp_router)
|
||||
|
||||
# 404 时返回主题首页(index 兼任 exception handler 与 GET / 路由)
|
||||
app.add_exception_handler(404, not_found_handler)
|
||||
|
||||
@@ -32,7 +32,7 @@ docker run -d --restart unless-stopped \
|
||||
--log-opt max-size=10m \
|
||||
--log-opt max-file=3 \
|
||||
--name filecodebox \
|
||||
lanol/filecodebox:2.7.0 # x-release-please-version
|
||||
lanol/filecodebox:2.8.3 # x-release-please-version
|
||||
```
|
||||
|
||||
访问 `http://localhost:12345`,完成首次初始化。生产环境建议固定版本号;`latest` 指向最新正式版。
|
||||
|
||||
+1
-1
@@ -32,7 +32,7 @@ docker run -d --restart unless-stopped \
|
||||
--log-opt max-size=10m \
|
||||
--log-opt max-file=3 \
|
||||
--name filecodebox \
|
||||
lanol/filecodebox:2.7.0 # x-release-please-version
|
||||
lanol/filecodebox:2.8.3 # x-release-please-version
|
||||
```
|
||||
|
||||
Open `http://localhost:12345` and complete first-run setup. Pin a version in production; `latest` tracks the newest stable release.
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
|
||||
import pytest
|
||||
|
||||
from apps.base.models import KeyValue
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_mcp_initialize_and_list_tools(initialized_client):
|
||||
init_response = await initialized_client.post(
|
||||
"/mcp",
|
||||
json={"jsonrpc": "2.0", "id": 1, "method": "initialize", "params": {}},
|
||||
)
|
||||
assert init_response.status_code == 200
|
||||
assert init_response.json()["result"]["capabilities"]["tools"]
|
||||
|
||||
tools_response = await initialized_client.post(
|
||||
"/mcp", json={"jsonrpc": "2.0", "id": 2, "method": "tools/list"}
|
||||
)
|
||||
assert tools_response.status_code == 200
|
||||
assert {tool["name"] for tool in tools_response.json()["result"]["tools"]} == {
|
||||
"share_text",
|
||||
"share_file",
|
||||
}
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_mcp_rejects_cross_origin_requests(initialized_client):
|
||||
response = await initialized_client.post(
|
||||
"/mcp",
|
||||
json={"jsonrpc": "2.0", "id": 3, "method": "tools/list"},
|
||||
headers={"origin": "https://attacker.invalid"},
|
||||
)
|
||||
assert response.status_code == 403
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_mcp_token_can_be_required(initialized_client):
|
||||
from core.settings import settings
|
||||
|
||||
record = await KeyValue.filter(key="settings").first()
|
||||
config = dict(record.value)
|
||||
config["mcp_require_token"] = 1
|
||||
record.value = config
|
||||
await record.save()
|
||||
settings.user_config = config
|
||||
|
||||
response = await initialized_client.post(
|
||||
"/mcp",
|
||||
json={
|
||||
"jsonrpc": "2.0",
|
||||
"id": 4,
|
||||
"method": "tools/call",
|
||||
"params": {"name": "share_text", "arguments": {"text": "private"}},
|
||||
},
|
||||
)
|
||||
assert response.status_code == 401
|
||||
from apps.admin.dependencies import create_token
|
||||
|
||||
token = create_token({"is_admin": True})
|
||||
authorized = await initialized_client.post(
|
||||
"/mcp",
|
||||
headers={"authorization": f"Bearer {token}"},
|
||||
json={
|
||||
"jsonrpc": "2.0",
|
||||
"id": 6,
|
||||
"method": "tools/call",
|
||||
"params": {"name": "share_text", "arguments": {"text": "private"}},
|
||||
},
|
||||
)
|
||||
assert authorized.status_code == 200
|
||||
assert "/#/?code=" in authorized.json()["result"]["structuredContent"]["url"]
|
||||
@@ -138,9 +138,23 @@ class TestNotFoundHandlerBranches:
|
||||
assert "text/html" not in response.headers["content-type"]
|
||||
|
||||
async def test_browser_accept_gets_theme_page(self, initialized_client):
|
||||
response = await initialized_client.get("/no-such-path", headers={"Accept": "text/html"})
|
||||
assert response.status_code == 200
|
||||
assert "text/html" in response.headers["content-type"]
|
||||
from core.settings import BASE_DIR
|
||||
|
||||
theme_dir = BASE_DIR / "themes" / "2024"
|
||||
theme_dir.mkdir(parents=True, exist_ok=True)
|
||||
index = theme_dir / "index.html"
|
||||
created = not index.exists()
|
||||
if created:
|
||||
index.write_text("<!doctype html><title>{{title}}</title>", encoding="utf-8")
|
||||
try:
|
||||
response = await initialized_client.get(
|
||||
"/no-such-path", headers={"Accept": "text/html"}
|
||||
)
|
||||
assert response.status_code == 200
|
||||
assert "text/html" in response.headers["content-type"]
|
||||
finally:
|
||||
if created:
|
||||
index.unlink(missing_ok=True)
|
||||
|
||||
async def test_default_star_accept_gets_json_404(self, initialized_client):
|
||||
"""curl 默认 */* 不含 text/html——必须走 JSON 分支(防误伤脚本调用方)。"""
|
||||
|
||||
@@ -90,6 +90,12 @@ def test_hostname_tier_rejects_url_forms(production_env):
|
||||
validate_outbound_hostname("http://127.0.0.1:9000")
|
||||
|
||||
|
||||
def test_hostname_tier_rejects_userinfo(production_env):
|
||||
"""存储层拼 https://{s3_hostname},@ 会被当成 userinfo,实际连 @ 后的地址。"""
|
||||
for hostname in ("evil.com@127.0.0.1", "attacker.example@127.0.0.1:8443"):
|
||||
with pytest.raises(ValueError):
|
||||
validate_outbound_hostname(hostname)
|
||||
|
||||
@pytest.mark.asyncio
|
||||
class TestChangedOnlyEnforcement:
|
||||
"""changed-only 集成回归:存量内网 endpoint 不得挡死无关设置保存。
|
||||
|
||||
Reference in new issue
Block a user