提交记录修改cmd/cage/mac_guest_download_darwin_arm64.go+112 −9看文件
修改cmd/cage/mac_guest_download_darwin_arm64_test.go+4 −17看文件
修改cmd/cage/main.go+8 −8看文件
修改docs/guide/installation.md+7 −1看文件
修改docs/guide/network.md+12 −0看文件
修改internal/cage/storage.go+14 −5看文件
新增internal/cage/storage_default.go+39 −0看文件
新增internal/cage/storage_default_test.go+45 −0看文件
新增internal/hostproxy/proxy_darwin.go+118 −0看文件
新增internal/hostproxy/proxy_darwin_nocgo.go+13 −0看文件
新增internal/hostproxy/proxy_darwin_test.go+89 −0看文件
新增internal/hostproxy/proxy_linux.go+77 −0看文件
新增internal/hostproxy/proxy_linux_test.go+17 −0看文件
新增internal/hostproxy/proxy_other.go+11 −0看文件
新增internal/hostproxy/proxy_windows.go+120 −0看文件
新增internal/hostproxy/proxy_windows_test.go+16 −0看文件
新增internal/hostproxy/transport.go+118 −0看文件
新增internal/hostproxy/transport_test.go+181 −0看文件
修改internal/workbench/guest_install.go+2 −4看文件
修改internal/workbench/host_clone.go+2 −19看文件
修改internal/workbench/storage.go+22 −1看文件
修改scripts/package-windows.ps1+1 −0看文件
修改scripts/test-windows-installation-files.ps1+14 −0看文件
修改ui/scripts/initialization-smoke.mjs+15 −3看文件
修改ui/scripts/installation-preview.mjs+2 −2看文件
修改ui/src/guest-system-picker.jsx+2 −1看文件
修改ui/src/initialization-storage.jsx+2 −1看文件
修改ui/src/initialization.jsx+3 −2看文件
| @@ -9,22 +9,34 @@ import ( | ||
| 9 | 9 | "errors" |
| 10 | 10 | "fmt" |
| 11 | 11 | "io" |
| 12 | 新增: "net/http" | |
| 12 | 13 | "os" |
| 13 | 删除: "os/exec" | |
| 14 | 新增: "strings" | |
| 14 | 15 | "time" |
| 16 | 新增: | |
| 17 | 新增: "github.com/sylvinus/agent-vm/internal/hostproxy" | |
| 15 | 18 | ) |
| 16 | 19 | |
| 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. | |
| 19 | 20 | func 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 { | |
| 20 | 27 | if _, err := os.Stat(media); err == nil { |
| 21 | 28 | return verifyMacRestoreMedia(ctx, media, digest, out) |
| 22 | 29 | } else if !errors.Is(err, os.ErrNotExist) { |
| 23 | 30 | return err |
| 24 | 31 | } |
| 25 | 32 | 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() | |
| 28 | 40 | report := func() { |
| 29 | 41 | var received int64 |
| 30 | 42 | if info, err := os.Stat(partial); err == nil { |
| @@ -33,11 +45,17 @@ func prepareMacRestoreMedia(ctx context.Context, media, url, digest string, tota | ||
| 33 | 45 | fmt.Fprintf(out, "CAGE_GUEST_BYTES macos download %d %d\n", received, total) |
| 34 | 46 | } |
| 35 | 47 | report() |
| 36 | 删除: if err := cmd.Start(); err != nil { | |
| 37 | 删除: return err | |
| 38 | 删除: } | |
| 39 | 48 | 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 | 新增: }() | |
| 41 | 59 | ticker := time.NewTicker(time.Second) |
| 42 | 60 | defer ticker.Stop() |
| 43 | 61 | for { |
| @@ -64,6 +82,91 @@ func prepareMacRestoreMedia(ctx context.Context, media, url, digest string, tota | ||
| 64 | 82 | } |
| 65 | 83 | } |
| 66 | 84 | |
| 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 | 新增: | |
| 67 | 170 | func verifyMacRestoreMedia(ctx context.Context, media, digest string, out io.Writer) error { |
| 68 | 171 | file, err := os.Open(media) |
| 69 | 172 | if err != nil { |
| @@ -7,7 +7,6 @@ import ( | ||
| 7 | 7 | "context" |
| 8 | 8 | "crypto/sha256" |
| 9 | 9 | "encoding/hex" |
| 10 | 删除: "encoding/pem" | |
| 11 | 10 | "errors" |
| 12 | 11 | "fmt" |
| 13 | 12 | "net/http" |
| @@ -19,15 +18,6 @@ import ( | ||
| 19 | 18 | "time" |
| 20 | 19 | ) |
| 21 | 20 | |
| 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 | 删除: | |
| 31 | 21 | func TestMacRestoreDownloadResumesAndReportsVerification(t *testing.T) { |
| 32 | 22 | body := bytes.Repeat([]byte("restore-image"), 10000) |
| 33 | 23 | offset := len(body) / 3 |
| @@ -42,14 +32,13 @@ func TestMacRestoreDownloadResumesAndReportsVerification(t *testing.T) { | ||
| 42 | 32 | _, _ = w.Write(body[offset:]) |
| 43 | 33 | })) |
| 44 | 34 | defer server.Close() |
| 45 | 删除: trustRestoreServer(t, server) | |
| 46 | 35 | media := filepath.Join(t.TempDir(), "MacOS.ipsw") |
| 47 | 36 | if err := os.WriteFile(media+".partial", body[:offset], 0600); err != nil { |
| 48 | 37 | t.Fatal(err) |
| 49 | 38 | } |
| 50 | 39 | hash := sha256.Sum256(body) |
| 51 | 40 | 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 { | |
| 53 | 42 | t.Fatal(err) |
| 54 | 43 | } |
| 55 | 44 | actual, err := os.ReadFile(media) |
| @@ -66,7 +55,7 @@ func TestMacRestoreDownloadResumesAndReportsVerification(t *testing.T) { | ||
| 66 | 55 | } |
| 67 | 56 | log.Reset() |
| 68 | 57 | // 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 { | |
| 70 | 59 | t.Fatal(err) |
| 71 | 60 | } |
| 72 | 61 | if strings.Contains(log.String(), "macos download") { |
| @@ -81,13 +70,12 @@ func TestMacRestoreCancelledDownloadKeepsPartial(t *testing.T) { | ||
| 81 | 70 | <-r.Context().Done() |
| 82 | 71 | })) |
| 83 | 72 | defer server.Close() |
| 84 | 删除: trustRestoreServer(t, server) | |
| 85 | 73 | media := filepath.Join(t.TempDir(), "MacOS.ipsw") |
| 86 | 74 | ctx, cancel := context.WithCancel(t.Context()) |
| 87 | 75 | defer cancel() |
| 88 | 76 | done := make(chan error, 1) |
| 89 | 77 | 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) | |
| 91 | 79 | }() |
| 92 | 80 | deadline := time.After(5 * time.Second) |
| 93 | 81 | ticker := time.NewTicker(10 * time.Millisecond) |
| @@ -119,9 +107,8 @@ func TestMacRestoreCancelledDownloadKeepsPartial(t *testing.T) { | ||
| 119 | 107 | func TestMacRestoreDigestFailureDoesNotPublishMedia(t *testing.T) { |
| 120 | 108 | server := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { _, _ = w.Write([]byte("invalid restore")) })) |
| 121 | 109 | defer server.Close() |
| 122 | 删除: trustRestoreServer(t, server) | |
| 123 | 110 | 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 { | |
| 125 | 112 | t.Fatal("invalid digest accepted") |
| 126 | 113 | } |
| 127 | 114 | for _, p := range []string{media, media + ".partial"} { |
| @@ -21,6 +21,7 @@ import ( | ||
| 21 | 21 | "github.com/sylvinus/agent-vm/internal/diagnostics" |
| 22 | 22 | "github.com/sylvinus/agent-vm/internal/guestos" |
| 23 | 23 | "github.com/sylvinus/agent-vm/internal/host" |
| 24 | 新增: "github.com/sylvinus/agent-vm/internal/hostproxy" | |
| 24 | 25 | "github.com/sylvinus/agent-vm/internal/limaembed" |
| 25 | 26 | "github.com/sylvinus/agent-vm/internal/managedproxy" |
| 26 | 27 | "github.com/sylvinus/agent-vm/internal/workbench" |
| @@ -75,6 +76,7 @@ func main() { | ||
| 75 | 76 | os.Exit(code) |
| 76 | 77 | } |
| 77 | 78 | func run() int { |
| 79 | 新增: hostproxy.CaptureEnvironment() | |
| 78 | 80 | // Apply this before desktop/serve dispatch: the control service and every |
| 79 | 81 | // child process must keep Cage's isolation even when launched from a shell |
| 80 | 82 | // configured to relax agent-vm's protections. |
| @@ -473,6 +475,9 @@ func run() int { | ||
| 473 | 475 | return fail(err) |
| 474 | 476 | } |
| 475 | 477 | 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")) | |
| 476 | 481 | if location.Custom { |
| 477 | 482 | // Resolve the profile prefix once, as Lima did before migration. |
| 478 | 483 | // Keep state itself logical so its original disk and socket paths survive. |
| @@ -481,7 +486,6 @@ func run() int { | ||
| 481 | 486 | return fail(err) |
| 482 | 487 | } |
| 483 | 488 | state = filepath.Join(realProfile, "state") |
| 484 | 删除: os.Setenv("CAGE_LIMA_CACHE_DIR", filepath.Join(location.Directory, "cache", "lima")) | |
| 485 | 489 | os.Setenv("CAGE_LOGICAL_LIMA_HOME", filepath.Join(state, "lima")) |
| 486 | 490 | } |
| 487 | 491 | } |
| @@ -491,6 +495,9 @@ func run() int { | ||
| 491 | 495 | 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"} { |
| 492 | 496 | os.Unsetenv(name) |
| 493 | 497 | } |
| 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() | |
| 494 | 501 | if limaembed.Run(args) { |
| 495 | 502 | return 0 |
| 496 | 503 | } |
| @@ -541,13 +548,6 @@ func run() int { | ||
| 541 | 548 | return fail(err) |
| 542 | 549 | } |
| 543 | 550 | |
| 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} | |
| 551 | 551 | if args[0] == "check" { |
| 552 | 552 | e, err := cage.NewEgress(cfg) |
| 553 | 553 | if err != nil { |
| @@ -36,10 +36,14 @@ Windows ARM64 和 Linux ARM64 暂不支持。平台依赖详情见 [Windows 指 | ||
| 36 | 36 | |
| 37 | 37 | ## 初始化系统与存储 |
| 38 | 38 | |
| 39 | 删除:首次登录后,Cage 显示独立的初始化界面。先选择适合项目的客机系统,可选择“自动匹配本机系统版本”或具体系统。自动匹配会在代理配置后获取对应的官方镜像,安装干净的独立系统,主机个人文件与登录资料不会复制。以后启动沿用原系统和磁盘,更新 Cage 不会替换客机系统。 | |
| 39 | 新增:首次登录后,Cage 显示独立的初始化界面。先选择适合项目的客机系统,可选择“自动匹配本机系统版本”或具体系统。自动匹配在下一步显示对应的官方镜像,安装干净的独立系统,主机个人文件与登录资料不会复制。以后启动沿用原系统和磁盘,更新 Cage 不会替换客机系统。 | |
| 40 | 40 | |
| 41 | 41 | “存储目录”已填入默认位置。需要更换时直接编辑,或点击“选择文件夹”选定本地磁盘上的专用空文件夹;点击“下一步:配置代理”时保存,目录无效时留在当前页提示修改。Windows 安装器里的程序目录与环境数据目录分开;例如应用装在 C 盘,环境可放在 `D:\CageData`。 |
| 42 | 42 | |
| 43 | 新增:Mac、Linux 使用默认配置时,环境数据放在用户主目录的 `.claude-cage/state`。Windows 正式安装版在首次初始化时,默认填入安装目录下的 `CageData`,例如应用装在 `D:\Cage`,环境数据就放在 `D:\Cage\CageData`;没有写入权限时,在当前字段选择其他有权限的本地文件夹。已有环境继续使用原存储位置,不会自动迁移。账户与配置仍保存在用户目录的 `.claude-cage`。 | |
| 44 | 新增: | |
| 45 | 新增:初始化页显示本机完整路径。系统镜像、后续镜像下载缓存与持久虚拟磁盘使用同一存储位置;旧版本已留在系统缓存目录的文件不自动移动或删除。更新、重装与卸载应用保留环境数据目录,重新安装后可以继续使用已有数据。不要手动删除这个目录。 | |
| 46 | 新增: | |
| 43 | 47 | 选择支持权限管理与稀疏文件的磁盘:Windows 可用 NTFS,Linux 可用 ext4 / XFS / Btrfs,macOS 使用已启用所有权的 APFS。不要选择磁盘根目录、网络盘、已有项目或应用安装目录。已有环境换盘请按[存储迁移](maintenance.md#迁移环境到另一块磁盘)操作。 |
| 44 | 48 | |
| 45 | 49 | ## 导入代理并启动 |
| @@ -56,6 +60,8 @@ Git 保护会修改当前主机用户的全局 `safe.bareRepository=explicit`, | ||
| 56 | 60 | |
| 57 | 61 | 首次安装内容取决于客机系统。克隆入口优先复用已校验的匹配材料,缺少时下载官方镜像。macOS 使用 Apple IPSW;Windows 克隆使用匹配的 Microsoft ESD,手动安装可选择官方 ISO;Linux 克隆使用对应发行版的云镜像。Debian 13 基础镜像约 320–325 MiB,开发工具另行安装。镜像来源、系统许可和存储要求见[客机系统指南](guest-systems.md#下载量与磁盘空间)。 |
| 58 | 62 | |
| 63 | 新增:系统镜像与镜像版本目录通过主机网络下载,遵循主机代理设置,不使用 Cage 为客机选择的节点。使用 Clash 等软件时,先开启其系统代理或 TUN;实际出口仍由该软件对镜像网站的规则决定。已选择的主机代理连接失败、明确配置的 PAC 解析失败时,下载会报错,保留已有文件,不自动回退直连。客机内的进程和开发工具继续使用 Cage 的独立代理,具体平台设置见[系统镜像的下载网络](network.md#系统镜像的下载网络)。 | |
| 64 | 新增: | |
| 59 | 65 | Debian 初始虚拟磁盘容量上限为 24 GiB,macOS 和 Windows 需为系统及开发工具留出更多空间。实际占用随安装和使用增加,创建前查看所选版本的要求。Claude Desktop 按需单独下载。随后启动会复用工具、文件与登录资料。 |
| 60 | 66 | |
| 61 | 67 | 下载中断时查看错误,修复网络或磁盘空间后点“继续安装”。已保留的文件会尝试续传;摘要不符时必须重新下载。不要通过清空 `.claude-cage` 或重建账户解决安装失败。 |
| @@ -59,6 +59,18 @@ Hysteria2 节点可使用 `mport` 指定端口跳跃范围、`pinSHA256` 指定 | ||
| 59 | 59 | <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> |
| 60 | 60 | </figure> |
| 61 | 61 | |
| 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 | 新增: | |
| 62 | 74 | ## 时区、语言与出口规则 |
| 63 | 75 | |
| 64 | 76 | 在“设置 → 时区与语言”选择跟随出口或手动设置。自动模式通过代理查询出口位置,不使用主机位置替代。位置服务失败时可重试或切换节点;手动设置时区和语言仍须确认出口国家或地区。 |
| @@ -124,7 +124,7 @@ func StoragePathsOverlap(a, b string) bool { | ||
| 124 | 124 | return StorageContains(a, b) || StorageContains(b, a) |
| 125 | 125 | } |
| 126 | 126 | |
| 127 | 删除:// Upgrades replace the entire application folder including its resources. | |
| 127 | 新增:// Resolve the application folder, including macOS bundles and Windows resources. | |
| 128 | 128 | func runningApplicationDir() (string, error) { |
| 129 | 129 | exe, err := os.Executable() |
| 130 | 130 | if err != nil { |
| @@ -306,6 +306,14 @@ func openStorageLockWithRuntime(ctx context.Context, profile string, exclusive b | ||
| 306 | 306 | } |
| 307 | 307 | |
| 308 | 308 | func 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 { | |
| 309 | 317 | if _, err := os.Readlink(storageAnchor(profile)); err == nil { |
| 310 | 318 | r, err := readStorageRecord(profile) |
| 311 | 319 | if err != nil { |
| @@ -350,11 +358,12 @@ func ValidateStorageTarget(profile, directory string) error { | ||
| 350 | 358 | return err |
| 351 | 359 | } |
| 352 | 360 | 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) | |
| 356 | 366 | } |
| 357 | 删除: private = append(private, app) | |
| 358 | 367 | for _, p := range private { |
| 359 | 368 | real, e := StoragePhysicalPath(p) |
| 360 | 369 | if e != nil && !errors.Is(e, os.ErrNotExist) { |
| @@ -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 | 新增:} | |
| @@ -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 | 新增:} | |
| @@ -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 | 新增:} | |
| @@ -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 | 新增:} | |
| @@ -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 | 新增:} | |
| @@ -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 | 新增:} | |
| @@ -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 | 新增:} | |
| @@ -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 } | |
| @@ -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 | 新增:} | |
| @@ -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 | 新增:} | |
| @@ -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(©, 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 | 新增:} | |
| @@ -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 | 新增:} | |
| @@ -16,6 +16,7 @@ import ( | ||
| 16 | 16 | "github.com/sylvinus/agent-vm/internal/guestos" |
| 17 | 17 | "github.com/sylvinus/agent-vm/internal/host" |
| 18 | 18 | "github.com/sylvinus/agent-vm/internal/hostimage" |
| 19 | 新增: "github.com/sylvinus/agent-vm/internal/hostproxy" | |
| 19 | 20 | ) |
| 20 | 21 | |
| 21 | 22 | type guestInstallRequest struct { |
| @@ -291,10 +292,7 @@ func (s *Server) beginGuestInstall(w http.ResponseWriter, r *http.Request, in gu | ||
| 291 | 292 | return fmt.Errorf("创建所选系统至少需要 %d GiB 可用空间,当前有 %d GiB,请在存储设置中选择空间充足的位置", minimumGiB, available) |
| 292 | 293 | } |
| 293 | 294 | s.setMessage("正在准备 " + guestProgressName(install.System) + " 官方系统镜像…") |
| 294 | 删除: transport, transportErr := s.hostCloneTransport() | |
| 295 | 删除: if transportErr != nil { | |
| 296 | 删除: return transportErr | |
| 297 | 删除: } | |
| 295 | 新增: transport := hostproxy.NewTransport() | |
| 298 | 296 | defer transport.CloseIdleConnections() |
| 299 | 297 | prepared, prepareErr := hostimage.Prepare(s.operationContext(), cache, install.Source, s.jobs.execution(), transport) |
| 300 | 298 | if prepareErr != nil { |
| @@ -6,11 +6,10 @@ import ( | ||
| 6 | 6 | "net/http" |
| 7 | 7 | "os" |
| 8 | 8 | "path/filepath" |
| 9 | 删除: "time" | |
| 10 | 9 | |
| 11 | 删除: "github.com/sylvinus/agent-vm/internal/cage" | |
| 12 | 10 | "github.com/sylvinus/agent-vm/internal/host" |
| 13 | 11 | "github.com/sylvinus/agent-vm/internal/hostimage" |
| 12 | 新增: "github.com/sylvinus/agent-vm/internal/hostproxy" | |
| 14 | 13 | "github.com/sylvinus/agent-vm/internal/limaembed" |
| 15 | 14 | ) |
| 16 | 15 | |
| @@ -31,27 +30,11 @@ func (s *Server) hostClonePlan(ctx context.Context) (hostimage.Plan, error) { | ||
| 31 | 30 | } |
| 32 | 31 | } |
| 33 | 32 | 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() | |
| 38 | 34 | defer transport.CloseIdleConnections() |
| 39 | 35 | return hostimage.Resolve(ctx, identity, cache, filepath.Join(home, "Downloads"), template, transport) |
| 40 | 36 | } |
| 41 | 37 | |
| 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 | 删除: | |
| 55 | 38 | func (s *Server) hostClone(w http.ResponseWriter, r *http.Request) { |
| 56 | 39 | if !s.hasTrustedView(r) || !s.localVMStorage() { |
| 57 | 40 | http.Error(w, "请在本机 Cage 窗口选择系统创建方式", http.StatusForbidden) |
| @@ -4,6 +4,7 @@ import ( | ||
| 4 | 4 | "errors" |
| 5 | 5 | "fmt" |
| 6 | 6 | "net/http" |
| 7 | 新增: "os" | |
| 7 | 8 | |
| 8 | 9 | "github.com/sylvinus/agent-vm/internal/cage" |
| 9 | 10 | "github.com/sylvinus/agent-vm/internal/containerenv" |
| @@ -29,7 +30,21 @@ func (s *Server) environmentStorage(w http.ResponseWriter, r *http.Request) { | ||
| 29 | 30 | requestError(w, err) |
| 30 | 31 | return |
| 31 | 32 | } |
| 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}) | |
| 33 | 48 | return |
| 34 | 49 | } |
| 35 | 50 | |
| @@ -53,6 +68,9 @@ func (s *Server) environmentStorage(w http.ResponseWriter, r *http.Request) { | ||
| 53 | 68 | return errors.New("环境或存储位置已改变,请重新打开设置后再选择") |
| 54 | 69 | } |
| 55 | 70 | if err = cage.ValidateStorageTarget(s.profile, input.Directory); err != nil { |
| 71 | 新增: if errors.Is(err, os.ErrPermission) { | |
| 72 | 新增: return errors.New("无法读取或写入所选存储目录,请在当前页面选择有权限的本地文件夹后重试,已有数据已保留") | |
| 73 | 新增: } | |
| 56 | 74 | return err |
| 57 | 75 | } |
| 58 | 76 | if err = s.validateStoragePlacement(input.Directory); err != nil { |
| @@ -71,6 +89,9 @@ func (s *Server) environmentStorage(w http.ResponseWriter, r *http.Request) { | ||
| 71 | 89 | _, err = cage.MoveStorageWithRuntime(s.operationContext(), s.profile, input.Directory, current, runtime, func(copied, total int64) { |
| 72 | 90 | s.setMessage(fmt.Sprintf("正在迁移环境数据 · %.1f / %.1f GiB", float64(copied)/(1<<30), float64(total)/(1<<30))) |
| 73 | 91 | }) |
| 92 | 新增: if errors.Is(err, os.ErrPermission) { | |
| 93 | 新增: return errors.New("无法写入所选存储目录。请在当前页面选择有写入权限的本地文件夹后重试,已有数据已保留") | |
| 94 | 新增: } | |
| 74 | 95 | return err |
| 75 | 96 | }) |
| 76 | 97 | } |
| @@ -16,6 +16,7 @@ if (-not $AppDirectory) { $AppDirectory = Join-Path $repository '_output/windows | ||
| 16 | 16 | if (-not $OutputDirectory) { $OutputDirectory = Join-Path $repository "_output/releases/$version/windows" } |
| 17 | 17 | $AppDirectory = [IO.Path]::GetFullPath($AppDirectory) |
| 18 | 18 | $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.' } | |
| 19 | 20 | if (-not $SkipBuild) { & (Join-Path $PSScriptRoot 'build-windows.ps1') -Release:$Release -Sign:$Sign -OutputDirectory $AppDirectory } |
| 20 | 21 | if ((Get-Content -LiteralPath (Join-Path $AppDirectory 'Cage.install-id') -Raw) -ne 'io.github.lee-xeo.claude-cage') { throw 'Invalid Cage app directory.' } |
| 21 | 22 | if ((Get-Content -LiteralPath (Join-Path $AppDirectory 'version.txt') -Raw).Trim() -ne $version) { throw 'App version differs from VERSION; rebuild before packaging.' } |
| @@ -74,6 +74,9 @@ try { | ||
| 74 | 74 | Write-File (Join-Path $old 'resources/customizable.txt') 'user customization' |
| 75 | 75 | Write-File (Join-Path $scenario 'outside/config.txt') 'outside data' |
| 76 | 76 | [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 | 新增: } | |
| 77 | 80 | Prepare $old $stage $receipt |
| 78 | 81 | Check ((Get-Content (Join-Path $old 'program.txt') -Raw) -eq 'old') 'Preparation modified the original installation.' |
| 79 | 82 | $backup = Commit $old $stage $receipt |
| @@ -84,6 +87,9 @@ try { | ||
| 84 | 87 | $copies = @(Get-ChildItem (Join-Path $old 'Cage-preserved-files') -File -Recurse | Where-Object { (Get-Content $_.FullName -Raw) -eq 'user customization' }) |
| 85 | 88 | Check ($copies.Count -eq 1) 'Modified same-name program content was not retained exactly once.' |
| 86 | 89 | 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 | 新增: } | |
| 87 | 93 | $embedded = Join-Path $scenario 'embedded.json' |
| 88 | 94 | Copy-Item (Join-Path $old 'Cage.install-files.json') $embedded |
| 89 | 95 | Write-File (Join-Path $old 'resources/customizable.txt') 'new customization' |
| @@ -93,10 +99,16 @@ try { | ||
| 93 | 99 | Check ((Get-Content (Join-Path $old 'resources/customizable.txt') -Raw) -eq 'new customization') 'Uninstall deleted a modified program file.' |
| 94 | 100 | Check (Test-Path (Join-Path $old 'empty-project') -PathType Container) 'Uninstall deleted an unknown empty project.' |
| 95 | 101 | 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 | 新增: } | |
| 96 | 105 | App $stage 'reinstalled' |
| 97 | 106 | Prepare $old $stage $receipt |
| 98 | 107 | $null = Commit $old $stage $receipt |
| 99 | 108 | 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 | 新增: } | |
| 100 | 112 | } |
| 101 | 113 | $scenario = Join-Path $root 'concurrent' |
| 102 | 114 | $old = Join-Path $scenario 'installed'; $stage = Join-Path $scenario 'staged'; $receipt = Join-Path $scenario 'receipt.json' |
| @@ -115,6 +127,7 @@ try { | ||
| 115 | 127 | $old = Join-Path $scenario 'installed'; $stage = Join-Path $scenario 'staged'; $receipt = Join-Path $scenario 'receipt.json' |
| 116 | 128 | App $old 'old'; App $stage 'new' |
| 117 | 129 | Write-File (Join-Path $old 'project.txt') 'rollback project' |
| 130 | 新增: Write-File (Join-Path $old 'CageData/state/lima/disk') 'rollback disk' | |
| 118 | 131 | Prepare $old $stage $receipt |
| 119 | 132 | $backup = $old + '-backup' |
| 120 | 133 | [IO.Directory]::Move($old, $backup) |
| @@ -124,6 +137,7 @@ try { | ||
| 124 | 137 | Invoke-Helper @('-Operation','complete','-Target',$old,'-Receipt',$receipt) |
| 125 | 138 | Check ((Get-Content (Join-Path $old 'project.txt') -Raw) -eq 'rollback project') 'Failed replacement lost the original project.' |
| 126 | 139 | 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.' | |
| 127 | 141 | $stage = Join-Path $scenario 'staged-again'; App $stage 'new' |
| 128 | 142 | $locked = [IO.File]::Open((Join-Path $old 'program.txt'), 'Open', 'ReadWrite', 'None') |
| 129 | 143 | try { Invoke-Helper @('-Operation','prepare','-Source',$old,'-Target',$stage,'-Receipt',$receipt) 1 } |
| @@ -7,12 +7,22 @@ if (evidence) await fs.mkdir(evidence, { recursive: true }); | ||
| 7 | 7 | |
| 8 | 8 | for (const [platform, system] of [["darwin", "macos"], ["windows", "windows-11"], ["linux", "ubuntu-22.04"]]) { |
| 9 | 9 | let starts = 0, rejectComplete = true; |
| 10 | 新增: let directory = "/preview/cage-state"; | |
| 11 | 新增: const initialDirectory = platform === "windows" ? "/preview/Cage/CageData" : directory; | |
| 10 | 12 | const fixture = await createWorkbench({ |
| 11 | 13 | initialization: { required: true, tracked: true, started: false }, |
| 12 | 14 | clientContext: { mode: "local", connection_id: "local", client_platform: platform, server_platform: platform }, |
| 13 | 15 | beforeNavigate: async (page, state) => { |
| 14 | 16 | 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 | 新增: }); | |
| 16 | 26 | await page.route("**/api/environment/guest-systems", route => route.fulfill({ json: { fresh: true, available: true, system, linux_systems: ["ubuntu-22.04"] } })); |
| 17 | 27 | 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 } } })); |
| 18 | 28 | await page.route("**/api/start", route => { |
| @@ -38,7 +48,8 @@ for (const [platform, system] of [["darwin", "macos"], ["windows", "windows-11"] | ||
| 38 | 48 | const picker = page.getByRole("combobox", { name: "客户机系统" }); |
| 39 | 49 | const storage = page.getByRole("region", { name: "环境存储目录" }); |
| 40 | 50 | 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(); | |
| 42 | 53 | assert.equal(await storage.getByText("当前环境目录", { exact: true }).count(), 0); |
| 43 | 54 | assert.equal(await storage.getByText("新存储位置", { exact: true }).count(), 0); |
| 44 | 55 | const before = await storage.boundingBox(); |
| @@ -52,7 +63,8 @@ for (const [platform, system] of [["darwin", "macos"], ["windows", "windows-11"] | ||
| 52 | 63 | 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"); |
| 53 | 64 | if (evidence) await page.screenshot({ path: `${evidence}/${platform}-systems-floating.png`, fullPage: true }); |
| 54 | 65 | 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(); | |
| 56 | 68 | if (system === "windows-11") await page.getByRole("checkbox").check(); |
| 57 | 69 | if (evidence) await page.screenshot({ path: `${evidence}/${platform}-system.png`, fullPage: true }); |
| 58 | 70 | await page.getByRole("button", { name: "下一步:配置代理" }).click(); |
| @@ -30,7 +30,7 @@ http.createServer(async (req, res) => { | ||
| 30 | 30 | const showProgress = scenario === "progress" || session.installing; |
| 31 | 31 | const showFailure = scenario === "failure"; |
| 32 | 32 | 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 }; | |
| 34 | 34 | 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" }; |
| 35 | 35 | const pending = scenario === "resume" ? { version: 1, id: "preview-install", system, source: plan, editor_terms: true } : undefined; |
| 36 | 36 | if (url.pathname.startsWith("/api/")) { |
| @@ -47,7 +47,7 @@ http.createServer(async (req, res) => { | ||
| 47 | 47 | } |
| 48 | 48 | value=session; |
| 49 | 49 | } |
| 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}; | |
| 51 | 51 | 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 }; |
| 52 | 52 | else if (url.pathname === "/api/appearance") value = { ...defaultAppearance, mode: "light" }; |
| 53 | 53 | 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" }] }] }; |
| @@ -99,7 +99,8 @@ export function GuestSystemPicker({ system, onChange, preserveOnUnmount = false, | ||
| 99 | 99 | <option value="macos" disabled={view.system !== "macos" || !view.available}>macOS{view.system === "macos" ? view.available ? "" : "(暂不可用)" : "(需要 Apple Silicon Mac)"}</option> |
| 100 | 100 | <option value="windows-11" disabled={view.system !== "windows-11" || !view.available}>Windows 11{view.system === "windows-11" ? view.available ? "" : "(暂不可用)" : "(需要 Windows 11 与 Hyper-V)"}</option> |
| 101 | 101 | </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>} | |
| 103 | 104 | {!system.clone && os !== "debian-13" && !system.activate && <div className="guest-install-fields"> |
| 104 | 105 | {os === "ubuntu-22.04" ? <> |
| 105 | 106 | <small>从 Ubuntu 官方源下载 Ubuntu 22.04 LTS 镜像,并校验 SHA-256。Cage 按主机架构选择 ARM64 或 x86_64。</small> |
| @@ -9,7 +9,7 @@ export function InitializationStorage({ value, onChange, disabled }) { | ||
| 9 | 9 | if (value) return; |
| 10 | 10 | let live = true; |
| 11 | 11 | api("/environment/storage").then(location => { |
| 12 | 删除: if (live) onChange({ location, directory: location.directory }); | |
| 12 | 新增: if (live) onChange({ location, directory: location.suggested_directory || location.directory }); | |
| 13 | 13 | }).catch(error => { if (live) setError(error.message); }); |
| 14 | 14 | return () => { live = false; }; |
| 15 | 15 | }, [Boolean(value), onChange, attempt]); |
| @@ -23,6 +23,7 @@ export function InitializationStorage({ value, onChange, disabled }) { | ||
| 23 | 23 | return <section className="initialization-storage" aria-label="环境存储目录"> |
| 24 | 24 | <label htmlFor="initialization-directory">存储目录</label> |
| 25 | 25 | <p>系统镜像、下载缓存和虚拟磁盘保存在这里。已填入默认目录,也可以选择其他本地磁盘上的专用空文件夹。</p> |
| 26 | 新增: <p>这是 Cage 的环境数据目录。更新、重装或卸载应用会保留这里的数据;请勿手动删除。</p> | |
| 26 | 27 | <div className="initialization-directory-control"> |
| 27 | 28 | <input id="initialization-directory" value={value?.directory || ""} disabled={locked} spellCheck={false} placeholder={value ? "请输入存储目录的完整路径" : "正在读取默认目录…"} onChange={event => onChange({ ...value, directory: event.target.value })} /> |
| 28 | 29 | {nativeAvailable() && <button type="button" disabled={locked} onClick={choose}><FolderOpen size={16} />选择文件夹</button>} |
| @@ -203,7 +203,7 @@ function Initialization({ initial, onComplete }) { | ||
| 203 | 203 | return <InitializationFrame> |
| 204 | 204 | <section className="initialization-content"> |
| 205 | 205 | <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> | |
| 207 | 207 | {connectionError && <div className="initialization-notice" role="alert"><SafetyMessage message={connectionError} /><button onClick={() => pollNow.current?.()}>重新连接</button></div>} |
| 208 | 208 | {!status ? <p role="status"><LoaderCircle size={18} className="spin" />正在读取安装状态…</p> : <> |
| 209 | 209 | <div className="initialization-stage" key={step}> |
| @@ -216,7 +216,8 @@ function Initialization({ initial, onComplete }) { | ||
| 216 | 216 | {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>} |
| 217 | 217 | {job.error && !progress && <div className="initialization-notice" role="alert"><SafetyMessage message={job.error} /><button className="primary" disabled={busy || Boolean(connectionError)} onClick={install}>继续安装</button></div>} |
| 218 | 218 | {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> | |
| 220 | 221 | </>)} |
| 221 | 222 | </div> |
| 222 | 223 | {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>} |

