跳到主要内容

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

提交记录

修复双栈代理节点的 IPv4 出口检测

通过 IPv4 专用端点获取出口并有界解析纯文本,保持所选代理、公共 IPv4 校验和客机诊断 JSON 契约。补充真实入口经本地认证 HTTP/SOCKS 代理的回归,以及可选公共端点验证。

作者
Lee-xeo
时间
2026/11/09 23:23
提交
6683f3e
上一个
e6b8fe1
这个版本的全部文件
修改docs/guide/network.md+2 −0看文件
@@ -50,6 +50,8 @@ Hysteria2 节点可使用 `mport` 指定端口跳跃范围、`pinSHA256` 指定
5050
5151代理核心就绪和工作环境获准联网是两个步骤。环境启动后先保持业务外网关闭,执行出口、DNS、系统与浏览器配置、共享目录、宿主管理接口和网络阻断等关键检查。任一关键项失败或证据缺失都会继续关闭外网。
5252
53新增:出口检测通过所选代理访问 `https://ipv4.icanhazip.com/`,读取公网 IPv4 地址。双栈节点使用其 IPv4 出口完成检查;宿主、客机终端和浏览器共用这一检测服务。检测服务不可达或返回无效地址时,业务外网保持关闭,可稍后重试或更换节点。
54新增:
5355点击底部网络状态查看失败项,修复后重新检查。核心运行但环境未启动时会显示“待启动环境”。关键检查通过、联网授权有效时才显示“已联网”。
5456
5557离线时仍可使用终端、共享文件及环境内的本地服务。浏览器地址栏中的 `localhost` 指当前 Cage 客机;开发服务应在 Cage 终端里启动。
修改internal/cage/gate_probe.go+6 −6看文件
@@ -33,7 +33,9 @@ func probeExitIP(ctx context.Context, e *Egress) (string, error) {
3333 transport := &http.Transport{Proxy: nil, DialContext: e.DialContext, DisableKeepAlives: true}
3434 defer transport.CloseIdleConnections()
3535 client := &http.Client{Transport: transport, Timeout: 12 * time.Second, CheckRedirect: func(*http.Request, []*http.Request) error { return errors.New("probe redirect refused") }}
36删除: req, _ := http.NewRequestWithContext(ctx, "GET", "https://api.ipify.org?format=json", nil)
36新增: // The proxy resolves this name remotely. An IPv4-only service measures the
37新增: // same address family as the guest policy even when the proxy is dual-stack.
38新增: req, _ := http.NewRequestWithContext(ctx, "GET", "https://ipv4.icanhazip.com/", nil)
3739 req.Header.Set("User-Agent", "Cage-network-check/1")
3840 resp, err := client.Do(req)
3941 if err != nil {
@@ -41,16 +43,14 @@ func probeExitIP(ctx context.Context, e *Egress) (string, error) {
4143 return "", usererror.Wrap("通过所选代理查询出口 IP", err, "请检查网络与代理中的节点是否可用,再重新检测;未能确认出口时,外网保持关闭。")
4244 }
4345 defer resp.Body.Close()
44删除: var data struct {
45删除: IP string `json:"ip"`
46删除: }
4746 if resp.StatusCode != 200 {
4847 return "", fmt.Errorf("查询出口 IP 失败:检测服务返回 HTTP %d。请检查所选代理,稍后重新检测;外网保持关闭。", resp.StatusCode)
4948 }
50删除: if json.NewDecoder(io.LimitReader(resp.Body, 4096)).Decode(&data) != nil {
49新增: body, err := io.ReadAll(io.LimitReader(resp.Body, 4097))
50新增: if err != nil || len(body) > 4096 {
5151 return "", errors.New("查询出口 IP 失败:检测服务没有返回有效的 IP 记录。请更换可用节点或稍后重新检测;外网保持关闭。")
5252 }
53删除: ip, err := netip.ParseAddr(data.IP)
53新增: ip, err := netip.ParseAddr(strings.TrimSpace(string(body)))
5454 if err != nil || !ip.Is4() || !ip.IsGlobalUnicast() || ip.IsPrivate() {
5555 return "", errors.New("出口检测结果不是有效公网 IPv4 地址")
5656 }
新增internal/cage/gate_probe_test.go+306 −0看文件
@@ -0,0 +1,306 @@
1新增:package cage
2新增:
3新增:import (
4新增: "bufio"
5新增: "context"
6新增: "crypto/ecdsa"
7新增: "crypto/elliptic"
8新增: "crypto/rand"
9新增: "crypto/tls"
10新增: "crypto/x509"
11新增: "encoding/binary"
12新增: "encoding/json"
13新增: "encoding/pem"
14新增: "fmt"
15新增: "io"
16新增: "math/big"
17新增: "net"
18新增: "net/http"
19新增: "net/http/httptest"
20新增: "net/netip"
21新增: "os"
22新增: "os/exec"
23新增: "path/filepath"
24新增: "strings"
25新增: "sync/atomic"
26新增: "testing"
27新增: "time"
28新增:)
29新增:
30新增:// The child uses a private test CA, so the real ProbeExitIP entry point verifies
31新增:// TLS without changing production trust or replacing the HTTP transport.
32新增:func TestExitProbeChild(t *testing.T) {
33新增: proxy := os.Getenv("CAGE_EXIT_PROBE_TEST_PROXY")
34新增: if proxy == "" {
35新增: t.Skip("subprocess fixture")
36新增: }
37新增: certificate, err := os.ReadFile(os.Getenv("CAGE_EXIT_PROBE_TEST_CA"))
38新增: if err != nil {
39新增: t.Fatal(err)
40新增: }
41新增: roots := x509.NewCertPool()
42新增: if !roots.AppendCertsFromPEM(certificate) {
43新增: t.Fatal("invalid test CA")
44新增: }
45新增: x509.SetFallbackRoots(roots)
46新增: cfg := DefaultConfig()
47新增: cfg.ProxyURL = proxy
48新增: ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
49新增: defer cancel()
50新增: want := os.Getenv("CAGE_EXIT_PROBE_TEST_IP")
51新增: ip, err := ProbeExitIP(ctx, cfg)
52新增: if want != "" {
53新增: if err != nil || ip != want {
54新增: t.Fatalf("host probe = %q, %v; want %q", ip, err, want)
55新增: }
56新增: } else if err == nil || ip != "" || strings.Contains(err.Error(), "private-value") || strings.Contains(err.Error(), "test-password") {
57新增: t.Fatalf("failed host probe returned an address or leaked a response: %q, %v", ip, err)
58新增: }
59新增: gate, err := NewEgressGate(cfg)
60新增: if err != nil {
61新增: t.Fatal(err)
62新增: }
63新增: defer gate.Close("test complete")
64新增: if err := gate.BeginCheck(); err != nil {
65新增: t.Fatal(err)
66新增: }
67新增: connection, err := gate.DialContext(ctx, "tcp", DiagnosticAddress)
68新增: if err != nil {
69新增: t.Fatal(err)
70新增: }
71新增: defer connection.Close()
72新增: _ = connection.SetDeadline(time.Now().Add(5 * time.Second))
73新增: _, err = io.WriteString(connection, "GET /egress HTTP/1.1\r\nHost: 198.18.0.254\r\nCookie: private-value\r\nAuthorization: private-value\r\n\r\n")
74新增: if err != nil {
75新增: t.Fatal(err)
76新增: }
77新增: response, err := http.ReadResponse(bufio.NewReader(connection), nil)
78新增: if err != nil {
79新增: t.Fatal(err)
80新增: }
81新增: defer response.Body.Close()
82新增: var result struct{ IP, Error string }
83新增: if err := json.NewDecoder(response.Body).Decode(&result); err != nil {
84新增: t.Fatal(err)
85新增: }
86新增: if want != "" {
87新增: if response.StatusCode != 200 || result.IP != want {
88新增: t.Fatalf("guest diagnostic lost IPv4 JSON contract: %d %+v", response.StatusCode, result)
89新增: }
90新增: } else if response.StatusCode != 503 || result.IP != "" || result.Error != "proxy_unavailable" {
91新增: t.Fatalf("failed guest diagnostic did not retain its fixed error contract: %d %+v", response.StatusCode, result)
92新增: }
93新增:}
94新增:
95新增:func TestExitProbeUsesIPv4ServiceThroughProxy(t *testing.T) {
96新增: key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
97新增: if err != nil {
98新增: t.Fatal(err)
99新增: }
100新增: template := &x509.Certificate{SerialNumber: big.NewInt(1), DNSNames: []string{"ipv4.icanhazip.com", "api.ipify.org"}, NotBefore: time.Now().Add(-time.Hour), NotAfter: time.Now().Add(time.Hour), IsCA: true, BasicConstraintsValid: true, KeyUsage: x509.KeyUsageCertSign | x509.KeyUsageDigitalSignature, ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth}}
101新增: certificate, err := x509.CreateCertificate(rand.Reader, template, template, &key.PublicKey, key)
102新增: if err != nil {
103新增: t.Fatal(err)
104新增: }
105新增: caFile := filepath.Join(t.TempDir(), "ca.pem")
106新增: if err := os.WriteFile(caFile, pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: certificate}), 0600); err != nil {
107新增: t.Fatal(err)
108新增: }
109新增: for _, scheme := range []string{"http", "socks5"} {
110新增: for _, tc := range []struct {
111新增: name, body, want string
112新增: status int
113新增: }{
114新增: {"public-ipv4", "8.8.8.8\n", "8.8.8.8", 200},
115新增: {"whitespace", " \r\n1.1.1.1\r\n", "1.1.1.1", 200},
116新增: {"ipv6", "2606:4700:4700::1111\n", "", 200},
117新增: {"mapped-ipv4", "::ffff:8.8.8.8", "", 200},
118新增: {"private-ipv4", "192.168.1.1", "", 200},
119新增: {"loopback", "127.0.0.1", "", 200},
120新增: {"link-local", "169.254.1.1", "", 200},
121新增: {"multicast", "224.0.0.1", "", 200},
122新增: {"empty", "", "", 200},
123新增: {"json-response", `{"ip":"8.8.8.8","secret":"private-value"}`, "", 200},
124新增: {"multiple-addresses", "8.8.8.8\n1.1.1.1", "", 200},
125新增: {"oversized", "8.8.8.8" + strings.Repeat(" ", 4096), "", 200},
126新增: {"short-read", "8.8.8.8", "", 200},
127新增: {"unavailable", "private-value", "", 503},
128新增: {"redirect", "private-value", "", 302},
129新增: } {
130新增: t.Run(scheme+"/"+tc.name, func(t *testing.T) {
131新增: var requests atomic.Int32
132新增: upstream := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, request *http.Request) {
133新增: requests.Add(1)
134新增: if request.Host == "api.ipify.org" {
135新增: _, _ = io.WriteString(w, `{"ip":"2606:4700:4700::1111"}`)
136新增: return
137新增: }
138新增: if request.Host != "ipv4.icanhazip.com" || request.URL.RequestURI() != "/" || request.Method != "GET" || request.Header.Get("User-Agent") != "Cage-network-check/1" || request.Header.Get("Cookie") != "" || request.Header.Get("Authorization") != "" || request.Header.Get("Proxy-Authorization") != "" {
139新增: t.Error("probe request changed destination or forwarded guest/proxy data")
140新增: }
141新增: w.Header().Set("Content-Type", "text/plain")
142新增: if tc.name == "redirect" {
143新增: w.Header().Set("Location", "https://private-value.invalid/")
144新增: }
145新增: if tc.name == "short-read" {
146新增: w.Header().Set("Content-Length", "50")
147新增: }
148新增: w.WriteHeader(tc.status)
149新增: _, _ = io.WriteString(w, tc.body)
150新增: }))
151新增: upstream.TLS = &tls.Config{Certificates: []tls.Certificate{{Certificate: [][]byte{certificate}, PrivateKey: key}}}
152新增: upstream.StartTLS()
153新增: defer upstream.Close()
154新增: proxy, connects := exitProbeProxy(t, scheme, upstream.Listener.Addr().String())
155新增: command := exec.Command(os.Args[0], "-test.run=^TestExitProbeChild$", "-test.timeout=15s")
156新增: command.Env = append(os.Environ(), "GODEBUG=x509usefallbackroots=1", "CAGE_EXIT_PROBE_TEST_PROXY="+proxy, "CAGE_EXIT_PROBE_TEST_CA="+caFile, "CAGE_EXIT_PROBE_TEST_IP="+tc.want)
157新增: if output, err := command.CombinedOutput(); err != nil {
158新增: t.Fatalf("real probe entry failed: %v\n%s", err, output)
159新增: }
160新增: if connects.Load() != 2 || requests.Load() != 2 {
161新增: t.Fatalf("host and guest probes must each use the configured proxy once: connects=%d requests=%d", connects.Load(), requests.Load())
162新增: }
163新增: })
164新增: }
165新增: }
166新增:}
167新增:
168新增:func TestExitProbeProxyRejectionDoesNotFallbackOrLeakResponse(t *testing.T) {
169新增: var requests atomic.Int32
170新增: proxy := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, request *http.Request) {
171新增: requests.Add(1)
172新增: w.WriteHeader(http.StatusBadGateway)
173新增: _, _ = io.WriteString(w, "private-proxy-response")
174新增: }))
175新增: defer proxy.Close()
176新增: cfg := DefaultConfig()
177新增: cfg.ProxyURL = proxy.URL
178新增: ip, err := ProbeExitIP(context.Background(), cfg)
179新增: if err == nil || ip != "" || requests.Load() != 1 || strings.Contains(err.Error(), "private-proxy-response") {
180新增: t.Fatalf("proxy rejection escaped the configured route or leaked its response: IP=%q error=%v requests=%d", ip, err, requests.Load())
181新增: }
182新增:}
183新增:
184新增:func TestExitProbePublicIPv4Service(t *testing.T) {
185新增: if os.Getenv("CAGE_EXIT_PROBE_LIVE") != "1" {
186新增: t.Skip("requires the public IPv4 service through an isolated local proxy")
187新增: }
188新增: for _, scheme := range []string{"http", "socks5"} {
189新增: t.Run(scheme, func(t *testing.T) {
190新增: proxy, requests := exitProbeProxy(t, scheme, "ipv4.icanhazip.com:443")
191新增: cfg := DefaultConfig()
192新增: cfg.ProxyURL = proxy
193新增: ip, err := ProbeExitIP(context.Background(), cfg)
194新增: if err != nil {
195新增: t.Fatal(err)
196新增: }
197新增: address, err := netip.ParseAddr(ip)
198新增: if err != nil || !address.Is4() || !address.IsGlobalUnicast() || address.IsPrivate() || requests.Load() != 1 {
199新增: t.Fatal("public service did not return IPv4 through the selected proxy")
200新增: }
201新增: t.Log("public endpoint returned a public IPv4 through the isolated proxy")
202新增: })
203新增: }
204新增:}
205新增:
206新增:// The local fixture accepts CONNECT or SOCKS domain requests and maps the fixed
207新增:// public hostname to an isolated TLS server without using the application's dialer.
208新增:func exitProbeProxy(t *testing.T, scheme, upstream string) (string, *atomic.Int32) {
209新增: t.Helper()
210新增: listener, err := net.Listen("tcp", "127.0.0.1:0")
211新增: if err != nil {
212新增: t.Fatal(err)
213新增: }
214新增: count := new(atomic.Int32)
215新增: t.Cleanup(func() { _ = listener.Close() })
216新增: go func() {
217新增: for {
218新增: connection, err := listener.Accept()
219新增: if err != nil {
220新增: return
221新增: }
222新增: go func() {
223新增: defer connection.Close()
224新增: _ = connection.SetDeadline(time.Now().Add(10 * time.Second))
225新增: reader := bufio.NewReader(connection)
226新增: var target string
227新增: if scheme == "http" {
228新增: request, err := http.ReadRequest(reader)
229新增: if err != nil || request.Method != "CONNECT" {
230新增: t.Error("expected HTTP CONNECT")
231新增: return
232新增: }
233新增: if request.Header.Get("Proxy-Authorization") != "Basic dGVzdC11c2VyOnRlc3QtcGFzc3dvcmQ=" {
234新增: t.Error("HTTP proxy authentication was lost")
235新增: return
236新增: }
237新增: target = request.Host
238新增: _, _ = io.WriteString(connection, "HTTP/1.1 200 Connection Established\r\n\r\n")
239新增: } else {
240新增: var header [4]byte
241新增: if _, err := io.ReadFull(reader, header[:2]); err != nil {
242新增: return
243新增: }
244新增: if _, err := io.CopyN(io.Discard, reader, int64(header[1])); err != nil {
245新增: return
246新增: }
247新增: _, _ = connection.Write([]byte{5, 2})
248新增: if _, err := io.ReadFull(reader, header[:2]); err != nil {
249新增: return
250新增: }
251新增: username := make([]byte, int(header[1]))
252新增: if _, err := io.ReadFull(reader, username); err != nil {
253新增: return
254新增: }
255新增: passwordLength, err := reader.ReadByte()
256新增: if err != nil {
257新增: return
258新增: }
259新增: password := make([]byte, int(passwordLength))
260新增: if _, err := io.ReadFull(reader, password); err != nil {
261新增: return
262新增: }
263新增: if string(username) != "test-user" || string(password) != "test-password" {
264新增: t.Error("SOCKS proxy authentication was lost")
265新增: return
266新增: }
267新增: _, _ = connection.Write([]byte{1, 0})
268新增: if _, err := io.ReadFull(reader, header[:]); err != nil {
269新增: return
270新增: }
271新增: if header[0] != 5 || header[1] != 1 || header[3] != 3 {
272新增: t.Error("SOCKS probe resolved its hostname outside the proxy")
273新增: return
274新增: }
275新增: length, err := reader.ReadByte()
276新增: if err != nil {
277新增: return
278新增: }
279新增: host := make([]byte, length)
280新增: if _, err := io.ReadFull(reader, host); err != nil {
281新增: return
282新增: }
283新增: if _, err := io.ReadFull(reader, header[:2]); err != nil {
284新增: return
285新增: }
286新增: target = net.JoinHostPort(string(host), fmt.Sprint(binary.BigEndian.Uint16(header[:2])))
287新增: _, _ = connection.Write([]byte{5, 0, 0, 1, 127, 0, 0, 1, 0, 80})
288新增: }
289新增: if target != "ipv4.icanhazip.com:443" && target != "api.ipify.org:443" {
290新增: t.Error("probe followed a redirect or changed destination")
291新增: return
292新增: }
293新增: count.Add(1)
294新增: remote, err := net.DialTimeout("tcp", upstream, time.Second)
295新增: if err != nil {
296新增: t.Error(err)
297新增: return
298新增: }
299新增: defer remote.Close()
300新增: go func() { _, _ = io.Copy(remote, reader); _ = remote.Close() }()
301新增: _, _ = io.Copy(connection, remote)
302新增: }()
303新增: }
304新增: }()
305新增: return scheme + "://test-user:test-password@" + listener.Addr().String(), count
306新增:}