diff --git a/backend/go.mod b/backend/go.mod index ea822164..764639ad 100644 --- a/backend/go.mod +++ b/backend/go.mod @@ -14,7 +14,10 @@ require ( github.com/golang-jwt/jwt/v5 v5.3.1 github.com/google/uuid v1.6.0 github.com/gorilla/websocket v1.5.3 + github.com/metacubex/sing v0.5.7 + github.com/metacubex/sing-vmess v0.2.5 github.com/redis/go-redis/v9 v9.21.0 + github.com/refraction-networking/utls v1.6.7 github.com/shadowsocks/go-shadowsocks2 v0.1.5 github.com/swaggo/files v1.0.1 github.com/swaggo/gin-swagger v1.6.1 @@ -41,6 +44,7 @@ require ( github.com/bytedance/sonic v1.15.0 // indirect github.com/bytedance/sonic/loader v0.5.0 // indirect github.com/cespare/xxhash/v2 v2.3.0 // indirect + github.com/cloudflare/circl v1.3.7 // indirect github.com/cloudwego/base64x v0.1.6 // indirect github.com/dustin/go-humanize v1.0.1 // indirect github.com/gabriel-vasile/mimetype v1.4.12 // indirect @@ -55,6 +59,7 @@ require ( github.com/go-playground/validator/v10 v10.30.1 // indirect github.com/goccy/go-json v0.10.5 // indirect github.com/goccy/go-yaml v1.19.2 // indirect + github.com/gofrs/uuid/v5 v5.3.2 // indirect github.com/jackc/pgpassfile v1.0.0 // indirect github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect github.com/jackc/pgx/v5 v5.6.0 // indirect diff --git a/backend/go.sum b/backend/go.sum index c4c442f6..066a5245 100644 --- a/backend/go.sum +++ b/backend/go.sum @@ -36,6 +36,8 @@ github.com/bytedance/sonic/loader v0.5.0 h1:gXH3KVnatgY7loH5/TkeVyXPfESoqSBSBEiD github.com/bytedance/sonic/loader v0.5.0/go.mod h1:AR4NYCk5DdzZizZ5djGqQ92eEhCCcdf5x77udYiSJRo= github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs= github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= +github.com/cloudflare/circl v1.3.7 h1:qlCDlTPz2n9fu58M0Nh1J/JzcFpfgkFHHX3O35r5vcU= +github.com/cloudflare/circl v1.3.7/go.mod h1:sRTcRWXGLrKw6yIGJ+l7amYJFfAXbZG0kBSc8r4zxgA= 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= @@ -80,6 +82,8 @@ github.com/goccy/go-json v0.10.5 h1:Fq85nIqj+gXn/S5ahsiTlK3TmC85qgirsdTP/+DeaC4= github.com/goccy/go-json v0.10.5/go.mod h1:oq7eo15ShAhp70Anwd5lgX2pLfOS3QCiwU/PULtXL6M= github.com/goccy/go-yaml v1.19.2 h1:PmFC1S6h8ljIz6gMRBopkjP1TVT7xuwrButHID66PoM= github.com/goccy/go-yaml v1.19.2/go.mod h1:XBurs7gK8ATbW4ZPGKgcbrY1Br56PdM69F7LkFRi1kA= +github.com/gofrs/uuid/v5 v5.3.2 h1:2jfO8j3XgSwlz/wHqemAEugfnTlikAYHhnqQ8Xh4fE0= +github.com/gofrs/uuid/v5 v5.3.2/go.mod h1:CDOjlDMVAtN56jqyRUZh58JT31Tiw7/oQyEXZV+9bD8= github.com/golang-jwt/jwt/v5 v5.3.1 h1:kYf81DTWFe7t+1VvL7eS+jKFVWaUnK9cB1qbwn63YCY= github.com/golang-jwt/jwt/v5 v5.3.1/go.mod h1:fxCRLWMO43lRc8nhHWY6LGqRcf+1gQWArsqaEUEa5bE= github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8= @@ -128,6 +132,10 @@ github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWE github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= github.com/mattn/go-sqlite3 v1.14.22 h1:2gZY6PC6kBnID23Tichd1K+Z0oS6nE/XwU+Vz/5o4kU= github.com/mattn/go-sqlite3 v1.14.22/go.mod h1:Uh1q+B4BYcTPb+yiD3kU8Ct7aC0hY9fxUwlHK0RXw+Y= +github.com/metacubex/sing v0.5.7 h1:8OC+fhKFSv/l9ehEhJRaZZAOuthfZo68SteBVLe8QqM= +github.com/metacubex/sing v0.5.7/go.mod h1:ypf0mjwlZm0sKdQSY+yQvmsbWa0hNPtkeqyRMGgoN+w= +github.com/metacubex/sing-vmess v0.2.5 h1:m9Zt5I27lB9fmLMZfism9sH2LcnAfShZfwSkf6/KJoE= +github.com/metacubex/sing-vmess v0.2.5/go.mod h1:AwtlzUgf8COe9tRYAKqWZ+leDH7p5U98a0ZUpYehl8Q= github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg= github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= @@ -154,6 +162,8 @@ github.com/quic-go/quic-go v0.59.0 h1:OLJkp1Mlm/aS7dpKgTc6cnpynnD2Xg7C1pwL6vy/SA github.com/quic-go/quic-go v0.59.0/go.mod h1:upnsH4Ju1YkqpLXC305eW3yDZ4NfnNbmQRCMWS58IKU= github.com/redis/go-redis/v9 v9.21.0 h1:FPBE4hhbAke+TLmcY3WkpbDffJEomdqPn3HYiqAtL9E= github.com/redis/go-redis/v9 v9.21.0/go.mod h1:v/M13XI1PVCDcm01VtPFOADfZtHf8YW3baQf57KlIkA= +github.com/refraction-networking/utls v1.6.7 h1:zVJ7sP1dJx/WtVuITug3qYUq034cDq9B2MR1K67ULZM= +github.com/refraction-networking/utls v1.6.7/go.mod h1:BC3O4vQzye5hqpmDTWUqi4P5DDhzJfkV1tdqtawQIH0= 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= diff --git a/backend/internal/app/application.go b/backend/internal/app/application.go index eb86333d..9d49bcdd 100644 --- a/backend/internal/app/application.go +++ b/backend/internal/app/application.go @@ -212,6 +212,7 @@ func New(ctx context.Context, cfg config.Config, logger *slog.Logger) (*Applicat ClientVersion: cfg.Provider.Build.ClientVersion, ClientIdentifier: cfg.Provider.Build.ClientIdentifier, TokenAuth: cfg.Provider.Build.TokenAuth, UserAgent: cfg.Provider.Build.UserAgent, ResponseHeaderTimeout: cfg.Provider.Build.ResponseHeaderTimeout.Value(), + StreamIdleTimeout: cfg.Provider.Build.StreamIdleTimeout.Value(), }, cipher) cliAdapter.SetLogger(logger) cliAdapter.SetEgress(egressManager) @@ -387,6 +388,7 @@ func New(ctx context.Context, cfg config.Config, logger *slog.Logger) (*Applicat ClientVersion: next.Provider.Build.ClientVersion, ClientIdentifier: next.Provider.Build.ClientIdentifier, TokenAuth: next.Provider.Build.TokenAuth, UserAgent: next.Provider.Build.UserAgent, ResponseHeaderTimeout: next.Provider.Build.ResponseHeaderTimeout.Value(), + StreamIdleTimeout: next.Provider.Build.StreamIdleTimeout.Value(), }) egressManager.UpdateBuildResponseHeaderTimeout(next.Provider.Build.ResponseHeaderTimeout.Value()) egressManager.UpdateBuildStreamIdleTimeout(next.Provider.Build.StreamIdleTimeout.Value()) diff --git a/backend/internal/application/egress/probe_match.go b/backend/internal/application/egress/probe_match.go new file mode 100644 index 00000000..c9f8bdb7 --- /dev/null +++ b/backend/internal/application/egress/probe_match.go @@ -0,0 +1,62 @@ +package egress + +import ( + "regexp" + "strings" + "unicode" +) + +const ( + MatchContains = "contains" + MatchLastLine = "last_line" + MatchRegex = "regex" +) + +func NormalizeMatchMode(mode string) string { + switch strings.ToLower(strings.TrimSpace(mode)) { + case MatchLastLine, "last-line", "lastline": + return MatchLastLine + case MatchRegex, "regexp": + return MatchRegex + default: + return MatchContains + } +} + +func lastNonEmptyLine(text string) string { + lines := strings.Split(text, "\n") + for i := len(lines) - 1; i >= 0; i-- { + line := strings.TrimSpace(lines[i]) + if line != "" { + return line + } + } + return "" +} + +// MatchExpected reports whether the probe body satisfies the expected marker. +// An empty expected string always matches so throughput-only profiles can skip +// content checks. +func MatchExpected(text, expected, mode string) bool { + expected = strings.TrimSpace(expected) + if expected == "" { + return true + } + text = strings.TrimRightFunc(text, unicode.IsSpace) + switch NormalizeMatchMode(mode) { + case MatchLastLine: + line := lastNonEmptyLine(text) + if line == "" { + return false + } + return strings.EqualFold(line, expected) + case MatchRegex: + re, err := regexp.Compile(expected) + if err != nil { + return false + } + return re.MatchString(text) + default: + return strings.Contains(text, expected) + } +} diff --git a/backend/internal/application/egress/probe_match_test.go b/backend/internal/application/egress/probe_match_test.go new file mode 100644 index 00000000..c39c5079 --- /dev/null +++ b/backend/internal/application/egress/probe_match_test.go @@ -0,0 +1,31 @@ +package egress + +import "testing" + +func TestMatchExpectedModes(t *testing.T) { + text := "天空是蓝的,因为瑞利散射。\nQUALITY_OK\n" + if !MatchExpected(text, "QUALITY_OK", MatchLastLine) { + t.Fatal("last line QUALITY_OK should match") + } + if MatchExpected("hello\nNOT_OK", "QUALITY_OK", MatchLastLine) { + t.Fatal("wrong last line must not match") + } + if !MatchExpected("prefix QUALITY_OK suffix", "QUALITY_OK", MatchContains) { + t.Fatal("contains should match") + } + if MatchExpected("done\nstatus=QUALITY_OK", "QUALITY_OK", MatchLastLine) { + t.Fatal("last-line mode must require the complete marker line") + } + if MatchExpected("done\nNOT_QUALITY_OK", "QUALITY_OK", MatchLastLine) { + t.Fatal("last-line mode must not accept a marker substring") + } + if !MatchExpected("alpha\nbeta QUALITY_OK", `QUALITY_OK$`, MatchRegex) { + t.Fatal("regex should match") + } + if MatchExpected("nope", "[", MatchRegex) { + t.Fatal("invalid regex must not match") + } + if !MatchExpected("anything", "", MatchContains) { + t.Fatal("empty expected is always a match") + } +} diff --git a/backend/internal/application/egress/quality_probe_test.go b/backend/internal/application/egress/quality_probe_test.go index af09b4a0..eb34adf0 100644 --- a/backend/internal/application/egress/quality_probe_test.go +++ b/backend/internal/application/egress/quality_probe_test.go @@ -71,3 +71,32 @@ func TestProbeQualityRejectsUnsupportedNodeAndMissingProber(t *testing.T) { t.Fatalf("missing prober error = %v", err) } } + +func TestProbeQualityScopesThinkingGuardToReasoningBuildModels(t *testing.T) { + repository := &qualityProbeRepository{node: domain.Node{ + ID: 7, Scope: domain.ScopeBuild, Enabled: true, EncryptedProxyURL: "encrypted", + }} + prober := &qualityProberStub{} + service := NewService(repository, nil, "") + service.SetQualityProber(prober) + + result, err := service.ProbeQuality(context.Background(), 7, QualityProbeInput{ + ClientKeyID: 3, Model: "grok-4.5", RequireThinking: true, + }) + if err != nil { + t.Fatal(err) + } + if !prober.input.RequireThinking || !result.ThinkingRequired { + t.Fatalf("reasoning model probe=%#v result=%#v", prober.input, result) + } + + result, err = service.ProbeQuality(context.Background(), 7, QualityProbeInput{ + ClientKeyID: 3, Model: "grok-composer-2.5-fast", RequireThinking: true, + }) + if err != nil { + t.Fatal(err) + } + if prober.input.RequireThinking || result.ThinkingRequired { + t.Fatalf("non-reasoning model probe=%#v result=%#v", prober.input, result) + } +} diff --git a/backend/internal/application/egress/service.go b/backend/internal/application/egress/service.go index 7bdefb59..308f024b 100644 --- a/backend/internal/application/egress/service.go +++ b/backend/internal/application/egress/service.go @@ -11,6 +11,7 @@ import ( accountdomain "github.com/chenyme/grok2api/backend/internal/domain/account" domain "github.com/chenyme/grok2api/backend/internal/domain/egress" + modeldomain "github.com/chenyme/grok2api/backend/internal/domain/model" "github.com/chenyme/grok2api/backend/internal/infra/security" "github.com/chenyme/grok2api/backend/internal/pkg/tunnelproxy" "github.com/chenyme/grok2api/backend/internal/repository" @@ -41,6 +42,8 @@ type QualityProbeInput struct { Model string Prompt string Expected string + MatchMode string + RequireThinking bool MaxOutputTokens int } @@ -59,6 +62,7 @@ type QualityProbeResult struct { VisibleCharacters int OutputTokensPerSecond float64 ExpectedMatched bool + ThinkingRequired bool ResponseSHA256 string } @@ -128,13 +132,15 @@ func (s *Service) ProbeQuality(ctx context.Context, nodeID uint64, input Quality input.Model = strings.TrimSpace(input.Model) input.Prompt = strings.TrimSpace(input.Prompt) input.Expected = strings.TrimSpace(input.Expected) + rawMatchMode := strings.TrimSpace(input.MatchMode) + input.MatchMode = NormalizeMatchMode(input.MatchMode) if input.Model == "" { return QualityProbeResult{}, fmt.Errorf("%w: model 必填", ErrInvalidInput) } if input.Prompt == "" { input.Prompt = DefaultQualityProbePrompt } - if input.Expected == "" { + if input.Expected == "" && rawMatchMode == "" { input.Expected = DefaultQualityProbeExpected } if len(input.Prompt) > MaxQualityProbePromptBytes || len(input.Expected) > MaxQualityProbeExpectedBytes { @@ -162,7 +168,16 @@ func (s *Service) ProbeQuality(ctx context.Context, nodeID uint64, input Quality if prober == nil { return QualityProbeResult{}, ErrQualityProbeUnavailable } - return prober.ProbeEgressQuality(ctx, nodeID, input) + // A profile may request the thinking guard, but only a known reasoning-capable + // Build model can make zero reasoning tokens meaningful. Unknown/custom and + // non-reasoning models stay observable without being falsely quarantined. + input.RequireThinking = input.RequireThinking && modeldomain.SupportsReasoningForProvider(accountdomain.ProviderBuild, input.Model) + result, err := prober.ProbeEgressQuality(ctx, nodeID, input) + if err != nil { + return QualityProbeResult{}, err + } + result.ThinkingRequired = input.RequireThinking + return result, nil } // AccountBindingRepository is intentionally narrow so existing account diff --git a/backend/internal/application/egress/subscription.go b/backend/internal/application/egress/subscription.go index 42ddff98..329c4cde 100644 --- a/backend/internal/application/egress/subscription.go +++ b/backend/internal/application/egress/subscription.go @@ -104,7 +104,7 @@ func fetchProxySubscription(ctx context.Context, value string, viaProxy string) } } request.Header.Set("Accept", "text/plain, text/*;q=0.9, */*;q=0.1") - request.Header.Set("User-Agent", "grok2api-egress-subscription/1") + request.Header.Set("User-Agent", "Clash.Meta") response, err := client.Do(request) if err != nil { return nil, err @@ -368,6 +368,9 @@ func parseProxySubscription(value string) ([]subscriptionEntry, int, error) { return entries, decodedSkipped, nil } } + if entries, clashSkipped, matched := parseClashSubscription(value); matched && len(entries) > 0 { + return entries, clashSkipped, nil + } return nil, skipped, errors.New("订阅中没有可用的代理节点") } diff --git a/backend/internal/application/egress/subscription_clash.go b/backend/internal/application/egress/subscription_clash.go new file mode 100644 index 00000000..56c15bcd --- /dev/null +++ b/backend/internal/application/egress/subscription_clash.go @@ -0,0 +1,289 @@ +package egress + +import ( + "encoding/base64" + "encoding/json" + "errors" + "fmt" + "net" + "net/url" + "strconv" + "strings" + + "gopkg.in/yaml.v3" +) + +type clashSubscription struct { + Proxies []yaml.Node `yaml:"proxies"` +} + +type clashProxy struct { + Type string `yaml:"type"` + Server string `yaml:"server"` + Port clashInteger `yaml:"port"` + Username string `yaml:"username"` + Password string `yaml:"password"` + Cipher string `yaml:"cipher"` + UUID string `yaml:"uuid"` + AlterID clashInteger `yaml:"alterId"` + Network string `yaml:"network"` + TLS bool `yaml:"tls"` + ServerName string `yaml:"servername"` + SNI string `yaml:"sni"` + Flow string `yaml:"flow"` + ALPN clashStringList `yaml:"alpn"` + SkipCertVerify bool `yaml:"skip-cert-verify"` + ClientFingerprint string `yaml:"client-fingerprint"` + Plugin string `yaml:"plugin"` + WSOptions clashWebSocketOption `yaml:"ws-opts"` + RealityOptions clashRealityOptions `yaml:"reality-opts"` +} + +type clashWebSocketOption struct { + Path string `yaml:"path"` + Headers map[string]string `yaml:"headers"` +} + +type clashRealityOptions struct { + PublicKey string `yaml:"public-key"` + ShortID string `yaml:"short-id"` +} + +type clashInteger int + +func (value *clashInteger) UnmarshalYAML(node *yaml.Node) error { + if node == nil || node.Kind != yaml.ScalarNode { + return errors.New("Clash 整数字段格式无效") + } + parsed, err := strconv.ParseInt(strings.TrimSpace(node.Value), 10, 32) + if err != nil { + return errors.New("Clash 整数字段格式无效") + } + *value = clashInteger(parsed) + return nil +} + +type clashStringList []string + +func (value *clashStringList) UnmarshalYAML(node *yaml.Node) error { + if node == nil { + return errors.New("Clash 字符串列表格式无效") + } + if node.Kind == yaml.AliasNode { + if node.Alias == nil { + return errors.New("Clash 字符串列表格式无效") + } + node = node.Alias + } + var items []string + switch node.Kind { + case yaml.ScalarNode: + items = strings.Split(node.Value, ",") + case yaml.SequenceNode: + if err := node.Decode(&items); err != nil { + return errors.New("Clash 字符串列表格式无效") + } + default: + return errors.New("Clash 字符串列表格式无效") + } + normalized := make([]string, 0, len(items)) + for _, item := range items { + if item = strings.TrimSpace(item); item != "" { + normalized = append(normalized, item) + } + } + *value = normalized + return nil +} + +type clashVMessShare struct { + Version string `json:"v"` + Address string `json:"add"` + Port string `json:"port"` + UUID string `json:"id"` + AlterID string `json:"aid"` + Cipher string `json:"scy"` + Network string `json:"net"` + TLS string `json:"tls,omitempty"` + ServerName string `json:"sni,omitempty"` + ALPN string `json:"alpn,omitempty"` + Host string `json:"host,omitempty"` + Path string `json:"path,omitempty"` + AllowInsecure bool `json:"allowInsecure,omitempty"` +} + +func parseClashSubscription(value string) ([]subscriptionEntry, int, bool) { + var document clashSubscription + if err := yaml.Unmarshal([]byte(strings.TrimPrefix(value, "\ufeff")), &document); err != nil || document.Proxies == nil { + return nil, 0, false + } + if len(document.Proxies) > maxSubscriptionEntries { + return nil, len(document.Proxies), true + } + lines := make([]string, 0, len(document.Proxies)) + skipped := 0 + for index := range document.Proxies { + var proxy clashProxy + if err := document.Proxies[index].Decode(&proxy); err != nil { + skipped++ + continue + } + line, err := clashProxyURL(proxy) + if err != nil { + skipped++ + continue + } + lines = append(lines, line) + } + entries, lineSkipped := parseProxyLines(strings.Join(lines, "\n")) + return entries, skipped + lineSkipped, true +} + +func clashProxyURL(proxy clashProxy) (string, error) { + server, err := clashProxyServer(proxy.Server, int(proxy.Port)) + if err != nil { + return "", err + } + proxyType := strings.ToLower(strings.TrimSpace(proxy.Type)) + switch proxyType { + case "http": + scheme := "http" + if proxy.TLS { + scheme = "https" + } + return clashStandardProxyURL(scheme, server, proxy.Username, proxy.Password), nil + case "socks5": + if proxy.TLS { + return "", errors.New("暂不支持 TLS SOCKS5") + } + return clashStandardProxyURL("socks5", server, proxy.Username, proxy.Password), nil + case "ss": + if strings.TrimSpace(proxy.Plugin) != "" { + return "", errors.New("暂不支持 Shadowsocks plugin") + } + method := strings.ToLower(strings.TrimSpace(proxy.Cipher)) + if method == "" || proxy.Password == "" { + return "", errors.New("Shadowsocks cipher/password 不能为空") + } + credential := base64.RawURLEncoding.EncodeToString([]byte(method + ":" + proxy.Password)) + return "ss://" + credential + "@" + server, nil + case "trojan": + if proxy.Password == "" { + return "", errors.New("Trojan password 不能为空") + } + query, err := clashTunnelQuery(proxy, "tls") + if err != nil { + return "", err + } + return (&url.URL{Scheme: "trojan", User: url.User(proxy.Password), Host: server, RawQuery: query.Encode()}).String(), nil + case "vless": + if proxy.UUID == "" { + return "", errors.New("VLESS UUID 不能为空") + } + security := "none" + if proxy.RealityOptions.PublicKey != "" || proxy.RealityOptions.ShortID != "" { + security = "reality" + } else if proxy.TLS { + security = "tls" + } + query, err := clashTunnelQuery(proxy, security) + if err != nil { + return "", err + } + query.Set("encryption", "none") + if flow := strings.TrimSpace(proxy.Flow); flow != "" { + query.Set("flow", flow) + } + if security == "reality" { + query.Set("pbk", proxy.RealityOptions.PublicKey) + query.Set("sid", proxy.RealityOptions.ShortID) + query.Set("fp", firstNonEmptySubscription(proxy.ClientFingerprint, "chrome")) + } + return (&url.URL{Scheme: "vless", User: url.User(proxy.UUID), Host: server, RawQuery: query.Encode()}).String(), nil + case "vmess": + return clashVMessURL(proxy) + default: + return "", fmt.Errorf("暂不支持 Clash 代理类型 %q", proxyType) + } +} + +func clashProxyServer(host string, port int) (string, error) { + host = strings.Trim(strings.TrimSpace(host), "[]") + if host == "" || port < 1 || port > 65535 { + return "", errors.New("Clash 代理服务器地址无效") + } + return net.JoinHostPort(host, strconv.Itoa(port)), nil +} + +func clashStandardProxyURL(scheme, server, username, password string) string { + value := &url.URL{Scheme: scheme, Host: server} + if username != "" || password != "" { + value.User = url.UserPassword(username, password) + } + return value.String() +} + +func clashTunnelQuery(proxy clashProxy, security string) (url.Values, error) { + transport := strings.ToLower(strings.TrimSpace(proxy.Network)) + if transport == "" { + transport = "tcp" + } + if transport == "websocket" { + transport = "ws" + } + query := make(url.Values) + query.Set("type", transport) + query.Set("security", security) + query.Set("sni", firstNonEmptySubscription(proxy.ServerName, proxy.SNI, proxy.Server)) + if proxy.SkipCertVerify { + query.Set("allowInsecure", "1") + } + if len(proxy.ALPN) != 0 { + query.Set("alpn", strings.Join(proxy.ALPN, ",")) + } + if transport == "ws" { + query.Set("path", firstNonEmptySubscription(proxy.WSOptions.Path, "/")) + query.Set("host", firstNonEmptySubscription(proxy.WSOptions.Headers["Host"], proxy.WSOptions.Headers["host"], proxy.ServerName, proxy.SNI, proxy.Server)) + } + return query, nil +} + +func clashVMessURL(proxy clashProxy) (string, error) { + if proxy.UUID == "" { + return "", errors.New("VMess UUID 不能为空") + } + network := strings.ToLower(strings.TrimSpace(proxy.Network)) + if network == "" { + network = "tcp" + } + if network == "websocket" { + network = "ws" + } + share := clashVMessShare{ + Version: "2", Address: proxy.Server, Port: strconv.Itoa(int(proxy.Port)), UUID: proxy.UUID, + AlterID: strconv.Itoa(int(proxy.AlterID)), Cipher: firstNonEmptySubscription(proxy.Cipher, "auto"), Network: network, + ServerName: firstNonEmptySubscription(proxy.ServerName, proxy.SNI, proxy.Server), ALPN: strings.Join(proxy.ALPN, ","), + AllowInsecure: proxy.SkipCertVerify, + } + if proxy.TLS { + share.TLS = "tls" + } + if network == "ws" { + share.Path = firstNonEmptySubscription(proxy.WSOptions.Path, "/") + share.Host = firstNonEmptySubscription(proxy.WSOptions.Headers["Host"], proxy.WSOptions.Headers["host"], proxy.ServerName, proxy.SNI, proxy.Server) + } + encoded, err := json.Marshal(share) + if err != nil { + return "", err + } + return "vmess://" + base64.RawStdEncoding.EncodeToString(encoded), nil +} + +func firstNonEmptySubscription(values ...string) string { + for _, value := range values { + if value = strings.TrimSpace(value); value != "" { + return value + } + } + return "" +} diff --git a/backend/internal/application/egress/subscription_test.go b/backend/internal/application/egress/subscription_test.go index d7bb2cb4..2536b967 100644 --- a/backend/internal/application/egress/subscription_test.go +++ b/backend/internal/application/egress/subscription_test.go @@ -15,6 +15,7 @@ import ( 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" ) type subscriptionSyncRepositoryStub struct { @@ -100,6 +101,197 @@ func TestParseProxySubscriptionImportsSupportedTunnelSchemes(t *testing.T) { } } +func TestParseProxySubscriptionAcceptsClashYAML(t *testing.T) { + content := ` +proxies: + - name: http + type: http + server: http.example + port: 8080 + username: user + password: pass + - name: socks + type: socks5 + server: socks.example + port: 1080 + - name: trojan + type: trojan + server: trojan.example + port: 443 + password: secret + network: ws + sni: edge.example + ws-opts: + path: /ws + headers: + Host: edge.example + - name: reality + type: vless + server: reality.example + port: 443 + uuid: 123e4567-e89b-12d3-a456-426614174000 + network: tcp + tls: true + servername: edge.example + flow: xtls-rprx-vision + client-fingerprint: chrome + alpn: [h2, http/1.1] + reality-opts: + public-key: SOW7P-17ibm_-kz-QUQwGGyitSbsa5wOmRGAigGvDH8 + short-id: 0123456789abcdef + - name: shadowsocks + type: ss + server: ss.example + port: 8388 + cipher: aes-128-gcm + password: secret + - name: vmess + type: vmess + server: vmess.example + port: 443 + uuid: 123e4567-e89b-12d3-a456-426614174000 + alterId: 0 + cipher: auto + network: ws + tls: true + servername: edge.example + alpn: [h2, http/1.1] + ws-opts: + path: /vmess + headers: + Host: edge.example + - name: ignored-hysteria + type: hysteria2 + server: hy.example + port: 443 + password: secret + - name: ignored-tuic + type: tuic + server: tuic.example + port: 443 + password: secret +proxy-groups: + - name: auto + type: select + proxies: [http, socks] +` + entries, skipped, err := parseProxySubscription(content) + if err != nil { + t.Fatal(err) + } + if len(entries) != 6 || skipped != 2 { + t.Fatalf("Clash entries=%d skipped=%d values=%#v", len(entries), skipped, entries) + } + var realityConfig tunnelproxy.Config + var vmessConfig tunnelproxy.Config + for _, entry := range entries { + if !strings.HasPrefix(entry.ProxyURL, "vless://") && !strings.HasPrefix(entry.ProxyURL, "vmess://") { + continue + } + config, parseErr := tunnelproxy.Parse(entry.ProxyURL) + if parseErr != nil { + t.Fatal(parseErr) + } + switch config.Scheme { + case "vless": + realityConfig = config + case "vmess": + vmessConfig = config + } + } + if realityConfig.Security != "reality" || realityConfig.Flow != "xtls-rprx-vision" || realityConfig.RealityPublicKey == "" || realityConfig.RealityShortID != "0123456789abcdef" || strings.Join(realityConfig.ALPN, ",") != "h2,http/1.1" { + t.Fatalf("Clash Reality config = %#v", realityConfig) + } + if strings.Join(vmessConfig.ALPN, ",") != "h2,http/1.1" { + t.Fatalf("Clash VMess config = %#v", vmessConfig) + } +} + +func TestParseProxySubscriptionSkipsMalformedClashEntriesIndividually(t *testing.T) { + content := ` +proxies: + - type: http + server: valid.example + port: "8080" + - type: hysteria2 + server: ignored.example + port: invalid +` + entries, skipped, err := parseProxySubscription(content) + if err != nil { + t.Fatal(err) + } + if len(entries) != 1 || skipped != 1 || entries[0].ProxyURL != "http://valid.example:8080" { + t.Fatalf("entries=%#v skipped=%d", entries, skipped) + } +} + +func TestFetchProxySubscriptionUsesClashUserAgent(t *testing.T) { + var userAgent string + proxy := httptest.NewServer(http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) { + userAgent = request.Header.Get("User-Agent") + _, _ = writer.Write([]byte("http://proxy.example:8080\n")) + })) + defer proxy.Close() + + body, err := fetchProxySubscription(context.Background(), "http://1.1.1.1/subscription", proxy.URL) + if err != nil { + t.Fatal(err) + } + if userAgent != "Clash.Meta" || !strings.Contains(string(body), "proxy.example") { + t.Fatalf("User-Agent=%q body=%q", userAgent, body) + } +} + +func TestClashRealityPreservesSupportedClientFingerprints(t *testing.T) { + content := ` +proxies: + - type: vless + server: chrome.example + port: 443 + uuid: 123e4567-e89b-12d3-a456-426614174000 + flow: xtls-rprx-vision + client-fingerprint: chrome + reality-opts: &reality + public-key: SOW7P-17ibm_-kz-QUQwGGyitSbsa5wOmRGAigGvDH8 + short-id: 0123456789abcdef + - type: vless + server: edge.example + port: 443 + uuid: 123e4567-e89b-12d3-a456-426614174000 + flow: xtls-rprx-vision + client-fingerprint: edge + reality-opts: *reality + - type: vless + server: safari.example + port: 443 + uuid: 123e4567-e89b-12d3-a456-426614174000 + flow: xtls-rprx-vision + client-fingerprint: safari + reality-opts: *reality +` + entries, skipped, err := parseProxySubscription(content) + if err != nil { + t.Fatal(err) + } + if len(entries) != 3 || skipped != 0 { + t.Fatalf("entries=%d skipped=%d", len(entries), skipped) + } + fingerprints := make(map[string]bool) + for _, entry := range entries { + config, parseErr := tunnelproxy.Parse(entry.ProxyURL) + if parseErr != nil { + t.Fatal(parseErr) + } + fingerprints[config.ClientFingerprint] = true + } + for _, fingerprint := range []string{"chrome", "edge", "safari"} { + if !fingerprints[fingerprint] { + t.Fatalf("missing client fingerprint %q", fingerprint) + } + } +} + 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/application/gateway/quality_probe.go b/backend/internal/application/gateway/quality_probe.go index 3ae37a0c..31fc3c7f 100644 --- a/backend/internal/application/gateway/quality_probe.go +++ b/backend/internal/application/gateway/quality_probe.go @@ -185,7 +185,7 @@ func (s *Service) ProbeEgressQuality(ctx context.Context, nodeID uint64, input e FirstTokenMS: firstTokenMS, DurationMS: durationMS, GenerationMS: generationMS, ChunkCount: chunkCount, OutputTokens: usage.OutputTokens, ReasoningTokens: usage.ReasoningTokens, VisibleTokens: visibleTokens, VisibleCharacters: visibleCharacters, OutputTokensPerSecond: outputTokensPerSecond, - ExpectedMatched: strings.Contains(text, input.Expected), ResponseSHA256: hex.EncodeToString(digest[:]), + ExpectedMatched: egressapp.MatchExpected(text, input.Expected, input.MatchMode), ResponseSHA256: hex.EncodeToString(digest[:]), }, nil } diff --git a/backend/internal/application/gateway/service.go b/backend/internal/application/gateway/service.go index e7dfb24d..bf89113f 100644 --- a/backend/internal/application/gateway/service.go +++ b/backend/internal/application/gateway/service.go @@ -44,6 +44,7 @@ var ( ErrConversationUnsupported = errors.New("目标模型不支持当前对话协议") ErrVideoInputTooLarge = errors.New("视频参考图片编码后总输入超过 32 MiB") ErrVideoInputUnavailable = errors.New("视频临时输入不存在或已过期") + ErrVideoParameterInvalid = errors.New("视频请求参数无效") ErrVideoOperationUnsupported = errors.New("视频编辑/延长仅支持路由到 Console grok-imagine-video") ErrLedgerUnavailable = errors.New("计费账本暂不可用") ) @@ -759,6 +760,17 @@ func (s *Service) selectSchedulableMediaRouteWithQuotaMode(ctx context.Context, if err != nil { return fallback, nil, err } + return s.selectSchedulableEligibleMediaRouteWithQuotaMode(ctx, eligible, key, consumesQuota, resolveQuotaMode) +} + +// selectSchedulableEligibleMediaRouteWithQuotaMode selects an account plan +// from routes that already passed capability, client-key, and Provider support +// checks. Callers may apply request-specific route constraints between the +// eligibility and scheduling phases without evaluating disallowed routes. +func (s *Service) selectSchedulableEligibleMediaRouteWithQuotaMode(ctx context.Context, eligible []modeldomain.Route, key clientkey.Key, consumesQuota bool, resolveQuotaMode func(modeldomain.Route) string) (modeldomain.Route, *selectionSession, error) { + if len(eligible) == 0 { + return modeldomain.Route{}, nil, ErrNoAvailableAccount + } var firstSelectionErr error for _, route := range eligible { quotaMode := "" diff --git a/backend/internal/application/gateway/video.go b/backend/internal/application/gateway/video.go index 82414ff7..58245927 100644 --- a/backend/internal/application/gateway/video.go +++ b/backend/internal/application/gateway/video.go @@ -121,6 +121,26 @@ func (s *Service) CreateVideo(ctx context.Context, input VideoInput) (media.Job, } } } + routes, err := s.models.GetByPublicIDCandidates(ctx, input.PublicModel) + if err != nil { + return media.Job{}, ErrModelNotFound + } + routes, err = routesForVideoOperation(routes, operation) + if err != nil { + return media.Job{}, err + } + providerSupported := func(providerValue account.Provider) bool { + _, ok := s.providers.Videos(providerValue) + return ok + } + routes, _, err = s.eligibleMediaRoutes(routes, input.ClientKey, model.CapabilityVideo, providerSupported) + if err != nil { + return media.Job{}, err + } + routes, err = routesForVideoParameters(routes, operation, input.Resolution, len(input.ReferenceURLs), input.Duration) + if err != nil { + return media.Job{}, err + } allRefs := videoInputReferences(input.ImageURL, input.ReferenceURLs) if err := s.validateVideoInputReferences(ctx, allRefs, "image"); err != nil { return media.Job{}, err @@ -134,26 +154,12 @@ func (s *Service) CreateVideo(ctx context.Context, input VideoInput) (media.Job, if err != nil { return media.Job{}, err } - routes, err := s.models.GetByPublicIDCandidates(ctx, input.PublicModel) - if err != nil { - return media.Job{}, ErrModelNotFound - } - routes, err = routesForVideoOperation(routes, operation) - if err != nil { - return media.Job{}, err - } - route, selection, err := s.selectSchedulableMediaRouteWithQuotaMode(ctx, routes, input.ClientKey, model.CapabilityVideo, true, func(providerValue account.Provider) bool { - _, ok := s.providers.Videos(providerValue) - return ok - }, func(route model.Route) string { + route, selection, err := s.selectSchedulableEligibleMediaRouteWithQuotaMode(ctx, routes, input.ClientKey, true, func(route model.Route) string { return videoQuotaMode(route.Provider, s.providers.QuotaMode(route.Provider, route.UpstreamModel), input.Resolution) }) if err != nil { return media.Job{}, err } - if err := validateVideoRouteParameters(operation, route.UpstreamModel, input.Resolution, len(input.ReferenceURLs) > 0); err != nil { - return media.Job{}, err - } if err := s.checkLedgerReady(); err != nil { return media.Job{}, err } @@ -197,11 +203,57 @@ func (s *Service) CreateVideo(ctx context.Context, input VideoInput) (media.Job, return job, nil } -func validateVideoRouteParameters(operation provider.VideoOperation, upstreamModel, resolution string, hasReferences bool) error { - if operation != provider.VideoOperationGenerate || !strings.EqualFold(strings.TrimSpace(resolution), "1080p") { +// routesForVideoParameters removes only routes that cannot accept this request. +// Callers must first apply capability, client-key, and Provider eligibility: +// the same public model may aggregate Console, Build, and Web routes with +// different input contracts. +func routesForVideoParameters(routes []model.Route, operation provider.VideoOperation, resolution string, referenceCount, duration int) ([]model.Route, error) { + if len(routes) == 0 { + return routes, nil + } + compatible := make([]model.Route, 0, len(routes)) + var firstErr error + for _, candidate := range routes { + if err := validateVideoRouteParameters(candidate.Provider, operation, candidate.UpstreamModel, resolution, referenceCount, duration); err != nil { + if firstErr == nil { + firstErr = err + } + continue + } + compatible = append(compatible, candidate) + } + if len(compatible) == 0 && firstErr != nil { + return nil, firstErr + } + return compatible, nil +} + +// Console 视频输入的上限与时长按「Provider + 入口字段 + 上游模型」分档。 +// /v1/videos/generations 是异步接口,只在 adapter 层拦截会产出必然失败的任务; +// adapter 仍保留同一约束,作为最终出站边界的防御校验。 +func validateVideoRouteParameters(providerValue account.Provider, operation provider.VideoOperation, upstreamModel, resolution string, referenceCount, duration int) error { + if operation != provider.VideoOperationGenerate { return nil } - if strings.TrimSpace(upstreamModel) != "grok-imagine-video-1.5" { + trimmedModel := strings.TrimSpace(upstreamModel) + hasReferences := referenceCount > 0 + if providerValue == account.ProviderConsole && (trimmedModel == "grok-imagine-video" || trimmedModel == "grok-imagine-video-1.5") { + // 实测:8 张 reference_images 上游回 400 + // "Too many reference images: 8. Maximum allowed is 7."(两个视频模型一致)。 + if referenceCount > provider.ConsoleVideoMaxReferenceImages { + return fmt.Errorf("%w: Console reference_images 最多 %d 张,当前为 %d 张", ErrVideoParameterInvalid, provider.ConsoleVideoMaxReferenceImages, referenceCount) + } + // 实测:grok-imagine-video 的 reference-to-video 上游回 400 + // "Duration 15s exceeds the maximum allowed for reference-to-video, which is 10s."; + // 走 image 字段的 image-to-video 与 grok-imagine-video-1.5 都保持 15s。 + if trimmedModel == "grok-imagine-video" && hasReferences && duration > provider.ConsoleVideoMaxReferenceDurationSeconds { + return fmt.Errorf("%w: Console %s 的参考图生视频最长 %d 秒,当前为 %d 秒", ErrVideoParameterInvalid, trimmedModel, provider.ConsoleVideoMaxReferenceDurationSeconds, duration) + } + } + if !strings.EqualFold(strings.TrimSpace(resolution), "1080p") { + return nil + } + if trimmedModel != "grok-imagine-video-1.5" { return fmt.Errorf("%w: %s 不支持 1080p", ErrVideoOperationUnsupported, upstreamModel) } if hasReferences { diff --git a/backend/internal/application/gateway/video_test.go b/backend/internal/application/gateway/video_test.go index fddc1e91..07445f74 100644 --- a/backend/internal/application/gateway/video_test.go +++ b/backend/internal/application/gateway/video_test.go @@ -165,14 +165,101 @@ func TestVideoPricingLeavesUnmeasurableOperationsUnpriced(t *testing.T) { } } +// 上游对 Console 视频的这两条限制原先只在 provider 层拦截,而生成接口是异步的, +// 客户端会先拿到 request_id 再从轮询里读到失败任务。入队前校验让错误立刻可见。 +func TestVideoRouteParametersRejectConsoleReferenceLimits(t *testing.T) { + // 实测:8 张 reference_images 上游回 400 "Too many reference images: 8. Maximum allowed is 7." + if err := validateVideoRouteParameters(account.ProviderConsole, provider.VideoOperationGenerate, "grok-imagine-video-1.5", "720p", 8, 6); !errors.Is(err, ErrVideoParameterInvalid) { + t.Fatalf("8 references error = %v", err) + } + if err := validateVideoRouteParameters(account.ProviderConsole, provider.VideoOperationGenerate, "grok-imagine-video-1.5", "720p", 7, 6); err != nil { + t.Fatalf("7 references error = %v", err) + } + // 实测:grok-imagine-video 的 reference-to-video 回 400 + // "Duration 15s exceeds the maximum allowed for reference-to-video, which is 10s." + if err := validateVideoRouteParameters(account.ProviderConsole, provider.VideoOperationGenerate, "grok-imagine-video", "720p", 1, 15); !errors.Is(err, ErrVideoParameterInvalid) { + t.Fatalf("base model reference duration error = %v", err) + } + if err := validateVideoRouteParameters(account.ProviderConsole, provider.VideoOperationGenerate, "grok-imagine-video", "720p", 1, 10); err != nil { + t.Fatalf("base model 10s reference error = %v", err) + } + // image-to-video(无 reference_images)与 1.5 都保持 15s。 + if err := validateVideoRouteParameters(account.ProviderConsole, provider.VideoOperationGenerate, "grok-imagine-video", "720p", 0, 15); err != nil { + t.Fatalf("base model text/first-frame 15s error = %v", err) + } + if err := validateVideoRouteParameters(account.ProviderConsole, provider.VideoOperationGenerate, "grok-imagine-video-1.5", "720p", 2, 15); err != nil { + t.Fatalf("1.5 multi-reference 15s error = %v", err) + } + // Build 使用相同的 1.5 上游模型名,但支持通用上限 8;不能因同名套用 Console 的 7 张限制。 + if err := validateVideoRouteParameters(account.ProviderBuild, provider.VideoOperationGenerate, "grok-imagine-video-1.5", "720p", 8, 15); err != nil { + t.Fatalf("Build 1.5 references error = %v", err) + } + // Web 同样与 Console 共享基础模型名,不受 Console 专属时长限制。 + if err := validateVideoRouteParameters(account.ProviderWeb, provider.VideoOperationGenerate, "grok-imagine-video", "720p", 8, 15); err != nil { + t.Fatalf("Web base references error = %v", err) + } +} + +func TestRoutesForVideoParametersKeepsCompatibleSameNameProviders(t *testing.T) { + routes := []model.Route{ + {ID: 1, PublicID: "shared-video", Provider: account.ProviderConsole, UpstreamModel: "grok-imagine-video-1.5"}, + {ID: 2, PublicID: "shared-video", Provider: account.ProviderBuild, UpstreamModel: "grok-imagine-video-1.5"}, + } + compatible, err := routesForVideoParameters(routes, provider.VideoOperationGenerate, "720p", 8, 15) + if err != nil { + t.Fatal(err) + } + if len(compatible) != 1 || compatible[0].ID != 2 { + t.Fatalf("compatible routes = %#v", compatible) + } + if _, err := routesForVideoParameters(routes[:1], provider.VideoOperationGenerate, "720p", 8, 15); !errors.Is(err, ErrVideoParameterInvalid) { + t.Fatalf("Console-only invalid route error = %v", err) + } +} + +func TestCreateVideoAppliesRouteConstraintsAfterKeyEligibilityAndBeforeInputIO(t *testing.T) { + routes := []model.Route{ + {ID: 1, PublicID: "shared-video", Provider: account.ProviderBuild, UpstreamModel: "grok-imagine-video-1.5", Capability: model.CapabilityResponses}, + {ID: 2, PublicID: "shared-video", Provider: account.ProviderBuild, UpstreamModel: "grok-imagine-video-1.5", Capability: model.CapabilityVideo}, + {ID: 3, PublicID: "shared-video", Provider: account.ProviderConsole, UpstreamModel: "grok-imagine-video-1.5", Capability: model.CapabilityVideo}, + } + jobs := &videoUsageRepository{} + assets := &videoAssetStoreStub{inputID: "unused", inputData: []byte("unused")} + service := &Service{ + models: &aliasRouteResolver{byPublic: map[string][]model.Route{"shared-video": routes}}, + clientKeys: clientkeyapp.NewService(nil, nil, nil, 60, 4, nil), + providers: provider.NewRegistry(consoleVideoAdmissionAdapter{}), + mediaJobs: jobs, mediaAssets: assets, mediaQueue: make(chan string, 1), mediaQueued: make(map[string]struct{}), + logger: slog.Default(), + } + references := make([]string, provider.ConsoleVideoMaxReferenceImages+1) + for index := range references { + references[index] = VideoInputFileReference(fmt.Sprintf("unused_%d", index)) + } + _, err := service.CreateVideo(context.Background(), VideoInput{ + PublicModel: "shared-video", Prompt: "animate", Duration: 6, Resolution: "720p", + ReferenceURLs: references, + ClientKey: clientkey.Key{ + ProviderScope: clientkey.ProviderScopeConsole, + AllowedModels: []uint64{3}, + }, + }) + if !errors.Is(err, ErrVideoParameterInvalid) { + t.Fatalf("CreateVideo error = %v", err) + } + if assets.openInputCalls != 0 || jobs.createCalls != 0 || len(service.mediaQueue) != 0 || len(service.mediaQueued) != 0 { + t.Fatalf("side effects: input opens=%d job creates=%d queue=%d queued-set=%d", assets.openInputCalls, jobs.createCalls, len(service.mediaQueue), len(service.mediaQueued)) + } +} + func TestVideo1080pValidationUsesResolvedUpstreamModel(t *testing.T) { - if err := validateVideoRouteParameters(provider.VideoOperationGenerate, "grok-imagine-video-1.5", "1080P", false); err != nil { + if err := validateVideoRouteParameters(account.ProviderConsole, provider.VideoOperationGenerate, "grok-imagine-video-1.5", "1080P", 0, 6); err != nil { t.Fatalf("1.5 text/image 1080p rejected: %v", err) } - if err := validateVideoRouteParameters(provider.VideoOperationGenerate, "grok-imagine-video", "1080p", false); !errors.Is(err, ErrVideoOperationUnsupported) { + if err := validateVideoRouteParameters(account.ProviderConsole, provider.VideoOperationGenerate, "grok-imagine-video", "1080p", 0, 6); !errors.Is(err, ErrVideoOperationUnsupported) { t.Fatalf("legacy 1080p error = %v", err) } - if err := validateVideoRouteParameters(provider.VideoOperationGenerate, "grok-imagine-video-1.5", "1080p", true); !errors.Is(err, ErrVideoOperationUnsupported) { + if err := validateVideoRouteParameters(account.ProviderConsole, provider.VideoOperationGenerate, "grok-imagine-video-1.5", "1080p", 1, 6); !errors.Is(err, ErrVideoOperationUnsupported) { t.Fatalf("reference 1080p error = %v", err) } } @@ -443,6 +530,14 @@ type videoPersistAdapter struct { lastCredentialID uint64 } +type consoleVideoAdmissionAdapter struct{} + +func (consoleVideoAdmissionAdapter) Provider() account.Provider { return account.ProviderConsole } + +func (consoleVideoAdmissionAdapter) GenerateVideo(context.Context, provider.VideoRequest) (provider.VideoResult, error) { + return provider.VideoResult{}, errors.New("unexpected Console video generation") +} + func (a *videoPersistAdapter) Provider() account.Provider { return account.ProviderWeb } func (a *videoPersistAdapter) GenerateVideo(context.Context, provider.VideoRequest) (provider.VideoResult, error) { @@ -460,15 +555,16 @@ func (a *videoPersistAdapter) DownloadVideo(_ context.Context, credential accoun } type videoAssetStoreStub struct { - saveCalls int - openAsset media.Asset - openData []byte - openErr error - inputID string - inputData []byte - inputSize int64 - inputKind string - inputMIME string + saveCalls int + openInputCalls int + openAsset media.Asset + openData []byte + openErr error + inputID string + inputData []byte + inputSize int64 + inputKind string + inputMIME string } func (s *videoAssetStoreStub) SaveVideo(_ context.Context, jobID, contentType string, body io.Reader) (media.Asset, error) { @@ -497,6 +593,7 @@ func (s *videoAssetStoreStub) OpenVideo(_ context.Context, id string) (media.Ass } func (s *videoAssetStoreStub) OpenInputAsset(_ context.Context, id string) (media.Asset, io.ReadCloser, error) { + s.openInputCalls++ if id != s.inputID || len(s.inputData) == 0 { return media.Asset{}, nil, errors.New("not implemented") } @@ -534,9 +631,16 @@ func (r *durableVideoAuditRecorder) CreateDurable(_ context.Context, value audit return nil } -type videoUsageRepository struct{ job media.Job } +type videoUsageRepository struct { + job media.Job + createCalls int +} -func (r *videoUsageRepository) CreateMediaJob(context.Context, media.Job) error { return nil } +func (r *videoUsageRepository) CreateMediaJob(_ context.Context, value media.Job) error { + r.createCalls++ + r.job = value + return nil +} func (r *videoUsageRepository) GetMediaJob(context.Context, string, uint64) (media.Job, error) { return r.job, nil diff --git a/backend/internal/infra/config/config.go b/backend/internal/infra/config/config.go index d7613841..f7a3c83f 100644 --- a/backend/internal/infra/config/config.go +++ b/backend/internal/infra/config/config.go @@ -28,7 +28,7 @@ const ( ClearanceModeOnDemand = "on_demand" DefaultStatsigSignerURL = "https://grok.wodf.de/sign" DefaultFlareSolverrURL = "http://flaresolverr:8191" - RecommendedBuildClientVersion = "0.2.119" + RecommendedBuildClientVersion = "1.0.4" RecommendedBuildUserAgent = "grok-shell/" + RecommendedBuildClientVersion + " (linux; x86_64)" maxServerBodyBytes = 256 << 20 @@ -211,10 +211,10 @@ type LocalMediaConfig struct { } type RoutingConfig struct { - StickyTTL Duration `yaml:"stickyTTL"` - CooldownBase Duration `yaml:"cooldownBase"` - CooldownMax Duration `yaml:"cooldownMax"` - CapacityWait Duration `yaml:"capacityWait"` + StickyTTL Duration `yaml:"stickyTTL"` + CooldownBase Duration `yaml:"cooldownBase"` + CooldownMax Duration `yaml:"cooldownMax"` + CapacityWait Duration `yaml:"capacityWait"` MaxAttempts int `yaml:"maxAttempts"` VideoMaxAttempts int `yaml:"videoMaxAttempts"` PreferFreeBuild bool `yaml:"preferFreeBuild"` diff --git a/backend/internal/infra/config/config_test.go b/backend/internal/infra/config/config_test.go index 9e2b2fa1..bee1da7f 100644 --- a/backend/internal/infra/config/config_test.go +++ b/backend/internal/infra/config/config_test.go @@ -239,13 +239,13 @@ func TestBuildResponseHeaderTimeoutIsRuntimeOnly(t *testing.T) { func TestDefaultGrokBuildClientVersionMatchesLocalBaseline(t *testing.T) { build := defaultConfig().Provider.Build - if RecommendedBuildClientVersion != "0.2.119" { + if RecommendedBuildClientVersion != "1.0.4" { t.Fatalf("recommended clientVersion = %q", RecommendedBuildClientVersion) } if build.ClientVersion != RecommendedBuildClientVersion { t.Fatalf("clientVersion = %q", build.ClientVersion) } - if RecommendedBuildUserAgent != "grok-shell/0.2.119 (linux; x86_64)" { + if RecommendedBuildUserAgent != "grok-shell/1.0.4 (linux; x86_64)" { t.Fatalf("recommended userAgent = %q", RecommendedBuildUserAgent) } if build.UserAgent != RecommendedBuildUserAgent { diff --git a/backend/internal/infra/egress/tlsclient.go b/backend/internal/infra/egress/tlsclient.go index 52b4d425..f8aa4d10 100644 --- a/backend/internal/infra/egress/tlsclient.go +++ b/backend/internal/infra/egress/tlsclient.go @@ -24,6 +24,16 @@ type browserClient struct{ inner tlsclient.HttpClient } var chromeMajorPattern = regexp.MustCompile(`(?i)Chrome/(\d+)`) func (l *Lease) DialWebSocket(ctx context.Context, endpoint string, headers fhttp.Header, handshakeTimeout time.Duration) (*websocket.Conn, *fhttp.Response, error) { + return l.dialWebSocket(ctx, endpoint, headers, handshakeTimeout, true) +} + +// DialWebSocketDeferredForbidden leaves a 403 handshake response for the +// caller to classify before invalidating the browser-session Clearance. +func (l *Lease) DialWebSocketDeferredForbidden(ctx context.Context, endpoint string, headers fhttp.Header, handshakeTimeout time.Duration) (*websocket.Conn, *fhttp.Response, error) { + return l.dialWebSocket(ctx, endpoint, headers, handshakeTimeout, false) +} + +func (l *Lease) dialWebSocket(ctx context.Context, endpoint string, headers fhttp.Header, handshakeTimeout time.Duration, invalidateForbidden bool) (*websocket.Conn, *fhttp.Response, error) { if l == nil || l.browser == nil { return nil, nil, errors.New("当前出口客户端不支持浏览器 WebSocket") } @@ -38,7 +48,7 @@ func (l *Lease) DialWebSocket(ctx context.Context, endpoint string, headers fhtt if l.proxyPool && safeProxyConnectionFailure(err, fhttpResponseAsHTTP(response)) { l.browser.CloseIdleConnections() } - if response != nil && response.StatusCode == http.StatusForbidden && l.clearanceManager != nil && l.clearanceKey != "" { + if invalidateForbidden && response != nil && response.StatusCode == http.StatusForbidden && l.clearanceManager != nil && l.clearanceKey != "" { l.clearanceManager.invalidateClearanceKey(l.clearanceKey, l.client) } return connection, response, err diff --git a/backend/internal/infra/provider/cli/adapter.go b/backend/internal/infra/provider/cli/adapter.go index 763c278f..3169b9fd 100644 --- a/backend/internal/infra/provider/cli/adapter.go +++ b/backend/internal/infra/provider/cli/adapter.go @@ -39,6 +39,7 @@ type Config struct { TokenAuth string UserAgent string ResponseHeaderTimeout time.Duration + StreamIdleTimeout time.Duration } const ( @@ -68,6 +69,7 @@ type Adapter struct { func NewAdapter(cfg Config, cipher *security.Cipher) *Adapter { cfg.ResponseHeaderTimeout = normalizeBuildResponseHeaderTimeout(cfg.ResponseHeaderTimeout) + cfg.StreamIdleTimeout = normalizeBuildStreamIdleTimeout(cfg.StreamIdleTimeout) transport := newBuildDirectTransport(cfg.ResponseHeaderTimeout) httpClient := &http.Client{Transport: transport} // The official CLI uses a persistent machine identity. The gateway does not collect machine fingerprints; @@ -156,6 +158,7 @@ func buildBotFlaggedFromClaims(claims map[string]any) bool { func (a *Adapter) UpdateConfig(cfg Config) { cfg.ResponseHeaderTimeout = normalizeBuildResponseHeaderTimeout(cfg.ResponseHeaderTimeout) + cfg.StreamIdleTimeout = normalizeBuildStreamIdleTimeout(cfg.StreamIdleTimeout) a.cfgMu.Lock() previousTimeout := a.cfg.ResponseHeaderTimeout a.cfg = cfg @@ -204,6 +207,13 @@ func normalizeBuildResponseHeaderTimeout(value time.Duration) time.Duration { return value } +func normalizeBuildStreamIdleTimeout(value time.Duration) time.Duration { + if value <= 0 { + return settingsdomain.DefaultBuildStreamIdleTimeout + } + return value +} + func (a *Adapter) config() Config { a.cfgMu.RLock() defer a.cfgMu.RUnlock() @@ -243,7 +253,7 @@ func (a *Adapter) ForwardResponse(ctx context.Context, request provider.Response } return invalidResponsesResponse(err), nil } - body, err = normalizeBuildRequest(body, request.Model) + body, err = normalizeBuildRequest(body, request.Model, request.Operation) if err != nil { if request.Operation == conversation.OperationChat || request.Operation == conversation.OperationMessages { return invalidConversationResponse(request.Operation, err), nil @@ -364,6 +374,9 @@ func (a *Adapter) ForwardResponse(ctx context.Context, request provider.Response } } } + if request.Streaming && isHTTPSuccess(resp.StatusCode) && resp.Body != nil { + resp.Body = wrapBuildSemanticIdle(resp.Body, a.config().StreamIdleTimeout) + } modelCatalogChanged := a.modelCatalogChanged(request.Credential.ID, resp.Header.Get("x-models-etag")) // Capture or clear reasoning replay in the upstream Responses shape before protocol conversion. if a.shouldCaptureReplay(request, resp, replayKey) { diff --git a/backend/internal/infra/provider/cli/adapter_test.go b/backend/internal/infra/provider/cli/adapter_test.go index 27e89378..ab26634a 100644 --- a/backend/internal/infra/provider/cli/adapter_test.go +++ b/backend/internal/infra/provider/cli/adapter_test.go @@ -6,6 +6,7 @@ import ( "context" "encoding/base64" "encoding/json" + "errors" "io" "net/http" "net/http/httptest" @@ -17,6 +18,7 @@ import ( "github.com/chenyme/grok2api/backend/internal/domain/account" modeldomain "github.com/chenyme/grok2api/backend/internal/domain/model" + settingsdomain "github.com/chenyme/grok2api/backend/internal/domain/settings" infraegress "github.com/chenyme/grok2api/backend/internal/infra/egress" "github.com/chenyme/grok2api/backend/internal/infra/provider" "github.com/chenyme/grok2api/backend/internal/infra/provider/conversation" @@ -60,16 +62,29 @@ func TestResponseRequestForcedEgressOverridesCredentialBinding(t *testing.T) { } func TestAdapterHotUpdatesDirectResponseHeaderTimeout(t *testing.T) { - adapter := NewAdapter(Config{ResponseHeaderTimeout: 2 * time.Minute}, nil) + adapter := NewAdapter(Config{ResponseHeaderTimeout: 2 * time.Minute, StreamIdleTimeout: 3 * time.Minute}, nil) before := adapter.base.current.Load() if before.ResponseHeaderTimeout != 2*time.Minute { t.Fatalf("initial timeout = %s", before.ResponseHeaderTimeout) } - adapter.UpdateConfig(Config{ResponseHeaderTimeout: 7 * time.Minute}) + if got := adapter.config().StreamIdleTimeout; got != 3*time.Minute { + t.Fatalf("initial stream idle timeout = %s", got) + } + adapter.UpdateConfig(Config{ResponseHeaderTimeout: 7 * time.Minute, StreamIdleTimeout: 11 * time.Minute}) after := adapter.base.current.Load() if after == before || after.ResponseHeaderTimeout != 7*time.Minute { t.Fatalf("updated transport=%p timeout=%s", after, after.ResponseHeaderTimeout) } + if got := adapter.config().StreamIdleTimeout; got != 11*time.Minute { + t.Fatalf("updated stream idle timeout = %s", got) + } +} + +func TestAdapterDefaultsStreamIdleTimeout(t *testing.T) { + adapter := NewAdapter(Config{}, nil) + if got := adapter.config().StreamIdleTimeout; got != settingsdomain.DefaultBuildStreamIdleTimeout { + t.Fatalf("stream idle timeout = %s, want %s", got, settingsdomain.DefaultBuildStreamIdleTimeout) + } } func TestCredentialMetadataMarksNumericBotFlagOneOrTwo(t *testing.T) { @@ -1098,6 +1113,40 @@ func TestForwardResponseInjectsPromptCacheKeyAfterChatConversion(t *testing.T) { } } +func TestForwardResponseRejectsInvalidChatWebSearchBeforeUpstream(t *testing.T) { + cipher, err := security.NewCipher(base64.StdEncoding.EncodeToString(make([]byte, 32))) + if err != nil { + t.Fatal(err) + } + encrypted, err := cipher.Encrypt("access-token") + if err != nil { + t.Fatal(err) + } + adapter := NewAdapter(Config{BaseURL: "https://cli-chat-proxy.grok.com/v1"}, cipher) + upstreamCalled := false + adapter.http.Transport = roundTripFunc(func(request *http.Request) (*http.Response, error) { + upstreamCalled = true + return nil, errors.New("unexpected upstream call") + }) + + response, err := adapter.ForwardResponse(context.Background(), provider.ResponseResourceRequest{ + Credential: account.Credential{Provider: account.ProviderBuild, AuthType: account.AuthTypeOAuth, EncryptedAccessToken: encrypted}, + Method: http.MethodPost, Path: "/responses", Model: "grok-4.6", NormalizeBody: true, + Operation: conversation.OperationChat, + Body: []byte(`{ + "model":"public","messages":[{"role":"user","content":"search"}], + "tools":[{"type":"web_search","filters":{"allowed_domains":["allow.example"],"excluded_domains":["deny.example"]}}] + }`), + }) + if err != nil { + t.Fatal(err) + } + defer response.Body.Close() + if upstreamCalled || response.StatusCode != http.StatusBadRequest { + t.Fatalf("upstreamCalled=%v status=%d", upstreamCalled, response.StatusCode) + } +} + func TestShouldSkipXAIFallbackForSafetyAndBlocked(t *testing.T) { if !shouldSkipXAIFallback([]byte(`{"code":"permission-denied","error":"Content violates usage guidelines. SAFETY_CHECK_TYPE_VIOLENCE"}`)) { t.Fatal("safety body must skip XAI fallback") diff --git a/backend/internal/infra/provider/cli/normalize.go b/backend/internal/infra/provider/cli/normalize.go index 1a50f12b..8f5374ef 100644 --- a/backend/internal/infra/provider/cli/normalize.go +++ b/backend/internal/infra/provider/cli/normalize.go @@ -7,6 +7,7 @@ import ( "strings" modeldomain "github.com/chenyme/grok2api/backend/internal/domain/model" + "github.com/chenyme/grok2api/backend/internal/infra/provider/conversation" ) // normalizeResponsesRequest 改写路由字段和兼容别名,并为上游不支持的新工具协议建立请求级映射。 @@ -16,7 +17,7 @@ func normalizeResponsesRequest(body []byte, model string) ([]byte, *responsesToo return nil, nil, fmt.Errorf("解析 Responses 请求: %w", err) } payload["model"] = mustJSON(model) - if _, err := normalizeBuildRequestPayload(payload, model); err != nil { + if _, err := normalizeBuildRequestPayload(payload, model, conversation.OperationResponses); err != nil { return nil, nil, err } if responseFormat, exists := payload["response_format"]; exists { @@ -57,12 +58,12 @@ func normalizeResponsesRequest(body []byte, model string) ([]byte, *responsesToo // normalizeBuildRequest applies the stable compatibility boundary shared by Responses, // Chat Completions, and Anthropic Messages before the request reaches Grok Build. -func normalizeBuildRequest(body []byte, model string) ([]byte, error) { +func normalizeBuildRequest(body []byte, model, operation string) ([]byte, error) { var payload map[string]json.RawMessage if err := json.Unmarshal(body, &payload); err != nil { return nil, fmt.Errorf("解析 Build 请求: %w", err) } - changed, err := normalizeBuildRequestPayload(payload, model) + changed, err := normalizeBuildRequestPayload(payload, model, operation) if err != nil { return nil, err } @@ -72,7 +73,7 @@ func normalizeBuildRequest(body []byte, model string) ([]byte, error) { return json.Marshal(payload) } -func normalizeBuildRequestPayload(payload map[string]json.RawMessage, model string) (bool, error) { +func normalizeBuildRequestPayload(payload map[string]json.RawMessage, model, operation string) (bool, error) { changed := false // client_metadata is a Codex transport envelope and may contain local paths, // repository remotes, and installation/session identifiers. It is consumed by @@ -84,6 +85,27 @@ func normalizeBuildRequestPayload(payload map[string]json.RawMessage, model stri if normalizeBuildReasoningEffortPayload(payload, model) { changed = true } + // grok-build 1.0.4 always requests a concise reasoning summary from its + // Responses backend, even when it uses the model's default effort. Chat + // Completions has no separate summary parameter, so make that Build-specific + // compatibility contract explicit without changing native Responses, + // Console, or Web semantics. + if operation == conversation.OperationChat { + var reasoning map[string]json.RawMessage + if raw := payload["reasoning"]; !isEmptyJSON(raw) { + if err := json.Unmarshal(raw, &reasoning); err != nil { + return false, fmt.Errorf("解析 Build reasoning: %w", err) + } + } + if reasoning == nil { + reasoning = make(map[string]json.RawMessage) + } + if isEmptyJSON(reasoning["summary"]) { + reasoning["summary"] = mustJSON("concise") + payload["reasoning"] = mustJSON(reasoning) + changed = true + } + } defaultsChanged, err := applyBuildResponseDefaults(payload) if err != nil { return false, err diff --git a/backend/internal/infra/provider/cli/normalize_test.go b/backend/internal/infra/provider/cli/normalize_test.go index ceb32a4e..0c6bfee0 100644 --- a/backend/internal/infra/provider/cli/normalize_test.go +++ b/backend/internal/infra/provider/cli/normalize_test.go @@ -65,7 +65,7 @@ func TestNormalizeBuildReasoningEffort(t *testing.T) { for _, test := range tests { t.Run(test.name, func(t *testing.T) { body := []byte(`{"reasoning":{"effort":"` + test.effort + `"},"input":"hello"}`) - normalized, err := normalizeBuildRequest(body, test.model) + normalized, err := normalizeBuildRequest(body, test.model, conversation.OperationResponses) if err != nil { t.Fatal(err) } @@ -81,13 +81,55 @@ func TestNormalizeBuildReasoningEffort(t *testing.T) { } } +func TestNormalizeBuildChatRequestsVisibleReasoningSummary(t *testing.T) { + tests := []struct { + name string + operation string + body string + wantSummary string + wantEffort string + wantObject bool + }{ + {name: "Chat model default", operation: conversation.OperationChat, body: `{"input":"hello"}`, wantSummary: "concise", wantObject: true}, + {name: "Chat explicit effort", operation: conversation.OperationChat, body: `{"input":"hello","reasoning":{"effort":"high"}}`, wantSummary: "concise", wantEffort: "high", wantObject: true}, + {name: "Chat explicit summary", operation: conversation.OperationChat, body: `{"input":"hello","reasoning":{"effort":"high","summary":"detailed"}}`, wantSummary: "detailed", wantEffort: "high", wantObject: true}, + {name: "native Responses remains caller controlled", operation: conversation.OperationResponses, body: `{"input":"hello"}`}, + } + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + normalized, err := normalizeBuildRequest([]byte(test.body), "grok-4.6", test.operation) + if err != nil { + t.Fatal(err) + } + var payload map[string]any + if err := json.Unmarshal(normalized, &payload); err != nil { + t.Fatal(err) + } + reasoning, ok := payload["reasoning"].(map[string]any) + if ok != test.wantObject { + t.Fatalf("reasoning = %#v, want object %v", payload["reasoning"], test.wantObject) + } + if !ok { + return + } + if reasoning["summary"] != test.wantSummary { + t.Fatalf("summary = %#v, want %q", reasoning["summary"], test.wantSummary) + } + if effort, _ := reasoning["effort"].(string); effort != test.wantEffort { + t.Fatalf("effort = %q, want %q", effort, test.wantEffort) + } + }) + } +} + func TestNormalizeBuildMaxAcrossCompatibilityProtocols(t *testing.T) { tests := []struct { - name string - body []byte + name string + body []byte + operation string }{ - {name: "responses", body: []byte(`{"reasoning":{"effort":"max"},"input":"hello"}`)}, - {name: "chat completions", body: func() []byte { + {name: "responses", operation: conversation.OperationResponses, body: []byte(`{"reasoning":{"effort":"max"},"input":"hello"}`)}, + {name: "chat completions", operation: conversation.OperationChat, body: func() []byte { converted, _, err := conversation.ConvertRequestWithOptions( []byte(`{"model":"public","messages":[{"role":"user","content":"hello"}],"reasoning_effort":"max"}`), "grok-4.6", @@ -98,7 +140,7 @@ func TestNormalizeBuildMaxAcrossCompatibilityProtocols(t *testing.T) { } return converted }()}, - {name: "anthropic messages", body: func() []byte { + {name: "anthropic messages", operation: conversation.OperationMessages, body: func() []byte { converted, _, err := conversation.ConvertRequestWithOptions( []byte(`{"model":"public","max_tokens":64,"messages":[{"role":"user","content":"hello"}],"thinking":{"type":"adaptive"},"output_config":{"effort":"max"}}`), "grok-4.6", @@ -113,7 +155,7 @@ func TestNormalizeBuildMaxAcrossCompatibilityProtocols(t *testing.T) { for _, test := range tests { t.Run(test.name, func(t *testing.T) { - normalized, err := normalizeBuildRequest(test.body, "grok-4.6") + normalized, err := normalizeBuildRequest(test.body, "grok-4.6", test.operation) if err != nil { t.Fatal(err) } @@ -131,11 +173,12 @@ func TestNormalizeBuildMaxAcrossCompatibilityProtocols(t *testing.T) { func TestNormalizeBuildComposerStripsReasoningEffort(t *testing.T) { tests := []struct { - name string - body []byte + name string + body []byte + operation string }{ - {name: "responses", body: []byte(`{"reasoning":{"effort":"high","summary":"auto"},"input":"hello"}`)}, - {name: "chat conversion", body: func() []byte { + {name: "responses", operation: conversation.OperationResponses, body: []byte(`{"reasoning":{"effort":"high","summary":"auto"},"input":"hello"}`)}, + {name: "chat conversion", operation: conversation.OperationChat, body: func() []byte { converted, _, err := conversation.ConvertRequestWithOptions( []byte(`{"model":"public","messages":[{"role":"user","content":"hello"}],"reasoning_effort":"high"}`), modeldomain.GrokComposer25Fast, @@ -146,7 +189,7 @@ func TestNormalizeBuildComposerStripsReasoningEffort(t *testing.T) { } return converted }()}, - {name: "messages conversion", body: func() []byte { + {name: "messages conversion", operation: conversation.OperationMessages, body: func() []byte { converted, _, err := conversation.ConvertRequestWithOptions( []byte(`{"model":"public","max_tokens":64,"messages":[{"role":"user","content":"hello"}],"thinking":{"type":"adaptive"},"output_config":{"effort":"xhigh"}}`), modeldomain.GrokComposer25Fast, @@ -160,7 +203,7 @@ func TestNormalizeBuildComposerStripsReasoningEffort(t *testing.T) { } for _, test := range tests { t.Run(test.name, func(t *testing.T) { - normalized, err := normalizeBuildRequest(test.body, modeldomain.GrokComposer25Fast) + normalized, err := normalizeBuildRequest(test.body, modeldomain.GrokComposer25Fast, test.operation) if err != nil { t.Fatal(err) } @@ -176,7 +219,7 @@ func TestNormalizeBuildComposerStripsReasoningEffort(t *testing.T) { }) } - stripped, err := normalizeBuildRequest([]byte(`{"reasoning":{"effort":"medium"},"input":"hello"}`), modeldomain.GrokComposer25Fast) + stripped, err := normalizeBuildRequest([]byte(`{"reasoning":{"effort":"medium"},"input":"hello"}`), modeldomain.GrokComposer25Fast, conversation.OperationResponses) if err != nil { t.Fatal(err) } @@ -194,7 +237,7 @@ func TestNormalizeBuildRequestAppliesSafeDefaultsAndStripsCodexEnvelope(t *testi "client_metadata":{"cwd":"/private/workspace","git_remote":"ssh://private/repo"}, "include":["web_search_call.action.sources"] }`) - normalized, err := normalizeBuildRequest(body, "grok-4.5") + normalized, err := normalizeBuildRequest(body, "grok-4.5", conversation.OperationResponses) if err != nil { t.Fatal(err) } @@ -216,7 +259,7 @@ func TestNormalizeBuildRequestAppliesSafeDefaultsAndStripsCodexEnvelope(t *testi func TestNormalizeBuildRequestPreservesExplicitStoreAndEncryptedInclude(t *testing.T) { body := []byte(`{"input":"hello","store":true,"include":["reasoning.encrypted_content"],"stream_tool_calls":true}`) - normalized, err := normalizeBuildRequest(body, "grok-4.5") + normalized, err := normalizeBuildRequest(body, "grok-4.5", conversation.OperationResponses) if err != nil { t.Fatal(err) } @@ -230,7 +273,7 @@ func TestNormalizeBuildRequestPreservesExplicitStoreAndEncryptedInclude(t *testi } func TestNormalizeBuildRequestDoesNotInventStreamToolCalls(t *testing.T) { - normalized, err := normalizeBuildRequest([]byte(`{"input":"hello"}`), "grok-4.5") + normalized, err := normalizeBuildRequest([]byte(`{"input":"hello"}`), "grok-4.5", conversation.OperationResponses) if err != nil { t.Fatal(err) } diff --git a/backend/internal/infra/provider/cli/responses_advanced_test.go b/backend/internal/infra/provider/cli/responses_advanced_test.go index 701cba81..9d617d62 100644 --- a/backend/internal/infra/provider/cli/responses_advanced_test.go +++ b/backend/internal/infra/provider/cli/responses_advanced_test.go @@ -188,12 +188,18 @@ func TestResponsesWebSearchAliasesAndOptions(t *testing.T) { t.Fatalf("compatibility warnings = %q", compatibility.warningHeader()) } - for _, supported := range []string{ - `"filters":{"allowed_domains":["example.com"]}`, - `"allowed_domains":["example.com"]`, + for _, supported := range []struct { + fragment string + field string + warning string + }{ + {fragment: `"filters":{"allowed_domains":["example.com"]}`, field: "allowed_domains"}, + {fragment: `"allowed_domains":["example.com"]`, field: "allowed_domains", warning: "web_search_allowed_domains_normalized"}, + {fragment: `"filters":{"excluded_domains":["example.com"]}`, field: "excluded_domains"}, + {fragment: `"excluded_domains":["example.com"]`, field: "excluded_domains", warning: "web_search_excluded_domains_normalized"}, } { normalized, compatibility, err = normalizeResponsesRequest([]byte(`{ - "model":"public","input":"search","tools":[{"type":"web_search",`+supported+`}] + "model":"public","input":"search","tools":[{"type":"web_search",`+supported.fragment+`}] }`), "grok-4.5") if err != nil { t.Fatal(err) @@ -203,15 +209,56 @@ func TestResponsesWebSearchAliasesAndOptions(t *testing.T) { t.Fatal(err) } tool = request["tools"].([]any)[0].(map[string]any) - domains := tool["filters"].(map[string]any)["allowed_domains"].([]any) + domains := tool["filters"].(map[string]any)[supported.field].([]any) if len(domains) != 1 || domains[0] != "example.com" { - t.Fatalf("allowed_domains 未保留: %#v", tool) + t.Fatalf("%s 未保留: %#v", supported.field, tool) } - if strings.Contains(supported, `"allowed_domains"`) && !strings.Contains(supported, `"filters"`) && (compatibility == nil || !strings.Contains(compatibility.warningHeader(), "web_search_allowed_domains_normalized")) { - t.Fatalf("top-level allowed_domains warning = %#v", compatibility) + if supported.warning != "" && (compatibility == nil || !strings.Contains(compatibility.warningHeader(), supported.warning)) { + t.Fatalf("top-level %s warning = %#v", supported.field, compatibility) } } + for _, invalid := range []string{ + `"filters":{"allowed_domains":["a.example","b.example","c.example","d.example","e.example","f.example"]}`, + `"filters":{"excluded_domains":["a.example","b.example","c.example","d.example","e.example","f.example"]}`, + `"filters":{"allowed_domains":["allow.example"],"excluded_domains":["deny.example"]}`, + } { + if _, _, err = normalizeResponsesRequest([]byte(`{ + "model":"public","input":"search","tools":[{"type":"web_search",`+invalid+`}] + }`), "grok-4.5"); err == nil { + t.Fatalf("invalid web_search filters accepted: %s", invalid) + } + } + + normalized, _, err = normalizeResponsesRequest([]byte(`{ + "model":"public","input":"search","tools":[{"type":"web_search","filters":{"excluded_domains":["a.example","b.example","c.example","d.example","e.example"]}}] + }`), "grok-4.6") + if err != nil { + t.Fatalf("five excluded domains must remain valid: %v", err) + } + request = nil + if err := json.Unmarshal(normalized, &request); err != nil { + t.Fatal(err) + } + domains := request["tools"].([]any)[0].(map[string]any)["filters"].(map[string]any)["excluded_domains"].([]any) + if len(domains) != maxWebSearchDomains { + t.Fatalf("excluded_domains count = %d", len(domains)) + } + + normalized, _, err = normalizeResponsesRequest([]byte(`{ + "model":"public","input":"search","tools":[{"type":"web_search","filters":{"allowed_domains":null,"excluded_domains":[]}}] + }`), "grok-4.6") + if err != nil { + t.Fatalf("null/empty domain filters must remain unbounded: %v", err) + } + request = nil + if err := json.Unmarshal(normalized, &request); err != nil { + t.Fatal(err) + } + if tool = request["tools"].([]any)[0].(map[string]any); len(tool) != 1 || tool["type"] != "web_search" { + t.Fatalf("empty domain filters were not omitted: %#v", tool) + } + for _, restricted := range []string{ `"search_content_types":["image"]`, `"filters":{"blocked_domains":["example.com"]}`, diff --git a/backend/internal/infra/provider/cli/responses_compaction_forward.go b/backend/internal/infra/provider/cli/responses_compaction_forward.go index 340c76e5..ed0c5bde 100644 --- a/backend/internal/infra/provider/cli/responses_compaction_forward.go +++ b/backend/internal/infra/provider/cli/responses_compaction_forward.go @@ -134,6 +134,7 @@ func (a *Adapter) forwardGatewayCompactionWithPolicy( return result, nil } + resp.Body = wrapBuildSemanticIdle(resp.Body, a.config().StreamIdleTimeout) data, readErr := io.ReadAll(io.LimitReader(resp.Body, maxCompatibleResponseBytes+1)) _ = resp.Body.Close() if readErr != nil { diff --git a/backend/internal/infra/provider/cli/responses_compaction_test.go b/backend/internal/infra/provider/cli/responses_compaction_test.go index d48baeec..c7af848e 100644 --- a/backend/internal/infra/provider/cli/responses_compaction_test.go +++ b/backend/internal/infra/provider/cli/responses_compaction_test.go @@ -15,6 +15,7 @@ import ( "github.com/chenyme/grok2api/backend/internal/infra/provider" "github.com/chenyme/grok2api/backend/internal/infra/provider/conversation" "github.com/chenyme/grok2api/backend/internal/infra/security" + "github.com/chenyme/grok2api/backend/internal/pkg/neterror" ) func TestGatewayCompactionLifecycle(t *testing.T) { @@ -107,6 +108,46 @@ func TestGatewayCompactionRetryVetoStopsSameAccountRetries(t *testing.T) { } } +func TestGatewayCompactionSemanticIdleIgnoresKeepalives(t *testing.T) { + adapter, encrypted := newCompactionTestAdapter(t) + cfg := adapter.config() + cfg.StreamIdleTimeout = 60 * time.Millisecond + adapter.UpdateConfig(cfg) + + writeDone := make(chan struct{}) + adapter.http.Transport = roundTripFunc(func(request *http.Request) (*http.Response, error) { + reader, writer := io.Pipe() + go func() { + defer close(writeDone) + defer writer.Close() + for { + if _, err := io.WriteString(writer, ": keep-alive\n\n"); err != nil { + return + } + time.Sleep(10 * time.Millisecond) + } + }() + return &http.Response{ + StatusCode: http.StatusOK, + Status: "200 OK", + Header: http.Header{"Content-Type": []string{"text/event-stream"}}, + Body: reader, + Request: request, + }, nil + }) + + request := compactionProviderRequest(encrypted) + _, err := adapter.forwardGatewayCompactionWithPolicy(t.Context(), request, "access-token", request.Body, "", 1, 0) + if !errors.Is(err, neterror.ErrUpstreamStreamIdleTimeout) { + t.Fatalf("compaction error = %v, want ErrUpstreamStreamIdleTimeout", err) + } + select { + case <-writeDone: + case <-time.After(time.Second): + t.Fatal("semantic timeout did not close the compaction response body") + } +} + func TestGatewayCompactionResponseNormalizesPartialUsage(t *testing.T) { response := map[string]any{ "id": "resp_usage", diff --git a/backend/internal/infra/provider/cli/responses_tool_types.go b/backend/internal/infra/provider/cli/responses_tool_types.go index dc20ff59..2a9a93ae 100644 --- a/backend/internal/infra/provider/cli/responses_tool_types.go +++ b/backend/internal/infra/provider/cli/responses_tool_types.go @@ -4,6 +4,8 @@ import ( "fmt" "strings" "time" + + "github.com/chenyme/grok2api/backend/internal/infra/provider/conversation" ) var nativeHostedToolChoiceTypes = map[string]string{ @@ -34,6 +36,8 @@ var webSearchCompatibilityFields = map[string]struct{}{ "safe_search": {}, } +const maxWebSearchDomains = conversation.MaxWebSearchDomains + // normalizeNativeTool preserves native Build tools and removes Tool Search-only fields. func (c *responsesToolCompatibility) normalizeNativeTool(tool map[string]any, _ string) ([]any, error) { converted := cloneJSONObject(tool) @@ -84,7 +88,7 @@ func (c *responsesToolCompatibility) normalizeXSearchTool(tool map[string]any, p return c.normalizeNativeTool(converted, param) } -// normalizeWebSearchTool preserves Build's allowed_domains constraint and safely +// normalizeWebSearchTool preserves Build's allowed/excluded domain constraints and safely // reduces newer controls that cannot be represented with equivalent semantics. func (c *responsesToolCompatibility) normalizeWebSearchTool(tool map[string]any, kind, param string) ([]any, error) { if external, exists := tool["external_web_access"]; exists { @@ -129,6 +133,11 @@ func (c *responsesToolCompatibility) normalizeWebSearchTool(tool map[string]any, c.addWarning("web_search_allowed_domains_normalized") continue } + if key == "excluded_domains" { + c.changed = true + c.addWarning("web_search_excluded_domains_normalized") + continue + } if _, compatible := webSearchCompatibilityFields[key]; !compatible { c.changed = true c.addWarning("web_search_unknown_controls_ignored") @@ -151,57 +160,83 @@ func (c *responsesToolCompatibility) normalizeWebSearchTool(tool map[string]any, } func (c *responsesToolCompatibility) normalizeWebSearchFilters(tool map[string]any, param string) (map[string]any, error) { - var nestedDomains []any + nested := make(map[string][]any, 2) if rawFilters, exists := tool["filters"]; exists && rawFilters != nil { filters, ok := rawFilters.(map[string]any) if !ok { return nil, &responsesRequestError{Message: "web_search filters 必须是对象", Param: param + ".filters", Code: "invalid_parameter"} } for key := range filters { - if key != "allowed_domains" { + if key != "allowed_domains" && key != "excluded_domains" { c.changed = true c.addWarning("web_search_filters_downgraded") } } - if rawDomains, exists := filters["allowed_domains"]; exists { - values, err := normalizeAllowedDomains(rawDomains, param+".filters.allowed_domains") + for _, field := range []string{"allowed_domains", "excluded_domains"} { + rawDomains, exists := filters[field] + if !exists { + continue + } + values, err := normalizeWebSearchDomains(rawDomains, field, param+".filters."+field) if err != nil { return nil, err } - nestedDomains = values + nested[field] = values } } - var topLevelDomains []any - if rawDomains, exists := tool["allowed_domains"]; exists { - values, err := normalizeAllowedDomains(rawDomains, param+".allowed_domains") - if err != nil { - return nil, err + topLevel := make(map[string][]any, 2) + for _, field := range []string{"allowed_domains", "excluded_domains"} { + if rawDomains, exists := tool[field]; exists { + values, err := normalizeWebSearchDomains(rawDomains, field, param+"."+field) + if err != nil { + return nil, err + } + topLevel[field] = values } - topLevelDomains = values } - if len(nestedDomains) > 0 && len(topLevelDomains) > 0 && !sameStringValues(nestedDomains, topLevelDomains) { - return nil, &responsesRequestError{Message: "web_search allowed_domains 声明冲突", Param: param + ".allowed_domains", Code: "invalid_parameter"} + + result := make(map[string]any, 2) + for _, field := range []string{"allowed_domains", "excluded_domains"} { + nestedDomains := nested[field] + topLevelDomains := topLevel[field] + if len(nestedDomains) > 0 && len(topLevelDomains) > 0 && !sameStringValues(nestedDomains, topLevelDomains) { + return nil, &responsesRequestError{Message: "web_search " + field + " 声明冲突", Param: param + "." + field, Code: "invalid_parameter"} + } + domains := nestedDomains + if len(domains) == 0 { + domains = topLevelDomains + } + if len(domains) > 0 { + result[field] = cloneJSONValue(domains) + } } - domains := nestedDomains - if len(domains) == 0 { - domains = topLevelDomains + if _, hasAllowed := result["allowed_domains"]; hasAllowed { + if _, hasExcluded := result["excluded_domains"]; hasExcluded { + return nil, &responsesRequestError{Message: "web_search 不能同时设置 allowed_domains 和 excluded_domains", Param: param + ".filters", Code: "invalid_parameter"} + } } - if len(domains) == 0 { + if len(result) == 0 { return nil, nil } - return map[string]any{"allowed_domains": cloneJSONValue(domains)}, nil + return result, nil } -func normalizeAllowedDomains(value any, param string) ([]any, error) { +func normalizeWebSearchDomains(value any, field, param string) ([]any, error) { + if value == nil { + return nil, nil + } values, ok := value.([]any) if !ok { - return nil, &responsesRequestError{Message: "allowed_domains 必须是字符串数组", Param: param, Code: "invalid_parameter"} + return nil, &responsesRequestError{Message: field + " 必须是字符串数组", Param: param, Code: "invalid_parameter"} + } + if len(values) > maxWebSearchDomains { + return nil, &responsesRequestError{Message: fmt.Sprintf("%s 不能超过 %d 个域名", field, maxWebSearchDomains), Param: param, Code: "invalid_parameter"} } for index, value := range values { domain, ok := value.(string) if !ok || strings.TrimSpace(domain) == "" { - return nil, &responsesRequestError{Message: "allowed_domains 必须包含有效域名", Param: fmt.Sprintf("%s[%d]", param, index), Code: "invalid_parameter"} + return nil, &responsesRequestError{Message: field + " 必须包含有效域名", Param: fmt.Sprintf("%s[%d]", param, index), Code: "invalid_parameter"} } } return values, nil diff --git a/backend/internal/infra/provider/cli/semantic_streamidle.go b/backend/internal/infra/provider/cli/semantic_streamidle.go new file mode 100644 index 00000000..035a8d20 --- /dev/null +++ b/backend/internal/infra/provider/cli/semantic_streamidle.go @@ -0,0 +1,225 @@ +package cli + +import ( + "bytes" + "encoding/json" + "io" + "strings" + "sync" + "time" + + "github.com/chenyme/grok2api/backend/internal/pkg/neterror" +) + +var buildGeneratedDeltaEvents = map[string]struct{}{ + "response.output_text.delta": {}, + "response.reasoning_summary_text.delta": {}, + "response.reasoning_text.delta": {}, + "response.refusal.delta": {}, + "response.function_call_arguments.delta": {}, + "response.custom_tool_call_input.delta": {}, +} + +var buildGeneratedOutputItemTypes = map[string]struct{}{ + "code_interpreter_call": {}, + "custom_tool_call": {}, + "file_search_call": {}, + "function_call": {}, + "image_generation_call": {}, + "mcp_call": {}, + "mcp_approval_request": {}, + "mcp_approval_response": {}, + "mcp_list_tools": {}, + "message": {}, + "reasoning": {}, + "shell_call": {}, + "web_search_call": {}, +} + +// semanticIdleReadCloser measures useful generated output rather than raw +// transport bytes, so SSE keepalives and Build control events cannot keep a +// stalled generation alive indefinitely. +type semanticIdleReadCloser struct { + inner io.ReadCloser + idle time.Duration + timer *time.Timer + + mu sync.Mutex + detector buildSSEActivityDetector + finished bool + timedOut bool + + closeOnce sync.Once + closeErr error +} + +func wrapBuildSemanticIdle(body io.ReadCloser, idle time.Duration) io.ReadCloser { + if body == nil || idle <= 0 { + return body + } + wrapper := &semanticIdleReadCloser{inner: body, idle: idle} + wrapper.timer = time.AfterFunc(idle, wrapper.timeout) + return wrapper +} + +func (r *semanticIdleReadCloser) timeout() { + r.mu.Lock() + if r.finished { + r.mu.Unlock() + return + } + r.finished = true + r.timedOut = true + r.mu.Unlock() + _ = r.closeInner() +} + +func (r *semanticIdleReadCloser) Read(buffer []byte) (int, error) { + n, err := r.inner.Read(buffer) + + r.mu.Lock() + if n > 0 && !r.finished && r.detector.Observe(buffer[:n]) { + // A failed Stop means the deadline has already elapsed and its callback + // owns the outcome. Reset only while the prior deadline is still live. + if r.timer.Stop() { + r.timer.Reset(r.idle) + } + } + if err != nil && !r.finished { + r.finished = true + r.timer.Stop() + } + timedOut := r.timedOut + r.mu.Unlock() + + if timedOut { + return n, neterror.ErrUpstreamStreamIdleTimeout + } + return n, err +} + +func (r *semanticIdleReadCloser) Close() error { + r.mu.Lock() + if !r.finished { + r.finished = true + r.timer.Stop() + } + r.mu.Unlock() + return r.closeInner() +} + +func (r *semanticIdleReadCloser) closeInner() error { + r.closeOnce.Do(func() { + r.closeErr = r.inner.Close() + }) + return r.closeErr +} + +func (r *semanticIdleReadCloser) TimedOut() bool { + r.mu.Lock() + defer r.mu.Unlock() + return r.timedOut +} + +// buildSSEActivityDetector incrementally parses SSE framing without modifying +// the bytes returned to downstream response wrappers. +type buildSSEActivityDetector struct { + pending []byte + eventName string + data []byte + eventBytes int + overLimit bool + firstLine bool +} + +func (d *buildSSEActivityDetector) Observe(chunk []byte) bool { + if len(chunk) == 0 { + return false + } + d.pending = append(d.pending, chunk...) + active := false + for { + newline := bytes.IndexByte(d.pending, '\n') + if newline < 0 { + break + } + line := d.pending[:newline] + d.pending = d.pending[newline+1:] + line = bytes.TrimSuffix(line, []byte{'\r'}) + if !d.firstLine { + line = bytes.TrimPrefix(line, []byte("\xef\xbb\xbf")) + d.firstLine = true + } + if len(line) == 0 { + active = d.finishEvent() || active + continue + } + d.observeLine(line) + } + if len(d.pending)+d.eventBytes > maxCompatibleSSEEventBytes { + d.pending = nil + d.overLimit = true + } + return active +} + +func (d *buildSSEActivityDetector) observeLine(line []byte) { + d.eventBytes += len(line) + if d.eventBytes > maxCompatibleSSEEventBytes { + d.overLimit = true + d.eventName = "" + d.data = nil + return + } + if d.overLimit || len(line) == 0 || line[0] == ':' { + return + } + field, value, found := bytes.Cut(line, []byte{':'}) + if found && len(value) > 0 && value[0] == ' ' { + value = value[1:] + } + switch string(field) { + case "event": + d.eventName = string(value) + case "data": + if len(d.data) > 0 { + d.data = append(d.data, '\n') + } + d.data = append(d.data, value...) + } +} + +func (d *buildSSEActivityDetector) finishEvent() bool { + active := false + if !d.overLimit && len(d.data) > 0 { + var payload struct { + Type string `json:"type"` + Delta string `json:"delta"` + Item struct { + ID string `json:"id"` + Type string `json:"type"` + CallID string `json:"call_id"` + Name string `json:"name"` + } `json:"item"` + } + if json.Unmarshal(d.data, &payload) == nil { + kind := strings.TrimSpace(payload.Type) + if kind == "" { + kind = strings.TrimSpace(d.eventName) + } + if _, generatedDelta := buildGeneratedDeltaEvents[kind]; generatedDelta { + active = payload.Delta != "" + } else if kind == "response.output_item.added" || kind == "response.output_item.done" { + itemType := strings.TrimSpace(payload.Item.Type) + _, generatedItem := buildGeneratedOutputItemTypes[itemType] + active = generatedItem && (strings.TrimSpace(payload.Item.ID) != "" || + strings.TrimSpace(payload.Item.CallID) != "" || strings.TrimSpace(payload.Item.Name) != "") + } + } + } + d.eventName = "" + d.data = nil + d.eventBytes = 0 + d.overLimit = false + return active +} diff --git a/backend/internal/infra/provider/cli/semantic_streamidle_test.go b/backend/internal/infra/provider/cli/semantic_streamidle_test.go new file mode 100644 index 00000000..e9777318 --- /dev/null +++ b/backend/internal/infra/provider/cli/semantic_streamidle_test.go @@ -0,0 +1,218 @@ +package cli + +import ( + "errors" + "fmt" + "io" + "strings" + "sync/atomic" + "testing" + "time" + + "github.com/chenyme/grok2api/backend/internal/pkg/neterror" +) + +func TestBuildSemanticIdleIgnoresNonGeneratedEvents(t *testing.T) { + tests := []struct { + name string + chunk string + }{ + {name: "keepalive comment", chunk: ": keep-alive\n\n"}, + {name: "doom loop control", chunk: "event: response.doom_loop_check\ndata: {\"type\":\"response.doom_loop_check\"}\n\n"}, + {name: "lifecycle event", chunk: "event: response.in_progress\ndata: {\"type\":\"response.in_progress\"}\n\n"}, + {name: "empty generated delta", chunk: "event: response.output_text.delta\ndata: {\"type\":\"response.output_text.delta\",\"delta\":\"\"}\n\n"}, + } + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + reader, writer := io.Pipe() + body := wrapBuildSemanticIdle(reader, 60*time.Millisecond) + readDone := make(chan error, 1) + go func() { + _, err := io.Copy(io.Discard, body) + readDone <- err + }() + writeDone := make(chan struct{}) + go func() { + defer close(writeDone) + defer writer.Close() + for { + if _, err := io.WriteString(writer, test.chunk); err != nil { + return + } + time.Sleep(10 * time.Millisecond) + } + }() + + select { + case err := <-readDone: + if !errors.Is(err, neterror.ErrUpstreamStreamIdleTimeout) { + t.Fatalf("body read error = %v, want ErrUpstreamStreamIdleTimeout", err) + } + case <-time.After(time.Second): + t.Fatal("semantic idle timeout did not interrupt the stream") + } + <-writeDone + }) + } +} + +func TestBuildSemanticIdleResetsOnGeneratedDelta(t *testing.T) { + reader, writer := io.Pipe() + body := wrapBuildSemanticIdle(reader, 300*time.Millisecond) + readDone := make(chan error, 1) + go func() { + _, err := io.Copy(io.Discard, body) + readDone <- err + }() + + chunk := "event: response.output_text.delta\ndata: {\"type\":\"response.output_text.delta\",\"delta\":\"x\"}\n\n" + if _, err := io.WriteString(writer, chunk); err != nil { + t.Fatal(err) + } + time.Sleep(180 * time.Millisecond) + if _, err := io.WriteString(writer, chunk); err != nil { + t.Fatal(err) + } + time.Sleep(180 * time.Millisecond) + if err := writer.Close(); err != nil { + t.Fatal(err) + } + + select { + case err := <-readDone: + if err != nil { + t.Fatalf("body read error = %v, want nil", err) + } + case <-time.After(time.Second): + t.Fatal("generated deltas did not keep the stream alive") + } +} + +func TestBuildSemanticIdleResetsOnGeneratedOutputItem(t *testing.T) { + reader, writer := io.Pipe() + body := wrapBuildSemanticIdle(reader, 300*time.Millisecond) + readDone := make(chan error, 1) + go func() { + _, err := io.Copy(io.Discard, body) + readDone <- err + }() + + time.Sleep(180 * time.Millisecond) + searchStarted := "event: response.output_item.added\ndata: {\"type\":\"response.output_item.added\",\"item\":{\"id\":\"ws_1\",\"type\":\"web_search_call\",\"status\":\"in_progress\",\"action\":{\"type\":\"search\",\"query\":\"current docs\"}}}\n\n" + if _, err := io.WriteString(writer, searchStarted); err != nil { + t.Fatal(err) + } + time.Sleep(180 * time.Millisecond) + if err := writer.Close(); err != nil { + t.Fatal(err) + } + + select { + case err := <-readDone: + if err != nil { + t.Fatalf("body read error = %v, want nil", err) + } + case <-time.After(time.Second): + t.Fatal("generated output item did not keep the stream alive") + } +} + +func TestBuildSSEActivityDetectorRecognizesSplitGeneratedEvents(t *testing.T) { + for kind := range buildGeneratedDeltaEvents { + t.Run(kind, func(t *testing.T) { + var detector buildSSEActivityDetector + event := fmt.Sprintf("event: %s\r\ndata: {\"type\":%q,\"delta\":\"x\"}\r\n\r\n", kind, kind) + active := false + for index := range event { + active = detector.Observe([]byte(event[index:index+1])) || active + } + if !active { + t.Fatal("split generated event was not recognized") + } + }) + } +} + +func TestBuildSSEActivityDetectorRequiresJSONGeneratedEvent(t *testing.T) { + var detector buildSSEActivityDetector + if detector.Observe([]byte("event: response.output_text.delta\ndata: not-json\n\n")) { + t.Fatal("malformed event unexpectedly counted as generated activity") + } + if detector.Observe([]byte(": keep-alive\n\n")) { + t.Fatal("keepalive unexpectedly counted as generated activity") + } + if detector.Observe([]byte("event: response.output_text.delta\ndata: {\"type\":\"response.output_text.delta\",\"delta\":\"\"}\n\n")) { + t.Fatal("empty delta unexpectedly counted as generated activity") + } + if detector.Observe([]byte("event: response.output_item.added\ndata: {\"type\":\"response.output_item.added\",\"item\":{\"type\":\"web_search_call\"}}\n\n")) { + t.Fatal("unidentified output item unexpectedly counted as generated activity") + } + if detector.Observe([]byte("event: response.output_item.added\ndata: {\"type\":\"response.output_item.added\",\"item\":{\"type\":\"web_search_call\",\"status\":\"in_progress\"}}\n\n")) { + t.Fatal("anonymous output item unexpectedly counted as generated activity") + } + if detector.Observe([]byte("event: response.output_item.added\ndata: {\"type\":\"response.output_item.added\",\"item\":{\"id\":\"control_1\",\"type\":\"private_control\"}}\n\n")) { + t.Fatal("unknown output item unexpectedly counted as generated activity") + } +} + +func TestBuildSSEActivityDetectorRecognizesGeneratedOutputItems(t *testing.T) { + tests := []string{ + `{"type":"response.output_item.added","item":{"id":"ws_1","type":"web_search_call","status":"in_progress"}}`, + `{"type":"response.output_item.added","item":{"id":"reasoning_1","type":"reasoning"}}`, + `{"type":"response.output_item.done","item":{"call_id":"call_1","type":"function_call","name":"lookup","status":"completed"}}`, + } + for _, payload := range tests { + var detector buildSSEActivityDetector + if !detector.Observe([]byte("data: " + payload + "\n\n")) { + t.Fatalf("generated output item was not recognized: %s", payload) + } + } +} + +func TestBuildSemanticIdleStopsAfterEOFOrClose(t *testing.T) { + t.Run("EOF", func(t *testing.T) { + inner := &countingReadCloser{Reader: strings.NewReader("done")} + body := wrapBuildSemanticIdle(inner, 20*time.Millisecond).(*semanticIdleReadCloser) + if _, err := io.ReadAll(body); err != nil { + t.Fatal(err) + } + time.Sleep(40 * time.Millisecond) + if body.TimedOut() { + t.Fatal("timer fired after EOF") + } + if err := body.Close(); err != nil { + t.Fatal(err) + } + if got := inner.closes.Load(); got != 1 { + t.Fatalf("inner Close calls = %d, want 1", got) + } + }) + + t.Run("Close", func(t *testing.T) { + inner := &countingReadCloser{Reader: strings.NewReader("")} + body := wrapBuildSemanticIdle(inner, 20*time.Millisecond).(*semanticIdleReadCloser) + if err := body.Close(); err != nil { + t.Fatal(err) + } + if err := body.Close(); err != nil { + t.Fatal(err) + } + time.Sleep(40 * time.Millisecond) + if body.TimedOut() { + t.Fatal("timer fired after Close") + } + if got := inner.closes.Load(); got != 1 { + t.Fatalf("inner Close calls = %d, want 1", got) + } + }) +} + +type countingReadCloser struct { + io.Reader + closes atomic.Int32 +} + +func (r *countingReadCloser) Close() error { + r.closes.Add(1) + return nil +} diff --git a/backend/internal/infra/provider/console/console_test.go b/backend/internal/infra/provider/console/console_test.go index eee5f7ef..9cd53e1f 100644 --- a/backend/internal/infra/provider/console/console_test.go +++ b/backend/internal/infra/provider/console/console_test.go @@ -1789,7 +1789,7 @@ func TestConsoleVideoPostsReferenceAudios(t *testing.T) { // 8. Maximum allowed is 7." on both grok-imagine-video and grok-imagine-video-1.5. func TestConsoleVideoRejectsTooManyReferenceImages(t *testing.T) { adapter, credential := newConsoleTestAdapter(t, "https://console.example") - references := make([]string, consoleMaxVideoReferenceImages+1) + references := make([]string, provider.ConsoleVideoMaxReferenceImages+1) for i := range references { references[i] = "https://example.com/" + strings.Repeat("x", i+1) + ".png" } @@ -1803,7 +1803,7 @@ func TestConsoleVideoRejectsTooManyReferenceImages(t *testing.T) { func TestConsoleVideoRejectsTooManyCombinedImages(t *testing.T) { adapter, credential := newConsoleTestAdapter(t, "https://console.example") - references := make([]string, consoleMaxVideoReferenceImages) + references := make([]string, provider.ConsoleVideoMaxReferenceImages) for i := range references { references[i] = "https://example.com/" + strings.Repeat("y", i+1) + ".png" } diff --git a/backend/internal/infra/provider/console/media.go b/backend/internal/infra/provider/console/media.go index cd0c3b65..82f23e1b 100644 --- a/backend/internal/infra/provider/console/media.go +++ b/backend/internal/infra/provider/console/media.go @@ -36,8 +36,7 @@ const ( // 8 references answer 400 "Too many reference images: 8. Maximum allowed is 7." // The two are mutually exclusive below and their limits are never summed, so a // combined ceiling would accept payloads that upstream then rejects. - consoleMaxVideoFirstFrames = 1 - consoleMaxVideoReferenceImages = 7 + consoleMaxVideoFirstFrames = 1 ) type consoleMediaUpstreamError struct { @@ -468,8 +467,8 @@ func (a *Adapter) GenerateVideo(ctx context.Context, request provider.VideoReque if firstFrames > consoleMaxVideoFirstFrames { return provider.VideoResult{}, fmt.Errorf("Console %s 最多支持 %d 张首帧图,当前为 %d 张", modelName, consoleMaxVideoFirstFrames, firstFrames) } - if referenceImages > consoleMaxVideoReferenceImages { - return provider.VideoResult{}, fmt.Errorf("Console %s 最多支持 %d 张参考图,当前为 %d 张", modelName, consoleMaxVideoReferenceImages, referenceImages) + if referenceImages > provider.ConsoleVideoMaxReferenceImages { + return provider.VideoResult{}, fmt.Errorf("Console %s 最多支持 %d 张参考图,当前为 %d 张", modelName, provider.ConsoleVideoMaxReferenceImages, referenceImages) } if operation == provider.VideoOperationGenerate { if request.Duration < 1 || request.Duration > 15 { @@ -480,8 +479,8 @@ func (a *Adapter) GenerateVideo(ctx context.Context, request provider.VideoReque // -> 400 "Duration 15s exceeds the maximum allowed for reference-to-video, which is 10s." // image-to-video (the image field) and grok-imagine-video-1.5 both keep 15s, // so the cap keys on reference_images plus the base model, not on duration alone. - if modelName == "grok-imagine-video" && referenceImages > 0 && request.Duration > 10 { - return provider.VideoResult{}, fmt.Errorf("%s 的参考图生视频最长 10 秒,当前为 %d 秒", modelName, request.Duration) + if modelName == "grok-imagine-video" && referenceImages > 0 && request.Duration > provider.ConsoleVideoMaxReferenceDurationSeconds { + return provider.VideoResult{}, fmt.Errorf("%s 的参考图生视频最长 %d 秒,当前为 %d 秒", modelName, provider.ConsoleVideoMaxReferenceDurationSeconds, request.Duration) } } else if operation == provider.VideoOperationExtend { // Official /v1/videos/extensions defaults to 6s and accepts 2-10s. diff --git a/backend/internal/infra/provider/conversation/chat_request.go b/backend/internal/infra/provider/conversation/chat_request.go index 82c49349..6eed845a 100644 --- a/backend/internal/infra/provider/conversation/chat_request.go +++ b/backend/internal/infra/provider/conversation/chat_request.go @@ -275,13 +275,9 @@ func convertChatTools(raw json.RawMessage) ([]any, error) { object, _ := value.(map[string]any) switch typeName { case "web_search", "web_search_preview", "web_search_preview_2025_03_11", "web_search_2025_08_26": - converted := map[string]any{"type": "web_search"} - if filters, ok := object["filters"].(map[string]any); ok { - if domains, exists := filters["allowed_domains"]; exists { - converted["filters"] = map[string]any{"allowed_domains": domains} - } - } else if domains, exists := object["allowed_domains"]; exists { - converted["filters"] = map[string]any{"allowed_domains": domains} + converted, err := convertChatWebSearchTool(object) + if err != nil { + return nil, err } result = append(result, converted) default: @@ -299,6 +295,89 @@ func convertChatTools(raw json.RawMessage) ([]any, error) { return result, nil } +func convertChatWebSearchTool(tool map[string]any) (map[string]any, error) { + nested := make(map[string][]any, 2) + if rawFilters, exists := tool["filters"]; exists && rawFilters != nil { + filters, ok := rawFilters.(map[string]any) + if !ok { + return nil, errors.New("web_search filters 必须是对象") + } + for _, field := range []string{"allowed_domains", "excluded_domains"} { + if value, exists := filters[field]; exists { + domains, err := normalizeChatWebSearchDomains(value, field) + if err != nil { + return nil, err + } + nested[field] = domains + } + } + } + + resultFilters := make(map[string]any, 2) + for _, field := range []string{"allowed_domains", "excluded_domains"} { + var topLevel []any + if value, exists := tool[field]; exists { + domains, err := normalizeChatWebSearchDomains(value, field) + if err != nil { + return nil, err + } + topLevel = domains + } + domains := nested[field] + if len(domains) > 0 && len(topLevel) > 0 && !sameChatWebSearchDomains(domains, topLevel) { + return nil, fmt.Errorf("web_search %s 声明冲突", field) + } + if len(domains) == 0 { + domains = topLevel + } + if len(domains) > 0 { + resultFilters[field] = domains + } + } + if _, hasAllowed := resultFilters["allowed_domains"]; hasAllowed { + if _, hasExcluded := resultFilters["excluded_domains"]; hasExcluded { + return nil, errors.New("web_search 不能同时设置 allowed_domains 和 excluded_domains") + } + } + converted := map[string]any{"type": "web_search"} + if len(resultFilters) > 0 { + converted["filters"] = resultFilters + } + return converted, nil +} + +func normalizeChatWebSearchDomains(value any, field string) ([]any, error) { + if value == nil { + return nil, nil + } + domains, ok := value.([]any) + if !ok { + return nil, fmt.Errorf("web_search %s 必须是字符串数组", field) + } + if len(domains) > MaxWebSearchDomains { + return nil, fmt.Errorf("web_search %s 不能超过 %d 个域名", field, MaxWebSearchDomains) + } + for index, value := range domains { + domain, ok := value.(string) + if !ok || strings.TrimSpace(domain) == "" { + return nil, fmt.Errorf("web_search %s[%d] 必须是非空字符串", field, index) + } + } + return domains, nil +} + +func sameChatWebSearchDomains(left, right []any) bool { + if len(left) != len(right) { + return false + } + for index := range left { + if left[index] != right[index] { + return false + } + } + return true +} + func containsToolType(tools []any, kind string) bool { for _, raw := range tools { tool, ok := raw.(map[string]any) diff --git a/backend/internal/infra/provider/conversation/conversation_test.go b/backend/internal/infra/provider/conversation/conversation_test.go index 9612c60f..64906284 100644 --- a/backend/internal/infra/provider/conversation/conversation_test.go +++ b/backend/internal/infra/provider/conversation/conversation_test.go @@ -53,6 +53,61 @@ func TestConvertChatRequestToResponses(t *testing.T) { } } +func TestConvertChatPreservesWebSearchExcludedDomains(t *testing.T) { + converted, err := ConvertRequest([]byte(`{ + "model":"public-chat","messages":[{"role":"user","content":"search"}], + "tools":[{"type":"web_search","filters":{"excluded_domains":["blocked.example"]}}] + }`), "grok-4.6", OperationChat) + if err != nil { + t.Fatal(err) + } + var payload map[string]any + if err := json.Unmarshal(converted, &payload); err != nil { + t.Fatal(err) + } + tool := payload["tools"].([]any)[0].(map[string]any) + domains := tool["filters"].(map[string]any)["excluded_domains"].([]any) + if len(domains) != 1 || domains[0] != "blocked.example" { + t.Fatalf("excluded_domains = %#v", tool) + } +} + +func TestConvertChatValidatesWebSearchDomainFilters(t *testing.T) { + for _, test := range []struct { + name string + tool string + wantErr bool + }{ + {name: "identical nested and top level", tool: `{"type":"web_search","filters":{"allowed_domains":["same.example"]},"allowed_domains":["same.example"]}`}, + {name: "conflicting duplicate", tool: `{"type":"web_search","filters":{"allowed_domains":["nested.example"]},"allowed_domains":["top.example"]}`, wantErr: true}, + {name: "allow and exclude", tool: `{"type":"web_search","filters":{"allowed_domains":["allow.example"],"excluded_domains":["deny.example"]}}`, wantErr: true}, + {name: "six domains", tool: `{"type":"web_search","excluded_domains":["a.example","b.example","c.example","d.example","e.example","f.example"]}`, wantErr: true}, + {name: "invalid filters type", tool: `{"type":"web_search","filters":"invalid"}`, wantErr: true}, + {name: "empty filters omitted", tool: `{"type":"web_search","filters":{"allowed_domains":null,"excluded_domains":[]}}`}, + } { + t.Run(test.name, func(t *testing.T) { + converted, err := ConvertRequest([]byte(`{ + "model":"public-chat","messages":[{"role":"user","content":"search"}], + "tools":[`+test.tool+`] + }`), "grok-4.6", OperationChat) + if (err != nil) != test.wantErr { + t.Fatalf("conversion error = %v, wantErr %v", err, test.wantErr) + } + if err != nil { + return + } + var payload map[string]any + if err := json.Unmarshal(converted, &payload); err != nil { + t.Fatal(err) + } + tool := payload["tools"].([]any)[0].(map[string]any) + if test.name == "empty filters omitted" && len(tool) != 1 { + t.Fatalf("empty filters were not omitted: %#v", tool) + } + }) + } +} + func TestConvertChatToolImageResultToMultimodalFunctionOutput(t *testing.T) { body := []byte(`{ "model":"public-chat", @@ -512,6 +567,28 @@ func TestConvertAnthropicWebSearchControls(t *testing.T) { if len(tool) != 1 || tool["type"] != "web_search" { t.Fatalf("downgraded tool = %#v", tool) } + + converted, _, err = ConvertRequestWithOptions([]byte(`{ + "model":"public","max_tokens":64,"messages":[{"role":"user","content":"search"}], + "tools":[{"type":"web_search_20250305","name":"web_search","blocked_domains":["blocked.example"]}] + }`), "grok-4.6", OperationMessages) + if err != nil { + t.Fatal(err) + } + payload = nil + _ = json.Unmarshal(converted, &payload) + tool = payload["tools"].([]any)[0].(map[string]any) + domains = tool["filters"].(map[string]any)["excluded_domains"].([]any) + if len(domains) != 1 || domains[0] != "blocked.example" { + t.Fatalf("blocked_domains conversion = %#v", tool) + } + + if _, _, err = ConvertRequestWithOptions([]byte(`{ + "model":"public","max_tokens":64,"messages":[{"role":"user","content":"search"}], + "tools":[{"type":"web_search_20250305","name":"web_search","allowed_domains":["allow.example"],"blocked_domains":["blocked.example"]}] + }`), "grok-4.6", OperationMessages); err == nil { + t.Fatal("allowed_domains + blocked_domains must be rejected") + } } func TestConvertResponsesJSONToChatAndMessages(t *testing.T) { diff --git a/backend/internal/infra/provider/conversation/messages_request.go b/backend/internal/infra/provider/conversation/messages_request.go index 5f26885c..68a42b91 100644 --- a/backend/internal/infra/provider/conversation/messages_request.go +++ b/backend/internal/infra/provider/conversation/messages_request.go @@ -686,7 +686,7 @@ func convertAnthropicWebSearchTool(tool map[string]json.RawMessage, index int) ( switch key { case "type", "name", "cache_control": continue - case "allowed_domains": + case "allowed_domains", "blocked_domains", "excluded_domains": var value any if json.Unmarshal(raw, &value) != nil { return nil, fmt.Errorf("tools[%d].%s 无效", index, key) @@ -695,17 +695,38 @@ func convertAnthropicWebSearchTool(tool map[string]json.RawMessage, index int) ( if !ok { return nil, fmt.Errorf("tools[%d].%s 必须是字符串数组", index, key) } - if len(domains) > 5 { - return nil, fmt.Errorf("tools[%d].%s 不能超过 5 个域名", index, key) + if len(domains) > MaxWebSearchDomains { + return nil, fmt.Errorf("tools[%d].%s 不能超过 %d 个域名", index, key, MaxWebSearchDomains) } for domainIndex, domain := range domains { if text, ok := domain.(string); !ok || strings.TrimSpace(text) == "" { return nil, fmt.Errorf("tools[%d].%s[%d] 必须是非空字符串", index, key, domainIndex) } } - converted["filters"] = map[string]any{"allowed_domains": value} - case "max_uses", "blocked_domains", "user_location", "search_context_size": - // The Build web-search wire contract supports only allowed_domains. Do not forward other optional Anthropic controls, + field := key + if field == "blocked_domains" { + field = "excluded_domains" + } + filters, _ := converted["filters"].(map[string]any) + if filters == nil { + filters = make(map[string]any, 2) + } + if len(domains) > 0 { + if _, exists := filters[field]; exists { + return nil, fmt.Errorf("tools[%d].%s 与同义域名过滤字段重复", index, key) + } + other := "allowed_domains" + if field == other { + other = "excluded_domains" + } + if existing, ok := filters[other].([]any); ok && len(existing) > 0 { + return nil, fmt.Errorf("tools[%d] 不能同时设置 allowed_domains 和 blocked_domains/excluded_domains", index) + } + filters[field] = value + converted["filters"] = filters + } + case "max_uses", "user_location", "search_context_size": + // These Anthropic controls have no equivalent in the Build web-search wire contract, // preventing unknown parameters from causing the upstream to reject the request. continue default: diff --git a/backend/internal/infra/provider/conversation/server_web_search.go b/backend/internal/infra/provider/conversation/server_web_search.go index 9df448d9..c62275e9 100644 --- a/backend/internal/infra/provider/conversation/server_web_search.go +++ b/backend/internal/infra/provider/conversation/server_web_search.go @@ -26,7 +26,11 @@ type webSearchCall struct { Code string } -const maxWebSearchCalls = 32 +const ( + maxWebSearchCalls = 32 + // MaxWebSearchDomains mirrors the Grok Build Web Search limit for each allow/exclude list. + MaxWebSearchDomains = 5 +) func unavailableWebSearchCall(query string) webSearchCall { fallback := map[string]string{"type": "web_search", "query": query, "error": "unavailable"} diff --git a/backend/internal/infra/provider/provider.go b/backend/internal/infra/provider/provider.go index 9e882970..87b048e3 100644 --- a/backend/internal/infra/provider/provider.go +++ b/backend/internal/infra/provider/provider.go @@ -449,6 +449,16 @@ const ( VideoOperationExtend = media.VideoOperationExtend ) +// ConsoleVideoMaxReferenceImages and ConsoleVideoMaxReferenceDurationSeconds +// describe the Console reference-to-video contract enforced by the upstream. +// They are shared by admission control and the Console adapter so invalid +// asynchronous jobs are rejected before enqueueing without weakening the +// adapter's final request-boundary validation. +const ( + ConsoleVideoMaxReferenceImages = 7 + ConsoleVideoMaxReferenceDurationSeconds = 10 +) + type VideoRequest struct { Credential account.Credential // Billing is used only to determine XAI eligibility in Build auto mode; nil means the account tier is unknown. diff --git a/backend/internal/infra/provider/web/chat.go b/backend/internal/infra/provider/web/chat.go index a6f94462..3eb32a05 100644 --- a/backend/internal/infra/provider/web/chat.go +++ b/backend/internal/infra/provider/web/chat.go @@ -254,7 +254,7 @@ func (a *Adapter) ForwardResponse(ctx context.Context, request provider.Response if attempt > 0 { attemptCtx = infraegress.WithPhysicalCallStage(ctx, "anti_bot_retry") } - upstream, lease, currentPrevious, statsigTarget, openErr := a.openChat(attemptCtx, request.Credential, input.PreviousResponseID, spec, normalized, true) + upstream, lease, currentPrevious, statsigTarget, openErr := a.openChat(attemptCtx, request.Credential, input.PreviousResponseID, spec, normalized, gatewayOpenOptions{enforceStreamIdle: true}) if openErr != nil { if errors.Is(openErr, errInvalidChatAttachment) || errors.Is(openErr, errInvalidChatImage) || errors.Is(openErr, errInvalidChatFile) { code := "invalid_attachment_input" @@ -418,8 +418,8 @@ func preflightUpstream(source io.ReadCloser) (io.ReadCloser, error) { return nil, fmt.Errorf("Grok Web 首个流事件超过安全检查上限") } -func (a *Adapter) openChat(ctx context.Context, credential account.Credential, previousResponseID string, spec ModelSpec, input normalizedChatInput, enforceStreamIdle bool) (*http.Response, *infraegress.Lease, *inferencedomain.WebResponseState, string, error) { - return a.openGatewayChat(ctx, credential, previousResponseID, spec, input, enforceStreamIdle) +func (a *Adapter) openChat(ctx context.Context, credential account.Credential, previousResponseID string, spec ModelSpec, input normalizedChatInput, options gatewayOpenOptions) (*http.Response, *infraegress.Lease, *inferencedomain.WebResponseState, string, error) { + return a.openGatewayChat(ctx, credential, previousResponseID, spec, input, options) } func (a *Adapter) handleResponseResource(ctx context.Context, request provider.ResponseResourceRequest) (*provider.Response, error) { diff --git a/backend/internal/infra/provider/web/gateway.go b/backend/internal/infra/provider/web/gateway.go index a9bef174..33fce1ab 100644 --- a/backend/internal/infra/provider/web/gateway.go +++ b/backend/internal/infra/provider/web/gateway.go @@ -49,6 +49,11 @@ type gatewaySender struct { connection *websocket.Conn } +type gatewayOpenOptions struct { + enforceStreamIdle bool + deferForbidden bool +} + func (s *gatewaySender) write(value any) error { s.mu.Lock() defer s.mu.Unlock() @@ -56,7 +61,7 @@ func (s *gatewaySender) write(value any) error { return s.connection.WriteJSON(value) } -func (a *Adapter) openGatewayChat(ctx context.Context, credential account.Credential, previousResponseID string, spec ModelSpec, input normalizedChatInput, enforceStreamIdle bool) (*http.Response, *infraegress.Lease, *inferencedomain.WebResponseState, string, error) { +func (a *Adapter) openGatewayChat(ctx context.Context, credential account.Credential, previousResponseID string, spec ModelSpec, input normalizedChatInput, options gatewayOpenOptions) (*http.Response, *infraegress.Lease, *inferencedomain.WebResponseState, string, error) { cfg := a.config() token, err := a.cipher.Decrypt(credential.EncryptedAccessToken) if err != nil { @@ -99,7 +104,7 @@ func (a *Adapter) openGatewayChat(ctx context.Context, credential account.Creden } requestCtx, totalCancel := context.WithTimeout(ctx, time.Duration(cfg.ChatTimeoutSeconds)*time.Second) var idleCancel context.CancelCauseFunc - if enforceStreamIdle && cfg.StreamIdleTimeoutSeconds > 0 { + if options.enforceStreamIdle && cfg.StreamIdleTimeoutSeconds > 0 { requestCtx, idleCancel = context.WithCancelCause(requestCtx) } cancel := func() { @@ -108,7 +113,14 @@ func (a *Adapter) openGatewayChat(ctx context.Context, credential account.Creden } totalCancel() } - connection, handshake, dialErr := lease.DialWebSocket(requestCtx, endpoint, gatewayHeaders(origin, userID, token, lease), gatewayHandshakeTimeout) + var connection *websocket.Conn + var handshake *fhttp.Response + var dialErr error + if options.deferForbidden { + connection, handshake, dialErr = lease.DialWebSocketDeferredForbidden(requestCtx, endpoint, gatewayHeaders(origin, userID, token, lease), gatewayHandshakeTimeout) + } else { + connection, handshake, dialErr = lease.DialWebSocket(requestCtx, endpoint, gatewayHeaders(origin, userID, token, lease), gatewayHandshakeTimeout) + } if dialErr != nil { cancel() if handshake != nil { diff --git a/backend/internal/infra/provider/web/image.go b/backend/internal/infra/provider/web/image.go index cb2b1438..4905e520 100644 --- a/backend/internal/infra/provider/web/image.go +++ b/backend/internal/infra/provider/web/image.go @@ -342,6 +342,10 @@ func (a *Adapter) generateLiteImage(ctx context.Context, request provider.ImageG for len(urls) < count { value, err := a.generateLiteImageURL(ctx, request.Credential, spec, request.Prompt) if err != nil { + var mediaErr *webMediaUpstreamError + if errors.As(err, &mediaErr) && len(urls) == 0 { + return mediaErr.providerResponse(), nil + } var upstreamErr *liteUpstreamError if errors.As(err, &upstreamErr) && len(urls) == 0 { return upstreamErr.Response(), nil @@ -379,18 +383,33 @@ func (e *liteUpstreamError) Response() *provider.Response { func (a *Adapter) generateLiteImageURL(ctx context.Context, credential account.Credential, spec ModelSpec, prompt string) (string, error) { for attempt := 0; attempt < 2; attempt++ { - upstream, lease, _, statsigTarget, err := a.openChat(ctx, credential, "", spec, normalizedChatInput{Prompt: "Drawing: " + prompt}, false) + upstream, lease, _, statsigTarget, err := a.openChat(ctx, credential, "", spec, normalizedChatInput{Prompt: "Drawing: " + prompt}, gatewayOpenOptions{deferForbidden: true}) if err != nil { return "", err } if upstream.StatusCode < 200 || upstream.StatusCode >= 300 { - body, _ := io.ReadAll(io.LimitReader(upstream.Body, 1<<20)) + body, _ := io.ReadAll(io.LimitReader(upstream.Body, webMediaDiagnosticBodyLimit+1)) _ = upstream.Body.Close() + truncated := len(body) > webMediaDiagnosticBodyLimit + if truncated { + body = body[:webMediaDiagnosticBodyLimit] + } if upstream.StatusCode == http.StatusForbidden { - if attempt == 0 && a.invalidateSignedStatsig(http.MethodPost, statsigTarget) { - lease.Release() - continue + upstreamErr := newWebMediaUpstreamError(upstream.StatusCode, body, truncated) + a.logWebMediaUpstreamRejection("image_lite_handshake", upstream, upstreamErr) + if isClearanceRefreshableMediaError(upstreamErr) { + // The failed WebSocket handshake invalidates the current browser + // session. Statsig is independent and must not gate reacquiring + // a fresh lease for the retry. + lease.InvalidateClearance() + _ = a.invalidateSignedStatsig(http.MethodPost, statsigTarget) + if attempt == 0 { + lease.Release() + continue + } } + lease.Release() + return "", upstreamErr } a.egress.Feedback(context.WithoutCancel(ctx), lease.NodeID, upstream.StatusCode, nil) lease.Release() @@ -421,7 +440,11 @@ func (a *Adapter) generateLiteImageURL(ctx context.Context, credential account.C status := 0 if errors.Is(consumeErr, errWebAntiBot) { status = http.StatusForbidden - if attempt == 0 && a.invalidateSignedStatsig(http.MethodPost, statsigTarget) { + // A challenge can arrive inside an otherwise successful stream, + // so the handshake path cannot invalidate it for us. + lease.InvalidateClearance() + if attempt == 0 { + _ = a.invalidateSignedStatsig(http.MethodPost, statsigTarget) lease.Release() continue } @@ -499,6 +522,10 @@ func (a *Adapter) forwardImageChatCompletion(ctx context.Context, request provid for range count { rawURL, err := a.generateLiteImageURL(ctx, request.Credential, spec, normalized.Prompt) if err != nil { + var mediaErr *webMediaUpstreamError + if errors.As(err, &mediaErr) && parsed.Text.Len() == 0 { + return mediaErr.providerResponse(), nil + } var upstreamErr *liteUpstreamError if errors.As(err, &upstreamErr) && parsed.Text.Len() == 0 { return upstreamErr.Response(), nil @@ -616,6 +643,24 @@ func liteImageMarkdown(item map[string]any) string { } func (a *Adapter) generateWSImage(ctx context.Context, request provider.ImageGenerationRequest, count int, format, ratio, resolution string, modelConfig imagineModelConfig) (*provider.Response, error) { + for attempt := 0; attempt < 2; attempt++ { + response, err := a.generateWSImageAttempt(ctx, request, count, format, ratio, resolution, modelConfig) + if err == nil { + return response, nil + } + var upstreamErr *webMediaUpstreamError + if !errors.As(err, &upstreamErr) || !isClearanceRefreshableMediaError(upstreamErr) || attempt > 0 { + if errors.As(err, &upstreamErr) { + return upstreamErr.providerResponse(), nil + } + return nil, err + } + a.log().Warn("web_image_clearance_retry", "operation", "imagine", "status", upstreamErr.status, "body_kind", upstreamErr.bodyKind) + } + return nil, fmt.Errorf("Imagine WebSocket Clearance 重试耗尽") +} + +func (a *Adapter) generateWSImageAttempt(ctx context.Context, request provider.ImageGenerationRequest, count int, format, ratio, resolution string, modelConfig imagineModelConfig) (*provider.Response, error) { cfg := a.config() token, err := a.cipher.Decrypt(request.Credential.EncryptedAccessToken) if err != nil { @@ -642,13 +687,32 @@ func (a *Adapter) generateWSImage(ctx context.Context, request provider.ImageGen headers.Set("Accept-Language", "zh-CN,zh;q=0.9,en;q=0.8") headers.Set("Cache-Control", "no-cache") headers.Set("Pragma", "no-cache") - connection, response, err := lease.DialWebSocket(ctx, wsURL, headers, 30*time.Second) + connection, response, err := lease.DialWebSocketDeferredForbidden(ctx, wsURL, headers, 30*time.Second) if err != nil { - status := 0 if response != nil { - status = response.StatusCode + var body []byte + if response.Body != nil { + body, _ = io.ReadAll(io.LimitReader(response.Body, webMediaDiagnosticBodyLimit+1)) + _ = response.Body.Close() + } + truncated := len(body) > webMediaDiagnosticBodyLimit + if truncated { + body = body[:webMediaDiagnosticBodyLimit] + } + upstreamErr := newWebMediaUpstreamError(response.StatusCode, body, truncated) + if isClearanceRefreshableMediaError(upstreamErr) { + lease.InvalidateClearance() + } + a.logWebMediaUpstreamRejection("image_imagine_handshake", &http.Response{ + StatusCode: response.StatusCode, + Header: http.Header(response.Header).Clone(), + }, upstreamErr) + if response.StatusCode != http.StatusForbidden { + a.egress.Feedback(context.WithoutCancel(ctx), lease.NodeID, response.StatusCode, err) + } + return nil, upstreamErr } - a.egress.Feedback(context.WithoutCancel(ctx), lease.NodeID, status, err) + a.egress.Feedback(context.WithoutCancel(ctx), lease.NodeID, 0, err) return nil, fmt.Errorf("连接 Imagine WebSocket: %w", err) } connectionOwned := true @@ -724,7 +788,28 @@ func (a *Adapter) generateWSImage(ctx context.Context, request provider.ImageGen return result, err } +// EditImage retries the complete browser media flow once after a challenge +// response. Reacquiring the lease is required because the failed lease keeps +// the immutable browser-session cookies that were rejected upstream. func (a *Adapter) EditImage(ctx context.Context, request provider.ImageEditRequest) (*provider.Response, error) { + for attempt := 0; attempt < 2; attempt++ { + response, err := a.editImageAttempt(ctx, request) + if err == nil { + return response, nil + } + var upstreamErr *webMediaUpstreamError + if !errors.As(err, &upstreamErr) || !isClearanceRefreshableMediaError(upstreamErr) || attempt > 0 { + if errors.As(err, &upstreamErr) { + return upstreamErr.providerResponse(), nil + } + return nil, err + } + a.log().Warn("web_image_clearance_retry", "operation", "edit", "status", upstreamErr.status, "body_kind", upstreamErr.bodyKind) + } + return nil, fmt.Errorf("图片编辑 Clearance 重试耗尽") +} + +func (a *Adapter) editImageAttempt(ctx context.Context, request provider.ImageEditRequest) (*provider.Response, error) { if strings.TrimSpace(request.Quality) != "" { return invalidImageRequest("Grok Web 图片模型不支持 quality") } @@ -810,9 +895,15 @@ func (a *Adapter) EditImage(ctx context.Context, request provider.ImageEditReque return nil, err } if response.StatusCode < 200 || response.StatusCode >= 300 { - body, _ := io.ReadAll(io.LimitReader(response.Body, 1<<20)) + body, _ := io.ReadAll(io.LimitReader(response.Body, webMediaDiagnosticBodyLimit+1)) _ = response.Body.Close() - return &provider.Response{StatusCode: response.StatusCode, Status: response.Status, Header: jsonHeaders(), Body: io.NopCloser(bytes.NewReader(body))}, nil + truncated := len(body) > webMediaDiagnosticBodyLimit + if truncated { + body = body[:webMediaDiagnosticBodyLimit] + } + upstreamErr := newWebMediaUpstreamError(response.StatusCode, body, truncated) + a.logWebMediaUpstreamRejection("image_edit_generate", response, upstreamErr) + return nil, upstreamErr } if request.Streaming { reader, writer := io.Pipe() @@ -1204,7 +1295,7 @@ func (a *Adapter) uploadFileV2Direct(ctx context.Context, cfg Config, lease *egr request.Header = buildHeaders(token, lease, contentType) request.Header.Del("x-xai-request-id") applyAppHeaders(request.Header, cfg.BaseURL, referer) - response, err := lease.Do(request) + response, err := lease.DoDeferredForbidden(request) if err != nil { return uploadedFile{}, err } @@ -1218,10 +1309,10 @@ func (a *Adapter) uploadFileV2Direct(ctx context.Context, cfg Config, lease *egr if truncated { responseBody = responseBody[:webMediaDiagnosticBodyLimit] } - if response.StatusCode == http.StatusForbidden { - a.egress.Feedback(context.WithoutCancel(ctx), lease.NodeID, response.StatusCode, nil) - } upstreamErr := newWebMediaUpstreamError(response.StatusCode, responseBody, truncated) + if isClearanceRefreshableMediaError(upstreamErr) { + lease.InvalidateClearance() + } a.logWebMediaUpstreamRejection(stage, response, upstreamErr) return uploadedFile{}, upstreamErr } @@ -1409,18 +1500,36 @@ func (a *Adapter) postJSONWithReferer(ctx context.Context, cfg Config, lease *eg request.Header = buildHeaders(token, lease, "application/json") applyAppHeaders(request.Header, cfg.BaseURL, referer) a.applySignedStatsig(requestCtx, request, token, lease) - response, err := lease.Do(request) + response, err := lease.DoDeferredForbidden(request) if err != nil { cancel() return nil, err } if response.StatusCode == http.StatusForbidden { - if attempt == 0 && a.invalidateSignedStatsig(http.MethodPost, endpoint) { - _ = response.Body.Close() - cancel() - continue + body, readErr := io.ReadAll(io.LimitReader(response.Body, webMediaDiagnosticBodyLimit+1)) + _ = response.Body.Close() + cancel() + if readErr != nil { + return nil, fmt.Errorf("读取 Grok Web 403 响应: %w", readErr) } - a.egress.Feedback(context.WithoutCancel(ctx), lease.NodeID, http.StatusForbidden, nil) + truncated := len(body) > webMediaDiagnosticBodyLimit + if truncated { + body = body[:webMediaDiagnosticBodyLimit] + } + upstreamErr := newWebMediaUpstreamError(response.StatusCode, body, truncated) + response.Body = io.NopCloser(bytes.NewReader(body)) + response.ContentLength = int64(len(body)) + if isClearanceRefreshableMediaError(upstreamErr) { + lease.InvalidateClearance() + _ = a.invalidateSignedStatsig(http.MethodPost, endpoint) + return response, nil + } + // Structured JSON responses are application policy decisions. They + // must not invalidate Clearance, affect egress health, or be replayed. + if upstreamErr.bodyKind == "json" || attempt > 0 || !a.invalidateSignedStatsig(http.MethodPost, endpoint) { + return response, nil + } + continue } response.Body = &cancelBody{ReadCloser: response.Body, cancel: cancel} return response, nil @@ -1734,7 +1843,14 @@ func imagineURL(baseURL string) (string, error) { if err != nil { return "", err } - value.Scheme = "wss" + switch value.Scheme { + case "https": + value.Scheme = "wss" + case "http": + value.Scheme = "ws" + default: + return "", fmt.Errorf("Grok Web Base URL 协议无效") + } value.Path = "/ws/imagine/listen" value.RawQuery = "" return value.String(), nil diff --git a/backend/internal/infra/provider/web/media_clearance_retry_test.go b/backend/internal/infra/provider/web/media_clearance_retry_test.go new file mode 100644 index 00000000..9ec33638 --- /dev/null +++ b/backend/internal/infra/provider/web/media_clearance_retry_test.go @@ -0,0 +1,498 @@ +package web + +import ( + "context" + "encoding/base64" + "encoding/json" + "fmt" + "io" + "net/http" + "strings" + "sync/atomic" + "testing" + "time" + + fhttp "github.com/bogdanfinn/fhttp" + fhttptest "github.com/bogdanfinn/fhttp/httptest" + "github.com/bogdanfinn/websocket" + + "github.com/chenyme/grok2api/backend/internal/domain/account" + infraegress "github.com/chenyme/grok2api/backend/internal/infra/egress" + "github.com/chenyme/grok2api/backend/internal/infra/provider" + "github.com/chenyme/grok2api/backend/internal/infra/security" +) + +func TestIsClearanceRefreshableMediaError(t *testing.T) { + tests := []struct { + name string + body string + code int + want bool + }{ + {name: "empty challenge response", code: http.StatusForbidden, want: true}, + {name: "cloudflare html", code: http.StatusForbidden, body: "Just a moment...", want: true}, + {name: "structured moderation response", code: http.StatusForbidden, body: `{"error":{"code":"content-moderated","message":"rejected"}}`, want: false}, + {name: "server failure", code: http.StatusBadGateway, want: false}, + } + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + err := newWebMediaUpstreamError(test.code, []byte(test.body), false) + if got := isClearanceRefreshableMediaError(err); got != test.want { + t.Fatalf("refreshable=%v, want %v (kind=%q challenge=%v)", got, test.want, err.bodyKind, err.cloudflareChallenge) + } + }) + } +} + +func TestWebMediaUpstreamErrorProviderResponseIsBounded(t *testing.T) { + err := newWebMediaUpstreamError(http.StatusForbidden, nil, false) + response := err.providerResponse() + if response == nil || response.StatusCode != http.StatusForbidden { + t.Fatalf("response=%#v", response) + } + body, readErr := io.ReadAll(response.Body) + _ = response.Body.Close() + if readErr != nil { + t.Fatal(readErr) + } + if !strings.Contains(string(body), "upstream_forbidden") || !strings.Contains(string(body), "Grok Web") { + t.Fatalf("body=%s", body) + } +} + +func TestGenerateWSImageReacquiresAfterChallengeHandshake(t *testing.T) { + var handshakes atomic.Int32 + var solverCalls atomic.Int32 + server := fhttptest.NewServer(fhttp.HandlerFunc(func(writer fhttp.ResponseWriter, request *fhttp.Request) { + if request.URL.Path == "/v1" { + writeTestClearanceSolution(t, writer, solverCalls.Add(1)) + return + } + if request.URL.Path != "/ws/imagine/listen" { + fhttp.NotFound(writer, request) + return + } + handshake := handshakes.Add(1) + if !strings.Contains(request.Header.Get("Cookie"), fmt.Sprintf("cf_clearance=clearance-%d", handshake)) { + t.Errorf("handshake %d did not use refreshed Clearance: %q", handshake, request.Header.Get("Cookie")) + } + if handshake == 1 { + writer.Header().Set("Content-Type", "text/html") + writer.WriteHeader(http.StatusForbidden) + _, _ = writer.Write([]byte("Just a moment...")) + return + } + connection, err := (&websocket.Upgrader{CheckOrigin: func(*fhttp.Request) bool { return true }}).Upgrade(writer, request, nil) + if err != nil { + t.Errorf("upgrade Imagine WebSocket: %v", err) + return + } + defer connection.Close() + for range 2 { + var message map[string]any + if err := connection.ReadJSON(&message); err != nil { + t.Errorf("read Imagine request: %v", err) + return + } + } + _ = connection.WriteJSON(map[string]any{ + "type": "image", "id": "image-1", "blob": "aW1hZ2U=", "percentage_complete": 100, "grid_index": 0, + }) + _ = connection.WriteJSON(map[string]any{ + "type": "json", "id": "image-1", "current_status": "completed", "moderated": false, "order": 0, + }) + })) + defer server.Close() + + adapter, credential := testMediaAdapter(t, server.URL) + enableTestClearance(adapter, server.URL) + response, err := adapter.GenerateImage(context.Background(), provider.ImageGenerationRequest{ + Credential: credential, Model: "grok-imagine-image-quality", Prompt: "draw a teapot", Count: 1, ResponseFormat: "b64_json", + }) + if err != nil { + t.Fatal(err) + } + defer response.Body.Close() + body, readErr := io.ReadAll(response.Body) + if readErr != nil || response.StatusCode != http.StatusOK || !strings.Contains(string(body), `"b64_json"`) { + t.Fatalf("status=%d body=%s err=%v", response.StatusCode, body, readErr) + } + if got := handshakes.Load(); got != 2 { + t.Fatalf("handshakes=%d, want 2", got) + } + if got := solverCalls.Load(); got != 2 { + t.Fatalf("solver calls=%d, want 2", got) + } +} + +func TestGenerateLiteImageReacquiresAfterChallengeHandshake(t *testing.T) { + var handshakes atomic.Int32 + var solverCalls atomic.Int32 + server := fhttptest.NewServer(fhttp.HandlerFunc(func(writer fhttp.ResponseWriter, request *fhttp.Request) { + if request.URL.Path == "/v1" { + writeTestClearanceSolution(t, writer, solverCalls.Add(1)) + return + } + if request.URL.Path != "/ws/mgw/" { + fhttp.NotFound(writer, request) + return + } + handshake := handshakes.Add(1) + if !strings.Contains(request.Header.Get("Cookie"), fmt.Sprintf("cf_clearance=clearance-%d", handshake)) { + t.Errorf("handshake %d did not use refreshed Clearance: %q", handshake, request.Header.Get("Cookie")) + } + if handshake == 1 { + writer.Header().Set("Content-Type", "text/html") + writer.WriteHeader(http.StatusForbidden) + _, _ = writer.Write([]byte("Just a moment...")) + return + } + connection, err := (&websocket.Upgrader{CheckOrigin: func(*fhttp.Request) bool { return true }}).Upgrade(writer, request, nil) + if err != nil { + t.Errorf("upgrade Gateway WebSocket: %v", err) + return + } + defer connection.Close() + var initial map[string]any + if err := connection.ReadJSON(&initial); err != nil { + t.Errorf("read Gateway session: %v", err) + return + } + event, _ := initial["event"].(map[string]any) + eventID, _ := event["event_id"].(string) + _ = connection.WriteJSON(map[string]any{ + "session_id": "session-1", "event": map[string]any{"type": "session.created", "client_event_id": eventID}, + }) + _ = connection.WriteJSON(map[string]any{ + "session_id": "session-1", "event": map[string]any{"type": "conversation.attached", "conversation": map[string]any{"id": "session-1"}}, + }) + for range 2 { + var message map[string]any + if err := connection.ReadJSON(&message); err != nil { + t.Errorf("read Gateway turn: %v", err) + return + } + } + _ = connection.WriteJSON(map[string]any{ + "session_id": "session-1", + "event": map[string]any{ + "type": "response.grok.output", + "output": map[string]any{"card_attachment": map[string]any{"jsonData": map[string]any{ + "id": "card-1", "image_chunk": map[string]any{"progress": 100, "imageUrl": "users/test/generated/image.jpg", "moderated": false}, + }}}, + }, + }) + })) + defer server.Close() + + adapter, credential := testMediaAdapter(t, server.URL) + enableTestClearance(adapter, server.URL) + credential.UserID = "497f19f8-49d4-458a-bee4-43ec3dcaf8ca" + spec, ok := Resolve("grok-imagine-image") + if !ok { + t.Fatal("missing Lite image model") + } + rawURL, err := adapter.generateLiteImageURL(context.Background(), credential, spec, "draw a teapot") + if err != nil { + t.Fatal(err) + } + if rawURL != "https://assets.grok.com/users/test/generated/image.jpg" { + t.Fatalf("url=%q", rawURL) + } + if got := handshakes.Load(); got != 2 { + t.Fatalf("handshakes=%d, want 2", got) + } + if got := solverCalls.Load(); got != 2 { + t.Fatalf("solver calls=%d, want 2", got) + } +} + +func TestStructuredImageForbiddenDoesNotInvalidateClearance(t *testing.T) { + var handshakes atomic.Int32 + var solverCalls atomic.Int32 + server := fhttptest.NewServer(fhttp.HandlerFunc(func(writer fhttp.ResponseWriter, request *fhttp.Request) { + switch request.URL.Path { + case "/v1": + writeTestClearanceSolution(t, writer, solverCalls.Add(1)) + case "/ws/imagine/listen": + handshakes.Add(1) + writer.Header().Set("Content-Type", "application/json") + writer.WriteHeader(http.StatusForbidden) + _, _ = writer.Write([]byte(`{"error":{"code":"content-moderated","message":"rejected"}}`)) + default: + fhttp.NotFound(writer, request) + } + })) + defer server.Close() + + adapter, credential := testMediaAdapter(t, server.URL) + enableTestClearance(adapter, server.URL) + for range 2 { + response, err := adapter.GenerateImage(context.Background(), provider.ImageGenerationRequest{ + Credential: credential, Model: "grok-imagine-image-quality", Prompt: "draw a teapot", Count: 1, + }) + if err != nil { + t.Fatal(err) + } + body, readErr := io.ReadAll(response.Body) + _ = response.Body.Close() + if readErr != nil || response.StatusCode != http.StatusForbidden || !json.Valid(body) { + t.Fatalf("status=%d body=%s err=%v", response.StatusCode, body, readErr) + } + } + if got := handshakes.Load(); got != 2 { + t.Fatalf("handshakes=%d, want one per request", got) + } + if got := solverCalls.Load(); got != 1 { + t.Fatalf("structured 403 refreshed Clearance: solver calls=%d, want 1", got) + } +} + +func TestLiteChallengeRetryExhaustionReturnsNormalizedJSON(t *testing.T) { + var handshakes atomic.Int32 + var solverCalls atomic.Int32 + server := fhttptest.NewServer(fhttp.HandlerFunc(func(writer fhttp.ResponseWriter, request *fhttp.Request) { + switch request.URL.Path { + case "/v1": + writeTestClearanceSolution(t, writer, solverCalls.Add(1)) + case "/ws/mgw/": + handshakes.Add(1) + writer.Header().Set("Content-Type", "text/html") + writer.WriteHeader(http.StatusForbidden) + _, _ = writer.Write([]byte("Just a moment...")) + default: + fhttp.NotFound(writer, request) + } + })) + defer server.Close() + + adapter, credential := testMediaAdapter(t, server.URL) + enableTestClearance(adapter, server.URL) + credential.UserID = "497f19f8-49d4-458a-bee4-43ec3dcaf8ca" + response, err := adapter.GenerateImage(context.Background(), provider.ImageGenerationRequest{ + Credential: credential, Model: "grok-imagine-image", Prompt: "draw a teapot", Count: 1, + }) + if err != nil { + t.Fatal(err) + } + body, readErr := io.ReadAll(response.Body) + _ = response.Body.Close() + if readErr != nil || response.StatusCode != http.StatusForbidden || !json.Valid(body) { + t.Fatalf("status=%d body=%s err=%v", response.StatusCode, body, readErr) + } + if strings.Contains(strings.ToLower(string(body)), "Just a moment...")) +} + +func writeTestPolicyForbidden(writer fhttp.ResponseWriter) { + writer.Header().Set("Content-Type", "application/json") + writer.WriteHeader(http.StatusForbidden) + _, _ = writer.Write([]byte(`{"error":{"code":"content-moderated","message":"rejected"}}`)) +} diff --git a/backend/internal/infra/provider/web/protocol_test.go b/backend/internal/infra/provider/web/protocol_test.go index c4f98c9e..eb36b0b0 100644 --- a/backend/internal/infra/provider/web/protocol_test.go +++ b/backend/internal/infra/provider/web/protocol_test.go @@ -610,7 +610,7 @@ func TestOpenChatScopesStreamIdleTimeoutToTextStreams(t *testing.T) { } for _, enforceStreamIdle := range []bool{false, true} { - upstream, lease, _, _, openErr := adapter.openChat(context.Background(), credential, "", spec, normalizedChatInput{Prompt: "hello"}, enforceStreamIdle) + upstream, lease, _, _, openErr := adapter.openChat(context.Background(), credential, "", spec, normalizedChatInput{Prompt: "hello"}, gatewayOpenOptions{enforceStreamIdle: enforceStreamIdle}) if openErr != nil { t.Fatal(openErr) } diff --git a/backend/internal/infra/provider/web/sso_build.go b/backend/internal/infra/provider/web/sso_build.go index b46ffc68..f6f443bb 100644 --- a/backend/internal/infra/provider/web/sso_build.go +++ b/backend/internal/infra/provider/web/sso_build.go @@ -24,7 +24,6 @@ import ( const ( ssoBuildClientID = "b1a00492-073a-47ea-816f-4c329264a828" ssoBuildScope = "openid profile email offline_access grok-cli:access api:access conversations:read conversations:write" - ssoAccountsURL = "https://accounts.x.ai/" ssoDeviceURL = "https://auth.x.ai/oauth2/device/code" ssoVerifyURL = "https://auth.x.ai/oauth2/device/verify" ssoApproveURL = "https://auth.x.ai/oauth2/device/approve" @@ -75,17 +74,6 @@ func (a *Adapter) ConvertToBuild(ctx context.Context, credential accountdomain.C } func (f *ssoBuildFlow) convert(ctx context.Context, credential accountdomain.Credential) (provider.CredentialSeed, error) { - status, finalURL, _, err := f.do(ctx, http.MethodGet, ssoAccountsURL, nil) - if err != nil { - return provider.CredentialSeed{}, err - } - if status == http.StatusUnauthorized || strings.Contains(finalURL, "sign-in") || strings.Contains(finalURL, "sign-up") { - return provider.CredentialSeed{}, provider.ErrUnauthorized - } - if status < 200 || status >= 400 { - return provider.CredentialSeed{}, fmt.Errorf("校验 Grok Web SSO 失败: %w", conversionHTTPError{status: status}) - } - form := url.Values{"client_id": {ssoBuildClientID}, "scope": {ssoBuildScope}} status, _, body, err := f.do(ctx, http.MethodPost, ssoDeviceURL, form) if err != nil { @@ -95,16 +83,15 @@ func (f *ssoBuildFlow) convert(ctx context.Context, credential accountdomain.Cre return provider.CredentialSeed{}, fmt.Errorf("xAI Device Flow 启动失败: %w", conversionHTTPError{status: status}) } var device struct { - DeviceCode string `json:"device_code"` - UserCode string `json:"user_code"` - VerificationURIComplete string `json:"verification_uri_complete"` - Interval int `json:"interval"` - ExpiresIn int `json:"expires_in"` + DeviceCode string `json:"device_code"` + UserCode string `json:"user_code"` + Interval int `json:"interval"` + ExpiresIn int `json:"expires_in"` } if err := json.Unmarshal(body, &device); err != nil { return provider.CredentialSeed{}, fmt.Errorf("解析 xAI Device Flow: %w", err) } - if device.DeviceCode == "" || device.UserCode == "" || !safeXAIURL(device.VerificationURIComplete) { + if device.DeviceCode == "" || device.UserCode == "" { return provider.CredentialSeed{}, fmt.Errorf("xAI Device Flow 返回字段不完整") } if device.Interval <= 0 { @@ -114,33 +101,37 @@ func (f *ssoBuildFlow) convert(ctx context.Context, credential accountdomain.Cre device.ExpiresIn = 1800 } - status, finalURL, _, err = f.do(ctx, http.MethodGet, device.VerificationURIComplete, nil) + // verify/approve 已在 auth.x.ai 完成状态变更。重定向目标只是结果页, + // 因此不访问 accounts.x.ai,直接解析首个 3xx Location 的状态路径。 + status, finalURL, _, err := f.doWithFollow(ctx, http.MethodPost, ssoVerifyURL, url.Values{"user_code": {device.UserCode}}, false) if err != nil { return provider.CredentialSeed{}, err } - if status < 200 || status >= 400 { - return provider.CredentialSeed{}, fmt.Errorf("打开 Device Flow 验证页失败: %w", conversionHTTPError{status: status}) - } - status, finalURL, _, err = f.do(ctx, http.MethodPost, ssoVerifyURL, url.Values{"user_code": {device.UserCode}}) - if err != nil { - return provider.CredentialSeed{}, err + if status == http.StatusUnauthorized { + return provider.CredentialSeed{}, provider.ErrUnauthorized } if status < 200 || status >= 400 { return provider.CredentialSeed{}, fmt.Errorf("SSO 自动验证 Device Flow 失败: %w", conversionHTTPError{status: status}) } - if !strings.Contains(finalURL, "consent") { + if redirectState := ssoDeviceRedirectState(finalURL); redirectState != "consent" { + if redirectState == "sign-in" { + return provider.CredentialSeed{}, provider.ErrUnauthorized + } return provider.CredentialSeed{}, fmt.Errorf("SSO 自动验证 Device Flow 失败") } - status, finalURL, _, err = f.do(ctx, http.MethodPost, ssoApproveURL, url.Values{ + status, finalURL, _, err = f.doWithFollow(ctx, http.MethodPost, ssoApproveURL, url.Values{ "user_code": {device.UserCode}, "action": {"allow"}, "principal_type": {"User"}, "principal_id": {""}, - }) + }, false) if err != nil { return provider.CredentialSeed{}, err } if status < 200 || status >= 400 { return provider.CredentialSeed{}, fmt.Errorf("SSO 自动批准 Device Flow 失败: %w", conversionHTTPError{status: status}) } - if !strings.Contains(finalURL, "done") { + if redirectState := ssoDeviceRedirectState(finalURL); redirectState != "done" { + if redirectState == "sign-in" { + return provider.CredentialSeed{}, provider.ErrUnauthorized + } return provider.CredentialSeed{}, fmt.Errorf("SSO 自动批准 Device Flow 失败") } @@ -226,6 +217,12 @@ func (f *ssoBuildFlow) pollToken(ctx context.Context, deviceCode string, interva } func (f *ssoBuildFlow) do(ctx context.Context, method, endpoint string, form url.Values) (int, string, []byte, error) { + return f.doWithFollow(ctx, method, endpoint, form, true) +} + +// doWithFollow 在 follow=false 时遇到 3xx 直接返回状态码与解析后的 Location 作为 finalURL, +// 用于重定向目标域会被 Cloudflare 拦截(accounts.x.ai)的请求。 +func (f *ssoBuildFlow) doWithFollow(ctx context.Context, method, endpoint string, form url.Values, follow bool) (int, string, []byte, error) { if !safeXAIURL(endpoint) { return 0, "", nil, fmt.Errorf("xAI OAuth URL 不安全") } @@ -277,6 +274,9 @@ func (f *ssoBuildFlow) do(ctx context.Context, method, endpoint string, form url if !safeXAIURL(currentURL) { return response.StatusCode, currentURL, data, fmt.Errorf("xAI OAuth 重定向到非受信域名") } + if !follow { + return response.StatusCode, currentURL, nil, nil + } if response.StatusCode == http.StatusSeeOther || ((response.StatusCode == http.StatusMovedPermanently || response.StatusCode == http.StatusFound) && currentMethod != http.MethodGet && currentMethod != http.MethodHead) { currentMethod = http.MethodGet currentForm = nil @@ -300,6 +300,24 @@ func (f *ssoBuildFlow) captureCookies(response *http.Response) { } } +func ssoDeviceRedirectState(raw string) string { + parsed, err := url.Parse(raw) + if err != nil || !safeXAIURL(raw) { + return "" + } + path := strings.TrimRight(parsed.EscapedPath(), "/") + switch path { + case "/oauth2/device/consent": + return "consent" + case "/oauth2/device/done": + return "done" + case "/sign-in", "/sign-up": + return "sign-in" + default: + return "" + } +} + func (f *ssoBuildFlow) cookieHeader() string { keys := make([]string, 0, len(f.cookies)) for key := range f.cookies { diff --git a/backend/internal/infra/provider/web/sso_build_test.go b/backend/internal/infra/provider/web/sso_build_test.go index 0e4e54f4..7bcd2615 100644 --- a/backend/internal/infra/provider/web/sso_build_test.go +++ b/backend/internal/infra/provider/web/sso_build_test.go @@ -2,10 +2,15 @@ package web import ( "context" + "errors" "io" "net/http" + "net/url" "strings" "testing" + + accountdomain "github.com/chenyme/grok2api/backend/internal/domain/account" + "github.com/chenyme/grok2api/backend/internal/infra/provider" ) type scriptedSSOClient struct { @@ -26,7 +31,7 @@ func TestSSOBuildFlowFollowsOnlyTrustedXAIHTTPSRedirects(t *testing.T) { {StatusCode: http.StatusOK, Header: http.Header{}, Body: io.NopCloser(strings.NewReader("ok"))}, }} flow := &ssoBuildFlow{client: client, userAgent: "test-agent", cookies: map[string]string{"sso": "secret"}} - status, finalURL, body, err := flow.do(context.Background(), http.MethodGet, ssoAccountsURL, nil) + status, finalURL, body, err := flow.do(context.Background(), http.MethodGet, ssoDeviceURL, nil) if err != nil { t.Fatal(err) } @@ -43,11 +48,89 @@ func TestSSOBuildFlowFollowsOnlyTrustedXAIHTTPSRedirects(t *testing.T) { unsafe := &scriptedSSOClient{responses: []*http.Response{{StatusCode: http.StatusFound, Header: http.Header{"Location": []string{"https://example.com/steal"}}, Body: io.NopCloser(strings.NewReader(""))}}} flow = &ssoBuildFlow{client: unsafe, userAgent: "test-agent", cookies: map[string]string{"sso": "secret"}} - if _, _, _, err := flow.do(context.Background(), http.MethodGet, ssoAccountsURL, nil); err == nil { + if _, _, _, err := flow.do(context.Background(), http.MethodGet, ssoDeviceURL, nil); err == nil { t.Fatal("unsafe redirect was accepted") } } +func TestSSOBuildFlowMapsDeadSSOToUnauthorized(t *testing.T) { + client := &scriptedSSOClient{responses: []*http.Response{ + {StatusCode: http.StatusOK, Header: http.Header{}, Body: io.NopCloser(strings.NewReader( + `{"device_code":"dc","user_code":"uc","interval":1,"expires_in":1800}`))}, + {StatusCode: http.StatusSeeOther, Header: http.Header{"Location": []string{"https://accounts.x.ai/sign-in"}}, Body: io.NopCloser(strings.NewReader(""))}, + }} + flow := &ssoBuildFlow{client: client, userAgent: "lease-agent", cookies: map[string]string{"sso": "dead"}} + _, err := flow.convert(context.Background(), fakeCredential()) + if !errors.Is(err, provider.ErrUnauthorized) { + t.Fatalf("err = %v, want ErrUnauthorized", err) + } + if len(client.requests) != 2 { + t.Fatalf("requests = %d, want 2 (device, verify)", len(client.requests)) + } +} + +func TestSSOBuildFlowUsesAuthEndpointsOnly(t *testing.T) { + client := &scriptedSSOClient{responses: []*http.Response{ + {StatusCode: http.StatusOK, Header: http.Header{}, Body: io.NopCloser(strings.NewReader( + `{"device_code":"dc","user_code":"uc","interval":1,"expires_in":1800}`))}, + {StatusCode: http.StatusSeeOther, Header: http.Header{"Location": []string{"https://accounts.x.ai/oauth2/device/consent"}}, Body: io.NopCloser(strings.NewReader(""))}, + {StatusCode: http.StatusSeeOther, Header: http.Header{"Location": []string{"https://accounts.x.ai/oauth2/device/done"}}, Body: io.NopCloser(strings.NewReader(""))}, + {StatusCode: http.StatusOK, Header: http.Header{}, Body: io.NopCloser(strings.NewReader( + `{"access_token":"access","refresh_token":"refresh","expires_in":3600}`))}, + }} + flow := &ssoBuildFlow{client: client, userAgent: "lease-agent", cookies: map[string]string{"sso": "live", "sso-rw": "live"}} + seed, err := flow.convert(context.Background(), fakeCredential()) + if err != nil { + t.Fatal(err) + } + if seed.AccessToken != "access" || seed.RefreshToken != "refresh" || len(client.requests) != 4 { + t.Fatalf("seed=%#v requests=%d", seed, len(client.requests)) + } + for _, request := range client.requests { + if request.URL.Hostname() != "auth.x.ai" { + t.Fatalf("device flow visited unexpected host %q", request.URL.Hostname()) + } + } +} + +func TestSSOBuildFlowVerifyDoesNotFollowRedirect(t *testing.T) { + client := &scriptedSSOClient{responses: []*http.Response{ + {StatusCode: http.StatusSeeOther, Header: http.Header{"Location": []string{"https://accounts.x.ai/oauth2/device/consent"}}, Body: io.NopCloser(strings.NewReader(""))}, + }} + flow := &ssoBuildFlow{client: client, userAgent: "lease-agent", cookies: map[string]string{"sso": "live"}} + status, finalURL, _, err := flow.doWithFollow(context.Background(), http.MethodPost, ssoVerifyURL, url.Values{"user_code": {"uc"}}, false) + if err != nil { + t.Fatal(err) + } + if status != http.StatusSeeOther { + t.Fatalf("status = %d, want 303", status) + } + if finalURL != "https://accounts.x.ai/oauth2/device/consent" { + t.Fatalf("finalURL = %q", finalURL) + } + if len(client.requests) != 1 { + t.Fatalf("redirect must not be followed, requests = %d", len(client.requests)) + } +} + +func TestSSODeviceRedirectStateRequiresExactTrustedPath(t *testing.T) { + tests := map[string]string{ + "https://accounts.x.ai/oauth2/device/consent": "consent", + "https://accounts.x.ai/oauth2/device/done/": "done", + "https://accounts.x.ai/sign-in?returnTo=%2Foauth2": "sign-in", + "https://accounts.x.ai/other?next=consent": "", + "https://accounts.x.ai/oauth2/device/consent-untrusted": "", + "https://example.com/oauth2/device/consent": "", + } + for raw, wanted := range tests { + if actual := ssoDeviceRedirectState(raw); actual != wanted { + t.Fatalf("ssoDeviceRedirectState(%q)=%q want=%q", raw, actual, wanted) + } + } +} + +func fakeCredential() accountdomain.Credential { return accountdomain.Credential{} } + func TestSSOBuildConversionSanitizesTokenAndURLs(t *testing.T) { if token := normalizeSSOToken("sso=token-value; x-userid=drop"); token != "token-value" { t.Fatalf("token = %q", token) diff --git a/backend/internal/infra/provider/web/video.go b/backend/internal/infra/provider/web/video.go index 39e90d74..33ee1ab3 100644 --- a/backend/internal/infra/provider/web/video.go +++ b/backend/internal/infra/provider/web/video.go @@ -44,6 +44,32 @@ func (e *webMediaUpstreamError) HTTPStatusCode() int { return e.status } +// isClearanceRefreshableMediaError distinguishes browser-session challenges +// from structured upstream policy responses such as content moderation. Empty +// and HTML 403 bodies are the forms returned by the media endpoints when the +// request is rejected before the application response is built. +func isClearanceRefreshableMediaError(e *webMediaUpstreamError) bool { + if e == nil || e.status != http.StatusForbidden { + return false + } + return e.cloudflareChallenge || e.bodyKind == "empty" || e.bodyKind == "html" +} + +func (e *webMediaUpstreamError) providerResponse() *provider.Response { + if e == nil { + return nil + } + code := "upstream_forbidden" + if e.status != http.StatusForbidden { + code = "upstream_unavailable" + } + return jsonProviderResponse(e.status, map[string]any{"error": map[string]any{ + "message": e.summary, + "type": "upstream_error", + "code": code, + }}) +} + const ( webMediaDiagnosticBodyLimit = 64 << 10 webMediaDiagnosticSummaryLimit = 256 diff --git a/backend/internal/pkg/tunnelproxy/reality.go b/backend/internal/pkg/tunnelproxy/reality.go new file mode 100644 index 00000000..fe697be3 --- /dev/null +++ b/backend/internal/pkg/tunnelproxy/reality.go @@ -0,0 +1,236 @@ +package tunnelproxy + +import ( + "bytes" + "context" + "crypto/aes" + "crypto/cipher" + "crypto/ecdh" + "crypto/ed25519" + "crypto/hmac" + "crypto/sha256" + "crypto/sha512" + "crypto/x509" + "encoding/base64" + "encoding/binary" + "encoding/hex" + "errors" + "fmt" + "net" + "time" + + "github.com/Asutorufa/yuhaiin/pkg/net/netapi" + utls "github.com/refraction-networking/utls" + "golang.org/x/crypto/chacha20poly1305" + "golang.org/x/crypto/hkdf" +) + +// realityProxy follows the Xray Reality client handshake used by yuhaiin, but +// keeps the ClientHello selectable so Clash client-fingerprint values are not +// silently replaced with Chrome. +type realityProxy struct { + netapi.EmptyDispatch + dialer netapi.Proxy + serverName string + publicKey *ecdh.PublicKey + shortID [8]byte + helloID utls.ClientHelloID + alpn []string +} + +func newRealityProxy(config Config, dialer netapi.Proxy) (netapi.Proxy, error) { + publicKeyBytes, err := base64.RawURLEncoding.DecodeString(config.RealityPublicKey) + if err != nil { + return nil, fmt.Errorf("解析 Reality public key: %w", err) + } + publicKey, err := ecdh.X25519().NewPublicKey(publicKeyBytes) + if err != nil { + return nil, errors.New("Reality public key 无效") + } + var shortID [8]byte + decodedLength, err := hex.Decode(shortID[:], []byte(config.RealityShortID)) + if err != nil || decodedLength > len(shortID) { + return nil, errors.New("Reality short ID 无效") + } + helloID, ok := realityClientHelloID(config.ClientFingerprint) + if !ok { + return nil, fmt.Errorf("VLESS Reality 暂不支持客户端指纹 %q", config.ClientFingerprint) + } + return &realityProxy{ + dialer: dialer, serverName: config.ServerName, publicKey: publicKey, + shortID: shortID, helloID: helloID, alpn: append([]string(nil), config.ALPN...), + }, nil +} + +func realityClientHelloID(fingerprint string) (utls.ClientHelloID, bool) { + switch fingerprint { + case "chrome": + return utls.HelloChrome_Auto, true + case "firefox": + return utls.HelloFirefox_Auto, true + case "safari": + return utls.HelloSafari_Auto, true + case "ios": + return utls.HelloIOS_Auto, true + case "edge": + return utls.HelloEdge_Auto, true + case "qq": + return utls.HelloQQ_Auto, true + default: + return utls.ClientHelloID{}, false + } +} + +func (p *realityProxy) Conn(ctx context.Context, address netapi.Address) (net.Conn, error) { + connection, err := p.dialer.Conn(ctx, address) + if err != nil { + return nil, err + } + handshakeCtx, cancel := newTunnelHandshakeContext(ctx) + defer cancel() + secure, err := p.handshake(handshakeCtx, connection) + if err != nil { + _ = connection.Close() + return nil, fmt.Errorf("Reality 握手: %w", err) + } + return secure, nil +} + +func (p *realityProxy) PacketConn(context.Context, netapi.Address) (net.PacketConn, error) { + return nil, errors.New("Reality 隧道不支持 UDP") +} + +func (p *realityProxy) handshake(ctx context.Context, connection net.Conn) (net.Conn, error) { + verifier := &realityVerifier{serverName: p.serverName} + secure, err := buildRealityClientHello(connection, p.serverName, p.alpn, p.helloID, verifier.verifyPeerCertificate) + if err != nil { + return nil, err + } + hello := secure.HandshakeState.Hello + privateKey := secure.HandshakeState.State13.EcdheKey + + hello.SessionId = make([]byte, 32) + copy(hello.Raw[39:], hello.SessionId) + binary.BigEndian.PutUint64(hello.SessionId, uint64(time.Now().Unix())) + hello.SessionId[0] = 1 + hello.SessionId[1] = 8 + hello.SessionId[2] = 1 + copy(hello.SessionId[8:], p.shortID[:]) + + peerKey, err := privateKey.ECDH(p.publicKey) + if err != nil { + return nil, fmt.Errorf("Reality ECDH: %w", err) + } + verifier.authKey = peerKey + if _, err := hkdf.New(sha256.New, peerKey, hello.Random[:20], []byte("REALITY")).Read(peerKey); err != nil { + return nil, err + } + var aead cipher.AEAD + if realityPrefersAESGCM(hello.CipherSuites) { + block, cipherErr := aes.NewCipher(peerKey) + if cipherErr != nil { + return nil, cipherErr + } + aead, err = cipher.NewGCM(block) + } else { + aead, err = chacha20poly1305.New(peerKey) + } + if err != nil { + return nil, err + } + aead.Seal(hello.SessionId[:0], hello.Random[20:], hello.SessionId[:16], hello.Raw) + copy(hello.Raw[39:], hello.SessionId) + + if err := secure.HandshakeContext(ctx); err != nil { + return nil, err + } + if !verifier.verified { + return nil, errors.New("Reality 身份验证失败") + } + return secure, nil +} + +func buildRealityClientHello(connection net.Conn, serverName string, alpn []string, helloID utls.ClientHelloID, verify func([][]byte, [][]*x509.Certificate) error) (*utls.UConn, error) { + config := &utls.Config{ + ServerName: serverName, InsecureSkipVerify: true, SessionTicketsDisabled: true, + NextProtos: append([]string(nil), alpn...), VerifyPeerCertificate: verify, + } + secure := utls.UClient(connection, config, helloID) + if err := secure.BuildHandshakeState(); err != nil { + return nil, err + } + if secure.HandshakeState.Hello == nil || len(secure.HandshakeState.Hello.Raw) < 71 { + return nil, errors.New("Reality ClientHello 无效") + } + if len(alpn) != 0 { + patched := false + for _, extension := range secure.Extensions { + if alpnExtension, ok := extension.(*utls.ALPNExtension); ok { + alpnExtension.AlpnProtocols = append([]string(nil), alpn...) + patched = true + break + } + } + if !patched { + secure.Extensions = append(secure.Extensions, &utls.ALPNExtension{AlpnProtocols: append([]string(nil), alpn...)}) + } + config.NextProtos = append([]string(nil), alpn...) + secure.HandshakeState.Hello.AlpnProtocols = append([]string(nil), alpn...) + } + privateKey := secure.HandshakeState.State13.EcdheKey + if privateKey == nil || privateKey.Curve() != ecdh.X25519() { + return nil, fmt.Errorf("Reality 客户端指纹 %q 未提供 X25519 TLS 1.3 key share", helloID.Client) + } + return secure, nil +} + +func realityPrefersAESGCM(cipherSuites []uint16) bool { + for _, cipherSuite := range cipherSuites { + switch cipherSuite { + case utls.TLS_AES_128_GCM_SHA256, utls.TLS_AES_256_GCM_SHA384, + utls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, utls.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384, + utls.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, utls.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384: + return true + case utls.TLS_CHACHA20_POLY1305_SHA256, utls.TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256, + utls.TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256: + return false + } + } + return false +} + +type realityVerifier struct { + serverName string + authKey []byte + verified bool +} + +func (v *realityVerifier) verifyPeerCertificate(rawCertificates [][]byte, _ [][]*x509.Certificate) error { + certificates := make([]*x509.Certificate, 0, len(rawCertificates)) + for _, rawCertificate := range rawCertificates { + certificate, err := x509.ParseCertificate(rawCertificate) + if err != nil { + return err + } + certificates = append(certificates, certificate) + } + if len(certificates) == 0 { + return errors.New("Reality 服务端未返回证书") + } + if publicKey, ok := certificates[0].PublicKey.(ed25519.PublicKey); ok { + digest := hmac.New(sha512.New, v.authKey) + _, _ = digest.Write(publicKey) + if bytes.Equal(digest.Sum(nil), certificates[0].Signature) { + v.verified = true + return nil + } + } + options := x509.VerifyOptions{ + DNSName: v.serverName, Intermediates: x509.NewCertPool(), CurrentTime: time.Now(), + } + for _, certificate := range certificates[1:] { + options.Intermediates.AddCert(certificate) + } + _, err := certificates[0].Verify(options) + return err +} diff --git a/backend/internal/pkg/tunnelproxy/tunnelproxy.go b/backend/internal/pkg/tunnelproxy/tunnelproxy.go index c6314036..26e4b11f 100644 --- a/backend/internal/pkg/tunnelproxy/tunnelproxy.go +++ b/backend/internal/pkg/tunnelproxy/tunnelproxy.go @@ -16,11 +16,15 @@ import ( "github.com/Asutorufa/yuhaiin/pkg/net/netapi" "github.com/Asutorufa/yuhaiin/pkg/net/proxy/trojan" - "github.com/Asutorufa/yuhaiin/pkg/net/proxy/vless" + visionproxy "github.com/Asutorufa/yuhaiin/pkg/net/proxy/vision" + yuhaiinvless "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" + singvmess "github.com/metacubex/sing-vmess" + singvless "github.com/metacubex/sing-vmess/vless" + singmetadata "github.com/metacubex/sing/common/metadata" sscore "github.com/shadowsocks/go-shadowsocks2/core" "github.com/shadowsocks/go-shadowsocks2/socks" ) @@ -34,9 +38,15 @@ type Config struct { Cipher string Transport string TLS bool + Security string + Flow string ServerName string Insecure bool ALPN []string + RealityPublicKey string + RealityShortID string + ClientFingerprint string + SpiderX string WebSocketHost string WebSocketPath string CanonicalProxyURL string @@ -111,9 +121,7 @@ func parseUserInfoProxy(value string) (Config, error) { 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) - } + flow := strings.ToLower(strings.TrimSpace(query.Get("flow"))) if scheme == "vless" { parsedUUID, err := uuid.Parse(credential) if err != nil { @@ -126,16 +134,39 @@ func parseUserInfoProxy(value string) (Config, error) { } security := strings.ToLower(strings.TrimSpace(query.Get("security"))) tlsEnabled := scheme == "trojan" + securityMode := "none" + if tlsEnabled { + securityMode = "tls" + } switch security { case "", "tls": if security == "tls" { tlsEnabled = true + securityMode = "tls" } case "none": tlsEnabled = false + securityMode = "none" + case "reality": + if scheme != "vless" { + return Config{}, errors.New("Reality security 当前仅支持 VLESS") + } + if transport != "tcp" { + return Config{}, errors.New("VLESS Reality 当前仅支持 TCP 传输") + } + tlsEnabled = true + securityMode = "reality" default: return Config{}, fmt.Errorf("暂不支持 %s security %q", strings.ToUpper(scheme), security) } + if flow != "" { + if scheme != "vless" || flow != "xtls-rprx-vision" { + return Config{}, fmt.Errorf("暂不支持 VLESS flow %q", flow) + } + if transport != "tcp" || (securityMode != "tls" && securityMode != "reality") { + return Config{}, errors.New("VLESS Vision 需要 TCP 和 TLS 或 Reality security") + } + } if headerType := strings.ToLower(strings.TrimSpace(query.Get("headerType"))); headerType != "" && headerType != "none" { return Config{}, fmt.Errorf("暂不支持 %s headerType %q", strings.ToUpper(scheme), headerType) } @@ -144,6 +175,23 @@ func parseUserInfoProxy(value string) (Config, error) { return Config{}, err } serverName := firstNonEmpty(query.Get("sni"), query.Get("peer"), parsed.Hostname()) + realityPublicKey := firstNonEmpty(query.Get("pbk"), query.Get("public-key"), query.Get("publicKey")) + realityShortID := firstNonEmpty(query.Get("sid"), query.Get("short-id"), query.Get("shortId")) + fingerprint := strings.ToLower(firstNonEmpty(query.Get("fp"), query.Get("fingerprint"), query.Get("client-fingerprint"))) + spiderX := firstNonEmpty(query.Get("spx"), query.Get("spider-x"), query.Get("spiderX")) + if securityMode == "reality" { + if realityPublicKey == "" { + return Config{}, errors.New("VLESS Reality public key 不能为空") + } + if fingerprint == "" { + fingerprint = "chrome" + } + if _, supported := realityClientHelloID(fingerprint); !supported { + return Config{}, fmt.Errorf("VLESS Reality 暂不支持客户端指纹 %q", fingerprint) + } + } else if realityPublicKey != "" || realityShortID != "" || fingerprint != "" || spiderX != "" { + return Config{}, errors.New("Reality 参数只能用于 Reality security") + } wsHost := firstNonEmpty(query.Get("host"), serverName) if err := validateWebSocketHost(wsHost); transport == "ws" && err != nil { return Config{}, err @@ -159,8 +207,9 @@ func parseUserInfoProxy(value string) (Config, error) { } 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, + TLS: tlsEnabled, Security: securityMode, Flow: flow, ServerName: serverName, Insecure: insecure, + ALPN: splitList(query.Get("alpn")), RealityPublicKey: realityPublicKey, RealityShortID: realityShortID, + ClientFingerprint: fingerprint, SpiderX: spiderX, WebSocketHost: wsHost, WebSocketPath: wsPath, } config.CanonicalProxyURL = canonicalUserInfoProxyURL(config) if err := validateConfig(config); err != nil { @@ -172,15 +221,29 @@ func parseUserInfoProxy(value string) (Config, error) { func canonicalUserInfoProxyURL(config Config) string { query := make(url.Values) query.Set("type", config.Transport) - if config.TLS { - query.Set("security", "tls") - } else { - query.Set("security", "none") + security := config.Security + if security == "" { + security = "none" + if config.TLS { + security = "tls" + } } + query.Set("security", security) if config.Scheme == "vless" { query.Set("encryption", "none") } + if config.Flow != "" { + query.Set("flow", config.Flow) + } query.Set("sni", config.ServerName) + if security == "reality" { + query.Set("pbk", config.RealityPublicKey) + query.Set("sid", config.RealityShortID) + query.Set("fp", config.ClientFingerprint) + if config.SpiderX != "" { + query.Set("spx", config.SpiderX) + } + } if config.Insecure { query.Set("allowInsecure", "1") } @@ -281,6 +344,7 @@ type vmessShare struct { Network string `json:"net"` TLS string `json:"tls,omitempty"` ServerName string `json:"sni,omitempty"` + ALPN string `json:"alpn,omitempty"` Host string `json:"host,omitempty"` Path string `json:"path,omitempty"` AllowInsecure bool `json:"allowInsecure,omitempty"` @@ -336,6 +400,10 @@ func parseVMess(value string) (Config, error) { } tlsEnabled := tlsMode == "tls" serverName := firstNonEmpty(jsonString(raw, "sni"), address) + alpn, err := jsonStringList(raw, "alpn") + if err != nil { + return Config{}, err + } host := firstNonEmpty(jsonString(raw, "host"), serverName) if err := validateWebSocketHost(host); transport == "ws" && err != nil { return Config{}, err @@ -355,7 +423,7 @@ func parseVMess(value string) (Config, error) { } share := vmessShare{ Version: "2", Address: address, Port: port, UUID: userID, AlterID: strconv.Itoa(alterID), Cipher: cipher, - Network: transport, ServerName: serverName, AllowInsecure: insecure, + Network: transport, ServerName: serverName, ALPN: strings.Join(alpn, ","), AllowInsecure: insecure, } if transport == "ws" { share.Host = host @@ -370,7 +438,7 @@ func parseVMess(value string) (Config, error) { } config := Config{ Scheme: "vmess", Server: server, Credential: userID, AlterID: alterID, Cipher: cipher, - Transport: transport, TLS: tlsEnabled, ServerName: serverName, Insecure: insecure, + Transport: transport, TLS: tlsEnabled, ServerName: serverName, Insecure: insecure, ALPN: alpn, WebSocketHost: host, WebSocketPath: path, CanonicalProxyURL: "vmess://" + base64.RawStdEncoding.EncodeToString(canonicalJSON), } @@ -456,6 +524,12 @@ 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.Security == "reality" { + var err error + current, err = newRealityProxy(config, current) + if err != nil { + return nil, fmt.Errorf("创建 Reality 客户端: %w", err) + } } else if config.TLS { current = &tlsProxy{config: config, dialer: current} } @@ -467,7 +541,7 @@ func buildProxy(config Config) (netapi.Proxy, error) { case "vless": protocolConfig := &protocol.Vless{} protocolConfig.SetUuid(config.Credential) - return newOwnedVLESSProxy(protocolConfig, current) + return newOwnedVLESSProxy(protocolConfig, current, config.Flow) case "vmess": protocolConfig := &protocol.Vmess{} protocolConfig.SetUuid(config.Credential) @@ -487,13 +561,23 @@ type ownedVLESSProxy struct { netapi.EmptyDispatch config *protocol.Vless dialer netapi.Proxy + flow string + uuid [16]byte } -func newOwnedVLESSProxy(config *protocol.Vless, dialer netapi.Proxy) (netapi.Proxy, error) { - if _, err := vless.NewClient(config, dialer); err != nil { +func newOwnedVLESSProxy(config *protocol.Vless, dialer netapi.Proxy, flow string) (netapi.Proxy, error) { + if _, err := yuhaiinvless.NewClient(config, dialer); err != nil { return nil, err } - return &ownedVLESSProxy{config: config, dialer: dialer}, nil + proxy := &ownedVLESSProxy{config: config, dialer: dialer, flow: flow} + if flow == "xtls-rprx-vision" { + userID, err := uuid.Parse(config.GetUuid()) + if err != nil { + return nil, errors.New("VLESS Vision UUID 无效") + } + copy(proxy.uuid[:], userID[:]) + } + return proxy, nil } func (p *ownedVLESSProxy) Conn(ctx context.Context, address netapi.Address) (net.Conn, error) { @@ -501,7 +585,20 @@ func (p *ownedVLESSProxy) Conn(ctx context.Context, address netapi.Address) (net if err != nil { return nil, err } - client, err := vless.NewClient(p.config, &singleConnectionProxy{connection: connection}) + if p.flow == "xtls-rprx-vision" { + result, requestErr := newVisionVLESSConn(connection, address, p.uuid, p.flow) + if requestErr != nil { + _ = connection.Close() + return nil, fmt.Errorf("发送 VLESS Vision 请求: %w", requestErr) + } + visionConnection, visionErr := visionproxy.NewVisionConn(result, connection, p.uuid) + if visionErr != nil { + _ = result.Close() + return nil, fmt.Errorf("创建 VLESS Vision 连接: %w", visionErr) + } + return visionConnection, nil + } + client, err := yuhaiinvless.NewClient(p.config, &singleConnectionProxy{connection: connection}) if err != nil { _ = connection.Close() return nil, err @@ -514,6 +611,15 @@ func (p *ownedVLESSProxy) Conn(ctx context.Context, address netapi.Address) (net return result, nil } +func newVisionVLESSConn(connection net.Conn, address netapi.Address, userID [16]byte, flow string) (net.Conn, error) { + destination := singmetadata.ParseSocksaddrHostPort(address.Hostname(), address.Port()) + result := singvless.NewConn(connection, userID, singvmess.CommandTCP, destination, flow) + if _, err := result.Write(nil); err != nil { + return nil, err + } + return result, nil +} + func (p *ownedVLESSProxy) PacketConn(ctx context.Context, address netapi.Address) (net.PacketConn, error) { return nil, errors.New("VLESS 隧道不支持 UDP") } @@ -743,3 +849,28 @@ func jsonString(value map[string]any, name string) string { return "" } } + +func jsonStringList(value map[string]any, name string) ([]string, error) { + raw, ok := value[name] + if !ok || raw == nil { + return nil, nil + } + if text, ok := raw.(string); ok { + return splitList(text), nil + } + items, ok := raw.([]any) + if !ok { + return nil, fmt.Errorf("%s 必须是字符串或字符串数组", name) + } + result := make([]string, 0, len(items)) + for _, item := range items { + text, ok := item.(string) + if !ok { + return nil, fmt.Errorf("%s 必须是字符串或字符串数组", name) + } + if text = strings.TrimSpace(text); text != "" { + result = append(result, text) + } + } + return result, nil +} diff --git a/backend/internal/pkg/tunnelproxy/tunnelproxy_test.go b/backend/internal/pkg/tunnelproxy/tunnelproxy_test.go index a34f86a8..c205cc6e 100644 --- a/backend/internal/pkg/tunnelproxy/tunnelproxy_test.go +++ b/backend/internal/pkg/tunnelproxy/tunnelproxy_test.go @@ -16,6 +16,9 @@ import ( "github.com/Asutorufa/yuhaiin/pkg/net/netapi" "github.com/Asutorufa/yuhaiin/pkg/protos/node/protocol" "github.com/coder/websocket" + "github.com/google/uuid" + singvless "github.com/metacubex/sing-vmess/vless" + utls "github.com/refraction-networking/utls" ) const testUUID = "123e4567-e89b-12d3-a456-426614174000" @@ -63,6 +66,100 @@ func TestNormalizeRemarksDoNotChangeIdentity(t *testing.T) { } } +func TestNormalizeRealityVisionBuildsDialer(t *testing.T) { + raw := "vless://" + testUUID + "@proxy.example:443?encryption=none&security=reality&sni=edge.example&type=tcp&flow=xtls-rprx-vision&fp=chrome&pbk=SOW7P-17ibm_-kz-QUQwGGyitSbsa5wOmRGAigGvDH8&sid=0123456789abcdef&spx=%2F" + normalized, err := Normalize(raw) + if err != nil { + t.Fatal(err) + } + config, err := Parse(normalized) + if err != nil { + t.Fatal(err) + } + if config.Security != "reality" || config.Flow != "xtls-rprx-vision" || config.RealityPublicKey == "" || config.RealityShortID != "0123456789abcdef" || config.ClientFingerprint != "chrome" || config.SpiderX != "/" { + t.Fatalf("Reality Vision config = %#v", config) + } + if _, err := NewDialer(normalized); err != nil { + t.Fatalf("construct Reality Vision dialer: %v", err) + } + for _, field := range []string{"security=reality", "flow=xtls-rprx-vision", "fp=chrome", "pbk=", "sid=0123456789abcdef", "spx=%2F"} { + if !strings.Contains(normalized, field) { + t.Fatalf("normalized Reality URL missing %q: %s", field, normalized) + } + } +} + +func TestNormalizeRealitySupportsStandardClientFingerprints(t *testing.T) { + for _, fingerprint := range []string{"chrome", "edge", "safari", "firefox", "ios", "qq"} { + t.Run(fingerprint, func(t *testing.T) { + raw := "vless://" + testUUID + "@proxy.example:443?encryption=none&security=reality&sni=edge.example&type=tcp&flow=xtls-rprx-vision&pbk=SOW7P-17ibm_-kz-QUQwGGyitSbsa5wOmRGAigGvDH8&sid=0123456789abcdef&fp=" + fingerprint + normalized, err := Normalize(raw) + if err != nil { + t.Fatal(err) + } + config, err := Parse(normalized) + if err != nil { + t.Fatal(err) + } + if config.ClientFingerprint != fingerprint { + t.Fatalf("client fingerprint = %q", config.ClientFingerprint) + } + }) + } +} + +func TestRealityAcceptedFingerprintsProvideX25519AndPreserveALPN(t *testing.T) { + wantedALPN := []string{"h2", "http/1.1"} + for _, fingerprint := range []string{"chrome", "edge", "safari", "firefox", "ios", "qq"} { + t.Run(fingerprint, func(t *testing.T) { + helloID, supported := realityClientHelloID(fingerprint) + if !supported { + t.Fatalf("fingerprint %q unexpectedly unsupported", fingerprint) + } + client, server := net.Pipe() + defer client.Close() + defer server.Close() + secure, err := buildRealityClientHello(client, "edge.example", wantedALPN, helloID, nil) + if err != nil { + t.Fatal(err) + } + if strings.Join(secure.HandshakeState.Hello.AlpnProtocols, ",") != strings.Join(wantedALPN, ",") { + t.Fatalf("ClientHello ALPN = %v", secure.HandshakeState.Hello.AlpnProtocols) + } + foundALPN := false + for _, extension := range secure.Extensions { + alpnExtension, ok := extension.(*utls.ALPNExtension) + if !ok { + continue + } + foundALPN = true + if strings.Join(alpnExtension.AlpnProtocols, ",") != strings.Join(wantedALPN, ",") { + t.Fatalf("ALPN extension = %v", alpnExtension.AlpnProtocols) + } + } + if !foundALPN { + t.Fatal("ClientHello has no ALPN extension") + } + }) + } +} + +func TestRealityClientHelloWithoutTLS13KeyShareReturnsError(t *testing.T) { + for name, helloID := range map[string]utls.ClientHelloID{ + "android": utls.HelloAndroid_11_OkHttp, + "360": utls.Hello360_Auto, + } { + t.Run(name, func(t *testing.T) { + client, server := net.Pipe() + defer client.Close() + defer server.Close() + if _, err := buildRealityClientHello(client, "edge.example", nil, helloID, nil); err == nil { + t.Fatalf("fingerprint %q unexpectedly produced a Reality key share", name) + } + }) + } +} + func TestNormalizeEquivalentShareLinksHaveOneIdentity(t *testing.T) { trojanOne, err := Normalize("trojan://secret@proxy.example:443?type=websocket&security=tls&sni=edge.example&host=edge.example&path=ws") if err != nil { @@ -99,6 +196,38 @@ func TestNormalizeEquivalentShareLinksHaveOneIdentity(t *testing.T) { } } +func TestNormalizeVMessPreservesALPN(t *testing.T) { + stringURL := vmessTestURL(t, map[string]any{ + "v": "2", "add": "proxy.example", "port": "443", "id": testUUID, + "aid": "0", "scy": "auto", "net": "tcp", "tls": "tls", "sni": "edge.example", + "alpn": "h2, http/1.1", + }) + arrayURL := vmessTestURL(t, map[string]any{ + "v": "2", "add": "proxy.example", "port": "443", "id": testUUID, + "aid": "0", "scy": "auto", "net": "tcp", "tls": "tls", "sni": "edge.example", + "alpn": []string{"h2", "http/1.1"}, + }) + stringNormalized, err := Normalize(stringURL) + if err != nil { + t.Fatal(err) + } + arrayNormalized, err := Normalize(arrayURL) + if err != nil { + t.Fatal(err) + } + if stringNormalized != arrayNormalized { + t.Fatalf("equivalent VMess ALPN forms have different identities: %q != %q", stringNormalized, arrayNormalized) + } + config, err := Parse(stringNormalized) + if err != nil { + t.Fatal(err) + } + wanted := "h2,http/1.1" + if strings.Join(config.ALPN, ",") != wanted || strings.Join((&tlsProxy{config: config}).tlsConfig().NextProtos, ",") != wanted { + t.Fatalf("VMess ALPN was not preserved in TLS config: %#v", config) + } +} + func TestOwnedVLESSProxyClosesConnectionWhenInitialWriteFails(t *testing.T) { client, server := net.Pipe() if err := server.Close(); err != nil { @@ -107,7 +236,7 @@ func TestOwnedVLESSProxyClosesConnectionWhenInitialWriteFails(t *testing.T) { tracked := &closeTrackingConn{Conn: client} config := &protocol.Vless{} config.SetUuid(testUUID) - proxy, err := newOwnedVLESSProxy(config, &singleConnectionProxy{connection: tracked}) + proxy, err := newOwnedVLESSProxy(config, &singleConnectionProxy{connection: tracked}, "") if err != nil { t.Fatal(err) } @@ -119,6 +248,41 @@ func TestOwnedVLESSProxyClosesConnectionWhenInitialWriteFails(t *testing.T) { } } +func TestVisionVLESSRequestIncludesFlowAddon(t *testing.T) { + client, server := net.Pipe() + defer server.Close() + + var userID [16]byte + parsedUUID, err := uuid.Parse(testUUID) + if err != nil { + t.Fatal(err) + } + copy(userID[:], parsedUUID[:]) + + result := make(chan error, 1) + go func() { + connection, requestErr := newVisionVLESSConn(client, netapi.ParseDomainPort("tcp", "target.example", 443), userID, "xtls-rprx-vision") + if connection != nil { + _ = connection.Close() + } + result <- requestErr + }() + + request, err := singvless.ReadRequest(server) + if err != nil { + t.Fatal(err) + } + if request.Flow != "xtls-rprx-vision" { + t.Fatalf("VLESS flow addon = %q", request.Flow) + } + if request.Destination.Fqdn != "target.example" || request.Destination.Port != 443 { + t.Fatalf("VLESS destination = %v", request.Destination) + } + if err := <-result; err != nil { + t.Fatal(err) + } +} + func TestTunnelHandshakeContextHasIndependentDeadline(t *testing.T) { ctx, cancel := newTunnelHandshakeContext(context.Background()) defer cancel() @@ -149,11 +313,19 @@ func TestParseRejectsUnsupportedOrMalformedLinks(t *testing.T) { "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", + "vless://" + testUUID + "@proxy.example:443?encryption=none&security=reality&sni=edge.example&pbk=invalid&sid=01", + "vless://" + testUUID + "@proxy.example:443?encryption=none&security=reality&sni=edge.example&pbk=SOW7P-17ibm_-kz-QUQwGGyitSbsa5wOmRGAigGvDH8&sid=01&fp=opera", + "vless://" + testUUID + "@proxy.example:443?encryption=none&security=reality&sni=edge.example&pbk=SOW7P-17ibm_-kz-QUQwGGyitSbsa5wOmRGAigGvDH8&sid=01&fp=android", + "vless://" + testUUID + "@proxy.example:443?encryption=none&security=reality&sni=edge.example&pbk=SOW7P-17ibm_-kz-QUQwGGyitSbsa5wOmRGAigGvDH8&sid=01&fp=360", "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", + vmessTestURL(t, map[string]any{ + "v": "2", "add": "proxy.example", "port": "443", "id": testUUID, + "aid": "0", "scy": "auto", "net": "tcp", "tls": "tls", "alpn": []any{"h2", 1}, + }), } { if _, err := Normalize(raw); err == nil { t.Fatalf("invalid tunnel accepted: %q", raw) diff --git a/backend/internal/transport/http/egress/handler.go b/backend/internal/transport/http/egress/handler.go index 52f73f07..362e1034 100644 --- a/backend/internal/transport/http/egress/handler.go +++ b/backend/internal/transport/http/egress/handler.go @@ -11,6 +11,7 @@ import ( "path/filepath" "strconv" "strings" + "sync" "time" egressapp "github.com/chenyme/grok2api/backend/internal/application/egress" @@ -26,6 +27,7 @@ type Handler struct { guardStatePath string guardConfigPath string guardProbe egressapp.QualityProbeInput + profilesMu sync.Mutex } func NewHandler(service *egressapp.Service, guardStatePath ...string) *Handler { @@ -59,6 +61,10 @@ func (h *Handler) Register(router *gin.RouterGroup) { router.POST("/egress-nodes/:id/quality-test", h.testQuality) router.GET("/egress-quality-guard", h.qualityGuardStatus) router.PUT("/egress-quality-guard/config", h.updateQualityGuardConfig) + router.GET("/egress-quality-guard/profiles", h.listQualityGuardProfiles) + router.POST("/egress-quality-guard/profiles", h.createQualityGuardProfile) + router.PUT("/egress-quality-guard/profiles/:id", h.updateQualityGuardProfile) + router.DELETE("/egress-quality-guard/profiles/:id", h.deleteQualityGuardProfile) router.POST("/egress-quality-guard/nodes/:id/test", h.testQualityGuardNode) router.POST("/egress-nodes/:id/accounts", h.assignAccounts) router.DELETE("/egress-nodes/accounts", h.unassignAccounts) @@ -203,6 +209,10 @@ func (h *Handler) qualityGuardStatus(c *gin.Context) { if state.Statistics.StartedAt > 0 { payload["statistics"] = state.Statistics } + if profiles, err := loadProbeProfileFile(h.profilesPath()); err == nil { + payload["activeProfileId"] = profiles.ActiveProfileID + payload["profiles"] = profiles.summaries() + } response.Success(c, http.StatusOK, payload) } @@ -361,11 +371,24 @@ func (h *Handler) testQualityGuardNode(c *gin.Context) { if !ok { return } - if h.guardProbe.ClientKeyID == 0 || strings.TrimSpace(h.guardProbe.Model) == "" || h.guardProbe.Prompt == "" || h.guardProbe.Expected == "" { + if h.guardProbe.ClientKeyID == 0 || strings.TrimSpace(h.guardProbe.Model) == "" { response.Error(c, http.StatusServiceUnavailable, "qualityGuardUnavailable", "质量守护配置暂不可用") return } - value, err := h.service.ProbeQuality(c.Request.Context(), nodeID, h.guardProbe) + var request struct { + ProfileID string `json:"profileId"` + } + _ = c.ShouldBindJSON(&request) + input, err := h.resolveProbeInput(strings.TrimSpace(request.ProfileID)) + if err != nil { + response.Error(c, http.StatusBadRequest, "invalidRequest", err.Error()) + return + } + if strings.TrimSpace(input.Prompt) == "" { + response.Error(c, http.StatusServiceUnavailable, "qualityGuardUnavailable", "质量守护配置暂不可用") + return + } + value, err := h.service.ProbeQuality(c.Request.Context(), nodeID, input) if err != nil { h.writeQualityProbeError(c, err) return @@ -378,7 +401,8 @@ func (h *Handler) testQualityGuardNode(c *gin.Context) { "visibleTokens": value.VisibleTokens, "visibleCharacters": value.VisibleCharacters, "outputTokensPerSecond": value.OutputTokensPerSecond, "visibleTokensPerSecond": value.OutputTokensPerSecond, "expectedMatched": value.ExpectedMatched, - "responseSha256": value.ResponseSHA256, + "thinkingRequired": value.ThinkingRequired, + "responseSha256": value.ResponseSHA256, }) } @@ -516,7 +540,8 @@ func (h *Handler) testQuality(c *gin.Context) { "visibleTokens": value.VisibleTokens, "visibleCharacters": value.VisibleCharacters, "outputTokensPerSecond": value.OutputTokensPerSecond, "visibleTokensPerSecond": value.OutputTokensPerSecond, "expectedMatched": value.ExpectedMatched, - "responseSha256": value.ResponseSHA256, + "thinkingRequired": value.ThinkingRequired, + "responseSha256": value.ResponseSHA256, }) } diff --git a/backend/internal/transport/http/egress/handler_test.go b/backend/internal/transport/http/egress/handler_test.go index 2b664174..9e8eb18f 100644 --- a/backend/internal/transport/http/egress/handler_test.go +++ b/backend/internal/transport/http/egress/handler_test.go @@ -3,10 +3,12 @@ package egress import ( "bytes" "errors" + "fmt" "net/http/httptest" "os" "runtime" "strings" + "sync" "testing" "time" @@ -94,6 +96,99 @@ func TestWriteQualityProbeErrorIdentifiesMissingProbeAccount(t *testing.T) { } } +func TestQualityGuardProfilesCRUDAndStatusOmitsPrompt(t *testing.T) { + directory := t.TempDir() + statePath := directory + "/state.json" + configPath := directory + "/runtime-config.json" + if err := os.WriteFile(statePath, []byte(`{"version":1,"guard":{"mode":"hybrid","model":"grok-4.5","node_ids":["8"]},"nodes":{}}`), 0o600); err != nil { + t.Fatal(err) + } + handler := NewHandler(nil, statePath, configPath) + + createRecorder := httptest.NewRecorder() + createContext, _ := gin.CreateTestContext(createRecorder) + createContext.Request = httptest.NewRequest("POST", "/egress-quality-guard/profiles", bytes.NewBufferString(`{"name":"自定义标记","prompt":"只输出 FLAG_OK","expectedText":"FLAG_OK","matchMode":"last_line","requireThinking":true,"active":true}`)) + createContext.Request.Header.Set("Content-Type", "application/json") + handler.createQualityGuardProfile(createContext) + if createRecorder.Code != 200 || !strings.Contains(createRecorder.Body.String(), `"FLAG_OK"`) || !strings.Contains(createRecorder.Body.String(), `"require_thinking":true`) { + t.Fatalf("create status=%d body=%s", createRecorder.Code, createRecorder.Body.String()) + } + + statusRecorder := httptest.NewRecorder() + statusContext, _ := gin.CreateTestContext(statusRecorder) + statusContext.Request = httptest.NewRequest("GET", "/egress-quality-guard", nil) + handler.qualityGuardStatus(statusContext) + body := statusRecorder.Body.String() + if statusRecorder.Code != 200 || !strings.Contains(body, `"activeProfileId":"p-2"`) || !strings.Contains(body, `"has_expected":true`) || !strings.Contains(body, `"require_thinking":true`) { + t.Fatalf("status=%d body=%s", statusRecorder.Code, body) + } + if strings.Contains(body, "只输出 FLAG_OK") || strings.Contains(body, "FLAG_OK") { + t.Fatalf("status leaked probe prompt or marker: %s", body) + } +} + +func TestQualityGuardProfileWritesAreSerialized(t *testing.T) { + directory := t.TempDir() + handler := NewHandler(nil, "", directory+"/runtime-config.json") + const count = 32 + var wait sync.WaitGroup + errorsFound := make(chan string, count) + for index := 0; index < count; index++ { + wait.Add(1) + go func(index int) { + defer wait.Done() + recorder := httptest.NewRecorder() + context, _ := gin.CreateTestContext(recorder) + body := fmt.Sprintf(`{"name":"profile-%d","prompt":"probe-%d","matchMode":"contains"}`, index, index) + context.Request = httptest.NewRequest("POST", "/egress-quality-guard/profiles", bytes.NewBufferString(body)) + context.Request.Header.Set("Content-Type", "application/json") + handler.createQualityGuardProfile(context) + if recorder.Code != 200 { + errorsFound <- recorder.Body.String() + } + }(index) + } + wait.Wait() + close(errorsFound) + for message := range errorsFound { + t.Fatalf("concurrent profile create failed: %s", message) + } + data, err := loadProbeProfileFile(directory + "/profiles.json") + if err != nil { + t.Fatal(err) + } + custom := 0 + for _, profile := range data.Profiles { + if !profile.BuiltIn { + custom++ + } + } + if custom != count { + t.Fatalf("custom profiles = %d, want %d", custom, count) + } +} + +func TestQualityGuardReservedProfilesAreCanonicalized(t *testing.T) { + directory := t.TempDir() + path := directory + "/profiles.json" + forged := `{"version":1,"active_profile_id":"quality-marker","profiles":{"quality-marker":{"id":"quality-marker","name":"forged","built_in":false,"prompt":"skip checks","expected_text":"","match_mode":"contains","require_thinking":false},"throughput":{"id":"throughput","name":"forged","built_in":false,"prompt":"skip checks","expected_text":"PASS","match_mode":"regex","require_thinking":true}}}` + if err := os.WriteFile(path, []byte(forged), 0o600); err != nil { + t.Fatal(err) + } + data, err := loadProbeProfileFile(path) + if err != nil { + t.Fatal(err) + } + marker := data.Profiles[profileQualityMarker] + if !marker.BuiltIn || marker.ExpectedText != "QUALITY_OK" || marker.MatchMode != egressapp.MatchLastLine || !marker.RequireThinking { + t.Fatalf("quality marker was not canonicalized: %#v", marker) + } + throughput := data.Profiles[profileThroughput] + if !throughput.BuiltIn || throughput.ExpectedText != "" || throughput.MatchMode != egressapp.MatchContains || throughput.RequireThinking { + t.Fatalf("throughput profile was not canonicalized: %#v", throughput) + } +} + func TestUpdateQualityGuardConfigWritesPrivateAtomicFile(t *testing.T) { directory := t.TempDir() statePath := directory + "/state.json" diff --git a/backend/internal/transport/http/egress/profiles.go b/backend/internal/transport/http/egress/profiles.go new file mode 100644 index 00000000..c727d928 --- /dev/null +++ b/backend/internal/transport/http/egress/profiles.go @@ -0,0 +1,431 @@ +package egress + +import ( + "encoding/json" + "errors" + "fmt" + "net/http" + "os" + "path/filepath" + "regexp" + "sort" + "strings" + "time" + + egressapp "github.com/chenyme/grok2api/backend/internal/application/egress" + "github.com/chenyme/grok2api/backend/internal/shared/response" + "github.com/gin-gonic/gin" +) + +const ( + profileThroughput = "throughput" + profileQualityMarker = "quality-marker" + maxCustomProfiles = 32 +) + +type probeProfile struct { + ID string `json:"id"` + Name string `json:"name"` + BuiltIn bool `json:"built_in"` + Prompt string `json:"prompt"` + ExpectedText string `json:"expected_text,omitempty"` + MatchMode string `json:"match_mode"` + RequireThinking bool `json:"require_thinking"` + MaxOutputTokens int `json:"max_output_tokens,omitempty"` + UpdatedAt float64 `json:"updated_at,omitempty"` +} + +type probeProfileFile struct { + Version int `json:"version"` + ActiveProfileID string `json:"active_profile_id"` + NextID int `json:"next_id"` + Profiles map[string]probeProfile `json:"profiles"` +} + +func builtinProbeProfiles() []probeProfile { + return []probeProfile{ + { + ID: profileQualityMarker, + Name: "预期标记", + BuiltIn: true, + Prompt: "先用三点总结为什么天空呈蓝色,最后一行只输出 QUALITY_OK。", + ExpectedText: "QUALITY_OK", + MatchMode: egressapp.MatchLastLine, + RequireThinking: true, + }, + { + ID: profileThroughput, + Name: "吞吐基线", + BuiltIn: true, + Prompt: "Write a detailed technical explanation of how TCP slow start works, at least 12 sentences, plain text only.", + MatchMode: egressapp.MatchContains, + }, + } +} + +func (h *Handler) profilesPath() string { + if h.guardConfigPath == "" { + return "" + } + return filepath.Join(filepath.Dir(h.guardConfigPath), "profiles.json") +} + +func seedProbeProfileFile(data *probeProfileFile) { + if data.Profiles == nil { + data.Profiles = map[string]probeProfile{} + } + if data.Version == 0 { + data.Version = 1 + } + now := float64(time.Now().Unix()) + for _, builtin := range builtinProbeProfiles() { + existing, ok := data.Profiles[builtin.ID] + if !ok { + builtin.UpdatedAt = now + data.Profiles[builtin.ID] = builtin + continue + } + // Reserved built-in IDs define recovery safety invariants. Never trust + // persisted metadata for these IDs, even if an older version or a manual + // edit incorrectly cleared built_in. + existing.ID = builtin.ID + existing.Name = builtin.Name + existing.BuiltIn = true + existing.Prompt = builtin.Prompt + existing.ExpectedText = builtin.ExpectedText + existing.MatchMode = builtin.MatchMode + existing.RequireThinking = builtin.RequireThinking + existing.MaxOutputTokens = builtin.MaxOutputTokens + data.Profiles[builtin.ID] = existing + } + if data.ActiveProfileID == "" { + data.ActiveProfileID = profileQualityMarker + } + if _, ok := data.Profiles[data.ActiveProfileID]; !ok { + data.ActiveProfileID = profileQualityMarker + } + if data.NextID < 1 { + data.NextID = 1 + } +} + +func loadProbeProfileFile(path string) (probeProfileFile, error) { + data := probeProfileFile{Version: 1, Profiles: map[string]probeProfile{}} + if path == "" { + seedProbeProfileFile(&data) + return data, nil + } + raw, err := os.ReadFile(path) + if err != nil { + if errors.Is(err, os.ErrNotExist) { + seedProbeProfileFile(&data) + return data, nil + } + return probeProfileFile{}, err + } + if err := json.Unmarshal(raw, &data); err != nil { + return probeProfileFile{}, err + } + seedProbeProfileFile(&data) + return data, nil +} + +func saveProbeProfileFile(path string, data probeProfileFile) error { + if path == "" { + return errors.New("profiles path is empty") + } + if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil { + return err + } + raw, err := json.Marshal(data) + if err != nil { + return err + } + temporary, err := os.CreateTemp(filepath.Dir(path), ".profiles-") + if err != nil { + return err + } + temporaryPath := temporary.Name() + defer os.Remove(temporaryPath) + if err := temporary.Chmod(0o600); err != nil { + _ = temporary.Close() + return err + } + if _, err := temporary.Write(raw); err != nil { + _ = temporary.Close() + return err + } + if err := temporary.Close(); err != nil { + return err + } + return os.Rename(temporaryPath, path) +} + +func (data probeProfileFile) resolve(id string) (probeProfile, bool) { + if id == "" { + id = data.ActiveProfileID + } + profile, ok := data.Profiles[id] + return profile, ok +} + +func (data probeProfileFile) summaries() []map[string]any { + out := make([]map[string]any, 0, len(data.Profiles)) + for _, profile := range data.Profiles { + out = append(out, map[string]any{ + "id": profile.ID, + "name": profile.Name, + "built_in": profile.BuiltIn, + "match_mode": profile.MatchMode, + "has_expected": strings.TrimSpace(profile.ExpectedText) != "", + "require_thinking": profile.RequireThinking, + }) + } + sort.Slice(out, func(i, j int) bool { + leftBuiltIn, _ := out[i]["built_in"].(bool) + rightBuiltIn, _ := out[j]["built_in"].(bool) + if leftBuiltIn != rightBuiltIn { + return leftBuiltIn + } + leftID, _ := out[i]["id"].(string) + rightID, _ := out[j]["id"].(string) + return leftID < rightID + }) + return out +} + +func validateProbeProfile(profile *probeProfile, creating bool) error { + profile.Name = strings.TrimSpace(profile.Name) + profile.Prompt = strings.TrimSpace(profile.Prompt) + profile.ExpectedText = strings.TrimSpace(profile.ExpectedText) + profile.MatchMode = egressapp.NormalizeMatchMode(profile.MatchMode) + if profile.Name == "" { + return errors.New("方案名称不能为空") + } + if len(profile.Name) > 80 { + return errors.New("方案名称不能超过 80 个字符") + } + if profile.Prompt == "" { + return errors.New("探测 Prompt 不能为空") + } + if len(profile.Prompt) > egressapp.MaxQualityProbePromptBytes { + return errors.New("探测 Prompt 过长") + } + if len(profile.ExpectedText) > egressapp.MaxQualityProbeExpectedBytes { + return errors.New("预期标记过长") + } + if profile.MatchMode == egressapp.MatchRegex && profile.ExpectedText != "" { + if _, err := regexp.Compile(profile.ExpectedText); err != nil { + return fmt.Errorf("正则预期标记无效") + } + } + if profile.MaxOutputTokens < 0 || profile.MaxOutputTokens > egressapp.MaxQualityProbeOutputTokens { + return fmt.Errorf("方案最大输出需在 0 到 %d Token 之间", egressapp.MaxQualityProbeOutputTokens) + } + if creating && profile.BuiltIn { + return errors.New("不能新建内置方案") + } + return nil +} + +func applyProfile(base egressapp.QualityProbeInput, profile probeProfile) egressapp.QualityProbeInput { + base.Prompt = profile.Prompt + base.Expected = profile.ExpectedText + base.MatchMode = egressapp.NormalizeMatchMode(profile.MatchMode) + base.RequireThinking = profile.RequireThinking + if profile.MaxOutputTokens > 0 { + base.MaxOutputTokens = profile.MaxOutputTokens + } + return base +} + +func (h *Handler) listQualityGuardProfiles(c *gin.Context) { + data, err := loadProbeProfileFile(h.profilesPath()) + if err != nil { + response.Error(c, http.StatusServiceUnavailable, "qualityGuardUnavailable", "探针方案暂不可用") + return + } + items := make([]probeProfile, 0, len(data.Profiles)) + for _, profile := range data.Profiles { + items = append(items, profile) + } + sort.Slice(items, func(i, j int) bool { + if items[i].BuiltIn != items[j].BuiltIn { + return items[i].BuiltIn + } + return items[i].ID < items[j].ID + }) + response.Success(c, http.StatusOK, gin.H{ + "activeProfileId": data.ActiveProfileID, + "items": items, + }) +} + +type probeProfileWriteRequest struct { + Name string `json:"name"` + Prompt string `json:"prompt"` + ExpectedText string `json:"expectedText"` + MatchMode string `json:"matchMode"` + RequireThinking bool `json:"requireThinking"` + MaxOutputTokens int `json:"maxOutputTokens"` + Active bool `json:"active"` +} + +func (h *Handler) createQualityGuardProfile(c *gin.Context) { + path := h.profilesPath() + if path == "" { + response.Error(c, http.StatusServiceUnavailable, "qualityGuardReadOnly", "探针方案当前只读") + return + } + var request probeProfileWriteRequest + if c.ShouldBindJSON(&request) != nil { + response.Error(c, http.StatusBadRequest, "invalidRequest", "请求参数无效") + return + } + h.profilesMu.Lock() + defer h.profilesMu.Unlock() + data, err := loadProbeProfileFile(path) + if err != nil { + response.Error(c, http.StatusServiceUnavailable, "qualityGuardUnavailable", "探针方案暂不可用") + return + } + custom := 0 + for _, profile := range data.Profiles { + if !profile.BuiltIn { + custom++ + } + } + if custom >= maxCustomProfiles { + response.Error(c, http.StatusBadRequest, "invalidRequest", fmt.Sprintf("自定义方案最多 %d 个", maxCustomProfiles)) + return + } + profile := probeProfile{ + Name: request.Name, Prompt: request.Prompt, ExpectedText: request.ExpectedText, + MatchMode: request.MatchMode, RequireThinking: request.RequireThinking, MaxOutputTokens: request.MaxOutputTokens, + } + if err := validateProbeProfile(&profile, true); err != nil { + response.Error(c, http.StatusBadRequest, "invalidRequest", err.Error()) + return + } + data.NextID++ + profile.ID = fmt.Sprintf("p-%d", data.NextID) + profile.UpdatedAt = float64(time.Now().Unix()) + data.Profiles[profile.ID] = profile + if request.Active { + data.ActiveProfileID = profile.ID + } + if err := saveProbeProfileFile(path, data); err != nil { + response.Error(c, http.StatusServiceUnavailable, "qualityGuardConfigWriteFailed", "探针方案保存失败") + return + } + response.Success(c, http.StatusOK, profile) +} + +func (h *Handler) updateQualityGuardProfile(c *gin.Context) { + path := h.profilesPath() + if path == "" { + response.Error(c, http.StatusServiceUnavailable, "qualityGuardReadOnly", "探针方案当前只读") + return + } + id := strings.TrimSpace(c.Param("id")) + var request probeProfileWriteRequest + if c.ShouldBindJSON(&request) != nil { + response.Error(c, http.StatusBadRequest, "invalidRequest", "请求参数无效") + return + } + h.profilesMu.Lock() + defer h.profilesMu.Unlock() + data, err := loadProbeProfileFile(path) + if err != nil { + response.Error(c, http.StatusServiceUnavailable, "qualityGuardUnavailable", "探针方案暂不可用") + return + } + existing, ok := data.Profiles[id] + if !ok { + response.Error(c, http.StatusNotFound, "notFound", "方案不存在") + return + } + if existing.BuiltIn { + if request.Active { + data.ActiveProfileID = existing.ID + if err := saveProbeProfileFile(path, data); err != nil { + response.Error(c, http.StatusServiceUnavailable, "qualityGuardConfigWriteFailed", "探针方案保存失败") + return + } + response.Success(c, http.StatusOK, existing) + return + } + response.Error(c, http.StatusBadRequest, "invalidRequest", "内置方案不能修改,请复制后另存") + return + } + existing.Name = request.Name + existing.Prompt = request.Prompt + existing.ExpectedText = request.ExpectedText + existing.MatchMode = request.MatchMode + existing.RequireThinking = request.RequireThinking + existing.MaxOutputTokens = request.MaxOutputTokens + if err := validateProbeProfile(&existing, false); err != nil { + response.Error(c, http.StatusBadRequest, "invalidRequest", err.Error()) + return + } + existing.UpdatedAt = float64(time.Now().Unix()) + data.Profiles[id] = existing + if request.Active { + data.ActiveProfileID = id + } + if err := saveProbeProfileFile(path, data); err != nil { + response.Error(c, http.StatusServiceUnavailable, "qualityGuardConfigWriteFailed", "探针方案保存失败") + return + } + response.Success(c, http.StatusOK, existing) +} + +func (h *Handler) deleteQualityGuardProfile(c *gin.Context) { + path := h.profilesPath() + if path == "" { + response.Error(c, http.StatusServiceUnavailable, "qualityGuardReadOnly", "探针方案当前只读") + return + } + id := strings.TrimSpace(c.Param("id")) + h.profilesMu.Lock() + defer h.profilesMu.Unlock() + data, err := loadProbeProfileFile(path) + if err != nil { + response.Error(c, http.StatusServiceUnavailable, "qualityGuardUnavailable", "探针方案暂不可用") + return + } + existing, ok := data.Profiles[id] + if !ok { + response.Error(c, http.StatusNotFound, "notFound", "方案不存在") + return + } + if existing.BuiltIn { + response.Error(c, http.StatusBadRequest, "invalidRequest", "内置方案不能删除") + return + } + delete(data.Profiles, id) + if data.ActiveProfileID == id { + data.ActiveProfileID = profileQualityMarker + } + if err := saveProbeProfileFile(path, data); err != nil { + response.Error(c, http.StatusServiceUnavailable, "qualityGuardConfigWriteFailed", "探针方案保存失败") + return + } + response.Success(c, http.StatusOK, gin.H{"deleted": true}) +} + +func (h *Handler) resolveProbeInput(profileID string) (egressapp.QualityProbeInput, error) { + input := h.guardProbe + data, err := loadProbeProfileFile(h.profilesPath()) + if err != nil { + return input, err + } + profile, ok := data.resolve(profileID) + if !ok { + if profileID != "" { + return input, fmt.Errorf("方案不存在") + } + return input, nil + } + return applyProfile(input, profile), nil +} diff --git a/backend/internal/transport/http/inference/handler.go b/backend/internal/transport/http/inference/handler.go index 0e990f8d..25a93754 100644 --- a/backend/internal/transport/http/inference/handler.go +++ b/backend/internal/transport/http/inference/handler.go @@ -1929,7 +1929,7 @@ func writeGatewayError(c *gin.Context, err error) { case errors.Is(err, gateway.ErrResponseStateUnsupported), errors.Is(err, gateway.ErrConversationUnsupported): status, code = http.StatusBadRequest, "unsupported_parameter" message = err.Error() - case errors.Is(err, gateway.ErrVideoInputTooLarge), errors.Is(err, gateway.ErrVideoInputUnavailable): + case errors.Is(err, gateway.ErrVideoInputTooLarge), errors.Is(err, gateway.ErrVideoInputUnavailable), errors.Is(err, gateway.ErrVideoParameterInvalid): status, code = http.StatusBadRequest, "invalid_request" message = err.Error() case errors.Is(err, gateway.ErrVideoOperationUnsupported): diff --git a/backend/internal/transport/http/inference/handler_test.go b/backend/internal/transport/http/inference/handler_test.go index 045e210f..d34f39b2 100644 --- a/backend/internal/transport/http/inference/handler_test.go +++ b/backend/internal/transport/http/inference/handler_test.go @@ -4,6 +4,7 @@ import ( "bytes" "encoding/json" "errors" + "fmt" "io" "math" "net/http" @@ -220,6 +221,19 @@ func TestGatewayErrorMapsOversizedVideoInputToBadRequest(t *testing.T) { } } +func TestGatewayErrorMapsInvalidVideoParametersToBadRequest(t *testing.T) { + gin.SetMode(gin.TestMode) + router := gin.New() + router.GET("/", func(c *gin.Context) { + writeGatewayError(c, fmt.Errorf("%w: Console reference_images 最多 7 张", gateway.ErrVideoParameterInvalid)) + }) + recorder := httptest.NewRecorder() + router.ServeHTTP(recorder, httptest.NewRequest(http.MethodGet, "/", nil)) + if recorder.Code != http.StatusBadRequest || !strings.Contains(recorder.Body.String(), `"code":"invalid_request"`) || !strings.Contains(recorder.Body.String(), "最多 7 张") { + t.Fatalf("status=%d body=%s", recorder.Code, recorder.Body.String()) + } +} + func TestGatewayErrorMapsLedgerUnavailableToServiceUnavailable(t *testing.T) { gin.SetMode(gin.TestMode) router := gin.New() diff --git a/backend/internal/transport/http/settings/security_test.go b/backend/internal/transport/http/settings/security_test.go index 8a5d8772..0bf00396 100644 --- a/backend/internal/transport/http/settings/security_test.go +++ b/backend/internal/transport/http/settings/security_test.go @@ -47,9 +47,9 @@ func TestSettingsResponseIncludesBuildTokenAuth(t *testing.T) { func TestSettingsResponseIncludesRecommendedBuildBaseline(t *testing.T) { response := newSettingsResponse(settingsapp.Snapshot{RecommendedProviderBuild: settingsapp.ProviderBuildRecommendation{ - ClientVersion: "0.2.119", UserAgent: "grok-shell/0.2.119 (linux; x86_64)", + ClientVersion: "1.0.4", UserAgent: "grok-shell/1.0.4 (linux; x86_64)", }}) - if response.RecommendedProviderBuild.ClientVersion != "0.2.119" || response.RecommendedProviderBuild.UserAgent == "" { + if response.RecommendedProviderBuild.ClientVersion != "1.0.4" || response.RecommendedProviderBuild.UserAgent == "" { t.Fatalf("recommended build = %#v", response.RecommendedProviderBuild) } } diff --git a/config.example.yaml b/config.example.yaml index d4f1da5e..788ba128 100644 --- a/config.example.yaml +++ b/config.example.yaml @@ -114,6 +114,7 @@ audit: qualityGuard: enabled: false # 主程序会自动创建并复用不可导出的内部探测身份,无需配置 Client Key。 + # 使用已验证会输出推理 Token 的 Build 模型时,内置恢复探针还会校验 reasoning Token。 model: "grok-4.5" mode: hybrid # passive | active | hybrid activeInterval: 30m diff --git a/frontend/src/features/quality-guard/probe-profiles-panel.tsx b/frontend/src/features/quality-guard/probe-profiles-panel.tsx new file mode 100644 index 00000000..43aaf676 --- /dev/null +++ b/frontend/src/features/quality-guard/probe-profiles-panel.tsx @@ -0,0 +1,197 @@ +import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; +import { Pencil, Plus, Star, Trash2 } from "lucide-react"; +import { useState } from "react"; +import { useTranslation } from "react-i18next"; +import { toast } from "sonner"; + +import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle } from "@/components/ui/alert-dialog"; +import { Badge } from "@/components/ui/badge"; +import { Button } from "@/components/ui/button"; +import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog"; +import { Input } from "@/components/ui/input"; +import { Label } from "@/components/ui/label"; +import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"; +import { Spinner } from "@/components/ui/spinner"; +import { Switch } from "@/components/ui/switch"; +import { Textarea } from "@/components/ui/textarea"; +import { createProbeProfile, deleteProbeProfile, listProbeProfiles, updateProbeProfile, type ProbeProfile } from "@/features/quality-guard/quality-guard-api"; + +type Draft = { + name: string; + prompt: string; + expectedText: string; + matchMode: string; + requireThinking: boolean; +}; + +const emptyDraft = (): Draft => ({ name: "", prompt: "", expectedText: "", matchMode: "last_line", requireThinking: false }); + +export function ProbeProfilesPanel() { + const { t } = useTranslation(); + const queryClient = useQueryClient(); + const [editing, setEditing] = useState(undefined); + const [draft, setDraft] = useState(emptyDraft()); + const [deleting, setDeleting] = useState(null); + const query = useQuery({ queryKey: ["quality-guard-profiles"], queryFn: listProbeProfiles }); + const invalidate = () => { + void queryClient.invalidateQueries({ queryKey: ["quality-guard-profiles"] }); + void queryClient.invalidateQueries({ queryKey: ["quality-guard"] }); + }; + const saveMutation = useMutation({ + mutationFn: async () => { + const payload = { + name: draft.name.trim(), + prompt: draft.prompt.trim(), + expectedText: draft.expectedText.trim(), + matchMode: draft.matchMode, + requireThinking: draft.requireThinking, + }; + if (editing && !editing.built_in) { + return updateProbeProfile(editing.id, payload); + } + return createProbeProfile(payload); + }, + onSuccess: () => { + toast.success(t("qualityGuard.profileSaved")); + setEditing(undefined); + invalidate(); + }, + onError: (error) => toast.error(error instanceof Error ? error.message : t("errors.generic")), + }); + const activateMutation = useMutation({ + mutationFn: (profile: ProbeProfile) => updateProbeProfile(profile.id, { + name: profile.name, + prompt: profile.prompt, + expectedText: profile.expected_text ?? "", + matchMode: profile.match_mode, + requireThinking: profile.require_thinking, + active: true, + }), + onSuccess: () => { + toast.success(t("qualityGuard.profileSaved")); + invalidate(); + }, + onError: (error) => toast.error(error instanceof Error ? error.message : t("errors.generic")), + }); + const deleteMutation = useMutation({ + mutationFn: (profile: ProbeProfile) => deleteProbeProfile(profile.id), + onSuccess: () => { + toast.success(t("qualityGuard.profileDeleted")); + setDeleting(null); + invalidate(); + }, + onError: (error) => toast.error(error instanceof Error ? error.message : t("errors.generic")), + }); + + const items = query.data?.items ?? []; + const activeId = query.data?.activeProfileId; + const readonly = Boolean(editing?.built_in); + const matchLabel = (mode: string) => { + if (mode === "last_line") return t("qualityGuard.profileMatchLastLine"); + if (mode === "regex") return t("qualityGuard.profileMatchRegex"); + return t("qualityGuard.profileMatchContains"); + }; + + return ( +
+
+
+

{t("qualityGuard.profilesTab")}

+

{t("qualityGuard.profilesHelp")}

+
+ +
+
+ {items.map((profile) => { + const active = profile.id === activeId; + const marker = profile.expected_text + ? `${t("qualityGuard.profileExpected")} ${profile.expected_text} · ${matchLabel(profile.match_mode)}` + : t("qualityGuard.profileNoExpected"); + return ( +
+
+
+ {profile.name} + {t(profile.built_in ? "qualityGuard.profileBuiltin" : "qualityGuard.profileCustom")} + {active ? {t("qualityGuard.profileActive")} : null} +
+

{marker}

+
+
+ {!active ? : null} + + {!profile.built_in ? : null} +
+
+ ); + })} +
+ + { if (!open && !saveMutation.isPending) setEditing(undefined); }}> + + + {editing ? t(readonly ? "qualityGuard.profileView" : "qualityGuard.profileEdit") : t("qualityGuard.profileCreate")} + {t("qualityGuard.profilesHelp")} + +
{ event.preventDefault(); if (!readonly) saveMutation.mutate(); }}> +
+ + setDraft({ ...draft, name: event.target.value })} /> +
+
+ + +
+
+ + setDraft({ ...draft, expectedText: event.target.value })} /> +

{t("qualityGuard.profileExpectedHelp")}

+
+
+ +