diff --git a/README.it.md b/README.it.md index d9d39f3..38b97d9 100644 --- a/README.it.md +++ b/README.it.md @@ -53,7 +53,7 @@ go build -o opencode2api ./cmd/opencode2api Prima di avviare il servizio, modifica `config.json`: 1. Sostituisci `server_keys` con una tua API key locale. -2. Configura le chiavi Zen o Go. In alternativa, imposta `anonymous: true` e lascia vuoti entrambi gli array delle chiavi upstream. +2. Prima dell'avvio, inserisci una Zen API Key (consigliata) in `zen_keys` oppure una chiave Go in `go_keys`. L'esempio disabilita l'accesso anonimo (`anonymous: false`) e lascia vuoti entrambi gli array; anche una connessione Go in abbonamento già salvata soddisfa il requisito. Il canale anonimo potrebbe essere fortemente bloccato a monte: preferisci una Zen API Key. 3. Sostituisci `webui.password`. La configurazione di esempio abilita la WebUI con l'utente `admin`. ```bash diff --git a/README.md b/README.md index 45fa525..2c35f27 100644 --- a/README.md +++ b/README.md @@ -11,7 +11,7 @@ The executable includes the WebUI. Running the service requires no Node.js runti - JSON and SSE responses across all three inference protocols. - Text, images, reasoning, function tools, tool calls, and tool results; file content where the target protocol can represent it. - Separate Zen and Go key pools, configurable tier preference, retries, and session affinity. -- Optional anonymous Zen access with the OpenCode `public` credential. +- Opt-in anonymous Zen access with the OpenCode `public` credential; disabled by default because upstream blocking can make it unavailable. - Optional userspace Cloudflare WARP egress for free-model traffic, without TUN or root. - Direct, HTTP, HTTPS, SOCKS5, and SOCKS5H connections, including a proxy file. - Dynamic model discovery, native protocol metadata, and disk caches. @@ -53,9 +53,11 @@ go build -o opencode2api ./cmd/opencode2api Before starting, edit `config.json`: 1. Replace `server_keys` with your own local API key. -2. Optionally supply Zen or Go keys. The example enables the anonymous free lane and leaves both upstream key arrays empty. +2. Supply a Zen API Key in `zen_keys` (recommended), or a Go key in `go_keys`. The example leaves both arrays empty and disables anonymous access, so configure an upstream credential before starting. An existing Go subscription connection also satisfies this requirement. 3. Replace `webui.password`. The example enables the WebUI with username `admin`. +**Anonymous traffic may be heavily blocked upstream. Prefer a Zen API Key.** Anonymous access is off by default in the configuration and WebUI; existing configurations that explicitly set `anonymous: true` keep that choice. Enable it deliberately only if you accept that free requests may still fail. + ```bash ./opencode2api -config config.json ``` @@ -223,6 +225,8 @@ Each `/v1/models` entry also carries `cost` (USD per million tokens: `input`, `o ### Anonymous access and fallback +**Anonymous traffic may be heavily blocked upstream. Prefer a Zen API Key.** The built-in default and example configuration set `anonymous: false`; the WebUI does not opt you in automatically or change an existing explicit `true` value. + With `anonymous: true`, either condition makes a model eligible for the anonymous Zen lane: - Its ID contains `free`, case-insensitively. @@ -248,7 +252,7 @@ Known OpenCode title requests are identified before prompt and message shaping, When only anonymous access is configured, `/v1/models` exposes only models eligible for that lane. -Free models never need a Zen key: with `anonymous: true` they are served by the public lane, and a configured key is only their fallback. To keep keys but expose free models only, set `models.free_only: true`. Paid models then disappear from `/v1/models`, direct requests for them are rejected, and rotation aliases keep only free members; free models may still fall back to the configured keys. +An eligible free model can be attempted without a Zen key only when anonymous access is explicitly enabled; eligibility does not guarantee upstream access. To keep authenticated keys but expose free models only, set `models.free_only: true`. Paid models then disappear from `/v1/models`, direct requests for them are rejected, and rotation aliases keep only free members; free models use the configured keys when anonymous access is off, or may fall back to them when it is on. ### WARP egress for free models @@ -319,7 +323,7 @@ Cooldowns grow exponentially up to eight times `performance.failure_cooldown_sec ## Configuration reference -See [config.example.json](config.example.json) for a complete starting configuration. JSON supports `//` and `/* ... */` comments; unknown fields and invalid values are rejected. +See [config.example.json](config.example.json) for a starting configuration; add an upstream credential before starting. The configuration-file loader supports `//` and `/* ... */` comments, which are not part of standard JSON; management API bodies must be standard JSON. Unknown fields, including `_comment`, and invalid values are rejected. ### Keys, listeners, and routing @@ -327,8 +331,8 @@ See [config.example.json](config.example.json) for a complete starting configura | --------------------------- | --------------------------------------------------------------------------- | | `listen` | `127.0.0.1:8080`. | | `server_keys` | At least one local key is required. | -| `zen_keys`, `go_keys` | At least one upstream key is required unless anonymous access is enabled. | -| `anonymous` | `false`. | +| `zen_keys`, `go_keys` | At least one upstream key or saved `go_subscription` connection is required unless anonymous access is explicitly enabled. | +| `anonymous` | `false`; opt-in only. Upstream blocking may make this lane unavailable; prefer a Zen API Key. | | `warp.enabled` | `false`; free-lane traffic leaves through Cloudflare WARP and no proxy. | | `warp.pool_size` | `2`; upper bound on WARP exits (half pre-registered in the background; the active ring follows concurrency), 1–32. | | `warp.stack` | `ipv6`; `ipv6`, `ipv4`, or `dual`. | @@ -465,6 +469,7 @@ The management listener serves the UI and `/api/*` routes. Authentication uses o | `GET /api/monitor` | Request, token, upstream, and resource statistics. | | `GET /api/debug/models` | Model routes, key fingerprints, and metadata diagnostics. | | `POST /api/debug/inference` | Run a Playground request. | +| `POST /api/proxies/check` | Check one saved or draft proxy's connectivity to the configured Zen upstream. | | `GET /api/logs`, `GET /api/logs/stream` | Recent logs or a live SSE subscription. | Playground requests require a session and `X-CSRF-Token` and are limited to 12 per minute per client IP: @@ -486,6 +491,34 @@ The server forces `stream: false`. Use `{"mode":"selected","tier":"zen","id":"KE After execution, the management endpoint returns HTTP 200 with the actual result in `ok`, `http_status`, `request_id`, `route`, and `response`. Selected-key results also include `selected_key` and `key_test`: `usable`, `rejected`, `rate_limited`, `transport_error`, `upstream_error`, `request_error`, or `unavailable`. Invalid management input, authentication, CSRF, and throttling retain their own HTTP error statuses. +### Bulk proxy management + +The WebUI can import multiple inline proxies, check selected entries, and stage selected entries for removal. Checks call `POST /api/proxies/check` once per proxy, with a login session, `X-CSRF-Token`, and exactly one of these standard JSON bodies: + +```json +{"id":"SAVED_PROXY_ID"} +``` + +```json +{"value":"https://proxy.example:8443"} +``` + +Use the masked entry ID from `GET /api/config` for an existing proxy, or `value` for an unsaved draft. Results return HTTP 200 with `ok`, `state`, and `reason`; `latency_ms` and upstream `status` may also be present. Invalid management requests, authentication, CSRF, and concurrency limits use their own HTTP error statuses. Each check has a 20-second timeout. The WebUI runs at most four checks concurrently; the server accepts at most eight and rejects excess checks without queuing. + +**This checks only proxy-to-Zen connectivity, not inference, key validity, or quota.** It sends an unauthenticated `GET` to the configured `upstream.zen` URL plus `/v1/models` through an isolated Bun client using only the selected proxy. No Zen/Go key, anonymous `public` credential, or OAuth token is sent, no inference is performed, redirects are not followed, and WARP is not used. It works with `anonymous: false` without enabling anonymous access. + +| `state` | Meaning / cleanup guidance | +| ------- | -------------------------- | +| `available` | The upstream responded with HTTP 200–399 or 401. A 401 means the endpoint was reached but requires authentication (`authentication_required`), not that a key was validated. | +| `unavailable` | A confirmed proxy-side connection refusal or DNS failure (`proxy_unreachable`), or proxy CONNECT HTTP 407 (`proxy_authentication_required`); eligible for unavailable-only selection for this check, not proof of permanent failure. | +| `limited` | The upstream returned 429; this is not evidence that the proxy is broken. | +| `rejected` | The upstream responded with 403 or another error status, excluding 401 and 429 (`upstream_responded`), or the proxy rejected the tunnel (`proxy_tunnel_rejected`); this is not evidence that the proxy is broken. An origin HTTP 407 is not classified as proxy authentication failure. | +| `inconclusive` | A timeout, other transport failure, or unavailable check prerequisite; do not treat this as a confirmed broken proxy. | + +Checks do not change production proxy health, key cooldowns, or bindings. A result describes this connection attempt, not permanent proxy health; upstream rejection, rate limiting, and timeouts must not be selected for cleanup as confirmed proxy failures. + +Removal is staged in the WebUI and takes effect only after saving the full configuration through `PUT /api/config`; checking does not delete anything. Proxies supplied by `proxyfile` are managed in that source file, not in the inline-proxy table. + ### Go subscription sign-in In **Models & Quota** (`/#model-quotas`), select **Sign in to Go in your browser**, open the displayed official OpenCode Device OAuth link, and enter the displayed `user_code`. Authorize the request you initiated; the WebUI schedules backend polling to complete sign-in. No token pasting, local credential-file import, or callback URL submission is required. If the account has multiple organizations, select the organization with the Go subscription in the WebUI. diff --git a/README.vi.md b/README.vi.md index 75b7515..d361b0a 100644 --- a/README.vi.md +++ b/README.vi.md @@ -55,7 +55,7 @@ go build -o opencode2api ./cmd/opencode2api Trước khi khởi động, hãy sửa `config.json`: 1. Thay `server_keys` bằng API key cục bộ của bạn. -2. Tùy chọn: thêm key Zen hoặc Go; ví dụ đã bật làn ẩn danh và để trống cả hai mảng key thượng nguồn. +2. Điền Zen API Key (khuyến nghị) vào `zen_keys` hoặc Go key vào `go_keys` trước khi khởi động. Cấu hình mẫu tắt truy cập ẩn danh (`anonymous: false`) và để trống cả hai mảng key; một kết nối thuê bao Go đã lưu cũng đáp ứng yêu cầu này. Làn ẩn danh có thể bị chặn mạnh ở thượng nguồn, nên ưu tiên Zen API Key. 3. Thay `webui.password`. File mẫu bật WebUI với tài khoản `admin`. ```bash @@ -573,4 +573,4 @@ Các quan sát được lưu theo URL upstream, mô hình và giao thức gốc, SPDX-License-Identifier: GPL-3.0-or-later -Dự án này là phần mềm tự do: bạn có thể phân phối lại và sửa đổi theo Giấy phép Công cộng GNU phiên bản 3 do Free Software Foundation công bố, hoặc phiên bản 3 hoặc mới hơn (tuỳ chọn của bạn). Phần mềm được cung cấp nguyên trạng, không kèm bảo đảm. Xem [LICENSE](LICENSE) để biết đầy đủ điều khoản. \ No newline at end of file +Dự án này là phần mềm tự do: bạn có thể phân phối lại và sửa đổi theo Giấy phép Công cộng GNU phiên bản 3 do Free Software Foundation công bố, hoặc phiên bản 3 hoặc mới hơn (tuỳ chọn của bạn). Phần mềm được cung cấp nguyên trạng, không kèm bảo đảm. Xem [LICENSE](LICENSE) để biết đầy đủ điều khoản. diff --git a/README.zh-CN.md b/README.zh-CN.md index 13a7d3a..35d7c47 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -11,7 +11,7 @@ WebUI 内嵌在可执行文件中,运行服务无需 Node.js 或数据库。 - 三种推理协议之间的普通 JSON 响应与 SSE 流式转换。 - 文本、图片、reasoning、函数工具、工具调用和工具结果;目标协议允许时支持文件内容转换。 - 独立的 Zen / Go Key 池,可配置优先级、重试和会话亲和性。 -- 使用 OpenCode `public` 凭证的可选 Zen 匿名通道。 +- 使用 OpenCode `public` 凭证的可选 Zen 匿名通道,默认关闭,上游封堵可能使其不可用。 - 可选的用户态 Cloudflare WARP 出口,免费模型流量无需 TUN 或 root 权限。 - 直连、HTTP、HTTPS、SOCKS5、SOCKS5H 连接,以及代理文件。 - 动态模型发现、原生协议与能力信息、磁盘缓存。 @@ -53,9 +53,11 @@ go build -o opencode2api ./cmd/opencode2api 启动前编辑 `config.json`: 1. 将 `server_keys` 替换为自己的本地 API Key。 -2. 可选:填入 Zen 或 Go Key;示例已启用匿名通道,并清空两个上游 Key 数组。 +2. 在 `zen_keys` 填入 Zen API Key(推荐),或在 `go_keys` 填入 Go Key。示例关闭匿名通道,且两个上游 Key 数组为空,必须先配置上游凭证才能启动;已有的 Go 订阅连接也满足此要求。 3. 替换 `webui.password`。示例配置启用了 WebUI,用户名为 `admin`。 +**匿名通道可能已被上游重点封堵,优先使用 Zen API Key。** 配置与 WebUI 默认关闭匿名访问;已有配置中明确设置的 `anonymous: true` 不会被自动改为关闭。只有接受免费请求仍可能失败时,才主动开启。 + ```bash ./opencode2api -config config.json ``` @@ -223,6 +225,8 @@ System One 将自由文本状态与类型化问题配对,并返回类型化答 ### 匿名通道与回退 +**匿名通道可能已被上游重点封堵,优先使用 Zen API Key。** 内置默认值与示例均为 `anonymous: false`,WebUI 不自动启用匿名通道,也不修改已有配置中明确设置的 `true`。 + 启用 `anonymous: true` 后,满足以下任一条件的模型可以进入 Zen 匿名通道: - 模型 ID 包含 `free`,不区分大小写。 @@ -232,7 +236,7 @@ System One 将自由文本状态与类型化问题配对,并返回类型化答 路由顺序: -1. 符合条件的模型最多尝试 `performance.max_anonymous_exits` 个可用匿名代理,每个代理一次;每个代理先走 v2 `/inference`,再走 v1 `/zen`。 +1. 符合条件的模型最多尝试 `performance.max_anonymous_exits` 个可用匿名代理,每个代理一次;仅使用 v2 `/inference`,免费模型的 v1 `/zen` 回退已停用。 2. 按 `prefer` 顺序尝试认证通道,仅包含已配置 Key 且可以提供该模型的 Tier。 3. 每个认证 Tier 分别使用 `retry.max_attempts` 预算。 @@ -248,7 +252,7 @@ System One 将自由文本状态与类型化问题配对,并返回类型化答 只有匿名通道可用时,`/v1/models` 仅展示符合匿名条件的模型。 -免费模型不需要 Zen Key:启用 `anonymous: true` 后由匿名通道提供,已配置的 Key 只作为回退。如果想保留 Key 但只暴露免费模型,设置 `models.free_only: true`:付费模型不再出现在 `/v1/models`,直接请求会被拒绝,轮转别名只保留免费成员;免费模型仍可回退到已配置的 Key。 +只有明确启用匿名通道后,符合条件的免费模型才可尝试不使用 Zen Key,但这不保证上游允许访问。如果想保留认证 Key 但只暴露免费模型,设置 `models.free_only: true`:付费模型不再出现在 `/v1/models`,直接请求会被拒绝,轮转别名只保留免费成员;匿名关闭时免费模型使用已配置的 Key,开启时也可回退到这些 Key。 ### 免费模型 WARP 出口 @@ -319,7 +323,7 @@ Key 初始化时均衡分配到代理。真实流量可以触发代理检查、K ## 配置参考 -完整起始配置见 [config.example.json](config.example.json)。配置支持 `//` 和 `/* ... */` 注释,未知字段和无效取值会被拒绝。 +起始配置见 [config.example.json](config.example.json),启动前须添加上游凭证。配置文件读取器支持非标准 JSON 的 `//` 和 `/* ... */` 注释;管理接口请求体仍须使用标准 JSON。未知字段(包括 `_comment`)和无效取值会被拒绝。 ### Key、监听地址与路由 @@ -327,8 +331,8 @@ Key 初始化时均衡分配到代理。真实流量可以触发代理检查、K | --------------------------- | ------------------------------------------------------------------------------------- | | `listen` | `127.0.0.1:8080`。 | | `server_keys` | 至少一个本地 Key。 | -| `zen_keys`、`go_keys` | 未启用匿名模式时,至少需要一个上游 Key。 | -| `anonymous` | `false`。 | +| `zen_keys`、`go_keys` | 未明确启用匿名模式时,至少需要一个上游 Key 或已有的 `go_subscription` 连接。 | +| `anonymous` | `false`;须主动开启,上游封堵可能使其不可用,优先使用 Zen API Key。 | | `warp.enabled` | `false`;免费通道流量通过 Cloudflare WARP 出口,不使用代理。 | | `warp.pool_size` | `2`;WARP 出口上限(后台预注册一半,活跃出口按并发调整),1–32。 | | `warp.stack` | `ipv6`;可选 `ipv6`、`ipv4`、`dual`。 | @@ -336,7 +340,7 @@ Key 初始化时均衡分配到代理。真实流量可以触发代理检查、K | `prefer` | `go`;可选 `go`、`zen`。 | | `upstream.zen` | `https://opencode.ai/zen`。 | | `upstream.go` | `https://opencode.ai/zen/go`。 | -| `upstream.anonymous` | `https://opencode.ai/inference`;匿名通道优先使用,失败后回退到 `/zen`。 | +| `upstream.anonymous` | `https://opencode.ai/inference`;匿名通道仅使用此地址,已停用 v1 `/zen` 回退。 | | `proxies` | 两个代理来源都为空时,使用 `["direct"]`。 | | `proxyfile` | 可选;相对路径基于配置文件所在目录解析。 | | `models.refresh_seconds` | `300`;最小为 1。 | @@ -459,6 +463,7 @@ pool+http://127.0.0.1:7891 | `GET /api/monitor` | 请求、Token、上游和资源统计。 | | `GET /api/debug/models` | 模型路由、Key 指纹和 metadata 诊断。 | | `POST /api/debug/inference` | 执行 Playground 请求。 | +| `POST /api/proxies/check` | 检查一个已保存或草稿代理到 Zen 上游的连通性。 | | `GET /api/logs`、`GET /api/logs/stream` | 最近日志或 SSE 实时订阅。 | Playground 需要已登录的 Session 和 `X-CSRF-Token`,每个客户端 IP 每分钟最多 12 次: @@ -480,6 +485,16 @@ Playground 需要已登录的 Session 和 `X-CSRF-Token`,每个客户端 IP 执行后,管理接口返回 HTTP 200,实际结果位于 `ok`、`http_status`、`request_id`、`route` 和 `response`。指定 Key 时还返回 `selected_key` 与 `key_test`,其值包括 `usable`、`rejected`、`rate_limited`、`transport_error`、`upstream_error`、`request_error`、`unavailable`。管理请求格式、认证、CSRF 和限速错误仍返回各自对应的 HTTP 状态。 +### 批量代理管理 + +WebUI 支持批量导入内联代理、检查选中条目和暂存批量移除。检查逐条调用 `POST /api/proxies/check`,需要管理登录和 `X-CSRF-Token`;请求体二选一:`{"id":"SAVED_PROXY_ID"}`(`GET /api/config` 返回的已保存代理 ID)或 `{"value":"https://proxy.example:8443"}`(草稿地址)。前端最多四个并发,后端最多八个,超出立即拒绝、不排队;每次检查限时 20 秒。 + +**仅检查代理到 Zen 的连通性,不验证推理、Key 或额度。** 请求通过指定代理的独立 Bun 客户端向配置的 `upstream.zen` 加 `/v1/models` 发送无认证 GET,不带 Zen/Go Key、`public` 或 OAuth 凭证,不发推理、不跟随重定向、不走 WARP,也不修改正式健康、冷却或绑定状态。`anonymous: false` 时仍可检查,不会擅自启用匿名推理。 + +成功执行检查后返回 HTTP 200,结果包含 `ok`、`state`、`reason`,以及可用时的 `status`、`latency_ms`。`available` 表示上游返回 200–399 或 401(401 仅表示到站后需要认证);`unavailable` 仅限本次确认的代理端拒绝连接、DNS 失败或代理 407;429 为 `limited`,上游 403 等错误为 `rejected`,超时及其他不能定位的错误为 `inconclusive`。后三种状态不得当作确认损坏代理批量清理;本次不可用也不代表永久故障。 + +移除只暂存在页面中,仍须通过 `PUT /api/config` 保存完整配置后才生效,检查本身不会删除代理。`proxyfile` 提供的代理在来源文件管理,不加入内联代理表格。 + ### Go 订阅登录 在「模型与额度」页面(`/#model-quotas`)点击「浏览器登录 Go 订阅」,打开页面显示的 OpenCode 官方 Device OAuth 链接,输入显示的 `user_code`。确认这是自己发起的授权后完成登录;WebUI 按间隔请求后端轮询并完成授权交换,无需手贴 Token、导入本机凭证文件或提交回调 URL。账号关联多个组织时,在 WebUI 选择 Go 订阅所在的组织。 diff --git a/config.example.json b/config.example.json index 0d1f1cb..ed5fc20 100644 --- a/config.example.json +++ b/config.example.json @@ -3,7 +3,8 @@ "server_keys": ["change-this-local-key"], "zen_keys": [], "go_keys": [], - "anonymous": true, + // Anonymous traffic may be heavily blocked upstream. Prefer a Zen API Key. + "anonymous": false, "warp": { "enabled": false, "pool_size": 2, diff --git a/docs/management.zh-CN.md b/docs/management.zh-CN.md index 64b3343..78b51c3 100644 --- a/docs/management.zh-CN.md +++ b/docs/management.zh-CN.md @@ -1,6 +1,38 @@ -# 管理控制台:模型轮转、Go 额度与 API Key +# 管理控制台:模型轮转、Go 额度、API Key 与代理 -本文说明三个新增管理页面的使用方式、配置和错误处理。 +本文说明管理页面的使用方式、配置和错误处理。 + +## 匿名通道默认关闭 + +**匿名通道可能已被上游重点封堵,优先使用 Zen API Key。** 配置和 WebUI 默认 `anonymous: false`;已有配置中明确设置的 `true` 保持不变,不会被自动关闭。示例的上游 Key 数组为空,启动前应先填入 Zen API Key(推荐)或 Go Key;已有的 Go 订阅连接也可满足上游凭证要求。不要为了检查代理而开启匿名推理。 + +## 批量代理管理 + +「Proxy 节点」页可批量导入内联代理、检查选中条目和暂存批量移除。代理文件 `proxyfile` 的条目在来源文件管理,不加入内联代理表格。移除不会立即修改运行时,仍需保存完整配置(`PUT /api/config`);检查本身不删除任何条目。 + +检查接口为 `POST /api/proxies/check`,需要管理 Session 与 `X-CSRF-Token`,请求体二选一: + +```json +{"id":"SAVED_PROXY_ID"} +``` + +```json +{"value":"https://proxy.example:8443"} +``` + +`id` 使用 `GET /api/config` 返回的已保存代理 ID;`value` 用于草稿地址。前端最多四个并发,服务端最多八个,超出立即拒绝、不排队;单次检查限时 20 秒。检查正常执行时返回 HTTP 200,包含 `ok`、`state`、`reason` 及可用时的 `status`、`latency_ms`;请求格式、认证、CSRF 和并发限制错误使用各自的 HTTP 错误状态。 + +**只检查代理到配置的 Zen 上游的连通性,不验证推理、Key 或额度。** 独立 Bun 客户端仅通过选中代理向 `upstream.zen` 加 `/v1/models` 发送无认证 GET,不带任何 Zen/Go Key、`public` 或 OAuth 凭证,不发推理、不跟随重定向、不走 WARP,也不改变正式代理健康、Key 冷却或绑定。匿名关闭时仍可检查,不会私自启用匿名推理。 + +| `state` | 含义与清理建议 | +| ------- | -------------- | +| `available` | 上游返回 200–399 或 401。401 的 `authentication_required` 表示已到站、需要认证,不代表验证了 Key。 | +| `unavailable` | 仅本次可确认的代理端拒绝连接、DNS 失败(`proxy_unreachable`)或代理 407(`proxy_authentication_required`),可加入不可用筛选,不代表永久故障。 | +| `limited` | 上游返回 429,不等于代理损坏。 | +| `rejected` | 上游返回 403 等错误,不等于代理损坏。 | +| `inconclusive` | 超时、其他不能定位的传输错误或检查前提不满足,不能确认代理损坏。 | + +只允许将 `unavailable` 作为本次确认不可用的清理筛选;不要把 `limited`、`rejected` 或 `inconclusive` 一并选为损坏代理。正式推理仍可能因模型、凭证、额度或上游策略失败。 ## 模型与额度 diff --git a/internal/admin/proxies.go b/internal/admin/proxies.go new file mode 100644 index 0000000..7c40f3c --- /dev/null +++ b/internal/admin/proxies.go @@ -0,0 +1,52 @@ +package admin + +import ( + "net/http" + "strings" + + "opencode2api/internal/config" + "opencode2api/internal/httpx" +) + +func (a *Server) handleCheckProxy(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Cache-Control", "no-store") + var input SecretInput + if err := decodeAdminJSON(w, r, &input); err != nil { + writeAdminError(w, http.StatusBadRequest, "invalid_request", "provide exactly one proxy id or value") + return + } + input.ID = strings.TrimSpace(input.ID) + input.Value = strings.TrimSpace(input.Value) + if (input.ID == "") == (input.Value == "") || len(input.Value) > 16<<10 { + writeAdminError(w, http.StatusBadRequest, "invalid_proxy", "provide exactly one proxy id or value of at most 16 KiB") + return + } + value := input.Value + if input.ID != "" { + for _, existing := range a.manager.Config().Proxies { + if config.Fingerprint(existing) == input.ID { + value = existing + break + } + } + if value == "" { + writeAdminError(w, http.StatusBadRequest, "unknown_proxy_id", "proxy id is unknown or stale; reload the configuration") + return + } + } + if err := config.ValidateProxyEntry(value); err != nil { + writeAdminError(w, http.StatusBadRequest, "invalid_proxy", "proxy must be direct or an HTTP, HTTPS, SOCKS5 or SOCKS5H URL") + return + } + select { + case a.proxyChecks <- struct{}{}: + defer func() { <-a.proxyChecks }() + case <-r.Context().Done(): + return + default: + w.Header().Set("Retry-After", "1") + writeAdminError(w, http.StatusTooManyRequests, "proxy_checks_busy", "too many proxy checks; retry shortly") + return + } + httpx.WriteJSON(w, http.StatusOK, a.manager.CheckProxy(r.Context(), value)) +} diff --git a/internal/admin/server.go b/internal/admin/server.go index 64b5388..833873a 100644 --- a/internal/admin/server.go +++ b/internal/admin/server.go @@ -41,6 +41,7 @@ type Server struct { goAuthMu sync.Mutex goAuth map[string]*goAuthAttempt goAuthClient *goauth.Client + proxyChecks chan struct{} } // New returns a Server for manager, reporting to monitor and logs. @@ -49,6 +50,7 @@ func New(manager *gateway.RuntimeController, monitor *telemetry.Metrics, logs *t manager: manager, monitor: monitor, logs: logs, logger: logger, sessions: make(map[string]adminSession), attempts: make(map[string]loginWindow), debugAttempts: make(map[string]loginWindow), goAuth: make(map[string]*goAuthAttempt), goAuthClient: goauth.NewClient(nil), + proxyChecks: make(chan struct{}, 8), } } @@ -66,6 +68,7 @@ func (a *Server) Handler() http.Handler { mux.Handle("PUT /api/config", a.authenticate(a.csrf(http.HandlerFunc(a.handlePutConfig)))) mux.Handle("POST /api/config/reload", a.authenticate(a.csrf(http.HandlerFunc(a.handleReload)))) mux.Handle("POST /api/config/reveal", a.authenticate(a.csrf(http.HandlerFunc(a.handleReveal)))) + mux.Handle("POST /api/proxies/check", a.authenticate(a.csrf(http.HandlerFunc(a.handleCheckProxy)))) mux.Handle("PUT /api/account", a.authenticate(a.csrf(http.HandlerFunc(a.handleAccount)))) mux.Handle("GET /api/monitor", a.authenticate(http.HandlerFunc(a.handleMonitor))) mux.Handle("GET /api/debug/models", a.authenticate(http.HandlerFunc(a.handleDebugModels))) diff --git a/internal/config/config.go b/internal/config/config.go index 40384d3..f64a173 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -336,6 +336,7 @@ func Load(path string) (Config, error) { } cfg := Config{ Listen: "127.0.0.1:8080", + Anonymous: false, Warp: WarpConfig{PoolSize: 2, Stack: string(warp.DefaultStack)}, Upstream: UpstreamConfig{Zen: "https://opencode.ai/zen", Go: "https://opencode.ai/zen/go", Anonymous: "https://opencode.ai/inference"}, Retry: RetryConfig{MaxAttempts: 3, TimeoutSeconds: 300}, @@ -435,7 +436,7 @@ func Normalize(path string, cfg Config) (Config, error) { return Config{}, errors.New("at least one server key must remain enabled") } if !cfg.Anonymous && len(cfg.ZenKeys) == 0 && len(cfg.GoKeys) == 0 && cfg.GoSubscription == nil { - return Config{}, errors.New("zen_keys or go_keys must contain at least one upstream key unless anonymous is enabled") + return Config{}, errors.New("configure a Zen API Key (zen_keys), a Go key (go_keys), or a Go subscription (go_subscription); anonymous access is disabled by default and may be blocked upstream") } if cfg.Retry.MaxAttempts < 1 { return Config{}, errors.New("retry.max_attempts must be at least 1") @@ -487,18 +488,8 @@ func Normalize(path string, cfg Config) (Config, error) { } } for _, raw := range cfg.RuntimeProxies() { - if raw == "direct" { - continue - } - clean, _ := ParseProxyEntry(raw) - u, err := url.Parse(clean) - if err != nil || u.Host == "" { - return Config{}, fmt.Errorf("invalid proxy URL %q", RedactURL(raw)) - } - switch strings.ToLower(u.Scheme) { - case "http", "https", "socks5", "socks5h": - default: - return Config{}, fmt.Errorf("unsupported proxy scheme %q", u.Scheme) + if err := ValidateProxyEntry(raw); err != nil { + return Config{}, err } } if err := cfg.Models.AnonymousBackoff.Normalize(); err != nil { diff --git a/internal/config/proxy.go b/internal/config/proxy.go index 3f55850..0dddcef 100644 --- a/internal/config/proxy.go +++ b/internal/config/proxy.go @@ -35,6 +35,23 @@ func ParseProxyEntry(raw string) (clean string, pool bool) { return trimmed, pool } +func ValidateProxyEntry(raw string) error { + if raw == "direct" { + return nil + } + clean, _ := ParseProxyEntry(raw) + parsed, err := url.Parse(clean) + if err != nil || parsed.Host == "" || parsed.Hostname() == "" { + return fmt.Errorf("invalid proxy URL %q", RedactURL(raw)) + } + switch strings.ToLower(parsed.Scheme) { + case "http", "https", "socks5", "socks5h": + return nil + default: + return fmt.Errorf("unsupported proxy scheme %q", parsed.Scheme) + } +} + // resolveProxyFiles trims cfg.Proxies in place and stores the runtime proxy // list: those proxies followed by the entries of cfg.ProxyFile (resolved // against the directory of configPath when relative), deduplicated, or diff --git a/internal/gateway/proxy_check.go b/internal/gateway/proxy_check.go new file mode 100644 index 0000000..23c746c --- /dev/null +++ b/internal/gateway/proxy_check.go @@ -0,0 +1,142 @@ +package gateway + +import ( + "context" + "errors" + "net" + "net/http" + "net/url" + "runtime" + "strings" + "syscall" + "time" + + "opencode2api/internal/config" + "opencode2api/internal/httpx" + "opencode2api/internal/models" +) + +type ProxyCheckResult struct { + OK bool `json:"ok"` + State string `json:"state"` + Reason string `json:"reason"` + LatencyMS int64 `json:"latency_ms"` + Status int `json:"status,omitempty"` +} + +func (m *RuntimeController) CheckProxy(parent context.Context, value string) (result ProxyCheckResult) { + started := time.Now() + result = ProxyCheckResult{State: "inconclusive", Reason: "transport_error"} + defer func() { result.LatencyMS = time.Since(started).Milliseconds() }() + runtime := m.current.Load() + if runtime == nil { + result.Reason = "runtime_unavailable" + return result + } + if err := config.ValidateProxyEntry(value); err != nil { + result.Reason = "invalid_proxy" + return result + } + ctx, cancel := context.WithTimeout(parent, 20*time.Second) + defer cancel() + performance := runtime.config.Performance + performance.ConnectTimeoutSeconds = min(max(performance.ConnectTimeoutSeconds, 1), 10) + performance.MaxIdleConns = 1 + performance.MaxIdleConnsPerHost = 1 + performance.MaxConnsPerHost = 1 + pool, err := transportPool([]string{value}, performance, 20*time.Second) + if err != nil { + return result + } + proxy := pool.items[0] + defer proxy.client.CloseIdleConnections() + defer proxy.bun.CloseIdleConnections() + client := proxy.bun + client.CheckRedirect = func(_ *http.Request, _ []*http.Request) error { return http.ErrUseLastResponse } + target, err := url.Parse(runtime.config.Upstream.Zen) + if err != nil || target.Host == "" { + result.Reason = "runtime_unavailable" + return result + } + target.User = nil + target.Path = strings.TrimRight(target.Path, "/") + "/v1/models" + target.RawPath, target.RawQuery, target.Fragment = "", "", "" + req, err := http.NewRequestWithContext(ctx, http.MethodGet, target.String(), nil) + if err != nil { + return result + } + req.Close = true + req.Header.Set("Accept", "application/json") + userAgent := httpx.V2UserAgent() + if models.IsV1Upstream(runtime.config.Upstream.Zen) { + userAgent = httpx.V1UserAgent() + } + req.Header.Set("User-Agent", userAgent) + req.Header.Set("x-opencode-client", "cli") + resp, err := client.Do(req) + if err != nil { + return proxyCheckFailure(ctx, value, err) + } + resp.Body.Close() + return proxyCheckStatus(resp.StatusCode) +} + +func proxyCheckStatus(status int) ProxyCheckResult { + result := ProxyCheckResult{State: "rejected", Reason: "upstream_responded", Status: status} + switch { + case status == http.StatusTooManyRequests: + result.State, result.Reason = "limited", "rate_limited" + case status == http.StatusUnauthorized: + result.OK, result.State, result.Reason = true, "available", "authentication_required" + case status >= 200 && status < 400: + result.OK, result.State, result.Reason = true, "available", "ok" + } + return result +} + +func proxyCheckFailure(ctx context.Context, value string, err error) ProxyCheckResult { + result := ProxyCheckResult{State: "inconclusive", Reason: "transport_error"} + if errors.Is(ctx.Err(), context.Canceled) { + result.Reason = "canceled" + return result + } + var timeout net.Error + if errors.Is(ctx.Err(), context.DeadlineExceeded) || errors.Is(err, context.DeadlineExceeded) || (errors.As(err, &timeout) && timeout.Timeout()) { + result.Reason = "check_timeout" + return result + } + var connectError *httpx.ProxyConnectError + if errors.As(err, &connectError) { + if connectError.StatusCode == http.StatusProxyAuthRequired { + result.State, result.Reason, result.Status = "unavailable", "proxy_authentication_required", connectError.StatusCode + return result + } + if connectError.StatusCode == http.StatusTooManyRequests { + return proxyCheckStatus(connectError.StatusCode) + } + result.State, result.Reason, result.Status = "rejected", "proxy_tunnel_rejected", connectError.StatusCode + return result + } + clean, _ := config.ParseProxyEntry(value) + if clean == "direct" { + return result + } + var routeError *net.OpError + if !errors.As(err, &routeError) || (routeError.Op != "proxyconnect" && routeError.Op != "socks connect") { + return result + } + var dialError *net.OpError + if !errors.As(routeError.Err, &dialError) || dialError.Op != "dial" { + return result + } + var dnsError *net.DNSError + refused := errors.Is(dialError, syscall.ECONNREFUSED) + if runtime.GOOS == "windows" { + const windowsConnectionRefused = syscall.Errno(10061) + refused = refused || errors.Is(dialError, windowsConnectionRefused) + } + if refused || (errors.As(dialError, &dnsError) && dnsError.IsNotFound) { + result.State, result.Reason = "unavailable", "proxy_unreachable" + } + return result +} diff --git a/internal/httpx/bun_dial.go b/internal/httpx/bun_dial.go index a0cea70..871182c 100644 --- a/internal/httpx/bun_dial.go +++ b/internal/httpx/bun_dial.go @@ -23,6 +23,14 @@ import ( // http.DefaultTransport. const bunHandshakeTimeout = 10 * time.Second +type ProxyConnectError struct { + StatusCode int +} + +func (err *ProxyConnectError) Error() string { + return fmt.Sprintf("proxy refused CONNECT: HTTP %d", err.StatusCode) +} + // bunClientHello returns the ClientHello of Bun's fetch, captured from Bun // 1.4.3. Bun links its own BoringSSL, so the hello is the same on every // platform: JA4 t13d1713h1, no GREASE, no padding, http/1.1 as the only ALPN @@ -189,7 +197,7 @@ func httpConnect(conn net.Conn, user *url.Userinfo, addr string) (net.Conn, erro return conn, err } if resp.StatusCode/100 != 2 { - return conn, fmt.Errorf("proxy refused CONNECT: %s", resp.Status) + return conn, &ProxyConnectError{StatusCode: resp.StatusCode} } if reader.Buffered() > 0 { return &bufferedConn{Conn: conn, reader: reader}, nil diff --git a/webui/css/pages.css b/webui/css/pages.css index 016e787..a545fe4 100644 --- a/webui/css/pages.css +++ b/webui/css/pages.css @@ -1,4 +1,40 @@ /* Page layouts: login, dashboards, charts, logs, playground and rotation. */ +.config-warning { + padding: var(--sp-3); + border: 1px solid var(--warn); + border-radius: var(--r-sm); + background: var(--warn-bg); + color: var(--warn); + font-size: var(--fs-sm); +} + +.proxy-actions, +.proxy-pager, +.proxy-row-actions { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: var(--sp-2); + margin-block: var(--sp-3); +} + +.proxy-row-actions { flex-wrap: nowrap; margin: 0; } +.proxy-search { max-width: 460px; } +.proxy-table-wrap { max-height: 60vh; overflow: auto; margin-block: var(--sp-3); } +.proxy-table { min-width: 820px; table-layout: fixed; } +.proxy-table thead th { position: sticky; top: 0; z-index: 1; background: var(--surface); } +.proxy-table th:first-child { width: 70px; } +.proxy-table th:nth-child(2) { width: 25%; } +.proxy-table th:nth-child(3) { width: 29%; } +.proxy-table th:nth-child(4) { width: 18%; } +.proxy-table th:nth-child(5) { width: 80px; } +.proxy-table th:last-child { width: 120px; } +.proxy-table td { vertical-align: middle; } +.proxy-address { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.proxy-reason { color: var(--text-2); font-size: var(--fs-xs); overflow-wrap: anywhere; } +.proxy-page-select { display: inline-flex; align-items: center; gap: var(--sp-1); } +.proxy-table input[type="checkbox"] { width: auto; margin: 0; } + .login-view { min-height: 100vh; display: grid; diff --git a/webui/index.html b/webui/index.html index 98aae1c..1b81d77 100644 --- a/webui/index.html +++ b/webui/index.html @@ -877,6 +877,7 @@ 启用 Zen 匿名通道 +
匿名通道默认关闭,可能已被上游重点封堵。建议优先配置 Zen API Key;启用匿名不保证可用,也不会自动修改当前设置。
仅检查指定代理到 Zen 的无认证连通性,不发模型推理、不验证额度、不使用上游 Key,也不依赖匿名通道开关。401 表示已到达上游且需认证;上游拒绝或限流不代表代理永久损坏,只有确认代理故障才会进入「选中确认故障」。
+检查与移除仅管理下列内联代理和新增草稿;proxyfile 条目请在文件中管理。移除需保存后生效,绑定验证失败时不会自动删除绑定。
+| + | 代理地址 | +检查结果 | +上游响应 | +耗时 | +操作 | +
|---|