diff --git a/README.md b/README.md index fc5a8ea..45fa525 100644 --- a/README.md +++ b/README.md @@ -486,6 +486,16 @@ The server forces `stream: false`. Use `{"mode":"selected","tier":"zen","id":"KE After execution, the management endpoint returns HTTP 200 with the actual result in `ok`, `http_status`, `request_id`, `route`, and `response`. Selected-key results also include `selected_key` and `key_test`: `usable`, `rejected`, `rate_limited`, `transport_error`, `upstream_error`, `request_error`, or `unavailable`. Invalid management input, authentication, CSRF, and throttling retain their own HTTP error statuses. +### Go subscription sign-in + +In **Models & Quota** (`/#model-quotas`), select **Sign in to Go in your browser**, open the displayed official OpenCode Device OAuth link, and enter the displayed `user_code`. Authorize the request you initiated; the WebUI schedules backend polling to complete sign-in. No token pasting, local credential-file import, or callback URL submission is required. If the account has multiple organizations, select the organization with the Go subscription in the WebUI. + +- The backend refreshes access credentials when needed and persists the connection in the local configuration (`go_subscription`). This includes access and refresh secrets: protect the configuration and its backups. These credentials are not sent to the WebUI. +- **Disconnect** removes the gateway's saved connection, not the official OpenCode session. Manually configured `go_keys` are retained but are not fallback routes while OAuth is connected; disconnecting restores their existing routing. If sign-in becomes invalid, reconnect rather than relying on those keys as a fallback. +- OAuth uses only confirmed official Go subscription routes, never a pay-as-you-go route as fallback. OAuth quota is currently shown as **unknown**; the gateway does not infer remaining allowance from models or request results. The existing usage endpoint remains available for manually configured Go keys. + +The implementation follows the upstream source snapshots [v2 `4617210822bdbb31e5749751afbfb4584ccedac8`](https://github.com/anomalyco/opencode/tree/4617210822bdbb31e5749751afbfb4584ccedac8) and [dev `7745079647b65036fe142e09ccd8623b25be1878`](https://github.com/anomalyco/opencode/tree/7745079647b65036fe142e09ccd8623b25be1878). Source compatibility and local checks are not a claim of live subscription validation; upstream authorization and routing can change. See the [management guide](docs/management.zh-CN.md) for lifecycle and management endpoints. + ### Interface language The WebUI loads its translations from `webui/js/i18n.js`. It ships with **简体中文** (default), **English**, **Tiếng Việt**, and **Italiano**. The original Simplified Chinese copy lives in `index.html` and `webui/js/` and stays the fallback for every string without a translation, so adding a language never rewrites the original. diff --git a/README.zh-CN.md b/README.zh-CN.md index 464eb14..13a7d3a 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -480,6 +480,16 @@ Playground 需要已登录的 Session 和 `X-CSRF-Token`,每个客户端 IP 执行后,管理接口返回 HTTP 200,实际结果位于 `ok`、`http_status`、`request_id`、`route` 和 `response`。指定 Key 时还返回 `selected_key` 与 `key_test`,其值包括 `usable`、`rejected`、`rate_limited`、`transport_error`、`upstream_error`、`request_error`、`unavailable`。管理请求格式、认证、CSRF 和限速错误仍返回各自对应的 HTTP 状态。 +### Go 订阅登录 + +在「模型与额度」页面(`/#model-quotas`)点击「浏览器登录 Go 订阅」,打开页面显示的 OpenCode 官方 Device OAuth 链接,输入显示的 `user_code`。确认这是自己发起的授权后完成登录;WebUI 按间隔请求后端轮询并完成授权交换,无需手贴 Token、导入本机凭证文件或提交回调 URL。账号关联多个组织时,在 WebUI 选择 Go 订阅所在的组织。 + +- 后端按需自动刷新访问凭证,并将连接保存到本地配置的 `go_subscription`。其中包含访问和刷新凭证,属于敏感信息,请保护配置文件及备份;WebUI 不接收这些凭证。 +- 「断开 Go 订阅登录」仅移除网关保存的连接,不撤销 OpenCode 官方会话。手动配置的 `go_keys` 仍保留,但 OAuth 连接期间不作备用通道;断开后恢复原有手动 Key 路由。登录失效时应重新登录,而非依赖手动 Key 回退。 +- OAuth 只使用已确认的官方 Go 订阅路由,不回退到按量付费(PAYG)通道。OAuth 额度当前显示为「未知」,不根据模型或请求结果推算;手动 Go Key 仍可使用原有额度查询接口。 + +实现参考上游源码快照:[v2 `4617210822bdbb31e5749751afbfb4584ccedac8`](https://github.com/anomalyco/opencode/tree/4617210822bdbb31e5749751afbfb4584ccedac8)、[dev `7745079647b65036fe142e09ccd8623b25be1878`](https://github.com/anomalyco/opencode/tree/7745079647b65036fe142e09ccd8623b25be1878)。源码对比和本地检查不代表已通过真实订阅登录验证,上游授权或路由仍可能变化。生命周期和管理接口见[管理控制台说明](docs/management.zh-CN.md)。 + ### 界面语言 WebUI 从 `webui/js/i18n.js` 加载翻译,内置 **简体中文**(默认)、**English**、**Tiếng Việt** 和 **Italiano**。原始简体中文文案保留在 `index.html` 和 `webui/js/` 中,并始终作为缺少翻译时的回退,因此新增语言不会覆盖原文。 diff --git a/docs/management.zh-CN.md b/docs/management.zh-CN.md index bcdaa2e..64b3343 100644 --- a/docs/management.zh-CN.md +++ b/docs/management.zh-CN.md @@ -7,13 +7,27 @@ 管理页面 `/#model-quotas`,登录后读取 `GET /api/model-quotas`。 - 模型来自网关同步的 OpenCode Go 目录,支持搜索和复制模型 ID。 -- 额度由网关使用已配置的 Go Key 查询 `https://opencode.ai/zen/go/v1/usage`。浏览器不会收到上游 Key。 +- 手动 Go Key 的额度由网关查询 `https://opencode.ai/zen/go/v1/usage`。浏览器不会收到上游 Key;OAuth 订阅账户的额度当前不可查询,显示未知,不复用其他 Key 的数据。 - 显示 5 小时、每周、每月窗口的剩余百分比和重置时间。接口只提供共享套餐窗口,不提供独立的逐模型余额,不推算金额或可用次数。多个 Key 的额度不相加。 - 成功响应缓存 60 秒,失败缓存 15 秒;失败时保留上次成功结果并明确标记历史数据。没有成功数据时显示未知。 - 页面打开期间每 60 秒查询一次;离开页面或隐藏浏览器时停止周期查询。手动刷新也受服务端缓存约束。 依据:[OpenCode 官方额度接口源码](https://github.com/anomalyco/opencode/blob/dev/packages/console/app/src/routes/zen/go/v1/usage.ts)。该接口未列入正式 API 文档,若响应格式变化,会显示查询异常而非虚构额度。 +## Go 订阅登录(Device OAuth) + +在同一页面的「Go 订阅登录」卡片点击「浏览器登录 Go 订阅」。页面显示官方 OpenCode 验证链接和 `user_code`;自行打开链接、输入代码,并确认这是自己发起的授权。浏览器不自动跳转,也不要求粘贴 Token、读取本机凭证文件或提交回调 URL。WebUI 按服务端给出的间隔请求后端轮询,授权交换和凭证刷新均由后端完成。 + +- 多个组织可选时,自动轮询暂停,选择订阅所在组织并点击「连接所选组织」。授权失败或过期可重新开始;「取消本次登录」只清除待完成的登录,不断开已保存的连接。 +- 离开页面或隐藏浏览器时停止自动轮询,返回页面后重新读取状态;未过期的待完成登录可继续。退出管理 Session 会取消该 Session 的待完成登录,但不删除已保存的订阅连接。 +- 成功连接后,配置与模型视图自动刷新。连接存于本地配置的 `go_subscription`,包含访问凭证及刷新凭证,后端按需自动刷新并持久化。配置及其备份包含敏感信息,应限制访问,不要上传或放入日志;WebUI 仅显示安全账户状态,不显示这些凭证。需重新登录时页面会提示,不把保留的连接误标为健康。 +- 「断开 Go 订阅登录」仅删除本地保存的连接,不撤销 OpenCode 官方会话。手动 `go_keys` 始终保留,但 OAuth 连接存在期间不作备用通道,包括授权失效或订阅路由不可用时;断开后恢复原有手动 Key 路由。 +- OAuth 只接入已确认的官方 Go 订阅路由,不自动改用余额或按量付费(PAYG)通道。OAuth 额度显示未知,不根据模型数量、成功响应或其他 Key 的共享窗口推算剩余量。 + +管理接口均要求现有管理 Session,写操作还需 CSRF:`GET /api/go/auth` 读取安全状态,`POST /api/go/auth/start` 开始登录,`POST /api/go/auth/poll` 携带登录 `id`(选组织时另带 `organization_id`)检查或完成授权,`DELETE /api/go/auth` 取消待完成登录,`DELETE /api/go/connection` 移除本地连接。这些接口不向浏览器返回访问或刷新凭证。 + +协议参考上游固定源码快照:[v2 `4617210822bdbb31e5749751afbfb4584ccedac8`](https://github.com/anomalyco/opencode/tree/4617210822bdbb31e5749751afbfb4584ccedac8)、[dev `7745079647b65036fe142e09ccd8623b25be1878`](https://github.com/anomalyco/opencode/tree/7745079647b65036fe142e09ccd8623b25be1878)。源码对比与本地模拟检查不代表真实订阅授权或真实推理已经验证;上游授权流程、组织权限及可用路由变化时,可能需要重新登录或更新实现。 + ## API Key 管理 管理页面 `/#api-keys`,支持列表、生成、自定义、重命名、启用、停用、删除和创建后复制环境变量。 diff --git a/internal/admin/auth.go b/internal/admin/auth.go index f6b6439..7f4d053 100644 --- a/internal/admin/auth.go +++ b/internal/admin/auth.go @@ -7,6 +7,7 @@ import ( "crypto/subtle" "encoding/base64" "encoding/hex" + "errors" "net" "net/http" "net/url" @@ -105,6 +106,7 @@ func (a *Server) handleLogout(w http.ResponseWriter, r *http.Request) { a.mu.Lock() delete(a.sessions, tokenDigest(cookie.Value)) a.mu.Unlock() + a.cancelGoAuth(tokenDigest(cookie.Value)) } http.SetCookie(w, &http.Cookie{Name: adminCookieName, Value: "", Path: "/", HttpOnly: true, SameSite: http.SameSiteStrictMode, MaxAge: -1, Secure: requestIsSecure(r)}) w.WriteHeader(http.StatusNoContent) @@ -194,19 +196,26 @@ func (a *Server) handleAccount(w http.ResponseWriter, r *http.Request) { writeAdminError(w, http.StatusForbidden, "verification_failed", "current password is incorrect") return } - if username := strings.TrimSpace(input.Username); username != "" { - cfg.WebUI.Username = username - } - if input.NewPassword != "" { - cfg.WebUI.Password = input.NewPassword - } - if _, err := a.manager.Apply(cfg, true); err != nil { + _, err := a.manager.Update(func(latest *config.Config) error { + if !a.goAuthSessionValid(goAuthOwner(r), *latest) || !config.VerifyPassword(latest.WebUI.PasswordHash, input.CurrentPassword) { + return errors.New("management account changed; sign in again") + } + if username := strings.TrimSpace(input.Username); username != "" { + latest.WebUI.Username = username + } + if input.NewPassword != "" { + latest.WebUI.Password = input.NewPassword + } + return nil + }) + if err != nil { writeAdminError(w, http.StatusBadRequest, "account_update_failed", err.Error()) return } a.mu.Lock() a.sessions = make(map[string]adminSession) a.mu.Unlock() + a.cancelGoAuth("") http.SetCookie(w, &http.Cookie{Name: adminCookieName, Value: "", Path: "/", HttpOnly: true, SameSite: http.SameSiteStrictMode, MaxAge: -1, Secure: requestIsSecure(r)}) a.logger.Info("admin account updated", "component", "auth", "event", "account_updated", "client_ip", clientIP(r)) httpx.WriteJSON(w, http.StatusOK, map[string]any{"updated": true, "reauthenticate": true}) diff --git a/internal/admin/go_auth.go b/internal/admin/go_auth.go new file mode 100644 index 0000000..c1461d3 --- /dev/null +++ b/internal/admin/go_auth.go @@ -0,0 +1,382 @@ +package admin + +import ( + "context" + "errors" + "net/http" + "slices" + "time" + + "opencode2api/internal/config" + "opencode2api/internal/goauth" + "opencode2api/internal/httpx" +) + +type goAuthAttempt struct { + ID string + Owner string + Status string + Device goauth.Device + Credential *goauth.Credential + Organizations []goauth.Organization + Expires time.Time + NextPoll time.Time + Busy bool + Cancel context.CancelFunc + Error string +} + +type goAuthPendingView struct { + ID string `json:"id"` + Status string `json:"status"` + VerificationURL string `json:"verification_url,omitempty"` + UserCode string `json:"user_code,omitempty"` + ExpiresAt time.Time `json:"expires_at"` + IntervalSeconds int `json:"interval_seconds"` + RetryAfterSeconds int `json:"retry_after_seconds"` + Organizations []goauth.Organization `json:"organizations,omitempty"` + Error string `json:"error,omitempty"` +} + +type goAccountView struct { + Email string `json:"email"` + Organization string `json:"organization"` + ExpiresAt time.Time `json:"expires_at"` + Models int `json:"models"` + NeedsLogin bool `json:"needs_login"` + Error string `json:"error,omitempty"` +} + +type goAuthView struct { + Connected bool `json:"connected"` + Account *goAccountView `json:"account,omitempty"` + Pending *goAuthPendingView `json:"pending,omitempty"` +} + +func goAuthOwner(r *http.Request) string { + cookie, err := r.Cookie(adminCookieName) + if err != nil || cookie.Value == "" { + return "" + } + return tokenDigest(cookie.Value) +} + +func (a *Server) goAuthSessionValid(owner string, cfg config.Config) bool { + a.mu.Lock() + session, ok := a.sessions[owner] + a.mu.Unlock() + return ok && time.Now().Before(session.Expires) && session.Username == cfg.WebUI.Username && session.AuthVersion == config.Fingerprint(cfg.WebUI.PasswordHash) +} + +func (a *Server) cleanupGoAuthLocked() { + now := time.Now() + cfg := a.manager.Config() + for owner, attempt := range a.goAuth { + if !now.Before(attempt.Expires) || !a.goAuthSessionValid(owner, cfg) { + if attempt.Cancel != nil { + attempt.Cancel() + } + delete(a.goAuth, owner) + } + } +} + +func (a *Server) cancelGoAuth(owner string) { + a.goAuthMu.Lock() + defer a.goAuthMu.Unlock() + for candidate, attempt := range a.goAuth { + if owner != "" && candidate != owner { + continue + } + if attempt.Cancel != nil { + attempt.Cancel() + } + delete(a.goAuth, candidate) + } +} + +func (a *Server) goAuthViewLocked(owner string) goAuthView { + view := goAuthView{} + connection := a.manager.Config().GoSubscription + if connection != nil { + view.Connected = true + view.Account = &goAccountView{ + Email: connection.Credential.Email, Organization: connection.Credential.OrganizationName, + ExpiresAt: connection.Credential.ExpiresAt, Models: len(connection.Routes), NeedsLogin: connection.NeedsLogin, + } + if connection.NeedsLogin { + view.Account.Error = "Go 订阅授权已失效或组织发生变化,请重新登录。" + } + } + if attempt := a.goAuth[owner]; attempt != nil { + wait := max(0, int(time.Until(attempt.NextPoll).Seconds()+0.999)) + view.Pending = &goAuthPendingView{ + ID: attempt.ID, Status: attempt.Status, ExpiresAt: attempt.Expires, + VerificationURL: attempt.Device.VerificationURI, UserCode: attempt.Device.UserCode, + IntervalSeconds: max(1, int(attempt.Device.Interval.Seconds())), RetryAfterSeconds: wait, + Organizations: append([]goauth.Organization(nil), attempt.Organizations...), Error: attempt.Error, + } + } + return view +} + +func (a *Server) handleGoAuthStatus(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Cache-Control", "no-store") + a.goAuthMu.Lock() + a.cleanupGoAuthLocked() + view := a.goAuthViewLocked(goAuthOwner(r)) + a.goAuthMu.Unlock() + httpx.WriteJSON(w, http.StatusOK, view) +} + +func (a *Server) handleGoAuthStart(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Cache-Control", "no-store") + var input struct{} + if err := decodeAdminJSON(w, r, &input); err != nil { + writeAdminError(w, http.StatusBadRequest, "invalid_request", "登录请求格式无效") + return + } + owner := goAuthOwner(r) + session, ok := sessionFromContext(r) + if !ok || owner == "" { + writeAdminError(w, http.StatusUnauthorized, "authentication_required", "login required") + return + } + id, err := randomToken(24) + if err != nil { + writeAdminError(w, http.StatusInternalServerError, "internal_error", "无法创建订阅登录") + return + } + ctx, cancel := context.WithTimeout(r.Context(), 20*time.Second) + defer cancel() + a.goAuthMu.Lock() + a.cleanupGoAuthLocked() + if existing := a.goAuth[owner]; existing != nil && existing.Status != "failed" { + view := a.goAuthViewLocked(owner) + a.goAuthMu.Unlock() + httpx.WriteJSON(w, http.StatusOK, view) + return + } + if len(a.goAuth) >= 32 && a.goAuth[owner] == nil { + a.goAuthMu.Unlock() + writeAdminError(w, http.StatusTooManyRequests, "login_capacity", "待完成的订阅登录过多,请稍后重试") + return + } + attempt := &goAuthAttempt{ID: id, Owner: owner, Status: "starting", Expires: minTime(session.Expires, time.Now().Add(15*time.Minute)), Busy: true, Cancel: cancel} + if a.goAuth == nil { + a.goAuth = make(map[string]*goAuthAttempt) + } + a.goAuth[owner] = attempt + a.goAuthMu.Unlock() + device, err := a.goAuthClient.Start(ctx) + a.goAuthMu.Lock() + if a.goAuth[owner] != attempt || !time.Now().Before(attempt.Expires) || !a.goAuthSessionValid(owner, a.manager.Config()) { + a.goAuthMu.Unlock() + writeAdminError(w, http.StatusConflict, "login_canceled", "订阅登录已取消或管理会话已失效") + return + } + attempt.Busy, attempt.Cancel = false, nil + if err != nil { + attempt.Status, attempt.Error = "failed", safeGoAuthError(err) + } else { + attempt.Device, attempt.Status = device, "pending" + attempt.Expires = minTime(attempt.Expires, device.ExpiresAt) + attempt.NextPoll = time.Now().Add(device.Interval) + } + view := a.goAuthViewLocked(owner) + a.goAuthMu.Unlock() + httpx.WriteJSON(w, http.StatusOK, view) +} + +func (a *Server) handleGoAuthPoll(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Cache-Control", "no-store") + var input struct { + ID string `json:"id"` + OrganizationID string `json:"organization_id,omitempty"` + } + if err := decodeAdminJSON(w, r, &input); err != nil || input.ID == "" { + writeAdminError(w, http.StatusBadRequest, "invalid_request", "登录请求格式无效") + return + } + owner := goAuthOwner(r) + ctx, cancel := context.WithTimeout(r.Context(), 45*time.Second) + defer cancel() + a.goAuthMu.Lock() + a.cleanupGoAuthLocked() + attempt := a.goAuth[owner] + if attempt == nil || attempt.ID != input.ID { + a.goAuthMu.Unlock() + writeAdminError(w, http.StatusNotFound, "login_not_found", "订阅登录已过期或不存在,请重新开始") + return + } + if attempt.Busy || attempt.Status == "failed" || time.Now().Before(attempt.NextPoll) { + view := a.goAuthViewLocked(owner) + a.goAuthMu.Unlock() + httpx.WriteJSON(w, http.StatusOK, view) + return + } + if input.OrganizationID != "" && !slices.ContainsFunc(attempt.Organizations, func(org goauth.Organization) bool { return org.ID == input.OrganizationID }) { + a.goAuthMu.Unlock() + writeAdminError(w, http.StatusBadRequest, "invalid_organization", "只能选择本次授权允许的组织") + return + } + if attempt.Status == "choosing_org" && input.OrganizationID == "" { + view := a.goAuthViewLocked(owner) + a.goAuthMu.Unlock() + httpx.WriteJSON(w, http.StatusOK, view) + return + } + var credential *goauth.Credential + if attempt.Credential != nil { + copied := *attempt.Credential + credential = &copied + } + organizations := append([]goauth.Organization(nil), attempt.Organizations...) + deviceCode := attempt.Device.DeviceCode + attempt.Busy, attempt.Cancel, attempt.Status = true, cancel, "authorizing" + a.goAuthMu.Unlock() + var err error + if credential == nil { + var token goauth.Token + token, err = a.goAuthClient.Poll(ctx, deviceCode) + if err == nil { + var user goauth.User + user, organizations, err = a.goAuthClient.Identify(ctx, token) + if err == nil { + credential = &goauth.Credential{ + AccessToken: token.AccessToken, RefreshToken: token.RefreshToken, ExpiresAt: token.ExpiresAt, + AccountID: user.ID, Email: user.Email, OrganizationID: token.OrganizationID, + } + } + } + } + if err == nil && credential.OrganizationID == "" { + switch { + case input.OrganizationID != "": + credential.OrganizationID = input.OrganizationID + case len(organizations) == 1: + credential.OrganizationID = organizations[0].ID + case len(organizations) > 1: + a.goAuthMu.Lock() + if a.goAuth[owner] == attempt && time.Now().Before(attempt.Expires) && a.goAuthSessionValid(owner, a.manager.Config()) { + attempt.Credential, attempt.Organizations = credential, organizations + attempt.Expires = minTime(attempt.Expires, credential.ExpiresAt) + attempt.Status, attempt.Busy, attempt.Cancel = "choosing_org", false, nil + attempt.NextPoll = time.Time{} + view := a.goAuthViewLocked(owner) + a.goAuthMu.Unlock() + httpx.WriteJSON(w, http.StatusOK, view) + } else { + a.goAuthMu.Unlock() + writeAdminError(w, http.StatusConflict, "login_canceled", "订阅登录已取消") + } + return + } + } + if credential != nil { + for _, organization := range organizations { + if organization.ID == credential.OrganizationID { + credential.OrganizationName = organization.Name + break + } + } + } + var routes map[string]goauth.Route + if err == nil { + routes, err = a.goAuthClient.Discover(ctx, *credential) + } + a.goAuthMu.Lock() + if a.goAuth[owner] != attempt || !time.Now().Before(attempt.Expires) || !a.goAuthSessionValid(owner, a.manager.Config()) { + a.goAuthMu.Unlock() + writeAdminError(w, http.StatusConflict, "login_canceled", "订阅登录已取消或管理会话已失效") + return + } + attempt.Busy, attempt.Cancel = false, nil + if err != nil { + var oauthError *goauth.OAuthError + if errors.As(err, &oauthError) && (oauthError.Code == "authorization_pending" || oauthError.Code == "slow_down") { + if oauthError.Code == "slow_down" { + attempt.Device.Interval = min(attempt.Device.Interval+5*time.Second, 5*time.Minute) + } + attempt.Status = "pending" + attempt.NextPoll = time.Now().Add(attempt.Device.Interval) + } else { + attempt.Status, attempt.Error, attempt.Credential = "failed", safeGoAuthError(err), nil + attempt.Device.DeviceCode = "" + } + view := a.goAuthViewLocked(owner) + a.goAuthMu.Unlock() + httpx.WriteJSON(w, http.StatusOK, view) + return + } + connection := &goauth.Connection{Credential: *credential, Routes: routes} + _, err = a.manager.Update(func(cfg *config.Config) error { + if ctx.Err() != nil || !time.Now().Before(attempt.Expires) || !time.Now().Before(credential.ExpiresAt) || !a.goAuthSessionValid(owner, *cfg) { + return errors.New("subscription login is no longer active") + } + if cfg.GoSubscription != nil { + connection.Proxy = cfg.GoSubscription.Proxy + } + cfg.GoSubscription = connection + return nil + }) + if err != nil { + attempt.Status, attempt.Error, attempt.Credential = "failed", "无法安全保存订阅登录,请检查配置后重新登录。", nil + attempt.Device.DeviceCode = "" + } else { + delete(a.goAuth, owner) + a.logger.Info("Go subscription connected", "component", "auth", "event", "go_subscription_connected") + } + view := a.goAuthViewLocked(owner) + a.goAuthMu.Unlock() + httpx.WriteJSON(w, http.StatusOK, view) +} + +func (a *Server) handleGoAuthCancel(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Cache-Control", "no-store") + a.cancelGoAuth(goAuthOwner(r)) + a.handleGoAuthStatus(w, r) +} + +func (a *Server) handleGoDisconnect(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Cache-Control", "no-store") + owner := goAuthOwner(r) + a.goAuthMu.Lock() + _, err := a.manager.Update(func(cfg *config.Config) error { + if !a.goAuthSessionValid(owner, *cfg) { + return errors.New("management session is no longer active") + } + cfg.GoSubscription = nil + return nil + }) + if err != nil { + a.goAuthMu.Unlock() + writeAdminError(w, http.StatusBadRequest, "disconnect_failed", "无法断开订阅;请确保保留至少一个上游 Key 或启用匿名通道。") + return + } + for candidate, attempt := range a.goAuth { + if attempt.Cancel != nil { + attempt.Cancel() + } + delete(a.goAuth, candidate) + } + a.logger.Info("Go subscription disconnected locally", "component", "auth", "event", "go_subscription_disconnected") + view := a.goAuthViewLocked(owner) + a.goAuthMu.Unlock() + httpx.WriteJSON(w, http.StatusOK, view) +} + +func safeGoAuthError(err error) string { + var oauthError *goauth.OAuthError + if errors.As(err, &oauthError) { + return oauthError.Error() + } + return "订阅授权未完成或请求已取消,请重新开始。" +} + +func minTime(first, second time.Time) time.Time { + if first.Before(second) { + return first + } + return second +} diff --git a/internal/admin/model_quotas.go b/internal/admin/model_quotas.go index 060cc5c..c196b10 100644 --- a/internal/admin/model_quotas.go +++ b/internal/admin/model_quotas.go @@ -147,16 +147,28 @@ func (a *Server) handleModelQuotas(w http.ResponseWriter, r *http.Request) { cfg := a.manager.Config() endpoint := strings.TrimRight(cfg.Upstream.Go, "/") + "/v1/usage" accounts := make([]quotaAccount, len(cfg.GoKeys)) + if connection := cfg.GoSubscription; connection != nil { + accounts = []quotaAccount{{ + ID: config.Fingerprint(connection.Credential.AccountID + "\x00" + connection.Credential.OrganizationID), + Display: "Go subscription (OAuth)", Status: "unavailable", CheckedAt: time.Now().UTC(), + Error: "OpenCode 未提供已验证的 OAuth 订阅额度接口,额度保持未知。", + }} + endpoint = "" + } // Coalesce refreshes from multiple browser tabs; at most four upstream // queries run at a time. a.quotaMu.Lock() if a.quotaCache == nil { a.quotaCache = map[string]quotaCacheEntry{} } - entries := make([]quotaCacheEntry, len(cfg.GoKeys)) + keys := cfg.GoKeys + if cfg.GoSubscription != nil { + keys = nil + } + entries := make([]quotaCacheEntry, len(keys)) var wg sync.WaitGroup sem := make(chan struct{}, 4) - for i, key := range cfg.GoKeys { + for i, key := range keys { cacheID := endpoint + "|" + config.Fingerprint(key) previous := a.quotaCache[cacheID] if time.Now().Before(previous.Expires) { @@ -178,7 +190,7 @@ func (a *Server) handleModelQuotas(w http.ResponseWriter, r *http.Request) { } wg.Wait() cache := map[string]quotaCacheEntry{} - for i, key := range cfg.GoKeys { + for i, key := range keys { cache[endpoint+"|"+config.Fingerprint(key)] = entries[i] accounts[i] = entries[i].Account } @@ -196,9 +208,13 @@ func (a *Server) handleModelQuotas(w http.ResponseWriter, r *http.Request) { models = append(models, modelView{ID: model.Model, Protocol: string(protocol)}) } } + note := "OpenCode 返回套餐共享额度,未提供逐模型独立余额;多个 Go Key 可能属于同一套餐,不能相加。百分比由上游取整。" + if cfg.GoSubscription != nil { + note = "OAuth 订阅使用官方 Go 推理路由;未提供已验证的订阅额度接口,不查询手动 Go Key 或按量计费余额。" + } httpx.WriteJSON(w, 200, map[string]any{ "models": models, "accounts": accounts, "scope": "shared_subscription", "source": endpoint, "cache_seconds": 60, "catalog": a.manager.Resources().Models, - "note": "OpenCode 返回套餐共享额度,未提供逐模型独立余额;多个 Go Key 可能属于同一套餐,不能相加。百分比由上游取整。", + "note": note, }) } diff --git a/internal/admin/server.go b/internal/admin/server.go index 81b84bb..64b5388 100644 --- a/internal/admin/server.go +++ b/internal/admin/server.go @@ -17,6 +17,7 @@ import ( "opencode2api/internal/buildinfo" "opencode2api/internal/config" "opencode2api/internal/gateway" + "opencode2api/internal/goauth" "opencode2api/internal/httpx" "opencode2api/internal/telemetry" "opencode2api/webui" @@ -37,6 +38,9 @@ type Server struct { lastInference *DebugInferenceResult quotaMu sync.Mutex quotaCache map[string]quotaCacheEntry + goAuthMu sync.Mutex + goAuth map[string]*goAuthAttempt + goAuthClient *goauth.Client } // New returns a Server for manager, reporting to monitor and logs. @@ -44,6 +48,7 @@ func New(manager *gateway.RuntimeController, monitor *telemetry.Metrics, logs *t return &Server{ manager: manager, monitor: monitor, logs: logs, logger: logger, sessions: make(map[string]adminSession), attempts: make(map[string]loginWindow), debugAttempts: make(map[string]loginWindow), + goAuth: make(map[string]*goAuthAttempt), goAuthClient: goauth.NewClient(nil), } } @@ -72,6 +77,11 @@ func (a *Server) Handler() http.Handler { mux.Handle("PUT /api/rotation", a.authenticate(a.csrf(http.HandlerFunc(a.handleSaveRotation)))) mux.Handle("POST /api/rotation/current", a.authenticate(a.csrf(http.HandlerFunc(a.handleSelectRotation)))) mux.Handle("GET /api/model-quotas", a.authenticate(http.HandlerFunc(a.handleModelQuotas))) + mux.Handle("GET /api/go/auth", a.authenticate(http.HandlerFunc(a.handleGoAuthStatus))) + mux.Handle("POST /api/go/auth/start", a.authenticate(a.csrf(http.HandlerFunc(a.handleGoAuthStart)))) + mux.Handle("POST /api/go/auth/poll", a.authenticate(a.csrf(http.HandlerFunc(a.handleGoAuthPoll)))) + mux.Handle("DELETE /api/go/auth", a.authenticate(a.csrf(http.HandlerFunc(a.handleGoAuthCancel)))) + mux.Handle("DELETE /api/go/connection", a.authenticate(a.csrf(http.HandlerFunc(a.handleGoDisconnect)))) mux.Handle("GET /api/api-keys", a.authenticate(http.HandlerFunc(a.handleListAPIKeys))) mux.Handle("POST /api/api-keys", a.authenticate(a.csrf(http.HandlerFunc(a.handleCreateAPIKey)))) mux.Handle("PATCH /api/api-keys/{id}", a.authenticate(a.csrf(http.HandlerFunc(a.handleUpdateAPIKey)))) @@ -254,13 +264,31 @@ func (a *Server) handlePutConfig(w http.ResponseWriter, r *http.Request) { candidate := config.Config{ ServerKeyMetadata: current.ServerKeyMetadata, Rotation: current.Rotation, + GoSubscription: current.GoSubscription, Listen: update.Listen, ServerKeys: serverKeys, ZenKeys: zenKeys, GoKeys: goKeys, Anonymous: update.Anonymous, Warp: update.Warp, Proxies: proxies, ProxyFile: update.ProxyFile, ProxyBindings: proxyBindings, 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}, } - result, err := a.manager.Apply(candidate, true) + result, err := a.manager.Update(func(latest *config.Config) error { + if !a.goAuthSessionValid(goAuthOwner(r), *latest) { + return errors.New("management session is no longer active") + } + candidate.GoSubscription = latest.GoSubscription + candidate.ServerKeyMetadata = latest.ServerKeyMetadata + candidate.Rotation = latest.Rotation + candidate.WebUI.Username = latest.WebUI.Username + candidate.WebUI.PasswordHash = latest.WebUI.PasswordHash + if update.Reasoning == nil { + candidate.Reasoning = latest.Reasoning + } + if update.ProxyBindings == nil { + candidate.ProxyBindings = latest.ProxyBindings + } + *latest = candidate + return nil + }) if err != nil { a.logger.Warn("configuration update rejected", "component", "config", "event", "config_rejected", "error", err) writeAdminError(w, http.StatusBadRequest, "configuration_rejected", err.Error()) diff --git a/internal/config/config.go b/internal/config/config.go index 5e419fa..40384d3 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -13,6 +13,7 @@ import ( "time" "unicode" + "opencode2api/internal/goauth" "opencode2api/internal/jsonutil" wire "opencode2api/internal/protocol" "opencode2api/internal/warp" @@ -33,6 +34,7 @@ type Config struct { ServerKeyMetadata map[string]ServerKeyMetadata `json:"server_key_metadata,omitempty"` ZenKeys []string `json:"zen_keys"` GoKeys []string `json:"go_keys"` + GoSubscription *goauth.Connection `json:"go_subscription,omitempty"` Anonymous bool `json:"anonymous"` Warp WarpConfig `json:"warp"` Proxies []string `json:"proxies"` @@ -377,6 +379,26 @@ func Normalize(path string, cfg Config) (Config, error) { if err := resolveProxyFiles(path, &cfg); err != nil { return Config{}, err } + if cfg.GoSubscription != nil { + connection := cloneGoSubscription(cfg.GoSubscription) + if err := connection.Validate(); err != nil { + return Config{}, errors.New("go_subscription contains an invalid credential or unsupported subscription route") + } + connection.Proxy = strings.TrimSpace(connection.Proxy) + if connection.Proxy != "" { + matched := false + for _, proxy := range cfg.RuntimeProxies() { + if proxy == connection.Proxy { + matched = true + break + } + } + if !matched { + return Config{}, errors.New("go_subscription.proxy must name a configured proxy") + } + } + cfg.GoSubscription = connection + } if cfg.Prefer != TierZen && cfg.Prefer != TierGo { return Config{}, errors.New("prefer must be \"zen\" or \"go\"") } @@ -412,7 +434,7 @@ func Normalize(path string, cfg Config) (Config, error) { if cfg.FirstEnabledServerKey() == "" { return Config{}, errors.New("at least one server key must remain enabled") } - if !cfg.Anonymous && len(cfg.ZenKeys) == 0 && len(cfg.GoKeys) == 0 { + if !cfg.Anonymous && len(cfg.ZenKeys) == 0 && len(cfg.GoKeys) == 0 && cfg.GoSubscription == nil { return Config{}, errors.New("zen_keys or go_keys must contain at least one upstream key unless anonymous is enabled") } if cfg.Retry.MaxAttempts < 1 { @@ -607,6 +629,7 @@ func Clone(cfg Config) Config { cfg.ServerKeyMetadata = metadata cfg.ZenKeys = append([]string(nil), cfg.ZenKeys...) cfg.GoKeys = append([]string(nil), cfg.GoKeys...) + cfg.GoSubscription = cloneGoSubscription(cfg.GoSubscription) cfg.Proxies = append([]string(nil), cfg.Proxies...) cfg.effectiveProxies = append([]string(nil), cfg.effectiveProxies...) if cfg.Upstream.PromptEnvironment != nil { @@ -641,6 +664,18 @@ func Clone(cfg Config) Config { return cfg } +func cloneGoSubscription(source *goauth.Connection) *goauth.Connection { + if source == nil { + return nil + } + connection := *source + connection.Routes = make(map[string]goauth.Route, len(source.Routes)) + for model, route := range source.Routes { + connection.Routes[model] = route + } + return &connection +} + // normalizeProxyBindings validates and canonicalizes explicit per-key proxy // bindings. Keys are mapped to their 16-hex fingerprint so secrets are never // stored twice, and target proxies must match a valid runtime proxy (or "direct"). diff --git a/internal/config/secrets.go b/internal/config/secrets.go index 6969e40..8137b82 100644 --- a/internal/config/secrets.go +++ b/internal/config/secrets.go @@ -66,6 +66,12 @@ func (r *Redactor) Replace(cfg Config) { values = append(values, cfg.ServerKeys...) values = append(values, cfg.ZenKeys...) values = append(values, cfg.GoKeys...) + if cfg.GoSubscription != nil { + values = append(values, cfg.GoSubscription.Credential.AccessToken, cfg.GoSubscription.Credential.RefreshToken) + if cfg.GoSubscription.Proxy != "" { + values = append(values, cfg.GoSubscription.Proxy) + } + } if cfg.WebUI.Password != "" { values = append(values, cfg.WebUI.Password) } diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go index 982b299..f7fe982 100644 --- a/internal/gateway/gateway.go +++ b/internal/gateway/gateway.go @@ -28,6 +28,7 @@ import ( "time" "opencode2api/internal/config" + "opencode2api/internal/goauth" "opencode2api/internal/httpx" "opencode2api/internal/identity" "opencode2api/internal/jsonutil" @@ -95,7 +96,9 @@ type Gateway struct { // anonymous cursor. Zero uses freeTierBlockTTL. freeTierBlock time.Duration // refreshMu prevents overlapping catalog refreshes across concurrent or scheduled callers. - refreshMu sync.Mutex + refreshMu sync.Mutex + resolveGoSubscription func(context.Context) (*goauth.Connection, error) + onGoSubscriptionUnauthorized func(context.Context, goauth.Credential) } // New builds a Gateway for cfg: one proxy transport per runtime proxy (a @@ -121,14 +124,18 @@ func New(cfg config.Config, logger *slog.Logger, monitor *telemetry.Metrics, war if err != nil { return nil, fmt.Errorf("zen node pool: %w", err) } - goNodes, err := nodePool(cfg.GoKeys, transports, cooldown, cfg.ProxyBindings) + goKeys := cfg.GoKeys + if cfg.GoSubscription != nil { + goKeys = nil + } + goNodes, err := nodePool(goKeys, transports, cooldown, cfg.ProxyBindings) if err != nil { return nil, fmt.Errorf("go node pool: %w", err) } catalog := models.Catalog(cfg.Prefer, cfg.Models.Protocols) catalog.SetRefreshInterval(time.Duration(cfg.Models.RefreshSeconds) * time.Second) catalog.SetFreeOnly(cfg.Models.FreeOnly) - return &Gateway{ + gateway := &Gateway{ cfg: cfg, rotation: rotationManager, logger: logger, @@ -141,7 +148,9 @@ func New(cfg config.Config, logger *slog.Logger, monitor *telemetry.Metrics, war monitor: monitor, attemptTimeout: attemptDeadline(cfg), freeTierBlock: time.Duration(cfg.Performance.FreeTierBlockSeconds) * time.Second, - }, nil + } + gateway.restoreGoSubscriptionCatalog() + return gateway, nil } // anonymousBackoffFromConfig converts the configured hours into the breaker's @@ -276,7 +285,11 @@ func (g *Gateway) handleInference(external wire.Protocol) http.HandlerFunc { g.handleRotation(w, r, external, payload, id, model) return } - if !g.catalog.Supported(model) { + subscriptionModel := false + if g.cfg.GoSubscription != nil { + _, subscriptionModel = g.cfg.GoSubscription.Routes[model] + } + if !subscriptionModel && !g.catalog.Supported(model) { // A model the catalog has never heard of is a bad model NAME: 404 // tells a client to pick a different model. A model the catalog // knows but cannot serve is a capability or routing problem, and @@ -292,13 +305,18 @@ func (g *Gateway) handleInference(external wire.Protocol) http.HandlerFunc { } return } - route, err := g.catalog.Route(model, len(g.cfg.ZenKeys) > 0, len(g.cfg.GoKeys) > 0, g.cfg.Anonymous) + route, err := g.routeForModel(model, "") if override, selected := debugKeyOverrideFrom(r.Context()); selected { // A per-key diagnostic must not silently be served by another key, // another tier or the anonymous lane. - route, err = g.catalog.RouteForTier(model, override.Tier, len(g.cfg.ZenKeys) > 0, len(g.cfg.GoKeys) > 0) + route, err = g.routeForModel(model, override.Tier) } if err != nil { + var oauthError *goauth.OAuthError + if errors.As(err, &oauthError) { + wire.WriteError(w, external, http.StatusServiceUnavailable, oauthError.Error(), "subscription_auth_error", "") + return + } wire.WriteError(w, external, http.StatusBadRequest, err.Error(), "invalid_request_error", "model") return } @@ -381,6 +399,11 @@ func (g *Gateway) handleInference(external wire.Protocol) http.HandlerFunc { wire.WriteError(w, external, status, message, code, ids.Request) return } + var subscriptionError *goauth.OAuthError + if errors.As(err, &subscriptionError) { + wire.WriteError(w, external, http.StatusServiceUnavailable, subscriptionError.Error(), "subscription_auth_error", ids.Request) + return + } // Every exit this request could use is under the free tier's IP // block. A 502 would read as a transient upstream fault and invite // the client to retry into the same penalty, so answer with the @@ -515,7 +538,7 @@ func (g *Gateway) handleSystemOne(w http.ResponseWriter, r *http.Request) { } return } - route, err := g.catalog.Route(model, len(g.cfg.ZenKeys) > 0, len(g.cfg.GoKeys) > 0, g.cfg.Anonymous) + route, err := g.routeForModel(model, "") if err != nil { wire.WriteError(w, wire.SystemOne, http.StatusBadRequest, err.Error(), "invalid_request_error", "model") return @@ -649,6 +672,13 @@ func (g *Gateway) prepareRouteBodies(from wire.Protocol, route models.Route, inp baseURL := g.cfg.Upstream.Zen if tier == config.TierGo { baseURL = g.cfg.Upstream.Go + if g.cfg.GoSubscription != nil { + subscriptionRoute, ok := g.cfg.GoSubscription.Routes[route.ID] + if !ok { + return nil, errors.New("model is not included in the connected Go subscription") + } + baseURL = subscriptionRoute.BaseURL + } } upstreamPayload, err := wire.PrepareRequest(from, protocol, input, baseURL) if err != nil { diff --git a/internal/gateway/gosubscription.go b/internal/gateway/gosubscription.go new file mode 100644 index 0000000..2d3d9b9 --- /dev/null +++ b/internal/gateway/gosubscription.go @@ -0,0 +1,372 @@ +package gateway + +import ( + "bytes" + "context" + "crypto/sha256" + "encoding/binary" + "encoding/json" + "errors" + "io" + "net/http" + "sort" + "strconv" + "strings" + "time" + + "opencode2api/internal/config" + "opencode2api/internal/goauth" + "opencode2api/internal/httpx" + "opencode2api/internal/identity" + "opencode2api/internal/models" + wire "opencode2api/internal/protocol" + "opencode2api/internal/telemetry" +) + +func (g *Gateway) goAvailable() bool { + return g.cfg.GoSubscription != nil || g.goNodes.Len() > 0 +} + +func (g *Gateway) routeForModel(model string, tier config.Tier) (models.Route, error) { + if connection := g.cfg.GoSubscription; connection != nil { + if subscriptionRoute, ok := connection.Routes[model]; ok && (tier == "" || tier == config.TierGo) { + if connection.NeedsLogin { + return models.Route{}, &goauth.OAuthError{Code: "invalid_grant"} + } + if g.cfg.Models.FreeOnly && !g.catalog.IsFreeModel(model) { + return models.Route{}, errors.New("this subscription model is excluded by models.free_only") + } + return models.Route{ + ID: model, Tier: config.TierGo, Protocol: subscriptionRoute.Protocol, + Protocols: map[config.Tier]wire.Protocol{config.TierGo: subscriptionRoute.Protocol}, + KeyTiers: []config.Tier{config.TierGo}, + }, nil + } + if tier == config.TierGo { + return models.Route{}, errors.New("model is not included in the connected Go subscription") + } + } + if tier != "" { + return g.catalog.RouteForTier(model, tier, g.zenNodes.Len() > 0, g.goAvailable()) + } + return g.catalog.Route(model, g.zenNodes.Len() > 0, g.goNodes.Len() > 0, g.cfg.Anonymous) +} + +func (g *Gateway) seedGoSubscriptionCatalog(capabilities *models.Capabilities) []string { + connection := g.cfg.GoSubscription + if connection == nil { + return nil + } + if capabilities.Protocols == nil { + capabilities.Protocols = map[config.Tier]map[string]wire.Protocol{} + } + if capabilities.Unsupported == nil { + capabilities.Unsupported = map[config.Tier]map[string]bool{} + } + protocols := make(map[string]wire.Protocol, len(connection.Routes)) + modelIDs := make([]string, 0, len(connection.Routes)) + for model, route := range connection.Routes { + modelIDs = append(modelIDs, model) + protocols[model] = route.Protocol + } + sort.Strings(modelIDs) + capabilities.Protocols[config.TierGo] = protocols + capabilities.Unsupported[config.TierGo] = map[string]bool{} + return modelIDs +} + +func (g *Gateway) restoreGoSubscriptionCatalog() { + if g.cfg.GoSubscription == nil { + return + } + capabilities := models.Capabilities{} + modelIDs := g.seedGoSubscriptionCatalog(&capabilities) + g.catalog.ReplaceWithCapabilities(nil, modelIDs, capabilities.Protocols, capabilities.Unsupported, nil) +} + +func (g *Gateway) subscriptionConnection(ctx context.Context) (*goauth.Connection, error) { + snapshot := g.cfg.GoSubscription + if snapshot == nil { + return nil, errors.New("Go subscription is not connected") + } + connection := snapshot + if g.resolveGoSubscription != nil { + resolved, err := g.resolveGoSubscription(ctx) + if err != nil { + return nil, err + } + connection = resolved + } + if connection == nil || connection.Credential.AccountID != snapshot.Credential.AccountID || connection.Credential.OrganizationID != snapshot.Credential.OrganizationID || connection.Proxy != snapshot.Proxy { + return nil, errors.New("Go subscription connection changed; retry with the current configuration") + } + if connection.NeedsLogin { + return nil, &goauth.OAuthError{Code: "invalid_grant"} + } + if err := connection.Validate(); err != nil { + return nil, err + } + if !time.Now().Before(connection.Credential.ExpiresAt) { + return nil, &goauth.OAuthError{Code: "expired_token"} + } + return connection, nil +} + +func subscriptionAccountID(connection *goauth.Connection) string { + return config.Fingerprint(connection.Credential.AccountID + "\x00" + connection.Credential.OrganizationID) +} + +func (g *Gateway) subscriptionProxy(ctx context.Context, connection *goauth.Connection, affinity string, offset int) (*proxyTransport, error) { + if g.transports == nil || len(g.transports.items) == 0 { + return nil, errProxyUnavailable + } + var pinned *proxyTransport + if selection, selected := relayOverrideFrom(ctx); selected { + var found bool + pinned, found = g.RelayProxy(selection) + if !found { + return nil, errRelayNotFound + } + } + if connection.Proxy != "" { + for _, proxy := range g.transports.items { + if proxy == nil || proxy.name != connection.Proxy { + continue + } + if pinned != nil && pinned != proxy { + return nil, errors.New("the selected relay conflicts with the Go subscription proxy binding") + } + if !proxy.healthy.Load() && !isDiagnosticRequest(ctx) { + return nil, errProxyUnavailable + } + return proxy, nil + } + return nil, errProxyUnavailable + } + if pinned != nil { + return pinned, nil + } + digest := sha256.Sum256([]byte(subscriptionAccountID(connection) + "\x00" + affinity)) + start := int(binary.LittleEndian.Uint64(digest[:8]) % uint64(len(g.transports.items))) + for step := range len(g.transports.items) { + proxy := g.transports.items[(start+offset+step)%len(g.transports.items)] + if proxy != nil && proxy.healthy.Load() { + return proxy, nil + } + } + return nil, errProxyUnavailable +} + +func (g *Gateway) goSubscriptionAttempt(ctx context.Context, route models.Route, body []byte, ids identity.RequestIDs, attempt, offset int, firstEventTimeout time.Duration) (*http.Response, error) { + connection, err := g.subscriptionConnection(ctx) + if err != nil { + return nil, err + } + subscriptionRoute, ok := connection.Routes[route.ID] + if !ok || subscriptionRoute.Protocol != route.Protocol || subscriptionRoute != g.cfg.GoSubscription.Routes[route.ID] { + return nil, errors.New("Go subscription route changed; retry with the current configuration") + } + var payload map[string]json.RawMessage + if err := json.Unmarshal(body, &payload); err != nil || payload == nil { + return nil, errors.New("invalid Go subscription request body") + } + payload["model"], err = json.Marshal(subscriptionRoute.ModelID) + if err != nil { + return nil, errors.New("invalid Go subscription model") + } + body, err = json.Marshal(payload) + if err != nil { + return nil, errors.New("invalid Go subscription request body") + } + proxy, err := g.subscriptionProxy(ctx, connection, ids.Session, offset) + if err != nil { + return nil, err + } + req, err := http.NewRequestWithContext(ctx, http.MethodPost, strings.TrimRight(subscriptionRoute.BaseURL, "/")+wire.Path(subscriptionRoute.Protocol), bytes.NewReader(body)) + if err != nil { + return nil, errors.New("invalid Go subscription endpoint") + } + req.Header.Set("Content-Type", "application/json") + req.Header.Set("Authorization", "Bearer "+connection.Credential.AccessToken) + req.Header.Set("x-opencode-session", ids.Session) + req.Header.Set("User-Agent", httpx.V2UserAgent()) + if connection.Credential.OrganizationID != "" { + req.Header.Set("x-org-id", connection.Credential.OrganizationID) + } + if route.Protocol == wire.Anthropic { + req.Header.Set("anthropic-version", "2023-06-01") + } + req.GetBody = nil + if proxy.pool { + req.Close = true + } + client := *proxy.client + client.CheckRedirect = func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse } + accountID := subscriptionAccountID(connection) + setRequestCredential(ctx, config.TierGo, accountID, "subscription", false, proxy) + setRequestShape(ctx, false, nil) + if meta := telemetry.MetaFromContext(ctx); meta != nil { + meta.Attempts = attempt + meta.Tier = string(config.TierGo) + } + started := time.Now() + resp, err := doInferenceAttempt(&client, req, firstEventTimeout, g.attemptTimeout) + if resp != nil { + sanitizeGoSubscriptionResponse(resp, connection.Credential) + if resp.StatusCode == http.StatusUnauthorized && g.onGoSubscriptionUnauthorized != nil { + g.onGoSubscriptionUnauthorized(ctx, connection.Credential) + } + } + if err != nil { + err = &goSubscriptionError{cause: err, message: redactGoSubscriptionValue(err.Error(), connection.Credential)} + } + if ctx.Err() == nil && !isDiagnosticRequest(ctx) { + g.syncProxyResult(ctx, proxy, upstreamStatus(resp), err) + } + g.recordUpstreamAttempt(ctx, route, ids, attempt, accountID, "subscription", false, proxy, resp, err, time.Since(started)) + if err != nil { + return resp, asProxyUnavailable(proxy, err) + } + return resp, nil +} + +type goSubscriptionError struct { + cause error + message string +} + +func (err *goSubscriptionError) Error() string { return err.message } +func (err *goSubscriptionError) Unwrap() error { return err.cause } + +func redactGoSubscriptionValue(value string, credential goauth.Credential) string { + secrets := []string{credential.AccessToken, credential.RefreshToken} + if len(secrets[1]) > len(secrets[0]) { + secrets[0], secrets[1] = secrets[1], secrets[0] + } + for _, secret := range secrets { + if secret == "" { + continue + } + value = strings.ReplaceAll(value, secret, "***") + encoded, _ := json.Marshal(secret) + value = strings.ReplaceAll(value, string(encoded[1:len(encoded)-1]), "***") + } + return value +} + +func sanitizeGoSubscriptionResponse(response *http.Response, credential goauth.Credential) { + if response.Header == nil { + response.Header = make(http.Header) + } + response.Request = nil + response.Status = redactGoSubscriptionValue(response.Status, credential) + if response.StatusCode/100 != 2 { + var body []byte + var readErr error + if response.Body != nil { + body, readErr = io.ReadAll(io.LimitReader(response.Body, 1<<20)) + response.Body.Close() + } + if readErr != nil || len(body) >= 1<<20 { + body = []byte(`{"error":{"message":"Go subscription upstream request was rejected"}}`) + response.Header.Set("Content-Type", "application/json") + response.Header.Del("Content-Encoding") + } else { + body = []byte(redactGoSubscriptionValue(string(body), credential)) + } + response.Body = io.NopCloser(bytes.NewReader(body)) + response.ContentLength = int64(len(body)) + response.TransferEncoding = nil + response.Header.Set("Content-Length", strconv.Itoa(len(body))) + } + for _, header := range []http.Header{response.Header, response.Trailer} { + for name, values := range header { + for index, value := range values { + values[index] = redactGoSubscriptionValue(value, credential) + } + safeName := redactGoSubscriptionValue(name, credential) + if safeName != name { + delete(header, name) + header[safeName] = append(header[safeName], values...) + } + } + } +} + +func (g *Gateway) doGoSubscriptionUpstream(ctx context.Context, route models.Route, bodies map[config.Tier][]byte, ids identity.RequestIDs, attemptOffset int) (response *http.Response, resultErr error, resultAttempts int) { + body := bodies[config.TierGo] + if len(body) == 0 { + return nil, errors.New("no prepared Go subscription request body"), 0 + } + limit := max(g.cfg.Retry.MaxAttempts, 1) + if isDiagnosticRequest(ctx) { + limit = 1 + } + var lastResponse *http.Response + var lastErr error + defer func() { + if lastResponse != nil && lastResponse != response { + httpx.DrainAndClose(lastResponse.Body) + } + }() + for attempts := 0; attempts < limit; attempts++ { + if ctx.Err() != nil { + lastErr = ctx.Err() + break + } + bufferRetryResponse(lastResponse) + resp, err := g.goSubscriptionAttempt(ctx, route, body, ids, attemptOffset+attempts+1, attempts, time.Duration(g.cfg.Performance.FirstEventTimeoutSeconds)*time.Second) + resultAttempts = attempts + 1 + lastResponse = replaceRetryResponse(lastResponse, resp) + lastErr = err + if ctx.Err() != nil { + break + } + var authorizationError *goauth.OAuthError + if errors.As(err, &authorizationError) { + return nil, err, resultAttempts + } + if resp != nil && (err == nil && resp.StatusCode/100 == 2 || resp.StatusCode < 500) { + return resp, err, resultAttempts + } + } + if errors.Is(ctx.Err(), context.Canceled) { + return nil, ctx.Err(), resultAttempts + } + if lastResponse != nil { + return lastResponse, nil, resultAttempts + } + if lastErr == nil { + lastErr = errors.New("Go subscription request could not be completed") + } + return nil, lastErr, resultAttempts +} + +func (g *Gateway) routeDiagnostic(model string, requested wire.Protocol) models.RouteDiagnostic { + diagnostic := g.catalog.Diagnostic(model, requested, g.zenNodes.Len() > 0, g.goNodes.Len() > 0, g.cfg.Anonymous) + subscriptionModel := false + if connection := g.cfg.GoSubscription; connection != nil { + subscriptionRoute, included := connection.Routes[model] + subscriptionModel, diagnostic.AvailableGo = included, included + if included { + diagnostic.NativeProtocol = subscriptionRoute.Protocol + diagnostic.NativeProtocols = map[config.Tier]wire.Protocol{config.TierGo: subscriptionRoute.Protocol} + diagnostic.ProtocolSource = "go_subscription" + diagnostic.Channel = "subscription" + diagnostic.KeyID = subscriptionAccountID(connection) + } + } + route, err := g.routeForModel(model, "") + if err != nil { + diagnostic.RouteError = err.Error() + if subscriptionModel { + diagnostic.Tier, diagnostic.Anonymous, diagnostic.KeyTiers = "", false, nil + } + return diagnostic + } + diagnostic.RouteError = "" + diagnostic.Tier, diagnostic.Anonymous = route.Tier, route.Anonymous + diagnostic.KeyTiers = route.KeyTiers + diagnostic.NativeProtocol, diagnostic.NativeProtocols = route.Protocol, route.Protocols + return diagnostic +} diff --git a/internal/gateway/gosubscription_refresh.go b/internal/gateway/gosubscription_refresh.go new file mode 100644 index 0000000..edded27 --- /dev/null +++ b/internal/gateway/gosubscription_refresh.go @@ -0,0 +1,149 @@ +package gateway + +import ( + "context" + "errors" + "time" + + "opencode2api/internal/config" + "opencode2api/internal/goauth" +) + +type goSubscriptionRefresh struct { + credential goauth.Credential + done chan struct{} + err error + retryAt time.Time +} + +func (m *RuntimeController) ResolveGoSubscription(ctx context.Context) (*goauth.Connection, error) { + for { + if err := ctx.Err(); err != nil { + return nil, err + } + m.goSubscriptionMu.Lock() + connection := m.Config().GoSubscription + if connection == nil { + m.goSubscriptionMu.Unlock() + return nil, errors.New("Go subscription is not connected") + } + if connection.NeedsLogin { + m.goSubscriptionMu.Unlock() + return nil, &goauth.OAuthError{Code: "invalid_grant"} + } + if err := connection.Validate(); err != nil { + m.goSubscriptionMu.Unlock() + return nil, err + } + if time.Until(connection.Credential.ExpiresAt) >= 5*time.Minute { + m.goSubscriptionMu.Unlock() + return connection, nil + } + refresh := m.goRefresh + if refresh == nil || refresh.done == nil && (refresh.credential != connection.Credential || !time.Now().Before(refresh.retryAt)) { + refresh = &goSubscriptionRefresh{credential: connection.Credential, done: make(chan struct{})} + m.goRefresh = refresh + go m.refreshGoSubscription(connection, refresh) + } + if refresh.done == nil { + err := refresh.err + m.goSubscriptionMu.Unlock() + if err != nil { + return nil, err + } + if !time.Now().Before(connection.Credential.ExpiresAt) { + return nil, &goauth.OAuthError{Code: "expired_token"} + } + return connection, nil + } + done := refresh.done + m.goSubscriptionMu.Unlock() + select { + case <-ctx.Done(): + return nil, ctx.Err() + case <-done: + } + } +} + +func (m *RuntimeController) refreshGoSubscription(connection *goauth.Connection, refresh *goSubscriptionRefresh) { + root := m.root + if root == nil { + root = context.Background() + } + ctx, cancel := context.WithTimeout(root, 20*time.Second) + defer cancel() + client := m.goAuthClient + if client == nil { + client = goauth.NewClient(nil) + } + credential, err := client.Refresh(ctx, connection.Credential) + if err != nil { + var oauthError *goauth.OAuthError + if errors.As(err, &oauthError) { + switch oauthError.Code { + case "invalid_grant", "expired_token", "unauthorized", "access_denied", "sso_required": + if saveErr := m.saveGoSubscriptionCredential(connection, connection.Credential, true); saveErr != nil { + err = saveErr + } + } + } else { + err = errors.New("Go subscription authorization could not be refreshed") + } + } else { + needsLogin := credential.OrganizationID != connection.Credential.OrganizationID + err = m.saveGoSubscriptionCredential(connection, credential, needsLogin) + if err == nil && needsLogin { + err = &goauth.OAuthError{Code: "invalid_grant"} + } + } + m.goSubscriptionMu.Lock() + defer m.goSubscriptionMu.Unlock() + refresh.err = err + refresh.retryAt = time.Now().Add(15 * time.Second) + if err == nil { + refresh.credential = credential + refresh.retryAt = time.Now().Add(min(30*time.Second, max(time.Millisecond, time.Until(credential.ExpiresAt)/2))) + } + close(refresh.done) + refresh.done = nil +} + +func (m *RuntimeController) saveGoSubscriptionCredential(previous *goauth.Connection, credential goauth.Credential, needsLogin bool) error { + changed := false + _, err := m.Update(func(cfg *config.Config) error { + connection := cfg.GoSubscription + if connection == nil || connection.Credential != previous.Credential || connection.NeedsLogin != previous.NeedsLogin { + changed = true + return errors.New("Go subscription connection changed") + } + connection.Credential = credential + connection.NeedsLogin = needsLogin + return nil + }) + if changed { + return errors.New("Go subscription connection changed; retry with the current configuration") + } + if err != nil { + return errors.New("Go subscription authorization could not be saved safely; sign in again") + } + return nil +} + +func (m *RuntimeController) invalidateGoSubscription(ctx context.Context, credential goauth.Credential) { + if ctx.Err() != nil { + return + } + unchanged := errors.New("Go subscription authorization is no longer current") + _, err := m.Update(func(cfg *config.Config) error { + connection := cfg.GoSubscription + if connection == nil || connection.Credential != credential || connection.NeedsLogin { + return unchanged + } + connection.NeedsLogin = true + return nil + }) + if err != nil && !errors.Is(err, unchanged) && m.logger != nil { + m.logger.Warn("Go subscription authorization could not be marked for reconnect", "component", "auth", "event", "go_subscription_reconnect_save_failed") + } +} diff --git a/internal/gateway/health.go b/internal/gateway/health.go index 51da981..ac3bf7e 100644 --- a/internal/gateway/health.go +++ b/internal/gateway/health.go @@ -70,6 +70,9 @@ 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() + if g.cfg.GoSubscription != nil { + goKeys = 1 + } staleAfter := max(2*time.Duration(g.cfg.Models.RefreshSeconds)*time.Second, time.Minute) var warpStatus *healthWarp warpActive := 0 @@ -93,6 +96,9 @@ func (g *Gateway) handleHealth(w http.ResponseWriter, _ *http.Request) { modelStatus := "ready" var lastRefresh *time.Time issues := make([]string, 0, 3) + if g.cfg.GoSubscription != nil && g.cfg.GoSubscription.NeedsLogin { + issues = append(issues, "go_subscription_authorization_required") + } if models.UpdatedAt.IsZero() { modelStatus = "pending" issues = append(issues, "model_catalog_pending") @@ -161,7 +167,29 @@ func (g *Gateway) handleHealth(w http.ResponseWriter, _ *http.Request) { } func (g *Gateway) availableModels() ([]modelcatalog.Route, modelcatalog.CatalogSnapshot) { - return g.catalog.AvailableModels(g.zenNodes.Len() > 0, g.goNodes.Len() > 0, g.cfg.Anonymous) + if g.cfg.GoSubscription == nil { + return g.catalog.AvailableModels(g.zenNodes.Len() > 0, g.goNodes.Len() > 0, g.cfg.Anonymous) + } + modelIDs := g.catalog.List() + seen := make(map[string]bool, len(modelIDs)+len(g.cfg.GoSubscription.Routes)) + for _, model := range modelIDs { + seen[model] = true + } + for model := range g.cfg.GoSubscription.Routes { + if !seen[model] { + modelIDs = append(modelIDs, model) + } + } + slices.Sort(modelIDs) + routes := make([]modelcatalog.Route, 0, len(modelIDs)) + for _, model := range modelIDs { + if route, err := g.routeForModel(model, ""); err == nil { + routes = append(routes, route) + } + } + snapshot := g.catalog.Snapshot() + snapshot.Exposed = len(routes) + return routes, snapshot } // reasoningLevels are the effort values the gateway accepts and forwards, from @@ -256,12 +284,12 @@ func (g *Gateway) handleModels(w http.ResponseWriter, _ *http.Request) { data = append(data, entry) } for _, group := range g.rotation.Snapshot().Groups { - if g.goNodes.Len() == 0 { + if !g.goAvailable() { continue } available := false for _, model := range group.Order { - if route, err := g.catalog.RouteForTier(model, config.TierGo, false, true); err == nil && route.Protocol != wire.SystemOne { + if route, err := g.routeForModel(model, config.TierGo); err == nil && route.Protocol != wire.SystemOne { available = true break } diff --git a/internal/gateway/refresh.go b/internal/gateway/refresh.go index c8591d1..b0e78c4 100644 --- a/internal/gateway/refresh.go +++ b/internal/gateway/refresh.go @@ -176,7 +176,12 @@ func (g *Gateway) RefreshCatalog(ctx context.Context) { var wg sync.WaitGroup wg.Add(3) go func() { defer wg.Done(); zen = g.refreshZen(ctx) }() - go func() { defer wg.Done(); goModels = g.refreshTier(ctx, g.cfg.Upstream.Go, g.goNodes) }() + go func() { + defer wg.Done() + if g.cfg.GoSubscription == nil { + goModels = g.refreshTier(ctx, g.cfg.Upstream.Go, g.goNodes) + } + }() go func() { defer wg.Done() capabilityCtx, cancel := context.WithTimeout(ctx, 30*time.Second) @@ -190,6 +195,9 @@ func (g *Gateway) RefreshCatalog(ctx context.Context) { if capabilitiesErr != nil { g.logger.Warn("OpenCode capability catalog refresh failed", "component", "models", "event", "capability_refresh_failed", "error", capabilitiesErr) } + if g.cfg.GoSubscription != nil { + goModels = g.seedGoSubscriptionCatalog(&capabilities) + } if zen != nil || goModels != nil { g.catalog.ReplaceWithCapabilities(zen, goModels, capabilities.Protocols, capabilities.Unsupported, capabilities.Metadata) g.syncRotation() diff --git a/internal/gateway/rotation.go b/internal/gateway/rotation.go index b37f6b4..32a538a 100644 --- a/internal/gateway/rotation.go +++ b/internal/gateway/rotation.go @@ -12,6 +12,7 @@ import ( "time" "opencode2api/internal/config" + "opencode2api/internal/goauth" "opencode2api/internal/identity" "opencode2api/internal/jsonutil" "opencode2api/internal/models" @@ -26,7 +27,7 @@ import ( func (g *Gateway) syncRotation() { available := map[string]bool{} for _, model := range g.catalog.List() { - if route, err := g.catalog.RouteForTier(model, config.TierGo, false, g.goNodes.Len() > 0); err == nil && route.Protocol != wire.SystemOne { + if route, err := g.routeForModel(model, config.TierGo); err == nil && route.Protocol != wire.SystemOne { available[model] = true } } @@ -101,6 +102,10 @@ func (g *Gateway) handleRotation(w http.ResponseWriter, r *http.Request, externa meta.Session = ids.Session meta.ModelAlias = alias } + if g.cfg.GoSubscription != nil && g.cfg.GoSubscription.NeedsLogin { + wire.WriteError(w, external, http.StatusServiceUnavailable, (&goauth.OAuthError{Code: "invalid_grant"}).Error(), "subscription_auth_error", ids.Request) + return + } visited := map[string]bool{} ordinaryModels, total := 0, 0 for ctx.Err() == nil { @@ -109,8 +114,13 @@ func (g *Gateway) handleRotation(w http.ResponseWriter, r *http.Request, externa break } visited[token.Model] = true - route, err := g.catalog.RouteForTier(token.Model, config.TierGo, false, g.goNodes.Len() > 0) + route, err := g.routeForModel(token.Model, config.TierGo) if err != nil { + var oauthError *goauth.OAuthError + if errors.As(err, &oauthError) { + wire.WriteError(w, external, http.StatusServiceUnavailable, oauthError.Error(), "subscription_auth_error", ids.Request) + return + } continue } counted := false @@ -148,6 +158,14 @@ func (g *Gateway) handleRotation(w http.ResponseWriter, r *http.Request, externa if result.err == nil { return } + var oauthError *goauth.OAuthError + if errors.As(result.err, &oauthError) { + wire.WriteError(w, external, http.StatusServiceUnavailable, oauthError.Error(), "subscription_auth_error", ids.Request) + return + } + if g.cfg.GoSubscription != nil && result.reason == "subscription_auth_error" { + return + } if result.committed { if meta != nil { meta.Outcome = "stream_error" @@ -214,58 +232,75 @@ func (g *Gateway) rotationAttempt(parent context.Context, w http.ResponseWriter, result.reason = "request_conversion_error" return result } - body, toolRenames, shaped := g.shapeKeyBody(bodies[config.TierGo], route, config.TierGo) - setRequestShape(parent, shaped, toolRenames) - cursor := g.goNodes.CursorFor(ids.Session) - var node *upstreamNode - // Each group attempt is exactly one HTTP call. Key selection may change, - // but there is no nested retry, stale-reasoning replay, or model-wide key ban. - for n := 0; n < attempt; n++ { - node = cursor.Next() + var resp *http.Response + var toolRenames *wire.ToolRenames + shaped := false + if g.cfg.GoSubscription != nil { + resp, err = g.goSubscriptionAttempt(ctx, route, bodies[config.TierGo], ids, attempt, attempt-1, 0) + } else { + var body []byte + body, toolRenames, shaped = g.shapeKeyBody(bodies[config.TierGo], route, config.TierGo) + setRequestShape(parent, shaped, toolRenames) + cursor := g.goNodes.CursorFor(ids.Session) + var node *upstreamNode + for selection := 0; selection < attempt; selection++ { + node = cursor.Next() + } + if node == nil { + result.err = errors.New("no Go key") + return result + } + proxy := g.goNodes.Proxy(node) + if proxy == nil { + result.err = errors.New("no proxy") + return result + } + req, requestErr := upstreamRequest(ctx, g.cfg.Upstream.Go, route.Protocol, body, ids, node.key) + if requestErr != nil { + result.err = requestErr + return result + } + req.GetBody = nil + client := *proxy.client + client.CheckRedirect = func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse } + setRequestCredential(parent, config.TierGo, config.KeyDisplayID(node.key), "key", false, proxy) + started := time.Now() + if proxy.pool { + req.Close = true + } + resp, err = doInferenceAttempt(&client, req, 0, g.attemptTimeout) + if err != nil && ctx.Err() != nil && parent.Err() == nil && !isProxyFailure(err) { + err = errFirstEventTimeout + } + g.recordUpstreamAttempt(parent, route, ids, attempt, config.KeyDisplayID(node.key), "key", false, proxy, resp, err, time.Since(started)) + if parent.Err() == nil { + g.observeKeyResult(parent, g.goNodes, node, proxy, resp, err) + } } - if node == nil { - result.err = errors.New("no Go key") - return result - } - proxy := g.goNodes.Proxy(node) - if proxy == nil { - result.err = errors.New("no proxy") - return result - } - req, err := upstreamRequest(ctx, g.cfg.Upstream.Go, route.Protocol, body, ids, node.key) - if err != nil { - result.err = err - return result - } - // A reused connection must not cause net/http to implicitly replay POSTs. - req.GetBody = nil - client := *proxy.client - client.CheckRedirect = func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse } - setRequestCredential(parent, config.TierGo, config.KeyDisplayID(node.key), "key", false, proxy) - started := time.Now() - if proxy.pool { - req.Close = true - } - resp, err := doInferenceAttempt(&client, req, 0, g.attemptTimeout) if err != nil && ctx.Err() != nil && parent.Err() == nil && !isProxyFailure(err) { - // The rotation-specific first-output deadline is not evidence that the - // proxy route failed. It still counts as a failed key attempt. err = errFirstEventTimeout } - g.recordUpstreamAttempt(parent, route, ids, attempt, config.KeyDisplayID(node.key), "key", false, proxy, resp, err, time.Since(started)) if resp != nil { defer resp.Body.Close() } - if parent.Err() == nil { - g.observeKeyResult(parent, g.goNodes, node, proxy, resp, err) - } if err != nil { result.err = err - if errors.Is(err, errFirstEventTimeout) || ctx.Err() != nil { + var oauthError *goauth.OAuthError + if errors.As(err, &oauthError) { + result.reason = "subscription_auth_error" + } else if errors.Is(err, errFirstEventTimeout) || ctx.Err() != nil { result.reason = "first_output_timeout" } return result } + if g.cfg.GoSubscription != nil && resp.StatusCode == http.StatusUnauthorized { + w.Header().Set("x-request-id", ids.Request) + copyErrorResponse(w, external, resp, ids.Request) + result.err = errors.New("Go subscription authorization was rejected") + result.reason = "subscription_auth_error" + result.committed = true + return result + } retryAfter := resp.Header.Get("Retry-After") if pause := parseRetryAfter(retryAfter); pause > 0 { result.pause = pause diff --git a/internal/gateway/runtime.go b/internal/gateway/runtime.go index 54e8a25..26308fb 100644 --- a/internal/gateway/runtime.go +++ b/internal/gateway/runtime.go @@ -2,16 +2,19 @@ package gateway import ( "context" + "errors" "fmt" "log/slog" "net/http" "net/netip" "os" + "slices" "sync" "sync/atomic" "time" "opencode2api/internal/config" + "opencode2api/internal/goauth" modelcatalog "opencode2api/internal/models" "opencode2api/internal/protocol" "opencode2api/internal/rotation" @@ -61,6 +64,9 @@ type RuntimeController struct { level *slog.LevelVar current atomic.Pointer[gatewayRuntime] updateMu sync.Mutex + goSubscriptionMu sync.Mutex + goAuthClient *goauth.Client + goRefresh *goSubscriptionRefresh effective EffectiveListeners metadata *modelcatalog.PricingRegistry availabilityCancel context.CancelFunc @@ -138,6 +144,7 @@ func RuntimeManager(root context.Context, configPath string, cfg config.Config, manager.logger.Warn("model catalog cache ignored", "component", "models", "event", "catalog_cache_load_failed", "path", modelcatalog.CatalogCachePath(configPath), "error", err) } } + runtime.gateway.restoreGoSubscriptionCatalog() if err := cfg.Rotation.Validate(runtime.gateway.catalog.List()); err != nil { if runtime.warpCreated && runtime.warpPool != nil { runtime.warpPool.Close() @@ -196,6 +203,17 @@ func (m *RuntimeController) build(cfg config.Config) (*gatewayRuntime, error) { return nil, err } gateway.rotation = m.rotation + gateway.onGoSubscriptionUnauthorized = m.invalidateGoSubscription + gateway.resolveGoSubscription = func(ctx context.Context) (*goauth.Connection, error) { + connection, err := m.ResolveGoSubscription(ctx) + if err != nil { + return nil, err + } + if !slices.Equal(cfg.RuntimeProxies(), m.Config().RuntimeProxies()) { + return nil, errors.New("Go subscription proxy configuration changed; retry with the current configuration") + } + return connection, nil + } availabilityPath := "" if m.configPath != "" { availabilityPath = m.configPath + "." + config.Fingerprint(cfg.Upstream.Zen) + ".availability.json" @@ -370,6 +388,7 @@ func (m *RuntimeController) applyLocked(candidate config.Config, persist bool) ( if current != nil { next.gateway.catalog.CopyState(current.gateway.catalog) } + next.gateway.restoreGoSubscriptionCatalog() if err := normalized.Rotation.Validate(next.gateway.catalog.List()); err != nil { if next.warpCreated && next.warpPool != nil { next.warpPool.Close() @@ -429,12 +448,14 @@ func (m *RuntimeController) applyLocked(candidate config.Config, persist bool) ( // it holds a plaintext WebUI password: that is hashed and saved, and the // backup holding the plaintext is removed. func (m *RuntimeController) Reload() (ApplyResult, error) { + m.updateMu.Lock() + defer m.updateMu.Unlock() cfg, err := config.Load(m.configPath) if err != nil { return ApplyResult{}, err } hadPlaintextPassword := cfg.WebUI.Password != "" - result, err := m.Apply(cfg, false) + result, err := m.applyLocked(cfg, false) if err == nil && hadPlaintextPassword { _ = os.Remove(m.configPath + ".bak") } @@ -519,7 +540,18 @@ func (m *RuntimeController) Resources() ResourceSnapshot { result := ResourceSnapshot{Models: models, Anonymous: gateway.cfg.Anonymous} result.Metadata = gateway.catalog.MetadataSnapshot() result.Keys = append(result.Keys, keyStatuses("zen", gateway.zenNodes)...) - result.Keys = append(result.Keys, keyStatuses("go", gateway.goNodes)...) + if connection := gateway.cfg.GoSubscription; connection != nil { + status := KeyStatus{ID: subscriptionAccountID(connection), Tier: string(config.TierGo), ProxyIndex: -1, Bound: connection.Proxy != ""} + for _, proxy := range gateway.transports.items { + if connection.Proxy != "" && proxy.name == connection.Proxy { + status.ProxyIndex = proxy.index + break + } + } + result.Keys = append(result.Keys, status) + } else { + result.Keys = append(result.Keys, keyStatuses("go", gateway.goNodes)...) + } gateway.zenNodes.bindingsMu.Lock() zenBindings := append([]int(nil), gateway.zenNodes.bindingCount...) gateway.zenNodes.bindingsMu.Unlock() @@ -534,6 +566,9 @@ func (m *RuntimeController) Resources() ResourceSnapshot { if proxy.index < len(goBindings) { status.GoKeys = goBindings[proxy.index] } + if gateway.cfg.GoSubscription != nil && gateway.cfg.GoSubscription.Proxy == proxy.name { + status.GoKeys = 1 + } result.Proxies = append(result.Proxies, status) } if gateway.warp != nil { @@ -558,7 +593,7 @@ func (m *RuntimeController) DebugModels() ([]modelcatalog.RouteDiagnostic, model models := gateway.catalog.List() result := make([]modelcatalog.RouteDiagnostic, 0, len(models)) for _, model := range models { - result = append(result, gateway.catalog.Diagnostic(model, "", len(gateway.cfg.ZenKeys) > 0, len(gateway.cfg.GoKeys) > 0, gateway.cfg.Anonymous)) + result = append(result, gateway.routeDiagnostic(model, "")) } metadata := gateway.catalog.MetadataSnapshot() return result, metadata @@ -572,7 +607,7 @@ func (m *RuntimeController) DebugRoute(model string, requested protocol.Protocol return modelcatalog.RouteDiagnostic{Model: model, RequestedProtocol: requested, RouteError: "gateway runtime is unavailable"} } gateway := runtime.gateway - return gateway.catalog.Diagnostic(model, requested, len(gateway.cfg.ZenKeys) > 0, len(gateway.cfg.GoKeys) > 0, gateway.cfg.Anonymous) + return gateway.routeDiagnostic(model, requested) } // DebugKeyView is the operator-facing view of one configured upstream key. It @@ -617,7 +652,11 @@ func (m *RuntimeController) DebugKeys() map[string][]DebugKeyView { } } appendKeys(config.TierZen, runtime.gateway.zenNodes.nodes) - appendKeys(config.TierGo, runtime.gateway.goNodes.nodes) + if connection := runtime.config.GoSubscription; connection != nil { + result["go"] = append(result["go"], DebugKeyView{ID: subscriptionAccountID(connection), Tier: config.TierGo, Display: "Go subscription"}) + } else { + appendKeys(config.TierGo, runtime.gateway.goNodes.nodes) + } return result } @@ -640,9 +679,8 @@ func (m *RuntimeController) DebugRouteForTier(model string, tier config.Tier) (m return modelcatalog.RouteDiagnostic{Model: model, RouteError: "gateway runtime is unavailable"}, fmt.Errorf("gateway runtime is unavailable") } gateway := runtime.gateway - hasZen, hasGo := len(gateway.cfg.ZenKeys) > 0, len(gateway.cfg.GoKeys) > 0 - diagnostic := gateway.catalog.Diagnostic(model, "", hasZen, hasGo, false) - route, err := gateway.catalog.RouteForTier(model, tier, hasZen, hasGo) + diagnostic := gateway.routeDiagnostic(model, "") + route, err := gateway.routeForModel(model, tier) if err != nil { diagnostic.RouteError = err.Error() return diagnostic, err @@ -651,6 +689,12 @@ func (m *RuntimeController) DebugRouteForTier(model string, tier config.Tier) (m diagnostic.Tier, diagnostic.Anonymous = route.Tier, false diagnostic.KeyTiers = []config.Tier{tier} diagnostic.NativeProtocol, diagnostic.NativeProtocols = route.Protocol, route.Protocols + if tier != config.TierGo { + diagnostic.Channel, diagnostic.KeyID = "", "" + if diagnostic.ProtocolSource == "go_subscription" { + diagnostic.ProtocolSource = "upstream" + } + } return diagnostic, nil } diff --git a/internal/gateway/upstream.go b/internal/gateway/upstream.go index 1e3e8a7..20fb1b4 100644 --- a/internal/gateway/upstream.go +++ b/internal/gateway/upstream.go @@ -155,7 +155,7 @@ func debugKeyOverrideFrom(ctx context.Context) (DebugKeyOverride, bool) { // replay so the Playground sees the selected key's own answer. func (g *Gateway) doUpstream(ctx context.Context, route models.Route, bodies map[config.Tier][]byte, ids identity.RequestIDs) (*http.Response, models.Route, error) { resp, effectiveRoute, attempts, err := g.doUpstreamTiers(ctx, route, bodies, ids, 0) - if _, selected := debugKeyOverrideFrom(ctx); selected { + if _, selected := debugKeyOverrideFrom(ctx); selected || effectiveRoute.Tier == config.TierGo && g.cfg.GoSubscription != nil { return resp, effectiveRoute, err } if err != nil || resp == nil || resp.StatusCode != http.StatusBadRequest { @@ -935,6 +935,12 @@ func (g *Gateway) shapeKeyBody(body []byte, route models.Route, tier config.Tier // live traffic before. The attempt is still recorded in telemetry, and any HTTP // response, whatever its status, is returned as is. func (g *Gateway) doSelectedKeyUpstream(ctx context.Context, route models.Route, bodies map[config.Tier][]byte, ids identity.RequestIDs, override DebugKeyOverride, attemptOffset int) (*http.Response, error, int) { + if override.Tier == config.TierGo && g.cfg.GoSubscription != nil { + if override.KeyID != subscriptionAccountID(g.cfg.GoSubscription) { + return nil, errors.New("the selected Go subscription is no longer connected"), 0 + } + return g.doGoSubscriptionUpstream(ctx, route, bodies, ids, attemptOffset) + } nodes := g.zenNodes baseURL := g.cfg.Upstream.Zen if override.Tier == config.TierGo { @@ -1016,6 +1022,9 @@ func (g *Gateway) doSelectedKeyUpstream(ctx context.Context, route models.Route, // response (body still open), else the last error, plus the number of // attempts made. func (g *Gateway) doKeyUpstream(ctx context.Context, route models.Route, bodies map[config.Tier][]byte, ids identity.RequestIDs, attemptOffset int) (response *http.Response, resultErr error, resultAttempts int) { + if route.Tier == config.TierGo && g.cfg.GoSubscription != nil { + return g.doGoSubscriptionUpstream(ctx, route, bodies, ids, attemptOffset) + } var lastResponse *http.Response defer func() { if lastResponse != nil && lastResponse != response { @@ -1296,7 +1305,7 @@ func (g *Gateway) recordUpstreamAttempt(ctx context.Context, route models.Route, KeyID: keyID, Channel: channel, Anonymous: anonymous, Proxy: proxyName, Status: status, DurationMS: max(duration.Milliseconds(), 0), Success: success, Outcome: outcome, }) - if !isDiagnosticRequest(ctx) && g.availability != nil && g.catalog.IsFreeModel(route.ID) { + if channel != "subscription" && !isDiagnosticRequest(ctx) && g.availability != nil && g.catalog.IsFreeModel(route.ID) { bodySnippet := "" if resp != nil && (resp.StatusCode == 400 || resp.StatusCode == 404 || resp.StatusCode == 410 || resp.StatusCode == 422) { bodySnippet = string(peekResponseBody(resp)) diff --git a/internal/goauth/client.go b/internal/goauth/client.go new file mode 100644 index 0000000..ff7131d --- /dev/null +++ b/internal/goauth/client.go @@ -0,0 +1,409 @@ +package goauth + +import ( + "bytes" + "context" + "encoding/json" + "io" + "net/http" + "net/url" + "strings" + "time" + "unicode" + "unicode/utf8" + + "opencode2api/internal/httpx" + "opencode2api/internal/protocol" +) + +const ( + ConsoleURL = "https://opencode.ai/console" + clientID = "opencode-cli" + requestTimeout = 15 * time.Second + responseLimit = 2 << 20 + maximumTokenSize = 16 << 10 +) + +type Credential struct { + AccessToken string `json:"access_token"` + RefreshToken string `json:"refresh_token"` + ExpiresAt time.Time `json:"expires_at"` + AccountID string `json:"account_id"` + Email string `json:"email"` + OrganizationID string `json:"organization_id"` + OrganizationName string `json:"organization_name"` +} + +type Device struct { + DeviceCode string `json:"-"` + UserCode string `json:"user_code"` + VerificationURI string `json:"verification_uri"` + ExpiresAt time.Time `json:"expires_at"` + Interval time.Duration `json:"interval"` +} + +type Token struct { + AccessToken string `json:"access_token"` + RefreshToken string `json:"refresh_token"` + ExpiresAt time.Time `json:"expires_at"` + OrganizationID string `json:"organization_id"` +} + +type User struct { + ID string `json:"id"` + Email string `json:"email"` +} + +type Organization struct { + ID string `json:"id"` + Name string `json:"name"` +} + +type Route struct { + ModelID string `json:"model_id"` + Protocol protocol.Protocol `json:"protocol"` + BaseURL string `json:"base_url"` +} + +type Connection struct { + Credential Credential `json:"credential"` + Routes map[string]Route `json:"routes"` + Proxy string `json:"proxy,omitempty"` + NeedsLogin bool `json:"needs_login,omitempty"` +} + +type OAuthError struct { + Code string +} + +func (err *OAuthError) Error() string { + switch err.Code { + case "authorization_pending": + return "OpenCode authorization is awaiting approval" + case "slow_down": + return "OpenCode authorization polling must slow down" + case "invalid_grant", "expired_token": + return "OpenCode authorization expired or was revoked; sign in again" + case "access_denied": + return "OpenCode authorization was denied" + case "unauthorized": + return "OpenCode sign-in is no longer authorized; sign in again" + case "sso_required": + return "OpenCode workspace requires a new SSO sign-in" + case "no_go_subscription": + return "OpenCode did not provide a supported Go subscription route" + case "rate_limited": + return "OpenCode authorization service is rate limited; try again later" + case "invalid_credential": + return "OpenCode subscription credential is invalid" + case "invalid_response": + return "OpenCode authorization service returned an invalid response" + case "request_timeout": + return "OpenCode authorization request timed out" + case "connection_failed": + return "OpenCode authorization service could not be reached" + default: + return "OpenCode authorization service rejected the request" + } +} + +type Client struct { + http *http.Client +} + +func NewClient(client *http.Client) *Client { + transport := http.Client{} + if client != nil { + transport = *client + } + if transport.Timeout <= 0 || transport.Timeout > requestTimeout { + transport.Timeout = requestTimeout + } + transport.CheckRedirect = func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse } + return &Client{http: &transport} +} + +func (credential Credential) Validate() error { + if !validOpaque(credential.AccessToken, maximumTokenSize) || !validOpaque(credential.RefreshToken, maximumTokenSize) || credential.ExpiresAt.IsZero() { + return &OAuthError{Code: "invalid_credential"} + } + if credential.OrganizationID != "" && !validOpaque(credential.OrganizationID, 1024) { + return &OAuthError{Code: "invalid_credential"} + } + if !validText(credential.AccountID, 1024) || !validText(credential.Email, 1024) || !validText(credential.OrganizationName, 4096) { + return &OAuthError{Code: "invalid_credential"} + } + return nil +} + +func (connection Connection) Validate() error { + if err := connection.Credential.Validate(); err != nil { + return err + } + if !validText(connection.Proxy, 8192) { + return &OAuthError{Code: "invalid_credential"} + } + if len(connection.Routes) == 0 { + return &OAuthError{Code: "no_go_subscription"} + } + for model, route := range connection.Routes { + base, ok := normalizeBase(route.BaseURL, route.Protocol) + if !validOpaque(model, 1024) || !validOpaque(route.ModelID, 1024) || !ok || base != route.BaseURL { + return &OAuthError{Code: "invalid_credential"} + } + } + return nil +} + +func (client *Client) Start(ctx context.Context) (Device, error) { + body, err := client.request(ctx, http.MethodPost, "/auth/device/code", map[string]any{ + "client_id": clientID, "supports_org_scope": true, + }, nil) + if err != nil { + return Device{}, err + } + var response struct { + DeviceCode string `json:"device_code"` + UserCode string `json:"user_code"` + VerificationURI string `json:"verification_uri_complete"` + ExpiresIn int64 `json:"expires_in"` + Interval int64 `json:"interval"` + } + if err := json.Unmarshal(body, &response); err != nil || !validOpaque(response.DeviceCode, maximumTokenSize) || !validOpaque(response.UserCode, 256) || !validText(response.VerificationURI, 8192) || response.ExpiresIn < 1 || response.ExpiresIn > 86400 || response.Interval < 0 || response.Interval > 300 { + return Device{}, &OAuthError{Code: "invalid_response"} + } + base, _ := url.Parse(ConsoleURL + "/") + verification, err := url.Parse(response.VerificationURI) + if err != nil || response.VerificationURI == "" { + return Device{}, &OAuthError{Code: "invalid_response"} + } + verification = base.ResolveReference(verification) + if !officialURL(verification) { + return Device{}, &OAuthError{Code: "invalid_response"} + } + interval := response.Interval + if interval == 0 { + interval = 5 + } + return Device{ + DeviceCode: response.DeviceCode, + UserCode: response.UserCode, + VerificationURI: verification.String(), + ExpiresAt: time.Now().UTC().Add(time.Duration(response.ExpiresIn) * time.Second), + Interval: time.Duration(interval) * time.Second, + }, nil +} + +func (client *Client) Poll(ctx context.Context, deviceCode string) (Token, error) { + if !validOpaque(deviceCode, maximumTokenSize) { + return Token{}, &OAuthError{Code: "invalid_credential"} + } + return client.exchange(ctx, map[string]string{ + "grant_type": "urn:ietf:params:oauth:grant-type:device_code", + "device_code": deviceCode, + "client_id": clientID, + }) +} + +func (client *Client) Identify(ctx context.Context, token Token) (User, []Organization, error) { + if !validOpaque(token.AccessToken, maximumTokenSize) { + return User{}, nil, &OAuthError{Code: "invalid_credential"} + } + credential := Credential{AccessToken: token.AccessToken} + body, err := client.request(ctx, http.MethodGet, "/api/user", nil, &credential) + if err != nil { + return User{}, nil, err + } + var user User + if err := json.Unmarshal(body, &user); err != nil || user.ID == "" || !validText(user.ID, 1024) || !validText(user.Email, 1024) { + return User{}, nil, &OAuthError{Code: "invalid_response"} + } + body, err = client.request(ctx, http.MethodGet, "/api/orgs", nil, &credential) + if err != nil { + return User{}, nil, err + } + var organizations []Organization + if err := json.Unmarshal(body, &organizations); err != nil || organizations == nil || len(organizations) > 4096 { + return User{}, nil, &OAuthError{Code: "invalid_response"} + } + seen := make(map[string]bool, len(organizations)) + for _, organization := range organizations { + if !validOpaque(organization.ID, 1024) || !validText(organization.Name, 4096) || seen[organization.ID] { + return User{}, nil, &OAuthError{Code: "invalid_response"} + } + seen[organization.ID] = true + } + if token.OrganizationID != "" && !seen[token.OrganizationID] { + return User{}, nil, &OAuthError{Code: "access_denied"} + } + return user, organizations, nil +} + +func (client *Client) Refresh(ctx context.Context, credential Credential) (Credential, error) { + if err := credential.Validate(); err != nil { + return Credential{}, err + } + token, err := client.exchange(ctx, map[string]string{ + "grant_type": "refresh_token", + "refresh_token": credential.RefreshToken, + "client_id": clientID, + }) + if err != nil { + return Credential{}, err + } + credential.AccessToken = token.AccessToken + credential.RefreshToken = token.RefreshToken + credential.ExpiresAt = token.ExpiresAt + if token.OrganizationID != "" { + if credential.OrganizationID != token.OrganizationID { + credential.OrganizationName = token.OrganizationID + } + credential.OrganizationID = token.OrganizationID + } + return credential, nil +} + +func (client *Client) exchange(ctx context.Context, payload map[string]string) (Token, error) { + body, err := client.request(ctx, http.MethodPost, "/auth/device/token", payload, nil) + if err != nil { + return Token{}, err + } + var response struct { + AccessToken string `json:"access_token"` + RefreshToken string `json:"refresh_token"` + ExpiresIn int64 `json:"expires_in"` + OrganizationID string `json:"org_id"` + Error string `json:"error"` + } + if err := json.Unmarshal(body, &response); err != nil { + return Token{}, &OAuthError{Code: "invalid_response"} + } + if response.Error != "" { + return Token{}, responseError(http.StatusBadRequest, body) + } + if !validOpaque(response.AccessToken, maximumTokenSize) || !validOpaque(response.RefreshToken, maximumTokenSize) || response.ExpiresIn < 1 || response.ExpiresIn > 30*86400 || response.OrganizationID != "" && !validOpaque(response.OrganizationID, 1024) { + return Token{}, &OAuthError{Code: "invalid_response"} + } + return Token{ + AccessToken: response.AccessToken, + RefreshToken: response.RefreshToken, + ExpiresAt: time.Now().UTC().Add(time.Duration(response.ExpiresIn) * time.Second), + OrganizationID: response.OrganizationID, + }, nil +} + +func (client *Client) request(ctx context.Context, method, path string, payload any, credential *Credential) ([]byte, error) { + requestCtx, cancel := context.WithTimeout(ctx, requestTimeout) + defer cancel() + var input io.Reader + if payload != nil { + encoded, err := json.Marshal(payload) + if err != nil { + return nil, &OAuthError{Code: "invalid_credential"} + } + input = bytes.NewReader(encoded) + } + request, err := http.NewRequestWithContext(requestCtx, method, ConsoleURL+path, input) + if err != nil { + return nil, &OAuthError{Code: "connection_failed"} + } + request.Header.Set("Accept", "application/json") + request.Header.Set("User-Agent", httpx.V2UserAgent()) + if payload != nil { + request.Header.Set("Content-Type", "application/json") + } + if credential != nil { + request.Header.Set("Authorization", "Bearer "+credential.AccessToken) + if credential.OrganizationID != "" { + request.Header.Set("x-org-id", credential.OrganizationID) + } + } + transport := client + if transport == nil || transport.http == nil { + transport = NewClient(nil) + } + response, err := transport.http.Do(request) + if err != nil { + if ctx.Err() != nil { + return nil, ctx.Err() + } + if requestCtx.Err() != nil { + return nil, &OAuthError{Code: "request_timeout"} + } + return nil, &OAuthError{Code: "connection_failed"} + } + defer response.Body.Close() + body, err := io.ReadAll(io.LimitReader(response.Body, responseLimit+1)) + if err != nil { + if ctx.Err() != nil { + return nil, ctx.Err() + } + if requestCtx.Err() != nil { + return nil, &OAuthError{Code: "request_timeout"} + } + return nil, &OAuthError{Code: "invalid_response"} + } + if len(body) > responseLimit { + return nil, &OAuthError{Code: "invalid_response"} + } + if response.StatusCode < 200 || response.StatusCode >= 300 { + return nil, responseError(response.StatusCode, body) + } + return body, nil +} + +func responseError(status int, body []byte) error { + var response struct { + Error string `json:"error"` + Tag string `json:"_tag"` + } + _ = json.Unmarshal(body, &response) + if response.Tag == "SsoRequired" { + return &OAuthError{Code: "sso_required"} + } + if response.Tag == "Unauthorized" { + return &OAuthError{Code: "unauthorized"} + } + switch response.Error { + case "authorization_pending", "slow_down", "invalid_grant", "expired_token", "access_denied": + return &OAuthError{Code: response.Error} + } + switch status { + case http.StatusUnauthorized: + return &OAuthError{Code: "unauthorized"} + case http.StatusForbidden: + return &OAuthError{Code: "access_denied"} + case http.StatusTooManyRequests: + return &OAuthError{Code: "rate_limited"} + default: + return &OAuthError{Code: "upstream_error"} + } +} + +func validOpaque(value string, limit int) bool { + if value == "" || len(value) > limit { + return false + } + for _, character := range value { + if character <= ' ' || character > '~' { + return false + } + } + return true +} + +func validText(value string, limit int) bool { + if len(value) > limit || !utf8.ValidString(value) { + return false + } + for _, character := range value { + if unicode.IsControl(character) || character == '\u2028' || character == '\u2029' { + return false + } + } + return true +} + +func officialURL(parsed *url.URL) bool { + return parsed != nil && parsed.Scheme == "https" && strings.EqualFold(parsed.Hostname(), "opencode.ai") && (parsed.Port() == "" || parsed.Port() == "443") && parsed.User == nil && parsed.Opaque == "" +} diff --git a/internal/goauth/discovery.go b/internal/goauth/discovery.go new file mode 100644 index 0000000..a5b192d --- /dev/null +++ b/internal/goauth/discovery.go @@ -0,0 +1,142 @@ +package goauth + +import ( + "context" + "encoding/json" + "net/http" + "net/url" + "strings" + + "opencode2api/internal/protocol" +) + +type remoteSettings struct { + BaseURL string `json:"baseURL"` +} + +type remoteModel struct { + ModelID string `json:"modelID"` + Package string `json:"package"` + Settings remoteSettings `json:"settings"` + Disabled bool `json:"disabled"` +} + +type remoteProvider struct { + Package string `json:"package"` + Settings remoteSettings `json:"settings"` + Disabled bool `json:"disabled"` + Models map[string]remoteModel `json:"models"` +} + +func (client *Client) Discover(ctx context.Context, credential Credential) (map[string]Route, error) { + if err := credential.Validate(); err != nil { + return nil, err + } + body, err := client.request(ctx, http.MethodGet, "/api/v2/config", nil, &credential) + if err != nil { + return nil, err + } + var response struct { + Providers map[string]remoteProvider `json:"providers"` + } + if err := json.Unmarshal(body, &response); err != nil || response.Providers == nil { + return nil, &OAuthError{Code: "invalid_response"} + } + routes := make(map[string]Route) + ambiguous := make(map[string]bool) + for _, provider := range response.Providers { + if provider.Disabled { + continue + } + for name, model := range provider.Models { + if model.Disabled || !validOpaque(name, 1024) || ambiguous[name] { + continue + } + modelID := model.ModelID + if modelID == "" { + modelID = name + } + if !validOpaque(modelID, 1024) { + continue + } + packageName := model.Package + if packageName == "" { + packageName = provider.Package + } + wireProtocol, ok := packageProtocol(packageName) + if !ok { + continue + } + baseURL := model.Settings.BaseURL + if baseURL == "" { + baseURL = provider.Settings.BaseURL + } + baseURL, ok = normalizeBase(baseURL, wireProtocol) + if !ok { + continue + } + route := Route{ModelID: modelID, Protocol: wireProtocol, BaseURL: baseURL} + if existing, exists := routes[name]; exists && existing != route { + delete(routes, name) + ambiguous[name] = true + continue + } + routes[name] = route + } + } + if len(routes) == 0 { + return nil, &OAuthError{Code: "no_go_subscription"} + } + return routes, nil +} + +func packageProtocol(packageName string) (protocol.Protocol, bool) { + if strings.HasPrefix(packageName, "aisdk:@ai-sdk/") { + packageName = strings.TrimPrefix(packageName, "aisdk:") + } + if strings.HasPrefix(packageName, "@opencode-ai/ai/providers/") { + packageName = "@opencode/ai/providers/" + strings.TrimPrefix(packageName, "@opencode-ai/ai/providers/") + } + switch packageName { + case "@ai-sdk/openai-compatible", "@opencode/ai/providers/openai-compatible", "@opencode/ai/providers/openai/chat": + return protocol.Chat, true + case "@ai-sdk/openai", "@opencode/ai/providers/openai", "@opencode/ai/providers/openai/responses", "@opencode/ai/providers/openai-compatible/responses", "@opencode/ai/providers/openai-compatible-responses": + return protocol.Responses, true + case "@ai-sdk/anthropic", "@opencode/ai/providers/anthropic", "@opencode/ai/providers/anthropic-compatible": + return protocol.Anthropic, true + default: + return "", false + } +} + +func normalizeBase(raw string, wireProtocol protocol.Protocol) (string, bool) { + if wireProtocol != protocol.Chat && wireProtocol != protocol.Responses && wireProtocol != protocol.Anthropic { + return "", false + } + parsed, err := url.Parse(raw) + if err != nil || !officialURL(parsed) || parsed.RawQuery != "" || parsed.ForceQuery || parsed.Fragment != "" || parsed.RawPath != "" { + return "", false + } + path := strings.TrimRight(parsed.Path, "/") + if path == "/inference/go" { + if wireProtocol == protocol.Anthropic { + path += "/anthropic" + } else { + path += "/openai" + } + } + switch path { + case "/inference/go/openai", "/inference/go/openai/v1": + if wireProtocol == protocol.Anthropic { + return "", false + } + return "https://opencode.ai/inference/go/openai", true + case "/inference/go/anthropic", "/inference/go/anthropic/v1": + if wireProtocol != protocol.Anthropic { + return "", false + } + return "https://opencode.ai/inference/go/anthropic", true + default: + return "", false + } +} diff --git a/webui/index.html b/webui/index.html index 87c0578..98aae1c 100644 --- a/webui/index.html +++ b/webui/index.html @@ -647,6 +647,22 @@
+
+
+
+

Go 订阅登录

+

通过 OpenCode 官方页面授权,无需复制凭证。手动 Go Key 仍保留,订阅连接期间不作备用通道,断开后恢复原有路由。

+
+ +
+
+
+ + + +
+

只接入已确认的 Go 订阅路由,不自动改用余额通道。OAuth 订阅额度查询不可用时显示未知,不推算剩余额度。

+
diff --git a/webui/js/go-auth.js b/webui/js/go-auth.js new file mode 100644 index 0000000..0420066 --- /dev/null +++ b/webui/js/go-auth.js @@ -0,0 +1,290 @@ +import { api, hasSession } from "./api.js"; +import * as store from "./store.js"; +import { t, onChange } from "./i18n.js"; +import { $, confirmDialog, el, localTime } from "./ui.js"; + +let state = null; +let timer = null; +let active = false; +let busy = false; +let generation = 0; +let controller = null; +let failure = ""; +let connectionChanged = null; +let synchronizationPending = false; + +function stopPolling() { + clearTimeout(timer); + timer = null; +} + +function verificationURL(value) { + try { + const parsed = new URL(value, "https://opencode.ai/console/"); + if ( + parsed.protocol !== "https:" || + parsed.host !== "opencode.ai" || + parsed.username || + parsed.password + ) + return null; + return parsed.href; + } catch { + return null; + } +} + +function pendingExpired() { + const expires = Date.parse(state?.pending?.expires_at); + return Number.isFinite(expires) && expires <= Date.now(); +} + +function connectionID(value) { + return value?.connected + ? JSON.stringify([ + value.account?.email, + value.account?.organization, + value.account?.models, + !!value.account?.needs_login, + ]) + : ""; +} + +function current(operation) { + return operation === generation && hasSession(); +} + +async function synchronize(operation) { + const [config, debug] = await Promise.all([api("/api/config"), api("/api/debug/models")]); + if (!current(operation)) return; + store.set("config", config); + if (debug.last_inference) store.set("lastPlayground", debug.last_inference); + store.set("debug", debug); + await connectionChanged?.(); + if (current(operation)) synchronizationPending = false; +} + +function schedulePoll() { + stopPolling(); + const pending = state?.pending; + if ( + !active || + document.hidden || + busy || + failure || + !hasSession() || + !pending || + pendingExpired() || + pending.status === "failed" || + pending.status === "choosing_org" + ) + return; + const seconds = Number(pending.retry_after_seconds ?? pending.interval_seconds ?? 5); + const wait = Number.isFinite(seconds) ? Math.max(1, Math.min(seconds, 86400)) : 5; + timer = setTimeout(() => { + if (pendingExpired() || state?.pending?.status === "starting") refresh(); + else poll(); + }, wait * 1000); +} + +async function request(path, options = {}, action = "refresh") { + if (busy || !hasSession()) return; + stopPolling(); + const operation = generation; + const previous = connectionID(state); + busy = true; + failure = ""; + controller = new AbortController(); + render(); + try { + const next = await api(path, { ...options, signal: controller.signal }); + if (!current(operation)) return; + state = next; + render(); + if ( + action === "disconnect" || + previous !== connectionID(next) || + (action === "poll" && next.connected && !next.pending) + ) + synchronizationPending = true; + if (synchronizationPending) await synchronize(operation); + } catch (error) { + if (current(operation) && error.name !== "AbortError") failure = error.message; + } finally { + if (current(operation)) { + busy = false; + controller = null; + render(); + schedulePoll(); + } + } +} + +function poll(organizationID) { + if (!state?.pending?.id) return; + const body = { id: state.pending.id }; + if (organizationID) body.organization_id = organizationID; + return request("/api/go/auth/poll", { method: "POST", body: JSON.stringify(body) }, "poll"); +} + +async function disconnect() { + const operation = generation; + const confirmed = await confirmDialog({ + title: t("断开 Go 订阅登录", "goAuth.disconnect"), + message: t( + "仅移除网关保存的订阅登录,不删除手动 Go Key,也不会撤销 OpenCode 官方会话。是否继续?", + "goAuth.disconnectConfirm", + ), + confirmLabel: t("断开连接", "goAuth.disconnectAction"), + danger: true, + }); + if (!confirmed || !current(operation)) return; + await request("/api/go/connection", { method: "DELETE", body: "{}" }, "disconnect"); +} + +function render() { + const pending = state?.pending; + const expired = pendingExpired(); + const selected = $("#go-auth-organization")?.value; + const host = $("#go-auth-content"); + host.replaceChildren(); + $("#go-auth-start").textContent = state?.connected + ? t("重新登录 Go 订阅", "goAuth.reconnect") + : t("浏览器登录 Go 订阅", "goAuth.start"); + $("#go-auth-start").disabled = busy || !!(pending && pending.status !== "failed" && !expired); + $("#go-auth-refresh").disabled = busy; + $("#go-auth-cancel").classList.toggle("hidden", !pending); + $("#go-auth-cancel").disabled = busy; + $("#go-auth-disconnect").classList.toggle("hidden", !state?.connected); + $("#go-auth-disconnect").disabled = busy; + if (state?.connected) { + const account = state.account || {}; + host.append( + el("p", { + class: account.needs_login ? "warn" : "ok", + text: account.needs_login + ? t("Go 订阅登录已失效,请重新登录。手动 Go Key 不会作为备用通道。", "goAuth.needsLogin") + : t("Go 订阅已连接,登录凭证仅保存在网关服务端。", "goAuth.connected"), + }), + ); + if (account.error) host.append(el("p", { class: "warn", text: account.error })); + if (account.email) host.append(el("p", { class: "mono", text: account.email })); + if (account.organization) + host.append(el("p", { text: t("组织:{0}", "goAuth.organizationValue", account.organization) })); + if (account.models != null) + host.append(el("p", { text: t("已获取 {0} 个订阅模型。", "goAuth.models", account.models) })); + if (account.expires_at && !account.needs_login) + host.append( + el("p", { + class: "section-caption", + text: t("访问凭证到期:{0};网关按需自动刷新。", "goAuth.expires", localTime(account.expires_at)), + }), + ); + } else if (!pending) { + host.append(el("p", { + class: "section-caption", + text: t("尚未连接 Go 订阅。手动配置的 Go Key 不受此登录影响。", "goAuth.disconnected"), + })); + } + if (pending) { + if (expired) { + host.append(el("p", { class: "warn", text: t("本次登录已过期,请重新开始。", "goAuth.expired") })); + } else if (pending.status === "failed") { + host.append(el("p", { + class: "warn", + text: pending.error || t("订阅登录未完成,请重新开始。", "goAuth.failed"), + })); + } else if (pending.status === "choosing_org") { + const select = el("select", { id: "go-auth-organization" }); + select.append(el("option", { value: "", text: t("请选择订阅所在组织", "goAuth.chooseOrganization") })); + for (const organization of pending.organizations || []) + select.append(el("option", { value: organization.id, text: organization.name || organization.id })); + if ([...select.options].some((option) => option.value === selected)) select.value = selected; + const confirm = el("button", { + type: "button", + class: "btn btn-sm btn-primary", + text: t("连接所选组织", "goAuth.confirmOrganization"), + disabled: busy || !select.value, + }); + select.disabled = busy; + select.addEventListener("change", () => (confirm.disabled = !select.value)); + confirm.addEventListener("click", () => poll(select.value)); + host.append(el("div", { class: "field" }, [ + el("label", { for: "go-auth-organization", text: t("订阅所在组织", "goAuth.organization") }), + select, + ]), confirm); + } else if (pending.status === "starting") { + host.append(el("p", { text: t("正在申请官方登录验证码…", "goAuth.starting") })); + } else { + host.append(el("p", { text: t("打开官方页面完成登录,并确认这是您发起的授权。", "goAuth.instructions") })); + if (pending.user_code) + host.append(el("p", {}, [ + el("span", { text: t("验证码:", "goAuth.userCode") }), + el("code", { class: "mono", text: pending.user_code }), + ])); + const url = pending.verification_url && verificationURL(pending.verification_url); + if (url) + host.append(el("a", { + class: "btn btn-sm btn-primary", + href: url, + target: "_blank", + rel: "noopener noreferrer", + text: t("打开 OpenCode 官方登录页", "goAuth.openVerification"), + })); + else + host.append(el("p", { class: "warn", text: t("官方验证链接无效,请取消后重试。", "goAuth.invalidURL") })); + if (pending.expires_at) + host.append(el("p", { + class: "section-caption", + text: t("验证码有效至 {0};授权后将自动检查结果。", "goAuth.pendingExpires", localTime(pending.expires_at)), + })); + } + } + if (failure) + host.append(el("p", { class: "warn", role: "alert", text: t("操作失败:{0}", "goAuth.error", failure) })); +} + +export function init(onConnectionChanged) { + connectionChanged = onConnectionChanged; + $("#go-auth-start").addEventListener("click", () => + request("/api/go/auth/start", { method: "POST", body: "{}" }, "start"), + ); + $("#go-auth-refresh").addEventListener("click", refresh); + $("#go-auth-cancel").addEventListener("click", () => + request("/api/go/auth", { method: "DELETE", body: "{}" }, "cancel"), + ); + $("#go-auth-disconnect").addEventListener("click", disconnect); + document.addEventListener("visibilitychange", () => { + if (document.hidden) stopPolling(); + else if (active) refresh(); + }); + onChange(render); + render(); +} + +export function refresh() { + return request("/api/go/auth"); +} + +export function show() { + active = true; + if (!document.hidden) refresh(); +} + +export function hide() { + active = false; + stopPolling(); +} + +export function reset() { + generation++; + active = false; + stopPolling(); + controller?.abort(); + controller = null; + state = null; + busy = false; + failure = ""; + synchronizationPending = false; + render(); +} diff --git a/webui/js/i18n.js b/webui/js/i18n.js index 66d5320..24ee49c 100644 --- a/webui/js/i18n.js +++ b/webui/js/i18n.js @@ -499,6 +499,35 @@ const DICTIONARY = { "diag.noAttempts": "No upstream attempts", "diag.noMatch": "No matching models", + "goAuth.title": "Go subscription sign-in", + "goAuth.caption": "Authorize on the official OpenCode page without copying credentials. Manual Go keys are kept but are not fallback routes while the subscription is connected; their previous routing resumes after disconnecting.", + "goAuth.refresh": "Refresh sign-in status", + "goAuth.start": "Sign in to Go in your browser", + "goAuth.reconnect": "Sign in to Go again", + "goAuth.cancel": "Cancel this sign-in", + "goAuth.disconnect": "Disconnect Go subscription", + "goAuth.disconnectAction": "Disconnect", + "goAuth.disconnectConfirm": "This only removes the subscription sign-in saved by the gateway. Manual Go keys are kept and the official OpenCode session is not revoked. Continue?", + "goAuth.notice": "Only confirmed Go subscription routes are used; there is no automatic switch to pay-as-you-go. Unavailable OAuth subscription quota stays unknown instead of being estimated.", + "goAuth.connected": "Go subscription connected. Sign-in credentials stay on the gateway server.", + "goAuth.needsLogin": "Your Go subscription sign-in has expired. Sign in again. Manual Go keys will not be used as fallback routes.", + "goAuth.disconnected": "No Go subscription is connected. Manually configured Go keys are not affected.", + "goAuth.organizationValue": "Organization: {0}", + "goAuth.models": "Loaded {0} subscription models.", + "goAuth.expires": "Access credential expires at {0}; the gateway refreshes it when needed.", + "goAuth.expired": "This sign-in has expired. Start again.", + "goAuth.failed": "Subscription sign-in did not finish. Start again.", + "goAuth.organization": "Subscription organization", + "goAuth.chooseOrganization": "Select the organization with your subscription", + "goAuth.confirmOrganization": "Connect selected organization", + "goAuth.starting": "Requesting an official sign-in code…", + "goAuth.instructions": "Open the official page to sign in, and confirm that you initiated this authorization.", + "goAuth.userCode": "Verification code: ", + "goAuth.openVerification": "Open official OpenCode sign-in", + "goAuth.invalidURL": "The official verification link is invalid. Cancel and try again.", + "goAuth.pendingExpires": "Code valid until {0}; authorization will be checked automatically.", + "goAuth.error": "Operation failed: {0}", + "quotas.noKey": "No Go Key configured", "quotas.addKeyFirst": "Add an OpenCode Go Key in the Configuration center first.", "quotas.queryFailed": "Query failed: {0}. The content shown is only the previous query result.", diff --git a/webui/js/pages/model-quotas.js b/webui/js/pages/model-quotas.js index cd37b34..bb321c5 100644 --- a/webui/js/pages/model-quotas.js +++ b/webui/js/pages/model-quotas.js @@ -1,6 +1,7 @@ // Page: 模型与额度 — Go quota windows and free model availability. import { api, hasSession } from "../api.js"; import { loadDebugModels } from "../data.js"; +import * as goAuth from "../go-auth.js"; import { t, onChange } from "../i18n.js"; import { $, bindTabs, copyText, el, emptyRow, localTime, toast } from "../ui.js"; @@ -14,36 +15,44 @@ let data = null; let timer = null; let loading = false; let activeTab = "quota"; +let generation = 0; async function load() { if (loading) return; + const operation = generation; loading = true; $("#quota-refresh").disabled = true; $("#quota-refresh").textContent = t("读取中…", "quotas.loading"); try { const value = await api("/api/model-quotas"); - if (!hasSession()) return; + if (operation !== generation || !hasSession()) return; data = value; const select = $("#quota-account"); const selected = select.value; select.replaceChildren(); for (const account of value.accounts || []) { - select.append(el("option", { value: account.id, text: `Go Key ${account.display}` })); + select.append(el("option", { + value: account.id, + text: value.source === "" ? account.display : `Go Key ${account.display}`, + })); } if ([...select.options].some((option) => option.value === selected)) select.value = selected; if (!select.options.length) select.append(el("option", { value: "", text: t("尚未配置 Go Key", "quotas.noKey") })); render(); } catch (error) { + if (operation !== generation || !hasSession()) return; $("#quota-status").textContent = t( `查询失败:${error.message}。已有显示仅为上次查询结果。`, "quotas.queryFailed", error.message, ); } finally { - loading = false; - $("#quota-refresh").disabled = false; - $("#quota-refresh").textContent = t("刷新额度", "quotas.refresh"); + if (operation === generation) { + loading = false; + $("#quota-refresh").disabled = false; + $("#quota-refresh").textContent = t("刷新额度", "quotas.refresh"); + } } } @@ -258,12 +267,15 @@ export default { title: "模型与额度", sub: "共享套餐额度与免费模型探测状态。", init() { + goAuth.init(load); bindTabs($("#page-model-quotas"), (id) => { activeTab = id; if (id === "quota") { + goAuth.show(); load(); startPolling(); } else { + goAuth.hide(); stopPolling(); loadAvailability(); } @@ -284,6 +296,7 @@ export default { }, show() { if (activeTab === "quota") { + goAuth.show(); load(); startPolling(); } else { @@ -291,10 +304,29 @@ export default { } }, hide() { + goAuth.hide(); stopPolling(); }, refresh() { - if (activeTab === "quota") load(); - else loadAvailability(); + if (activeTab === "quota") { + goAuth.refresh(); + load(); + } else loadAvailability(); + }, + reset() { + generation++; + data = null; + loading = false; + stopPolling(); + goAuth.reset(); + $("#quota-account").replaceChildren(); + $("#quota-cards").replaceChildren(); + $("#quota-models").replaceChildren(); + $("#quota-updated").textContent = ""; + $("#quota-catalog-status").textContent = ""; + $("#quota-model-count").textContent = ""; + $("#quota-refresh").disabled = false; + $("#quota-refresh").textContent = t("刷新额度", "quotas.refresh"); + $("#quota-status").textContent = t("进入页面后读取额度。", "quotas.pending"); }, };