mirror of
https://github.com/vastsa/FileCodeBox.git
synced 2026-11-20 13:29:56 +08:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f1fee1edff | ||
|
|
65f4929d40 |
No files matched your search
@@ -1,3 +1,3 @@
|
||||
{
|
||||
".": "2.8.2"
|
||||
".": "2.8.3"
|
||||
}
|
||||
@@ -5,7 +5,6 @@ import html
|
||||
import io
|
||||
import json
|
||||
from typing import Any
|
||||
from html.parser import HTMLParser
|
||||
from urllib.parse import quote, urlsplit
|
||||
|
||||
from fastapi import APIRouter, HTTPException, Request, UploadFile
|
||||
@@ -230,75 +229,3 @@ async def mcp_endpoint(request: Request):
|
||||
_jsonrpc_error(request_id, -32001 if exc.status_code == 401 else -32003, str(exc.detail)),
|
||||
status_code=exc.status_code,
|
||||
)
|
||||
|
||||
|
||||
_SAFE_TAGS = {
|
||||
"a", "abbr", "article", "b", "blockquote", "br", "caption", "code", "dd", "del", "details",
|
||||
"div", "dl", "dt", "em", "figcaption", "figure", "h1", "h2", "h3", "h4", "h5", "h6",
|
||||
"hr", "i", "img", "li", "main", "mark", "ol", "p", "pre", "s", "section", "small", "span",
|
||||
"strong", "sub", "summary", "sup", "table", "tbody", "td", "th", "thead", "tr", "u", "ul",
|
||||
}
|
||||
_VOID_TAGS = {"br", "hr", "img"}
|
||||
_DROP_CONTENT_TAGS = {"script", "style", "iframe", "object", "embed", "svg", "math", "form", "template"}
|
||||
_SAFE_ATTRS = {"alt", "title", "class", "id", "colspan", "rowspan", "width", "height", "scope", "dir", "lang"}
|
||||
|
||||
|
||||
class _HTMLPreviewSanitizer(HTMLParser):
|
||||
"""Whitelist-only HTML serializer; scripts, active embeds and URL attrs are removed."""
|
||||
|
||||
def __init__(self):
|
||||
super().__init__(convert_charrefs=True)
|
||||
self.output: list[str] = []
|
||||
self.drop_depth = 0
|
||||
|
||||
def handle_starttag(self, tag, attrs):
|
||||
tag = tag.lower()
|
||||
if self.drop_depth:
|
||||
if tag in _DROP_CONTENT_TAGS:
|
||||
self.drop_depth += 1
|
||||
return
|
||||
if tag in _DROP_CONTENT_TAGS:
|
||||
self.drop_depth = 1
|
||||
return
|
||||
if tag not in _SAFE_TAGS:
|
||||
return
|
||||
safe_attrs = []
|
||||
for name, value in attrs:
|
||||
name = name.lower()
|
||||
if value is None or name.startswith("on") or name not in _SAFE_ATTRS:
|
||||
continue
|
||||
safe_attrs.append(f' {name}="{html.escape(value, quote=True)}"')
|
||||
self.output.append(f"<{tag}{''.join(safe_attrs)}>")
|
||||
|
||||
def handle_startendtag(self, tag, attrs):
|
||||
self.handle_starttag(tag, attrs)
|
||||
if tag.lower() in _SAFE_TAGS and tag.lower() not in _VOID_TAGS:
|
||||
self.handle_endtag(tag)
|
||||
|
||||
def handle_endtag(self, tag):
|
||||
tag = tag.lower()
|
||||
if self.drop_depth:
|
||||
if tag in _DROP_CONTENT_TAGS:
|
||||
self.drop_depth -= 1
|
||||
return
|
||||
if tag in _SAFE_TAGS and tag not in _VOID_TAGS:
|
||||
self.output.append(f"</{tag}>")
|
||||
|
||||
def handle_data(self, data):
|
||||
if not self.drop_depth:
|
||||
self.output.append(html.escape(data))
|
||||
|
||||
def handle_entityref(self, name):
|
||||
if not self.drop_depth:
|
||||
self.output.append(f"&{html.escape(name)};")
|
||||
|
||||
def handle_charref(self, name):
|
||||
if not self.drop_depth:
|
||||
self.output.append(f"&#{html.escape(name)};")
|
||||
|
||||
|
||||
def sanitize_html_preview(source: str) -> str:
|
||||
parser = _HTMLPreviewSanitizer()
|
||||
parser.feed(source)
|
||||
parser.close()
|
||||
return "<!doctype html><meta charset=\"utf-8\"><meta name=\"viewport\" content=\"width=device-width,initial-scale=1\"><body>" + "".join(parser.output) + "</body>"
|
||||
+1
-46
@@ -1,5 +1,4 @@
|
||||
import hashlib
|
||||
import asyncio
|
||||
import hmac
|
||||
import os
|
||||
import uuid
|
||||
@@ -11,7 +10,7 @@ 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 HTMLResponse, Response
|
||||
from starlette.responses import Response
|
||||
from tortoise.expressions import Case, F, Q, When
|
||||
|
||||
from apps.base.auth import share_required_login
|
||||
@@ -40,7 +39,6 @@ from apps.base.utils import (
|
||||
validate_expire_style,
|
||||
)
|
||||
from apps.base.local_share import is_local_ref
|
||||
from apps.base.mcp import sanitize_html_preview
|
||||
from core.response import APIResponse
|
||||
from core.settings import settings
|
||||
from core.storage import storages, FileStorageInterface
|
||||
@@ -196,49 +194,6 @@ async def post_file_metadata(
|
||||
return APIResponse(detail=build_file_metadata(file_code))
|
||||
|
||||
|
||||
@share_api.get("/preview/html/{code}", include_in_schema=False)
|
||||
async def preview_html(code: str):
|
||||
has, file_code = await get_code_file_by_code(code)
|
||||
if not has or not isinstance(file_code, FileCodes):
|
||||
raise HTTPException(status_code=404, detail="文件不存在")
|
||||
if file_code.text is not None or (file_code.suffix or "").lower() not in {".html", ".htm"}:
|
||||
raise HTTPException(status_code=415, detail="仅支持 HTML 文件预览")
|
||||
preview_limit = 2 * 1024 * 1024
|
||||
if file_code.size > preview_limit:
|
||||
raise HTTPException(status_code=413, detail="HTML 文件过大,无法在线预览")
|
||||
download = await get_stored_download(file_code)
|
||||
if download.path is not None:
|
||||
if download.path.stat().st_size > preview_limit:
|
||||
raise HTTPException(status_code=413, detail="HTML 文件过大,无法在线预览")
|
||||
content = await asyncio.to_thread(download.path.read_bytes)
|
||||
elif download.content is not None:
|
||||
content = download.content
|
||||
elif download.stream_factory is not None:
|
||||
stream = download.stream_factory()
|
||||
if hasattr(stream, "__aiter__"):
|
||||
chunks = bytearray()
|
||||
async for chunk in stream:
|
||||
chunks.extend(chunk)
|
||||
if len(chunks) > preview_limit:
|
||||
raise HTTPException(status_code=413, detail="HTML 文件过大,无法在线预览")
|
||||
content = bytes(chunks)
|
||||
else:
|
||||
raise HTTPException(status_code=500, detail="HTML 预览读取失败")
|
||||
else:
|
||||
raise HTTPException(status_code=500, detail="HTML 预览读取失败")
|
||||
if len(content) > preview_limit:
|
||||
raise HTTPException(status_code=413, detail="HTML 文件过大,无法在线预览")
|
||||
safe_html = sanitize_html_preview(content.decode("utf-8-sig", errors="replace"))
|
||||
return HTMLResponse(
|
||||
safe_html,
|
||||
headers={
|
||||
"Content-Security-Policy": "sandbox; default-src 'none'; img-src data:; style-src 'unsafe-inline'; font-src data:; base-uri 'none'; form-action 'none'",
|
||||
"X-Content-Type-Options": "nosniff",
|
||||
"Cache-Control": "private, no-store",
|
||||
"Content-Disposition": 'inline; filename="preview.html"',
|
||||
},
|
||||
background=download.background,
|
||||
)
|
||||
|
||||
|
||||
@share_api.get("/select/")
|
||||
|
||||
+1
-1
@@ -1,7 +1,7 @@
|
||||
version: "3"
|
||||
services:
|
||||
file-code-box:
|
||||
image: lanol/filecodebox:2.8.2 # 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,5 +1,12 @@
|
||||
# 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)
|
||||
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
## [Unreleased]
|
||||
|
||||
<!-- Current release: 2.8.2 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.8.2 # 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.8.2 # x-release-please-version
|
||||
lanol/filecodebox:2.8.3 # x-release-please-version
|
||||
```
|
||||
|
||||
打开 `http://localhost:12345`,按引导完成首次初始化。
|
||||
|
||||
@@ -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.8.2 # 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.8.2 # 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.
|
||||
|
||||
@@ -1,21 +1,7 @@
|
||||
import base64
|
||||
|
||||
import pytest
|
||||
|
||||
from apps.base.models import KeyValue
|
||||
from apps.base.mcp import sanitize_html_preview
|
||||
|
||||
|
||||
def test_html_preview_sanitizer_removes_active_content_and_event_handlers():
|
||||
output = sanitize_html_preview(
|
||||
'<h1 onclick="alert(1)">Hello</h1><script>alert(2)</script>'
|
||||
'<iframe src="https://attacker.invalid"></iframe><a href="javascript:alert(3)">link</a>'
|
||||
)
|
||||
assert "Hello" in output
|
||||
assert "<script" not in output.lower()
|
||||
assert "onclick" not in output.lower()
|
||||
assert "attacker.invalid" not in output
|
||||
assert "javascript:" not in output.lower()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@@ -83,35 +69,3 @@ async def test_mcp_token_can_be_required(initialized_client):
|
||||
)
|
||||
assert authorized.status_code == 200
|
||||
assert "/#/?code=" in authorized.json()["result"]["structuredContent"]["url"]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_mcp_html_share_has_sandboxed_safe_preview(initialized_client):
|
||||
dangerous_html = '<h1>Hello</h1><script>alert(1)</script><img src=x onerror="alert(2)">'
|
||||
response = await initialized_client.post(
|
||||
"/mcp",
|
||||
json={
|
||||
"jsonrpc": "2.0",
|
||||
"id": 5,
|
||||
"method": "tools/call",
|
||||
"params": {
|
||||
"name": "share_file",
|
||||
"arguments": {
|
||||
"filename": "preview.html",
|
||||
"content_type": "text/html",
|
||||
"content_base64": base64.b64encode(dangerous_html.encode()).decode(),
|
||||
},
|
||||
},
|
||||
},
|
||||
)
|
||||
assert response.status_code == 200
|
||||
code = response.json()["result"]["structuredContent"]["code"]
|
||||
|
||||
preview = await initialized_client.get(f"/share/preview/html/{code}")
|
||||
assert preview.status_code == 200
|
||||
assert preview.headers["content-type"].startswith("text/html")
|
||||
assert "sandbox" in preview.headers["content-security-policy"]
|
||||
assert "Hello" in preview.text
|
||||
assert "<script" not in preview.text.lower()
|
||||
assert "onerror" not in preview.text.lower()
|
||||
assert "nosniff" in preview.headers["x-content-type-options"]
|
||||
Reference in new issue
Block a user