forked from james-6-23/codex2api
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhandler.go
More file actions
3145 lines (2785 loc) · 98.7 KB
/
handler.go
File metadata and controls
3145 lines (2785 loc) · 98.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package admin
import (
"bytes"
"context"
"crypto/rand"
"database/sql"
"encoding/hex"
"encoding/json"
"fmt"
"io"
"log"
"net"
"net/http"
"reflect"
"sort"
"strconv"
"strings"
"sync"
"sync/atomic"
"time"
"unicode/utf8"
"github.com/codex2api/auth"
"github.com/codex2api/cache"
"github.com/codex2api/database"
"github.com/codex2api/proxy"
"github.com/codex2api/security"
"github.com/codex2api/security/promptfilter"
"github.com/gin-gonic/gin"
"github.com/tidwall/gjson"
)
// Handler 管理后台 API 处理器
type Handler struct {
store *auth.Store
cache cache.TokenCache
db *database.DB
rateLimiter *proxy.RateLimiter
refreshAccount func(context.Context, int64) error
cpuSampler *cpuSampler
startedAt time.Time
pgMaxConns int
redisPoolSize int
databaseDriver string
databaseLabel string
cacheDriver string
cacheLabel string
adminSecretEnv string
imageProxy *proxy.Handler
// 图表聚合内存缓存(10秒 TTL)
chartCacheMu sync.RWMutex
chartCacheData map[string]*chartCacheEntry
// 账号请求统计缓存(30秒 TTL)
reqCountMu sync.RWMutex
reqCountCache map[int64]*database.AccountRequestCount
reqCountExpiresAt time.Time
}
type chartCacheEntry struct {
data *database.ChartAggregation
expiresAt time.Time
}
// NewHandler 创建管理后台处理器
func NewHandler(store *auth.Store, db *database.DB, tc cache.TokenCache, rl *proxy.RateLimiter, adminSecretEnv string) *Handler {
handler := &Handler{
store: store,
cache: tc,
db: db,
rateLimiter: rl,
cpuSampler: newCPUSampler(),
startedAt: time.Now(),
databaseDriver: db.Driver(),
databaseLabel: db.Label(),
cacheDriver: tc.Driver(),
cacheLabel: tc.Label(),
adminSecretEnv: adminSecretEnv,
imageProxy: proxy.NewHandler(store, db, nil, nil),
chartCacheData: make(map[string]*chartCacheEntry),
}
handler.refreshAccount = handler.refreshSingleAccount
if db != nil {
if err := db.MarkInterruptedImageJobs(context.Background()); err != nil {
log.Printf("标记中断生图任务失败: %v", err)
}
}
return handler
}
// SetPoolSizes 设置连接池大小跟踪值(由 main.go 在启动时调用)
func (h *Handler) SetPoolSizes(pgMaxConns, redisPoolSize int) {
h.pgMaxConns = pgMaxConns
h.redisPoolSize = redisPoolSize
}
// RegisterRoutes 注册管理 API 路由
func (h *Handler) RegisterRoutes(r *gin.Engine) {
r.GET("/p/img/:id", h.GetSignedImageAssetFile)
// 首次初始化端点(无需鉴权,仅在系统未配置 ADMIN_SECRET 时可用)
// 这两个端点必须注册在 adminAuthMiddleware 之外,否则会被 fail-closed 拦截。
r.GET("/api/admin/bootstrap-status", h.GetBootstrapStatus)
r.POST("/api/admin/bootstrap", h.PostBootstrap)
api := r.Group("/api/admin")
api.Use(h.adminAuthMiddleware())
api.GET("/stats", h.GetStats)
api.GET("/accounts", h.ListAccounts)
api.POST("/accounts", h.AddAccount)
api.POST("/accounts/at", h.AddATAccount)
api.POST("/accounts/import", h.ImportAccounts)
api.PATCH("/accounts/:id/scheduler", h.UpdateAccountScheduler)
api.DELETE("/accounts/:id", h.DeleteAccount)
api.POST("/accounts/:id/refresh", h.RefreshAccount)
api.POST("/accounts/:id/lock", h.ToggleAccountLock)
api.POST("/accounts/:id/reset-status", h.ResetAccountStatus)
api.GET("/accounts/:id/test", h.TestConnection)
api.GET("/accounts/:id/usage", h.GetAccountUsage)
api.GET("/accounts/:id/auth-json", h.GetAccountAuthJSON)
api.POST("/accounts/batch-test", h.BatchTest)
api.POST("/accounts/batch-reset-status", h.BatchResetStatus)
api.POST("/accounts/clean-banned", h.CleanBanned)
api.POST("/accounts/clean-rate-limited", h.CleanRateLimited)
api.POST("/accounts/clean-error", h.CleanError)
api.GET("/accounts/export", h.ExportAccounts)
api.POST("/accounts/migrate", h.MigrateAccounts)
api.GET("/accounts/event-trend", h.GetAccountEventTrend)
api.GET("/usage/stats", h.GetUsageStats)
api.GET("/usage/logs", h.GetUsageLogs)
api.GET("/usage/chart-data", h.GetChartData)
api.DELETE("/usage/logs", h.ClearUsageLogs)
api.GET("/keys", h.ListAPIKeys)
api.POST("/keys", h.CreateAPIKey)
api.DELETE("/keys/:id", h.DeleteAPIKey)
api.GET("/health", h.GetHealth)
api.GET("/ops/overview", h.GetOpsOverview)
api.GET("/settings", h.GetSettings)
api.PUT("/settings", h.UpdateSettings)
api.GET("/prompt-filter/logs", h.ListPromptFilterLogs)
api.DELETE("/prompt-filter/logs", h.ClearPromptFilterLogs)
api.POST("/prompt-filter/test", h.TestPromptFilter)
api.GET("/prompt-filter/rules", h.GetPromptFilterRules)
api.GET("/models", h.ListModels)
api.POST("/models/sync", h.SyncModels)
api.GET("/image-prompts", h.ListImagePromptTemplates)
api.POST("/image-prompts", h.CreateImagePromptTemplate)
api.PATCH("/image-prompts/:id", h.UpdateImagePromptTemplate)
api.DELETE("/image-prompts/:id", h.DeleteImagePromptTemplate)
api.POST("/images/jobs", h.CreateImageGenerationJob)
api.GET("/images/jobs", h.ListImageGenerationJobs)
api.GET("/images/jobs/:id", h.GetImageGenerationJob)
api.GET("/images/assets", h.ListImageAssets)
api.GET("/images/assets/:id/file", h.GetImageAssetFile)
api.DELETE("/images/assets/:id", h.DeleteImageAsset)
api.GET("/proxies", h.ListProxies)
api.POST("/proxies", h.AddProxies)
api.DELETE("/proxies/:id", h.DeleteProxy)
api.PATCH("/proxies/:id", h.UpdateProxy)
api.POST("/proxies/batch-delete", h.BatchDeleteProxies)
api.POST("/proxies/test", h.TestProxy)
// OAuth 授权流程
api.POST("/oauth/generate-auth-url", h.GenerateOAuthURL)
api.POST("/oauth/exchange-code", h.ExchangeOAuthCode)
api.GET("/oauth/poll-callback", h.PollOAuthCallback)
// OAuth 回调端点(无需 admin 鉴权,供 OpenAI 重定向调用)
r.GET("/auth/callback", h.OAuthCallback)
}
// adminAuthMiddleware 管理接口鉴权中间件(增强版,增加安全审计日志)
//
// 安全策略(fail-closed):
// - 未配置 ADMIN_SECRET 时一律拒绝(503),防止 /api/admin/* 裸奔。
// - 用户应通过前端「首次初始化」页面(无鉴权的 /api/admin/bootstrap 端点)
// 设置初始密钥,或者在 .env 中显式设置 ADMIN_SECRET 后重启。
func (h *Handler) adminAuthMiddleware() gin.HandlerFunc {
return func(c *gin.Context) {
adminSecret, source := h.resolveAdminSecret(c.Request.Context())
if adminSecret == "" {
// fail-closed:拒绝并提示用户配置 ADMIN_SECRET
security.SecurityAuditLog("ADMIN_BLOCKED_NO_SECRET", fmt.Sprintf("path=%s ip=%s", c.Request.URL.Path, c.ClientIP()))
c.JSON(http.StatusServiceUnavailable, gin.H{
"error": "管理接口未初始化:ADMIN_SECRET 尚未配置。请在浏览器访问 /admin/ 完成首次初始化,或在 .env 中设置 ADMIN_SECRET 后重启。",
"code": "bootstrap_required",
})
c.Abort()
return
}
adminKey := c.GetHeader("X-Admin-Key")
if adminKey == "" {
// 兼容 Authorization: Bearer 方式
authHeader := c.GetHeader("Authorization")
if strings.HasPrefix(authHeader, "Bearer ") {
adminKey = strings.TrimPrefix(authHeader, "Bearer ")
}
}
// 清理输入
adminKey = security.SanitizeInput(adminKey)
// 使用安全比较防止时序攻击
if !security.SecureCompare(adminKey, adminSecret) {
// 记录安全审计日志
security.SecurityAuditLog("ADMIN_AUTH_FAILED", fmt.Sprintf("path=%s ip=%s source=%s", c.Request.URL.Path, c.ClientIP(), source))
c.JSON(http.StatusUnauthorized, gin.H{
"error": "管理密钥无效或缺失",
})
c.Abort()
return
}
// 成功认证,记录审计日志
if security.IsSensitiveEndpoint(c.Request.URL.Path) {
security.SecurityAuditLog("ADMIN_ACCESS", fmt.Sprintf("path=%s ip=%s method=%s", c.Request.URL.Path, c.ClientIP(), c.Request.Method))
}
c.Next()
}
}
func (h *Handler) resolveAdminSecret(ctx context.Context) (string, string) {
if h.adminSecretEnv != "" {
return h.adminSecretEnv, "env"
}
readCtx, cancel := context.WithTimeout(ctx, 3*time.Second)
defer cancel()
settings, err := h.db.GetSystemSettings(readCtx)
if err != nil || settings == nil || settings.AdminSecret == "" {
return "", "disabled"
}
return settings.AdminSecret, "database"
}
func (h *Handler) hasConfiguredAdminSecret(ctx context.Context) bool {
adminSecret, _ := h.resolveAdminSecret(ctx)
return strings.TrimSpace(adminSecret) != ""
}
// ==================== Stats ====================
// GetStats 获取仪表盘统计
func (h *Handler) GetStats(c *gin.Context) {
ctx, cancel := context.WithTimeout(c.Request.Context(), 5*time.Second)
defer cancel()
accounts, err := h.db.ListActive(ctx)
if err != nil {
writeInternalError(c, err)
return
}
total := len(accounts)
available := h.store.AvailableCount()
errCount := 0
for _, acc := range accounts {
if acc.Status == "error" {
errCount++
}
}
usageStats, _ := h.db.GetUsageStats(ctx)
todayReqs := int64(0)
if usageStats != nil {
todayReqs = usageStats.TodayRequests
}
c.JSON(http.StatusOK, statsResponse{
Total: total,
Available: available,
Error: errCount,
TodayRequests: todayReqs,
})
}
// ==================== Accounts ====================
type accountResponse struct {
ID int64 `json:"id"`
Name string `json:"name"`
Email string `json:"email"`
PlanType string `json:"plan_type"`
Status string `json:"status"`
ATOnly bool `json:"at_only"`
HealthTier string `json:"health_tier"`
SchedulerScore float64 `json:"scheduler_score"`
DispatchScore float64 `json:"dispatch_score"`
ScoreBiasOverride *int64 `json:"score_bias_override"`
ScoreBiasEffective int64 `json:"score_bias_effective"`
BaseConcurrencyOverride *int64 `json:"base_concurrency_override"`
BaseConcurrencyEffective int64 `json:"base_concurrency_effective"`
ConcurrencyCap int64 `json:"dynamic_concurrency_limit"`
ProxyURL string `json:"proxy_url"`
CreatedAt string `json:"created_at"`
UpdatedAt string `json:"updated_at"`
ActiveRequests int64 `json:"active_requests"`
TotalRequests int64 `json:"total_requests"`
LastUsedAt string `json:"last_used_at"`
SuccessRequests int64 `json:"success_requests"`
ErrorRequests int64 `json:"error_requests"`
UsagePercent7d *float64 `json:"usage_percent_7d"`
UsagePercent5h *float64 `json:"usage_percent_5h"`
Usage5hDetail *accountUsageWindow `json:"usage_5h_detail,omitempty"`
Usage7dDetail *accountUsageWindow `json:"usage_7d_detail,omitempty"`
Reset5hAt string `json:"reset_5h_at,omitempty"`
Reset7dAt string `json:"reset_7d_at,omitempty"`
ScoreBreakdown schedulerBreakdownResponse `json:"scheduler_breakdown"`
LastUnauthorizedAt string `json:"last_unauthorized_at,omitempty"`
LastRateLimitedAt string `json:"last_rate_limited_at,omitempty"`
LastTimeoutAt string `json:"last_timeout_at,omitempty"`
LastServerErrorAt string `json:"last_server_error_at,omitempty"`
Locked bool `json:"locked"`
AllowedAPIKeyIDs []int64 `json:"allowed_api_key_ids"`
// 图片配额信息
ImageQuotaRemaining *int `json:"image_quota_remaining,omitempty"`
ImageQuotaTotal *int `json:"image_quota_total,omitempty"`
TodayUsedCount *int `json:"today_used_count,omitempty"`
ImageQuotaResetAt string `json:"image_quota_reset_at,omitempty"`
}
type accountUsageWindow struct {
Requests int64 `json:"requests"`
Tokens int64 `json:"tokens"`
AccountBilled float64 `json:"account_billed"`
UserBilled float64 `json:"user_billed"`
}
type schedulerBreakdownResponse struct {
UnauthorizedPenalty float64 `json:"unauthorized_penalty"`
RateLimitPenalty float64 `json:"rate_limit_penalty"`
TimeoutPenalty float64 `json:"timeout_penalty"`
ServerPenalty float64 `json:"server_penalty"`
FailurePenalty float64 `json:"failure_penalty"`
SuccessBonus float64 `json:"success_bonus"`
UsagePenalty7d float64 `json:"usage_penalty_7d"`
LatencyPenalty float64 `json:"latency_penalty"`
SuccessRatePenalty float64 `json:"success_rate_penalty"`
}
// ListAccounts 获取账号列表
func (h *Handler) ListAccounts(c *gin.Context) {
ctx, cancel := context.WithTimeout(c.Request.Context(), 5*time.Second)
defer cancel()
h.store.TriggerUsageProbeAsync()
h.store.TriggerRecoveryProbeAsync()
rows, err := h.db.ListActive(ctx)
if err != nil {
writeInternalError(c, err)
return
}
// 合并内存中的调度指标
accountMap := make(map[int64]*auth.Account)
for _, acc := range h.store.Accounts() {
accountMap[acc.DBID] = acc
}
// 获取每账号近 7 天请求统计(带 30 秒内存缓存)
reqCounts := h.getCachedRequestCounts()
usage5h, usage7d := h.getAccountUsageWindows(ctx)
accounts := make([]accountResponse, 0, len(rows))
for _, row := range rows {
resp := accountResponse{
ID: row.ID,
Name: row.Name,
Email: row.GetCredential("email"),
PlanType: row.GetCredential("plan_type"),
Status: row.Status,
ATOnly: row.GetCredential("refresh_token") == "" && row.GetCredential("access_token") != "",
ProxyURL: row.ProxyURL,
Locked: row.Locked,
AllowedAPIKeyIDs: row.GetCredentialInt64Slice("allowed_api_key_ids"),
ScoreBiasOverride: nullableInt64Pointer(row.ScoreBiasOverride),
ScoreBiasEffective: effectiveScoreBias(row.GetCredential("plan_type"), row.ScoreBiasOverride),
BaseConcurrencyOverride: nullableInt64Pointer(row.BaseConcurrencyOverride),
BaseConcurrencyEffective: effectiveBaseConcurrency(row.BaseConcurrencyOverride, int64(h.store.GetMaxConcurrency())),
CreatedAt: row.CreatedAt.Format(time.RFC3339),
UpdatedAt: row.UpdatedAt.Format(time.RFC3339),
}
if acc, ok := accountMap[row.ID]; ok {
resp.ActiveRequests = acc.GetActiveRequests()
resp.TotalRequests = acc.GetTotalRequests()
debug := acc.GetSchedulerDebugSnapshot(int64(h.store.GetMaxConcurrency()))
resp.HealthTier = debug.HealthTier
resp.SchedulerScore = debug.SchedulerScore
resp.ConcurrencyCap = debug.DynamicConcurrencyLimit
if dispatchScore, ok := reflectFloat64Field(debug, "DispatchScore"); ok {
resp.DispatchScore = dispatchScore
}
if scoreBiasEffective, ok := reflectInt64Field(debug, "ScoreBiasEffective"); ok {
resp.ScoreBiasEffective = scoreBiasEffective
}
if baseConcurrencyEffective, ok := reflectInt64Field(debug, "BaseConcurrencyEffective"); ok {
resp.BaseConcurrencyEffective = baseConcurrencyEffective
}
resp.ScoreBreakdown = schedulerBreakdownResponse{
UnauthorizedPenalty: debug.Breakdown.UnauthorizedPenalty,
RateLimitPenalty: debug.Breakdown.RateLimitPenalty,
TimeoutPenalty: debug.Breakdown.TimeoutPenalty,
ServerPenalty: debug.Breakdown.ServerPenalty,
FailurePenalty: debug.Breakdown.FailurePenalty,
SuccessBonus: debug.Breakdown.SuccessBonus,
UsagePenalty7d: debug.Breakdown.UsagePenalty7d,
LatencyPenalty: debug.Breakdown.LatencyPenalty,
SuccessRatePenalty: debug.Breakdown.SuccessRatePenalty,
}
if usagePct, ok := acc.GetUsagePercent7d(); ok {
resp.UsagePercent7d = &usagePct
}
if usagePct5h, ok := acc.GetUsagePercent5h(); ok {
resp.UsagePercent5h = &usagePct5h
}
if t := acc.GetReset5hAt(); !t.IsZero() {
resp.Reset5hAt = t.Format(time.RFC3339)
}
if t := acc.GetReset7dAt(); !t.IsZero() {
resp.Reset7dAt = t.Format(time.RFC3339)
}
if t := acc.GetLastUsedAt(); !t.IsZero() {
resp.LastUsedAt = t.Format(time.RFC3339)
}
if !debug.LastUnauthorizedAt.IsZero() {
resp.LastUnauthorizedAt = debug.LastUnauthorizedAt.Format(time.RFC3339)
}
if !debug.LastRateLimitedAt.IsZero() {
resp.LastRateLimitedAt = debug.LastRateLimitedAt.Format(time.RFC3339)
}
if !debug.LastTimeoutAt.IsZero() {
resp.LastTimeoutAt = debug.LastTimeoutAt.Format(time.RFC3339)
}
if !debug.LastServerErrorAt.IsZero() {
resp.LastServerErrorAt = debug.LastServerErrorAt.Format(time.RFC3339)
}
// 使用运行时状态(优先于 DB 状态)
resp.Status = acc.RuntimeStatus()
}
if resp.DispatchScore == 0 {
resp.DispatchScore = dispatchScoreFallback(resp.SchedulerScore, resp.ScoreBiasEffective, resp.HealthTier, resp.Status)
}
if rc, ok := reqCounts[row.ID]; ok {
resp.SuccessRequests = rc.SuccessCount
resp.ErrorRequests = rc.ErrorCount
}
if usage, ok := usage5h[row.ID]; ok {
resp.Usage5hDetail = &accountUsageWindow{
Requests: usage.Requests,
Tokens: usage.Tokens,
AccountBilled: usage.AccountBilled,
UserBilled: usage.UserBilled,
}
}
if usage, ok := usage7d[row.ID]; ok {
resp.Usage7dDetail = &accountUsageWindow{
Requests: usage.Requests,
Tokens: usage.Tokens,
AccountBilled: usage.AccountBilled,
UserBilled: usage.UserBilled,
}
}
accounts = append(accounts, resp)
}
c.JSON(http.StatusOK, accountsResponse{Accounts: accounts})
}
type updateAccountSchedulerReq struct {
ScoreBiasOverride json.RawMessage `json:"score_bias_override"`
BaseConcurrencyOverride json.RawMessage `json:"base_concurrency_override"`
AllowedAPIKeyIDs json.RawMessage `json:"allowed_api_key_ids"`
}
// UpdateAccountScheduler 更新账号调度配置。
func (h *Handler) UpdateAccountScheduler(c *gin.Context) {
id, err := strconv.ParseInt(c.Param("id"), 10, 64)
if err != nil {
writeError(c, http.StatusBadRequest, "无效的账号 ID")
return
}
var req updateAccountSchedulerReq
decoder := json.NewDecoder(c.Request.Body)
decoder.DisallowUnknownFields()
if err := decoder.Decode(&req); err != nil {
writeError(c, http.StatusBadRequest, "请求格式错误")
return
}
scoreBiasOverride, err := parseOptionalIntegerField(req.ScoreBiasOverride, "score_bias_override", -200, 200)
if err != nil {
writeError(c, http.StatusBadRequest, err.Error())
return
}
baseConcurrencyOverride, err := parseOptionalIntegerField(req.BaseConcurrencyOverride, "base_concurrency_override", 1, 50)
if err != nil {
writeError(c, http.StatusBadRequest, err.Error())
return
}
allowedAPIKeyIDs, err := parseOptionalIntegerSliceField(req.AllowedAPIKeyIDs, "allowed_api_key_ids")
if err != nil {
writeError(c, http.StatusBadRequest, err.Error())
return
}
ctx, cancel := context.WithTimeout(c.Request.Context(), 5*time.Second)
defer cancel()
if allowedAPIKeyIDs.Set {
missingAPIKeyIDs, err := h.findMissingAPIKeyIDs(ctx, allowedAPIKeyIDs.Values)
if err != nil {
writeError(c, http.StatusInternalServerError, "校验 API Key 失败: "+err.Error())
return
}
if len(missingAPIKeyIDs) > 0 {
values := make([]string, 0, len(missingAPIKeyIDs))
for _, value := range missingAPIKeyIDs {
values = append(values, strconv.FormatInt(value, 10))
}
writeError(c, http.StatusBadRequest, "allowed_api_key_ids 包含不存在的 API Key ID: "+strings.Join(values, ", "))
return
}
}
if err := h.db.UpdateAccountSchedulerConfig(ctx, id, scoreBiasOverride, baseConcurrencyOverride, allowedAPIKeyIDs); err != nil {
if err == sql.ErrNoRows {
writeError(c, http.StatusNotFound, "账号不存在")
return
}
writeError(c, http.StatusInternalServerError, "更新账号调度配置失败: "+err.Error())
return
}
if h.store != nil {
h.store.ApplyAccountSchedulerOverrides(id, nullableInt64Pointer(scoreBiasOverride), nullableInt64Pointer(baseConcurrencyOverride))
if allowedAPIKeyIDs.Set {
h.store.ApplyAccountAllowedAPIKeys(id, allowedAPIKeyIDs.Values)
}
}
writeMessage(c, http.StatusOK, "账号调度配置已更新")
}
func parseOptionalIntegerField(raw json.RawMessage, field string, minValue, maxValue int64) (sql.NullInt64, error) {
if len(raw) == 0 || string(raw) == "null" {
return sql.NullInt64{}, nil
}
var number json.Number
if err := json.Unmarshal(raw, &number); err != nil {
return sql.NullInt64{}, fmt.Errorf("%s 必须是整数或 null", field)
}
value, err := number.Int64()
if err != nil {
return sql.NullInt64{}, fmt.Errorf("%s 必须是整数或 null", field)
}
if value < minValue || value > maxValue {
return sql.NullInt64{}, fmt.Errorf("%s 超出范围,必须在 %d..%d 之间", field, minValue, maxValue)
}
return sql.NullInt64{Int64: value, Valid: true}, nil
}
func parseOptionalIntegerSliceField(raw json.RawMessage, field string) (database.OptionalInt64Slice, error) {
if len(raw) == 0 {
return database.OptionalInt64Slice{}, nil
}
if string(raw) == "null" {
return database.OptionalInt64Slice{Set: true, Values: []int64{}}, nil
}
var values []json.Number
if err := json.Unmarshal(raw, &values); err != nil {
return database.OptionalInt64Slice{}, fmt.Errorf("%s 必须是整数数组或 null", field)
}
if len(values) == 0 {
return database.OptionalInt64Slice{Set: true, Values: []int64{}}, nil
}
unique := make(map[int64]struct{}, len(values))
result := make([]int64, 0, len(values))
for _, number := range values {
value, err := number.Int64()
if err != nil {
return database.OptionalInt64Slice{}, fmt.Errorf("%s 必须是整数数组或 null", field)
}
if value <= 0 {
return database.OptionalInt64Slice{}, fmt.Errorf("%s 中的值必须是正整数", field)
}
if _, exists := unique[value]; exists {
continue
}
unique[value] = struct{}{}
result = append(result, value)
}
sort.Slice(result, func(i, j int) bool {
return result[i] < result[j]
})
return database.OptionalInt64Slice{Set: true, Values: result}, nil
}
func (h *Handler) findMissingAPIKeyIDs(ctx context.Context, ids []int64) ([]int64, error) {
if len(ids) == 0 {
return nil, nil
}
keys, err := h.db.ListAPIKeys(ctx)
if err != nil {
return nil, err
}
existing := make(map[int64]struct{}, len(keys))
for _, key := range keys {
if key == nil {
continue
}
existing[key.ID] = struct{}{}
}
missing := make([]int64, 0)
for _, id := range ids {
if _, ok := existing[id]; ok {
continue
}
missing = append(missing, id)
}
return missing, nil
}
func nullableInt64Pointer(v sql.NullInt64) *int64 {
if !v.Valid {
return nil
}
value := v.Int64
return &value
}
func effectiveScoreBias(planType string, override sql.NullInt64) int64 {
if override.Valid {
return override.Int64
}
switch strings.ToLower(strings.TrimSpace(planType)) {
case "pro", "plus", "team":
return 50
default:
return 0
}
}
func effectiveBaseConcurrency(override sql.NullInt64, defaultValue int64) int64 {
if override.Valid {
return override.Int64
}
return defaultValue
}
func dispatchScoreFallback(schedulerScore float64, scoreBiasEffective int64, healthTier string, status string) float64 {
if schedulerScore == 0 {
return 0
}
if !allowScoreBias(healthTier, status) {
return schedulerScore
}
return schedulerScore + float64(scoreBiasEffective)
}
func allowScoreBias(healthTier string, status string) bool {
if status != "" && status != "active" {
return false
}
switch strings.ToLower(healthTier) {
case "healthy", "warm":
return true
default:
return false
}
}
// 这里优先读取 auth 层并行实现新增的 runtime/debug 字段,字段名约定为:
// DispatchScore / ScoreBiasEffective / BaseConcurrencyEffective。
// 若主分支尚未集成这些字段,则回退到管理层可推导的兼容值,避免阻塞前后端联调。
func reflectFloat64Field(value interface{}, field string) (float64, bool) {
v := reflect.Indirect(reflect.ValueOf(value))
if !v.IsValid() || v.Kind() != reflect.Struct {
return 0, false
}
f := v.FieldByName(field)
if !f.IsValid() {
return 0, false
}
switch f.Kind() {
case reflect.Float32, reflect.Float64:
return f.Convert(reflect.TypeOf(float64(0))).Float(), true
default:
return 0, false
}
}
func reflectInt64Field(value interface{}, field string) (int64, bool) {
v := reflect.Indirect(reflect.ValueOf(value))
if !v.IsValid() || v.Kind() != reflect.Struct {
return 0, false
}
f := v.FieldByName(field)
if !f.IsValid() {
return 0, false
}
switch f.Kind() {
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
return f.Int(), true
default:
return 0, false
}
}
// getCachedRequestCounts 返回带 30 秒 TTL 的账号请求统计缓存
func (h *Handler) getCachedRequestCounts() map[int64]*database.AccountRequestCount {
h.reqCountMu.RLock()
if h.reqCountCache != nil && time.Now().Before(h.reqCountExpiresAt) {
cached := h.reqCountCache
h.reqCountMu.RUnlock()
return cached
}
h.reqCountMu.RUnlock()
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
defer cancel()
counts, err := h.db.GetAccountRequestCounts(ctx)
if err != nil {
log.Printf("获取账号请求统计失败: %v", err)
return make(map[int64]*database.AccountRequestCount)
}
h.reqCountMu.Lock()
h.reqCountCache = counts
h.reqCountExpiresAt = time.Now().Add(30 * time.Second)
h.reqCountMu.Unlock()
return counts
}
func (h *Handler) getAccountUsageWindows(ctx context.Context) (map[int64]*database.AccountTimeRangeUsage, map[int64]*database.AccountTimeRangeUsage) {
now := time.Now()
usage5h, err := h.db.GetAccountTimeRangeUsage(ctx, now.Add(-5*time.Hour))
if err != nil {
log.Printf("获取账号 5h 用量统计失败: %v", err)
usage5h = make(map[int64]*database.AccountTimeRangeUsage)
}
usage7d, err := h.db.GetAccountTimeRangeUsage(ctx, now.AddDate(0, 0, -7))
if err != nil {
log.Printf("获取账号 7d 用量统计失败: %v", err)
usage7d = make(map[int64]*database.AccountTimeRangeUsage)
}
return usage5h, usage7d
}
type addAccountReq struct {
Name string `json:"name"`
RefreshToken string `json:"refresh_token"`
ProxyURL string `json:"proxy_url"`
}
// AddAccount 添加新账号(支持批量:refresh_token 按行分割)
func (h *Handler) AddAccount(c *gin.Context) {
var req addAccountReq
if err := c.ShouldBindJSON(&req); err != nil {
writeError(c, http.StatusBadRequest, "请求格式错误")
return
}
// 输入验证和清理
req.Name = security.SanitizeInput(req.Name)
req.ProxyURL = security.SanitizeInput(req.ProxyURL)
if req.RefreshToken == "" {
writeError(c, http.StatusBadRequest, "refresh_token 是必填字段")
return
}
// 检查XSS和SQL注入
if security.ContainsXSS(req.Name) || security.ContainsSQLInjection(req.Name) {
writeError(c, http.StatusBadRequest, "名称包含非法字符")
return
}
// 验证名称长度
if utf8.RuneCountInString(req.Name) > 100 {
writeError(c, http.StatusBadRequest, "名称长度不能超过100字符")
return
}
// 验证代理URL
if err := security.ValidateProxyURL(req.ProxyURL); err != nil {
writeError(c, http.StatusBadRequest, "代理URL无效")
return
}
// 按行分割,支持批量添加
lines := strings.Split(req.RefreshToken, "\n")
var tokens []string
for _, line := range lines {
t := strings.TrimSpace(security.SanitizeInput(line))
if t != "" {
tokens = append(tokens, t)
}
}
if len(tokens) == 0 {
writeError(c, http.StatusBadRequest, "未找到有效的 Refresh Token")
return
}
// 限制批量添加数量
if len(tokens) > 100 {
writeError(c, http.StatusBadRequest, "单次最多添加100个账号")
return
}
ctx, cancel := context.WithTimeout(c.Request.Context(), 30*time.Second)
defer cancel()
successCount := 0
failCount := 0
for i, rt := range tokens {
name := req.Name
if name == "" {
name = fmt.Sprintf("account-%d", i+1)
} else if len(tokens) > 1 {
name = fmt.Sprintf("%s-%d", req.Name, i+1)
}
id, err := h.db.InsertAccount(ctx, name, rt, req.ProxyURL)
if err != nil {
log.Printf("批量添加账号 %d 失败: %v", i+1, err)
failCount++
continue
}
successCount++
h.db.InsertAccountEventAsync(id, "added", "manual")
// 热加载:直接加入内存池
newAcc := &auth.Account{
DBID: id,
RefreshToken: rt,
ProxyURL: req.ProxyURL,
}
h.store.AddAccount(newAcc)
// 异步刷新 AT
go func(accountID int64) {
refreshCtx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
if err := h.store.RefreshSingle(refreshCtx, accountID); err != nil {
log.Printf("新账号 %d 刷新失败: %v", accountID, err)
} else {
log.Printf("新账号 %d 刷新成功,已加入号池", accountID)
}
}(id)
}
// 记录安全审计日志
security.SecurityAuditLog("ACCOUNTS_ADDED", fmt.Sprintf("success=%d failed=%d ip=%s", successCount, failCount, c.ClientIP()))
msg := fmt.Sprintf("成功添加 %d 个账号", successCount)
if failCount > 0 {
msg += fmt.Sprintf(",%d 个失败", failCount)
}
c.JSON(http.StatusOK, gin.H{
"message": msg,
"success": successCount,
"failed": failCount,
})
}
// addATAccountReq AT 模式添加账号请求
type addATAccountReq struct {
Name string `json:"name"`
AccessToken string `json:"access_token"`
ProxyURL string `json:"proxy_url"`
}
// AddATAccount 添加 AT-only 账号(支持批量:access_token 按行分割)
func (h *Handler) AddATAccount(c *gin.Context) {
var req addATAccountReq
if err := c.ShouldBindJSON(&req); err != nil {
writeError(c, http.StatusBadRequest, "请求格式错误")
return
}
req.Name = security.SanitizeInput(req.Name)
req.ProxyURL = security.SanitizeInput(req.ProxyURL)
if req.AccessToken == "" {
writeError(c, http.StatusBadRequest, "access_token 是必填字段")
return
}
if security.ContainsXSS(req.Name) || security.ContainsSQLInjection(req.Name) {
writeError(c, http.StatusBadRequest, "名称包含非法字符")
return
}
if utf8.RuneCountInString(req.Name) > 100 {
writeError(c, http.StatusBadRequest, "名称长度不能超过100字符")
return
}
if err := security.ValidateProxyURL(req.ProxyURL); err != nil {
writeError(c, http.StatusBadRequest, "代理URL无效")
return
}
// 按行分割,支持批量添加
lines := strings.Split(req.AccessToken, "\n")
var tokens []string
for _, line := range lines {
t := strings.TrimSpace(line)
if t != "" {
tokens = append(tokens, t)
}
}
if len(tokens) == 0 {
writeError(c, http.StatusBadRequest, "未找到有效的 Access Token")
return
}
if len(tokens) > 100 {
writeError(c, http.StatusBadRequest, "单次最多添加100个账号")
return
}
ctx, cancel := context.WithTimeout(c.Request.Context(), 30*time.Second)
defer cancel()
successCount := 0
failCount := 0
for i, at := range tokens {
name := req.Name
if name == "" {
name = fmt.Sprintf("at-account-%d", i+1)
} else if len(tokens) > 1 {
name = fmt.Sprintf("%s-%d", req.Name, i+1)
}
id, err := h.db.InsertATAccount(ctx, name, at, req.ProxyURL)
if err != nil {
log.Printf("添加 AT 账号 %d 失败: %v", i+1, err)
failCount++
continue
}
successCount++
h.db.InsertAccountEventAsync(id, "added", "manual_at")
// 解析 AT JWT 提取账号信息(email、plan_type、account_id、过期时间)
atInfo := auth.ParseAccessToken(at)
// 热加载到内存池(AT-only,无 RT)
newAcc := &auth.Account{
DBID: id,
AccessToken: at,
ExpiresAt: time.Now().Add(1 * time.Hour),
ProxyURL: req.ProxyURL,
}
if atInfo != nil {
newAcc.Email = atInfo.Email
newAcc.AccountID = atInfo.ChatGPTAccountID
newAcc.PlanType = atInfo.PlanType
if !atInfo.ExpiresAt.IsZero() {
newAcc.ExpiresAt = atInfo.ExpiresAt
}
}
h.store.AddAccount(newAcc)
// 将解析到的信息持久化到数据库
if atInfo != nil {
creds := map[string]interface{}{
"email": atInfo.Email,
"account_id": atInfo.ChatGPTAccountID,
"plan_type": atInfo.PlanType,
"expires_at": newAcc.ExpiresAt.Format(time.RFC3339),
}
if err := h.db.UpdateCredentials(ctx, id, creds); err != nil {
log.Printf("AT 账号 %d 更新 credentials 失败: %v", id, err)
}
}
log.Printf("AT 账号 %d 已加入号池 (id=%d, email=%s)", i+1, id, newAcc.Email)
}
security.SecurityAuditLog("AT_ACCOUNTS_ADDED", fmt.Sprintf("success=%d failed=%d ip=%s", successCount, failCount, c.ClientIP()))
msg := fmt.Sprintf("成功添加 %d 个 AT 账号", successCount)