跳到主要内容

Claude Cage · 面向 Claude 的隔离开发环境,支持桌面工作台、多账号、远程部署与移动端连接。上游 Lee-xeo/Claude-Cage 完整源码镜像,非灵栈原创;主许可 MIT,第三方组件遵循各自许可。来源:https://github.com/Lee-xeo/Claude-Cage 。手动同步,不附带 Release 安装包。

浏览文件

fetch.go

201 行 · 7.1 KB历史下载
1package managedproxy
2
3import (
4 "bytes"
5 "context"
6 "crypto/tls"
7 "errors"
8 "io"
9 "net"
10 "net/http"
11 "net/netip"
12 "net/url"
13 "strconv"
14 "strings"
15 "time"
16
17 "github.com/miekg/dns"
18 "github.com/sylvinus/agent-vm/internal/hostproxy"
19)
20
21// BootstrapClient serves only explicitly host-routed subscription requests.
22func BootstrapClient() *http.Client {
23 return &http.Client{Transport: subscriptionHostTransport{hostproxy.NewTransport(), BootstrapDNSURLs()}, Timeout: 30 * time.Second, CheckRedirect: func(r *http.Request, via []*http.Request) error {
24 if len(via) >= 3 || r.URL.Scheme != "https" || r.URL.User != nil {
25 return errors.New("订阅重定向被拒绝")
26 }
27 return nil
28 }}
29}
30
31type subscriptionHostTransport struct {
32 host *http.Transport
33 resolvers []string
34}
35
36func (t subscriptionHostTransport) RoundTrip(req *http.Request) (*http.Response, error) {
37 // Resolve routing for the original hostname (including on redirects).
38 // Pin both DoH and the subscription transfer to the selected route.
39 routing := req.Clone(req.Context())
40 routing.URL.Path, routing.URL.RawPath, routing.URL.RawQuery = "", "", ""
41 route, err := t.host.Proxy(routing)
42 if err != nil {
43 return nil, err
44 }
45 tr := t.host.Clone()
46 tr.Proxy = http.ProxyURL(route)
47 tr.DisableKeepAlives = true
48 host := req.URL.Hostname()
49 ip, err := netip.ParseAddr(host)
50 if err != nil {
51 dnsClient := &http.Client{Transport: tr, CheckRedirect: func(*http.Request, []*http.Request) error { return errors.New("DNS redirect refused") }}
52 ip, err = resolveInfrastructureWith(req.Context(), host, dnsClient, t.resolvers)
53 if err != nil {
54 return nil, err
55 }
56 }
57 if !publicIP(ip) {
58 return nil, errors.New("订阅服务器必须使用公网地址")
59 }
60
61 // CONNECT (or SOCKS) must address the validated IP, while HTTP Host and
62 // TLS SNI/certificate checks still use the subscription's original name.
63 // DoH requests may still be finishing, so configure a separate transport.
64 target := tr.Clone()
65 if target.TLSClientConfig == nil {
66 target.TLSClientConfig = &tls.Config{}
67 }
68 if route != nil && route.Scheme == "https" {
69 // The outer TLS handshake authenticates the proxy, independently of
70 // the inner TLS session established through its CONNECT tunnel.
71 outer := target.TLSClientConfig.Clone()
72 outer.ServerName, outer.NextProtos = route.Hostname(), []string{"http/1.1"}
73 target.DialTLSContext = (&tls.Dialer{Config: outer, NetDialer: &net.Dialer{Timeout: 10 * time.Second}}).DialContext
74 }
75 target.TLSClientConfig.ServerName = host
76 pinned := req.Clone(req.Context())
77 pinned.Host = req.URL.Host
78 pinned.URL.Host = ip.String()
79 if port := req.URL.Port(); port != "" {
80 pinned.URL.Host = net.JoinHostPort(ip.String(), port)
81 }
82 return target.RoundTrip(pinned)
83}
84
85func usageSummary(raw string) string {
86 parts := []string{}
87 for _, field := range strings.Split(raw, ";") {
88 kv := strings.SplitN(strings.TrimSpace(field), "=", 2)
89 if len(kv) != 2 {
90 continue
91 }
92 if kv[0] != "upload" && kv[0] != "download" && kv[0] != "total" && kv[0] != "expire" {
93 continue
94 }
95 if _, err := strconv.ParseUint(kv[1], 10, 64); err == nil {
96 parts = append(parts, kv[0]+"="+kv[1])
97 }
98 }
99 return strings.Join(parts, "; ")
100}
101func publicIP(ip netip.Addr) bool {
102 return ip.Is4() && ip.IsGlobalUnicast() && !ip.IsPrivate() && !ip.IsLoopback() && !ip.IsLinkLocalUnicast() && !netip.MustParsePrefix("100.64.0.0/10").Contains(ip) && !netip.MustParsePrefix("198.18.0.0/15").Contains(ip)
103}
104
105// BootstrapDNSURLs is shared by host downloads and the core's node resolver.
106// Numeric HTTPS endpoints need neither the host resolver nor a working proxy.
107func BootstrapDNSURLs() []string {
108 return []string{"https://1.1.1.1/dns-query", "https://223.5.5.5/dns-query"}
109}
110
111func resolveInfrastructureWith(ctx context.Context, host string, client *http.Client, servers []string) (netip.Addr, error) {
112 ctx, cancel := context.WithTimeout(ctx, 8*time.Second)
113 defer cancel()
114 q := new(dns.Msg)
115 q.SetQuestion(dns.Fqdn(host), dns.TypeA)
116 wire, err := q.Pack()
117 if err != nil {
118 return netip.Addr{}, errors.New("代理基础设施域名无效")
119 }
120 type result struct {
121 ip netip.Addr
122 err error
123 }
124 results := make(chan result, len(servers))
125 // A blocked resolver must not delay a reachable one. Cancel the remaining
126 // HTTPS requests once a usable public answer is available.
127 for _, server := range servers {
128 go func() {
129 ip, err := queryInfrastructureDNS(ctx, client, server, q, wire)
130 results <- result{ip, err}
131 }()
132 }
133 for range servers {
134 select {
135 case <-ctx.Done():
136 return netip.Addr{}, ctx.Err()
137 case result := <-results:
138 if result.err == nil {
139 return result.ip, nil
140 }
141 }
142 }
143 return netip.Addr{}, errors.New("代理基础设施 DNS 均不可用或未返回公网 IPv4;请检查主机网络后重试,未使用系统 DNS 回退")
144}
145
146func queryInfrastructureDNS(ctx context.Context, client *http.Client, server string, q *dns.Msg, wire []byte) (netip.Addr, error) {
147 req, err := http.NewRequestWithContext(ctx, "POST", server, bytes.NewReader(wire))
148 if err != nil {
149 return netip.Addr{}, err
150 }
151 req.Header.Set("Content-Type", "application/dns-message")
152 req.Header.Set("Accept", "application/dns-message")
153 resp, err := client.Do(req)
154 if err != nil {
155 return netip.Addr{}, errors.New("代理基础设施域名解析失败")
156 }
157 defer resp.Body.Close()
158 wire, err = io.ReadAll(io.LimitReader(resp.Body, 65536))
159 var answer dns.Msg
160 if err != nil || resp.StatusCode != 200 || answer.Unpack(wire) != nil || answer.Id != q.Id ||
161 !answer.Response || answer.Truncated || answer.Rcode != dns.RcodeSuccess || len(answer.Question) != 1 ||
162 !strings.EqualFold(answer.Question[0].Name, q.Question[0].Name) || answer.Question[0].Qtype != dns.TypeA || answer.Question[0].Qclass != dns.ClassINET {
163 return netip.Addr{}, errors.New("代理基础设施 DNS 响应无效")
164 }
165 for _, rr := range answer.Answer {
166 if a, ok := rr.(*dns.A); ok {
167 if ip, ok := netip.AddrFromSlice(a.A); ok && publicIP(ip.Unmap()) {
168 return ip.Unmap(), nil
169 }
170 }
171 }
172 return netip.Addr{}, errors.New("代理基础设施域名没有可用公网 IPv4")
173}
174func Fetch(ctx context.Context, client *http.Client, rawURL string) ([]byte, string, error) {
175 u, err := url.Parse(rawURL)
176 if err != nil || u.Scheme != "https" || u.Hostname() == "" || u.User != nil || u.Fragment != "" {
177 return nil, "", errors.New("订阅需要完整的 HTTPS 网址,不支持地址内用户名和密码")
178 }
179 req, err := http.NewRequestWithContext(ctx, "GET", u.String(), nil)
180 if err != nil {
181 return nil, "", errors.New("订阅网址无效")
182 }
183 req.Header.Set("User-Agent", "clash.meta/Cage")
184 res, err := client.Do(req)
185 if err != nil {
186 return nil, "", errors.New("订阅下载失败,请检查下载路径和服务地址")
187 }
188 defer res.Body.Close()
189 if res.StatusCode != 200 {
190 return nil, "", errors.New("订阅服务器返回 HTTP " + strconv.Itoa(res.StatusCode))
191 }
192 b, err := io.ReadAll(io.LimitReader(res.Body, MaxImport+1))
193 if err != nil || len(b) > MaxImport {
194 return nil, "", errors.New("订阅下载中断或超过 8 MiB")
195 }
196 usage := "" // Keep only known numeric metadata; never echo arbitrary headers.
197 if raw := res.Header.Get("Subscription-Userinfo"); len(raw) < 300 {
198 usage = usageSummary(raw)
199 }
200 return b, usage, nil
201}