发布准备:合入 #36、#46、#48、#49、#50、#53;修复 #42、#44、#51、#52,并添加 GPL-3.0-or-later。

保留 reasoning 配置,新增免费模型可用性探测 / 手动恢复、首 SSE 事件超时,元数据改用官方地址。按维护者要求,最终文件树排除测试文件。

验证:本地 Go 回归、go vet / build、Prettier、JS / shell 语法及独立实例管理端验收通过。
This commit is contained in:
Jason Xu committed 2026-10-07 19:55:34 +08:00
1 parent 31c35704be
commit df119c48e4
29 files changed
+1301 -807

No files matched your search

-65
View File
@@ -1,65 +0,0 @@
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")
}
}
}
+26
View File
@@ -0,0 +1,26 @@
package admin
import (
"net/http"
"opencode2api/internal/httpx"
)
func (a *Server) handleAvailability(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Cache-Control", "no-store")
httpx.WriteJSON(w, http.StatusOK, map[string]any{"models": a.manager.AvailabilitySnapshot()})
}
func (a *Server) handleRestoreModel(w http.ResponseWriter, r *http.Request) {
var input struct {
Model string `json:"model"`
}
if err := decodeAdminJSON(w, r, &input); err != nil {
writeAdminError(w, 400, "invalid_request", err.Error())
return
}
if err := a.manager.RestoreModel(input.Model); err != nil {
writeAdminError(w, 400, "restore_failed", a.manager.Redact(err.Error()))
return
}
a.handleAvailability(w, r)
}
-74
View File
@@ -1,74 +0,0 @@
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")
}
}
+2
View File
@@ -55,6 +55,8 @@ 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/models/availability", a.authenticate(http.HandlerFunc(a.handleAvailability)))
mux.Handle("POST /api/models/restore", a.authenticate(a.csrf(http.HandlerFunc(a.handleRestoreModel))))
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))))