Skip to content

Commit 65f4929

Browse files
committed
fix: remove HTML preview endpoint
1 parent 40f22de commit 65f4929

3 files changed

Lines changed: 1 addition & 165 deletions

File tree

‎apps/base/mcp.py‎

Lines changed: 0 additions & 73 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,6 @@
55
import io
66
import json
77
from typing import Any
8-
from html.parser import HTMLParser
98
from urllib.parse import quote, urlsplit
109

1110
from fastapi import APIRouter, HTTPException, Request, UploadFile
@@ -230,75 +229,3 @@ async def mcp_endpoint(request: Request):
230229
_jsonrpc_error(request_id, -32001 if exc.status_code == 401 else -32003, str(exc.detail)),
231230
status_code=exc.status_code,
232231
)
233-
234-
235-
_SAFE_TAGS = {
236-
"a", "abbr", "article", "b", "blockquote", "br", "caption", "code", "dd", "del", "details",
237-
"div", "dl", "dt", "em", "figcaption", "figure", "h1", "h2", "h3", "h4", "h5", "h6",
238-
"hr", "i", "img", "li", "main", "mark", "ol", "p", "pre", "s", "section", "small", "span",
239-
"strong", "sub", "summary", "sup", "table", "tbody", "td", "th", "thead", "tr", "u", "ul",
240-
}
241-
_VOID_TAGS = {"br", "hr", "img"}
242-
_DROP_CONTENT_TAGS = {"script", "style", "iframe", "object", "embed", "svg", "math", "form", "template"}
243-
_SAFE_ATTRS = {"alt", "title", "class", "id", "colspan", "rowspan", "width", "height", "scope", "dir", "lang"}
244-
245-
246-
class _HTMLPreviewSanitizer(HTMLParser):
247-
"""Whitelist-only HTML serializer; scripts, active embeds and URL attrs are removed."""
248-
249-
def __init__(self):
250-
super().__init__(convert_charrefs=True)
251-
self.output: list[str] = []
252-
self.drop_depth = 0
253-
254-
def handle_starttag(self, tag, attrs):
255-
tag = tag.lower()
256-
if self.drop_depth:
257-
if tag in _DROP_CONTENT_TAGS:
258-
self.drop_depth += 1
259-
return
260-
if tag in _DROP_CONTENT_TAGS:
261-
self.drop_depth = 1
262-
return
263-
if tag not in _SAFE_TAGS:
264-
return
265-
safe_attrs = []
266-
for name, value in attrs:
267-
name = name.lower()
268-
if value is None or name.startswith("on") or name not in _SAFE_ATTRS:
269-
continue
270-
safe_attrs.append(f' {name}="{html.escape(value, quote=True)}"')
271-
self.output.append(f"<{tag}{''.join(safe_attrs)}>")
272-
273-
def handle_startendtag(self, tag, attrs):
274-
self.handle_starttag(tag, attrs)
275-
if tag.lower() in _SAFE_TAGS and tag.lower() not in _VOID_TAGS:
276-
self.handle_endtag(tag)
277-
278-
def handle_endtag(self, tag):
279-
tag = tag.lower()
280-
if self.drop_depth:
281-
if tag in _DROP_CONTENT_TAGS:
282-
self.drop_depth -= 1
283-
return
284-
if tag in _SAFE_TAGS and tag not in _VOID_TAGS:
285-
self.output.append(f"</{tag}>")
286-
287-
def handle_data(self, data):
288-
if not self.drop_depth:
289-
self.output.append(html.escape(data))
290-
291-
def handle_entityref(self, name):
292-
if not self.drop_depth:
293-
self.output.append(f"&amp;{html.escape(name)};")
294-
295-
def handle_charref(self, name):
296-
if not self.drop_depth:
297-
self.output.append(f"&amp;#{html.escape(name)};")
298-
299-
300-
def sanitize_html_preview(source: str) -> str:
301-
parser = _HTMLPreviewSanitizer()
302-
parser.feed(source)
303-
parser.close()
304-
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: 1 addition & 46 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
11
import hashlib
2-
import asyncio
32
import hmac
43
import os
54
import uuid
@@ -11,7 +10,7 @@
1110
from fastapi import APIRouter, Form, Request, UploadFile, File, Depends, HTTPException
1211
from pydantic import BaseModel, ValidationError
1312
from starlette import status
14-
from starlette.responses import HTMLResponse, Response
13+
from starlette.responses import Response
1514
from tortoise.expressions import Case, F, Q, When
1615

1716
from apps.base.auth import share_required_login
@@ -40,7 +39,6 @@
4039
validate_expire_style,
4140
)
4241
from apps.base.local_share import is_local_ref
43-
from apps.base.mcp import sanitize_html_preview
4442
from core.response import APIResponse
4543
from core.settings import settings
4644
from core.storage import storages, FileStorageInterface
@@ -196,49 +194,6 @@ async def post_file_metadata(
196194
return APIResponse(detail=build_file_metadata(file_code))
197195

198196

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

243198

244199
@share_api.get("/select/")

‎tests/test_mcp_upload.py‎

Lines changed: 0 additions & 46 deletions
Original file line numberDiff line numberDiff line change
@@ -1,21 +1,7 @@
1-
import base64
21

32
import pytest
43

54
from apps.base.models import KeyValue
6-
from apps.base.mcp import sanitize_html_preview
7-
8-
9-
def test_html_preview_sanitizer_removes_active_content_and_event_handlers():
10-
output = sanitize_html_preview(
11-
'<h1 onclick="alert(1)">Hello</h1><script>alert(2)</script>'
12-
'<iframe src="https://attacker.invalid"></iframe><a href="javascript:alert(3)">link</a>'
13-
)
14-
assert "Hello" in output
15-
assert "<script" not in output.lower()
16-
assert "onclick" not in output.lower()
17-
assert "attacker.invalid" not in output
18-
assert "javascript:" not in output.lower()
195

206

217
@pytest.mark.asyncio
@@ -83,35 +69,3 @@ async def test_mcp_token_can_be_required(initialized_client):
8369
)
8470
assert authorized.status_code == 200
8571
assert "/#/?code=" in authorized.json()["result"]["structuredContent"]["url"]
86-
87-
88-
@pytest.mark.asyncio
89-
async def test_mcp_html_share_has_sandboxed_safe_preview(initialized_client):
90-
dangerous_html = '<h1>Hello</h1><script>alert(1)</script><img src=x onerror="alert(2)">'
91-
response = await initialized_client.post(
92-
"/mcp",
93-
json={
94-
"jsonrpc": "2.0",
95-
"id": 5,
96-
"method": "tools/call",
97-
"params": {
98-
"name": "share_file",
99-
"arguments": {
100-
"filename": "preview.html",
101-
"content_type": "text/html",
102-
"content_base64": base64.b64encode(dangerous_html.encode()).decode(),
103-
},
104-
},
105-
},
106-
)
107-
assert response.status_code == 200
108-
code = response.json()["result"]["structuredContent"]["code"]
109-
110-
preview = await initialized_client.get(f"/share/preview/html/{code}")
111-
assert preview.status_code == 200
112-
assert preview.headers["content-type"].startswith("text/html")
113-
assert "sandbox" in preview.headers["content-security-policy"]
114-
assert "Hello" in preview.text
115-
assert "<script" not in preview.text.lower()
116-
assert "onerror" not in preview.text.lower()
117-
assert "nosniff" in preview.headers["x-content-type-options"]

0 commit comments

Comments
 (0)