mirror of
https://github.com/jasonxu114514/opencode2api.git
synced 2026-12-05 08:02:53 +00:00
feat: 新增模型轮转、额度看板和密钥管理
This commit is contained in:
1 parent
e5f4e3a583
commit
3440273f43
32 files changed
+2918
-32
No files matched your search
@@ -0,0 +1,174 @@
|
||||
package admin
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"opencode2api/internal/config"
|
||||
"opencode2api/internal/httpx"
|
||||
)
|
||||
|
||||
type APIKeyView struct {
|
||||
ID string `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Display string `json:"display"`
|
||||
Enabled bool `json:"enabled"`
|
||||
CreatedAt *time.Time `json:"created_at,omitempty"`
|
||||
}
|
||||
|
||||
func apiKeyViews(cfg config.Config) []APIKeyView {
|
||||
items := make([]APIKeyView, 0, len(cfg.ServerKeys))
|
||||
for i, key := range cfg.ServerKeys {
|
||||
id := config.Fingerprint(key)
|
||||
meta := cfg.ServerKeyMetadata[id]
|
||||
name := meta.Name
|
||||
if name == "" {
|
||||
name = fmt.Sprintf("已有 Key %d", i+1)
|
||||
}
|
||||
item := APIKeyView{ID: id, Name: name, Display: config.MaskValue(key), Enabled: !meta.Disabled}
|
||||
if !meta.CreatedAt.IsZero() {
|
||||
created := meta.CreatedAt
|
||||
item.CreatedAt = &created
|
||||
}
|
||||
items = append(items, item)
|
||||
}
|
||||
return items
|
||||
}
|
||||
|
||||
func (a *Server) handleListAPIKeys(w http.ResponseWriter, _ *http.Request) {
|
||||
w.Header().Set("Cache-Control", "no-store")
|
||||
httpx.WriteJSON(w, http.StatusOK, map[string]any{"keys": apiKeyViews(a.manager.Config())})
|
||||
}
|
||||
|
||||
func validateKeyName(name string) error {
|
||||
if name == "" || len([]rune(name)) > 80 {
|
||||
return errors.New("名称需为 1–80 个字符")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func addAPIKey(cfg *config.Config, name, key string) error {
|
||||
if err := validateKeyName(name); err != nil {
|
||||
return err
|
||||
}
|
||||
if len(key) < 16 || len(key) > 256 {
|
||||
return errors.New("自定义 Key 需为 16–256 位")
|
||||
}
|
||||
for _, ch := range key {
|
||||
if !((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') || (ch >= '0' && ch <= '9') || ch == '-' || ch == '_' || ch == '.') {
|
||||
return errors.New("Key 仅支持英文字母、数字、短横线、下划线和点")
|
||||
}
|
||||
}
|
||||
if len(cfg.ServerKeys) >= 200 {
|
||||
return errors.New("最多创建 200 个 API Key")
|
||||
}
|
||||
id := config.Fingerprint(key)
|
||||
for _, existing := range cfg.ServerKeys {
|
||||
if config.Fingerprint(existing) == id {
|
||||
return errors.New("此 API Key 已存在")
|
||||
}
|
||||
}
|
||||
if cfg.ServerKeyMetadata == nil {
|
||||
cfg.ServerKeyMetadata = map[string]config.ServerKeyMetadata{}
|
||||
}
|
||||
cfg.ServerKeys = append(cfg.ServerKeys, key)
|
||||
cfg.ServerKeyMetadata[id] = config.ServerKeyMetadata{Name: name, CreatedAt: time.Now().UTC()}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (a *Server) handleCreateAPIKey(w http.ResponseWriter, r *http.Request) {
|
||||
var input struct {
|
||||
Name string `json:"name"`
|
||||
Value string `json:"value"`
|
||||
}
|
||||
if err := decodeAdminJSON(w, r, &input); err != nil {
|
||||
writeAdminError(w, 400, "invalid_request", err.Error())
|
||||
return
|
||||
}
|
||||
key := input.Value
|
||||
if key == "" {
|
||||
var random [24]byte
|
||||
if _, err := rand.Read(random[:]); err != nil {
|
||||
writeAdminError(w, 500, "generation_failed", "无法生成密钥")
|
||||
return
|
||||
}
|
||||
key = "sk-local-" + hex.EncodeToString(random[:])
|
||||
}
|
||||
_, err := a.manager.Update(func(cfg *config.Config) error { return addAPIKey(cfg, strings.TrimSpace(input.Name), key) })
|
||||
if err != nil {
|
||||
writeAdminError(w, 400, "key_create_failed", a.manager.Redact(err.Error()))
|
||||
return
|
||||
}
|
||||
w.Header().Set("Cache-Control", "no-store")
|
||||
httpx.WriteJSON(w, 201, map[string]any{"key": key, "keys": apiKeyViews(a.manager.Config())})
|
||||
}
|
||||
|
||||
func changeAPIKey(cfg *config.Config, id string, name *string, enabled *bool, remove bool) error {
|
||||
index := -1
|
||||
for i, key := range cfg.ServerKeys {
|
||||
if config.Fingerprint(key) == id {
|
||||
index = i
|
||||
break
|
||||
}
|
||||
}
|
||||
if index < 0 {
|
||||
return errors.New("API Key 不存在,请刷新列表")
|
||||
}
|
||||
if cfg.ServerKeyMetadata == nil {
|
||||
cfg.ServerKeyMetadata = map[string]config.ServerKeyMetadata{}
|
||||
}
|
||||
if remove {
|
||||
cfg.ServerKeys = append(cfg.ServerKeys[:index], cfg.ServerKeys[index+1:]...)
|
||||
delete(cfg.ServerKeyMetadata, id)
|
||||
} else {
|
||||
meta := cfg.ServerKeyMetadata[id]
|
||||
if name != nil {
|
||||
value := strings.TrimSpace(*name)
|
||||
if err := validateKeyName(value); err != nil {
|
||||
return err
|
||||
}
|
||||
meta.Name = value
|
||||
}
|
||||
if enabled != nil {
|
||||
meta.Disabled = !*enabled
|
||||
}
|
||||
cfg.ServerKeyMetadata[id] = meta
|
||||
}
|
||||
if cfg.FirstEnabledServerKey() == "" {
|
||||
return errors.New("至少保留一个启用的 API Key,请先创建替代密钥")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (a *Server) handleUpdateAPIKey(w http.ResponseWriter, r *http.Request) {
|
||||
var input struct {
|
||||
Name *string `json:"name"`
|
||||
Enabled *bool `json:"enabled"`
|
||||
}
|
||||
if err := decodeAdminJSON(w, r, &input); err != nil {
|
||||
writeAdminError(w, 400, "invalid_request", err.Error())
|
||||
return
|
||||
}
|
||||
_, err := a.manager.Update(func(cfg *config.Config) error {
|
||||
return changeAPIKey(cfg, r.PathValue("id"), input.Name, input.Enabled, false)
|
||||
})
|
||||
if err != nil {
|
||||
writeAdminError(w, 400, "key_update_failed", a.manager.Redact(err.Error()))
|
||||
return
|
||||
}
|
||||
a.handleListAPIKeys(w, r)
|
||||
}
|
||||
|
||||
func (a *Server) handleDeleteAPIKey(w http.ResponseWriter, r *http.Request) {
|
||||
_, err := a.manager.Update(func(cfg *config.Config) error { return changeAPIKey(cfg, r.PathValue("id"), nil, nil, true) })
|
||||
if err != nil {
|
||||
writeAdminError(w, 400, "key_delete_failed", a.manager.Redact(err.Error()))
|
||||
return
|
||||
}
|
||||
a.handleListAPIKeys(w, r)
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
package admin
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"opencode2api/internal/config"
|
||||
)
|
||||
|
||||
func TestManagedKeyLifecycle(t *testing.T) {
|
||||
base := "sk-existing-1234567890"
|
||||
cfg := config.Config{ServerKeys: []string{base}}
|
||||
key := "sk-client-12345678901234"
|
||||
if err := addAPIKey(&cfg, "笔记助手", key); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := addAPIKey(&cfg, "重复", key); err == nil {
|
||||
t.Fatal("duplicate accepted")
|
||||
}
|
||||
views, _ := json.Marshal(apiKeyViews(cfg))
|
||||
if strings.Contains(string(views), key) || strings.Contains(string(views), base) {
|
||||
t.Fatal("list leaked secret")
|
||||
}
|
||||
id := config.Fingerprint(key)
|
||||
enabled := false
|
||||
candidate := config.Clone(cfg)
|
||||
if err := changeAPIKey(&candidate, id, nil, &enabled, false); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if candidate.ServerKeyEnabled(key) || !cfg.ServerKeyEnabled(key) {
|
||||
t.Fatal("clone metadata aliases source")
|
||||
}
|
||||
cfg = candidate
|
||||
name := "新的名称"
|
||||
if err := changeAPIKey(&cfg, id, &name, nil, false); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if cfg.ServerKeyMetadata[id].Name != name {
|
||||
t.Fatal("rename not applied")
|
||||
}
|
||||
if err := changeAPIKey(&cfg, config.Fingerprint(base), nil, &enabled, false); err == nil {
|
||||
t.Fatal("last active key disabled")
|
||||
}
|
||||
// Failed mutations are applied only to a clone by RuntimeManager.Update.
|
||||
cfg = config.Config{ServerKeys: []string{base, key}}
|
||||
if err := changeAPIKey(&cfg, id, nil, nil, true); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(cfg.ServerKeys) != 1 || cfg.ServerKeys[0] != base {
|
||||
t.Fatal("wrong key deleted")
|
||||
}
|
||||
if err := changeAPIKey(&cfg, config.Fingerprint(base), nil, nil, true); err == nil {
|
||||
t.Fatal("last key deleted")
|
||||
}
|
||||
}
|
||||
|
||||
func TestCustomKeyValidation(t *testing.T) {
|
||||
for _, key := range []string{"short", "long-key with-space-123", "含中文的密钥12345678901234567890", "secret\n12345678901234567890"} {
|
||||
cfg := config.Config{}
|
||||
if addAPIKey(&cfg, "test", key) == nil {
|
||||
t.Errorf("invalid key accepted")
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -115,11 +115,11 @@ func (a *Server) handleDebugInference(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
cfg := a.manager.Config()
|
||||
if len(cfg.ServerKeys) == 0 {
|
||||
if cfg.FirstEnabledServerKey() == "" {
|
||||
writeAdminError(w, http.StatusServiceUnavailable, "debug_unavailable", "no local server key is configured")
|
||||
return
|
||||
}
|
||||
request.Header.Set("Authorization", "Bearer "+cfg.ServerKeys[0])
|
||||
request.Header.Set("Authorization", "Bearer "+cfg.FirstEnabledServerKey())
|
||||
if selectedKey != nil {
|
||||
request = request.WithContext(gateway.WithDebugKeyOverride(request.Context(), gateway.DebugKeyOverride{Tier: selectedKey.Tier, KeyID: selectedKey.ID}))
|
||||
}
|
||||
|
||||
@@ -0,0 +1,171 @@
|
||||
package admin
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"opencode2api/internal/config"
|
||||
"opencode2api/internal/httpx"
|
||||
)
|
||||
|
||||
type quotaWindow struct {
|
||||
Status string `json:"status"`
|
||||
UsedPercent float64 `json:"used_percent"`
|
||||
RemainingPercent float64 `json:"remaining_percent"`
|
||||
ResetsAt time.Time `json:"resets_at"`
|
||||
}
|
||||
|
||||
type quotaAccount struct {
|
||||
ID string `json:"id"`
|
||||
Display string `json:"display"`
|
||||
Status string `json:"status"`
|
||||
Error string `json:"error,omitempty"`
|
||||
FetchedAt *time.Time `json:"fetched_at,omitempty"`
|
||||
CheckedAt time.Time `json:"checked_at"`
|
||||
Windows map[string]quotaWindow `json:"windows,omitempty"`
|
||||
}
|
||||
|
||||
type quotaCacheEntry struct {
|
||||
Account quotaAccount
|
||||
Expires time.Time
|
||||
}
|
||||
|
||||
// The first-party endpoint returns subscription-wide percentages, not balances
|
||||
// for individual models. Never infer model dollars or sum keys' shared quotas.
|
||||
// Reference: anomalyco/opencode packages/console/app/src/routes/zen/go/v1/usage.ts
|
||||
func decodeQuota(reader io.Reader) (map[string]quotaWindow, error) {
|
||||
var body struct {
|
||||
Usage map[string]struct {
|
||||
Status string `json:"status"`
|
||||
Percent *float64 `json:"percent"`
|
||||
ResetsAt time.Time `json:"resetsAt"`
|
||||
} `json:"usage"`
|
||||
}
|
||||
if err := json.NewDecoder(io.LimitReader(reader, 1<<20)).Decode(&body); err != nil {
|
||||
return nil, errors.New("OpenCode 返回的额度格式无法识别")
|
||||
}
|
||||
result := map[string]quotaWindow{}
|
||||
for _, name := range []string{"rolling", "weekly", "monthly"} {
|
||||
item, ok := body.Usage[name]
|
||||
if !ok || item.Percent == nil || *item.Percent < 0 || *item.Percent > 100 || item.ResetsAt.IsZero() || (item.Status != "ok" && item.Status != "rate-limited") {
|
||||
return nil, errors.New("OpenCode 返回的额度窗口不完整")
|
||||
}
|
||||
result[name] = quotaWindow{Status: item.Status, UsedPercent: *item.Percent, RemainingPercent: 100 - *item.Percent, ResetsAt: item.ResetsAt}
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func fetchQuota(ctx context.Context, endpoint, key string) (map[string]quotaWindow, error) {
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, endpoint, nil)
|
||||
if err != nil {
|
||||
return nil, errors.New("额度查询地址无效")
|
||||
}
|
||||
req.Header.Set("Authorization", "Bearer "+key)
|
||||
req.Header.Set("User-Agent", "opencode2api-admin/1.0")
|
||||
req.Header.Set("Accept", "application/json")
|
||||
req.Header.Set("x-opencode-session", "opencode2api-quota-"+config.Fingerprint(key))
|
||||
client := &http.Client{Timeout: 12 * time.Second, CheckRedirect: func(_ *http.Request, _ []*http.Request) error { return http.ErrUseLastResponse }}
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
return nil, errors.New("暂时无法连接 OpenCode,请稍后刷新")
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode != 200 {
|
||||
switch resp.StatusCode {
|
||||
case 401:
|
||||
return nil, errors.New("Go API Key 无效或已被撤销")
|
||||
case 403:
|
||||
return nil, errors.New("此 Key 未获准读取 Go 套餐额度")
|
||||
case 429:
|
||||
return nil, errors.New("额度查询过于频繁,请稍后刷新")
|
||||
default:
|
||||
return nil, fmt.Errorf("OpenCode 额度接口返回 HTTP %d", resp.StatusCode)
|
||||
}
|
||||
}
|
||||
return decodeQuota(resp.Body)
|
||||
}
|
||||
|
||||
func refreshQuota(ctx context.Context, endpoint, key string, previous quotaCacheEntry) quotaCacheEntry {
|
||||
now := time.Now().UTC()
|
||||
account := previous.Account
|
||||
account.ID, account.Display = config.Fingerprint(key), config.MaskValue(key)
|
||||
account.CheckedAt = now
|
||||
windows, err := fetchQuota(ctx, endpoint, key)
|
||||
if err != nil {
|
||||
account.Status, account.Error = "unavailable", err.Error()
|
||||
if account.FetchedAt != nil {
|
||||
account.Status = "stale"
|
||||
}
|
||||
return quotaCacheEntry{Account: account, Expires: now.Add(15 * time.Second)}
|
||||
}
|
||||
account.Status, account.Error, account.Windows = "ok", "", windows
|
||||
account.FetchedAt = &now
|
||||
return quotaCacheEntry{Account: account, Expires: now.Add(60 * time.Second)}
|
||||
}
|
||||
|
||||
func (a *Server) handleModelQuotas(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Cache-Control", "no-store")
|
||||
cfg := a.manager.Config()
|
||||
endpoint := strings.TrimRight(cfg.Upstream.Go, "/") + "/v1/usage"
|
||||
accounts := make([]quotaAccount, len(cfg.GoKeys))
|
||||
// Coalesce refreshes from multiple browser tabs; at most four upstream
|
||||
// queries run at a time. The cache is pruned when upstream credentials change.
|
||||
a.quotaMu.Lock()
|
||||
if a.quotaCache == nil {
|
||||
a.quotaCache = map[string]quotaCacheEntry{}
|
||||
}
|
||||
entries := make([]quotaCacheEntry, len(cfg.GoKeys))
|
||||
var wg sync.WaitGroup
|
||||
sem := make(chan struct{}, 4)
|
||||
for i, key := range cfg.GoKeys {
|
||||
cacheID := endpoint + "|" + config.Fingerprint(key)
|
||||
previous := a.quotaCache[cacheID]
|
||||
if time.Now().Before(previous.Expires) {
|
||||
entries[i] = previous
|
||||
continue
|
||||
}
|
||||
wg.Add(1)
|
||||
go func(i int, key string, previous quotaCacheEntry) {
|
||||
defer wg.Done()
|
||||
select {
|
||||
case sem <- struct{}{}:
|
||||
defer func() { <-sem }()
|
||||
case <-r.Context().Done():
|
||||
return
|
||||
}
|
||||
entries[i] = refreshQuota(r.Context(), endpoint, key, previous)
|
||||
}(i, key, previous)
|
||||
}
|
||||
wg.Wait()
|
||||
newCache := map[string]quotaCacheEntry{}
|
||||
for i, key := range cfg.GoKeys {
|
||||
newCache[endpoint+"|"+config.Fingerprint(key)] = entries[i]
|
||||
accounts[i] = entries[i].Account
|
||||
}
|
||||
a.quotaCache = newCache
|
||||
a.quotaMu.Unlock()
|
||||
all, _ := a.manager.DebugModels()
|
||||
type modelView struct {
|
||||
ID string `json:"id"`
|
||||
Protocol string `json:"protocol"`
|
||||
}
|
||||
models := []modelView{}
|
||||
for _, model := range all {
|
||||
if model.AvailableGo && model.RouteError == "" {
|
||||
protocol := model.NativeProtocols[config.TierGo]
|
||||
models = append(models, modelView{ID: model.Model, Protocol: string(protocol)})
|
||||
}
|
||||
}
|
||||
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 可能属于同一套餐,不能相加。百分比由上游取整。",
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
package admin
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
const validQuota = `{"usage":{"rolling":{"status":"ok","percent":19,"resetsAt":"2026-09-20T12:00:00Z"},"weekly":{"status":"rate-limited","percent":100,"resetsAt":"2026-09-21T00:00:00Z"},"monthly":{"status":"ok","percent":0,"resetsAt":"2026-10-20T00:00:00Z"}}}`
|
||||
|
||||
func TestQuotaDecode(t *testing.T) {
|
||||
windows, err := decodeQuota(strings.NewReader(validQuota))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if windows["rolling"].RemainingPercent != 81 || windows["weekly"].RemainingPercent != 0 || windows["monthly"].RemainingPercent != 100 {
|
||||
t.Fatal("incorrect percentage semantics")
|
||||
}
|
||||
for _, raw := range []string{`{}`, strings.Replace(validQuota, `"percent":19`, `"percent":null`, 1), strings.Replace(validQuota, `"percent":19`, `"percent":101`, 1), strings.Replace(validQuota, "2026-09-20T12:00:00Z", "invalid", 1), strings.Replace(validQuota, `"status":"ok"`, `"status":"unknown"`, 1)} {
|
||||
if _, err := decodeQuota(strings.NewReader(raw)); err == nil {
|
||||
t.Fatal("malformed quota accepted")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestQuotaFailureRetainsLastGoodAndRedacts(t *testing.T) {
|
||||
failing := false
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Header.Get("Authorization") != "Bearer test-upstream-secret" {
|
||||
t.Error("missing authorization")
|
||||
}
|
||||
if r.Header.Get("User-Agent") != "opencode2api-admin/1.0" {
|
||||
t.Error("incorrect identity")
|
||||
}
|
||||
if failing {
|
||||
w.WriteHeader(401)
|
||||
w.Write([]byte(`{"error":"test-upstream-secret"}`))
|
||||
return
|
||||
}
|
||||
w.Write([]byte(validQuota))
|
||||
}))
|
||||
defer srv.Close()
|
||||
first := refreshQuota(context.Background(), srv.URL, "test-upstream-secret", quotaCacheEntry{})
|
||||
if first.Account.Status != "ok" {
|
||||
t.Fatal(first.Account.Error)
|
||||
}
|
||||
failing = true
|
||||
stale := refreshQuota(context.Background(), srv.URL, "test-upstream-secret", first)
|
||||
if stale.Account.Status != "stale" || stale.Account.Windows["rolling"].RemainingPercent != 81 || !stale.Account.FetchedAt.Equal(*first.Account.FetchedAt) {
|
||||
t.Fatal("last known quota lost")
|
||||
}
|
||||
encoded, _ := json.Marshal(stale.Account)
|
||||
if strings.Contains(string(encoded), "test-upstream-secret") {
|
||||
t.Fatal("secret leaked")
|
||||
}
|
||||
missing := refreshQuota(context.Background(), srv.URL, "test-upstream-secret", quotaCacheEntry{})
|
||||
if missing.Account.Status != "unavailable" || missing.Account.Windows != nil {
|
||||
t.Fatal("invented unavailable balance")
|
||||
}
|
||||
}
|
||||
|
||||
func TestQuotaDoesNotFollowRedirect(t *testing.T) {
|
||||
reached := false
|
||||
target := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { reached = true }))
|
||||
defer target.Close()
|
||||
source := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { http.Redirect(w, r, target.URL, 302) }))
|
||||
defer source.Close()
|
||||
if _, err := fetchQuota(context.Background(), source.URL, "secret"); err == nil || reached {
|
||||
t.Fatal("redirect leaked credentials")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
package admin
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
"opencode2api/internal/config"
|
||||
"opencode2api/internal/httpx"
|
||||
"slices"
|
||||
)
|
||||
|
||||
func (a *Server) handleRotation(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Cache-Control", "no-store")
|
||||
httpx.WriteJSON(w, 200, a.manager.RotationSnapshot())
|
||||
}
|
||||
func (a *Server) handleSaveRotation(w http.ResponseWriter, r *http.Request) {
|
||||
var input config.RotationConfig
|
||||
if err := decodeAdminJSON(w, r, &input); err != nil {
|
||||
writeAdminError(w, 400, "invalid_request", err.Error())
|
||||
return
|
||||
}
|
||||
_, err := a.manager.Update(func(cfg *config.Config) error {
|
||||
if err := input.Validate(nil); err != nil {
|
||||
return err
|
||||
}
|
||||
state := a.manager.RotationSnapshot()
|
||||
for i, g := range state.Groups {
|
||||
order := input.SOTA.Order
|
||||
if i == 1 {
|
||||
order = input.Sweet.Order
|
||||
}
|
||||
if len(order) != len(g.Order) {
|
||||
return fmt.Errorf("模型列表已更新,请刷新后重新排序")
|
||||
}
|
||||
for _, v := range order {
|
||||
if !slices.Contains(g.Order, v) {
|
||||
return fmt.Errorf("只能调整组内模型的顺序")
|
||||
}
|
||||
}
|
||||
}
|
||||
cfg.Rotation = input
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
writeAdminError(w, 400, "rotation_rejected", a.manager.Redact(err.Error()))
|
||||
return
|
||||
}
|
||||
a.handleRotation(w, r)
|
||||
}
|
||||
func (a *Server) handleSelectRotation(w http.ResponseWriter, r *http.Request) {
|
||||
var input struct {
|
||||
Group string `json:"group"`
|
||||
Model string `json:"model"`
|
||||
}
|
||||
if err := decodeAdminJSON(w, r, &input); err != nil {
|
||||
writeAdminError(w, 400, "invalid_request", err.Error())
|
||||
return
|
||||
}
|
||||
if err := a.manager.SelectRotation(input.Group, input.Model); err != nil {
|
||||
writeAdminError(w, 400, "rotation_rejected", a.manager.Redact(err.Error()))
|
||||
return
|
||||
}
|
||||
a.handleRotation(w, r)
|
||||
}
|
||||
@@ -32,6 +32,8 @@ type Server struct {
|
||||
attempts map[string]loginWindow
|
||||
debugAttempts map[string]loginWindow
|
||||
lastInference *DebugInferenceResult
|
||||
quotaMu sync.Mutex
|
||||
quotaCache map[string]quotaCacheEntry
|
||||
}
|
||||
|
||||
func New(manager *gateway.RuntimeManager, monitor *telemetry.Monitor, logs *telemetry.LogHub, logger *slog.Logger) *Server {
|
||||
@@ -53,6 +55,14 @@ func (a *Server) Handler() http.Handler {
|
||||
mux.Handle("PUT /api/account", a.authenticate(a.csrf(http.HandlerFunc(a.handleAccount))))
|
||||
mux.Handle("GET /api/monitor", a.authenticate(http.HandlerFunc(a.handleMonitor)))
|
||||
mux.Handle("GET /api/debug/models", a.authenticate(http.HandlerFunc(a.handleDebugModels)))
|
||||
mux.Handle("GET /api/rotation", a.authenticate(http.HandlerFunc(a.handleRotation)))
|
||||
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/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))))
|
||||
mux.Handle("DELETE /api/api-keys/{id}", a.authenticate(a.csrf(http.HandlerFunc(a.handleDeleteAPIKey))))
|
||||
mux.Handle("POST /api/debug/inference", a.authenticate(a.csrf(http.HandlerFunc(a.handleDebugInference))))
|
||||
mux.Handle("GET /api/logs", a.authenticate(http.HandlerFunc(a.handleLogs)))
|
||||
mux.Handle("GET /api/logs/stream", a.authenticate(http.HandlerFunc(a.handleLogStream)))
|
||||
@@ -181,7 +191,9 @@ func (a *Server) handlePutConfig(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
candidate := config.Config{
|
||||
Listen: update.Listen, ServerKeys: serverKeys, ZenKeys: zenKeys, GoKeys: goKeys, Anonymous: update.Anonymous, Proxies: proxies, ProxyFile: update.ProxyFile,
|
||||
ServerKeyMetadata: current.ServerKeyMetadata,
|
||||
Rotation: current.Rotation,
|
||||
Listen: update.Listen, ServerKeys: serverKeys, ZenKeys: zenKeys, GoKeys: goKeys, Anonymous: update.Anonymous, Proxies: proxies, ProxyFile: update.ProxyFile,
|
||||
Upstream: update.Upstream, Retry: update.Retry, Models: update.Models, Performance: update.Performance, Logging: update.Logging, Prefer: update.Prefer,
|
||||
WebUI: config.WebUIConfig{Enabled: update.WebUI.Enabled, Listen: update.WebUI.Listen, Username: current.WebUI.Username, PasswordHash: current.WebUI.PasswordHash, SessionTTLMinutes: update.WebUI.SessionTTLMinutes},
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user