与 mitmproxy 对比

如果你用过 mitmproxy 的 Python addon,这份对比说明 RelayCore 脚本在钩子、数据模型和工具链上的异同。详细 API 见脚本 API,实践模式见脚本开发指引

能力对照

能力RelayCoremitmproxy说明
HTTP 请求/响应钩子✅ 4 钩子✅ 4 钩子功能对等
WebSocket 消息帧功能对等
WebSocket 生命周期✅ start/end/error功能对等
连接级钩子✅ onConnect/onDisconnect✅ clientconnect/clientdisconnectRelayCore 支持连接拒绝(drop)
错误回调✅ onError✅ errorRelayCore 含 stage 定位
跨请求状态✅ sharedState✅ Python 全局变量模型不同:per-isolate vs 进程全局
环境变量✅ relay.env + 白名单✅ os.environRelayCore 需 --script-env-allow
日志✅ console.* → tracing✅ logging功能对等
执行指标✅ Prometheus✅ addon traceRelayCore 接入 /api/v1/metrics
内置工具✅ relay.*✅ Python 标准库语言生态差异
子请求✅ relay.fetch(可选)✅ requests/httpxmitmproxy 侧 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、HTTP POST /api/v1/script、Tauri load_script

选型参考

场景更适合
日常 HTTP/HTTPS 抓包与 header/body 修改两者均可
Python 生态与 pip 依赖mitmproxy
TypeScript / npm 与 Rust 代理栈集成RelayCore
规则 + 脚本联动(命中上下文注入脚本)RelayCore
透明代理 TCP/UDP/DNS 层脚本mitmproxy
CLI + HTTP API + MCP + 桌面内嵌同一 runtimeRelayCore