feat(go): add browser device OAuth subscription sign-in

Add WebUI device authorization, organization selection, persisted token refresh, and fail-closed official Go subscription routing. Preserve manual keys without PAYG fallback and keep OAuth quota unknown.

Validation: offline regression checks, go vet, JavaScript syntax, and Windows/Linux amd64 compilation passed. Live subscription authorization and inference are not yet verified.

Refs #168
This commit is contained in:
Jason Xu committed 2026-11-17 05:28:09 +08:00
1 parent 95575c5fd6
commit 159d7fdf0f
23 files changed
+2187 -84

No files matched your search

+16 -7
View File
@@ -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})
+382
View File
@@ -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
}
+20 -4
View File
@@ -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,
})
}
+29 -1
View File
@@ -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())
+36 -1
View File
@@ -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").
+6
View File
@@ -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)
}
+38 -8
View File
@@ -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 {
+372
View File
@@ -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
}
+149
View File
@@ -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")
}
}
+31 -3
View File
@@ -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
}
+9 -1
View File
@@ -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()
+76 -41
View File
@@ -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
+52 -8
View File
@@ -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
}
+11 -2
View File
@@ -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))
+409
View File
@@ -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 == ""
}
+142
View File
@@ -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
}
}