Compare commits

..

3 Commits

Author SHA1 Message Date
CJACK.
1c749b6803 Merge pull request #73 from CJackHwang/dev
Merge pull request #72 from CJackHwang/codex/review-changes-to-test-account-logic

Normalize mobile login numbers, skip completion flow for session-only account tests, and add tests
2026-03-03 00:07:57 +08:00
CJACK.
c329bf26b6 Merge pull request #72 from CJackHwang/codex/review-changes-to-test-account-logic
Normalize mobile login numbers, skip completion flow for session-only account tests, and add tests
2026-03-02 23:56:27 +08:00
CJACK.
3ae5b57ebe fix(deepseek): normalize mobile before login token refresh 2026-03-02 23:48:54 +08:00
4 changed files with 348 additions and 211 deletions

View File

@@ -1,209 +1,212 @@
package admin package admin
import ( import (
"bytes" "bytes"
"context" "context"
"encoding/json" "encoding/json"
"fmt" "fmt"
"io" "io"
"net/http" "net/http"
"strings" "strings"
"sync" "sync"
"time" "time"
authn "ds2api/internal/auth" authn "ds2api/internal/auth"
"ds2api/internal/config" "ds2api/internal/config"
"ds2api/internal/sse" "ds2api/internal/sse"
) )
func (h *Handler) testSingleAccount(w http.ResponseWriter, r *http.Request) { func (h *Handler) testSingleAccount(w http.ResponseWriter, r *http.Request) {
var req map[string]any var req map[string]any
_ = json.NewDecoder(r.Body).Decode(&req) _ = json.NewDecoder(r.Body).Decode(&req)
identifier, _ := req["identifier"].(string) identifier, _ := req["identifier"].(string)
if strings.TrimSpace(identifier) == "" { if strings.TrimSpace(identifier) == "" {
writeJSON(w, http.StatusBadRequest, map[string]any{"detail": "需要账号标识identifier / email / mobile"}) writeJSON(w, http.StatusBadRequest, map[string]any{"detail": "需要账号标识identifier / email / mobile"})
return return
} }
acc, ok := findAccountByIdentifier(h.Store, identifier) acc, ok := findAccountByIdentifier(h.Store, identifier)
if !ok { if !ok {
writeJSON(w, http.StatusNotFound, map[string]any{"detail": "账号不存在"}) writeJSON(w, http.StatusNotFound, map[string]any{"detail": "账号不存在"})
return return
} }
model, _ := req["model"].(string) model, _ := req["model"].(string)
if model == "" { if model == "" {
model = "deepseek-chat" model = "deepseek-chat"
} }
message, _ := req["message"].(string) message, _ := req["message"].(string)
result := h.testAccount(r.Context(), acc, model, message) result := h.testAccount(r.Context(), acc, model, message)
writeJSON(w, http.StatusOK, result) writeJSON(w, http.StatusOK, result)
} }
func (h *Handler) testAllAccounts(w http.ResponseWriter, r *http.Request) { func (h *Handler) testAllAccounts(w http.ResponseWriter, r *http.Request) {
var req map[string]any var req map[string]any
_ = json.NewDecoder(r.Body).Decode(&req) _ = json.NewDecoder(r.Body).Decode(&req)
model, _ := req["model"].(string) model, _ := req["model"].(string)
if model == "" { if model == "" {
model = "deepseek-chat" model = "deepseek-chat"
} }
accounts := h.Store.Snapshot().Accounts accounts := h.Store.Snapshot().Accounts
if len(accounts) == 0 { if len(accounts) == 0 {
writeJSON(w, http.StatusOK, map[string]any{"total": 0, "success": 0, "failed": 0, "results": []any{}}) writeJSON(w, http.StatusOK, map[string]any{"total": 0, "success": 0, "failed": 0, "results": []any{}})
return return
} }
// Concurrent testing with a semaphore to limit parallelism. // Concurrent testing with a semaphore to limit parallelism.
const maxConcurrency = 5 const maxConcurrency = 5
results := runAccountTestsConcurrently(accounts, maxConcurrency, func(_ int, account config.Account) map[string]any { results := runAccountTestsConcurrently(accounts, maxConcurrency, func(_ int, account config.Account) map[string]any {
return h.testAccount(r.Context(), account, model, "") return h.testAccount(r.Context(), account, model, "")
}) })
success := 0 success := 0
for _, res := range results { for _, res := range results {
if ok, _ := res["success"].(bool); ok { if ok, _ := res["success"].(bool); ok {
success++ success++
} }
} }
writeJSON(w, http.StatusOK, map[string]any{"total": len(accounts), "success": success, "failed": len(accounts) - success, "results": results}) writeJSON(w, http.StatusOK, map[string]any{"total": len(accounts), "success": success, "failed": len(accounts) - success, "results": results})
} }
func runAccountTestsConcurrently(accounts []config.Account, maxConcurrency int, testFn func(int, config.Account) map[string]any) []map[string]any { func runAccountTestsConcurrently(accounts []config.Account, maxConcurrency int, testFn func(int, config.Account) map[string]any) []map[string]any {
if maxConcurrency <= 0 { if maxConcurrency <= 0 {
maxConcurrency = 1 maxConcurrency = 1
} }
sem := make(chan struct{}, maxConcurrency) sem := make(chan struct{}, maxConcurrency)
results := make([]map[string]any, len(accounts)) results := make([]map[string]any, len(accounts))
var wg sync.WaitGroup var wg sync.WaitGroup
for i, acc := range accounts { for i, acc := range accounts {
wg.Add(1) wg.Add(1)
go func(idx int, account config.Account) { go func(idx int, account config.Account) {
defer wg.Done() defer wg.Done()
sem <- struct{}{} // acquire sem <- struct{}{} // acquire
defer func() { <-sem }() // release defer func() { <-sem }() // release
results[idx] = testFn(idx, account) results[idx] = testFn(idx, account)
}(i, acc) }(i, acc)
} }
wg.Wait() wg.Wait()
return results return results
} }
func (h *Handler) testAccount(ctx context.Context, acc config.Account, model, message string) map[string]any { func (h *Handler) testAccount(ctx context.Context, acc config.Account, model, message string) map[string]any {
start := time.Now() start := time.Now()
identifier := acc.Identifier() identifier := acc.Identifier()
result := map[string]any{"account": identifier, "success": false, "response_time": 0, "message": "", "model": model} result := map[string]any{"account": identifier, "success": false, "response_time": 0, "message": "", "model": model}
defer func() { defer func() {
status := "failed" status := "failed"
if ok, _ := result["success"].(bool); ok { if ok, _ := result["success"].(bool); ok {
status = "ok" status = "ok"
} }
_ = h.Store.UpdateAccountTestStatus(identifier, status) _ = h.Store.UpdateAccountTestStatus(identifier, status)
}() }()
token := strings.TrimSpace(acc.Token) token := strings.TrimSpace(acc.Token)
if token == "" { if token == "" {
newToken, err := h.DS.Login(ctx, acc) newToken, err := h.DS.Login(ctx, acc)
if err != nil { if err != nil {
result["message"] = "登录失败: " + err.Error() result["message"] = "登录失败: " + err.Error()
return result return result
} }
token = newToken token = newToken
_ = h.Store.UpdateAccountToken(acc.Identifier(), token) _ = h.Store.UpdateAccountToken(acc.Identifier(), token)
} }
authCtx := &authn.RequestAuth{UseConfigToken: false, DeepSeekToken: token} authCtx := &authn.RequestAuth{UseConfigToken: false, DeepSeekToken: token}
sessionID, err := h.DS.CreateSession(ctx, authCtx, 1) sessionID, err := h.DS.CreateSession(ctx, authCtx, 1)
if err != nil { if err != nil {
newToken, loginErr := h.DS.Login(ctx, acc) newToken, loginErr := h.DS.Login(ctx, acc)
if loginErr != nil { if loginErr != nil {
result["message"] = "创建会话失败: " + err.Error() result["message"] = "创建会话失败: " + err.Error()
return result return result
} }
token = newToken token = newToken
authCtx.DeepSeekToken = token authCtx.DeepSeekToken = token
_ = h.Store.UpdateAccountToken(acc.Identifier(), token) _ = h.Store.UpdateAccountToken(acc.Identifier(), token)
sessionID, err = h.DS.CreateSession(ctx, authCtx, 1) sessionID, err = h.DS.CreateSession(ctx, authCtx, 1)
if err != nil { if err != nil {
result["message"] = "创建会话失败: " + err.Error() result["message"] = "创建会话失败: " + err.Error()
return result return result
} }
} }
if strings.TrimSpace(message) == "" { if strings.TrimSpace(message) == "" {
message = "你是谁?" result["success"] = true
} result["message"] = "API 测试成功(仅会话创建)"
thinking, search, ok := config.GetModelConfig(model) result["response_time"] = int(time.Since(start).Milliseconds())
if !ok { return result
thinking, search = false, false }
} thinking, search, ok := config.GetModelConfig(model)
_ = search if !ok {
pow, err := h.DS.GetPow(ctx, authCtx, 1) thinking, search = false, false
if err != nil { }
result["message"] = "获取 PoW 失败: " + err.Error() _ = search
return result pow, err := h.DS.GetPow(ctx, authCtx, 1)
} if err != nil {
payload := map[string]any{"chat_session_id": sessionID, "prompt": "<User>" + message, "ref_file_ids": []any{}, "thinking_enabled": thinking, "search_enabled": search} result["message"] = "获取 PoW 失败: " + err.Error()
resp, err := h.DS.CallCompletion(ctx, authCtx, payload, pow, 1) return result
if err != nil { }
result["message"] = "请求失败: " + err.Error() payload := map[string]any{"chat_session_id": sessionID, "prompt": "<User>" + message, "ref_file_ids": []any{}, "thinking_enabled": thinking, "search_enabled": search}
return result resp, err := h.DS.CallCompletion(ctx, authCtx, payload, pow, 1)
} if err != nil {
if resp.StatusCode != http.StatusOK { result["message"] = "请求失败: " + err.Error()
defer resp.Body.Close() return result
result["message"] = fmt.Sprintf("请求失败: HTTP %d", resp.StatusCode) }
return result if resp.StatusCode != http.StatusOK {
} defer resp.Body.Close()
collected := sse.CollectStream(resp, thinking, true) result["message"] = fmt.Sprintf("请求失败: HTTP %d", resp.StatusCode)
result["success"] = true return result
result["response_time"] = int(time.Since(start).Milliseconds()) }
if collected.Text != "" { collected := sse.CollectStream(resp, thinking, true)
result["message"] = collected.Text result["success"] = true
} else { result["response_time"] = int(time.Since(start).Milliseconds())
result["message"] = "(无回复内容)" if collected.Text != "" {
} result["message"] = collected.Text
if collected.Thinking != "" { } else {
result["thinking"] = collected.Thinking result["message"] = "(无回复内容)"
} }
return result if collected.Thinking != "" {
} result["thinking"] = collected.Thinking
}
func (h *Handler) testAPI(w http.ResponseWriter, r *http.Request) { return result
var req map[string]any }
_ = json.NewDecoder(r.Body).Decode(&req)
model, _ := req["model"].(string) func (h *Handler) testAPI(w http.ResponseWriter, r *http.Request) {
message, _ := req["message"].(string) var req map[string]any
apiKey, _ := req["api_key"].(string) _ = json.NewDecoder(r.Body).Decode(&req)
if model == "" { model, _ := req["model"].(string)
model = "deepseek-chat" message, _ := req["message"].(string)
} apiKey, _ := req["api_key"].(string)
if message == "" { if model == "" {
message = "你好" model = "deepseek-chat"
} }
if apiKey == "" { if message == "" {
keys := h.Store.Snapshot().Keys message = "你好"
if len(keys) == 0 { }
writeJSON(w, http.StatusBadRequest, map[string]any{"detail": "没有可用的 API Key"}) if apiKey == "" {
return keys := h.Store.Snapshot().Keys
} if len(keys) == 0 {
apiKey = keys[0] writeJSON(w, http.StatusBadRequest, map[string]any{"detail": "没有可用的 API Key"})
} return
host := r.Host }
scheme := "http" apiKey = keys[0]
if strings.Contains(strings.ToLower(host), "vercel") || strings.Contains(strings.ToLower(r.Header.Get("X-Forwarded-Proto")), "https") { }
scheme = "https" host := r.Host
} scheme := "http"
payload := map[string]any{"model": model, "messages": []map[string]any{{"role": "user", "content": message}}, "stream": false} if strings.Contains(strings.ToLower(host), "vercel") || strings.Contains(strings.ToLower(r.Header.Get("X-Forwarded-Proto")), "https") {
b, _ := json.Marshal(payload) scheme = "https"
request, _ := http.NewRequestWithContext(r.Context(), http.MethodPost, fmt.Sprintf("%s://%s/v1/chat/completions", scheme, host), bytes.NewReader(b)) }
request.Header.Set("Authorization", "Bearer "+apiKey) payload := map[string]any{"model": model, "messages": []map[string]any{{"role": "user", "content": message}}, "stream": false}
request.Header.Set("Content-Type", "application/json") b, _ := json.Marshal(payload)
resp, err := (&http.Client{Timeout: 60 * time.Second}).Do(request) request, _ := http.NewRequestWithContext(r.Context(), http.MethodPost, fmt.Sprintf("%s://%s/v1/chat/completions", scheme, host), bytes.NewReader(b))
if err != nil { request.Header.Set("Authorization", "Bearer "+apiKey)
writeJSON(w, http.StatusOK, map[string]any{"success": false, "error": err.Error()}) request.Header.Set("Content-Type", "application/json")
return resp, err := (&http.Client{Timeout: 60 * time.Second}).Do(request)
} if err != nil {
defer resp.Body.Close() writeJSON(w, http.StatusOK, map[string]any{"success": false, "error": err.Error()})
body, _ := io.ReadAll(resp.Body) return
if resp.StatusCode == http.StatusOK { }
var parsed any defer resp.Body.Close()
_ = json.Unmarshal(body, &parsed) body, _ := io.ReadAll(resp.Body)
writeJSON(w, http.StatusOK, map[string]any{"success": true, "status_code": resp.StatusCode, "response": parsed}) if resp.StatusCode == http.StatusOK {
return var parsed any
} _ = json.Unmarshal(body, &parsed)
writeJSON(w, http.StatusOK, map[string]any{"success": false, "status_code": resp.StatusCode, "response": string(body)}) writeJSON(w, http.StatusOK, map[string]any{"success": true, "status_code": resp.StatusCode, "response": parsed})
} return
}
writeJSON(w, http.StatusOK, map[string]any{"success": false, "status_code": resp.StatusCode, "response": string(body)})
}

View File

@@ -0,0 +1,76 @@
package admin
import (
"context"
"errors"
"net/http"
"strings"
"testing"
"ds2api/internal/auth"
"ds2api/internal/config"
)
type testingDSMock struct {
loginCalls int
createSessionCalls int
getPowCalls int
callCompletionCalls int
}
func (m *testingDSMock) Login(_ context.Context, _ config.Account) (string, error) {
m.loginCalls++
return "new-token", nil
}
func (m *testingDSMock) CreateSession(_ context.Context, _ *auth.RequestAuth, _ int) (string, error) {
m.createSessionCalls++
return "session-id", nil
}
func (m *testingDSMock) GetPow(_ context.Context, _ *auth.RequestAuth, _ int) (string, error) {
m.getPowCalls++
return "", errors.New("should not call GetPow in this test")
}
func (m *testingDSMock) CallCompletion(_ context.Context, _ *auth.RequestAuth, _ map[string]any, _ string, _ int) (*http.Response, error) {
m.callCompletionCalls++
return nil, errors.New("should not call CallCompletion in this test")
}
func TestTestAccount_BatchModeOnlyCreatesSession(t *testing.T) {
t.Setenv("DS2API_CONFIG_JSON", `{"accounts":[{"email":"batch@example.com","password":"pwd","token":""}]}`)
store := config.LoadStore()
ds := &testingDSMock{}
h := &Handler{Store: store, DS: ds}
acc, ok := store.FindAccount("batch@example.com")
if !ok {
t.Fatal("expected test account")
}
result := h.testAccount(context.Background(), acc, "deepseek-chat", "")
if ok, _ := result["success"].(bool); !ok {
t.Fatalf("expected success=true, got %#v", result)
}
msg, _ := result["message"].(string)
if !strings.Contains(msg, "仅会话创建") {
t.Fatalf("expected session-only success message, got %q", msg)
}
if ds.loginCalls != 1 || ds.createSessionCalls != 1 {
t.Fatalf("unexpected Login/CreateSession calls: login=%d createSession=%d", ds.loginCalls, ds.createSessionCalls)
}
if ds.getPowCalls != 0 || ds.callCompletionCalls != 0 {
t.Fatalf("expected no completion flow calls, got getPow=%d callCompletion=%d", ds.getPowCalls, ds.callCompletionCalls)
}
updated, ok := store.FindAccount("batch@example.com")
if !ok {
t.Fatal("expected updated account")
}
if updated.Token != "new-token" {
t.Fatalf("expected refreshed token to be persisted, got %q", updated.Token)
}
if updated.TestStatus != "ok" {
t.Fatalf("expected test status ok, got %q", updated.TestStatus)
}
}

View File

@@ -6,6 +6,7 @@ import (
"fmt" "fmt"
"net/http" "net/http"
"strings" "strings"
"unicode"
"ds2api/internal/auth" "ds2api/internal/auth"
"ds2api/internal/config" "ds2api/internal/config"
@@ -20,8 +21,9 @@ func (c *Client) Login(ctx context.Context, acc config.Account) (string, error)
if email := strings.TrimSpace(acc.Email); email != "" { if email := strings.TrimSpace(acc.Email); email != "" {
payload["email"] = email payload["email"] = email
} else if mobile := strings.TrimSpace(acc.Mobile); mobile != "" { } else if mobile := strings.TrimSpace(acc.Mobile); mobile != "" {
payload["mobile"] = mobile loginMobile, areaCode := normalizeMobileForLogin(mobile)
payload["area_code"] = nil payload["mobile"] = loginMobile
payload["area_code"] = areaCode
} else { } else {
return "", errors.New("missing email/mobile") return "", errors.New("missing email/mobile")
} }
@@ -151,3 +153,26 @@ func isTokenInvalid(status int, code int, msg string) bool {
} }
return strings.Contains(msg, "token") || strings.Contains(msg, "unauthorized") return strings.Contains(msg, "token") || strings.Contains(msg, "unauthorized")
} }
func normalizeMobileForLogin(raw string) (mobile string, areaCode any) {
s := strings.TrimSpace(raw)
if s == "" {
return "", nil
}
hasPlus := strings.HasPrefix(s, "+")
var b strings.Builder
b.Grow(len(s))
for _, r := range s {
if unicode.IsDigit(r) {
b.WriteRune(r)
}
}
digits := b.String()
if digits == "" {
return "", nil
}
if (hasPlus || strings.HasPrefix(digits, "86")) && strings.HasPrefix(digits, "86") && len(digits) == 13 {
return digits[2:], nil
}
return digits, nil
}

View File

@@ -0,0 +1,33 @@
package deepseek
import "testing"
func TestNormalizeMobileForLogin_ChinaWithPlus86(t *testing.T) {
mobile, areaCode := normalizeMobileForLogin("+8613800138000")
if mobile != "13800138000" {
t.Fatalf("unexpected mobile: %q", mobile)
}
if areaCode != nil {
t.Fatalf("expected nil areaCode, got %#v", areaCode)
}
}
func TestNormalizeMobileForLogin_ChinaWith86Prefix(t *testing.T) {
mobile, areaCode := normalizeMobileForLogin("8613800138000")
if mobile != "13800138000" {
t.Fatalf("unexpected mobile: %q", mobile)
}
if areaCode != nil {
t.Fatalf("expected nil areaCode, got %#v", areaCode)
}
}
func TestNormalizeMobileForLogin_KeepPlainDigits(t *testing.T) {
mobile, areaCode := normalizeMobileForLogin("13800138000")
if mobile != "13800138000" {
t.Fatalf("unexpected mobile: %q", mobile)
}
if areaCode != nil {
t.Fatalf("expected nil areaCode, got %#v", areaCode)
}
}