Skip to content

Commit 63e72c1

Browse files
committed
feat: add MCP quick share and safe HTML preview
1 parent 648d578 commit 63e72c1

6 files changed

Lines changed: 471 additions & 2 deletions

File tree

‎apps/admin/config_service.py‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,7 @@ class ConfigService:
4040
"max_save_seconds",
4141
"onedrive_proxy",
4242
"open_upload",
43+
"mcp_require_token",
4344
"port",
4445
"s3_proxy",
4546
"server_port",

‎apps/base/mcp.py‎

Lines changed: 302 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,302 @@
1+
"""Stateless MCP Streamable HTTP endpoint for quick share uploads."""
2+
import base64
3+
import binascii
4+
import html
5+
import io
6+
import json
7+
from html.parser import HTMLParser
8+
from urllib.parse import quote, urlsplit
9+
10+
from fastapi import APIRouter, HTTPException, Request, UploadFile
11+
from starlette.datastructures import Headers
12+
from starlette.responses import JSONResponse, Response
13+
14+
from apps.base.auth import _require_admin_payload
15+
from apps.base.file_validation import validate_file_type, validate_upload_file
16+
from apps.base.services import FileUploadService, validate_file_size
17+
from apps.base.utils import ip_limit, validate_expire_style
18+
from core.settings import settings
19+
from core.utils import sanitize_filename
20+
21+
router = APIRouter(tags=["MCP"])
22+
23+
MCP_PROTOCOL_VERSION = "2025-03-26"
24+
TEXT_SHARE_MAX_BYTES = 222 * 1024
25+
MAX_MCP_BODY_BYTES = 64 * 1024 * 1024
26+
27+
28+
def _jsonrpc_error(request_id, code: int, message: str) -> dict:
29+
return {"jsonrpc": "2.0", "id": request_id, "error": {"code": code, "message": message}}
30+
31+
32+
def _jsonrpc_result(request_id, result: dict) -> dict:
33+
return {"jsonrpc": "2.0", "id": request_id, "result": result}
34+
35+
36+
def _validate_origin(request: Request) -> None:
37+
"""Reject browser cross-site POSTs before parsing any upload tool."""
38+
origin = request.headers.get("origin")
39+
fetch_site = request.headers.get("sec-fetch-site", "").lower()
40+
if fetch_site == "cross-site":
41+
raise HTTPException(status_code=403, detail="跨站请求已拒绝")
42+
if not origin:
43+
return # Native MCP clients do not send Origin and use no ambient cookies.
44+
try:
45+
parsed = urlsplit(origin)
46+
host = request.headers.get("host", "").lower()
47+
if (
48+
parsed.scheme not in {"http", "https"}
49+
or not parsed.netloc
50+
or parsed.netloc.lower() != host
51+
or parsed.username is not None
52+
or parsed.password is not None
53+
or parsed.path not in {"", "/"}
54+
or parsed.query
55+
or parsed.fragment
56+
):
57+
raise ValueError("origin mismatch")
58+
except (ValueError, TypeError):
59+
raise HTTPException(status_code=403, detail="跨站请求已拒绝")
60+
61+
62+
async def _read_limited_body(request: Request) -> bytes:
63+
max_size = min(
64+
MAX_MCP_BODY_BYTES,
65+
max(1024 * 1024, int(settings.upload_size * 4 / 3) + 256 * 1024),
66+
)
67+
declared_size = request.headers.get("content-length")
68+
if declared_size:
69+
try:
70+
if int(declared_size) > max_size:
71+
raise HTTPException(status_code=413, detail="MCP 请求体过大")
72+
except ValueError:
73+
raise HTTPException(status_code=400, detail="Content-Length 无效")
74+
body = bytearray()
75+
async for chunk in request.stream():
76+
body.extend(chunk)
77+
if len(body) > max_size:
78+
raise HTTPException(status_code=413, detail="MCP 请求体过大")
79+
return bytes(body)
80+
81+
82+
def _tool_definitions() -> list[dict]:
83+
return [
84+
{
85+
"name": "share_text",
86+
"description": "将文本快速上传到 FileCodeBox 并创建分享链接。",
87+
"inputSchema": {
88+
"type": "object",
89+
"properties": {
90+
"text": {"type": "string", "description": "要分享的文本"},
91+
"expire_value": {"type": "integer", "minimum": 1, "default": 1},
92+
"expire_style": {"type": "string", "enum": ["day", "hour", "minute", "forever", "count"], "default": "day"},
93+
},
94+
"required": ["text"],
95+
},
96+
},
97+
{
98+
"name": "share_file",
99+
"description": "将 Base64 编码的文件上传到 FileCodeBox 并创建分享链接。",
100+
"inputSchema": {
101+
"type": "object",
102+
"properties": {
103+
"filename": {"type": "string", "description": "文件名"},
104+
"content_base64": {"type": "string", "description": "文件内容的标准 Base64 编码"},
105+
"content_type": {"type": "string", "default": "application/octet-stream"},
106+
"expire_value": {"type": "integer", "minimum": 1, "default": 1},
107+
"expire_style": {"type": "string", "enum": ["day", "hour", "minute", "forever", "count"], "default": "day"},
108+
},
109+
"required": ["filename", "content_base64"],
110+
},
111+
},
112+
]
113+
114+
115+
def _share_result(request: Request, code: str, name: str) -> dict:
116+
base_url = str(request.base_url).rstrip("/")
117+
share_url = f"{base_url}/#/?code={quote(code, safe='')}"
118+
markdown_name = html.escape(name).replace("[", "\\[").replace("]", "\\]")
119+
return {
120+
"code": code,
121+
"name": name,
122+
"url": share_url,
123+
"markdown": f"[{markdown_name}]({share_url})",
124+
}
125+
126+
127+
async def _call_tool(request: Request, tool_name: str, arguments: dict) -> dict:
128+
authorization = request.headers.get("authorization", "")
129+
if settings.mcp_require_token or not settings.open_upload:
130+
_require_admin_payload(authorization)
131+
ip = ip_limit["upload"](request)
132+
133+
if tool_name == "share_text":
134+
text = arguments.get("text")
135+
if not isinstance(text, str):
136+
raise ValueError("text 必须是字符串")
137+
if len(text.encode("utf-8")) > TEXT_SHARE_MAX_BYTES:
138+
raise ValueError("内容过多,请改用文件分享")
139+
expire_value = int(arguments.get("expire_value", 1))
140+
expire_style = str(arguments.get("expire_style", "day"))
141+
if expire_value < 1:
142+
raise ValueError("expire_value 必须大于 0")
143+
validate_expire_style(expire_style)
144+
code = await FileUploadService.create_text_share(text, expire_value, expire_style)
145+
ip_limit["upload"].add_ip(ip)
146+
return _share_result(request, code, "Text")
147+
148+
if tool_name == "share_file":
149+
filename = arguments.get("filename")
150+
encoded_content = arguments.get("content_base64")
151+
content_type = str(arguments.get("content_type", "application/octet-stream"))
152+
if not isinstance(filename, str) or not filename.strip():
153+
raise ValueError("filename 不能为空")
154+
if not isinstance(encoded_content, str):
155+
raise ValueError("content_base64 必须是字符串")
156+
try:
157+
content = base64.b64decode(encoded_content, validate=True)
158+
except (ValueError, binascii.Error):
159+
raise ValueError("content_base64 不是有效的标准 Base64")
160+
safe_name = await sanitize_filename(filename.rsplit("/", 1)[-1].rsplit("\\", 1)[-1])
161+
validate_file_type(safe_name, content_type)
162+
upload = UploadFile(filename=safe_name, file=io.BytesIO(content), size=len(content), headers=Headers({"content-type": content_type}))
163+
size = await validate_file_size(upload, settings.upload_size)
164+
await validate_upload_file(upload)
165+
expire_value = int(arguments.get("expire_value", 1))
166+
expire_style = str(arguments.get("expire_style", "day"))
167+
if expire_value < 1:
168+
raise ValueError("expire_value 必须大于 0")
169+
validate_expire_style(expire_style)
170+
share = await FileUploadService.create_file_share(upload, size=size, expire_value=expire_value, expire_style=expire_style)
171+
ip_limit["upload"].add_ip(ip)
172+
return _share_result(request, share["code"], share["name"])
173+
174+
raise LookupError(f"未知工具:{tool_name}")
175+
176+
177+
@router.post("/mcp", include_in_schema=False)
178+
async def mcp_endpoint(request: Request):
179+
_validate_origin(request)
180+
media_type = request.headers.get("content-type", "").split(";", 1)[0].strip().lower()
181+
if media_type != "application/json":
182+
raise HTTPException(status_code=415, detail="MCP 请求必须使用 application/json")
183+
try:
184+
message = json.loads(await _read_limited_body(request))
185+
except (json.JSONDecodeError, UnicodeDecodeError):
186+
return JSONResponse(_jsonrpc_error(None, -32700, "Parse error"), status_code=400)
187+
if not isinstance(message, dict) or message.get("jsonrpc") != "2.0" or not isinstance(message.get("method"), str):
188+
return JSONResponse(_jsonrpc_error(message.get("id") if isinstance(message, dict) else None, -32600, "Invalid Request"), status_code=400)
189+
190+
request_id = message.get("id")
191+
method = message["method"]
192+
if request_id is None and method.startswith("notifications/"):
193+
return Response(status_code=202)
194+
try:
195+
if method == "initialize":
196+
result = {
197+
"protocolVersion": MCP_PROTOCOL_VERSION,
198+
"capabilities": {"tools": {"listChanged": False}},
199+
"serverInfo": {"name": "filecodebox", "version": "1.0.0"},
200+
}
201+
elif method == "ping":
202+
result = {}
203+
elif method == "tools/list":
204+
result = {"tools": _tool_definitions()}
205+
elif method == "tools/call":
206+
params = message.get("params")
207+
if not isinstance(params, dict) or not isinstance(params.get("name"), str):
208+
return JSONResponse(_jsonrpc_error(request_id, -32602, "Invalid params"))
209+
arguments = params.get("arguments", {})
210+
if not isinstance(arguments, dict):
211+
return JSONResponse(_jsonrpc_error(request_id, -32602, "Invalid params"))
212+
try:
213+
tool_value = await _call_tool(request, params["name"], arguments)
214+
result = {"content": [{"type": "text", "text": json.dumps(tool_value, ensure_ascii=False)}], "structuredContent": tool_value}
215+
except LookupError as exc:
216+
return JSONResponse(_jsonrpc_error(request_id, -32602, str(exc)))
217+
except HTTPException as exc:
218+
if exc.status_code in {401, 403}:
219+
raise
220+
result = {"content": [{"type": "text", "text": str(exc.detail)}], "isError": True}
221+
except (TypeError, ValueError) as exc:
222+
result = {"content": [{"type": "text", "text": str(exc)}], "isError": True}
223+
else:
224+
return JSONResponse(_jsonrpc_error(request_id, -32601, "Method not found"))
225+
return JSONResponse(_jsonrpc_result(request_id, result), headers={"MCP-Protocol-Version": MCP_PROTOCOL_VERSION})
226+
except HTTPException as exc:
227+
return JSONResponse(
228+
_jsonrpc_error(request_id, -32001 if exc.status_code == 401 else -32003, str(exc.detail)),
229+
status_code=exc.status_code,
230+
)
231+
232+
233+
_SAFE_TAGS = {
234+
"a", "abbr", "article", "b", "blockquote", "br", "caption", "code", "dd", "del", "details",
235+
"div", "dl", "dt", "em", "figcaption", "figure", "h1", "h2", "h3", "h4", "h5", "h6",
236+
"hr", "i", "img", "li", "main", "mark", "ol", "p", "pre", "s", "section", "small", "span",
237+
"strong", "sub", "summary", "sup", "table", "tbody", "td", "th", "thead", "tr", "u", "ul",
238+
}
239+
_VOID_TAGS = {"br", "hr", "img"}
240+
_DROP_CONTENT_TAGS = {"script", "style", "iframe", "object", "embed", "svg", "math", "form", "template"}
241+
_SAFE_ATTRS = {"alt", "title", "class", "id", "colspan", "rowspan", "width", "height", "scope", "dir", "lang"}
242+
243+
244+
class _HTMLPreviewSanitizer(HTMLParser):
245+
"""Whitelist-only HTML serializer; scripts, active embeds and URL attrs are removed."""
246+
247+
def __init__(self):
248+
super().__init__(convert_charrefs=True)
249+
self.output: list[str] = []
250+
self.drop_depth = 0
251+
252+
def handle_starttag(self, tag, attrs):
253+
tag = tag.lower()
254+
if self.drop_depth:
255+
if tag in _DROP_CONTENT_TAGS:
256+
self.drop_depth += 1
257+
return
258+
if tag in _DROP_CONTENT_TAGS:
259+
self.drop_depth = 1
260+
return
261+
if tag not in _SAFE_TAGS:
262+
return
263+
safe_attrs = []
264+
for name, value in attrs:
265+
name = name.lower()
266+
if value is None or name.startswith("on") or name not in _SAFE_ATTRS:
267+
continue
268+
safe_attrs.append(f' {name}="{html.escape(value, quote=True)}"')
269+
self.output.append(f"<{tag}{''.join(safe_attrs)}>")
270+
271+
def handle_startendtag(self, tag, attrs):
272+
self.handle_starttag(tag, attrs)
273+
if tag.lower() in _SAFE_TAGS and tag.lower() not in _VOID_TAGS:
274+
self.handle_endtag(tag)
275+
276+
def handle_endtag(self, tag):
277+
tag = tag.lower()
278+
if self.drop_depth:
279+
if tag in _DROP_CONTENT_TAGS:
280+
self.drop_depth -= 1
281+
return
282+
if tag in _SAFE_TAGS and tag not in _VOID_TAGS:
283+
self.output.append(f"</{tag}>")
284+
285+
def handle_data(self, data):
286+
if not self.drop_depth:
287+
self.output.append(html.escape(data))
288+
289+
def handle_entityref(self, name):
290+
if not self.drop_depth:
291+
self.output.append(f"&amp;{html.escape(name)};")
292+
293+
def handle_charref(self, name):
294+
if not self.drop_depth:
295+
self.output.append(f"&amp;#{html.escape(name)};")
296+
297+
298+
def sanitize_html_preview(source: str) -> str:
299+
parser = _HTMLPreviewSanitizer()
300+
parser.feed(source)
301+
parser.close()
302+
return "<!doctype html><meta charset=\"utf-8\"><meta name=\"viewport\" content=\"width=device-width,initial-scale=1\"><body>" + "".join(parser.output) + "</body>"

‎apps/base/views.py‎

Lines changed: 48 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import hashlib
2+
import asyncio
23
import hmac
34
import os
45
import uuid
@@ -9,8 +10,7 @@
910

1011
from fastapi import APIRouter, Form, Request, UploadFile, File, Depends, HTTPException
1112
from pydantic import BaseModel, ValidationError
12-
from starlette import status
13-
from starlette.responses import Response
13+
from starlette.responses import HTMLResponse, Response
1414
from tortoise.expressions import Case, F, Q, When
1515

1616
from apps.base.auth import share_required_login
@@ -39,6 +39,7 @@
3939
validate_expire_style,
4040
)
4141
from apps.base.local_share import is_local_ref
42+
from apps.base.mcp import sanitize_html_preview
4243
from core.response import APIResponse
4344
from core.settings import settings
4445
from core.storage import storages, FileStorageInterface
@@ -194,6 +195,51 @@ async def post_file_metadata(
194195
return APIResponse(detail=build_file_metadata(file_code))
195196

196197

198+
@share_api.get("/preview/html/{code}", include_in_schema=False)
199+
async def preview_html(code: str):
200+
has, file_code = await get_code_file_by_code(code)
201+
if not has or not isinstance(file_code, FileCodes):
202+
raise HTTPException(status_code=404, detail="文件不存在")
203+
if file_code.text is not None or (file_code.suffix or "").lower() not in {".html", ".htm"}:
204+
raise HTTPException(status_code=415, detail="仅支持 HTML 文件预览")
205+
preview_limit = 2 * 1024 * 1024
206+
if file_code.size > preview_limit:
207+
raise HTTPException(status_code=413, detail="HTML 文件过大,无法在线预览")
208+
download = await get_stored_download(file_code)
209+
if download.path is not None:
210+
if download.path.stat().st_size > preview_limit:
211+
raise HTTPException(status_code=413, detail="HTML 文件过大,无法在线预览")
212+
content = await asyncio.to_thread(download.path.read_bytes)
213+
elif download.content is not None:
214+
content = download.content
215+
elif download.stream_factory is not None:
216+
stream = download.stream_factory()
217+
if hasattr(stream, "__aiter__"):
218+
chunks = bytearray()
219+
async for chunk in stream:
220+
chunks.extend(chunk)
221+
if len(chunks) > preview_limit:
222+
raise HTTPException(status_code=413, detail="HTML 文件过大,无法在线预览")
223+
content = bytes(chunks)
224+
else:
225+
raise HTTPException(status_code=500, detail="HTML 预览读取失败")
226+
else:
227+
raise HTTPException(status_code=500, detail="HTML 预览读取失败")
228+
if len(content) > preview_limit:
229+
raise HTTPException(status_code=413, detail="HTML 文件过大,无法在线预览")
230+
safe_html = sanitize_html_preview(content.decode("utf-8-sig", errors="replace"))
231+
return HTMLResponse(
232+
safe_html,
233+
headers={
234+
"Content-Security-Policy": "sandbox; default-src 'none'; img-src data:; style-src 'unsafe-inline'; font-src data:; base-uri 'none'; form-action 'none'",
235+
"X-Content-Type-Options": "nosniff",
236+
"Cache-Control": "private, no-store",
237+
"Content-Disposition": 'inline; filename="preview.html"',
238+
},
239+
background=download.background,
240+
)
241+
242+
197243
@share_api.get("/select/")
198244
async def get_code_file(code: str, ip: str = Depends(ip_limit["error"])):
199245
file_storage: FileStorageInterface = storages[settings.file_storage]()

‎core/settings.py‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,7 @@
4848
"jwt_secret": "",
4949
"admin_session_expire": ADMIN_SESSION_EXPIRE_DEFAULT,
5050
"open_upload": 1,
51+
"mcp_require_token": 0,
5152
"upload_size": 1024 * 1024 * 10,
5253
"allowed_file_types": ["*"],
5354
"expire_style": ["day", "hour", "minute", "forever", "count"],

0 commit comments

Comments
 (0)