From 4438acb8e713f619f129727618d4fcc842adf29c Mon Sep 17 00:00:00 2001 From: Jason Xu Date: Sun, 25 Oct 2026 05:51:00 +0800 Subject: [PATCH] feat(egress): route free-model traffic through userspace WARP Free-tier requests now optionally leave through a Cloudflare WARP tunnel that runs inside the gateway process: WireGuard over UDP plus a gVisor netstack, so no TUN device, root, NET_ADMIN, or route changes are needed. Adapted from github.com/sudogeeker/ai-route (MIT). - warp.enabled/pool_size/stack in config, the WebUI, config.example.json and all READMEs; startup and hot reload fail closed when WARP cannot initialize. - Anonymous lane, free-model Zen-key fallback, free-model probes and the anonymous catalog refresh send no proxy traffic while enabled; Go keys and paid models keep their proxies. - Per-attempt leases feed 403/429 rotation and broken-tunnel failures back into the pool; /healthz and /api/monitor expose the pool state and readiness requires an active exit. - errWARPUnavailable maps to a 503 warp_unavailable response. --- README.it.md | 16 +- README.md | 16 +- README.vi.md | 16 +- README.zh-CN.md | 16 +- config.example.json | 5 + docs/management.zh-CN.md | 8 + go.mod | 10 +- go.sum | 12 + internal/admin/server.go | 6 +- internal/config/config.go | 38 +++ internal/gateway/gateway.go | 30 +- internal/gateway/health.go | 47 +++- internal/gateway/probe.go | 58 +++- internal/gateway/refresh.go | 50 ++++ internal/gateway/runtime.go | 100 ++++++- internal/gateway/upstream.go | 98 +++++-- internal/gateway/warp.go | 347 +++++++++++++++++++++++ internal/httpx/bun.go | 8 +- internal/httpx/bun_dial.go | 4 +- internal/warp/bind.go | 137 +++++++++ internal/warp/doc.go | 9 + internal/warp/exit.go | 485 ++++++++++++++++++++++++++++++++ internal/warp/pool.go | 527 +++++++++++++++++++++++++++++++++++ internal/warp/registrar.go | 315 +++++++++++++++++++++ webui/index.html | 30 ++ webui/js/i18n.js | 27 +- webui/js/pages/config.js | 9 + webui/js/pages/overview.js | 22 +- 28 files changed, 2381 insertions(+), 65 deletions(-) create mode 100644 internal/gateway/warp.go create mode 100644 internal/warp/bind.go create mode 100644 internal/warp/doc.go create mode 100644 internal/warp/exit.go create mode 100644 internal/warp/pool.go create mode 100644 internal/warp/registrar.go diff --git a/README.it.md b/README.it.md index 4b44792..cd19b21 100644 --- a/README.it.md +++ b/README.it.md @@ -12,6 +12,7 @@ L'eseguibile include la WebUI: per eseguire il servizio non servono Node.js né - Testo, immagini, ragionamento, function tool, tool call e tool result; contenuti di file quando il protocollo di destinazione li supporta. - Pool separati di chiavi Zen e Go, preferenza del tier configurabile, retry e affinità di sessione. - Accesso anonimo opzionale a Zen con la credenziale `public` di OpenCode. +- Uscita Cloudflare WARP in userspace per il traffico dei modelli gratuiti, senza TUN né root. - Connessioni dirette e tramite HTTP, HTTPS, SOCKS5 e SOCKS5H, anche da un file proxy. - Rilevamento dinamico dei modelli, metadati del protocollo nativo e cache su disco. - Porta di gestione separata con modifica della configurazione, Playground, diagnostica, statistiche dei token e log in tempo reale. @@ -77,6 +78,8 @@ docker compose restart Il container esegue il servizio con un utente non privilegiato. Compose usa un filesystem root in sola lettura, un volume di stato scrivibile e un filesystem temporaneo `/tmp`. +WARP richiede solo UDP in uscita (endpoint Cloudflare, porta `2408`), quindi la configurazione dell'immagine senza privilegi e senza `NET_ADMIN` funziona così com'è; non serve passare a host networking né aggiungere `--cap-add`. Se la rete del container blocca UDP, l'abilitazione di WARP fallisce all'avvio. + | Variabile Compose | Predefinito | Effetto | | --------------------------- | ----------- | ---------------------------------------------------------- | | `OPENCODE2API_VERSION` | `latest` | Tag dell'immagine; fissa un tag di release per una versione precisa. | @@ -223,9 +226,17 @@ Quando è configurato solo l'accesso anonimo, `/v1/models` espone esclusivamente I modelli gratuiti non richiedono una chiave Zen: con `anonymous: true` usano il canale pubblico e un'eventuale chiave configurata serve solo come fallback. Per conservare le chiavi ma esporre solo modelli gratuiti, imposta `models.free_only: true`. I modelli a pagamento scompaiono da `/v1/models`, le richieste dirette vengono rifiutate e gli alias di rotazione mantengono solo i membri gratuiti; questi ultimi possono comunque usare le chiavi configurate come fallback. +### Uscita WARP per i modelli gratuiti + +`warp.enabled` sposta ogni richiesta di un modello gratuito sul canale gratuito — canale anonimo, fallback dei modelli gratuiti tramite chiave Zen, probe di disponibilità e aggiornamento anonimo del catalogo — su un tunnel Cloudflare WARP in userspace. Queste richieste non usano alcun proxy, quindi l'upstream vede l'indirizzo di uscita WARP invece del nodo configurato. Le chiavi del piano Go e i modelli a pagamento mantengono i loro proxy. + +Il tunnel vive nel processo del gateway: registra un dispositivo WARP, parla WireGuard su UDP con Cloudflare e termina in uno stack di rete in userspace. Non richiede dispositivi TUN, root, `NET_ADMIN` né modifiche alla tabella di routing, ma l'host o il container deve poter inviare UDP verso l'endpoint di Cloudflare (porta `2408`). Registrazione e probe del trace `warp=on` avvengono all'avvio; se WARP non riesce a inizializzarsi, l'avvio fallisce invece di ripiegare silenziosamente sui proxy. Anche l'abilitazione dalla WebUI è fail-closed: un valore errato restituisce un errore e il runtime precedente continua a servire. + +`warp.pool_size` (1–8, predefinito `2`) mantiene attive altrettante uscite e sostituisce automaticamente un'uscita bloccata o guasta; `warp.stack` seleziona `ipv4` (predefinito), `ipv6` o `dual`. `/healthz` restituisce un blocco `warp` e risponde 503 quando WARP è attivo ma nessuna uscita è operativa; `no_healthy_proxies` blocca la readiness solo con WARP disattivato o quando servono proxy per le chiavi Go. Le richieste diagnostiche acquisiscono un'uscita ma non la ruotano né la penalizzano. Disattivando WARP, i canali gratuiti tornano a usare i proxy. + ### Disponibilità dei modelli gratuiti -Il gateway verifica con una breve richiesta e il protocollo nativo i modelli il cui ID contiene `free` (senza distinzione tra maiuscole e minuscole) oppure i cui metadati indicano un costo input/output pari a zero e che non sono deprecati. Prova prima il canale anonimo abilitato, poi una chiave Zen configurata. Una risposta valida e completa su uno dei canali mantiene il modello abilitato. Il modello viene disabilitato nel rilevamento e nell'instradamento solo quando tutti i canali provati indicano esplicitamente che non esiste o è stato ritirato. Errori di autenticazione, limiti di frequenza, timeout, errori di trasporto, risposte 5xx e risposte malformate non sono conclusivi: non disabilitano nuovi modelli e vengono verificati di nuovo dopo un'ora. I controlli non alterano cooldown, stato dei proxy o statistiche delle richieste di produzione, ma raggiungono comunque l'upstream e possono consumare la quota gratuita. +Il gateway verifica con una breve richiesta e il protocollo nativo i modelli il cui ID contiene `free` (senza distinzione tra maiuscole e minuscole) oppure i cui metadati indicano un costo input/output pari a zero e che non sono deprecati. Prova prima il canale anonimo abilitato, poi una chiave Zen configurata. Con `warp.enabled`, ogni canale di probe esce tramite WARP invece che da un proxy; se non è possibile acquisire un'uscita il risultato è `warp_unavailable` e resta inconcludente. Una risposta valida e completa su uno dei canali mantiene il modello abilitato. Il modello viene disabilitato nel rilevamento e nell'instradamento solo quando tutti i canali provati indicano esplicitamente che non esiste o è stato ritirato. Errori di autenticazione, limiti di frequenza, timeout, errori di trasporto, risposte 5xx e risposte malformate non sono conclusivi: non disabilitano nuovi modelli e vengono verificati di nuovo dopo un'ora. I controlli non alterano cooldown, stato dei proxy o statistiche delle richieste di produzione, ma raggiungono comunque l'upstream e possono consumare la quota gratuita. I modelli System One usano una domanda nativa `noul` che chiede se 1 + 1 è uguale a 2; non ricevono mai payload chat/tool. Il rilevamento dei modelli include `native_protocol` e `supported_endpoints`; gli alias di rotazione sono elencati solo quando esistono chiavi Go e modelli idonei. Le disabilitazioni legacy della versione v1.3.6 vengono cancellate al caricamento e verificate subito, perché quei controlli usavano ID sessione non validi. @@ -259,6 +270,9 @@ Consulta [config.example.json](config.example.json) per una configurazione inizi | `server_keys` | È richiesta almeno una chiave locale. | | `zen_keys`, `go_keys` | È richiesta una chiave upstream, salvo accesso anonimo abilitato. | | `anonymous` | `false`. | +| `warp.enabled` | `false`; il traffico dei canali gratuiti esce via Cloudflare WARP, senza proxy. | +| `warp.pool_size` | `2`; uscite WARP attive, 1–8. | +| `warp.stack` | `ipv4`; `ipv4`, `ipv6` o `dual`. | | `prefer` | `go`; accetta `go` o `zen`. | | `upstream.zen` | `https://opencode.ai/inference/openai`. | | `upstream.go` | `https://opencode.ai/zen/go`. | diff --git a/README.md b/README.md index 17e2ebb..31218f4 100644 --- a/README.md +++ b/README.md @@ -12,6 +12,7 @@ The executable includes the WebUI. Running the service requires no Node.js runti - 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. +- 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. - A separate management port with configuration editing, a Playground, diagnostics, token statistics, and live logs. @@ -77,6 +78,8 @@ docker compose restart The container runs the service as an unprivileged user. Compose uses a read-only root filesystem, a writable state volume, and a temporary `/tmp` filesystem. +WARP needs only outbound UDP (Cloudflare endpoint port `2408`), so the image's non-root, no-`NET_ADMIN` setup still works; do not switch to host networking or add `--cap-add` for it. If the container network blocks UDP, enabling WARP fails at startup. + | Compose variable | Default | Effect | | --------------------------- | -------- | ------------------------------------------------- | | `OPENCODE2API_VERSION` | `latest` | Image tag. Pin a release tag for a fixed version. | @@ -225,9 +228,17 @@ When only anonymous access is configured, `/v1/models` exposes only models eligi 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. +### WARP egress for free models + +`warp.enabled` moves every free-model request on a free lane — the anonymous lane, the free-model fallback through a Zen key, free-model availability probes, and the anonymous catalog refresh — onto a userspace Cloudflare WARP tunnel. Those requests use no proxy, so the free tier sees the WARP exit address instead of a configured node. Go-plan keys and paid models keep their proxy bindings. + +The tunnel lives inside the gateway process: it registers a WARP device, speaks WireGuard over UDP to Cloudflare, and terminates in a userspace network stack. It needs no TUN device, root, `NET_ADMIN`, or routing-table change, but the host or container must be able to send UDP to Cloudflare's endpoint (port `2408`). Registration and the `warp=on` trace probe run at startup; if WARP cannot initialize, startup fails instead of silently falling back to proxies. Enabling it through the WebUI is also fail-closed: a bad value returns an error and the previous runtime keeps serving. + +`warp.pool_size` (1–8, default `2`) keeps that many exits active and replaces a blocked or broken exit automatically. `warp.stack` selects `ipv4` (default), `ipv6`, or `dual`. `/healthz` reports a `warp` block and answers 503 while WARP is enabled but no exit is active; `no_healthy_proxies` only blocks readiness when WARP is off or Go keys need proxies. Diagnostics acquire an exit but never rotate or penalize it. Turning WARP off restores proxy routing for the free lanes. + ### Free model availability -The gateway probes models whose IDs contain `free` (case-insensitive), or whose metadata reports zero input/output cost without deprecation, with a short request using its native protocol. It tries the enabled anonymous lane first and then one configured Zen Key. A valid completed response on either lane keeps the model enabled; the model is disabled in discovery and routing only when every attempted lane explicitly reports that the model does not exist or has been retired. Authentication errors, rate limits, timeouts, transport errors, 5xx responses, and malformed replies are inconclusive: they do not create a new disable, and are checked again in one hour. Probe traffic does not alter production key/proxy cooldowns or request statistics. It still reaches the upstream and may consume its free allowance. +The gateway probes models whose IDs contain `free` (case-insensitive), or whose metadata reports zero input/output cost without deprecation, with a short request using its native protocol. It tries the enabled anonymous lane first and then one configured Zen Key. With `warp.enabled`, every probe lane leaves through WARP instead of a proxy; when no exit can be acquired the probe reports `warp_unavailable` and stays inconclusive. A valid completed response on either lane keeps the model enabled; the model is disabled in discovery and routing only when every attempted lane explicitly reports that the model does not exist or has been retired. Authentication errors, rate limits, timeouts, transport errors, 5xx responses, and malformed replies are inconclusive: they do not create a new disable, and are checked again in one hour. Probe traffic does not alter production key/proxy cooldowns or request statistics. It still reaches the upstream and may consume its free allowance. System One models use a native `noul` question asking whether 1 + 1 equals 2; they are never sent chat/tool payloads. Model discovery includes `native_protocol` and `supported_endpoints`; rotation aliases are listed only when Go keys and eligible models exist. Legacy v1.3.6 disables are cleared on load and scheduled for immediate recheck because those probes used invalid session IDs. @@ -261,6 +272,9 @@ See [config.example.json](config.example.json) for a complete starting configura | `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`. | +| `warp.enabled` | `false`; free-lane traffic leaves through Cloudflare WARP and no proxy. | +| `warp.pool_size` | `2`; active WARP exits, 1–8. | +| `warp.stack` | `ipv4`; `ipv4`, `ipv6`, or `dual`. | | `prefer` | `go`; accepts `go` or `zen`. | | `upstream.zen` | `https://opencode.ai/zen`. | | `upstream.go` | `https://opencode.ai/zen/go`. | diff --git a/README.vi.md b/README.vi.md index bca7484..88c9440 100644 --- a/README.vi.md +++ b/README.vi.md @@ -12,6 +12,7 @@ File thực thi đã bao gồm WebUI. Việc chạy dịch vụ không cần Nod - Văn bản, hình ảnh, suy luận, function tool, tool call và tool result; nội dung tệp ở nơi giao thức đích có thể biểu diễn. - Hai nhóm key Zen và Go riêng biệt, tier ưu tiên có thể cấu hình, retry và session affinity. - Truy cập Zen ẩn danh tuỳ chọn bằng credential `public` của OpenCode. +- Đầu ra Cloudflare WARP chạy trong tiến trình cho lưu lượng mô hình miễn phí, không cần TUN hay root. - Kết nối direct, HTTP, HTTPS, SOCKS5 và SOCKS5H, bao gồm cả file proxy. - Tự động phát hiện mô hình, metadata giao thức gốc và cache trên đĩa. - Cổng quản trị riêng với chỉnh sửa cấu hình, Playground, chẩn đoán, thống kê token và log trực tiếp. @@ -79,6 +80,8 @@ docker compose restart Container chạy dịch vụ bằng user không có đặc quyền. Compose dùng hệ thống file gốc chỉ đọc, volume trạng thái ghi được và hệ thống file tạm `/tmp`. +WARP chỉ cần UDP ra ngoài (endpoint Cloudflare, cổng `2408`), nên thiết lập user thường, không `NET_ADMIN` của image vẫn dùng được; không cần chuyển sang host networking hay thêm `--cap-add`. Nếu mạng container chặn UDP, việc bật WARP sẽ thất bại lúc khởi động. + | Biến Compose | Mặc định | Tác dụng | | -------------------------------- | --------- | ----------------------------------------------------------- | | `OPENCODE2API_VERSION` | `latest` | Tag image. Ghim tag release khi cần phiên bản cố định. | @@ -229,9 +232,17 @@ Khi chỉ cấu hình truy cập ẩn danh, `/v1/models` chỉ công khai các m Mô hình miễn phí không bao giờ cần key Zen: với `anonymous: true` chúng được phục vụ bởi làn public, và key được cấu hình chỉ là phương án dự phòng. Muốn giữ key nhưng chỉ công khai mô hình miễn phí, hãy đặt `models.free_only: true`. Khi đó mô hình trả phí biến mất khỏi `/v1/models`, request trực tiếp tới chúng bị từ chối, và bí danh luân chuyển chỉ giữ lại thành viên miễn phí; mô hình miễn phí vẫn có thể dự phòng về các key đã cấu hình. +### Đầu ra WARP cho mô hình miễn phí + +`warp.enabled` đưa mọi request mô hình miễn phí trên làn miễn phí — làn ẩn danh, dự phòng mô hình miễn phí qua Zen Key, dò tính khả dụng mô hình miễn phí, và làm mới danh mục mô hình ẩn danh — sang đường hầm Cloudflare WARP chạy trong tiến trình. Các request này không dùng proxy nào, nên upstream thấy địa chỉ đầu ra WARP thay vì nút đã cấu hình. Key gói Go và mô hình trả phí vẫn giữ proxy. + +Đường hầm chạy bên trong tiến trình gateway: đăng ký thiết bị WARP, nói WireGuard qua UDP với Cloudflare và kết thúc trong một ngăn xếp mạng userspace. Nó không cần thiết bị TUN, root, `NET_ADMIN` hay thay đổi bảng định tuyến, nhưng máy chủ hoặc container phải gửi được UDP tới endpoint của Cloudflare (cổng `2408`). Đăng ký và probe trace `warp=on` chạy lúc khởi động; nếu WARP không khởi tạo được, quá trình khởi động thất bại thay vì âm thầm quay về proxy. Bật qua WebUI cũng đóng khi lỗi: giá trị sai trả về lỗi và runtime cũ tiếp tục phục vụ. + +`warp.pool_size` (1–8, mặc định `2`) giữ số đầu ra đó ở trạng thái hoạt động và tự thay thế đầu ra bị chặn hoặc hỏng; `warp.stack` chọn `ipv4` (mặc định), `ipv6` hoặc `dual`. `/healthz` trả về khối `warp` và 503 khi WARP bật nhưng không có đầu ra nào hoạt động; `no_healthy_proxies` chỉ chặn readiness khi WARP tắt hoặc có key Go cần proxy. Request chẩn đoán có lấy đầu ra nhưng không bao giờ luân chuyển hay phạt nó. Tắt WARP sẽ khôi phục định tuyến qua proxy cho các làn miễn phí. + ### Tính khả dụng của mô hình miễn phí -Gateway dò các mô hình có ID chứa `free` (không phân biệt hoa thường), hoặc có metadata báo chi phí input/output bằng 0 mà không bị ngừng cấp, bằng một request ngắn dùng giao thức gốc của mô hình. Nó thử làn ẩn danh đang bật trước, rồi tới một Zen Key đã cấu hình. Một phản hồi hợp lệ và hoàn tất trên bất kỳ làn nào sẽ giữ mô hình ở trạng thái bật; mô hình chỉ bị tắt trong phát hiện và định tuyến khi mọi làn được thử đều báo rõ ràng rằng mô hình không tồn tại hoặc đã bị thu hồi. Lỗi xác thực, giới hạn tần suất, timeout, lỗi truyền tải, phản hồi 5xx và câu trả lời sai định dạng đều không kết luận: chúng không tạo ra lần tắt mới và sẽ được kiểm tra lại sau một giờ. Lưu lượng dò không làm thay đổi cooldown key/proxy sản xuất hay thống kê request. Nó vẫn đi tới upstream và có thể tiêu tốn hạn mức miễn phí của họ. +Gateway dò các mô hình có ID chứa `free` (không phân biệt hoa thường), hoặc có metadata báo chi phí input/output bằng 0 mà không bị ngừng cấp, bằng một request ngắn dùng giao thức gốc của mô hình. Nó thử làn ẩn danh đang bật trước, rồi tới một Zen Key đã cấu hình. Khi bật `warp.enabled`, mọi làn dò đi qua WARP thay vì proxy; nếu không lấy được đầu ra, kết quả là `warp_unavailable` và được coi là không kết luận. Một phản hồi hợp lệ và hoàn tất trên bất kỳ làn nào sẽ giữ mô hình ở trạng thái bật; mô hình chỉ bị tắt trong phát hiện và định tuyến khi mọi làn được thử đều báo rõ ràng rằng mô hình không tồn tại hoặc đã bị thu hồi. Lỗi xác thực, giới hạn tần suất, timeout, lỗi truyền tải, phản hồi 5xx và câu trả lời sai định dạng đều không kết luận: chúng không tạo ra lần tắt mới và sẽ được kiểm tra lại sau một giờ. Lưu lượng dò không làm thay đổi cooldown key/proxy sản xuất hay thống kê request. Nó vẫn đi tới upstream và có thể tiêu tốn hạn mức miễn phí của họ. Mô hình System One dùng câu hỏi `noul` gốc hỏi rằng 1 + 1 có bằng 2 không; chúng không bao giờ được gửi payload chat/tool. Việc phát hiện mô hình gồm `native_protocol` và `supported_endpoints`; bí danh luân chuyển chỉ được liệt kê khi có key Go và mô hình đủ điều kiện. Lần tắt còn sót từ bản v1.3.6 sẽ được xoá khi nạp và lên lịch kiểm tra lại ngay, vì các lần dó đó dùng session ID không hợp lệ. @@ -265,6 +276,9 @@ Xem [config.example.json](config.example.json) để có một cấu hình khở | `server_keys` | Cần ít nhất một key cục bộ. | | `zen_keys`, `go_keys` | Cần ít nhất một key upstream trừ khi bật truy cập ẩn danh. | | `anonymous` | `false`. | +| `warp.enabled` | `false`; lưu lượng làn miễn phí đi qua Cloudflare WARP, không dùng proxy. | +| `warp.pool_size` | `2`; số đầu ra WARP hoạt động, 1–8. | +| `warp.stack` | `ipv4`; `ipv4`, `ipv6` hoặc `dual`. | | `prefer` | `go`; nhận `go` hoặc `zen`. | | `upstream.zen` | `https://opencode.ai/zen`. | | `upstream.go` | `https://opencode.ai/zen/go`. | diff --git a/README.zh-CN.md b/README.zh-CN.md index f355417..a325ae3 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -12,6 +12,7 @@ WebUI 内嵌在可执行文件中,运行服务无需 Node.js 或数据库。 - 文本、图片、reasoning、函数工具、工具调用和工具结果;目标协议允许时支持文件内容转换。 - 独立的 Zen / Go Key 池,可配置优先级、重试和会话亲和性。 - 使用 OpenCode `public` 凭证的可选 Zen 匿名通道。 +- 可选的用户态 Cloudflare WARP 出口,免费模型流量无需 TUN 或 root 权限。 - 直连、HTTP、HTTPS、SOCKS5、SOCKS5H 连接,以及代理文件。 - 动态模型发现、原生协议与能力信息、磁盘缓存。 - 独立管理端口,支持配置编辑、Playground、路由诊断、Token 统计和实时日志。 @@ -77,6 +78,8 @@ docker compose restart 容器内的服务进程使用普通用户运行。Compose 启用只读根文件系统,并提供可写状态卷和临时 `/tmp` 文件系统。 +WARP 只需要出站 UDP(Cloudflare 端点端口 `2408`),因此镜像的普通用户、无 `NET_ADMIN` 配置无需改动;不要为此改用 host 网络或添加 `--cap-add`。如果容器网络禁止 UDP,启用 WARP 会在启动时失败。 + | Compose 环境变量 | 默认值 | 作用 | | --------------------------- | -------- | ------------------------------------ | | `OPENCODE2API_VERSION` | `latest` | 镜像标签;可指定发行标签来固定版本。 | @@ -225,9 +228,17 @@ System One 将自由文本状态与类型化问题配对,并返回类型化答 免费模型不需要 Zen Key:启用 `anonymous: true` 后由匿名通道提供,已配置的 Key 只作为回退。如果想保留 Key 但只暴露免费模型,设置 `models.free_only: true`:付费模型不再出现在 `/v1/models`,直接请求会被拒绝,轮转别名只保留免费成员;免费模型仍可回退到已配置的 Key。 +### 免费模型 WARP 出口 + +启用 `warp.enabled` 后,免费通道上的所有免费模型请求——匿名通道、通过 Zen Key 的免费模型回退、免费模型可用性探测,以及匿名模型目录刷新——都改走用户态 Cloudflare WARP 隧道,不再使用任何代理,因此上游看到的是 WARP 出口地址,而不是配置的节点。Go 套餐 Key 与付费模型仍使用原有代理绑定。 + +隧道运行在网关进程内:注册 WARP 设备,通过 UDP 与 Cloudflare 建立 WireGuard 连接,并在用户态网络栈中终结。它不需要 TUN 设备、root、`NET_ADMIN` 或修改路由表,但宿主机(或容器)必须能向 Cloudflare 端点发送 UDP(端口 `2408`)。注册与 `warp=on` 的 trace 探测在启动时完成;WARP 无法初始化时启动直接失败,不会静默回退到代理。通过 WebUI 启用同样采用失败即拒绝:参数错误会返回错误,旧运行时继续服务。 + +`warp.pool_size`(1–8,默认 `2`)保持相应数量的出口可用,并在出口被封锁或损坏时自动替换;`warp.stack` 可选 `ipv4`(默认)、`ipv6` 或 `dual`。`/healthz` 会返回 `warp` 状态块;启用 WARP 但没有任何活跃出口时返回 503。只有 WARP 关闭或存在 Go Key 需要代理时,`no_healthy_proxies` 才会阻塞就绪。诊断请求会占用出口,但不会轮换或淘汰它。关闭 WARP 后,免费通道恢复使用代理。 + ### 免费模型可用性 -只探测 ID 含 `free`(不区分大小写),或元数据输入、输出价格均为零且未弃用的模型,按模型原生协议发送简短探测请求。先尝试已启用的匿名通道,再尝试一个配置的 Zen Key;任一通道返回完整有效响应即视为可用,只有所有实际尝试的通道都明确返回模型不存在或已下架时才自动禁用,从模型列表与路由中移除。认证失败、429、超时、网络错误、5xx 和响应格式异常均视为结果不确定,不新增禁用,1 小时后复测。探测不修改生产 Key / 代理的冷却状态,也不计入请求统计,但仍会访问上游并可能消耗免费额度。 +只探测 ID 含 `free`(不区分大小写),或元数据输入、输出价格均为零且未弃用的模型,按模型原生协议发送简短探测请求。先尝试已启用的匿名通道,再尝试一个配置的 Zen Key;启用 `warp.enabled` 时,每条探测通道都改走 WARP 而不是代理,无法取得出口时结果为 `warp_unavailable`,视为不确定。任一通道返回完整有效响应即视为可用,只有所有实际尝试的通道都明确返回模型不存在或已下架时才自动禁用,从模型列表与路由中移除。认证失败、429、超时、网络错误、5xx 和响应格式异常均视为结果不确定,不新增禁用,1 小时后复测。探测不修改生产 Key / 代理的冷却状态,也不计入请求统计,但仍会访问上游并可能消耗免费额度。 System One 使用原生 `noul` 类型询问“1+1 是否等于 2”,不注入聊天或工具字段。模型列表标明 `native_protocol` 和 `supported_endpoints`;仅在配置 Go Key 且有可用模型时展示轮转别名。升级时解除 v1.3.6 旧探测生成的禁用并立即安排复测,避免非法会话 ID 造成的误判继续保留。 @@ -261,6 +272,9 @@ Key 初始化时均衡分配到代理。真实流量可以触发代理检查、K | `server_keys` | 至少一个本地 Key。 | | `zen_keys`、`go_keys` | 未启用匿名模式时,至少需要一个上游 Key。 | | `anonymous` | `false`。 | +| `warp.enabled` | `false`;免费通道流量通过 Cloudflare WARP 出口,不使用代理。 | +| `warp.pool_size` | `2`;活跃 WARP 出口数量,1–8。 | +| `warp.stack` | `ipv4`;可选 `ipv4`、`ipv6`、`dual`。 | | `prefer` | `go`;可选 `go`、`zen`。 | | `upstream.zen` | `https://opencode.ai/zen`。 | | `upstream.go` | `https://opencode.ai/zen/go`。 | diff --git a/config.example.json b/config.example.json index 40cade1..3528a1d 100644 --- a/config.example.json +++ b/config.example.json @@ -4,6 +4,11 @@ "zen_keys": [], "go_keys": [], "anonymous": true, + "warp": { + "enabled": false, + "pool_size": 2, + "stack": "ipv4" + }, "proxies": ["direct"], "proxyfile": "", "upstream": { diff --git a/docs/management.zh-CN.md b/docs/management.zh-CN.md index a43b36c..7a1a663 100644 --- a/docs/management.zh-CN.md +++ b/docs/management.zh-CN.md @@ -27,6 +27,14 @@ - 元数据以 `server_key_metadata` 保存在原配置中,按 Key 指纹关联;已有 `server_keys` 自动兼容。 - 当前未实现按 Key 单独分配模型权限、用量配额或过期时间。 +## WARP 免费模型出口 + +WebUI「Proxy 节点」页底部新增 WARP 开关,对应配置 `warp.enabled`(默认关闭)、`warp.pool_size`(1–8,默认 2)和 `warp.stack`(`ipv4`、`ipv6` 或 `dual`)。开启后,匿名通道、免费模型的 Zen Key 回退、免费模型可用性探测和匿名模型目录刷新都通过用户态 Cloudflare WARP 出网,不再使用任何代理;Go 套餐 Key 与付费模型保持原有代理绑定。 + +- 主机或容器必须能向 Cloudflare 端点发送 UDP(端口 `2408`);不需要 TUN 设备、root、`NET_ADMIN` 或修改路由表。 +- WARP 无法初始化时启动直接失败;通过 WebUI 启用时参数错误会返回错误,旧运行时继续服务,不会静默回退到代理。 +- `/healthz` 的 `warp` 块与 `/api/monitor` 的 `resources.warp` 显示堆栈、出口数量、活跃/备用/冷却数量和出口地址;启用 WARP 但无活跃出口时健康检查返回 503,此时若没有 Go Key,`no_healthy_proxies` 不再阻塞就绪。 + ## 验证和构建 ```bash diff --git a/go.mod b/go.mod index d2e0777..5ea5c5d 100644 --- a/go.mod +++ b/go.mod @@ -7,6 +7,14 @@ require ( github.com/klauspost/compress v1.18.0 github.com/refraction-networking/utls v1.8.2 golang.org/x/crypto v0.41.0 + golang.zx2c4.com/wireguard v0.0.0-20261006164505-2631ce99a06f ) -require golang.org/x/sys v0.35.0 // indirect +require ( + github.com/google/btree v1.1.2 // indirect + golang.org/x/net v0.42.0 // indirect + golang.org/x/sys v0.35.0 // indirect + golang.org/x/time v0.7.0 // indirect + golang.zx2c4.com/wintun v0.0.0-20230126152724-0fa3db229ce2 // indirect + gvisor.dev/gvisor v0.0.0-20250503011706-39ed1f5ac29c // indirect +) diff --git a/go.sum b/go.sum index e295d23..5603523 100644 --- a/go.sum +++ b/go.sum @@ -1,5 +1,7 @@ github.com/andybalholm/brotli v1.1.1 h1:PR2pgnyFznKEugtsUo0xLdDop5SKXd5Qf5ysW+7XdTA= github.com/andybalholm/brotli v1.1.1/go.mod h1:05ib4cKhjx3OQYUY22hTVd34Bc8upXjOLL2rKwwZBoA= +github.com/google/btree v1.1.2 h1:xf4v41cLI2Z6FxbKm+8Bu+m8ifhj15JuZ9sa0jZCMUU= +github.com/google/btree v1.1.2/go.mod h1:qOPhT0dTNdNzV6Z/lhRX0YXUafgPLFUh+gZMl761Gm4= github.com/klauspost/compress v1.18.0 h1:c/Cqfb0r+Yi+JtIEq73FWXVkRonBlf0CRNYc8Zttxdo= github.com/klauspost/compress v1.18.0/go.mod h1:2Pp+KzxcywXVXMr50+X0Q/Lsb43OQHYWRCY2AiWywWQ= github.com/refraction-networking/utls v1.8.2 h1:j4Q1gJj0xngdeH+Ox/qND11aEfhpgoEvV+S9iJ2IdQo= @@ -8,5 +10,15 @@ github.com/xyproto/randomstring v1.0.5 h1:YtlWPoRdgMu3NZtP45drfy1GKoojuR7hmRcnhZ github.com/xyproto/randomstring v1.0.5/go.mod h1:rgmS5DeNXLivK7YprL0pY+lTuhNQW3iGxZ18UQApw/E= golang.org/x/crypto v0.41.0 h1:WKYxWedPGCTVVl5+WHSSrOBT0O8lx32+zxmHxijgXp4= golang.org/x/crypto v0.41.0/go.mod h1:pO5AFd7FA68rFak7rOAGVuygIISepHftHnr8dr6+sUc= +golang.org/x/net v0.42.0 h1:jzkYrhi3YQWD6MLBJcsklgQsoAcw89EcZbJw8Z614hs= +golang.org/x/net v0.42.0/go.mod h1:FF1RA5d3u7nAYA4z2TkclSCKh68eSXtiFwcWQpPXdt8= golang.org/x/sys v0.35.0 h1:vz1N37gP5bs89s7He8XuIYXpyY0+QlsKmzipCbUtyxI= golang.org/x/sys v0.35.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k= +golang.org/x/time v0.7.0 h1:ntUhktv3OPE6TgYxXWv9vKvUSJyIFJlyohwbkEwPrKQ= +golang.org/x/time v0.7.0/go.mod h1:3BpzKBy/shNhVucY/MWOyx10tF3SFh9QdLuxbVysPQM= +golang.zx2c4.com/wintun v0.0.0-20230126152724-0fa3db229ce2 h1:B82qJJgjvYKsXS9jeunTOisW56dUokqW/FOteYJJ/yg= +golang.zx2c4.com/wintun v0.0.0-20230126152724-0fa3db229ce2/go.mod h1:deeaetjYA+DHMHg+sMSMI58GrEteJUUzzw7en6TJQcI= +golang.zx2c4.com/wireguard v0.0.0-20261006164505-2631ce99a06f h1:gJI6OVshWW0mvGyTVmW8mJoaw2OM69wVCeZkwpX+Jdc= +golang.zx2c4.com/wireguard v0.0.0-20261006164505-2631ce99a06f/go.mod h1:rpwXGsirqLqN2L0JDJQlwOboGHmptD5ZD6T2VmcqhTw= +gvisor.dev/gvisor v0.0.0-20250503011706-39ed1f5ac29c h1:m/r7OM+Y2Ty1sgBQ7Qb27VgIMBW8ZZhT4gLnUyDIhzI= +gvisor.dev/gvisor v0.0.0-20250503011706-39ed1f5ac29c/go.mod h1:3r5CMtNQMKIvBlrmM9xWUNamjKBYPOWyXOjmg5Kts3g= diff --git a/internal/admin/server.go b/internal/admin/server.go index b333bd1..8e94f38 100644 --- a/internal/admin/server.go +++ b/internal/admin/server.go @@ -140,6 +140,7 @@ type ConfigView struct { ZenKeys []SecretView `json:"zen_keys"` GoKeys []SecretView `json:"go_keys"` Anonymous bool `json:"anonymous"` + Warp config.WarpConfig `json:"warp"` Proxies []SecretView `json:"proxies"` ProxyFile string `json:"proxyfile"` Upstream config.UpstreamConfig `json:"upstream"` @@ -187,6 +188,7 @@ type ConfigUpdate struct { ZenKeys []SecretInput `json:"zen_keys"` GoKeys []SecretInput `json:"go_keys"` Anonymous bool `json:"anonymous"` + Warp config.WarpConfig `json:"warp"` Proxies []SecretInput `json:"proxies"` ProxyFile string `json:"proxyfile"` Upstream config.UpstreamConfig `json:"upstream"` @@ -245,7 +247,7 @@ func (a *Server) handlePutConfig(w http.ResponseWriter, r *http.Request) { candidate := config.Config{ ServerKeyMetadata: current.ServerKeyMetadata, Rotation: current.Rotation, - Listen: update.Listen, ServerKeys: serverKeys, ZenKeys: zenKeys, GoKeys: goKeys, Anonymous: update.Anonymous, Proxies: proxies, ProxyFile: update.ProxyFile, + Listen: update.Listen, ServerKeys: serverKeys, ZenKeys: zenKeys, GoKeys: goKeys, Anonymous: update.Anonymous, Warp: update.Warp, Proxies: proxies, ProxyFile: update.ProxyFile, Upstream: update.Upstream, Retry: update.Retry, Models: update.Models, Performance: update.Performance, Logging: update.Logging, Prefer: update.Prefer, Reasoning: reasoning, WebUI: config.WebUIConfig{Enabled: update.WebUI.Enabled, Listen: update.WebUI.Listen, Username: current.WebUI.Username, PasswordHash: current.WebUI.PasswordHash, SessionTTLMinutes: update.WebUI.SessionTTLMinutes}, @@ -387,7 +389,7 @@ func (a *Server) configView() ConfigView { cfg := a.manager.Config() effective, restart := a.manager.RestartStatus() return ConfigView{ - Listen: cfg.Listen, ServerKeys: maskSecrets(cfg.ServerKeys, false), ZenKeys: maskSecrets(cfg.ZenKeys, false), GoKeys: maskSecrets(cfg.GoKeys, false), Anonymous: cfg.Anonymous, + Listen: cfg.Listen, ServerKeys: maskSecrets(cfg.ServerKeys, false), ZenKeys: maskSecrets(cfg.ZenKeys, false), GoKeys: maskSecrets(cfg.GoKeys, false), Anonymous: cfg.Anonymous, Warp: cfg.Warp, Proxies: maskSecrets(cfg.Proxies, true), ProxyFile: cfg.ProxyFile, Upstream: cfg.Upstream, Retry: cfg.Retry, Models: cfg.Models, Performance: cfg.Performance, Logging: cfg.Logging, Prefer: cfg.Prefer, Reasoning: cfg.Reasoning, WebUI: WebUIView{Enabled: cfg.WebUI.Enabled, Listen: cfg.WebUI.Listen, Username: cfg.WebUI.Username, SessionTTLMinutes: cfg.WebUI.SessionTTLMinutes}, diff --git a/internal/config/config.go b/internal/config/config.go index 310c2f7..c9f581f 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -13,6 +13,7 @@ import ( "opencode2api/internal/jsonutil" wire "opencode2api/internal/protocol" + "opencode2api/internal/warp" ) // Config is the service configuration stored in config.json. @@ -31,6 +32,7 @@ type Config struct { ZenKeys []string `json:"zen_keys"` GoKeys []string `json:"go_keys"` Anonymous bool `json:"anonymous"` + Warp WarpConfig `json:"warp"` Proxies []string `json:"proxies"` ProxyFile string `json:"proxyfile"` Upstream UpstreamConfig `json:"upstream"` @@ -62,6 +64,38 @@ type ReasoningConfig struct { EffortByModel map[string]string `json:"effort_by_model,omitempty"` } +// WarpConfig controls the optional Cloudflare WARP egress. While enabled, +// free-model traffic on the anonymous lane and the free Zen-key fallback is +// sent through a userspace WireGuard tunnel instead of any configured proxy. +// PoolSize is the number of registered WARP exits kept warm (the last one is +// held as hot standby); Stack selects the tunnel's address family. Initialization +// is fail-closed: a configuration that enables WARP is rejected when no exit +// can be established. +type WarpConfig struct { + Enabled bool `json:"enabled"` + PoolSize int `json:"pool_size,omitempty"` + Stack string `json:"stack,omitempty"` +} + +// Normalize fills the defaults and canonicalizes the stack name. +func (w *WarpConfig) Normalize() error { + if w.PoolSize == 0 { + w.PoolSize = 2 + } + if strings.TrimSpace(w.Stack) == "" { + w.Stack = string(warp.DefaultStack) + } + stack, err := warp.ParseStack(w.Stack) + if err != nil { + return fmt.Errorf("warp.stack: %w", err) + } + w.Stack = string(stack) + if w.PoolSize < 1 || w.PoolSize > 8 { + return errors.New("warp.pool_size must be between 1 and 8") + } + return nil +} + // UpstreamConfig holds the base URLs of the OpenCode origins. The gateway // picks the request shape from the base URL (models.IsV1Upstream): one ending // in /zen is the v1 lane, any other a v2 lane. @@ -237,6 +271,7 @@ func Load(path string) (Config, error) { } cfg := Config{ Listen: "127.0.0.1:8080", + 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}, Models: ModelsConfig{RefreshSeconds: 300, Protocols: map[string]string{}}, @@ -264,6 +299,9 @@ func Normalize(path string, cfg Config) (Config, error) { if err := cfg.Rotation.Validate(nil); err != nil { return Config{}, err } + if err := cfg.Warp.Normalize(); err != nil { + return Config{}, err + } trimList(&cfg.ServerKeys) remapServerKeyMetadata(&cfg) diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go index 838e532..36a6fdc 100644 --- a/internal/gateway/gateway.go +++ b/internal/gateway/gateway.go @@ -33,6 +33,7 @@ import ( wire "opencode2api/internal/protocol" "opencode2api/internal/rotation" "opencode2api/internal/telemetry" + "opencode2api/internal/warp" ) const maxRequestBody = 32 << 20 @@ -69,13 +70,17 @@ const proxyUnavailableMessage = "all proxies are unavailable; the upstream could // config; applying a new config builds a new Gateway (see RuntimeController) // instead of mutating this one. type Gateway struct { - rotation *rotation.Manager - cfg config.Config - logger *slog.Logger - transports *proxyTransports - zenNodes *upstreamNodes - goNodes *upstreamNodes - anonymous *anonymousNodes + rotation *rotation.Manager + cfg config.Config + logger *slog.Logger + transports *proxyTransports + zenNodes *upstreamNodes + goNodes *upstreamNodes + anonymous *anonymousNodes + // warp, when non-nil, is the shared userspace WARP pool. Free-model + // traffic on the anonymous lane and the Zen key tier leaves through it + // instead of the configured proxies and transports. + warp *warp.Pool catalog *models.ModelCatalog monitor *telemetry.Metrics availability *models.AvailabilityRegistry @@ -94,7 +99,7 @@ type Gateway struct { // bound to those transports, the anonymous node pool and a model catalog. Its // rotation manager is not persisted; RuntimeController replaces it with the // shared one. -func New(cfg config.Config, logger *slog.Logger, monitor *telemetry.Metrics) (*Gateway, error) { +func New(cfg config.Config, logger *slog.Logger, monitor *telemetry.Metrics, warpPool *warp.Pool) (*Gateway, error) { cfg.Rotation.Defaults() rotationManager, err := rotation.New("", cfg.Rotation) if err != nil { @@ -124,6 +129,7 @@ func New(cfg config.Config, logger *slog.Logger, monitor *telemetry.Metrics) (*G zenNodes: zenNodes, goNodes: goNodes, anonymous: anonymousPool(cfg.Anonymous, transports, cooldown, anonymousBackoffFromConfig(cfg.Models.AnonymousBackoff)), + warp: warpPool, catalog: catalog, monitor: monitor, attemptTimeout: attemptDeadline(cfg), @@ -337,6 +343,10 @@ func (g *Gateway) handleInference(external wire.Protocol) http.HandlerFunc { wire.WriteError(w, external, http.StatusServiceUnavailable, proxyUnavailableMessage, "proxy_error", ids.Request) return } + if errors.Is(err, errWARPUnavailable) { + wire.WriteError(w, external, http.StatusServiceUnavailable, warpUnavailableMessage, "warp_unavailable", ids.Request) + return + } // An exhausted request budget is a timeout, not a bad gateway: the // distinction matters to clients that retry on 502. if errors.Is(err, context.DeadlineExceeded) { @@ -528,6 +538,10 @@ func (g *Gateway) forwardSystemOne(w http.ResponseWriter, r *http.Request, body wire.WriteError(w, wire.SystemOne, http.StatusServiceUnavailable, proxyUnavailableMessage, "proxy_error", ids.Request) return } + if errors.Is(err, errWARPUnavailable) { + wire.WriteError(w, wire.SystemOne, http.StatusServiceUnavailable, warpUnavailableMessage, "warp_unavailable", ids.Request) + return + } if errors.Is(err, context.DeadlineExceeded) { wire.WriteError(w, wire.SystemOne, http.StatusGatewayTimeout, "upstream request timed out", "upstream_timeout", ids.Request) return diff --git a/internal/gateway/health.go b/internal/gateway/health.go index 697b345..b9d40dd 100644 --- a/internal/gateway/health.go +++ b/internal/gateway/health.go @@ -19,6 +19,7 @@ type healthResponse struct { Models healthModels `json:"models"` Keys healthKeys `json:"keys"` Proxies healthProxies `json:"proxies"` + Warp *healthWarp `json:"warp,omitempty"` Issues []string `json:"issues,omitempty"` } @@ -47,15 +48,45 @@ type healthProxies struct { Unhealthy int `json:"unhealthy"` } +// healthWarp reports the state of the userspace WARP pool. It is omitted when +// the switch is off so existing readiness consumers see the same document. +type healthWarp struct { + Status string `json:"status"` + Stack string `json:"stack"` + Size int `json:"size"` + Active int `json:"active"` + Standby int `json:"standby"` + Cooling int `json:"cooling"` +} + // handleHealth reports readiness. It answers 503 while the model catalog is -// pending or empty or no proxy is healthy, and 200 otherwise. Any issue, -// including a stale catalog or no upstream credentials, marks the status -// degraded, except that a pending catalog reports starting. +// pending or empty, while WARP is enabled but no exit is active, or while no +// proxy is healthy when free traffic cannot leave through WARP (WARP off, or Go +// keys configured). Any issue, including a stale catalog or no upstream +// credentials, marks the status degraded, except that a pending catalog reports +// starting. func (g *Gateway) handleHealth(w http.ResponseWriter, _ *http.Request) { _, models := g.availableModels() proxyTotal, proxyHealthy := g.transports.healthCounts() zenKeys, goKeys := g.zenNodes.Len(), g.goNodes.Len() staleAfter := max(2*time.Duration(g.cfg.Models.RefreshSeconds)*time.Second, time.Minute) + var warpStatus *healthWarp + warpActive := 0 + if g.warp != nil { + snapshot := g.warp.Snapshot() + warpActive = snapshot.Active + warpStatus = &healthWarp{ + Status: "unavailable", + Stack: snapshot.Stack, + Size: snapshot.Size, + Active: snapshot.Active, + Standby: snapshot.Standby, + Cooling: snapshot.Cooling, + } + if snapshot.Active > 0 { + warpStatus.Status = "ready" + } + } modelStatus := "ready" var lastRefresh *time.Time @@ -77,6 +108,13 @@ func (g *Gateway) handleHealth(w http.ResponseWriter, _ *http.Request) { if zenKeys+goKeys == 0 && !g.cfg.Anonymous { issues = append(issues, "no_upstream_keys") } + warpBlocking := g.warp != nil && warpActive == 0 + if warpBlocking { + issues = append(issues, "warp_unavailable") + } + // Proxies carry Go-tier traffic whenever Go keys exist, and every lane + // while WARP is off; free-model traffic alone does not need them. + proxyBlocking := proxyHealthy == 0 && (g.warp == nil || goKeys > 0) if proxyHealthy == 0 { issues = append(issues, "no_healthy_proxies") } @@ -85,7 +123,7 @@ func (g *Gateway) handleHealth(w http.ResponseWriter, _ *http.Request) { if len(issues) > 0 { status = "degraded" } - blocking := modelStatus == "pending" || modelStatus == "empty" || proxyHealthy == 0 + blocking := modelStatus == "pending" || modelStatus == "empty" || warpBlocking || proxyBlocking httpStatus := http.StatusOK ready := !blocking if blocking { @@ -115,6 +153,7 @@ func (g *Gateway) handleHealth(w http.ResponseWriter, _ *http.Request) { Healthy: proxyHealthy, Unhealthy: proxyTotal - proxyHealthy, }, + Warp: warpStatus, Issues: issues, }) } diff --git a/internal/gateway/probe.go b/internal/gateway/probe.go index a668876..9d0a1e7 100644 --- a/internal/gateway/probe.go +++ b/internal/gateway/probe.go @@ -3,6 +3,7 @@ package gateway import ( "context" "encoding/json" + "errors" "fmt" "io" "net/http" @@ -100,18 +101,28 @@ func (g *Gateway) probeFreeModel(ctx context.Context, model string) probeResult type lane struct { key, name, baseURL string client *http.Client + warp bool } var lanes []lane anonymousPaused := false if g.cfg.Anonymous { if g.anonymous.AllowAttempt() { defer g.anonymous.ReleaseProbe() - cursor := g.anonymous.CursorFor(ids.Session) - if node := cursor.Next(); node != nil { - // Try the anonymous upstreams in preference order: the v2 - // /inference origin before the v1 fallback. + if g.warp != nil { + // WARP replaces the anonymous proxy: try the anonymous + // upstreams in preference order without consulting the proxy + // cursor or a proxy binding. for _, baseURL := range g.anonymousUpstreams() { - lanes = append(lanes, lane{anonymousZenKey, "anonymous", baseURL, g.inferenceClient(node.proxy, baseURL, model)}) + lanes = append(lanes, lane{key: anonymousZenKey, name: "anonymous", baseURL: baseURL, warp: true}) + } + } else { + cursor := g.anonymous.CursorFor(ids.Session) + if node := cursor.Next(); node != nil { + // Try the anonymous upstreams in preference order: the v2 + // /inference origin before the v1 fallback. + for _, baseURL := range g.anonymousUpstreams() { + lanes = append(lanes, lane{key: anonymousZenKey, name: "anonymous", baseURL: baseURL, client: g.inferenceClient(node.proxy, baseURL, model)}) + } } } } else { @@ -123,8 +134,10 @@ func (g *Gateway) probeFreeModel(ctx context.Context, model string) probeResult } cursor := g.zenNodes.CursorFor(ids.Session) if node := cursor.Next(); node != nil { - if proxy := g.zenNodes.Proxy(node); proxy != nil { - lanes = append(lanes, lane{node.key, "zen", g.cfg.Upstream.Zen, g.inferenceClient(proxy, g.cfg.Upstream.Zen, model)}) + if g.usesWARP(model, config.TierZen, false) { + lanes = append(lanes, lane{key: node.key, name: "zen", baseURL: g.cfg.Upstream.Zen, warp: true}) + } else if proxy := g.zenNodes.Proxy(node); proxy != nil { + lanes = append(lanes, lane{key: node.key, name: "zen", baseURL: g.cfg.Upstream.Zen, client: g.inferenceClient(proxy, g.cfg.Upstream.Zen, model)}) } } result := probeResult{reason: "no_probe_channel"} @@ -137,7 +150,7 @@ func (g *Gateway) probeFreeModel(ctx context.Context, model string) probeResult return probeResult{reason: "canceled"} } run := func(effort string) probeResult { - return g.probeAttempt(ctx, lane.client, lane.baseURL, lane.key, model, protocol, ids, effort) + return g.probeAttempt(ctx, lane.client, lane.baseURL, lane.key, model, protocol, ids, effort, lane.warp) } result = run("") result.channel = lane.name @@ -188,12 +201,14 @@ func (g *Gateway) probeFreeModel(ctx context.Context, model string) probeResult // probeAttempt sends one probe request through client with a 60-second budget // and classifies the result. Unlike live traffic it bypasses -// doInferenceAttempt and records nothing against keys or proxies. Success -// requires a 2xx whose SSE stream collapses cleanly or whose JSON document has -// the protocol's result field; a failure carries a reason code (http_, -// model_unavailable, probe_timeout, ...) and whether the upstream rejected the -// reasoning effort. -func (g *Gateway) probeAttempt(parent context.Context, client *http.Client, baseURL, key, model string, protocol wire.Protocol, ids identity.RequestIDs, effort string) probeResult { +// doInferenceAttempt and records nothing against keys or proxies. When overWARP +// is set the probe leaves through an acquired WARP exit instead of client, and +// the pool sees the outcome (Report on a response, Fail on a transport error). +// Success requires a 2xx whose SSE stream collapses cleanly or whose JSON +// document has the protocol's result field; a failure carries a reason code +// (http_, model_unavailable, probe_timeout, warp_unavailable, ...) and +// whether the upstream rejected the reasoning effort. +func (g *Gateway) probeAttempt(parent context.Context, client *http.Client, baseURL, key, model string, protocol wire.Protocol, ids identity.RequestIDs, effort string, overWARP bool) probeResult { b, err := probePayload(model, protocol, effort, models.IsV1Upstream(baseURL)) if err != nil { return probeResult{reason: "request_conversion_error"} @@ -206,9 +221,22 @@ func (g *Gateway) probeAttempt(parent context.Context, client *http.Client, base return probeResult{reason: "request_creation_error"} } result := probeResult{attempted: true} - resp, err := client.Do(req) + var resp *http.Response + if overWARP { + // The probe context already bounds the attempt; no first-event or + // attempt deadline applies on top of it. + resp, _, err = g.doWARPAttempt(ctx, req, baseURL, model, 0) + } else { + resp, err = client.Do(req) + } if err != nil { result.reason = "transport_error" + if overWARP && errors.Is(err, errWARPUnavailable) { + // No exit could be acquired, so no request reached the upstream. + result.attempted = false + result.reason = "warp_unavailable" + return result + } if ctx.Err() != nil { result.reason = "probe_timeout" } diff --git a/internal/gateway/refresh.go b/internal/gateway/refresh.go index 969bb38..0176057 100644 --- a/internal/gateway/refresh.go +++ b/internal/gateway/refresh.go @@ -259,6 +259,9 @@ func (g *Gateway) refreshAnonymousTier(ctx context.Context, base string) []strin return nil } defer g.anonymous.ReleaseProbe() + if g.warp != nil { + return g.refreshAnonymousWARP(ctx, base) + } cursor := g.anonymous.CursorFor("") limit := min(g.anonymous.Len(), g.maxAnonymousExits()) if g.anonymous.HasPool() && g.cfg.Retry.MaxAttempts > limit { @@ -295,6 +298,53 @@ func (g *Gateway) refreshAnonymousTier(ctx context.Context, base string) []strin return nil } +// refreshAnonymousWARP lists models through WARP instead of an anonymous +// proxy. The catalog is what makes free models discoverable at all, so with +// the WARP switch on it must not depend on a working proxy pool. One lease per +// attempt; the pool learns about a blocked exit through Report. +func (g *Gateway) refreshAnonymousWARP(ctx context.Context, base string) []string { + limit := max(g.cfg.Retry.MaxAttempts, 1) + for attempt := 1; attempt <= limit; attempt++ { + refreshCtx, cancel := context.WithTimeout(ctx, 30*time.Second) + lease, err := g.warp.Acquire(refreshCtx) + if err != nil { + cancel() + if ctx.Err() != nil { + return nil + } + continue + } + owned, err := g.newWarpLease(lease, false) + if err != nil { + lease.Release() + cancel() + g.logger.Warn("anonymous model catalog refresh could not use WARP", "component", "models", "event", "anonymous_refresh_failed", "upstream", config.RedactURL(base), "error", err) + return nil + } + egress := "warp:" + lease.EgressKey() + var listed []string + var status int + for _, upstream := range g.anonymousUpstreams() { + listed, status, err = modelcatalog.FetchModels(refreshCtx, owned.regular, upstream, anonymousZenKey) + if err == nil || isProxyFailure(err) { + break + } + } + if status > 0 { + g.warp.Report(lease, status, nil) + } + owned.close() + cancel() + if err == nil { + g.anonymous.NoteSuccess() + return listed + } + g.logger.Debug("anonymous model catalog refresh attempt failed", "component", "models", "event", "anonymous_refresh_attempt_failed", "upstream", config.RedactURL(base), "attempt", attempt, "proxy", egress, "error", err) + } + g.logger.Warn("anonymous model catalog refresh failed", "component", "models", "event", "anonymous_refresh_failed", "upstream", config.RedactURL(base)) + return nil +} + // refreshTier lists the models at base with up to retry.max_attempts keys // from nodes, updating proxy health and key cooldowns after every attempt. It // returns nil when the pool has no keys or every attempt fails. diff --git a/internal/gateway/runtime.go b/internal/gateway/runtime.go index 5053252..0b9ee17 100644 --- a/internal/gateway/runtime.go +++ b/internal/gateway/runtime.go @@ -15,6 +15,7 @@ import ( "opencode2api/internal/protocol" "opencode2api/internal/rotation" "opencode2api/internal/telemetry" + "opencode2api/internal/warp" ) // gatewayRuntime is one applied configuration: the Gateway built from it, that @@ -26,6 +27,13 @@ type gatewayRuntime struct { gateway *Gateway handler http.Handler cancel context.CancelFunc + // warpPool is the userspace WARP pool this runtime uses, if any. warpKey + // identifies its size and stack; an unchanged key is reused across + // configuration reloads. warpCreated marks a pool this build owns and + // must close if the build is discarded. + warpPool *warp.Pool + warpKey string + warpCreated bool } // ApplyResult reports whether a configuration was applied and which listener @@ -55,6 +63,10 @@ type RuntimeController struct { effective EffectiveListeners metadata *modelcatalog.PricingRegistry availabilityCancel context.CancelFunc + // warpPool is the pool shared by successive runtimes when the WARP size + // and stack are unchanged. warpKey is the identity used for that reuse. + warpPool *warp.Pool + warpKey string } // EffectiveListeners are the listener settings the running process actually @@ -123,10 +135,14 @@ func RuntimeManager(root context.Context, configPath string, cfg config.Config, } } if err := cfg.Rotation.Validate(runtime.gateway.catalog.List()); err != nil { + if runtime.warpCreated && runtime.warpPool != nil { + runtime.warpPool.Close() + } return nil, err } runtime.gateway.syncRotation() manager.current.Store(runtime) + manager.warpPool, manager.warpKey = runtime.warpPool, runtime.warpKey manager.redactor.Replace(cfg) telemetry.SetLogLevel(manager.level, cfg.Logging.Level) manager.start(runtime) @@ -161,20 +177,32 @@ func migrateAvailabilityPath(legacyPath, currentPath string) error { // current runtime's availability registry while the Zen upstream is // unchanged; otherwise it uses the registry persisted for the new upstream. func (m *RuntimeController) build(cfg config.Config) (*gatewayRuntime, error) { - gateway, err := New(cfg, m.logger, m.monitor) + warpPool, warpKey, warpCreated, err := m.selectWARP(cfg) if err != nil { return nil, err } + discardWARP := func() { + if warpCreated && warpPool != nil { + warpPool.Close() + } + } + gateway, err := New(cfg, m.logger, m.monitor, warpPool) + if err != nil { + discardWARP() + return nil, err + } gateway.rotation = m.rotation availabilityPath := "" if m.configPath != "" { availabilityPath = m.configPath + "." + config.Fingerprint(cfg.Upstream.Zen) + ".availability.json" if err := migrateAvailabilityPath(m.configPath+"."+config.Fingerprint(cfg.Upstream.Zen)[:10]+".availability.json", availabilityPath); err != nil { + discardWARP() return nil, fmt.Errorf("migrate model availability: %w", err) } } availability, err := modelcatalog.AvailabilityStore(availabilityPath) if err != nil { + discardWARP() return nil, fmt.Errorf("load model availability: %w", err) } if current := m.current.Load(); current != nil && current.config.Upstream.Zen == cfg.Upstream.Zen { @@ -184,7 +212,32 @@ func (m *RuntimeController) build(cfg config.Config) (*gatewayRuntime, error) { gateway.catalog.SetAvailabilityStore(availability) gateway.availability = availability gateway.catalog.SetCachePath(modelcatalog.CatalogCachePath(m.configPath)) - return &gatewayRuntime{config: cfg, gateway: gateway, availability: availability, handler: gateway.Handler(), cancel: func() {}}, nil + return &gatewayRuntime{config: cfg, gateway: gateway, availability: availability, handler: gateway.Handler(), cancel: func() {}, warpPool: warpPool, warpKey: warpKey, warpCreated: warpCreated}, nil +} + +// selectWARP returns the WARP pool a runtime built for cfg must use. A pool +// with the same size and stack is shared across runtimes; creating a new one +// registers its first exit synchronously, so enabling WARP fails closed when +// Cloudflare cannot be reached. A disabled configuration returns no pool. +func (m *RuntimeController) selectWARP(cfg config.Config) (*warp.Pool, string, bool, error) { + if !cfg.Warp.Enabled { + return nil, "", false, nil + } + key := fmt.Sprintf("%d|%s", cfg.Warp.PoolSize, cfg.Warp.Stack) + if m.warpPool != nil && m.warpKey == key { + return m.warpPool, key, false, nil + } + timeout := time.Duration(cfg.Retry.TimeoutSeconds) * time.Second + if timeout <= 0 || timeout > 2*time.Minute { + timeout = 2 * time.Minute + } + ctx, cancel := context.WithTimeout(m.root, timeout) + defer cancel() + pool, err := warp.NewWithStack(ctx, m.logger, cfg.Warp.PoolSize, warp.Stack(cfg.Warp.Stack)) + if err != nil { + return nil, "", false, fmt.Errorf("initialize WARP egress: %w", err) + } + return pool, key, true, nil } // start launches runtime's proxy health checks and model refresh, and stores @@ -298,11 +351,17 @@ func (m *RuntimeController) applyLocked(candidate config.Config, persist bool) ( next.gateway.catalog.CopyState(current.gateway.catalog) } if err := normalized.Rotation.Validate(next.gateway.catalog.List()); err != nil { + if next.warpCreated && next.warpPool != nil { + next.warpPool.Close() + } return ApplyResult{}, err } if persist || hadPlaintextPassword { if err := config.SaveAtomic(m.configPath, normalized); err != nil { next.cancel() + if next.warpCreated && next.warpPool != nil { + next.warpPool.Close() + } return ApplyResult{}, err } } @@ -327,8 +386,20 @@ func (m *RuntimeController) applyLocked(candidate config.Config, persist bool) ( next.gateway.syncRotation() m.start(next) previous := m.current.Swap(next) + m.warpPool, m.warpKey = next.warpPool, next.warpKey if previous != nil { previous.cancel() + if previous.warpPool != nil && previous.warpPool != next.warpPool { + // Requests that loaded the previous runtime may still acquire a + // lease. Close the old pool only after the longest request budget + // has passed; leases already held keep their exits alive. + grace := time.Duration(normalized.Retry.TimeoutSeconds) * time.Second + if grace <= 0 || grace > 5*time.Minute { + grace = 5 * time.Minute + } + retired := previous.warpPool + time.AfterFunc(grace, retired.Close) + } } m.logger.Info("configuration applied", "component", "config", "event", "config_applied", "restart_required", result.RestartRequired, "restart_fields", result.RestartFields) return result, nil @@ -359,6 +430,11 @@ func (m *RuntimeController) Shutdown() { if current := m.current.Load(); current != nil { current.cancel() } + if m.warpPool != nil { + m.warpPool.Close() + m.warpPool = nil + m.warpKey = "" + } } // ResourceSnapshot is the operator view of the current runtime's models, keys, @@ -368,9 +444,21 @@ type ResourceSnapshot struct { Keys []KeyStatus `json:"keys"` Proxies []ProxyStatus `json:"proxies"` Anonymous bool `json:"anonymous"` + Warp *WarpStatus `json:"warp,omitempty"` Metadata modelcatalog.MetadataSnapshot `json:"metadata"` } +// WarpStatus is the operator view of the WARP egress pool. +type WarpStatus struct { + Enabled bool `json:"enabled"` + Stack string `json:"stack"` + Size int `json:"size"` + Active int `json:"active"` + Standby int `json:"standby"` + Cooling int `json:"cooling"` + Egress []string `json:"egress,omitempty"` +} + // KeyStatus describes one upstream key by its display ID (its last five // characters): its tier, its current proxy binding, its consecutive failures // and any active cooldown. @@ -427,6 +515,14 @@ func (m *RuntimeController) Resources() ResourceSnapshot { } result.Proxies = append(result.Proxies, status) } + if gateway.warp != nil { + snapshot := gateway.warp.Snapshot() + result.Warp = &WarpStatus{ + Enabled: true, Stack: snapshot.Stack, Size: snapshot.Size, + Active: snapshot.Active, Standby: snapshot.Standby, Cooling: snapshot.Cooling, + Egress: snapshot.Egress, + } + } return result } diff --git a/internal/gateway/upstream.go b/internal/gateway/upstream.go index 29451fb..2ad5ba8 100644 --- a/internal/gateway/upstream.go +++ b/internal/gateway/upstream.go @@ -358,6 +358,9 @@ func (g *Gateway) maxAnonymousExits() int { // control to the preferred authenticated tiers. It returns the last response // (body still open), else the last error, plus the number of attempts made. func (g *Gateway) doAnonymousUpstream(ctx context.Context, route models.Route, bodies map[config.Tier][]byte, ids identity.RequestIDs, attemptOffset int) (*http.Response, error, int) { + if g.usesWARP(route.ID, config.TierZen, true) { + return g.doWarpAnonymousUpstream(ctx, route, bodies, ids, attemptOffset) + } // The breaker holds the lane shut for an hour-scale window after repeated // failures: poking a flagged upstream again would only extend the block. if !g.anonymous.AllowAttempt() { @@ -1200,28 +1203,48 @@ func (g *Gateway) doSelectedKeyUpstream(ctx context.Context, route models.Route, body = shaped } setRequestShape(ctx, changed, alias) + useWARP := g.usesWARP(route.ID, override.Tier, false) proxy := nodes.Proxy(node) - if proxy == nil { - return nil, errors.New("selected upstream key has no proxy binding"), 0 + if !useWARP { + if proxy == nil { + return nil, errors.New("selected upstream key has no proxy binding"), 0 + } } if meta := telemetry.MetaFromContext(ctx); meta != nil { meta.Attempts = attemptOffset + 1 meta.Tier = string(override.Tier) } keyID := config.KeyDisplayID(node.key) - setRequestCredential(ctx, override.Tier, keyID, "key", false, proxy) + if useWARP { + setRequestCredential(ctx, override.Tier, keyID, "key", false, nil) + } else { + setRequestCredential(ctx, override.Tier, keyID, "key", false, proxy) + } req, err := upstreamRequest(ctx, baseURL, route.ProtocolFor(override.Tier), body, ids, node.key) if err != nil { return nil, err, 0 } - if proxy.pool { + if !useWARP && proxy.pool { req.Close = true } started := time.Now() - resp, err := doInferenceAttempt(g.inferenceClient(proxy, baseURL, route.ID), req, time.Duration(g.cfg.Performance.FirstEventTimeoutSeconds)*time.Second, g.attemptTimeout) + var resp *http.Response + var egress string + if useWARP { + resp, egress, err = g.doWARPAttempt(ctx, req, baseURL, route.ID, time.Duration(g.cfg.Performance.FirstEventTimeoutSeconds)*time.Second) + } else { + resp, err = doInferenceAttempt(g.inferenceClient(proxy, baseURL, route.ID), req, time.Duration(g.cfg.Performance.FirstEventTimeoutSeconds)*time.Second, g.attemptTimeout) + } duration := time.Since(started) - g.recordUpstreamAttempt(ctx, route, ids, attemptOffset+1, keyID, "key", false, proxy, resp, err, duration) + recordProxy := proxy + if useWARP { + recordProxy = warpProxy(egress) + } + g.recordUpstreamAttempt(ctx, route, ids, attemptOffset+1, keyID, "key", false, recordProxy, resp, err, duration) if err != nil { + if useWARP { + return nil, err, 1 + } return nil, asProxyUnavailable(proxy, err), 1 } return resp, nil, 1 @@ -1261,6 +1284,7 @@ func (g *Gateway) doKeyUpstream(ctx context.Context, route models.Route, bodies body = shaped } setRequestShape(ctx, changed, alias) + useWARP := g.usesWARP(route.ID, route.Tier, false) for attempts < g.cfg.Retry.MaxAttempts { if ctx.Err() != nil { // Same guard as the anonymous loop: an exhausted request budget @@ -1290,17 +1314,29 @@ func (g *Gateway) doKeyUpstream(ctx context.Context, route models.Route, bodies return nil, err, attempts } proxy := nodes.Proxy(node) - if proxy == nil { - lastErr = errors.New("upstream key has no proxy binding") - break - } - if proxy.pool { - req.Close = true + if !useWARP { + if proxy == nil { + lastErr = errors.New("upstream key has no proxy binding") + break + } + if proxy.pool { + req.Close = true + } } keyID := config.KeyDisplayID(node.key) - setRequestCredential(ctx, route.Tier, keyID, "key", false, proxy) + if useWARP { + setRequestCredential(ctx, route.Tier, keyID, "key", false, nil) + } else { + setRequestCredential(ctx, route.Tier, keyID, "key", false, proxy) + } attemptStarted := time.Now() - resp, err := doInferenceAttempt(g.inferenceClient(proxy, baseURL, route.ID), req, time.Duration(g.cfg.Performance.FirstEventTimeoutSeconds)*time.Second, g.attemptTimeout) + var resp *http.Response + var egress string + if useWARP { + resp, egress, err = g.doWARPAttempt(ctx, req, baseURL, route.ID, time.Duration(g.cfg.Performance.FirstEventTimeoutSeconds)*time.Second) + } else { + resp, err = doInferenceAttempt(g.inferenceClient(proxy, baseURL, route.ID), req, time.Duration(g.cfg.Performance.FirstEventTimeoutSeconds)*time.Second, g.attemptTimeout) + } attemptDuration := time.Since(attemptStarted) if ctx.Err() != nil { // The request budget expired while this attempt was in flight. A @@ -1313,10 +1349,19 @@ func (g *Gateway) doKeyUpstream(ctx context.Context, route models.Route, bodies } break } - g.observeKeyResult(ctx, nodes, node, proxy, resp, err) - g.recordUpstreamAttempt(ctx, route, ids, attemptOffset+attempts, keyID, "key", false, proxy, resp, err, attemptDuration) + recordProxy := proxy + proxyLabel := "" + if useWARP { + recordProxy = warpProxy(egress) + proxyLabel = egress + g.observeKeyResultWARP(ctx, nodes, node, resp, err) + } else { + proxyLabel = config.RedactURL(proxy.name) + g.observeKeyResult(ctx, nodes, node, proxy, resp, err) + } + g.recordUpstreamAttempt(ctx, route, ids, attemptOffset+attempts, keyID, "key", false, recordProxy, resp, err, attemptDuration) if err == nil && resp.StatusCode/100 == 2 { - g.logger.Debug("upstream accepted request", "component", "upstream", "event", "attempt_succeeded", "request_id", ids.Request, "attempt", attempts, "tier", route.Tier, "key_id", keyID, "proxy", config.RedactURL(proxy.name), "status", resp.StatusCode, "duration_ms", attemptDuration.Milliseconds()) + g.logger.Debug("upstream accepted request", "component", "upstream", "event", "attempt_succeeded", "request_id", ids.Request, "attempt", attempts, "tier", route.Tier, "key_id", keyID, "proxy", proxyLabel, "status", resp.StatusCode, "duration_ms", attemptDuration.Milliseconds()) return resp, nil, attempts } // Request-shape errors are deterministic and must leave this tier without @@ -1324,15 +1369,24 @@ func (g *Gateway) doKeyUpstream(ctx context.Context, route models.Route, bodies // tier in prefer order. Authentication, throttling, server, and transport // failures remain retryable inside this tier. if isNonRetryableClientResponse(resp, err) { - g.logger.Debug("upstream rejected a non-retryable request", "component", "upstream", "event", "attempt_rejected", "request_id", ids.Request, "attempt", attempts, "tier", route.Tier, "key_id", keyID, "status", resp.StatusCode, "proxy", config.RedactURL(proxy.name), "duration_ms", attemptDuration.Milliseconds()) + g.logger.Debug("upstream rejected a non-retryable request", "component", "upstream", "event", "attempt_rejected", "request_id", ids.Request, "attempt", attempts, "tier", route.Tier, "key_id", keyID, "status", resp.StatusCode, "proxy", proxyLabel, "duration_ms", attemptDuration.Milliseconds()) return resp, nil, attempts } lastResponse = resp - lastErr = asProxyUnavailable(proxy, err) - if err != nil { - g.logger.Debug("upstream transport attempt failed", "component", "upstream", "event", "attempt_transport_failed", "request_id", ids.Request, "attempt", attempts, "tier", route.Tier, "key_id", keyID, "proxy", config.RedactURL(proxy.name), "duration_ms", attemptDuration.Milliseconds(), "error", err) + if useWARP && errors.Is(err, errWARPUnavailable) { + // No exit at all: another key would only wait on the same pool. + lastErr = err + break + } + if useWARP { + lastErr = err } else { - g.logger.Debug("upstream returned a retryable response", "component", "upstream", "event", "attempt_retryable_response", "request_id", ids.Request, "attempt", attempts, "tier", route.Tier, "key_id", keyID, "status", resp.StatusCode, "proxy", config.RedactURL(proxy.name), "duration_ms", attemptDuration.Milliseconds()) + lastErr = asProxyUnavailable(proxy, err) + } + if err != nil { + g.logger.Debug("upstream transport attempt failed", "component", "upstream", "event", "attempt_transport_failed", "request_id", ids.Request, "attempt", attempts, "tier", route.Tier, "key_id", keyID, "proxy", proxyLabel, "duration_ms", attemptDuration.Milliseconds(), "error", err) + } else { + g.logger.Debug("upstream returned a retryable response", "component", "upstream", "event", "attempt_retryable_response", "request_id", ids.Request, "attempt", attempts, "tier", route.Tier, "key_id", keyID, "status", resp.StatusCode, "proxy", proxyLabel, "duration_ms", attemptDuration.Milliseconds()) } } if lastResponse != nil { diff --git a/internal/gateway/warp.go b/internal/gateway/warp.go new file mode 100644 index 0000000..5d98d89 --- /dev/null +++ b/internal/gateway/warp.go @@ -0,0 +1,347 @@ +package gateway + +import ( + "context" + "errors" + "fmt" + "io" + "net" + "net/http" + "strings" + "sync" + "time" + + "opencode2api/internal/config" + "opencode2api/internal/httpx" + "opencode2api/internal/identity" + "opencode2api/internal/models" + "opencode2api/internal/telemetry" + "opencode2api/internal/warp" +) + +// errWARPUnavailable marks a free-lane attempt that could not acquire a WARP +// exit at all. The client gets a 503 that points at the egress switch instead +// of a generic upstream failure. +var errWARPUnavailable = errors.New("WARP egress is unavailable") + +// warpUnavailableMessage is what a client receives when the free lane is +// configured to leave through WARP but no exit could be acquired. It is a 503 +// because the request never reached the upstream. +const warpUnavailableMessage = "no WARP exit could carry this free-model request; the upstream was not contacted. Check the WARP switch and this host's UDP access to the Cloudflare endpoint." + +// usesWARP reports whether this request's egress must bypass proxies. Only +// free models on the anonymous lane and the Zen key tier qualify; the Go plan +// and paid models keep their proxy bindings. +func (g *Gateway) usesWARP(model string, tier config.Tier, anonymous bool) bool { + return g.warp != nil && g.catalog.IsFreeModel(model) && (anonymous || tier == config.TierZen) +} + +// warpUsesBun mirrors inferenceClient for traffic that leaves through WARP: +// free-model traffic to the v1 /zen lane or the v2 /inference origin must look +// like the official Bun runtime. The other lanes use the regular client. +func (g *Gateway) warpUsesBun(baseURL, model string) bool { + lane := strings.ToLower(strings.TrimRight(strings.TrimSpace(baseURL), "/")) + return g.catalog.IsFreeModel(model) && (models.IsV1Upstream(baseURL) || strings.HasSuffix(lane, "/inference")) +} + +// warpLease is one acquired WARP exit together with the HTTP clients that dial +// through it. Every client is per-attempt: the exit is released as soon as the +// response body is closed, so pooled connections must be closed at the same +// time. +type warpLease struct { + lease *warp.Lease + pool *warp.Pool + regular *http.Client + bun *http.Client + useBun bool + once sync.Once +} + +func (g *Gateway) newWarpLease(lease *warp.Lease, useBun bool) (*warpLease, error) { + perf := g.cfg.Performance + dial := func(ctx context.Context, _, address string) (net.Conn, error) { + return lease.DialContext(ctx, lease.DialNetwork(), address) + } + transport := http.DefaultTransport.(*http.Transport).Clone() + transport.Proxy = nil + transport.DialContext = dial + transport.ForceAttemptHTTP2 = false + transport.MaxIdleConns = perf.MaxIdleConns + transport.MaxIdleConnsPerHost = perf.MaxIdleConnsPerHost + transport.MaxConnsPerHost = perf.MaxConnsPerHost + transport.IdleConnTimeout = time.Duration(perf.IdleConnTimeoutSeconds) * time.Second + transport.ResponseHeaderTimeout = g.attemptTimeout + bun, err := httpx.NewBunTransport(httpx.BunOptions{ + DialContext: dial, + ConnectTimeout: time.Duration(perf.ConnectTimeoutSeconds) * time.Second, + ResponseHeaderTimeout: g.attemptTimeout, + IdleConnTimeout: transport.IdleConnTimeout, + MaxIdleConnsPerHost: perf.MaxIdleConnsPerHost, + }) + if err != nil { + return nil, err + } + return &warpLease{ + lease: lease, + pool: g.warp, + regular: &http.Client{Transport: transport}, + bun: &http.Client{Transport: bun}, + useBun: useBun, + }, nil +} + +func (l *warpLease) client() *http.Client { + if l.useBun { + return l.bun + } + return l.regular +} + +func (l *warpLease) close() { + if l == nil { + return + } + l.once.Do(func() { + l.bun.CloseIdleConnections() + l.regular.CloseIdleConnections() + l.lease.Release() + }) +} + +// warpBody ties the lease to the response body. Closing the body (or the +// gateway's drain helpers) releases the exit, and an upstream stream that dies +// mid-body retires the exit that carried it. +type warpBody struct { + io.ReadCloser + lease *warpLease + diagnostic bool +} + +func (b *warpBody) Read(data []byte) (int, error) { + n, err := b.ReadCloser.Read(data) + if err != nil && err != io.EOF && !b.diagnostic && !errors.Is(err, context.Canceled) { + b.lease.pool.Fail(b.lease.lease, "stream read error") + } + return n, err +} + +func (b *warpBody) Close() error { + err := b.ReadCloser.Close() + b.lease.close() + return err +} + +// warpFailReason names the condition that should retire an exit. A stalled +// first token is treated as a tunnel failure: retrying the same userspace +// tunnel would only repeat the stall. +func warpFailReason(err error) string { + switch { + case errors.Is(err, errFirstEventTimeout): + return "first event timeout" + case errors.Is(err, errAttemptTimeout): + return "attempt timeout" + default: + return "transport error" + } +} + +// doWARPAttempt sends one prepared request through an acquired WARP exit, +// feeds the outcome back into the pool, and returns the response with a body +// that releases the exit when closed. The egress label is returned for +// telemetry ("warp:"). +func (g *Gateway) doWARPAttempt(ctx context.Context, req *http.Request, baseURL, model string, firstEventTimeout time.Duration) (*http.Response, string, error) { + lease, err := g.warp.Acquire(ctx) + if err != nil { + if ctx.Err() != nil { + return nil, "", ctx.Err() + } + return nil, "", fmt.Errorf("%w: %v", errWARPUnavailable, err) + } + owned, err := g.newWarpLease(lease, g.warpUsesBun(baseURL, model)) + if err != nil { + lease.Release() + return nil, "", fmt.Errorf("%w: %v", errWARPUnavailable, err) + } + label := "warp:" + lease.EgressKey() + setWarpEgress(ctx, label) + diagnostic := isDiagnosticRequest(ctx) + resp, err := doInferenceAttempt(owned.client(), req, firstEventTimeout, g.attemptTimeout) + if err != nil { + if ctx.Err() == nil && !diagnostic { + g.warp.Fail(lease, warpFailReason(err)) + } + owned.close() + return nil, label, err + } + if !diagnostic { + var body []byte + if resp.StatusCode == http.StatusForbidden || resp.StatusCode == http.StatusTooManyRequests { + body = peekResponseBody(resp) + } + g.warp.Report(lease, resp.StatusCode, body) + } + resp.Body = &warpBody{ReadCloser: resp.Body, lease: owned, diagnostic: diagnostic} + return resp, label, nil +} + +// setWarpEgress records the exit that actually carries the attempt so request +// logs show the WARP address instead of the unused key proxy binding. +func setWarpEgress(ctx context.Context, label string) { + if meta := telemetry.MetaFromContext(ctx); meta != nil { + meta.Proxy = label + } +} + +// warpProxy is a name-only proxyTransport used by telemetry records for WARP +// attempts. The value is never used for dialing or health tracking. +func warpProxy(label string) *proxyTransport { + if label == "" { + return nil + } + return &proxyTransport{name: label} +} + +// doWarpAnonymousUpstream is the anonymous lane with WARP as its only egress. +// It walks the same two upstream gates (v2 /inference first, v1 /zen second) +// as doAnonymousUpstream, but draws a WARP lease per attempt instead of a +// proxy. The lane breaker still applies; per-proxy cooldowns and the block +// cursor do not, because a block is a property of the WARP exit and rotation +// replaces it. +func (g *Gateway) doWarpAnonymousUpstream(ctx context.Context, route models.Route, bodies map[config.Tier][]byte, ids identity.RequestIDs, attemptOffset int) (*http.Response, error, int) { + if !g.anonymous.AllowAttempt() { + return nil, errAnonymousLanePaused, 0 + } + defer g.anonymous.ReleaseProbe() + rawBody := bodies[config.TierZen] + if len(rawBody) == 0 { + return nil, errors.New("no prepared Zen request body"), 0 + } + protocol := route.ProtocolFor(config.TierZen) + upstreams := g.anonymousUpstreams() + prepared := make([][]byte, len(upstreams)) + aliases := make([]string, len(upstreams)) + for index, baseURL := range upstreams { + prepared[index], aliases[index] = prepareAnonymousBody(rawBody, protocol, models.IsV1Upstream(baseURL)) + } + limit := max(g.cfg.Retry.MaxAttempts, g.warp.Size()+1) + firstEventTimeout := time.Duration(g.cfg.Performance.FirstEventTimeoutSeconds) * time.Second + var lastResponse *http.Response + var lastErr error + blocked, halted := false, false + attempts := 0 + for attempts < limit { + if ctx.Err() != nil { + if lastErr == nil { + lastErr = ctx.Err() + } + break + } + leaseBlocked := false + for index, baseURL := range upstreams { + if ctx.Err() != nil { + break + } + setRequestShape(ctx, false, aliases[index]) + attempts++ + if meta := telemetry.MetaFromContext(ctx); meta != nil { + meta.Attempts = attemptOffset + attempts + meta.Tier = string(config.TierZen) + } + if lastResponse != nil { + httpx.DrainAndClose(lastResponse.Body) + lastResponse = nil + } + req, err := upstreamRequest(ctx, baseURL, protocol, prepared[index], ids, anonymousZenKey) + if err != nil { + return nil, err, attempts + } + setRequestCredential(ctx, config.TierZen, "anonymous", "anonymous", true, nil) + started := time.Now() + resp, egress, err := g.doWARPAttempt(ctx, req, baseURL, route.ID, firstEventTimeout) + duration := time.Since(started) + if ctx.Err() != nil { + lastResponse, lastErr = resp, err + if lastErr == nil && lastResponse == nil { + lastErr = ctx.Err() + } + break + } + status := upstreamStatus(resp) + g.recordUpstreamAttempt(ctx, route, ids, attemptOffset+attempts, "anonymous", "anonymous", true, warpProxy(egress), resp, err, duration) + if err == nil && status/100 == 2 { + g.anonymous.NoteSuccess() + g.logger.Debug("anonymous WARP upstream accepted request", "component", "upstream", "event", "anonymous_attempt_succeeded", "request_id", ids.Request, "attempt", attempts, "tier", config.TierZen, "upstream", config.RedactURL(baseURL), "key_id", "anonymous", "channel", "anonymous", "anonymous", true, "proxy", egress, "status", status, "duration_ms", duration.Milliseconds()) + return resp, nil, attempts + } + lastResponse, lastErr = resp, err + if err != nil { + g.logger.Debug("anonymous WARP transport attempt failed", "component", "upstream", "event", "anonymous_attempt_transport_failed", "request_id", ids.Request, "attempt", attempts, "tier", config.TierZen, "upstream", config.RedactURL(baseURL), "key_id", "anonymous", "channel", "anonymous", "anonymous", true, "proxy", egress, "duration_ms", duration.Milliseconds(), "error", err) + // A broken tunnel affects both upstream gates; rotate the exit + // instead of repeating the request on the same lease. + break + } + if peekNetworkAbuseBlock(resp) { + lastErr = errFreeTierIPBlocked + blocked, leaseBlocked = true, true + g.logger.Warn("free tier blocked the WARP exit; rotating it", "component", "upstream", "event", "free_tier_ip_blocked", "request_id", ids.Request, "attempt", attempts, "tier", config.TierZen, "upstream", config.RedactURL(baseURL), "proxy", egress) + break + } + if isDeterministicClientResponse(status, peekResponseBody(resp)) { + lastErr = errDeterministicClientRejection + halted = true + g.logger.Warn("upstream rejected the request; not trying other upstreams", "component", "upstream", "event", "deterministic_rejection", "request_id", ids.Request, "attempt", attempts, "tier", config.TierZen, "upstream", config.RedactURL(baseURL), "status", status, "duration_ms", duration.Milliseconds()) + break + } + g.logger.Debug("anonymous WARP upstream returned an error response; trying the next upstream or exit", "component", "upstream", "event", "anonymous_attempt_response_failed", "request_id", ids.Request, "attempt", attempts, "tier", config.TierZen, "upstream", config.RedactURL(baseURL), "key_id", "anonymous", "channel", "anonymous", "anonymous", true, "proxy", egress, "status", status, "duration_ms", duration.Milliseconds()) + if index+1 < len(upstreams) { + break + } + } + if halted || ctx.Err() != nil { + break + } + if !leaseBlocked { + if pause, tripped := g.anonymous.NoteFailure(); tripped { + g.logger.Warn("anonymous lane circuit breaker opened", "component", "upstream", "event", "anonymous_breaker_open", "status", upstreamStatus(lastResponse), "paused_for", pause.String()) + break + } + } + } + if halted { + return lastResponse, errDeterministicClientRejection, attempts + } + if lastResponse != nil { + if blocked { + return lastResponse, errFreeTierIPBlocked, attempts + } + return lastResponse, nil, attempts + } + if blocked { + return nil, errFreeTierIPBlocked, attempts + } + if lastErr == nil { + lastErr = errWARPUnavailable + } + return nil, lastErr, attempts +} + +// observeKeyResultWARP is observeKeyResult for a keyed attempt that left +// through WARP: the key still cools on an upstream rejection, but failures of +// the tunnel itself (no exit, dial or first-event failure) are not the key's +// fault and must not cool it. +func (g *Gateway) observeKeyResultWARP(ctx context.Context, nodes *upstreamNodes, node *upstreamNode, resp *http.Response, err error) { + if isDiagnosticRequest(ctx) { + return + } + status := upstreamStatus(resp) + if err == nil && status/100 == 2 || isNonRetryableClientResponse(resp, err) { + nodes.MarkSuccess(node) + return + } + if err != nil && resp == nil { + // The lease acquisition, dial, or first event failed: the upstream + // never judged this key. The pool already retired the exit. + return + } + nodes.MarkFailure(node, resp, err) +} diff --git a/internal/httpx/bun.go b/internal/httpx/bun.go index 23363a8..a9c3855 100644 --- a/internal/httpx/bun.go +++ b/internal/httpx/bun.go @@ -29,7 +29,11 @@ import ( // BunOptions configures a BunTransport. The fields mirror their namesakes on // http.Transport; a nil Proxy dials the upstream directly. type BunOptions struct { - Proxy *url.URL + Proxy *url.URL + // DialContext, when set, replaces the direct or proxied TCP dial. The + // caller owns the transport (for example a userspace WARP netstack); Bun + // still performs the uTLS handshake over the returned connection. + DialContext func(ctx context.Context, network, address string) (net.Conn, error) ConnectTimeout time.Duration ResponseHeaderTimeout time.Duration IdleConnTimeout time.Duration @@ -53,6 +57,7 @@ type BunOptions struct { // connections per host. type BunTransport struct { proxy *url.URL + dialContext func(context.Context, string, string) (net.Conn, error) dialer *net.Dialer responseHeaderTimeout time.Duration idleTimeout time.Duration @@ -79,6 +84,7 @@ func NewBunTransport(options BunOptions) (*BunTransport, error) { } return &BunTransport{ proxy: options.Proxy, + dialContext: options.DialContext, dialer: &net.Dialer{Timeout: options.ConnectTimeout, KeepAlive: 30 * time.Second}, responseHeaderTimeout: options.ResponseHeaderTimeout, idleTimeout: options.IdleConnTimeout, diff --git a/internal/httpx/bun_dial.go b/internal/httpx/bun_dial.go index 4f8e410..a0cea70 100644 --- a/internal/httpx/bun_dial.go +++ b/internal/httpx/bun_dial.go @@ -88,7 +88,9 @@ func bunClientHello() *utls.ClientHelloSpec { func (t *BunTransport) dial(ctx context.Context, scheme, addr, serverName string) (net.Conn, error) { var conn net.Conn var err error - if t.proxy == nil { + if t.dialContext != nil { + conn, err = t.dialContext(ctx, "tcp", addr) + } else if t.proxy == nil { conn, err = t.dialer.DialContext(ctx, "tcp", addr) } else { conn, err = t.dialProxy(ctx, addr) diff --git a/internal/warp/bind.go b/internal/warp/bind.go new file mode 100644 index 0000000..36e54ce --- /dev/null +++ b/internal/warp/bind.go @@ -0,0 +1,137 @@ +package warp + +import ( + "errors" + "net" + "net/netip" + "sync" + + "golang.zx2c4.com/wireguard/conn" +) + +type simpleBind struct { + mu sync.Mutex + ipv4 *net.UDPConn + ipv6 *net.UDPConn + closed bool +} + +type simpleEndpoint struct { + addr netip.AddrPort +} + +func (b *simpleBind) Open(port uint16) ([]conn.ReceiveFunc, uint16, error) { + b.mu.Lock() + defer b.mu.Unlock() + if b.ipv4 != nil || b.ipv6 != nil { + return nil, 0, conn.ErrBindAlreadyOpen + } + b.closed = false + var v4, v6 *net.UDPConn + var err error + if port == 0 { + v4, err = net.ListenUDP("udp4", &net.UDPAddr{}) + if err == nil { + port = uint16(v4.LocalAddr().(*net.UDPAddr).Port) + } + } else { + v4, err = net.ListenUDP("udp4", &net.UDPAddr{Port: int(port)}) + } + if err == nil { + v6, _ = net.ListenUDP("udp6", &net.UDPAddr{Port: int(port)}) + } + if v4 == nil && v6 == nil { + v6, err = net.ListenUDP("udp6", &net.UDPAddr{Port: int(port)}) + if err != nil { + return nil, 0, err + } + port = uint16(v6.LocalAddr().(*net.UDPAddr).Port) + } + var receives []conn.ReceiveFunc + if v4 != nil { + receives = append(receives, receiveUDP(v4)) + } + if v6 != nil { + receives = append(receives, receiveUDP(v6)) + } + b.ipv4, b.ipv6 = v4, v6 + return receives, port, nil +} + +func receiveUDP(udp *net.UDPConn) conn.ReceiveFunc { + return func(packets [][]byte, sizes []int, endpoints []conn.Endpoint) (int, error) { + n, addr, err := udp.ReadFromUDPAddrPort(packets[0]) + if err != nil { + return 0, err + } + sizes[0] = n + endpoints[0] = &simpleEndpoint{addr: addr} + return 1, nil + } +} + +func (b *simpleBind) Close() error { + b.mu.Lock() + defer b.mu.Unlock() + if b.closed { + return nil + } + b.closed = true + var errs []error + if b.ipv4 != nil { + errs = append(errs, b.ipv4.Close()) + b.ipv4 = nil + } + if b.ipv6 != nil { + errs = append(errs, b.ipv6.Close()) + b.ipv6 = nil + } + return errors.Join(errs...) +} + +func (b *simpleBind) SetMark(uint32) error { return nil } + +func (b *simpleBind) Send(bufs [][]byte, endpoint conn.Endpoint) error { + ep, ok := endpoint.(*simpleEndpoint) + if !ok { + return conn.ErrWrongEndpointType + } + b.mu.Lock() + var udp *net.UDPConn + if ep.addr.Addr().Is4() { + udp = b.ipv4 + } else { + udp = b.ipv6 + } + closed := b.closed + b.mu.Unlock() + if closed || udp == nil { + return net.ErrClosed + } + for _, buf := range bufs { + if _, err := udp.WriteToUDPAddrPort(buf, ep.addr); err != nil { + return err + } + } + return nil +} + +func (*simpleBind) ParseEndpoint(value string) (conn.Endpoint, error) { + addr, err := netip.ParseAddrPort(value) + if err != nil { + return nil, err + } + return &simpleEndpoint{addr: addr}, nil +} + +func (*simpleBind) BatchSize() int { return 1 } + +func (e *simpleEndpoint) ClearSrc() {} +func (e *simpleEndpoint) SrcToString() string { return "" } +func (e *simpleEndpoint) DstToString() string { return e.addr.String() } +func (e *simpleEndpoint) DstIP() netip.Addr { return e.addr.Addr() } +func (e *simpleEndpoint) SrcIP() netip.Addr { return netip.Addr{} } +func (e *simpleEndpoint) DstToBytes() []byte { + value, _ := e.addr.MarshalBinary() + return value +} diff --git a/internal/warp/doc.go b/internal/warp/doc.go new file mode 100644 index 0000000..3d8d337 --- /dev/null +++ b/internal/warp/doc.go @@ -0,0 +1,9 @@ +// Package warp carries outbound TCP traffic through Cloudflare WARP using a +// userspace WireGuard device and a gVisor network stack. It needs no TUN +// device, root privileges, or system routes: UDP sockets carry WireGuard +// packets, and the netstack terminates TCP inside the process. +// +// The implementation is adapted from github.com/sudogeeker/ai-route +// (internal/warp), which is MIT licensed. Only the parts this gateway needs +// are kept: registration, exit verification, and a small rotating pool. +package warp diff --git a/internal/warp/exit.go b/internal/warp/exit.go new file mode 100644 index 0000000..de95c94 --- /dev/null +++ b/internal/warp/exit.go @@ -0,0 +1,485 @@ +package warp + +import ( + "bufio" + "context" + "encoding/base64" + "encoding/hex" + "errors" + "fmt" + "io" + "net" + "net/http" + "net/netip" + "strings" + "sync" + "time" + + "golang.zx2c4.com/wireguard/device" + "golang.zx2c4.com/wireguard/tun/netstack" +) + +const rateLimitWindow = 10 + +const ( + probeTimeout = 5 * time.Second + probeCandidates = 10 +) + +type Stack string + +const ( + StackIPv4 Stack = "ipv4" + StackIPv6 Stack = "ipv6" + StackDual Stack = "dual" + + DefaultStack = StackIPv4 +) + +var ( + dnsV4 = netip.MustParseAddr("1.1.1.1") + dnsV6 = netip.MustParseAddr("2606:4700:4700::1111") +) + +func ParseStack(value string) (Stack, error) { + switch strings.ToLower(strings.TrimSpace(value)) { + case "": + return DefaultStack, nil + case "ipv6", "v6": + return StackIPv6, nil + case "ipv4", "v4": + return StackIPv4, nil + case "dual", "both": + return StackDual, nil + default: + return "", fmt.Errorf("unsupported WARP stack %q; use ipv6, ipv4 or dual", value) + } +} + +type exit struct { + id string + egress netip.Addr + stack Stack + device *device.Device + network *netstack.Net + mu sync.Mutex + refs int + retired bool + closed bool + penalized bool + recent []int + closeOnce sync.Once +} + +func newExit(ctx context.Context, reg registration) (*exit, error) { + return newExitWithStack(ctx, reg, DefaultStack) +} + +func newExitWithStack(ctx context.Context, reg registration, stack Stack) (*exit, error) { + normalized, err := ParseStack(string(stack)) + if err != nil { + return nil, err + } + stack = normalized + localV6, v6Err := parseAddress(reg.AddressV6) + localV4, v4Err := parseAddress(reg.AddressV4) + var localAddresses []netip.Addr + var dns []netip.Addr + switch stack { + case StackIPv6: + if v6Err != nil || !localV6.Is6() { + return nil, fmt.Errorf("invalid WARP IPv6 address %q", reg.AddressV6) + } + localAddresses = []netip.Addr{localV6} + dns = []netip.Addr{dnsV6} + case StackIPv4: + if v4Err != nil || !localV4.Is4() { + return nil, fmt.Errorf("invalid WARP IPv4 address %q", reg.AddressV4) + } + localAddresses = []netip.Addr{localV4} + dns = []netip.Addr{dnsV4} + case StackDual: + if v6Err == nil && localV6.Is6() { + localAddresses = append(localAddresses, localV6) + } + if v4Err == nil && localV4.Is4() { + localAddresses = append(localAddresses, localV4) + } + if len(localAddresses) == 0 { + return nil, fmt.Errorf("WARP registration has no usable address: v4=%q v6=%q", reg.AddressV4, reg.AddressV6) + } + dns = []netip.Addr{dnsV4, dnsV6} + } + tunDevice, network, err := netstack.CreateNetTUN(localAddresses, dns, 1280) + if err != nil { + return nil, fmt.Errorf("create WARP network stack: %w", err) + } + privateKey, err := uapiKey(reg.PrivateKey) + if err != nil { + tunDevice.Close() + return nil, fmt.Errorf("decode WARP private key: %w", err) + } + peerKey, err := uapiKey(reg.PeerPublicKey) + if err != nil { + tunDevice.Close() + return nil, fmt.Errorf("decode WARP peer key: %w", err) + } + endpoints, err := resolveEndpoints(ctx, reg.Endpoints, reg.Endpoint) + if err != nil { + tunDevice.Close() + return nil, err + } + wg := device.NewDevice(tunDevice, &simpleBind{}, device.NewLogger(device.LogLevelError, "warp: ")) + uapi := fmt.Sprintf( + "private_key=%s\npublic_key=%s\nallowed_ip=0.0.0.0/0\nallowed_ip=::/0\nendpoint=%s\npersistent_keepalive_interval=25\n", + privateKey, peerKey, endpoints[0], + ) + if err := wg.IpcSet(uapi); err != nil { + wg.Close() + <-wg.Wait() + return nil, fmt.Errorf("configure WARP device: %w", err) + } + if err := wg.Up(); err != nil { + wg.Close() + <-wg.Wait() + return nil, fmt.Errorf("start WARP device: %w", err) + } + e := &exit{id: reg.ID, stack: stack, device: wg, network: network} + egress, err := e.probe(ctx, wg, peerKey, endpoints) + if err != nil { + e.close() + return nil, err + } + e.egress = egress + return e, nil +} + +func resolveEndpoints(ctx context.Context, candidates []string, fallback string) ([]string, error) { + if len(candidates) == 0 && fallback != "" { + candidates = []string{fallback} + } + seen := make(map[string]bool) + var endpoints []string + for _, candidate := range candidates { + normalized, err := normalizeEndpoint(candidate) + if err != nil { + continue + } + host, port, _ := net.SplitHostPort(normalized) + if net.ParseIP(host) != nil { + if !seen[normalized] { + seen[normalized] = true + endpoints = append(endpoints, normalized) + } + } else { + addrs, err := net.DefaultResolver.LookupIPAddr(ctx, host) + if err != nil { + continue + } + for _, ip := range addrs { + value := net.JoinHostPort(ip.IP.String(), port) + if !seen[value] { + seen[value] = true + endpoints = append(endpoints, value) + } + } + } + if len(endpoints) >= probeCandidates { + break + } + } + if len(endpoints) == 0 { + return nil, fmt.Errorf("resolve WARP endpoint candidates %v", candidates) + } + return endpoints[:min(len(endpoints), probeCandidates)], nil +} + +func normalizeEndpoint(endpoint string) (string, error) { + endpoint = strings.TrimSpace(endpoint) + if !strings.Contains(endpoint, ":") { + endpoint = net.JoinHostPort(endpoint, "2408") + } else if addr, err := netip.ParseAddr(endpoint); err == nil { + endpoint = net.JoinHostPort(addr.String(), "2408") + } + host, port, err := net.SplitHostPort(endpoint) + if err != nil { + return "", fmt.Errorf("invalid WARP endpoint %q", endpoint) + } + if port == "" || port == "0" { + port = "2408" + } + return net.JoinHostPort(host, port), nil +} + +func parseAddress(value string) (netip.Addr, error) { + value = strings.TrimSpace(value) + if addr, err := netip.ParseAddr(value); err == nil { + return addr.Unmap(), nil + } + prefix, err := netip.ParsePrefix(value) + if err != nil { + return netip.Addr{}, err + } + return prefix.Addr().Unmap(), nil +} + +func uapiKey(encoded string) (string, error) { + key, err := base64.StdEncoding.DecodeString(strings.TrimSpace(encoded)) + if err != nil || len(key) != 32 { + return "", errors.New("invalid WireGuard key") + } + return hex.EncodeToString(key), nil +} + +type probeTarget struct { + network string + url string +} + +func probeTargets(stack Stack) []probeTarget { + switch stack { + case StackIPv4: + return []probeTarget{{network: "tcp4", url: "https://1.1.1.1/cdn-cgi/trace"}} + case StackDual: + return []probeTarget{ + {network: "tcp4", url: "https://1.1.1.1/cdn-cgi/trace"}, + {network: "tcp6", url: "https://[2606:4700:4700::1111]/cdn-cgi/trace"}, + } + default: + return []probeTarget{{network: "tcp6", url: "https://[2606:4700:4700::1111]/cdn-cgi/trace"}} + } +} + +func (e *exit) probe(ctx context.Context, wg *device.Device, peerKey string, endpoints []string) (netip.Addr, error) { + var lastErr error + for index, endpoint := range endpoints { + if index > 0 { + if err := wg.IpcSet(fmt.Sprintf("public_key=%s\nendpoint=%s\n", peerKey, endpoint)); err != nil { + lastErr = fmt.Errorf("switch WARP endpoint to %s: %w", endpoint, err) + continue + } + } + for _, target := range probeTargets(e.stack) { + egress, err := e.probeTarget(ctx, target) + if err == nil { + return egress, nil + } + lastErr = err + } + } + return netip.Addr{}, fmt.Errorf("verify WARP %s egress: %w", e.stack, lastErr) +} + +func (e *exit) probeTarget(ctx context.Context, target probeTarget) (netip.Addr, error) { + probeCtx, cancel := context.WithTimeout(ctx, probeTimeout) + defer cancel() + transport := &http.Transport{ + Proxy: nil, + ForceAttemptHTTP2: false, + DisableKeepAlives: true, + TLSHandshakeTimeout: 10 * time.Second, + DialContext: func(ctx context.Context, _, address string) (net.Conn, error) { + return e.network.DialContext(ctx, target.network, address) + }, + } + defer transport.CloseIdleConnections() + req, err := http.NewRequestWithContext(probeCtx, http.MethodGet, target.url, nil) + if err != nil { + return netip.Addr{}, err + } + resp, err := (&http.Client{Transport: transport}).Do(req) + if err != nil { + return netip.Addr{}, err + } + defer resp.Body.Close() + egress, err := parseTrace(resp.Body) + if err != nil { + return netip.Addr{}, err + } + if target.network == "tcp4" && !egress.Is4() { + return netip.Addr{}, fmt.Errorf("WARP trace over IPv4 reported %s", egress) + } + if target.network == "tcp6" && !egress.Is6() { + return netip.Addr{}, fmt.Errorf("WARP trace over IPv6 reported %s", egress) + } + return egress, nil +} + +func parseTrace(body io.Reader) (netip.Addr, error) { + scanner := bufio.NewScanner(io.LimitReader(body, 64<<10)) + var rawIP string + warpEnabled := false + for scanner.Scan() { + key, value, ok := strings.Cut(scanner.Text(), "=") + if !ok { + continue + } + switch strings.TrimSpace(key) { + case "ip": + rawIP = strings.TrimSpace(value) + case "warp": + warpEnabled = strings.TrimSpace(value) == "on" + } + } + if err := scanner.Err(); err != nil { + return netip.Addr{}, err + } + if !warpEnabled { + return netip.Addr{}, errors.New("Cloudflare trace reports warp=off") + } + addr, err := netip.ParseAddr(rawIP) + if err != nil { + return netip.Addr{}, fmt.Errorf("invalid trace IP %q", rawIP) + } + addr = addr.Unmap() + if (!addr.Is4() && !addr.Is6()) || !addr.IsGlobalUnicast() || addr.IsPrivate() { + return netip.Addr{}, fmt.Errorf("trace returned non-public address %s", addr) + } + return addr, nil +} + +func (e *exit) addRef() bool { + e.mu.Lock() + defer e.mu.Unlock() + if e.retired || e.closed { + return false + } + e.refs++ + return true +} + +func (e *exit) release() { + e.mu.Lock() + if e.refs > 0 { + e.refs-- + } + closeNow := e.refs == 0 && e.retired && !e.closed + e.mu.Unlock() + if closeNow { + e.close() + } +} + +func (e *exit) retire() { + e.mu.Lock() + e.retired = true + closeNow := e.refs == 0 && !e.closed + e.mu.Unlock() + if closeNow { + e.close() + } +} + +func (e *exit) close() { + e.closeOnce.Do(func() { + e.mu.Lock() + e.closed = true + e.mu.Unlock() + if e.device != nil { + e.device.Close() + <-e.device.Wait() + } + }) +} + +func (e *exit) observe(status int, body []byte) (bool, string) { + e.mu.Lock() + defer e.mu.Unlock() + if e.penalized { + return false, "" + } + if status == http.StatusForbidden { + e.recent = e.recent[:0] + reason := "HTTP 403" + if networkAnomaly(body) { + reason += " network anomaly" + } + return true, reason + } + if status != http.StatusTooManyRequests { + e.recent = e.recent[:0] + return false, "" + } + e.recent = append(e.recent, status) + if len(e.recent) > rateLimitWindow { + e.recent = e.recent[len(e.recent)-rateLimitWindow:] + } + if len(e.recent) == rateLimitWindow { + e.recent = e.recent[:0] + return true, fmt.Sprintf("%d consecutive HTTP 429 responses", rateLimitWindow) + } + return false, "" +} + +func (e *exit) markPenalized() bool { + e.mu.Lock() + defer e.mu.Unlock() + if e.penalized { + return false + } + e.penalized = true + return true +} + +func (e *exit) clearPenalty() { + e.mu.Lock() + e.penalized = false + e.mu.Unlock() +} + +func networkAnomaly(body []byte) bool { + return strings.Contains(strings.ToLower(string(body)), "network") +} + +func (e *exit) dialContext(ctx context.Context, network, address string) (net.Conn, error) { + if e.network == nil { + return nil, errors.New("WARP network is closed") + } + network = strings.ToLower(strings.TrimSpace(network)) + switch network { + case "tcp": + network = e.dialNetwork() + case "tcp4", "tcp6": + default: + return nil, fmt.Errorf("WARP supports TCP only, got %q", network) + } + switch e.stack { + case StackIPv4: + if network != "tcp4" { + return nil, fmt.Errorf("WARP IPv4 stack cannot dial %q", network) + } + case StackIPv6: + if network != "tcp6" { + return nil, fmt.Errorf("WARP IPv6 stack cannot dial %q", network) + } + case StackDual: + // Both address families are present in the netstack. + default: + return nil, fmt.Errorf("unsupported WARP stack %q", e.stack) + } + return e.network.DialContext(ctx, network, address) +} + +func (e *exit) dialNetwork() string { + switch e.stack { + case StackIPv4: + return "tcp4" + case StackDual: + if e.egress.Is4() { + return "tcp4" + } + return "tcp6" + default: + return "tcp6" + } +} + +func (e *exit) egressKey() string { + if e.egress.Is4() { + return netip.PrefixFrom(e.egress, 32).Masked().String() + } + if !e.egress.Is6() { + return "" + } + return netip.PrefixFrom(e.egress, 64).Masked().String() +} diff --git a/internal/warp/pool.go b/internal/warp/pool.go new file mode 100644 index 0000000..9233cc8 --- /dev/null +++ b/internal/warp/pool.go @@ -0,0 +1,527 @@ +package warp + +import ( + "context" + "errors" + "fmt" + "log/slog" + "net" + "sync" + "time" +) + +const DefaultPoolSize = 2 + +const egressCooldown = 10 * time.Minute + +// ErrClosed is returned when a pool is used after Close. Callers use it to +// tell a retiring pool apart from a temporary capacity wait. +var ErrClosed = errors.New("WARP pool is closed") + +type logger interface { + Debugf(string, ...interface{}) + Infof(string, ...interface{}) + Warnf(string, ...interface{}) + Errorf(string, ...interface{}) +} + +// slogLogger adapts the structured logger used by the gateway to the short +// diagnostic messages this package emits at its own lifecycle boundaries. +type slogLogger struct { + log *slog.Logger +} + +func (l slogLogger) logf(level slog.Level, format string, args ...interface{}) { + if l.log == nil { + return + } + l.log.Log(context.Background(), level, fmt.Sprintf(format, args...), "component", "warp") +} + +func (l slogLogger) Debugf(format string, args ...interface{}) { + l.logf(slog.LevelDebug, format, args...) +} + +func (l slogLogger) Infof(format string, args ...interface{}) { + l.logf(slog.LevelInfo, format, args...) +} + +func (l slogLogger) Warnf(format string, args ...interface{}) { + l.logf(slog.LevelWarn, format, args...) +} + +func (l slogLogger) Errorf(format string, args ...interface{}) { + l.logf(slog.LevelError, format, args...) +} + +type Pool struct { + ctx context.Context + cancel context.CancelFunc + logger logger + size int + stack Stack + newExit func(context.Context) (*exit, error) + + mu sync.Mutex + active []*exit + standby []*exit + activeTarget int + standbyTarget int + next int + reserved map[string]bool + cooling map[string]time.Time + changed chan struct{} + closed bool + refilling bool + wait sync.WaitGroup + createMu sync.Mutex +} + +type Lease struct { + exit *exit + once sync.Once +} + +// Snapshot is a point-in-time view of a pool for health and admin reporting. +type Snapshot struct { + Stack string + Size int + Active int + Standby int + Cooling int + Egress []string +} + +// NewWithStack creates a WARP pool whose exits use the selected IP stack. +func NewWithStack(ctx context.Context, log *slog.Logger, size int, stack Stack) (*Pool, error) { + normalized, err := ParseStack(string(stack)) + if err != nil { + return nil, err + } + if size <= 0 { + size = DefaultPoolSize + } + r := newRegistrar() + pool, err := newPool(ctx, slogLogger{log: log}, size, func(ctx context.Context) (*exit, error) { + reg, err := r.register(ctx) + if err != nil { + return nil, err + } + return newExitWithStack(ctx, reg, normalized) + }) + if err != nil { + return nil, err + } + pool.stack = normalized + return pool, nil +} + +func newPool(ctx context.Context, log logger, size int, create func(context.Context) (*exit, error)) (*Pool, error) { + if size <= 0 { + size = DefaultPoolSize + } + poolCtx, cancel := context.WithCancel(ctx) + activeTarget, standbyTarget := poolTargets(size) + p := &Pool{ + ctx: poolCtx, + cancel: cancel, + logger: log, + size: size, + activeTarget: activeTarget, + standbyTarget: standbyTarget, + newExit: create, + reserved: make(map[string]bool), + cooling: make(map[string]time.Time), + changed: make(chan struct{}), + } + first, err := p.createExit(poolCtx) + if err != nil { + cancel() + return nil, err + } + p.active = []*exit{first} + if log != nil { + log.Infof("OpenCode WARP/%s egress %s ready at %s (active target %d, standby target %d)", first.stack, first.id, first.egress, activeTarget, standbyTarget) + } + p.startRefill() + return p, nil +} + +func (p *Pool) Acquire(ctx context.Context) (*Lease, error) { + for { + p.mu.Lock() + if p.closed { + p.mu.Unlock() + return nil, ErrClosed + } + for attempts := 0; attempts < len(p.active); attempts++ { + index := p.next % len(p.active) + p.next = (p.next + 1) % len(p.active) + active := p.active[index] + if active.addRef() { + p.mu.Unlock() + return &Lease{exit: active}, nil + } + } + changed := p.changed + p.mu.Unlock() + select { + case <-ctx.Done(): + return nil, ctx.Err() + case <-p.ctx.Done(): + return nil, ErrClosed + case <-changed: + } + } +} + +func (p *Pool) Report(lease *Lease, status int, body []byte) { + if lease == nil || lease.exit == nil { + return + } + rotate, reason := lease.exit.observe(status, body) + if !rotate { + return + } + p.penalize(lease.exit, reason) +} + +// Fail drops an exit that cannot carry traffic even though the upstream never +// produced an HTTP response, such as a broken WARP handshake or a stalled first +// token. Retrying the same user-space tunnel would only repeat the stall. +func (p *Pool) Fail(lease *Lease, reason string) { + if lease == nil || lease.exit == nil || reason == "" { + return + } + p.penalize(lease.exit, reason) +} + +func (p *Pool) Size() int { return p.size } + +// Snapshot reports the pool's current capacity and the public egress address +// of every active exit. It never exposes keys or device tokens. +func (p *Pool) Snapshot() Snapshot { + p.mu.Lock() + defer p.mu.Unlock() + snapshot := Snapshot{Stack: string(p.stack), Size: p.size, Active: len(p.active), Standby: len(p.standby), Cooling: len(p.cooling)} + for _, active := range p.active { + if key := active.egressKey(); key != "" { + snapshot.Egress = append(snapshot.Egress, key) + } + } + return snapshot +} + +func (p *Pool) penalize(bad *exit, reason string) { + p.mu.Lock() + if p.closed { + p.mu.Unlock() + return + } + index := p.activeIndexLocked(bad) + if index < 0 { + p.mu.Unlock() + return + } + if !bad.markPenalized() { + p.mu.Unlock() + return + } + if key := bad.egressKey(); key != "" { + p.cooling[key] = time.Now().Add(egressCooldown) + delete(p.reserved, key) + } + p.active = append(p.active[:index], p.active[index+1:]...) + if p.next >= len(p.active) { + p.next = 0 + } + var replacement *exit + if len(p.standby) > 0 && len(p.active) < p.activeTarget { + replacement = p.standby[0] + p.standby = p.standby[1:] + p.active = append(p.active, replacement) + } + if replacement != nil { + p.wait.Add(1) + } + p.wait.Add(1) + p.notifyLocked() + p.mu.Unlock() + + if p.logger != nil { + p.logger.Warnf("Rotating OpenCode WARP egress %s (%s)", bad.id, reason) + } + if replacement != nil { + go func() { + defer p.wait.Done() + bad.retire() + }() + if p.logger != nil { + p.logger.Infof("OpenCode WARP exit switched to standby %s at %s", replacement.id, replacement.egress) + } + } + go func() { + defer p.wait.Done() + p.replace(bad, reason) + }() +} + +func (p *Pool) replace(old *exit, reason string) { + replacement, err := p.createExit(p.ctx) + p.mu.Lock() + if p.closed { + p.mu.Unlock() + if replacement != nil { + p.releaseReservation(replacement) + replacement.close() + } + old.retire() + return + } + if err != nil { + restored := len(p.active) == 0 + if restored { + old.clearPenalty() + if key := old.egressKey(); key != "" { + p.reserved[key] = true + delete(p.cooling, key) + } + p.active = append(p.active, old) + p.notifyLocked() + } + p.mu.Unlock() + if !restored { + old.retire() + } + if p.logger != nil { + p.logger.Errorf("Cannot replace OpenCode WARP egress %s: %v", old.id, err) + } + p.startRefill() + return + } + if p.activeIndexLocked(old) >= 0 { + p.mu.Unlock() + p.releaseReservation(replacement) + replacement.close() + old.retire() + return + } + placed := false + if len(p.active) < p.activeTarget { + p.active = append(p.active, replacement) + placed = true + } else if len(p.standby) < p.standbyTarget { + p.standby = append(p.standby, replacement) + placed = true + } + p.notifyLocked() + p.mu.Unlock() + if !placed { + p.releaseReservation(replacement) + replacement.close() + old.retire() + return + } + if p.logger != nil { + p.logger.Infof("OpenCode WARP egress %s replaced by %s at %s (%s), active=%d standby=%d", old.id, replacement.id, replacement.egress, reason, len(p.active), len(p.standby)) + } + old.retire() + p.startRefill() +} + +func (p *Pool) refill() { + p.mu.Lock() + if p.closed || p.refilling || len(p.active) == 0 || !p.needsRefillLocked() { + p.mu.Unlock() + return + } + p.refilling = true + p.mu.Unlock() + + replacement, err := p.createExit(p.ctx) + p.mu.Lock() + p.refilling = false + if err == nil && !p.closed { + if len(p.active) < p.activeTarget { + p.active = append(p.active, replacement) + replacement = nil + p.notifyLocked() + } else if len(p.standby) < p.standbyTarget { + p.standby = append(p.standby, replacement) + replacement = nil + p.notifyLocked() + } + } + if p.closed { + p.notifyLocked() + } + p.mu.Unlock() + + if replacement != nil { + p.releaseReservation(replacement) + replacement.close() + } + if err != nil && p.ctx.Err() == nil && p.logger != nil { + p.logger.Warnf("Cannot pre-register OpenCode WARP egress: %v", err) + } + p.startRefill() +} + +func (p *Pool) startRefill() { + p.mu.Lock() + if p.closed || p.refilling || len(p.active) == 0 || !p.needsRefillLocked() { + p.mu.Unlock() + return + } + p.wait.Add(1) + p.mu.Unlock() + go func() { + defer p.wait.Done() + p.refill() + }() +} + +func (p *Pool) createExit(ctx context.Context) (*exit, error) { + p.createMu.Lock() + defer p.createMu.Unlock() + var lastErr error + for attempt := 0; attempt < 4; attempt++ { + p.mu.Lock() + closed := p.closed + p.mu.Unlock() + if closed { + return nil, ErrClosed + } + candidate, err := p.newExit(ctx) + if err != nil { + return nil, err + } + key := candidate.egressKey() + now := time.Now() + p.mu.Lock() + for subnet, until := range p.cooling { + if !until.After(now) { + delete(p.cooling, subnet) + } + } + usable := key != "" && !p.reserved[key] && !p.cooling[key].After(now) + if usable { + p.reserved[key] = true + } + p.mu.Unlock() + if usable { + return candidate, nil + } + lastErr = fmt.Errorf("WARP egress %s is already active or cooling down", key) + if p.logger != nil { + p.logger.Warnf("Discarding duplicate WARP exit %s: %v", candidate.id, lastErr) + } + candidate.close() + } + return nil, lastErr +} + +func (p *Pool) releaseReservation(e *exit) { + if e == nil { + return + } + key := e.egressKey() + if key == "" { + return + } + p.mu.Lock() + delete(p.reserved, key) + p.mu.Unlock() +} + +func (p *Pool) notifyLocked() { + close(p.changed) + p.changed = make(chan struct{}) +} + +func (p *Pool) activeIndexLocked(target *exit) int { + for index, candidate := range p.active { + if candidate == target { + return index + } + } + return -1 +} + +func (p *Pool) needsRefillLocked() bool { + return len(p.active) < p.activeTarget || len(p.standby) < p.standbyTarget +} + +func poolTargets(size int) (active, standby int) { + if size <= 1 { + return 1, 0 + } + return size - 1, 1 +} + +func (p *Pool) Close() { + p.mu.Lock() + if p.closed { + p.mu.Unlock() + return + } + p.closed = true + active := p.active + p.active = nil + standby := p.standby + p.standby = nil + p.notifyLocked() + p.mu.Unlock() + + p.cancel() + for _, item := range active { + p.releaseReservation(item) + item.retire() + } + for _, item := range standby { + p.releaseReservation(item) + item.retire() + } + p.wait.Wait() +} + +func (l *Lease) DialContext(ctx context.Context, network, address string) (net.Conn, error) { + if l == nil || l.exit == nil { + return nil, errors.New("WARP lease is closed") + } + return l.exit.dialContext(ctx, network, address) +} + +func (l *Lease) Release() { + if l == nil { + return + } + l.once.Do(func() { + if l.exit != nil { + l.exit.release() + } + }) +} + +func (l *Lease) EgressKey() string { + if l == nil || l.exit == nil { + return "" + } + return l.exit.egressKey() +} + +// DialNetwork is the explicit TCP address family for this lease. Callers should +// pass it to DialContext instead of assuming IPv6. +func (l *Lease) DialNetwork() string { + if l == nil || l.exit == nil { + return "" + } + return l.exit.dialNetwork() +} + +func (l *Lease) String() string { + if l == nil || l.exit == nil { + return "" + } + return fmt.Sprintf("%s/%s", l.exit.id, l.exit.egress) +} diff --git a/internal/warp/registrar.go b/internal/warp/registrar.go new file mode 100644 index 0000000..e227e41 --- /dev/null +++ b/internal/warp/registrar.go @@ -0,0 +1,315 @@ +package warp + +import ( + "bytes" + "context" + "crypto/ecdh" + "crypto/rand" + "encoding/base64" + "encoding/json" + "errors" + "fmt" + "io" + "net" + "net/http" + "net/netip" + "strconv" + "strings" + "sync" + "time" +) + +const ( + defaultAPIBase = "https://api.cloudflareclient.com/v0i1909051800" + defaultPeer = "bmXOC+F1FxEMF9dyiK2H5/1SUtzH0JuVo51h2wPfgyo=" + registerGap = 12 * time.Second +) + +var fallbackEndpoints = []string{ + "162.159.192.1:2408", + "[2606:4700:d0::a29f:c001]:2408", + "162.159.193.1:2408", + "engage.cloudflareclient.com:2408", +} + +type registration struct { + ID string + Token string + PrivateKey string + PublicKey string + AddressV4 string + AddressV6 string + PeerPublicKey string + Endpoint string + Endpoints []string +} + +type registrar struct { + base string + client *http.Client + minGap time.Duration + mu sync.Mutex + lastReg time.Time +} + +func newRegistrar() *registrar { + return ®istrar{ + base: defaultAPIBase, + client: &http.Client{ + Timeout: 30 * time.Second, + Transport: &http.Transport{ + Proxy: nil, + ForceAttemptHTTP2: false, + MaxIdleConns: 4, + IdleConnTimeout: 30 * time.Second, + TLSHandshakeTimeout: 10 * time.Second, + }, + }, + minGap: registerGap, + } +} + +func (r *registrar) register(ctx context.Context) (registration, error) { + r.mu.Lock() + defer r.mu.Unlock() + + if wait := r.minGap - time.Since(r.lastReg); wait > 0 { + timer := time.NewTimer(wait) + defer timer.Stop() + select { + case <-ctx.Done(): + return registration{}, ctx.Err() + case <-timer.C: + } + } + r.lastReg = time.Now() + + privateKey, publicKey, err := wireGuardKeypair() + if err != nil { + return registration{}, err + } + request := map[string]string{ + "key": publicKey, + "install_id": "", + "fcm_token": "", + "tos": "2021-09-14T17:00:00.000+00:00", + "model": "PC", + "serial_number": "", + "locale": "en_US", + } + payload, err := json.Marshal(request) + if err != nil { + return registration{}, err + } + var created deviceEnvelope + if err := r.doJSON(ctx, http.MethodPost, "/reg", payload, "", &created); err != nil { + return registration{}, fmt.Errorf("create WARP device: %w", err) + } + if created.Result.ID == "" || created.Result.Token == "" { + return registration{}, errors.New("create WARP device: response omitted id or token") + } + + enabled, err := json.Marshal(map[string]bool{"warp_enabled": true}) + if err != nil { + return registration{}, err + } + var patched deviceEnvelope + if err := r.doJSON(ctx, http.MethodPatch, "/reg/"+created.Result.ID, enabled, created.Result.Token, &patched); err != nil { + return registration{}, fmt.Errorf("enable WARP device: %w", err) + } + var current deviceEnvelope + if err := r.doJSON(ctx, http.MethodGet, "/reg/"+created.Result.ID, nil, created.Result.Token, ¤t); err != nil { + return registration{}, fmt.Errorf("read WARP device: %w", err) + } + if !current.Result.WARPEnabled { + return registration{}, errors.New("read WARP device: WARP is not enabled") + } + addresses := current.Result.Config.Interface.Addresses + var peerPublicKey, endpoint string + var endpoints []string + if len(current.Result.Config.Peers) != 0 { + peer := current.Result.Config.Peers[0] + peerPublicKey = peer.PublicKey + bases := []string{peer.Endpoint.V4, peer.Endpoint.V6, peer.Endpoint.Host} + ports := []int{2408} + for _, port := range peer.Endpoint.Ports { + if port <= 0 || port > 65535 { + continue + } + if port != 2408 { + ports = append(ports, port) + } + } + for _, port := range ports { + for _, base := range bases { + endpoints = append(endpoints, replaceEndpointPort(base, port)) + } + } + endpoints = append(endpoints, bases...) + } + endpoints = append(endpoints, fallbackEndpoints...) + endpoints = uniqueEndpoints(endpoints) + if peerPublicKey == "" { + peerPublicKey = defaultPeer + } + if len(endpoints) != 0 { + endpoint = endpoints[0] + } + if addresses.V4 == "" && addresses.V6 == "" { + return registration{}, errors.New("read WARP device: config omitted both IP addresses") + } + return registration{ + ID: created.Result.ID, + Token: created.Result.Token, + PrivateKey: privateKey, + PublicKey: publicKey, + AddressV4: addresses.V4, + AddressV6: addresses.V6, + PeerPublicKey: peerPublicKey, + Endpoint: endpoint, + Endpoints: endpoints, + }, nil +} + +func replaceEndpointPort(endpoint string, port int) string { + endpoint = strings.TrimSpace(endpoint) + if endpoint == "" { + return "" + } + host, _, err := net.SplitHostPort(endpoint) + if err == nil { + return net.JoinHostPort(host, strconv.Itoa(port)) + } + if addr, err := netip.ParseAddr(endpoint); err == nil { + return net.JoinHostPort(addr.String(), strconv.Itoa(port)) + } + return net.JoinHostPort(endpoint, strconv.Itoa(port)) +} + +func uniqueEndpoints(endpoints []string) []string { + seen := make(map[string]bool, len(endpoints)) + result := make([]string, 0, len(endpoints)) + for _, endpoint := range endpoints { + endpoint = strings.TrimSpace(endpoint) + if endpoint == "" || seen[endpoint] { + continue + } + seen[endpoint] = true + result = append(result, endpoint) + } + return result +} + +func (r *registrar) doJSON(ctx context.Context, method, path string, body []byte, token string, target any) error { + var lastErr error + for attempt := 0; attempt < 4; attempt++ { + if attempt > 0 { + wait := time.Duration(1<<(attempt-1)) * 2 * time.Second + timer := time.NewTimer(wait) + select { + case <-ctx.Done(): + timer.Stop() + return ctx.Err() + case <-timer.C: + } + } + var reader io.Reader + if body != nil { + reader = bytes.NewReader(body) + } + req, err := http.NewRequestWithContext(ctx, method, strings.TrimRight(r.base, "/")+path, reader) + if err != nil { + return err + } + req.Header.Set("Content-Type", "application/json") + req.Header.Set("CF-Client-Version", "a-6.10-2158") + req.Header.Set("User-Agent", "okhttp/3.12.1") + if token != "" { + req.Header.Set("Authorization", "Bearer "+token) + } + resp, err := r.client.Do(req) + if err != nil { + lastErr = err + continue + } + data, readErr := io.ReadAll(io.LimitReader(resp.Body, 1<<20)) + resp.Body.Close() + if readErr != nil { + lastErr = readErr + continue + } + if resp.StatusCode < 200 || resp.StatusCode >= 300 { + lastErr = fmt.Errorf("Cloudflare API HTTP %d: %s", resp.StatusCode, strings.TrimSpace(string(data))) + if resp.StatusCode != http.StatusTooManyRequests && resp.StatusCode < 500 { + return lastErr + } + if retryAfter := parseRetryAfter(resp.Header.Get("Retry-After")); retryAfter > 0 { + timer := time.NewTimer(retryAfter) + select { + case <-ctx.Done(): + timer.Stop() + return ctx.Err() + case <-timer.C: + } + } + continue + } + if err := json.Unmarshal(data, target); err != nil { + return fmt.Errorf("decode Cloudflare API response: %w", err) + } + return nil + } + if lastErr == nil { + lastErr = errors.New("Cloudflare API request failed") + } + return lastErr +} + +func wireGuardKeypair() (string, string, error) { + privateKey, err := ecdh.X25519().GenerateKey(rand.Reader) + if err != nil { + return "", "", err + } + return base64.StdEncoding.EncodeToString(privateKey.Bytes()), base64.StdEncoding.EncodeToString(privateKey.PublicKey().Bytes()), nil +} + +func parseRetryAfter(value string) time.Duration { + value = strings.TrimSpace(value) + if value == "" { + return 0 + } + if seconds, err := strconv.Atoi(value); err == nil && seconds > 0 { + return time.Duration(seconds) * time.Second + } + if at, err := http.ParseTime(value); err == nil && at.After(time.Now()) { + return time.Until(at) + } + return 0 +} + +type deviceEnvelope struct { + Result deviceResult `json:"result"` +} + +type deviceResult struct { + ID string `json:"id"` + Token string `json:"token"` + WARPEnabled bool `json:"warp_enabled"` + Config struct { + Interface struct { + Addresses struct { + V4 string `json:"v4"` + V6 string `json:"v6"` + } `json:"addresses"` + } `json:"interface"` + Peers []struct { + PublicKey string `json:"public_key"` + Endpoint struct { + V4 string `json:"v4"` + V6 string `json:"v6"` + Host string `json:"host"` + Ports []int `json:"ports"` + } `json:"endpoint"` + } `json:"peers"` + } `json:"config"` +} diff --git a/webui/index.html b/webui/index.html index deb6102..1c6f06a 100644 --- a/webui/index.html +++ b/webui/index.html @@ -861,6 +861,36 @@ +
+
+
+

WARP 出口

+

+ 开启后,免费模型流量(匿名通道、免费模型 Zen Key、免费模型探测)改走用户态 WARP,不再使用任何 Proxy;Go 套餐与付费模型保持不变。 +

+
+
+
+
+ +
+
+ + +
+
+ + +
+
+