与 mitmproxy 对比
如果你用过 mitmproxy 的 Python addon,这份对比说明 RelayCore 脚本在钩子、数据模型和工具链上的异同。详细 API 见脚本 API,实践模式见脚本开发指引。
能力对照
| 能力 | RelayCore | mitmproxy | 说明 |
|---|---|---|---|
| HTTP 请求/响应钩子 | ✅ 4 钩子 | ✅ 4 钩子 | 功能对等 |
| WebSocket 消息帧 | ✅ | ✅ | 功能对等 |
| WebSocket 生命周期 | ✅ start/end/error | ✅ | 功能对等 |
| 连接级钩子 | ✅ onConnect/onDisconnect | ✅ clientconnect/clientdisconnect | RelayCore 支持连接拒绝(drop) |
| 错误回调 | ✅ onError | ✅ error | RelayCore 含 stage 定位 |
| 跨请求状态 | ✅ sharedState | ✅ Python 全局变量 | 模型不同:per-isolate vs 进程全局 |
| 环境变量 | ✅ relay.env + 白名单 | ✅ os.environ | RelayCore 需 --script-env-allow |
| 日志 | ✅ console.* → tracing | ✅ logging | 功能对等 |
| 执行指标 | ✅ Prometheus | ✅ addon trace | RelayCore 接入 /api/v1/metrics |
| 内置工具 | ✅ relay.* | ✅ Python 标准库 | 语言生态差异 |
| 子请求 | ✅ relay.fetch(可选) | ✅ requests/httpx | mitmproxy 侧 HTTP 客户端更灵活 |
| 规则命中上下文 | ✅ matched_rules / rule_variables | — | 脚本可读取规则执行结果 |
| npm 包 | ✅ esbuild bundle | ✅ pip | 打包方式不同 |
| DNS/TCP/UDP 层钩子 | — | ✅ | mitmproxy 覆盖更低协议层 |
| TLS clienthello 钩子 | — | ✅ | SNI 等场景 mitmproxy 更直接 |
| 流式 body 逐块修改 | — | ✅ | RelayCore 当前为完整 body 读写 |
迁移示例
修改请求头
# mitmproxy
def request(flow):
flow.request.headers["X-Custom"] = "value"
# RelayCore
globalThis.onRequestHeaders = (_ctx, flow) => {
flow.layer.data.request.headers.push(["X-Custom", "value"]);
return flow;
}; Mock 响应
mitmproxy 可在 response 钩子里直接构造响应。RelayCore 0.5.x 推荐用规则引擎的 MockResponse;脚本适合动态逻辑。
# mitmproxy
def response(flow):
if flow.response.status_code == 404:
flow.response = http.Response.make(200, b"OK", {"Content-Type": "text/plain"})
# RelayCore — 规则示例(JSON)
{
"filter": { "type": "Url", "config": { "mode": "Contains", "value": "/missing" } },
"actions": [{ "type": "MockResponse", "config": { "status": 200, "body": "OK" } }]
} 关键差异
- 语言:TypeScript(Deno/V8)vs Python
- Headers:RelayCore 用
[key, value][]数组,保留重复 header;mitmproxy 用 dict - Body:RelayCore 的
body.content为 base64,需atob()/btoa() - Flow 结构:HTTP 数据在
flow.layer.data.request/response(见脚本 API) - 全局状态:RelayCore 用
sharedState.get/set;mitmproxy 用 Python 模块级变量 - 加载方式:
relay-core-cli run --script、HTTPPOST /api/v1/script、Tauriload_script
选型参考
| 场景 | 更适合 |
|---|---|
| 日常 HTTP/HTTPS 抓包与 header/body 修改 | 两者均可 |
| Python 生态与 pip 依赖 | mitmproxy |
| TypeScript / npm 与 Rust 代理栈集成 | RelayCore |
| 规则 + 脚本联动(命中上下文注入脚本) | RelayCore |
| 透明代理 TCP/UDP/DNS 层脚本 | mitmproxy |
| CLI + HTTP API + MCP + 桌面内嵌同一 runtime | RelayCore |