diff --git a/internal/app/admin.go b/internal/app/admin.go index 4a6be41..8e5207e 100644 --- a/internal/app/admin.go +++ b/internal/app/admin.go @@ -10,6 +10,8 @@ import ( "strings" "sync" "time" + + "cmdcode2api/internal/i18n" ) // registerAdminRoutes wires the admin JSON API used by the WebUI. It must be @@ -46,8 +48,11 @@ func writeAdminJSON(w http.ResponseWriter, status int, payload any) { json.NewEncoder(w).Encode(payload) } -func writeAdminError(w http.ResponseWriter, status int, msg string) { - writeAdminJSON(w, status, map[string]any{"error": msg}) +// writeAdminError answers with an error message localized for the caller's +// Accept-Language. Messages are written in English at the call site; English is +// also the fallback, so an unsupported language changes nothing. +func writeAdminError(w http.ResponseWriter, r *http.Request, status int, msg string) { + writeAdminJSON(w, status, map[string]any{"error": i18n.Message(i18n.FromRequest(r), msg)}) } func subtleConstantTimeEqual(a, b string) bool { @@ -62,14 +67,35 @@ type adminAccount struct { Quota *QuotaSnapshot `json:"quota,omitempty"` } -func adminAccountViews(pool *AccountPool, usage *UsageTracker) []adminAccount { +// localizeQuotaSnapshot returns a shallow copy of snap with the user-facing +// error texts (LastError, Failures) translated to the request language. The +// stored snapshot keeps English sources; only the admin API copy is localized. +// English returns the snapshot unchanged, matching i18n's EN-is-source design. +func localizeQuotaSnapshot(lang i18n.Lang, snap *QuotaSnapshot) *QuotaSnapshot { + if snap == nil || lang == i18n.EN || (snap.LastError == "" && len(snap.Failures) == 0) { + return snap + } + out := *snap + if out.LastError != "" { + out.LastError = i18n.Message(lang, out.LastError) + } + if len(out.Failures) > 0 { + out.Failures = make([]string, len(snap.Failures)) + for i, f := range snap.Failures { + out.Failures[i] = i18n.Message(lang, f) + } + } + return &out +} + +func adminAccountViews(pool *AccountPool, usage *UsageTracker, r *http.Request) []adminAccount { views := pool.Views() out := make([]adminAccount, 0, len(views)) for _, v := range views { out = append(out, adminAccount{ AccountView: v, UsageSnapshotEntry: usage.AccountUsage(v.ID), - Quota: usage.Quota(v.ID), + Quota: localizeQuotaSnapshot(i18n.FromRequest(r), usage.Quota(v.ID)), }) } return out @@ -164,7 +190,7 @@ func quotaSummary(pool *AccountPool, usage *UsageTracker) adminQuotaSummary { func handleAdminAccountsList(pool *AccountPool, usage *UsageTracker) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { - writeAdminJSON(w, 200, map[string]any{"accounts": adminAccountViews(pool, usage)}) + writeAdminJSON(w, 200, map[string]any{"accounts": adminAccountViews(pool, usage, r)}) } } @@ -175,7 +201,7 @@ func handleAdminAccountAdd(pool *AccountPool, cfg *Config, usage *UsageTracker, APIKey string `json:"api_key"` } if err := decodeJSONBody(w, r, &body); err != nil { - writeAdminError(w, 400, err.Error()) + writeAdminError(w, r, 400, err.Error()) return } body.Name = strings.TrimSpace(body.Name) @@ -184,11 +210,11 @@ func handleAdminAccountAdd(pool *AccountPool, cfg *Config, usage *UsageTracker, } acct, err := pool.Add(body.Name, body.APIKey, true) if err != nil { - writeAdminError(w, http.StatusConflict, err.Error()) + writeAdminError(w, r, http.StatusConflict, err.Error()) return } if err := persistPool(pool, cfg); err != nil { - writeAdminError(w, 500, "account added but saving config failed: "+err.Error()) + writeAdminError(w, r, 500, "account added but saving config failed: "+err.Error()) return } // Started without accounts? The model catalog is empty then; fetch it @@ -213,16 +239,16 @@ func handleAdminAccountPatch(pool *AccountPool, cfg *Config, usage *UsageTracker APIKey *string `json:"api_key"` } if err := decodeJSONBody(w, r, &body); err != nil { - writeAdminError(w, 400, err.Error()) + writeAdminError(w, r, 400, err.Error()) return } if body.Enabled != nil && !pool.SetEnabled(id, *body.Enabled) { - writeAdminError(w, 404, "account not found") + writeAdminError(w, r, 404, "account not found") return } if body.Name != nil { if !pool.Rename(id, strings.TrimSpace(*body.Name)) { - writeAdminError(w, 404, "account not found") + writeAdminError(w, r, 404, "account not found") return } } @@ -230,7 +256,7 @@ func handleAdminAccountPatch(pool *AccountPool, cfg *Config, usage *UsageTracker if body.APIKey != nil { newID, err := pool.SetKey(id, *body.APIKey) if err != nil { - writeAdminError(w, http.StatusConflict, err.Error()) + writeAdminError(w, r, http.StatusConflict, err.Error()) return } // The ID derives from the key; carry the usage history over, but @@ -241,7 +267,7 @@ func handleAdminAccountPatch(pool *AccountPool, cfg *Config, usage *UsageTracker keyChanged = true } if err := persistPool(pool, cfg); err != nil { - writeAdminError(w, 500, "saving config failed: "+err.Error()) + writeAdminError(w, r, 500, "saving config failed: "+err.Error()) return } acct := pool.Get(id) @@ -256,12 +282,12 @@ func handleAdminAccountDelete(pool *AccountPool, cfg *Config, usage *UsageTracke return func(w http.ResponseWriter, r *http.Request) { id := r.PathValue("id") if !pool.Remove(id) { - writeAdminError(w, 404, "account not found") + writeAdminError(w, r, 404, "account not found") return } usage.DropAccount(id) if err := persistPool(pool, cfg); err != nil { - writeAdminError(w, 500, "saving config failed: "+err.Error()) + writeAdminError(w, r, 500, "saving config failed: "+err.Error()) return } writeAdminJSON(w, 200, map[string]any{"deleted": true}) @@ -274,15 +300,15 @@ func handleAdminAccountQuotaRefresh(pool *AccountPool, usage *UsageTracker, quot return func(w http.ResponseWriter, r *http.Request) { acct := pool.Get(r.PathValue("id")) if acct == nil { - writeAdminError(w, 404, "account not found") + writeAdminError(w, r, 404, "account not found") return } if quotas == nil { - writeAdminError(w, http.StatusServiceUnavailable, "quota service unavailable") + writeAdminError(w, r, http.StatusServiceUnavailable, "quota service unavailable") return } quotas.RefreshAccount(r.Context(), acct) - writeAdminJSON(w, 200, adminAccount{AccountView: acct.View(), UsageSnapshotEntry: usage.AccountUsage(acct.ID), Quota: usage.Quota(acct.ID)}) + writeAdminJSON(w, 200, adminAccount{AccountView: acct.View(), UsageSnapshotEntry: usage.AccountUsage(acct.ID), Quota: localizeQuotaSnapshot(i18n.FromRequest(r), usage.Quota(acct.ID))}) } } @@ -293,7 +319,7 @@ func handleAdminAccountQuotaRefresh(pool *AccountPool, usage *UsageTracker, quot func handleAdminQuotaRefreshAll(pool *AccountPool, usage *UsageTracker, quotas *QuotaService) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { if quotas == nil { - writeAdminError(w, http.StatusServiceUnavailable, "quota service unavailable") + writeAdminError(w, r, http.StatusServiceUnavailable, "quota service unavailable") return } var body struct { @@ -305,11 +331,11 @@ func handleAdminQuotaRefreshAll(pool *AccountPool, usage *UsageTracker, quotas * if body.ID != "" { acct := pool.Get(body.ID) if acct == nil { - writeAdminError(w, 404, "account not found") + writeAdminError(w, r, 404, "account not found") return } quotas.RefreshAccount(r.Context(), acct) - writeAdminJSON(w, 200, map[string]any{"accounts": adminAccountViews(pool, usage)}) + writeAdminJSON(w, 200, map[string]any{"accounts": adminAccountViews(pool, usage, r)}) return } queued := quotas.RefreshAllAsync() @@ -347,7 +373,7 @@ func handleAdminModelsPut(cfg *Config) http.HandlerFunc { Exposed []string `json:"exposed"` } if err := decodeJSONBody(w, r, &body); err != nil { - writeAdminError(w, 400, err.Error()) + writeAdminError(w, r, 400, err.Error()) return } exposed := make(map[string]bool, len(body.Exposed)) @@ -381,7 +407,7 @@ func handleAdminModelsPut(cfg *Config) http.HandlerFunc { cfg.SetExcludes(excludes) if err := saveConfig(configFile, cfg); err != nil { - writeAdminError(w, 500, "applied but saving config failed: "+err.Error()) + writeAdminError(w, r, 500, "applied but saving config failed: "+err.Error()) return } log.Printf("model exposure updated via webui (%d exposed, %d excluded)", len(exposed), len(excludes)) @@ -421,7 +447,7 @@ func handleAdminKeyAdd(keys *ClientKeyPool, cfg *Config, usage *UsageTracker) ht Name string `json:"name"` } if err := decodeJSONBody(w, r, &body); err != nil { - writeAdminError(w, 400, err.Error()) + writeAdminError(w, r, 400, err.Error()) return } body.Name = strings.TrimSpace(body.Name) @@ -430,11 +456,11 @@ func handleAdminKeyAdd(keys *ClientKeyPool, cfg *Config, usage *UsageTracker) ht } key, err := keys.Add(body.Name, "", true) if err != nil { - writeAdminError(w, http.StatusConflict, err.Error()) + writeAdminError(w, r, http.StatusConflict, err.Error()) return } if err := persistKeys(keys, cfg); err != nil { - writeAdminError(w, 500, "key created but saving config failed: "+err.Error()) + writeAdminError(w, r, 500, "key created but saving config failed: "+err.Error()) return } log.Printf("client key %q added via webui", key.Name) @@ -454,7 +480,7 @@ func handleAdminKeyReveal(keys *ClientKeyPool) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { key := keys.Get(r.PathValue("id")) if key == nil { - writeAdminError(w, 404, "key not found") + writeAdminError(w, r, 404, "key not found") return } writeAdminJSON(w, 200, map[string]any{"id": key.ID, "key": key.Key}) @@ -469,21 +495,21 @@ func handleAdminKeyPatch(keys *ClientKeyPool, cfg *Config, usage *UsageTracker) Name *string `json:"name"` } if err := decodeJSONBody(w, r, &body); err != nil { - writeAdminError(w, 400, err.Error()) + writeAdminError(w, r, 400, err.Error()) return } if body.Enabled != nil && !keys.SetEnabled(id, *body.Enabled) { - writeAdminError(w, 404, "key not found") + writeAdminError(w, r, 404, "key not found") return } if body.Name != nil { if !keys.Rename(id, strings.TrimSpace(*body.Name)) { - writeAdminError(w, 404, "key not found") + writeAdminError(w, r, 404, "key not found") return } } if err := persistKeys(keys, cfg); err != nil { - writeAdminError(w, 500, "saving config failed: "+err.Error()) + writeAdminError(w, r, 500, "saving config failed: "+err.Error()) return } key := keys.Get(id) @@ -495,12 +521,12 @@ func handleAdminKeyDelete(keys *ClientKeyPool, cfg *Config, usage *UsageTracker) return func(w http.ResponseWriter, r *http.Request) { id := r.PathValue("id") if !keys.Remove(id) { - writeAdminError(w, 404, "key not found") + writeAdminError(w, r, 404, "key not found") return } usage.DropClientKey(id) if err := persistKeys(keys, cfg); err != nil { - writeAdminError(w, 500, "saving config failed: "+err.Error()) + writeAdminError(w, r, 500, "saving config failed: "+err.Error()) return } writeAdminJSON(w, 200, map[string]any{"deleted": true}) @@ -513,7 +539,7 @@ func handleAdminAccountTest(pool *AccountPool, cc *CCClient) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { acct := pool.Get(r.PathValue("id")) if acct == nil { - writeAdminError(w, 404, "account not found") + writeAdminError(w, r, 404, "account not found") return } result := testAccountKey(cc.BaseURLValue(), acct.APIKey) @@ -606,17 +632,17 @@ func handleAdminSettingsPut(cfg *Config, cc *CCClient, pool *AccountPool) http.H return func(w http.ResponseWriter, r *http.Request) { var body adminSettingsUpdate if err := decodeJSONBody(w, r, &body); err != nil { - writeAdminError(w, 400, err.Error()) + writeAdminError(w, r, 400, err.Error()) return } // 修改管理密码必须提供原密码;错误即拒绝,不泄露当前值。 if body.AdminPassword != nil && len(strings.TrimSpace(*body.AdminPassword)) < 8 { - writeAdminError(w, 400, "admin_password must be at least 8 characters") + writeAdminError(w, r, 400, "admin_password must be at least 8 characters") return } if body.AdminPassword != nil { if body.OldPassword == nil || !subtleConstantTimeEqual(*body.OldPassword, cfg.adminPassword()) { - writeAdminError(w, http.StatusForbidden, "当前管理密码不正确") + writeAdminError(w, r, http.StatusForbidden, "current admin password is incorrect") return } } @@ -629,7 +655,7 @@ func handleAdminSettingsPut(cfg *Config, cc *CCClient, pool *AccountPool) http.H if body.BaseURL != nil { url := strings.TrimSpace(*body.BaseURL) if url == "" { - writeAdminError(w, 400, "base_url cannot be empty") + writeAdminError(w, r, 400, "base_url cannot be empty") return } cfg.SetUpstreamBaseURL(url) @@ -638,7 +664,7 @@ func handleAdminSettingsPut(cfg *Config, cc *CCClient, pool *AccountPool) http.H if body.AdminPassword != nil { password := strings.TrimSpace(*body.AdminPassword) if len(password) < 8 { - writeAdminError(w, 400, "admin_password must be at least 8 characters") + writeAdminError(w, r, 400, "admin_password must be at least 8 characters") return } // 管理认证就是密码本身:改完即踢出所有已持有的旧凭据。 @@ -660,7 +686,7 @@ func handleAdminSettingsPut(cfg *Config, cc *CCClient, pool *AccountPool) http.H // Keep the persisted config consistent with the live pool. pool.SyncToConfig(cfg) if err := saveConfig(configFile, cfg); err != nil { - writeAdminError(w, 500, "applied but saving config failed: "+err.Error()) + writeAdminError(w, r, 500, "applied but saving config failed: "+err.Error()) return } log.Printf("settings updated via webui (restart required: %v)", restartRequired) @@ -713,7 +739,7 @@ func handleAdminOAuthStart(pool *AccountPool, cfg *Config, quotas *QuotaService) opts := OAuthOptions{} if body.CallbackURL != "" { if err := validateCallbackURL(body.CallbackURL); err != nil { - writeAdminError(w, 400, err.Error()) + writeAdminError(w, r, 400, err.Error()) return } // 自定义回调走网关自身的公开回调端点,浏览器可达即可, @@ -732,7 +758,7 @@ func handleAdminOAuthStart(pool *AccountPool, cfg *Config, quotas *QuotaService) flow, err := StartOAuthFlow(opts) if err != nil { webOAuthMu.Unlock() - writeAdminError(w, 500, err.Error()) + writeAdminError(w, r, 500, err.Error()) return } webOAuthFlow = flow @@ -792,7 +818,7 @@ func handleAdminOAuthStatus(pool *AccountPool) http.HandlerFunc { } case "failed": if err := flow.Err(); err != nil { - resp["error"] = err.Error() + resp["error"] = i18n.Message(i18n.FromRequest(r), err.Error()) } } writeAdminJSON(w, 200, resp) @@ -830,7 +856,7 @@ func handleWebOAuthCallback() http.HandlerFunc { if r.Method != "POST" { w.Header().Set("Content-Type", "application/json") w.WriteHeader(405) - json.NewEncoder(w).Encode(map[string]any{"success": false, "error": "method not allowed"}) + json.NewEncoder(w).Encode(map[string]any{"success": false, "error": i18n.Message(i18n.FromRequest(r), "method not allowed")}) return } @@ -840,7 +866,7 @@ func handleWebOAuthCallback() http.HandlerFunc { if flow == nil || flow.StateName() != "pending" { w.Header().Set("Content-Type", "application/json") w.WriteHeader(400) - json.NewEncoder(w).Encode(map[string]any{"success": false, "error": "no pending OAuth flow"}) + json.NewEncoder(w).Encode(map[string]any{"success": false, "error": i18n.Message(i18n.FromRequest(r), "no pending OAuth flow")}) return } @@ -848,7 +874,7 @@ func handleWebOAuthCallback() http.HandlerFunc { if err := json.NewDecoder(io.LimitReader(r.Body, 64*1024)).Decode(&cb); err != nil { w.Header().Set("Content-Type", "application/json") w.WriteHeader(400) - json.NewEncoder(w).Encode(map[string]any{"success": false, "error": "invalid JSON"}) + json.NewEncoder(w).Encode(map[string]any{"success": false, "error": i18n.Message(i18n.FromRequest(r), "invalid JSON")}) return } if errMsg, _ := r.URL.Query()["error"]; len(errMsg) > 0 { @@ -861,14 +887,14 @@ func handleWebOAuthCallback() http.HandlerFunc { if cb.APIKey == "" || cb.State == "" { w.Header().Set("Content-Type", "application/json") w.WriteHeader(400) - json.NewEncoder(w).Encode(map[string]any{"success": false, "error": "缺少必要字段"}) + json.NewEncoder(w).Encode(map[string]any{"success": false, "error": i18n.Message(i18n.FromRequest(r), "api_key and state are required")}) return } if err := flow.deliver(cb); err != nil { w.Header().Set("Content-Type", "application/json") w.WriteHeader(400) - json.NewEncoder(w).Encode(map[string]any{"success": false, "error": err.Error()}) + json.NewEncoder(w).Encode(map[string]any{"success": false, "error": i18n.Message(i18n.FromRequest(r), err.Error())}) return } w.Header().Set("Content-Type", "application/json") diff --git a/internal/app/admin_i18n_test.go b/internal/app/admin_i18n_test.go new file mode 100644 index 0000000..444360f --- /dev/null +++ b/internal/app/admin_i18n_test.go @@ -0,0 +1,137 @@ +package app + +import ( + "bytes" + "encoding/json" + "net/http" + "net/http/httptest" + "path/filepath" + "strings" + "testing" +) + +// adminRequestIn mirrors adminRequest but sets Accept-Language, which is what +// the WebUI sends to have the admin API answer in the selected UI language. +func adminRequestIn(t *testing.T, srv *httptest.Server, method, path, password, lang string, body any) (*http.Response, map[string]any) { + t.Helper() + var reader *bytes.Reader + if body != nil { + data, _ := json.Marshal(body) + reader = bytes.NewReader(data) + } else { + reader = bytes.NewReader(nil) + } + req, err := http.NewRequest(method, srv.URL+path, reader) + if err != nil { + t.Fatal(err) + } + req.Header.Set("Authorization", "Bearer "+password) + if lang != "" { + req.Header.Set("Accept-Language", lang) + } + resp, err := http.DefaultClient.Do(req) + if err != nil { + t.Fatal(err) + } + defer resp.Body.Close() + var payload map[string]any + if err := json.NewDecoder(resp.Body).Decode(&payload); err != nil { + t.Fatalf("decode %s %s: %v", method, path, err) + } + return resp, payload +} + +func errorOf(t *testing.T, payload map[string]any) string { + t.Helper() + msg, _ := payload["error"].(string) + if msg == "" { + t.Fatalf("payload has no error message: %#v", payload) + } + return msg +} + +// TestAdminErrorsFollowAcceptLanguage covers the three ways a message reaches +// the client: messages composed in the handler, messages produced by a deeper +// layer, and errors that wrap an underlying cause. +func TestAdminErrorsFollowAcceptLanguage(t *testing.T) { + srv, _, _, _, _, _ := newAdminTestEnv(t) + + t.Run("handler message, chinese", func(t *testing.T) { + resp, payload := adminRequestIn(t, srv, "PATCH", "/admin/api/accounts/missing", "admin-pass-123", "zh-CN,zh;q=0.9,en;q=0.8", map[string]any{"enabled": false}) + if resp.StatusCode != http.StatusNotFound { + t.Fatalf("status = %d, want 404", resp.StatusCode) + } + if got := errorOf(t, payload); got != "账号不存在" { + t.Errorf("error = %q, want %q", got, "账号不存在") + } + }) + + t.Run("handler message, english default", func(t *testing.T) { + resp, payload := adminRequestIn(t, srv, "PATCH", "/admin/api/accounts/missing", "admin-pass-123", "de-DE,de;q=0.9", map[string]any{"enabled": false}) + if resp.StatusCode != http.StatusNotFound { + t.Fatalf("status = %d, want 404", resp.StatusCode) + } + if got := errorOf(t, payload); got != "account not found" { + t.Errorf("error = %q, want %q", got, "account not found") + } + }) + + t.Run("domain layer message", func(t *testing.T) { + resp, payload := adminRequestIn(t, srv, "POST", "/admin/api/accounts", "admin-pass-123", "zh-CN", map[string]any{"name": "empty-key"}) + if resp.StatusCode != http.StatusConflict { + t.Fatalf("status = %d, want 409", resp.StatusCode) + } + if got := errorOf(t, payload); got != "api_key 不能为空" { + t.Errorf("error = %q, want %q", got, "api_key 不能为空") + } + }) + + t.Run("wrapped cause keeps its detail", func(t *testing.T) { + // Point persistence into a directory that does not exist, so saving + // fails and the handler wraps the filesystem error. + configFile = filepath.Join(t.TempDir(), "missing-dir", "config.yaml") + resp, payload := adminRequestIn(t, srv, "PUT", "/admin/api/settings", "admin-pass-123", "zh-CN", map[string]any{"base_url": "https://api.example.test"}) + if resp.StatusCode != http.StatusInternalServerError { + t.Fatalf("status = %d, want 500", resp.StatusCode) + } + got := errorOf(t, payload) + if !strings.HasPrefix(got, "已应用,但保存配置失败:") { + t.Errorf("error = %q, want the localized wrapper prefix", got) + } + if !strings.Contains(got, "missing-dir") { + t.Errorf("error = %q, want the underlying cause kept verbatim", got) + } + }) +} + +// TestAdminAuthErrorsFollowAcceptLanguage localizes the middleware, which +// answers before any handler runs, including the lockout message. +func TestAdminAuthErrorsFollowAcceptLanguage(t *testing.T) { + srv, _, _, _, _, _ := newAdminTestEnv(t) + + resp, payload := adminRequestIn(t, srv, "GET", "/admin/api/overview", "wrong", "zh-CN", nil) + if resp.StatusCode != http.StatusUnauthorized { + t.Fatalf("status = %d, want 401", resp.StatusCode) + } + if got := errorOf(t, payload); got != "管理密码不正确" { + t.Errorf("error = %q, want %q", got, "管理密码不正确") + } + + // Repeated failures arm the lockout; the lockout message is localized too. + locked := false + for i := 0; i < adminFailLimit+1 && !locked; i++ { + attempt, _ := adminRequestIn(t, srv, "GET", "/admin/api/overview", "wrong", "zh-CN", nil) + locked = attempt.StatusCode == http.StatusTooManyRequests + } + if !locked { + t.Fatal("admin auth never locked out after repeated failures") + } + resp, payload = adminRequestIn(t, srv, "GET", "/admin/api/overview", "admin-pass-123", "zh-CN", nil) + if resp.StatusCode != http.StatusTooManyRequests { + t.Fatalf("status = %d, want 429", resp.StatusCode) + } + got := errorOf(t, payload) + if !strings.HasPrefix(got, "失败次数过多,请 ") || !strings.HasSuffix(got, " 秒后重试") { + t.Errorf("error = %q, want the localized lockout message", got) + } +} diff --git a/internal/app/admin_test.go b/internal/app/admin_test.go index 44c684b..83f1454 100644 --- a/internal/app/admin_test.go +++ b/internal/app/admin_test.go @@ -10,6 +10,8 @@ import ( "path/filepath" "strings" "testing" + + "cmdcode2api/internal/i18n" ) // newAdminTestEnv starts an admin API server backed by temp-dir persistence. @@ -400,3 +402,39 @@ func TestConfigFileRedirectedForAdminPersistence(t *testing.T) { t.Fatalf("config file not written: %v", err) } } + +func TestLocalizeQuotaSnapshot(t *testing.T) { + snap := &QuotaSnapshot{ + LastError: "API key rejected: HTTP 401", + Failures: []string{"whoami: context deadline exceeded", "quota endpoints returned no data"}, + } + + // English (the source of truth) returns the snapshot unchanged. + if got := localizeQuotaSnapshot(i18n.EN, snap); got != snap { + t.Fatalf("EN should return the same snapshot, got %+v", got) + } + + // Chinese translates both fields and leaves the stored snapshot intact. + got := localizeQuotaSnapshot(i18n.ZHCN, snap) + if got.LastError != "API Key 被拒绝:HTTP 401" { + t.Fatalf("LastError = %q", got.LastError) + } + wantFailures := []string{"whoami: context deadline exceeded", "额度接口返回空数据"} + if len(got.Failures) != len(wantFailures) || got.Failures[0] != wantFailures[0] || got.Failures[1] != wantFailures[1] { + t.Fatalf("Failures = %v, want %v", got.Failures, wantFailures) + } + if snap.LastError != "API key rejected: HTTP 401" || len(snap.Failures) != 2 { + t.Fatalf("stored snapshot was mutated: %+v", snap) + } + + // A snapshot without error texts is passed through untouched. + clean := &QuotaSnapshot{MonthlyCredits: floatPtr(1)} + if got := localizeQuotaSnapshot(i18n.ZHCN, clean); got != clean { + t.Fatalf("clean snapshot should be returned as-is, got %+v", got) + } + + // Nil is nil-safe (mirrors usage.Quota returning nil for unknown accounts). + if got := localizeQuotaSnapshot(i18n.ZHCN, nil); got != nil { + t.Fatalf("nil snapshot = %+v, want nil", got) + } +} diff --git a/internal/app/oauth.go b/internal/app/oauth.go index a4432e8..54b3940 100644 --- a/internal/app/oauth.go +++ b/internal/app/oauth.go @@ -96,7 +96,7 @@ func StartOAuthFlow(opts OAuthOptions) (*OAuthFlow, error) { } } if err != nil { - return nil, fmt.Errorf("无法启动回调服务器: %w", err) + return nil, fmt.Errorf("start callback server: %w", err) } } @@ -142,7 +142,7 @@ func StartOAuthFlow(opts OAuthOptions) (*OAuthFlow, error) { w.Header().Set("Content-Type", "application/json") w.WriteHeader(200) json.NewEncoder(w).Encode(map[string]any{"success": true}) - errCh <- fmt.Errorf("授权被取消: %s", errMsg[0]) + errCh <- fmt.Errorf("authorization canceled: %s", errMsg[0]) return } @@ -151,7 +151,7 @@ func StartOAuthFlow(opts OAuthOptions) (*OAuthFlow, error) { w.WriteHeader(400) json.NewEncoder(w).Encode(map[string]any{ "success": false, - "error": "缺少必要字段", + "error": "api_key and state are required", }) return } @@ -239,7 +239,7 @@ func (f *OAuthFlow) deliver(cb oauthCallback) error { default: } if cb.State != f.State { - return fmt.Errorf("state token 不匹配,可能被篡改") + return fmt.Errorf("state token mismatch (possible tampering)") } f.mu.Lock() f.result = &cb @@ -259,7 +259,7 @@ func (f *OAuthFlow) Wait(timeout time.Duration) (oauthCallback, error) { select { case cb := <-f.resultCh: if cb.State != f.State { - err := fmt.Errorf("state token 不匹配,可能被篡改") + err := fmt.Errorf("state token mismatch (possible tampering)") f.finish(err) return oauthCallback{}, err } diff --git a/internal/app/quota.go b/internal/app/quota.go index 5ef2ff8..b6ae0e3 100644 --- a/internal/app/quota.go +++ b/internal/app/quota.go @@ -404,7 +404,7 @@ func fetchQuotaSnapshot(ctx context.Context, client *http.Client, baseURL, apiKe orgID := "" if who, err := quotaGet(ctx, client, base+"/alpha/whoami", apiKey); err != nil { if quotaKeyRejected(err) { - return nil, fmt.Errorf("API Key 被拒绝(%v)", err) + return nil, fmt.Errorf("API key rejected: %v", err) } failures = append(failures, "whoami: "+err.Error()) } else { @@ -488,9 +488,9 @@ func fetchQuotaSnapshot(ctx context.Context, client *http.Client, baseURL, apiKe } if !snapshotHasData(snap) { if len(failures) == 0 { - return nil, fmt.Errorf("额度接口返回空数据") + return nil, fmt.Errorf("quota endpoints returned no data") } - return nil, fmt.Errorf("所有额度接口均无法访问:%s", strings.Join(failures, "; ")) + return nil, fmt.Errorf("all quota endpoints failed: %s", strings.Join(failures, "; ")) } return snap, nil } diff --git a/internal/app/quota_test.go b/internal/app/quota_test.go index a8bd5db..acf5254 100644 --- a/internal/app/quota_test.go +++ b/internal/app/quota_test.go @@ -280,7 +280,7 @@ func TestFetchQuotaSnapshotNonJSONFailsWhenNoData(t *testing.T) { defer srv.Close() _, err := fetchQuotaSnapshot(context.Background(), srv.Client(), srv.URL, "cc-key") - if err == nil || !strings.Contains(err.Error(), "所有额度接口均无法访问") { + if err == nil || !strings.Contains(err.Error(), "all quota endpoints failed") { t.Fatalf("err = %v, want aggregate failure", err) } } diff --git a/internal/app/server.go b/internal/app/server.go index 124acb6..0a55c04 100644 --- a/internal/app/server.go +++ b/internal/app/server.go @@ -14,6 +14,7 @@ import ( "syscall" "time" + "cmdcode2api/internal/i18n" "cmdcode2api/internal/web" ) @@ -95,20 +96,20 @@ func adminAuth(cfg *Config, limiter *ipRateLimiter) func(http.Handler) http.Hand if ok, retryAfter := limiter.Allow(ip); !ok { seconds := int(retryAfter.Seconds()) + 1 w.Header().Set("Retry-After", strconv.Itoa(seconds)) - writeAdminError(w, http.StatusTooManyRequests, - fmt.Sprintf("失败次数过多,请 %d 秒后重试", seconds)) + writeAdminError(w, r, http.StatusTooManyRequests, + i18n.Message(i18n.FromRequest(r), "too many failed attempts, retry in %d seconds", seconds)) return } auth := r.Header.Get("Authorization") if !strings.HasPrefix(auth, "Bearer ") { limiter.Fail(ip) - writeAdminError(w, 401, "missing Authorization header") + writeAdminError(w, r, 401, "missing Authorization header") return } key := strings.TrimPrefix(auth, "Bearer ") if !subtleConstantTimeEqual(key, cfg.adminPassword()) { limiter.Fail(ip) - writeAdminError(w, 401, "invalid admin password") + writeAdminError(w, r, 401, "invalid admin password") return } limiter.Reset(ip) diff --git a/internal/i18n/i18n.go b/internal/i18n/i18n.go new file mode 100644 index 0000000..c76c0ec --- /dev/null +++ b/internal/i18n/i18n.go @@ -0,0 +1,196 @@ +// Package i18n localizes the messages the admin API returns to the WebUI. +// +// Only the admin API is localized. The OpenAI-compatible /v1 API keeps its +// English messages on purpose, because clients, SDKs, and proxies may match on +// their text. +// +// English is the source of truth: messages are written in English in the code +// and the catalog only holds the other languages. A missing entry, an +// unsupported Accept-Language, or a language added later therefore never +// changes the English output. +package i18n + +import ( + "fmt" + "net/http" + "strconv" + "strings" +) + +// Lang identifies a supported language. The tags match what the WebUI sends in +// Accept-Language and keeps in localStorage. +type Lang string + +const ( + // EN is the default and fallback language. It needs no catalog entries, + // because every message is already written in English. + EN Lang = "en" + // ZHCN is Simplified Chinese. + ZHCN Lang = "zh-CN" +) + +// translations holds "English source -> localized text" per language. A source +// containing a fmt verb is a template: the lookup happens first and the +// argument is formatted into the localized template, never into the English one. +var translations = map[Lang]map[string]string{ + ZHCN: { + // adminAuth + "missing Authorization header": "缺少 Authorization 请求头", + "invalid admin password": "管理密码不正确", + "too many failed attempts, retry in %d seconds": "失败次数过多,请 %d 秒后重试", + + // request bodies + "request body is required": "请求体不能为空", + + // accounts + "account not found": "账号不存在", + "api_key is required": "api_key 不能为空", + "api_key cannot be empty": "api_key 不能为空", + "an account with this key already exists": "该 Key 对应的账号已存在", + + // client keys + "key not found": "密钥不存在", + "a key with this value already exists": "该密钥值已存在", + + // settings + "admin_password must be at least 8 characters": "admin_password 至少 8 位", + "base_url cannot be empty": "base_url 不能为空", + "current admin password is incorrect": "当前管理密码不正确", + + // OAuth + "oauth callback url must use http or https": "回调地址必须使用 http 或 https", + "oauth callback url must include a host": "回调地址必须包含主机名", + "oauth callback url path must end with /callback": "回调地址路径必须以 /callback 结尾", + "OAuth flow is no longer pending": "OAuth 授权流程已不再等待回调", + "OAuth flow canceled": "OAuth 授权流程已取消", + "state token mismatch (possible tampering)": "state token 不匹配,可能被篡改", + "api_key and state are required": "缺少必要字段", + "no pending OAuth flow": "当前没有进行中的 OAuth 授权", + "method not allowed": "请求方法不允许", + "invalid JSON": "JSON 无效", + + // quota + "quota endpoints returned no data": "额度接口返回空数据", + }, +} + +// wrapped holds English prefixes whose remainder (a wrapped error, a path, a +// duration) is produced outside this package and stays as it is. The longest +// matching prefix wins, so a specific entry such as "account added but saving +// config failed: " takes precedence over the generic "saving config failed: ". +var wrapped = map[Lang]map[string]string{ + ZHCN: { + "saving config failed: ": "保存配置失败:", + "account added but saving config failed: ": "账号已添加,但保存配置失败:", + "key created but saving config failed: ": "密钥已创建,但保存配置失败:", + "applied but saving config failed: ": "已应用,但保存配置失败:", + "read request body: ": "读取请求体失败:", + "invalid JSON body: ": "JSON 请求体无效:", + "parse oauth callback url: ": "解析回调地址失败:", + "generate oauth state: ": "生成 OAuth state 失败:", + "start callback server: ": "启动回调服务器失败:", + "authorization canceled: ": "授权被取消:", + "OAuth timed out after ": "OAuth 授权超时:", + "decode response: ": "解析响应失败:", + "API key rejected: ": "API Key 被拒绝:", + "all quota endpoints failed: ": "所有额度接口均无法访问:", + }, +} + +// Message returns source in lang, formatted with args. Sources that the catalog +// does not know, and every message for EN, are returned unchanged. +func Message(lang Lang, source string, args ...any) string { + if text, ok := translations[lang][source]; ok { + if len(args) > 0 { + return fmt.Sprintf(text, args...) + } + return text + } + if len(args) > 0 { + source = fmt.Sprintf(source, args...) + } + if text, ok := wrappedMessage(lang, source); ok { + return text + } + return source +} + +// wrappedMessage localizes source when it starts with a known wrapper prefix, +// keeping everything after that prefix untouched. +func wrappedMessage(lang Lang, source string) (string, bool) { + table := wrapped[lang] + longest := "" + for prefix := range table { + if len(prefix) > len(longest) && strings.HasPrefix(source, prefix) { + longest = prefix + } + } + if longest == "" { + return "", false + } + return table[longest] + source[len(longest):], true +} + +// FromRequest negotiates the response language of an admin request. +func FromRequest(r *http.Request) Lang { + return FromHeader(r.Header.Get("Accept-Language")) +} + +// FromHeader picks the best supported language from an Accept-Language header, +// honouring q-values and falling back to EN. Unsupported languages, and entries +// with q=0 (RFC 9110: "not acceptable"), never win. +func FromHeader(header string) Lang { + best := EN + bestQ := 0.0 + for _, item := range strings.Split(header, ",") { + tag, q := parseAcceptLanguageItem(item) + if q <= 0 { + continue + } + lang, ok := matchLang(tag) + if !ok { + continue + } + // Strictly greater keeps the earliest entry on ties, and header order + // is the client's own preference order. + if q > bestQ { + best, bestQ = lang, q + } + } + return best +} + +// parseAcceptLanguageItem splits one "tag;q=value" entry. A malformed q-value +// makes the entry unusable, which q=0 encodes. +func parseAcceptLanguageItem(item string) (string, float64) { + parts := strings.Split(item, ";") + tag := strings.ToLower(strings.TrimSpace(parts[0])) + q := 1.0 + for _, param := range parts[1:] { + param = strings.TrimSpace(param) + if !strings.HasPrefix(param, "q=") && !strings.HasPrefix(param, "Q=") { + continue + } + value, err := strconv.ParseFloat(strings.TrimSpace(param[2:]), 64) + if err != nil { + return tag, 0 + } + q = value + } + return tag, q +} + +// matchLang maps a language tag (or "*") to a supported language. Every zh +// variant resolves to Simplified Chinese, the only Chinese catalog we ship, so +// a zh-TW reader still gets Chinese rather than English. +func matchLang(tag string) (Lang, bool) { + tag = strings.ReplaceAll(tag, "_", "-") + switch { + case tag == "*" || tag == "en" || strings.HasPrefix(tag, "en-"): + return EN, true + case tag == "zh" || strings.HasPrefix(tag, "zh-"): + return ZHCN, true + default: + return EN, false + } +} diff --git a/internal/i18n/i18n_test.go b/internal/i18n/i18n_test.go new file mode 100644 index 0000000..2f31f67 --- /dev/null +++ b/internal/i18n/i18n_test.go @@ -0,0 +1,179 @@ +package i18n + +import ( + "fmt" + "net/http" + "strings" + "testing" +) + +func TestFromHeader(t *testing.T) { + cases := []struct { + header string + want Lang + }{ + {"", EN}, + {"en-US", EN}, + {"en", EN}, + {"zh", ZHCN}, + {"zh-CN", ZHCN}, + {"zh-Hans-CN", ZHCN}, + {"ZH-TW", ZHCN}, + {"zh_TW", ZHCN}, + {"de-DE,de;q=0.9", EN}, // unsupported only: fall back + {"de,zh;q=0.8", ZHCN}, + {"de-DE,de;q=0.9,en-US;q=0.8", EN}, + {"zh-CN,zh;q=0.9,en;q=0.8", ZHCN}, + {"en;q=0.3,zh;q=0.9", ZHCN}, + {"zh;q=0", EN}, // q=0 means "not acceptable" + {"zh;q=0,*;q=0.5", EN}, // wildcard still allows English + {"zh;q=abc", EN}, // malformed q-value: unusable entry + {"*", EN}, + {"en;q=0.9,zh;q=0.9", EN}, // tie: first entry wins + {" zh-CN ", ZHCN}, + {"de-DE;q=0.9,fr;q=0.8", EN}, + } + for _, tc := range cases { + if got := FromHeader(tc.header); got != tc.want { + t.Errorf("FromHeader(%q) = %q, want %q", tc.header, got, tc.want) + } + } +} + +func TestFromRequestReadsHeader(t *testing.T) { + req, err := http.NewRequest("GET", "/admin/api/overview", nil) + if err != nil { + t.Fatal(err) + } + if got := FromRequest(req); got != EN { + t.Fatalf("no header: got %q, want %q", got, EN) + } + req.Header.Set("Accept-Language", "zh-CN,zh;q=0.9") + if got := FromRequest(req); got != ZHCN { + t.Fatalf("zh header: got %q, want %q", got, ZHCN) + } +} + +func TestMessage(t *testing.T) { + cases := []struct { + name string + lang Lang + source string + args []any + want string + }{ + {"english is unchanged", EN, "account not found", nil, "account not found"}, + {"english keeps args", EN, "retry in %d seconds", []any{7}, "retry in 7 seconds"}, + {"chinese exact", ZHCN, "account not found", nil, "账号不存在"}, + {"chinese template formats the translation", ZHCN, "too many failed attempts, retry in %d seconds", []any{7}, "失败次数过多,请 7 秒后重试"}, + {"english template stays english for en", EN, "too many failed attempts, retry in %d seconds", []any{7}, "too many failed attempts, retry in 7 seconds"}, + {"unknown source passes through", ZHCN, "dial tcp 127.0.0.1:443: connect: refused", nil, "dial tcp 127.0.0.1:443: connect: refused"}, + {"unknown source keeps args", ZHCN, "connection failed after %dm", []any{3}, "connection failed after 3m"}, + {"wrapped prefix keeps the cause", ZHCN, "saving config failed: open /data/config.yaml: permission denied", nil, "保存配置失败:open /data/config.yaml: permission denied"}, + {"longest wrapped prefix wins", ZHCN, "applied but saving config failed: disk full", nil, "已应用,但保存配置失败:disk full"}, + {"wrapped prefix without cause", ZHCN, "read request body: ", nil, "读取请求体失败:"}, + {"wrapped prefix only at the start", ZHCN, "note: saving config failed: x", nil, "note: saving config failed: x"}, + {"unknown language falls back to english", Lang("de"), "account not found", nil, "account not found"}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + if got := Message(tc.lang, tc.source, tc.args...); got != tc.want { + t.Errorf("Message(%q, %q) = %q, want %q", tc.lang, tc.source, got, tc.want) + } + }) + } +} + +// TestCatalogConsistency guards the catalog itself: every entry must be usable +// and must not be shadowed by an earlier lookup step. +func TestCatalogConsistency(t *testing.T) { + supported := map[Lang]bool{EN: true, ZHCN: true} + for lang := range translations { + if !supported[lang] { + t.Errorf("translations has unsupported language %q", lang) + } + } + for lang := range wrapped { + if !supported[lang] { + t.Errorf("wrapped has unsupported language %q", lang) + } + } + + for lang, table := range translations { + if lang == EN { + continue // English is the source; it needs no catalog. + } + for source, text := range table { + if strings.TrimSpace(text) == "" { + t.Errorf("%s: empty translation for %q", lang, source) + } + if strings.TrimSpace(source) == "" { + t.Errorf("%s: empty source", lang) + } + if n, m := countVerbs(source), countVerbs(text); n != m { + t.Errorf("%s: %q has %d format verb(s) but the translation has %d", lang, source, n, m) + } + if _, shadowed := wrapped[lang][source]; shadowed { + t.Errorf("%s: %q is both an exact message and a wrapper prefix", lang, source) + } + // A translated message must actually differ from its source, and a + // wrapper prefix must still be a prefix of the localized text it + // replaces... only the first property is checkable here. + if text == source { + t.Errorf("%s: %q is not translated", lang, source) + } + } + for prefix, text := range wrapped[lang] { + if strings.TrimSpace(text) == "" { + t.Errorf("%s: empty wrapper translation for %q", lang, prefix) + } + if !strings.HasSuffix(prefix, " ") { + t.Errorf("%s: wrapper prefix %q should end with a space", lang, prefix) + } + } + } + + // Every non-English catalog must cover the same sources, so adding a + // language cannot silently leave a message behind. + for source := range translations[ZHCN] { + for lang := range translations { + if _, ok := translations[lang][source]; !ok { + t.Errorf("%s: missing translation for %q", lang, source) + } + } + } + + // Wrapper prefixes must not go stale: each one has to match the message a + // caller actually produces, so each is exercised against a sample. + for lang, table := range wrapped { + for prefix := range table { + if got := Message(lang, prefix+"detail"); !strings.HasSuffix(got, "detail") { + t.Errorf("%s: wrapper %q dropped its cause: %q", lang, prefix, got) + } + } + } +} + +// countVerbs counts fmt verbs, treating "%%" as a literal percent. +func countVerbs(s string) int { + count := 0 + for i := 0; i < len(s); i++ { + if s[i] != '%' { + continue + } + if i+1 < len(s) && s[i+1] == '%' { + i++ + continue + } + count++ + } + return count +} + +func ExampleMessage() { + fmt.Println(Message(ZHCN, "account not found")) + fmt.Println(Message(EN, "account not found")) + // Output: + // 账号不存在 + // account not found +} diff --git a/internal/web/index.html b/internal/web/index.html index 09d5622..471884e 100644 --- a/internal/web/index.html +++ b/internal/web/index.html @@ -1,9 +1,9 @@ - + -cmdcode2api 控制台 +cmdcode2api Console