From ed834ff3fe4d02e36973966d670e23c35983a554 Mon Sep 17 00:00:00 2001 From: scv Date: Sun, 9 Aug 2026 03:34:59 +0800 Subject: [PATCH 01/40] feat: sync imagine quota from upstream after generation Imagine image/video quotas (image_pro/image_edit/video/video_720p) were read-only snapshots that never refreshed after generation, so the "Accounts > Grok Web" view showed stale quotas despite real consumption. The post-generation refresh path was blocked end-to-end: imagine models had empty catalog Mode, QueueQuotaRefresh rejected imagine modes, runQuotaRefresh force-switched non-console modes back to weekly, and SyncQuotaMode only supported weekly and /rest/rate-limits. Wire imagine models into the per-generation refresh pipeline: - catalog: assign image_pro/image_edit/video Mode to imagine models so QuotaMode() returns the imagine mode for routing/finalize - SyncQuotaMode: add imagine branch calling syncImagineQuota and picking the requested mode's window - QueueQuotaRefresh: accept imagine modes via new isWebImagineQuotaMode (reuses imagineQuotaBlockModels keys) - runQuotaRefresh: skip the force-weekly override for imagine modes - refreshQuotaMode: apply imagine cooldown after persisting the window - image/video gateways: pass the catalog imagine mode (image_pro/video) to QueueQuotaRefresh instead of the always-weekly effectiveQuotaMode Also surface imagine quota windows in the accounts UI with a dedicated row (remaining/total, exhaustion, reset tooltip) and i18n labels, and extend full SyncQuota to retain imagine windows alongside the weekly snapshot. Routing is unchanged: getRoutingQuotaWindows keeps weekly first, so candidate.QuotaWindow and effectiveQuotaMode stay weekly. --- .../internal/application/account/service.go | 60 +++++++- backend/internal/application/gateway/image.go | 13 +- backend/internal/application/gateway/video.go | 13 +- backend/internal/domain/audit/pricing.go | 2 +- .../relational/account_repository.go | 26 ++++ .../relational/model_repository.go | 2 + .../internal/infra/provider/web/catalog.go | 7 +- .../infra/provider/web/protocol_test.go | 7 +- backend/internal/infra/provider/web/quota.go | 137 +++++++++++++++++- backend/internal/repository/account.go | 2 + .../src/features/accounts/account-quota.tsx | 88 +++++++++-- frontend/src/shared/i18n/index.ts | 9 +- 12 files changed, 338 insertions(+), 28 deletions(-) diff --git a/backend/internal/application/account/service.go b/backend/internal/application/account/service.go index 62931634..1ece9d8e 100644 --- a/backend/internal/application/account/service.go +++ b/backend/internal/application/account/service.go @@ -2786,9 +2786,56 @@ func (s *Service) refreshQuota(ctx context.Context, id uint64) (quotaRefreshResu if err := s.accounts.ReplaceQuotaWindows(ctx, id, snapshot.Tier, snapshot.SyncedAt, snapshot.Windows); err != nil { return quotaRefreshResult{}, err } + if value.Provider == accountdomain.ProviderWeb { + s.applyImagineQuotaCooldown(ctx, id, snapshot.Windows) + } return quotaRefreshResult{Credential: value, Windows: snapshot.Windows}, nil } +// imagineQuotaBlockModel 把 Imagine 配额窗口的 mode 映射到受冷却影响的上游模型。 +// imagePro 由 quality 文本生图(imagine-x-1 与 grok-imagine-image-quality)共用, +// 触顶时两者一并冷却;其余 mode 一一对应。 +var imagineQuotaBlockModels = map[string][]string{ + "image_pro": {"imagine-x-1", "grok-imagine-image-quality"}, + "image_edit": {"imagine-image-edit"}, + "video": {"grok-imagine-video"}, + "video_720p": {"grok-imagine-video"}, +} + +// applyImagineQuotaCooldown 在 Imagine 配额触顶(剩余 0)时为受影响的模型写入 +// model 级冷却块。CooldownUntil 对齐上游 nextAvailableAt(即配额窗口 ResetAt), +// 未提供时回退为 24 小时。selector 通过 ModelQuotaBlock 跳过该账号用于该模型, +// 过期记录由 model_cooldown_cleanup 定时任务清理。 +func (s *Service) applyImagineQuotaCooldown(ctx context.Context, accountID uint64, windows []accountdomain.QuotaWindow) { + const fallbackCooldown = 24 * time.Hour + now := s.now() + for _, window := range windows { + models, ok := imagineQuotaBlockModels[window.Mode] + if !ok { + continue + } + if window.Remaining > 0 { + continue + } + cooldownUntil := now.Add(fallbackCooldown) + if window.ResetAt != nil && window.ResetAt.After(now) { + cooldownUntil = *window.ResetAt + } + for _, upstreamModel := range models { + block := accountdomain.ModelQuotaBlock{ + AccountID: accountID, + UpstreamModel: upstreamModel, + Reason: "imagine_quota_exhausted", + CooldownUntil: cooldownUntil, + UpdatedAt: now, + } + if err := s.accounts.OverwriteModelQuotaBlock(ctx, block); err != nil { + s.logger.Warn("imagine_quota_cooldown_write_failed", "account_id", accountID, "upstream_model", upstreamModel, "mode", window.Mode, "error", err) + } + } + } +} + func preserveActiveQuotaWindows(existing, incoming []accountdomain.QuotaWindow, now time.Time) []accountdomain.QuotaWindow { byMode := make(map[string]accountdomain.QuotaWindow, len(existing)) for _, window := range existing { @@ -2941,6 +2988,9 @@ func (s *Service) refreshQuotaMode(ctx context.Context, id uint64, mode string) } else if err := s.accounts.SaveQuotaWindows(ctx, id, tier, syncedAt, windows); err != nil { return quotaRefreshResult{}, err } + if isWebImagineQuotaMode(mode) { + s.applyImagineQuotaCooldown(ctx, id, windows) + } return quotaRefreshResult{Credential: value, Windows: windows}, nil } @@ -3012,7 +3062,7 @@ func quotaRecoveryDueAt(window accountdomain.QuotaWindow, now time.Time, exhaust // QueueQuotaRefresh asynchronously refreshes the remote quota window after a successful request. func (s *Service) QueueQuotaRefresh(id uint64, mode string) { mode = strings.TrimSpace(mode) - if id == 0 || (!isConsoleUsageQuotaMode(mode) && mode != "weekly" && !isWebChatQuotaMode(mode)) { + if id == 0 || (!isConsoleUsageQuotaMode(mode) && mode != "weekly" && !isWebChatQuotaMode(mode) && !isWebImagineQuotaMode(mode)) { return } key := strconv.FormatUint(id, 10) + ":" + mode @@ -3181,9 +3231,10 @@ func (s *Service) runQuotaRefresh(parent context.Context, request quotaRefreshRe break } } - } else { + } else if !isWebImagineQuotaMode(request.mode) { // Weekly remains a Grok Web capability. Console never inherits this // legacy mode and always refreshes its authoritative /usage snapshot. + // Imagine 配额走 /rest/media/imagine/quota_info,保持原 mode,不可被改刷 weekly。 for _, window := range windows[request.accountID] { if window.Mode == "weekly" { refreshMode = "weekly" @@ -3460,6 +3511,11 @@ func isConsoleUsageQuotaMode(mode string) bool { } } +func isWebImagineQuotaMode(mode string) bool { + _, ok := imagineQuotaBlockModels[mode] + return ok +} + func quotaWindowControlsRouting(providerValue accountdomain.Provider, mode string) bool { return providerValue != accountdomain.ProviderConsole || isConsoleUsageQuotaMode(mode) } diff --git a/backend/internal/application/gateway/image.go b/backend/internal/application/gateway/image.go index 9da4fad3..b6ca7145 100644 --- a/backend/internal/application/gateway/image.go +++ b/backend/internal/application/gateway/image.go @@ -295,8 +295,15 @@ func (s *Service) executeImage( } } quotaKind, _ := s.providers.QuotaKind(route.Provider) - if successful && quotaKind == provider.QuotaRemoteWindow && effectiveQuotaMode != "" { - if effectiveQuotaMode != "weekly" { + // catalog 有 Mode 且 effectiveQuotaMode=weekly → imagine 模型,配额为只读快照, + // 本地不递减,仅触发上游 /rest/media/imagine/quota_info 同步以反映消耗。 + imagineModel := quotaMode != "" && effectiveQuotaMode == "weekly" + refreshMode := effectiveQuotaMode + if imagineModel { + refreshMode = quotaMode + } + if successful && quotaKind == provider.QuotaRemoteWindow && (effectiveQuotaMode != "" || imagineModel) { + if refreshMode != "weekly" && !imagineModel { units := max(1, response.QuotaUnits) var updated bool err := budget.run("quota_decrement", finalizationQuotaBudget, func(stageCtx context.Context) error { @@ -310,7 +317,7 @@ func (s *Service) executeImage( s.selector.ConsumeQuota(route.Provider, accountID, effectiveQuotaMode, units) } } - s.accounts.QueueQuotaRefresh(accountID, effectiveQuotaMode) + s.accounts.QueueQuotaRefresh(accountID, refreshMode) } if err := budget.run("audit", finalizationAuditBudget, func(stageCtx context.Context) error { return s.audits.Create(stageCtx, record) diff --git a/backend/internal/application/gateway/video.go b/backend/internal/application/gateway/video.go index 50ede4ea..91c801d1 100644 --- a/backend/internal/application/gateway/video.go +++ b/backend/internal/application/gateway/video.go @@ -433,7 +433,14 @@ func (s *Service) runVideoJob(parent context.Context, job media.Job, route model return } s.selector.MarkSuccess(context.Background(), lease.Credential) - if lease.QuotaMode != "" && lease.QuotaMode != "weekly" { + // catalog 有 Mode 且 lease.QuotaMode=weekly → imagine 视频,配额为只读快照, + // 本地不递减,仅触发上游 /rest/media/imagine/quota_info 同步以反映消耗。 + imagineModel := quotaMode != "" && lease.QuotaMode == "weekly" + refreshMode := lease.QuotaMode + if imagineModel { + refreshMode = quotaMode + } + if lease.QuotaMode != "" && lease.QuotaMode != "weekly" && !imagineModel { quotaCtx, quotaCancel := context.WithTimeout(context.Background(), accountStateWriteTimeout) updated, quotaErr := s.accounts.DecrementQuota(quotaCtx, job.AccountID, lease.QuotaMode, 1) quotaCancel() @@ -446,8 +453,8 @@ func (s *Service) runVideoJob(parent context.Context, job media.Job, route model if err := s.recordVideoAudit(context.Background(), job, time.Since(startedAt).Milliseconds()); err != nil { s.logger.Error("video_usage_record_failed", "job_id", job.ID, "event_id", "video_usage_"+job.ID, "error", err) } - if quotaKind, _ := s.providers.QuotaKind(route.Provider); quotaKind == provider.QuotaRemoteWindow && lease.QuotaMode != "" { - s.accounts.QueueQuotaRefresh(job.AccountID, lease.QuotaMode) + if quotaKind, _ := s.providers.QuotaKind(route.Provider); quotaKind == provider.QuotaRemoteWindow && refreshMode != "" { + s.accounts.QueueQuotaRefresh(job.AccountID, refreshMode) } // 输入回收放在账号状态、计费和审计收尾之后,存储抖动不得延迟关键终态逻辑。 s.releaseVideoInputs(job) diff --git a/backend/internal/domain/audit/pricing.go b/backend/internal/domain/audit/pricing.go index 19226cba..d282b69b 100644 --- a/backend/internal/domain/audit/pricing.go +++ b/backend/internal/domain/audit/pricing.go @@ -237,7 +237,7 @@ func EstimateOfficialImageCost(model, resolution string, count int) (PricingResu if model == "grok-imagine-image" { return PricingResult{Model: "grok-imagine-image", CostInUSDTicks: int64(count) * 200_000_000}, true } - if model != "grok-imagine-image-quality" { + if model != "grok-imagine-image-quality" && model != "imagine-x-1" { return PricingResult{}, false } resolution = strings.ToLower(strings.TrimSpace(resolution)) diff --git a/backend/internal/infra/persistence/relational/account_repository.go b/backend/internal/infra/persistence/relational/account_repository.go index f216af86..58e857d1 100644 --- a/backend/internal/infra/persistence/relational/account_repository.go +++ b/backend/internal/infra/persistence/relational/account_repository.go @@ -2102,6 +2102,32 @@ func (r *AccountRepository) UpsertModelQuotaBlock(ctx context.Context, value acc return err } +// OverwriteModelQuotaBlock 无条件以新值覆盖既有的模型冷却块(包括把更长的旧块缩短)。 +// 用于对齐上游权威恢复时刻(如 Imagine quota_info 的 nextAvailableAt), +// 与 UpsertModelQuotaBlock 的“只延长不缩短”保护语义相反,调用方必须确认覆盖是安全的。 +func (r *AccountRepository) OverwriteModelQuotaBlock(ctx context.Context, value account.ModelQuotaBlock) error { + value.UpstreamModel = strings.TrimSpace(value.UpstreamModel) + value.Reason = strings.TrimSpace(value.Reason) + if value.AccountID == 0 || value.UpstreamModel == "" || value.Reason == "" || value.CooldownUntil.IsZero() { + return repository.ErrConflict + } + now := time.Now().UTC() + row := accountModelQuotaBlockModel{ + AccountID: value.AccountID, UpstreamModel: truncate(value.UpstreamModel, 255), Reason: truncate(value.Reason, 100), + CooldownUntil: value.CooldownUntil.UTC(), UpdatedAt: now, + } + err := r.db.db.WithContext(ctx).Clauses(clause.OnConflict{ + Columns: []clause.Column{{Name: "account_id"}, {Name: "upstream_model"}}, + DoUpdates: clause.Assignments(map[string]any{ + "reason": row.Reason, "cooldown_until": row.CooldownUntil, "updated_at": now, + }), + }).Create(&row).Error + if err == nil { + r.notifyInvalidation(ctx, repository.InvalidationEvent{Kind: repository.InvalidationAccountModelQuotaChanged, AccountID: value.AccountID, UpstreamModel: value.UpstreamModel}) + } + return err +} + func (r *AccountRepository) PruneExpiredModelQuotaBlocks(ctx context.Context, now time.Time, limit int) (int64, error) { if limit <= 0 || limit > 1000 { limit = 100 diff --git a/backend/internal/infra/persistence/relational/model_repository.go b/backend/internal/infra/persistence/relational/model_repository.go index 2809acf3..27414223 100644 --- a/backend/internal/infra/persistence/relational/model_repository.go +++ b/backend/internal/infra/persistence/relational/model_repository.go @@ -735,6 +735,8 @@ func discoveredRouteDefaults(provider account.Provider, upstreamModel string) (s return "grok-imagine-image-quality-lite", model.CapabilityImage case "imagine-image-edit": return "grok-imagine-image-edit", model.CapabilityImageEdit + case "imagine-x-1": + return upstreamModel, model.CapabilityImage case "grok-imagine-video": return upstreamModel, model.CapabilityVideo default: diff --git a/backend/internal/infra/provider/web/catalog.go b/backend/internal/infra/provider/web/catalog.go index 83bf552c..c6094c13 100644 --- a/backend/internal/infra/provider/web/catalog.go +++ b/backend/internal/infra/provider/web/catalog.go @@ -20,9 +20,10 @@ var catalog = []ModelSpec{ {PublicID: "grok-chat-expert", UpstreamModel: "grok-chat-expert", Capability: modeldomain.CapabilityChat, Mode: "expert", MinimumTier: account.WebTierSuper}, {PublicID: "grok-chat-heavy", UpstreamModel: "grok-chat-heavy", Capability: modeldomain.CapabilityChat, Mode: "heavy", MinimumTier: account.WebTierHeavy}, {PublicID: "grok-imagine-image-lite", UpstreamModel: "grok-imagine-image", ProtocolModel: "imagine-lite", Capability: modeldomain.CapabilityImage, Mode: "fast", MinimumTier: account.WebTierBasic}, - {PublicID: "grok-imagine-image-quality-lite", UpstreamModel: "grok-imagine-image-quality", ProtocolModel: "imagine", Capability: modeldomain.CapabilityImage, MinimumTier: account.WebTierSuper}, - {PublicID: "grok-imagine-image-edit", UpstreamModel: "imagine-image-edit", Capability: modeldomain.CapabilityImageEdit, MinimumTier: account.WebTierSuper}, - {PublicID: "grok-imagine-video", UpstreamModel: "grok-imagine-video", ProtocolModel: "imagine-video-gen", Capability: modeldomain.CapabilityVideo, MinimumTier: account.WebTierSuper}, + {PublicID: "grok-imagine-image-quality-lite", UpstreamModel: "grok-imagine-image-quality", ProtocolModel: "imagine", Capability: modeldomain.CapabilityImage, Mode: "image_pro", MinimumTier: account.WebTierSuper}, + {PublicID: "imagine-x-1", UpstreamModel: "imagine-x-1", ProtocolModel: "imagine", Capability: modeldomain.CapabilityImage, Mode: "image_pro", MinimumTier: account.WebTierBasic}, + {PublicID: "grok-imagine-image-edit", UpstreamModel: "imagine-image-edit", Capability: modeldomain.CapabilityImageEdit, Mode: "image_edit", MinimumTier: account.WebTierBasic}, + {PublicID: "grok-imagine-video", UpstreamModel: "grok-imagine-video", ProtocolModel: "imagine-video-gen", Capability: modeldomain.CapabilityVideo, Mode: "video", MinimumTier: account.WebTierSuper}, } func Catalog() []ModelSpec { return append([]ModelSpec(nil), catalog...) } diff --git a/backend/internal/infra/provider/web/protocol_test.go b/backend/internal/infra/provider/web/protocol_test.go index 474a1be5..56f22b85 100644 --- a/backend/internal/infra/provider/web/protocol_test.go +++ b/backend/internal/infra/provider/web/protocol_test.go @@ -37,7 +37,7 @@ import ( func TestCatalogMatchesSupportedSurface(t *testing.T) { values := Catalog() - if len(values) != 8 { + if len(values) != 9 { t.Fatalf("catalog size = %d", len(values)) } publicIDs := make(map[string]struct{}, len(values)) @@ -52,7 +52,7 @@ func TestCatalogMatchesSupportedSurface(t *testing.T) { publicIDs[value.PublicID] = struct{}{} upstreamIDs[value.UpstreamModel] = struct{}{} } - for _, required := range []string{"grok-chat-fast", "grok-chat-auto", "grok-chat-expert", "grok-chat-heavy", "grok-imagine-image-lite", "grok-imagine-image-quality-lite", "grok-imagine-image-edit", "grok-imagine-video"} { + for _, required := range []string{"grok-chat-fast", "grok-chat-auto", "grok-chat-expert", "grok-chat-heavy", "grok-imagine-image-lite", "grok-imagine-image-quality-lite", "grok-imagine-image-edit", "imagine-x-1", "grok-imagine-video"} { if _, exists := publicIDs[required]; !exists { t.Fatalf("missing supported model: %s", required) } @@ -1047,6 +1047,9 @@ func TestOnlyChatModelsExposeRateLimitModes(t *testing.T) { } continue } + if isImagineQuotaMode(spec.Mode) { + continue + } if spec.Mode != "" { t.Fatalf("media model %s must not expose chat quota mode %q", spec.PublicID, spec.Mode) } diff --git a/backend/internal/infra/provider/web/quota.go b/backend/internal/infra/provider/web/quota.go index f7268d43..1d0ee660 100644 --- a/backend/internal/infra/provider/web/quota.go +++ b/backend/internal/infra/provider/web/quota.go @@ -36,13 +36,26 @@ func (a *Adapter) SyncQuota(ctx context.Context, credential account.Credential) if fastErr == nil { windows = append(windows, fastWindow) } + imagineWindows, imagineErr := a.syncImagineQuota(ctx, credential) + if errors.Is(imagineErr, provider.ErrUnauthorized) { + return provider.QuotaSnapshot{}, imagineErr + } + if imagineErr == nil { + windows = append(windows, imagineWindows...) + } if len(windows) > 0 { tier, _ := resolveWebTierFromQuota(credential.WebTier, windows, false) // Basic/未知账号没有付费周池,避免为每次完整同步额外访问付费端点。 // 只有模式额度已经确认付费等级时才读取 weekly 作为权威额度。 if tier == account.WebTierSuper || tier == account.WebTierHeavy { if weekly, weeklyErr := a.syncWeeklyCredits(ctx, credential); weeklyErr == nil { - windows = []account.QuotaWindow{weekly} + // 周池覆盖 chat 模式窗口,但保留 imagine 窗口供前端展示与触顶判定。 + kept := make([]account.QuotaWindow, 0, 1+len(imagineWindows)) + kept = append(kept, weekly) + if imagineErr == nil { + kept = append(kept, imagineWindows...) + } + windows = kept } } return provider.QuotaSnapshot{Tier: tier, Windows: windows, SyncedAt: time.Now().UTC()}, nil @@ -51,7 +64,11 @@ func (a *Adapter) SyncQuota(ctx context.Context, credential account.Credential) // Basic/Auto 不能凭周额度探测提权,也不应制造无意义的付费端点流量。 if credential.WebTier == account.WebTierSuper || credential.WebTier == account.WebTierHeavy { if weekly, weeklyErr := a.syncWeeklyCredits(ctx, credential); weeklyErr == nil { - return provider.QuotaSnapshot{Tier: credential.WebTier, Windows: []account.QuotaWindow{weekly}, SyncedAt: time.Now().UTC()}, nil + kept := []account.QuotaWindow{weekly} + if imagineErr == nil { + kept = append(kept, imagineWindows...) + } + return provider.QuotaSnapshot{Tier: credential.WebTier, Windows: kept, SyncedAt: time.Now().UTC()}, nil } else { return provider.QuotaSnapshot{}, weeklyErr } @@ -62,6 +79,110 @@ func (a *Adapter) SyncQuota(ctx context.Context, credential account.Credential) return provider.QuotaSnapshot{}, autoErr } +// syncImagineQuota 调用 POST /rest/media/imagine/quota_info 同步 Imagine 文本生图/编辑/视频配额。 +// 上游响应按产品字段返回剩余次数与窗口长度,不含总量;以同步时刻剩余次数近似总量, +// 触顶后 remaining=0。该窗口仅用于前端展示与配额刷新时的触顶判定,selector 选号冷却 +// 由 ModelQuotaBlock 承载(见 syncAccountCapabilities 触顶写入)。 +func (a *Adapter) syncImagineQuota(ctx context.Context, credential account.Credential) ([]account.QuotaWindow, error) { + cfg := a.config() + token, err := a.cipher.Decrypt(credential.EncryptedAccessToken) + if err != nil { + return nil, err + } + lease, err := a.egress.AcquireCredential(ctx, domainegress.ScopeWeb, credential) + if err != nil { + return nil, err + } + defer lease.Release() + endpoint := cfg.BaseURL + "/rest/media/imagine/quota_info" + requestCtx, cancel := context.WithTimeout(ctx, time.Duration(cfg.QuotaTimeoutSeconds)*time.Second) + defer cancel() + request, err := http.NewRequestWithContext(requestCtx, http.MethodPost, endpoint, bytes.NewReader([]byte("{}"))) + if err != nil { + return nil, err + } + request.Header = buildHeaders(token, lease, "application/json") + applyAppHeaders(request.Header, cfg.BaseURL, cfg.BaseURL+"/imagine") + a.applySignedStatsig(requestCtx, request, token, lease) + response, err := lease.DoDeferredForbidden(request) + if err != nil { + a.egress.Feedback(context.WithoutCancel(ctx), lease.NodeID, 0, err) + return nil, err + } + body, err := io.ReadAll(io.LimitReader(response.Body, 4<<20)) + _ = response.Body.Close() + if err != nil { + return nil, err + } + if response.StatusCode == http.StatusUnauthorized { + return nil, provider.ErrUnauthorized + } + if response.StatusCode == http.StatusForbidden && provider.IsDefinitiveAccountBlockBody(body) { + return nil, fmt.Errorf("%w: account blocked", provider.ErrUnauthorized) + } + if response.StatusCode < 200 || response.StatusCode >= 300 { + a.egress.Feedback(context.WithoutCancel(ctx), lease.NodeID, response.StatusCode, nil) + return nil, fmt.Errorf("Grok Web Imagine 配额接口返回 %d", response.StatusCode) + } + a.egress.Feedback(context.WithoutCancel(ctx), lease.NodeID, response.StatusCode, nil) + var value struct { + Image *imagineQuotaProduct `json:"image"` + ImagePro *imagineQuotaProduct `json:"imagePro"` + ImageEdit *imagineQuotaProduct `json:"imageEdit"` + Video *imagineQuotaProduct `json:"video"` + Video720p *imagineQuotaProduct `json:"video720p"` + } + if err := json.Unmarshal(body, &value); err != nil { + return nil, err + } + now := time.Now().UTC() + windows := make([]account.QuotaWindow, 0, 4) + windows = appendImagineQuotaWindow(windows, credential.ID, "image_pro", value.ImagePro, now) + windows = appendImagineQuotaWindow(windows, credential.ID, "image_edit", value.ImageEdit, now) + windows = appendImagineQuotaWindow(windows, credential.ID, "video", value.Video, now) + windows = appendImagineQuotaWindow(windows, credential.ID, "video_720p", value.Video720p, now) + return windows, nil +} + +type imagineQuotaProduct struct { + Available bool `json:"available"` + RemainingQueries int `json:"remainingQueries"` + WindowSizeSeconds int `json:"windowSizeSeconds"` + NextAvailableAt *time.Time `json:"nextAvailableAt"` +} + +func isImagineQuotaMode(mode string) bool { + switch mode { + case "image_pro", "image_edit", "video", "video_720p": + return true + default: + return false + } +} + +func appendImagineQuotaWindow(windows []account.QuotaWindow, accountID uint64, mode string, product *imagineQuotaProduct, now time.Time) []account.QuotaWindow { + if product == nil || !product.Available { + return windows + } + windowSeconds := product.WindowSizeSeconds + if windowSeconds <= 0 { + windowSeconds = 86400 + } + remaining := product.RemainingQueries + if remaining < 0 { + remaining = 0 + } + // 上游返回 nextAvailableAt 时直接对齐恢复时刻,否则按窗口时长估算。 + resetAt := now.Add(time.Duration(windowSeconds) * time.Second) + if product.NextAvailableAt != nil { + resetAt = *product.NextAvailableAt + } + return append(windows, account.QuotaWindow{ + AccountID: accountID, Mode: mode, Remaining: remaining, Total: remaining, + WindowSeconds: windowSeconds, ResetAt: &resetAt, SyncedAt: &now, Source: account.QuotaSourceUpstream, UpdatedAt: now, + }) +} + func resolveWebTierFromQuota(current account.WebTier, windows []account.QuotaWindow, weeklyAvailable bool) (account.WebTier, bool) { if len(windows) > 0 { tier, known := inferWebTierFromQuota(windows) @@ -126,6 +247,18 @@ func (a *Adapter) SyncQuotaMode(ctx context.Context, credential account.Credenti if mode == weeklyQuotaMode { return a.syncWeeklyCredits(ctx, credential) } + if isImagineQuotaMode(mode) { + windows, err := a.syncImagineQuota(ctx, credential) + if err != nil { + return account.QuotaWindow{}, err + } + for _, w := range windows { + if w.Mode == mode { + return w, nil + } + } + return account.QuotaWindow{}, fmt.Errorf("imagine 配额响应缺少 %s", mode) + } cfg := a.config() token, err := a.cipher.Decrypt(credential.EncryptedAccessToken) if err != nil { diff --git a/backend/internal/repository/account.go b/backend/internal/repository/account.go index 98ea4865..60bf5463 100644 --- a/backend/internal/repository/account.go +++ b/backend/internal/repository/account.go @@ -157,6 +157,8 @@ type AccountRepository interface { // MarkWebBirthDateSet 幂等记录 Web 账号首次确认生日已设置的时间。 MarkWebBirthDateSet(ctx context.Context, id uint64, setAt time.Time) error UpsertModelQuotaBlock(ctx context.Context, value account.ModelQuotaBlock) error + // OverwriteModelQuotaBlock 无条件覆盖既有模型冷却块(可缩短),用于对齐上游权威恢复时刻。 + OverwriteModelQuotaBlock(ctx context.Context, value account.ModelQuotaBlock) error PruneExpiredModelQuotaBlocks(ctx context.Context, now time.Time, limit int) (int64, error) SaveBilling(ctx context.Context, value account.Billing) error GetBilling(ctx context.Context, accountID uint64) (account.Billing, error) diff --git a/frontend/src/features/accounts/account-quota.tsx b/frontend/src/features/accounts/account-quota.tsx index 778c295f..16ab7119 100644 --- a/frontend/src/features/accounts/account-quota.tsx +++ b/frontend/src/features/accounts/account-quota.tsx @@ -103,6 +103,18 @@ function BuildQuota({ quota, billing, locale }: { quota: QuotaDTO; billing?: Bil const visibleWebQuotaModes = ["auto", "fast", "expert", "heavy"] as const; +const imagineQuotaModes = [ + { mode: "image_pro", labelKey: "imagineModeImagePro" as const }, + { mode: "image_edit", labelKey: "imagineModeImageEdit" as const }, + { mode: "video", labelKey: "imagineModeVideo" as const }, + { mode: "video_720p", labelKey: "imagineModeVideo720p" as const }, +] as const; + +function imagineWindowsOf(windows: WebQuotaWindow[]): WebQuotaWindow[] { + const known: Set = new Set(imagineQuotaModes.map((item) => item.mode)); + return windows.filter((window) => known.has(window.mode)); +} + export function ConsoleQuota({ windows, locale }: { windows: NonNullable; locale: string }) { const { t } = useTranslation(); if (windows.length === 0) return {t("accounts.quotaNotSynced")}; @@ -129,26 +141,80 @@ export function WebQuota({ windows, locale, tier }: { windows: NonNullable{t("accounts.quotaNotSynced")}; const windowsByMode = new Map(windows.map((window) => [window.mode, window])); + const imagineWindows = imagineWindowsOf(windows); const weekly = windowsByMode.get("weekly"); - if (weekly) return ; - const fast = windowsByMode.get("fast"); - if (tier === "basic" && fast) return ; + const mainBlock = (() => { + if (weekly) return ; + const fast = windowsByMode.get("fast"); + if (tier === "basic" && fast) return ; + return ( +
+ {visibleWebQuotaModes.map((mode) => { + const window = windowsByMode.get(mode); + if (!window) { + return
{mode}-
; + } + return ; + })} +
+ ); + })(); + + if (imagineWindows.length === 0) return mainBlock; return ( -
- {visibleWebQuotaModes.map((mode) => { - const window = windowsByMode.get(mode); - if (!window) { - return
{mode}-
; - } - return ; - })} +
+ {mainBlock} +
); } type WebQuotaWindow = NonNullable[number]; +function imagineModeLabel(mode: string, t: TFunction): string { + const entry = imagineQuotaModes.find((item) => item.mode === mode); + return entry ? t(`accounts.${entry.labelKey}`) : mode; +} + +function ImagineQuotaRow({ windows, locale, t }: { windows: WebQuotaWindow[]; locale: string; t: TFunction }) { + const windowsByMode = new Map(windows.map((window) => [window.mode, window])); + const columns = imagineQuotaModes.filter((item) => windowsByMode.has(item.mode)); + if (columns.length === 0) return null; + return ( +
+ {columns.map(({ mode }) => { + const window = windowsByMode.get(mode)!; + const exhausted = window.remaining <= 0; + const used = Math.max(0, window.total - window.remaining); + const percent = window.total > 0 ? Math.max(0, Math.min(100, used / window.total * 100)) : 100; + const label = imagineModeLabel(mode, t); + return ( + + + + + +
{exhausted ? t("accounts.imagineQuotaExhausted") : t("accounts.imagineQuotaRemaining", { remaining: formatNumber(window.remaining, locale, 0) })}
+
{window.resetAt ? t("accounts.quotaResetAt", { time: formatDateTime(window.resetAt, locale) }) : t("accounts.quotaResetUnknown")}
+
+
+ ); + })} +
+ ); +} + function WeeklyWebQuota({ window, locale, t }: { window: WebQuotaWindow; locale: string; t: TFunction }) { const usedPercent = Math.max(0, Math.min(100, window.usagePercent)); const breakdown = (window.breakdown ?? []).filter((item) => item.usagePercent > 0); diff --git a/frontend/src/shared/i18n/index.ts b/frontend/src/shared/i18n/index.ts index bef6f887..b1de1d3a 100644 --- a/frontend/src/shared/i18n/index.ts +++ b/frontend/src/shared/i18n/index.ts @@ -517,6 +517,13 @@ const resources = { webModeQuotaRemaining: "{{mode}} 剩余可调用 {{remaining}} 次", webWeeklyQuotaUsage: "周额度剩余 {{remaining}}%", paidQuotaDetails: "剩余 {{remaining}} credits", + imagineQuota: "Imagine 配额", + imagineQuotaRemaining: "剩余 {{remaining}} 次", + imagineQuotaExhausted: "已耗尽,冷却中", + imagineModeImagePro: "生图", + imagineModeImageEdit: "图片编辑", + imagineModeVideo: "视频", + imagineModeVideo720p: "视频 720p", created: "账号接入成功", createdWithSyncFailure: "账号已接入,但额度或模型初始同步失败", updated: "账号已更新", @@ -1340,7 +1347,7 @@ const resources = { accountQuotaTask: { title: "Process quota for {{count}} selected accounts", description: "Choose the quota task to run for the selected Grok Build accounts.", allTitle: "Process quota for all accounts", allDescription: "Choose the quota task to run for all enabled Grok Build accounts.", syncDescription: "Request upstream Billing and update local quota snapshots, account tiers, and recovery state.", resetAllDescription: "Clear local waiting-reset and exhausted-quota blocks for all enabled Grok Build accounts without changing upstream Billing or audit history.", execute: "Run task" }, accountExport: { countDescription: "Exports accounts in stable order, up to 10,000 per batch.", batchProgress: "Exported {{count}} accounts; the next download is batch {{batch}}.", nextBatch: "Export next batch", batchCompleted: "Exported {{count}} accounts in this batch", completed: "Export complete: {{count}} accounts" }, dashboard: { title: "Dashboard", subtitle: "Welcome, {{name}}", lastUpdated: "Updated {{time}}", welcome: "Welcome, {{name}}", gatewayOnline: "Gateway healthy", gatewayOffline: "Unavailable", gatewayReady: "The gateway is ready to process API requests.", gatewayNeedsAccount: "Connect an available account to process API requests.", manageAccounts: "Manage accounts", usage: "Usage overview", seeAll: "View audits", activeAccounts: "Available accounts", accountCapacity: "{{total}} accounts · {{rate}}% success", manage: "Manage", tokens: "Total tokens", requests: "Requests", successRate: "Success rate", accountCount: "Accounts", accountDistribution: "Build {{build}} · Web {{web}} · Console {{console}}", requestSuccessRate: "{{rate}}% success", averageRequestCost: "{{cost}} per request", availableSummary: "{{active}} / {{total}} available", requestBreakdown: "{{success}} succeeded · {{failed}} failed", requestQualitySummary: "{{success}}% success · {{failed}} failed", periodSummary: "Current {{period}} range", successSummary: "{{success}} / {{total}} requests succeeded", trend: "Usage trend", trendRequests: "Requests", trendTokens: "Tokens", trendSummary: "{{requests}} requests · {{rate}}% success", resourcesTitle: "Resource availability", availability: "Account availability", unavailableAccounts: "Unavailable accounts", unavailableSummary: "{{unavailable}} / {{total}} unavailable", enabledModels: "Enabled models", modelsAvailableSummary: "{{enabled}} / {{total}} enabled", activeClientKeys: "Available keys", keysAvailableSummary: "{{active}} / {{total}} available", allTimeRequests: "All-time requests", allTimeRequestsSummary: "Since the first recorded request", qualityTitle: "Request quality", successfulRequests: "Successful requests", failedRequests: "Failed requests", topModels: "Top 10 model billing", model: "Model", share: "Call share", noTopModels: "No model calls in this period", noTrendData: "No usage data in this period", billing: "Billing", billingSummary: "Accumulated in the current {{period}} range", inputTokens: "Input", cachedTokens: "Cached", outputTokens: "Output", reasoningTokens: "Reasoning", uncachedInput: "Uncached input", visibleOutput: "Visible output", otherModels: "Other models", providerDistribution: "Provider distribution", providerDetail: "{{rate}}% success · {{tokens}} tokens", providerStripeDetail: "{{provider}} · {{requests}} requests · {{share}}%", providerNoRequests: "No provider requests", activityTitle: "Request activity", lastDays: "Last {{count}} days", activityDay: "{{date}} · {{requests}} requests", activityLess: "Less", activityMore: "More", tokenBreakdown: "Input {{input}} · Cached {{cached}} · Output {{output}} · Reasoning {{reasoning}}", tokenEfficiency: "Cache hit rate {{rate}}%", explore: "Manage resources", accountsProduct: "Upstream accounts", accountsProductDescription: "Manage OAuth credentials, health, quota, and concurrency.", keysProduct: "Client keys", keysProductDescription: "Create downstream API keys and control models, RPM, and concurrency.", modelsProduct: "Model routes", modelsProductDescription: "Manage public model IDs, upstream mappings, and availability.", auditsProduct: "Request audits", auditsProductDescription: "Inspect status, latency, and token usage records.", gatewayFooter: "A lightweight API gateway", learnMore: "View models", unknown: "Unknown" }, - accounts: { title: "Upstream accounts", description: "Manage separate Grok Build OAuth and Grok Web SSO pools, health, concurrency, and quotas.", add: "Connect account", connectAccount: "Connect account", convertToBuild: "Convert to Build", convertToBuildTitle: "Convert Grok Web accounts to Build?", convertToBuildDescription: "Choose the conversion scope for the selected {{count}} Web accounts. Conversion may take a moment.", convertingProgress: "Converting {{completed}} / {{total}}", syncingProgress: "Syncing {{completed}} / {{total}}", conversionCompleted: "Conversion complete: {{created}} created, {{linked}} linked, {{skipped}} skipped, {{failed}} failed", linkedAccountTooltip: "Linked account: {{name}}", syncAll: "Sync all", renewAll: "Renew all", syncAllTitle: "Sync all accounts?", syncAllDescription: "Refresh quota data for every enabled Grok Build account.", syncAllWebDescription: "Refresh real quota data for every enabled Grok Web account.", renewAllTitle: "Renew all accounts?", renewAllDescription: "Refresh every renewable Grok Build credential. Accounts without automatic renewal will be skipped.", search: "Search accounts", deviceLogin: "Device OAuth", importAuth: "Import account files", importSSO: "Import SSO JSON", quickImportSSO: "Quick import SSO", importWebFile: "Import account files", quickImportTitle: "Quick import Grok Web accounts", quickImportDescription: "Paste multiple SSO tokens or upload a TXT file with one token per line. Duplicate entries are ignored.", ssoTokens: "SSO tokens (one per line)", uploadTXT: "Upload TXT", ssoTokenPlaceholder: "sso_token_1\nsso_token_2\nsso=token_3", importAction: "Import", exportAuth: "Export account file", exported: "Account credentials exported", exportTitle: "Export {{provider}} accounts?", exportDescription: "The JSON contains credentials for the current provider and any configured Cloudflare cookies, and can be imported back into this project. Store it only in a trusted location.", exportCount: "Export count", exportCountDescription: "Exports newest accounts first, up to 10,000 per batch.", refreshAllBilling: "Sync all quotas", account: "Account", status: "Status", type: "Type", quota: "Quota", routing: "Routing", credentialExpiry: "Credential expiry", credentialRenewal: "Renewal capability", autoRefresh: "Auto-renewal", noAutoRefresh: "No auto-renewal", buildAccountCount: "Grok Build accounts", webAccountCount: "Grok Web accounts", consoleAccountCount: "Grok Console accounts", abnormalAccountCount: "Abnormal accounts", routableAccountCount: "{{count}} routable", abnormalAccountBreakdown: "Recovering {{recovering}} · Needs attention {{attention}}", riskAccountCount: "Risk {{count}}", riskFilter: "Risk", riskNormal: "Normal", lastUsed: "Last used", createdAt: "Created at", name: "Name", priority: "Priority", maxConcurrent: "Max concurrency", minimumRemaining: "Minimum remaining threshold", routingSummary: "Priority {{priority}} · {{count}} concurrent", minimumRemainingSummary: "Minimum remaining {{value}}", minimumRemainingNotApplicable: "Minimum remaining does not apply to Free", refreshToken: "Refresh credential", refreshBilling: "Sync quota", refreshModeQuota: "Sync quota", quotaNotSynced: "Not synced", quotaResetAt: "Next reset {{time}}", quotaResetUnknown: "The upstream did not return a reset time", webQuotaUsage: "Used {{used}} / {{total}} total · {{remaining}} remaining", webModeQuotaRemaining: "{{mode}} has {{remaining}} calls remaining", webWeeklyQuotaUsage: "Weekly quota {{remaining}}% remaining", paidQuotaDetails: "{{remaining}} credits remaining", created: "Account connected", createdWithSyncFailure: "Account connected, but initial quota or model sync failed", updated: "Account updated", updatedWithModelSyncFailure: "Account updated, but model capability sync failed. Run model sync again later.", deleted: "Account deleted", imported: "Import complete: {{created}} created, {{updated}} updated", importedWithSyncFailures: "Import complete: {{created}} created, {{updated}} updated; {{synced}} synced, {{syncFailed}} failed initial sync", billingRefreshed: "Quota synced", authRefreshed: "Credential refreshed", allBillingRefreshed: "Sync complete: {{succeeded}} succeeded, {{failed}} failed", allTokensRefreshed: "Renewal complete: {{succeeded}} succeeded, {{failed}} failed, {{skipped}} skipped", statusDisabled: "Disabled", statusReauthRequired: "Invalid", statusCooldown: "Cooling", statusActive: "Normal", botRisk: "Risk", botRiskTooltip: "Bot risk control.", botRiskTooltipSource1: "Bot risk control (bot_flag_source/bfs=1).", botRiskTooltipSource2: "Bot risk control (bot_flag_source/bfs=2).", nsfwEnabledMark: "NSFW", nsfwEnabledTooltip: "NSFW enabled · {{time}}", agreementFilter: "Account agreements", agreementNsfwEnabled: "NSFW enabled", agreementNsfwDisabled: "NSFW not enabled", agreementTermsAccepted: "Terms accepted", agreementTermsNotAccepted: "Terms not accepted", agreementAllAccepted: "All accepted", agreementAllNotAccepted: "All not accepted", associationFilter: "Account links", associationWebLinked: "Web linked", associationWebUnlinked: "Web not linked", associationBuildLinked: "Build linked", associationBuildUnlinked: "Build not linked", associationConsoleLinked: "Console linked", associationConsoleUnlinked: "Console not linked", associationAllLinked: "All linked", associationAllUnlinked: "All not linked", buildRouteMode: { label: "Upstream endpoint", auto: "Automatic", build: "Build", xai: "XAI", autoDescription: "Selects an upstream based on account tier and risk status.", buildDescription: "Routes all requests to Build with XAI fallback disabled.", xaiDescription: "Routes all inference and video requests to XAI.", xaiUnconfirmedWarning: "This account has not been confirmed for XAI access; the upstream may reject requests." }, buildSuperEntitled: { label: "Mark as Super manually", description: "Use only when automatic tier detection is inaccurate. Enabled accounts sync models with Super access." }, quotaFree: "Free", quotaSuper: "Super", quotaPaid: "Super", quotaUnknown: "Unknown", paidQuotaUsage: "Upstream quota usage", weeklyQuota: "Weekly", monthlyQuota: "Monthly", weeklyLimit: "Weekly limit {{percent}}% remaining", freeObservedUsage: "{{used}} tokens observed in the last 24 hours", freeEstimatedUsage: "About {{used}} / {{limit}} tokens", freeEstimatedDescription: "Estimated from observed Grok Build Free characteristics; upstream exhaustion data takes precedence", observedRolling: "Free accounts use this proxy's rolling observation and may differ from upstream billing data", upstreamConfirmed: "Exhaustion confirmed by upstream", waitingReset: "Waiting reset", waitingResetUntil: "Waiting for reset · probe after {{time}} on real traffic", paidWaitingResetUntil: "Waiting for reset · check the upstream Billing period after {{time}}", probing: "Probing", probingQuota: "Checking quota recovery with real traffic", paidProbingQuota: "Checking whether the upstream Billing period has recovered", upstreamBilling: "Upstream billing data", deviceTitle: "Connect Grok Build", deviceDescription: "Complete authorization in a new window. This page will check status automatically.", userCode: "Device code", openVerification: "Continue to authorization", waiting: "Waiting for authorization", expiresAt: "Expires {{time}}", deleteTitle: "Delete account?", deleteDescription: "Credentials and quota snapshots will be removed. This cannot be undone.", deleteConfirm: "Delete", linkedDeleteTitle: "Also delete linked accounts?", linkedDeleteSelectAll: "Select all linked", linkedDeleteClearAll: "Clear linked selection", linkedDeleteExtra: "+{{count}}", linkedDeleteExtraPending: "+—", linkedDeleteExtraFailed: "!", linkedDeleteHint: "Only linked accounts are deleted; unlinked accounts remain unchanged.", linkedDeletePreviewFailed: "Failed to load linked counts. Uncheck and retry, or delete later.", batchUpdated: "Selected accounts updated", batchSetConcurrency: "Set concurrency", batchConcurrencyTitle: "Set concurrency for {{count}} selected accounts?", batchConcurrencyDescription: "Sets the number of simultaneous requests per account from 1 to 256. Large pools can start at 1 to reduce per-account pressure.", batchConcurrencyUpdated: "Concurrency updated for selected accounts", batchBillingRefreshed: "Quota sync complete: {{succeeded}} succeeded, {{failed}} failed", batchDeleteTitle: "Delete {{count}} selected accounts?", cleanupAction: "Clean up accounts", cleanupTitle: "Clean up {{provider}} accounts", cleanupDescription: "Delete accounts in the selected states from this provider, including their quota data. Normal accounts are never affected. This cannot be undone.", cleanupCompleted: "Deleted {{deleted}} accounts", deletedWithSkipped: "Deleted {{deleted}} accounts, skipped {{skipped}} groups with active video jobs", cleanupCompletedDetailed: "Deleted {{deleted}} accounts ({{linked}} linked), skipped {{skipped}} groups", cleanupLinkedWarning: "Warning: linked accounts are not limited to the selected states and may include healthy accounts; they will be deleted too.", cleanupPreviewFailed: "Failed to load estimated counts. Adjust selection and retry, or clean up later.", cleanupPreviewTotal: "About {{total}} accounts will be deleted", cleanupStart: "Start cleanup" }, + accounts: { title: "Upstream accounts", description: "Manage separate Grok Build OAuth and Grok Web SSO pools, health, concurrency, and quotas.", add: "Connect account", connectAccount: "Connect account", convertToBuild: "Convert to Build", convertToBuildTitle: "Convert Grok Web accounts to Build?", convertToBuildDescription: "Choose the conversion scope for the selected {{count}} Web accounts. Conversion may take a moment.", convertingProgress: "Converting {{completed}} / {{total}}", syncingProgress: "Syncing {{completed}} / {{total}}", conversionCompleted: "Conversion complete: {{created}} created, {{linked}} linked, {{skipped}} skipped, {{failed}} failed", linkedAccountTooltip: "Linked account: {{name}}", syncAll: "Sync all", renewAll: "Renew all", syncAllTitle: "Sync all accounts?", syncAllDescription: "Refresh quota data for every enabled Grok Build account.", syncAllWebDescription: "Refresh real quota data for every enabled Grok Web account.", renewAllTitle: "Renew all accounts?", renewAllDescription: "Refresh every renewable Grok Build credential. Accounts without automatic renewal will be skipped.", search: "Search accounts", deviceLogin: "Device OAuth", importAuth: "Import account files", importSSO: "Import SSO JSON", quickImportSSO: "Quick import SSO", importWebFile: "Import account files", quickImportTitle: "Quick import Grok Web accounts", quickImportDescription: "Paste multiple SSO tokens or upload a TXT file with one token per line. Duplicate entries are ignored.", ssoTokens: "SSO tokens (one per line)", uploadTXT: "Upload TXT", ssoTokenPlaceholder: "sso_token_1\nsso_token_2\nsso=token_3", importAction: "Import", exportAuth: "Export account file", exported: "Account credentials exported", exportTitle: "Export {{provider}} accounts?", exportDescription: "The JSON contains credentials for the current provider and any configured Cloudflare cookies, and can be imported back into this project. Store it only in a trusted location.", exportCount: "Export count", exportCountDescription: "Exports newest accounts first, up to 10,000 per batch.", refreshAllBilling: "Sync all quotas", account: "Account", status: "Status", type: "Type", quota: "Quota", routing: "Routing", credentialExpiry: "Credential expiry", credentialRenewal: "Renewal capability", autoRefresh: "Auto-renewal", noAutoRefresh: "No auto-renewal", buildAccountCount: "Grok Build accounts", webAccountCount: "Grok Web accounts", consoleAccountCount: "Grok Console accounts", abnormalAccountCount: "Abnormal accounts", routableAccountCount: "{{count}} routable", abnormalAccountBreakdown: "Recovering {{recovering}} · Needs attention {{attention}}", riskAccountCount: "Risk {{count}}", riskFilter: "Risk", riskNormal: "Normal", lastUsed: "Last used", createdAt: "Created at", name: "Name", priority: "Priority", maxConcurrent: "Max concurrency", minimumRemaining: "Minimum remaining threshold", routingSummary: "Priority {{priority}} · {{count}} concurrent", minimumRemainingSummary: "Minimum remaining {{value}}", minimumRemainingNotApplicable: "Minimum remaining does not apply to Free", refreshToken: "Refresh credential", refreshBilling: "Sync quota", refreshModeQuota: "Sync quota", quotaNotSynced: "Not synced", quotaResetAt: "Next reset {{time}}", quotaResetUnknown: "The upstream did not return a reset time", webQuotaUsage: "Used {{used}} / {{total}} total · {{remaining}} remaining", webModeQuotaRemaining: "{{mode}} has {{remaining}} calls remaining", webWeeklyQuotaUsage: "Weekly quota {{remaining}}% remaining", paidQuotaDetails: "{{remaining}} credits remaining", imagineQuota: "Imagine quota", imagineQuotaRemaining: "{{remaining}} remaining", imagineQuotaExhausted: "Exhausted, cooling down", imagineModeImagePro: "Image", imagineModeImageEdit: "Image edit", imagineModeVideo: "Video", imagineModeVideo720p: "Video 720p", created: "Account connected", createdWithSyncFailure: "Account connected, but initial quota or model sync failed", updated: "Account updated", updatedWithModelSyncFailure: "Account updated, but model capability sync failed. Run model sync again later.", deleted: "Account deleted", imported: "Import complete: {{created}} created, {{updated}} updated", importedWithSyncFailures: "Import complete: {{created}} created, {{updated}} updated; {{synced}} synced, {{syncFailed}} failed initial sync", billingRefreshed: "Quota synced", authRefreshed: "Credential refreshed", allBillingRefreshed: "Sync complete: {{succeeded}} succeeded, {{failed}} failed", allTokensRefreshed: "Renewal complete: {{succeeded}} succeeded, {{failed}} failed, {{skipped}} skipped", statusDisabled: "Disabled", statusReauthRequired: "Invalid", statusCooldown: "Cooling", statusActive: "Normal", botRisk: "Risk", botRiskTooltip: "Bot risk control.", botRiskTooltipSource1: "Bot risk control (bot_flag_source/bfs=1).", botRiskTooltipSource2: "Bot risk control (bot_flag_source/bfs=2).", nsfwEnabledMark: "NSFW", nsfwEnabledTooltip: "NSFW enabled · {{time}}", agreementFilter: "Account agreements", agreementNsfwEnabled: "NSFW enabled", agreementNsfwDisabled: "NSFW not enabled", agreementTermsAccepted: "Terms accepted", agreementTermsNotAccepted: "Terms not accepted", agreementAllAccepted: "All accepted", agreementAllNotAccepted: "All not accepted", associationFilter: "Account links", associationWebLinked: "Web linked", associationWebUnlinked: "Web not linked", associationBuildLinked: "Build linked", associationBuildUnlinked: "Build not linked", associationConsoleLinked: "Console linked", associationConsoleUnlinked: "Console not linked", associationAllLinked: "All linked", associationAllUnlinked: "All not linked", buildRouteMode: { label: "Upstream endpoint", auto: "Automatic", build: "Build", xai: "XAI", autoDescription: "Selects an upstream based on account tier and risk status.", buildDescription: "Routes all requests to Build with XAI fallback disabled.", xaiDescription: "Routes all inference and video requests to XAI.", xaiUnconfirmedWarning: "This account has not been confirmed for XAI access; the upstream may reject requests." }, buildSuperEntitled: { label: "Mark as Super manually", description: "Use only when automatic tier detection is inaccurate. Enabled accounts sync models with Super access." }, quotaFree: "Free", quotaSuper: "Super", quotaPaid: "Super", quotaUnknown: "Unknown", paidQuotaUsage: "Upstream quota usage", weeklyQuota: "Weekly", monthlyQuota: "Monthly", weeklyLimit: "Weekly limit {{percent}}% remaining", freeObservedUsage: "{{used}} tokens observed in the last 24 hours", freeEstimatedUsage: "About {{used}} / {{limit}} tokens", freeEstimatedDescription: "Estimated from observed Grok Build Free characteristics; upstream exhaustion data takes precedence", observedRolling: "Free accounts use this proxy's rolling observation and may differ from upstream billing data", upstreamConfirmed: "Exhaustion confirmed by upstream", waitingReset: "Waiting reset", waitingResetUntil: "Waiting for reset · probe after {{time}} on real traffic", paidWaitingResetUntil: "Waiting for reset · check the upstream Billing period after {{time}}", probing: "Probing", probingQuota: "Checking quota recovery with real traffic", paidProbingQuota: "Checking whether the upstream Billing period has recovered", upstreamBilling: "Upstream billing data", deviceTitle: "Connect Grok Build", deviceDescription: "Complete authorization in a new window. This page will check status automatically.", userCode: "Device code", openVerification: "Continue to authorization", waiting: "Waiting for authorization", expiresAt: "Expires {{time}}", deleteTitle: "Delete account?", deleteDescription: "Credentials and quota snapshots will be removed. This cannot be undone.", deleteConfirm: "Delete", linkedDeleteTitle: "Also delete linked accounts?", linkedDeleteSelectAll: "Select all linked", linkedDeleteClearAll: "Clear linked selection", linkedDeleteExtra: "+{{count}}", linkedDeleteExtraPending: "+—", linkedDeleteExtraFailed: "!", linkedDeleteHint: "Only linked accounts are deleted; unlinked accounts remain unchanged.", linkedDeletePreviewFailed: "Failed to load linked counts. Uncheck and retry, or delete later.", batchUpdated: "Selected accounts updated", batchSetConcurrency: "Set concurrency", batchConcurrencyTitle: "Set concurrency for {{count}} selected accounts?", batchConcurrencyDescription: "Sets the number of simultaneous requests per account from 1 to 256. Large pools can start at 1 to reduce per-account pressure.", batchConcurrencyUpdated: "Concurrency updated for selected accounts", batchBillingRefreshed: "Quota sync complete: {{succeeded}} succeeded, {{failed}} failed", batchDeleteTitle: "Delete {{count}} selected accounts?", cleanupAction: "Clean up accounts", cleanupTitle: "Clean up {{provider}} accounts", cleanupDescription: "Delete accounts in the selected states from this provider, including their quota data. Normal accounts are never affected. This cannot be undone.", cleanupCompleted: "Deleted {{deleted}} accounts", deletedWithSkipped: "Deleted {{deleted}} accounts, skipped {{skipped}} groups with active video jobs", cleanupCompletedDetailed: "Deleted {{deleted}} accounts ({{linked}} linked), skipped {{skipped}} groups", cleanupLinkedWarning: "Warning: linked accounts are not limited to the selected states and may include healthy accounts; they will be deleted too.", cleanupPreviewFailed: "Failed to load estimated counts. Adjust selection and retry, or clean up later.", cleanupPreviewTotal: "About {{total}} accounts will be deleted", cleanupStart: "Start cleanup" }, models: { title: "Model routes", description: "Configure multiple independent upstream targets for one client-facing model name. Requests remain session-sticky across schedulable targets and avoid unavailable targets automatically. Multiple public names may also target the same upstream model.", sync: "Sync models", search: "Search models", model: "Public model name", publicId: "Public model name", upstream: "Upstream model", provider: "Model source", providerGrokBuild: "Grok Build", providerGrokWeb: "Grok Web", accountSupport: "Supported accounts", lastSyncedAt: "Last synced", capability: "Account model capabilities", supportSummary: "{{supported}} available / {{total}} total", awaitingCapabilitySync: "Awaiting model capability sync", unknownCapability: "Pending sync", partialCapability: "Awaiting remaining accounts", available: "Available", unavailable: "Unavailable", status: "Status", create: "Add model", createTitle: "Add model route", createDescription: "Add a Grok Build route target. Public names are customizable and may be duplicated; targets with the same name form a scheduling pool. Public names omit the source prefix, while upstream models use Build/.", editTitle: "Edit model route", bindAccounts: "Bind specific accounts", boundAccounts: "Bound accounts", bindAccountsDescription: "Route only through selected accounts; when disabled, use synchronized model capabilities.", enabledDescription: "Controls whether this route participates in model discovery and request scheduling.", searchAccounts: "Search account name or ID", selectedAccounts: "{{count}} accounts selected", selectAccountRequired: "Select at least one account", noBindableAccounts: "No accounts from this provider can be bound", deleteTitle: "Delete model route?", deleteDescription: "This removes {{name}} and its client-key permissions. A later sync recreates it if upstream accounts still support the model.", batchDeleteTitle: "Delete {{count}} selected model routes?", batchDeleteDescription: "This removes the selected routes and their client-key permissions. Models still supported by upstream accounts are recreated on a later sync.", synced: "Synced {{count}} models", created: "Model route created", updated: "Model route updated", deleted: "Model route deleted", batchDeleted: "Deleted {{count}} model routes", batchUpdated: "Selected models updated" }, keys: { title: "Client keys", description: "Control downstream model access, RPM, concurrency, billed usage, and expiration.", search: "Search keys", create: "Create key", name: "Name", prefix: "Key", limits: "Limits", rpmLimit: "RPM limit", concurrencyLimit: "Concurrency limit", rpmShort: "RPM", concurrencyShort: "Concurrency", billingLimit: "Usage limit", models: "Allowed models", status: "Status", statusActive: "Active", statusExpired: "Expired", modelScope: "Model scope", restrictedModels: "Selected models", expires: "Expires", lastUsed: "Last used", rpm: "Requests per minute", maxConcurrent: "Max concurrency", accountScope: "Routing scope", providerScope: "Provider scope", tierScope: "Subscription scope", allProviders: "All providers", allTiers: "All subscriptions", allTiersIncludingUnknown: "All, including unknown", accountScopeDescription: "The model list follows the provider and subscription scope, and routing never falls back outside it. All subscriptions include unknown accounts; Free + Super excludes unknown accounts. Console ignores subscription restrictions.", rpmValue: "{{value}} RPM", concurrentValue: "{{value}} concurrent", unlimited: "Unlimited", billedUsage: "{{value}} billed", billingLimitDescription: "Accumulates billed request audits, preferring upstream-reported cost and otherwise using the official price estimate.", enabledDescription: "Controls whether this key can make API requests.", modelAliases: "Model aliases", modelAliasesDescription: "Suffix aliases are generated only for available models with multiple supported reasoning levels.", modelAliasesBuildSupport: "Grok Build: grok-4.5, grok-3-mini, and grok-3-mini-fast support low / medium / high.", modelAliasesConsoleSupport: "Grok Console: grok-4.3 supports none / low / medium / high; grok-4.20-0309-reasoning uses fixed reasoning and does not accept effort controls; grok-4.20-multi-agent-0309 also supports xhigh.", modelAliasesUnsupported: "Grok Web, image models, and video models do not generate reasoning-effort suffixes.", modelAliasesOn: "On: discover and call the reasoning aliases supported by available models.", modelAliasesOff: "Off: dynamic reasoning aliases are disabled; existing Console compatibility aliases remain available.", allModels: "All models", modelSearch: "Search models", selectedModels: "{{count}} models selected", selectModelRequired: "Select at least one model, or switch to All models.", modelsClearedForScopeChange: "The routing scope changed. Select the allowed models again.", neverExpires: "Never expires", selectExpiry: "Select expiration date", clearExpiry: "Clear expiration", expiryTime: "Expiration time", createTitle: "Create client key", editTitle: "Edit client key", secretTitle: "Client key created", secretDescription: "Store this key securely.", secretLabel: "Key", copySecret: "Copy", copySecretTitle: "Copy key", copySecretDescription: "Use the button below to copy your key.", secretReady: "Ready", created: "Client key created", updated: "Client key updated", deleted: "Client key deleted", deleteTitle: "Delete client key?", deleteDescription: "All downstream requests using this key will stop immediately.", batchUpdated: "Selected keys updated", batchDeleteTitle: "Delete {{count}} selected keys?" }, audits: { From fd5a35284d8baa31e27d90ea2263ecceb848f2f0 Mon Sep 17 00:00:00 2001 From: WuxiVIP Date: Mon, 10 Aug 2026 15:52:13 +0800 Subject: [PATCH 02/40] fix(egress): scope proxy to subscriptions Move subscription fetch proxy configuration from global operations settings to each subscription source.\n\nMigrate the legacy global proxy to existing sources during schema upgrade. --- .../internal/application/egress/assignment.go | 2 +- .../internal/application/egress/operations.go | 54 +++---- .../egress/operations_config_test.go | 153 ------------------ .../application/egress/subscription_test.go | 14 ++ backend/internal/application/egress/sync.go | 17 +- backend/internal/domain/egress/egress.go | 9 +- .../relational/egress_operations_test.go | 24 ++- .../relational/egress_repository.go | 10 +- .../infra/persistence/relational/models.go | 36 ++--- .../infra/persistence/relational/schema.go | 32 ++++ .../schema_subscription_proxy_upgrade_test.go | 104 ++++++++++++ .../internal/transport/http/egress/handler.go | 31 ++-- .../transport/http/egress/handler_test.go | 13 -- .../features/settings/egress-operations.tsx | 102 +++--------- .../src/features/settings/settings-api.ts | 18 +-- .../src/features/settings/settings-model.ts | 2 +- frontend/src/shared/i18n/index.ts | 22 +-- 17 files changed, 282 insertions(+), 361 deletions(-) delete mode 100644 backend/internal/application/egress/operations_config_test.go create mode 100644 backend/internal/infra/persistence/relational/schema_subscription_proxy_upgrade_test.go diff --git a/backend/internal/application/egress/assignment.go b/backend/internal/application/egress/assignment.go index b0cde2a1..0abb1e0e 100644 --- a/backend/internal/application/egress/assignment.go +++ b/backend/internal/application/egress/assignment.go @@ -304,7 +304,7 @@ func (s *Service) RunMaintenance(ctx context.Context) error { resultErr = errors.Join(resultErr, err) } else { for _, source := range sources { - if _, syncErr := s.syncSourceWithConfig(ctx, operations, source, config); syncErr != nil { + if _, syncErr := s.syncSource(ctx, operations, source); syncErr != nil { resultErr = errors.Join(resultErr, syncErr) } } diff --git a/backend/internal/application/egress/operations.go b/backend/internal/application/egress/operations.go index ca8e8868..fd3822ac 100644 --- a/backend/internal/application/egress/operations.go +++ b/backend/internal/application/egress/operations.go @@ -58,6 +58,8 @@ type SubscriptionSourceInput struct { Enabled bool URL *string ClearURL bool + ProxyURL *string + ClearProxyURL bool RefreshIntervalSeconds *int DefaultAccountCapacity *int } @@ -90,12 +92,7 @@ type OperationsConfigInput struct { AutoAssignEnabled bool AutoBalanceEnabled bool AssignmentIntervalSeconds int - // SubscriptionProxyURL updates the optional proxy used when fetching remote - // subscription sources and must be non-empty when supplied. The explicit - // ClearSubscriptionProxy flag clears it; nil leaves the secret unchanged. - SubscriptionProxyURL *string - ClearSubscriptionProxy bool - Fallbacks map[domain.Scope]FallbackConfigInput + Fallbacks map[domain.Scope]FallbackConfigInput } type FallbackConfigInput struct { @@ -413,31 +410,10 @@ func (s *Service) UpdateOperationsConfig(ctx context.Context, input OperationsCo return domain.OperationsConfig{}, err } } - subscriptionProxyURL := current.EncryptedSubscriptionProxyURL - if input.ClearSubscriptionProxy { - subscriptionProxyURL = "" - } else if input.SubscriptionProxyURL != nil { - normalized, normalizeErr := NormalizeProxyURL(*input.SubscriptionProxyURL) - if normalizeErr != nil { - return domain.OperationsConfig{}, fmt.Errorf("%w: 订阅拉取代理地址无效: %v", ErrInvalidInput, normalizeErr) - } - if normalized == "" { - return domain.OperationsConfig{}, fmt.Errorf("%w: 订阅拉取代理地址不能为空;如需清除请显式指定 clearSubscriptionProxy", ErrInvalidInput) - } - if strings.Contains(normalized, ProxyAccountPlaceholder) { - return domain.OperationsConfig{}, fmt.Errorf("%w: 订阅拉取代理不能使用账号占位符", ErrInvalidInput) - } - encrypted, encryptErr := s.cipher.Encrypt(normalized) - if encryptErr != nil { - return domain.OperationsConfig{}, encryptErr - } - subscriptionProxyURL = encrypted - } saved, err := operations.SaveEgressOperationsConfig(ctx, domain.OperationsConfig{ ProbeProvider: probeProvider, ProbeIntervalSeconds: input.ProbeIntervalSeconds, AutoAssignEnabled: input.AutoAssignEnabled, AutoBalanceEnabled: input.AutoBalanceEnabled, AssignmentIntervalSeconds: input.AssignmentIntervalSeconds, - EncryptedSubscriptionProxyURL: subscriptionProxyURL, - Fallbacks: fallbacks, UpdatedAt: time.Now().UTC(), + Fallbacks: fallbacks, UpdatedAt: time.Now().UTC(), }) if errors.Is(err, repository.ErrEgressFallbackInUse) { return domain.OperationsConfig{}, fmt.Errorf("%w: 固定回退节点必须保持启用且可用", ErrInvalidInput) @@ -553,7 +529,26 @@ func (s *Service) applySourceInput(value domain.SubscriptionSource, input Subscr if create && value.EncryptedURL == "" { return domain.SubscriptionSource{}, fmt.Errorf("%w: 必须提供订阅地址", ErrInvalidInput) } - if create || input.URL != nil || input.ClearURL { + if input.ClearProxyURL { + value.EncryptedProxyURL = "" + } else if input.ProxyURL != nil { + proxyURL, err := NormalizeProxyURL(*input.ProxyURL) + if err != nil { + return domain.SubscriptionSource{}, fmt.Errorf("%w: %v", ErrInvalidInput, err) + } + if proxyURL == "" { + return domain.SubscriptionSource{}, fmt.Errorf("%w: 订阅代理地址不能为空", ErrInvalidInput) + } + if strings.Contains(proxyURL, ProxyAccountPlaceholder) { + return domain.SubscriptionSource{}, fmt.Errorf("%w: 订阅代理地址不能包含账号占位符", ErrInvalidInput) + } + encryptedProxyURL, err := s.cipher.Encrypt(proxyURL) + if err != nil { + return domain.SubscriptionSource{}, err + } + value.EncryptedProxyURL = encryptedProxyURL + } + if create || input.URL != nil || input.ClearURL || input.ProxyURL != nil || input.ClearProxyURL { value.NextSyncAt = nil value.LastSyncError = "" } @@ -563,6 +558,7 @@ func (s *Service) applySourceInput(value domain.SubscriptionSource, input Subscr func publicSource(value domain.SubscriptionSource) domain.PublicSubscriptionSource { return domain.PublicSubscriptionSource{ ID: value.ID, Name: value.Name, Scope: value.Scope, Enabled: value.Enabled, URLConfigured: value.EncryptedURL != "", + ProxyConfigured: value.EncryptedProxyURL != "", RefreshIntervalSeconds: value.RefreshIntervalSeconds, DefaultAccountCapacity: value.DefaultAccountCapacity, LastSyncedAt: value.LastSyncedAt, NextSyncAt: value.NextSyncAt, LastSyncImported: value.LastSyncImported, LastSyncError: value.LastSyncError, CreatedAt: value.CreatedAt, UpdatedAt: value.UpdatedAt, diff --git a/backend/internal/application/egress/operations_config_test.go b/backend/internal/application/egress/operations_config_test.go deleted file mode 100644 index bff839c0..00000000 --- a/backend/internal/application/egress/operations_config_test.go +++ /dev/null @@ -1,153 +0,0 @@ -package egress - -import ( - "context" - "errors" - "testing" - "time" - - domain "github.com/chenyme/grok2api/backend/internal/domain/egress" - "github.com/chenyme/grok2api/backend/internal/infra/security" -) - -type operationsConfigRepositoryStub struct { - OperationsRepository - config domain.OperationsConfig - getErr error - saved domain.OperationsConfig - saveCalls int - syncUpdates int -} - -func (r *operationsConfigRepositoryStub) GetEgressOperationsConfig(context.Context) (domain.OperationsConfig, error) { - if r.getErr != nil { - return domain.OperationsConfig{}, r.getErr - } - return r.config, nil -} - -func (r *operationsConfigRepositoryStub) SaveEgressOperationsConfig(_ context.Context, value domain.OperationsConfig) (domain.OperationsConfig, error) { - r.saved = value - r.config = value - r.saveCalls++ - return value, nil -} - -func (r *operationsConfigRepositoryStub) UpdateEgressSourceSync(context.Context, uint64, time.Time, time.Time, int, string) error { - r.syncUpdates++ - return nil -} - -func testOperationsConfigInput() OperationsConfigInput { - return OperationsConfigInput{ - ProbeProvider: domain.ProbeProviderCloudflare, - ProbeIntervalSeconds: 900, - AssignmentIntervalSeconds: 300, - } -} - -func testEgressCipher(t *testing.T) *security.Cipher { - t.Helper() - cipher, err := security.NewCipher("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=") - if err != nil { - t.Fatal(err) - } - return cipher -} - -func TestUpdateOperationsConfigUsesExplicitSubscriptionProxyTriState(t *testing.T) { - cipher := testEgressCipher(t) - existing, err := cipher.Encrypt("socks5h://old.example:1080") - if err != nil { - t.Fatal(err) - } - - t.Run("omitted preserves existing secret", func(t *testing.T) { - repository := &operationsConfigRepositoryStub{config: domain.DefaultOperationsConfig()} - repository.config.EncryptedSubscriptionProxyURL = existing - service := &Service{operations: repository, cipher: cipher} - if _, err := service.UpdateOperationsConfig(context.Background(), testOperationsConfigInput()); err != nil { - t.Fatal(err) - } - if repository.saved.EncryptedSubscriptionProxyURL != existing { - t.Fatal("omitted subscription proxy did not preserve the existing secret") - } - }) - - t.Run("empty value requires explicit clear", func(t *testing.T) { - repository := &operationsConfigRepositoryStub{config: domain.DefaultOperationsConfig()} - repository.config.EncryptedSubscriptionProxyURL = existing - service := &Service{operations: repository, cipher: cipher} - input := testOperationsConfigInput() - empty := "" - input.SubscriptionProxyURL = &empty - _, err := service.UpdateOperationsConfig(context.Background(), input) - if !errors.Is(err, ErrInvalidInput) || repository.saveCalls != 0 { - t.Fatalf("empty proxy error=%v saveCalls=%d", err, repository.saveCalls) - } - }) - - t.Run("clear removes existing secret", func(t *testing.T) { - repository := &operationsConfigRepositoryStub{config: domain.DefaultOperationsConfig()} - repository.config.EncryptedSubscriptionProxyURL = existing - service := &Service{operations: repository, cipher: cipher} - input := testOperationsConfigInput() - input.ClearSubscriptionProxy = true - if _, err := service.UpdateOperationsConfig(context.Background(), input); err != nil { - t.Fatal(err) - } - if repository.saved.EncryptedSubscriptionProxyURL != "" { - t.Fatal("explicit clear preserved the subscription proxy") - } - }) - - t.Run("new value is encrypted", func(t *testing.T) { - repository := &operationsConfigRepositoryStub{config: domain.DefaultOperationsConfig()} - service := &Service{operations: repository, cipher: cipher} - input := testOperationsConfigInput() - proxyURL := "socks5h://user:secret@new.example:1080" - input.SubscriptionProxyURL = &proxyURL - if _, err := service.UpdateOperationsConfig(context.Background(), input); err != nil { - t.Fatal(err) - } - if repository.saved.EncryptedSubscriptionProxyURL == "" || repository.saved.EncryptedSubscriptionProxyURL == proxyURL { - t.Fatal("new subscription proxy was not encrypted") - } - decrypted, err := cipher.Decrypt(repository.saved.EncryptedSubscriptionProxyURL) - if err != nil || decrypted != proxyURL { - t.Fatalf("decrypted proxy=%q err=%v", decrypted, err) - } - }) - - t.Run("account placeholder is rejected", func(t *testing.T) { - repository := &operationsConfigRepositoryStub{config: domain.DefaultOperationsConfig()} - service := &Service{operations: repository, cipher: cipher} - input := testOperationsConfigInput() - proxyURL := "socks5h://Default.{account}:secret@proxy.example:1080" - input.SubscriptionProxyURL = &proxyURL - _, err := service.UpdateOperationsConfig(context.Background(), input) - if !errors.Is(err, ErrInvalidInput) || repository.saveCalls != 0 { - t.Fatalf("placeholder proxy error=%v saveCalls=%d", err, repository.saveCalls) - } - }) -} - -func TestSyncSourceFailsClosedWhenOperationsConfigCannotBeRead(t *testing.T) { - repository := &operationsConfigRepositoryStub{getErr: errors.New("database unavailable")} - service := &Service{operations: repository, cipher: testEgressCipher(t)} - _, err := service.syncSource(context.Background(), repository, domain.SubscriptionSource{ID: 7, RefreshIntervalSeconds: 900}) - if !errors.Is(err, ErrSubscriptionSync) { - t.Fatalf("sync error=%v", err) - } - if repository.syncUpdates != 1 { - t.Fatalf("failure status updates=%d", repository.syncUpdates) - } -} - -func TestSubscriptionFetchProxyRejectsCorruptConfiguredSecret(t *testing.T) { - service := &Service{cipher: testEgressCipher(t)} - _, err := service.subscriptionFetchProxy(domain.OperationsConfig{EncryptedSubscriptionProxyURL: "not-ciphertext"}) - if err == nil { - t.Fatal("corrupt configured subscription proxy was accepted") - } -} diff --git a/backend/internal/application/egress/subscription_test.go b/backend/internal/application/egress/subscription_test.go index 4ee997c5..a231b46e 100644 --- a/backend/internal/application/egress/subscription_test.go +++ b/backend/internal/application/egress/subscription_test.go @@ -8,6 +8,9 @@ import ( "strings" "testing" "time" + + domain "github.com/chenyme/grok2api/backend/internal/domain/egress" + "github.com/chenyme/grok2api/backend/internal/infra/security" ) func TestParseProxySubscriptionAcceptsPlainAndBase64Lists(t *testing.T) { @@ -118,3 +121,14 @@ func TestSubscriptionTransportSupportsConfiguredProxyProtocols(t *testing.T) { transport.CloseIdleConnections() } } + +func TestSubscriptionFetchProxyRejectsCorruptSourceSecret(t *testing.T) { + cipher, err := security.NewCipher("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=") + if err != nil { + t.Fatal(err) + } + service := &Service{cipher: cipher} + if _, err := service.subscriptionFetchProxy(domain.SubscriptionSource{EncryptedProxyURL: "not-ciphertext"}); err == nil { + t.Fatal("corrupt per-source subscription proxy was accepted") + } +} diff --git a/backend/internal/application/egress/sync.go b/backend/internal/application/egress/sync.go index e54d97c4..2418e4d2 100644 --- a/backend/internal/application/egress/sync.go +++ b/backend/internal/application/egress/sync.go @@ -13,17 +13,6 @@ import ( var ErrSubscriptionSync = errors.New("代理订阅同步失败") func (s *Service) syncSource(ctx context.Context, operations OperationsRepository, source domain.SubscriptionSource) (ImportResult, error) { - config, err := operations.GetEgressOperationsConfig(ctx) - if err != nil { - now := time.Now().UTC() - nextSyncAt := sourceNextSyncAt(source, now) - _ = operations.UpdateEgressSourceSync(context.WithoutCancel(ctx), source.ID, now, nextSyncAt, 0, "订阅拉取或解析失败") - return ImportResult{}, ErrSubscriptionSync - } - return s.syncSourceWithConfig(ctx, operations, source, config) -} - -func (s *Service) syncSourceWithConfig(ctx context.Context, operations OperationsRepository, source domain.SubscriptionSource, config domain.OperationsConfig) (ImportResult, error) { now := time.Now().UTC() nextSyncAt := sourceNextSyncAt(source, now) recordFailure := func() { @@ -40,7 +29,7 @@ func (s *Service) syncSourceWithConfig(ctx context.Context, operations Operation recordFailure() return ImportResult{}, ErrSubscriptionSync } - fetchProxy, err := s.subscriptionFetchProxy(config) + fetchProxy, err := s.subscriptionFetchProxy(source) if err != nil { recordFailure() return ImportResult{}, ErrSubscriptionSync @@ -93,8 +82,8 @@ func sourceNextSyncAt(source domain.SubscriptionSource, now time.Time) time.Time return now.Add(time.Duration(source.RefreshIntervalSeconds) * time.Second) } -func (s *Service) subscriptionFetchProxy(config domain.OperationsConfig) (string, error) { - encrypted := strings.TrimSpace(config.EncryptedSubscriptionProxyURL) +func (s *Service) subscriptionFetchProxy(source domain.SubscriptionSource) (string, error) { + encrypted := strings.TrimSpace(source.EncryptedProxyURL) if encrypted == "" { return "", nil } diff --git a/backend/internal/domain/egress/egress.go b/backend/internal/domain/egress/egress.go index c17a1d8d..b704cafe 100644 --- a/backend/internal/domain/egress/egress.go +++ b/backend/internal/domain/egress/egress.go @@ -131,6 +131,7 @@ type SubscriptionSource struct { Scope Scope Enabled bool EncryptedURL string + EncryptedProxyURL string RefreshIntervalSeconds int DefaultAccountCapacity int LastSyncedAt *time.Time @@ -147,6 +148,7 @@ type PublicSubscriptionSource struct { Scope Scope Enabled bool URLConfigured bool + ProxyConfigured bool RefreshIntervalSeconds int DefaultAccountCapacity int LastSyncedAt *time.Time @@ -218,11 +220,8 @@ type OperationsConfig struct { AutoAssignEnabled bool AutoBalanceEnabled bool AssignmentIntervalSeconds int - // EncryptedSubscriptionProxyURL is the optional proxy used only when - // fetching remote proxy subscription sources. It is write-only at rest. - EncryptedSubscriptionProxyURL string - Fallbacks map[Scope]FallbackConfig - UpdatedAt time.Time + Fallbacks map[Scope]FallbackConfig + UpdatedAt time.Time } func DefaultOperationsConfig() OperationsConfig { diff --git a/backend/internal/infra/persistence/relational/egress_operations_test.go b/backend/internal/infra/persistence/relational/egress_operations_test.go index 634a04fb..00c047a6 100644 --- a/backend/internal/infra/persistence/relational/egress_operations_test.go +++ b/backend/internal/infra/persistence/relational/egress_operations_test.go @@ -790,16 +790,17 @@ func TestEgressOperationsStoresSubscriptionURLEncrypted(t *testing.T) { cipher := egressOperationsCipher(t) service := egressapp.NewService(nodes, cipher, "test-browser", accounts) url := "https://subscription.example/proxies?token=subscription-token" + proxyURL := "socks5h://proxy-user:proxy-secret@proxy.example:1080" interval := 900 capacity := 3 created, err := service.CreateSource(ctx, egressapp.SubscriptionSourceInput{ - Name: "source", Scope: egress.ScopeBuild, Enabled: true, URL: &url, + Name: "source", Scope: egress.ScopeBuild, Enabled: true, URL: &url, ProxyURL: &proxyURL, RefreshIntervalSeconds: &interval, DefaultAccountCapacity: &capacity, }) if err != nil { t.Fatal(err) } - if !created.URLConfigured || created.DefaultAccountCapacity != capacity { + if !created.URLConfigured || !created.ProxyConfigured || created.DefaultAccountCapacity != capacity { t.Fatalf("public source = %#v", created) } stored, err := nodes.GetEgressSource(ctx, created.ID) @@ -809,6 +810,25 @@ func TestEgressOperationsStoresSubscriptionURLEncrypted(t *testing.T) { if stored.EncryptedURL == url || strings.Contains(stored.EncryptedURL, "subscription-token") { t.Fatalf("subscription URL stored in plaintext: %q", stored.EncryptedURL) } + if stored.EncryptedProxyURL == proxyURL || strings.Contains(stored.EncryptedProxyURL, "proxy-secret") { + t.Fatalf("subscription proxy URL stored in plaintext: %q", stored.EncryptedProxyURL) + } + updated, err := service.UpdateSource(ctx, created.ID, egressapp.SubscriptionSourceInput{ + Name: created.Name, Scope: created.Scope, Enabled: created.Enabled, ClearProxyURL: true, + }) + if err != nil { + t.Fatal(err) + } + if updated.ProxyConfigured { + t.Fatal("cleared subscription proxy remains publicly configured") + } + stored, err = nodes.GetEgressSource(ctx, created.ID) + if err != nil { + t.Fatal(err) + } + if stored.EncryptedProxyURL != "" { + t.Fatal("cleared subscription proxy remains encrypted at rest") + } } func TestEgressOperationsSubscriptionImportCountsOnlyNewNodes(t *testing.T) { diff --git a/backend/internal/infra/persistence/relational/egress_repository.go b/backend/internal/infra/persistence/relational/egress_repository.go index 22650af2..90bd7812 100644 --- a/backend/internal/infra/persistence/relational/egress_repository.go +++ b/backend/internal/infra/persistence/relational/egress_repository.go @@ -823,7 +823,7 @@ func probeFamilyFromRow(status string, testedAt *time.Time, latencyMS int, exitI func toEgressSubscriptionSourceDomain(row egressSubscriptionSourceModel) egress.SubscriptionSource { return egress.SubscriptionSource{ - ID: row.ID, Name: row.Name, Scope: egress.Scope(row.Scope), Enabled: row.Enabled, EncryptedURL: row.EncryptedURL, + ID: row.ID, Name: row.Name, Scope: egress.Scope(row.Scope), Enabled: row.Enabled, EncryptedURL: row.EncryptedURL, EncryptedProxyURL: row.EncryptedProxyURL, RefreshIntervalSeconds: row.RefreshIntervalSeconds, DefaultAccountCapacity: row.DefaultAccountCapacity, LastSyncedAt: row.LastSyncedAt, NextSyncAt: row.NextSyncAt, LastSyncImported: row.LastSyncImported, LastSyncError: row.LastSyncError, CreatedAt: row.CreatedAt, UpdatedAt: row.UpdatedAt, @@ -832,7 +832,7 @@ func toEgressSubscriptionSourceDomain(row egressSubscriptionSourceModel) egress. func fromEgressSubscriptionSourceDomain(value egress.SubscriptionSource) egressSubscriptionSourceModel { return egressSubscriptionSourceModel{ - ID: value.ID, Name: value.Name, Scope: string(value.Scope), Enabled: value.Enabled, EncryptedURL: value.EncryptedURL, + ID: value.ID, Name: value.Name, Scope: string(value.Scope), Enabled: value.Enabled, EncryptedURL: value.EncryptedURL, EncryptedProxyURL: value.EncryptedProxyURL, RefreshIntervalSeconds: value.RefreshIntervalSeconds, DefaultAccountCapacity: value.DefaultAccountCapacity, LastSyncedAt: value.LastSyncedAt, NextSyncAt: value.NextSyncAt, LastSyncImported: value.LastSyncImported, LastSyncError: value.LastSyncError, CreatedAt: value.CreatedAt, UpdatedAt: value.UpdatedAt, @@ -843,8 +843,7 @@ func toEgressOperationsConfigDomain(row egressOperationsConfigModel) egress.Oper return egress.OperationsConfig{ ProbeProvider: egress.ProbeProvider(row.ProbeProvider).Normalized(), ProbeIntervalSeconds: row.ProbeIntervalSeconds, AutoAssignEnabled: row.AutoAssignEnabled, AutoBalanceEnabled: row.AutoBalanceEnabled, - AssignmentIntervalSeconds: row.AssignmentIntervalSeconds, - EncryptedSubscriptionProxyURL: row.EncryptedSubscriptionProxyURL, + AssignmentIntervalSeconds: row.AssignmentIntervalSeconds, Fallbacks: map[egress.Scope]egress.FallbackConfig{ egress.ScopeBuild: {Mode: egress.FallbackMode(row.BuildFallbackMode).Normalized(), NodeID: row.BuildFallbackNodeID}, egress.ScopeWeb: {Mode: egress.FallbackMode(row.WebFallbackMode).Normalized(), NodeID: row.WebFallbackNodeID}, @@ -865,8 +864,7 @@ func fromEgressOperationsConfigDomain(value egress.OperationsConfig) egressOpera return egressOperationsConfigModel{ ID: 1, ProbeProvider: string(value.ProbeProvider.Normalized()), ProbeIntervalSeconds: value.ProbeIntervalSeconds, AutoAssignEnabled: value.AutoAssignEnabled, AutoBalanceEnabled: value.AutoBalanceEnabled, AssignmentIntervalSeconds: value.AssignmentIntervalSeconds, - EncryptedSubscriptionProxyURL: value.EncryptedSubscriptionProxyURL, - BuildFallbackMode: string(buildFallback.Mode), BuildFallbackNodeID: buildFallback.NodeID, + BuildFallbackMode: string(buildFallback.Mode), BuildFallbackNodeID: buildFallback.NodeID, WebFallbackMode: string(webFallback.Mode), WebFallbackNodeID: webFallback.NodeID, ConsoleFallbackMode: string(consoleFallback.Mode), ConsoleFallbackNodeID: consoleFallback.NodeID, WebAssetFallbackMode: string(webAssetFallback.Mode), WebAssetFallbackNodeID: webAssetFallback.NodeID, diff --git a/backend/internal/infra/persistence/relational/models.go b/backend/internal/infra/persistence/relational/models.go index 2a594014..66d568cb 100644 --- a/backend/internal/infra/persistence/relational/models.go +++ b/backend/internal/infra/persistence/relational/models.go @@ -477,6 +477,7 @@ type egressSubscriptionSourceModel struct { Scope string `gorm:"size:32;not null;check:chk_egress_subscription_sources_scope,scope IN ('grok_build','grok_web','grok_console','grok_web_asset','grok_console_asset')"` Enabled bool `gorm:"not null;default:true"` EncryptedURL string `gorm:"type:text;not null;default:'';check:chk_egress_subscription_sources_url,length(encrypted_url) <= 65536"` + EncryptedProxyURL string `gorm:"type:text;not null;default:'';check:chk_egress_subscription_sources_proxy_url,length(encrypted_proxy_url) <= 65536"` RefreshIntervalSeconds int `gorm:"not null;default:900;check:chk_egress_subscription_sources_refresh,refresh_interval_seconds BETWEEN 60 AND 86400"` DefaultAccountCapacity int `gorm:"not null;default:0;check:chk_egress_subscription_sources_capacity,default_account_capacity BETWEEN 0 AND 100000"` LastSyncedAt *time.Time @@ -532,24 +533,23 @@ type egressNodeModel struct { func (egressNodeModel) TableName() string { return "egress_nodes" } type egressOperationsConfigModel struct { - ID uint64 `gorm:"primaryKey;check:chk_egress_operations_config_id,id = 1"` - ProbeProvider string `gorm:"size:16;not null;default:cloudflare;check:chk_egress_operations_config_probe_provider,probe_provider IN ('ipinfo','cloudflare')"` - ProbeIntervalSeconds int `gorm:"not null;default:900;check:chk_egress_operations_config_probe_interval,probe_interval_seconds BETWEEN 60 AND 86400"` - AutoAssignEnabled bool `gorm:"not null;default:false"` - AutoBalanceEnabled bool `gorm:"not null;default:false"` - AssignmentIntervalSeconds int `gorm:"not null;default:300;check:chk_egress_operations_config_assignment_interval,assignment_interval_seconds BETWEEN 60 AND 86400"` - EncryptedSubscriptionProxyURL string `gorm:"type:text;not null;default:'';check:chk_egress_operations_config_subscription_proxy,length(encrypted_subscription_proxy_url) <= 65536"` - BuildFallbackMode string `gorm:"size:16;not null;default:none"` - BuildFallbackNodeID uint64 `gorm:"not null;default:0"` - WebFallbackMode string `gorm:"size:16;not null;default:none"` - WebFallbackNodeID uint64 `gorm:"not null;default:0"` - ConsoleFallbackMode string `gorm:"size:16;not null;default:none"` - ConsoleFallbackNodeID uint64 `gorm:"not null;default:0"` - WebAssetFallbackMode string `gorm:"size:16;not null;default:none"` - WebAssetFallbackNodeID uint64 `gorm:"not null;default:0"` - ConsoleAssetFallbackMode string `gorm:"size:16;not null;default:none"` - ConsoleAssetFallbackNodeID uint64 `gorm:"not null;default:0"` - UpdatedAt time.Time `gorm:"not null"` + ID uint64 `gorm:"primaryKey;check:chk_egress_operations_config_id,id = 1"` + ProbeProvider string `gorm:"size:16;not null;default:cloudflare;check:chk_egress_operations_config_probe_provider,probe_provider IN ('ipinfo','cloudflare')"` + ProbeIntervalSeconds int `gorm:"not null;default:900;check:chk_egress_operations_config_probe_interval,probe_interval_seconds BETWEEN 60 AND 86400"` + AutoAssignEnabled bool `gorm:"not null;default:false"` + AutoBalanceEnabled bool `gorm:"not null;default:false"` + AssignmentIntervalSeconds int `gorm:"not null;default:300;check:chk_egress_operations_config_assignment_interval,assignment_interval_seconds BETWEEN 60 AND 86400"` + BuildFallbackMode string `gorm:"size:16;not null;default:none"` + BuildFallbackNodeID uint64 `gorm:"not null;default:0"` + WebFallbackMode string `gorm:"size:16;not null;default:none"` + WebFallbackNodeID uint64 `gorm:"not null;default:0"` + ConsoleFallbackMode string `gorm:"size:16;not null;default:none"` + ConsoleFallbackNodeID uint64 `gorm:"not null;default:0"` + WebAssetFallbackMode string `gorm:"size:16;not null;default:none"` + WebAssetFallbackNodeID uint64 `gorm:"not null;default:0"` + ConsoleAssetFallbackMode string `gorm:"size:16;not null;default:none"` + ConsoleAssetFallbackNodeID uint64 `gorm:"not null;default:0"` + UpdatedAt time.Time `gorm:"not null"` } func (egressOperationsConfigModel) TableName() string { return "egress_operations_config" } diff --git a/backend/internal/infra/persistence/relational/schema.go b/backend/internal/infra/persistence/relational/schema.go index dab56f5a..1bac25c0 100644 --- a/backend/internal/infra/persistence/relational/schema.go +++ b/backend/internal/infra/persistence/relational/schema.go @@ -129,6 +129,7 @@ func (d *Database) initializeSchema(ctx context.Context) error { hadProviderScope := hadClientKeys && db.Migrator().HasColumn(&clientKeyModel{}, "ProviderScopeMask") hadTierScope := hadClientKeys && db.Migrator().HasColumn(&clientKeyModel{}, "TierScopeMask") hadLegacyAccountPool := hadClientKeys && db.Migrator().HasColumn("client_keys", "account_pool") + hadGlobalSubscriptionProxy := db.Migrator().HasTable("egress_operations_config") && db.Migrator().HasColumn("egress_operations_config", "encrypted_subscription_proxy_url") // all 作用域会让 Build 与 Web 共用 UA、健康度和冷却状态,升级时直接移除旧节点。 if db.Migrator().HasTable(&egressNodeModel{}) { if err := db.Where("scope = ?", "all").Delete(&egressNodeModel{}).Error; err != nil { @@ -149,6 +150,11 @@ func (d *Database) initializeSchema(ctx context.Context) error { if migrateErr != nil { return fmt.Errorf("初始化数据库表: %w", migrateErr) } + if hadGlobalSubscriptionProxy { + if err := d.migratePerSourceSubscriptionProxy(ctx); err != nil { + return fmt.Errorf("迁移代理订阅拉取代理: %w", err) + } + } if err := d.migrateClientKeyAccountScopes(ctx, hadLegacyAccountPool, !hadProviderScope, !hadTierScope); err != nil { return fmt.Errorf("迁移客户端 Key 调用范围: %w", err) } @@ -216,6 +222,32 @@ func (d *Database) initializeSchema(ctx context.Context) error { return nil } +func (d *Database) migratePerSourceSubscriptionProxy(ctx context.Context) error { + return d.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error { + var legacy struct { + EncryptedProxyURL string `gorm:"column:encrypted_subscription_proxy_url"` + } + err := tx.Table("egress_operations_config").Select("encrypted_subscription_proxy_url").Where("id = ?", 1).Take(&legacy).Error + if errors.Is(err, gorm.ErrRecordNotFound) { + return nil + } + if err != nil { + return err + } + if strings.TrimSpace(legacy.EncryptedProxyURL) == "" { + return nil + } + if err := tx.Model(&egressSubscriptionSourceModel{}).Where("encrypted_proxy_url = ''").Updates(map[string]any{ + "encrypted_proxy_url": legacy.EncryptedProxyURL, + "next_sync_at": nil, + "last_sync_error": "", + }).Error; err != nil { + return err + } + return tx.Table("egress_operations_config").Where("id = ?", 1).Update("encrypted_subscription_proxy_url", "").Error + }) +} + // migrateClientKeyAccountScopes translates the short-lived account_pool // representation only when the corresponding scope columns are first added. func (d *Database) migrateClientKeyAccountScopes(ctx context.Context, hadLegacyAccountPool, providerScopeAdded, tierScopeAdded bool) error { diff --git a/backend/internal/infra/persistence/relational/schema_subscription_proxy_upgrade_test.go b/backend/internal/infra/persistence/relational/schema_subscription_proxy_upgrade_test.go new file mode 100644 index 00000000..0a24d4e0 --- /dev/null +++ b/backend/internal/infra/persistence/relational/schema_subscription_proxy_upgrade_test.go @@ -0,0 +1,104 @@ +package relational + +import ( + "context" + "path/filepath" + "testing" + "time" +) + +type legacyOperationsConfigWithSubscriptionProxy struct { + ID uint64 `gorm:"primaryKey"` + ProbeProvider string `gorm:"size:16;not null;default:cloudflare"` + ProbeIntervalSeconds int `gorm:"not null;default:900"` + AutoAssignEnabled bool `gorm:"not null;default:false"` + AutoBalanceEnabled bool `gorm:"not null;default:false"` + AssignmentIntervalSeconds int `gorm:"not null;default:300"` + EncryptedSubscriptionProxyURL string `gorm:"type:text;not null;default:''"` + BuildFallbackMode string `gorm:"size:16;not null;default:none"` + BuildFallbackNodeID uint64 `gorm:"not null;default:0"` + WebFallbackMode string `gorm:"size:16;not null;default:none"` + WebFallbackNodeID uint64 `gorm:"not null;default:0"` + ConsoleFallbackMode string `gorm:"size:16;not null;default:none"` + ConsoleFallbackNodeID uint64 `gorm:"not null;default:0"` + WebAssetFallbackMode string `gorm:"size:16;not null;default:none"` + WebAssetFallbackNodeID uint64 `gorm:"not null;default:0"` + ConsoleAssetFallbackMode string `gorm:"size:16;not null;default:none"` + ConsoleAssetFallbackNodeID uint64 `gorm:"not null;default:0"` + UpdatedAt time.Time `gorm:"not null"` +} + +func (legacyOperationsConfigWithSubscriptionProxy) TableName() string { + return "egress_operations_config" +} + +type legacySubscriptionSourceWithoutProxy struct { + ID uint64 `gorm:"primaryKey"` + Name string `gorm:"size:160;not null"` + Scope string `gorm:"size:32;not null"` + Enabled bool `gorm:"not null;default:true"` + EncryptedURL string `gorm:"type:text;not null;default:''"` + RefreshIntervalSeconds int `gorm:"not null;default:900"` + DefaultAccountCapacity int `gorm:"not null;default:0"` + LastSyncedAt *time.Time + NextSyncAt *time.Time + LastSyncImported int `gorm:"not null;default:0"` + LastSyncError string `gorm:"size:512;not null;default:''"` + CreatedAt time.Time `gorm:"not null"` + UpdatedAt time.Time `gorm:"not null"` +} + +func (legacySubscriptionSourceWithoutProxy) TableName() string { + return "egress_subscription_sources" +} + +func TestSchemaMigratesGlobalSubscriptionProxyToEverySource(t *testing.T) { + ctx := context.Background() + database, err := OpenSQLite(ctx, filepath.Join(t.TempDir(), "subscription-proxy-upgrade.db")) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = database.Close() }) + + if err := database.db.AutoMigrate(&legacyOperationsConfigWithSubscriptionProxy{}, &legacySubscriptionSourceWithoutProxy{}); err != nil { + t.Fatal(err) + } + const encryptedProxy = "encrypted-global-subscription-proxy" + if err := database.db.Create(&legacyOperationsConfigWithSubscriptionProxy{ID: 1, EncryptedSubscriptionProxyURL: encryptedProxy}).Error; err != nil { + t.Fatal(err) + } + for _, source := range []legacySubscriptionSourceWithoutProxy{ + {ID: 1, Name: "domestic", Scope: "grok_build", Enabled: true}, + {ID: 2, Name: "overseas", Scope: "grok_web", Enabled: true}, + } { + if err := database.db.Create(&source).Error; err != nil { + t.Fatal(err) + } + } + + if err := database.InitializeSchema(ctx); err != nil { + t.Fatal(err) + } + var sources []egressSubscriptionSourceModel + if err := database.db.Order("id").Find(&sources).Error; err != nil { + t.Fatal(err) + } + if len(sources) != 2 { + t.Fatalf("migrated sources = %d", len(sources)) + } + for _, source := range sources { + if source.EncryptedProxyURL != encryptedProxy || source.NextSyncAt != nil { + t.Fatalf("migrated source = %#v", source) + } + } + var legacy legacyOperationsConfigWithSubscriptionProxy + if err := database.db.First(&legacy, 1).Error; err != nil { + t.Fatal(err) + } + if legacy.EncryptedSubscriptionProxyURL != "" { + t.Fatal("legacy global subscription proxy was not cleared") + } + if err := database.InitializeSchema(ctx); err != nil { + t.Fatalf("repeated migration failed: %v", err) + } +} diff --git a/backend/internal/transport/http/egress/handler.go b/backend/internal/transport/http/egress/handler.go index c5d792eb..a8610f96 100644 --- a/backend/internal/transport/http/egress/handler.go +++ b/backend/internal/transport/http/egress/handler.go @@ -800,6 +800,8 @@ type sourceRequest struct { Enabled bool `json:"enabled"` URL *string `json:"url"` ClearURL bool `json:"clearUrl"` + ProxyURL *string `json:"proxyURL"` + ClearProxyURL bool `json:"clearProxyURL"` RefreshIntervalSeconds *int `json:"refreshIntervalSeconds"` DefaultAccountCapacity *int `json:"defaultAccountCapacity"` } @@ -810,6 +812,7 @@ type sourceResponse struct { Scope string `json:"scope"` Enabled bool `json:"enabled"` URLConfigured bool `json:"urlConfigured"` + ProxyConfigured bool `json:"proxyConfigured"` RefreshIntervalSeconds int `json:"refreshIntervalSeconds"` DefaultAccountCapacity int `json:"defaultAccountCapacity"` LastSyncedAt *time.Time `json:"lastSyncedAt,omitempty"` @@ -835,8 +838,6 @@ type operationsConfigRequest struct { AutoAssignEnabled bool `json:"autoAssignEnabled"` AutoBalanceEnabled bool `json:"autoBalanceEnabled"` AssignmentIntervalSeconds int `json:"assignmentIntervalSeconds"` - SubscriptionProxyURL *string `json:"subscriptionProxyURL,omitempty"` - ClearSubscriptionProxy bool `json:"clearSubscriptionProxy,omitempty"` Fallbacks map[string]operationsFallbackRequest `json:"fallbacks"` } @@ -846,14 +847,13 @@ type operationsFallbackRequest struct { } type operationsConfigResponse struct { - ProbeProvider string `json:"probeProvider"` - ProbeIntervalSeconds int `json:"probeIntervalSeconds"` - AutoAssignEnabled bool `json:"autoAssignEnabled"` - AutoBalanceEnabled bool `json:"autoBalanceEnabled"` - AssignmentIntervalSeconds int `json:"assignmentIntervalSeconds"` - SubscriptionProxyConfigured bool `json:"subscriptionProxyConfigured"` - Fallbacks map[string]operationsFallbackResponse `json:"fallbacks"` - UpdatedAt time.Time `json:"updatedAt"` + ProbeProvider string `json:"probeProvider"` + ProbeIntervalSeconds int `json:"probeIntervalSeconds"` + AutoAssignEnabled bool `json:"autoAssignEnabled"` + AutoBalanceEnabled bool `json:"autoBalanceEnabled"` + AssignmentIntervalSeconds int `json:"assignmentIntervalSeconds"` + Fallbacks map[string]operationsFallbackResponse `json:"fallbacks"` + UpdatedAt time.Time `json:"updatedAt"` } type operationsFallbackResponse struct { @@ -866,12 +866,6 @@ func (value operationsConfigRequest) input() (egressapp.OperationsConfigInput, e ProbeProvider: egressdomain.ProbeProvider(strings.TrimSpace(value.ProbeProvider)), ProbeIntervalSeconds: value.ProbeIntervalSeconds, AutoAssignEnabled: value.AutoAssignEnabled, AutoBalanceEnabled: value.AutoBalanceEnabled, AssignmentIntervalSeconds: value.AssignmentIntervalSeconds, } - if value.SubscriptionProxyURL != nil { - result.SubscriptionProxyURL = value.SubscriptionProxyURL - } - if value.ClearSubscriptionProxy { - result.ClearSubscriptionProxy = true - } if value.Fallbacks == nil { return result, nil } @@ -895,6 +889,7 @@ func (value operationsConfigRequest) input() (egressapp.OperationsConfigInput, e func (value sourceRequest) input() egressapp.SubscriptionSourceInput { return egressapp.SubscriptionSourceInput{ Name: value.Name, Scope: egressdomain.Scope(value.Scope), Enabled: value.Enabled, URL: value.URL, ClearURL: value.ClearURL, + ProxyURL: value.ProxyURL, ClearProxyURL: value.ClearProxyURL, RefreshIntervalSeconds: value.RefreshIntervalSeconds, DefaultAccountCapacity: value.DefaultAccountCapacity, } } @@ -902,6 +897,7 @@ func (value sourceRequest) input() egressapp.SubscriptionSourceInput { func newSourceResponse(value egressdomain.PublicSubscriptionSource) sourceResponse { return sourceResponse{ ID: value.ID, Name: value.Name, Scope: string(value.Scope), Enabled: value.Enabled, URLConfigured: value.URLConfigured, + ProxyConfigured: value.ProxyConfigured, RefreshIntervalSeconds: value.RefreshIntervalSeconds, DefaultAccountCapacity: value.DefaultAccountCapacity, LastSyncedAt: value.LastSyncedAt, NextSyncAt: value.NextSyncAt, LastSyncImported: value.LastSyncImported, LastSyncError: value.LastSyncError, } @@ -920,8 +916,7 @@ func newOperationsConfigResponse(value egressdomain.OperationsConfig) operations return operationsConfigResponse{ ProbeProvider: string(value.ProbeProvider.Normalized()), ProbeIntervalSeconds: value.ProbeIntervalSeconds, AutoAssignEnabled: value.AutoAssignEnabled, AutoBalanceEnabled: value.AutoBalanceEnabled, AssignmentIntervalSeconds: value.AssignmentIntervalSeconds, - SubscriptionProxyConfigured: value.EncryptedSubscriptionProxyURL != "", - Fallbacks: fallbacks, UpdatedAt: value.UpdatedAt, + Fallbacks: fallbacks, UpdatedAt: value.UpdatedAt, } } diff --git a/backend/internal/transport/http/egress/handler_test.go b/backend/internal/transport/http/egress/handler_test.go index 5e53991e..ad182620 100644 --- a/backend/internal/transport/http/egress/handler_test.go +++ b/backend/internal/transport/http/egress/handler_test.go @@ -281,16 +281,3 @@ func TestOperationsConfigRequestRejectsInvalidFallbackNodeID(t *testing.T) { t.Fatalf("invalid node ID error = %v", err) } } - -func TestOperationsConfigResponseReportsSubscriptionProxyWithoutExposingIt(t *testing.T) { - response := newOperationsConfigResponse(egressdomain.OperationsConfig{ - ProbeProvider: egressdomain.ProbeProviderCloudflare, - EncryptedSubscriptionProxyURL: "encrypted-secret-must-not-be-returned", - }) - if !response.SubscriptionProxyConfigured { - t.Fatal("configured subscription proxy was not reported") - } - if response.ProbeProvider != "cloudflare" { - t.Fatalf("probe provider=%q", response.ProbeProvider) - } -} diff --git a/frontend/src/features/settings/egress-operations.tsx b/frontend/src/features/settings/egress-operations.tsx index f1d5ca5e..4002c595 100644 --- a/frontend/src/features/settings/egress-operations.tsx +++ b/frontend/src/features/settings/egress-operations.tsx @@ -30,7 +30,6 @@ import { type EgressFallbackMode, type EgressNodeDTO, type EgressOperationsConfigDTO, - type EgressOperationsConfigInput, type EgressScope, type EgressSourceDTO, type EgressSourceInput, @@ -43,13 +42,9 @@ import { DataTableShell } from "@/shared/components/data-table-shell"; import { Pagination } from "@/shared/components/pagination"; import { VirtualTableBody } from "@/shared/components/virtual-table-body"; -type SourceForm = EgressSourceInput & { url: string }; -type OperationsForm = Omit & { - subscriptionProxyURL: string; - clearSubscriptionProxy: boolean; -}; +type SourceForm = Omit & { url: string; proxyEnabled: boolean; proxyURL: string }; const emptySource: SourceForm = { - name: "", scope: "grok_build", enabled: true, url: "", refreshIntervalSeconds: 900, defaultAccountCapacity: 0, + name: "", scope: "grok_build", enabled: true, url: "", proxyEnabled: false, proxyURL: "", refreshIntervalSeconds: 900, defaultAccountCapacity: 0, }; // Eight nodes run concurrently; each checks IPv4 and IPv6 in parallel with a // 15-second ceiling. Keeping a request to 32 nodes leaves enough headroom for @@ -71,11 +66,11 @@ function defaultFallbacks(): Record { }; } -const defaultOperationsForm: OperationsForm = { - probeProvider: "cloudflare", probeIntervalSeconds: 900, autoAssignEnabled: false, autoBalanceEnabled: false, assignmentIntervalSeconds: 300, fallbacks: defaultFallbacks(), subscriptionProxyURL: "", subscriptionProxyConfigured: false, clearSubscriptionProxy: false, +const defaultOperationsForm: Omit = { + probeProvider: "cloudflare", probeIntervalSeconds: 900, autoAssignEnabled: false, autoBalanceEnabled: false, assignmentIntervalSeconds: 300, fallbacks: defaultFallbacks(), }; -function operationsFormFrom(value?: EgressOperationsConfigDTO): OperationsForm { +function operationsFormFrom(value?: EgressOperationsConfigDTO): Omit { if (!value) return { ...defaultOperationsForm, fallbacks: defaultFallbacks() }; const defaults = defaultFallbacks(); @@ -92,26 +87,9 @@ function operationsFormFrom(value?: EgressOperationsConfigDTO): OperationsForm { grok_web_asset: { ...defaults.grok_web_asset, ...value.fallbacks.grok_web_asset }, grok_console_asset: { ...defaults.grok_console_asset, ...value.fallbacks.grok_console_asset }, }, - subscriptionProxyURL: "", - subscriptionProxyConfigured: value.subscriptionProxyConfigured, - clearSubscriptionProxy: false, }; } -function operationsInputFrom(value: OperationsForm): EgressOperationsConfigInput { - const result: EgressOperationsConfigInput = { - probeProvider: value.probeProvider, - probeIntervalSeconds: value.probeIntervalSeconds, - autoAssignEnabled: value.autoAssignEnabled, - autoBalanceEnabled: value.autoBalanceEnabled, - assignmentIntervalSeconds: value.assignmentIntervalSeconds, - fallbacks: value.fallbacks, - }; - if (value.clearSubscriptionProxy) result.clearSubscriptionProxy = true; - else if (value.subscriptionProxyURL.trim()) result.subscriptionProxyURL = value.subscriptionProxyURL.trim(); - return result; -} - async function testAllEgressNodes() { const nodes = await listAllEgressNodes(); const ids = nodes.items.filter((node) => node.enabled && node.proxyConfigured).map((node) => node.id); @@ -138,8 +116,7 @@ async function testAllEgressNodes() { export function EgressAutomation({ scopeLabel }: { scopeLabel: (scope: EgressScope) => string }) { const { t } = useTranslation(); const queryClient = useQueryClient(); - const [operationsDraft, setOperationsDraft] = useState(null); - const [subscriptionProxyError, setSubscriptionProxyError] = useState(""); + const [operationsDraft, setOperationsDraft] = useState | null>(null); const operationsQuery = useQuery({ queryKey: ["egress-operations"], queryFn: getEgressOperationsConfig }); const nodesQuery = useQuery({ queryKey: ["egress-nodes", "fallback-options"], queryFn: () => listAllEgressNodes() }); const operationsForm = operationsDraft ?? operationsFormFrom(operationsQuery.data); @@ -163,7 +140,7 @@ export function EgressAutomation({ scopeLabel }: { scopeLabel: (scope: EgressSco onError: showError, }); const saveOperations = useMutation({ - mutationFn: () => updateEgressOperationsConfig(operationsInputFrom(operationsForm)), + mutationFn: () => updateEgressOperationsConfig(operationsForm), onSuccess: () => { setOperationsDraft(null); invalidate(); toast.success(t("settings.egress.automationSaved")); }, onError: showError, }); @@ -188,7 +165,7 @@ export function EgressAutomation({ scopeLabel }: { scopeLabel: (scope: EgressSco - + {operationsQuery.isError ? void operationsQuery.refetch()} /> : operationsQuery.isPending ? : ( @@ -214,43 +191,6 @@ export function EgressAutomation({ scopeLabel }: { scopeLabel: (scope: EgressSco
setOperationsDraft({ ...operationsForm, autoBalanceEnabled })} />
- -
-
- { - const value = event.target.value; - setOperationsDraft({ ...operationsForm, subscriptionProxyURL: value, clearSubscriptionProxy: false }); - setSubscriptionProxyError(value.trim() && !validSubscriptionProxyURL(value) ? t("settings.egress.invalidProxy") : ""); - }} - /> - {operationsForm.subscriptionProxyConfigured ? ( - - ) : null} -
- {operationsForm.subscriptionProxyConfigured ? ( -
- - {operationsForm.clearSubscriptionProxy ? t("settings.egress.subscriptionProxyClearPending") : t("settings.egress.configured")} - - {!operationsForm.clearSubscriptionProxy && !operationsForm.subscriptionProxyURL ? {t("settings.egress.keepConfigured")} : null} -
- ) : null} -
-

{t("settings.egress.fallback")}

@@ -319,7 +259,13 @@ export function EgressSources({ scopeLabel }: { scopeLabel: (scope: EgressScope) }; const saveSource = useMutation({ mutationFn: () => { - const input: EgressSourceInput = { ...sourceForm, url: sourceForm.url.trim() || undefined }; + const input: EgressSourceInput = { + name: sourceForm.name, scope: sourceForm.scope, enabled: sourceForm.enabled, + url: sourceForm.url.trim() || undefined, + proxyURL: sourceForm.proxyEnabled ? (sourceForm.proxyURL.trim() || undefined) : undefined, + clearProxyURL: Boolean(sourceEditing?.proxyConfigured && !sourceForm.proxyEnabled), + refreshIntervalSeconds: sourceForm.refreshIntervalSeconds, defaultAccountCapacity: sourceForm.defaultAccountCapacity, + }; return sourceEditing ? updateEgressSource(sourceEditing.id, input) : createEgressSource(input); }, onSuccess: () => { if (!sourceEditing) setPage(1); invalidate(); setSourceEditing(undefined); toast.success(t("settings.egress.sourceSaved")); }, @@ -344,7 +290,7 @@ export function EgressSources({ scopeLabel }: { scopeLabel: (scope: EgressScope) } setSourceForm({ name: value.name, scope: value.scope, enabled: value.enabled, url: "", refreshIntervalSeconds: value.refreshIntervalSeconds, - defaultAccountCapacity: value.defaultAccountCapacity, + proxyEnabled: value.proxyConfigured, proxyURL: "", defaultAccountCapacity: value.defaultAccountCapacity, }); setSourceEditing(value); } @@ -359,6 +305,7 @@ export function EgressSources({ scopeLabel }: { scopeLabel: (scope: EgressScope) const currentPage = Math.min(page, pageCount); const pagedSources = filteredSources.slice((currentPage - 1) * pageSize, currentPage * pageSize); const hasActiveFilters = Boolean(normalizedSearch || scopeFilter); + const sourceProxyInvalid = sourceForm.proxyEnabled && Boolean(sourceForm.proxyURL.trim()) && !validSubscriptionProxyURL(sourceForm.proxyURL); return (
@@ -388,14 +335,15 @@ export function EgressSources({ scopeLabel }: { scopeLabel: (scope: EgressScope) footer={filteredSources.length > 0 ? { setPageSize(value); setPage(1); }} /> : undefined} > {sourcesQuery.isError ? void sourcesQuery.refetch()} /> : null} - {!sourcesQuery.isError ? - {t("settings.egress.source")}{t("settings.egress.scope")}{t("settings.egress.lastSync")}{t("settings.egress.capacity")} - {sourcesQuery.isPending ? : null} - {!sourcesQuery.isPending && pagedSources.length === 0 ? {hasActiveFilters ? t("settings.egress.noSubscriptionMatches") : t("settings.egress.noSources")} : null} - {!sourcesQuery.isPending && pagedSources.length > 0 ? ( + {!sourcesQuery.isError ?
+ {t("settings.egress.source")}{t("settings.egress.scope")}{t("settings.egress.subscriptionRoute")}{t("settings.egress.lastSync")}{t("settings.egress.capacity")} + {sourcesQuery.isPending ? : null} + {!sourcesQuery.isPending && pagedSources.length === 0 ? {hasActiveFilters ? t("settings.egress.noSubscriptionMatches") : t("settings.egress.noSources")} : null} + {!sourcesQuery.isPending && pagedSources.length > 0 ? (
{source.name}{source.lastSyncError ? : null}
{scopeLabel(source.scope)} + {source.proxyConfigured ? t("settings.egress.subscriptionProxyShort") : t("settings.egress.direct")} {source.lastSyncedAt ? formatDateTime(source.lastSyncedAt, i18n.language) : t("settings.egress.never")} {source.defaultAccountCapacity || t("settings.egress.unlimited")} @@ -419,11 +367,13 @@ export function EgressSources({ scopeLabel }: { scopeLabel: (scope: EgressScope) setSourceForm({ ...sourceForm, name: event.target.value })} /> setSourceForm({ ...sourceForm, scope })} scopeLabel={scopeLabel} /> setSourceForm({ ...sourceForm, url: event.target.value })} /> + setSourceForm({ ...sourceForm, proxyEnabled })} /> + {sourceForm.proxyEnabled ? setSourceForm({ ...sourceForm, proxyURL: event.target.value })} />{sourceProxyInvalid ?

{t("settings.egress.invalidSubscriptionProxy")}

: null}
: null}
setSourceForm({ ...sourceForm, refreshIntervalSeconds: Number(event.target.value) })} /> setSourceForm({ ...sourceForm, defaultAccountCapacity: Number(event.target.value) })} />
- + diff --git a/frontend/src/features/settings/settings-api.ts b/frontend/src/features/settings/settings-api.ts index 22fda831..dcd53ed9 100644 --- a/frontend/src/features/settings/settings-api.ts +++ b/frontend/src/features/settings/settings-api.ts @@ -64,7 +64,7 @@ export type EgressNodeListDTO = { defaultUserAgents: Record; }; export type EgressSourceDTO = { - id: string; name: string; scope: EgressScope; enabled: boolean; urlConfigured: boolean; + id: string; name: string; scope: EgressScope; enabled: boolean; urlConfigured: boolean; proxyConfigured: boolean; refreshIntervalSeconds: number; defaultAccountCapacity: number; lastSyncedAt?: string; nextSyncAt?: string; lastSyncImported: number; lastSyncError?: string; }; @@ -76,16 +76,12 @@ export type EgressSourceListDTO = { }; export type EgressSourceInput = { name: string; scope: EgressScope; enabled: boolean; url?: string; clearUrl?: boolean; + proxyURL?: string; clearProxyURL?: boolean; refreshIntervalSeconds: number; defaultAccountCapacity: number; }; export type EgressOperationsConfigDTO = { probeProvider: "ipinfo" | "cloudflare"; probeIntervalSeconds: number; autoAssignEnabled: boolean; autoBalanceEnabled: boolean; assignmentIntervalSeconds: number; fallbacks: Record; updatedAt: string; - subscriptionProxyConfigured: boolean; -}; -export type EgressOperationsConfigInput = Omit & { - subscriptionProxyURL?: string; - clearSubscriptionProxy?: boolean; }; export type EgressImportResultDTO = { imported: number; skipped: number }; export type EgressIPProbeDTO = { status: "unknown" | "healthy" | "unhealthy"; testedAt?: string; latencyMs: number; exitIp?: string; error?: string }; @@ -195,9 +191,8 @@ const egressIPProbeValidator = hasShape({ status: isOneOf("unknown", "healthy", "unhealthy"), testedAt: isOptional(isString), latencyMs: isNumber, exitIp: isOptional(isString), error: isOptional(isString), }); type EgressNodeWireDTO = Omit & { ipv4Probe?: EgressIPProbeDTO; ipv6Probe?: EgressIPProbeDTO }; -type EgressOperationsConfigWireDTO = Omit & { +type EgressOperationsConfigWireDTO = Omit & { probeProvider?: "ipinfo" | "cloudflare"; - subscriptionProxyConfigured?: boolean; }; type EgressProbeResultWireDTO = Omit & { ipv4?: EgressIPProbeDTO; ipv6?: EgressIPProbeDTO }; const unknownEgressIPProbe = (): EgressIPProbeDTO => ({ status: "unknown", latencyMs: 0 }); @@ -253,11 +248,13 @@ const decodeEgressNodeList = (value: unknown): EgressNodeListDTO => { }; const egressSourceValidator = hasShape({ id: isString, name: isString, scope: isOneOf("grok_build", "grok_web", "grok_console", "grok_web_asset", "grok_console_asset"), enabled: isBoolean, urlConfigured: isBoolean, + proxyConfigured: isBoolean, refreshIntervalSeconds: isNumber, defaultAccountCapacity: isNumber, lastSyncedAt: isOptional(isString), nextSyncAt: isOptional(isString), lastSyncImported: isNumber, lastSyncError: isOptional(isString), }); const decodeEgressSource = createObjectDecoder("egress source", { id: isString, name: isString, scope: isOneOf("grok_build", "grok_web", "grok_console", "grok_web_asset", "grok_console_asset"), enabled: isBoolean, urlConfigured: isBoolean, + proxyConfigured: isBoolean, refreshIntervalSeconds: isNumber, defaultAccountCapacity: isNumber, lastSyncedAt: isOptional(isString), nextSyncAt: isOptional(isString), lastSyncImported: isNumber, lastSyncError: isOptional(isString), }); @@ -286,11 +283,10 @@ const egressFallbackConfigValidator = hasShape({ mode: isOneOf("none", "direct", const decodeEgressOperationsConfigRaw = createObjectDecoder("egress operations config", { probeProvider: isOptional(isOneOf("ipinfo", "cloudflare")), probeIntervalSeconds: isNumber, autoAssignEnabled: isBoolean, autoBalanceEnabled: isBoolean, assignmentIntervalSeconds: isNumber, fallbacks: isRecordOf(egressFallbackConfigValidator), updatedAt: isString, - subscriptionProxyConfigured: isOptional(isBoolean), }); const decodeEgressOperationsConfig = (value: unknown): EgressOperationsConfigDTO => { const decoded = decodeEgressOperationsConfigRaw(value); - return { ...decoded, probeProvider: decoded.probeProvider ?? "cloudflare", subscriptionProxyConfigured: decoded.subscriptionProxyConfigured ?? false }; + return { ...decoded, probeProvider: decoded.probeProvider ?? "cloudflare" }; }; const decodeEgressProbeResultRaw = createObjectDecoder("egress probe", { status: isOneOf("unknown", "healthy", "unhealthy"), testedAt: isString, latencyMs: isNumber, exitIp: isOptional(isString), error: isOptional(isString), probeProvider: isOptional(isOneOf("ipinfo", "cloudflare")), @@ -428,7 +424,7 @@ export function getEgressOperationsConfig(): Promise return apiRequest("/api/admin/v1/egress-operations", {}, decodeEgressOperationsConfig); } -export function updateEgressOperationsConfig(input: EgressOperationsConfigInput): Promise { +export function updateEgressOperationsConfig(input: Omit): Promise { return apiRequest("/api/admin/v1/egress-operations", { method: "PUT", body: input }, decodeEgressOperationsConfig); } diff --git a/frontend/src/features/settings/settings-model.ts b/frontend/src/features/settings/settings-model.ts index d31c1411..e599cbfe 100644 --- a/frontend/src/features/settings/settings-model.ts +++ b/frontend/src/features/settings/settings-model.ts @@ -376,7 +376,7 @@ function validProxyURL(value: string): boolean { } } -/** Subscription fetch proxies are global and must never use per-account lease placeholders. */ +/** Subscription fetch proxies must never use per-account lease placeholders. */ export function validSubscriptionProxyURL(value: string): boolean { return !value.includes("{account}") && validProxyURL(value); } diff --git a/frontend/src/shared/i18n/index.ts b/frontend/src/shared/i18n/index.ts index bef6f887..42a9894f 100644 --- a/frontend/src/shared/i18n/index.ts +++ b/frontend/src/shared/i18n/index.ts @@ -1753,7 +1753,8 @@ Object.assign(resources.en.translation.settings.egress as unknown as Record, { @@ -1816,7 +1811,12 @@ Object.assign(resources["zh-CN"].translation.settings.egress as unknown as Recor sourceDeleted: "代理订阅已删除", sourceSynced: "代理订阅同步完成:导入 {{imported}},跳过 {{skipped}}", editSource: "编辑订阅", - sourceDialogDescription: "配置订阅地址、作用域、同步间隔和单节点账号容量。", + sourceDialogDescription: "配置订阅地址、拉取线路、作用域、同步间隔和单节点账号容量。", + subscriptionProxy: "使用代理拉取", + subscriptionProxyURL: "订阅拉取代理地址", + subscriptionRoute: "拉取线路", + subscriptionProxyShort: "代理", + invalidSubscriptionProxy: "请输入有效的 HTTP 或 SOCKS 代理地址;此处不支持 {account}", refreshInterval: "同步间隔(秒)", noSources: "暂无代理订阅", probeInterval: "节点检测间隔", @@ -1864,12 +1864,6 @@ Object.assign(resources["zh-CN"].translation.settings.egress as unknown as Recor cleanupSubscriptionHint: "订阅管理的节点可能在下次订阅同步时重新创建。", cleanupUnavailableConfirm: "删除不可用节点", cleanupUnavailableComplete: "已删除 {{deleted}} 个不可用代理节点", - subscriptionProxy: "订阅拉取代理", - subscriptionProxyHelp: "用于拉取代理订阅内容。许多订阅源不支持国外网络,可填写 HTTP/HTTPS/SOCKS 代理地址。", - clearSubscriptionProxy: "清除", - cancelClearSubscriptionProxy: "保留", - subscriptionProxyClearPending: "保存后清除", - invalidProxy: "请输入有效的代理地址(http/https/socks4/socks4a/socks5/socks5h);此处不支持 {account}", }); Object.assign(resources["zh-CN"].translation.accounts as unknown as Record, { From beed4c858465c33e1aafed69a5e6f873f6af195c Mon Sep 17 00:00:00 2001 From: WuxiVIP Date: Mon, 10 Aug 2026 14:51:41 +0800 Subject: [PATCH 03/40] feat(egress): support trojan/vless/ss/vmess/hysteria/tuic in proxy subscription validation --- backend/internal/application/egress/service.go | 16 ++++++++++++---- .../internal/application/egress/service_test.go | 6 ++++++ 2 files changed, 18 insertions(+), 4 deletions(-) diff --git a/backend/internal/application/egress/service.go b/backend/internal/application/egress/service.go index 4ab205dc..c76e7010 100644 --- a/backend/internal/application/egress/service.go +++ b/backend/internal/application/egress/service.go @@ -855,12 +855,20 @@ func NormalizeProxyURL(value string) (string, error) { return "", errors.New("代理地址格式无效") } switch strings.ToLower(parsed.Scheme) { - case "http", "https", "socks4", "socks4a", "socks5", "socks5h": + case "http", "https", "socks4", "socks4a", "socks5", "socks5h", + "trojan", "vless", "ss", "vmess", "hysteria", "hysteria2", "tuic", "tuicv5": default: - return "", errors.New("代理地址协议必须是 HTTP、HTTPS、SOCKS4 或 SOCKS5") + return "", errors.New("代理地址协议需为 HTTP、HTTPS、SOCKS4、SOCKS5,或 Trojan、VLESS、SS、VMess、Hysteria 等主流隧道协议。") } - if parsed.RawQuery != "" || parsed.Fragment != "" || (parsed.Path != "" && parsed.Path != "/") { - return "", errors.New("代理地址不能包含路径、查询参数或片段") + tunnelSchemes := map[string]bool{ + "trojan": true, "vless": true, "ss": true, "vmess": true, + "hysteria": true, "hysteria2": true, "tuic": true, "tuicv5": true, + } + scheme := strings.ToLower(parsed.Scheme) + if !tunnelSchemes[scheme] { + if parsed.RawQuery != "" || parsed.Fragment != "" || (parsed.Path != "" && parsed.Path != "/") { + return "", errors.New("代理地址不能包含路径、查询参数或片段") + } } if hasAccountPlaceholder { if parsed.User == nil || !strings.Contains(parsed.User.Username(), proxyAccountSentinel) { diff --git a/backend/internal/application/egress/service_test.go b/backend/internal/application/egress/service_test.go index d848d6cd..4dad16ec 100644 --- a/backend/internal/application/egress/service_test.go +++ b/backend/internal/application/egress/service_test.go @@ -25,6 +25,12 @@ func TestNormalizeProxyURLValidatesStructure(t *testing.T) { "http://user:password@127.0.0.1:8080", "https://proxy.example:8443", "socks4://127.0.0.1:1080", "socks4a://proxy.example:1080", "socks5://user:password@127.0.0.1:1080", "socks5h://user:password@proxy.example:1080", + "trojan://password@127.0.0.1:8443?allowInsecure=0#remark", + "vless://uuid@127.0.0.1:443?encryption=none&flow=xtls-rprx-vision#remark", + "ss://base64#remark", + "vmess://base64#remark", + "hysteria://127.0.0.1:443", + "tuic://user:pass@127.0.0.1:443", } { value, err := NormalizeProxyURL(raw) if err != nil || value == "" { From 4cfa751c0fc39a111192d6debfd5c5abe6c7d1c5 Mon Sep 17 00:00:00 2001 From: WuxiVIP Date: Mon, 10 Aug 2026 17:01:58 +0800 Subject: [PATCH 04/40] fix(egress): add real tunnel proxy dialers Parse and normalize Trojan, VLESS, Shadowsocks, and VMess share links, then route Build, browser, pinned HTTPS, and subscription fetch traffic through embedded dialers. Update validation, UI help, redaction, docs, and protocol coverage tests. Hysteria and TUIC remain unsupported and are intentionally deferred. --- README.md | 7 +- README.zh-CN.md | 7 +- backend/go.mod | 13 + backend/go.sum | 34 +- .../internal/application/egress/service.go | 35 +- .../application/egress/service_test.go | 34 +- .../application/egress/subscription.go | 9 +- .../application/egress/subscription_test.go | 24 + backend/internal/infra/egress/buildclient.go | 7 + .../internal/infra/egress/buildclient_test.go | 35 + backend/internal/infra/egress/flaresolverr.go | 6 + .../infra/egress/flaresolverr_test.go | 11 +- backend/internal/infra/egress/pinnedclient.go | 7 + backend/internal/infra/egress/tlsclient.go | 16 +- .../internal/pkg/tunnelproxy/tunnelproxy.go | 651 ++++++++++++++++++ .../pkg/tunnelproxy/tunnelproxy_test.go | 132 ++++ .../src/features/settings/settings-model.ts | 42 +- frontend/src/shared/i18n/index.ts | 14 +- 18 files changed, 1042 insertions(+), 42 deletions(-) create mode 100644 backend/internal/pkg/tunnelproxy/tunnelproxy.go create mode 100644 backend/internal/pkg/tunnelproxy/tunnelproxy_test.go diff --git a/README.md b/README.md index 38208957..79c166a0 100644 --- a/README.md +++ b/README.md @@ -138,7 +138,7 @@ The Gateway routes requests through the Provider Registry. Account Sync refreshe | Routing | Model discovery, Provider pinning, sticky sessions, quota/concurrency guards, and bounded failover | | Sessions | Stored responses, compact, prompt-cache affinity, and optional reasoning replay | | Media | Image generation/editing, video jobs, local archiving, and URL/Base64/SSE output | -| Egress | HTTP/SOCKS/Resin, subscriptions, probes, proxy pools, allocation, fallback, and FlareSolverr | +| Egress | HTTP/SOCKS/Resin and Trojan/VLESS/Shadowsocks/VMess tunnels, subscriptions, probes, proxy pools, allocation, fallback, and FlareSolverr | | Operations | Dashboard, model routes, client keys, audits, runtime settings, and media libraries | ### Provider boundaries @@ -330,7 +330,8 @@ curl http://127.0.0.1:8000/v1/responses \ Egress nodes are scoped to Build, Web, Console, or Web assets. The admin console supports: -- HTTP, HTTPS, SOCKS4/4A, SOCKS5/5H, and Resin +- HTTP, HTTPS, SOCKS4/4A, SOCKS5/5H, Resin, Trojan, VLESS, Shadowsocks, and VMess +- TCP, WebSocket, and TLS tunnel transports; unsupported variants are rejected during import - Subscription and text/Base64 import - Batch probes, filtering, deletion, assignment, and balancing - Fallback per scope: none, direct, or a fixed node @@ -338,6 +339,8 @@ Egress nodes are scoped to Build, Web, Console, or Web assets. The admin console - Immediate recovery probes after fixed-proxy transport failures, with per-node coalescing and bounded waiting for fast retry - Optional [Egress Quality Guard](./tools/egress-quality-guard/README.md) for active per-node model probes, guarded quarantine, and recovery; enable it with the built-in `quality-guard` Compose profile +Hysteria and TUIC are not supported yet. FlareSolverr accepts only HTTP/SOCKS proxy URLs, so automatic clearance refresh cannot use a tunnel share URL directly. + To enable the guard, add a `qualityGuard` section to `config.yaml`, then start the profile. The main service creates and reuses a non-exportable system probe identity automatically: diff --git a/README.zh-CN.md b/README.zh-CN.md index 38aff70d..79ad456a 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -139,7 +139,7 @@ flowchart LR | 路由 | 模型发现、Provider 限定、会话粘滞、额度/并发门禁和有界切换 | | 会话 | stored response、compact、Prompt Cache 亲和与可选 reasoning replay | | 媒体 | 图片生成与编辑、视频任务、本地归档及 URL/Base64/SSE 输出 | -| 出口 | HTTP/SOCKS/Resin、订阅、探测、代理池、调配、回退与 FlareSolverr | +| 出口 | HTTP/SOCKS/Resin 与 Trojan/VLESS/Shadowsocks/VMess 隧道、订阅、探测、代理池、调配、回退与 FlareSolverr | | 运维 | Dashboard、模型路由、客户端密钥、审计、运行设置和媒体库 | ### Provider 边界 @@ -331,7 +331,8 @@ curl http://127.0.0.1:8000/v1/responses \ 出口节点按 Build、Web、Console 或 Web 资源隔离。管理端支持: -- HTTP、HTTPS、SOCKS4/4A、SOCKS5/5H 与 Resin +- HTTP、HTTPS、SOCKS4/4A、SOCKS5/5H、Resin、Trojan、VLESS、Shadowsocks 与 VMess +- 隧道协议支持 TCP、WebSocket 和 TLS,未实现的传输形态会在导入时拒绝 - 订阅和文本/Base64 导入 - 批量探测、筛选、删除、分配与均衡 - 按作用域配置无回退、直连或固定节点 @@ -339,6 +340,8 @@ curl http://127.0.0.1:8000/v1/responses \ - 固定代理传输失败后立即复测;同节点复测自动合并,后续绑定请求限时等待并在恢复后快速重试 - 可选的[出口质量守护程序](./tools/egress-quality-guard/README.zh-CN.md),支持逐节点模型探测、防误杀隔离和自动恢复;通过内置的 `quality-guard` Compose profile 按需启用 +Hysteria 与 TUIC 暂未支持。FlareSolverr 仅接受 HTTP/SOCKS 代理地址,因此自动刷新 Clearance 暂不能直接使用隧道分享链接。 + 首次启用时只需在 `config.yaml` 中增加 `qualityGuard` 并启动 profile。主程序会自动创建并稳定复用不可导出的系统探测身份: ```yaml diff --git a/backend/go.mod b/backend/go.mod index 7cdc90a9..f30e3898 100644 --- a/backend/go.mod +++ b/backend/go.mod @@ -3,15 +3,18 @@ module github.com/chenyme/grok2api/backend go 1.26 require ( + github.com/Asutorufa/yuhaiin v0.3.8 github.com/bdandy/go-socks4 v1.2.3 github.com/bogdanfinn/fhttp v0.6.8 github.com/bogdanfinn/tls-client v1.15.1 github.com/bogdanfinn/websocket v1.5.5-barnius + github.com/coder/websocket v1.8.14 github.com/gin-gonic/gin v1.12.0 github.com/glebarez/sqlite v1.11.0 github.com/golang-jwt/jwt/v5 v5.3.1 github.com/google/uuid v1.6.0 github.com/redis/go-redis/v9 v9.21.0 + github.com/shadowsocks/go-shadowsocks2 v0.1.5 github.com/swaggo/files v1.0.1 github.com/swaggo/gin-swagger v1.6.1 github.com/swaggo/swag v1.16.6 @@ -30,6 +33,7 @@ require ( github.com/PuerkitoBio/urlesc v0.0.0-20170810143723-de5bf2ad4578 // indirect github.com/andybalholm/brotli v1.2.0 // indirect github.com/bdandy/go-errors v1.2.2 // indirect + github.com/beorn7/perks v1.0.1 // indirect github.com/bogdanfinn/quic-go-utls v1.0.9-utls // indirect github.com/bogdanfinn/utls v1.7.7-barnius // indirect github.com/bytedance/gopkg v0.1.3 // indirect @@ -65,21 +69,30 @@ require ( github.com/mattn/go-isatty v0.0.20 // indirect github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect github.com/modern-go/reflect2 v1.0.2 // indirect + github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect github.com/pelletier/go-toml/v2 v2.2.4 // indirect + github.com/prometheus/client_golang v1.20.5 // indirect + github.com/prometheus/client_model v0.6.1 // indirect + github.com/prometheus/common v0.55.0 // indirect + github.com/prometheus/procfs v0.15.1 // indirect github.com/quic-go/qpack v0.6.0 // indirect github.com/quic-go/quic-go v0.59.0 // indirect github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect + github.com/riobard/go-bloom v0.0.0-20200614022211-cdc8013cb5b3 // indirect github.com/tam7t/hpkp v0.0.0-20160821193359-2b70b4024ed5 // indirect github.com/twitchyliquid64/golang-asm v0.15.1 // indirect github.com/ugorji/go/codec v1.3.1 // indirect go.mongodb.org/mongo-driver/v2 v2.5.0 // indirect go.uber.org/atomic v1.11.0 // indirect golang.org/x/arch v0.22.0 // indirect + golang.org/x/exp v0.0.0-20241204233417-43b7b7cde48d // indirect golang.org/x/mod v0.37.0 // indirect golang.org/x/sys v0.47.0 // indirect golang.org/x/text v0.40.0 // indirect + golang.org/x/time v0.9.0 // indirect golang.org/x/tools v0.47.0 // indirect gopkg.in/yaml.v2 v2.4.0 // indirect + gvisor.dev/gvisor v0.0.0-20241220022509-4690b2e35d70 // indirect modernc.org/libc v1.22.5 // indirect modernc.org/mathutil v1.5.0 // indirect modernc.org/memory v1.5.0 // indirect diff --git a/backend/go.sum b/backend/go.sum index e91d31b7..7699ea4e 100644 --- a/backend/go.sum +++ b/backend/go.sum @@ -1,3 +1,5 @@ +github.com/Asutorufa/yuhaiin v0.3.8 h1:HrEqvXNVYUviL2+Zu01AxRJiPayZa7lZvoYQlvgMkgc= +github.com/Asutorufa/yuhaiin v0.3.8/go.mod h1:fLEwJOwgPumPQvGgJNJn392c63GyAaP4QCkZTj6LRyo= github.com/KyleBanks/depth v1.2.1 h1:5h8fQADFrWtarTdtDudMmGsC7GPbOAu6RVB3ffsVFHc= github.com/KyleBanks/depth v1.2.1/go.mod h1:jzSb9d0L43HxTQfT+oSA1EEp2q+ne2uh6XgeJcm8brE= github.com/PuerkitoBio/purell v1.1.1 h1:WEQqlqaGbrPkxLJWfBwQmfEAE1Z7ONdDLqrN38tNFfI= @@ -10,6 +12,8 @@ github.com/bdandy/go-errors v1.2.2 h1:WdFv/oukjTJCLa79UfkGmwX7ZxONAihKu4V0mLIs11 github.com/bdandy/go-errors v1.2.2/go.mod h1:NkYHl4Fey9oRRdbB1CoC6e84tuqQHiqrOcZpqFEkBxM= github.com/bdandy/go-socks4 v1.2.3 h1:Q6Y2heY1GRjCtHbmlKfnwrKVU/k81LS8mRGLRlmDlic= github.com/bdandy/go-socks4 v1.2.3/go.mod h1:98kiVFgpdogR8aIGLWLvjDVZ8XcKPsSI/ypGrO+bqHI= +github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM= +github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw= github.com/bogdanfinn/fhttp v0.6.8 h1:LiQyHOY3i0QoxxNB7nq27/nGNNbtPj0fuBPozhR7Ws4= github.com/bogdanfinn/fhttp v0.6.8/go.mod h1:A+EKDzMx2hb4IUbMx4TlkoHnaJEiLl8r/1Ss1Y+5e5M= github.com/bogdanfinn/quic-go-utls v1.0.9-utls h1:tV6eDEiRbRCcepALSzxR94JUVD3N3ACIiRLgyc2Ep8s= @@ -34,6 +38,8 @@ github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UF github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= github.com/cloudwego/base64x v0.1.6 h1:t11wG9AECkCDk5fMSoxmufanudBtJ+/HemLstXDLI2M= github.com/cloudwego/base64x v0.1.6/go.mod h1:OFcloc187FXDaYHvrNIjxSe8ncn0OOM8gEHfghB2IPU= +github.com/coder/websocket v1.8.14 h1:9L0p0iKiNOibykf283eHkKUHHrpG7f65OE3BhhO7v9g= +github.com/coder/websocket v1.8.14/go.mod h1:NX3SzP+inril6yawo5CQXx8+fk145lPDC6pumgx0mVg= github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= @@ -79,8 +85,8 @@ github.com/golang-jwt/jwt/v5 v5.3.1/go.mod h1:fxCRLWMO43lRc8nhHWY6LGqRcf+1gQWArs github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8= github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU= github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= -github.com/google/pprof v0.0.0-20221118152302-e6195bd50e26 h1:Xim43kblpZXfIBQsbuBVKCudVG457BR2GZFIz3uw3hQ= -github.com/google/pprof v0.0.0-20221118152302-e6195bd50e26/go.mod h1:dDKJzRmX4S37WGHujM7tX//fmj1uioxKzKxz3lo4HJo= +github.com/google/pprof v0.0.0-20240910150728-a0b0bb1d4134 h1:c5FlPPgxOn7kJz3VoPLkQYQXGBS3EklQ4Zfi57uOuqQ= +github.com/google/pprof v0.0.0-20240910150728-a0b0bb1d4134/go.mod h1:vavhavw2zAxS5dIdcRluK6cSGGPlZynqzFM8NdvU144= github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM= @@ -125,11 +131,21 @@ github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M= github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk= +github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 h1:C3w9PqII01/Oq1c1nUAm88MOHcQC9l5mIlSMApZMrHA= +github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822/go.mod h1:+n7T8mK8HuQTcFwEeznm/DIxMOiR9yIdICNftLE1DvQ= github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e/go.mod h1:zD1mROLANZcx1PVRCS0qkT7pwLkGfwJo4zjcN/Tysno= github.com/pelletier/go-toml/v2 v2.2.4 h1:mye9XuhQ6gvn5h28+VilKrrPoQVanw5PMw/TB0t5Ec4= github.com/pelletier/go-toml/v2 v2.2.4/go.mod h1:2gIqNv+qfxSVS7cM2xJQKtLSTLUE9V8t9Stt+h56mCY= github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/prometheus/client_golang v1.20.5 h1:cxppBPuYhUnsO6yo/aoRol4L7q7UFfdm+bR9r+8l63Y= +github.com/prometheus/client_golang v1.20.5/go.mod h1:PIEt8X02hGcP8JWbeHyeZ53Y/jReSnHgO035n//V5WE= +github.com/prometheus/client_model v0.6.1 h1:ZKSh/rekM+n3CeS952MLRAdFwIKqeY8b62p8ais2e9E= +github.com/prometheus/client_model v0.6.1/go.mod h1:OrxVMOVHjw3lKMa8+x6HeMGkHMQyHDk9E3jmP2AmGiY= +github.com/prometheus/common v0.55.0 h1:KEi6DK7lXW/m7Ig5i47x0vRzuBsHuvJdi5ee6Y3G1dc= +github.com/prometheus/common v0.55.0/go.mod h1:2SECS4xJG1kd8XF9IcM1gMX6510RAEL65zxzNImwdc8= +github.com/prometheus/procfs v0.15.1 h1:YagwOFzUgYfKKHX6Dr+sHT7km/hxC76UB0learggepc= +github.com/prometheus/procfs v0.15.1/go.mod h1:fB45yRUv8NstnjriLhBQLuOUt+WW4BsoGhij/e3PBqk= github.com/quic-go/qpack v0.6.0 h1:g7W+BMYynC1LbYLSqRt8PBg5Tgwxn214ZZR34VIOjz8= github.com/quic-go/qpack v0.6.0/go.mod h1:lUpLKChi8njB4ty2bFLX2x4gzDqXwUpaO1DP9qMDZII= github.com/quic-go/quic-go v0.59.0 h1:OLJkp1Mlm/aS7dpKgTc6cnpynnD2Xg7C1pwL6vy/SAw= @@ -139,8 +155,12 @@ github.com/redis/go-redis/v9 v9.21.0/go.mod h1:v/M13XI1PVCDcm01VtPFOADfZtHf8YW3b github.com/remyoudompheng/bigfft v0.0.0-20200410134404-eec4a21b6bb0/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo= github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE= github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo= +github.com/riobard/go-bloom v0.0.0-20200614022211-cdc8013cb5b3 h1:f/FNXud6gA3MNr8meMVVGxhp+QBTqY91tM8HjEuMjGg= +github.com/riobard/go-bloom v0.0.0-20200614022211-cdc8013cb5b3/go.mod h1:HgjTstvQsPGkxUsCd2KWxErBblirPizecHcpD3ffK+s= github.com/rogpeppe/go-internal v1.10.0 h1:TMyTOH3F/DB16zRVcYyreMH6GnZZrwQVAoYjRBZyWFQ= github.com/rogpeppe/go-internal v1.10.0/go.mod h1:UQnix2H7Ngw/k4C5ijL5+65zddjncjaFoBhdsK/akog= +github.com/shadowsocks/go-shadowsocks2 v0.1.5 h1:PDSQv9y2S85Fl7VBeOMF9StzeXZyK1HakRm86CUbr28= +github.com/shadowsocks/go-shadowsocks2 v0.1.5/go.mod h1:AGGpIoek4HRno4xzyFiAtLHkOpcoznZEkAccaI/rplM= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo= @@ -180,12 +200,16 @@ go.uber.org/mock v0.6.0/go.mod h1:KiVJ4BqZJaMj4svdfmHM0AUx4NJYO8ZNpPnZn1Z+BBU= golang.org/x/arch v0.22.0 h1:c/Zle32i5ttqRXjdLyyHZESLD/bB90DCU1g9l/0YBDI= golang.org/x/arch v0.22.0/go.mod h1:dNHoOeKiyja7GTvF9NJS1l3Z2yntpQNzgrjh1cU103A= golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= +golang.org/x/crypto v0.0.0-20210220033148-5ea612d1eb83/go.mod h1:jdWPYTVW3xRLrWPugEBEK3UY2ZEsg3UU495nc5E+M+I= golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= golang.org/x/crypto v0.54.0 h1:YLIA59K4fiNzHzjnZt2tUJQjQtUWfWbeHBqKtk3eScw= golang.org/x/crypto v0.54.0/go.mod h1:KWL8ny2AZdGR2cWmzeHrp2azQPGogOv+HeQaVEXC2dk= +golang.org/x/exp v0.0.0-20241204233417-43b7b7cde48d h1:0olWaB5pg3+oychR51GUVCEsGkeCU/2JxjBgIo4f3M0= +golang.org/x/exp v0.0.0-20241204233417-43b7b7cde48d/go.mod h1:qj5a5QZpwLU2NLQudwIN5koi3beDhSAlJwa67PuM98c= golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4= golang.org/x/mod v0.37.0 h1:vF1DjpVEshcIqoEaauuHebaLk1O1forxjxBaVn884JQ= golang.org/x/mod v0.37.0/go.mod h1:m8S8VeM9r4dzDwjrKO0a1sZP3YjeMamRRlD+fmR2Q/0= +golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= golang.org/x/net v0.0.0-20210421230115-4e50805a0758/go.mod h1:72T/g9IO56b78aLF+1Kcs5dz7/ng1VjMUvfKvpfy+jM= @@ -199,6 +223,7 @@ golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJ golang.org/x/sync v0.22.0 h1:SZjpbeLmrCk4xhRSZFNZW5gFUeCeFgjekvI/+gfScek= golang.org/x/sync v0.22.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0= golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20191026070338-33540a1f6037/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210420072515-93ed5bcd2bfe/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= @@ -209,6 +234,7 @@ golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.47.0 h1:o7XGOvZQCADBQQ4Y7VNq2dRWQR7JmOUW8Kxx4ZsNgWs= golang.org/x/sys v0.47.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw= +golang.org/x/term v0.0.0-20201117132131-f5c789dd3221/go.mod h1:Nr5EML6q2oocZ2LXRh80K7BxOlk5/8JxuGnuhpl+muw= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k= @@ -219,6 +245,8 @@ golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= golang.org/x/text v0.40.0 h1:Ub2Z6/xjgF1WrYQz2nuITOEegKFtiIy+rieRJ5lHZKs= golang.org/x/text v0.40.0/go.mod h1:hpnzDAfGV753zIKo+wk3u1bVKCGPbrnF7+7LBF/UHVY= +golang.org/x/time v0.9.0 h1:EsRrnYcQiGH+5FfbgvV4AP7qEZstoyrHB0DzarOQ4ZY= +golang.org/x/time v0.9.0/go.mod h1:3BpzKBy/shNhVucY/MWOyx10tF3SFh9QdLuxbVysPQM= golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc= @@ -245,6 +273,8 @@ gorm.io/driver/sqlite v1.6.0 h1:WHRRrIiulaPiPFmDcod6prc4l2VGVWHz80KspNsxSfQ= gorm.io/driver/sqlite v1.6.0/go.mod h1:AO9V1qIQddBESngQUKWL9yoH93HIeA1X6V633rBwyT8= gorm.io/gorm v1.31.2 h1:3o8FXNo9v9S858gil+3LlZA1LkCOzgb4g5BL64FgaCo= gorm.io/gorm v1.31.2/go.mod h1:XyQVbO2k6YkOis7C2437jSit3SsDK72s7n7rsSHd+Gs= +gvisor.dev/gvisor v0.0.0-20241220022509-4690b2e35d70 h1:YAGAbMnGNRna7ajnsDuRjV1o/Mc2LDwEliRemNFDVF4= +gvisor.dev/gvisor v0.0.0-20241220022509-4690b2e35d70/go.mod h1:5DMfjtclAbTIjbXqO1qCe2K5GKKxWz2JHvCChuTcJEM= modernc.org/libc v1.22.5 h1:91BNch/e5B0uPbJFgqbxXuOnxBQjlS//icfQEGmvyjE= modernc.org/libc v1.22.5/go.mod h1:jj+Z7dTNX8fBScMVNRAYZ/jF91K8fdT2hYMThc3YjBY= modernc.org/mathutil v1.5.0 h1:rV0Ko/6SfM+8G+yKiyI830l3Wuz1zRutdslNoQ0kfiQ= diff --git a/backend/internal/application/egress/service.go b/backend/internal/application/egress/service.go index c76e7010..7bdefb59 100644 --- a/backend/internal/application/egress/service.go +++ b/backend/internal/application/egress/service.go @@ -12,6 +12,7 @@ import ( accountdomain "github.com/chenyme/grok2api/backend/internal/domain/account" domain "github.com/chenyme/grok2api/backend/internal/domain/egress" "github.com/chenyme/grok2api/backend/internal/infra/security" + "github.com/chenyme/grok2api/backend/internal/pkg/tunnelproxy" "github.com/chenyme/grok2api/backend/internal/repository" ) @@ -851,24 +852,30 @@ func NormalizeProxyURL(value string) (string, error) { } parseValue := strings.ReplaceAll(value, ProxyAccountPlaceholder, proxyAccountSentinel) parsed, err := url.Parse(parseValue) - if err != nil || parsed.Host == "" || parsed.Hostname() == "" { + if err != nil { return "", errors.New("代理地址格式无效") } - switch strings.ToLower(parsed.Scheme) { - case "http", "https", "socks4", "socks4a", "socks5", "socks5h", - "trojan", "vless", "ss", "vmess", "hysteria", "hysteria2", "tuic", "tuicv5": - default: - return "", errors.New("代理地址协议需为 HTTP、HTTPS、SOCKS4、SOCKS5,或 Trojan、VLESS、SS、VMess、Hysteria 等主流隧道协议。") - } - tunnelSchemes := map[string]bool{ - "trojan": true, "vless": true, "ss": true, "vmess": true, - "hysteria": true, "hysteria2": true, "tuic": true, "tuicv5": true, - } scheme := strings.ToLower(parsed.Scheme) - if !tunnelSchemes[scheme] { - if parsed.RawQuery != "" || parsed.Fragment != "" || (parsed.Path != "" && parsed.Path != "/") { - return "", errors.New("代理地址不能包含路径、查询参数或片段") + if tunnelproxy.IsSupportedScheme(scheme) { + if hasAccountPlaceholder { + return "", errors.New("隧道代理不支持 {account} 占位符") } + normalized, normalizeErr := tunnelproxy.Normalize(value) + if normalizeErr != nil { + return "", normalizeErr + } + return normalized, nil + } + if parsed.Host == "" || parsed.Hostname() == "" { + return "", errors.New("代理地址格式无效") + } + switch scheme { + case "http", "https", "socks4", "socks4a", "socks5", "socks5h": + default: + return "", errors.New("代理地址协议必须是 HTTP、HTTPS、SOCKS4、SOCKS5、Trojan、VLESS、SS 或 VMess") + } + if parsed.RawQuery != "" || parsed.Fragment != "" || (parsed.Path != "" && parsed.Path != "/") { + return "", errors.New("代理地址不能包含路径、查询参数或片段") } if hasAccountPlaceholder { if parsed.User == nil || !strings.Contains(parsed.User.Username(), proxyAccountSentinel) { diff --git a/backend/internal/application/egress/service_test.go b/backend/internal/application/egress/service_test.go index 4dad16ec..02507e41 100644 --- a/backend/internal/application/egress/service_test.go +++ b/backend/internal/application/egress/service_test.go @@ -1,6 +1,7 @@ package egress import ( + "encoding/base64" "errors" "strings" "testing" @@ -21,29 +22,48 @@ func TestSanitizeCloudflareCookiesDropsControlsAndNonCloudflareValues(t *testing } func TestNormalizeProxyURLValidatesStructure(t *testing.T) { + vmess := "vmess://" + base64.RawStdEncoding.EncodeToString([]byte(`{"v":"2","ps":"node","add":"proxy.example","port":"443","id":"123e4567-e89b-12d3-a456-426614174000","aid":"0","scy":"auto","net":"ws","tls":"tls","sni":"edge.example","host":"edge.example","path":"/ws"}`)) for _, raw := range []string{ "http://user:password@127.0.0.1:8080", "https://proxy.example:8443", "socks4://127.0.0.1:1080", "socks4a://proxy.example:1080", "socks5://user:password@127.0.0.1:1080", "socks5h://user:password@proxy.example:1080", - "trojan://password@127.0.0.1:8443?allowInsecure=0#remark", - "vless://uuid@127.0.0.1:443?encryption=none&flow=xtls-rprx-vision#remark", - "ss://base64#remark", - "vmess://base64#remark", - "hysteria://127.0.0.1:443", - "tuic://user:pass@127.0.0.1:443", + "trojan://password@proxy.example:443?security=tls&sni=edge.example#remark", + "vless://123e4567-e89b-12d3-a456-426614174000@proxy.example:443?encryption=none&security=tls&sni=edge.example#remark", + "ss://YWVzLTEyOC1nY206c2VjcmV0@proxy.example:8388#remark", + vmess, } { value, err := NormalizeProxyURL(raw) if err != nil || value == "" { t.Fatalf("valid proxy %q = %q, err = %v", raw, value, err) } } - for _, invalid := range []string{"file:///tmp/proxy", "https://", "http://proxy.example/path", "http://proxy.example\r\nX-Leak: yes"} { + for _, invalid := range []string{ + "file:///tmp/proxy", "https://", "http://proxy.example/path", "http://proxy.example\r\nX-Leak: yes", + "vless://uuid@127.0.0.1:443?encryption=none&flow=xtls-rprx-vision#remark", + "ss://base64#remark", "vmess://base64#remark", "hysteria://127.0.0.1:443", + "hysteria2://127.0.0.1:443", "tuic://user:pass@127.0.0.1:443", "tuicv5://user:pass@127.0.0.1:443", + } { if _, err := NormalizeProxyURL(invalid); err == nil { t.Fatalf("invalid proxy accepted: %q", invalid) } } } +func TestNormalizeProxyURLStripsTunnelRemarks(t *testing.T) { + base := "trojan://password@proxy.example:443?security=tls&sni=edge.example" + one, err := NormalizeProxyURL(base + "#one") + if err != nil { + t.Fatal(err) + } + two, err := NormalizeProxyURL(base + "#two") + if err != nil { + t.Fatal(err) + } + if one != two || strings.Contains(one, "#") { + t.Fatalf("normalized tunnel identities = %q and %q", one, two) + } +} + func TestNormalizeProxyURLAllowsAccountPlaceholderOnlyInUsername(t *testing.T) { value, err := NormalizeProxyURL("socks5h://Default.{account}:token@resin:2260") if err != nil { diff --git a/backend/internal/application/egress/subscription.go b/backend/internal/application/egress/subscription.go index bb882462..ec20f7a3 100644 --- a/backend/internal/application/egress/subscription.go +++ b/backend/internal/application/egress/subscription.go @@ -17,6 +17,7 @@ import ( "unicode/utf8" _ "github.com/bdandy/go-socks4" + "github.com/chenyme/grok2api/backend/internal/pkg/tunnelproxy" xproxy "golang.org/x/net/proxy" ) @@ -163,8 +164,14 @@ func subscriptionTransport(viaProxy string) (*http.Transport, error) { return nil, fmt.Errorf("创建订阅拉取 SOCKS 代理: %w", err) } transport.DialContext = subscriptionProxyDialContext(dialer) + case "trojan", "vless", "ss", "vmess": + dialer, err := tunnelproxy.NewDialer(viaProxy) + if err != nil { + return nil, fmt.Errorf("创建订阅拉取隧道代理: %w", err) + } + transport.DialContext = dialer.DialContext default: - return nil, errors.New("订阅拉取代理协议必须是 HTTP、HTTPS、SOCKS4 或 SOCKS5") + return nil, errors.New("订阅拉取代理协议不受支持") } return transport, nil } diff --git a/backend/internal/application/egress/subscription_test.go b/backend/internal/application/egress/subscription_test.go index 4ee997c5..51c0c6c2 100644 --- a/backend/internal/application/egress/subscription_test.go +++ b/backend/internal/application/egress/subscription_test.go @@ -46,6 +46,30 @@ func TestParseProxySubscriptionRejectsNoUsableEntries(t *testing.T) { } } +func TestParseProxySubscriptionImportsSupportedTunnelSchemes(t *testing.T) { + vmess := "vmess://" + base64.RawStdEncoding.EncodeToString([]byte(`{"v":"2","ps":"node","add":"proxy.example","port":"443","id":"123e4567-e89b-12d3-a456-426614174000","aid":"0","scy":"auto","net":"tcp"}`)) + entries, skipped, err := parseProxySubscription(strings.Join([]string{ + "http://proxy.example:8080", + "trojan://password@proxy.example:443#remark", + "vless://123e4567-e89b-12d3-a456-426614174000@proxy.example:443?encryption=none#remark", + "ss://YWVzLTEyOC1nY206c2VjcmV0@proxy.example:8388#remark", + vmess, + "hysteria2://proxy.example:443", + "tuic://user:pass@proxy.example:443", + }, "\n")) + if err != nil { + t.Fatal(err) + } + if len(entries) != 5 || skipped != 2 || entries[0].ProxyURL != "http://proxy.example:8080" { + t.Fatalf("entries=%#v skipped=%d", entries, skipped) + } + for _, entry := range entries[1:] { + if strings.Contains(entry.ProxyURL, "#") { + t.Fatalf("subscription remark was retained: %q", entry.ProxyURL) + } + } +} + func TestIsPublicAddressRejectsNonPublicRanges(t *testing.T) { for _, raw := range []string{ "0.0.0.1", "10.0.0.1", "100.64.0.1", "127.0.0.1", "169.254.10.1", diff --git a/backend/internal/infra/egress/buildclient.go b/backend/internal/infra/egress/buildclient.go index 196639ca..d01a5b1d 100644 --- a/backend/internal/infra/egress/buildclient.go +++ b/backend/internal/infra/egress/buildclient.go @@ -10,6 +10,7 @@ import ( "time" _ "github.com/bdandy/go-socks4" + "github.com/chenyme/grok2api/backend/internal/pkg/tunnelproxy" xproxy "golang.org/x/net/proxy" ) @@ -58,6 +59,12 @@ func newBuildClientWithOptions(proxyURL string, responseHeaderTimeout time.Durat return nil, fmt.Errorf("创建 Grok Build SOCKS 代理: %w", err) } transport.DialContext = dialContext(dialer) + case "trojan", "vless", "ss", "vmess": + dialer, err := tunnelproxy.NewDialer(proxyURL) + if err != nil { + return nil, fmt.Errorf("创建 Grok Build 隧道代理: %w", err) + } + transport.DialContext = dialer.DialContext default: return nil, fmt.Errorf("Grok Build 不支持代理协议 %q", parsed.Scheme) } diff --git a/backend/internal/infra/egress/buildclient_test.go b/backend/internal/infra/egress/buildclient_test.go index 1afe1b70..a0ceaec6 100644 --- a/backend/internal/infra/egress/buildclient_test.go +++ b/backend/internal/infra/egress/buildclient_test.go @@ -1,6 +1,7 @@ package egress import ( + "encoding/base64" "encoding/binary" "fmt" "io" @@ -11,6 +12,7 @@ import ( "testing" "time" + application "github.com/chenyme/grok2api/backend/internal/application/egress" neterrorpkg "github.com/chenyme/grok2api/backend/internal/pkg/neterror" ) @@ -123,6 +125,39 @@ func TestNewBuildClientRejectsUnsupportedProxyScheme(t *testing.T) { } } +func TestValidatedProxySchemesCreateBuildAndBrowserClients(t *testing.T) { + vmess := "vmess://" + base64.RawStdEncoding.EncodeToString([]byte(`{"v":"2","add":"proxy.example","port":"443","id":"123e4567-e89b-12d3-a456-426614174000","aid":"0","scy":"auto","net":"tcp"}`)) + for _, raw := range []string{ + "http://user:password@127.0.0.1:8080", + "https://proxy.example:8443", + "socks4://127.0.0.1:1080", + "socks4a://proxy.example:1080", + "socks5://user:password@127.0.0.1:1080", + "socks5h://user:password@proxy.example:1080", + "trojan://password@proxy.example:443?security=tls&sni=edge.example", + "vless://123e4567-e89b-12d3-a456-426614174000@proxy.example:443?encryption=none&security=tls&sni=edge.example", + "ss://YWVzLTEyOC1nY206c2VjcmV0@proxy.example:8388", + vmess, + } { + t.Run(raw, func(t *testing.T) { + normalized, err := application.NormalizeProxyURL(raw) + if err != nil { + t.Fatal(err) + } + build, err := newBuildClient(normalized, 5*time.Minute) + if err != nil { + t.Fatalf("build client: %v", err) + } + build.CloseIdleConnections() + browser, err := newBrowserClient(normalized, DefaultUserAgent) + if err != nil { + t.Fatalf("browser client: %v", err) + } + browser.CloseIdleConnections() + }) + } +} + func TestBuildClientRoutesThroughSOCKS5HWithRemoteDNS(t *testing.T) { target := httptest.NewServer(http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) { if request.Header.Get("User-Agent") != "grok-shell/0.2.102 (linux; x86_64)" { diff --git a/backend/internal/infra/egress/flaresolverr.go b/backend/internal/infra/egress/flaresolverr.go index a76ec42b..9e94426e 100644 --- a/backend/internal/infra/egress/flaresolverr.go +++ b/backend/internal/infra/egress/flaresolverr.go @@ -14,12 +14,14 @@ import ( "time" application "github.com/chenyme/grok2api/backend/internal/application/egress" + "github.com/chenyme/grok2api/backend/internal/pkg/tunnelproxy" ) const maxFlareSolverrResponseBytes = 2 << 20 var ( proxyCredentialPattern = regexp.MustCompile(`(?i)\b(https?|socks4a?|socks5h?)://[^\s/@:]+:[^\s/@]+@`) + tunnelCredentialPattern = regexp.MustCompile(`(?i)\b(?:trojan|vless)://[^\s/@]+@|\b(?:ss|vmess)://[^\s,;]+`) bearerCredentialPattern = regexp.MustCompile(`(?i)\bbearer\s+[a-z0-9._~+/=-]+`) namedCredentialPattern = regexp.MustCompile(`(?i)\b(token|password|passwd|authorization|cookie)\s*[:=]\s*[^\s,;]+`) ) @@ -44,6 +46,9 @@ type clearanceSolver interface { type flaresolverrSolver struct{} func (flaresolverrSolver) Solve(ctx context.Context, cfg ClearanceConfig, proxyURL string) (clearanceSolution, error) { + if parsedProxy, parseErr := url.Parse(proxyURL); parseErr == nil && tunnelproxy.IsSupportedScheme(parsedProxy.Scheme) { + return clearanceSolution{}, errors.New("FlareSolverr 暂不支持 Trojan、VLESS、SS 或 VMess 隧道代理") + } endpoint, err := flaresolverrEndpoint(cfg.FlareSolverrURL) if err != nil { return clearanceSolution{}, err @@ -139,6 +144,7 @@ func sanitizeFlareSolverrMessage(value string) string { } return candidate[:separator+3] + "***:***@" }) + value = tunnelCredentialPattern.ReplaceAllString(value, "[redacted tunnel proxy]") value = bearerCredentialPattern.ReplaceAllString(value, "Bearer [redacted]") value = namedCredentialPattern.ReplaceAllString(value, "$1=[redacted]") characters := []rune(value) diff --git a/backend/internal/infra/egress/flaresolverr_test.go b/backend/internal/infra/egress/flaresolverr_test.go index e067e943..e41062d8 100644 --- a/backend/internal/infra/egress/flaresolverr_test.go +++ b/backend/internal/infra/egress/flaresolverr_test.go @@ -60,6 +60,13 @@ func TestFlareSolverrSolveAcceptsNoChallengeWithoutCloudflareCookies(t *testing. } } +func TestFlareSolverrSolveRejectsTunnelProxy(t *testing.T) { + _, err := (flaresolverrSolver{}).Solve(context.Background(), ClearanceConfig{}, "trojan://secret@proxy.example:443") + if err == nil || !strings.Contains(err.Error(), "FlareSolverr") { + t.Fatalf("tunnel proxy error = %v", err) + } +} + func TestFlareSolverrEndpointAcceptsBaseAndV1Path(t *testing.T) { for input, expected := range map[string]string{ "http://flaresolverr:8191": "http://flaresolverr:8191/v1", @@ -74,8 +81,8 @@ func TestFlareSolverrEndpointAcceptsBaseAndV1Path(t *testing.T) { } func TestSanitizeFlareSolverrMessageRedactsCredentials(t *testing.T) { - message := sanitizeFlareSolverrMessage("proxy socks5h://user:secret@resin:2260 failed; token=abc123 Authorization: Bearer.SECRET cookie=sso-value") - for _, secret := range []string{"user", "secret", "abc123", "Bearer.SECRET", "sso-value"} { + message := sanitizeFlareSolverrMessage("proxy socks5h://user:secret@resin:2260 and trojan://tunnel-secret@proxy.example:443 and vmess://base64-secret failed; token=abc123 Authorization: Bearer.SECRET cookie=sso-value") + for _, secret := range []string{"user", "secret", "tunnel-secret", "base64-secret", "abc123", "Bearer.SECRET", "sso-value"} { if strings.Contains(message, secret) { t.Fatalf("sanitized message leaked %q: %q", secret, message) } diff --git a/backend/internal/infra/egress/pinnedclient.go b/backend/internal/infra/egress/pinnedclient.go index 11fa8328..996cc518 100644 --- a/backend/internal/infra/egress/pinnedclient.go +++ b/backend/internal/infra/egress/pinnedclient.go @@ -11,6 +11,7 @@ import ( "strings" "time" + "github.com/chenyme/grok2api/backend/internal/pkg/tunnelproxy" xproxy "golang.org/x/net/proxy" ) @@ -81,6 +82,12 @@ func newPinnedHTTPSClient(proxyURL, serverName string, tlsConfig *tls.Config) (* return nil, fmt.Errorf("创建固定地址 SOCKS 代理: %w", err) } transport.DialContext = dialContext(dialer) + case "trojan", "vless", "ss", "vmess": + dialer, err := tunnelproxy.NewDialer(proxyURL) + if err != nil { + return nil, fmt.Errorf("创建固定地址隧道代理: %w", err) + } + transport.DialContext = dialer.DialContext default: return nil, fmt.Errorf("固定地址请求不支持代理协议 %q", parsed.Scheme) } diff --git a/backend/internal/infra/egress/tlsclient.go b/backend/internal/infra/egress/tlsclient.go index 4b9d2b2a..52b4d425 100644 --- a/backend/internal/infra/egress/tlsclient.go +++ b/backend/internal/infra/egress/tlsclient.go @@ -6,6 +6,7 @@ import ( "fmt" "io" "net/http" + "net/url" "regexp" "strconv" "strings" @@ -15,6 +16,7 @@ import ( tlsclient "github.com/bogdanfinn/tls-client" "github.com/bogdanfinn/tls-client/profiles" "github.com/bogdanfinn/websocket" + "github.com/chenyme/grok2api/backend/internal/pkg/tunnelproxy" ) type browserClient struct{ inner tlsclient.HttpClient } @@ -62,7 +64,19 @@ func newBrowserClient(proxyURL, userAgent string) (*browserClient, error) { tlsclient.WithNotFollowRedirects(), } if proxyURL != "" { - options = append(options, tlsclient.WithProxyUrl(proxyURL)) + parsed, err := url.Parse(proxyURL) + if err != nil { + return nil, fmt.Errorf("解析浏览器出口代理: %w", err) + } + if tunnelproxy.IsSupportedScheme(parsed.Scheme) { + dialer, err := tunnelproxy.NewDialer(proxyURL) + if err != nil { + return nil, fmt.Errorf("创建浏览器隧道代理: %w", err) + } + options = append(options, tlsclient.WithDialContext(dialer.DialContext)) + } else { + options = append(options, tlsclient.WithProxyUrl(proxyURL)) + } } client, err := tlsclient.NewHttpClient(tlsclient.NewNoopLogger(), options...) if err != nil { diff --git a/backend/internal/pkg/tunnelproxy/tunnelproxy.go b/backend/internal/pkg/tunnelproxy/tunnelproxy.go new file mode 100644 index 00000000..4b35809c --- /dev/null +++ b/backend/internal/pkg/tunnelproxy/tunnelproxy.go @@ -0,0 +1,651 @@ +package tunnelproxy + +import ( + "context" + "crypto/tls" + "encoding/base64" + "encoding/json" + "errors" + "fmt" + "net" + "net/http" + "net/url" + "strconv" + "strings" + "time" + + "github.com/Asutorufa/yuhaiin/pkg/net/netapi" + "github.com/Asutorufa/yuhaiin/pkg/net/proxy/trojan" + "github.com/Asutorufa/yuhaiin/pkg/net/proxy/vless" + "github.com/Asutorufa/yuhaiin/pkg/net/proxy/vmess" + "github.com/Asutorufa/yuhaiin/pkg/protos/node/protocol" + "github.com/coder/websocket" + "github.com/google/uuid" + sscore "github.com/shadowsocks/go-shadowsocks2/core" + "github.com/shadowsocks/go-shadowsocks2/socks" +) + +type Config struct { + Scheme string + Server string + Credential string + Method string + AlterID int + Cipher string + Transport string + TLS bool + ServerName string + Insecure bool + ALPN []string + WebSocketHost string + WebSocketPath string + CanonicalProxyURL string +} + +func IsSupportedScheme(scheme string) bool { + switch strings.ToLower(strings.TrimSpace(scheme)) { + case "trojan", "vless", "ss", "vmess": + return true + default: + return false + } +} + +func Normalize(value string) (string, error) { + config, err := Parse(value) + if err != nil { + return "", err + } + return config.CanonicalProxyURL, nil +} + +func Parse(value string) (Config, error) { + value = strings.TrimSpace(value) + if strings.IndexFunc(value, func(character rune) bool { return character < 0x20 || character == 0x7f }) >= 0 { + return Config{}, errors.New("隧道代理地址包含控制字符") + } + scheme, _, ok := strings.Cut(value, "://") + if !ok || !IsSupportedScheme(scheme) { + return Config{}, errors.New("不支持的隧道代理协议") + } + switch strings.ToLower(scheme) { + case "ss": + return parseShadowsocks(value) + case "vmess": + return parseVMess(value) + default: + return parseUserInfoProxy(value) + } +} + +func parseUserInfoProxy(value string) (Config, error) { + parsed, err := url.Parse(value) + if err != nil || parsed.Hostname() == "" || parsed.User == nil { + return Config{}, errors.New("隧道代理地址格式无效") + } + scheme := strings.ToLower(parsed.Scheme) + credential := parsed.User.Username() + if credential == "" { + return Config{}, errors.New("隧道代理凭据不能为空") + } + if _, hasPassword := parsed.User.Password(); hasPassword { + return Config{}, errors.New("隧道代理凭据格式无效") + } + if parsed.Path != "" && parsed.Path != "/" { + return Config{}, errors.New("隧道代理地址路径无效") + } + server, err := canonicalServer(parsed.Hostname(), parsed.Port()) + if err != nil { + return Config{}, err + } + query := parsed.Query() + transport := strings.ToLower(firstNonEmpty(query.Get("type"), query.Get("network"))) + if transport == "" || transport == "none" { + transport = "tcp" + } + if transport == "websocket" { + transport = "ws" + } + if transport != "tcp" && transport != "ws" { + return Config{}, fmt.Errorf("暂不支持 %s 传输", transport) + } + if flow := strings.TrimSpace(query.Get("flow")); flow != "" { + return Config{}, fmt.Errorf("暂不支持 VLESS flow %q", flow) + } + if scheme == "vless" { + if _, err := uuid.Parse(credential); err != nil { + return Config{}, errors.New("VLESS UUID 无效") + } + if encryption := strings.ToLower(strings.TrimSpace(query.Get("encryption"))); encryption != "" && encryption != "none" { + return Config{}, errors.New("VLESS encryption 必须为 none") + } + } + security := strings.ToLower(strings.TrimSpace(query.Get("security"))) + tlsEnabled := scheme == "trojan" + switch security { + case "", "tls": + if security == "tls" { + tlsEnabled = true + } + case "none": + tlsEnabled = false + default: + return Config{}, fmt.Errorf("暂不支持 %s security %q", strings.ToUpper(scheme), security) + } + if headerType := strings.ToLower(strings.TrimSpace(query.Get("headerType"))); headerType != "" && headerType != "none" { + return Config{}, fmt.Errorf("暂不支持 %s headerType %q", strings.ToUpper(scheme), headerType) + } + insecure, err := queryBool(query, "allowInsecure", "insecure", "skip-cert-verify") + if err != nil { + return Config{}, err + } + serverName := firstNonEmpty(query.Get("sni"), query.Get("peer"), parsed.Hostname()) + wsHost := firstNonEmpty(query.Get("host"), serverName) + if err := validateWebSocketHost(wsHost); transport == "ws" && err != nil { + return Config{}, err + } + wsPath := query.Get("path") + if wsPath == "" { + wsPath = "/" + } else if !strings.HasPrefix(wsPath, "/") { + wsPath = "/" + wsPath + } + if transport == "tcp" && (query.Get("path") != "" || query.Get("host") != "") { + return Config{}, errors.New("TCP 隧道不能包含 WebSocket host/path") + } + parsed.Scheme = scheme + parsed.Host = server + parsed.User = url.User(credential) + parsed.Path = "" + parsed.RawPath = "" + parsed.Fragment = "" + parsed.RawFragment = "" + parsed.RawQuery = query.Encode() + config := Config{ + Scheme: scheme, Server: server, Credential: credential, Transport: transport, + TLS: tlsEnabled, ServerName: serverName, Insecure: insecure, + ALPN: splitList(query.Get("alpn")), WebSocketHost: wsHost, WebSocketPath: wsPath, + CanonicalProxyURL: parsed.String(), + } + if err := validateConfig(config); err != nil { + return Config{}, fmt.Errorf("创建 %s 隧道配置: %w", strings.ToUpper(scheme), err) + } + return config, nil +} + +func parseShadowsocks(value string) (Config, error) { + payload := value[len("ss://"):] + if before, _, found := strings.Cut(payload, "#"); found { + payload = before + } + if before, rawQuery, found := strings.Cut(payload, "?"); found { + query, err := url.ParseQuery(rawQuery) + if err != nil { + return Config{}, errors.New("Shadowsocks 查询参数无效") + } + if plugin := strings.TrimSpace(query.Get("plugin")); plugin != "" { + return Config{}, errors.New("暂不支持 Shadowsocks plugin") + } + if len(query) != 0 { + return Config{}, errors.New("Shadowsocks 查询参数无效") + } + payload = before + } + var userPart, serverPart string + if separator := strings.LastIndex(payload, "@"); separator >= 0 { + userPart, serverPart = payload[:separator], payload[separator+1:] + decoded, err := url.PathUnescape(userPart) + if err != nil { + return Config{}, errors.New("Shadowsocks 凭据无效") + } + if !strings.Contains(decoded, ":") { + decoded, err = decodeBase64String(decoded) + if err != nil { + return Config{}, errors.New("Shadowsocks 凭据不是有效的 Base64") + } + } + userPart = decoded + } else { + decoded, err := decodeBase64String(payload) + if err != nil { + return Config{}, errors.New("旧式 Shadowsocks 地址不是有效的 Base64") + } + separator := strings.LastIndex(decoded, "@") + if separator < 0 { + return Config{}, errors.New("旧式 Shadowsocks 地址格式无效") + } + userPart, serverPart = decoded[:separator], decoded[separator+1:] + } + method, password, ok := strings.Cut(userPart, ":") + if !ok || strings.TrimSpace(method) == "" || password == "" { + return Config{}, errors.New("Shadowsocks method/password 不能为空") + } + method = strings.ToLower(strings.TrimSpace(method)) + switch method { + case "aes-128-gcm", "aes-256-gcm", "chacha20-ietf-poly1305": + default: + return Config{}, fmt.Errorf("暂不支持 Shadowsocks method %q", method) + } + serverURL, err := url.Parse("ss://" + serverPart) + if err != nil || serverURL.User != nil || (serverURL.Path != "" && serverURL.Path != "/") || serverURL.RawQuery != "" || serverURL.Fragment != "" { + return Config{}, errors.New("Shadowsocks 服务器地址无效") + } + server, err := canonicalServer(serverURL.Hostname(), serverURL.Port()) + if err != nil { + return Config{}, err + } + credential := method + ":" + password + config := Config{ + Scheme: "ss", Server: server, Credential: password, Method: method, Transport: "tcp", + CanonicalProxyURL: "ss://" + base64.RawURLEncoding.EncodeToString([]byte(credential)) + "@" + server, + } + if err := validateConfig(config); err != nil { + return Config{}, fmt.Errorf("创建 Shadowsocks 隧道配置: %w", err) + } + return config, nil +} + +type vmessShare struct { + Version string `json:"v,omitempty"` + Address string `json:"add"` + Port string `json:"port"` + UUID string `json:"id"` + AlterID string `json:"aid"` + Cipher string `json:"scy,omitempty"` + Network string `json:"net"` + TLS string `json:"tls,omitempty"` + ServerName string `json:"sni,omitempty"` + Host string `json:"host,omitempty"` + Path string `json:"path,omitempty"` + AllowInsecure bool `json:"allowInsecure,omitempty"` +} + +func parseVMess(value string) (Config, error) { + payload := value[len("vmess://"):] + if before, _, found := strings.Cut(payload, "#"); found { + payload = before + } + decoded, err := decodeBase64Bytes(payload) + if err != nil { + return Config{}, errors.New("VMess 配置不是有效的 Base64") + } + var raw map[string]any + if err := json.Unmarshal(decoded, &raw); err != nil { + return Config{}, errors.New("VMess 配置不是有效的 JSON") + } + address := jsonString(raw, "add") + port := jsonString(raw, "port") + server, err := canonicalServer(address, port) + if err != nil { + return Config{}, fmt.Errorf("VMess %w", err) + } + userID := jsonString(raw, "id") + if _, err := uuid.Parse(userID); err != nil { + return Config{}, errors.New("VMess UUID 无效") + } + alterID, err := strconv.Atoi(firstNonEmpty(jsonString(raw, "aid"), "0")) + if err != nil || alterID < 0 || alterID > 65535 { + return Config{}, errors.New("VMess alterId 无效") + } + cipher := strings.ToLower(firstNonEmpty(jsonString(raw, "scy"), jsonString(raw, "security"), "auto")) + switch cipher { + case "auto", "aes-128-gcm", "chacha20-poly1305", "none": + default: + return Config{}, fmt.Errorf("暂不支持 VMess cipher %q", cipher) + } + transport := strings.ToLower(firstNonEmpty(jsonString(raw, "net"), "tcp")) + if transport == "websocket" { + transport = "ws" + } + if transport != "tcp" && transport != "ws" { + return Config{}, fmt.Errorf("暂不支持 VMess %s 传输", transport) + } + if headerType := strings.ToLower(jsonString(raw, "type")); headerType != "" && headerType != "none" { + return Config{}, fmt.Errorf("暂不支持 VMess header type %q", headerType) + } + tlsMode := strings.ToLower(jsonString(raw, "tls")) + if tlsMode != "" && tlsMode != "none" && tlsMode != "tls" { + return Config{}, fmt.Errorf("暂不支持 VMess TLS 模式 %q", tlsMode) + } + tlsEnabled := tlsMode == "tls" + serverName := firstNonEmpty(jsonString(raw, "sni"), address) + host := firstNonEmpty(jsonString(raw, "host"), serverName) + if err := validateWebSocketHost(host); transport == "ws" && err != nil { + return Config{}, err + } + path := jsonString(raw, "path") + if path == "" { + path = "/" + } + if transport == "tcp" && (jsonString(raw, "path") != "" || jsonString(raw, "host") != "") { + return Config{}, errors.New("VMess TCP 隧道不能包含 WebSocket host/path") + } + insecure, err := jsonBool(raw, "allowInsecure") + if err != nil { + return Config{}, err + } + share := vmessShare{ + Version: "2", Address: address, Port: port, UUID: userID, AlterID: strconv.Itoa(alterID), Cipher: cipher, + Network: transport, ServerName: serverName, AllowInsecure: insecure, + } + if transport == "ws" { + share.Host = host + share.Path = path + } + if tlsEnabled { + share.TLS = "tls" + } + canonicalJSON, err := json.Marshal(share) + if err != nil { + return Config{}, err + } + config := Config{ + Scheme: "vmess", Server: server, Credential: userID, AlterID: alterID, Cipher: cipher, + Transport: transport, TLS: tlsEnabled, ServerName: serverName, Insecure: insecure, + WebSocketHost: host, WebSocketPath: path, + CanonicalProxyURL: "vmess://" + base64.RawStdEncoding.EncodeToString(canonicalJSON), + } + if err := validateConfig(config); err != nil { + return Config{}, fmt.Errorf("创建 VMess 隧道配置: %w", err) + } + return config, nil +} + +type Dialer struct { + proxy netapi.Proxy + shadowsocksCipher sscore.StreamConnCipher + server string +} + +func NewDialer(value string) (*Dialer, error) { + config, err := Parse(value) + if err != nil { + return nil, err + } + if config.Scheme == "ss" { + cipher, err := sscore.PickCipher(config.Method, nil, config.Credential) + if err != nil { + return nil, err + } + return &Dialer{shadowsocksCipher: cipher, server: config.Server}, nil + } + proxy, err := buildProxy(config) + if err != nil { + return nil, err + } + return &Dialer{proxy: proxy}, nil +} + +func (d *Dialer) Dial(network, address string) (net.Conn, error) { + return d.DialContext(context.Background(), network, address) +} + +func (d *Dialer) DialContext(ctx context.Context, network, address string) (net.Conn, error) { + if d == nil || (d.proxy == nil && d.shadowsocksCipher == nil) { + return nil, errors.New("隧道代理拨号器未初始化") + } + if !strings.HasPrefix(network, "tcp") { + return nil, fmt.Errorf("隧道代理不支持网络 %q", network) + } + if d.shadowsocksCipher != nil { + return d.dialShadowsocks(ctx, address) + } + target, err := netapi.ParseAddress(network, address) + if err != nil { + return nil, err + } + return d.proxy.Conn(ctx, target) +} + +func (d *Dialer) dialShadowsocks(ctx context.Context, address string) (net.Conn, error) { + target := socks.ParseAddr(address) + if target == nil { + return nil, errors.New("Shadowsocks 目标地址无效") + } + connection, err := newServerNetDialer().DialContext(ctx, "tcp", d.server) + if err != nil { + return nil, err + } + connection = d.shadowsocksCipher.StreamConn(connection) + if _, err := connection.Write(target); err != nil { + _ = connection.Close() + return nil, fmt.Errorf("写入 Shadowsocks 目标地址: %w", err) + } + return connection, nil +} + +func validateConfig(config Config) error { + if config.Scheme == "ss" { + _, err := sscore.PickCipher(config.Method, nil, config.Credential) + return err + } + _, err := buildProxy(config) + return err +} + +func buildProxy(config Config) (netapi.Proxy, error) { + var current netapi.Proxy = &serverDialer{address: config.Server} + if config.Transport == "ws" { + current = &websocketProxy{config: config, dialer: current} + } else if config.TLS { + current = &tlsProxy{config: config, dialer: current} + } + switch config.Scheme { + case "trojan": + protocolConfig := &protocol.Trojan{} + protocolConfig.SetPassword(config.Credential) + return trojan.NewClient(protocolConfig, current) + case "vless": + protocolConfig := &protocol.Vless{} + protocolConfig.SetUuid(config.Credential) + return vless.NewClient(protocolConfig, current) + case "vmess": + protocolConfig := &protocol.Vmess{} + protocolConfig.SetUuid(config.Credential) + protocolConfig.SetAlterId(strconv.Itoa(config.AlterID)) + protocolConfig.SetSecurity(config.Cipher) + return vmess.NewClient(protocolConfig, current) + default: + return nil, errors.New("不支持的隧道代理协议") + } +} + +type tlsProxy struct { + netapi.EmptyDispatch + config Config + dialer netapi.Proxy +} + +func (p *tlsProxy) Conn(ctx context.Context, address netapi.Address) (net.Conn, error) { + connection, err := p.dialer.Conn(ctx, address) + if err != nil { + return nil, err + } + tlsConnection := tls.Client(connection, p.tlsConfig()) + if err := tlsConnection.HandshakeContext(ctx); err != nil { + _ = connection.Close() + return nil, fmt.Errorf("隧道 TLS 握手: %w", err) + } + return tlsConnection, nil +} + +func (p *tlsProxy) PacketConn(context.Context, netapi.Address) (net.PacketConn, error) { + return nil, errors.New("TLS 隧道不支持 UDP") +} + +func (p *tlsProxy) tlsConfig() *tls.Config { + return &tls.Config{ + MinVersion: tls.VersionTLS12, ServerName: p.config.ServerName, + InsecureSkipVerify: p.config.Insecure, NextProtos: append([]string(nil), p.config.ALPN...), + } +} + +type websocketProxy struct { + netapi.EmptyDispatch + config Config + dialer netapi.Proxy +} + +func (p *websocketProxy) Conn(ctx context.Context, address netapi.Address) (net.Conn, error) { + scheme := "ws" + if p.config.TLS { + scheme = "wss" + } + path, rawQuery, _ := strings.Cut(p.config.WebSocketPath, "?") + endpoint := (&url.URL{Scheme: scheme, Host: p.config.WebSocketHost, Path: path, RawQuery: rawQuery}).String() + transport := &http.Transport{ + Proxy: nil, + DialContext: func(dialCtx context.Context, _, _ string) (net.Conn, error) { + return p.dialer.Conn(dialCtx, address) + }, + ForceAttemptHTTP2: false, + TLSClientConfig: websocketTLSConfig(p.config), + } + connection, _, err := websocket.Dial(ctx, endpoint, &websocket.DialOptions{ + HTTPClient: &http.Client{Transport: transport}, + Host: p.config.WebSocketHost, + }) + if err != nil { + transport.CloseIdleConnections() + return nil, fmt.Errorf("隧道 WebSocket 握手: %w", err) + } + return websocket.NetConn(context.Background(), connection, websocket.MessageBinary), nil +} + +func (p *websocketProxy) PacketConn(context.Context, netapi.Address) (net.PacketConn, error) { + return nil, errors.New("WebSocket 隧道不支持 UDP") +} + +type serverDialer struct { + netapi.EmptyDispatch + address string +} + +func (d *serverDialer) Conn(ctx context.Context, _ netapi.Address) (net.Conn, error) { + return newServerNetDialer().DialContext(ctx, "tcp", d.address) +} + +func newServerNetDialer() *net.Dialer { + return &net.Dialer{Timeout: 10 * time.Second, KeepAlive: 30 * time.Second} +} + +func websocketTLSConfig(config Config) *tls.Config { + tlsConfig := (&tlsProxy{config: config}).tlsConfig() + tlsConfig.NextProtos = []string{"http/1.1"} + return tlsConfig +} + +func validateWebSocketHost(host string) error { + parsed, err := url.Parse("http://" + strings.TrimSpace(host)) + if err != nil || parsed.Hostname() == "" || parsed.User != nil || parsed.Path != "" || parsed.RawQuery != "" || parsed.Fragment != "" { + return errors.New("WebSocket host 无效") + } + if parsed.Port() != "" { + if _, err := canonicalServer(parsed.Hostname(), parsed.Port()); err != nil { + return errors.New("WebSocket host 无效") + } + } + return nil +} + +func (d *serverDialer) PacketConn(context.Context, netapi.Address) (net.PacketConn, error) { + return nil, errors.New("当前隧道代理不支持 UDP") +} + +func canonicalServer(host, port string) (string, error) { + host = strings.TrimSpace(strings.Trim(host, "[]")) + if host == "" { + return "", errors.New("隧道代理服务器不能为空") + } + parsedPort, err := strconv.ParseUint(strings.TrimSpace(port), 10, 16) + if err != nil || parsedPort == 0 { + return "", errors.New("隧道代理端口无效") + } + return net.JoinHostPort(host, strconv.FormatUint(parsedPort, 10)), nil +} + +func decodeBase64String(value string) (string, error) { + decoded, err := decodeBase64Bytes(value) + return string(decoded), err +} + +func decodeBase64Bytes(value string) ([]byte, error) { + value = strings.TrimSpace(value) + for _, encoding := range []*base64.Encoding{base64.RawStdEncoding, base64.StdEncoding, base64.RawURLEncoding, base64.URLEncoding} { + if decoded, err := encoding.DecodeString(value); err == nil { + return decoded, nil + } + } + return nil, errors.New("invalid base64") +} + +func firstNonEmpty(values ...string) string { + for _, value := range values { + if strings.TrimSpace(value) != "" { + return strings.TrimSpace(value) + } + } + return "" +} + +func splitList(value string) []string { + var result []string + for item := range strings.SplitSeq(value, ",") { + if item = strings.TrimSpace(item); item != "" { + result = append(result, item) + } + } + return result +} + +func queryBool(query url.Values, names ...string) (bool, error) { + for _, name := range names { + if raw, ok := query[name]; ok && len(raw) != 0 { + return parseBool(raw[0], name) + } + } + return false, nil +} + +func jsonBool(value map[string]any, name string) (bool, error) { + raw, ok := value[name] + if !ok || raw == nil { + return false, nil + } + switch typed := raw.(type) { + case bool: + return typed, nil + case string: + return parseBool(typed, name) + case float64: + return parseBool(strconv.FormatFloat(typed, 'f', -1, 64), name) + default: + return false, fmt.Errorf("%s 必须是布尔值", name) + } +} + +func parseBool(value, name string) (bool, error) { + switch strings.ToLower(strings.TrimSpace(value)) { + case "1", "true", "yes": + return true, nil + case "", "0", "false", "no": + return false, nil + default: + return false, fmt.Errorf("%s 必须是布尔值", name) + } +} + +func jsonString(value map[string]any, name string) string { + raw, ok := value[name] + if !ok || raw == nil { + return "" + } + switch typed := raw.(type) { + case string: + return strings.TrimSpace(typed) + case float64: + return strconv.FormatFloat(typed, 'f', -1, 64) + default: + return "" + } +} diff --git a/backend/internal/pkg/tunnelproxy/tunnelproxy_test.go b/backend/internal/pkg/tunnelproxy/tunnelproxy_test.go new file mode 100644 index 00000000..33ffc121 --- /dev/null +++ b/backend/internal/pkg/tunnelproxy/tunnelproxy_test.go @@ -0,0 +1,132 @@ +package tunnelproxy + +import ( + "context" + "encoding/base64" + "fmt" + "io" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" + + "github.com/Asutorufa/yuhaiin/pkg/net/netapi" + "github.com/coder/websocket" +) + +const testUUID = "123e4567-e89b-12d3-a456-426614174000" + +func TestNormalizeStripsRemarksAndBuildsDialers(t *testing.T) { + vmessJSON := fmt.Sprintf(`{"v":"2","ps":"node one","add":"proxy.example","port":"443","id":%q,"aid":"0","scy":"auto","net":"ws","tls":"tls","sni":"edge.example","host":"edge.example","path":"/ws"}`, testUUID) + vmessURL := "vmess://" + base64.RawStdEncoding.EncodeToString([]byte(vmessJSON)) + tests := []struct { + name string + raw string + }{ + {name: "trojan", raw: "trojan://secret@proxy.example:443?security=tls&sni=edge.example&type=ws&host=edge.example&path=%2Fws#one"}, + {name: "vless", raw: "vless://" + testUUID + "@proxy.example:443?encryption=none&security=tls&sni=edge.example&type=ws&host=edge.example&path=%2Fws#one"}, + {name: "shadowsocks", raw: "ss://" + base64.RawURLEncoding.EncodeToString([]byte("aes-128-gcm:secret")) + "@proxy.example:8388#one"}, + {name: "vmess", raw: vmessURL}, + } + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + normalized, err := Normalize(test.raw) + if err != nil { + t.Fatal(err) + } + if strings.Contains(normalized, "#") || strings.Contains(normalized, "node one") { + t.Fatalf("remark leaked into normalized URL: %q", normalized) + } + if _, err := NewDialer(normalized); err != nil { + t.Fatalf("construct dialer: %v", err) + } + }) + } +} + +func TestNormalizeRemarksDoNotChangeIdentity(t *testing.T) { + base := "trojan://secret@proxy.example:443?security=tls&sni=edge.example" + one, err := Normalize(base + "#one") + if err != nil { + t.Fatal(err) + } + two, err := Normalize(base + "#two") + if err != nil { + t.Fatal(err) + } + if one != two { + t.Fatalf("remark changed identity: %q != %q", one, two) + } +} + +func TestNormalizeSupportsLegacyShadowsocks(t *testing.T) { + raw := "ss://" + base64.RawStdEncoding.EncodeToString([]byte("chacha20-ietf-poly1305:secret@proxy.example:8388")) + "#legacy" + normalized, err := Normalize(raw) + if err != nil { + t.Fatal(err) + } + if !strings.HasPrefix(normalized, "ss://") || strings.Contains(normalized, "#") { + t.Fatalf("normalized legacy URL = %q", normalized) + } +} + +func TestParseRejectsUnsupportedOrMalformedLinks(t *testing.T) { + for _, raw := range []string{ + "hysteria2://secret@proxy.example:443", + "tuic://user:secret@proxy.example:443", + "vless://not-a-uuid@proxy.example:443?encryption=none", + "vless://" + testUUID + "@proxy.example:443?encryption=none&flow=xtls-rprx-vision", + "trojan://secret@proxy.example:443?type=grpc", + "trojan://secret@proxy.example:443/unexpected", + "ss://" + base64.RawURLEncoding.EncodeToString([]byte("rc4-md5:secret")) + "@proxy.example:8388", + "ss://" + base64.RawURLEncoding.EncodeToString([]byte("aes-128-gcm:secret")) + "@proxy.example:8388/unexpected", + "vmess://not-base64", + } { + if _, err := Normalize(raw); err == nil { + t.Fatalf("invalid tunnel accepted: %q", raw) + } + } +} + +func TestWebSocketTransportCarriesBinaryStream(t *testing.T) { + handlerResult := make(chan error, 1) + server := httptest.NewServer(http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) { + if request.Host != "edge.example" || request.URL.Path != "/ws" { + handlerResult <- fmt.Errorf("request host=%q path=%q", request.Host, request.URL.Path) + return + } + connection, err := websocket.Accept(writer, request, nil) + if err != nil { + handlerResult <- err + return + } + stream := websocket.NetConn(context.Background(), connection, websocket.MessageBinary) + defer stream.Close() + _, err = io.CopyN(stream, stream, 4) + handlerResult <- err + })) + defer server.Close() + serverAddress := strings.TrimPrefix(server.URL, "http://") + proxy := &websocketProxy{ + config: Config{Server: serverAddress, WebSocketHost: "edge.example", WebSocketPath: "/ws"}, + dialer: &serverDialer{address: serverAddress}, + } + ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) + defer cancel() + connection, err := proxy.Conn(ctx, netapi.ParseDomainPort("tcp", "target.example", 443)) + if err != nil { + t.Fatal(err) + } + defer connection.Close() + if _, err := connection.Write([]byte("pong")); err != nil { + t.Fatal(err) + } + response := make([]byte, 4) + if _, err := io.ReadFull(connection, response); err != nil || string(response) != "pong" { + t.Fatalf("response=%q err=%v", response, err) + } + if err := <-handlerResult; err != nil { + t.Fatal(err) + } +} diff --git a/frontend/src/features/settings/settings-model.ts b/frontend/src/features/settings/settings-model.ts index d31c1411..239c4e70 100644 --- a/frontend/src/features/settings/settings-model.ts +++ b/frontend/src/features/settings/settings-model.ts @@ -351,21 +351,35 @@ function validHTTPURL(value: string): boolean { } } -/** Validates HTTP and SOCKS proxy URLs. Empty is allowed for write-only form fields. */ +/** Performs fast client-side proxy validation; the backend remains authoritative. */ function validProxyURL(value: string): boolean { const trimmed = value.trim(); if (trimmed.length === 0) return true; - if (trimmed.length > 2048 || [...trimmed].some((char) => { + if (trimmed.length > 8192 || [...trimmed].some((char) => { const code = char.charCodeAt(0); return code <= 0x1f || code === 0x7f; })) return false; if ((trimmed.match(/\{account\}/g) ?? []).length > 1) return false; + const scheme = trimmed.slice(0, trimmed.indexOf(":")).toLowerCase(); + if (["trojan", "vless", "ss", "vmess"].includes(scheme) && trimmed.includes("{account}")) return false; + if (scheme === "vmess") return validVMessURL(trimmed); + if (scheme === "ss") return /^ss:\/\/[^\s#]+(?:#[^\r\n]*)?$/.test(trimmed); try { const parseValue = trimmed.replaceAll("{account}", "grok2api_account_placeholder"); const parsed = new URL(parseValue); if (!parsed.host || !parsed.hostname) return false; - const scheme = parsed.protocol.replace(/:$/, "").toLowerCase(); - if (!["http", "https", "socks4", "socks4a", "socks5", "socks5h"].includes(scheme)) return false; + const parsedScheme = parsed.protocol.replace(/:$/, "").toLowerCase(); + if (["trojan", "vless"].includes(parsedScheme)) { + if (!parsed.username || parsed.password) return false; + const transport = (parsed.searchParams.get("type") ?? parsed.searchParams.get("network") ?? "tcp").toLowerCase(); + if (!["tcp", "none", "ws", "websocket"].includes(transport)) return false; + const security = (parsed.searchParams.get("security") ?? "").toLowerCase(); + if (!["", "none", "tls"].includes(security)) return false; + if (parsed.searchParams.get("flow")) return false; + if (parsedScheme === "vless" && !/^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/i.test(parsed.username)) return false; + return parsed.pathname === "" || parsed.pathname === "/"; + } + if (!["http", "https", "socks4", "socks4a", "socks5", "socks5h"].includes(parsedScheme)) return false; if (parsed.search || parsed.hash || (parsed.pathname !== "" && parsed.pathname !== "/")) return false; if (trimmed.includes("{account}")) { if (!parsed.username.includes("grok2api_account_placeholder")) return false; @@ -376,7 +390,25 @@ function validProxyURL(value: string): boolean { } } -/** Subscription fetch proxies are global and must never use per-account lease placeholders. */ +function validVMessURL(value: string): boolean { + try { + let payload = value.slice("vmess://".length).split("#", 1)[0].replaceAll("-", "+").replaceAll("_", "/"); + payload += "=".repeat((4 - (payload.length % 4)) % 4); + const bytes = Uint8Array.from(atob(payload), (character) => character.charCodeAt(0)); + const config = JSON.parse(new TextDecoder().decode(bytes)) as Record; + const id = String(config.id ?? ""); + const port = Number(config.port); + const network = String(config.net ?? "tcp").toLowerCase(); + const tls = String(config.tls ?? "").toLowerCase(); + return typeof config.add === "string" && config.add.trim() !== "" && Number.isInteger(port) && port > 0 && port <= 65535 + && /^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/i.test(id) + && ["tcp", "ws", "websocket"].includes(network) && ["", "none", "tls"].includes(tls); + } catch { + return false; + } +} + +/** Subscription fetch proxies must never use per-account lease placeholders. */ export function validSubscriptionProxyURL(value: string): boolean { return !value.includes("{account}") && validProxyURL(value); } diff --git a/frontend/src/shared/i18n/index.ts b/frontend/src/shared/i18n/index.ts index bef6f887..6fd6b5fa 100644 --- a/frontend/src/shared/i18n/index.ts +++ b/frontend/src/shared/i18n/index.ts @@ -895,7 +895,7 @@ const resources = { console: { baseURLHelp: "Grok Console 请求与账号操作使用的基础端点。", chatTimeoutHelp: "Grok Console 聊天请求完成前允许等待的最长时间。", streamIdleTimeout: "流式空闲超时", streamIdleTimeoutHelp: "仅文本 SSE 连续无上游数据时允许等待的最长时间;不影响媒体和非流式请求。" }, batch: { title: "批量任务", importConcurrency: "导入同步并发", importConcurrencyHelp: "批量导入后并行执行账号初始化与信息同步的任务数。", conversionConcurrency: "账号转换并发", conversionConcurrencyHelp: "跨 Provider 转换账号时允许同时处理的任务数。", syncConcurrency: "数据同步并发", syncConcurrencyHelp: "批量同步账号额度、状态与能力时允许同时处理的任务数。", refreshConcurrency: "凭据刷新并发", refreshConcurrencyHelp: "批量刷新账号凭据时允许同时处理的任务数。", randomDelay: "随机延迟上限(ms)", randomDelayHelp: "批量任务启动前增加的随机延迟上限,用于平滑上游请求峰值。" }, media: { title: "媒体存储", maxImageSize: "单张图片上限", maxImageSizeHelp: "单个图片文件允许写入本地媒体存储的最大大小。", maxTotalSize: "媒体存储上限", maxTotalSizeHelp: "本地图片与视频文件允许占用的总存储空间。", cleanupThresholdPercent: "自动清理阈值", cleanupThresholdPercentHelp: "存储使用率达到该比例后,系统按时间清理较早的媒体文件。", cleanupInterval: "容量检查间隔", cleanupIntervalHelp: "后台检查媒体存储使用量并触发清理的时间间隔。", sizeUnit: "存储单位", publicApiBaseURL: "公共 API 地址", publicApiBaseURLHelp: "用于生成图片公开 URL 与文档示例地址。留空时回退到服务启动值,默认为 http://127.0.0.1:8000。" }, - egress: { title: "出口代理", description: "节点按 Grok Build、Grok Web、Grok Console 或 Web 资源独立管理代理和健康状态。Build 沿用 Provider 的 User-Agent;Web 与 Console 节点单独管理浏览器 User-Agent 和 Cookie。代理地址和 Cloudflare Cookie 仅写入。", add: "添加节点", saved: "代理节点已保存", deleted: "代理节点已删除", name: "名称", scope: "作用域", proxy: "代理", clearance: "Clearance", health: "健康度", directFallback: "未配置节点时使用直连", scopeBuild: "Grok Build", scopeWeb: "Grok Web", scopeWebAsset: "Grok Web(仅资源)", configured: "已配置", direct: "直连", none: "无", editTitle: "编辑代理节点", addTitle: "添加代理节点", dialogDescription: "Build 节点只配置代理并沿用 Provider 的 User-Agent;Web 与 Console 节点使用各自的浏览器 User-Agent 和 Cloudflare Cookie。", enabled: "启用", proxyURL: "代理地址", proxyProtocols: "支持 HTTP、HTTPS、SOCKS4、SOCKS4A、SOCKS5、SOCKS5H\nResin 可在用户名中使用 {account} 绑定账号租约。", proxyPool: "代理池模式", proxyPoolHelp: "共享代理池的单次连接失败不会使整个出口节点进入冷却;包含 {account} 的代理会自动启用此策略。", userAgent: "User-Agent", cloudflareCookie: "Cloudflare Cookie", keepConfigured: "已配置,留空保持不变", operationFailed: "操作失败", refreshClearance: "刷新 Clearance", clearanceRefreshed: "Clearance 已刷新", clearanceManaged: "Cloudflare Cookie 与 User-Agent 由 FlareSolverr 自动维护;Resin 等账号粘性代理会按账号隔离。", accounts: "已绑定", probe: "探测", healthy: "可用", unhealthy: "不可用", notTested: "未测试", test: "测试代理", testedOne: "代理测试完成", operations: "代理运营", automation: "自动任务", subscriptions: "代理订阅", testAll: "测试全部", rebalance: "立即调配", importText: "导入文本", addSource: "添加订阅", source: "订阅源", sync: "同步", capacity: "账号容量", noSources: "暂无订阅源", never: "从未", unlimited: "无限制", sourceSaved: "订阅源已保存", sourceDeleted: "订阅源已删除", sourceSynced: "订阅同步完成:导入 {{imported}},跳过 {{skipped}}", imported: "代理导入完成:导入 {{imported}},跳过 {{skipped}}", tested: "代理测试完成:可用 {{healthy}},不可用 {{unhealthy}}", rebalanced: "账号调配完成:新增 {{assigned}},均衡 {{rebalanced}},未分配 {{unplaced}}", automationSaved: "自动任务已保存", editSource: "编辑订阅", subscriptionURL: "订阅地址", sourceDialogDescription: "配置订阅来源、作用域、刷新周期和单节点账号容量。", importDialogDescription: "支持明文或 Base64 代理列表,每行一个 HTTP 或 SOCKS 地址。", probeInterval: "探测间隔(秒)", probeIntervalHelp: "后台重新测试已启用代理节点的间隔。", assignmentInterval: "调配间隔(秒)", assignmentIntervalHelp: "后台检查自动分配与节点容量的间隔。", autoAssign: "自动分配未绑定账号", autoAssignHelp: "将可调度且未绑定的账号分配到近期探测可用的节点。", autoBalance: "自动均衡自动绑定账号", autoBalanceHelp: "在健康节点之间调整自动绑定;手工绑定始终保持不变。", refreshInterval: "订阅刷新间隔(秒)", proxyList: "代理列表" }, + egress: { title: "出口代理", description: "节点按 Grok Build、Grok Web、Grok Console 或 Web 资源独立管理代理和健康状态。Build 沿用 Provider 的 User-Agent;Web 与 Console 节点单独管理浏览器 User-Agent 和 Cookie。代理地址和 Cloudflare Cookie 仅写入。", add: "添加节点", saved: "代理节点已保存", deleted: "代理节点已删除", name: "名称", scope: "作用域", proxy: "代理", clearance: "Clearance", health: "健康度", directFallback: "未配置节点时使用直连", scopeBuild: "Grok Build", scopeWeb: "Grok Web", scopeWebAsset: "Grok Web(仅资源)", configured: "已配置", direct: "直连", none: "无", editTitle: "编辑代理节点", addTitle: "添加代理节点", dialogDescription: "Build 节点只配置代理并沿用 Provider 的 User-Agent;Web 与 Console 节点使用各自的浏览器 User-Agent 和 Cloudflare Cookie。", enabled: "启用", proxyURL: "代理地址", proxyProtocols: "支持 HTTP、HTTPS、SOCKS4/4A、SOCKS5/5H、Trojan、VLESS、Shadowsocks 和 VMess。\n隧道协议支持 TCP、WebSocket 与 TLS;Resin 可在用户名中使用 {account}。", proxyPool: "代理池模式", proxyPoolHelp: "共享代理池的单次连接失败不会使整个出口节点进入冷却;包含 {account} 的代理会自动启用此策略。", userAgent: "User-Agent", cloudflareCookie: "Cloudflare Cookie", keepConfigured: "已配置,留空保持不变", operationFailed: "操作失败", refreshClearance: "刷新 Clearance", clearanceRefreshed: "Clearance 已刷新", clearanceManaged: "Cloudflare Cookie 与 User-Agent 由 FlareSolverr 自动维护;Resin 等账号粘性代理会按账号隔离。", accounts: "已绑定", probe: "探测", healthy: "可用", unhealthy: "不可用", notTested: "未测试", test: "测试代理", testedOne: "代理测试完成", operations: "代理运营", automation: "自动任务", subscriptions: "代理订阅", testAll: "测试全部", rebalance: "立即调配", importText: "导入文本", addSource: "添加订阅", source: "订阅源", sync: "同步", capacity: "账号容量", noSources: "暂无订阅源", never: "从未", unlimited: "无限制", sourceSaved: "订阅源已保存", sourceDeleted: "订阅源已删除", sourceSynced: "订阅同步完成:导入 {{imported}},跳过 {{skipped}}", imported: "代理导入完成:导入 {{imported}},跳过 {{skipped}}", tested: "代理测试完成:可用 {{healthy}},不可用 {{unhealthy}}", rebalanced: "账号调配完成:新增 {{assigned}},均衡 {{rebalanced}},未分配 {{unplaced}}", automationSaved: "自动任务已保存", editSource: "编辑订阅", subscriptionURL: "订阅地址", sourceDialogDescription: "配置订阅来源、作用域、刷新周期和单节点账号容量。", importDialogDescription: "支持明文或 Base64 代理列表,每行一个 HTTP、SOCKS、Trojan、VLESS、SS 或 VMess 地址。", probeInterval: "探测间隔(秒)", probeIntervalHelp: "后台重新测试已启用代理节点的间隔。", assignmentInterval: "调配间隔(秒)", assignmentIntervalHelp: "后台检查自动分配与节点容量的间隔。", autoAssign: "自动分配未绑定账号", autoAssignHelp: "将可调度且未绑定的账号分配到近期探测可用的节点。", autoBalance: "自动均衡自动绑定账号", autoBalanceHelp: "在健康节点之间调整自动绑定;手工绑定始终保持不变。", refreshInterval: "订阅刷新间隔(秒)", proxyList: "代理列表" }, routing: { title: "路由策略", stickyTTL: "会话粘性时长", stickyTTLHelp: "同一会话优先复用已选账号的有效时长;到期后重新参与调度。", cooldownBase: "基础冷却时间", cooldownBaseHelp: "账号发生可恢复故障后首次进入冷却的时长。", cooldownMax: "最大冷却时间", cooldownMaxHelp: "连续故障触发指数退避时允许达到的最长冷却时间。", capacityWait: "账号满载等待", capacityWaitHelp: "全部候选账号并发已满时,切换或失败前等待容量释放的时间。", maxAttempts: "最大尝试次数", maxAttemptsHelp: "单次请求在可用账号之间切换并重试的最大次数,范围为 1–200。", preferFreeBuild: "Grok Build Free 账号优先", preferFreeBuildHelp: "启用后优先选择已确认可用的 Free 账号,其他路由条件保持不变。", accountIsolatedConnections: "按账号隔离上游连接", accountIsolatedConnectionsHelp: "开启后,不同账号使用各自的上游 TCP/HTTP 连接池,便于外部 L4 或按连接哈希的负载均衡器分散流量;同一账号仍可复用连接。适用于 Build / Web / Console 出站及 Web 转 Build。会增加连接数、TLS 握手、内存和文件描述符占用,建议仅在确有外部连接级负载均衡需求时开启。" }, audit: { title: "请求审计", bufferSize: "队列容量", bufferSizeHelp: "审计记录进入持久化前可在内存队列中等待的最大数量。", batchSize: "批量写入数", batchSizeHelp: "每次数据库事务最多写入的审计记录数量。", flushInterval: "刷新间隔", flushIntervalHelp: "队列未达到批量写入数时,强制提交待处理审计记录的间隔。", commitDelay: "提交聚合等待(毫秒)", commitDelayHelp: "需要确认提交的请求进入原子批次前允许等待的最长时间。" }, clientKeys: { title: "密钥默认限制", rpmLimit: "默认 RPM", rpmLimitHelp: "新建客户端密钥默认允许的每分钟请求数。", maxConcurrent: "默认并发数", maxConcurrentHelp: "新建客户端密钥默认允许同时执行的请求数。" }, @@ -1725,6 +1725,7 @@ Object.assign(resources.en.translation.models as unknown as Record, { description: "节点按 Grok Build、Grok Web、Grok Console、Web 资源和 Console 资源独立管理代理与健康状态。Console 资源节点仅使用代理与 User-Agent,不发送账号或 Cloudflare Cookie。代理地址和 Cookie 仅写入。", dialogDescription: "配置节点作用域、代理地址和浏览器身份;Console 资源节点用于匿名媒体下载,不使用 Clearance Cookie。", + proxyProtocols: "支持 HTTP、HTTPS、SOCKS4/4A、SOCKS5/5H、Trojan、VLESS、Shadowsocks 和 VMess。\n隧道协议支持 TCP、WebSocket 与 TLS;Resin 可在用户名中使用 {account}。", scopeConsoleAsset: "Grok Console(仅资源)", health: "请求健康", healthHelp: "由真实 Grok 请求的成功、连接失败和反爬拒绝累计得出,与连通探测独立。", @@ -1737,6 +1738,7 @@ Object.assign(resources["zh-CN"].translation.settings.egress as unknown as Recor Object.assign(resources.en.translation.settings.egress as unknown as Record, { description: "Nodes manage proxy and health independently for Grok Build, Grok Web, Grok Console, Web assets, and Console assets. Console asset nodes use only the proxy and User-Agent and never send account or Cloudflare cookies. Proxy URLs and cookies are write-only.", dialogDescription: "Configure the node scope, proxy address, and browser identity. Console asset nodes are for anonymous media downloads and do not use clearance cookies.", + proxyProtocols: "Supports HTTP, HTTPS, SOCKS4/4A, SOCKS5/5H, Trojan, VLESS, Shadowsocks, and VMess.\nTunnel protocols support TCP, WebSocket, and TLS; Resin users can put {account} in the username.", scopeConsoleAsset: "Grok Console (assets only)", accounts: "Bound", health: "Request health", healthHelp: "Accumulated from real Grok request successes, transport failures, and anti-bot rejections; independent of the connectivity probe.", addManually: "Form entry", @@ -1754,7 +1756,7 @@ Object.assign(resources.en.translation.settings.egress as unknown as Record, { @@ -1865,11 +1867,11 @@ Object.assign(resources["zh-CN"].translation.settings.egress as unknown as Recor cleanupUnavailableConfirm: "删除不可用节点", cleanupUnavailableComplete: "已删除 {{deleted}} 个不可用代理节点", subscriptionProxy: "订阅拉取代理", - subscriptionProxyHelp: "用于拉取代理订阅内容。许多订阅源不支持国外网络,可填写 HTTP/HTTPS/SOCKS 代理地址。", + subscriptionProxyHelp: "用于拉取代理订阅内容,支持 HTTP、SOCKS、Trojan、VLESS、SS 和 VMess。", clearSubscriptionProxy: "清除", cancelClearSubscriptionProxy: "保留", subscriptionProxyClearPending: "保存后清除", - invalidProxy: "请输入有效的代理地址(http/https/socks4/socks4a/socks5/socks5h);此处不支持 {account}", + invalidProxy: "请输入有效的 HTTP、SOCKS、Trojan、VLESS、SS 或 VMess 代理地址;此处不支持 {account}", }); Object.assign(resources["zh-CN"].translation.accounts as unknown as Record, { From dd9183e2b02e6a3f59439adb6e8237a355bc77c5 Mon Sep 17 00:00:00 2001 From: noxenys Date: Tue, 11 Aug 2026 23:02:56 +0800 Subject: [PATCH 05/40] feat: forward x_search time range and image search in console provider Console path normalizeConsoleTools currently strips every x_search field except type/enable_video_understanding and every web_search field except type/enable_image_understanding, dropping from_date/to_date and enable_image_search that clients legitimately send. - web_search: pass through enable_image_search (image search toggle) - x_search: pass through from_date/to_date (YYYY-MM-DD) with format and order validation; invalid values are dropped instead of erroring, matching the console provider's tolerate-and-drop style. The cli provider already validates these fields the same way. Behavior is unchanged for requests that do not set the new fields. --- .../infra/provider/console/normalize.go | 27 +++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/backend/internal/infra/provider/console/normalize.go b/backend/internal/infra/provider/console/normalize.go index d6143594..2505ea97 100644 --- a/backend/internal/infra/provider/console/normalize.go +++ b/backend/internal/infra/provider/console/normalize.go @@ -229,12 +229,39 @@ func normalizeConsoleTools(payload map[string]any) bool { if enabled, ok := tool["enable_image_understanding"].(bool); ok { clean["enable_image_understanding"] = enabled } + // Forward the image-search toggle (enable_image_search) so clients + // can explicitly enable/disable it; absent when not requested. + if enabled, ok := tool["enable_image_search"].(bool); ok { + clean["enable_image_search"] = enabled + } result = append(result, clean) case "x_search": clean := map[string]any{"type": "x_search", "enable_video_understanding": true} if enabled, ok := tool["enable_video_understanding"].(bool); ok { clean["enable_video_understanding"] = enabled } + // Forward the X-search time bounds (from_date/to_date, YYYY-MM-DD). + // Invalid formats and empty strings are dropped; if from_date is + // later than to_date both are dropped to avoid an upstream 400. + for _, field := range []string{"from_date", "to_date"} { + text, ok := tool[field].(string) + if !ok || text == "" { + continue + } + if date, err := time.Parse("2006-01-02", text); err == nil && date.Format("2006-01-02") == text { + clean[field] = text + } + } + from, hasFrom := clean["from_date"].(string) + to, hasTo := clean["to_date"].(string) + if hasFrom && hasTo { + fromDate, _ := time.Parse("2006-01-02", from) + toDate, _ := time.Parse("2006-01-02", to) + if fromDate.After(toDate) { + delete(clean, "from_date") + delete(clean, "to_date") + } + } result = append(result, clean) case "function": name, _ := tool["name"].(string) From 8b16d6d0b197173a44778e14c6062c1659c22fa8 Mon Sep 17 00:00:00 2001 From: noxenys Date: Tue, 11 Aug 2026 23:13:37 +0800 Subject: [PATCH 06/40] test: cover console x_search date bounds and web_search image search forwarding Add table-style subtests for normalizeConsoleTools: - forward enable_image_search on web_search; omit when unset - strip unknown web_search fields - forward valid x_search from_date/to_date - drop invalid formats and inverted ranges - keep single-sided from_date Keeps Console's tolerate-and-drop style (unlike CLI which returns 400). --- .../infra/provider/console/console_test.go | 134 ++++++++++++++++++ 1 file changed, 134 insertions(+) diff --git a/backend/internal/infra/provider/console/console_test.go b/backend/internal/infra/provider/console/console_test.go index bb88af56..2219b2ed 100644 --- a/backend/internal/infra/provider/console/console_test.go +++ b/backend/internal/infra/provider/console/console_test.go @@ -185,6 +185,140 @@ func TestNormalizeRequestAppliesConsoleContract(t *testing.T) { } } +func TestNormalizeRequestForwardsXSearchTimeRangeAndImageSearch(t *testing.T) { + spec, ok := Resolve("grok-4.3") + if !ok { + t.Fatal("grok-4.3 missing") + } + + t.Run("forwards enable_image_search on web_search", func(t *testing.T) { + body, err := normalizeRequest([]byte(`{ + "model":"grok-4.3", + "tools":[{"type":"web_search","enable_image_search":true,"custom":true}] + }`), spec) + if err != nil { + t.Fatal(err) + } + var payload map[string]any + if err := json.Unmarshal(body, &payload); err != nil { + t.Fatal(err) + } + tools, _ := payload["tools"].([]any) + if len(tools) != 1 { + t.Fatalf("tools = %#v", tools) + } + webSearch, _ := tools[0].(map[string]any) + if webSearch["type"] != "web_search" || webSearch["enable_image_understanding"] != true { + t.Fatalf("web_search defaults = %#v", webSearch) + } + if webSearch["enable_image_search"] != true { + t.Fatalf("enable_image_search not forwarded: %#v", webSearch) + } + if webSearch["custom"] != nil { + t.Fatalf("unknown field custom should be stripped: %#v", webSearch) + } + }) + + t.Run("omits enable_image_search when client does not set it", func(t *testing.T) { + body, err := normalizeRequest([]byte(`{ + "model":"grok-4.3", + "tools":[{"type":"web_search"}] + }`), spec) + if err != nil { + t.Fatal(err) + } + var payload map[string]any + if err := json.Unmarshal(body, &payload); err != nil { + t.Fatal(err) + } + webSearch, _ := payload["tools"].([]any)[0].(map[string]any) + if _, exists := webSearch["enable_image_search"]; exists { + t.Fatalf("enable_image_search should be absent by default: %#v", webSearch) + } + }) + + t.Run("forwards valid x_search from_date and to_date", func(t *testing.T) { + body, err := normalizeRequest([]byte(`{ + "model":"grok-4.3", + "tools":[{"type":"x_search","from_date":"2026-07-01","to_date":"2026-07-23","noise":1}] + }`), spec) + if err != nil { + t.Fatal(err) + } + var payload map[string]any + if err := json.Unmarshal(body, &payload); err != nil { + t.Fatal(err) + } + xSearch, _ := payload["tools"].([]any)[0].(map[string]any) + if xSearch["type"] != "x_search" || xSearch["enable_video_understanding"] != true { + t.Fatalf("x_search defaults = %#v", xSearch) + } + if xSearch["from_date"] != "2026-07-01" || xSearch["to_date"] != "2026-07-23" { + t.Fatalf("date bounds not forwarded: %#v", xSearch) + } + if xSearch["noise"] != nil { + t.Fatalf("unknown field noise should be stripped: %#v", xSearch) + } + }) + + t.Run("drops invalid date formats", func(t *testing.T) { + body, err := normalizeRequest([]byte(`{ + "model":"grok-4.3", + "tools":[{"type":"x_search","from_date":"2026-7-01","to_date":"2026-02-30"}] + }`), spec) + if err != nil { + t.Fatal(err) + } + var payload map[string]any + if err := json.Unmarshal(body, &payload); err != nil { + t.Fatal(err) + } + xSearch, _ := payload["tools"].([]any)[0].(map[string]any) + if xSearch["from_date"] != nil || xSearch["to_date"] != nil { + t.Fatalf("invalid dates should be dropped: %#v", xSearch) + } + if xSearch["type"] != "x_search" || xSearch["enable_video_understanding"] != true { + t.Fatalf("x_search defaults should remain: %#v", xSearch) + } + }) + + t.Run("drops inverted date range", func(t *testing.T) { + body, err := normalizeRequest([]byte(`{ + "model":"grok-4.3", + "tools":[{"type":"x_search","from_date":"2026-07-24","to_date":"2026-07-23"}] + }`), spec) + if err != nil { + t.Fatal(err) + } + var payload map[string]any + if err := json.Unmarshal(body, &payload); err != nil { + t.Fatal(err) + } + xSearch, _ := payload["tools"].([]any)[0].(map[string]any) + if xSearch["from_date"] != nil || xSearch["to_date"] != nil { + t.Fatalf("inverted range should drop both bounds: %#v", xSearch) + } + }) + + t.Run("keeps only from_date when to_date absent", func(t *testing.T) { + body, err := normalizeRequest([]byte(`{ + "model":"grok-4.3", + "tools":[{"type":"x_search","from_date":"2026-08-01"}] + }`), spec) + if err != nil { + t.Fatal(err) + } + var payload map[string]any + if err := json.Unmarshal(body, &payload); err != nil { + t.Fatal(err) + } + xSearch, _ := payload["tools"].([]any)[0].(map[string]any) + if xSearch["from_date"] != "2026-08-01" || xSearch["to_date"] != nil { + t.Fatalf("single bound = %#v", xSearch) + } + }) +} + func TestNormalizeRequestDoesNotInjectToolsForConsoleCatalog(t *testing.T) { for _, spec := range catalog { t.Run(spec.PublicID, func(t *testing.T) { From 3f7a0f91ff210cd37e4991fd93dbbe7fa93fbbfd Mon Sep 17 00:00:00 2001 From: lindahao Date: Sat, 8 Aug 2026 23:34:56 +0800 Subject: [PATCH 07/40] fix: pass multi-reference video images and enable free video 1.5 Console/Build adapters now map multiple input images to official reference_images instead of rejecting anything beyond a single start frame. Build account capability normalization keeps grok-imagine-video-1.5 for free accounts on the primary Build path. --- .../application/model/service_test.go | 18 ++- .../internal/infra/provider/cli/adapter.go | 14 +- .../infra/provider/cli/adapter_test.go | 30 ++-- backend/internal/infra/provider/cli/video.go | 30 +++- .../internal/infra/provider/cli/video_test.go | 130 ++++++++++++++++-- .../infra/provider/console/console_test.go | 65 +++++++++ .../internal/infra/provider/console/media.go | 25 +++- 7 files changed, 263 insertions(+), 49 deletions(-) diff --git a/backend/internal/application/model/service_test.go b/backend/internal/application/model/service_test.go index 3bc6a3d8..7000b87f 100644 --- a/backend/internal/application/model/service_test.go +++ b/backend/internal/application/model/service_test.go @@ -260,8 +260,8 @@ func TestSyncAccountNormalizesBuildVideo15ByBillingSuper(t *testing.T) { assertSupports(superPrimary.ID, video15, true) assertSupports(superFallback.ID, video15, true) - assertSupports(freeAccount.ID, video15, false) - assertSupports(unknownAccount.ID, video15, false) + assertSupports(freeAccount.ID, video15, true) + assertSupports(unknownAccount.ID, video15, true) assertSupports(superPrimary.ID, "grok-4.5", true) assertSupports(superFallback.ID, "grok-code-fast-1", true) assertSupports(freeAccount.ID, "grok-4.5", true) @@ -374,11 +374,12 @@ type buildCapabilityNormalizerAdapter struct { } func (a *buildCapabilityNormalizerAdapter) NormalizeAccountModelCapabilities(models []string, billing *account.Billing, credential account.Credential) []string { - // Match cli.Adapter rules: Build OAuth adds Composer; Super (paid or - // entitlement) ensures 1.5; otherwise remove video 1.5 exactly. + // Match cli.Adapter rules: Build OAuth adds Composer; all Build accounts + // ensure video 1.5 so Free can schedule grok-imagine-video-1.5. + _ = billing const video15 = "grok-imagine-video-1.5" - super := account.IsBuildSuper(credential, billing) - composer := credential.Provider == account.ProviderBuild && credential.AuthType == account.AuthTypeOAuth + buildAccount := credential.Provider == account.ProviderBuild + composer := buildAccount && credential.AuthType == account.AuthTypeOAuth result := make([]string, 0, len(models)+2) seen := make(map[string]struct{}, len(models)+2) hasVideo15 := false @@ -390,15 +391,12 @@ func (a *buildCapabilityNormalizerAdapter) NormalizeAccountModelCapabilities(mod continue } if modelName == video15 { - if !super { - continue - } hasVideo15 = true } seen[modelName] = struct{}{} result = append(result, modelName) } - if super && !hasVideo15 { + if buildAccount && !hasVideo15 { result = append(result, video15) } if composer { diff --git a/backend/internal/infra/provider/cli/adapter.go b/backend/internal/infra/provider/cli/adapter.go index f172208c..5d637369 100644 --- a/backend/internal/infra/provider/cli/adapter.go +++ b/backend/internal/infra/provider/cli/adapter.go @@ -619,11 +619,12 @@ func (a *Adapter) ListModels(ctx context.Context, credential account.Credential) // NormalizeAccountModelCapabilities normalizes capabilities that the OAuth // session contract exposes independently of the account's sparse /models list. // Composer is available to Build OAuth sessions even though the live catalog can -// return only grok-4.5. Super always includes video 1.5; Free and Unknown remove -// video 1.5 exactly. BuildAPIFallback is ignored. +// return only grok-4.5. Build accounts always include video 1.5 so Free can use +// grok-imagine-video-1.5 on the primary Build path. BuildAPIFallback is ignored. func (a *Adapter) NormalizeAccountModelCapabilities(models []string, billing *account.Billing, credential account.Credential) []string { - super := account.IsBuildSuper(credential, billing) - composer := credential.Provider == account.ProviderBuild && credential.AuthType == account.AuthTypeOAuth + _ = billing + buildAccount := credential.Provider == account.ProviderBuild + composer := buildAccount && credential.AuthType == account.AuthTypeOAuth result := make([]string, 0, len(models)+2) seen := make(map[string]struct{}, len(models)+2) hasVideo15 := false @@ -636,15 +637,12 @@ func (a *Adapter) NormalizeAccountModelCapabilities(models []string, billing *ac continue } if model == buildVideoModel { - if !super { - continue - } hasVideo15 = true } seen[model] = struct{}{} result = append(result, model) } - if super && !hasVideo15 { + if buildAccount && !hasVideo15 { result = append(result, buildVideoModel) } if composer { diff --git a/backend/internal/infra/provider/cli/adapter_test.go b/backend/internal/infra/provider/cli/adapter_test.go index f0cac0c2..16227d65 100644 --- a/backend/internal/infra/provider/cli/adapter_test.go +++ b/backend/internal/infra/provider/cli/adapter_test.go @@ -566,7 +566,7 @@ func TestGetBillingUsesCreditsAndLiveSubscriptionTier(t *testing.T) { } } -func TestNormalizeAccountModelCapabilitiesSuperAddsVideo15(t *testing.T) { +func TestNormalizeAccountModelCapabilitiesBuildAddsVideo15(t *testing.T) { adapter := &Adapter{} build := account.Credential{Provider: account.ProviderBuild} // Super / paid: add 1.5 even when primary Build returns only grok-4.5. @@ -583,16 +583,21 @@ func TestNormalizeAccountModelCapabilitiesSuperAddsVideo15(t *testing.T) { if len(got) != 3 || got[0] != "grok-4.5" || got[1] != buildVideoModel || got[2] != "grok-code-fast-1" { t.Fatalf("super catalog = %#v", got) } - // Free: remove 1.5 even when the catalog exposes it. + // Free: keep/add 1.5 so free Build accounts can use video generation. got = adapter.NormalizeAccountModelCapabilities([]string{"grok-4.5", buildVideoModel}, &account.Billing{Used: 1, PlanName: "free"}, build) - if len(got) != 1 || got[0] != "grok-4.5" { + if len(got) != 2 || got[0] != "grok-4.5" || got[1] != buildVideoModel { t.Fatalf("free catalog = %#v", got) } - // Unknown (no Billing): treat as Free and remove 1.5. + // Unknown (no Billing): still keep 1.5 for Build accounts. got = adapter.NormalizeAccountModelCapabilities([]string{buildVideoModel, "grok-4.5"}, nil, build) - if len(got) != 1 || got[0] != "grok-4.5" { + if len(got) != 2 || got[0] != buildVideoModel || got[1] != "grok-4.5" { t.Fatalf("unknown catalog = %#v", got) } + // Free catalog without 1.5: inject it. + got = adapter.NormalizeAccountModelCapabilities([]string{"grok-4.5"}, &account.Billing{PlanName: "free"}, build) + if len(got) != 2 || got[0] != "grok-4.5" || got[1] != buildVideoModel { + t.Fatalf("free inject catalog = %#v", got) + } // Do not depend on BuildAPIFallback; an empty catalog with Billing Super adds only 1.5. got = adapter.NormalizeAccountModelCapabilities(nil, &account.Billing{PlanName: "SuperGrok", CreditUsagePercent: 1}, build) if len(got) != 1 || got[0] != buildVideoModel { @@ -610,11 +615,11 @@ func TestNormalizeAccountModelCapabilitiesAddsComposerOnlyForBuildOAuth(t *testi adapter := &Adapter{} oauth := account.Credential{Provider: account.ProviderBuild, AuthType: account.AuthTypeOAuth} got := adapter.NormalizeAccountModelCapabilities([]string{"grok-4.5"}, &account.Billing{PlanName: "free"}, oauth) - if len(got) != 2 || got[0] != "grok-4.5" || got[1] != modeldomain.GrokComposer25Fast { + if len(got) != 3 || got[0] != "grok-4.5" || got[1] != buildVideoModel || got[2] != modeldomain.GrokComposer25Fast { t.Fatalf("OAuth Free capabilities = %#v", got) } got = adapter.NormalizeAccountModelCapabilities([]string{"grok-4.5", modeldomain.GrokComposer25Fast, modeldomain.GrokComposer25Fast}, nil, oauth) - if len(got) != 2 || got[0] != "grok-4.5" || got[1] != modeldomain.GrokComposer25Fast { + if len(got) != 3 || got[0] != "grok-4.5" || got[1] != modeldomain.GrokComposer25Fast || got[2] != buildVideoModel { t.Fatalf("Composer capability was not deduplicated: %#v", got) } for _, credential := range []account.Credential{ @@ -622,8 +627,15 @@ func TestNormalizeAccountModelCapabilitiesAddsComposerOnlyForBuildOAuth(t *testi {Provider: account.ProviderWeb, AuthType: account.AuthTypeOAuth}, } { got = adapter.NormalizeAccountModelCapabilities([]string{"grok-4.5"}, nil, credential) - if len(got) != 1 || got[0] != "grok-4.5" { - t.Fatalf("Composer leaked outside Build OAuth for %#v: %#v", credential, got) + switch credential.Provider { + case account.ProviderBuild: + if len(got) != 2 || got[0] != "grok-4.5" || got[1] != buildVideoModel { + t.Fatalf("Build SSO capabilities = %#v", got) + } + default: + if len(got) != 1 || got[0] != "grok-4.5" { + t.Fatalf("Composer leaked outside Build OAuth for %#v: %#v", credential, got) + } } } } diff --git a/backend/internal/infra/provider/cli/video.go b/backend/internal/infra/provider/cli/video.go index 672e0a6d..7a707def 100644 --- a/backend/internal/infra/provider/cli/video.go +++ b/backend/internal/infra/provider/cli/video.go @@ -14,6 +14,7 @@ import ( "unicode/utf8" "github.com/chenyme/grok2api/backend/internal/domain/account" + mediadomain "github.com/chenyme/grok2api/backend/internal/domain/media" infraegress "github.com/chenyme/grok2api/backend/internal/infra/egress" "github.com/chenyme/grok2api/backend/internal/infra/provider" ) @@ -21,7 +22,9 @@ import ( const ( buildVideoModel = "grok-imagine-video-1.5" xaiVideoModel = "grok-imagine-video-1.5-preview" - buildVideoMaxImages = 1 + // Align with the gateway ceiling and official xAI video inputs: + // one start frame via image, or multiple references via reference_images. + buildVideoMaxImages = mediadomain.MaxInputImages buildVideoPollEvery = 2 * time.Second buildVideoMaxBodySize = 2 << 20 buildVideoErrorSummaryLimit = 256 @@ -148,13 +151,13 @@ func boundDiagnosticText(value string, limit int) string { } // GenerateVideo 通过 Build OAuth 创建并轮询视频任务;对外仍使用 grok-imagine-video-1.5, -// 发往 XAI 时仅在出站协议层转换为官方 preview 模型与 image.url 结构。 -// 最多 1 张首图;多于 1 张在调用上游前失败,不静默截断。 +// 发往 XAI 时仅在出站协议层转换为官方 preview 模型与 image/reference_images 结构。 +// 1 张图映射为 image;多张图映射为 reference_images。超过网关上限时失败,不静默截断。 // 显式模式优先;auto 下仅已确认 Super 且 bot_flag_source/bfs 为 1 或 2 默认使用 XAI。 // 其他 auto Super 账号仅在当次 Build 创建返回 403 后探测 XAI。 func (a *Adapter) GenerateVideo(ctx context.Context, request provider.VideoRequest) (provider.VideoResult, error) { if len(request.ReferenceURLs) > buildVideoMaxImages { - return provider.VideoResult{}, fmt.Errorf("Build grok-imagine-video-1.5 最多支持 1 张首图,当前为 %d 张", len(request.ReferenceURLs)) + return provider.VideoResult{}, fmt.Errorf("Build grok-imagine-video-1.5 最多支持 %d 张参考图,当前为 %d 张", buildVideoMaxImages, len(request.ReferenceURLs)) } accessToken, err := a.cipher.Decrypt(request.Credential.EncryptedAccessToken) if err != nil { @@ -291,16 +294,31 @@ func videoCreatePayload(request provider.VideoRequest, uploadURL string, profile if resolution := strings.TrimSpace(request.Resolution); resolution != "" { payload["resolution"] = resolution } - if len(request.ReferenceURLs) == 1 { + switch len(request.ReferenceURLs) { + case 0: + // text-to-video + case 1: imageURL := strings.TrimSpace(request.ReferenceURLs[0]) if imageURL == "" { return nil, fmt.Errorf("视频首图 URL 不能为空") } payload["image"] = map[string]any{profile.imageURLField: imageURL} + default: + references := make([]map[string]any, 0, len(request.ReferenceURLs)) + for _, rawURL := range request.ReferenceURLs { + imageURL := strings.TrimSpace(rawURL) + if imageURL == "" { + return nil, fmt.Errorf("视频参考图 URL 不能为空") + } + references = append(references, map[string]any{profile.imageURLField: imageURL}) + } + payload["reference_images"] = references } if _, hasPrompt := payload["prompt"]; !hasPrompt { if _, hasImage := payload["image"]; !hasImage { - return nil, fmt.Errorf("文本生视频必须提供 prompt;图片生视频可以省略 prompt") + if _, hasReferences := payload["reference_images"]; !hasReferences { + return nil, fmt.Errorf("文本生视频必须提供 prompt;图片生视频可以省略 prompt") + } } } if uploadURL = strings.TrimSpace(uploadURL); uploadURL != "" { diff --git a/backend/internal/infra/provider/cli/video_test.go b/backend/internal/infra/provider/cli/video_test.go index ebd2f822..9060652c 100644 --- a/backend/internal/infra/provider/cli/video_test.go +++ b/backend/internal/infra/provider/cli/video_test.go @@ -108,23 +108,69 @@ func TestXAIVideoCreatePayloadMatchesOfficialSchema(t *testing.T) { } } -func TestGenerateVideoRejectsTwoImagesBeforeUpstream(t *testing.T) { - adapter, encrypted := newTestBuildVideoAdapter(t) - var hits atomic.Int32 - adapter.http.Transport = roundTripFunc(func(request *http.Request) (*http.Response, error) { - hits.Add(1) - t.Fatalf("two-image request must not reach upstream: %s %s", request.Method, request.URL) - return nil, nil - }) - _, err := adapter.GenerateVideo(context.Background(), provider.VideoRequest{ - Credential: account.Credential{ID: 1, EncryptedAccessToken: encrypted}, - Prompt: "animate", +func TestBuildVideoCreatePayloadMapsMultipleReferences(t *testing.T) { + payload, err := videoCreatePayload(provider.VideoRequest{ + Prompt: "animate", + Duration: 6, + AspectRatio: "16:9", + Resolution: "720p", + ReferenceURLs: []string{ + "https://cdn.example.com/one.png", + "https://cdn.example.com/two.png", + "https://cdn.example.com/three.png", + }, + }, "", buildVideoRequestProfile) + if err != nil { + t.Fatal(err) + } + if _, exists := payload["image"]; exists { + t.Fatalf("multi-reference payload must not include image: %#v", payload) + } + references, ok := payload["reference_images"].([]map[string]any) + if !ok || len(references) != 3 { + t.Fatalf("reference_images = %#v", payload["reference_images"]) + } + if references[0]["image_url"] != "https://cdn.example.com/one.png" || references[2]["image_url"] != "https://cdn.example.com/three.png" { + t.Fatalf("reference_images = %#v", references) + } + + xaiPayload, err := videoCreatePayload(provider.VideoRequest{ + Prompt: "animate", ReferenceURLs: []string{ "https://cdn.example.com/one.png", "https://cdn.example.com/two.png", }, + }, "https://api.example/v1/media/uploads/tok", xaiVideoRequestProfile) + if err != nil { + t.Fatal(err) + } + xaiReferences, ok := xaiPayload["reference_images"].([]map[string]any) + if !ok || len(xaiReferences) != 2 || xaiReferences[0]["url"] != "https://cdn.example.com/one.png" { + t.Fatalf("xai reference_images = %#v", xaiPayload["reference_images"]) + } + if _, exists := xaiPayload["image"]; exists { + t.Fatalf("xai multi-reference payload must not include image: %#v", xaiPayload) + } +} + +func TestGenerateVideoRejectsTooManyImagesBeforeUpstream(t *testing.T) { + adapter, encrypted := newTestBuildVideoAdapter(t) + var hits atomic.Int32 + adapter.http.Transport = roundTripFunc(func(request *http.Request) (*http.Response, error) { + hits.Add(1) + t.Fatalf("oversized reference request must not reach upstream: %s %s", request.Method, request.URL) + return nil, nil }) - if err == nil || !strings.Contains(err.Error(), "最多支持 1 张首图") { + references := make([]string, buildVideoMaxImages+1) + for i := range references { + references[i] = "https://cdn.example.com/" + strings.Repeat("x", i+1) + ".png" + } + _, err := adapter.GenerateVideo(context.Background(), provider.VideoRequest{ + Credential: account.Credential{ID: 1, EncryptedAccessToken: encrypted}, + Prompt: "animate", + ReferenceURLs: references, + }) + if err == nil || !strings.Contains(err.Error(), "最多支持") { t.Fatalf("error = %v", err) } if hits.Load() != 0 { @@ -132,6 +178,66 @@ func TestGenerateVideoRejectsTwoImagesBeforeUpstream(t *testing.T) { } } +func TestGenerateVideoPostsReferenceImagesAndPollsUntilReady(t *testing.T) { + adapter, encrypted := newTestBuildVideoAdapter(t) + var createBody map[string]any + var pollCount atomic.Int32 + adapter.http.Transport = roundTripFunc(func(request *http.Request) (*http.Response, error) { + if identity := infraegress.AccountFromContext(request.Context()); identity != "grok_build_9" { + t.Fatalf("egress account identity = %q", identity) + } + switch { + case request.Method == http.MethodPost && request.URL.Path == "/v1/videos/generations": + if request.Header.Get("Authorization") != "Bearer access-token" { + t.Fatalf("missing auth header: %#v", request.Header) + } + if err := json.NewDecoder(request.Body).Decode(&createBody); err != nil { + t.Fatal(err) + } + return jsonResponse(http.StatusOK, `{"request_id":"vid_ref_123","status":"queued"}`, request), nil + case request.Method == http.MethodGet && request.URL.Path == "/v1/videos/vid_ref_123": + count := pollCount.Add(1) + if count == 1 { + return jsonResponse(http.StatusOK, `{"status":"processing","progress":40}`, request), nil + } + return jsonResponse(http.StatusOK, `{"status":"completed","progress":100,"video":{"url":"https://assets.grok.com/videos/ref.mp4"}}`, request), nil + default: + t.Fatalf("unexpected request %s %s", request.Method, request.URL) + return nil, nil + } + }) + + result, err := adapter.GenerateVideo(context.Background(), provider.VideoRequest{ + Credential: account.Credential{ID: 9, UserID: "user-1", EncryptedAccessToken: encrypted}, + Prompt: "animate knife", + Duration: 6, + AspectRatio: "16:9", + Resolution: "720p", + ReferenceURLs: []string{ + "https://r2.example.com/first.png", + "https://r2.example.com/second.png", + }, + }) + if err != nil { + t.Fatal(err) + } + if result.URL != "https://assets.grok.com/videos/ref.mp4" || result.ContentType != "video/mp4" { + t.Fatalf("result = %#v", result) + } + if _, exists := createBody["image"]; exists { + t.Fatalf("create body unexpectedly includes image: %#v", createBody) + } + references, ok := createBody["reference_images"].([]any) + if !ok || len(references) != 2 { + t.Fatalf("create body reference_images = %#v", createBody["reference_images"]) + } + first, _ := references[0].(map[string]any) + second, _ := references[1].(map[string]any) + if first["image_url"] != "https://r2.example.com/first.png" || second["image_url"] != "https://r2.example.com/second.png" { + t.Fatalf("create body = %#v", createBody) + } +} + func TestGenerateVideoPostsSingleImageAndPollsUntilReady(t *testing.T) { adapter, encrypted := newTestBuildVideoAdapter(t) var createBody map[string]any diff --git a/backend/internal/infra/provider/console/console_test.go b/backend/internal/infra/provider/console/console_test.go index bb88af56..23df3ab8 100644 --- a/backend/internal/infra/provider/console/console_test.go +++ b/backend/internal/infra/provider/console/console_test.go @@ -1266,6 +1266,71 @@ func TestConsoleVideoCreatesAndPollsStandardResources(t *testing.T) { } } +func TestConsoleVideoPostsReferenceImages(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) { + if serveTestDPoPToken(t, writer, request) { + return + } + verifyTestDPoPProof(t, request) + writer.Header().Set("Content-Type", "application/json") + switch { + case request.Method == http.MethodPost && request.URL.Path == "/v1/videos/generations": + var payload map[string]any + if err := json.NewDecoder(request.Body).Decode(&payload); err != nil { + t.Error(err) + } + if _, exists := payload["image"]; exists { + t.Errorf("multi-reference payload must not include image: %#v", payload) + } + references, ok := payload["reference_images"].([]any) + if !ok || len(references) != 3 { + t.Errorf("reference_images = %#v", payload["reference_images"]) + } else { + first, _ := references[0].(map[string]any) + third, _ := references[2].(map[string]any) + if first["url"] != "https://example.com/a.png" || third["url"] != "https://example.com/c.png" { + t.Errorf("reference_images = %#v", references) + } + } + _, _ = writer.Write([]byte(`{"request_id":"upstream-video-ref-1"}`)) + case request.Method == http.MethodGet && request.URL.Path == "/v1/videos/upstream-video-ref-1": + _, _ = writer.Write([]byte(`{"status":"done","progress":100,"video":{"url":"https://vidgen.x.ai/result-ref.mp4"}}`)) + default: + http.NotFound(writer, request) + } + })) + t.Cleanup(server.Close) + adapter, credential := newConsoleTestAdapter(t, server.URL) + result, err := adapter.GenerateVideo(context.Background(), provider.VideoRequest{ + Credential: credential, Prompt: "animate", Duration: 6, AspectRatio: "16:9", Resolution: "720p", + ReferenceURLs: []string{ + "https://example.com/a.png", + "https://example.com/b.png", + "https://example.com/c.png", + }, + }) + if err != nil { + t.Fatal(err) + } + if result.URL != "https://vidgen.x.ai/result-ref.mp4" || result.ContentType != "video/mp4" { + t.Fatalf("video result = %#v", result) + } +} + +func TestConsoleVideoRejectsTooManyReferenceImages(t *testing.T) { + adapter, credential := newConsoleTestAdapter(t, "https://console.example") + references := make([]string, consoleMaxVideoImages+1) + for i := range references { + references[i] = "https://example.com/" + strings.Repeat("x", i+1) + ".png" + } + _, err := adapter.GenerateVideo(context.Background(), provider.VideoRequest{ + Credential: credential, Prompt: "animate", Duration: 6, ReferenceURLs: references, + }) + if err == nil || !strings.Contains(err.Error(), "最多支持") { + t.Fatalf("error = %v", err) + } +} + func TestParseConsoleVideoStatusRejectsUnknownState(t *testing.T) { if _, _, err := parseConsoleVideoStatus([]byte(`{"status":"mystery"}`), nil); err == nil || !strings.Contains(err.Error(), "状态无效") { t.Fatalf("unknown status error = %v", err) diff --git a/backend/internal/infra/provider/console/media.go b/backend/internal/infra/provider/console/media.go index 21d358a5..1f0edb71 100644 --- a/backend/internal/infra/provider/console/media.go +++ b/backend/internal/infra/provider/console/media.go @@ -29,7 +29,9 @@ const ( consoleMediaOutputAttempts = 3 consoleVideoPollEvery = 2 * time.Second consoleMaxEditImages = 3 - consoleMaxVideoImages = 1 + // Align with the gateway ceiling and official xAI video inputs: + // one start frame via image, or multiple references via reference_images. + consoleMaxVideoImages = mediadomain.MaxInputImages ) type consoleMediaUpstreamError struct { @@ -398,7 +400,7 @@ func (a *Adapter) GenerateVideo(ctx context.Context, request provider.VideoReque return provider.VideoResult{}, errors.New("Console 视频模型未注册") } if len(request.ReferenceURLs) > consoleMaxVideoImages { - return provider.VideoResult{}, fmt.Errorf("Console grok-imagine-video 最多支持 1 张首图,当前为 %d 张", len(request.ReferenceURLs)) + return provider.VideoResult{}, fmt.Errorf("Console grok-imagine-video 最多支持 %d 张参考图,当前为 %d 张", consoleMaxVideoImages, len(request.ReferenceURLs)) } if request.Duration < 1 || request.Duration > 15 { return provider.VideoResult{}, errors.New("duration 必须在 1 到 15 秒之间") @@ -418,16 +420,31 @@ func (a *Adapter) GenerateVideo(ctx context.Context, request provider.VideoReque if resolution := strings.TrimSpace(request.Resolution); resolution != "" { payload["resolution"] = resolution } - if len(request.ReferenceURLs) == 1 { + switch len(request.ReferenceURLs) { + case 0: + // text-to-video + case 1: value := strings.TrimSpace(request.ReferenceURLs[0]) if !validConsoleMediaInputURL(value, "image") { return provider.VideoResult{}, errors.New("视频首图必须是 HTTPS URL 或 image data URL") } payload["image"] = map[string]any{"url": value} + default: + references := make([]map[string]any, 0, len(request.ReferenceURLs)) + for _, rawURL := range request.ReferenceURLs { + value := strings.TrimSpace(rawURL) + if !validConsoleMediaInputURL(value, "image") { + return provider.VideoResult{}, errors.New("每张视频参考图都必须是 HTTPS URL 或 image data URL") + } + references = append(references, map[string]any{"url": value}) + } + payload["reference_images"] = references } if _, hasPrompt := payload["prompt"]; !hasPrompt { if _, hasImage := payload["image"]; !hasImage { - return provider.VideoResult{}, errors.New("文本生视频必须提供 prompt;图片生视频可以省略 prompt") + if _, hasReferences := payload["reference_images"]; !hasReferences { + return provider.VideoResult{}, errors.New("文本生视频必须提供 prompt;图片生视频可以省略 prompt") + } } } From c93cabbf714d9bdf7fa3de01fb5d05785f70f6fd Mon Sep 17 00:00:00 2001 From: lindahao Date: Sun, 9 Aug 2026 00:21:42 +0800 Subject: [PATCH 08/40] fix: expose Console grok-imagine-video-1.5 for free accounts Move video 1.5 onto the Console catalog/media path instead of Build free capability injection. Gateway now forwards the selected upstream video model, and Console GenerateVideo sends grok-imagine-video-1.5 upstream. Build free accounts again follow the original Super-only 1.5 rule. --- backend/internal/app/console_routes_test.go | 3 ++ backend/internal/application/gateway/video.go | 3 +- .../application/model/service_test.go | 18 +++++---- .../relational/model_repository.go | 2 +- .../internal/infra/provider/cli/adapter.go | 14 ++++--- .../infra/provider/cli/adapter_test.go | 30 +++++--------- .../infra/provider/console/catalog.go | 2 + .../infra/provider/console/console_test.go | 39 ++++++++++++++++++- .../internal/infra/provider/console/media.go | 14 ++++--- backend/internal/infra/provider/provider.go | 4 +- 10 files changed, 85 insertions(+), 44 deletions(-) diff --git a/backend/internal/app/console_routes_test.go b/backend/internal/app/console_routes_test.go index 01331b52..cc8245c7 100644 --- a/backend/internal/app/console_routes_test.go +++ b/backend/internal/app/console_routes_test.go @@ -40,4 +40,7 @@ func TestConsoleRoutesUseStableProviderNamespace(t *testing.T) { if !seen["Console/grok-imagine-video"]["video"] { t.Fatal("Console video route is missing") } + if !seen["Console/grok-imagine-video-1.5"]["video"] { + t.Fatal("Console video 1.5 route is missing") + } } diff --git a/backend/internal/application/gateway/video.go b/backend/internal/application/gateway/video.go index 50ede4ea..e0136c7c 100644 --- a/backend/internal/application/gateway/video.go +++ b/backend/internal/application/gateway/video.go @@ -340,7 +340,8 @@ func (s *Service) runVideoJob(parent context.Context, job media.Job, route model } lastProgress := job.Progress result, err := adapter.GenerateVideo(ctx, provider.VideoRequest{ - Credential: lease.Credential, Billing: lease.Billing, JobID: job.ID, Prompt: job.Prompt, Duration: job.Seconds, AspectRatio: job.Size, Resolution: job.Quality, + Credential: lease.Credential, Billing: lease.Billing, JobID: job.ID, Model: route.UpstreamModel, + Prompt: job.Prompt, Duration: job.Seconds, AspectRatio: job.Size, Resolution: job.Quality, ReferenceURLs: referenceURLs, Progress: func(value int) { value = min(99, max(1, value)) diff --git a/backend/internal/application/model/service_test.go b/backend/internal/application/model/service_test.go index 7000b87f..3bc6a3d8 100644 --- a/backend/internal/application/model/service_test.go +++ b/backend/internal/application/model/service_test.go @@ -260,8 +260,8 @@ func TestSyncAccountNormalizesBuildVideo15ByBillingSuper(t *testing.T) { assertSupports(superPrimary.ID, video15, true) assertSupports(superFallback.ID, video15, true) - assertSupports(freeAccount.ID, video15, true) - assertSupports(unknownAccount.ID, video15, true) + assertSupports(freeAccount.ID, video15, false) + assertSupports(unknownAccount.ID, video15, false) assertSupports(superPrimary.ID, "grok-4.5", true) assertSupports(superFallback.ID, "grok-code-fast-1", true) assertSupports(freeAccount.ID, "grok-4.5", true) @@ -374,12 +374,11 @@ type buildCapabilityNormalizerAdapter struct { } func (a *buildCapabilityNormalizerAdapter) NormalizeAccountModelCapabilities(models []string, billing *account.Billing, credential account.Credential) []string { - // Match cli.Adapter rules: Build OAuth adds Composer; all Build accounts - // ensure video 1.5 so Free can schedule grok-imagine-video-1.5. - _ = billing + // Match cli.Adapter rules: Build OAuth adds Composer; Super (paid or + // entitlement) ensures 1.5; otherwise remove video 1.5 exactly. const video15 = "grok-imagine-video-1.5" - buildAccount := credential.Provider == account.ProviderBuild - composer := buildAccount && credential.AuthType == account.AuthTypeOAuth + super := account.IsBuildSuper(credential, billing) + composer := credential.Provider == account.ProviderBuild && credential.AuthType == account.AuthTypeOAuth result := make([]string, 0, len(models)+2) seen := make(map[string]struct{}, len(models)+2) hasVideo15 := false @@ -391,12 +390,15 @@ func (a *buildCapabilityNormalizerAdapter) NormalizeAccountModelCapabilities(mod continue } if modelName == video15 { + if !super { + continue + } hasVideo15 = true } seen[modelName] = struct{}{} result = append(result, modelName) } - if buildAccount && !hasVideo15 { + if super && !hasVideo15 { result = append(result, video15) } if composer { diff --git a/backend/internal/infra/persistence/relational/model_repository.go b/backend/internal/infra/persistence/relational/model_repository.go index 2809acf3..c2a48529 100644 --- a/backend/internal/infra/persistence/relational/model_repository.go +++ b/backend/internal/infra/persistence/relational/model_repository.go @@ -752,7 +752,7 @@ func discoveredRouteDefaults(provider account.Provider, upstreamModel string) (s // Discovery only needs one existing managed capability to remain // idempotent and must never synthesize a Responses route. return upstreamModel, model.CapabilityImage - case "grok-imagine-video": + case "grok-imagine-video", "grok-imagine-video-1.5": return upstreamModel, model.CapabilityVideo default: return upstreamModel, model.CapabilityResponses diff --git a/backend/internal/infra/provider/cli/adapter.go b/backend/internal/infra/provider/cli/adapter.go index 5d637369..f172208c 100644 --- a/backend/internal/infra/provider/cli/adapter.go +++ b/backend/internal/infra/provider/cli/adapter.go @@ -619,12 +619,11 @@ func (a *Adapter) ListModels(ctx context.Context, credential account.Credential) // NormalizeAccountModelCapabilities normalizes capabilities that the OAuth // session contract exposes independently of the account's sparse /models list. // Composer is available to Build OAuth sessions even though the live catalog can -// return only grok-4.5. Build accounts always include video 1.5 so Free can use -// grok-imagine-video-1.5 on the primary Build path. BuildAPIFallback is ignored. +// return only grok-4.5. Super always includes video 1.5; Free and Unknown remove +// video 1.5 exactly. BuildAPIFallback is ignored. func (a *Adapter) NormalizeAccountModelCapabilities(models []string, billing *account.Billing, credential account.Credential) []string { - _ = billing - buildAccount := credential.Provider == account.ProviderBuild - composer := buildAccount && credential.AuthType == account.AuthTypeOAuth + super := account.IsBuildSuper(credential, billing) + composer := credential.Provider == account.ProviderBuild && credential.AuthType == account.AuthTypeOAuth result := make([]string, 0, len(models)+2) seen := make(map[string]struct{}, len(models)+2) hasVideo15 := false @@ -637,12 +636,15 @@ func (a *Adapter) NormalizeAccountModelCapabilities(models []string, billing *ac continue } if model == buildVideoModel { + if !super { + continue + } hasVideo15 = true } seen[model] = struct{}{} result = append(result, model) } - if buildAccount && !hasVideo15 { + if super && !hasVideo15 { result = append(result, buildVideoModel) } if composer { diff --git a/backend/internal/infra/provider/cli/adapter_test.go b/backend/internal/infra/provider/cli/adapter_test.go index 16227d65..f0cac0c2 100644 --- a/backend/internal/infra/provider/cli/adapter_test.go +++ b/backend/internal/infra/provider/cli/adapter_test.go @@ -566,7 +566,7 @@ func TestGetBillingUsesCreditsAndLiveSubscriptionTier(t *testing.T) { } } -func TestNormalizeAccountModelCapabilitiesBuildAddsVideo15(t *testing.T) { +func TestNormalizeAccountModelCapabilitiesSuperAddsVideo15(t *testing.T) { adapter := &Adapter{} build := account.Credential{Provider: account.ProviderBuild} // Super / paid: add 1.5 even when primary Build returns only grok-4.5. @@ -583,21 +583,16 @@ func TestNormalizeAccountModelCapabilitiesBuildAddsVideo15(t *testing.T) { if len(got) != 3 || got[0] != "grok-4.5" || got[1] != buildVideoModel || got[2] != "grok-code-fast-1" { t.Fatalf("super catalog = %#v", got) } - // Free: keep/add 1.5 so free Build accounts can use video generation. + // Free: remove 1.5 even when the catalog exposes it. got = adapter.NormalizeAccountModelCapabilities([]string{"grok-4.5", buildVideoModel}, &account.Billing{Used: 1, PlanName: "free"}, build) - if len(got) != 2 || got[0] != "grok-4.5" || got[1] != buildVideoModel { + if len(got) != 1 || got[0] != "grok-4.5" { t.Fatalf("free catalog = %#v", got) } - // Unknown (no Billing): still keep 1.5 for Build accounts. + // Unknown (no Billing): treat as Free and remove 1.5. got = adapter.NormalizeAccountModelCapabilities([]string{buildVideoModel, "grok-4.5"}, nil, build) - if len(got) != 2 || got[0] != buildVideoModel || got[1] != "grok-4.5" { + if len(got) != 1 || got[0] != "grok-4.5" { t.Fatalf("unknown catalog = %#v", got) } - // Free catalog without 1.5: inject it. - got = adapter.NormalizeAccountModelCapabilities([]string{"grok-4.5"}, &account.Billing{PlanName: "free"}, build) - if len(got) != 2 || got[0] != "grok-4.5" || got[1] != buildVideoModel { - t.Fatalf("free inject catalog = %#v", got) - } // Do not depend on BuildAPIFallback; an empty catalog with Billing Super adds only 1.5. got = adapter.NormalizeAccountModelCapabilities(nil, &account.Billing{PlanName: "SuperGrok", CreditUsagePercent: 1}, build) if len(got) != 1 || got[0] != buildVideoModel { @@ -615,11 +610,11 @@ func TestNormalizeAccountModelCapabilitiesAddsComposerOnlyForBuildOAuth(t *testi adapter := &Adapter{} oauth := account.Credential{Provider: account.ProviderBuild, AuthType: account.AuthTypeOAuth} got := adapter.NormalizeAccountModelCapabilities([]string{"grok-4.5"}, &account.Billing{PlanName: "free"}, oauth) - if len(got) != 3 || got[0] != "grok-4.5" || got[1] != buildVideoModel || got[2] != modeldomain.GrokComposer25Fast { + if len(got) != 2 || got[0] != "grok-4.5" || got[1] != modeldomain.GrokComposer25Fast { t.Fatalf("OAuth Free capabilities = %#v", got) } got = adapter.NormalizeAccountModelCapabilities([]string{"grok-4.5", modeldomain.GrokComposer25Fast, modeldomain.GrokComposer25Fast}, nil, oauth) - if len(got) != 3 || got[0] != "grok-4.5" || got[1] != modeldomain.GrokComposer25Fast || got[2] != buildVideoModel { + if len(got) != 2 || got[0] != "grok-4.5" || got[1] != modeldomain.GrokComposer25Fast { t.Fatalf("Composer capability was not deduplicated: %#v", got) } for _, credential := range []account.Credential{ @@ -627,15 +622,8 @@ func TestNormalizeAccountModelCapabilitiesAddsComposerOnlyForBuildOAuth(t *testi {Provider: account.ProviderWeb, AuthType: account.AuthTypeOAuth}, } { got = adapter.NormalizeAccountModelCapabilities([]string{"grok-4.5"}, nil, credential) - switch credential.Provider { - case account.ProviderBuild: - if len(got) != 2 || got[0] != "grok-4.5" || got[1] != buildVideoModel { - t.Fatalf("Build SSO capabilities = %#v", got) - } - default: - if len(got) != 1 || got[0] != "grok-4.5" { - t.Fatalf("Composer leaked outside Build OAuth for %#v: %#v", credential, got) - } + if len(got) != 1 || got[0] != "grok-4.5" { + t.Fatalf("Composer leaked outside Build OAuth for %#v: %#v", credential, got) } } } diff --git a/backend/internal/infra/provider/console/catalog.go b/backend/internal/infra/provider/console/catalog.go index 3715bd1b..063d5375 100644 --- a/backend/internal/infra/provider/console/catalog.go +++ b/backend/internal/infra/provider/console/catalog.go @@ -38,6 +38,8 @@ var mediaCatalog = []struct { {PublicID: "grok-imagine-image-quality", UpstreamModel: "grok-imagine-image-quality", Capabilities: []modeldomain.Capability{modeldomain.CapabilityImage, modeldomain.CapabilityImageEdit}}, {PublicID: "grok-imagine-image", UpstreamModel: "grok-imagine-image", Capabilities: []modeldomain.Capability{modeldomain.CapabilityImage, modeldomain.CapabilityImageEdit}}, {PublicID: "grok-imagine-video", UpstreamModel: "grok-imagine-video", Capabilities: []modeldomain.Capability{modeldomain.CapabilityVideo}}, + // Free Console accounts can use the 1.5 video model on the official Console media API. + {PublicID: "grok-imagine-video-1.5", UpstreamModel: "grok-imagine-video-1.5", Capabilities: []modeldomain.Capability{modeldomain.CapabilityVideo}}, } // Effort-suffixed aliases only include levels each Provider/model combination diff --git a/backend/internal/infra/provider/console/console_test.go b/backend/internal/infra/provider/console/console_test.go index 23df3ab8..91a033d9 100644 --- a/backend/internal/infra/provider/console/console_test.go +++ b/backend/internal/infra/provider/console/console_test.go @@ -52,6 +52,7 @@ func TestCatalogContainsAllConsoleModelsAndAliases(t *testing.T) { {publicID: "Console/grok-imagine-image", capability: modeldomain.CapabilityImage}: "grok-imagine-image", {publicID: "Console/grok-imagine-image", capability: modeldomain.CapabilityImageEdit}: "grok-imagine-image", {publicID: "Console/grok-imagine-video", capability: modeldomain.CapabilityVideo}: "grok-imagine-video", + {publicID: "Console/grok-imagine-video-1.5", capability: modeldomain.CapabilityVideo}: "grok-imagine-video-1.5", } routes := Routes() if len(routes) != len(expected) { @@ -91,7 +92,7 @@ func TestCatalogContainsAllConsoleModelsAndAliases(t *testing.T) { adapter := NewAdapter(Config{}, nil, nil, nil) for model, want := range map[string]string{ "grok-4.5": QuotaMode, "grok-imagine-image-quality": QuotaModeImage, - "grok-imagine-image": QuotaModeImage, "grok-imagine-video": QuotaModeVideo, + "grok-imagine-image": QuotaModeImage, "grok-imagine-video": QuotaModeVideo, "grok-imagine-video-1.5": QuotaModeVideo, } { if got := adapter.QuotaMode(model); got != want { t.Fatalf("QuotaMode(%q) = %q, want %q", model, got, want) @@ -1331,6 +1332,42 @@ func TestConsoleVideoRejectsTooManyReferenceImages(t *testing.T) { } } +func TestConsoleVideoUsesImagineVideo15Model(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) { + if serveTestDPoPToken(t, writer, request) { + return + } + verifyTestDPoPProof(t, request) + writer.Header().Set("Content-Type", "application/json") + switch { + case request.Method == http.MethodPost && request.URL.Path == "/v1/videos/generations": + var payload map[string]any + if err := json.NewDecoder(request.Body).Decode(&payload); err != nil { + t.Error(err) + } + if payload["model"] != "grok-imagine-video-1.5" { + t.Errorf("video model = %#v", payload["model"]) + } + _, _ = writer.Write([]byte(`{"request_id":"upstream-video-15"}`)) + case request.Method == http.MethodGet && request.URL.Path == "/v1/videos/upstream-video-15": + _, _ = writer.Write([]byte(`{"status":"done","progress":100,"video":{"url":"https://vidgen.x.ai/result-15.mp4"}}`)) + default: + http.NotFound(writer, request) + } + })) + t.Cleanup(server.Close) + adapter, credential := newConsoleTestAdapter(t, server.URL) + result, err := adapter.GenerateVideo(context.Background(), provider.VideoRequest{ + Credential: credential, Model: "grok-imagine-video-1.5", Prompt: "animate", Duration: 6, AspectRatio: "16:9", Resolution: "720p", + }) + if err != nil { + t.Fatal(err) + } + if result.URL != "https://vidgen.x.ai/result-15.mp4" { + t.Fatalf("video result = %#v", result) + } +} + func TestParseConsoleVideoStatusRejectsUnknownState(t *testing.T) { if _, _, err := parseConsoleVideoStatus([]byte(`{"status":"mystery"}`), nil); err == nil || !strings.Contains(err.Error(), "状态无效") { t.Fatalf("unknown status error = %v", err) diff --git a/backend/internal/infra/provider/console/media.go b/backend/internal/infra/provider/console/media.go index 1f0edb71..79885f98 100644 --- a/backend/internal/infra/provider/console/media.go +++ b/backend/internal/infra/provider/console/media.go @@ -396,20 +396,24 @@ func trustedConsoleImageHost(host string) bool { } func (a *Adapter) GenerateVideo(ctx context.Context, request provider.VideoRequest) (provider.VideoResult, error) { - if !ResolveMedia("grok-imagine-video", modeldomain.CapabilityVideo) { - return provider.VideoResult{}, errors.New("Console 视频模型未注册") + modelName := strings.TrimSpace(request.Model) + if modelName == "" { + modelName = "grok-imagine-video" + } + if !ResolveMedia(modelName, modeldomain.CapabilityVideo) { + return provider.VideoResult{}, fmt.Errorf("Console 视频模型未注册: %s", modelName) } if len(request.ReferenceURLs) > consoleMaxVideoImages { - return provider.VideoResult{}, fmt.Errorf("Console grok-imagine-video 最多支持 %d 张参考图,当前为 %d 张", consoleMaxVideoImages, len(request.ReferenceURLs)) + return provider.VideoResult{}, fmt.Errorf("Console %s 最多支持 %d 张参考图,当前为 %d 张", modelName, consoleMaxVideoImages, len(request.ReferenceURLs)) } if request.Duration < 1 || request.Duration > 15 { return provider.VideoResult{}, errors.New("duration 必须在 1 到 15 秒之间") } if request.Resolution != "" && request.Resolution != "480p" && request.Resolution != "720p" { - return provider.VideoResult{}, errors.New("grok-imagine-video 仅支持 480p 或 720p") + return provider.VideoResult{}, fmt.Errorf("%s 仅支持 480p 或 720p", modelName) } payload := map[string]any{ - "model": "grok-imagine-video", "duration": request.Duration, + "model": modelName, "duration": request.Duration, } if prompt := strings.TrimSpace(request.Prompt); prompt != "" { payload["prompt"] = prompt diff --git a/backend/internal/infra/provider/provider.go b/backend/internal/infra/provider/provider.go index 358927b8..a1aa45dd 100644 --- a/backend/internal/infra/provider/provider.go +++ b/backend/internal/infra/provider/provider.go @@ -278,7 +278,9 @@ type VideoRequest struct { // Billing is used only to determine XAI eligibility in Build auto mode; nil means the account tier is unknown. Billing *account.Billing // JobID binds the local video job to XAI ZDR upload tickets and result assets. - JobID string + JobID string + // Model is the selected upstream video model when the Provider supports more than one. + Model string Prompt string Duration int AspectRatio string From d8d5c24d4988ef84291e013c03970ceee2e2c996 Mon Sep 17 00:00:00 2001 From: lindahao Date: Sun, 9 Aug 2026 15:56:46 +0800 Subject: [PATCH 09/40] fix: enable Web Image 2.0 quality mode for free accounts Grok Web now ships Image 2.0 as Quality Mode with a separate imagePro quota on basic accounts, so expose grok-imagine-image-quality-lite to basic tier instead of super-only. --- README.md | 2 +- README.zh-CN.md | 2 +- backend/internal/infra/provider/web/catalog.go | 4 +++- backend/internal/infra/provider/web/protocol_test.go | 6 +++++- 4 files changed, 10 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 38208957..e18835f6 100644 --- a/README.md +++ b/README.md @@ -258,7 +258,7 @@ Web uses a built-in catalog filtered by account tier; higher tiers inherit lower | `grok-chat-expert` | Conversation | Super | Chat Completions, Responses, Messages | | `grok-chat-heavy` | Conversation | Heavy | Chat Completions, Responses, Messages | | `grok-imagine-image-lite` | Image | Basic | Images Generations | -| `grok-imagine-image-quality-lite` | Image | Super | Images Generations | +| `grok-imagine-image-quality-lite` | Image | Basic | Images Generations | | `grok-imagine-image-edit` | Image Edit | Super | Images Edits | | `grok-imagine-video` | Video | Super | Videos | diff --git a/README.zh-CN.md b/README.zh-CN.md index 38aff70d..486c6deb 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -259,7 +259,7 @@ Web 使用内置目录并按账号等级过滤;更高等级继承低等级模 | `grok-chat-expert` | 对话 | Super | Chat Completions、Responses、Messages | | `grok-chat-heavy` | 对话 | Heavy | Chat Completions、Responses、Messages | | `grok-imagine-image-lite` | 图像 | Basic | Images Generations | -| `grok-imagine-image-quality-lite` | 图像 | Super | Images Generations | +| `grok-imagine-image-quality-lite` | 图像 | Basic | Images Generations | | `grok-imagine-image-edit` | 图像编辑 | Super | Images Edits | | `grok-imagine-video` | 视频 | Super | Videos | diff --git a/backend/internal/infra/provider/web/catalog.go b/backend/internal/infra/provider/web/catalog.go index 83bf552c..5d1df9ea 100644 --- a/backend/internal/infra/provider/web/catalog.go +++ b/backend/internal/infra/provider/web/catalog.go @@ -20,7 +20,9 @@ var catalog = []ModelSpec{ {PublicID: "grok-chat-expert", UpstreamModel: "grok-chat-expert", Capability: modeldomain.CapabilityChat, Mode: "expert", MinimumTier: account.WebTierSuper}, {PublicID: "grok-chat-heavy", UpstreamModel: "grok-chat-heavy", Capability: modeldomain.CapabilityChat, Mode: "heavy", MinimumTier: account.WebTierHeavy}, {PublicID: "grok-imagine-image-lite", UpstreamModel: "grok-imagine-image", ProtocolModel: "imagine-lite", Capability: modeldomain.CapabilityImage, Mode: "fast", MinimumTier: account.WebTierBasic}, - {PublicID: "grok-imagine-image-quality-lite", UpstreamModel: "grok-imagine-image-quality", ProtocolModel: "imagine", Capability: modeldomain.CapabilityImage, MinimumTier: account.WebTierSuper}, + // Image 2.0 is Grok Web Quality Mode (enable_pro=true). Free/basic accounts + // now receive a separate imagePro quota and can call this path directly. + {PublicID: "grok-imagine-image-quality-lite", UpstreamModel: "grok-imagine-image-quality", ProtocolModel: "imagine", Capability: modeldomain.CapabilityImage, MinimumTier: account.WebTierBasic}, {PublicID: "grok-imagine-image-edit", UpstreamModel: "imagine-image-edit", Capability: modeldomain.CapabilityImageEdit, MinimumTier: account.WebTierSuper}, {PublicID: "grok-imagine-video", UpstreamModel: "grok-imagine-video", ProtocolModel: "imagine-video-gen", Capability: modeldomain.CapabilityVideo, MinimumTier: account.WebTierSuper}, } diff --git a/backend/internal/infra/provider/web/protocol_test.go b/backend/internal/infra/provider/web/protocol_test.go index 474a1be5..a7d63a01 100644 --- a/backend/internal/infra/provider/web/protocol_test.go +++ b/backend/internal/infra/provider/web/protocol_test.go @@ -1014,7 +1014,7 @@ func TestWebMediaUpstreamDiagnosticLogsStageHeadersWithoutBodyPreview(t *testing } } -func TestChatModelsUseLowestSufficientTierFirst(t *testing.T) { +func TestModelsUseLowestSufficientTierFirst(t *testing.T) { adapter := &Adapter{} tests := []struct { model string @@ -1024,6 +1024,10 @@ func TestChatModelsUseLowestSufficientTierFirst(t *testing.T) { {model: "grok-chat-auto", want: []account.WebTier{account.WebTierSuper, account.WebTierHeavy}}, {model: "grok-chat-expert", want: []account.WebTier{account.WebTierSuper, account.WebTierHeavy}}, {model: "grok-chat-heavy", want: []account.WebTier{account.WebTierHeavy}}, + {model: "grok-imagine-image", want: []account.WebTier{account.WebTierBasic, account.WebTierSuper, account.WebTierHeavy}}, + {model: "grok-imagine-image-quality", want: []account.WebTier{account.WebTierBasic, account.WebTierSuper, account.WebTierHeavy}}, + {model: "imagine-image-edit", want: []account.WebTier{account.WebTierSuper, account.WebTierHeavy}}, + {model: "grok-imagine-video", want: []account.WebTier{account.WebTierSuper, account.WebTierHeavy}}, } for _, test := range tests { got := adapter.TierOrder(test.model) From 7b1a3e14a5a32d02df1445c75362b20b741d01ec Mon Sep 17 00:00:00 2001 From: lindahao Date: Mon, 10 Aug 2026 13:47:43 +0800 Subject: [PATCH 10/40] fix: rename Web image models to 2.0 and expose edit capabilities Replace the ambiguous -lite public names with grok-imagine-image-2.0 and grok-imagine-image-quality-2.0, and register image_edit routes so the admin model list shows edit badges like Console. --- README.md | 4 +- README.zh-CN.md | 4 +- .../application/gateway/service_test.go | 14 +++---- .../model_capability_repository_test.go | 12 +++--- .../relational/model_repository.go | 4 +- .../internal/infra/provider/web/adapter.go | 6 ++- .../internal/infra/provider/web/catalog.go | 13 ++++-- backend/internal/infra/provider/web/chat.go | 2 +- backend/internal/infra/provider/web/image.go | 4 +- .../infra/provider/web/protocol_test.go | 41 ++++++++++++------- .../http/inference/model_list_test.go | 4 +- frontend/src/features/docs/api-docs-page.tsx | 2 +- frontend/src/shared/i18n/index.ts | 4 +- 13 files changed, 68 insertions(+), 46 deletions(-) diff --git a/README.md b/README.md index e18835f6..62b31003 100644 --- a/README.md +++ b/README.md @@ -257,8 +257,8 @@ Web uses a built-in catalog filtered by account tier; higher tiers inherit lower | `grok-chat-auto` | Conversation | Super | Chat Completions, Responses, Messages | | `grok-chat-expert` | Conversation | Super | Chat Completions, Responses, Messages | | `grok-chat-heavy` | Conversation | Heavy | Chat Completions, Responses, Messages | -| `grok-imagine-image-lite` | Image | Basic | Images Generations | -| `grok-imagine-image-quality-lite` | Image | Basic | Images Generations | +| `grok-imagine-image-2.0` | Image, Image Edit | Basic | Images Generations, Images Edits | +| `grok-imagine-image-quality-2.0` | Image, Image Edit | Basic | Images Generations, Images Edits | | `grok-imagine-image-edit` | Image Edit | Super | Images Edits | | `grok-imagine-video` | Video | Super | Videos | diff --git a/README.zh-CN.md b/README.zh-CN.md index 486c6deb..cd97bfd6 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -258,8 +258,8 @@ Web 使用内置目录并按账号等级过滤;更高等级继承低等级模 | `grok-chat-auto` | 对话 | Super | Chat Completions、Responses、Messages | | `grok-chat-expert` | 对话 | Super | Chat Completions、Responses、Messages | | `grok-chat-heavy` | 对话 | Heavy | Chat Completions、Responses、Messages | -| `grok-imagine-image-lite` | 图像 | Basic | Images Generations | -| `grok-imagine-image-quality-lite` | 图像 | Basic | Images Generations | +| `grok-imagine-image-2.0` | 图像、图像编辑 | Basic | Images Generations、Images Edits | +| `grok-imagine-image-quality-2.0` | 图像、图像编辑 | Basic | Images Generations、Images Edits | | `grok-imagine-image-edit` | 图像编辑 | Super | Images Edits | | `grok-imagine-video` | 视频 | Super | Videos | diff --git a/backend/internal/application/gateway/service_test.go b/backend/internal/application/gateway/service_test.go index e1b29c9d..d24c4d70 100644 --- a/backend/internal/application/gateway/service_test.go +++ b/backend/internal/application/gateway/service_test.go @@ -1863,8 +1863,8 @@ func TestImageStreamPropagatesWithoutTouchingChatQuota(t *testing.T) { t.Fatal(err) } if err := modelRepo.UpsertRoutes(ctx, []modeldomain.Route{ - {PublicID: "grok-imagine-image-quality-lite", Provider: account.ProviderWeb, UpstreamModel: "grok-imagine-image-quality", Capability: modeldomain.CapabilityImage, Enabled: true}, - {PublicID: "grok-imagine-image-lite", Provider: account.ProviderWeb, UpstreamModel: "grok-imagine-image", Capability: modeldomain.CapabilityImage, Enabled: true}, + {PublicID: "grok-imagine-image-quality-2.0", Provider: account.ProviderWeb, UpstreamModel: "grok-imagine-image-quality", Capability: modeldomain.CapabilityImage, Enabled: true}, + {PublicID: "grok-imagine-image-2.0", Provider: account.ProviderWeb, UpstreamModel: "grok-imagine-image", Capability: modeldomain.CapabilityImage, Enabled: true}, {PublicID: "grok-imagine-image-edit", Provider: account.ProviderWeb, UpstreamModel: "grok-imagine-image-edit", Capability: modeldomain.CapabilityImageEdit, Enabled: true}, }); err != nil { t.Fatal(err) @@ -1888,7 +1888,7 @@ func TestImageStreamPropagatesWithoutTouchingChatQuota(t *testing.T) { service := NewService(modelRepo, auditRepo, accountService, clientkeyapp.NewService(keyRepo, nil, nil, 60, 4, nil), registry, selector, responseRepo, 1) result, err := service.GenerateImage(ctx, ImageGenerationInput{ - RequestID: "req-image-stream", ClientKey: key, PublicModel: "grok-imagine-image-quality-lite", + RequestID: "req-image-stream", ClientKey: key, PublicModel: "grok-imagine-image-quality-2.0", Prompt: "test", Count: 1, Resolution: "1k", ResponseFormat: "url", Streaming: true, PartialImages: 1, }) if err != nil { @@ -1928,7 +1928,7 @@ func TestImageStreamPropagatesWithoutTouchingChatQuota(t *testing.T) { } liteResult, err := service.GenerateImage(ctx, ImageGenerationInput{ - RequestID: "req-image-lite", ClientKey: key, PublicModel: "grok-imagine-image-lite", + RequestID: "req-image-lite", ClientKey: key, PublicModel: "grok-imagine-image-2.0", Prompt: "test", Count: 1, ResponseFormat: "url", }) if err != nil { @@ -1967,8 +1967,8 @@ func TestImageStreamPropagatesWithoutTouchingChatQuota(t *testing.T) { } chatResult, err := service.CreateChatCompletion(ctx, Input{ - RequestID: "req-image-lite-chat", ClientKey: key, PublicModel: "grok-imagine-image-lite", - Body: []byte(`{"model":"grok-imagine-image-lite","messages":[{"role":"user","content":"draw"}],"image_config":{"n":3}}`), + RequestID: "req-image-lite-chat", ClientKey: key, PublicModel: "grok-imagine-image-2.0", + Body: []byte(`{"model":"grok-imagine-image-2.0","messages":[{"role":"user","content":"draw"}],"image_config":{"n":3}}`), }) if err != nil { t.Fatal(err) @@ -2022,7 +2022,7 @@ func TestImageStreamPropagatesWithoutTouchingChatQuota(t *testing.T) { attemptsBeforeFailure := len(adapter.Attempts()) adapter.FailWithEgress(infraegress.NewManager(relational.NewEgressRepository(database), testCipher(t))) if _, err := service.GenerateImage(ctx, ImageGenerationInput{ - RequestID: "req-image-failed", ClientKey: key, PublicModel: "grok-imagine-image-quality-lite", + RequestID: "req-image-failed", ClientKey: key, PublicModel: "grok-imagine-image-quality-2.0", Prompt: "test", Count: 1, Resolution: "1k", ResponseFormat: "url", }); err == nil { t.Fatal("expected image transport failure") diff --git a/backend/internal/infra/persistence/relational/model_capability_repository_test.go b/backend/internal/infra/persistence/relational/model_capability_repository_test.go index 5e1d4e9a..e5284183 100644 --- a/backend/internal/infra/persistence/relational/model_capability_repository_test.go +++ b/backend/internal/infra/persistence/relational/model_capability_repository_test.go @@ -571,8 +571,8 @@ func TestReplaceProviderRoutesRenamesWebImagePublicIDs(t *testing.T) { t.Fatal(err) } if err := repo.ReplaceProviderRoutes(ctx, account.ProviderWeb, []model.Route{ - {PublicID: "grok-imagine-image-lite", Provider: account.ProviderWeb, UpstreamModel: "grok-imagine-image", Capability: model.CapabilityImage, Enabled: true}, - {PublicID: "grok-imagine-image-quality-lite", Provider: account.ProviderWeb, UpstreamModel: "grok-imagine-image-quality", Capability: model.CapabilityImage, Enabled: true}, + {PublicID: "grok-imagine-image-2.0", Provider: account.ProviderWeb, UpstreamModel: "grok-imagine-image", Capability: model.CapabilityImage, Enabled: true}, + {PublicID: "grok-imagine-image-quality-2.0", Provider: account.ProviderWeb, UpstreamModel: "grok-imagine-image-quality", Capability: model.CapabilityImage, Enabled: true}, }); err != nil { t.Fatal(err) } @@ -580,7 +580,7 @@ func TestReplaceProviderRoutesRenamesWebImagePublicIDs(t *testing.T) { if err := database.db.WithContext(ctx).Where("provider = ?", account.ProviderWeb).Order("upstream_model ASC").Find(&after).Error; err != nil { t.Fatal(err) } - if len(after) != 2 || after[0].PublicID != "Web/grok-imagine-image-lite" || after[1].PublicID != "Web/grok-imagine-image-quality-lite" { + if len(after) != 2 || after[0].PublicID != "Web/grok-imagine-image-2.0" || after[1].PublicID != "Web/grok-imagine-image-quality-2.0" { t.Fatalf("renamed routes = %#v", after) } beforeIDs := make(map[string]uint64, len(before)) @@ -747,13 +747,13 @@ func TestWebRediscoveryRestoresCatalogRouteDefaults(t *testing.T) { } } -func TestWebImageRediscoveryUsesLitePublicNames(t *testing.T) { +func TestWebImageRediscoveryUsesVersionedPublicNames(t *testing.T) { ctx := context.Background() database := openTestDatabase(t) repo := NewModelRepository(database) tests := map[string]string{ - "grok-imagine-image": "Web/grok-imagine-image-lite", - "grok-imagine-image-quality": "Web/grok-imagine-image-quality-lite", + "grok-imagine-image": "Web/grok-imagine-image-2.0", + "grok-imagine-image-quality": "Web/grok-imagine-image-quality-2.0", } for upstreamModel, publicID := range tests { if err := repo.UpsertDiscovered(ctx, account.ProviderWeb, []string{upstreamModel}); err != nil { diff --git a/backend/internal/infra/persistence/relational/model_repository.go b/backend/internal/infra/persistence/relational/model_repository.go index c2a48529..aed777a8 100644 --- a/backend/internal/infra/persistence/relational/model_repository.go +++ b/backend/internal/infra/persistence/relational/model_repository.go @@ -730,9 +730,9 @@ func discoveredRouteDefaults(provider account.Provider, upstreamModel string) (s case account.ProviderWeb: switch upstreamModel { case "grok-imagine-image": - return "grok-imagine-image-lite", model.CapabilityImage + return "grok-imagine-image-2.0", model.CapabilityImage case "grok-imagine-image-quality": - return "grok-imagine-image-quality-lite", model.CapabilityImage + return "grok-imagine-image-quality-2.0", model.CapabilityImage case "imagine-image-edit": return "grok-imagine-image-edit", model.CapabilityImageEdit case "grok-imagine-video": diff --git a/backend/internal/infra/provider/web/adapter.go b/backend/internal/infra/provider/web/adapter.go index 0d39acc9..949a2e4f 100644 --- a/backend/internal/infra/provider/web/adapter.go +++ b/backend/internal/infra/provider/web/adapter.go @@ -136,11 +136,15 @@ func (a *Adapter) PricingModel(upstreamModel string) string { if spec.Capability == modeldomain.CapabilityChat { return "grok-4.5" } - // Public Web image names carry the -lite suffix to distinguish them from + // Public Web image names use the -2.0 suffix to distinguish them from // Console routes. Billing continues to use the upstream xAI model name. if spec.Capability == modeldomain.CapabilityImage { return spec.UpstreamModel } + // Dedicated Web edit upstream keeps a stable billing name. + if spec.Capability == modeldomain.CapabilityImageEdit { + return "grok-imagine-image-edit" + } return spec.PublicID } return upstreamModel diff --git a/backend/internal/infra/provider/web/catalog.go b/backend/internal/infra/provider/web/catalog.go index 5d1df9ea..4880ab8a 100644 --- a/backend/internal/infra/provider/web/catalog.go +++ b/backend/internal/infra/provider/web/catalog.go @@ -19,10 +19,15 @@ var catalog = []ModelSpec{ {PublicID: "grok-chat-auto", UpstreamModel: "grok-chat-auto", Capability: modeldomain.CapabilityChat, Mode: "auto", MinimumTier: account.WebTierSuper}, {PublicID: "grok-chat-expert", UpstreamModel: "grok-chat-expert", Capability: modeldomain.CapabilityChat, Mode: "expert", MinimumTier: account.WebTierSuper}, {PublicID: "grok-chat-heavy", UpstreamModel: "grok-chat-heavy", Capability: modeldomain.CapabilityChat, Mode: "heavy", MinimumTier: account.WebTierHeavy}, - {PublicID: "grok-imagine-image-lite", UpstreamModel: "grok-imagine-image", ProtocolModel: "imagine-lite", Capability: modeldomain.CapabilityImage, Mode: "fast", MinimumTier: account.WebTierBasic}, - // Image 2.0 is Grok Web Quality Mode (enable_pro=true). Free/basic accounts - // now receive a separate imagePro quota and can call this path directly. - {PublicID: "grok-imagine-image-quality-lite", UpstreamModel: "grok-imagine-image-quality", ProtocolModel: "imagine", Capability: modeldomain.CapabilityImage, MinimumTier: account.WebTierBasic}, + // Image 2.0 public names distinguish Web routes from Console without the ambiguous -lite suffix. + // Generation and edit share the same upstream so admin grouping shows both capability badges, + // matching Console image models. The dedicated edit model below keeps the Super-only path. + {PublicID: "grok-imagine-image-2.0", UpstreamModel: "grok-imagine-image", ProtocolModel: "imagine-lite", Capability: modeldomain.CapabilityImage, Mode: "fast", MinimumTier: account.WebTierBasic}, + {PublicID: "grok-imagine-image-2.0", UpstreamModel: "grok-imagine-image", ProtocolModel: "imagine-lite", Capability: modeldomain.CapabilityImageEdit, MinimumTier: account.WebTierBasic}, + // Quality Mode (enable_pro=true) is Grok Web Image 2.0. Free/basic accounts now + // receive a separate imagePro quota and can call generation directly. + {PublicID: "grok-imagine-image-quality-2.0", UpstreamModel: "grok-imagine-image-quality", ProtocolModel: "imagine", Capability: modeldomain.CapabilityImage, MinimumTier: account.WebTierBasic}, + {PublicID: "grok-imagine-image-quality-2.0", UpstreamModel: "grok-imagine-image-quality", ProtocolModel: "imagine", Capability: modeldomain.CapabilityImageEdit, MinimumTier: account.WebTierBasic}, {PublicID: "grok-imagine-image-edit", UpstreamModel: "imagine-image-edit", Capability: modeldomain.CapabilityImageEdit, MinimumTier: account.WebTierSuper}, {PublicID: "grok-imagine-video", UpstreamModel: "grok-imagine-video", ProtocolModel: "imagine-video-gen", Capability: modeldomain.CapabilityVideo, MinimumTier: account.WebTierSuper}, } diff --git a/backend/internal/infra/provider/web/chat.go b/backend/internal/infra/provider/web/chat.go index 9549be88..a2477352 100644 --- a/backend/internal/infra/provider/web/chat.go +++ b/backend/internal/infra/provider/web/chat.go @@ -224,7 +224,7 @@ func (a *Adapter) ForwardResponse(ctx context.Context, request provider.Response spec, ok := Resolve(request.Model) if ok && spec.ProtocolModel == "imagine-lite" && request.Operation == "chat" { if len(tools.ResponseTools) > 0 { - return invalidImageRequest("grok-imagine-image-lite 不支持 tools") + return invalidImageRequest("grok-imagine-image-2.0 不支持 tools") } return a.forwardLiteChatCompletion(ctx, request, input, normalized, spec) } diff --git a/backend/internal/infra/provider/web/image.go b/backend/internal/infra/provider/web/image.go index 45ce0a79..39c604bb 100644 --- a/backend/internal/infra/provider/web/image.go +++ b/backend/internal/infra/provider/web/image.go @@ -304,7 +304,7 @@ func (a *Adapter) GenerateImage(ctx context.Context, request provider.ImageGener } if protocolModel == "imagine-lite" { if request.Streaming { - return invalidImageRequest("grok-imagine-image-lite 不支持 stream") + return invalidImageRequest("grok-imagine-image-2.0 不支持 stream") } if count > maxGeneratedImages { return invalidImageRequest("n 不能超过 10") @@ -469,7 +469,7 @@ func (a *Adapter) generateLiteImageURL(ctx context.Context, credential account.C func (a *Adapter) forwardLiteChatCompletion(ctx context.Context, request provider.ResponseResourceRequest, input openAIRequest, normalized normalizedChatInput, spec ModelSpec) (*provider.Response, error) { if len(normalized.Attachments) > 0 { - return invalidImageRequest("grok-imagine-image-lite 只支持纯文本生图;附件请使用对应的图片编辑或对话模型") + return invalidImageRequest("grok-imagine-image-2.0 只支持纯文本生图;附件请使用对应的图片编辑或对话模型") } count := 1 format := "url" diff --git a/backend/internal/infra/provider/web/protocol_test.go b/backend/internal/infra/provider/web/protocol_test.go index a7d63a01..d6d3fe00 100644 --- a/backend/internal/infra/provider/web/protocol_test.go +++ b/backend/internal/infra/provider/web/protocol_test.go @@ -37,47 +37,60 @@ import ( func TestCatalogMatchesSupportedSurface(t *testing.T) { values := Catalog() - if len(values) != 8 { + if len(values) != 10 { t.Fatalf("catalog size = %d", len(values)) } publicIDs := make(map[string]struct{}, len(values)) - upstreamIDs := make(map[string]struct{}, len(values)) + routeKeys := make(map[string]struct{}, len(values)) for _, value := range values { - if _, exists := publicIDs[value.PublicID]; exists { - t.Fatalf("duplicate public model: %s", value.PublicID) - } - if _, exists := upstreamIDs[value.UpstreamModel]; exists { - t.Fatalf("duplicate route upstream model: %s", value.UpstreamModel) + routeKey := value.PublicID + "|" + string(value.Capability) + if _, exists := routeKeys[routeKey]; exists { + t.Fatalf("duplicate public model capability: %s", routeKey) } + routeKeys[routeKey] = struct{}{} publicIDs[value.PublicID] = struct{}{} - upstreamIDs[value.UpstreamModel] = struct{}{} } - for _, required := range []string{"grok-chat-fast", "grok-chat-auto", "grok-chat-expert", "grok-chat-heavy", "grok-imagine-image-lite", "grok-imagine-image-quality-lite", "grok-imagine-image-edit", "grok-imagine-video"} { + for _, required := range []string{"grok-chat-fast", "grok-chat-auto", "grok-chat-expert", "grok-chat-heavy", "grok-imagine-image-2.0", "grok-imagine-image-quality-2.0", "grok-imagine-image-edit", "grok-imagine-video"} { if _, exists := publicIDs[required]; !exists { t.Fatalf("missing supported model: %s", required) } } - for _, removed := range []string{"grok-imagine-image", "grok-imagine-image-quality", "grok-imagine-image-speed", "grok-imagine-image-pro"} { + for _, required := range []string{ + "grok-imagine-image-2.0|image", + "grok-imagine-image-2.0|image_edit", + "grok-imagine-image-quality-2.0|image", + "grok-imagine-image-quality-2.0|image_edit", + "grok-imagine-image-edit|image_edit", + } { + if _, exists := routeKeys[required]; !exists { + t.Fatalf("missing supported route: %s", required) + } + } + for _, removed := range []string{"grok-imagine-image", "grok-imagine-image-quality", "grok-imagine-image-lite", "grok-imagine-image-quality-lite", "grok-imagine-image-speed", "grok-imagine-image-pro"} { if _, exists := publicIDs[removed]; exists { t.Fatalf("obsolete image model remains: %s", removed) } } } -func TestWebImageLitePublicNamesPreserveGatewayModels(t *testing.T) { +func TestWebImagePublicNamesPreserveGatewayModels(t *testing.T) { tests := map[string]string{ - "grok-imagine-image": "grok-imagine-image-lite", - "grok-imagine-image-quality": "grok-imagine-image-quality-lite", + "grok-imagine-image": "grok-imagine-image-2.0", + "grok-imagine-image-quality": "grok-imagine-image-quality-2.0", } for upstreamModel, publicID := range tests { spec, ok := Resolve(upstreamModel) if !ok { t.Fatalf("missing upstream model %s", upstreamModel) } - if spec.PublicID != publicID || spec.UpstreamModel != upstreamModel { + if spec.PublicID != publicID || spec.UpstreamModel != upstreamModel || spec.Capability != modeldomain.CapabilityImage { t.Fatalf("resolved %s as %#v", upstreamModel, spec) } } + spec, ok := Resolve("imagine-image-edit") + if !ok || spec.PublicID != "grok-imagine-image-edit" || spec.Capability != modeldomain.CapabilityImageEdit { + t.Fatalf("edit upstream resolved as %#v ok=%v", spec, ok) + } } func TestParseMediaPostResponsePreservesStatusAndPostID(t *testing.T) { diff --git a/backend/internal/transport/http/inference/model_list_test.go b/backend/internal/transport/http/inference/model_list_test.go index 8af1ac50..f3f2451c 100644 --- a/backend/internal/transport/http/inference/model_list_test.go +++ b/backend/internal/transport/http/inference/model_list_test.go @@ -142,7 +142,7 @@ func TestCodexCatalogHidesMediaModels(t *testing.T) { now := time.Unix(100, 0).UTC() routes := []modeldomain.Route{ {PublicID: "Build/grok-4.5", Provider: account.ProviderBuild, Capability: modeldomain.CapabilityResponses, CreatedAt: now}, - {PublicID: "Web/grok-imagine-image-lite", Provider: account.ProviderWeb, Capability: modeldomain.CapabilityImage, CreatedAt: now}, + {PublicID: "Web/grok-imagine-image-2.0", Provider: account.ProviderWeb, Capability: modeldomain.CapabilityImage, CreatedAt: now}, {PublicID: "Web/grok-imagine-video", Provider: account.ProviderWeb, Capability: modeldomain.CapabilityVideo, CreatedAt: now}, } catalog := newCodexModelCatalog(newModelListItems(routes)) @@ -155,7 +155,7 @@ func TestCodexCatalogHidesMediaModels(t *testing.T) { if entry.Visibility != "list" { t.Fatalf("visibility for %s = %q, want list", entry.Slug, entry.Visibility) } - case "grok-imagine-image-lite", "grok-imagine-video": + case "grok-imagine-image-2.0", "grok-imagine-video": if entry.Visibility != "hide" { t.Fatalf("visibility for %s = %q, want hide", entry.Slug, entry.Visibility) } diff --git a/frontend/src/features/docs/api-docs-page.tsx b/frontend/src/features/docs/api-docs-page.tsx index c5096f6d..a177a84a 100644 --- a/frontend/src/features/docs/api-docs-page.tsx +++ b/frontend/src/features/docs/api-docs-page.tsx @@ -233,7 +233,7 @@ function withExampleModel(response: Record, model: string): Rec } function fallbackModel(key: string): string { - if (key.startsWith("image/")) return key === "image/edits" ? "grok-imagine-image-edit" : "grok-imagine-image-lite"; + if (key.startsWith("image/")) return key === "image/edits" ? "grok-imagine-image-edit" : "grok-imagine-image-2.0"; if (key.startsWith("video/")) return "grok-imagine-video"; return "your-enabled-model"; } diff --git a/frontend/src/shared/i18n/index.ts b/frontend/src/shared/i18n/index.ts index bef6f887..f9f9639b 100644 --- a/frontend/src/shared/i18n/index.ts +++ b/frontend/src/shared/i18n/index.ts @@ -1063,7 +1063,7 @@ const resources = { noteMessagesAuth: "Messages 使用 x-api-key,并携带 anthropic-version: 2023-06-01。", noteMessagesEvents: "流式响应输出 Anthropic Messages 事件,不混用 OpenAI SSE 事件名。", noteMessagesLimits: "仅适配当前聊天模型共有的 Messages 能力,Provider 不支持的扩展字段会被拒绝。", - noteImageModels: "grok-imagine-image-lite 与 grok-imagine-image-quality-lite 使用统一图片接口,模型决定上游生成链路与计费。", + noteImageModels: "grok-imagine-image-2.0 与 grok-imagine-image-quality-2.0 使用统一图片接口,同时支持生成与编辑;模型决定上游链路与计费。", noteImageCount: "客户端按 n 获取结果;网关可使用 4、8、12 张上游批次,并只返回请求数量。", noteImageStorage: "生成结果统一归档到媒体存储;url 返回网关资源地址,b64_json 返回编码后的图片内容。", noteEditJSON: "图片编辑采用 JSON 请求体,不提供 multipart 兼容层。", @@ -1603,7 +1603,7 @@ const resources = { noteMessagesAuth: "Messages uses x-api-key with anthropic-version: 2023-06-01.", noteMessagesEvents: "Streaming emits Anthropic Messages events rather than OpenAI SSE event names.", noteMessagesLimits: "Only the common Messages capabilities of the current chat models are adapted; unsupported provider extensions are rejected.", - noteImageModels: "grok-imagine-image-lite and grok-imagine-image-quality-lite share this endpoint; the model selects the upstream path and pricing.", + noteImageModels: "grok-imagine-image-2.0 and grok-imagine-image-quality-2.0 share this endpoint for generation and edits; the model selects the upstream path and pricing.", noteImageCount: "Clients receive exactly n results. The gateway may use an upstream batch of 4, 8, or 12 and trim the response.", noteImageStorage: "Generated images are archived in media storage. url returns a gateway asset URL; b64_json returns encoded image data.", noteEditJSON: "Image edits use a JSON request body and do not provide a multipart compatibility layer.", From 4fe04ef623f64111e4ed1ffb5282f0167793720d Mon Sep 17 00:00:00 2001 From: lindahao Date: Wed, 12 Aug 2026 11:24:21 +0800 Subject: [PATCH 11/40] feat: add console image 2.0 and full voice surfaces Expose Console Imagine Image 2.0 aliases, TTS/STT/realtime/custom-voice gateway routes, and creative-console voice controls while keeping the existing web-image-2.0 customizations. --- backend/internal/app/console_routes_test.go | 10 +- backend/internal/application/gateway/voice.go | 638 +++++++++++++++ backend/internal/application/model/service.go | 8 +- backend/internal/domain/audit/audit.go | 4 + backend/internal/domain/model/model.go | 6 + .../relational/model_repository.go | 10 +- .../infra/provider/console/adapter.go | 3 + .../infra/provider/console/catalog.go | 12 +- .../infra/provider/console/console_test.go | 20 +- .../infra/provider/console/definition.go | 4 + .../internal/infra/provider/console/dpop.go | 22 +- .../internal/infra/provider/console/voice.go | 741 ++++++++++++++++++ backend/internal/infra/provider/definition.go | 9 +- .../provider/definition_contract_test.go | 4 +- backend/internal/infra/provider/provider.go | 245 ++++++ .../transport/http/inference/handler.go | 11 + .../transport/http/inference/voice_handler.go | 522 ++++++++++++ .../transport/http/middleware/body_memory.go | 8 + frontend/src/entities/model/model-api.ts | 6 +- frontend/src/entities/model/types.ts | 4 +- .../creative-console/creative-console-api.ts | 137 ++++ .../creative-console-page.tsx | 142 +++- frontend/src/features/models/models-page.tsx | 10 +- frontend/src/shared/i18n/index.ts | 38 +- 24 files changed, 2584 insertions(+), 30 deletions(-) create mode 100644 backend/internal/application/gateway/voice.go create mode 100644 backend/internal/infra/provider/console/voice.go create mode 100644 backend/internal/transport/http/inference/voice_handler.go diff --git a/backend/internal/app/console_routes_test.go b/backend/internal/app/console_routes_test.go index cc8245c7..566640cc 100644 --- a/backend/internal/app/console_routes_test.go +++ b/backend/internal/app/console_routes_test.go @@ -32,11 +32,19 @@ func TestConsoleRoutesUseStableProviderNamespace(t *testing.T) { if seen["Console/grok-4.3"] == nil { t.Fatal("canonical Console/grok-4.3 route is missing") } - for _, modelID := range []string{"Console/grok-imagine-image-quality", "Console/grok-imagine-image"} { + for _, modelID := range []string{"Console/grok-imagine-image-quality-2.0", "Console/grok-imagine-image-2.0"} { if !seen[modelID]["image"] || !seen[modelID]["image_edit"] { t.Fatalf("Console image route capabilities for %s = %#v", modelID, seen[modelID]) } } + for _, modelID := range []string{"Console/grok-voice-latest", "Console/grok-voice-think-fast-2.0", "Console/grok-voice-think-fast-1.0"} { + if !seen[modelID]["realtime"] || !seen[modelID]["tts"] { + t.Fatalf("Console voice route capabilities for %s = %#v", modelID, seen[modelID]) + } + } + if !seen["Console/grok-transcribe"]["stt"] { + t.Fatal("Console STT route is missing") + } if !seen["Console/grok-imagine-video"]["video"] { t.Fatal("Console video route is missing") } diff --git a/backend/internal/application/gateway/voice.go b/backend/internal/application/gateway/voice.go new file mode 100644 index 00000000..9b1a0566 --- /dev/null +++ b/backend/internal/application/gateway/voice.go @@ -0,0 +1,638 @@ +package gateway + +import ( + "bytes" + "context" + "encoding/base64" + "encoding/json" + "errors" + "fmt" + "io" + "net/http" + "strings" + "sync" + "time" + + accountdomain "github.com/chenyme/grok2api/backend/internal/domain/account" + "github.com/chenyme/grok2api/backend/internal/domain/audit" + "github.com/chenyme/grok2api/backend/internal/domain/clientkey" + modeldomain "github.com/chenyme/grok2api/backend/internal/domain/model" + infraegress "github.com/chenyme/grok2api/backend/internal/infra/egress" + "github.com/chenyme/grok2api/backend/internal/infra/provider" +) + +type TTSInput struct { + RequestID string + ClientKey clientkey.Key + PublicModel string + Text string + VoiceID string + Language string + OutputFormat provider.TTSOutputFormat + Speed float64 + OptimizeStreamingLatency int + TextNormalization bool + WithTimestamps bool +} + +type STTInput struct { + RequestID string + ClientKey clientkey.Key + PublicModel string + FileName string + FileMIME string + FileData []byte + URL string + AudioFormat string + SampleRate string + Language string + Format bool + Multichannel bool + Channels int + Diarize bool + KeyTerms []string + FillerWords bool + VADThreshold *float64 +} + +type RealtimeClientSecretInput struct { + RequestID string + ClientKey clientkey.Key + PublicModel string + ExpiresAfter int + SessionJSON []byte +} + +type VoiceListInput struct { + RequestID string + ClientKey clientkey.Key + PublicModel string +} + +type CustomVoiceCreateInput struct { + RequestID string + ClientKey clientkey.Key + PublicModel string + Name string + Language string + Gender string + Tone string + UseCase string + FileName string + FileMIME string + FileData []byte +} + +type CustomVoiceUpdateInput struct { + RequestID string + ClientKey clientkey.Key + PublicModel string + VoiceID string + Name *string + Language *string + Gender *string + Tone *string + UseCase *string +} + +type CustomVoiceIDInput struct { + RequestID string + ClientKey clientkey.Key + PublicModel string + VoiceID string +} + +type voiceProviderSupport func(accountdomain.Provider) bool + +func (s *Service) SynthesizeSpeech(ctx context.Context, input TTSInput) (*Result, error) { + return s.executeVoice(ctx, input.RequestID, input.ClientKey, input.PublicModel, audit.OperationTTS, modeldomain.CapabilityTTS, func(providerValue accountdomain.Provider) bool { + _, ok := s.providers.TTS(providerValue) + return ok + }, func(executionCtx context.Context, providerValue accountdomain.Provider, credential accountdomain.Credential, upstream string) (*provider.Response, error) { + adapter, ok := s.providers.TTS(providerValue) + if !ok { + return nil, ErrNoAvailableAccount + } + result, err := adapter.SynthesizeSpeech(executionCtx, provider.TTSRequest{ + Credential: credential, Model: upstream, Text: input.Text, VoiceID: input.VoiceID, Language: input.Language, + OutputFormat: input.OutputFormat, Speed: input.Speed, OptimizeStreamingLatency: input.OptimizeStreamingLatency, + TextNormalization: input.TextNormalization, WithTimestamps: input.WithTimestamps, + }) + if err != nil { + return voiceErrorResponse(err) + } + if result.JSONEnvelope || input.WithTimestamps { + payload := map[string]any{ + "audio": firstNonEmpty(result.Base64Audio, base64.StdEncoding.EncodeToString(result.Audio)), + "content_type": firstNonEmpty(result.ContentType, "audio/mpeg"), + "duration": result.Duration, + } + if result.Timestamps != nil { + times := make([]map[string]any, 0, len(result.Timestamps.GraphTimes)) + for _, item := range result.Timestamps.GraphTimes { + times = append(times, map[string]any{"start": item.Start, "end": item.End}) + } + payload["audio_timestamps"] = map[string]any{"graph_chars": result.Timestamps.GraphChars, "graph_times": times} + } + return jsonVoiceResponse(http.StatusOK, payload), nil + } + header := http.Header{} + header.Set("Content-Type", firstNonEmpty(result.ContentType, "audio/mpeg")) + header.Set("Content-Length", fmt.Sprintf("%d", len(result.Audio))) + return &provider.Response{ + StatusCode: http.StatusOK, + Status: fmt.Sprintf("%d %s", http.StatusOK, http.StatusText(http.StatusOK)), + Header: header, + Body: io.NopCloser(bytes.NewReader(result.Audio)), + QuotaUnits: 1, + }, nil + }) +} + +func (s *Service) ListTTSVoices(ctx context.Context, input VoiceListInput) (*Result, error) { + return s.executeVoice(ctx, input.RequestID, input.ClientKey, input.PublicModel, audit.OperationTTS, modeldomain.CapabilityTTS, func(providerValue accountdomain.Provider) bool { + _, ok := s.providers.TTS(providerValue) + return ok + }, func(executionCtx context.Context, providerValue accountdomain.Provider, credential accountdomain.Credential, _ string) (*provider.Response, error) { + adapter, ok := s.providers.TTS(providerValue) + if !ok { + return nil, ErrNoAvailableAccount + } + voices, err := adapter.ListTTSVoices(executionCtx, credential) + if err != nil { + return voiceErrorResponse(err) + } + items := make([]map[string]any, 0, len(voices)) + for _, voice := range voices { + item := map[string]any{"voice_id": voice.VoiceID, "name": voice.Name} + if voice.Language != "" { + item["language"] = voice.Language + } else { + item["language"] = nil + } + items = append(items, item) + } + return jsonVoiceResponse(http.StatusOK, map[string]any{"voices": items}), nil + }) +} + +func (s *Service) GetTTSVoice(ctx context.Context, input CustomVoiceIDInput) (*Result, error) { + return s.executeVoice(ctx, input.RequestID, input.ClientKey, input.PublicModel, audit.OperationTTS, modeldomain.CapabilityTTS, func(providerValue accountdomain.Provider) bool { + _, ok := s.providers.TTS(providerValue) + return ok + }, func(executionCtx context.Context, providerValue accountdomain.Provider, credential accountdomain.Credential, _ string) (*provider.Response, error) { + adapter, ok := s.providers.TTS(providerValue) + if !ok { + return nil, ErrNoAvailableAccount + } + voice, err := adapter.GetTTSVoice(executionCtx, credential, input.VoiceID) + if err != nil { + return voiceErrorResponse(err) + } + payload := map[string]any{"voice_id": voice.VoiceID, "name": voice.Name} + if voice.Language != "" { + payload["language"] = voice.Language + } else { + payload["language"] = nil + } + return jsonVoiceResponse(http.StatusOK, payload), nil + }) +} + +func (s *Service) TranscribeSpeech(ctx context.Context, input STTInput) (*Result, error) { + return s.executeVoice(ctx, input.RequestID, input.ClientKey, input.PublicModel, audit.OperationSTT, modeldomain.CapabilitySTT, func(providerValue accountdomain.Provider) bool { + _, ok := s.providers.STT(providerValue) + return ok + }, func(executionCtx context.Context, providerValue accountdomain.Provider, credential accountdomain.Credential, upstream string) (*provider.Response, error) { + adapter, ok := s.providers.STT(providerValue) + if !ok { + return nil, ErrNoAvailableAccount + } + result, err := adapter.TranscribeSpeech(executionCtx, provider.STTRequest{ + Credential: credential, Model: upstream, FileName: input.FileName, FileMIME: input.FileMIME, FileData: input.FileData, + URL: input.URL, AudioFormat: input.AudioFormat, SampleRate: input.SampleRate, Language: input.Language, Format: input.Format, + Multichannel: input.Multichannel, Channels: input.Channels, Diarize: input.Diarize, KeyTerms: input.KeyTerms, + FillerWords: input.FillerWords, VADThreshold: input.VADThreshold, + }) + if err != nil { + return voiceErrorResponse(err) + } + if len(result.RawJSON) > 0 { + header := http.Header{} + header.Set("Content-Type", "application/json") + header.Set("Content-Length", fmt.Sprintf("%d", len(result.RawJSON))) + return &provider.Response{StatusCode: http.StatusOK, Status: "200 OK", Header: header, Body: io.NopCloser(bytes.NewReader(result.RawJSON)), QuotaUnits: 1}, nil + } + payload := map[string]any{"text": result.Text, "language": result.Language, "duration": result.Duration} + if len(result.Words) > 0 { + words := make([]map[string]any, 0, len(result.Words)) + for _, word := range result.Words { + item := map[string]any{"text": word.Text, "start": word.Start, "end": word.End} + if word.Speaker != nil { + item["speaker"] = *word.Speaker + } + words = append(words, item) + } + payload["words"] = words + } + if len(result.Channels) > 0 { + channels := make([]map[string]any, 0, len(result.Channels)) + for _, channel := range result.Channels { + item := map[string]any{"index": channel.Index, "text": channel.Text} + if len(channel.Words) > 0 { + words := make([]map[string]any, 0, len(channel.Words)) + for _, word := range channel.Words { + wordItem := map[string]any{"text": word.Text, "start": word.Start, "end": word.End} + if word.Speaker != nil { + wordItem["speaker"] = *word.Speaker + } + words = append(words, wordItem) + } + item["words"] = words + } + channels = append(channels, item) + } + payload["channels"] = channels + } + return jsonVoiceResponse(http.StatusOK, payload), nil + }) +} + +func (s *Service) CreateRealtimeClientSecret(ctx context.Context, input RealtimeClientSecretInput) (*Result, error) { + return s.executeVoice(ctx, input.RequestID, input.ClientKey, input.PublicModel, audit.OperationRealtime, modeldomain.CapabilityRealtime, func(providerValue accountdomain.Provider) bool { + _, ok := s.providers.RealtimeVoice(providerValue) + return ok + }, func(executionCtx context.Context, providerValue accountdomain.Provider, credential accountdomain.Credential, upstream string) (*provider.Response, error) { + adapter, ok := s.providers.RealtimeVoice(providerValue) + if !ok { + return nil, ErrNoAvailableAccount + } + result, err := adapter.CreateRealtimeClientSecret(executionCtx, provider.RealtimeClientSecretRequest{ + Credential: credential, Model: firstNonEmpty(upstream, input.PublicModel), ExpiresAfter: input.ExpiresAfter, SessionJSON: input.SessionJSON, + }) + if err != nil { + return voiceErrorResponse(err) + } + if len(result.RawJSON) > 0 { + header := http.Header{} + header.Set("Content-Type", "application/json") + header.Set("Content-Length", fmt.Sprintf("%d", len(result.RawJSON))) + return &provider.Response{StatusCode: http.StatusOK, Status: "200 OK", Header: header, Body: io.NopCloser(bytes.NewReader(result.RawJSON)), QuotaUnits: 1}, nil + } + return jsonVoiceResponse(http.StatusOK, map[string]any{"value": result.Value, "expires_at": result.ExpiresAt}), nil + }) +} + +func (s *Service) CreateCustomVoice(ctx context.Context, input CustomVoiceCreateInput) (*Result, error) { + return s.executeVoice(ctx, input.RequestID, input.ClientKey, input.PublicModel, audit.OperationVoice, modeldomain.CapabilityTTS, func(providerValue accountdomain.Provider) bool { + _, ok := s.providers.CustomVoices(providerValue) + return ok + }, func(executionCtx context.Context, providerValue accountdomain.Provider, credential accountdomain.Credential, _ string) (*provider.Response, error) { + adapter, ok := s.providers.CustomVoices(providerValue) + if !ok { + return nil, ErrNoAvailableAccount + } + result, err := adapter.CreateCustomVoice(executionCtx, provider.CustomVoiceCreateRequest{ + Credential: credential, Name: input.Name, Language: input.Language, Gender: input.Gender, Tone: input.Tone, + UseCase: input.UseCase, FileName: input.FileName, FileMIME: input.FileMIME, FileData: input.FileData, + }) + if err != nil { + return voiceErrorResponse(err) + } + if len(result.RawJSON) > 0 { + header := http.Header{} + header.Set("Content-Type", "application/json") + header.Set("Content-Length", fmt.Sprintf("%d", len(result.RawJSON))) + return &provider.Response{StatusCode: http.StatusOK, Status: "200 OK", Header: header, Body: io.NopCloser(bytes.NewReader(result.RawJSON)), QuotaUnits: 1}, nil + } + return jsonVoiceResponse(http.StatusOK, customVoicePayload(result)), nil + }) +} + +func (s *Service) ListCustomVoices(ctx context.Context, input VoiceListInput, limit int, paginationToken string) (*Result, error) { + return s.executeVoice(ctx, input.RequestID, input.ClientKey, input.PublicModel, audit.OperationVoice, modeldomain.CapabilityTTS, func(providerValue accountdomain.Provider) bool { + _, ok := s.providers.CustomVoices(providerValue) + return ok + }, func(executionCtx context.Context, providerValue accountdomain.Provider, credential accountdomain.Credential, _ string) (*provider.Response, error) { + adapter, ok := s.providers.CustomVoices(providerValue) + if !ok { + return nil, ErrNoAvailableAccount + } + voices, next, err := adapter.ListCustomVoices(executionCtx, credential, limit, paginationToken) + if err != nil { + return voiceErrorResponse(err) + } + items := make([]map[string]any, 0, len(voices)) + for _, voice := range voices { + items = append(items, customVoicePayload(voice)) + } + payload := map[string]any{"voices": items} + if next != "" { + payload["pagination_token"] = next + } + return jsonVoiceResponse(http.StatusOK, payload), nil + }) +} + +func (s *Service) GetCustomVoice(ctx context.Context, input CustomVoiceIDInput) (*Result, error) { + return s.executeVoice(ctx, input.RequestID, input.ClientKey, input.PublicModel, audit.OperationVoice, modeldomain.CapabilityTTS, func(providerValue accountdomain.Provider) bool { + _, ok := s.providers.CustomVoices(providerValue) + return ok + }, func(executionCtx context.Context, providerValue accountdomain.Provider, credential accountdomain.Credential, _ string) (*provider.Response, error) { + adapter, ok := s.providers.CustomVoices(providerValue) + if !ok { + return nil, ErrNoAvailableAccount + } + result, err := adapter.GetCustomVoice(executionCtx, credential, input.VoiceID) + if err != nil { + return voiceErrorResponse(err) + } + if len(result.RawJSON) > 0 { + header := http.Header{} + header.Set("Content-Type", "application/json") + header.Set("Content-Length", fmt.Sprintf("%d", len(result.RawJSON))) + return &provider.Response{StatusCode: http.StatusOK, Status: "200 OK", Header: header, Body: io.NopCloser(bytes.NewReader(result.RawJSON)), QuotaUnits: 1}, nil + } + return jsonVoiceResponse(http.StatusOK, customVoicePayload(result)), nil + }) +} + +func (s *Service) UpdateCustomVoice(ctx context.Context, input CustomVoiceUpdateInput) (*Result, error) { + return s.executeVoice(ctx, input.RequestID, input.ClientKey, input.PublicModel, audit.OperationVoice, modeldomain.CapabilityTTS, func(providerValue accountdomain.Provider) bool { + _, ok := s.providers.CustomVoices(providerValue) + return ok + }, func(executionCtx context.Context, providerValue accountdomain.Provider, credential accountdomain.Credential, _ string) (*provider.Response, error) { + adapter, ok := s.providers.CustomVoices(providerValue) + if !ok { + return nil, ErrNoAvailableAccount + } + result, err := adapter.UpdateCustomVoice(executionCtx, provider.CustomVoiceUpdateRequest{ + Credential: credential, VoiceID: input.VoiceID, Name: input.Name, Language: input.Language, Gender: input.Gender, Tone: input.Tone, UseCase: input.UseCase, + }) + if err != nil { + return voiceErrorResponse(err) + } + if len(result.RawJSON) > 0 { + header := http.Header{} + header.Set("Content-Type", "application/json") + header.Set("Content-Length", fmt.Sprintf("%d", len(result.RawJSON))) + return &provider.Response{StatusCode: http.StatusOK, Status: "200 OK", Header: header, Body: io.NopCloser(bytes.NewReader(result.RawJSON)), QuotaUnits: 1}, nil + } + return jsonVoiceResponse(http.StatusOK, customVoicePayload(result)), nil + }) +} + +func (s *Service) DeleteCustomVoice(ctx context.Context, input CustomVoiceIDInput) (*Result, error) { + return s.executeVoice(ctx, input.RequestID, input.ClientKey, input.PublicModel, audit.OperationVoice, modeldomain.CapabilityTTS, func(providerValue accountdomain.Provider) bool { + _, ok := s.providers.CustomVoices(providerValue) + return ok + }, func(executionCtx context.Context, providerValue accountdomain.Provider, credential accountdomain.Credential, _ string) (*provider.Response, error) { + adapter, ok := s.providers.CustomVoices(providerValue) + if !ok { + return nil, ErrNoAvailableAccount + } + if err := adapter.DeleteCustomVoice(executionCtx, credential, input.VoiceID); err != nil { + return voiceErrorResponse(err) + } + return jsonVoiceResponse(http.StatusOK, map[string]any{"deleted": true, "voice_id": input.VoiceID}), nil + }) +} + +func (s *Service) GetCustomVoiceAudio(ctx context.Context, input CustomVoiceIDInput) (*Result, error) { + return s.executeVoice(ctx, input.RequestID, input.ClientKey, input.PublicModel, audit.OperationVoice, modeldomain.CapabilityTTS, func(providerValue accountdomain.Provider) bool { + _, ok := s.providers.CustomVoices(providerValue) + return ok + }, func(executionCtx context.Context, providerValue accountdomain.Provider, credential accountdomain.Credential, _ string) (*provider.Response, error) { + adapter, ok := s.providers.CustomVoices(providerValue) + if !ok { + return nil, ErrNoAvailableAccount + } + data, contentType, err := adapter.GetCustomVoiceAudio(executionCtx, credential, input.VoiceID) + if err != nil { + return voiceErrorResponse(err) + } + header := http.Header{} + header.Set("Content-Type", firstNonEmpty(contentType, "audio/mpeg")) + header.Set("Content-Length", fmt.Sprintf("%d", len(data))) + return &provider.Response{StatusCode: http.StatusOK, Status: "200 OK", Header: header, Body: io.NopCloser(bytes.NewReader(data)), QuotaUnits: 1}, nil + }) +} + +func (s *Service) executeVoice( + ctx context.Context, + requestID string, + key clientkey.Key, + publicModel string, + operation audit.Operation, + capability modeldomain.Capability, + supports voiceProviderSupport, + execute func(context.Context, accountdomain.Provider, accountdomain.Credential, string) (*provider.Response, error), +) (*Result, error) { + ctx, egressTrace := infraegress.WithTrace(ctx) + startedAt := time.Now() + eventID := newAuditEventID() + routes, err := s.models.GetByPublicIDCandidates(ctx, publicModel) + if err != nil { + // Voice catalog helpers may not require a specific model when only voices are listed. + // Fall back to any enabled route for the capability so built-in voice listing still works. + if publicModel == "" || publicModel == "grok-voice-latest" || publicModel == "grok-transcribe" { + return nil, ErrModelNotFound + } + return nil, ErrModelNotFound + } + route, err := s.selectMediaRoute(routes, key, capability, supports) + if err != nil { + return nil, err + } + externalModel := modeldomain.ExternalPublicID(route.Provider, route.PublicID) + auditBase := audit.Record{ + EventID: eventID, RequestID: requestID, ClientKeyID: key.ID, ClientKeyName: key.Name, + ModelRouteID: route.ID, ModelPublicID: externalModel, ModelUpstreamModel: modeldomain.DisplayUpstreamModel(route.Provider, route.UpstreamModel), + Provider: string(route.Provider), Operation: operation, UsageSource: audit.UsageSourceNone, + } + if err := s.checkLedgerReady(); err != nil { + return nil, err + } + writeFailureAudit := func(statusCode int, errorCode string, credential *accountdomain.Credential) { + record := auditBase + record.StatusCode = statusCode + record.ErrorCode = errorCode + record.DurationMS = time.Since(startedAt).Milliseconds() + record.CreatedAt = time.Now().UTC() + if credential != nil { + accountID := credential.ID + record.AccountID = &accountID + record.AccountName = credential.Name + } + applyAuditEgress(&record, egressTrace, route.Provider) + persistCtx, cancel := context.WithTimeout(context.Background(), finalizationTimeout) + defer cancel() + if auditErr := s.audits.Create(persistCtx, record); auditErr != nil { + s.logger.Error("request_usage_write_failed", "event_id", record.EventID, "request_id", requestID, "error", auditErr) + } + } + quotaMode := s.providers.QuotaMode(route.Provider, route.UpstreamModel) + attemptPolicy := newRoutingAttemptPolicy(int(s.maxAttempts.Load())) + excluded := make(map[uint64]bool) + var selection *selectionSession + var lease *accountLease + var credential accountdomain.Credential + var response *provider.Response + var lastCredentialFailure *accountdomain.Credential + var lastCredentialError error + for attempt := 0; attemptPolicy.allows(attempt); attempt++ { + if selection == nil { + selection, err = s.selector.beginSelectionSessionForKey(ctx, route.Provider, route.ID, route.UpstreamModel, quotaMode, "", excluded, false, key.AccountScope()) + } + if err == nil { + lease, err = selection.Acquire(ctx, excluded, false) + } + if err != nil { + errorCode := "upstream_unavailable" + var selectionFailure *SelectionUnavailableError + if errors.As(err, &selectionFailure) { + errorCode = selectionFailure.Code() + } + writeFailureAudit(http.StatusServiceUnavailable, errorCode, lastCredentialFailure) + return nil, fmt.Errorf("%w: %w", ErrNoAvailableAccount, err) + } + excluded[lease.Credential.ID] = true + credential, err = s.accounts.EnsureCredential(ctx, lease.Credential, false) + if err != nil { + failedCredential := lease.Credential + lastCredentialFailure = &failedCredential + lastCredentialError = err + lease.Release() + continue + } + lease.markSelectorUpstreamStarted() + response, err = execute(ctx, route.Provider, credential, route.UpstreamModel) + if err != nil { + if isSSOCredentialRejected(err, credential) { + s.markSSOCredentialRejected(ctx, credential, fmt.Sprintf("%s SSO credential rejected", credential.Provider)) + failedCredential := credential + lastCredentialFailure = &failedCredential + lastCredentialError = provider.ErrUnauthorized + lease.Release() + continue + } + s.selector.MarkFailure(ctx, credential, 0, 0) + lease.Release() + writeFailureAudit(http.StatusBadGateway, "upstream_unavailable", &credential) + return nil, err + } + if response.StatusCode == http.StatusUnauthorized && credential.AuthType == accountdomain.AuthTypeSSO { + _, _ = readRetryableBody(response.Body) + s.markSSOCredentialRejected(ctx, credential, fmt.Sprintf("%s SSO credential rejected", credential.Provider)) + failedCredential := credential + lastCredentialFailure = &failedCredential + lastCredentialError = provider.ErrUnauthorized + response = nil + lease.Release() + continue + } + if s.providers.RetryForbiddenAsEgress(credential.Provider) && response.StatusCode == http.StatusForbidden && attempt == 0 && attemptPolicy.hasNext(attempt) { + _, _ = readRetryableBody(response.Body) + delete(excluded, credential.ID) + if selection != nil { + selection.RetryAccount(credential.ID) + } + lease.Release() + continue + } + if response.StatusCode == http.StatusTooManyRequests && attemptPolicy.hasNext(attempt) { + retryAfter := parseRetryAfter(response.Header.Get("Retry-After"), time.Now().UTC()) + body, _ := readRetryableBody(response.Body) + s.selector.MarkFailure(ctx, credential, response.StatusCode, retryAfter) + response.Body = io.NopCloser(bytes.NewReader(body)) + _, _ = readRetryableBody(response.Body) + lease.Release() + continue + } + break + } + if response == nil { + writeFailureAudit(http.StatusServiceUnavailable, "upstream_unavailable", lastCredentialFailure) + if lastCredentialError == nil { + lastCredentialError = ErrNoAvailableAccount + } + return nil, fmt.Errorf("%w: %w", ErrNoAvailableAccount, lastCredentialError) + } + accountID := credential.ID + var once sync.Once + finalize := func(_ Usage, _ string, errorCode string) { + once.Do(func() { + successful := auditRequestSucceeded(response.StatusCode, errorCode) + lease.completeSelectorObservation(successful) + lease.Release() + record := auditBase + record.AccountID, record.AccountName, record.StatusCode = &accountID, credential.Name, response.StatusCode + record.ErrorCode = errorCode + record.DurationMS, record.CreatedAt = time.Since(startedAt).Milliseconds(), time.Now().UTC() + applyAuditEgress(&record, egressTrace, route.Provider) + persistCtx, cancel := context.WithTimeout(context.Background(), finalizationTimeout) + defer cancel() + if err := s.audits.Create(persistCtx, record); err != nil { + s.logger.Error("request_usage_write_failed", "event_id", record.EventID, "request_id", requestID, "error", err) + } + }) + } + return &Result{StatusCode: response.StatusCode, Status: response.Status, Header: response.Header, Body: &finalizingBody{ReadCloser: response.Body, finalize: func() { finalize(Usage{}, "", "stream_closed") }}, Finalize: finalize}, nil +} + +func jsonVoiceResponse(status int, value any) *provider.Response { + data, _ := json.Marshal(value) + header := http.Header{} + header.Set("Content-Type", "application/json") + header.Set("Content-Length", fmt.Sprintf("%d", len(data))) + return &provider.Response{ + StatusCode: status, + Status: fmt.Sprintf("%d %s", status, http.StatusText(status)), + Header: header, + Body: io.NopCloser(bytes.NewReader(data)), + QuotaUnits: 1, + } +} + +func voiceErrorResponse(err error) (*provider.Response, error) { + var upstream interface{ HTTPStatusCode() int; Error() string } + if errors.As(err, &upstream) && upstream.HTTPStatusCode() > 0 { + return jsonVoiceResponse(upstream.HTTPStatusCode(), map[string]any{"error": map[string]any{"type": "upstream_error", "message": upstream.Error()}}), nil + } + return nil, err +} + +func customVoicePayload(value provider.CustomVoice) map[string]any { + payload := map[string]any{ + "voice_id": value.VoiceID, + "name": value.Name, + } + if value.Language != "" { + payload["language"] = value.Language + } + if value.Gender != "" { + payload["gender"] = value.Gender + } + if value.Tone != "" { + payload["tone"] = value.Tone + } + if value.UseCase != "" { + payload["use_case"] = value.UseCase + } + if value.CreatedAt != "" { + payload["created_at"] = value.CreatedAt + } + if value.UpdatedAt != "" { + payload["updated_at"] = value.UpdatedAt + } + return payload +} + +func firstNonEmpty(values ...string) string { + for _, value := range values { + if strings.TrimSpace(value) != "" { + return strings.TrimSpace(value) + } + } + return "" +} diff --git a/backend/internal/application/model/service.go b/backend/internal/application/model/service.go index 79b3b4eb..d9e41a08 100644 --- a/backend/internal/application/model/service.go +++ b/backend/internal/application/model/service.go @@ -153,9 +153,15 @@ func endpointCapabilitiesForDefinition(routes []modeldomain.Route, definition pr available["image_edit"] = definition.Media.ImageEdit case modeldomain.CapabilityVideo: available["video"] = definition.Media.VideoGeneration + case modeldomain.CapabilityTTS: + available["tts"] = definition.Media.TTS + case modeldomain.CapabilitySTT: + available["stt"] = definition.Media.STT + case modeldomain.CapabilityRealtime: + available["realtime"] = definition.Media.Realtime } } - order := []string{"completions", "responses", "messages", "image", "image_edit", "video"} + order := []string{"completions", "responses", "messages", "image", "image_edit", "video", "tts", "stt", "realtime"} result := make([]string, 0, len(order)) for _, capability := range order { if available[capability] { diff --git a/backend/internal/domain/audit/audit.go b/backend/internal/domain/audit/audit.go index 7d11ac6e..1cbb1a54 100644 --- a/backend/internal/domain/audit/audit.go +++ b/backend/internal/domain/audit/audit.go @@ -12,6 +12,10 @@ const ( OperationImage Operation = "image" OperationImageEdit Operation = "image_edit" OperationVideo Operation = "video" + OperationTTS Operation = "tts" + OperationSTT Operation = "stt" + OperationRealtime Operation = "realtime" + OperationVoice Operation = "voice" ) type UsageSource string diff --git a/backend/internal/domain/model/model.go b/backend/internal/domain/model/model.go index 684d5b98..3eb4fa36 100644 --- a/backend/internal/domain/model/model.go +++ b/backend/internal/domain/model/model.go @@ -22,6 +22,9 @@ const ( CapabilityImage Capability = "image" CapabilityImageEdit Capability = "image_edit" CapabilityVideo Capability = "video" + CapabilityTTS Capability = "tts" + CapabilitySTT Capability = "stt" + CapabilityRealtime Capability = "realtime" ) // Capabilities returns every persisted route capability. Callers use this as @@ -33,6 +36,9 @@ func Capabilities() []Capability { CapabilityImage, CapabilityImageEdit, CapabilityVideo, + CapabilityTTS, + CapabilitySTT, + CapabilityRealtime, } } diff --git a/backend/internal/infra/persistence/relational/model_repository.go b/backend/internal/infra/persistence/relational/model_repository.go index aed777a8..0c3c327f 100644 --- a/backend/internal/infra/persistence/relational/model_repository.go +++ b/backend/internal/infra/persistence/relational/model_repository.go @@ -747,13 +747,19 @@ func discoveredRouteDefaults(provider account.Provider, upstreamModel string) (s return upstreamModel, model.CapabilityResponses case account.ProviderConsole: switch upstreamModel { - case "grok-imagine-image", "grok-imagine-image-quality": + case "grok-imagine-image": // The catalog also registers image_edit for the same public model. // Discovery only needs one existing managed capability to remain // idempotent and must never synthesize a Responses route. - return upstreamModel, model.CapabilityImage + return "grok-imagine-image-2.0", model.CapabilityImage + case "grok-imagine-image-quality": + return "grok-imagine-image-quality-2.0", model.CapabilityImage case "grok-imagine-video", "grok-imagine-video-1.5": return upstreamModel, model.CapabilityVideo + case "grok-voice-latest", "grok-voice-think-fast-2.0", "grok-voice-think-fast-1.0": + return upstreamModel, model.CapabilityRealtime + case "grok-transcribe": + return upstreamModel, model.CapabilitySTT default: return upstreamModel, model.CapabilityResponses } diff --git a/backend/internal/infra/provider/console/adapter.go b/backend/internal/infra/provider/console/adapter.go index b6ef8d2d..6c399053 100644 --- a/backend/internal/infra/provider/console/adapter.go +++ b/backend/internal/infra/provider/console/adapter.go @@ -78,6 +78,9 @@ func (a *Adapter) QuotaMode(upstreamModel string) string { if ResolveMedia(upstreamModel, modeldomain.CapabilityVideo) { return QuotaModeVideo } + if ResolveMedia(upstreamModel, modeldomain.CapabilityTTS) || ResolveMedia(upstreamModel, modeldomain.CapabilitySTT) || ResolveMedia(upstreamModel, modeldomain.CapabilityRealtime) { + return QuotaMode + } return "" } diff --git a/backend/internal/infra/provider/console/catalog.go b/backend/internal/infra/provider/console/catalog.go index 063d5375..bbe86072 100644 --- a/backend/internal/infra/provider/console/catalog.go +++ b/backend/internal/infra/provider/console/catalog.go @@ -35,17 +35,25 @@ var mediaCatalog = []struct { UpstreamModel string Capabilities []modeldomain.Capability }{ - {PublicID: "grok-imagine-image-quality", UpstreamModel: "grok-imagine-image-quality", Capabilities: []modeldomain.Capability{modeldomain.CapabilityImage, modeldomain.CapabilityImageEdit}}, - {PublicID: "grok-imagine-image", UpstreamModel: "grok-imagine-image", Capabilities: []modeldomain.Capability{modeldomain.CapabilityImage, modeldomain.CapabilityImageEdit}}, + // Console Image 2.0 uses the same upstream model IDs as the official image API. + // Public names keep the -2.0 suffix so Console and Web stay distinguishable. + {PublicID: "grok-imagine-image-quality-2.0", UpstreamModel: "grok-imagine-image-quality", Capabilities: []modeldomain.Capability{modeldomain.CapabilityImage, modeldomain.CapabilityImageEdit}}, + {PublicID: "grok-imagine-image-2.0", UpstreamModel: "grok-imagine-image", Capabilities: []modeldomain.Capability{modeldomain.CapabilityImage, modeldomain.CapabilityImageEdit}}, {PublicID: "grok-imagine-video", UpstreamModel: "grok-imagine-video", Capabilities: []modeldomain.Capability{modeldomain.CapabilityVideo}}, // Free Console accounts can use the 1.5 video model on the official Console media API. {PublicID: "grok-imagine-video-1.5", UpstreamModel: "grok-imagine-video-1.5", Capabilities: []modeldomain.Capability{modeldomain.CapabilityVideo}}, + {PublicID: "grok-voice-latest", UpstreamModel: "grok-voice-latest", Capabilities: []modeldomain.Capability{modeldomain.CapabilityRealtime, modeldomain.CapabilityTTS}}, + {PublicID: "grok-voice-think-fast-2.0", UpstreamModel: "grok-voice-think-fast-2.0", Capabilities: []modeldomain.Capability{modeldomain.CapabilityRealtime, modeldomain.CapabilityTTS}}, + {PublicID: "grok-voice-think-fast-1.0", UpstreamModel: "grok-voice-think-fast-1.0", Capabilities: []modeldomain.Capability{modeldomain.CapabilityRealtime, modeldomain.CapabilityTTS}}, + {PublicID: "grok-transcribe", UpstreamModel: "grok-transcribe", Capabilities: []modeldomain.Capability{modeldomain.CapabilitySTT}}, } // Effort-suffixed aliases only include levels each Provider/model combination // actually supports (see domain/model.SupportedReasoningEffortsForProvider). // No blanket none/low/medium/high/xhigh/max template. var aliases = []provider.ModelAlias{ + consoleAlias("grok-imagine-image", "grok-imagine-image-2.0", "grok-imagine-image", ""), + consoleAlias("grok-imagine-image-quality", "grok-imagine-image-quality-2.0", "grok-imagine-image-quality", ""), consoleAlias("grok-4.3-console", "grok-4.3", "grok-4.3", ""), consoleAlias("grok-4.20-0309-reasoning-console", "grok-4.20-0309-reasoning", "grok-4.20-0309-reasoning", ""), consoleAlias("grok-4.20-0309-non-reasoning-console", "grok-4.20-0309-non-reasoning", "grok-4.20-0309-non-reasoning", ""), diff --git a/backend/internal/infra/provider/console/console_test.go b/backend/internal/infra/provider/console/console_test.go index 91a033d9..fb18c21b 100644 --- a/backend/internal/infra/provider/console/console_test.go +++ b/backend/internal/infra/provider/console/console_test.go @@ -47,12 +47,19 @@ func TestCatalogContainsAllConsoleModelsAndAliases(t *testing.T) { {publicID: "Console/grok-4.20-multi-agent-0309", capability: modeldomain.CapabilityResponses}: "grok-4.20-multi-agent-0309", {publicID: "Console/grok-4.5", capability: modeldomain.CapabilityResponses}: "grok-4.5", {publicID: "Console/grok-build-0.1", capability: modeldomain.CapabilityResponses}: "grok-build-0.1", - {publicID: "Console/grok-imagine-image-quality", capability: modeldomain.CapabilityImage}: "grok-imagine-image-quality", - {publicID: "Console/grok-imagine-image-quality", capability: modeldomain.CapabilityImageEdit}: "grok-imagine-image-quality", - {publicID: "Console/grok-imagine-image", capability: modeldomain.CapabilityImage}: "grok-imagine-image", - {publicID: "Console/grok-imagine-image", capability: modeldomain.CapabilityImageEdit}: "grok-imagine-image", - {publicID: "Console/grok-imagine-video", capability: modeldomain.CapabilityVideo}: "grok-imagine-video", - {publicID: "Console/grok-imagine-video-1.5", capability: modeldomain.CapabilityVideo}: "grok-imagine-video-1.5", + {publicID: "Console/grok-imagine-image-quality-2.0", capability: modeldomain.CapabilityImage}: "grok-imagine-image-quality", + {publicID: "Console/grok-imagine-image-quality-2.0", capability: modeldomain.CapabilityImageEdit}: "grok-imagine-image-quality", + {publicID: "Console/grok-imagine-image-2.0", capability: modeldomain.CapabilityImage}: "grok-imagine-image", + {publicID: "Console/grok-imagine-image-2.0", capability: modeldomain.CapabilityImageEdit}: "grok-imagine-image", + {publicID: "Console/grok-imagine-video", capability: modeldomain.CapabilityVideo}: "grok-imagine-video", + {publicID: "Console/grok-imagine-video-1.5", capability: modeldomain.CapabilityVideo}: "grok-imagine-video-1.5", + {publicID: "Console/grok-voice-latest", capability: modeldomain.CapabilityRealtime}: "grok-voice-latest", + {publicID: "Console/grok-voice-latest", capability: modeldomain.CapabilityTTS}: "grok-voice-latest", + {publicID: "Console/grok-voice-think-fast-2.0", capability: modeldomain.CapabilityRealtime}: "grok-voice-think-fast-2.0", + {publicID: "Console/grok-voice-think-fast-2.0", capability: modeldomain.CapabilityTTS}: "grok-voice-think-fast-2.0", + {publicID: "Console/grok-voice-think-fast-1.0", capability: modeldomain.CapabilityRealtime}: "grok-voice-think-fast-1.0", + {publicID: "Console/grok-voice-think-fast-1.0", capability: modeldomain.CapabilityTTS}: "grok-voice-think-fast-1.0", + {publicID: "Console/grok-transcribe", capability: modeldomain.CapabilitySTT}: "grok-transcribe", } routes := Routes() if len(routes) != len(expected) { @@ -93,6 +100,7 @@ func TestCatalogContainsAllConsoleModelsAndAliases(t *testing.T) { for model, want := range map[string]string{ "grok-4.5": QuotaMode, "grok-imagine-image-quality": QuotaModeImage, "grok-imagine-image": QuotaModeImage, "grok-imagine-video": QuotaModeVideo, "grok-imagine-video-1.5": QuotaModeVideo, + "grok-voice-latest": QuotaMode, "grok-voice-think-fast-2.0": QuotaMode, "grok-voice-think-fast-1.0": QuotaMode, "grok-transcribe": QuotaMode, } { if got := adapter.QuotaMode(model); got != want { t.Fatalf("QuotaMode(%q) = %q, want %q", model, got, want) diff --git a/backend/internal/infra/provider/console/definition.go b/backend/internal/infra/provider/console/definition.go index 94eb6e57..16bd7075 100644 --- a/backend/internal/infra/provider/console/definition.go +++ b/backend/internal/infra/provider/console/definition.go @@ -18,6 +18,9 @@ func (a *Adapter) Definition() provider.Definition { modeldomain.CapabilityImage, modeldomain.CapabilityImageEdit, modeldomain.CapabilityVideo, + modeldomain.CapabilityTTS, + modeldomain.CapabilitySTT, + modeldomain.CapabilityRealtime, }, Quota: provider.QuotaRemoteWindow, Credential: provider.CredentialSurface{ @@ -28,6 +31,7 @@ func (a *Adapter) Definition() provider.Definition { }, Media: provider.MediaSurface{ ImageGeneration: true, ImageEdit: true, VideoGeneration: true, + TTS: true, STT: true, Realtime: true, CustomVoices: true, }, // Console shares the browser/clearance surface with Web. A 403 is // therefore normally an egress challenge, not proof that the SSO diff --git a/backend/internal/infra/provider/console/dpop.go b/backend/internal/infra/provider/console/dpop.go index fb6c6d2c..ffc50411 100644 --- a/backend/internal/infra/provider/console/dpop.go +++ b/backend/internal/infra/provider/console/dpop.go @@ -292,6 +292,23 @@ func (a *Adapter) doDPoPRequest( method, endpoint string, body []byte, accept string, +) (*http.Response, error) { + contentType := "" + if len(body) > 0 { + contentType = "application/json" + } + return a.doDPoPRequestWithContentType(ctx, credential, ssoToken, lease, method, endpoint, body, contentType, accept) +} + +func (a *Adapter) doDPoPRequestWithContentType( + ctx context.Context, + credential account.Credential, + ssoToken string, + lease *infraegress.Lease, + method, endpoint string, + body []byte, + contentType string, + accept string, ) (*http.Response, error) { for attempt := 0; attempt < 2; attempt++ { session, cacheKey, err := a.dpop.get(ctx, a, credential, ssoToken, lease) @@ -308,7 +325,10 @@ func (a *Adapter) doDPoPRequest( } applyBrowserHeaders(request, ssoToken, lease) if len(body) > 0 { - request.Header.Set("Content-Type", "application/json") + if strings.TrimSpace(contentType) == "" { + contentType = "application/json" + } + request.Header.Set("Content-Type", contentType) } if strings.TrimSpace(accept) != "" { request.Header.Set("Accept", accept) diff --git a/backend/internal/infra/provider/console/voice.go b/backend/internal/infra/provider/console/voice.go new file mode 100644 index 00000000..b10329b7 --- /dev/null +++ b/backend/internal/infra/provider/console/voice.go @@ -0,0 +1,741 @@ +package console + +import ( + "bytes" + "context" + "encoding/base64" + "encoding/json" + "errors" + "fmt" + "io" + "mime/multipart" + "net/http" + "net/url" + "path" + "strconv" + "strings" + "time" + "unicode/utf8" + + "github.com/chenyme/grok2api/backend/internal/domain/account" + egressdomain "github.com/chenyme/grok2api/backend/internal/domain/egress" + modeldomain "github.com/chenyme/grok2api/backend/internal/domain/model" + "github.com/chenyme/grok2api/backend/internal/infra/provider" +) + +const ( + consoleVoiceBodyLimit = 64 << 20 + consoleVoiceAudioLimit = 512 << 20 + consoleCustomVoiceLimit = 32 << 20 +) + +func (a *Adapter) SynthesizeSpeech(ctx context.Context, request provider.TTSRequest) (provider.TTSResult, error) { + if model := strings.TrimSpace(request.Model); model != "" && !ResolveMedia(model, modeldomain.CapabilityTTS) { + // Official REST TTS is not strictly bound to a single model id; catalog + // models remain preferred when callers supply one. + } + text := strings.TrimSpace(request.Text) + if text == "" { + return provider.TTSResult{}, invalidConsoleVoiceError("text 不能为空") + } + if utf8.RuneCountInString(text) > 15000 { + return provider.TTSResult{}, invalidConsoleVoiceError("text 最多 15000 个字符") + } + language := strings.TrimSpace(request.Language) + if language == "" { + return provider.TTSResult{}, invalidConsoleVoiceError("language 不能为空") + } + payload := map[string]any{"text": text, "language": language} + if voiceID := strings.TrimSpace(request.VoiceID); voiceID != "" { + payload["voice_id"] = voiceID + } + if format := normalizeTTSOutputFormat(request.OutputFormat); format != nil { + payload["output_format"] = format + } + if request.Speed > 0 { + payload["speed"] = request.Speed + } + if request.OptimizeStreamingLatency > 0 { + payload["optimize_streaming_latency"] = strconv.Itoa(request.OptimizeStreamingLatency) + } + if request.TextNormalization { + payload["text_normalization"] = true + } + if request.WithTimestamps { + payload["with_timestamps"] = true + } + response, err := a.forwardConsoleVoice(ctx, request.Credential, http.MethodPost, "/tts", payload, "application/json", "*/*") + if err != nil { + return provider.TTSResult{}, err + } + defer response.Body.Close() + if response.StatusCode < 200 || response.StatusCode >= 300 { + return provider.TTSResult{}, consoleVoiceResponseError(response) + } + contentType := strings.ToLower(strings.TrimSpace(response.Header.Get("Content-Type"))) + data, err := io.ReadAll(io.LimitReader(response.Body, consoleVoiceAudioLimit+1)) + if err != nil { + return provider.TTSResult{}, err + } + if len(data) > consoleVoiceAudioLimit { + return provider.TTSResult{}, errors.New("Console TTS 响应超过安全上限") + } + if strings.Contains(contentType, "application/json") || request.WithTimestamps { + var envelope struct { + Audio string `json:"audio"` + ContentType string `json:"content_type"` + Duration float64 `json:"duration"` + AudioTimestamps *struct { + GraphChars []string `json:"graph_chars"` + GraphTimes []struct { + Start float64 `json:"start"` + End float64 `json:"end"` + } `json:"graph_times"` + } `json:"audio_timestamps"` + } + if err := json.Unmarshal(data, &envelope); err != nil { + if !strings.Contains(contentType, "application/json") { + return provider.TTSResult{Audio: data, ContentType: firstNonEmpty(contentType, "audio/mpeg")}, nil + } + return provider.TTSResult{}, fmt.Errorf("解析 Console TTS JSON 响应失败: %w", err) + } + audio, err := base64.StdEncoding.DecodeString(strings.TrimSpace(envelope.Audio)) + if err != nil { + return provider.TTSResult{}, fmt.Errorf("解码 Console TTS audio 失败: %w", err) + } + result := provider.TTSResult{ + Audio: audio, ContentType: firstNonEmpty(envelope.ContentType, contentType, "audio/mpeg"), + Duration: envelope.Duration, Base64Audio: envelope.Audio, JSONEnvelope: true, + } + if envelope.AudioTimestamps != nil { + times := make([]provider.TTSTimestampSpan, 0, len(envelope.AudioTimestamps.GraphTimes)) + for _, item := range envelope.AudioTimestamps.GraphTimes { + times = append(times, provider.TTSTimestampSpan{Start: item.Start, End: item.End}) + } + result.Timestamps = &provider.TTSTimestamps{ + GraphChars: append([]string(nil), envelope.AudioTimestamps.GraphChars...), + GraphTimes: times, + } + } + return result, nil + } + return provider.TTSResult{Audio: data, ContentType: firstNonEmpty(contentType, "audio/mpeg")}, nil +} + +func (a *Adapter) ListTTSVoices(ctx context.Context, credential account.Credential) ([]provider.VoiceInfo, error) { + response, err := a.forwardConsoleVoice(ctx, credential, http.MethodGet, "/tts/voices", nil, "", "application/json") + if err != nil { + return nil, err + } + defer response.Body.Close() + if response.StatusCode < 200 || response.StatusCode >= 300 { + return nil, consoleVoiceResponseError(response) + } + data, err := io.ReadAll(io.LimitReader(response.Body, consoleVoiceBodyLimit+1)) + if err != nil { + return nil, err + } + var payload struct { + Voices []struct { + VoiceID string `json:"voice_id"` + Name string `json:"name"` + Language *string `json:"language"` + } `json:"voices"` + } + if err := json.Unmarshal(data, &payload); err != nil { + return nil, fmt.Errorf("解析 Console TTS voices 失败: %w", err) + } + result := make([]provider.VoiceInfo, 0, len(payload.Voices)) + for _, item := range payload.Voices { + language := "" + if item.Language != nil { + language = strings.TrimSpace(*item.Language) + } + result = append(result, provider.VoiceInfo{VoiceID: strings.TrimSpace(item.VoiceID), Name: strings.TrimSpace(item.Name), Language: language}) + } + return result, nil +} + +func (a *Adapter) GetTTSVoice(ctx context.Context, credential account.Credential, voiceID string) (provider.VoiceInfo, error) { + voiceID = strings.TrimSpace(voiceID) + if voiceID == "" { + return provider.VoiceInfo{}, invalidConsoleVoiceError("voice_id 不能为空") + } + response, err := a.forwardConsoleVoice(ctx, credential, http.MethodGet, "/tts/voices/"+url.PathEscape(voiceID), nil, "", "application/json") + if err != nil { + return provider.VoiceInfo{}, err + } + defer response.Body.Close() + if response.StatusCode < 200 || response.StatusCode >= 300 { + return provider.VoiceInfo{}, consoleVoiceResponseError(response) + } + data, err := io.ReadAll(io.LimitReader(response.Body, consoleVoiceBodyLimit+1)) + if err != nil { + return provider.VoiceInfo{}, err + } + var payload struct { + VoiceID string `json:"voice_id"` + Name string `json:"name"` + Language *string `json:"language"` + } + if err := json.Unmarshal(data, &payload); err != nil { + return provider.VoiceInfo{}, fmt.Errorf("解析 Console TTS voice 失败: %w", err) + } + language := "" + if payload.Language != nil { + language = strings.TrimSpace(*payload.Language) + } + return provider.VoiceInfo{VoiceID: strings.TrimSpace(payload.VoiceID), Name: strings.TrimSpace(payload.Name), Language: language}, nil +} + +func (a *Adapter) TranscribeSpeech(ctx context.Context, request provider.STTRequest) (provider.STTResult, error) { + hasFile := len(request.FileData) > 0 + hasURL := strings.TrimSpace(request.URL) != "" + if hasFile == hasURL { + return provider.STTResult{}, invalidConsoleVoiceError("STT 必须提供 file 或 url 其中之一") + } + var body bytes.Buffer + writer := multipart.NewWriter(&body) + writeField := func(name, value string) error { + value = strings.TrimSpace(value) + if value == "" { + return nil + } + return writer.WriteField(name, value) + } + _ = writeField("audio_format", request.AudioFormat) + _ = writeField("sample_rate", request.SampleRate) + _ = writeField("language", request.Language) + if request.Format { + _ = writer.WriteField("format", "true") + } + if request.Multichannel { + _ = writer.WriteField("multichannel", "true") + } + if request.Channels > 0 { + _ = writer.WriteField("channels", strconv.Itoa(request.Channels)) + } + if request.Diarize { + _ = writer.WriteField("diarize", "true") + } + for _, term := range request.KeyTerms { + _ = writeField("keyterm", term) + } + if request.FillerWords { + _ = writer.WriteField("filler_words", "true") + } + if request.VADThreshold != nil { + _ = writer.WriteField("vad_threshold", strconv.FormatFloat(*request.VADThreshold, 'f', -1, 64)) + } + if modelName := strings.TrimSpace(request.Model); modelName != "" { + _ = writer.WriteField("model", modelName) + } + if hasURL { + _ = writer.WriteField("url", strings.TrimSpace(request.URL)) + } + if hasFile { + fileName := strings.TrimSpace(request.FileName) + if fileName == "" { + fileName = "audio.bin" + } + part, err := writer.CreateFormFile("file", path.Base(fileName)) + if err != nil { + return provider.STTResult{}, err + } + if _, err := part.Write(request.FileData); err != nil { + return provider.STTResult{}, err + } + } + if err := writer.Close(); err != nil { + return provider.STTResult{}, err + } + response, err := a.forwardConsoleVoiceBytes(ctx, request.Credential, http.MethodPost, "/stt", body.Bytes(), writer.FormDataContentType(), "application/json") + if err != nil { + return provider.STTResult{}, err + } + defer response.Body.Close() + if response.StatusCode < 200 || response.StatusCode >= 300 { + return provider.STTResult{}, consoleVoiceResponseError(response) + } + data, err := io.ReadAll(io.LimitReader(response.Body, consoleVoiceBodyLimit+1)) + if err != nil { + return provider.STTResult{}, err + } + result, err := parseSTTResult(data) + if err != nil { + return provider.STTResult{}, err + } + result.RawJSON = append([]byte(nil), data...) + return result, nil +} + +func (a *Adapter) CreateRealtimeClientSecret(ctx context.Context, request provider.RealtimeClientSecretRequest) (provider.RealtimeClientSecretResult, error) { + payload := map[string]any{} + if request.ExpiresAfter > 0 { + payload["expires_after"] = map[string]any{"seconds": request.ExpiresAfter} + } + if len(bytes.TrimSpace(request.SessionJSON)) > 0 { + var session any + if err := json.Unmarshal(request.SessionJSON, &session); err != nil { + return provider.RealtimeClientSecretResult{}, invalidConsoleVoiceError("session 必须是合法 JSON 对象") + } + payload["session"] = session + } else if modelName := strings.TrimSpace(request.Model); modelName != "" { + payload["session"] = map[string]any{"model": modelName} + } + response, err := a.forwardConsoleVoice(ctx, request.Credential, http.MethodPost, "/realtime/client_secrets", payload, "application/json", "application/json") + if err != nil { + return provider.RealtimeClientSecretResult{}, err + } + defer response.Body.Close() + if response.StatusCode < 200 || response.StatusCode >= 300 { + return provider.RealtimeClientSecretResult{}, consoleVoiceResponseError(response) + } + data, err := io.ReadAll(io.LimitReader(response.Body, consoleVoiceBodyLimit+1)) + if err != nil { + return provider.RealtimeClientSecretResult{}, err + } + var payloadResult struct { + Value string `json:"value"` + ExpiresAt int64 `json:"expires_at"` + } + if err := json.Unmarshal(data, &payloadResult); err != nil { + return provider.RealtimeClientSecretResult{}, fmt.Errorf("解析 Console realtime client secret 失败: %w", err) + } + if strings.TrimSpace(payloadResult.Value) == "" { + return provider.RealtimeClientSecretResult{}, errors.New("Console realtime client secret 响应缺少 value") + } + return provider.RealtimeClientSecretResult{Value: payloadResult.Value, ExpiresAt: payloadResult.ExpiresAt, RawJSON: append([]byte(nil), data...)}, nil +} + +func (a *Adapter) RealtimeWebSocketURL(modelName string, query string) (string, error) { + base := strings.TrimRight(strings.TrimSpace(a.config().BaseURL), "/") + if base == "" { + return "", errors.New("Console BaseURL 未配置") + } + endpoint, err := url.Parse(consoleV1Endpoint(base, "/realtime")) + if err != nil { + return "", err + } + switch strings.ToLower(endpoint.Scheme) { + case "https": + endpoint.Scheme = "wss" + case "http": + endpoint.Scheme = "ws" + case "wss", "ws": + default: + return "", fmt.Errorf("不支持的 Console realtime scheme: %s", endpoint.Scheme) + } + values := endpoint.Query() + if modelName = strings.TrimSpace(modelName); modelName != "" { + values.Set("model", modelName) + } + if extra := strings.TrimSpace(query); extra != "" { + extraValues, err := url.ParseQuery(strings.TrimPrefix(extra, "?")) + if err != nil { + return "", invalidConsoleVoiceError("realtime query 无效") + } + for key, items := range extraValues { + for _, item := range items { + values.Add(key, item) + } + } + } + endpoint.RawQuery = values.Encode() + return endpoint.String(), nil +} + +func (a *Adapter) CreateCustomVoice(ctx context.Context, request provider.CustomVoiceCreateRequest) (provider.CustomVoice, error) { + if strings.TrimSpace(request.Name) == "" { + return provider.CustomVoice{}, invalidConsoleVoiceError("name 不能为空") + } + if len(request.FileData) == 0 { + return provider.CustomVoice{}, invalidConsoleVoiceError("自定义音色必须提供参考音频") + } + if len(request.FileData) > consoleCustomVoiceLimit { + return provider.CustomVoice{}, invalidConsoleVoiceError("参考音频不能超过 32 MiB") + } + var body bytes.Buffer + writer := multipart.NewWriter(&body) + _ = writer.WriteField("name", strings.TrimSpace(request.Name)) + for key, value := range map[string]string{"language": request.Language, "gender": request.Gender, "tone": request.Tone, "use_case": request.UseCase} { + if strings.TrimSpace(value) != "" { + _ = writer.WriteField(key, strings.TrimSpace(value)) + } + } + fileName := strings.TrimSpace(request.FileName) + if fileName == "" { + fileName = "reference.wav" + } + part, err := writer.CreateFormFile("file", path.Base(fileName)) + if err != nil { + return provider.CustomVoice{}, err + } + if _, err := part.Write(request.FileData); err != nil { + return provider.CustomVoice{}, err + } + if err := writer.Close(); err != nil { + return provider.CustomVoice{}, err + } + response, err := a.forwardConsoleVoiceBytes(ctx, request.Credential, http.MethodPost, "/custom-voices", body.Bytes(), writer.FormDataContentType(), "application/json") + if err != nil { + return provider.CustomVoice{}, err + } + defer response.Body.Close() + if response.StatusCode < 200 || response.StatusCode >= 300 { + return provider.CustomVoice{}, consoleVoiceResponseError(response) + } + data, err := io.ReadAll(io.LimitReader(response.Body, consoleVoiceBodyLimit+1)) + if err != nil { + return provider.CustomVoice{}, err + } + return parseCustomVoice(data) +} + +func (a *Adapter) ListCustomVoices(ctx context.Context, credential account.Credential, limit int, paginationToken string) ([]provider.CustomVoice, string, error) { + values := url.Values{} + if limit > 0 { + values.Set("limit", strconv.Itoa(limit)) + } + if token := strings.TrimSpace(paginationToken); token != "" { + values.Set("pagination_token", token) + } + pathValue := "/custom-voices" + if encoded := values.Encode(); encoded != "" { + pathValue += "?" + encoded + } + response, err := a.forwardConsoleVoice(ctx, credential, http.MethodGet, pathValue, nil, "", "application/json") + if err != nil { + return nil, "", err + } + defer response.Body.Close() + if response.StatusCode < 200 || response.StatusCode >= 300 { + return nil, "", consoleVoiceResponseError(response) + } + data, err := io.ReadAll(io.LimitReader(response.Body, consoleVoiceBodyLimit+1)) + if err != nil { + return nil, "", err + } + var payload struct { + Voices []json.RawMessage `json:"voices"` + PaginationToken string `json:"pagination_token"` + NextPaginationToken string `json:"next_pagination_token"` + } + if err := json.Unmarshal(data, &payload); err != nil { + return nil, "", fmt.Errorf("解析 Console custom voices 失败: %w", err) + } + result := make([]provider.CustomVoice, 0, len(payload.Voices)) + for _, raw := range payload.Voices { + item, err := parseCustomVoice(raw) + if err != nil { + return nil, "", err + } + result = append(result, item) + } + next := strings.TrimSpace(payload.NextPaginationToken) + if next == "" { + next = strings.TrimSpace(payload.PaginationToken) + } + return result, next, nil +} + +func (a *Adapter) GetCustomVoice(ctx context.Context, credential account.Credential, voiceID string) (provider.CustomVoice, error) { + voiceID = strings.TrimSpace(voiceID) + if voiceID == "" { + return provider.CustomVoice{}, invalidConsoleVoiceError("voice_id 不能为空") + } + response, err := a.forwardConsoleVoice(ctx, credential, http.MethodGet, "/custom-voices/"+url.PathEscape(voiceID), nil, "", "application/json") + if err != nil { + return provider.CustomVoice{}, err + } + defer response.Body.Close() + if response.StatusCode < 200 || response.StatusCode >= 300 { + return provider.CustomVoice{}, consoleVoiceResponseError(response) + } + data, err := io.ReadAll(io.LimitReader(response.Body, consoleVoiceBodyLimit+1)) + if err != nil { + return provider.CustomVoice{}, err + } + return parseCustomVoice(data) +} + +func (a *Adapter) UpdateCustomVoice(ctx context.Context, request provider.CustomVoiceUpdateRequest) (provider.CustomVoice, error) { + voiceID := strings.TrimSpace(request.VoiceID) + if voiceID == "" { + return provider.CustomVoice{}, invalidConsoleVoiceError("voice_id 不能为空") + } + payload := map[string]any{} + set := func(key string, value *string) { + if value != nil { + payload[key] = strings.TrimSpace(*value) + } + } + set("name", request.Name) + set("language", request.Language) + set("gender", request.Gender) + set("tone", request.Tone) + set("use_case", request.UseCase) + if len(payload) == 0 { + return provider.CustomVoice{}, invalidConsoleVoiceError("至少提供一个可更新字段") + } + response, err := a.forwardConsoleVoice(ctx, request.Credential, http.MethodPatch, "/custom-voices/"+url.PathEscape(voiceID), payload, "application/json", "application/json") + if err != nil { + return provider.CustomVoice{}, err + } + defer response.Body.Close() + if response.StatusCode < 200 || response.StatusCode >= 300 { + return provider.CustomVoice{}, consoleVoiceResponseError(response) + } + data, err := io.ReadAll(io.LimitReader(response.Body, consoleVoiceBodyLimit+1)) + if err != nil { + return provider.CustomVoice{}, err + } + return parseCustomVoice(data) +} + +func (a *Adapter) DeleteCustomVoice(ctx context.Context, credential account.Credential, voiceID string) error { + voiceID = strings.TrimSpace(voiceID) + if voiceID == "" { + return invalidConsoleVoiceError("voice_id 不能为空") + } + response, err := a.forwardConsoleVoice(ctx, credential, http.MethodDelete, "/custom-voices/"+url.PathEscape(voiceID), nil, "", "application/json") + if err != nil { + return err + } + defer response.Body.Close() + if response.StatusCode < 200 || response.StatusCode >= 300 { + return consoleVoiceResponseError(response) + } + return nil +} + +func (a *Adapter) GetCustomVoiceAudio(ctx context.Context, credential account.Credential, voiceID string) ([]byte, string, error) { + voiceID = strings.TrimSpace(voiceID) + if voiceID == "" { + return nil, "", invalidConsoleVoiceError("voice_id 不能为空") + } + response, err := a.forwardConsoleVoice(ctx, credential, http.MethodGet, "/custom-voices/"+url.PathEscape(voiceID)+"/audio", nil, "", "*/*") + if err != nil { + return nil, "", err + } + defer response.Body.Close() + if response.StatusCode < 200 || response.StatusCode >= 300 { + return nil, "", consoleVoiceResponseError(response) + } + data, err := io.ReadAll(io.LimitReader(response.Body, consoleCustomVoiceLimit+1)) + if err != nil { + return nil, "", err + } + if len(data) > consoleCustomVoiceLimit { + return nil, "", errors.New("Console custom voice audio 超过安全上限") + } + return data, firstNonEmpty(response.Header.Get("Content-Type"), "audio/mpeg"), nil +} + +func (a *Adapter) ProxyVoice(ctx context.Context, request provider.VoiceProxyRequest) (*provider.Response, error) { + method := strings.ToUpper(strings.TrimSpace(request.Method)) + if method == "" { + method = http.MethodGet + } + pathValue := strings.TrimSpace(request.Path) + if pathValue == "" || strings.Contains(pathValue, "://") || strings.Contains(pathValue, "..") { + return invalidConsoleMediaRequest("voice path 无效"), nil + } + if !strings.HasPrefix(pathValue, "/") { + pathValue = "/" + pathValue + } + if query := strings.TrimSpace(request.Query); query != "" { + if strings.Contains(pathValue, "?") { + pathValue += "&" + strings.TrimPrefix(query, "?") + } else { + pathValue += "?" + strings.TrimPrefix(query, "?") + } + } + accept := strings.TrimSpace(request.Accept) + if accept == "" { + accept = "*/*" + } + response, err := a.forwardConsoleVoiceBytes(ctx, request.Credential, method, pathValue, request.Body, request.ContentType, accept) + if err != nil { + return nil, err + } + return responseResult(response, response.Body), nil +} + +func (a *Adapter) forwardConsoleVoice(ctx context.Context, credential account.Credential, method, pathValue string, payload any, contentType, accept string) (*http.Response, error) { + var body []byte + var err error + if payload != nil { + body, err = json.Marshal(payload) + if err != nil { + return nil, err + } + if contentType == "" { + contentType = "application/json" + } + } + return a.forwardConsoleVoiceBytes(ctx, credential, method, pathValue, body, contentType, accept) +} + +func (a *Adapter) forwardConsoleVoiceBytes(ctx context.Context, credential account.Credential, method, pathValue string, body []byte, contentType, accept string) (*http.Response, error) { + if strings.HasPrefix(strings.ToLower(strings.TrimSpace(contentType)), "multipart/") { + return a.forwardConsoleVoiceMultipart(ctx, credential, method, pathValue, body, contentType, accept) + } + token, err := a.cipher.Decrypt(credential.EncryptedAccessToken) + if err != nil { + return nil, err + } + cfg := a.config() + requestCtx, cancel := context.WithTimeout(ctx, time.Duration(cfg.TimeoutSeconds)*time.Second) + lease, err := a.egress.AcquireCredential(requestCtx, egressdomain.ScopeConsole, credential) + if err != nil { + cancel() + return nil, err + } + if accept == "" { + accept = "*/*" + } + response, err := a.doDPoPRequestWithContentType(requestCtx, credential, token, lease, method, consoleV1Endpoint(cfg.BaseURL, pathValue), body, contentType, accept) + if err != nil { + a.egress.FeedbackForScope(context.WithoutCancel(ctx), egressdomain.ScopeConsole, lease.NodeID, 0, err) + lease.Release() + cancel() + return nil, err + } + response.Body = &releaseBody{ReadCloser: response.Body, release: func() { + a.egress.FeedbackForScope(context.WithoutCancel(ctx), egressdomain.ScopeConsole, lease.NodeID, response.StatusCode, nil) + lease.Release() + cancel() + }} + return response, nil +} + +func (a *Adapter) forwardConsoleVoiceMultipart(ctx context.Context, credential account.Credential, method, pathValue string, body []byte, contentType, accept string) (*http.Response, error) { + token, err := a.cipher.Decrypt(credential.EncryptedAccessToken) + if err != nil { + return nil, err + } + cfg := a.config() + requestCtx, cancel := context.WithTimeout(ctx, time.Duration(cfg.TimeoutSeconds)*time.Second) + lease, err := a.egress.AcquireCredential(requestCtx, egressdomain.ScopeConsole, credential) + if err != nil { + cancel() + return nil, err + } + if accept == "" { + accept = "*/*" + } + response, err := a.doDPoPRequestWithContentType(requestCtx, credential, token, lease, method, consoleV1Endpoint(cfg.BaseURL, pathValue), body, contentType, accept) + if err != nil { + a.egress.FeedbackForScope(context.WithoutCancel(ctx), egressdomain.ScopeConsole, lease.NodeID, 0, err) + lease.Release() + cancel() + return nil, err + } + response.Body = &releaseBody{ReadCloser: response.Body, release: func() { + a.egress.FeedbackForScope(context.WithoutCancel(ctx), egressdomain.ScopeConsole, lease.NodeID, response.StatusCode, nil) + lease.Release() + cancel() + }} + return response, nil +} + +func normalizeTTSOutputFormat(format provider.TTSOutputFormat) map[string]any { + codec := strings.ToLower(strings.TrimSpace(format.Codec)) + if codec == "" && format.SampleRate == 0 && format.BitRate == 0 { + return nil + } + if codec == "" { + codec = "mp3" + } + result := map[string]any{"codec": codec} + if format.SampleRate > 0 { + result["sample_rate"] = format.SampleRate + } + if format.BitRate > 0 { + result["bit_rate"] = format.BitRate + } + return result +} + +func parseSTTResult(data []byte) (provider.STTResult, error) { + var payload struct { + Text string `json:"text"` + Language string `json:"language"` + Duration float64 `json:"duration"` + Words []struct { + Text string `json:"text"` + Start float64 `json:"start"` + End float64 `json:"end"` + Speaker *int `json:"speaker"` + } `json:"words"` + Channels []struct { + Index int `json:"index"` + Text string `json:"text"` + Words []struct { + Text string `json:"text"` + Start float64 `json:"start"` + End float64 `json:"end"` + Speaker *int `json:"speaker"` + } `json:"words"` + } `json:"channels"` + } + if err := json.Unmarshal(data, &payload); err != nil { + return provider.STTResult{}, fmt.Errorf("解析 Console STT 响应失败: %w", err) + } + result := provider.STTResult{Text: payload.Text, Language: payload.Language, Duration: payload.Duration} + for _, word := range payload.Words { + result.Words = append(result.Words, provider.STTWord{Text: word.Text, Start: word.Start, End: word.End, Speaker: word.Speaker}) + } + for _, channel := range payload.Channels { + item := provider.STTChannel{Index: channel.Index, Text: channel.Text} + for _, word := range channel.Words { + item.Words = append(item.Words, provider.STTWord{Text: word.Text, Start: word.Start, End: word.End, Speaker: word.Speaker}) + } + result.Channels = append(result.Channels, item) + } + return result, nil +} + +func parseCustomVoice(data []byte) (provider.CustomVoice, error) { + var payload struct { + VoiceID string `json:"voice_id"` + Name string `json:"name"` + Language string `json:"language"` + Gender string `json:"gender"` + Tone string `json:"tone"` + UseCase string `json:"use_case"` + CreatedAt string `json:"created_at"` + UpdatedAt string `json:"updated_at"` + } + if err := json.Unmarshal(data, &payload); err != nil { + return provider.CustomVoice{}, fmt.Errorf("解析 Console custom voice 失败: %w", err) + } + if strings.TrimSpace(payload.VoiceID) == "" { + return provider.CustomVoice{}, errors.New("Console custom voice 响应缺少 voice_id") + } + return provider.CustomVoice{ + VoiceID: strings.TrimSpace(payload.VoiceID), Name: strings.TrimSpace(payload.Name), Language: strings.TrimSpace(payload.Language), + Gender: strings.TrimSpace(payload.Gender), Tone: strings.TrimSpace(payload.Tone), UseCase: strings.TrimSpace(payload.UseCase), + CreatedAt: strings.TrimSpace(payload.CreatedAt), UpdatedAt: strings.TrimSpace(payload.UpdatedAt), RawJSON: append([]byte(nil), data...), + }, nil +} + +func consoleVoiceResponseError(response *http.Response) error { + data, _, err := provider.ReadDiagnosticBody(response.Body) + if err != nil { + return err + } + summary := strings.TrimSpace(string(data)) + if summary == "" { + summary = http.StatusText(response.StatusCode) + } + if len(summary) > 2048 { + summary = summary[:2048] + } + return &consoleMediaUpstreamError{status: response.StatusCode, summary: summary} +} + +func invalidConsoleVoiceError(message string) error { + return &consoleMediaUpstreamError{status: http.StatusBadRequest, summary: message} +} diff --git a/backend/internal/infra/provider/definition.go b/backend/internal/infra/provider/definition.go index e68d30f0..fff6379a 100644 --- a/backend/internal/infra/provider/definition.go +++ b/backend/internal/infra/provider/definition.go @@ -55,6 +55,10 @@ type MediaSurface struct { ImageGeneration bool ImageEdit bool VideoGeneration bool + TTS bool + STT bool + Realtime bool + CustomVoices bool } // CredentialSurface 描述号池凭据的接入和维护方式。 @@ -131,7 +135,7 @@ func (d Definition) Validate() error { capabilities := make(map[modeldomain.Capability]struct{}, len(d.ModelCapabilities)) for _, capability := range d.ModelCapabilities { switch capability { - case modeldomain.CapabilityResponses, modeldomain.CapabilityChat, modeldomain.CapabilityImage, modeldomain.CapabilityImageEdit, modeldomain.CapabilityVideo: + case modeldomain.CapabilityResponses, modeldomain.CapabilityChat, modeldomain.CapabilityImage, modeldomain.CapabilityImageEdit, modeldomain.CapabilityVideo, modeldomain.CapabilityTTS, modeldomain.CapabilitySTT, modeldomain.CapabilityRealtime: default: return fmt.Errorf("Provider %s 声明了无效模型能力 %q", d.Provider, capability) } @@ -163,6 +167,9 @@ func (d Definition) Validate() error { {enabled: d.Media.ImageGeneration, capability: modeldomain.CapabilityImage, name: "图像生成"}, {enabled: d.Media.ImageEdit, capability: modeldomain.CapabilityImageEdit, name: "图像编辑"}, {enabled: d.Media.VideoGeneration, capability: modeldomain.CapabilityVideo, name: "视频生成"}, + {enabled: d.Media.TTS, capability: modeldomain.CapabilityTTS, name: "语音合成"}, + {enabled: d.Media.STT, capability: modeldomain.CapabilitySTT, name: "语音识别"}, + {enabled: d.Media.Realtime, capability: modeldomain.CapabilityRealtime, name: "实时语音"}, } for _, item := range mediaCapabilities { _, declared := capabilities[item.capability] diff --git a/backend/internal/infra/provider/definition_contract_test.go b/backend/internal/infra/provider/definition_contract_test.go index d9e79abc..003a1c23 100644 --- a/backend/internal/infra/provider/definition_contract_test.go +++ b/backend/internal/infra/provider/definition_contract_test.go @@ -62,10 +62,10 @@ func TestProductionProviderDefinitionsMatchImplementedCapabilities(t *testing.T) }, { provider: account.ProviderConsole, catalog: provider.ModelCatalogStatic, quota: provider.QuotaRemoteWindow, - capabilities: []modeldomain.Capability{modeldomain.CapabilityResponses, modeldomain.CapabilityImage, modeldomain.CapabilityImageEdit, modeldomain.CapabilityVideo}, + capabilities: []modeldomain.Capability{modeldomain.CapabilityResponses, modeldomain.CapabilityImage, modeldomain.CapabilityImageEdit, modeldomain.CapabilityVideo, modeldomain.CapabilityTTS, modeldomain.CapabilitySTT, modeldomain.CapabilityRealtime}, credential: provider.CredentialSurface{AuthType: account.AuthTypeSSO, Import: true}, conversation: provider.ConversationSurface{Responses: true, ChatCompletions: true, Messages: true}, - media: provider.MediaSurface{ImageGeneration: true, ImageEdit: true, VideoGeneration: true}, + media: provider.MediaSurface{ImageGeneration: true, ImageEdit: true, VideoGeneration: true, TTS: true, STT: true, Realtime: true, CustomVoices: true}, inference: provider.InferencePolicy{Usage: provider.UsageUpstream, RetryForbiddenAsEgress: true}, }, } diff --git a/backend/internal/infra/provider/provider.go b/backend/internal/infra/provider/provider.go index a1aa45dd..b0d17cba 100644 --- a/backend/internal/infra/provider/provider.go +++ b/backend/internal/infra/provider/provider.go @@ -296,6 +296,148 @@ type VideoResult struct { AssetID string } +type TTSOutputFormat struct { + Codec string + SampleRate int + BitRate int +} + +type TTSRequest struct { + Credential account.Credential + Model string + Text string + VoiceID string + Language string + OutputFormat TTSOutputFormat + Speed float64 + OptimizeStreamingLatency int + TextNormalization bool + WithTimestamps bool +} + +type TTSTimestampSpan struct { + Start float64 + End float64 +} + +type TTSTimestamps struct { + GraphChars []string + GraphTimes []TTSTimestampSpan +} + +type TTSResult struct { + Audio []byte + ContentType string + Duration float64 + Base64Audio string + Timestamps *TTSTimestamps + JSONEnvelope bool +} + +type STTRequest struct { + Credential account.Credential + Model string + FileName string + FileMIME string + FileData []byte + URL string + AudioFormat string + SampleRate string + Language string + Format bool + Multichannel bool + Channels int + Diarize bool + KeyTerms []string + FillerWords bool + VADThreshold *float64 +} + +type STTWord struct { + Text string + Start float64 + End float64 + Speaker *int +} + +type STTChannel struct { + Index int + Text string + Words []STTWord +} + +type STTResult struct { + Text string + Language string + Duration float64 + Words []STTWord + Channels []STTChannel + RawJSON []byte +} + +type VoiceInfo struct { + VoiceID string + Name string + Language string +} + +type CustomVoice struct { + VoiceID string + Name string + Language string + Gender string + Tone string + UseCase string + CreatedAt string + UpdatedAt string + RawJSON []byte +} + +type CustomVoiceCreateRequest struct { + Credential account.Credential + Name string + Language string + Gender string + Tone string + UseCase string + FileName string + FileMIME string + FileData []byte +} + +type CustomVoiceUpdateRequest struct { + Credential account.Credential + VoiceID string + Name *string + Language *string + Gender *string + Tone *string + UseCase *string +} + +type RealtimeClientSecretRequest struct { + Credential account.Credential + Model string + ExpiresAfter int + SessionJSON []byte +} + +type RealtimeClientSecretResult struct { + Value string + ExpiresAt int64 + RawJSON []byte +} + +type VoiceProxyRequest struct { + Credential account.Credential + Method string + Path string + Query string + Body []byte + ContentType string + Accept string +} + // RefreshedCredential represents rotated credentials returned by an OAuth refresh. type RefreshedCredential struct { EncryptedAccessToken string @@ -428,6 +570,44 @@ type VideoContentDownloader interface { DownloadVideo(ctx context.Context, credential account.Credential, rawURL string) (io.ReadCloser, string, int64, error) } +// TTSAdapter synthesizes speech audio for text prompts. +type TTSAdapter interface { + Adapter + SynthesizeSpeech(ctx context.Context, request TTSRequest) (TTSResult, error) + ListTTSVoices(ctx context.Context, credential account.Credential) ([]VoiceInfo, error) + GetTTSVoice(ctx context.Context, credential account.Credential, voiceID string) (VoiceInfo, error) +} + +// STTAdapter transcribes audio into text. +type STTAdapter interface { + Adapter + TranscribeSpeech(ctx context.Context, request STTRequest) (STTResult, error) +} + +// RealtimeVoiceAdapter issues ephemeral secrets and can proxy websocket sessions. +type RealtimeVoiceAdapter interface { + Adapter + CreateRealtimeClientSecret(ctx context.Context, request RealtimeClientSecretRequest) (RealtimeClientSecretResult, error) + RealtimeWebSocketURL(model string, query string) (string, error) +} + +// CustomVoiceAdapter manages team-scoped cloned voices. +type CustomVoiceAdapter interface { + Adapter + CreateCustomVoice(ctx context.Context, request CustomVoiceCreateRequest) (CustomVoice, error) + ListCustomVoices(ctx context.Context, credential account.Credential, limit int, paginationToken string) ([]CustomVoice, string, error) + GetCustomVoice(ctx context.Context, credential account.Credential, voiceID string) (CustomVoice, error) + UpdateCustomVoice(ctx context.Context, request CustomVoiceUpdateRequest) (CustomVoice, error) + DeleteCustomVoice(ctx context.Context, credential account.Credential, voiceID string) error + GetCustomVoiceAudio(ctx context.Context, credential account.Credential, voiceID string) ([]byte, string, error) +} + +// VoiceProxyAdapter forwards arbitrary official voice REST resources with account auth. +type VoiceProxyAdapter interface { + Adapter + ProxyVoice(ctx context.Context, request VoiceProxyRequest) (*Response, error) +} + type RoutingMetadataAdapter interface { Adapter QuotaMode(upstreamModel string) string @@ -609,6 +789,26 @@ func (r *Registry) Validate() error { return fmt.Errorf("Provider %s 声明视频能力但未实现适配器", value) } } + if definition.Media.TTS { + if _, ok := adapter.(TTSAdapter); !ok { + return fmt.Errorf("Provider %s 声明语音合成能力但未实现适配器", value) + } + } + if definition.Media.STT { + if _, ok := adapter.(STTAdapter); !ok { + return fmt.Errorf("Provider %s 声明语音识别能力但未实现适配器", value) + } + } + if definition.Media.Realtime { + if _, ok := adapter.(RealtimeVoiceAdapter); !ok { + return fmt.Errorf("Provider %s 声明实时语音能力但未实现适配器", value) + } + } + if definition.Media.CustomVoices { + if _, ok := adapter.(CustomVoiceAdapter); !ok { + return fmt.Errorf("Provider %s 声明自定义音色能力但未实现适配器", value) + } + } } return nil } @@ -829,6 +1029,51 @@ func (r *Registry) Videos(value account.Provider) (VideoAdapter, bool) { return result, ok } +func (r *Registry) TTS(value account.Provider) (TTSAdapter, bool) { + adapter, ok := r.Get(value) + if !ok { + return nil, false + } + result, ok := adapter.(TTSAdapter) + return result, ok +} + +func (r *Registry) STT(value account.Provider) (STTAdapter, bool) { + adapter, ok := r.Get(value) + if !ok { + return nil, false + } + result, ok := adapter.(STTAdapter) + return result, ok +} + +func (r *Registry) RealtimeVoice(value account.Provider) (RealtimeVoiceAdapter, bool) { + adapter, ok := r.Get(value) + if !ok { + return nil, false + } + result, ok := adapter.(RealtimeVoiceAdapter) + return result, ok +} + +func (r *Registry) CustomVoices(value account.Provider) (CustomVoiceAdapter, bool) { + adapter, ok := r.Get(value) + if !ok { + return nil, false + } + result, ok := adapter.(CustomVoiceAdapter) + return result, ok +} + +func (r *Registry) VoiceProxy(value account.Provider) (VoiceProxyAdapter, bool) { + adapter, ok := r.Get(value) + if !ok { + return nil, false + } + result, ok := adapter.(VoiceProxyAdapter) + return result, ok +} + // CredentialRejection 表示上游响应或错误是否构成「凭据被拒」的稳定判定。 // 与网关 UpstreamFailure 的 CredentialRejected / PermanentAccountDenial / SpendingLimitBlocked 分类保持一致, // 供 account.Service 等非网关路径复用同一套失效收敛语义。 diff --git a/backend/internal/transport/http/inference/handler.go b/backend/internal/transport/http/inference/handler.go index 6a59717d..b8034987 100644 --- a/backend/internal/transport/http/inference/handler.go +++ b/backend/internal/transport/http/inference/handler.go @@ -90,6 +90,17 @@ func (h *Handler) Register(router *gin.RouterGroup) { router.POST("/videos/generations", h.generateVideo) router.GET("/videos/:requestId", h.getVideo) router.GET("/videos/:requestId/content", h.getVideoContent) + router.POST("/tts", h.synthesizeSpeech) + router.GET("/tts/voices", h.listTTSVoices) + router.GET("/tts/voices/:voiceId", h.getTTSVoice) + router.POST("/stt", h.transcribeSpeech) + router.POST("/realtime/client_secrets", h.createRealtimeClientSecret) + router.POST("/custom-voices", h.createCustomVoice) + router.GET("/custom-voices", h.listCustomVoices) + router.GET("/custom-voices/:voiceId", h.getCustomVoice) + router.PATCH("/custom-voices/:voiceId", h.updateCustomVoice) + router.DELETE("/custom-voices/:voiceId", h.deleteCustomVoice) + router.GET("/custom-voices/:voiceId/audio", h.getCustomVoiceAudio) router.POST("/responses/compact", h.compactResponse) router.GET("/responses/:responseId", h.getResponse) router.DELETE("/responses/:responseId", h.deleteResponse) diff --git a/backend/internal/transport/http/inference/voice_handler.go b/backend/internal/transport/http/inference/voice_handler.go new file mode 100644 index 00000000..fae5b2c6 --- /dev/null +++ b/backend/internal/transport/http/inference/voice_handler.go @@ -0,0 +1,522 @@ +package inference + +import ( + "encoding/json" + "io" + "net/http" + "strconv" + "strings" + + "github.com/chenyme/grok2api/backend/internal/application/gateway" + "github.com/chenyme/grok2api/backend/internal/infra/provider" + "github.com/chenyme/grok2api/backend/internal/transport/http/middleware" + "github.com/gin-gonic/gin" +) + +type ttsRequest struct { + Model string `json:"model"` + Text string `json:"text"` + VoiceID string `json:"voice_id"` + Language string `json:"language"` + OutputFormat json.RawMessage `json:"output_format"` + Speed *float64 `json:"speed"` + OptimizeStreamingLatency json.RawMessage `json:"optimize_streaming_latency"` + TextNormalization *bool `json:"text_normalization"` + WithTimestamps *bool `json:"with_timestamps"` +} + +type realtimeClientSecretRequest struct { + Model string `json:"model"` + ExpiresAfter json.RawMessage `json:"expires_after"` + Session json.RawMessage `json:"session"` +} + +func (h *Handler) synthesizeSpeech(c *gin.Context) { + c.Request.Body = http.MaxBytesReader(c.Writer, c.Request.Body, h.maxBodyBytes) + if !isJSONRequest(c) { + writeOpenAIError(c, http.StatusUnsupportedMediaType, "invalid_request", "TTS 仅支持 application/json") + return + } + var request ttsRequest + if err := decodeSingleJSON(c.Request.Body, &request, false); err != nil { + writeOpenAIError(c, http.StatusBadRequest, "invalid_request", "TTS 请求无效") + return + } + text := strings.TrimSpace(request.Text) + language := strings.TrimSpace(request.Language) + if text == "" || language == "" { + writeOpenAIError(c, http.StatusBadRequest, "invalid_request", "TTS 缺少有效 text 或 language") + return + } + model := strings.TrimSpace(request.Model) + if model == "" { + model = "grok-voice-latest" + } + format := provider.TTSOutputFormat{} + if len(bytesTrim(request.OutputFormat)) > 0 { + var raw struct { + Codec string `json:"codec"` + SampleRate *int `json:"sample_rate"` + BitRate *int `json:"bit_rate"` + } + if err := json.Unmarshal(request.OutputFormat, &raw); err != nil { + writeOpenAIError(c, http.StatusBadRequest, "invalid_request", "output_format 无效") + return + } + format.Codec = strings.TrimSpace(raw.Codec) + if raw.SampleRate != nil { + format.SampleRate = *raw.SampleRate + } + if raw.BitRate != nil { + format.BitRate = *raw.BitRate + } + } + speed := 0.0 + if request.Speed != nil { + speed = *request.Speed + } + optimize := 0 + if len(bytesTrim(request.OptimizeStreamingLatency)) > 0 { + var asString string + var asNumber float64 + if json.Unmarshal(request.OptimizeStreamingLatency, &asString) == nil { + optimize, _ = strconv.Atoi(strings.TrimSpace(asString)) + } else if json.Unmarshal(request.OptimizeStreamingLatency, &asNumber) == nil { + optimize = int(asNumber) + } + } + clientKey, requestID, ok := requestIdentity(c) + if !ok { + return + } + input := gateway.TTSInput{ + RequestID: requestID, ClientKey: clientKey, PublicModel: model, Text: text, VoiceID: strings.TrimSpace(request.VoiceID), + Language: language, OutputFormat: format, Speed: speed, OptimizeStreamingLatency: optimize, + } + if request.TextNormalization != nil { + input.TextNormalization = *request.TextNormalization + } + if request.WithTimestamps != nil { + input.WithTimestamps = *request.WithTimestamps + } + result, err := h.gateway.SynthesizeSpeech(c.Request.Context(), input) + if err != nil { + writeGatewayError(c, err) + return + } + h.writeMediaResult(c, result) +} + +func (h *Handler) listTTSVoices(c *gin.Context) { + clientKey, requestID, ok := requestIdentity(c) + if !ok { + return + } + model := strings.TrimSpace(c.Query("model")) + if model == "" { + model = "grok-voice-latest" + } + result, err := h.gateway.ListTTSVoices(c.Request.Context(), gateway.VoiceListInput{RequestID: requestID, ClientKey: clientKey, PublicModel: model}) + if err != nil { + writeGatewayError(c, err) + return + } + h.writeMediaResult(c, result) +} + +func (h *Handler) getTTSVoice(c *gin.Context) { + clientKey, requestID, ok := requestIdentity(c) + if !ok { + return + } + model := strings.TrimSpace(c.Query("model")) + if model == "" { + model = "grok-voice-latest" + } + result, err := h.gateway.GetTTSVoice(c.Request.Context(), gateway.CustomVoiceIDInput{ + RequestID: requestID, ClientKey: clientKey, PublicModel: model, VoiceID: c.Param("voiceId"), + }) + if err != nil { + writeGatewayError(c, err) + return + } + h.writeMediaResult(c, result) +} + +func (h *Handler) transcribeSpeech(c *gin.Context) { + c.Request.Body = http.MaxBytesReader(c.Writer, c.Request.Body, h.maxBodyBytes) + clientKey, requestID, ok := requestIdentity(c) + if !ok { + return + } + contentType := strings.ToLower(strings.TrimSpace(c.GetHeader("Content-Type"))) + input := gateway.STTInput{RequestID: requestID, ClientKey: clientKey, PublicModel: "grok-transcribe"} + if strings.HasPrefix(contentType, "multipart/form-data") { + if err := c.Request.ParseMultipartForm(h.maxBodyBytes); err != nil { + writeOpenAIError(c, http.StatusBadRequest, "invalid_request", "STT multipart 请求无效") + return + } + form := c.Request.MultipartForm + get := func(name string) string { + if form == nil { + return "" + } + values := form.Value[name] + if len(values) == 0 { + return "" + } + return strings.TrimSpace(values[0]) + } + if model := get("model"); model != "" { + input.PublicModel = model + } + input.URL = get("url") + input.AudioFormat = get("audio_format") + input.SampleRate = firstNonEmpty(get("sample_rate"), get("sample_rate_hertz")) + input.Language = get("language") + input.Format = parseTruthy(get("format")) + input.Multichannel = parseTruthy(get("multichannel")) + if channels := get("channels"); channels != "" { + if value, err := strconv.Atoi(channels); err == nil { + input.Channels = value + } + } + input.Diarize = parseTruthy(get("diarize")) + input.FillerWords = parseTruthy(get("filler_words")) + if form != nil { + input.KeyTerms = append([]string(nil), form.Value["keyterm"]...) + } + if threshold := get("vad_threshold"); threshold != "" { + if value, err := strconv.ParseFloat(threshold, 64); err == nil { + input.VADThreshold = &value + } + } + file, header, err := c.Request.FormFile("file") + if err == nil { + defer file.Close() + data, readErr := io.ReadAll(io.LimitReader(file, h.maxBodyBytes+1)) + if readErr != nil { + writeOpenAIError(c, http.StatusBadRequest, "invalid_request", "读取音频文件失败") + return + } + if int64(len(data)) > h.maxBodyBytes { + writeOpenAIError(c, http.StatusRequestEntityTooLarge, "request_too_large", "音频文件超过限制") + return + } + input.FileData = data + if header != nil { + input.FileName = header.Filename + input.FileMIME = header.Header.Get("Content-Type") + } + } + } else if isJSONRequest(c) { + var payload struct { + Model string `json:"model"` + URL string `json:"url"` + AudioFormat string `json:"audio_format"` + SampleRate any `json:"sample_rate"` + Language string `json:"language"` + Format any `json:"format"` + Multichannel any `json:"multichannel"` + Channels any `json:"channels"` + Diarize any `json:"diarize"` + KeyTerms []string `json:"keyterm"` + FillerWords any `json:"filler_words"` + VADThreshold *float64 `json:"vad_threshold"` + } + if err := decodeSingleJSON(c.Request.Body, &payload, false); err != nil { + writeOpenAIError(c, http.StatusBadRequest, "invalid_request", "STT JSON 请求无效") + return + } + if strings.TrimSpace(payload.Model) != "" { + input.PublicModel = strings.TrimSpace(payload.Model) + } + input.URL = strings.TrimSpace(payload.URL) + input.AudioFormat = strings.TrimSpace(payload.AudioFormat) + input.SampleRate = anyString(payload.SampleRate) + input.Language = strings.TrimSpace(payload.Language) + input.Format = anyTruthy(payload.Format) + input.Multichannel = anyTruthy(payload.Multichannel) + if channels := anyString(payload.Channels); channels != "" { + if value, err := strconv.Atoi(channels); err == nil { + input.Channels = value + } + } + input.Diarize = anyTruthy(payload.Diarize) + input.KeyTerms = payload.KeyTerms + input.FillerWords = anyTruthy(payload.FillerWords) + input.VADThreshold = payload.VADThreshold + } else { + writeOpenAIError(c, http.StatusUnsupportedMediaType, "invalid_request", "STT 支持 multipart/form-data 或 application/json") + return + } + if len(input.FileData) == 0 && strings.TrimSpace(input.URL) == "" { + writeOpenAIError(c, http.StatusBadRequest, "invalid_request", "STT 必须提供 file 或 url") + return + } + result, err := h.gateway.TranscribeSpeech(c.Request.Context(), input) + if err != nil { + writeGatewayError(c, err) + return + } + h.writeMediaResult(c, result) +} + +func (h *Handler) createRealtimeClientSecret(c *gin.Context) { + c.Request.Body = http.MaxBytesReader(c.Writer, c.Request.Body, h.maxBodyBytes) + if !isJSONRequest(c) { + writeOpenAIError(c, http.StatusUnsupportedMediaType, "invalid_request", "realtime client secret 仅支持 application/json") + return + } + var request realtimeClientSecretRequest + if err := decodeSingleJSON(c.Request.Body, &request, false); err != nil { + writeOpenAIError(c, http.StatusBadRequest, "invalid_request", "realtime client secret 请求无效") + return + } + model := strings.TrimSpace(request.Model) + if model == "" { + model = "grok-voice-latest" + } + expiresAfter := 0 + if len(bytesTrim(request.ExpiresAfter)) > 0 { + var wrapper struct { + Seconds int `json:"seconds"` + } + if err := json.Unmarshal(request.ExpiresAfter, &wrapper); err == nil { + expiresAfter = wrapper.Seconds + } + } + clientKey, requestID, ok := requestIdentity(c) + if !ok { + return + } + result, err := h.gateway.CreateRealtimeClientSecret(c.Request.Context(), gateway.RealtimeClientSecretInput{ + RequestID: requestID, ClientKey: clientKey, PublicModel: model, ExpiresAfter: expiresAfter, SessionJSON: request.Session, + }) + if err != nil { + writeGatewayError(c, err) + return + } + h.writeMediaResult(c, result) +} + +func (h *Handler) createCustomVoice(c *gin.Context) { + c.Request.Body = http.MaxBytesReader(c.Writer, c.Request.Body, h.maxBodyBytes) + clientKey, requestID, ok := requestIdentity(c) + if !ok { + return + } + if err := c.Request.ParseMultipartForm(h.maxBodyBytes); err != nil { + writeOpenAIError(c, http.StatusBadRequest, "invalid_request", "custom voice 请求无效") + return + } + name := strings.TrimSpace(c.PostForm("name")) + if name == "" { + writeOpenAIError(c, http.StatusBadRequest, "invalid_request", "name 不能为空") + return + } + file, header, err := c.Request.FormFile("file") + if err != nil { + writeOpenAIError(c, http.StatusBadRequest, "invalid_request", "必须提供参考音频 file") + return + } + defer file.Close() + data, err := io.ReadAll(io.LimitReader(file, h.maxBodyBytes+1)) + if err != nil || int64(len(data)) > h.maxBodyBytes { + writeOpenAIError(c, http.StatusBadRequest, "invalid_request", "读取参考音频失败") + return + } + model := strings.TrimSpace(c.PostForm("model")) + if model == "" { + model = "grok-voice-latest" + } + input := gateway.CustomVoiceCreateInput{ + RequestID: requestID, ClientKey: clientKey, PublicModel: model, Name: name, + Language: c.PostForm("language"), Gender: c.PostForm("gender"), Tone: c.PostForm("tone"), UseCase: c.PostForm("use_case"), + FileData: data, + } + if header != nil { + input.FileName = header.Filename + input.FileMIME = header.Header.Get("Content-Type") + } + result, err := h.gateway.CreateCustomVoice(c.Request.Context(), input) + if err != nil { + writeGatewayError(c, err) + return + } + h.writeMediaResult(c, result) +} + +func (h *Handler) listCustomVoices(c *gin.Context) { + clientKey, requestID, ok := requestIdentity(c) + if !ok { + return + } + model := strings.TrimSpace(c.Query("model")) + if model == "" { + model = "grok-voice-latest" + } + limit := 0 + if raw := strings.TrimSpace(c.Query("limit")); raw != "" { + if value, err := strconv.Atoi(raw); err == nil { + limit = value + } + } + result, err := h.gateway.ListCustomVoices(c.Request.Context(), gateway.VoiceListInput{RequestID: requestID, ClientKey: clientKey, PublicModel: model}, limit, c.Query("pagination_token")) + if err != nil { + writeGatewayError(c, err) + return + } + h.writeMediaResult(c, result) +} + +func (h *Handler) getCustomVoice(c *gin.Context) { + clientKey, requestID, ok := requestIdentity(c) + if !ok { + return + } + model := strings.TrimSpace(c.Query("model")) + if model == "" { + model = "grok-voice-latest" + } + result, err := h.gateway.GetCustomVoice(c.Request.Context(), gateway.CustomVoiceIDInput{RequestID: requestID, ClientKey: clientKey, PublicModel: model, VoiceID: c.Param("voiceId")}) + if err != nil { + writeGatewayError(c, err) + return + } + h.writeMediaResult(c, result) +} + +func (h *Handler) updateCustomVoice(c *gin.Context) { + c.Request.Body = http.MaxBytesReader(c.Writer, c.Request.Body, h.maxBodyBytes) + if !isJSONRequest(c) { + writeOpenAIError(c, http.StatusUnsupportedMediaType, "invalid_request", "custom voice 更新仅支持 application/json") + return + } + var payload struct { + Model string `json:"model"` + Name *string `json:"name"` + Language *string `json:"language"` + Gender *string `json:"gender"` + Tone *string `json:"tone"` + UseCase *string `json:"use_case"` + } + if err := decodeSingleJSON(c.Request.Body, &payload, false); err != nil { + writeOpenAIError(c, http.StatusBadRequest, "invalid_request", "custom voice 更新请求无效") + return + } + model := strings.TrimSpace(payload.Model) + if model == "" { + model = "grok-voice-latest" + } + clientKey, requestID, ok := requestIdentity(c) + if !ok { + return + } + result, err := h.gateway.UpdateCustomVoice(c.Request.Context(), gateway.CustomVoiceUpdateInput{ + RequestID: requestID, ClientKey: clientKey, PublicModel: model, VoiceID: c.Param("voiceId"), + Name: payload.Name, Language: payload.Language, Gender: payload.Gender, Tone: payload.Tone, UseCase: payload.UseCase, + }) + if err != nil { + writeGatewayError(c, err) + return + } + h.writeMediaResult(c, result) +} + +func (h *Handler) deleteCustomVoice(c *gin.Context) { + clientKey, requestID, ok := requestIdentity(c) + if !ok { + return + } + model := strings.TrimSpace(c.Query("model")) + if model == "" { + model = "grok-voice-latest" + } + result, err := h.gateway.DeleteCustomVoice(c.Request.Context(), gateway.CustomVoiceIDInput{RequestID: requestID, ClientKey: clientKey, PublicModel: model, VoiceID: c.Param("voiceId")}) + if err != nil { + writeGatewayError(c, err) + return + } + h.writeMediaResult(c, result) +} + +func (h *Handler) getCustomVoiceAudio(c *gin.Context) { + clientKey, requestID, ok := requestIdentity(c) + if !ok { + return + } + model := strings.TrimSpace(c.Query("model")) + if model == "" { + model = "grok-voice-latest" + } + result, err := h.gateway.GetCustomVoiceAudio(c.Request.Context(), gateway.CustomVoiceIDInput{RequestID: requestID, ClientKey: clientKey, PublicModel: model, VoiceID: c.Param("voiceId")}) + if err != nil { + writeGatewayError(c, err) + return + } + h.writeMediaResult(c, result) +} + +func bytesTrim(value json.RawMessage) []byte { + return []byte(strings.TrimSpace(string(value))) +} + +func parseTruthy(value string) bool { + switch strings.ToLower(strings.TrimSpace(value)) { + case "1", "true", "yes", "on": + return true + default: + return false + } +} + +func anyTruthy(value any) bool { + switch typed := value.(type) { + case nil: + return false + case bool: + return typed + case string: + return parseTruthy(typed) + case float64: + return typed != 0 + default: + return false + } +} + +func anyString(value any) string { + switch typed := value.(type) { + case nil: + return "" + case string: + return strings.TrimSpace(typed) + case float64: + return strconv.FormatInt(int64(typed), 10) + case json.Number: + return typed.String() + default: + return strings.TrimSpace(stringify(value)) + } +} + +func stringify(value any) string { + data, err := json.Marshal(value) + if err != nil { + return "" + } + return strings.Trim(string(data), `"`) +} + +func firstNonEmpty(values ...string) string { + for _, value := range values { + if strings.TrimSpace(value) != "" { + return strings.TrimSpace(value) + } + } + return "" +} + +// keep middleware import used for request identity compatibility in package docs. +var _ = middleware.ClientKey diff --git a/backend/internal/transport/http/middleware/body_memory.go b/backend/internal/transport/http/middleware/body_memory.go index baab60a9..f837e777 100644 --- a/backend/internal/transport/http/middleware/body_memory.go +++ b/backend/internal/transport/http/middleware/body_memory.go @@ -94,6 +94,14 @@ func inferenceBodyOperation(path string) string { return "image_generation" case "/v1/images/edits": return "image_edit" + case "/v1/tts": + return "tts" + case "/v1/stt": + return "stt" + case "/v1/realtime/client_secrets": + return "realtime_client_secret" + case "/v1/custom-voices": + return "custom_voices" case "/v1/videos/generations": return "video_generation" default: diff --git a/frontend/src/entities/model/model-api.ts b/frontend/src/entities/model/model-api.ts index 2303e683..f32bbb72 100644 --- a/frontend/src/entities/model/model-api.ts +++ b/frontend/src/entities/model/model-api.ts @@ -21,7 +21,7 @@ const modelRouteValidator = hasShape({ publicId: isString, provider: isOneOf("grok_build", "grok_web", "grok_console"), upstreamModel: isString, - capability: isOneOf("responses", "chat", "image", "image_edit", "video"), + capability: isOneOf("responses", "chat", "image", "image_edit", "video", "tts", "stt", "realtime"), origin: isOneOf("catalog", "discovered", "manual"), enabled: isBoolean, accountIds: isArrayOf(isString), @@ -35,7 +35,7 @@ const modelRouteValidator = hasShape({ }); const decodeModelRoute = createObjectDecoder("model route", { id: isString, publicId: isString, provider: isOneOf("grok_build", "grok_web", "grok_console"), upstreamModel: isString, - capability: isOneOf("responses", "chat", "image", "image_edit", "video"), origin: isOneOf("catalog", "discovered", "manual"), + capability: isOneOf("responses", "chat", "image", "image_edit", "video", "tts", "stt", "realtime"), origin: isOneOf("catalog", "discovered", "manual"), enabled: isBoolean, accountIds: isArrayOf(isString), bindingMode: isBoolean, supportedAccounts: isNumber, syncedAccounts: isNumber, totalAccounts: isNumber, capabilityKnown: isBoolean, available: isBoolean, lastSyncedAt: isOptional(isString), }); @@ -43,7 +43,7 @@ const decodeModelPage = createPaginatedDecoder(modelRouteValidato const modelRouteGroupValidator = hasShape({ key: isString, routes: (value) => Array.isArray(value) && value.length > 0 && value.every(modelRouteValidator), - endpointCapabilities: isArrayOf(isOneOf("completions", "responses", "messages", "image", "image_edit", "video")), + endpointCapabilities: isArrayOf(isOneOf("completions", "responses", "messages", "image", "image_edit", "video", "tts", "stt", "realtime")), }); const decodeModelGroupPage = createPaginatedDecoder(modelRouteGroupValidator); const modelAccountValidator = hasShape({ id: isString, name: isString }); diff --git a/frontend/src/entities/model/types.ts b/frontend/src/entities/model/types.ts index 997d81d6..ed36fa8b 100644 --- a/frontend/src/entities/model/types.ts +++ b/frontend/src/entities/model/types.ts @@ -3,7 +3,7 @@ export type ModelRouteDTO = { publicId: string; provider: "grok_build" | "grok_web" | "grok_console"; upstreamModel: string; - capability: "responses" | "chat" | "image" | "image_edit" | "video"; + capability: "responses" | "chat" | "image" | "image_edit" | "video" | "tts" | "stt" | "realtime"; origin: "catalog" | "discovered" | "manual"; enabled: boolean; accountIds: string[]; @@ -16,7 +16,7 @@ export type ModelRouteDTO = { lastSyncedAt?: string; }; -export type ModelEndpointCapability = "completions" | "responses" | "messages" | "image" | "image_edit" | "video"; +export type ModelEndpointCapability = "completions" | "responses" | "messages" | "image" | "image_edit" | "video" | "tts" | "stt" | "realtime"; export type ModelRouteGroupDTO = { key: string; diff --git a/frontend/src/features/creative-console/creative-console-api.ts b/frontend/src/features/creative-console/creative-console-api.ts index 06796dfc..962c2315 100644 --- a/frontend/src/features/creative-console/creative-console-api.ts +++ b/frontend/src/features/creative-console/creative-console-api.ts @@ -157,6 +157,143 @@ export async function getVideo(input: { return status.video ? { ...status, video: { ...status.video, url: resolveMediaURL(status.video.url) } } : status; } + +export type VoiceInfo = { + voiceId: string; + name: string; + language?: string; +}; + +export type TTSResult = { + url: string; + contentType: string; + duration?: number; +}; + +export type STTResult = { + text: string; + language?: string; + duration?: number; + words?: Array<{ text: string; start: number; end: number; speaker?: number }>; +}; + +export async function listVoices(input: { + apiKey: string; + model?: string; + signal?: AbortSignal; +}): Promise { + const query = input.model ? `?model=${encodeURIComponent(input.model)}` : ""; + const payload = await publicApiRequest(input.apiKey, `/tts/voices${query}`, { method: "GET", signal: input.signal }); + if (!isRecord(payload) || !Array.isArray(payload.voices)) { + throw new CreativeApiError(200, "The voice list response was invalid", "invalid_response"); + } + return payload.voices.map((item) => { + if (!isRecord(item) || typeof item.voice_id !== "string") { + throw new CreativeApiError(200, "The voice list response was invalid", "invalid_response"); + } + return { + voiceId: item.voice_id, + name: typeof item.name === "string" ? item.name : item.voice_id, + language: typeof item.language === "string" ? item.language : undefined, + }; + }); +} + +export async function synthesizeSpeech(input: { + apiKey: string; + model: string; + text: string; + voiceId: string; + language: string; + signal?: AbortSignal; +}): Promise { + const response = await fetch("/v1/tts", { + method: "POST", + headers: new Headers({ + Accept: "application/json, audio/*", + Authorization: `Bearer ${input.apiKey}`, + "Content-Type": "application/json", + }), + body: JSON.stringify({ + model: input.model, + text: input.text, + voice_id: input.voiceId, + language: input.language, + }), + signal: input.signal, + }); + const contentType = response.headers.get("content-type") || ""; + if (!response.ok) { + const responseText = await response.text(); + const payload = parseJSON(responseText); + const error = readError(payload); + throw new CreativeApiError(response.status, error.message ?? (responseText.trim() || response.statusText || `HTTP ${response.status}`), error.code); + } + if (contentType.includes("application/json")) { + const payload = await response.json(); + if (!isRecord(payload) || typeof payload.audio !== "string") { + throw new CreativeApiError(200, "The TTS response was invalid", "invalid_response"); + } + const mime = typeof payload.content_type === "string" ? payload.content_type : "audio/mpeg"; + const url = `data:${mime};base64,${payload.audio}`; + return { + url, + contentType: mime, + duration: typeof payload.duration === "number" ? payload.duration : undefined, + }; + } + const buffer = await response.arrayBuffer(); + const mime = contentType || "audio/mpeg"; + const blob = new Blob([buffer], { type: mime }); + return { url: URL.createObjectURL(blob), contentType: mime }; +} + +export async function transcribeSpeech(input: { + apiKey: string; + model: string; + file: File; + language?: string; + signal?: AbortSignal; +}): Promise { + const form = new FormData(); + form.append("model", input.model); + if (input.language) form.append("language", input.language); + form.append("format", "true"); + form.append("file", input.file, input.file.name); + const response = await fetch("/v1/stt", { + method: "POST", + headers: new Headers({ Accept: "application/json", Authorization: `Bearer ${input.apiKey}` }), + body: form, + signal: input.signal, + }); + const responseText = await response.text(); + const payload = parseJSON(responseText); + if (!response.ok) { + const error = readError(payload); + throw new CreativeApiError(response.status, error.message ?? (responseText.trim() || response.statusText || `HTTP ${response.status}`), error.code); + } + if (!isRecord(payload) || typeof payload.text !== "string") { + throw new CreativeApiError(200, "The STT response was invalid", "invalid_response"); + } + const words = Array.isArray(payload.words) + ? payload.words.flatMap((item) => { + if (!isRecord(item) || typeof item.text !== "string") return []; + return [{ + text: item.text, + start: typeof item.start === "number" ? item.start : 0, + end: typeof item.end === "number" ? item.end : 0, + speaker: typeof item.speaker === "number" ? item.speaker : undefined, + }]; + }) + : undefined; + return { + text: payload.text, + language: typeof payload.language === "string" ? payload.language : undefined, + duration: typeof payload.duration === "number" ? payload.duration : undefined, + words, + }; +} + async function publicApiRequest(apiKey: string, path: string, options: RequestOptions): Promise { const headers = new Headers({ Accept: "application/json", Authorization: `Bearer ${apiKey}` }); let body: string | undefined; diff --git a/frontend/src/features/creative-console/creative-console-page.tsx b/frontend/src/features/creative-console/creative-console-page.tsx index 51afa3ff..02e82a60 100644 --- a/frontend/src/features/creative-console/creative-console-page.tsx +++ b/frontend/src/features/creative-console/creative-console-page.tsx @@ -1,5 +1,5 @@ import { useMutation, useQuery } from "@tanstack/react-query"; -import { ArrowUp, BrainCircuit, Check, CheckCircle2, Clock3, ExternalLink, Globe, History, ImageIcon, ImagePlus, ImageUpscale, Images, Loader2, MessageSquareText, Pencil, RefreshCw, Sparkle, Square, SquarePen, Trash2, TriangleAlert, TvMinimal, Upload, Video, Wrench, X } from "lucide-react"; +import { ArrowUp, AudioLines, BrainCircuit, Check, CheckCircle2, Clock3, ExternalLink, Globe, History, ImageIcon, ImagePlus, ImageUpscale, Images, Loader2, MessageSquareText, Mic, Pencil, RefreshCw, Sparkle, Square, SquarePen, Trash2, TriangleAlert, TvMinimal, Upload, Video, Wrench, X } from "lucide-react"; import { marked } from "marked"; import { useEffect, useMemo, useRef, useState, type FormEvent, type KeyboardEvent, type ReactNode } from "react"; import { createPortal } from "react-dom"; @@ -24,19 +24,25 @@ import { createVideo, generateImage, getVideo, + listVoices, + synthesizeSpeech, + transcribeSpeech, type ChatMessage, type ChatStreamSnapshot, type ChatToolActivity, type ImageResult, type ReasoningEffort, + type STTResult, + type TTSResult, type VideoStatus, + type VoiceInfo, } from "@/features/creative-console/creative-console-api"; import { getClientKeySecret, listClientKeys, type ClientKeyDTO } from "@/features/client-keys/client-keys-api"; import { importVideoInputFromURL, uploadVideoInput } from "@/features/media/media-api"; import { PageHeader } from "@/shared/components/page-header"; import { cn } from "@/shared/lib/cn"; -type CreativeMode = "chat" | "image" | "video"; +type CreativeMode = "chat" | "image" | "video" | "voice"; type ConversationMessage = ChatMessage & { id: string; reasoning?: string; @@ -94,7 +100,7 @@ export function CreativeConsolePage() { const [selectedKeyId, setSelectedKeyId] = useState(""); const [secretState, setSecretState] = useState(null); const [keyError, setKeyError] = useState(""); - const [selectedModels, setSelectedModels] = useState>({ chat: "", image: "", video: "" }); + const [selectedModels, setSelectedModels] = useState>({ chat: "", image: "", video: "", voice: "" }); const [chatToolbarElement, setChatToolbarElement] = useState(null); const requestedSecretKeyRef = useRef(""); @@ -124,11 +130,13 @@ export function CreativeConsolePage() { chat: uniqueModelsByPublicID(permittedModels.filter((model) => model.capability === "chat" || model.capability === "responses")), image: uniqueModelsByPublicID(permittedModels.filter((model) => model.capability === "image")), video: uniqueModelsByPublicID(permittedModels.filter((model) => model.capability === "video")), + voice: uniqueModelsByPublicID(permittedModels.filter((model) => model.capability === "tts" || model.capability === "stt" || model.capability === "realtime")), }), [permittedModels]); const effectiveModels = useMemo>(() => ({ chat: modelGroups.chat.some((model) => model.publicId === selectedModels.chat) ? selectedModels.chat : modelGroups.chat[0]?.publicId ?? "", image: modelGroups.image.some((model) => model.publicId === selectedModels.image) ? selectedModels.image : modelGroups.image[0]?.publicId ?? "", video: modelGroups.video.some((model) => model.publicId === selectedModels.video) ? selectedModels.video : modelGroups.video[0]?.publicId ?? "", + voice: modelGroups.voice.some((model) => model.publicId === selectedModels.voice) ? selectedModels.voice : modelGroups.voice[0]?.publicId ?? "", }), [modelGroups, selectedModels]); const secretMutation = useMutation({ @@ -193,6 +201,7 @@ export function CreativeConsolePage() { {t("creativeConsole.modes.chat")} {t("creativeConsole.modes.image")} + {t("creativeConsole.modes.voice")} @@ -220,6 +229,7 @@ export function CreativeConsolePage() { + @@ -1071,6 +1081,132 @@ function VideoResult({ requestId, status, loading, error, onRetry }: { requestId ); } + +function VoicePanel({ apiKey, model, modelOptions, onModelChange }: CreativePanelProps) { + const { t } = useTranslation(); + const [subMode, setSubMode] = useState<"tts" | "stt">("tts"); + const [prompt, setPrompt] = useState(""); + const [language, setLanguage] = useState("zh"); + const [voiceId, setVoiceId] = useState("eve"); + const [audioFile, setAudioFile] = useState(null); + const [ttsResult, setTtsResult] = useState(null); + const [sttResult, setSttResult] = useState(null); + const fileInputRef = useRef(null); + + const voicesQuery = useQuery({ + queryKey: ["creative-console", "voices", apiKey, model], + queryFn: ({ signal }) => listVoices({ apiKey, model: model || "grok-voice-latest", signal }), + enabled: Boolean(apiKey), + staleTime: 60_000, + }); + const voices = voicesQuery.data ?? []; + useEffect(() => { + if (voices.length === 0) return; + if (!voices.some((voice) => voice.voiceId === voiceId)) { + setVoiceId(voices[0].voiceId); + } + }, [voiceId, voices]); + + const ttsMutation = useMutation({ + mutationFn: () => synthesizeSpeech({ apiKey, model: model || "grok-voice-latest", text: prompt.trim(), voiceId, language }), + onSuccess: (result) => { + setTtsResult(result); + setSttResult(null); + }, + }); + const sttMutation = useMutation({ + mutationFn: async () => { + if (!audioFile) throw new Error(t("creativeConsole.errors.noAudio")); + return transcribeSpeech({ apiKey, model: model || "grok-transcribe", file: audioFile, language }); + }, + onSuccess: (result) => { + setSttResult(result); + setTtsResult(null); + }, + }); + + function submit(event: FormEvent) { + event.preventDefault(); + if (!apiKey || !model) return; + if (subMode === "tts") { + if (!prompt.trim() || ttsMutation.isPending) return; + ttsMutation.reset(); + ttsMutation.mutate(); + return; + } + if (!audioFile || sttMutation.isPending) return; + sttMutation.reset(); + sttMutation.mutate(); + } + + const busy = ttsMutation.isPending || sttMutation.isPending; + const languageOptions = ["auto", "zh", "en", "ja", "ko", "fr", "de", "es"] as const; + + return ( +
+
+ {!ttsResult && !sttResult && !busy ? : null} + {busy ? : null} + {ttsResult ? ( +
+
+ ) : null} + {sttResult ? ( +
+

{sttResult.text}

+
+ {[sttResult.language, typeof sttResult.duration === "number" ? `${sttResult.duration.toFixed(2)}s` : ""].filter(Boolean).join(" · ")} +
+
+ ) : null} + {ttsMutation.isError ?
{ttsMutation.error.message}
: null} + {sttMutation.isError ?
{sttMutation.error.message}
: null} +
+
+
+ + +
+ {subMode === "tts" ? ( +