diff --git a/CHANGELOG.md b/CHANGELOG.md index 42a73d1..0af2ab3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,16 @@ ## 2026-11-11 +### 🔒 MCP 端点强制 Bearer 鉴权 + +**公网必须授权(使用 MCP 一定要授权)** + +- `mcp/server.py` 新增入站鉴权中间件:`/mcp` 一律要求 `Authorization: Bearer `(`hmac.compare_digest` 恒定时间比较防时序侧信道),不带 / 错误令牌 → `401` + `WWW-Authenticate: Bearer`;`MCP_AUTH_TOKEN` 未配置时拒绝一切调用(fail-closed) +- 放行两类路径:`/health`(nginx `/mcp-health` 监控探针)、`/out/*`(`/mcp-out/` 工程 ZIP / 配音 mp3 下载直链,浏览器点开无法附带请求头) +- 部署:令牌写项目 `.env` 的 `MCP_AUTH_TOKEN`(git 已忽略不入仓库,`secrets.token_urlsafe(32)` 生成),`docker-compose.yml` 注入该环境变量并重建 `unicut-mcp` +- 文档:mcp/README.md 连接示例全部更新为带鉴权头(Claude Desktop `mcp-remote --header` / Claude Code `--header` / Cursor `headers` / Hermes `mcp_servers.headers`),并修正 Hermes 旧示例错误键名 `mcp: servers:` → 官方 `mcp_servers:`;`.env` 清单与验证 curl 同步加令牌;主 README MCP 章节补授权说明 +- 验证:无令牌 / 错令牌 401 ✓、正确令牌完整握手(initialize 200 + session → initialized 202 → tools/list 9 工具 → `service_status` 真实调用成功)✓、`/mcp-health` 与 `/mcp-out/*.zip` 开放 200 ✓、空令牌 fail-closed 401 ✓ + ### ✨ 素材页下载入口 **工作台素材页新增「下载更多素材」按钮** diff --git a/README.md b/README.md index 01d15ae..8f9a3c2 100644 --- a/README.md +++ b/README.md @@ -53,7 +53,7 @@ | 模板导入修复 | 修复"导入第一个模板后,再导入会把浏览器拖崩"的问题,支持连续换模板 | | 品牌与首页 | 产品名改为米剪,首页新增导航站 / 开源地址入口,移除收费栏目与账号类外链 | | 接入授权中心 | 版本号、公告、检查更新(授权中心不可达时静默降级,绝不拦功能) | -| MCP 接入 | 新增 `unicut-mcp` 服务:Claude / Cursor / Hermes 等 AI 客户端经 `https://<站点>/mcp` 调用抓取文章、生成口播、edge-tts 配音、生成米剪工程 ZIP | +| MCP 接入 | 新增 `unicut-mcp` 服务:Claude / Cursor / Hermes 等 AI 客户端经 `https://<站点>/mcp` 调用抓取文章、生成口播、edge-tts 配音、生成米剪工程 ZIP;端点强制 `Authorization: Bearer` 鉴权(公网必须授权) | ### 最近更新(2026-11-11) @@ -198,6 +198,8 @@ UNICUT 是一款面向创作者、开发者与企业团队的在线视频编辑 米剪内置 [MCP](https://modelcontextprotocol.io)(Model Context Protocol)服务 `unicut-mcp`,站点同源端点 `https://<站点>/mcp`。接入后,Claude Desktop、Claude Code、Cursor、Hermes 等 AI 客户端可以把米剪当工具用: +> 🔒 **端点强制授权**:`/mcp` 暴露在公网,请求必须携带 `Authorization: Bearer `(令牌在项目 `.env`,未配置时拒绝一切调用),否则返回 401;各客户端带鉴权头的接入示例见 [mcp/README.md](./mcp/README.md)。 + | 工具 | 能力 | | --- | --- | | `grab_url` | 抓网页正文与配图(公众号文章可用,规则与编辑器内抓取一致) | @@ -278,6 +280,7 @@ services: - MCP_LLM_KEY=${MCP_LLM_KEY:-} - MCP_LLM_MODEL=${MCP_LLM_MODEL:-mimo-v2.6-flash} - MCP_PUBLIC_URL=${MCP_PUBLIC_URL:-https://127.0.0.1:3005} + - MCP_AUTH_TOKEN=${MCP_AUTH_TOKEN:-} - MCP_PROJECTS_DIR=${MCP_PROJECTS_DIR:-} volumes: # 生成的工程 ZIP / 配音 mp3 落盘(nginx /mcp-out/ 提供下载) diff --git a/docker-compose.yml b/docker-compose.yml index ed4ac1d..79df163 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -35,6 +35,7 @@ services: - MCP_LLM_KEY=${MCP_LLM_KEY:-} - MCP_LLM_MODEL=${MCP_LLM_MODEL:-mimo-v2.6-flash} - MCP_PUBLIC_URL=${MCP_PUBLIC_URL:-https://127.0.0.1:3005} + - MCP_AUTH_TOKEN=${MCP_AUTH_TOKEN:-} - MCP_PROJECTS_DIR=${MCP_PROJECTS_DIR:-} volumes: # 生成的工程 ZIP / 配音 mp3 落盘(nginx /mcp-out/ 提供下载) diff --git a/mcp/README.md b/mcp/README.md index c99e487..5a6bcd8 100644 --- a/mcp/README.md +++ b/mcp/README.md @@ -37,6 +37,8 @@ https://<米剪站点>/mcp ──► unicut-mcp 容器(本目录) **端点**:`https://<米剪站点>/mcp`(Streamable HTTP;本机默认 `https://127.0.0.1:3005/mcp`,自签证书需客户端允许 insecure)。局域网内也可直连容器端口 `http://<主机>:8765/mcp`(默认只在 compose 网络内,未映射宿主端口)。 +> 🔒 **必须授权**:服务暴露在公网,`/mcp` 一律要求请求头 `Authorization: Bearer `(令牌取项目 `.env` 的 `MCP_AUTH_TOKEN`;未配置令牌时服务拒绝一切调用,fail-closed)。不带 / 错误令牌返回 `401 {"error":"unauthorized"}`。仅两类路径开放:`/mcp-health`(监控探针)与 `/mcp-out/*`(工程 ZIP / 配音 mp3 下载直链,浏览器点开无法附带请求头)。 + **Claude Desktop**(`claude_desktop_config.json`): ```json @@ -44,27 +46,39 @@ https://<米剪站点>/mcp ──► unicut-mcp 容器(本目录) "mcpServers": { "unicut": { "command": "npx", - "args": ["mcp-remote", "https://127.0.0.1:3005/mcp", "--allow-self-signed"] + "args": ["mcp-remote", "https://127.0.0.1:3005/mcp", "--allow-self-signed", "--header", "Authorization: Bearer <令牌>"] } } } ``` -**Claude Code / Cursor**: +**Claude Code**: ```bash -claude mcp add unicut --transport http https://127.0.0.1:3005/mcp -# Cursor:~/.cursor/mcp.json → {"mcpServers":{"unicut":{"url":"https://127.0.0.1:3005/mcp"}}} +claude mcp add unicut --transport http --header "Authorization: Bearer <令牌>" https://127.0.0.1:3005/mcp +``` + +**Cursor**(`~/.cursor/mcp.json`): + +```json +{ + "mcpServers": { + "unicut": { + "url": "https://127.0.0.1:3005/mcp", + "headers": { "Authorization": "Bearer <令牌>" } + } + } +} ``` **Hermes**(`~/.hermes` 或项目 `config.yaml`): ```yaml -mcp: - servers: - unicut: - transport: http - url: https://127.0.0.1:3005/mcp +mcp_servers: + unicut: + url: https://127.0.0.1:3005/mcp + headers: + Authorization: "Bearer <令牌>" ``` ## 部署 @@ -77,6 +91,7 @@ MCP_LLM_BASE=http://192.168.68.19:3099/v1 # OpenAI 兼容 /v1 网关 MCP_LLM_KEY=sk-xxxx # 网关 Key MCP_LLM_MODEL=mimo-v2.6-flash MCP_PUBLIC_URL=https://127.0.0.1:3005 # 对外站点地址(生成 zip_url / 音频 URL 用) +MCP_AUTH_TOKEN=<随机长串> # 必填:/mcp 的 Bearer 令牌(公网必须授权;python3 -c 'import secrets;print(secrets.token_urlsafe(32))' 生成) MCP_PROJECTS_DIR= # 可选:米剪「选择文件夹」的同一目录(文件夹模式) ``` @@ -98,10 +113,13 @@ docker run -d --name unicut-mcp --restart always \ ## 验证 ```bash -# 协议握手 +# 协议握手(必须带 Authorization,否则 401) curl -sk https://127.0.0.1:3005/mcp -H 'Content-Type: application/json' \ -H 'Accept: application/json, text/event-stream' \ + -H "Authorization: Bearer $MCP_AUTH_TOKEN" \ -d '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18","capabilities":{},"clientInfo":{"name":"curl","version":"0"}}}' + +# 预期:不带令牌 → 401 {"ok":false,"error":"unauthorized"} + WWW-Authenticate: Bearer ``` 产物下载:`https://<站点>/mcp-out/<工程名>.zip`;健康检查:经 nginx 用 `https://<站点>/mcp-health`,直连容器用 `http://<容器>:8765/health`(`/mcp/health` 不是端点,会被 SPA 回退成首页 HTML)。 diff --git a/mcp/server.py b/mcp/server.py index e5d67f7..11e077b 100644 --- a/mcp/server.py +++ b/mcp/server.py @@ -23,6 +23,7 @@ from __future__ import annotations +import hmac import io import ipaddress import json @@ -53,6 +54,7 @@ LLM_MODEL = os.getenv("MCP_LLM_MODEL", "mimo-v2.6-flash") PUBLIC_URL = os.getenv("MCP_PUBLIC_URL", "https://127.0.0.1:3005").rstrip("/") PROJECTS_DIR = os.getenv("MCP_PROJECTS_DIR", "") # 文件夹模式工作目录(可空) OUT_DIR = Path(os.getenv("MCP_OUT_DIR", "/data/out")) +AUTH_TOKEN = os.getenv("MCP_AUTH_TOKEN", "").strip() # 入站 Bearer 令牌(公网必授权;为空则拒绝一切调用) IMG_MIN_W, IMG_MIN_H = 160, 120 # 与前端 sourceImport.ts 常量一致 IMG_MAX_BYTES = 10 * 1024 * 1024 @@ -833,6 +835,80 @@ except AttributeError: # 老版本 SDK 无 custom_route,静默降级 pass +# ---------------------------------------------------------------- 入站鉴权 +class _AuthMiddleware: + """公网暴露的 MCP 端点强制 Bearer 鉴权(fail-closed:MCP_AUTH_TOKEN 未配置时全部 401)。 + + 放行两类路径: + - /health 监控探针(nginx /mcp-health 转发,无法附带鉴权头) + - /out/* 工具产物下载直链(zip/mp3 交人浏览器点开,无法附带鉴权头) + 其余路径(含 MCP 协议端点 /mcp 与全部未知路径)必须携带 + Authorization: Bearer 。 + """ + + OPEN_EXACT = ("/health",) + OPEN_PREFIX = ("/out/",) + + def __init__(self, app): + self.app = app + + async def __call__(self, scope, receive, send): + if scope["type"] != "http": + await self.app(scope, receive, send) + return + + path = scope.get("path", "") + if path in self.OPEN_EXACT or path.startswith(self.OPEN_PREFIX): + await self.app(scope, receive, send) + return + + headers = {k.decode("latin-1").lower(): v.decode("latin-1") for k, v in scope.get("headers", [])} + got = headers.get("authorization", "") + authorized = ( + bool(AUTH_TOKEN) + and got.startswith("Bearer ") + and hmac.compare_digest(got[7:].strip(), AUTH_TOKEN) # 恒定时间比较,防时序侧信道 + ) + if authorized: + await self.app(scope, receive, send) + return + + detail = ( + "MCP_AUTH_TOKEN not configured on server (fail-closed)" + if not AUTH_TOKEN + else "missing or invalid bearer token" + ) + body = json.dumps({"ok": False, "error": "unauthorized", "detail": detail}, ensure_ascii=False).encode() + await send( + { + "type": "http.response.start", + "status": 401, + "headers": [ + (b"content-type", b"application/json"), + (b"content-length", str(len(body)).encode("ascii")), + (b"www-authenticate", b'Bearer realm="unicut-mcp", charset="UTF-8"'), + ], + } + ) + await send({"type": "http.response.body", "body": body}) + + if __name__ == "__main__": OUT_DIR.mkdir(parents=True, exist_ok=True) - mcp.run(transport="streamable-http") + if not AUTH_TOKEN: + print("[auth] MCP_AUTH_TOKEN 未配置:MCP 端点将拒绝一切调用(公网必须授权,fail-closed)", flush=True) + else: + print(f"[auth] MCP Bearer 鉴权已启用(令牌 {len(AUTH_TOKEN)} 字符)", flush=True) + + import anyio + import uvicorn + + app = mcp.streamable_http_app() # 含 /mcp 路由、自定义路由与 session-manager lifespan + app.add_middleware(_AuthMiddleware) # 鉴权中间件(最外层) + config = uvicorn.Config( + app, + host=mcp.settings.host, + port=mcp.settings.port, + log_level=mcp.settings.log_level.lower(), + ) + anyio.run(uvicorn.Server(config).serve)