# api-proxy **Repository Path**: jieimbyte/api-proxy ## Basic Information - **Project Name**: api-proxy - **Description**: 这仅仅是我想将工作的ai拿出来用,写的小脚本 - **Primary Language**: Unknown - **License**: Not specified - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 0 - **Created**: 2026-06-10 - **Last Updated**: 2026-06-10 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README # API Proxy 通过 WebSocket 隧道将内网 Anthropic 格式 API 暴露到外网的中转服务。 ## 架构 ``` 外部客户端 ──HTTP──▶ 云服务器 ◀──WebSocket──▶ 内网机器 ──HTTP──▶ 内网 API (server.js) (client.js) ``` 内网机器主动向云服务器建立 WebSocket 长连接,绕过 NAT 限制,无需配置端口映射。 ## 快速开始 ### 1. 安装依赖 ```bash npm install ``` ### 2. 云服务器端 (server.js) ```bash # CLI 参数 node server.js --port 3000 --api-key "your-public-key" # 或环境变量 cp .env.example .env # 编辑 PUBLIC_API_KEY 和 PORT node server.js ``` 启动后: - API 网关:`http://<云服务器IP>:3000/v1/messages` - 健康检查:`http://<云服务器IP>:3000/health` - WebSocket 隧道:`ws://<云服务器IP>:3000/tunnel` ### 3. 内网机器端 (client.js) ```bash # CLI 参数 node client.js \ --server-url "ws://<云服务器IP>:3000/tunnel" \ --target-url "http://<内网API地址>" \ --inner-api-key "<内网API的Key>" # 或环境变量 cp .env.example .env # 编辑 TUNNEL_SERVER_URL, TARGET_API_URL, INNER_API_KEY node client.js ``` ### 4. 外网调用 ```bash curl http://<云服务器IP>:3000/v1/messages \ -H "Content-Type: application/json" \ -H "x-api-key: your-public-key" \ -H "anthropic-version: 2023-06-01" \ -d '{ "model": "claude-sonnet-4-5-20250514", "max_tokens": 1024, "messages": [{"role": "user", "content": "Hello"}] }' ``` 流式请求: ```bash curl http://<云服务器IP>:3000/v1/messages \ -H "Content-Type: application/json" \ -H "x-api-key: your-public-key" \ -d '{ "model": "claude-sonnet-4-5-20250514", "max_tokens": 1024, "messages": [{"role": "user", "content": "Hello"}], "stream": true }' ``` ## 环境变量 | 变量 | 脚本 | 说明 | |------|------|------| | `PUBLIC_API_KEY` | server.js | 外网客户端使用的 API Key | | `PORT` | server.js | 服务端口(默认 3000) | | `TUNNEL_SERVER_URL` | client.js | 云服务器 WebSocket 地址 | | `TARGET_API_URL` | client.js | 内网 Anthropic API 地址 | | `INNER_API_KEY` | client.js | 内网 API 的认证 Key(可选) | ## 特性 - **完全兼容 Anthropic API 协议** — 外网调用方式与直接调用 Anthropic API 一致 - **支持流式响应 (SSE)** — 逐片转发,保证低首字延迟 - **内网主动连接** — 无需路由器端口映射,天然穿透 NAT - **断线自动重连** — 内网机器断线后 3 秒自动重连 - **双层 API Key** — 外层保护云服务器入口,内层转发到内网 API - **双文件部署** — `server.js` 部署在云服务器,`client.js` 部署在内网机器 ## 生产建议 - 使用 `pm2` 或 `systemd` 管理进程,保证断线自动重启 - 设置 `PUBLIC_API_KEY` 为强随机字符串 - 云服务器安全组仅开放 API 端口(如 3000)