跳到主要内容

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

提交记录
修改cmd/cage/mac_guest_download_darwin_arm64.go+112 −9看文件
@@ -9,22 +9,34 @@ import (
99 "errors"
1010 "fmt"
1111 "io"
12新增: "net/http"
1213 "os"
13删除: "os/exec"
14新增: "strings"
1415 "time"
16新增:
17新增: "github.com/sylvinus/agent-vm/internal/hostproxy"
1518)
1619
17删除:// Keep the existing curl resume/retry behavior. Sampling the partial file also
18删除:// reports progress when curl's output is connected to the workbench log pipe.
1920func prepareMacRestoreMedia(ctx context.Context, media, url, digest string, total int64, out io.Writer) error {
21新增: transport := hostproxy.NewTransport()
22新增: defer transport.CloseIdleConnections()
23新增: return prepareMacRestoreMediaWithTransport(ctx, media, url, digest, total, out, transport)
24新增:}
25新增:
26新增:func prepareMacRestoreMediaWithTransport(ctx context.Context, media, url, digest string, total int64, out io.Writer, transport http.RoundTripper) error {
2027 if _, err := os.Stat(media); err == nil {
2128 return verifyMacRestoreMedia(ctx, media, digest, out)
2229 } else if !errors.Is(err, os.ErrNotExist) {
2330 return err
2431 }
2532 partial := media + ".partial"
26删除: cmd := exec.CommandContext(ctx, "/usr/bin/curl", "--disable", "-fsSL", "--proto", "=https", "--proto-redir", "=https", "--retry", "2", "--connect-timeout", "15", "--speed-time", "90", "--speed-limit", "1024", "--continue-at", "-", url, "-o", partial)
27删除: cmd.Stderr = os.Stderr
33新增: client := &http.Client{Transport: transport, Timeout: 2 * time.Hour, CheckRedirect: func(req *http.Request, previous []*http.Request) error {
34新增: if req.URL.Scheme != "https" || len(previous) >= 5 {
35新增: return errors.New("Apple 镜像重定向无效")
36新增: }
37新增: return nil
38新增: }}
39新增: defer client.CloseIdleConnections()
2840 report := func() {
2941 var received int64
3042 if info, err := os.Stat(partial); err == nil {
@@ -33,11 +45,17 @@ func prepareMacRestoreMedia(ctx context.Context, media, url, digest string, tota
3345 fmt.Fprintf(out, "CAGE_GUEST_BYTES macos download %d %d\n", received, total)
3446 }
3547 report()
36删除: if err := cmd.Start(); err != nil {
37删除: return err
38删除: }
3948 done := make(chan error, 1)
40删除: go func() { done <- cmd.Wait() }()
49新增: go func() {
50新增: var err error
51新增: for attempt := 0; attempt < 3; attempt++ {
52新增: err = downloadMacRestore(ctx, client, url, partial, total)
53新增: if err == nil || ctx.Err() != nil {
54新增: break
55新增: }
56新增: }
57新增: done <- err
58新增: }()
4159 ticker := time.NewTicker(time.Second)
4260 defer ticker.Stop()
4361 for {
@@ -64,6 +82,91 @@ func prepareMacRestoreMedia(ctx context.Context, media, url, digest string, tota
6482 }
6583}
6684
85新增:func downloadMacRestore(ctx context.Context, client *http.Client, address, partial string, total int64) error {
86新增: ctx, cancel := context.WithCancel(ctx)
87新增: defer cancel()
88新增: if !strings.HasPrefix(address, "https://") {
89新增: return errors.New("Apple 镜像必须通过 HTTPS 下载")
90新增: }
91新增: file, err := os.OpenFile(partial, os.O_CREATE|os.O_RDWR, 0600)
92新增: if err != nil {
93新增: return err
94新增: }
95新增: defer file.Close()
96新增: info, err := file.Stat()
97新增: if err != nil {
98新增: return err
99新增: }
100新增: offset := info.Size()
101新增: if total > 0 && offset > total {
102新增: if err := file.Truncate(0); err != nil {
103新增: return err
104新增: }
105新增: offset = 0
106新增: }
107新增: if total > 0 && offset == total {
108新增: return nil
109新增: }
110新增: req, err := http.NewRequestWithContext(ctx, http.MethodGet, address, nil)
111新增: if err != nil {
112新增: return err
113新增: }
114新增: req.Header.Set("Accept-Encoding", "identity")
115新增: if offset > 0 {
116新增: req.Header.Set("Range", fmt.Sprintf("bytes=%d-", offset))
117新增: }
118新增: resp, err := client.Do(req)
119新增: if err != nil {
120新增: return err
121新增: }
122新增: defer resp.Body.Close()
123新增: switch resp.StatusCode {
124新增: case http.StatusOK:
125新增: offset = 0
126新增: if err := file.Truncate(0); err != nil {
127新增: return err
128新增: }
129新增: case http.StatusPartialContent:
130新增: var start, end, size int64
131新增: if _, err := fmt.Sscanf(resp.Header.Get("Content-Range"), "bytes %d-%d/%d", &start, &end, &size); err != nil || start != offset || end < start || total > 0 && size != total {
132新增: return errors.New("Apple 镜像续传范围不匹配")
133新增: }
134新增: default:
135新增: return fmt.Errorf("Apple 镜像下载返回 HTTP %d", resp.StatusCode)
136新增: }
137新增: if _, err := file.Seek(offset, io.SeekStart); err != nil {
138新增: return err
139新增: }
140新增: // Retain the old curl path's protection against a stalled image stream.
141新增: watchdog := time.AfterFunc(90*time.Second, cancel)
142新增: defer watchdog.Stop()
143新增: limit := total
144新增: if limit <= 0 {
145新增: limit = 64 << 30
146新增: }
147新增: count, err := io.Copy(file, io.LimitReader(restoreDownloadReader{reader: resp.Body, watchdog: watchdog}, limit-offset+1))
148新增: if err != nil {
149新增: return err
150新增: }
151新增: if count+offset > limit || total > 0 && count+offset != total {
152新增: return errors.New("Apple 镜像下载大小不匹配")
153新增: }
154新增: return nil
155新增:}
156新增:
157新增:type restoreDownloadReader struct {
158新增: reader io.Reader
159新增: watchdog *time.Timer
160新增:}
161新增:
162新增:func (r restoreDownloadReader) Read(buffer []byte) (int, error) {
163新增: n, err := r.reader.Read(buffer)
164新增: if n > 0 {
165新增: r.watchdog.Reset(90 * time.Second)
166新增: }
167新增: return n, err
168新增:}
169新增:
67170func verifyMacRestoreMedia(ctx context.Context, media, digest string, out io.Writer) error {
68171 file, err := os.Open(media)
69172 if err != nil {
修改cmd/cage/mac_guest_download_darwin_arm64_test.go+4 −17看文件
@@ -7,7 +7,6 @@ import (
77 "context"
88 "crypto/sha256"
99 "encoding/hex"
10删除: "encoding/pem"
1110 "errors"
1211 "fmt"
1312 "net/http"
@@ -19,15 +18,6 @@ import (
1918 "time"
2019)
2120
22删除:func trustRestoreServer(t *testing.T, server *httptest.Server) {
23删除: t.Helper()
24删除: cert := filepath.Join(t.TempDir(), "ca.pem")
25删除: if err := os.WriteFile(cert, pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: server.Certificate().Raw}), 0600); err != nil {
26删除: t.Fatal(err)
27删除: }
28删除: t.Setenv("CURL_CA_BUNDLE", cert)
29删除:}
30删除:
3121func TestMacRestoreDownloadResumesAndReportsVerification(t *testing.T) {
3222 body := bytes.Repeat([]byte("restore-image"), 10000)
3323 offset := len(body) / 3
@@ -42,14 +32,13 @@ func TestMacRestoreDownloadResumesAndReportsVerification(t *testing.T) {
4232 _, _ = w.Write(body[offset:])
4333 }))
4434 defer server.Close()
45删除: trustRestoreServer(t, server)
4635 media := filepath.Join(t.TempDir(), "MacOS.ipsw")
4736 if err := os.WriteFile(media+".partial", body[:offset], 0600); err != nil {
4837 t.Fatal(err)
4938 }
5039 hash := sha256.Sum256(body)
5140 var log bytes.Buffer
52删除: if err := prepareMacRestoreMedia(t.Context(), media, server.URL, hex.EncodeToString(hash[:]), int64(len(body)), &log); err != nil {
41新增: if err := prepareMacRestoreMediaWithTransport(t.Context(), media, server.URL, hex.EncodeToString(hash[:]), int64(len(body)), &log, server.Client().Transport); err != nil {
5342 t.Fatal(err)
5443 }
5544 actual, err := os.ReadFile(media)
@@ -66,7 +55,7 @@ func TestMacRestoreDownloadResumesAndReportsVerification(t *testing.T) {
6655 }
6756 log.Reset()
6857 // A verified cached archive must not make another request to the server.
69删除: if err := prepareMacRestoreMedia(t.Context(), media, "https://invalid.invalid", hex.EncodeToString(hash[:]), int64(len(body)), &log); err != nil {
58新增: if err := prepareMacRestoreMediaWithTransport(t.Context(), media, "https://invalid.invalid", hex.EncodeToString(hash[:]), int64(len(body)), &log, server.Client().Transport); err != nil {
7059 t.Fatal(err)
7160 }
7261 if strings.Contains(log.String(), "macos download") {
@@ -81,13 +70,12 @@ func TestMacRestoreCancelledDownloadKeepsPartial(t *testing.T) {
8170 <-r.Context().Done()
8271 }))
8372 defer server.Close()
84删除: trustRestoreServer(t, server)
8573 media := filepath.Join(t.TempDir(), "MacOS.ipsw")
8674 ctx, cancel := context.WithCancel(t.Context())
8775 defer cancel()
8876 done := make(chan error, 1)
8977 go func() {
90删除: done <- prepareMacRestoreMedia(ctx, media, server.URL, strings.Repeat("0", 64), 1<<20, &bytes.Buffer{})
78新增: done <- prepareMacRestoreMediaWithTransport(ctx, media, server.URL, strings.Repeat("0", 64), 1<<20, &bytes.Buffer{}, server.Client().Transport)
9179 }()
9280 deadline := time.After(5 * time.Second)
9381 ticker := time.NewTicker(10 * time.Millisecond)
@@ -119,9 +107,8 @@ func TestMacRestoreCancelledDownloadKeepsPartial(t *testing.T) {
119107func TestMacRestoreDigestFailureDoesNotPublishMedia(t *testing.T) {
120108 server := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { _, _ = w.Write([]byte("invalid restore")) }))
121109 defer server.Close()
122删除: trustRestoreServer(t, server)
123110 media := filepath.Join(t.TempDir(), "MacOS.ipsw")
124删除: if err := prepareMacRestoreMedia(t.Context(), media, server.URL, strings.Repeat("0", 64), 15, &bytes.Buffer{}); err == nil {
111新增: if err := prepareMacRestoreMediaWithTransport(t.Context(), media, server.URL, strings.Repeat("0", 64), 15, &bytes.Buffer{}, server.Client().Transport); err == nil {
125112 t.Fatal("invalid digest accepted")
126113 }
127114 for _, p := range []string{media, media + ".partial"} {
修改cmd/cage/main.go+8 −8看文件
@@ -21,6 +21,7 @@ import (
2121 "github.com/sylvinus/agent-vm/internal/diagnostics"
2222 "github.com/sylvinus/agent-vm/internal/guestos"
2323 "github.com/sylvinus/agent-vm/internal/host"
24新增: "github.com/sylvinus/agent-vm/internal/hostproxy"
2425 "github.com/sylvinus/agent-vm/internal/limaembed"
2526 "github.com/sylvinus/agent-vm/internal/managedproxy"
2627 "github.com/sylvinus/agent-vm/internal/workbench"
@@ -75,6 +76,7 @@ func main() {
7576 os.Exit(code)
7677}
7778func run() int {
79新增: hostproxy.CaptureEnvironment()
7880 // Apply this before desktop/serve dispatch: the control service and every
7981 // child process must keep Cage's isolation even when launched from a shell
8082 // configured to relax agent-vm's protections.
@@ -473,6 +475,9 @@ func run() int {
473475 return fail(err)
474476 }
475477 defer lease.Close()
478新增: // Keep image caches on the same volume the initialization page shows,
479新增: // including the default location. The saved path survives app updates.
480新增: os.Setenv("CAGE_LIMA_CACHE_DIR", filepath.Join(location.Directory, "cache", "lima"))
476481 if location.Custom {
477482 // Resolve the profile prefix once, as Lima did before migration.
478483 // Keep state itself logical so its original disk and socket paths survive.
@@ -481,7 +486,6 @@ func run() int {
481486 return fail(err)
482487 }
483488 state = filepath.Join(realProfile, "state")
484删除: os.Setenv("CAGE_LIMA_CACHE_DIR", filepath.Join(location.Directory, "cache", "lima"))
485489 os.Setenv("CAGE_LOGICAL_LIMA_HOME", filepath.Join(state, "lima"))
486490 }
487491 }
@@ -491,6 +495,9 @@ func run() int {
491495 for _, name := range []string{"HTTP_PROXY", "HTTPS_PROXY", "ALL_PROXY", "FTP_PROXY", "NO_PROXY", "http_proxy", "https_proxy", "all_proxy", "ftp_proxy", "no_proxy", "ANTHROPIC_API_KEY", "CLAUDE_CODE_OAUTH_TOKEN"} {
492496 os.Unsetenv(name)
493497 }
498新增: // Lima's host-side image downloader follows system proxy settings/TUN.
499新增: // Guest traffic keeps the isolated hostagent hooks in limaembed.Run.
500新增: http.DefaultTransport = hostproxy.NewTransport()
494501 if limaembed.Run(args) {
495502 return 0
496503 }
@@ -541,13 +548,6 @@ func run() int {
541548 return fail(err)
542549 }
543550
544删除: // Host-side image downloads also use the selected proxy. Guest traffic
545删除: // uses the separate hostagent hooks installed by limaembed.Run.
546删除: egress, err := cage.NewEgress(cfg)
547删除: if err != nil {
548删除: return fail(err)
549删除: }
550删除: http.DefaultTransport = &http.Transport{Proxy: nil, DialContext: egress.DialContext, ForceAttemptHTTP2: true}
551551 if args[0] == "check" {
552552 e, err := cage.NewEgress(cfg)
553553 if err != nil {
修改docs/guide/installation.md+7 −1看文件
@@ -36,10 +36,14 @@ Windows ARM64 和 Linux ARM64 暂不支持。平台依赖详情见 [Windows 指
3636
3737## 初始化系统与存储
3838
39删除:首次登录后,Cage 显示独立的初始化界面。先选择适合项目的客机系统,可选择“自动匹配本机系统版本”或具体系统。自动匹配会在代理配置后获取对应的官方镜像,安装干净的独立系统,主机个人文件与登录资料不会复制。以后启动沿用原系统和磁盘,更新 Cage 不会替换客机系统。
39新增:首次登录后,Cage 显示独立的初始化界面。先选择适合项目的客机系统,可选择“自动匹配本机系统版本”或具体系统。自动匹配在下一步显示对应的官方镜像,安装干净的独立系统,主机个人文件与登录资料不会复制。以后启动沿用原系统和磁盘,更新 Cage 不会替换客机系统。
4040
4141“存储目录”已填入默认位置。需要更换时直接编辑,或点击“选择文件夹”选定本地磁盘上的专用空文件夹;点击“下一步:配置代理”时保存,目录无效时留在当前页提示修改。Windows 安装器里的程序目录与环境数据目录分开;例如应用装在 C 盘,环境可放在 `D:\CageData`。
4242
43新增:Mac、Linux 使用默认配置时,环境数据放在用户主目录的 `.claude-cage/state`。Windows 正式安装版在首次初始化时,默认填入安装目录下的 `CageData`,例如应用装在 `D:\Cage`,环境数据就放在 `D:\Cage\CageData`;没有写入权限时,在当前字段选择其他有权限的本地文件夹。已有环境继续使用原存储位置,不会自动迁移。账户与配置仍保存在用户目录的 `.claude-cage`。
44新增:
45新增:初始化页显示本机完整路径。系统镜像、后续镜像下载缓存与持久虚拟磁盘使用同一存储位置;旧版本已留在系统缓存目录的文件不自动移动或删除。更新、重装与卸载应用保留环境数据目录,重新安装后可以继续使用已有数据。不要手动删除这个目录。
46新增:
4347选择支持权限管理与稀疏文件的磁盘:Windows 可用 NTFS,Linux 可用 ext4 / XFS / Btrfs,macOS 使用已启用所有权的 APFS。不要选择磁盘根目录、网络盘、已有项目或应用安装目录。已有环境换盘请按[存储迁移](maintenance.md#迁移环境到另一块磁盘)操作。
4448
4549## 导入代理并启动
@@ -56,6 +60,8 @@ Git 保护会修改当前主机用户的全局 `safe.bareRepository=explicit`,
5660
5761首次安装内容取决于客机系统。克隆入口优先复用已校验的匹配材料,缺少时下载官方镜像。macOS 使用 Apple IPSW;Windows 克隆使用匹配的 Microsoft ESD,手动安装可选择官方 ISO;Linux 克隆使用对应发行版的云镜像。Debian 13 基础镜像约 320–325 MiB,开发工具另行安装。镜像来源、系统许可和存储要求见[客机系统指南](guest-systems.md#下载量与磁盘空间)。
5862
63新增:系统镜像与镜像版本目录通过主机网络下载,遵循主机代理设置,不使用 Cage 为客机选择的节点。使用 Clash 等软件时,先开启其系统代理或 TUN;实际出口仍由该软件对镜像网站的规则决定。已选择的主机代理连接失败、明确配置的 PAC 解析失败时,下载会报错,保留已有文件,不自动回退直连。客机内的进程和开发工具继续使用 Cage 的独立代理,具体平台设置见[系统镜像的下载网络](network.md#系统镜像的下载网络)。
64新增:
5965Debian 初始虚拟磁盘容量上限为 24 GiB,macOS 和 Windows 需为系统及开发工具留出更多空间。实际占用随安装和使用增加,创建前查看所选版本的要求。Claude Desktop 按需单独下载。随后启动会复用工具、文件与登录资料。
6066
6167下载中断时查看错误,修复网络或磁盘空间后点“继续安装”。已保留的文件会尝试续传;摘要不符时必须重新下载。不要通过清空 `.claude-cage` 或重建账户解决安装失败。
修改docs/guide/network.md+12 −0看文件
@@ -59,6 +59,18 @@ Hysteria2 节点可使用 `mport` 指定端口跳跃范围、`pinSHA256` 指定
5959 <figcaption>跟随出口 IP 的时区与语言设置。截图版本:0.1.6-alpha-preview(开发构建) · macOS 原生应用 · 2026-11-07。<a href="../../www/public/docs/screenshots/region-settings.jpg" target="_blank" rel="noopener">查看原图(2560 × 1764) ↗</a></figcaption>
6060</figure>
6161
62新增:## 系统镜像的下载网络
63新增:
64新增:系统镜像和镜像版本目录使用主机网络,与 Cage 客机的代理节点分开。Clash 等软件只开启“系统代理”也可以接管镜像下载,无需为了 Cage 下载镜像而开启 TUN;下载连接不绑定物理网卡,也不会修改代理软件的节点或规则。镜像网站若被主机代理规则设为直连,Cage 遵循该规则。
65新增:
66新增:- macOS:读取系统 HTTP、HTTPS、SOCKS 代理及 PAC,每次请求和重定向按目标地址解析。
67新增:- Windows:读取当前用户的系统代理;PAC 与自动检测通过 WinHTTP 按目标地址解析。
68新增:- Linux:支持代理环境变量、GNOME 手动桌面代理及主机 TUN。此构建遇到 GNOME 自动 PAC 会停止并提示改用 TUN 或代理环境变量;其他桌面环境请设置代理环境变量或开启 TUN。
69新增:
70新增:从终端启动时,目标协议对应的 `HTTP_PROXY`、`HTTPS_PROXY` 优先于系统设置,`ALL_PROXY` 作为缺省代理,并遵循对应的 `NO_PROXY` 例外。这些主机设置不会传入客机。代理连不上或已配置的 PAC 解析失败时,下载停止,不因失败切换直连;修复主机代理后,在初始化界面继续安装,已有下载会尝试续传。
71新增:
72新增:客机进程和开发工具安装继续走 Cage 的独立代理。系统镜像下载成功不代表客机网络检查通过,进入工作台仍需完成客机的网络与隔离检查。
73新增:
6274## 时区、语言与出口规则
6375
6476在“设置 → 时区与语言”选择跟随出口或手动设置。自动模式通过代理查询出口位置,不使用主机位置替代。位置服务失败时可重试或切换节点;手动设置时区和语言仍须确认出口国家或地区。
修改internal/cage/storage.go+14 −5看文件
@@ -124,7 +124,7 @@ func StoragePathsOverlap(a, b string) bool {
124124 return StorageContains(a, b) || StorageContains(b, a)
125125}
126126
127删除:// Upgrades replace the entire application folder including its resources.
127新增:// Resolve the application folder, including macOS bundles and Windows resources.
128128func runningApplicationDir() (string, error) {
129129 exe, err := os.Executable()
130130 if err != nil {
@@ -306,6 +306,14 @@ func openStorageLockWithRuntime(ctx context.Context, profile string, exclusive b
306306}
307307
308308func ValidateStorageTarget(profile, directory string) error {
309新增: app, err := runningApplicationDir()
310新增: if err != nil {
311新增: return err
312新增: }
313新增: return validateStorageTarget(profile, directory, app, runtime.GOOS)
314新增:}
315新增:
316新增:func validateStorageTarget(profile, directory, app, platform string) error {
309317 if _, err := os.Readlink(storageAnchor(profile)); err == nil {
310318 r, err := readStorageRecord(profile)
311319 if err != nil {
@@ -350,11 +358,12 @@ func ValidateStorageTarget(profile, directory string) error {
350358 return err
351359 }
352360 private = append(private, profile, EnvironmentDir(profile))
353删除: app, err := runningApplicationDir()
354删除: if err != nil {
355删除: return err
361新增: appData := windowsApplicationDataDirectory(app, platform)
362新增: // Windows reserves this one data folder beside its program files. The
363新增: // installer preserves it by file ownership during update and uninstall.
364新增: if appData == "" || !sameStoragePath(directory, appData) {
365新增: private = append(private, app)
356366 }
357删除: private = append(private, app)
358367 for _, p := range private {
359368 real, e := StoragePhysicalPath(p)
360369 if e != nil && !errors.Is(e, os.ErrNotExist) {
新增internal/cage/storage_default.go+39 −0看文件
@@ -0,0 +1,39 @@
1新增:package cage
2新增:
3新增:import (
4新增: "os"
5新增: "path/filepath"
6新增: "runtime"
7新增: "strings"
8新增:)
9新增:
10新增:// InitialStorageDirectory supplies a fresh packaged Windows installation's
11新增:// data location. Profiles and existing storage records keep their own paths.
12新增:func InitialStorageDirectory(exe string) string {
13新增: resolved, err := filepath.EvalSymlinks(exe)
14新增: if err != nil {
15新增: return ""
16新增: }
17新增: return initialStorageDirectory(resolved, runtime.GOOS)
18新增:}
19新增:
20新增:func initialStorageDirectory(exe, platform string) string {
21新增: if platform != "windows" || !strings.EqualFold(filepath.Base(filepath.Dir(exe)), "resources") {
22新增: return ""
23新增: }
24新增: return windowsApplicationDataDirectory(filepath.Dir(filepath.Dir(exe)), platform)
25新增:}
26新增:
27新增:func windowsApplicationDataDirectory(app, platform string) string {
28新增: if platform != "windows" {
29新增: return ""
30新增: }
31新增: marker, err := os.ReadFile(filepath.Join(app, "Cage.install-id"))
32新增: if err != nil || string(marker) != "io.github.lee-xeo.claude-cage" {
33新增: return ""
34新增: }
35新增: if info, err := os.Stat(filepath.Join(app, "Cage.exe")); err != nil || !info.Mode().IsRegular() {
36新增: return ""
37新增: }
38新增: return filepath.Join(app, "CageData")
39新增:}
新增internal/cage/storage_default_test.go+45 −0看文件
@@ -0,0 +1,45 @@
1新增:package cage
2新增:
3新增:import (
4新增: "os"
5新增: "path/filepath"
6新增: "testing"
7新增:)
8新增:
9新增:func TestWindowsInitialDataDirectoryAndApplicationBoundary(t *testing.T) {
10新增: profile, root := newStorageFixture(t)
11新增: app := filepath.Join(root, "Cage")
12新增: backend := filepath.Join(app, "resources", "cage.exe")
13新增: writeStorageFixture(t, backend, []byte("backend"))
14新增: writeStorageFixture(t, filepath.Join(app, "Cage.exe"), []byte("launcher"))
15新增: if got := initialStorageDirectory(backend, "windows"); got != "" {
16新增: t.Fatalf("unmarked build default=%s", got)
17新增: }
18新增: writeStorageFixture(t, filepath.Join(app, "Cage.install-id"), []byte("io.github.lee-xeo.claude-cage"))
19新增: data := filepath.Join(app, "CageData")
20新增: if got := initialStorageDirectory(backend, "windows"); got != data {
21新增: t.Fatalf("default=%s want=%s", got, data)
22新增: }
23新增: for _, platform := range []string{"darwin", "linux"} {
24新增: if got := initialStorageDirectory(backend, platform); got != "" {
25新增: t.Fatalf("%s default changed to %s", platform, got)
26新增: }
27新增: }
28新增: if err := validateStorageTarget(profile, data, app, "windows"); err != nil {
29新增: t.Fatalf("reserved Windows data folder rejected: %v", err)
30新增: }
31新增: for _, target := range []string{app, filepath.Join(app, "resources", "data"), filepath.Join(app, "OtherData")} {
32新增: if err := validateStorageTarget(profile, target, app, "windows"); err == nil {
33新增: t.Fatalf("program boundary opened for %s", target)
34新增: }
35新增: }
36新增: if err := validateStorageTarget(profile, data, app, "darwin"); err == nil {
37新增: t.Fatal("Mac application directory allowed")
38新增: }
39新增: if err := os.Remove(filepath.Join(app, "Cage.install-id")); err != nil {
40新增: t.Fatal(err)
41新增: }
42新增: if err := validateStorageTarget(profile, data, app, "windows"); err == nil {
43新增: t.Fatal("unmarked installation allowed data inside app")
44新增: }
45新增:}
新增internal/hostproxy/proxy_darwin.go+118 −0看文件
@@ -0,0 +1,118 @@
1新增://go:build darwin && cgo
2新增:
3新增:package hostproxy
4新增:
5新增:/*
6新增:#cgo LDFLAGS: -framework CoreFoundation -framework CFNetwork
7新增:#include <CFNetwork/CFNetwork.h>
8新增:#include <stdlib.h>
9新增:#include <string.h>
10新增:
11新增:typedef struct { char *url; int failed; } CageProxy;
12新增:static char *cageString(CFStringRef value) {
13新增: if (!value) return NULL;
14新增: CFIndex size = CFStringGetMaximumSizeForEncoding(CFStringGetLength(value), kCFStringEncodingUTF8) + 1;
15新增: char *text = calloc(size, 1);
16新增: if (!CFStringGetCString(value, text, size, kCFStringEncodingUTF8)) { free(text); return NULL; }
17新增: return text;
18新增:}
19新增:static void cagePACCallback(void *client, CFArrayRef proxies, CFErrorRef error) {
20新增: CFTypeRef *result = client;
21新增: *result = CFRetain(error ? (CFTypeRef)error : (CFTypeRef)proxies);
22新增: CFRunLoopStop(CFRunLoopGetCurrent());
23新增:}
24新增:static CageProxy cageResolveArray(CFArrayRef proxies, CFURLRef target, int allowPAC) {
25新增: CageProxy result = {NULL, 1};
26新增: if (!proxies || !CFArrayGetCount(proxies)) return result;
27新增: CFDictionaryRef proxy = CFArrayGetValueAtIndex(proxies, 0);
28新增: CFStringRef type = CFDictionaryGetValue(proxy, kCFProxyTypeKey);
29新增: if (!type) return result;
30新增: if (CFEqual(type, kCFProxyTypeNone)) { result.failed = 0; return result; }
31新增: if (allowPAC && CFEqual(type, kCFProxyTypeAutoConfigurationURL)) {
32新增: CFURLRef pac = CFDictionaryGetValue(proxy, kCFProxyAutoConfigurationURLKey);
33新增: if (!pac) return result;
34新增: CFTypeRef answer = NULL;
35新增: CFStreamClientContext context = {0, &answer, NULL, NULL, NULL};
36新增: CFRunLoopSourceRef source = CFNetworkExecuteProxyAutoConfigurationURL(pac, target, cagePACCallback, &context);
37新增: if (source) {
38新增: CFStringRef mode = CFSTR("CageImageProxy");
39新增: CFRunLoopAddSource(CFRunLoopGetCurrent(), source, mode);
40新增: CFRunLoopRunInMode(mode, 15, false);
41新增: CFRunLoopRemoveSource(CFRunLoopGetCurrent(), source, mode);
42新增: CFRunLoopSourceInvalidate(source);
43新增: CFRelease(source);
44新增: }
45新增: if (answer) {
46新增: if (CFGetTypeID(answer) == CFArrayGetTypeID()) result = cageResolveArray((CFArrayRef)answer, target, 0);
47新增: CFRelease(answer);
48新增: }
49新增: return result;
50新增: }
51新增: const char *scheme = NULL;
52新增: if (CFEqual(type, kCFProxyTypeHTTP)) scheme = "http";
53新增: // CFNetwork's HTTPS type means HTTP CONNECT, not TLS to the proxy.
54新增: if (CFEqual(type, kCFProxyTypeHTTPS)) scheme = "http";
55新增: if (CFEqual(type, kCFProxyTypeSOCKS)) scheme = "socks5";
56新增: if (!scheme) return result;
57新增: char *host = cageString(CFDictionaryGetValue(proxy, kCFProxyHostNameKey));
58新增: int port = 0;
59新增: CFNumberRef number = CFDictionaryGetValue(proxy, kCFProxyPortNumberKey);
60新增: if (number) CFNumberGetValue(number, kCFNumberIntType, &port);
61新增: if (host && port > 0 && port <= 65535) {
62新增: CFStringRef url = CFStringCreateWithFormat(NULL, NULL, CFSTR("%s://%s%s%s:%d"), scheme,
63新增: strchr(host, ':') ? "[" : "", host, strchr(host, ':') ? "]" : "", port);
64新增: result.url = cageString(url);
65新增: result.failed = result.url == NULL;
66新增: CFRelease(url);
67新增: }
68新增: free(host);
69新增: return result;
70新增:}
71新增:static CageProxy cageSystemProxy(char *raw) {
72新增: CageProxy result = {NULL, 1};
73新增: CFStringRef text = CFStringCreateWithCString(NULL, raw, kCFStringEncodingUTF8);
74新增: CFURLRef url = text ? CFURLCreateWithString(NULL, text, NULL) : NULL;
75新增: CFDictionaryRef settings = CFNetworkCopySystemProxySettings();
76新增: if (url && settings) {
77新增: CFArrayRef proxies = CFNetworkCopyProxiesForURL(url, settings);
78新增: result = cageResolveArray(proxies, url, 1);
79新增: if (proxies) CFRelease(proxies);
80新增: }
81新增: if (settings) CFRelease(settings);
82新增: if (url) CFRelease(url);
83新增: if (text) CFRelease(text);
84新增: return result;
85新增:}
86新增:*/
87新增:import "C"
88新增:
89新增:import (
90新增: "errors"
91新增: "net/http"
92新增: "net/url"
93新增: "runtime"
94新增: "unsafe"
95新增:)
96新增:
97新增:func systemProxy(req *http.Request) (*url.URL, error) {
98新增: if err := req.Context().Err(); err != nil {
99新增: return nil, err
100新增: }
101新增: // CFNetwork's PAC callback and run loop belong to the same OS thread.
102新增: runtime.LockOSThread()
103新增: defer runtime.UnlockOSThread()
104新增: raw := C.CString(req.URL.String())
105新增: defer C.free(unsafe.Pointer(raw))
106新增: result := C.cageSystemProxy(raw)
107新增: defer C.free(unsafe.Pointer(result.url))
108新增: if err := req.Context().Err(); err != nil {
109新增: return nil, err
110新增: }
111新增: if result.failed != 0 {
112新增: return nil, errors.New("无法解析主机系统代理或 PAC,请检查 Clash 等代理软件后重试;未切换直连")
113新增: }
114新增: if result.url == nil {
115新增: return nil, nil
116新增: }
117新增: return proxyURL(C.GoString(result.url))
118新增:}
新增internal/hostproxy/proxy_darwin_nocgo.go+13 −0看文件
@@ -0,0 +1,13 @@
1新增://go:build darwin && !cgo
2新增:
3新增:package hostproxy
4新增:
5新增:import (
6新增: "errors"
7新增: "net/http"
8新增: "net/url"
9新增:)
10新增:
11新增:func systemProxy(*http.Request) (*url.URL, error) {
12新增: return nil, errors.New("此构建无法读取 macOS 系统代理,请使用正式原生构建或设置 HTTPS_PROXY;未切换直连")
13新增:}
新增internal/hostproxy/proxy_darwin_test.go+89 −0看文件
@@ -0,0 +1,89 @@
1新增://go:build darwin && cgo
2新增:
3新增:package hostproxy
4新增:
5新增:import (
6新增: "bytes"
7新增: "net/http"
8新增: "net/http/httptest"
9新增: "os"
10新增: "os/exec"
11新增: "path/filepath"
12新增: "strings"
13新增: "testing"
14新增:)
15新增:
16新增:func TestMacPACResolutionUsesNativeCodeWithoutChangingSystemSettings(t *testing.T) {
17新增: // Compile the production CFNetwork bridge in an isolated harness. This lets
18新增: // real PAC evaluation run without replacing the developer's system proxy.
19新增: source, err := os.ReadFile("proxy_darwin.go")
20新增: if err != nil {
21新增: t.Fatal(err)
22新增: }
23新增: _, sourceC, ok := strings.Cut(string(source), "/*")
24新增: if !ok {
25新增: t.Fatal("missing C bridge")
26新增: }
27新增: sourceC, _, ok = strings.Cut(sourceC, "*/")
28新增: if !ok {
29新增: t.Fatal("missing C bridge end")
30新增: }
31新增: var lines []string
32新增: for _, line := range strings.Split(sourceC, "\n") {
33新增: if !strings.HasPrefix(line, "#cgo ") {
34新增: lines = append(lines, line)
35新增: }
36新增: }
37新增: sourceC = strings.Join(lines, "\n")
38新增: sourceC += `
39新增:#include <stdio.h>
40新增:int main(int argc, char **argv) {
41新增: CFStringRef pacText = CFStringCreateWithCString(NULL, argv[1], kCFStringEncodingUTF8);
42新增: CFURLRef pacURL = CFURLCreateWithString(NULL, pacText, NULL);
43新增: const void *keys[] = { kCFProxyTypeKey, kCFProxyAutoConfigurationURLKey };
44新增: const void *values[] = { kCFProxyTypeAutoConfigurationURL, pacURL };
45新增: CFDictionaryRef proxy = CFDictionaryCreate(NULL, keys, values, 2, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
46新增: const void *items[] = {proxy};
47新增: CFArrayRef proxies = CFArrayCreate(NULL, items, 1, &kCFTypeArrayCallBacks);
48新增: CFURLRef target = CFURLCreateWithString(NULL, CFSTR("https://cloud.debian.org/image"), NULL);
49新增: CageProxy result = cageResolveArray(proxies, target, 1);
50新增: if (result.failed) return 2;
51新增: puts(result.url ? result.url : "DIRECT");
52新增: free(result.url);
53新增: CFRelease(target); CFRelease(proxies); CFRelease(proxy); CFRelease(pacURL); CFRelease(pacText);
54新增: return 0;
55新增:}`
56新增: program := filepath.Join(t.TempDir(), "pac-check")
57新增: compile := exec.Command("clang", "-x", "c", "-", "-framework", "CoreFoundation", "-framework", "CFNetwork", "-o", program)
58新增: compile.Stdin = strings.NewReader(sourceC)
59新增: if output, err := compile.CombinedOutput(); err != nil {
60新增: t.Fatalf("compile native PAC harness: %v\n%s", err, output)
61新增: }
62新增: for _, test := range []struct {
63新增: name, script, want string
64新增: failure bool
65新增: }{
66新增: {"http", `function FindProxyForURL(url,host){return "PROXY 127.0.0.1:7896";}`, "http://127.0.0.1:7896", false},
67新增: {"direct", `function FindProxyForURL(url,host){return "DIRECT";}`, "DIRECT", false},
68新增: {"socks", `function FindProxyForURL(url,host){return "SOCKS 127.0.0.1:7896";}`, "socks5://127.0.0.1:7896", false},
69新增: {"broken-script", `this is not a PAC script`, "", true},
70新增: } {
71新增: t.Run(test.name, func(t *testing.T) {
72新增: server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
73新增: w.Header().Set("Content-Type", "application/x-ns-proxy-autoconfig")
74新增: w.Write([]byte(test.script))
75新增: }))
76新增: defer server.Close()
77新增: output, err := exec.CommandContext(t.Context(), program, server.URL+"/proxy.pac").CombinedOutput()
78新增: if test.failure {
79新增: if err == nil {
80新增: t.Fatalf("broken PAC became direct: %s", output)
81新增: }
82新增: return
83新增: }
84新增: if err != nil || !bytes.Equal(bytes.TrimSpace(output), []byte(test.want)) {
85新增: t.Fatalf("result=%q err=%v want=%q", output, err, test.want)
86新增: }
87新增: })
88新增: }
89新增:}
新增internal/hostproxy/proxy_linux.go+77 −0看文件
@@ -0,0 +1,77 @@
1新增:package hostproxy
2新增:
3新增:import (
4新增: "context"
5新增: "errors"
6新增: "net"
7新增: "net/http"
8新增: "net/url"
9新增: "os/exec"
10新增: "strconv"
11新增: "strings"
12新增: "time"
13新增:)
14新增:
15新增:func systemProxy(req *http.Request) (*url.URL, error) {
16新增: if _, err := exec.LookPath("gsettings"); err != nil {
17新增: return nil, nil
18新增: }
19新增: ctx, cancel := context.WithTimeout(req.Context(), 3*time.Second)
20新增: defer cancel()
21新增: output, err := exec.CommandContext(ctx, "gsettings", "list-recursively", "org.gnome.system.proxy").Output()
22新增: if err != nil {
23新增: return nil, errors.New("无法读取主机桌面代理设置,请检查代理软件或设置 HTTPS_PROXY;未切换直连")
24新增: }
25新增: return gnomeProxy(req, string(output))
26新增:}
27新增:
28新增:func gnomeProxy(req *http.Request, settings string) (*url.URL, error) {
29新增: values := map[string]string{}
30新增: for _, line := range strings.Split(settings, "\n") {
31新增: parts := strings.SplitN(line, " ", 3)
32新增: if len(parts) == 3 {
33新增: values[parts[0]+" "+parts[1]] = strings.Trim(parts[2], " '")
34新增: }
35新增: }
36新增: switch values["org.gnome.system.proxy mode"] {
37新增: case "auto":
38新增: return nil, errors.New("此 Linux 构建暂不解析桌面 PAC,请启用主机 TUN 或设置 HTTPS_PROXY 后继续下载")
39新增: case "manual":
40新增: address := func(protocol string) string {
41新增: prefix := "org.gnome.system.proxy." + protocol + " "
42新增: host, port := values[prefix+"host"], values[prefix+"port"]
43新增: if host == "" || port == "0" || port == "" {
44新增: return ""
45新增: }
46新增: scheme := "http://"
47新增: if protocol == "socks" {
48新增: scheme = "socks5://"
49新增: }
50新增: return scheme + net.JoinHostPort(host, port)
51新增: }
52新增: httpProxy, httpsProxy, socks := address("http"), address("https"), address("socks")
53新增: if values["org.gnome.system.proxy use-same-proxy"] == "true" {
54新增: httpsProxy = httpProxy
55新增: }
56新增: if httpProxy == "" {
57新增: httpProxy = socks
58新增: }
59新增: if httpsProxy == "" {
60新增: httpsProxy = socks
61新增: }
62新增: bypass := strings.Trim(values["org.gnome.system.proxy ignore-hosts"], "[]")
63新增: var hosts []string
64新增: for _, entry := range strings.Split(bypass, ",") {
65新增: entry = strings.TrimSpace(entry)
66新增: if entry == "" {
67新增: continue
68新增: }
69新增: if value, err := strconv.Unquote(strings.ReplaceAll(entry, "'", "\"")); err == nil {
70新增: hosts = append(hosts, value)
71新增: }
72新增: }
73新增: return staticProxy(req, httpProxy, httpsProxy, strings.Join(hosts, ","))
74新增: default:
75新增: return nil, nil
76新增: }
77新增:}
新增internal/hostproxy/proxy_linux_test.go+17 −0看文件
@@ -0,0 +1,17 @@
1新增:package hostproxy
2新增:
3新增:import (
4新增: "net/http"
5新增: "testing"
6新增:)
7新增:
8新增:func TestGnomeProxyManualAndPACFailure(t *testing.T) {
9新增: req, _ := http.NewRequest("GET", "https://cloud.debian.org/image", nil)
10新增: u, err := gnomeProxy(req, "org.gnome.system.proxy mode 'manual'\norg.gnome.system.proxy.https host '127.0.0.1'\norg.gnome.system.proxy.https port 7890\norg.gnome.system.proxy ignore-hosts ['localhost', '127.0.0.1']")
11新增: if err != nil || u == nil || u.String() != "http://127.0.0.1:7890" {
12新增: t.Fatalf("proxy=%v err=%v", u, err)
13新增: }
14新增: if _, err := gnomeProxy(req, "org.gnome.system.proxy mode 'auto'"); err == nil {
15新增: t.Fatal("unsupported PAC became direct")
16新增: }
17新增:}
新增internal/hostproxy/proxy_other.go+11 −0看文件
@@ -0,0 +1,11 @@
1新增://go:build !windows && !darwin && !linux
2新增:
3新增:package hostproxy
4新增:
5新增:import (
6新增: "net/http"
7新增: "net/url"
8新增:)
9新增:
10新增:// Unix downloads use the captured proxy environment or normal host routing/TUN.
11新增:func systemProxy(*http.Request) (*url.URL, error) { return nil, nil }
新增internal/hostproxy/proxy_windows.go+120 −0看文件
@@ -0,0 +1,120 @@
1新增:package hostproxy
2新增:
3新增:import (
4新增: "fmt"
5新增: "net/http"
6新增: "net/url"
7新增: "strings"
8新增: "unsafe"
9新增:
10新增: "golang.org/x/sys/windows"
11新增:)
12新增:
13新增:var winhttp = windows.NewLazySystemDLL("winhttp.dll")
14新增:var globalFree = windows.NewLazySystemDLL("kernel32.dll").NewProc("GlobalFree")
15新增:
16新增:type ieConfig struct {
17新增: AutoDetect int32
18新增: URL, Proxy, Bypass *uint16
19新增:}
20新增:type autoOptions struct {
21新增: Flags, DetectFlags uint32
22新增: URL *uint16
23新增: Reserved uintptr
24新增: ReservedFlags uint32
25新增: AutoLogon int32
26新增:}
27新增:type proxyInfo struct {
28新增: AccessType uint32
29新增: Proxy, Bypass *uint16
30新增:}
31新增:
32新增:func freeString(p *uint16) {
33新增: if p != nil {
34新增: globalFree.Call(uintptr(unsafe.Pointer(p)))
35新增: }
36新增:}
37新增:func proxyString(p *uint16) string { return windows.UTF16PtrToString(p) }
38新增:
39新增:func systemProxy(req *http.Request) (*url.URL, error) {
40新增: var config ieConfig
41新增: ok, _, err := winhttp.NewProc("WinHttpGetIEProxyConfigForCurrentUser").Call(uintptr(unsafe.Pointer(&config)))
42新增: if ok == 0 {
43新增: if err == windows.ERROR_FILE_NOT_FOUND {
44新增: return nil, nil
45新增: }
46新增: return nil, fmt.Errorf("无法读取主机系统代理,未切换直连:%w", err)
47新增: }
48新增: defer freeString(config.URL)
49新增: defer freeString(config.Proxy)
50新增: defer freeString(config.Bypass)
51新增: if config.URL != nil || config.AutoDetect != 0 {
52新增: handle, _, err := winhttp.NewProc("WinHttpOpen").Call(0, 1, 0, 0, 0)
53新增: if handle == 0 {
54新增: return nil, fmt.Errorf("无法解析主机自动代理:%w", err)
55新增: }
56新增: defer winhttp.NewProc("WinHttpCloseHandle").Call(handle)
57新增: winhttp.NewProc("WinHttpSetTimeouts").Call(handle, 15000, 15000, 15000, 15000)
58新增: options := autoOptions{URL: config.URL}
59新增: if config.URL != nil {
60新增: options.Flags = 2
61新增: } else {
62新增: options.Flags = 1
63新增: options.DetectFlags = 3
64新增: }
65新增: target, err := windows.UTF16PtrFromString(req.URL.String())
66新增: if err != nil {
67新增: return nil, err
68新增: }
69新增: var info proxyInfo
70新增: ok, _, err := winhttp.NewProc("WinHttpGetProxyForUrl").Call(handle, uintptr(unsafe.Pointer(target)), uintptr(unsafe.Pointer(&options)), uintptr(unsafe.Pointer(&info)))
71新增: defer freeString(info.Proxy)
72新增: defer freeString(info.Bypass)
73新增: if ok != 0 {
74新增: if info.AccessType == 1 {
75新增: return nil, nil
76新增: } // PAC explicitly selected DIRECT.
77新增: if info.Proxy == nil {
78新增: return nil, fmt.Errorf("主机自动代理返回空地址,未切换直连")
79新增: }
80新增: return windowsProxy(req, proxyString(info.Proxy), proxyString(info.Bypass))
81新增: }
82新增: // Windows commonly enables WPAD even when this network has no PAC.
83新增: // An explicitly configured PAC that fails must never become DIRECT.
84新增: if config.URL != nil || err != windows.Errno(12180) {
85新增: return nil, fmt.Errorf("主机 PAC/自动代理解析失败,未切换直连,请检查代理软件:%w", err)
86新增: }
87新增: }
88新增: return windowsProxy(req, proxyString(config.Proxy), proxyString(config.Bypass))
89新增:}
90新增:
91新增:func windowsProxy(req *http.Request, list, bypass string) (*url.URL, error) {
92新增: if list == "" {
93新增: return nil, nil
94新增: }
95新增: var fallback, httpProxy, httpsProxy string
96新增: for _, entry := range strings.Split(list, ";") {
97新增: key, value, specific := strings.Cut(strings.TrimSpace(entry), "=")
98新增: if !specific {
99新增: if fallback == "" {
100新增: fallback = key
101新增: }
102新增: continue
103新增: }
104新增: switch strings.ToLower(key) {
105新增: case "http":
106新增: httpProxy = value
107新增: case "https":
108新增: httpsProxy = value
109新增: case "socks":
110新增: fallback = "socks5://" + value
111新增: }
112新增: }
113新增: if httpProxy == "" {
114新增: httpProxy = fallback
115新增: }
116新增: if httpsProxy == "" {
117新增: httpsProxy = fallback
118新增: }
119新增: return staticProxy(req, httpProxy, httpsProxy, bypass)
120新增:}
新增internal/hostproxy/proxy_windows_test.go+16 −0看文件
@@ -0,0 +1,16 @@
1新增:package hostproxy
2新增:
3新增:import (
4新增: "net/http"
5新增: "testing"
6新增:)
7新增:
8新增:func TestWindowsSystemProxyMapping(t *testing.T) {
9新增: req, _ := http.NewRequest("GET", "https://cloud.debian.org/image", nil)
10新增: for _, list := range []string{"127.0.0.1:7890", "http=127.0.0.1:7891;https=127.0.0.1:7890"} {
11新增: u, err := windowsProxy(req, list, "localhost;127.*")
12新增: if err != nil || u == nil || u.String() != "http://127.0.0.1:7890" {
13新增: t.Fatalf("proxy=%v err=%v", u, err)
14新增: }
15新增: }
16新增:}
新增internal/hostproxy/transport.go+118 −0看文件
@@ -0,0 +1,118 @@
1新增:// Package hostproxy routes host-side system image requests through the host's
2新增:// proxy settings. Guest traffic must continue to use cage.Egress instead.
3新增:package hostproxy
4新增:
5新增:import (
6新增: "errors"
7新增: "net"
8新增: "net/http"
9新增: "net/url"
10新增: "os"
11新增: "strings"
12新增: "sync"
13新增: "time"
14新增:
15新增: "golang.org/x/net/http/httpproxy"
16新增:)
17新增:
18新增:var environment struct {
19新增: sync.Mutex
20新增: config *httpproxy.Config
21新增:}
22新增:
23新增:// CaptureEnvironment preserves host proxy settings before the CLI removes them
24新增:// from child/guest environments. It never restores them to the process env.
25新增:func CaptureEnvironment() {
26新增: environment.Lock()
27新增: defer environment.Unlock()
28新增: if environment.config == nil {
29新增: environment.config = readEnvironment()
30新增: }
31新增:}
32新增:
33新增:func readEnvironment() *httpproxy.Config {
34新增: cfg := httpproxy.FromEnvironment()
35新增: all := os.Getenv("ALL_PROXY")
36新增: if all == "" {
37新增: all = os.Getenv("all_proxy")
38新增: }
39新增: if cfg.HTTPProxy == "" {
40新增: cfg.HTTPProxy = all
41新增: }
42新增: if cfg.HTTPSProxy == "" {
43新增: cfg.HTTPSProxy = all
44新增: }
45新增: return cfg
46新增:}
47新增:
48新增:func NewTransport() *http.Transport {
49新增: environment.Lock()
50新增: cfg := environment.config
51新增: if cfg == nil {
52新增: cfg = readEnvironment()
53新增: }
54新增: copy := *cfg
55新增: environment.Unlock()
56新增: return transport(&copy, systemProxy)
57新增:}
58新增:
59新增:func transport(env *httpproxy.Config, system func(*http.Request) (*url.URL, error)) *http.Transport {
60新增: envProxy := env.ProxyFunc()
61新增: return &http.Transport{
62新增: Proxy: func(req *http.Request) (*url.URL, error) {
63新增: value := env.HTTPProxy
64新增: if req.URL.Scheme == "https" {
65新增: value = env.HTTPSProxy
66新增: }
67新增: if value != "" {
68新增: if _, err := proxyURL(value); err != nil {
69新增: return nil, err
70新增: }
71新增: return envProxy(req.URL)
72新增: }
73新增: return system(req)
74新增: },
75新增: // No interface binding: host TUN/routing rules apply to these sockets.
76新增: DialContext: (&net.Dialer{Timeout: 30 * time.Second, KeepAlive: 30 * time.Second}).DialContext,
77新增: ForceAttemptHTTP2: true, TLSHandshakeTimeout: 15 * time.Second,
78新增: ResponseHeaderTimeout: 30 * time.Second, IdleConnTimeout: 90 * time.Second,
79新增: }
80新增:}
81新增:
82新增:func proxyURL(value string) (*url.URL, error) {
83新增: value = strings.TrimSpace(value)
84新增: if !strings.Contains(value, "://") {
85新增: value = "http://" + value
86新增: }
87新增: u, err := url.Parse(value)
88新增: if err != nil || u.Hostname() == "" {
89新增: return nil, errors.New("主机代理地址无效,请检查系统代理设置")
90新增: }
91新增: switch u.Scheme {
92新增: case "http", "https", "socks5", "socks5h":
93新增: return u, nil
94新增: default:
95新增: return nil, errors.New("主机代理协议不受支持,请使用 HTTP 或 SOCKS5 系统代理")
96新增: }
97新增:}
98新增:
99新增:func staticProxy(req *http.Request, httpProxy, httpsProxy, bypass string) (*url.URL, error) {
100新增: selected := httpProxy
101新增: if req.URL.Scheme == "https" {
102新增: selected = httpsProxy
103新增: }
104新增: if selected != "" {
105新增: if _, err := proxyURL(selected); err != nil {
106新增: return nil, err
107新增: }
108新增: }
109新增: cfg := httpproxy.Config{HTTPProxy: httpProxy, HTTPSProxy: httpsProxy, NoProxy: strings.ReplaceAll(bypass, ";", ",")}
110新增: u, err := cfg.ProxyFunc()(req.URL)
111新增: if err != nil {
112新增: return nil, errors.New("主机代理设置无效,请检查系统代理设置")
113新增: }
114新增: if u != nil {
115新增: return proxyURL(u.String())
116新增: }
117新增: return nil, nil
118新增:}
新增internal/hostproxy/transport_test.go+181 −0看文件
@@ -0,0 +1,181 @@
1新增:package hostproxy
2新增:
3新增:import (
4新增: "bufio"
5新增: "context"
6新增: "errors"
7新增: "io"
8新增: "net"
9新增: "net/http"
10新增: "net/http/httptest"
11新增: "net/url"
12新增: "os"
13新增: "strings"
14新增: "sync/atomic"
15新增: "testing"
16新增: "time"
17新增:
18新增: "golang.org/x/net/http/httpproxy"
19新增:)
20新增:
21新增:func TestHTTPSDownloadUsesHostProxyAndRedirects(t *testing.T) {
22新增: var connects atomic.Int32
23新增: origin := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
24新增: if r.URL.Path == "/first" {
25新增: http.Redirect(w, r, "/image", http.StatusFound)
26新增: return
27新增: }
28新增: io.WriteString(w, "image bytes")
29新增: }))
30新增: defer origin.Close()
31新增: proxy := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
32新增: if r.Method != "CONNECT" || r.Host != "image.invalid:443" {
33新增: t.Errorf("unexpected proxy request: %s %s", r.Method, r.Host)
34新增: http.Error(w, "bad target", 400)
35新增: return
36新增: }
37新增: connects.Add(1)
38新增: upstream, err := net.Dial("tcp", strings.TrimPrefix(origin.URL, "https://"))
39新增: if err != nil {
40新增: t.Error(err)
41新增: return
42新增: }
43新增: defer upstream.Close()
44新增: downstream, buffer, err := w.(http.Hijacker).Hijack()
45新增: if err != nil {
46新增: t.Error(err)
47新增: return
48新增: }
49新增: defer downstream.Close()
50新增: buffer.WriteString("HTTP/1.1 200 Connection Established\r\n\r\n")
51新增: buffer.Flush()
52新增: go io.Copy(upstream, buffer)
53新增: io.Copy(downstream, upstream)
54新增: }))
55新增: defer proxy.Close()
56新增: proxyURL, _ := url.Parse(proxy.URL)
57新增: tr := transport(&httpproxy.Config{}, func(*http.Request) (*url.URL, error) { return proxyURL, nil })
58新增: tr.TLSClientConfig = origin.Client().Transport.(*http.Transport).TLSClientConfig.Clone()
59新增: // The simulated official domain is intentionally unresolvable. TLS still
60新增: // checks the fixture certificate using its original name.
61新增: tr.TLSClientConfig.ServerName = "example.com"
62新增: defer tr.CloseIdleConnections()
63新增: client := &http.Client{Transport: tr, Timeout: 5 * time.Second}
64新增: resp, err := client.Get("https://image.invalid/first")
65新增: if err != nil {
66新增: t.Fatal(err)
67新增: }
68新增: defer resp.Body.Close()
69新增: body, _ := io.ReadAll(resp.Body)
70新增: if string(body) != "image bytes" || connects.Load() == 0 {
71新增: t.Fatalf("body=%q proxy CONNECTs=%d", body, connects.Load())
72新增: }
73新增:}
74新增:
75新增:func TestHostProxyFailureNeverFallsBackToOrigin(t *testing.T) {
76新增: var direct atomic.Int32
77新增: origin := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { direct.Add(1) }))
78新增: defer origin.Close()
79新增: listener, err := net.Listen("tcp", "127.0.0.1:0")
80新增: if err != nil {
81新增: t.Fatal(err)
82新增: }
83新增: dead, _ := url.Parse("http://" + listener.Addr().String())
84新增: listener.Close()
85新增: for _, resolve := range []func(*http.Request) (*url.URL, error){
86新增: func(*http.Request) (*url.URL, error) { return dead, nil },
87新增: func(*http.Request) (*url.URL, error) { return nil, errors.New("PAC failed") },
88新增: } {
89新增: tr := transport(&httpproxy.Config{}, resolve)
90新增: _, err := (&http.Client{Transport: tr, Timeout: time.Second}).Get(origin.URL)
91新增: tr.CloseIdleConnections()
92新增: if err == nil {
93新增: t.Fatal("proxy failure accepted")
94新增: }
95新增: }
96新增: if direct.Load() != 0 {
97新增: t.Fatal("origin contacted after proxy failure")
98新增: }
99新增:}
100新增:
101新增:func TestEnvironmentOverridesAndBypass(t *testing.T) {
102新增: for _, test := range []struct{ address, want string }{{"https://official.invalid/image", "http://127.0.0.1:7890"}, {"https://skip.invalid/image", ""}} {
103新增: tr := transport(&httpproxy.Config{HTTPSProxy: "http://127.0.0.1:7890", NoProxy: "skip.invalid"}, func(*http.Request) (*url.URL, error) { t.Fatal("system proxy used over explicit env"); return nil, nil })
104新增: req, _ := http.NewRequest("GET", test.address, nil)
105新增: got, err := tr.Proxy(req)
106新增: if err != nil {
107新增: t.Fatal(err)
108新增: }
109新增: value := ""
110新增: if got != nil {
111新增: value = got.String()
112新增: }
113新增: if value != test.want {
114新增: t.Fatalf("got %q want %q", value, test.want)
115新增: }
116新增: }
117新增:}
118新增:
119新增:func TestHTTPOnlyEnvironmentKeepsHTTPSSystemProxy(t *testing.T) {
120新增: want, _ := url.Parse("http://127.0.0.1:7896")
121新增: tr := transport(&httpproxy.Config{HTTPProxy: "http://127.0.0.1:7890"}, func(*http.Request) (*url.URL, error) { return want, nil })
122新增: req, _ := http.NewRequest("GET", "https://official.invalid/image", nil)
123新增: got, err := tr.Proxy(req)
124新增: if err != nil || got == nil || got.String() != want.String() {
125新增: t.Fatalf("proxy=%v err=%v", got, err)
126新增: }
127新增:}
128新增:
129新增:// Run manually to verify the real system proxy without changing host settings.
130新增:func TestLiveSystemProxyDownload(t *testing.T) {
131新增: if testing.Short() {
132新增: t.Skip("live check")
133新增: }
134新增: // Opt-in keeps ordinary tests independent of the developer's network.
135新增: if os.Getenv("CAGE_TEST_HOST_PROXY_LIVE") == "" {
136新增: t.Skip("set CAGE_TEST_HOST_PROXY_LIVE=1")
137新增: }
138新增: for _, name := range []string{"HTTP_PROXY", "HTTPS_PROXY", "ALL_PROXY", "http_proxy", "https_proxy", "all_proxy", "NO_PROXY", "no_proxy"} {
139新增: t.Setenv(name, "")
140新增: }
141新增: tr := NewTransport()
142新增: defer tr.CloseIdleConnections()
143新增: req, _ := http.NewRequestWithContext(context.Background(), "GET", "https://cloud.debian.org/images/cloud/bookworm/latest/SHA512SUMS", nil)
144新增: proxy, err := tr.Proxy(req)
145新增: if err != nil || proxy == nil {
146新增: t.Fatalf("system proxy=%v err=%v", proxy, err)
147新增: }
148新增: var peer string
149新增: dial := tr.DialContext
150新增: tr.DialContext = func(ctx context.Context, network, address string) (net.Conn, error) {
151新增: peer = address
152新增: return dial(ctx, network, address)
153新增: }
154新增: resp, err := (&http.Client{Transport: tr, Timeout: 30 * time.Second}).Do(req)
155新增: if err != nil {
156新增: t.Fatal(err)
157新增: }
158新增: defer resp.Body.Close()
159新增: line, err := bufio.NewReader(resp.Body).ReadString('\n')
160新增: if err != nil {
161新增: t.Fatal(err)
162新增: }
163新增: if peer != proxy.Host || resp.StatusCode != 200 || len(line) < 128 {
164新增: t.Fatalf("peer=%s proxy=%s status=%d bytes=%d", peer, proxy.Host, resp.StatusCode, len(line))
165新增: }
166新增: t.Logf("system proxy %s, connected peer %s, official Debian checksum HTTP %d (%d-byte first line)", proxy.Redacted(), peer, resp.StatusCode, len(line))
167新增: if image := os.Getenv("CAGE_TEST_HOST_IMAGE_URL"); image != "" {
168新增: req, _ := http.NewRequest("GET", image, nil)
169新增: req.Header.Set("Range", "bytes=0-65535")
170新增: resp, err := (&http.Client{Transport: tr, Timeout: 30 * time.Second}).Do(req)
171新增: if err != nil {
172新增: t.Fatal(err)
173新增: }
174新增: defer resp.Body.Close()
175新增: count, err := io.Copy(io.Discard, io.LimitReader(resp.Body, 65537))
176新增: if err != nil || resp.StatusCode != 206 || count != 65536 || peer != proxy.Host {
177新增: t.Fatalf("image peer=%s status=%d bytes=%d err=%v", peer, resp.StatusCode, count, err)
178新增: }
179新增: t.Logf("official system image HTTP %d, received %d bytes through %s", resp.StatusCode, count, peer)
180新增: }
181新增:}
修改internal/workbench/guest_install.go+2 −4看文件
@@ -16,6 +16,7 @@ import (
1616 "github.com/sylvinus/agent-vm/internal/guestos"
1717 "github.com/sylvinus/agent-vm/internal/host"
1818 "github.com/sylvinus/agent-vm/internal/hostimage"
19新增: "github.com/sylvinus/agent-vm/internal/hostproxy"
1920)
2021
2122type guestInstallRequest struct {
@@ -291,10 +292,7 @@ func (s *Server) beginGuestInstall(w http.ResponseWriter, r *http.Request, in gu
291292 return fmt.Errorf("创建所选系统至少需要 %d GiB 可用空间,当前有 %d GiB,请在存储设置中选择空间充足的位置", minimumGiB, available)
292293 }
293294 s.setMessage("正在准备 " + guestProgressName(install.System) + " 官方系统镜像…")
294删除: transport, transportErr := s.hostCloneTransport()
295删除: if transportErr != nil {
296删除: return transportErr
297删除: }
295新增: transport := hostproxy.NewTransport()
298296 defer transport.CloseIdleConnections()
299297 prepared, prepareErr := hostimage.Prepare(s.operationContext(), cache, install.Source, s.jobs.execution(), transport)
300298 if prepareErr != nil {
修改internal/workbench/host_clone.go+2 −19看文件
@@ -6,11 +6,10 @@ import (
66 "net/http"
77 "os"
88 "path/filepath"
9删除: "time"
109
11删除: "github.com/sylvinus/agent-vm/internal/cage"
1210 "github.com/sylvinus/agent-vm/internal/host"
1311 "github.com/sylvinus/agent-vm/internal/hostimage"
12新增: "github.com/sylvinus/agent-vm/internal/hostproxy"
1413 "github.com/sylvinus/agent-vm/internal/limaembed"
1514)
1615
@@ -31,27 +30,11 @@ func (s *Server) hostClonePlan(ctx context.Context) (hostimage.Plan, error) {
3130 }
3231 }
3332 cache := filepath.Join(s.profile, "state", "guest-media", identity.System)
34删除: transport, err := s.hostCloneTransport()
35删除: if err != nil {
36删除: return hostimage.Plan{}, err
37删除: }
33新增: transport := hostproxy.NewTransport()
3834 defer transport.CloseIdleConnections()
3935 return hostimage.Resolve(ctx, identity, cache, filepath.Join(home, "Downloads"), template, transport)
4036}
4137
42删除:func (s *Server) hostCloneTransport() (*http.Transport, error) {
43删除: cfg, err := loadConfig(s.configPath)
44删除: if err != nil {
45删除: return nil, err
46删除: }
47删除: egress, err := cage.NewEgress(cfg)
48删除: if err != nil {
49删除: return nil, err
50删除: }
51删除: return &http.Transport{Proxy: nil, DialContext: egress.DialContext, ForceAttemptHTTP2: true,
52删除: TLSHandshakeTimeout: 15 * time.Second, ResponseHeaderTimeout: 30 * time.Second}, nil
53删除:}
54删除:
5538func (s *Server) hostClone(w http.ResponseWriter, r *http.Request) {
5639 if !s.hasTrustedView(r) || !s.localVMStorage() {
5740 http.Error(w, "请在本机 Cage 窗口选择系统创建方式", http.StatusForbidden)
修改internal/workbench/storage.go+22 −1看文件
@@ -4,6 +4,7 @@ import (
44 "errors"
55 "fmt"
66 "net/http"
7新增: "os"
78
89 "github.com/sylvinus/agent-vm/internal/cage"
910 "github.com/sylvinus/agent-vm/internal/containerenv"
@@ -29,7 +30,21 @@ func (s *Server) environmentStorage(w http.ResponseWriter, r *http.Request) {
2930 requestError(w, err)
3031 return
3132 }
32删除: jsonReply(w, location)
33新增: suggested := ""
34新增: if !location.Custom && !location.HasEnvironment {
35新增: initialization, err := s.initializationState()
36新增: if err != nil {
37新增: requestError(w, err)
38新增: return
39新增: }
40新增: if initialization.Required && !initialization.Started && !initialization.Prepared {
41新增: suggested = cage.InitialStorageDirectory(s.exe)
42新增: }
43新增: }
44新增: jsonReply(w, struct {
45新增: cage.StorageLocation
46新增: SuggestedDirectory string `json:"suggested_directory,omitempty"`
47新增: }{location, suggested})
3348 return
3449 }
3550
@@ -53,6 +68,9 @@ func (s *Server) environmentStorage(w http.ResponseWriter, r *http.Request) {
5368 return errors.New("环境或存储位置已改变,请重新打开设置后再选择")
5469 }
5570 if err = cage.ValidateStorageTarget(s.profile, input.Directory); err != nil {
71新增: if errors.Is(err, os.ErrPermission) {
72新增: return errors.New("无法读取或写入所选存储目录,请在当前页面选择有权限的本地文件夹后重试,已有数据已保留")
73新增: }
5674 return err
5775 }
5876 if err = s.validateStoragePlacement(input.Directory); err != nil {
@@ -71,6 +89,9 @@ func (s *Server) environmentStorage(w http.ResponseWriter, r *http.Request) {
7189 _, err = cage.MoveStorageWithRuntime(s.operationContext(), s.profile, input.Directory, current, runtime, func(copied, total int64) {
7290 s.setMessage(fmt.Sprintf("正在迁移环境数据 · %.1f / %.1f GiB", float64(copied)/(1<<30), float64(total)/(1<<30)))
7391 })
92新增: if errors.Is(err, os.ErrPermission) {
93新增: return errors.New("无法写入所选存储目录。请在当前页面选择有写入权限的本地文件夹后重试,已有数据已保留")
94新增: }
7495 return err
7596 })
7697}
修改scripts/package-windows.ps1+1 −0看文件
@@ -16,6 +16,7 @@ if (-not $AppDirectory) { $AppDirectory = Join-Path $repository '_output/windows
1616if (-not $OutputDirectory) { $OutputDirectory = Join-Path $repository "_output/releases/$version/windows" }
1717$AppDirectory = [IO.Path]::GetFullPath($AppDirectory)
1818$OutputDirectory = [IO.Path]::GetFullPath($OutputDirectory)
19新增:if (Test-Path -LiteralPath (Join-Path $AppDirectory 'CageData')) { throw 'App directory contains CageData user data. Package a clean build directory; do not package an installed application.' }
1920if (-not $SkipBuild) { & (Join-Path $PSScriptRoot 'build-windows.ps1') -Release:$Release -Sign:$Sign -OutputDirectory $AppDirectory }
2021if ((Get-Content -LiteralPath (Join-Path $AppDirectory 'Cage.install-id') -Raw) -ne 'io.github.lee-xeo.claude-cage') { throw 'Invalid Cage app directory.' }
2122if ((Get-Content -LiteralPath (Join-Path $AppDirectory 'version.txt') -Raw).Trim() -ne $version) { throw 'App version differs from VERSION; rebuild before packaging.' }
修改scripts/test-windows-installation-files.ps1+14 −0看文件
@@ -74,6 +74,9 @@ try {
7474 Write-File (Join-Path $old 'resources/customizable.txt') 'user customization'
7575 Write-File (Join-Path $scenario 'outside/config.txt') 'outside data'
7676 [IO.Directory]::CreateDirectory((Join-Path $old 'empty-project')) | Out-Null
77新增: foreach ($file in @('state/guest-media/system.img','state/lima/instance/disk','cache/lima/image')) {
78新增: Write-File (Join-Path $old ('CageData/' + $file)) ('persistent-' + $file)
79新增: }
7780 Prepare $old $stage $receipt
7881 Check ((Get-Content (Join-Path $old 'program.txt') -Raw) -eq 'old') 'Preparation modified the original installation.'
7982 $backup = Commit $old $stage $receipt
@@ -84,6 +87,9 @@ try {
8487 $copies = @(Get-ChildItem (Join-Path $old 'Cage-preserved-files') -File -Recurse | Where-Object { (Get-Content $_.FullName -Raw) -eq 'user customization' })
8588 Check ($copies.Count -eq 1) 'Modified same-name program content was not retained exactly once.'
8689 Check (!(Test-Path $backup)) 'Completed transfer left a full old application copy.'
90新增: foreach ($file in @('state/guest-media/system.img','state/lima/instance/disk','cache/lima/image')) {
91新增: Check ((Get-Content (Join-Path $old ('CageData/' + $file)) -Raw) -eq ('persistent-' + $file)) 'Update changed CageData.'
92新增: }
8793 $embedded = Join-Path $scenario 'embedded.json'
8894 Copy-Item (Join-Path $old 'Cage.install-files.json') $embedded
8995 Write-File (Join-Path $old 'resources/customizable.txt') 'new customization'
@@ -93,10 +99,16 @@ try {
9399 Check ((Get-Content (Join-Path $old 'resources/customizable.txt') -Raw) -eq 'new customization') 'Uninstall deleted a modified program file.'
94100 Check (Test-Path (Join-Path $old 'empty-project') -PathType Container) 'Uninstall deleted an unknown empty project.'
95101 Check (Test-Path (Join-Path $old 'Cage.install-id')) 'Retained data directory cannot be recognized on reinstall.'
102新增: foreach ($file in @('state/guest-media/system.img','state/lima/instance/disk','cache/lima/image')) {
103新增: Check ((Get-Content (Join-Path $old ('CageData/' + $file)) -Raw) -eq ('persistent-' + $file)) 'Uninstall changed CageData.'
104新增: }
96105 App $stage 'reinstalled'
97106 Prepare $old $stage $receipt
98107 $null = Commit $old $stage $receipt
99108 Check ((Get-Content (Join-Path $old 'my-project/work.txt') -Raw) -eq 'project data') 'Reinstall after uninstall lost the project.'
109新增: foreach ($file in @('state/guest-media/system.img','state/lima/instance/disk','cache/lima/image')) {
110新增: Check ((Get-Content (Join-Path $old ('CageData/' + $file)) -Raw) -eq ('persistent-' + $file)) 'Reinstall changed CageData.'
111新增: }
100112 }
101113 $scenario = Join-Path $root 'concurrent'
102114 $old = Join-Path $scenario 'installed'; $stage = Join-Path $scenario 'staged'; $receipt = Join-Path $scenario 'receipt.json'
@@ -115,6 +127,7 @@ try {
115127 $old = Join-Path $scenario 'installed'; $stage = Join-Path $scenario 'staged'; $receipt = Join-Path $scenario 'receipt.json'
116128 App $old 'old'; App $stage 'new'
117129 Write-File (Join-Path $old 'project.txt') 'rollback project'
130新增: Write-File (Join-Path $old 'CageData/state/lima/disk') 'rollback disk'
118131 Prepare $old $stage $receipt
119132 $backup = $old + '-backup'
120133 [IO.Directory]::Move($old, $backup)
@@ -124,6 +137,7 @@ try {
124137 Invoke-Helper @('-Operation','complete','-Target',$old,'-Receipt',$receipt)
125138 Check ((Get-Content (Join-Path $old 'project.txt') -Raw) -eq 'rollback project') 'Failed replacement lost the original project.'
126139 Check ((Get-Content (Join-Path $old 'program.txt') -Raw) -eq 'old') 'Failed replacement changed the original program.'
140新增: Check ((Get-Content (Join-Path $old 'CageData/state/lima/disk') -Raw) -eq 'rollback disk') 'Failed replacement changed CageData.'
127141 $stage = Join-Path $scenario 'staged-again'; App $stage 'new'
128142 $locked = [IO.File]::Open((Join-Path $old 'program.txt'), 'Open', 'ReadWrite', 'None')
129143 try { Invoke-Helper @('-Operation','prepare','-Source',$old,'-Target',$stage,'-Receipt',$receipt) 1 }
修改ui/scripts/initialization-smoke.mjs+15 −3看文件
@@ -7,12 +7,22 @@ if (evidence) await fs.mkdir(evidence, { recursive: true });
77
88for (const [platform, system] of [["darwin", "macos"], ["windows", "windows-11"], ["linux", "ubuntu-22.04"]]) {
99 let starts = 0, rejectComplete = true;
10新增: let directory = "/preview/cage-state";
11新增: const initialDirectory = platform === "windows" ? "/preview/Cage/CageData" : directory;
1012 const fixture = await createWorkbench({
1113 initialization: { required: true, tracked: true, started: false },
1214 clientContext: { mode: "local", connection_id: "local", client_platform: platform, server_platform: platform },
1315 beforeNavigate: async (page, state) => {
1416 state.status.local_vm_storage = true;
15删除: await page.route("**/api/environment/storage", route => route.fulfill({ json: { directory: "/preview/cage-state", has_environment: false } }));
17新增: await page.route("**/api/environment/storage", route => {
18新增: if (route.request().method() === "POST") {
19新增: assert.equal(route.request().postDataJSON().previous, directory);
20新增: directory = route.request().postDataJSON().directory;
21新增: state.status.job = { id: "storage-default", kind: "storage", running: false };
22新增: return route.fulfill({ json: state.status.job });
23新增: }
24新增: return route.fulfill({ json: { directory, has_environment: false, suggested_directory: directory === "/preview/cage-state" ? initialDirectory : undefined } });
25新增: });
1626 await page.route("**/api/environment/guest-systems", route => route.fulfill({ json: { fresh: true, available: true, system, linux_systems: ["ubuntu-22.04"] } }));
1727 await page.route("**/api/environment/guest-systems/clone", route => route.fulfill({ json: { key: "matched-image", enough_space: true, minimum_free_gib: 51, free_gib: 120, download_bytes: 19769944180, plan: { host: { system, version: system === "windows-11" ? "25H2" : "26.5", build: "123", edition: "Professional", language: "zh-CN" }, version: "26.5", build: "456", bytes: 19769944180 } } }));
1828 await page.route("**/api/start", route => {
@@ -38,7 +48,8 @@ for (const [platform, system] of [["darwin", "macos"], ["windows", "windows-11"]
3848 const picker = page.getByRole("combobox", { name: "客户机系统" });
3949 const storage = page.getByRole("region", { name: "环境存储目录" });
4050 await storage.getByLabel("存储目录", { exact: true }).waitFor();
41删除: assert.equal(await storage.getByLabel("存储目录", { exact: true }).inputValue(), "/preview/cage-state");
51新增: assert.equal(await storage.getByLabel("存储目录", { exact: true }).inputValue(), initialDirectory);
52新增: await storage.getByText("这是 Cage 的环境数据目录。更新、重装或卸载应用会保留这里的数据;请勿手动删除。").waitFor();
4253 assert.equal(await storage.getByText("当前环境目录", { exact: true }).count(), 0);
4354 assert.equal(await storage.getByText("新存储位置", { exact: true }).count(), 0);
4455 const before = await storage.boundingBox();
@@ -52,7 +63,8 @@ for (const [platform, system] of [["darwin", "macos"], ["windows", "windows-11"]
5263 assert.ok(menu.x >= 0 && menu.y >= 0 && menu.x + menu.width <= 1280 && menu.y + menu.height <= 850, "floating menu must stay inside the viewport");
5364 if (evidence) await page.screenshot({ path: `${evidence}/${platform}-systems-floating.png`, fullPage: true });
5465 await picker.press("Home"); await picker.press("Enter");
55删除: await page.getByText("Cage 会检测本机系统版本。配置代理后匹配官方镜像,并显示下载量与空间要求。").waitFor();
66新增: await page.getByText("Cage 会检测本机系统版本,在下一步显示匹配的官方镜像、下载量与空间要求。").waitFor();
67新增: await page.getByText(/系统镜像通过主机网络下载.*系统代理或 TUN/).waitFor();
5668 if (system === "windows-11") await page.getByRole("checkbox").check();
5769 if (evidence) await page.screenshot({ path: `${evidence}/${platform}-system.png`, fullPage: true });
5870 await page.getByRole("button", { name: "下一步:配置代理" }).click();
修改ui/scripts/installation-preview.mjs+2 −2看文件
@@ -30,7 +30,7 @@ http.createServer(async (req, res) => {
3030 const showProgress = scenario === "progress" || session.installing;
3131 const showFailure = scenario === "failure";
3232 const showReady = scenario === "ready";
33删除: const job = showProgress || showFailure ? { id: "preview-install", kind: "guest-install", running: !showFailure, error: showFailure ? "系统镜像下载中断。请检查代理连接,已下载文件和虚拟磁盘会保留。" : "", message: "正在下载系统镜像", setup_progress: { system, phase: "image", operation: "download", label: `正在下载 ${system === "macos" ? "macOS" : system === "windows-11" ? "Windows 11" : "Ubuntu"} 系统镜像`, received: Math.floor(host.bytes * .43), total: host.bytes, bytes_per_second: 26 * 1048576 }, log: "正在通过所选代理下载官方系统镜像。" } : { running: false };
33新增: const job = showProgress || showFailure ? { id: "preview-install", kind: "guest-install", running: !showFailure, error: showFailure ? "系统镜像下载中断。请检查代理连接,已下载文件和虚拟磁盘会保留。" : "", message: "正在下载系统镜像", setup_progress: { system, phase: "image", operation: "download", label: `正在下载 ${system === "macos" ? "macOS" : system === "windows-11" ? "Windows 11" : "Ubuntu"} 系统镜像`, received: Math.floor(host.bytes * .43), total: host.bytes, bytes_per_second: 26 * 1048576 }, log: "正在通过主机系统代理或 TUN 下载官方系统镜像。" } : { running: false };
3434 const status = { local_vm_storage: true, ready: showReady, vm_running: showReady, safety: showReady ? { gate: { mode: "open", until: new Date(Date.now()+3600000).toISOString() } } : {}, keyboard: host.platform === "darwin" ? "mac" : "native", job, projects: [], environment_workspace: true, environment_directory: "/preview/workspace", workspace: "/preview/workspace" };
3535 const pending = scenario === "resume" ? { version: 1, id: "preview-install", system, source: plan, editor_terms: true } : undefined;
3636 if (url.pathname.startsWith("/api/")) {
@@ -47,7 +47,7 @@ http.createServer(async (req, res) => {
4747 }
4848 value=session;
4949 }
50删除: else if (url.pathname === "/api/environment/storage") value={directory: host.platform === "windows" ? "D:\\CageData" : "/preview/cage-state",has_environment:false};
50新增: else if (url.pathname === "/api/environment/storage") value={directory: host.platform === "windows" ? "D:\\Cage\\CageData" : "/preview/cage-state",has_environment:false};
5151 else if (url.pathname === "/api/settings") value = { workspace: "/preview/workspace", browser_home_url: "https://www.bing.com/", timezone: "Asia/Shanghai", locale: "zh_CN.UTF-8", keyboard: status.keyboard };
5252 else if (url.pathname === "/api/appearance") value = { ...defaultAppearance, mode: "light" };
5353 else if (url.pathname === "/api/proxy") value = { active: true, selected: "preview-node", port: 17896, core_available: true, state: "prepared", sources: [{ id: "preview", name: "预览代理", nodes: [{ id: "preview-node", name: "预览节点", type: "http" }] }] };
修改ui/src/guest-system-picker.jsx+2 −1看文件
@@ -99,7 +99,8 @@ export function GuestSystemPicker({ system, onChange, preserveOnUnmount = false,
9999 <option value="macos" disabled={view.system !== "macos" || !view.available}>macOS{view.system === "macos" ? view.available ? "" : "(暂不可用)" : "(需要 Apple Silicon Mac)"}</option>
100100 <option value="windows-11" disabled={view.system !== "windows-11" || !view.available}>Windows 11{view.system === "windows-11" ? view.available ? "" : "(暂不可用)" : "(需要 Windows 11 与 Hyper-V)"}</option>
101101 </InlineSelect>
102删除: {system.clone && !system.activate && (deferMatch ? <small className="guest-install-fields">Cage 会检测本机系统版本。配置代理后匹配官方镜像,并显示下载量与空间要求。</small> : <HostCloneSummary pending={system.pending} onChange={onChange} />)}
102新增: {system.clone && !system.activate && (deferMatch ? <small className="guest-install-fields">Cage 会检测本机系统版本,在下一步显示匹配的官方镜像、下载量与空间要求。</small> : <HostCloneSummary pending={system.pending} onChange={onChange} />)}
103新增: {!system.activate && <small className="guest-install-fields">系统镜像通过主机网络下载,遵循主机系统代理或 TUN 设置,不使用 Cage 的客机代理。使用 Clash 等软件时,请先开启系统代理或 TUN;代理规则决定镜像网站的实际出口。</small>}
103104 {!system.clone && os !== "debian-13" && !system.activate && <div className="guest-install-fields">
104105 {os === "ubuntu-22.04" ? <>
105106 <small>从 Ubuntu 官方源下载 Ubuntu 22.04 LTS 镜像,并校验 SHA-256。Cage 按主机架构选择 ARM64 或 x86_64。</small>
修改ui/src/initialization-storage.jsx+2 −1看文件
@@ -9,7 +9,7 @@ export function InitializationStorage({ value, onChange, disabled }) {
99 if (value) return;
1010 let live = true;
1111 api("/environment/storage").then(location => {
12删除: if (live) onChange({ location, directory: location.directory });
12新增: if (live) onChange({ location, directory: location.suggested_directory || location.directory });
1313 }).catch(error => { if (live) setError(error.message); });
1414 return () => { live = false; };
1515 }, [Boolean(value), onChange, attempt]);
@@ -23,6 +23,7 @@ export function InitializationStorage({ value, onChange, disabled }) {
2323 return <section className="initialization-storage" aria-label="环境存储目录">
2424 <label htmlFor="initialization-directory">存储目录</label>
2525 <p>系统镜像、下载缓存和虚拟磁盘保存在这里。已填入默认目录,也可以选择其他本地磁盘上的专用空文件夹。</p>
26新增: <p>这是 Cage 的环境数据目录。更新、重装或卸载应用会保留这里的数据;请勿手动删除。</p>
2627 <div className="initialization-directory-control">
2728 <input id="initialization-directory" value={value?.directory || ""} disabled={locked} spellCheck={false} placeholder={value ? "请输入存储目录的完整路径" : "正在读取默认目录…"} onChange={event => onChange({ ...value, directory: event.target.value })} />
2829 {nativeAvailable() && <button type="button" disabled={locked} onClick={choose}><FolderOpen size={16} />选择文件夹</button>}
修改ui/src/initialization.jsx+3 −2看文件
@@ -203,7 +203,7 @@ function Initialization({ initial, onComplete }) {
203203 return <InitializationFrame>
204204 <section className="initialization-content">
205205 <ol className="initialization-steps" aria-label="初始化步骤">{steps.map(([key, label], position) => <li key={key} aria-current={step === key ? "step" : undefined}><span>{position < index ? <Check size={14} /> : position + 1}</span>{label}</li>)}</ol>
206删除: <div className="initialization-title"><h1>{title}</h1><p>{step === "system" ? "选择客机系统和存储位置。初始化完成后,再进入工作台。" : step === "proxy" ? "系统镜像与开发工具通过所选代理下载。配置会保留供环境日常使用。" : ready ? "系统、开发组件和网络检查均已完成,可以进入工作台开始使用。" : "下载、安装、必要授权和检查都在这里完成。中断后可以继续原任务。"}</p></div>
206新增: <div className="initialization-title"><h1>{title}</h1><p>{step === "system" ? "选择客机系统和存储位置。初始化完成后,再进入工作台。" : step === "proxy" ? "这里的代理供客机内的进程和开发工具使用。系统镜像通过主机代理下载,遵循 Clash 等软件的系统代理或 TUN 设置。" : ready ? "系统、开发组件和网络检查均已完成,可以进入工作台开始使用。" : "下载、安装、必要授权和检查都在这里完成。中断后可以继续原任务。"}</p></div>
207207 {connectionError && <div className="initialization-notice" role="alert"><SafetyMessage message={connectionError} /><button onClick={() => pollNow.current?.()}>重新连接</button></div>}
208208 {!status ? <p role="status"><LoaderCircle size={18} className="spin" />正在读取安装状态…</p> : <>
209209 <div className="initialization-stage" key={step}>
@@ -216,7 +216,8 @@ function Initialization({ initial, onComplete }) {
216216 {progress ? <SetupProgress job={progress} onDetails={() => setDetails(true)} onStop={stop} onRetry={install} disconnected={Boolean(connectionError) || submitting} /> : <div className="initialization-operation" role="status">{busy && <LoaderCircle size={22} className="spin" />}<p>{job.message || (status.vm_running ? "请完成客机连接和网络检查。" : "准备继续原安装,已有文件和磁盘会保留。")}</p>{!busy && !job.error && <button className="primary" disabled={Boolean(connectionError)} onClick={install}>{status.ready ? "重新启动并检查" : "继续安装"}</button>}{busy && <button onClick={stop} disabled={submitting}>停止安装</button>}</div>}
217217 {job.error && !progress && <div className="initialization-notice" role="alert"><SafetyMessage message={job.error} /><button className="primary" disabled={busy || Boolean(connectionError)} onClick={install}>继续安装</button></div>}
218218 {status.ready && network.mode !== "open" && !busy && <div className="initialization-network"><p>{status.network_error || status.safety?.error || "客机已经连接,请完成网络和隔离检查后进入工作台。"}</p><button className="primary" disabled={Boolean(connectionError)} onClick={checkNetwork}>运行网络与隔离检查</button></div>}
219删除: <div className="initialization-recovery"><button onClick={() => setStep("proxy")} disabled={busy}>检查代理配置</button>{!progress && <button onClick={() => setDetails(true)}>查看操作详情</button>}</div>
219新增: {(progress?.setup_progress.phase === "image" || failed) && <p>系统镜像下载使用主机代理;下载失败请检查 Clash 等主机代理软件。客机联网与开发工具使用 Cage 代理。</p>}
220新增: <div className="initialization-recovery"><button onClick={() => setStep("proxy")} disabled={busy}>检查 Cage 代理配置</button>{!progress && <button onClick={() => setDetails(true)}>查看操作详情</button>}</div>
220221 </>)}
221222 </div>
222223 {git && <section className="initialization-notice" aria-label="Git 安全保护"><h2>安装前,保护本机 Git</h2><p>{git.message}</p>{git.can_enable && <><p>启用后,Git 会忽略未经你明确指定的裸仓库。该操作会修改当前用户的全局设置,影响本机其他 Git 工具,普通项目保持原有操作。</p><pre>git config --global safe.bareRepository explicit</pre><button className="primary" disabled={busy} onClick={enableGit}>启用 Git 保护</button></>}<button disabled={busy} onClick={install}>重新检查并安装</button></section>}