Files
tbphp 4f9eba5802 feat(proxy): 完成数据面代理与渠道约束 (#459)
* feat(proxy): 实现第一阶段数据面代理

* feat(proxy): 收敛渠道与代理协议支持

* fix(proxy): 修复环境检测与迁移验证

* fix(proxy): 回收旧代理运行时并校验地址

* fix(proxy): 补齐创建链路与前端校验

* fix(proxy): 收口订阅代理与迁移兼容

* fix(proxy): 修复环境代理与运行时回收

* fix(proxy): 为系统外部请求应用全局代理

* docs(config): 精简环境配置说明

* feat(proxy): 重构代理设置的前端交互与样式

设置页与分组设置页:
- 代理设置接入页面统一的草稿态与保存栏,不再独立即时提交
- 计入页面 dirty/valid,参与未保存离开拦截与并发冲突推迟
- 新增 ProxyOverrideRow,用分段控件替代原独立编辑弹层

账号卡片与密钥行:
- ProxyConfigEditor 新增 card 外观:标题在白底面板外,与相邻小节同级
- 修掉按视口宽度判断断点的问题,窄容器内不再挤压错乱
- 编辑态下拉固定宽度,不随所选模式伸缩;整体收进两行
- 新增 ProxyScopeIndicator,凭据配置了独立代理时给出标识与悬停提示

密钥行交互:
- 操作列收成「更多操作」菜单与展开图标,与账号卡片同构
- 折叠区分为权重、出站代理、运行诊断三个带标题小节,设置与诊断不再混放
- 权重编辑从弹层迁入折叠区,权重列的值可点击直达
- 释放的列宽还给凭据、权重与最近调用列

文案精简为继承、直连、自定义,并清理两处无引用的死键

* refactor(proxy): 统一代理设置的覆盖交互并消除样式重复

设置页与分组设置页:
- 代理行改用 RuntimeOverrideRow,与超时等设置项共用同一组件
- inherit 映射为“未覆盖”,direct/custom 映射为“显式覆盖”,因此补齐了
  覆盖/恢复默认按钮、覆盖状态徽章、当前有效值与待恢复默认态
- 分段控件只保留直连与自定义,继承由外层覆盖开关表达
- 删除自造的 ProxyOverrideRow,新增只含编辑控件的 ProxyOverrideControl

已保存的自定义地址:
- 输入框不做回填,统一由 placeholder 展示已存地址
- 同模式下留空或与已存地址逐字相同均视为未改动,顺带挡住掩码被当作
  新密码存回;无改动时保存按钮禁用
- 重新开启覆盖时回到基线已存的覆盖模式,使恢复默认可原路撤销

代码质量:
- 面板外壳(标题 + 白底面板 + 标签/值/编辑图标/操作)抽为全局
  .setting-panel,代理、权重、诊断三处共用,不再各写一份
- 删除 ProxyConfigEditor 已无调用方的 row 外观及随之失效的 props、
  徽章分支与始终隐藏的文案
- 占位地址推导与覆盖开关规则收敛为 proxy.ts 中的共享函数
- 移除代理输入提示文案及其失去引用的 i18n 键

密钥行折叠区诊断值字号对齐上方面板。重构以构建产物 CSS 逐条比对验证,
差异均为已论证的等价改写。

* fix(proxy): 修复代理传输与校验边界
2026-08-24 11:11:22 +08:00

240 lines
6.8 KiB
Go

package httpclient
import (
"crypto/sha256"
"errors"
"fmt"
"net"
"net/http"
"net/url"
"strconv"
"strings"
"sync"
"time"
"github.com/sirupsen/logrus"
"gpt-load/internal/outboundproxy"
)
// Config defines the parameters for creating an HTTP client.
// This struct is used to generate a unique fingerprint for client reuse.
type Config struct {
ConnectTimeout time.Duration
RequestTimeout time.Duration
IdleConnTimeout time.Duration
MaxIdleConns int
MaxIdleConnsPerHost int
ResponseHeaderTimeout time.Duration
DisableCompression bool
WriteBufferSize int
ReadBufferSize int
ForceAttemptHTTP2 bool
TLSHandshakeTimeout time.Duration
ExpectContinueTimeout time.Duration
ProxyURL string
DisableProxy bool
DisableRedirects bool
}
// OutboundProxyProvider returns the current frozen system-level proxy policy.
type OutboundProxyProvider func() outboundproxy.Effective
// HTTPClientManager manages the lifecycle of HTTP clients.
// It creates and caches clients based on their configuration fingerprint,
// ensuring that clients with the same configuration are reused.
type HTTPClientManager struct {
clients map[string]*http.Client
lock sync.RWMutex
}
// NewHTTPClientManager creates a new client manager.
func NewHTTPClientManager() *HTTPClientManager {
return &HTTPClientManager{
clients: make(map[string]*http.Client),
}
}
// GetClient returns an HTTP client that matches the given configuration.
// If a matching client already exists in the cache, it is returned.
// Otherwise, a new client is created, cached, and returned.
func (m *HTTPClientManager) GetClient(config *Config) *http.Client {
fingerprint := config.getFingerprint()
// Fast path with read lock
m.lock.RLock()
client, exists := m.clients[fingerprint]
m.lock.RUnlock()
if exists {
return client
}
// Slow path with write lock
m.lock.Lock()
defer m.lock.Unlock()
// Double-check in case another goroutine created the client while we were waiting for the lock.
if client, exists = m.clients[fingerprint]; exists {
return client
}
newClient := newHTTPClient(config)
m.clients[fingerprint] = newClient
return newClient
}
func newHTTPClient(config *Config) *http.Client {
// Create a new transport and client with the specified configuration.
transport := &http.Transport{
DialContext: (&net.Dialer{
Timeout: config.ConnectTimeout,
KeepAlive: 30 * time.Second,
}).DialContext,
ForceAttemptHTTP2: config.ForceAttemptHTTP2,
MaxIdleConns: config.MaxIdleConns,
MaxIdleConnsPerHost: config.MaxIdleConnsPerHost,
IdleConnTimeout: config.IdleConnTimeout,
TLSHandshakeTimeout: config.TLSHandshakeTimeout,
ExpectContinueTimeout: config.ExpectContinueTimeout,
ResponseHeaderTimeout: config.ResponseHeaderTimeout,
DisableCompression: config.DisableCompression,
WriteBufferSize: config.WriteBufferSize,
ReadBufferSize: config.ReadBufferSize,
}
// Set http proxy.
if config.DisableProxy {
transport.Proxy = nil
} else if config.ProxyURL != "" {
proxyURL, err := url.Parse(config.ProxyURL)
if err != nil {
logrus.Warnf("Invalid proxy URL '%s' provided, falling back to environment settings: %v", config.ProxyURL, err)
transport.Proxy = http.ProxyFromEnvironment
} else {
transport.Proxy = http.ProxyURL(proxyURL)
}
} else {
transport.Proxy = http.ProxyFromEnvironment
}
checkRedirect := rejectCrossOriginRedirect
if config.DisableRedirects {
checkRedirect = func(*http.Request, []*http.Request) error {
return http.ErrUseLastResponse
}
}
return &http.Client{
Transport: transport,
Timeout: config.RequestTimeout,
CheckRedirect: checkRedirect,
}
}
// NewClientForOutboundProxy creates one operation-scoped client from a frozen
// system proxy policy. Dynamic proxy credentials are not retained in the
// shared client cache after settings change.
func (m *HTTPClientManager) NewClientForOutboundProxy(
config *Config,
effective outboundproxy.Effective,
) (*http.Client, error) {
normalized, err := outboundproxy.NormalizeEffective(effective)
if err != nil {
return nil, fmt.Errorf("invalid outbound proxy policy")
}
resolved := Config{}
if config != nil {
resolved = *config
}
resolved.ProxyURL = ""
resolved.DisableProxy = false
switch normalized.Config.Mode {
case outboundproxy.ModeDirect:
resolved.DisableProxy = true
case outboundproxy.ModeEnvironment:
case outboundproxy.ModeCustom:
resolved.ProxyURL = normalized.Config.URL
default:
return nil, fmt.Errorf("invalid outbound proxy policy")
}
return newHTTPClient(&resolved), nil
}
var errCrossOriginRedirect = errors.New("cross-origin redirect is not allowed")
// rejectCrossOriginRedirect follows redirects only while they remain on the
// original effective origin. Rejecting the redirect also prevents 307/308 from
// replaying request bodies or arbitrary credential headers to another origin.
func rejectCrossOriginRedirect(req *http.Request, via []*http.Request) error {
if len(via) >= 10 {
return fmt.Errorf("stopped after 10 redirects")
}
if len(via) == 0 {
return nil
}
if !sameOrigin(req, via[0]) {
return errCrossOriginRedirect
}
return nil
}
func sameOrigin(left, right *http.Request) bool {
leftScheme, leftHost, leftPort, leftOK := normalizedOrigin(left)
rightScheme, rightHost, rightPort, rightOK := normalizedOrigin(right)
return leftOK && rightOK &&
leftScheme == rightScheme &&
leftHost == rightHost &&
leftPort == rightPort
}
func normalizedOrigin(request *http.Request) (scheme, host, port string, ok bool) {
if request == nil || request.URL == nil {
return "", "", "", false
}
scheme = strings.ToLower(request.URL.Scheme)
switch scheme {
case "http":
port = "80"
case "https":
port = "443"
default:
return "", "", "", false
}
host = strings.ToLower(request.URL.Hostname())
if host == "" {
return "", "", "", false
}
if explicitPort := request.URL.Port(); explicitPort != "" {
parsedPort, err := strconv.Atoi(explicitPort)
if err != nil || parsedPort < 1 || parsedPort > 65535 {
return "", "", "", false
}
port = strconv.Itoa(parsedPort)
}
return scheme, host, port, true
}
// getFingerprint generates a unique string representation of the client configuration.
func (c *Config) getFingerprint() string {
proxyFingerprint := sha256.Sum256([]byte(c.ProxyURL))
return fmt.Sprintf(
"ct:%.0fs|rt:%.0fs|it:%.0fs|mic:%d|mich:%d|rht:%.0fs|dc:%t|wbs:%d|rbs:%d|fh2:%t|tlst:%.0fs|ect:%.0fs|proxy:%x|dp:%t|dr:%t",
c.ConnectTimeout.Seconds(),
c.RequestTimeout.Seconds(),
c.IdleConnTimeout.Seconds(),
c.MaxIdleConns,
c.MaxIdleConnsPerHost,
c.ResponseHeaderTimeout.Seconds(),
c.DisableCompression,
c.WriteBufferSize,
c.ReadBufferSize,
c.ForceAttemptHTTP2,
c.TLSHandshakeTimeout.Seconds(),
c.ExpectContinueTimeout.Seconds(),
proxyFingerprint,
c.DisableProxy,
c.DisableRedirects,
)
}