a3216's picture
feat: 同步上游 320f5d4;扩展模型(多免费渠道/自定义映射/访问密钥/模型白名单)
e48a2d8
Raw History Blame Contribute Delete
6.71 kB
// tls.go 免费车道的出站传输:用 uTLS 复刻 Bun fetch 的 ClientHello。
//
// 为什么需要:OpenCode 的免费车道在 HTTP 指纹之外还看 TLS 指纹。Go crypto/tls
// 的 ClientHello 与官方客户端(Bun/OpenCode CLI)差异明显,实测同字节的 HTTP
// 请求在 Go 栈上也可能被判成非官方客户端并回 429 FreeUsageLimitError。这里
// 照抄参考实现 opencode2api 的 Bun ClientHello(JA4 t13d1713h1),只支持
// HTTP(S) 代理与直连。
package freemodel
import (
"bufio"
"context"
"crypto/tls"
"encoding/base64"
"fmt"
"io"
"net"
"net/http"
"net/url"
"time"
utls "github.com/refraction-networking/utls"
)
const handshakeTimeout = 10 * time.Second
// bunClientHello 复刻 Bun 1.4.3 fetch 的 ClientHello(参考实现抓包)。
func bunClientHello() *utls.ClientHelloSpec {
return &utls.ClientHelloSpec{
TLSVersMin: utls.VersionTLS12,
TLSVersMax: utls.VersionTLS13,
CipherSuites: []uint16{
utls.TLS_AES_128_GCM_SHA256,
utls.TLS_AES_256_GCM_SHA384,
utls.TLS_CHACHA20_POLY1305_SHA256,
utls.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
utls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
utls.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,
utls.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,
utls.TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256,
utls.TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256,
utls.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA,
utls.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA,
utls.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA,
utls.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA,
utls.TLS_RSA_WITH_AES_128_GCM_SHA256,
utls.TLS_RSA_WITH_AES_256_GCM_SHA384,
utls.TLS_RSA_WITH_AES_128_CBC_SHA,
utls.TLS_RSA_WITH_AES_256_CBC_SHA,
},
CompressionMethods: []uint8{0},
Extensions: []utls.TLSExtension{
&utls.SNIExtension{},
&utls.ExtendedMasterSecretExtension{},
&utls.RenegotiationInfoExtension{Renegotiation: utls.RenegotiateOnceAsClient},
&utls.SupportedCurvesExtension{Curves: []utls.CurveID{utls.X25519MLKEM768, utls.X25519, utls.CurveP256, utls.CurveP384}},
&utls.SupportedPointsExtension{SupportedPoints: []uint8{0}},
&utls.SessionTicketExtension{},
&utls.ALPNExtension{AlpnProtocols: []string{"http/1.1"}},
&utls.StatusRequestExtension{},
&utls.SignatureAlgorithmsExtension{SupportedSignatureAlgorithms: []utls.SignatureScheme{
utls.ECDSAWithP256AndSHA256,
utls.PSSWithSHA256,
utls.PKCS1WithSHA256,
utls.ECDSAWithP384AndSHA384,
utls.PSSWithSHA384,
utls.PKCS1WithSHA384,
utls.PSSWithSHA512,
utls.PKCS1WithSHA512,
utls.PKCS1WithSHA1,
}},
&utls.SCTExtension{},
&utls.KeyShareExtension{KeyShares: []utls.KeyShare{{Group: utls.X25519MLKEM768}, {Group: utls.X25519}}},
&utls.PSKKeyExchangeModesExtension{Modes: []uint8{utls.PskModeDHE}},
&utls.SupportedVersionsExtension{Versions: []uint16{utls.VersionTLS13, utls.VersionTLS12}},
},
}
}
// newFreeHTTPClient 构建免费车道专用客户端:HTTP/1.1、uTLS Bun 指纹、
// 自己处理 HTTP(S)_PROXY(因为同时用 DialTLSContext 时 http.Transport 的
// 内建代理隧道不会走这里)。
func newFreeHTTPClient() *http.Client {
tr := &http.Transport{
Proxy: nil,
DialTLSContext: dialBunTLS,
ForceAttemptHTTP2: false,
MaxIdleConns: 64,
IdleConnTimeout: 90 * time.Second,
ResponseHeaderTimeout: headerTimeout,
}
return &http.Client{Transport: tr}
}
func dialBunTLS(ctx context.Context, network, addr string) (net.Conn, error) {
host, _, err := net.SplitHostPort(addr)
if err != nil {
return nil, err
}
conn, err := dialMaybeProxy(ctx, addr)
if err != nil {
return nil, err
}
tlsConn := utls.UClient(conn, &utls.Config{ServerName: host}, utls.HelloCustom)
if err := tlsConn.ApplyPreset(bunClientHello()); err != nil {
_ = conn.Close()
return nil, err
}
handshakeCtx, cancel := context.WithTimeout(ctx, handshakeTimeout)
defer cancel()
if err := tlsConn.HandshakeContext(handshakeCtx); err != nil {
_ = conn.Close()
return nil, err
}
return tlsConn, nil
}
func dialMaybeProxy(ctx context.Context, addr string) (net.Conn, error) {
proxyURL := proxyFor(addr)
if proxyURL == nil {
d := &net.Dialer{Timeout: handshakeTimeout, KeepAlive: 30 * time.Second}
return d.DialContext(ctx, "tcp", addr)
}
switch proxyURL.Scheme {
case "http", "https":
return dialHTTPProxy(ctx, proxyURL, addr)
default:
return nil, fmt.Errorf("unsupported proxy scheme %q for free model lane (http/https only)", proxyURL.Scheme)
}
}
func proxyFor(addr string) *url.URL {
req := &http.Request{URL: &url.URL{Scheme: "https", Host: addr}}
u, err := http.ProxyFromEnvironment(req)
if err != nil {
return nil
}
return u
}
func dialHTTPProxy(ctx context.Context, proxyURL *url.URL, addr string) (net.Conn, error) {
d := &net.Dialer{Timeout: handshakeTimeout, KeepAlive: 30 * time.Second}
conn, err := d.DialContext(ctx, "tcp", proxyAddr(proxyURL))
if err != nil {
return nil, err
}
stop := context.AfterFunc(ctx, func() { _ = conn.Close() })
_ = conn.SetDeadline(time.Now().Add(handshakeTimeout))
if proxyURL.Scheme == "https" {
tlsConn := tls.Client(conn, &tls.Config{ServerName: proxyURL.Hostname()})
if err = tlsConn.HandshakeContext(ctx); err == nil {
conn = tlsConn
}
}
if err == nil {
conn, err = httpConnect(conn, proxyURL.User, addr)
}
if !stop() && err == nil {
err = ctx.Err()
}
if err == nil {
err = conn.SetDeadline(time.Time{})
}
if err != nil {
_ = conn.Close()
return nil, err
}
return conn, nil
}
func proxyAddr(proxy *url.URL) string {
port := proxy.Port()
if port == "" {
switch proxy.Scheme {
case "https":
port = "443"
default:
port = "80"
}
}
return net.JoinHostPort(proxy.Hostname(), port)
}
func httpConnect(conn net.Conn, user *url.Userinfo, addr string) (net.Conn, error) {
request := "CONNECT " + addr + " HTTP/1.1\r\nHost: " + addr + "\r\n"
if user != nil {
password, _ := user.Password()
request += "Proxy-Authorization: Basic " +
base64.StdEncoding.EncodeToString([]byte(user.Username()+":"+password)) + "\r\n"
}
if _, err := io.WriteString(conn, request+"\r\n"); err != nil {
return conn, err
}
reader := bufio.NewReader(conn)
resp, err := http.ReadResponse(reader, &http.Request{Method: http.MethodConnect})
if err != nil {
return conn, err
}
if resp.StatusCode/100 != 2 {
return conn, fmt.Errorf("proxy refused CONNECT: %s", resp.Status)
}
if reader.Buffered() > 0 {
return &bufferedConn{Conn: conn, reader: reader}, nil
}
return conn, nil
}
type bufferedConn struct {
net.Conn
reader *bufio.Reader
}
func (c *bufferedConn) Read(p []byte) (int, error) { return c.reader.Read(p) }