mcp开发
](https://pypi.org/project/mcp-devdiag/)      
模型上下文协议服务器 安全生产自主开发诊断提供用于读取日志、环境状态、CORS配置、网络摘要和基于角色的访问控制的实时探测的工具。
现在包括: 独立HTTP服务器 用于EvalForge和CI集成(FastAPI+JWT+速率限制)。
特性
- 🔒 安全生产:采样、编辑和基于同种异体的探测
- 🎯 基于角色的访问控制(RBAC):具有JWT身份验证的读者和操作员角色
- 📊 指标集成:用于速率和延迟的Prometheus/OTLP适配器
- 🔍 智能探测:允许使用标头编校列出的URL诊断
- 📈 自适应采样:开发、暂存和生产的可配置速率
- 🛡️ 安全第一:prod中没有请求/响应体,敏感的标头过滤
范围
支持的环境
- 发展:完整记录,无采样(100%),无限制访问
- 暂存:中等抽样(5-10%),对大多数用户只读
- 生产:最低抽样(1-5%),严格的分配,审计记录
操作模式
dev-完全访问,无限制prod:observe-带有采样的只读指标和日志prod:incident-TTL自动恢复的临时提升访问权限
安装
# Latest release
pip install mcp-devdiag
# Pinned version
pip install "mcp-devdiag==0.2.0"
# With optional extras for add-ons
pip install "mcp-devdiag[playwright,export]" # DOM checks + S3 export
# From GitHub
pip install "mcp-devdiag @ git+https://github.com/leok974/mcp-devdiag.git@v0.2.0"
# From source
pip install -e .任选附件
安装增强诊断的附加组件:
# Playwright driver (runtime DOM/console checks - staging only)
pip install "mcp-devdiag[playwright]"
playwright install chromium
# S3 export (redacted incident snapshots)
pip install "mcp-devdiag[export]"
# All add-ons
pip install "mcp-devdiag[playwright,export]"看 docs/ADDONS.md 获取完整的附加组件文档。
快速开始
消费者快速入门 (复制/粘贴):
# Install
pip install mcp-devdiag==0.2.0
# Run MCP server
mcp-devdiag --stdio
# Or: python -m mcp_devdiag --stdio配置VS代码 (settings.json):
{
"mcpServers": {
"mcp-devdiag": {
"command": "mcp-devdiag",
"args": ["--stdio"]
}
}
}最小配置 (devdiag.yaml):
mode: dev
tenant: my-app
rbac:
provider: jwt
jwks_url: "https://auth.example.com/.well-known/jwks.json"
allow_probes:
- "GET https://api.example.com/**"60秒烟雾测试(复制/粘贴)
# Set once
BASE="$DEVDIAG_URL" # e.g. https://diag.example.com
JWT="$DEVDIAG_READER_JWT" # reader token (JWKS-backed)
APP="https://app.example.com" # target app base
# 1) HTTP-only quickcheck (CI safe)
curl -s -X POST "$BASE/mcp/diag/quickcheck" \
-H "Authorization: Bearer $JWT" -H "Content-Type: application/json" \
-d "{\"url\":\"$APP/chat/\"}" | jq
# 2) Full status with score + fixes
curl -s -G "$BASE/mcp/diag/status_plus" \
--data-urlencode "base_url=$APP" \
-H "Authorization: Bearer $JWT" | jq
# 3) Probe schema (for client typing)
curl -s "$BASE/mcp/diag/schema/probe_result" \
-H "Authorization: Bearer $JWT" | jq迁移(0.1.x→ 0.2.0)
如果从v0.1.x升级:
所需更改 devdiag.yaml:
- 添加
rbac.jwks_url: "https://auth.example.com/.well-known/jwks.json" - 添加
allow_probes:使用您允许的显式URL模式 - 添加
diag:块(可选,用于预设/覆盖)
可采用的可选新功能:
- 新端点:
/mcp/diag/status_plus(得分+定位球),/mcp/diag/quickcheck(仅限CI HTTP) - 导入
dashboards/devdiag.json进入Grafana进行即时监控 - 启用
.github/workflows/devdiag-quickcheck.yml用于PR验证 - 使用
/mcp/diag/schema/probe_result用于TypeScript类型生成
重大变化: 没有。 get_status 保持向后兼容; status_plus 添加新字段。
配置
最小devdiag.yaml骨架(任何项目)
mode: prod:observe
tenant: default
allow_probes:
- "GET https://app.example.com/healthz"
- "GET https://app.example.com/api/ready"
- "HEAD https://cdn.example.com/**"
sampling:
frontend_events: 0.02
network_spans: 0.02
retention:
logs_ttl_days: 7
metrics_ttl_days: 30
rbac:
provider: jwt
jwks_url: "https://auth.example.com/.well-known/jwks.json"
roles:
- name: reader
can: [get_status, get_network_summary, get_metrics, get_request_diagnostics]
- name: operator
can: ["*"]
redaction:
headers_deny: [authorization, cookie, set-cookie, x-api-key]
diag:
portal_roots: ["#__PORTAL_ROOT__", "#toast-root", "#__NEXT_PORTAL__"]
overlay_min_width_pct: 0.85
overlay_min_height_pct: 0.50
handshake: { message_types: ["chat:ready","embed:ready"], timeout_ms: 3000 }
csp:
must_include:
- directive: "frame-ancestors"
any_of: ["'self'", "https://*.example.com"]
forbidden_xfo: ["DENY"]完整配置示例
创建 devdiag.yaml 在项目根目录中:
mode: prod:observe
tenant: yourapp
allow_probes:
- "GET https://api.yourapp.com/healthz"
- "HEAD https://cdn.yourapp.com/**"
sampling:
frontend_events: 0.02 # 2%
network_spans: 0.02 # 2%
backend_logs: "rate:5/sec"
retention:
logs_ttl_days: 7
metrics_ttl_days: 30
rbac:
provider: jwt
roles:
- name: reader
can: [get_status, get_network_summary, get_metrics]
- name: operator
can: ["*"]
redaction:
headers_deny: [authorization, cookie, set-cookie, x-api-key]
path_params_regex: ["^/users/\\d+", "^/tokens/[^/]+"]
query_keys_deny: [token, key, code]用法
运行MCP服务器
mcp-devdiag --stdioVS代码/副本集成
添加到您的 .vscode/settings.json:
{
"mcpServers": {
"mcp-devdiag": {
"command": "mcp-devdiag",
"args": ["--stdio"]
}
}
}副驾驶提示:
- “运行mcp.devdiag.status_plushttps://app.example.com并打印修复。"
- “快速检查聊天路径,并为任何CSP问题提出nginx/header补丁。”
- “获取探测模式并为ProbeResult生成TypeScript类型。”
可用工具
读者角色
get_status()-全面的诊断快照get_network_summary()-聚合网络指标get_metrics(window)-Prometheus支持的速率和延迟get_request_diagnostics(url, method)-实时探头(仅限allowlist)diag_status_plus(base_url, preset)-具有评分的管理员等级状态diag_quickcheck(url)-快速HTTP专用CSP/嵌入检查(CI安全)diag_bundle(url, driver, preset)-多探头诊断包diag_probe_csp_headers(url)-CSP和iframe兼容性检查diag_remediation(problems)-获取问题代码的修复
操作员角色
set_mode(mode, ttl_seconds)-更改操作模式export_snapshot()-用于事件分析的捆绑日志compare_envs(a, b)-不同的环境配置
HTTP API示例
单次烟雾测试(复制/粘贴)
# Set once
BASE="$DEVDIAG_URL" # e.g., https://diag.example.com
JWT="$DEVDIAG_READER_JWT" # reader token
APP="https://app.example.com"
# HTTP-only quickcheck (CI-safe)
curl -s -X POST "$BASE/mcp/diag/quickcheck" \
-H "Authorization: Bearer $JWT" -H "Content-Type: application/json" \
-d "{\"url\":\"$APP/chat/\"}" | jq
# Status + scoring + fix recipes
curl -s -G "$BASE/mcp/diag/status_plus" \
--data-urlencode "base_url=$APP" \
-H "Authorization: Bearer $JWT" | jq
# ProbeResult schema (client integration)
curl -s "$BASE/mcp/diag/schema/probe_result" \
-H "Authorization: Bearer $JWT" | jq如果 ok:false 和 score>0,你会得到 fixes{code:[steps...]} 准备在UI中出现。
目标CSP检查(CI使用)
# CSP headers validation for chat embedding
curl -s -X POST "$HOST/mcp/diag/probe_csp_headers" \
-H "Authorization: Bearer $READER" \
-H "Content-Type: application/json" \
-d '{"url":"https://app.example.com/chat/"}' | jq与预设捆绑
# Full diagnostic bundle with "app" preset
curl -s -X POST "$HOST/mcp/diag/bundle" \
-H "Authorization: Bearer $READER" \
-H "Content-Type: application/json" \
-d '{"url":"https://app.example.com", "preset":"app"}' | jq局限性
生产限制
- 无请求/响应机构:中的设计禁用了身体捕捉
prod:*模式 - 仅采样:高容量端点采样率≤5%,以尽量减少开销
- 允许列表探测:只能通过以下方式探测预先批准的URL
get_request_diagnostics - 标题修改:自动过滤敏感标头(身份验证、Cookie)
- 速率限制:后端日志尾随限制为5行/秒
隐私和安全
- JWT验证:目前使用轻量级JWT解析;使用完整的JWKS验证进行部署
- 审计日志:所有操作员操作记录到OTLP/S3
- TTL自动还原:配置TTL后,事件模式自动恢复
运营
RBAC角色
- 读者:对指标、日志和摘要的只读访问(所有用户的默认设置)
- 操作员:可以更改模式、导出快照和比较环境
入射模式
暂时提高活动事件的记录/采样:
set_mode("prod:incident", ttl_seconds=3600) # Auto-revert after 1 hour指标集成
集 PROM_URL 环境变量:
export PROM_URL=http://prometheus:9090
mcp-devdiag --stdioGrafana快速面板
将这些粘贴到Grafana仪表板中:
统计面板:HTTP 5xx速率
- 查询:
sum(rate(http_requests_total{code=~"5.."}[5m])) - 单位:需求/秒
- 阈值:红色>0.5
统计面板:HTTP 4xx速率
- 查询:
sum(rate(http_requests_total{code=~"4.."}[5m])) - 单位:需求/秒
- 阈值:警告>2.0
测量:探测成功
- 查询:
avg(probe_success{job=~"blackbox.*"}) - 最小值:0,最大值:1
- 阈值:红色\/mcp/diag/status_plus?base_url=${__url.params:app}
**标头**:
Authorization: Bearer ${secret:DEVDIAG_READER_JWT}
**面板路径**:
- 问题: `$.problems`
- 分数: `$.score`
- 修复: `$.fixes`
- 严重程度: `$.severity`
## 客户端SDK
### TypeScript
从JSON模式生成类型:
npx quicktype -s schema -o src/types/devdiag.ts mcp_devdiag/schemas/probe_result.json
或者使用现成的SDK:
// Install dependencies first: npm install zod // See docs/examples/devdiag.ts import { statusPlus, quickcheck } from './devdiag';
const client = { baseUrl: "https://diag.example.com", jwt: process.env.DEVDIAG_JWT! }; const result = await statusPlus(client, "https://app.example.com", "full");
### python
See docs/examples/devdiag_client.py
from devdiag_client import DevDiagClient
client = DevDiagClient(base_url=os.environ["DEVDIAG_URL"], jwt=os.environ["DEVDIAG_JWT"]) result = client.status_plus("https://app.example.com", preset="full")
从以下位置复制SDK文件 `docs/examples/` 到你的项目。
## HTTP服务器
**独立的FastAPI包装器** 用于从EvalForge web应用程序和CI管道调用DevDiag。包括JWT认证(JWKS)、速率限制和SSRF保护。
### 快速开始
Local development (no auth)
cd apps/devdiag-http pip install -r requirements.txt uvicorn main:app --reload --port 8080
Test
curl -s http://127.0.0.1:8080/healthz curl -s -X POST "http://127.0.0.1:8080/diag/run" \ -H "Content-Type: application/json" \ -d '{"url":"https://www.leoklemet.com","preset":"app"}' | jq .
### Docker Compose
docker compose -f docker-compose.devdiag.yml up -d --build curl -s http://127.0.0.1:8080/healthz
### 配置
环境变量:
- `JWKS_URL`:JWT验证的JWKS端点(空=本地开发禁用身份验证)
- `JWT_AUD`:JWT受众声明(默认值: `mcp-devdiag`)
- `RATE_LIMIT_RPS`:每秒请求数限制(默认值:2.0)
- `ALLOW_PRIVATE_IP`:允许私有/环回IP(默认值:0,本地测试设置为1)
- `ALLOWED_ORIGINS`:CORS起源(逗号分隔)
- `ALLOW_TARGET_HOSTS`:服务器端为目标URL分配列表(支持 `.domain.com`、确切的主机, `pr-*.domain.com` 地球仪)
- `DEVDIAG_CLI`:CLI二进制名称(默认值: `mcp-devdiag`)
- `DEVDIAG_TIMEOUT_S`:CLI超时(默认值:180秒)
- `MAX_CONCURRENT`:最大并发运行数(默认值:2)
### API终点
**`POST /diag/run`** -对URL运行诊断
请求:
{ "url": "https://example.com", "preset": "app", "suppress": ["CSP_FRAME_ANCESTORS"], "extra_args": ["--verbose"] }
答复:
{ "ok": true, "url": "https://example.com", "preset": "app", "result": {"problems": [], "fixes": {}, "evidence": {}} }
**`GET /healthz`** -健康检查(也支持HEAD)\
**`GET /selfcheck`** -验证CLI可用性(可用于调试502错误)\
**`GET /ready`** -准备就绪探测(CLI+满列表+JWKS检查,用于K8s)\
**`GET /metrics`** -Prometheus兼容指标\
**`GET /probes`** -列出可用预设
### 部署
**云运行:**
gcloud run deploy devdiag-http \ --image ghcr.io/leok974/mcp-devdiag/devdiag-http:latest \ --set-env-vars JWKS_URL=https://YOUR-IDP/.well-known/jwks.json \ --set-env-vars JWT_AUD=mcp-devdiag \ --set-env-vars ALLOWED_ORIGINS=https://evalforge.app \ --set-env-vars ALLOW_TARGET_HOSTS=.ledger-mind.org
**Fly.io/渲染:** 看 `apps/devdiag-http/README.md` 获取完整的部署指南。
### EvalForge集成
**选项1:直接前端呼叫**
const response = await fetch('http://127.0.0.1:8080/diag/run', { method: 'POST', headers: { 'Content-Type': 'application/json', 'Authorization': Bearer ${jwt}, }, body: JSON.stringify({url: 'https://example.com', preset: 'app'}), }); const data = await response.json();
**选项2:后端代理(推荐)**
从前端隐藏JWT,添加主机分配列表验证,并提供重试逻辑。
apps/backend/app/routes/devdiag_proxy.py
from app.routes import devdiag_proxy
app.include_router(devdiag_proxy.router, tags=["ops"])
Environment
DEVDIAG_BASE=https://devdiag-http.example.run.app DEVDIAG_JWT= DEVDIAG_ALLOW_HOSTS=.ledger-mind.org,app.ledger-mind.org
// Frontend calls backend proxy (no JWT needed) const res = await fetch('/ops/diag', { method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify({url: 'https://app.ledger-mind.org', preset: 'app'}), });
完整文档:
- **HTTP服务器**: [apps/devdiag http://README.md](apps/devdiag-http/README.md)
- **后端代理**: [apps/backend/app/routes/README.md](apps/backend/app/routes/README.md)
## 部署
### Docker Compose
See deployments/docker-compose.yml
docker-compose up -d
### Kubernetes
See deployments/kubernetes.yaml
kubectl apply -f deployments/kubernetes.yaml
**健康检查**:
- 生活: `GET /healthz` (端口8000,延迟10秒,周期10秒)
- 准备就绪: `GET /ready` (端口8000,延迟5秒,周期5秒)
## 预建资产
### Grafana仪表板
导入 `dashboards/devdiag.json` 通过以下方式进行即时监控:
- HTTP 5xx速率(阈值:0.5请求/秒)
- 探测成功率(阈值:95%)
- 顶部探头问题
- 响应延迟p90(阈值:300ms/500ms)
### 邮差收藏
导入 `postman/devdiag.postman_collection.json` 快速测试:
- 集 `DEVDIAG_JWT` 环境变量
- 配置 `BASE_URL` 和 `TARGET_URL`
- 包括:快速检查、状态加、修复、捆绑包、模式、单个探测
## 附加组件
### 编剧司机(仅限舞台)
启用运行时DOM检查和控制台日志捕获:
devdiag.yaml
diag: browser_enabled: true # Enable Playwright driver
Install Playwright
pip install playwright playwright install chromium
Use in probes
curl -s -X POST "$BASE/mcp/diag/bundle" \ -H "Authorization: Bearer $JWT" \ -H "Content-Type: application/json" \ -d '{"url":"https://app.example.com","driver":"playwright","preset":"full"}' | jq
**备注**:仅在dev/stating中启用。生产应该使用仅HTTP驱动程序。
### 抑制
忽略诊断中的已知/故意问题:
devdiag.yaml
diag: suppress: - code: "PORTAL_ROOT_MISSING" reason: "App uses native toasts; no portal needed" - code: "FRAMEWORK_VERSION_MISMATCH" reason: "Deliberate canary test in staging"
被抑制的问题会从捆绑包结果中过滤出来,但会记录下来以供审计。
### S3导出
导出编辑后的诊断包以进行事件分析:
devdiag.yaml
export: s3_bucket: "mcp-devdiag-artifacts" region: "us-east-1"
Export snapshot (operator role required)
pip install boto3
curl -s -X POST "$BASE/mcp/devdiag/export_snapshot" \ -H "Authorization: Bearer $OPERATOR_JWT" \ -H "Content-Type: application/json" \ -d '{"problems":["CSP_MISSING"],"score":5,"evidence":{}}' | jq
导出会自动编辑(没有标头、正文或身份验证令牌),并使用AES256-SSE加密。
### 闭环学习
DevDiag包括 **闭环学习** 自动学习哪些修复程序在哪些环境中工作。启用时:
- 记录每次诊断运行(问题、证据、环境指纹)
- 当问题在修复后消失时,DevDiag认为修复是成功的
- 未来的建议按以下方式对修复进行排名 **置信度得分** (支持×环境相似性)
**配置** (`devdiag.yaml`):
learn: enabled: true store: "sqlite:///devdiag.db" # or PostgreSQL connection string privacy: hash_targets: true # hash URLs to target_hash (privacy-first) keep_evidence_keys: ["csp", "xfo", "framework", "server", "routes"] retention_days: 180 # data retention (default 6 months) min_support: 2 # min fix successes before suggesting alpha: 0.6 # confidence α for support scaling beta: 0.7 # confidence β for similarity weighting
**隐私保证**:
- ✅ **未存储尸体或秘密** -仅安全证据密钥(CSP、框架等)
- ✅ **目标URL哈希** 当 `hash_targets: true` (默认)
- ✅ **无请求/响应数据** -只有问题代码和修复配方
- ✅ **租户隔离** -每个租户的学习数据都是单独的
- ✅ **可配置的保留** -自动清除旧数据(默认180天)
**运作原理**:
1. **记录**:每个 `diag_status_plus()` 通话记录问题+环境
1. **检测**:如果问题在下次运行时消失,则归功于应用的修复
1. **学习**:根据以下内容建立信心评分:
- **支持** -这个修复程序工作了多少次
- **相似性** -当前的环境与过去的成功有多相似
1. **建议**:当同样的问题再次出现时,按置信度进行排名修复
**示例用法**:
status_plus automatically records runs when learning is enabled
result = await diag_status_plus(base_url="https://app.example.com", preset="chat")
Manually query suggestions for a specific problem
from mcp_devdiag.tools_learn import learn_suggest suggestions = await learn_suggest( problem_code="CSP_INLINE_BLOCKED", evidence={"framework": "react@18.3.1", "xfo": "DENY"}, tenant="my-app" )
Returns: [{"fix_code": "FIX_CSP_NONCE", "confidence": 0.85, "support": 12}, ...]
**选择退出**:设置 `learn.enabled: false` 禁用学习。禁用时不会收集任何数据。
## 建议的后续步骤(可选)
未来需要考虑的增强功能:
1. **OpenAPI摘要** 刀具反思路径研究
1. **剧作家司机** 后面 `diag.browser_enabled=true` 用于运行时DOM检查
1. **抑制** 在 `devdiag.yaml`:suppress: - code: "PORTAL_ROOT_MISSING" reason: "Native toasts; no portal needed"
看 `TODO.md` 查看完整的路线图和工作量估算。
## 使用模式
### 用于开发/IDE和纯CLI CI的MCP(stdio)
使用 **`scripts/mcp_probe.py`** 直接与 `mcp-devdiag --stdio` 如果没有HTTP服务器:
Run probe via MCP stdio
python scripts/mcp_probe.py --url https://www.leoklemet.com --preset app --pretty
CI usage with policy gate
python scripts/mcp_probe.py --url https://app.example.com --preset app \ --max-problems 25 > diag.json
Customize CLI binary and timeout
export MCP_DEV_DIAG_BIN="mcp-devdiag" export MCP_PROBE_TIMEOUT_S=240 python scripts/mcp_probe.py --url https://example.com --preset full
**环境变量:**
- `MCP_DEV_DIAG_BIN` -CLI二进制名称(默认值: `mcp-devdiag`)
- `MCP_PROBE_TIMEOUT_S` -超时时间(秒)(默认值: `180`)
**退出代码:**
- `0` -成功
- `1` -错误(未找到CLI,响应无效)
- `2` -问题太多(当 `--max-problems` 超过阈值)
**VS代码任务集成:**
看 `.vscode/tasks.json` 通过以下方式快速访问 `Tasks: Run Task` 菜单。
**完整文档:** [docs/MCP_STDIO.md](docs/MCP_STDIO.md)
### 应用程序/团队的HTTP
使用 **HTTP服务器** (`apps/devdiag-http`)当你需要:
- JWT身份验证(JWKS)
- 速率限制(默认值:2 RPS)
- SSRF保护
- 主机分配
- 多租户隔离
- 后端代理模式(从前端隐藏JWT)
看 [HTTP服务器](#http-server) 上面的部分。
## 兼容性
|区域|默认值|注释|
|----------------------|---------|-----------------------------------------|
|运行时|HTTP|浏览器驱动程序可选(Playwright)|
|Auth|JWKS|RS256;aud= `mcp-devdiag` |
|Prod capture |关闭|从来没有尸体;标题已编辑|
|探测器|CSP/DOM|仅在HTTP中优雅降级|
|CI |快速| `/mcp/diag/quickcheck` 或 `scripts/mcp_probe.py` |
## 隐私和数据处理
- ✅ **未捕获请求正文** 在任何模式下
- ✅ **身份验证标头和Cookie** 从未坚持过;服务器端强制拒绝列表
- ✅ **探测器允许列表** 必须明确包含每个URL模式
- ✅ **SSRF防护装置** 默认情况下阻止RFC1918+127.0.0.0/8+169.254.0.0/16
- ✅ **保留** 可配置;默认7天日志/30天指标
看 `SECURITY.md` 获取完整的安全文档和合规说明。
## 发展
Setup
python -m venv .venv source .venv/bin/activate # or .venv\Scripts\activate on Windows pip install -e . pip install -r requirements-dev.txt
Run tests
pytest
Run policy tests
pytest tests/test_devdiag_policy.py -v
Lint
ruff check . ruff format .
Type check
mypy mcp_devdiag
### 发布到PyPI
对于发布新版本的维护人员:
1. **配置PyPI凭据** (一次性设置):
# Create ~/.pypirc (Linux/Mac) or C:\Users\USERNAME\.pypirc (Windows) # Get tokens from: https://pypi.org/manage/account/token/
[distutils] index-servers = pypi testpypi
[pypi] username = __token__ password = YOUR_PYPI_API_TOKEN_HERE
[testpypi] repository = https://test.pypi.org/legacy/ username = __token__ password = YOUR_TESTPYPI_API_TOKEN_HERE
1. **构建和发布**:
# Build distributions python -m build
# Validate packages twine check dist/*
# Test upload (recommended first) twine upload --repository testpypi dist/mcp_devdiag-X.Y.Z*
# Production upload twine upload dist/mcp_devdiag-X.Y.Z*
1. **验证安装**:
pip install mcp-devdiag==X.Y.Z mcp-devdiag --help
## 使用的文件
- `.tasteos_logs/backend.log` -后端应用程序日志
- `.tasteos_logs/frontend.log` -前端控制台日志
- `.tasteos_logs/network.jsonl` -网络请求遥测
- `.tasteos_logs/env.json` -环境配置快照
## 安全
### 秘密扫描
此存储库使用 [Gitleaks](https://github.com/gitleaks/gitleaks) 以防止意外提交机密(API密钥、令牌、密码)。
**对于贡献者:**
克隆存储库后,运行安装脚本安装git钩子:
Windows (PowerShell)
.\scripts\setup-git-hooks.ps1
Linux/macOS
./scripts/setup-git-hooks.sh
**手动安装:**
Windows
winget install gitleaks
macOS
brew install gitleaks
Linux
curl -sSL https://github.com/gitleaks/gitleaks/releases/download/v8.29.0/gitleaks_8.29.0_linux_x64.tar.gz -o /tmp/gitleaks.tar.gz tar -xzf /tmp/gitleaks.tar.gz -C /tmp sudo mv /tmp/gitleaks /usr/local/bin/
**预提交挂钩:**
预提交钩子在每次提交之前自动扫描暂存文件中的秘密。如果检测到秘密:
1. **删除秘密** 并改用环境变量
1. **增添 `.gitleaksignore`** 如果是假阳性
1. **旁路(不建议):** `git commit --no-verify`
**CI/CD:**
GitHub Actions在每次推送和拉取请求时运行Gitleaks(`.github/workflows/security-scan.yml`).
## 许可证
MIT许可证-请参阅许可证文件