# Matchlock > **实验性:** 该项目仍在积极开发中,可能会发生破坏性变更。 Matchlock 是一个 CLI 工具,用于在临时微VM中运行 AI 代理——具有网络允许列表、通过中间人代理的秘密注入以及 VM 级隔离。你的秘密永远不会进入 VM。 ## 为什么使用 Matchlock? AI 代理需要运行代码,但给予它们对你机器的不受限制的访问存在风险。Matchlock 让你为代理提供一个完整的 Linux 环境,该环境在一秒内启动——隔离且一次性。 当你传递 `--allow-host` 或 `--secret` 时,Matchlock 会封锁网络——只有明确允许的主机的流量可以通过,其他一切都被阻止。当你的代理调用 API 时,真实凭据由主机在飞行中注入。沙盒只看到一个占位符。即使代理被诱骗运行恶意软件,你的密钥也不会泄露,数据也无处可去。内部,代理拥有完整的 Linux 环境,可以做任何需要的事情。它可以安装软件包、写入文件、制造混乱。外部,你的机器毫无感觉。卷叠加挂载是隔离的快照,完成后消失。无论在 Linux 服务器上还是在 MacBook 上,CLI 和行为都相同。 ## 快速开始 ### 系统要求 - **Linux** 支持 KVM - **Apple Silicon 上的 macOS** ### 安装 完整安装详情请参见 [`docs/install.md`](https://github.com/jingkaihe/matchlock/blob/main/docs/install.md)。 **快速安装** 下面的脚本检测操作系统,并在 macOS 上使用 Homebrew 安装 matchlock,在基于 Debian/RHEL 的 Linux 发行版上使用 rpm/deb 安装。 ```bash curl -fsSL https://raw.githubusercontent.com/jingkaihe/matchlock/main/scripts/install.sh | bash # Or install a specific release curl -fsSL https://raw.githubusercontent.com/jingkaihe/matchlock/main/scripts/install.sh | bash -s -- --version 0.2.4 ``` **Homebrew** 基于 Homebrew 的安装支持 macOS 和 Linux: ```bash brew tap jingkaihe/essentials brew install matchlock ``` **Debian / Ubuntu (.deb)** ```bash sudo dpkg -i ./matchlock_<version>_linux_amd64.deb sudo apt-get install -f matchlock diagnose ``` **Fedora / RHEL / CentOS Stream (.rpm)** ```bash sudo dnf install ./matchlock_<version>_linux_amd64.rpm matchlock diagnose ``` 如果 `matchlock diagnose` 报告缺少主机设置,请运行: ```bash sudo matchlock setup linux ``` 要显式注册特定用户,请运行: ```bash sudo matchlock setup user <name> ``` ### 用法 ```bash # Basic matchlock run --image alpine:latest cat /etc/os-release matchlock run --image alpine:latest -it sh matchlock run --image alpine:latest --no-network -- sh -lc 'echo offline' # Network allowlist matchlock run --image python:3.12-alpine \ --allow-host "api.openai.com" python agent.py # Keep interception enabled even with an empty allowlist, # so hosts can be added/removed at runtime. matchlock run --image alpine:latest --rm=false --network-intercept matchlock allow-list add <vm-id> api.openai.com,api.anthropic.com matchlock allow-list delete <vm-id> api.openai.com # Secret injection (never enters the VM) export ANTHROPIC_API_KEY=sk-xxx matchlock run --image python:3.12-alpine \ --secret [email protected] python call_api.py # Long-lived sandboxes matchlock run --image alpine:latest --rm=false # prints VM ID matchlock run --image nginx:latest -d # same as above, detached matchlock exec vm-abc12345 -it sh # attach to it matchlock port-forward vm-abc12345 8080:8080 # forward host:8080 -> guest:8080 # Publish ports at startup matchlock run --image alpine:latest --rm=false -p 8080:8080 # Lifecycle matchlock list | kill | rm | prune # Build from Dockerfile (uses BuildKit-in-VM) matchlock build -f Dockerfile -t myapp:latest . # Pre-build rootfs from registry image (caches for faster startup) matchlock build alpine:latest # Image management matchlock image ls # List all images matchlock image rm myapp:latest # Remove a local image docker save myapp:latest | matchlock image import myapp:latest # Import from tarball ``` ## SDK Matchlock 提供了 Go、Python 和 TypeScript SDK,用于将沙盒直接嵌入到你的应用程序中。你可以以编程方式启动 VM、执行命令、流式输出和管理文件。 **Go** ```go package main import ( "context" "fmt" "os" "github.com/jingkaihe/matchlock/pkg/sdk" ) func main() { ctx := context.Background() client, err := sdk.NewClient(sdk.DefaultConfig()) if err != nil { panic(err) } defer client.Close(0) defer client.Remove() sandbox := sdk.New("alpine:latest"). AllowHost("dl-cdn.alpinelinux.org", "api.anthropic.com"). AddSecret("ANTHROPIC_API_KEY", os.Getenv("ANTHROPIC_API_KEY"), "api.anthropic.com") if _, err := client.Launch(sandbox); err != nil { panic(err) } if _, err := client.Exec(ctx, "apk add --no-cache curl"); err != nil { panic(err) } // The VM only ever sees a placeholder - the real key never enters the sandbox result, err := client.Exec(ctx, "echo $ANTHROPIC_API_KEY") if err != nil { panic(err) } fmt.Print(result.Stdout) // prints "SANDBOX_SECRET_a1b2c3d4..." curlCmd := `curl -s --no-buffer https://api.anthropic.com/v1/messages \ -H "content-type: application/json" \ -H "x-api-key: $ANTHROPIC_API_KEY" \ -H "anthropic-version: 2023-06-01" \ -d '{"model":"claude-haiku-4-5-20251001","max_tokens":1024,"stream":true, "messages":[{"role":"user","content":"Explain TCP to me"}]}'` if _, err := client.ExecStream(ctx, curlCmd, os.Stdout, os.Stderr); err != nil { panic(err) } } ``` Go SDK 私有 IP 行为(`10/8`、`172.16/12`、`192.168/16`): - 默认(未设置):每当发送网络配置时,私有 IP 被阻止。 - 显式阻止:调用 `.WithBlockPrivateIPs(true)`(或 `.BlockPrivateIPs()`)。 - 显式允许:调用 `.AllowPrivateIPs()` 或 `.WithBlockPrivateIPs(false)`。 ```go sandbox := sdk.New("alpine:latest"). AllowHost("api.openai.com"). AddHost("api.internal", "10.0.0.10"). WithNetworkMTU(1200). AllowPrivateIPs() // explicit override: block_private_ips=false // SDK network interception (request/response mutation, body shaping, SSE data-line transform) sandbox = sandbox.WithNetworkInterception(&sdk.NetworkInterceptionConfig{ Rules: []sdk.NetworkHookRule{ { Phase: sdk.NetworkHookPhaseBefore, Action: sdk.NetworkHookActionMutate, Hosts: []string{"api.openai.com"}, SetHeaders: map[string]string{"X-Trace-Id": "trace-123"}, }, { Phase: sdk.NetworkHookPhaseAfter, Action: sdk.NetworkHookActionMutate, Hosts: []string{"api.openai.com"}, BodyReplacements: []sdk.NetworkBodyTransform{ {Find: "internal-id", Replace: "redacted"}, }, }, }, }) ``` 如果你直接使用 `client.Create(...)`(不带构建器),设置: - `BlockPrivateIPsSet: true` - `BlockPrivateIPs: false`(或 `true`) 对于完全离线的沙盒(无 guest NIC / 无出站),使用: - CLI:`--no-network` - Go SDK 构建器:`.WithNoNetwork()` - Python SDK 构建器:`.with_no_network()` - TypeScript SDK 构建器:`.withNoNetwork()` **Python** ([PyPI](https://pypi.org/project/matchlock/)) ```bash pip install matchlock # or uv add matchlock ``` ```python import os import sys from matchlock import Client, Sandbox sandbox = ( Sandbox("python:3.12-alpine") .allow_host( "dl-cdn.alpinelinux.org", "files.pythonhosted.org", "pypi.org", "astral.sh", "github.com", "objects.githubusercontent.com", "api.anthropic.com", ) .add_secret( "ANTHROPIC_API_KEY", os.environ["ANTHROPIC_API_KEY"], "api.anthropic.com" ) ) SCRIPT = """\ # /// script # requires-python = ">=3.12" # dependencies = ["anthropic"] # /// import anthropic, os client = anthropic.Anthropic(api_key=os.environ["ANTHROPIC_API_KEY"]) with client.messages.stream( model="claude-haiku-4-5-20251001", max_tokens=1024, messages=[{"role": "user", "content": "Explain TCP/IP."}], ) as stream: for text in stream.text_stream: print(text, end="", flush=True) print() """ with Client() as client: client.launch(sandbox) client.exec("pip install --quiet uv") client.write_file("/workspace/ask.py", SCRIPT) client.exec_stream("uv run /workspace/ask.py", stdout=sys.stdout, stderr=sys.stderr) client.remove() ``` **TypeScript** ```bash npm install matchlock-sdk ``` ```ts import { Client, Sandbox } from "matchlock-sdk"; const SCRIPT = `import Anthropic from "@anthropic-ai/sdk"; const anthropic = new Anthropic({ apiKey: process.env.ANTHROPIC_API_KEY, }); const stream = anthropic.messages .stream({ model: "claude-haiku-4-5-20251001", max_tokens: 1024, messages: [{ role: "user", content: "Explain TCP/IP." }], }) .on("text", (text) => { process.stdout.write(text); }); await stream.finalMessage(); process.stdout.write("\\n"); `; const client = new Client(); try { const sandbox = new Sandbox("node:22-alpine") .allowHost("registry.npmjs.org", "*.npmjs.org", "api.anthropic.com") .addSecret("ANTHROPIC_API_KEY", process.env.ANTHROPIC_API_KEY ?? "", "api.anthropic.com"); await client.launch(sandbox); await client.exec( "npm init -y >/dev/null 2>&1 && npm install --quiet --no-bin-links @anthropic-ai/sdk", { workingDir: "/workspace" }, ); await client.writeFile("/workspace/ask.mjs", SCRIPT); await client.execStream("node ask.mjs", { workingDir: "/workspace", stdout: process.stdout, stderr: process.stderr, }); } finally { await client.close(); await client.remove(); } ``` 更多示例位于 [`examples/`](https://github.com/jingkaihe/matchlock/blob/main/examples) 目录: | 描述 | 示例 | |---|---| | 使用秘密注入流式传输 Anthropic API 响应 (Go) | [`examples/go/basic/`](https://github.com/jingkaihe/matchlock/blob/main/examples/go/basic) | | 使用 ExecInteractive 的交互式终端带 PTY (Go) | [`examples/go/exec_modes/`](https://github.com/jingkaihe/matchlock/blob/main/examples/go/exec_modes) | | 通过网络拦截钩子注入 API 密钥 (Go) | [`examples/go/network_interception/`](https://github.com/jingkaihe/matchlock/blob/main/examples/go/network_interception) | | 用于文件操作变异的 VFS 拦截钩子 (Go) | [`examples/go/vfs_hooks/`](https://github.com/jingkaihe/matchlock/blob/main/examples/go/vfs_hooks) | | 流式传输 Anthropic API 响应 (Python) | [`examples/python/basic/`](https://github.com/jingkaihe/matchlock/blob/main/examples/python/basic) | | 流、管道和交互式执行模式 (Python) | [`examples/python/exec_modes/`](https://github.com/jingkaihe/matchlock/blob/main/examples/python/exec_modes) | | 通过网络拦截钩子注入 API 密钥 (Python) | [`examples/python/network_interception/`](https://github.com/jingkaihe/matchlock/blob/main/examples/python/network_interception) | | 用于文件操作变异的 VFS 拦截钩子 (Python) | [`examples/python/vfs_hooks/`](https://github.com/jingkaihe/matchlock/blob/main/examples/python/vfs_hooks) | | 流式传输 Anthropic API 响应 (TypeScript) | [`examples/typescript/basic/`](https://github.com/jingkaihe/matchlock/blob/main/examples/typescript/basic) | | 流、管道和交互式执行模式 (TypeScript) | [`examples/typescript/exec_modes/`](https://github.com/jingkaihe/matchlock/blob/main/examples/typescript/exec_modes) | | 通过网络拦截钩子注入 API 密钥 (TypeScript) | [`examples/typescript/network_interception/`](https://github.com/jingkaihe/matchlock/blob/main/examples/typescript/network_interception) | | 在微VM中使用 GitHub 引导的 Claude Code CLI | [`examples/claude-code/`](https://github.com/jingkaihe/matchlock/blob/main/examples/claude-code) | | 通过 SDK 在沙盒内使用 Docker 的 Claude Code | [`examples/claude-code-with-docker/`](https://github.com/jingkaihe/matchlock/blob/main/examples/claude-code-with-docker) | | 在沙盒中使用 Claude Pro/Max 订阅的 Claude Code | [`examples/claude-danger/`](https://github.com/jingkaihe/matchlock/blob/main/examples/claude-danger) | | 在微VM中使用 GitHub 引导的 OpenAI Codex CLI | [`examples/codex/`](https://github.com/jingkaihe/matchlock/blob/main/examples/codex) | | 在沙盒内使用 systemd 的 Docker 守护进程 | [`examples/docker-in-sandbox/`](https://github.com/jingkaihe/matchlock/blob/main/examples/docker-in-sandbox) | | 使用代理客户端协议的 Streamlit 聊天机器人 | [`examples/agent-client-protocol/`](https://github.com/jingkaihe/matchlock/blob/main/examples/agent-client-protocol) | | 使用 Kodelet 和 Playwright MCP 的浏览器自动化 | [`examples/playwright/`](https://github.com/jingkaihe/matchlock/blob/main/examples/playwright) | ## 架构 ```mermaid graph LR subgraph Host CLI["Matchlock CLI"] Policy["Policy Engine"] Proxy["Transparent Proxy + TLS MITM"] VFS["VFS Server"] CLI --> Policy CLI --> Proxy Policy --> Proxy end subgraph VM["Micro-VM (Firecracker / Virtualization.framework)"] Agent["Guest Agent"] FUSE["/workspace (FUSE)"] Image["Any OCI Image (Alpine, Ubuntu, etc.)"] Agent --- Image FUSE --- Image end Proxy -- "vsock :5000" --> Agent VFS -- "vsock :5001" --> FUSE ``` ### 网络模式 | 平台 | 模式 | 机制 | |----------|------|-----------| | Linux | 透明代理 | nftables DNAT 在端口 80/443 | | macOS | NAT (默认) | Virtualization.framework 内置 NAT | | macOS | 拦截 (带 `--allow-host`/`--secret`) | gVisor 用户空间 TCP/IP 在 L4 | ## 文档 - [生命周期和清理操作手册](https://github.com/jingkaihe/matchlock/blob/main/docs/lifecycle.md) - [网络拦截](https://github.com/jingkaihe/matchlock/blob/main/docs/network-interception.md) - [VFS 拦截](https://github.com/jingkaihe/matchlock/blob/main/docs/vfs-interception.md) - [开发者参考](https://github.com/jingkaihe/matchlock/blob/main/AGENTS.md) ## 许可证 MIT