提交记录修改.gitattributes+2 −0看文件
修改.gitignore+3 −0看文件
修改cmd/cage-client/main.go+5 −0看文件
修改cmd/cage-guest-files/main.go+17 −20看文件
修改cmd/cage-hyperv-manager/main_windows.go+9 −2看文件
修改cmd/cage/main.go+13 −1看文件
修改desktop/Cage.swift+11 −5看文件
修改desktop/linux/cage-desktop.c+16 −4看文件
修改desktop/windows/Backend.cs+8 −5看文件
修改desktop/windows/MainWindow.cs+9 −0看文件
修改desktop/windows/SharedClipboard.cs+12 −7看文件
修改docs/getting-started.md+2 −2看文件
修改docs/guide/guest-systems.md+9 −0看文件
修改docs/guide/tailscale.md+1 −1看文件
修改docs/windows.md+2 −2看文件
修改internal/cage/browser-clipboard.mjs+61 −20看文件
修改internal/cage/browser-clipboard.test.mjs+14 −0看文件
修改internal/cage/desktop-files.py+79 −3看文件
修改internal/cage/environment.go+59 −10看文件
修改internal/cage/guest-open.sh+5 −1看文件
修改internal/cage/shared-clipboard.py+55 −6看文件
修改internal/cage/shared-clipboard.test.py+38 −3看文件
修改internal/cage/storage_runtime.go+7 −2看文件
修改internal/cage/storage_windows.go+6 −0看文件
修改internal/cli/licenses_test.go+2 −1看文件
修改internal/clipboardfiles/ownership.go+3 −6看文件
修改internal/clipboardfiles/ownership_test.go+20 −0看文件
修改internal/clipboardfiles/ownership_unix.go+11 −0看文件
修改internal/clipboardfiles/ownership_windows.go+43 −0看文件
修改internal/guestos/macos_login.go+26 −15看文件
修改internal/guestos/maintenance_windows.go+33 −0看文件
新增internal/guestos/maintenance_windows_test.go+57 −0看文件
新增internal/guestos/testdata/windows_storage.ps1+70 −0看文件
修改internal/guestos/windows_host_manager_client_windows.go+43 −0看文件
修改internal/guestos/windows_host_manager_server_windows.go+1 −1看文件
修改internal/guestos/windows_host_manager_wire.go+3 −4看文件
修改internal/guestos/windows_host_storage_windows.go+65 −80看文件
修改internal/guestos/windows_storage.go+27 −17看文件
修改internal/guestos/windows_storage.ps1+4 −2看文件
新增internal/guestos/windows_storage_disk_nonwindows_test.go+15 −0看文件
新增internal/guestos/windows_storage_disk_windows.go+246 −0看文件
新增internal/guestos/windows_storage_disk_windows_test.go+299 −0看文件
修改internal/guestos/windows_storage_nonwindows.go+9 −0看文件
新增internal/guestos/windows_storage_script_test.go+32 −0看文件
新增internal/guestos/windows_storage_test.go+245 −0看文件
修改internal/guestos/windows_storage_windows.go+4 −0看文件
新增internal/guestos/windows_storage_windows_test.go+173 −0看文件
修改internal/maclogin/bridge.h+2 −0看文件
修改internal/maclogin/bridge_darwin.m+41 −0看文件
新增internal/maclogin/guest_probe_darwin_arm64.go+48 −0看文件
修改internal/maclogin/login_darwin_arm64.go+45 −39看文件
新增internal/maclogin/maintenance.go+81 −0看文件
新增internal/maclogin/maintenance_darwin_arm64.go+341 −0看文件
新增internal/maclogin/maintenance_test.go+128 −0看文件
新增internal/maclogin/maintenance_transport_darwin_arm64_test.go+41 −0看文件
新增internal/maclogin/password_target.go+30 −0看文件
新增internal/maclogin/password_target_darwin_arm64.go+150 −0看文件
新增internal/maclogin/password_target_test.go+53 −0看文件
修改internal/workbench/browser_http.go+1 −1看文件
修改internal/workbench/browser_service.go+1 −1看文件
修改internal/workbench/desktop_file_open.go+6 −7看文件
修改internal/workbench/diagnostics.go+3 −1看文件
修改internal/workbench/environment_test.go+60 −0看文件
修改internal/workbench/environment_versions.go+5 −0看文件
修改internal/workbench/failure_message.go+9 −0看文件
修改internal/workbench/file_input.go+28 −2看文件
修改internal/workbench/image_input.go+3 −3看文件
修改internal/workbench/initialization.go+1 −1看文件
修改internal/workbench/jobs_service.go+9 −1看文件
修改internal/workbench/macos_claude.go+1 −0看文件
修改internal/workbench/macos_guest.go+3 −1看文件
修改internal/workbench/macos_input_contract_test.go+2 −2看文件
修改internal/workbench/macos_login.go+94 −3看文件
新增internal/workbench/macos_maintenance_unix_test.go+158 −0看文件
新增internal/workbench/macos_project_recovery_test.go+85 −0看文件
修改internal/workbench/macos_projects.go+92 −17看文件
修改internal/workbench/macos_window_connection.go+1 −0看文件
修改internal/workbench/macos_workspace_test.go+47 −0看文件
修改internal/workbench/native_desktop_downloads.go+8 −0看文件
修改internal/workbench/native_desktop_downloads_test.go+83 −0看文件
修改internal/workbench/native_routes.go+1 −0看文件
新增internal/workbench/native_state_contract_test.go+73 −0看文件
修改internal/workbench/projects.go+37 −10看文件
修改internal/workbench/readable_errors_test.go+33 −0看文件
修改internal/workbench/remote_gateway.go+1 −1看文件
修改internal/workbench/runtime.go+10 −0看文件
修改internal/workbench/runtime_failure_test.go+2 −0看文件
修改internal/workbench/server.go+28 −6看文件
修改internal/workbench/settings.go+29 −24看文件
修改internal/workbench/shared_clipboard.go+8 −14看文件
修改internal/workbench/shared_clipboard_test.go+7 −3看文件
修改internal/workbench/storage.go+122 −3看文件
修改internal/workbench/storage_paths.go+2 −0看文件
新增internal/workbench/storage_recovery_test.go+406 −0看文件
修改internal/workbench/tailnet_install.go+19 −2看文件
新增internal/workbench/tailnet_install_test.go+84 −0看文件
修改internal/workbench/windows_browser.go+11 −1看文件
修改internal/workbench/windows_browser_client.go+13 −0看文件
修改internal/workbench/windows_browser_client_test.go+35 −0看文件
修改internal/workbench/windows_clipboard_e2e_test.go+5 −2看文件
修改internal/workbench/windows_guest.go+14 −0看文件
修改scripts/guest-os/build-macos-claude-window.sh+7 −1看文件
修改scripts/guest-os/build-macos-sshfs.sh+2 −0看文件
修改scripts/guest-os/guest-clipboard-macos.swift+25 −5看文件
修改scripts/guest-os/guest-clipboard-windows/ClaudeWindowRpc.cs+3 −3看文件
修改scripts/guest-os/guest-clipboard-windows/ClipboardAgent.cs+26 −11看文件
修改scripts/guest-os/guest-clipboard-windows/WindowsDesktopDownloads.cs+117 −13看文件
修改scripts/guest-os/guest-clipboard-windows/WindowsDesktopFiles.cs+17 −5看文件
修改scripts/guest-os/install-windows-host-manager.ps1+5 −3看文件
修改scripts/guest-os/macos-browser-service.mjs+7 −5看文件
修改scripts/guest-os/macos-claude-window-app.swift+29 −15看文件
修改scripts/guest-os/macos-desktop-downloads.swift+121 −4看文件
修改scripts/guest-os/macos-desktop-files.swift+3 −3看文件
新增scripts/guest-os/macos-maintenance.swift+114 −0看文件
修改scripts/guest-os/macos-native-browser.mjs+5 −2看文件
新增scripts/guest-os/macos-native-open.swift+194 −0看文件
新增scripts/guest-os/macos-setup-password.swift+191 −0看文件
修改scripts/guest-os/maintain-windows-workbench.ps1+82 −13看文件
新增scripts/guest-os/maintain-windows-workbench.tests.ps1+140 −0看文件
修改scripts/guest-os/native-component-manifest.pl+0 −0看文件 新增scripts/guest-os/sshfs-openwith.patch+109 −0看文件
修改scripts/guest-os/tests/macos-browser-service.test.mjs+14 −3看文件
修改scripts/guest-os/tests/windows-browser.test.mjs+110 −1看文件
修改scripts/guest-os/windows-browser.mjs+200 −32看文件
修改scripts/package-macos.sh+6 −5看文件
修改ui/scripts/macos-default-workspace-smoke.mjs+23 −2看文件
修改ui/scripts/macos-login-fullscreen-smoke.mjs+74 −0看文件
新增ui/scripts/macos-project-recovery-smoke.mjs+133 −0看文件
新增ui/scripts/storage-recovery-smoke.mjs+97 −0看文件
修改ui/src/api.js+1 −0看文件
修改ui/src/browser-downloads.jsx+22 −1看文件
修改ui/src/environment-storage.jsx+33 −9看文件
修改ui/src/image-transfer.js+5 −5看文件
修改ui/src/macos-login.css+7 −0看文件
修改ui/src/macos-login.jsx+81 −42看文件
修改ui/src/macos-project-approval.jsx+7 −1看文件
修改ui/src/main.jsx+34 −13看文件
修改ui/src/project-dialog.jsx+9 −2看文件
新增ui/src/project-recovery.jsx+15 −0看文件
修改ui/src/remote-input.js+15 −8看文件
修改ui/src/remote-input.test.mjs+19 −0看文件
修改ui/src/settings.jsx+14 −4看文件
修改ui/src/style.css+1 −0看文件
修改ui/src/views.jsx+2 −1看文件
| @@ -27,3 +27,5 @@ | ||
| 27 | 27 | /third_party/** -text -whitespace |
| 28 | 28 | /patches/** -text -whitespace |
| 29 | 29 | /ui/vendor/** -text -whitespace |
| 30 | 新增:# Build patches retain the upstream context whitespace required by patch(1). | |
| 31 | 新增:/scripts/guest-os/sshfs-openwith.patch -text -whitespace | |
| @@ -81,3 +81,6 @@ __pycache__/ | ||
| 81 | 81 | /packaging/nfpm.yaml |
| 82 | 82 | /ui/vendor/novnc/README.cage.md |
| 83 | 83 | /ui/vendor/novnc/vendor/pako/README.md |
| 84 | 新增: | |
| 85 | 新增:# Unfinished local native file-open prototype, excluded from compilation. | |
| 86 | 新增:/scripts/guest-os/guest-clipboard-windows/WindowsNativeOpen.cs.local | |
| @@ -123,6 +123,11 @@ func run(args []string) error { | ||
| 123 | 123 | return errors.New("share-project --json --connection ID read|write DIRECTORY") |
| 124 | 124 | } |
| 125 | 125 | return printJSON(workbench.ShareNativeCloudProject(config, args[3], args[5], args[4] == "read")) |
| 126 | 新增: case "desktop-file": | |
| 127 | 新增: if len(args) != 5 || args[1] != "--json" || args[2] != "--connection" || args[3] == "" { | |
| 128 | 新增: return errors.New("desktop-file --json --connection ID REQUEST") | |
| 129 | 新增: } | |
| 130 | 新增: return printJSON(workbench.DesktopFileForConnection(config, args[3], args[4])) | |
| 126 | 131 | case "clipboard-files", "upload-files", "browser-file": |
| 127 | 132 | if len(args) < 4 || args[1] != "--json" { |
| 128 | 133 | return errors.New("invalid file command") |
| @@ -9,7 +9,6 @@ import ( | ||
| 9 | 9 | "fmt" |
| 10 | 10 | "io" |
| 11 | 11 | "os" |
| 12 | 删除: "path/filepath" | |
| 13 | 12 | |
| 14 | 13 | "github.com/sylvinus/agent-vm/internal/clipboardfiles" |
| 15 | 14 | ) |
| @@ -33,22 +32,30 @@ func run(args []string, input io.Reader, output io.Writer) error { | ||
| 33 | 32 | } |
| 34 | 33 | return json.NewEncoder(output).Encode(result) |
| 35 | 34 | } |
| 35 | 新增: var store clipboardfiles.CacheStore | |
| 36 | 新增: if args[0] != "export" { | |
| 37 | 新增: var err error | |
| 38 | 新增: store, err = clipboardfiles.UserCacheStore() | |
| 39 | 新增: if err != nil { | |
| 40 | 新增: return err | |
| 41 | 新增: } | |
| 42 | 新增: } | |
| 36 | 43 | if args[0] == "save" { |
| 37 | 44 | if len(args) != 2 { |
| 38 | 45 | return errors.New("file name required") |
| 39 | 46 | } |
| 40 | 删除: path, err := clipboardfiles.Save(&framedInput{reader: input}, args[1]) | |
| 47 | 新增: selection, err := store.Save(&framedInput{reader: input}, args[1]) | |
| 41 | 48 | if err != nil { |
| 42 | 49 | return err |
| 43 | 50 | } |
| 44 | 删除: return returnCachedPaths(output, []string{path}) | |
| 51 | 新增: return returnCachedSelection(output, store, selection) | |
| 45 | 52 | } |
| 46 | 53 | if args[0] == "import" { |
| 47 | 删除: paths, err := clipboardfiles.Read(input) | |
| 54 | 新增: selection, err := store.Read(input) | |
| 48 | 55 | if err != nil { |
| 49 | 56 | return err |
| 50 | 57 | } |
| 51 | 删除: return returnCachedPaths(output, paths) | |
| 58 | 新增: return returnCachedSelection(output, store, selection) | |
| 52 | 59 | } |
| 53 | 60 | var paths []string |
| 54 | 61 | if len(args) == 2 && args[1] != "--paths-stdin" { |
| @@ -63,35 +70,25 @@ func run(args []string, input io.Reader, output io.Writer) error { | ||
| 63 | 70 | } |
| 64 | 71 | switch args[0] { |
| 65 | 72 | case "link-cached": |
| 66 | 删除: linked, err := clipboardfiles.LinkCachedFiles(paths) | |
| 73 | 新增: linked, err := store.LinkCachedFiles(paths) | |
| 67 | 74 | if err != nil { |
| 68 | 75 | return err |
| 69 | 76 | } |
| 70 | 删除: return returnCachedPaths(output, linked) | |
| 77 | 新增: return returnCachedSelection(output, store, linked) | |
| 71 | 78 | case "export": |
| 72 | 79 | return clipboardfiles.Write(output, paths) |
| 73 | 80 | case "copy": |
| 74 | 删除: copied, err := clipboardfiles.Copy(paths) | |
| 81 | 新增: copied, err := store.Copy(paths) | |
| 75 | 82 | if err != nil { |
| 76 | 83 | return err |
| 77 | 84 | } |
| 78 | 删除: return returnCachedPaths(output, copied) | |
| 85 | 新增: return returnCachedSelection(output, store, copied) | |
| 79 | 86 | default: |
| 80 | 87 | return errors.New("guest file operation invalid") |
| 81 | 88 | } |
| 82 | 89 | } |
| 83 | 90 | |
| 84 | 删除:func returnCachedPaths(output io.Writer, paths []string) error { | |
| 85 | 删除: store, err := clipboardfiles.UserCacheStore() | |
| 86 | 删除: if err != nil { | |
| 87 | 删除: _ = os.RemoveAll(filepath.Dir(paths[0])) | |
| 88 | 删除: return err | |
| 89 | 删除: } | |
| 90 | 删除: selection, err := store.Register(paths) | |
| 91 | 删除: if err != nil { | |
| 92 | 删除: _ = os.RemoveAll(filepath.Dir(paths[0])) | |
| 93 | 删除: return err | |
| 94 | 删除: } | |
| 91 | 新增:func returnCachedSelection(output io.Writer, store clipboardfiles.CacheStore, selection clipboardfiles.CachedSelection) error { | |
| 95 | 92 | if err := json.NewEncoder(output).Encode(selection); err != nil { |
| 96 | 93 | _ = store.Release(selection.ID) |
| 97 | 94 | return err |
| @@ -38,7 +38,7 @@ func main() { | ||
| 38 | 38 | os.Exit(2) |
| 39 | 39 | } |
| 40 | 40 | err = guestos.RunWindowsHostManagerService(*binding) |
| 41 | 删除: case "prepare": | |
| 41 | 新增: case "prepare", "binding": | |
| 42 | 42 | id, parseErr := uuid.Parse(*vm) |
| 43 | 43 | if parseErr != nil || id == uuid.Nil || *hostSID == "" || *binding != "" || enrollmentFlags { |
| 44 | 44 | os.Exit(2) |
| @@ -46,7 +46,14 @@ func main() { | ||
| 46 | 46 | ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) |
| 47 | 47 | defer cancel() |
| 48 | 48 | var record guestos.WindowsHostManagerBinding |
| 49 | 删除: record, err = guestos.PrepareWindowsHostManagerBinding(ctx, id, *hostSID) | |
| 49 | 新增: if os.Args[1] == "binding" { | |
| 50 | 新增: record, err = guestos.LoadWindowsHostManagerBinding(guestos.WindowsHostManagerBindingPath(id)) | |
| 51 | 新增: if err == nil && (record.VMID != id || record.HostSID != *hostSID) { | |
| 52 | 新增: err = fmt.Errorf("binding_mismatch") | |
| 53 | 新增: } | |
| 54 | 新增: } else { | |
| 55 | 新增: record, err = guestos.PrepareWindowsHostManagerBinding(ctx, id, *hostSID) | |
| 56 | 新增: } | |
| 50 | 57 | if err == nil { |
| 51 | 58 | err = json.NewEncoder(os.Stdout).Encode(record) |
| 52 | 59 | } |
| @@ -298,7 +298,7 @@ func run() int { | ||
| 298 | 298 | return appupdate.Run(path, args[1:], os.Stdout) |
| 299 | 299 | } |
| 300 | 300 | connectionID := "" |
| 301 | 删除: if (args[0] == "clipboard-files" || args[0] == "upload-files" || args[0] == "browser-file" || args[0] == "share-project") && len(args) >= 3 && args[2] == "--connection" { | |
| 301 | 新增: if (args[0] == "clipboard-files" || args[0] == "upload-files" || args[0] == "browser-file" || args[0] == "desktop-file" || args[0] == "share-project") && len(args) >= 3 && args[2] == "--connection" { | |
| 302 | 302 | if len(args) < 4 || args[3] == "" { |
| 303 | 303 | return fail(fmt.Errorf("missing file connection identity")) |
| 304 | 304 | } |
| @@ -317,6 +317,18 @@ func run() int { | ||
| 317 | 317 | _ = json.NewEncoder(os.Stdout).Encode(result) |
| 318 | 318 | return 0 |
| 319 | 319 | } |
| 320 | 新增: if args[0] == "desktop-file" { | |
| 321 | 新增: if len(args) != 3 || args[1] != "--json" { | |
| 322 | 新增: return fail(fmt.Errorf("desktop-file --json --connection ID REQUEST")) | |
| 323 | 新增: } | |
| 324 | 新增: result, err := workbench.DesktopFileForConnection(workbench.DesktopHelperConfig(path, connectionID), connectionID, args[2]) | |
| 325 | 新增: if err != nil { | |
| 326 | 新增: _ = json.NewEncoder(os.Stdout).Encode(map[string]string{"status": "error", "message": err.Error()}) | |
| 327 | 新增: return 1 | |
| 328 | 新增: } | |
| 329 | 新增: _ = json.NewEncoder(os.Stdout).Encode(result) | |
| 330 | 新增: return 0 | |
| 331 | 新增: } | |
| 320 | 332 | if args[0] == "share-project" { |
| 321 | 333 | if connectionID == "" || len(args) != 4 || args[1] != "--json" || (args[2] != "read" && args[2] != "write") { |
| 322 | 334 | return fail(fmt.Errorf("share-project --json --connection ID read|write DIRECTORY")) |
| @@ -281,11 +281,14 @@ final class CageApp: NSObject, NSApplicationDelegate, NSWindowDelegate, WKNaviga | ||
| 281 | 281 | private func clipboardCacheCommand(_ action: String, id: String = "", reply: @escaping (Any?, String?) -> Void) { |
| 282 | 282 | guard let data = try? JSONSerialization.data(withJSONObject: ["action": action, "cache_id": id]), |
| 283 | 283 | let request = String(data: data, encoding: .utf8) else { reply(nil,"剪贴板缓存请求无效"); return } |
| 284 | 删除: fileCommand(["clipboard-files", "--json", "cache", request], reply: reply) | |
| 284 | 新增: fileCommand(["clipboard-files", "--json", "cache", request], replyLimit: 30 << 20, seconds: 10, reply: reply) | |
| 285 | 285 | } |
| 286 | 286 | private func watchClipboardCaches() { |
| 287 | 287 | guard clipboardCacheTimer == nil else { return } |
| 288 | 288 | clipboardCacheTimer = Timer.scheduledTimer(withTimeInterval: 1, repeats: true) { [weak self] _ in self?.collectClipboardCaches() } |
| 289 | 新增: restoreClipboardCaches() | |
| 290 | 新增: } | |
| 291 | 新增: private func restoreClipboardCaches() { | |
| 289 | 292 | clipboardCacheCommand("list") { result, _ in |
| 290 | 293 | self.clipboardCacheLoaded = true |
| 291 | 294 | for selection in (result as? [String:Any])?["selections"] as? [[String:Any]] ?? [] { |
| @@ -319,7 +322,7 @@ final class CageApp: NSObject, NSApplicationDelegate, NSWindowDelegate, WKNaviga | ||
| 319 | 322 | if !referenced { releaseClipboardCache(id) } |
| 320 | 323 | } |
| 321 | 324 | } |
| 322 | 删除: private func fileCommand(_ arguments: [String], reply: @escaping (Any?, String?) -> Void) { | |
| 325 | 新增: private func fileCommand(_ arguments: [String], replyLimit: Int = 65536, seconds: TimeInterval = 1800, reply: @escaping (Any?, String?) -> Void) { | |
| 323 | 326 | guard let executable = Bundle.main.url(forResource: "cage", withExtension: nil) else { reply(nil,"无法找到文件传递组件"); return } |
| 324 | 327 | DispatchQueue.global(qos: .userInitiated).async { |
| 325 | 328 | let process = Process(); process.executableURL = executable |
| @@ -328,10 +331,10 @@ final class CageApp: NSObject, NSApplicationDelegate, NSWindowDelegate, WKNaviga | ||
| 328 | 331 | do { |
| 329 | 332 | try process.run() |
| 330 | 333 | let timeout = DispatchWorkItem { if process.isRunning { process.terminate() } } |
| 331 | 删除: DispatchQueue.global().asyncAfter(deadline: .now() + 1800, execute: timeout) | |
| 334 | 新增: DispatchQueue.global().asyncAfter(deadline: .now() + seconds, execute: timeout) | |
| 332 | 335 | defer { timeout.cancel() } |
| 333 | 336 | let data = output.fileHandleForReading.readDataToEndOfFile(); process.waitUntilExit() |
| 334 | 删除: guard data.count <= 65536, let result = try JSONSerialization.jsonObject(with: data) as? [String:Any] else { throw CageUpdateError("文件操作未返回有效结果") } | |
| 337 | 新增: guard data.count <= replyLimit, let result = try JSONSerialization.jsonObject(with: data) as? [String:Any] else { throw CageUpdateError("文件操作未返回有效结果") } | |
| 335 | 338 | DispatchQueue.main.async { reply(process.terminationStatus == 0 ? result : nil, process.terminationStatus == 0 ? nil : result["message"] as? String ?? "文件操作失败") } |
| 336 | 339 | } catch { CageDiagnostics.record(error.localizedDescription); DispatchQueue.main.async { reply(nil,error.localizedDescription) } } |
| 337 | 340 | } |
| @@ -487,7 +490,7 @@ final class CageApp: NSObject, NSApplicationDelegate, NSWindowDelegate, WKNaviga | ||
| 487 | 490 | } |
| 488 | 491 | if let id = body["files"] as? String, UUID(uuidString:id) != nil { |
| 489 | 492 | fileCommand(["clipboard-files","--json","--connection",body["connection_id"] as? String ?? "local","receive",id]) { result, error in |
| 490 | 删除: guard error == nil, let paths = (result as? [String:Any])?["paths"] as? [String] else { replyHandler(nil,error ?? "剪贴板文件读取失败"); return } | |
| 493 | 新增: guard error == nil, let paths = (result as? [String:Any])?["paths"] as? [String] else { self.restoreClipboardCaches(); replyHandler(nil,error ?? "剪贴板文件读取失败"); return } | |
| 491 | 494 | let cache = (result as? [String:Any])?["cache_id"] as? String ?? "" |
| 492 | 495 | if !cache.isEmpty { self.clipboardCopies[cache] = paths; self.clipboardPending.insert(cache) } |
| 493 | 496 | write(paths.map { URL(fileURLWithPath:$0) }, cache) |
| @@ -552,6 +555,9 @@ final class CageApp: NSObject, NSApplicationDelegate, NSWindowDelegate, WKNaviga | ||
| 552 | 555 | guard response == .OK, let url = panel.url else { replyHandler(["canceled":true],nil); return } |
| 553 | 556 | self.browserFile("save",id:id,connection:body["connection_id"] as? String ?? "local",path:url.path,reply:replyHandler) |
| 554 | 557 | } |
| 558 | 新增: case "desktopFileAction": | |
| 559 | 新增: guard let id = body["id"] as? String, UUID(uuidString:id) != nil else { replyHandler(nil,"文件打开标识无效"); return } | |
| 560 | 新增: fileCommand(["desktop-file", "--json", "--connection", body["connection_id"] as? String ?? "local", id], reply: replyHandler) | |
| 555 | 561 | case "browserDownloadAction": |
| 556 | 562 | guard let id = body["id"] as? String, let operation = body["operation"] as? String, ["open","reveal"].contains(operation) else { replyHandler(nil,"下载操作无效"); return } |
| 557 | 563 | browserFile(operation,id:id,connection:body["connection_id"] as? String ?? "local",reply:replyHandler) |
| @@ -62,6 +62,7 @@ typedef struct { | ||
| 62 | 62 | GSubprocess *process; |
| 63 | 63 | GCancellable *cancel; |
| 64 | 64 | guint deadline; |
| 65 | 新增: gsize output_limit; | |
| 65 | 66 | BackendCallback callback; |
| 66 | 67 | gpointer data; |
| 67 | 68 | } Command; |
| @@ -156,7 +157,7 @@ static void command_finished(GObject *source, GAsyncResult *result, gpointer dat | ||
| 156 | 157 | JsonObject *object = NULL; |
| 157 | 158 | if (command->deadline) g_source_remove(command->deadline); |
| 158 | 159 | if (g_subprocess_communicate_utf8_finish(G_SUBPROCESS(source), result, &output, NULL, &error)) { |
| 159 | 删除: if (!output || strlen(output) > 65536 || !json_parser_load_from_data(parser, output, -1, NULL) || | |
| 160 | 新增: if (!output || strlen(output) > command->output_limit || !json_parser_load_from_data(parser, output, -1, NULL) || | |
| 160 | 161 | !JSON_NODE_HOLDS_OBJECT(json_parser_get_root(parser))) { |
| 161 | 162 | g_set_error_literal(&error, G_IO_ERROR, G_IO_ERROR_INVALID_DATA, "Cage 后台未返回有效状态,请查看私有配置中的 logs/。"); |
| 162 | 163 | } else { |
| @@ -176,7 +177,7 @@ static void command_finished(GObject *source, GAsyncResult *result, gpointer dat | ||
| 176 | 177 | g_object_unref(command->cancel); |
| 177 | 178 | g_free(command); |
| 178 | 179 | } |
| 179 | 删除:static void backend_arguments(const char *const *args, guint seconds, BackendCallback callback, gpointer data) { | |
| 180 | 新增:static void backend_arguments_limited(const char *const *args, guint seconds, gsize output_limit, BackendCallback callback, gpointer data) { | |
| 180 | 181 | GError *error = NULL; |
| 181 | 182 | GSubprocessLauncher *launcher = g_subprocess_launcher_new(G_SUBPROCESS_FLAGS_STDOUT_PIPE | G_SUBPROCESS_FLAGS_STDERR_SILENCE); |
| 182 | 183 | g_subprocess_launcher_setenv(launcher, "CLAUDE_CAGE_CONFIG", app.profile, TRUE); |
| @@ -197,9 +198,13 @@ static void backend_arguments(const char *const *args, guint seconds, BackendCal | ||
| 197 | 198 | command->cancel = g_cancellable_new(); |
| 198 | 199 | command->callback = callback; |
| 199 | 200 | command->data = data; |
| 201 | 新增: command->output_limit = output_limit; | |
| 200 | 202 | command->deadline = g_timeout_add_seconds(seconds, command_timeout, command); |
| 201 | 203 | g_subprocess_communicate_utf8_async(process, NULL, command->cancel, command_finished, command); |
| 202 | 204 | } |
| 205 | 新增:static void backend_arguments(const char *const *args, guint seconds, BackendCallback callback, gpointer data) { | |
| 206 | 新增: backend_arguments_limited(args, seconds, 65536, callback, data); | |
| 207 | 新增:} | |
| 203 | 208 | static void backend(const char *action, const char *option, BackendCallback callback, gpointer data) { |
| 204 | 209 | const char *args[] = {app.backend, action, "--json", option, NULL}; |
| 205 | 210 | backend_arguments(args, 180, callback, data); |
| @@ -456,7 +461,7 @@ static void clipboard_cache_command(const char *action, const char *id, BackendC | ||
| 456 | 461 | char *quoted = quote(id ? id : ""); |
| 457 | 462 | char *request = g_strdup_printf("{\"action\":\"%s\",\"cache_id\":%s}", action, quoted); |
| 458 | 463 | const char *args[] = {app.backend, "clipboard-files", "--json", "cache", request, NULL}; |
| 459 | 删除: backend_arguments(args, 10, callback, data); | |
| 464 | 新增: backend_arguments_limited(args, 10, 30 << 20, callback, data); | |
| 460 | 465 | g_free(request); g_free(quoted); |
| 461 | 466 | } |
| 462 | 467 | static void clipboard_cache_ignored(JsonObject *object, const GError *error, gpointer data) { (void)object; (void)error; (void)data; } |
| @@ -565,7 +570,7 @@ static void clipboard_sync_provide(GtkClipboard *clipboard, GtkSelectionData *se | ||
| 565 | 570 | static void clipboard_sync_clear(GtkClipboard *clipboard, gpointer data) { (void)clipboard; g_strfreev(data); } |
| 566 | 571 | static void clipboard_files_received(JsonObject *object, const GError *error, gpointer data) { |
| 567 | 572 | PendingReply *pending = data; |
| 568 | 删除: if (error) { reply_error(pending->reply, error->message); pending_free(pending); return; } | |
| 573 | 新增: if (error) { clipboard_cache_command("list", "", clipboard_cache_loaded_reply, NULL); reply_error(pending->reply, error->message); pending_free(pending); return; } | |
| 569 | 574 | clipboard_cache_watch(); clipboard_cache_remember(object, TRUE); |
| 570 | 575 | const char *cache = text_member(object, "cache_id"); |
| 571 | 576 | if (pending->generation != clipboard_generation || pending->revision != clipboard_current_revision()) { clipboard_cache_release(cache, pending); return; } |
| @@ -763,6 +768,13 @@ static gboolean bridge_received(WebKitUserContentManager *manager, JSCValue *val | ||
| 763 | 768 | reply_json(reply, context, state); |
| 764 | 769 | g_free(state); g_free(version); g_free(message); |
| 765 | 770 | } |
| 771 | 新增: } else if (!strcmp(name, "desktopFileAction")) { | |
| 772 | 新增: const char *id = text_member(request, "id"), *connection = text_member(request, "connection_id"); | |
| 773 | 新增: if (!g_uuid_string_is_valid(id)) reply_error(reply, "文件打开标识无效。"); | |
| 774 | 新增: else { | |
| 775 | 新增: const char *args[] = {app.backend,"desktop-file","--json","--connection",*connection ? connection : "local",id,NULL}; | |
| 776 | 新增: backend_arguments(args,1800,browser_file_finished,pending_reply(reply,context)); | |
| 777 | 新增: } | |
| 766 | 778 | } else if (!strcmp(name, "saveBrowserDownload") || !strcmp(name, "browserDownloadAction")) { |
| 767 | 779 | const char *id = text_member(request, "id"); |
| 768 | 780 | const char *operation = !strcmp(name, "saveBrowserDownload") ? "save" : text_member(request, "operation"); |
| @@ -28,10 +28,10 @@ internal static class Backend | ||
| 28 | 28 | return start; |
| 29 | 29 | } |
| 30 | 30 | |
| 31 | 删除: public static Task<(int Exit, JsonElement Data)> Json(string[] arguments, CancellationToken cancellation = default, TimeSpan? deadline = null) => | |
| 32 | 删除: JsonAt(Executable, arguments, cancellation, deadline); | |
| 31 | 新增: public static Task<(int Exit, JsonElement Data)> Json(string[] arguments, CancellationToken cancellation = default, TimeSpan? deadline = null, int outputLimit = 65536) => | |
| 32 | 新增: JsonAt(Executable, arguments, cancellation, deadline, outputLimit); | |
| 33 | 33 | |
| 34 | 删除: public static async Task<(int Exit, JsonElement Data)> JsonAt(string executable, string[] arguments, CancellationToken cancellation = default, TimeSpan? deadline = null) | |
| 34 | 新增: public static async Task<(int Exit, JsonElement Data)> JsonAt(string executable, string[] arguments, CancellationToken cancellation = default, TimeSpan? deadline = null, int outputLimit = 65536) | |
| 35 | 35 | { |
| 36 | 36 | using var timeout = CancellationTokenSource.CreateLinkedTokenSource(cancellation); |
| 37 | 37 | timeout.CancelAfter(deadline ?? TimeSpan.FromMinutes(3)); |
| @@ -41,12 +41,15 @@ internal static class Backend | ||
| 41 | 41 | try |
| 42 | 42 | { |
| 43 | 43 | var errors = Drain(process.StandardError, timeout.Token); |
| 44 | 删除: var text = await ReadLimited(process.StandardOutput, 65536, timeout.Token); | |
| 44 | 新增: var text = await ReadLimited(process.StandardOutput, outputLimit, timeout.Token); | |
| 45 | 45 | await process.WaitForExitAsync(timeout.Token); await errors; |
| 46 | 46 | try { return (process.ExitCode, JsonDocument.Parse(text).RootElement.Clone()); } |
| 47 | 47 | catch (JsonException) { throw new IOException("Cage 后台未返回有效状态,请查看工作台日志"); } |
| 48 | 48 | } |
| 49 | 删除: finally { if (!process.HasExited) process.Kill(); } | |
| 49 | 新增: finally | |
| 50 | 新增: { | |
| 51 | 新增: if (!process.HasExited) { process.Kill(); await process.WaitForExitAsync(); } | |
| 52 | 新增: } | |
| 50 | 53 | } |
| 51 | 54 | |
| 52 | 55 | public static async Task<string> ReadLimited(StreamReader reader, int limit, CancellationToken token) |
| @@ -351,6 +351,15 @@ internal sealed class MainWindow : Form | ||
| 351 | 351 | case "clipboardSyncRead": result = await SharedClipboard.Read(request, lifetime.Token); break; |
| 352 | 352 | case "clipboardSyncWrite": result = await SharedClipboard.Write(request, lifetime.Token); break; |
| 353 | 353 | case "clipboardSyncRelease": result = await SharedClipboard.Release(request, lifetime.Token); break; |
| 354 | 新增: case "desktopFileAction": | |
| 355 | 新增: { | |
| 356 | 新增: var fileRequestID = request.Text("id"); | |
| 357 | 新增: if (!Guid.TryParse(fileRequestID, out _)) throw new InvalidDataException("文件打开标识无效"); | |
| 358 | 新增: var connection = request.Text("connection_id"); | |
| 359 | 新增: var response = await Backend.Json(["desktop-file", "--json", "--connection", string.IsNullOrEmpty(connection) ? "local" : connection, fileRequestID], lifetime.Token, TimeSpan.FromMinutes(30)); | |
| 360 | 新增: if (response.Exit != 0) throw new IOException(response.Data.Text("message")); | |
| 361 | 新增: result = response.Data; break; | |
| 362 | 新增: } | |
| 354 | 363 | case "saveBrowserDownload": |
| 355 | 364 | case "browserDownloadAction": |
| 356 | 365 | { |
| @@ -33,7 +33,7 @@ internal static class SharedClipboard | ||
| 33 | 33 | private static async Task<JsonElement> Cache(string action, string id = "") |
| 34 | 34 | { |
| 35 | 35 | var request = JsonSerializer.Serialize(new { action, cache_id = id }); |
| 36 | 删除: var result = await Backend.Json(["clipboard-files", "--json", "cache", request], CancellationToken.None, TimeSpan.FromSeconds(10)); | |
| 36 | 新增: var result = await Backend.Json(["clipboard-files", "--json", "cache", request], CancellationToken.None, TimeSpan.FromSeconds(10), outputLimit: 30 << 20); | |
| 37 | 37 | if (result.Exit != 0) throw new IOException("clipboard_cache_operation_failed"); |
| 38 | 38 | return result.Data; |
| 39 | 39 | } |
| @@ -60,10 +60,10 @@ internal static class SharedClipboard | ||
| 60 | 60 | { |
| 61 | 61 | if (!loaded) |
| 62 | 62 | { |
| 63 | 删除: loaded = true; | |
| 64 | 63 | var result = await Cache("list"); |
| 65 | 64 | foreach (var item in result.GetProperty("selections").EnumerateArray()) |
| 66 | 65 | copies.TryAdd(item.Text("cache_id"), item.GetProperty("paths").EnumerateArray().Select(path => path.GetString()!).ToArray()); |
| 66 | 新增: loaded = true; | |
| 67 | 67 | } |
| 68 | 68 | foreach (var copy in copies.ToArray()) |
| 69 | 69 | { |
| @@ -127,17 +127,22 @@ internal static class SharedClipboard | ||
| 127 | 127 | |
| 128 | 128 | public static async Task<object> Write(JsonElement request, CancellationToken token) |
| 129 | 129 | { |
| 130 | 新增: _ = Revision; | |
| 130 | 131 | var currentGeneration = generation; |
| 131 | 132 | string[]? paths = null; |
| 132 | 133 | var cache = ""; |
| 133 | 134 | if (request.Text("files") is { Length: > 0 } id) |
| 134 | 135 | { |
| 135 | 136 | if (!Guid.TryParse(id, out _)) throw new InvalidDataException("剪贴板文件标识无效"); |
| 136 | 删除: var response = await Backend.Json(["clipboard-files", "--json", "--connection", request.Text("connection_id"), "receive", id], token, TimeSpan.FromMinutes(30)); | |
| 137 | 删除: if (response.Exit != 0) throw new IOException(response.Data.Text("message")); | |
| 138 | 删除: paths = response.Data.GetProperty("paths").EnumerateArray().Select(value => value.GetString()!).ToArray(); | |
| 139 | 删除: cache = response.Data.Text("cache_id"); | |
| 140 | 删除: if (cache.Length != 0) { copies[cache] = paths; pending.Add(cache); } | |
| 137 | 新增: try | |
| 138 | 新增: { | |
| 139 | 新增: var response = await Backend.Json(["clipboard-files", "--json", "--connection", request.Text("connection_id"), "receive", id], token, TimeSpan.FromMinutes(30)); | |
| 140 | 新增: if (response.Exit != 0) throw new IOException(response.Data.Text("message")); | |
| 141 | 新增: paths = response.Data.GetProperty("paths").EnumerateArray().Select(value => value.GetString()!).ToArray(); | |
| 142 | 新增: cache = response.Data.Text("cache_id"); | |
| 143 | 新增: if (cache.Length != 0) { copies[cache] = paths; pending.Add(cache); } | |
| 144 | 新增: } | |
| 145 | 新增: catch { loaded = false; throw; } | |
| 141 | 146 | } |
| 142 | 147 | try |
| 143 | 148 | { |
| @@ -23,7 +23,7 @@ | ||
| 23 | 23 | | 平台 | 安装方式 | |
| 24 | 24 | |---|---| |
| 25 | 25 | | macOS | 下载 Apple Silicon `.dmg`,打开后将 Cage 拖入 Applications(应用程序),再从“应用程序”启动。 | |
| 26 | 删除:| Windows | 下载 x64 `.exe` 安装器,运行后从开始菜单打开 Cage。预览包会标明“未签名”,用于手动安装测试,不能自动安装更新。详见 [Windows 指南](windows.md)。 | | |
| 26 | 新增:| Windows | 下载 x64 `.exe` 安装器,运行后从开始菜单打开 Cage。可信签名包支持校验发布者身份;旧版或单独标明“未签名”的预览包仅用于手动安装测试,不能自动安装更新。详见 [Windows 指南](windows.md)。 | | |
| 27 | 27 | | Linux | 下载 x86_64 `.deb`,使用 `sudo apt install ./Cage-<版本>-linux-amd64.deb` 安装。缺少 QEMU、GTK、WebKitGTK、OpenSSH 等主机依赖时,APT 会从系统配置的软件源补齐,再从应用菜单打开 Cage。详见 [Linux 指南](linux.md)。 | |
| 28 | 28 | |
| 29 | 29 | 无需先安装开发工具或 Clash。签名、公证和平台验证情况以该安装包的 Release 说明为准。如果系统拒绝打开,先按[安装问题](troubleshooting.md#下载或安装受阻)核对版本与来源。下述代理、环境和项目操作共用。 |
| @@ -289,7 +289,7 @@ macOS 的 `0.1.3-alpha.1` 及更早公开版本存在本机更新校验错误。 | ||
| 289 | 289 | |
| 290 | 290 | 检查和下载使用已经应用并运行的所选代理,失败不会改用主机直连。自动安装要求当前 App 与新 App 使用相同发布者的 Developer ID 签名,且新包通过 Apple 验证;ad-hoc 开发构建不能自动安装。更新器使用公开的 GitHub Releases 接口,无需 GitHub 登录,也不读取浏览器会话。若提示更新源不可访问,先确认所选代理可用,再检查对应 Release 是否仍公开且附件完整;需要手动下载时使用同一公开 Release。实际安装、重启和恢复的验收范围以该版本说明为准。 |
| 291 | 291 | |
| 292 | 删除:手动替换 App 前,保存文件并选择“停止环境并退出”。新 App 会核对后台版本;若出现“更新待完成”,可先打开现有环境保存文件,再选择“保存后停止环境并完成更新”。Alpha 版本间的兼容性和特殊迁移要求以对应 Release 说明为准。 | |
| 292 | 新增:手动替换 App 前,保存文件并选择“停止环境并退出”。新 App 会核对后台版本;若出现“更新待完成”,可先打开现有环境保存文件,再选择“保存后停止环境并完成更新”。预发行版本间的兼容性和特殊迁移要求以对应 Release 说明为准。 | |
| 293 | 293 | |
| 294 | 294 | “设置 → 环境与恢复”分别提供环境组件与工具更新,并显示实际版本。组件更新会重启浏览器和编辑器,保留 VM、磁盘和工作台独立终端;编辑器内的集成终端可能结束,操作前需要保存内容。依赖安装和工具更新使用所选代理,无需业务网络已经放行;工具更新采用当前 App 指定的最低版本,人工暂停外网不会被更新操作解除。替换 App 不等于已经升级全部 Linux 工具。 |
| 295 | 295 | |
| @@ -33,6 +33,7 @@ keywords: 客机 客户机 克隆 本机 系统选择 macOS Windows Debian Ubunt | ||
| 33 | 33 | | Mac 本机版本匹配 | 真实首次创建、系统恢复、权限确认、项目双向读写、编辑器及冷启动持久性 | 官方 Claude 在线登录与完整工作流程;本轮创建验证保持客机外网关闭 | |
| 34 | 34 | | Windows 本机版本匹配 | 官方材料下载与校验、自动建机、首次启动、冷启动和测试文件保留 | 修复后的最终工作台登记与完整首次使用 | |
| 35 | 35 | | Linux 同发行版匹配 | 镜像身份、安装来源和模板;Ubuntu 22.04 容器中的原生窗口、重装与卸载数据保留,以及真实浏览器启动 | 完整 KVM 首装、项目共享、物理桌面输入和官方 Claude 登录 | |
| 36 | 新增:| 独立 Ubuntu 22.04 | Mac ARM64 真实安装、冷启动、项目共享、终端、浏览器、编辑器、中文输入、音频、剪贴板、Desktop 安装及欢迎页、网络暂停与代理中断、原磁盘持久化 | Windows WHPX / Linux KVM 实机首装,官方 Claude 登录和业务会话 | | |
| 36 | 37 | |
| 37 | 38 | 多账号、手机和原生 Desktop 文件操作还需各自的应用级检查,分别见[多账号与额度](accounts.md)、[手机连接](mobile.md)和[Claude Desktop](desktop.md)。 |
| 38 | 39 | |
| @@ -136,3 +137,11 @@ macOS 默认工作区使用与其他项目相同的文件夹授权。主界面 | ||
| 136 | 137 | 手机用于连接电脑上的 Cage,接续 Claude Code 会话、处理工具审批和操作远程窗口,任务仍在电脑上运行。手机不会安装上述桌面客机系统;连接方式见[手机连接与远程会话](mobile.md)。 |
| 137 | 138 | |
| 138 | 139 | macOS 客机的手机 Desktop 共享电脑 Cage 中的同一个 Claude 窗口和登录状态。需要通过外部浏览器登录 Claude 时,在电脑 Cage 中完成登录,手机随后继续使用该登录状态。虚拟 Mac 锁屏或切换系统账户后,原手机图形会话结束,需要登录原客机账户后重新打开。 |
| 140 | 新增: | |
| 141 | 新增:## 环境存储与项目恢复 | |
| 142 | 新增: | |
| 143 | 新增:环境存储所在磁盘未连接或迁移尚未完成时,工作台会提示“环境存储需要恢复”。连接原磁盘后,在设置的项目与环境页面点击“重试恢复”;Windows 如提示系统助手需要修复,使用“修复系统助手并恢复”,完成系统授权后继续。恢复完成前不要另建环境或删除原虚拟磁盘。 | |
| 144 | 新增: | |
| 145 | 新增:macOS 项目连接遇到权限问题时,按提示打开对应的文件共享、屏幕录制或辅助功能授权入口。完成授权并关闭维护窗口后,Cage 会重新检查项目连接。需要客机登录时,先登录并解锁普通账户,再重试项目。 | |
| 146 | 新增: | |
| 147 | 新增:旧版默认项目若位于 Cage 配置目录中,升级后保留该目录中的文件与环境身份。请按设置页显示的旧目录找到项目,将其移至配置目录之外的专用项目文件夹后,再从工作台打开。 | |
| @@ -12,7 +12,7 @@ keywords: Tailscale tailnet 设备 私网 SSH Web TCP 代理 | ||
| 12 | 12 | |
| 13 | 13 | 启动 Cage 环境,打开 Tailscale 面板,点击「连接并登录」。在打开的官方授权页面完成登录,然后重新打开 Tailscale 面板。连接成功后,可看到当前账号、网络名称、Cage 的私网地址与设备清单。网络要求设备审批时,面板显示「等待管理员批准」,由网络管理员在 Tailscale 管理台批准 Cage 后即可继续。 |
| 14 | 14 | |
| 15 | 删除:Debian 环境首次使用时需点击「安装 Tailscale」。macOS 和 Windows 环境随客机组件提供,已有环境可按面板提示更新环境组件。 | |
| 15 | 新增:Debian 环境首次使用时需点击「安装 Tailscale」。macOS 和 Windows 环境随客机组件提供,已有环境可按面板提示更新环境组件。Linux 已安装的 Tailscale 也会随环境组件同步更新,设备身份和 SSH 公钥保留;尚未安装的环境继续按需安装。 | |
| 16 | 16 | |
| 17 | 17 | 设备清单显示当前网络允许 Cage 发现的设备,在线设备排在前面,支持按名称、系统或私网地址搜索。清单为空时,先检查其他设备是否加入同一网络,以及网络的设备访问规则。 |
| 18 | 18 | |
| @@ -25,7 +25,7 @@ DISM /Online /Enable-Feature /FeatureName:HypervisorPlatform /All | ||
| 25 | 25 | |
| 26 | 26 | ## 安装并开始工作 |
| 27 | 27 | |
| 28 | 删除:1. 在[项目主页](https://lee-xeo.github.io/Claude-Cage/#download)点击“下载应用”并选择 Windows,核对对应发行条目的 `SHA256SUMS`。签名安装包名为 `Cage-<版本>-windows-amd64-setup.exe`;当前公开预览包名为 `Cage-<版本>-windows-amd64-setup-unsigned.exe`,主页标明“预览版 · 未签名”。未签名包可能触发未知发布者提示,需手动安装和更新。 | |
| 28 | 新增:1. 在[项目主页](https://lee-xeo.github.io/Claude-Cage/#download)点击“下载应用”并选择 Windows,核对对应发行条目的 `SHA256SUMS`。签名安装包名为 `Cage-<版本>-windows-amd64-setup.exe`;单独标明未签名的开发预览包名为 `Cage-<版本>-windows-amd64-setup-unsigned.exe`。未签名包可能触发未知发布者提示,需手动安装和更新。 | |
| 29 | 29 | 2. 运行安装程序,选择安装位置。首次安装时,默认选择本地 D 盘的 `D:\Cage`;没有本地 D 盘时使用当前用户的 `%LOCALAPPDATA%\Programs\Cage`。已有安装沿用原目录,也可以手动选择其他位置。安装器随附 .NET 桌面运行组件、WebView2 安装程序、QEMU、OpenSSH 客户端和代理核心,无需另装 Go、Node.js 或 Clash。 |
| 30 | 30 | 3. 在“快捷方式”页选择“添加桌面快捷方式”和“添加到开始菜单”。首次安装默认勾选两项,覆盖安装沿用上次选择,旧安装按已有快捷方式恢复选择。卸载会清理 Cage 创建的快捷方式。 |
| 31 | 31 | 4. 从选中的快捷方式启动 Cage,选择客机系统。如果 C 盘空间有限,在工作台点击“选择环境存储位置”,选择其他磁盘的专用空文件夹,再导入代理并启动环境。镜像、工具和虚拟磁盘按所选系统准备;已有环境也可以从设置迁移。见[选盘与迁移步骤](getting-started.md#选择环境存储位置)和[客机系统指南](guide/guest-systems.md)。 |
| @@ -60,7 +60,7 @@ Windows Hypervisor Platform 已启用时,QEMU 仍可能因嵌套虚拟化初 | ||
| 60 | 60 | |
| 61 | 61 | 当前开发构建在升级或强制结束后会自动检查旧连接记录及控制锁。旧锁空闲时修复其所有者和私有权限,再由新后台重建连接记录;真实后台持有的锁继续阻止接管。权限无法迁移时显示具体原因。请保留个人配置目录,不要通过删除账户或虚拟磁盘解决连接问题。点右上角 × 隐藏窗口并保留托盘,结束应用请使用“退出 Cage”;运行中的环境可选择保留运行或停止后退出。 |
| 62 | 62 | |
| 63 | 删除:本地开发包已适配含中文的安装目录。启动时优先读取随附 QEMU 的 UEFI 固件,无需在用户目录另存副本。在默认虚拟 CPU 配置下,Cage 会向 Windows 虚拟机监控程序平台查询可用指令;Claude Code 需要客机提供 SSE4.2。自行指定了虚拟 CPU 型号的环境仍沿用该设置。这两项修复尚未进入公开的 `v0.1.5-alpha.2` 安装包。 | |
| 63 | 新增:Cage 支持含中文的安装目录。启动时优先读取随附 QEMU 的 UEFI 固件,无需在用户目录另存副本。在默认虚拟 CPU 配置下,Cage 会向 Windows 虚拟机监控程序平台查询可用指令;Claude Code 需要客机提供 SSE4.2。自行指定了虚拟 CPU 型号的环境仍沿用该设置。 | |
| 64 | 64 | |
| 65 | 65 | - 提示虚拟化不可用:检查 BIOS/UEFI 的虚拟化开关及 Windows 虚拟机监控程序平台,重启后再试。远程或嵌套虚拟机还需要外层宿主允许嵌套虚拟化。 |
| 66 | 66 | - 提示缺少 WebView2:重新运行完整安装程序。不要从第三方站点下载同名 DLL。 |
| @@ -3,7 +3,7 @@ import { randomBytes } from "node:crypto"; | ||
| 3 | 3 | // This runs before site scripts, in each new document's main world. The binding |
| 4 | 4 | // and token stay in the closure. Existing documents expose only captured |
| 5 | 5 | // function references to CDP for native-code verification before installation. |
| 6 | 删除:function prepareCopies(bindingName, token, contextSetter, limit) { | |
| 6 | 新增:function prepareCopies(bindingName, token, contextSetter, limit, includeChanges) { | |
| 7 | 7 | const emit = globalThis[bindingName]; |
| 8 | 8 | delete globalThis[bindingName]; |
| 9 | 9 | if (typeof emit !== "function") return; |
| @@ -58,6 +58,8 @@ function prepareCopies(bindingName, token, contextSetter, limit) { | ||
| 58 | 58 | ).get; |
| 59 | 59 | const getSelection = Document.prototype.getSelection; |
| 60 | 60 | const selectionText = Selection.prototype.toString; |
| 61 | 新增: const selectionCollapsed = descriptor(Selection.prototype, "isCollapsed").get; | |
| 62 | 新增: const schedule = globalThis.setTimeout; | |
| 61 | 63 | const nativeFunctions = { |
| 62 | 64 | "": emit, |
| 63 | 65 | apply, |
| @@ -93,6 +95,8 @@ function prepareCopies(bindingName, token, contextSetter, limit) { | ||
| 93 | 95 | "get selectionEnd#textarea": textareaEnd, |
| 94 | 96 | getSelection, |
| 95 | 97 | toString: selectionText, |
| 98 | 新增: "get isCollapsed": selectionCollapsed, | |
| 99 | 新增: setTimeout: schedule, | |
| 96 | 100 | }; |
| 97 | 101 | const plain = (value) => { |
| 98 | 102 | const type = apply(lower, value, []); |
| @@ -118,11 +122,15 @@ function prepareCopies(bindingName, token, contextSetter, limit) { | ||
| 118 | 122 | context && current() && apply(activated, activation, []) |
| 119 | 123 | ? { epoch, context } |
| 120 | 124 | : null; |
| 121 | 删除: const selectedControlText = () => { | |
| 125 | 新增: const focusedElement = () => { | |
| 122 | 126 | let element = apply(activeElement, document, []); |
| 123 | 127 | let root; |
| 124 | 128 | while (element && (root = apply(shadowRoot, element, []))) |
| 125 | 129 | element = apply(shadowActiveElement, root, []); |
| 130 | 新增: return element; | |
| 131 | 新增: }; | |
| 132 | 新增: const selectedControlText = () => { | |
| 133 | 新增: const element = focusedElement(); | |
| 126 | 134 | if (!element) return; |
| 127 | 135 | const tag = apply(tagName, element, []); |
| 128 | 136 | if (tag !== "TEXTAREA" && tag !== "INPUT") return; |
| @@ -150,22 +158,39 @@ function prepareCopies(bindingName, token, contextSetter, limit) { | ||
| 150 | 158 | const selection = apply(getSelection, document, []); |
| 151 | 159 | return selection && apply(selectionText, selection, []); |
| 152 | 160 | }; |
| 161 | 新增: const hasCopySelection = () => { | |
| 162 | 新增: const element = focusedElement(); | |
| 163 | 新增: if (!element) return false; | |
| 164 | 新增: const tag = apply(tagName, element, []); | |
| 165 | 新增: if (tag === "INPUT" || tag === "TEXTAREA") { | |
| 166 | 新增: if (tag === "INPUT") { | |
| 167 | 新增: const type = apply(inputType, element, []); | |
| 168 | 新增: if (type !== "text" && type !== "search" && type !== "url" && type !== "tel") return false; | |
| 169 | 新增: } | |
| 170 | 新增: const start = apply(tag === "INPUT" ? inputStart : textareaStart, element, []); | |
| 171 | 新增: const end = apply(tag === "INPUT" ? inputEnd : textareaEnd, element, []); | |
| 172 | 新增: return start !== null && end > start; | |
| 173 | 新增: } | |
| 174 | 新增: const selection = apply(getSelection, document, []); | |
| 175 | 新增: return selection && !apply(selectionCollapsed, selection, []); | |
| 176 | 新增: }; | |
| 153 | 177 | const send = (text, started) => { |
| 154 | 178 | if ( |
| 155 | 179 | started === null || |
| 156 | 180 | epoch !== started.epoch || |
| 157 | 181 | !current() || |
| 158 | 删除: typeof text !== "string" || | |
| 159 | 删除: text.length > limit | |
| 182 | 新增: !includeChanges && (typeof text !== "string" || text.length > limit) | |
| 160 | 183 | ) |
| 161 | 184 | return; |
| 185 | 新增: const content = typeof text === "string" && text.length <= limit | |
| 186 | 新增: ? ',"text":' + stringify(text) | |
| 187 | 新增: : ',"changed":true'; | |
| 162 | 188 | emit( |
| 163 | 189 | '{"token":"' + |
| 164 | 190 | token + |
| 165 | 191 | '","context":' + |
| 166 | 192 | stringify(started.context) + |
| 167 | 删除: ',"text":' + | |
| 168 | 删除: stringify(text) + | |
| 193 | 新增: content + | |
| 169 | 194 | "}", |
| 170 | 195 | ); |
| 171 | 196 | }; |
| @@ -229,7 +254,9 @@ function prepareCopies(bindingName, token, contextSetter, limit) { | ||
| 229 | 254 | }, |
| 230 | 255 | }); |
| 231 | 256 | const promise = apply(write, this, [items]); |
| 232 | 删除: if (started === null || items.length !== 1) return promise; | |
| 257 | 新增: if (started === null) return promise; | |
| 258 | 新增: if (includeChanges) return watch(promise, undefined, started); | |
| 259 | 新增: if (items.length !== 1) return promise; | |
| 233 | 260 | let text, |
| 234 | 261 | written = false; |
| 235 | 262 | const completed = () => { |
| @@ -297,16 +324,27 @@ function prepareCopies(bindingName, token, contextSetter, limit) { | ||
| 297 | 324 | return result; |
| 298 | 325 | }, |
| 299 | 326 | }); |
| 300 | 删除: apply(addListener, document, [ | |
| 301 | 删除: "copy", | |
| 327 | 新增: const copied = | |
| 302 | 328 | (event) => { |
| 303 | 删除: if (operation && event.isTrusted) { | |
| 329 | 新增: if (!event.isTrusted) return; | |
| 330 | 新增: if (operation && !operation.native) { | |
| 304 | 331 | operation.event = event; |
| 305 | 332 | operation.data = apply(clipboardData, event, []); |
| 333 | 新增: } else if (includeChanges) { | |
| 334 | 新增: const copy = { native: true, event, data: apply(clipboardData, event, []), started: begin(), selected: hasCopySelection() }; | |
| 335 | 新增: operation = copy; | |
| 336 | 新增: // The default copy runs after the DOM event. A trusted no-selection | |
| 337 | 新增: // or password-field event must never export an older clipboard. | |
| 338 | 新增: apply(schedule, globalThis, [() => { | |
| 339 | 新增: if (operation === copy) operation = undefined; | |
| 340 | 新增: if (apply(prevented, event, [])) { | |
| 341 | 新增: if (typeof copy.text === "string") send(copy.text, copy.started); | |
| 342 | 新增: } else if (copy.selected) send(undefined, copy.started); | |
| 343 | 新增: }, 0]); | |
| 306 | 344 | } |
| 307 | 删除: }, | |
| 308 | 删除: true, | |
| 309 | 删除: ]); | |
| 345 | 新增: }; | |
| 346 | 新增: apply(addListener, document, ["copy", copied, true]); | |
| 347 | 新增: if (includeChanges) apply(addListener, document, ["cut", copied, true]); | |
| 310 | 348 | define(documentPrototype, "execCommand", { |
| 311 | 349 | configurable: true, |
| 312 | 350 | writable: true, |
| @@ -317,7 +355,7 @@ function prepareCopies(bindingName, token, contextSetter, limit) { | ||
| 317 | 355 | if (apply(lower, name, []) !== "copy" || this !== document) |
| 318 | 356 | return apply(exec, this, [name, ...args]); |
| 319 | 357 | const parent = operation; |
| 320 | 删除: const copy = { started: begin() }; | |
| 358 | 新增: const copy = { started: begin(), selected: includeChanges && hasCopySelection() }; | |
| 321 | 359 | operation = copy; |
| 322 | 360 | let result; |
| 323 | 361 | try { |
| @@ -326,12 +364,15 @@ function prepareCopies(bindingName, token, contextSetter, limit) { | ||
| 326 | 364 | operation = parent; |
| 327 | 365 | } |
| 328 | 366 | if (result && copy.event) { |
| 329 | 删除: if (apply(prevented, copy.event, [])) send(copy.text, copy.started); | |
| 367 | 新增: if (apply(prevented, copy.event, [])) { | |
| 368 | 新增: if (typeof copy.text === "string") send(copy.text, copy.started); | |
| 369 | 新增: } | |
| 330 | 370 | else { |
| 331 | 371 | // Chromium's default DOM copy may add image alt text or transform |
| 332 | 372 | // whitespace. Text controls have an exact selection representation. |
| 333 | 373 | const text = selectedControlText(); |
| 334 | 374 | if (text) send(text, copy.started); |
| 375 | 新增: else if (copy.selected) send(undefined, copy.started); | |
| 335 | 376 | } |
| 336 | 377 | } |
| 337 | 378 | return result; |
| @@ -342,9 +383,10 @@ function prepareCopies(bindingName, token, contextSetter, limit) { | ||
| 342 | 383 | } |
| 343 | 384 | |
| 344 | 385 | export class BrowserClipboard { |
| 345 | 删除: constructor(cdp, onCopy) { | |
| 386 | 新增: constructor(cdp, onCopy, { includeChanges = false } = {}) { | |
| 346 | 387 | this.cdp = cdp; |
| 347 | 388 | this.onCopy = onCopy; |
| 389 | 新增: this.includeChanges = includeChanges; | |
| 348 | 390 | this.sessions = new Map(); |
| 349 | 391 | this.copyContexts = new Map(); |
| 350 | 392 | } |
| @@ -369,7 +411,7 @@ export class BrowserClipboard { | ||
| 369 | 411 | await this.cdp("Page.enable", {}, sessionId); |
| 370 | 412 | await this.cdp("Runtime.enable", {}, sessionId); |
| 371 | 413 | await this.cdp("Runtime.addBinding", { name: state.name }, sessionId); |
| 372 | 删除: const source = `(${prepareCopies})(${JSON.stringify(state.name)},${JSON.stringify(state.token)},${JSON.stringify(state.contextSetter)},65536)`; | |
| 414 | 新增: const source = `(${prepareCopies})(${JSON.stringify(state.name)},${JSON.stringify(state.token)},${JSON.stringify(state.contextSetter)},65536,${this.includeChanges})`; | |
| 373 | 415 | await this.cdp( |
| 374 | 416 | "Page.addScriptToEvaluateOnNewDocument", |
| 375 | 417 | { source: `(${source})?.install()` }, |
| @@ -572,13 +614,12 @@ export class BrowserClipboard { | ||
| 572 | 614 | value?.token !== state.token || |
| 573 | 615 | typeof value.context !== "string" || |
| 574 | 616 | value.context.length > 64 || |
| 575 | 删除: typeof value.text !== "string" || | |
| 576 | 删除: value.text.length > 65536 | |
| 617 | 新增: !(typeof value.text === "string" && value.text.length <= 65536 || this.includeChanges && value.changed === true && value.text === undefined) | |
| 577 | 618 | ) |
| 578 | 619 | return; |
| 579 | 620 | this.onCopy({ |
| 580 | 621 | id: state.tabId, |
| 581 | 删除: text: value.text, | |
| 622 | 新增: ...(typeof value.text === "string" ? { text: value.text } : { changed: true }), | |
| 582 | 623 | context: value.context, |
| 583 | 624 | }); |
| 584 | 625 | } |
| @@ -113,6 +113,20 @@ test("host copy context reaches every existing frame and newly attached child", | ||
| 113 | 113 | assert.equal(observer.sessions.size, 0); |
| 114 | 114 | }); |
| 115 | 115 | |
| 116 | 新增:test("private clipboard format notifications require an enabled receiver and the binding token", async () => { | |
| 117 | 新增: for (const includeChanges of [false, true]) { | |
| 118 | 新增: const copies = []; | |
| 119 | 新增: const observer = new BrowserClipboard(async () => ({}), value => copies.push(value), { includeChanges }); | |
| 120 | 新增: await observer.attach("session", "tab"); | |
| 121 | 新增: const state = observer.sessions.get("session"); | |
| 122 | 新增: observer.event({ sessionId: "session", method: "Runtime.executionContextCreated", params: { context: { id: 1, auxData: { isDefault: true, frameId: "frame" } } } }); | |
| 123 | 新增: for (const token of ["wrong", state.token]) observer.event({ sessionId: "session", method: "Runtime.bindingCalled", params: { | |
| 124 | 新增: name: state.name, executionContextId: 1, payload: JSON.stringify({ token, context: "gesture", changed: true }), | |
| 125 | 新增: } }); | |
| 126 | 新增: assert.deepEqual(copies, includeChanges ? [{ id: "tab", context: "gesture", changed: true }] : []); | |
| 127 | 新增: } | |
| 128 | 新增:}); | |
| 129 | 新增: | |
| 116 | 130 | test("failed setup removes the session and allows retry", async () => { |
| 117 | 131 | let fail = true; |
| 118 | 132 | const observer = new BrowserClipboard( |
| @@ -321,6 +321,13 @@ class Portal: | ||
| 321 | 321 | <arg type="a{sv}" direction="in"/><arg type="o" direction="out"/></method> |
| 322 | 322 | <method name="SaveFile"><arg type="s" direction="in"/><arg type="s" direction="in"/> |
| 323 | 323 | <arg type="a{sv}" direction="in"/><arg type="o" direction="out"/></method> |
| 324 | 新增: </interface><interface name="org.freedesktop.portal.OpenURI"> | |
| 325 | 新增: <property name="version" type="u" access="read"/> | |
| 326 | 新增: <method name="OpenDirectory"><arg type="s" direction="in"/><arg type="h" direction="in"/> | |
| 327 | 新增: <arg type="a{sv}" direction="in"/><arg type="o" direction="out"/></method> | |
| 328 | 新增: </interface><interface name="org.freedesktop.FileManager1"> | |
| 329 | 新增: <method name="ShowItems"><arg type="as" direction="in"/><arg type="s" direction="in"/></method> | |
| 330 | 新增: <method name="ShowFolders"><arg type="as" direction="in"/><arg type="s" direction="in"/></method> | |
| 324 | 331 | </interface><interface name="org.freedesktop.portal.Request"> |
| 325 | 332 | <method name="Close"/><signal name="Response"><arg type="u"/><arg type="a{sv}"/></signal> |
| 326 | 333 | </interface></node>''' |
| @@ -362,6 +369,17 @@ class Portal: | ||
| 362 | 369 | self.unref(name_reply) |
| 363 | 370 | if code_value != 1: |
| 364 | 371 | raise RuntimeError('已有其他桌面文件选择服务') |
| 372 | 新增: name_reply = call(self.connection, b'org.freedesktop.DBus', b'/org/freedesktop/DBus', b'org.freedesktop.DBus', | |
| 373 | 新增: b'RequestName', self.tuple(self.new_string(b'org.freedesktop.FileManager1'), self.new_uint(4)), | |
| 374 | 新增: None, 0, 5000, None, None) | |
| 375 | 新增: if not name_reply: | |
| 376 | 新增: raise RuntimeError('本机文件打开服务无法注册') | |
| 377 | 新增: code = self.child(name_reply, 0) | |
| 378 | 新增: code_value = bind(self.glib, 'g_variant_get_uint32', u, p)(code) | |
| 379 | 新增: self.unref(code) | |
| 380 | 新增: self.unref(name_reply) | |
| 381 | 新增: if code_value != 1: | |
| 382 | 新增: raise RuntimeError('已有其他文件管理服务') | |
| 365 | 383 | self.reply = bind(self.gio, 'g_dbus_method_invocation_return_value', None, p, p) |
| 366 | 384 | self.error = bind(self.gio, 'g_dbus_method_invocation_return_dbus_error', None, p, s, s) |
| 367 | 385 | self.emit = bind(self.gio, 'g_dbus_connection_emit_signal', C.c_int, p, s, s, s, s, p, p) |
| @@ -378,6 +396,10 @@ class Portal: | ||
| 378 | 396 | self.vtable = VTable(self.method_callback, self.property_callback, None) |
| 379 | 397 | if not self.register(self.connection, ROOT.encode(), self.interface(self.node, PORTAL.encode()), C.byref(self.vtable), None, None, None): |
| 380 | 398 | raise RuntimeError('桌面文件选择接口无法注册') |
| 399 | 新增: for object_path, interface in ((ROOT, 'org.freedesktop.portal.OpenURI'), | |
| 400 | 新增: ('/org/freedesktop/FileManager1', 'org.freedesktop.FileManager1')): | |
| 401 | 新增: if not self.register(self.connection, object_path.encode(), self.interface(self.node, interface.encode()), C.byref(self.vtable), None, None, None): | |
| 402 | 新增: raise RuntimeError('本机文件打开接口无法注册') | |
| 381 | 403 | self.loop = bind(self.glib, 'g_main_loop_new', p, p, C.c_int)(None, False) |
| 382 | 404 | |
| 383 | 405 | def tuple(self, *values): |
| @@ -401,6 +423,22 @@ class Portal: | ||
| 401 | 423 | |
| 402 | 424 | def method(self, _connection, sender, path, _interface, method, parameters, invocation, _data): |
| 403 | 425 | try: |
| 426 | 新增: if method in (b'ShowItems', b'ShowFolders'): | |
| 427 | 新增: uris = self.child(parameters, 0) | |
| 428 | 新增: try: | |
| 429 | 新增: count = bind(self.glib, 'g_variant_n_children', C.c_size_t, C.c_void_p)(uris) | |
| 430 | 新增: if count > 32: | |
| 431 | 新增: raise ValueError('一次最多打开 32 个位置') | |
| 432 | 新增: for index in range(count): | |
| 433 | 新增: uri = self.child(uris, index) | |
| 434 | 新增: try: | |
| 435 | 新增: self.broker.open_path(self.string(uri, None).decode(), 'reveal' if method == b'ShowItems' else 'open') | |
| 436 | 新增: finally: | |
| 437 | 新增: self.unref(uri) | |
| 438 | 新增: finally: | |
| 439 | 新增: self.unref(uris) | |
| 440 | 新增: self.reply(invocation, self.tuple()) | |
| 441 | 新增: return | |
| 404 | 442 | if method == b'Close': |
| 405 | 443 | request = next((r for r in self.broker.requests.values() if r.get('handle') == path.decode() and r.get('sender') == sender.decode()), None) |
| 406 | 444 | if request: |
| @@ -424,9 +462,24 @@ class Portal: | ||
| 424 | 462 | key = None |
| 425 | 463 | try: |
| 426 | 464 | saving = method == b'SaveFile' |
| 427 | 删除: key = self.broker.start('save' if saving else 'chooser', self.option(options, 'multiple', False) and not directory, | |
| 428 | 删除: directory=directory, | |
| 429 | 删除: handle=handle, sender=sender.decode(), title=self.string(title, None).decode())['id'] | |
| 465 | 新增: if method == b'OpenDirectory': | |
| 466 | 新增: # The handle belongs to the caller's D-Bus message, not | |
| 467 | 新增: # to this service's file descriptor table. | |
| 468 | 新增: message = bind(self.gio, 'g_dbus_method_invocation_get_message', C.c_void_p, C.c_void_p)(invocation) | |
| 469 | 新增: descriptors = bind(self.gio, 'g_dbus_message_get_unix_fd_list', C.c_void_p, C.c_void_p)(message) | |
| 470 | 新增: index = bind(self.glib, 'g_variant_get_handle', C.c_int, C.c_void_p)(title) | |
| 471 | 新增: fd = bind(self.gio, 'g_unix_fd_list_get', C.c_int, C.c_void_p, C.c_int, C.c_void_p)(descriptors, index, None) if descriptors else -1 | |
| 472 | 新增: if fd < 0: | |
| 473 | 新增: raise ValueError('文件位置无法读取') | |
| 474 | 新增: try: | |
| 475 | 新增: key = self.broker.open_path(os.readlink('/proc/self/fd/' + str(fd)), 'reveal', | |
| 476 | 新增: handle=handle, sender=sender.decode())['id'] | |
| 477 | 新增: finally: | |
| 478 | 新增: os.close(fd) | |
| 479 | 新增: else: | |
| 480 | 新增: key = self.broker.start('save' if saving else 'chooser', self.option(options, 'multiple', False) and not directory, | |
| 481 | 新增: directory=directory, | |
| 482 | 新增: handle=handle, sender=sender.decode(), title=self.string(title, None).decode())['id'] | |
| 430 | 483 | if saving: |
| 431 | 484 | if not self.broker.downloads: |
| 432 | 485 | raise ValueError('下载服务不可用') |
| @@ -548,6 +601,29 @@ def clipboard(paths, expected_context=None): | ||
| 548 | 601 | |
| 549 | 602 | |
| 550 | 603 | def main(): |
| 604 | 新增: if len(sys.argv) == 3 and sys.argv[1] == '--open': | |
| 605 | 新增: import http.client | |
| 606 | 新增: import socket | |
| 607 | 新增: class Connection(http.client.HTTPConnection): | |
| 608 | 新增: def connect(self): | |
| 609 | 新增: self.sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) | |
| 610 | 新增: self.sock.settimeout(self.timeout) | |
| 611 | 新增: self.sock.connect('/run/cage-desktop/files.sock') | |
| 612 | 新增: client = Connection('localhost', timeout=5) | |
| 613 | 新增: try: | |
| 614 | 新增: # Electron's folder fallback invokes `xdg-open .` with the target | |
| 615 | 新增: # directory as its cwd. Preserve the caller's cwd across the socket. | |
| 616 | 新增: path = sys.argv[2] | |
| 617 | 新增: if not path.startswith('file:'): | |
| 618 | 新增: path = str(Path(path).resolve(strict=True)) | |
| 619 | 新增: client.request('POST', '/open', json.dumps({'path': path}), {'Content-Type': 'application/json'}) | |
| 620 | 新增: response = client.getresponse() | |
| 621 | 新增: data = response.read() | |
| 622 | 新增: if response.status != 200: | |
| 623 | 新增: raise ValueError(data.decode()) | |
| 624 | 新增: finally: | |
| 625 | 新增: client.close() | |
| 626 | 新增: return | |
| 551 | 627 | if len(sys.argv) == 3 and sys.argv[1] == '--save-file': |
| 552 | 628 | # Terminal attachments are independent of the graphical session. |
| 553 | 629 | root = Path.home() / '.local/share/cage/attachments/files' |
| @@ -2,20 +2,58 @@ package cage | ||
| 2 | 2 | |
| 3 | 3 | import ( |
| 4 | 4 | "encoding/json" |
| 5 | 删除: "github.com/sylvinus/agent-vm/internal/paths" | |
| 5 | 新增: "errors" | |
| 6 | 6 | "os" |
| 7 | 7 | "path/filepath" |
| 8 | 8 | "strings" |
| 9 | 9 | |
| 10 | 新增: "github.com/sylvinus/agent-vm/internal/paths" | |
| 10 | 11 | "github.com/sylvinus/agent-vm/internal/vmname" |
| 11 | 12 | ) |
| 12 | 13 | |
| 13 | 删除:// EnvironmentDir is the stable VM anchor for this profile, independent of projects. | |
| 14 | 删除:func EnvironmentDir(profile string) string { | |
| 15 | 删除: var saved struct { | |
| 16 | 删除: Directory string `json:"directory"` | |
| 14 | 新增:type EnvironmentRecord struct { | |
| 15 | 新增: Directory string `json:"directory"` | |
| 16 | 新增: IdentityDirectory string `json:"identity_directory,omitempty"` | |
| 17 | 新增:} | |
| 18 | 新增: | |
| 19 | 新增:func LoadEnvironmentRecord(profile string) (EnvironmentRecord, error) { | |
| 20 | 新增: var saved EnvironmentRecord | |
| 21 | 新增: data, err := os.ReadFile(filepath.Join(profile, "environment.json")) | |
| 22 | 新增: if errors.Is(err, os.ErrNotExist) { | |
| 23 | 新增: return saved, nil | |
| 24 | 新增: } | |
| 25 | 新增: if err != nil { | |
| 26 | 新增: return saved, err | |
| 27 | 新增: } | |
| 28 | 新增: if json.Unmarshal(data, &saved) != nil || !filepath.IsAbs(saved.Directory) || | |
| 29 | 新增: saved.IdentityDirectory != "" && !filepath.IsAbs(saved.IdentityDirectory) { | |
| 30 | 新增: return saved, errors.New("环境工作目录记录无效,请保留原配置并导出诊断记录") | |
| 17 | 31 | } |
| 18 | 删除: if b, err := os.ReadFile(filepath.Join(profile, "environment.json")); err == nil && json.Unmarshal(b, &saved) == nil && filepath.IsAbs(saved.Directory) { | |
| 32 | 新增: return saved, nil | |
| 33 | 新增:} | |
| 34 | 新增: | |
| 35 | 新增:// DefaultEnvironmentDir keeps generated workspaces outside the default profile, | |
| 36 | 新增:// including independent profiles stored below that profile's directory. | |
| 37 | 新增:func DefaultEnvironmentDir(profile string) string { | |
| 38 | 新增: path := filepath.Clean(profile) + "-workspace" | |
| 39 | 新增: if home, err := os.UserHomeDir(); err == nil { | |
| 40 | 新增: defaultProfile := filepath.Join(home, ".claude-cage") | |
| 41 | 新增: if !paths.Equal(profile, defaultProfile) && StorageContains(defaultProfile, profile) { | |
| 42 | 新增: if relative, err := filepath.Rel(defaultProfile, profile); err == nil { | |
| 43 | 新增: path = filepath.Join(defaultProfile+"-workspaces", relative) | |
| 44 | 新增: } | |
| 45 | 新增: } | |
| 46 | 新增: } | |
| 47 | 新增: if real, err := filepath.EvalSymlinks(path); err == nil { | |
| 48 | 新增: return real | |
| 49 | 新增: } | |
| 50 | 新增: return path | |
| 51 | 新增:} | |
| 52 | 新增: | |
| 53 | 新增:// EnvironmentDir is the default shared workspace, independent of the currently | |
| 54 | 新增:// selected project. IdentityDirectory retains a legacy VM's naming input. | |
| 55 | 新增:func EnvironmentDir(profile string) string { | |
| 56 | 新增: if saved, err := LoadEnvironmentRecord(profile); err == nil && saved.Directory != "" { | |
| 19 | 57 | return saved.Directory |
| 20 | 58 | } |
| 21 | 59 | // CLI and desktop upgrades must retain the same existing virtual disk. |
| @@ -27,16 +65,27 @@ func EnvironmentDir(profile string) string { | ||
| 27 | 65 | return legacy.Workspace |
| 28 | 66 | } |
| 29 | 67 | } |
| 30 | 删除: path := filepath.Clean(profile) + "-workspace" | |
| 31 | 删除: if real, err := filepath.EvalSymlinks(path); err == nil { | |
| 32 | 删除: return real | |
| 68 | 新增: previous := filepath.Clean(profile) + "-workspace" | |
| 69 | 新增: if _, err := os.Stat(filepath.Join(profile, "state", "lima", InstanceName(profile, previous), "lima.yaml")); err == nil { | |
| 70 | 新增: return previous | |
| 33 | 71 | } |
| 34 | 删除: return path | |
| 72 | 新增: return DefaultEnvironmentDir(profile) | |
| 73 | 新增:} | |
| 74 | 新增: | |
| 75 | 新增:func EnvironmentIdentityDir(profile string) string { | |
| 76 | 新增: if saved, err := LoadEnvironmentRecord(profile); err == nil && saved.IdentityDirectory != "" { | |
| 77 | 新增: return saved.IdentityDirectory | |
| 78 | 新增: } | |
| 79 | 新增: return EnvironmentDir(profile) | |
| 35 | 80 | } |
| 36 | 81 | |
| 37 | 82 | // InstanceName is shared by the controller and each Cage CLI subprocess. |
| 38 | 83 | // It uses the same spelling as the CLI's AbsDir, including Windows drives. |
| 39 | 84 | func InstanceName(profile, workspace string) string { |
| 85 | 新增: if saved, err := LoadEnvironmentRecord(profile); err == nil && saved.IdentityDirectory != "" && | |
| 86 | 新增: paths.Equal(paths.Host(filepath.Clean(workspace)), paths.Host(filepath.Clean(saved.Directory))) { | |
| 87 | 新增: workspace = saved.IdentityDirectory | |
| 88 | 新增: } | |
| 40 | 89 | home := filepath.Join(profile, "state", "lima") |
| 41 | 90 | _, err := os.Stat(filepath.Join(profile, locationFile)) |
| 42 | 91 | logical := err == nil |
| @@ -18,7 +18,11 @@ case "${1:-}" in | ||
| 18 | 18 | set -- /new "$1" |
| 19 | 19 | fi |
| 20 | 20 | ;; |
| 21 | 删除: *) echo 'Only HTTP(S) browser URLs and Claude desktop callbacks are accepted.' >&2; exit 2;; | |
| 21 | 新增: *) | |
| 22 | 新增: # File operations belong to the desktop session, never the browser control | |
| 23 | 新增: # token. The host resolves them only within Cage project directories. | |
| 24 | 新增: exec /usr/local/bin/cage-desktop-files --open "${1:-}" | |
| 25 | 新增: ;; | |
| 22 | 26 | esac |
| 23 | 27 | # sudo records its arguments in the system journal. Send the URL on stdin. |
| 24 | 28 | browser_request() { |
| @@ -36,6 +36,31 @@ class CacheRegistry: | ||
| 36 | 36 | if not stat.S_ISDIR(info.st_mode) or info.st_uid != os.geteuid() or info.st_mode & 0o077: |
| 37 | 37 | raise ValueError('Clipboard ownership directory is not private') |
| 38 | 38 | |
| 39 | 新增: def session_path(self, session): | |
| 40 | 新增: if not isinstance(session, str) or not 1 <= len(session) <= 256 or any(c not in 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-' for c in session): | |
| 41 | 新增: raise ValueError('Invalid clipboard session') | |
| 42 | 新增: return self.directory / ('session-' + session) | |
| 43 | 新增: | |
| 44 | 新增: def begin_session(self, session): | |
| 45 | 新增: self.ensure_directory() | |
| 46 | 新增: path = self.session_path(session) | |
| 47 | 新增: with path.open('x') as output: | |
| 48 | 新增: os.chmod(path, 0o600) | |
| 49 | 新增: json.dump({'owner': os.getpid()}, output) | |
| 50 | 新增: | |
| 51 | 新增: def require_session(self, session): | |
| 52 | 新增: try: | |
| 53 | 新增: value = json.loads(self.session_path(session).read_text()) | |
| 54 | 新增: owner = value['owner'] | |
| 55 | 新增: if not isinstance(owner, int) or owner < 1: | |
| 56 | 新增: raise ValueError('Invalid clipboard session owner') | |
| 57 | 新增: os.kill(owner, 0) | |
| 58 | 新增: except (OSError, ValueError, KeyError, TypeError) as error: | |
| 59 | 新增: raise ValueError('Clipboard session changed') from error | |
| 60 | 新增: | |
| 61 | 新增: def end_session(self, session): | |
| 62 | 新增: self.session_path(session).unlink(missing_ok=True) | |
| 63 | 新增: | |
| 39 | 64 | def records(self): |
| 40 | 65 | if not self.directory.exists(): |
| 41 | 66 | return [] |
| @@ -55,7 +80,9 @@ class CacheRegistry: | ||
| 55 | 80 | or not isinstance(paths, list) or not 1 <= len(paths) <= 100 |
| 56 | 81 | or any(not isinstance(item, str) or Path(item).parent != Path(directory) or os.path.normpath(item) != item for item in paths) |
| 57 | 82 | or not isinstance(marker, str) or marker in ('', '.', '..') or Path(marker).name != marker |
| 58 | 删除: or not isinstance(record.get('session'), str) or not isinstance(record.get('retired'), bool)): | |
| 83 | 新增: or not isinstance(record.get('session'), str) or not isinstance(record.get('retired'), bool) | |
| 84 | 新增: or not isinstance(record.get('pending', False), bool) | |
| 85 | 新增: or record.get('pending') and (not isinstance(record.get('producer'), int) or record['producer'] < 1)): | |
| 59 | 86 | raise ValueError('Invalid clipboard ownership record') |
| 60 | 87 | records.append(record) |
| 61 | 88 | return records |
| @@ -70,7 +97,7 @@ class CacheRegistry: | ||
| 70 | 97 | finally: |
| 71 | 98 | Path(temporary).unlink(missing_ok=True) |
| 72 | 99 | |
| 73 | 删除: def register(self, paths, session): | |
| 100 | 新增: def register(self, paths, session, pending=False): | |
| 74 | 101 | root = Path(paths[0]).parent |
| 75 | 102 | identity = uuid.uuid4().hex |
| 76 | 103 | fd, marker = tempfile.mkstemp(dir=root, prefix='.cage-clipboard-owner-') |
| @@ -80,8 +107,10 @@ class CacheRegistry: | ||
| 80 | 107 | lock = self.directory / (identity + '.lock') |
| 81 | 108 | lock.touch(mode=0o600, exist_ok=False) |
| 82 | 109 | try: |
| 83 | 删除: self.save({'id': identity, 'directory': str(root), 'marker': Path(marker).name, | |
| 84 | 删除: 'paths': paths, 'session': session, 'retired': False}) | |
| 110 | 新增: record = {'id': identity, 'directory': str(root), 'marker': Path(marker).name, | |
| 111 | 新增: 'paths': paths, 'session': session, 'retired': False, 'pending': pending, 'producer': os.getpid()} | |
| 112 | 新增: self.save(record) | |
| 113 | 新增: return record | |
| 85 | 114 | except BaseException: |
| 86 | 115 | lock.unlink(missing_ok=True) |
| 87 | 116 | raise |
| @@ -118,7 +147,13 @@ class CacheRegistry: | ||
| 118 | 147 | def collect(self, selected, session): |
| 119 | 148 | for record in self.records(): |
| 120 | 149 | root = Path(record['directory']) |
| 121 | 删除: if root.exists() and not record['retired'] and (not record['session'] or record['session'] == session): | |
| 150 | 新增: if root.exists() and record.get('pending') and not record['retired']: | |
| 151 | 新增: try: | |
| 152 | 新增: os.kill(record['producer'], 0) | |
| 153 | 新增: continue | |
| 154 | 新增: except ProcessLookupError: | |
| 155 | 新增: pass | |
| 156 | 新增: if root.exists() and not record.get('pending') and not record['retired'] and (not record['session'] or record['session'] == session): | |
| 122 | 157 | continue |
| 123 | 158 | if any(Path(path).is_relative_to(root) or root.is_relative_to(Path(path)) for path in selected): |
| 124 | 159 | continue |
| @@ -182,13 +217,25 @@ def export_files(paths, output): | ||
| 182 | 217 | |
| 183 | 218 | |
| 184 | 219 | def import_files(source, session=''): |
| 220 | 新增: registry = CacheRegistry() | |
| 221 | 新增: if session: | |
| 222 | 新增: registry.require_session(session) | |
| 185 | 223 | root = Path(tempfile.mkdtemp(prefix='cage-clipboard-')) |
| 224 | 新增: record = None | |
| 186 | 225 | try: |
| 226 | 新增: record = registry.register([str(root / '.pending')], session, pending=True) | |
| 187 | 227 | paths = extract_files(source, root) |
| 188 | 删除: CacheRegistry().register(paths, session) | |
| 228 | 新增: record['paths'] = paths | |
| 229 | 新增: record['pending'] = False | |
| 230 | 新增: registry.save(record) | |
| 231 | 新增: if session: | |
| 232 | 新增: registry.require_session(session) | |
| 189 | 233 | return paths |
| 190 | 234 | except BaseException: |
| 191 | 235 | shutil.rmtree(root) |
| 236 | 新增: if record: | |
| 237 | 新增: (registry.directory / (record['id'] + '.json')).unlink(missing_ok=True) | |
| 238 | 新增: (registry.directory / (record['id'] + '.lock')).unlink(missing_ok=True) | |
| 192 | 239 | raise |
| 193 | 240 | |
| 194 | 241 | |
| @@ -466,6 +513,7 @@ def bridge(): | ||
| 466 | 513 | session = str(uuid.uuid4()) |
| 467 | 514 | announced = None |
| 468 | 515 | registry = CacheRegistry() |
| 516 | 新增: registry.begin_session(session) | |
| 469 | 517 | current_files = {} |
| 470 | 518 | next_cache_check = 0 |
| 471 | 519 | cleanup_needed = True |
| @@ -598,6 +646,7 @@ def bridge(): | ||
| 598 | 646 | next_cache_check = time.monotonic() + 1 |
| 599 | 647 | finally: |
| 600 | 648 | try: |
| 649 | 新增: registry.end_session(session) | |
| 601 | 650 | for record in registry.records(): |
| 602 | 651 | if record['session'] == session: |
| 603 | 652 | registry.retire(record['paths']) |
| @@ -97,8 +97,9 @@ class CacheOwnershipTests(unittest.TestCase): | ||
| 97 | 97 | clipboard.export_files(self.paths, source) |
| 98 | 98 | source.seek(0) |
| 99 | 99 | with patch.object(clipboard.tempfile, 'tempdir', str(self.root)): |
| 100 | 删除: paths = clipboard.import_files(source, 'import-session') | |
| 101 | 100 | registry = clipboard.CacheRegistry() |
| 101 | 新增: registry.begin_session('import-session') | |
| 102 | 新增: paths = clipboard.import_files(source, 'import-session') | |
| 102 | 103 | self.assertEqual(registry.records()[0]['paths'], paths) |
| 103 | 104 | registry.retire(paths) |
| 104 | 105 | registry.collect([], 'import-session') |
| @@ -112,12 +113,46 @@ class CacheOwnershipTests(unittest.TestCase): | ||
| 112 | 113 | entry.size = 1 |
| 113 | 114 | archive.addfile(entry, io.BytesIO(b'x')) |
| 114 | 115 | source.seek(0) |
| 115 | 删除: before = set(self.root.iterdir()) | |
| 116 | 116 | with patch.object(clipboard.tempfile, 'tempdir', str(self.root)): |
| 117 | 新增: clipboard.CacheRegistry().ensure_directory() | |
| 118 | 新增: before = set(self.root.iterdir()) | |
| 117 | 119 | with self.assertRaises(ValueError): |
| 118 | 删除: clipboard.import_files(source, 'import-session') | |
| 120 | 新增: clipboard.import_files(source) | |
| 119 | 121 | self.assertEqual(set(self.root.iterdir()), before) |
| 120 | 122 | |
| 123 | 新增: def test_an_import_finishing_after_disconnect_releases_its_created_directory(self): | |
| 124 | 新增: source = io.BytesIO() | |
| 125 | 新增: clipboard.export_files(self.paths, source) | |
| 126 | 新增: source.seek(0) | |
| 127 | 新增: with patch.object(clipboard.tempfile, 'tempdir', str(self.root)): | |
| 128 | 新增: registry = clipboard.CacheRegistry() | |
| 129 | 新增: registry.begin_session('import-session') | |
| 130 | 新增: original = clipboard.extract_files | |
| 131 | 新增: created = [] | |
| 132 | 新增: def disconnected(stream, root): | |
| 133 | 新增: created.append(root) | |
| 134 | 新增: paths = original(stream, root) | |
| 135 | 新增: registry.end_session('import-session') | |
| 136 | 新增: return paths | |
| 137 | 新增: with patch.object(clipboard, 'extract_files', side_effect=disconnected): | |
| 138 | 新增: with self.assertRaises(ValueError): | |
| 139 | 新增: clipboard.import_files(source, 'import-session') | |
| 140 | 新增: self.assertFalse(created[0].exists()) | |
| 141 | 新增: registry.collect([], 'next-session') | |
| 142 | 新增: self.assertEqual(registry.records(), []) | |
| 143 | 新增: self.assertEqual(self.file.read_bytes(), b'complete copied bytes') | |
| 144 | 新增: | |
| 145 | 新增: def test_an_incomplete_copy_keeps_a_live_producer_and_reclaims_a_terminated_one(self): | |
| 146 | 新增: record = self.registry.records()[0] | |
| 147 | 新增: record['pending'] = True | |
| 148 | 新增: self.registry.save(record) | |
| 149 | 新增: self.registry.collect([], 'next-session') | |
| 150 | 新增: self.assertTrue(self.cache.exists()) | |
| 151 | 新增: record['producer'] = 2147483647 | |
| 152 | 新增: self.registry.save(record) | |
| 153 | 新增: self.registry.collect([], 'next-session') | |
| 154 | 新增: self.assertFalse(self.cache.exists()) | |
| 155 | 新增: | |
| 121 | 156 | |
| 122 | 157 | if __name__ == '__main__': |
| 123 | 158 | unittest.main() |
| @@ -56,11 +56,16 @@ func RecoverStorage(ctx context.Context, profile string, runtime StorageRuntime) | ||
| 56 | 56 | |
| 57 | 57 | // CopyStorage copies an additional runtime-owned directory into a fresh private |
| 58 | 58 | // directory. It uses the same sparse-file and digest verification as the move. |
| 59 | 删除:func CopyStorage(ctx context.Context, source, target string, report func(int64, int64)) error { | |
| 59 | 新增:func CopyStorage(ctx context.Context, source, target string, excluded []string, report func(int64, int64)) error { | |
| 60 | 新增: for _, path := range excluded { | |
| 61 | 新增: if !filepath.IsAbs(path) || sameStoragePath(path, source) || !StorageContains(source, path) { | |
| 62 | 新增: return errors.New("客机管理文件超出当前存储目录") | |
| 63 | 新增: } | |
| 64 | 新增: } | |
| 60 | 65 | if err := os.Mkdir(target, 0700); err != nil { |
| 61 | 66 | return err |
| 62 | 67 | } |
| 63 | 删除: return copyStorage(ctx, source, target, report) | |
| 68 | 新增: return copyStorageExcluding(ctx, source, target, excluded, report) | |
| 64 | 69 | } |
| 65 | 70 | |
| 66 | 71 | func CopyStorageFile(ctx context.Context, source, target string) error { |
| @@ -97,6 +97,12 @@ func linkStorage(link, target string) (err error) { | ||
| 97 | 97 | } |
| 98 | 98 | |
| 99 | 99 | func sparseStorageFile(f *os.File) error { |
| 100 | 新增: // Hyper-V virtual disks manage their own allocation. Adding an NTFS sparse | |
| 101 | 新增: // attribute changes which Virtual Disk API open flags can mount the copy. | |
| 102 | 新增: switch strings.ToLower(filepath.Ext(f.Name())) { | |
| 103 | 新增: case ".vhd", ".vhdx", ".avhd", ".avhdx": | |
| 104 | 新增: return nil | |
| 105 | 新增: } | |
| 100 | 106 | var n uint32 |
| 101 | 107 | return windows.DeviceIoControl(windows.Handle(f.Fd()), windows.FSCTL_SET_SPARSE, nil, 0, nil, 0, &n, nil) |
| 102 | 108 | } |
| @@ -4,6 +4,7 @@ import ( | ||
| 4 | 4 | "strings" |
| 5 | 5 | "testing" |
| 6 | 6 | |
| 7 | 新增: agentvm "github.com/sylvinus/agent-vm" | |
| 7 | 8 | "github.com/sylvinus/agent-vm/internal/vm/vmtest" |
| 8 | 9 | ) |
| 9 | 10 | |
| @@ -17,7 +18,7 @@ func TestLicenses(t *testing.T) { | ||
| 17 | 18 | // binary: Apache-2.0 (with Lima's NOTICE), BSD-2 and BSD-3 ones. |
| 18 | 19 | for _, want := range []string{ |
| 19 | 20 | "MIT License", "Copyright (c) 2026 Sylvain Zimmer", |
| 20 | 删除: "third_party/ holds", "section 4(b)", | |
| 21 | 新增: agentvm.Notice, | |
| 21 | 22 | "github.com/lima-vm/lima/v2 ./third_party/lima: LICENSE", |
| 22 | 23 | "github.com/lima-vm/lima/v2 ./third_party/lima: NOTICE", |
| 23 | 24 | "github.com/lima-vm/sshocker ./third_party/sshocker: LICENSE", |
| @@ -262,7 +262,8 @@ func (store CacheStore) List() ([]CachedSelection, error) { | ||
| 262 | 262 | if err != nil { |
| 263 | 263 | return nil, err |
| 264 | 264 | } |
| 265 | 删除: if record.Pending && !cacheOwnerAlive(record.Producer) || !record.Pending && (record.Published || !cacheOwnerAlive(record.Owner)) { | |
| 265 | 新增: if record.Pending && !cacheOwnerAlive(record.Producer) || !record.Pending && | |
| 266 | 新增: (record.Published && record.Owner == os.Getppid() || !cacheOwnerAlive(record.Owner)) { | |
| 266 | 267 | selections = append(selections, record.CachedSelection) |
| 267 | 268 | } |
| 268 | 269 | } |
| @@ -313,13 +314,9 @@ func (store CacheStore) Release(id string) error { | ||
| 313 | 314 | } |
| 314 | 315 | } |
| 315 | 316 | } |
| 316 | 删除: if err := root.Remove(record.Marker); err != nil { | |
| 317 | 新增: if err := removeCacheDirectory(root, record); err != nil { | |
| 317 | 318 | return err |
| 318 | 319 | } |
| 319 | 删除: if err := os.Remove(record.Directory); err != nil { | |
| 320 | 删除: // A busy directory must retain its proof of ownership for a later retry. | |
| 321 | 删除: return errors.Join(err, root.WriteFile(record.Marker, []byte(id), 0600)) | |
| 322 | 删除: } | |
| 323 | 320 | return os.Remove(path) |
| 324 | 321 | } |
| 325 | 322 | |
| @@ -105,6 +105,26 @@ func TestCacheRejectsForeignOrMalformedIdentifiers(t *testing.T) { | ||
| 105 | 105 | } |
| 106 | 106 | } |
| 107 | 107 | |
| 108 | 新增:func TestCacheRecoveryLeavesAnotherLiveNativeOwnerInControl(t *testing.T) { | |
| 109 | 新增: store, selection := cacheFixture(t) | |
| 110 | 新增: record, err := store.load(selection.ID) | |
| 111 | 新增: if err != nil { | |
| 112 | 新增: t.Fatal(err) | |
| 113 | 新增: } | |
| 114 | 新增: record.Published = true | |
| 115 | 新增: record.Owner = os.Getpid() | |
| 116 | 新增: if err := store.save(record); err != nil { | |
| 117 | 新增: t.Fatal(err) | |
| 118 | 新增: } | |
| 119 | 新增: listed, err := store.List() | |
| 120 | 新增: if err != nil || len(listed) != 0 { | |
| 121 | 新增: t.Fatal("another live native owner's clipboard entered recovery", err) | |
| 122 | 新增: } | |
| 123 | 新增: if _, err := os.Stat(selection.Paths[0]); err != nil { | |
| 124 | 新增: t.Fatal(err) | |
| 125 | 新增: } | |
| 126 | 新增:} | |
| 127 | 新增: | |
| 108 | 128 | func TestCacheConcurrentPublishCannotRecreateAReleasedReceipt(t *testing.T) { |
| 109 | 129 | for range 20 { |
| 110 | 130 | store, selection := cacheFixture(t) |
| @@ -3,10 +3,21 @@ | ||
| 3 | 3 | package clipboardfiles |
| 4 | 4 | |
| 5 | 5 | import ( |
| 6 | 新增: "errors" | |
| 6 | 7 | "os" |
| 7 | 8 | "syscall" |
| 8 | 9 | ) |
| 9 | 10 | |
| 11 | 新增:func removeCacheDirectory(root *os.Root, record cacheRecord) error { | |
| 12 | 新增: if err := root.Remove(record.Marker); err != nil { | |
| 13 | 新增: return err | |
| 14 | 新增: } | |
| 15 | 新增: if err := os.Remove(record.Directory); err != nil { | |
| 16 | 新增: return errors.Join(err, root.WriteFile(record.Marker, []byte(record.ID), 0600)) | |
| 17 | 新增: } | |
| 18 | 新增: return nil | |
| 19 | 新增:} | |
| 20 | 新增: | |
| 10 | 21 | func lockCacheStore(file *os.File) (func(), error) { |
| 11 | 22 | if err := syscall.Flock(int(file.Fd()), syscall.LOCK_EX); err != nil { |
| 12 | 23 | return nil, err |
| @@ -1,11 +1,54 @@ | ||
| 1 | 1 | package clipboardfiles |
| 2 | 2 | |
| 3 | 3 | import ( |
| 4 | 新增: "errors" | |
| 4 | 5 | "os" |
| 6 | 新增: "path/filepath" | |
| 5 | 7 | |
| 6 | 8 | "golang.org/x/sys/windows" |
| 7 | 9 | ) |
| 8 | 10 | |
| 11 | 新增:func removeCacheDirectory(root *os.Root, record cacheRecord) error { | |
| 12 | 新增: identity, err := root.Stat(".") | |
| 13 | 新增: if err != nil { | |
| 14 | 新增: return err | |
| 15 | 新增: } | |
| 16 | 新增: // os.Root denies delete sharing on Windows. Replace it with a handle that | |
| 17 | 新增: // can remove this exact directory, and check its identity before deleting. | |
| 18 | 新增: if err := root.Close(); err != nil { | |
| 19 | 新增: return err | |
| 20 | 新增: } | |
| 21 | 新增: path, err := windows.UTF16PtrFromString(record.Directory) | |
| 22 | 新增: if err != nil { | |
| 23 | 新增: return err | |
| 24 | 新增: } | |
| 25 | 新增: handle, err := windows.CreateFile(path, windows.DELETE|windows.FILE_READ_ATTRIBUTES, | |
| 26 | 新增: windows.FILE_SHARE_READ|windows.FILE_SHARE_WRITE, nil, windows.OPEN_EXISTING, | |
| 27 | 新增: windows.FILE_FLAG_BACKUP_SEMANTICS|windows.FILE_FLAG_OPEN_REPARSE_POINT, 0) | |
| 28 | 新增: if err != nil { | |
| 29 | 新增: return err | |
| 30 | 新增: } | |
| 31 | 新增: file := os.NewFile(uintptr(handle), record.Directory) | |
| 32 | 新增: defer file.Close() | |
| 33 | 新增: current, err := file.Stat() | |
| 34 | 新增: if err != nil || !current.IsDir() || current.Mode()&os.ModeSymlink != 0 || !os.SameFile(identity, current) { | |
| 35 | 新增: return errors.New("clipboard cache directory identity changed") | |
| 36 | 新增: } | |
| 37 | 新增: marker := filepath.Join(record.Directory, record.Marker) | |
| 38 | 新增: contents, err := os.ReadFile(marker) | |
| 39 | 新增: if err != nil || string(contents) != record.ID { | |
| 40 | 新增: return errors.New("clipboard cache creation record no longer matches") | |
| 41 | 新增: } | |
| 42 | 新增: if err := os.Remove(marker); err != nil { | |
| 43 | 新增: return err | |
| 44 | 新增: } | |
| 45 | 新增: discard := byte(1) | |
| 46 | 新增: if err := windows.SetFileInformationByHandle(handle, windows.FileDispositionInfo, &discard, 1); err != nil { | |
| 47 | 新增: return errors.Join(err, os.WriteFile(marker, []byte(record.ID), 0600)) | |
| 48 | 新增: } | |
| 49 | 新增: return nil | |
| 50 | 新增:} | |
| 51 | 新增: | |
| 9 | 52 | func lockCacheStore(file *os.File) (func(), error) { |
| 10 | 53 | var overlapped windows.Overlapped |
| 11 | 54 | if err := windows.LockFileEx(windows.Handle(file.Fd()), windows.LOCKFILE_EXCLUSIVE_LOCK, 0, 1, 0, &overlapped); err != nil { |
| @@ -4,21 +4,32 @@ package guestos | ||
| 4 | 4 | // host file paths, clipboard contents, or global shortcuts are accepted. Only |
| 5 | 5 | // the authenticated host may attach a stored password to fill-password. |
| 6 | 6 | type MacLoginRequest struct { |
| 7 | 删除: Action string `json:"action"` | |
| 8 | 删除: Session string `json:"session,omitempty"` | |
| 9 | 删除: Setup bool `json:"initial_setup,omitempty"` | |
| 10 | 删除: Code int `json:"code"` | |
| 11 | 删除: Shift bool `json:"shift"` | |
| 12 | 删除: X int `json:"x"` | |
| 13 | 删除: Y int `json:"y"` | |
| 14 | 删除: DeltaX int `json:"delta_x,omitempty"` | |
| 15 | 删除: DeltaY int `json:"delta_y,omitempty"` | |
| 16 | 删除: Password string `json:"password,omitempty"` | |
| 7 | 新增: Action string `json:"action"` | |
| 8 | 新增: Session string `json:"session,omitempty"` | |
| 9 | 新增: Setup bool `json:"initial_setup,omitempty"` | |
| 10 | 新增: Maintenance string `json:"maintenance,omitempty"` | |
| 11 | 新增: Geometry string `json:"geometry,omitempty"` | |
| 12 | 新增: Code int `json:"code"` | |
| 13 | 新增: Shift bool `json:"shift"` | |
| 14 | 新增: X int `json:"x"` | |
| 15 | 新增: Y int `json:"y"` | |
| 16 | 新增: DeltaX int `json:"delta_x,omitempty"` | |
| 17 | 新增: DeltaY int `json:"delta_y,omitempty"` | |
| 18 | 新增: Password string `json:"password,omitempty"` | |
| 17 | 19 | } |
| 18 | 20 | type MacLoginReply struct { |
| 19 | 删除: MIME string `json:"mime,omitempty"` | |
| 20 | 删除: Session string `json:"session,omitempty"` | |
| 21 | 删除: Image []byte `json:"image,omitempty"` | |
| 22 | 删除: Error string `json:"error,omitempty"` | |
| 23 | 删除: Closed bool `json:"closed,omitempty"` | |
| 21 | 新增: MIME string `json:"mime,omitempty"` | |
| 22 | 新增: Session string `json:"session,omitempty"` | |
| 23 | 新增: Image []byte `json:"image,omitempty"` | |
| 24 | 新增: Error string `json:"error,omitempty"` | |
| 25 | 新增: Closed bool `json:"closed,omitempty"` | |
| 26 | 新增: Geometry string `json:"geometry,omitempty"` | |
| 27 | 新增: Region []int `json:"region,omitempty"` | |
| 28 | 新增: Recovery string `json:"recovery,omitempty"` | |
| 29 | 新增: Administrator string `json:"administrator,omitempty"` | |
| 30 | 新增: MaintenanceVersion int `json:"maintenance_version,omitempty"` | |
| 31 | 新增:} | |
| 32 | 新增: | |
| 33 | 新增:func ValidMacMaintenancePurpose(value string) bool { | |
| 34 | 新增: return value == "projects" || value == "screen" || value == "input" | |
| 24 | 35 | } |
| @@ -5,8 +5,10 @@ package guestos | ||
| 5 | 5 | import ( |
| 6 | 6 | "context" |
| 7 | 7 | "crypto/sha256" |
| 8 | 新增: "encoding/json" | |
| 8 | 9 | "errors" |
| 9 | 10 | "fmt" |
| 11 | 新增: "io" | |
| 10 | 12 | "os" |
| 11 | 13 | "os/exec" |
| 12 | 14 | "path/filepath" |
| @@ -37,3 +39,34 @@ func WindowsMaintenanceCommand(ctx context.Context, profile, kit, manifest strin | ||
| 37 | 39 | } |
| 38 | 40 | return exec.CommandContext(ctx, filepath.Join(system, "WindowsPowerShell", "v1.0", "powershell.exe"), args...), nil |
| 39 | 41 | } |
| 42 | 新增: | |
| 43 | 新增:// RepairWindowsHostManager uses the existing UAC maintenance entry point. It | |
| 44 | 新增:// updates the fixed host service without requiring a running GUI guest. | |
| 45 | 新增:func RepairWindowsHostManager(ctx context.Context, profile, kit string, stdout, stderr io.Writer) error { | |
| 46 | 新增: manifest, err := RequiredNativeComponents(kit, Windows11) | |
| 47 | 新增: if err != nil { | |
| 48 | 新增: return err | |
| 49 | 新增: } | |
| 50 | 新增: file, err := os.CreateTemp(profile, "native-host-repair-*.json") | |
| 51 | 新增: if err != nil { | |
| 52 | 新增: return err | |
| 53 | 新增: } | |
| 54 | 新增: defer os.Remove(file.Name()) | |
| 55 | 新增: err = json.NewEncoder(file).Encode(manifest) | |
| 56 | 新增: if err = errors.Join(err, file.Close()); err != nil { | |
| 57 | 新增: return err | |
| 58 | 新增: } | |
| 59 | 新增: command, err := WindowsMaintenanceCommand(ctx, profile, kit, file.Name(), false) | |
| 60 | 新增: if err != nil { | |
| 61 | 新增: return err | |
| 62 | 新增: } | |
| 63 | 新增: command.Args = append(command.Args, "-HostOnly") | |
| 64 | 新增: command.Stdout, command.Stderr = stdout, stderr | |
| 65 | 新增: if err := command.Run(); err != nil { | |
| 66 | 新增: if ctx.Err() != nil { | |
| 67 | 新增: return ctx.Err() | |
| 68 | 新增: } | |
| 69 | 新增: return err | |
| 70 | 新增: } | |
| 71 | 新增: return nil | |
| 72 | 新增:} | |
| @@ -0,0 +1,57 @@ | ||
| 1 | 新增://go:build windows | |
| 2 | 新增: | |
| 3 | 新增:package guestos | |
| 4 | 新增: | |
| 5 | 新增:import ( | |
| 6 | 新增: "context" | |
| 7 | 新增: "errors" | |
| 8 | 新增: "os" | |
| 9 | 新增: "os/exec" | |
| 10 | 新增: "path/filepath" | |
| 11 | 新增: "strings" | |
| 12 | 新增: "testing" | |
| 13 | 新增: "time" | |
| 14 | 新增: | |
| 15 | 新增: "github.com/sylvinus/agent-vm/internal/diagnostics" | |
| 16 | 新增:) | |
| 17 | 新增: | |
| 18 | 新增:func TestWindowsHostRepairPreservesProcessOutput(t *testing.T) { | |
| 19 | 新增: profile := t.TempDir() | |
| 20 | 新增: if err := BindWindowsProfile(profile, windowsBindingFixture(profile)); err != nil { | |
| 21 | 新增: t.Fatal(err) | |
| 22 | 新增: } | |
| 23 | 新增: kit := nativeManifestKit(t, Windows11) | |
| 24 | 新增: script := `param([string]$Profile,[string]$ManifestPath,[string]$ManifestSHA256,[switch]$HostOnly) | |
| 25 | 新增:$ErrorActionPreference='Stop' | |
| 26 | 新增:[Console]::OutputEncoding=[Text.UTF8Encoding]::new($false) | |
| 27 | 新增:if (!$HostOnly -or (Get-FileHash -LiteralPath $ManifestPath -Algorithm SHA256).Hash -ne $ManifestSHA256) { exit 38 } | |
| 28 | 新增:Write-Output 'repair-fixture-stdout' | |
| 29 | 新增:[Console]::Error.WriteLine('repair-fixture-service-registration-failed token=repair-fixture-secret') | |
| 30 | 新增:exit 37 | |
| 31 | 新增:` | |
| 32 | 新增: if err := os.WriteFile(filepath.Join(kit, "maintain-windows-workbench.ps1"), []byte(script), 0600); err != nil { | |
| 33 | 新增: t.Fatal(err) | |
| 34 | 新增: } | |
| 35 | 新增: var stdout, stderr strings.Builder | |
| 36 | 新增: out := diagnostics.NewStream(nil, "storage-recovery", "info", func(line string) { stdout.WriteString(line) }) | |
| 37 | 新增: errOut := diagnostics.NewStream(nil, "storage-recovery", "warn", func(line string) { stderr.WriteString(line) }) | |
| 38 | 新增: ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) | |
| 39 | 新增: defer cancel() | |
| 40 | 新增: err := RepairWindowsHostManager(ctx, profile, kit, out, errOut) | |
| 41 | 新增: _ = out.Close() | |
| 42 | 新增: _ = errOut.Close() | |
| 43 | 新增: var exit *exec.ExitError | |
| 44 | 新增: if !errors.As(err, &exit) || exit.ExitCode() != 37 { | |
| 45 | 新增: t.Fatalf("repair lost the original process result: %v", err) | |
| 46 | 新增: } | |
| 47 | 新增: if !strings.Contains(stdout.String(), "repair-fixture-stdout") || !strings.Contains(stderr.String(), "repair-fixture-service-registration-failed") { | |
| 48 | 新增: t.Fatalf("repair output did not reach the shared diagnostic streams: stdout=%q stderr=%q", stdout.String(), stderr.String()) | |
| 49 | 新增: } | |
| 50 | 新增: if strings.Contains(stderr.String(), "repair-fixture-secret") || !strings.Contains(stderr.String(), "[redacted]") { | |
| 51 | 新增: t.Fatal("repair output bypassed diagnostic redaction") | |
| 52 | 新增: } | |
| 53 | 新增: remaining, err := filepath.Glob(filepath.Join(profile, "native-host-repair-*.json")) | |
| 54 | 新增: if err != nil || len(remaining) != 0 { | |
| 55 | 新增: t.Fatalf("repair manifest was retained after failure: %v %v", remaining, err) | |
| 56 | 新增: } | |
| 57 | 新增:} | |
| @@ -0,0 +1,70 @@ | ||
| 1 | 新增:param([Parameter(Mandatory)][string]$Implementation) | |
| 2 | 新增:$ErrorActionPreference='Stop' | |
| 3 | 新增:$global:cageStorageVMID=[guid]'2a6f8208-3906-4e16-8233-2b9d28ecf7be' | |
| 4 | 新增:$old=[pscustomobject]@{configuration="C:\Cage original\config";snapshots="C:\Cage original\snapshots";paging="C:\Cage original\paging"} | |
| 5 | 新增:$next=[pscustomobject]@{configuration="C:\ProgramData\Cage\测试's\config";snapshots="C:\ProgramData\Cage\测试's\snapshots";paging="C:\ProgramData\Cage\测试's\paging"} | |
| 6 | 新增:$source="C:\Cage original\system.vhdx" | |
| 7 | 新增:$destination="D:\Cage 新位置's\system.vhdx" | |
| 8 | 新增:function Reset-VM { | |
| 9 | 新增: $global:cageStorageVM=[pscustomobject]@{Id=$global:cageStorageVMID;State='Off';Generation=2;ConfigurationLocation=$old.configuration;SnapshotFileLocation=$old.snapshots;SmartPagingFilePath=$old.paging} | |
| 10 | 新增: $global:cageStorageDisk=[pscustomobject]@{Path=$source} | |
| 11 | 新增: $global:cageStorageMoves=0 | |
| 12 | 新增: $global:cageStorageAttachments=0 | |
| 13 | 新增: $global:cageStorageFailMove=$false | |
| 14 | 新增:} | |
| 15 | 新增:function Get-VM { param([guid]$Id) if($Id -ne $global:cageStorageVMID){throw 'wrong_vm'};return $global:cageStorageVM } | |
| 16 | 新增:function Get-VMNetworkAdapter { param($VM) if($VM.Id -ne $global:cageStorageVMID){throw 'wrong_vm'} } | |
| 17 | 新增:function Get-VMFirmware { param($VM) [pscustomobject]@{SecureBoot='On'} } | |
| 18 | 新增:function Get-VMSecurity { param($VM) [pscustomobject]@{TpmEnabled=$true} } | |
| 19 | 新增:function Get-VMHardDiskDrive { param($VM) if($VM.Id -ne $global:cageStorageVMID){throw 'wrong_vm'};return $global:cageStorageDisk } | |
| 20 | 新增:function Move-VMStorage { | |
| 21 | 新增: param($VM,[string]$VirtualMachinePath,[string]$SnapshotFilePath,[string]$SmartPagingFilePath,[switch]$Confirm) | |
| 22 | 新增: if($VM.Id -ne $global:cageStorageVMID -or $VM.State -ne 'Off'){throw 'unsafe_move'} | |
| 23 | 新增: $global:cageStorageMoves++ | |
| 24 | 新增: if($VirtualMachinePath){$global:cageStorageVM.ConfigurationLocation=$VirtualMachinePath} | |
| 25 | 新增: if($global:cageStorageFailMove){throw 'injected_metadata_failure'} | |
| 26 | 新增: if($SnapshotFilePath){$global:cageStorageVM.SnapshotFileLocation=$SnapshotFilePath} | |
| 27 | 新增: if($SmartPagingFilePath){$global:cageStorageVM.SmartPagingFilePath=$SmartPagingFilePath} | |
| 28 | 新增:} | |
| 29 | 新增:function Set-VMHardDiskDrive { | |
| 30 | 新增: param($VMHardDiskDrive,[string]$Path) | |
| 31 | 新增: if($global:cageStorageVM.State -notin @('Off','OffCritical') -or $VMHardDiskDrive -ne $global:cageStorageDisk){throw 'unsafe_attachment'} | |
| 32 | 新增: $global:cageStorageAttachments++ | |
| 33 | 新增: $global:cageStorageDisk.Path=$Path | |
| 34 | 新增: $global:cageStorageVM.State='Off' | |
| 35 | 新增:} | |
| 36 | 新增:function Invoke-Storage($Target,[string]$Disk) { | |
| 37 | 新增: $inputData=[pscustomobject]@{vm_id=$global:cageStorageVMID.ToString('D');action='apply';old=$old;next=$next;target=$Target;old_disk=$source;source_disk=$source;new_disk=$destination;disk=$Disk} | |
| 38 | 新增: & $Implementation | Out-Null | |
| 39 | 新增:} | |
| 40 | 新增:Reset-VM | |
| 41 | 新增:Invoke-Storage $next $source | |
| 42 | 新增:if($global:cageStorageMoves -ne 1 -or $global:cageStorageAttachments -ne 0){throw 'registration_not_prepared_before_copy'} | |
| 43 | 新增:Invoke-Storage $next $destination | |
| 44 | 新增:if($global:cageStorageVM.ConfigurationLocation -cne $next.configuration -or $global:cageStorageVM.SnapshotFileLocation -cne $next.snapshots -or $global:cageStorageVM.SmartPagingFilePath -cne $next.paging -or $global:cageStorageDisk.Path -cne $destination){throw 'incomplete_migration'} | |
| 45 | 新增:if($global:cageStorageMoves -ne 1 -or $global:cageStorageAttachments -ne 1){throw 'unexpected_mutation_count'} | |
| 46 | 新增:Invoke-Storage $next $destination | |
| 47 | 新增:if($global:cageStorageMoves -ne 1 -or $global:cageStorageAttachments -ne 1){throw 'retry_repeated_mutations'} | |
| 48 | 新增:$global:cageStorageVM.State='OffCritical' | |
| 49 | 新增:Invoke-Storage $next $source | |
| 50 | 新增:if($global:cageStorageVM.ConfigurationLocation -cne $next.configuration -or $global:cageStorageVM.SnapshotFileLocation -cne $next.snapshots -or $global:cageStorageDisk.Path -cne $source){throw 'offline_target_rollback_failed'} | |
| 51 | 新增: | |
| 52 | 新增:Reset-VM | |
| 53 | 新增:$global:cageStorageFailMove=$true | |
| 54 | 新增:$failed=$false | |
| 55 | 新增:try{Invoke-Storage $next $destination}catch{$failed=$true} | |
| 56 | 新增:if(!$failed -or $global:cageStorageVM.ConfigurationLocation -cne $next.configuration -or $global:cageStorageAttachments -ne 0){throw 'partial_failure_fixture_invalid'} | |
| 57 | 新增:$global:cageStorageFailMove=$false | |
| 58 | 新增:Invoke-Storage $next $source | |
| 59 | 新增:if($global:cageStorageVM.ConfigurationLocation -cne $next.configuration -or $global:cageStorageDisk.Path -cne $source){throw 'partial_metadata_rollback_failed'} | |
| 60 | 新增: | |
| 61 | 新增:foreach($failure in @('running','foreign_disk','foreign_configuration')){ | |
| 62 | 新增: Reset-VM | |
| 63 | 新增: if($failure -eq 'running'){$global:cageStorageVM.State='Running'} | |
| 64 | 新增: if($failure -eq 'foreign_disk'){$global:cageStorageDisk.Path='C:\Another VM\private.vhdx'} | |
| 65 | 新增: if($failure -eq 'foreign_configuration'){$global:cageStorageVM.ConfigurationLocation='C:\Another VM\config'} | |
| 66 | 新增: $failed=$false | |
| 67 | 新增: try{Invoke-Storage $next $destination}catch{$failed=$true} | |
| 68 | 新增: if(!$failed -or $global:cageStorageMoves -ne 0 -or $global:cageStorageAttachments -ne 0){throw ('unsafe_state_accepted_'+$failure)} | |
| 69 | 新增:} | |
| 70 | 新增:Write-Output 'PASS fixed system registration, disk move, idempotence, offline target rollback, partial metadata recovery, running and unrelated VM state rejection' | |
| @@ -43,6 +43,13 @@ func windowsHostManagerRequestCall(ctx context.Context, request windowsHostManag | ||
| 43 | 43 | } |
| 44 | 44 | connection, err := winio.DialPipeAccessImpLevel(connect, `\\.\pipe\Cage.HyperV.`+id.String(), 0x120003, level) |
| 45 | 45 | finish() |
| 46 | 新增: if err != nil && ctx.Err() == nil { | |
| 47 | 新增: if startErr := startRegisteredWindowsHostManager(id); startErr == nil { | |
| 48 | 新增: retry, finish := context.WithTimeout(ctx, 10*time.Second) | |
| 49 | 新增: connection, err = winio.DialPipeAccessImpLevel(retry, `\\.\pipe\Cage.HyperV.`+id.String(), 0x120003, level) | |
| 50 | 新增: finish() | |
| 51 | 新增: } | |
| 52 | 新增: } | |
| 46 | 53 | if err != nil { |
| 47 | 54 | if ctx.Err() != nil { |
| 48 | 55 | return ctx.Err() |
| @@ -126,6 +133,10 @@ func verifyWindowsHostManagerPeer(connection net.Conn, id uuid.UUID) error { | ||
| 126 | 133 | if windows.QueryServiceStatusEx(service, windows.SC_STATUS_PROCESS_INFO, (*byte)(unsafe.Pointer(&status)), uint32(unsafe.Sizeof(status)), &needed) != nil || status.ProcessId != pid || status.CurrentState != windows.SERVICE_RUNNING { |
| 127 | 134 | return errors.New("Windows 系统管理通道不属于当前已登记服务") |
| 128 | 135 | } |
| 136 | 新增: return verifyWindowsHostManagerService(service, id) | |
| 137 | 新增:} | |
| 138 | 新增: | |
| 139 | 新增:func verifyWindowsHostManagerService(service windows.Handle, id uuid.UUID) error { | |
| 129 | 140 | binaryPath, account, err := windowsHostServiceConfig(service) |
| 130 | 141 | if err != nil { |
| 131 | 142 | return errors.New("Windows 系统管理服务配置无法核验") |
| @@ -161,6 +172,38 @@ func verifyWindowsHostManagerPeer(connection net.Conn, id uuid.UUID) error { | ||
| 161 | 172 | return nil |
| 162 | 173 | } |
| 163 | 174 | |
| 175 | 新增:// Installation already grants the bound user SERVICE_START. Restoring that | |
| 176 | 新增:// fixed service after a reboot does not grant VM discovery or service editing. | |
| 177 | 新增:func startRegisteredWindowsHostManager(id uuid.UUID) error { | |
| 178 | 新增: binding, err := LoadWindowsHostManagerBinding(WindowsHostManagerBindingPath(id)) | |
| 179 | 新增: if err != nil { | |
| 180 | 新增: return err | |
| 181 | 新增: } | |
| 182 | 新增: user, err := windows.GetCurrentProcessToken().GetTokenUser() | |
| 183 | 新增: if err != nil || user.User.Sid.String() != binding.HostSID { | |
| 184 | 新增: return errors.New("unauthorized") | |
| 185 | 新增: } | |
| 186 | 新增: manager, err := windows.OpenSCManager(nil, nil, windows.SC_MANAGER_CONNECT) | |
| 187 | 新增: if err != nil { | |
| 188 | 新增: return err | |
| 189 | 新增: } | |
| 190 | 新增: defer windows.CloseServiceHandle(manager) | |
| 191 | 新增: name, _ := windows.UTF16PtrFromString(WindowsHostManagerServiceName(id)) | |
| 192 | 新增: service, err := windows.OpenService(manager, name, windows.SERVICE_QUERY_CONFIG|windows.SERVICE_START) | |
| 193 | 新增: if err != nil { | |
| 194 | 新增: return err | |
| 195 | 新增: } | |
| 196 | 新增: defer windows.CloseServiceHandle(service) | |
| 197 | 新增: if err = verifyWindowsHostManagerService(service, id); err != nil { | |
| 198 | 新增: return err | |
| 199 | 新增: } | |
| 200 | 新增: err = windows.StartService(service, 0, nil) | |
| 201 | 新增: if errors.Is(err, windows.ERROR_SERVICE_ALREADY_RUNNING) { | |
| 202 | 新增: return nil | |
| 203 | 新增: } | |
| 204 | 新增: return err | |
| 205 | 新增:} | |
| 206 | 新增: | |
| 164 | 207 | func windowsHostServiceConfig(service windows.Handle) (string, string, error) { |
| 165 | 208 | // QUERY_SERVICE_CONFIG contains pointers into this native output buffer. |
| 166 | 209 | // A variable-sized allocation stays on the heap when later Go calls grow |
| @@ -300,7 +300,7 @@ func (server *windowsHostManagerServer) request(ctx context.Context, request win | ||
| 300 | 300 | } |
| 301 | 301 | // Hold the verified inode across the operation. A same-user caller cannot |
| 302 | 302 | // replace the VHDX path after validation while the SYSTEM operation runs. |
| 303 | 删除: lockedDisk, err := windows.CreateFile(name, windows.FILE_READ_ATTRIBUTES, windows.FILE_SHARE_READ|windows.FILE_SHARE_WRITE, nil, windows.OPEN_EXISTING, windows.FILE_FLAG_OPEN_REPARSE_POINT, 0) | |
| 303 | 新增: lockedDisk, err := windows.CreateFile(name, windows.GENERIC_READ, windows.FILE_SHARE_READ|windows.FILE_SHARE_WRITE, nil, windows.OPEN_EXISTING, windows.FILE_FLAG_OPEN_REPARSE_POINT, 0) | |
| 304 | 304 | if err != nil { |
| 305 | 305 | return nil, errors.New("vm_changed") |
| 306 | 306 | } |
| @@ -38,7 +38,6 @@ type windowsHostStorageRequest struct { | ||
| 38 | 38 | SourceVolume uint32 `json:"source_volume,omitempty"` |
| 39 | 39 | SourceFileID uint64 `json:"source_file_id,omitempty"` |
| 40 | 40 | Disk string `json:"disk,omitempty"` |
| 41 | 删除: Directory string `json:"directory,omitempty"` | |
| 42 | 41 | } |
| 43 | 42 | |
| 44 | 43 | type windowsHostStorageState struct { |
| @@ -54,7 +53,7 @@ func validWindowsStorageID(id string) bool { | ||
| 54 | 53 | |
| 55 | 54 | func (r windowsHostStorageRequest) validate() error { |
| 56 | 55 | if r.Action == "status" { |
| 57 | 删除: if r.ID == "" && r.SourceVolume == 0 && r.SourceFileID == 0 && r.Disk == "" && r.Directory == "" { | |
| 56 | 新增: if r.ID == "" && r.SourceVolume == 0 && r.SourceFileID == 0 && r.Disk == "" { | |
| 58 | 57 | return nil |
| 59 | 58 | } |
| 60 | 59 | return errors.New("invalid_request") |
| @@ -64,11 +63,11 @@ func (r windowsHostStorageRequest) validate() error { | ||
| 64 | 63 | } |
| 65 | 64 | switch r.Action { |
| 66 | 65 | case "begin", "commit", "rollback": |
| 67 | 删除: if r.Disk != "" || r.Directory != "" { | |
| 66 | 新增: if r.Disk != "" { | |
| 68 | 67 | return errors.New("invalid_request") |
| 69 | 68 | } |
| 70 | 69 | case "attach": |
| 71 | 删除: if r.Disk == "" || r.Directory == "" || len(r.Disk) > 32700 || len(r.Directory) > 32700 || strings.ContainsAny(r.Disk+r.Directory, "\x00\r\n") { | |
| 70 | 新增: if r.Disk == "" || len(r.Disk) > 32700 || strings.ContainsAny(r.Disk, "\x00\r\n") { | |
| 72 | 71 | return errors.New("invalid_request") |
| 73 | 72 | } |
| 74 | 73 | default: |
| @@ -20,28 +20,32 @@ import ( | ||
| 20 | 20 | "golang.org/x/sys/windows" |
| 21 | 21 | |
| 22 | 22 | "github.com/sylvinus/agent-vm/internal/cage" |
| 23 | 删除: "github.com/sylvinus/agent-vm/internal/paths" | |
| 24 | 23 | ) |
| 25 | 24 | |
| 26 | 25 | //go:embed windows_storage.ps1 |
| 27 | 26 | var windowsStorageScript string |
| 28 | 27 | |
| 29 | 28 | type windowsHostStorageJournal struct { |
| 30 | 删除: ID string `json:"id"` | |
| 31 | 删除: Phase string `json:"phase"` | |
| 32 | 删除: Before WindowsHostManagerBinding `json:"before"` | |
| 33 | 删除: OldDisk string `json:"old_disk"` | |
| 34 | 删除: OldLayout windowsVMStorageLayout `json:"old_layout"` | |
| 35 | 删除: After *WindowsHostManagerBinding `json:"after,omitempty"` | |
| 36 | 删除: NewLayout *windowsVMStorageLayout `json:"new_layout,omitempty"` | |
| 37 | 删除: Directory windowsStorageDisk `json:"directory"` | |
| 38 | 删除: Backup string `json:"backup"` | |
| 29 | 新增: ID string `json:"id"` | |
| 30 | 新增: Phase string `json:"phase"` | |
| 31 | 新增: Before WindowsHostManagerBinding `json:"before"` | |
| 32 | 新增: OldDisk string `json:"old_disk"` | |
| 33 | 新增: OldLayout windowsVMStorageLayout `json:"old_layout"` | |
| 34 | 新增: After *WindowsHostManagerBinding `json:"after,omitempty"` | |
| 35 | 新增: NewLayout *windowsVMStorageLayout `json:"new_layout,omitempty"` | |
| 36 | 新增: Backup string `json:"backup"` | |
| 37 | 新增: RegistrationStarted bool `json:"registration_started,omitempty"` | |
| 39 | 38 | } |
| 40 | 39 | |
| 41 | 40 | func (server *windowsHostManagerServer) storageJournalPath() string { |
| 42 | 41 | return filepath.Join(filepath.Dir(WindowsHostManagerBindingPath(server.binding.VMID)), "storage.json") |
| 43 | 42 | } |
| 44 | 43 | |
| 44 | 新增:func (server *windowsHostManagerServer) storageRegistrationLayout() windowsVMStorageLayout { | |
| 45 | 新增: root := filepath.Join(filepath.Dir(server.storageJournalPath()), "machine") | |
| 46 | 新增: return windowsVMStorageLayout{Configuration: filepath.Join(root, "configuration"), Snapshots: filepath.Join(root, "snapshots"), Paging: filepath.Join(root, "paging")} | |
| 47 | 新增:} | |
| 48 | 新增: | |
| 45 | 49 | func (server *windowsHostManagerServer) loadStorageJournal() (*windowsHostStorageJournal, error) { |
| 46 | 50 | path := server.storageJournalPath() |
| 47 | 51 | file, err := os.Open(path) |
| @@ -61,7 +65,12 @@ func (server *windowsHostManagerServer) loadStorageJournal() (*windowsHostStorag | ||
| 61 | 65 | if decoder.Decode(&journal) != nil || decoder.Decode(new(any)) != io.EOF || !validWindowsStorageID(journal.ID) || |
| 62 | 66 | journal.Before.VMID != server.binding.VMID || journal.Before.HostSID != server.binding.HostSID || |
| 63 | 67 | journal.Phase != "pending" && journal.Phase != "commit" && journal.Phase != "rollback" || |
| 64 | 删除: (journal.After == nil) != (journal.NewLayout == nil) { | |
| 68 | 新增: journal.NewLayout == nil || *journal.NewLayout != server.storageRegistrationLayout() || journal.Backup != filepath.Join(filepath.Dir(path), "storage-backup-"+journal.ID) || | |
| 69 | 新增: journal.Before.DiskVolume == 0 || journal.Before.DiskFileID == 0 { | |
| 70 | 新增: return nil, errors.New("binding_invalid") | |
| 71 | 新增: } | |
| 72 | 新增: if journal.After != nil && (journal.After.VMID != server.binding.VMID || journal.After.HostSID != server.binding.HostSID || | |
| 73 | 新增: journal.After.DiskVolume == 0 || journal.After.DiskFileID == 0) { | |
| 65 | 74 | return nil, errors.New("binding_invalid") |
| 66 | 75 | } |
| 67 | 76 | return &journal, nil |
| @@ -212,7 +221,8 @@ func (server *windowsHostManagerServer) storageRequest(ctx context.Context, inpu | ||
| 212 | 221 | return nil, err |
| 213 | 222 | } |
| 214 | 223 | backup := filepath.Join(filepath.Dir(server.storageJournalPath()), "storage-backup-"+input.ID) |
| 215 | 删除: journal = &windowsHostStorageJournal{ID: input.ID, Phase: "pending", Before: server.binding, OldDisk: oldDisk, OldLayout: layout, Backup: backup} | |
| 224 | 新增: registration := server.storageRegistrationLayout() | |
| 225 | 新增: journal = &windowsHostStorageJournal{ID: input.ID, Phase: "pending", Before: server.binding, OldDisk: oldDisk, OldLayout: layout, NewLayout: ®istration, Backup: backup} | |
| 216 | 226 | if err = managerWriteStorageJSON(server.storageJournalPath(), server.binding.HostSID, journal); err != nil { |
| 217 | 227 | return nil, err |
| 218 | 228 | } |
| @@ -225,6 +235,9 @@ func (server *windowsHostManagerServer) storageRequest(ctx context.Context, inpu | ||
| 225 | 235 | if err := server.ensureStorageBackup(ctx, journal); err != nil { |
| 226 | 236 | return nil, err |
| 227 | 237 | } |
| 238 | 新增: if err := server.prepareStorageRegistration(ctx, journal); err != nil { | |
| 239 | 新增: return nil, err | |
| 240 | 新增: } | |
| 228 | 241 | case "attach": |
| 229 | 242 | if err := server.attachStorage(ctx, journal, input, conn); err != nil { |
| 230 | 243 | return nil, err |
| @@ -237,6 +250,30 @@ func (server *windowsHostManagerServer) storageRequest(ctx context.Context, inpu | ||
| 237 | 250 | return server.storageState(journal, input.Action), nil |
| 238 | 251 | } |
| 239 | 252 | |
| 253 | 新增:// Registration belongs to the fixed system helper. Keeping it on the system | |
| 254 | 新增:// volume lets rollback reattach the original VHDX even when the target volume | |
| 255 | 新增:// disappears. VM identity and the exported recovery metadata remain available. | |
| 256 | 新增:func (server *windowsHostManagerServer) prepareStorageRegistration(ctx context.Context, journal *windowsHostStorageJournal) error { | |
| 257 | 新增: root := filepath.Dir(journal.NewLayout.Configuration) | |
| 258 | 新增: if err := os.Mkdir(root, 0700); err == nil { | |
| 259 | 新增: if err := managerProtectStoragePath(root, server.binding.HostSID); err != nil { | |
| 260 | 新增: return err | |
| 261 | 新增: } | |
| 262 | 新增: } else if !errors.Is(err, os.ErrExist) { | |
| 263 | 新增: return err | |
| 264 | 新增: } | |
| 265 | 新增: if err := managerProtected(root, server.binding.HostSID); err != nil { | |
| 266 | 新增: return err | |
| 267 | 新增: } | |
| 268 | 新增: if !journal.RegistrationStarted { | |
| 269 | 新增: journal.RegistrationStarted = true | |
| 270 | 新增: if err := managerWriteStorageJSON(server.storageJournalPath(), server.binding.HostSID, journal); err != nil { | |
| 271 | 新增: return err | |
| 272 | 新增: } | |
| 273 | 新增: } | |
| 274 | 新增: return server.applyStorage(ctx, journal, journal.Before, *journal.NewLayout) | |
| 275 | 新增:} | |
| 276 | 新增: | |
| 240 | 277 | func (server *windowsHostManagerServer) ensureStorageBackup(ctx context.Context, journal *windowsHostStorageJournal) error { |
| 241 | 278 | complete := filepath.Join(journal.Backup, "cage-export-complete.json") |
| 242 | 279 | if data, err := os.ReadFile(complete); err == nil && bytes.Equal(data, []byte(`{"id":"`+journal.ID+`"}`)) { |
| @@ -336,6 +373,7 @@ func managerPinStorageParents(path string) (func(), error) { | ||
| 336 | 373 | for _, handle := range handles { |
| 337 | 374 | windows.CloseHandle(handle) |
| 338 | 375 | } |
| 376 | 新增: handles = nil | |
| 339 | 377 | } |
| 340 | 378 | var parents []string |
| 341 | 379 | for parent := filepath.Dir(path); ; parent = filepath.Dir(parent) { |
| @@ -351,7 +389,7 @@ func managerPinStorageParents(path string) (func(), error) { | ||
| 351 | 389 | closeAll() |
| 352 | 390 | return nil, err |
| 353 | 391 | } |
| 354 | 删除: handle, err := windows.CreateFile(name, windows.FILE_READ_ATTRIBUTES, windows.FILE_SHARE_READ|windows.FILE_SHARE_WRITE, nil, windows.OPEN_EXISTING, windows.FILE_FLAG_OPEN_REPARSE_POINT|windows.FILE_FLAG_BACKUP_SEMANTICS, 0) | |
| 392 | 新增: handle, err := windows.CreateFile(name, windows.GENERIC_READ, windows.FILE_SHARE_READ|windows.FILE_SHARE_WRITE, nil, windows.OPEN_EXISTING, windows.FILE_FLAG_OPEN_REPARSE_POINT|windows.FILE_FLAG_BACKUP_SEMANTICS, 0) | |
| 355 | 393 | if err != nil { |
| 356 | 394 | closeAll() |
| 357 | 395 | return nil, err |
| @@ -366,26 +404,6 @@ func managerPinStorageParents(path string) (func(), error) { | ||
| 366 | 404 | return closeAll, nil |
| 367 | 405 | } |
| 368 | 406 | |
| 369 | 删除:func managerProtectVMMetadata(handle windows.Handle, sid string, release bool) error { | |
| 370 | 删除: owner, access := "SY", "FRFX" | |
| 371 | 删除: if release { | |
| 372 | 删除: owner, access = sid, "FA" | |
| 373 | 删除: } | |
| 374 | 删除: sd, err := windows.SecurityDescriptorFromString("O:" + owner + "G:SYD:P(A;OICI;FA;;;SY)(A;OICI;FA;;;BA)(A;OICI;" + access + ";;;" + sid + ")") | |
| 375 | 删除: if err != nil { | |
| 376 | 删除: return err | |
| 377 | 删除: } | |
| 378 | 删除: ownerSID, _, err := sd.Owner() | |
| 379 | 删除: if err != nil { | |
| 380 | 删除: return err | |
| 381 | 删除: } | |
| 382 | 删除: acl, _, err := sd.DACL() | |
| 383 | 删除: if err != nil { | |
| 384 | 删除: return err | |
| 385 | 删除: } | |
| 386 | 删除: return windows.SetSecurityInfo(handle, windows.SE_FILE_OBJECT, windows.OWNER_SECURITY_INFORMATION|windows.DACL_SECURITY_INFORMATION|windows.PROTECTED_DACL_SECURITY_INFORMATION, ownerSID, nil, acl, nil) | |
| 387 | 删除:} | |
| 388 | 删除: | |
| 389 | 407 | func managerStorageObject(handle windows.Handle, directory bool) (windowsStorageDisk, error) { |
| 390 | 408 | var value windowsStorageDisk |
| 391 | 409 | var info windows.ByHandleFileInformation |
| @@ -430,6 +448,9 @@ func managerGrantVMDisk(handle windows.Handle, id uuid.UUID) error { | ||
| 430 | 448 | } |
| 431 | 449 | |
| 432 | 450 | func (server *windowsHostManagerServer) attachStorage(ctx context.Context, journal *windowsHostStorageJournal, input windowsHostStorageRequest, conn net.Conn) error { |
| 451 | 新增: if !journal.RegistrationStarted { | |
| 452 | 新增: return errors.New("invalid_request") | |
| 453 | 新增: } | |
| 433 | 454 | if err := server.ensureStorageBackup(ctx, journal); err != nil { |
| 434 | 455 | return err |
| 435 | 456 | } |
| @@ -443,40 +464,22 @@ func (server *windowsHostManagerServer) attachStorage(ctx context.Context, journ | ||
| 443 | 464 | return err |
| 444 | 465 | } |
| 445 | 466 | defer diskParents() |
| 446 | 删除: dirHandle, directory, err := managerOpenStorageDestination(conn, input.Directory, server.binding.HostSID, true) | |
| 447 | 删除: if err != nil { | |
| 448 | 删除: return err | |
| 449 | 删除: } | |
| 450 | 删除: defer windows.CloseHandle(dirHandle) | |
| 451 | 删除: directoryParents, err := managerPinStorageParents(directory.Path) | |
| 452 | 删除: if err != nil { | |
| 453 | 删除: return err | |
| 454 | 删除: } | |
| 455 | 删除: defer directoryParents() | |
| 456 | 删除: if cage.StoragePathsOverlap(directory.Path, disk.Path) || disk.Volume == journal.Before.DiskVolume && disk.FileID == journal.Before.DiskFileID { | |
| 467 | 新增: if disk.Volume == journal.Before.DiskVolume && disk.FileID == journal.Before.DiskFileID { | |
| 457 | 468 | return errors.New("invalid_request") |
| 458 | 469 | } |
| 459 | 470 | if journal.After == nil { |
| 460 | 删除: entries, err := os.ReadDir(directory.Path) | |
| 461 | 删除: if err != nil || len(entries) != 0 { | |
| 462 | 删除: return errors.New("destination_not_empty") | |
| 463 | 删除: } | |
| 464 | 471 | after := journal.Before |
| 465 | 472 | after.DiskPath, after.DiskVolume, after.DiskFileID = disk.Path, disk.Volume, disk.FileID |
| 466 | 删除: layout := windowsVMStorageLayout{Configuration: filepath.Join(directory.Path, "configuration"), Snapshots: filepath.Join(directory.Path, "snapshots"), Paging: filepath.Join(directory.Path, "paging")} | |
| 467 | 删除: journal.After, journal.NewLayout, journal.Directory = &after, &layout, directory | |
| 473 | 新增: journal.After = &after | |
| 468 | 474 | if err = managerWriteStorageJSON(server.storageJournalPath(), server.binding.HostSID, journal); err != nil { |
| 469 | 475 | return err |
| 470 | 476 | } |
| 471 | 删除: } else if journal.After.DiskPath != disk.Path || journal.After.DiskVolume != disk.Volume || journal.After.DiskFileID != disk.FileID || journal.Directory != directory { | |
| 477 | 新增: } else if journal.After.DiskPath != disk.Path || journal.After.DiskVolume != disk.Volume || journal.After.DiskFileID != disk.FileID { | |
| 472 | 478 | return errors.New("vm_changed") |
| 473 | 479 | } |
| 474 | 480 | if err = managerGrantVMDisk(diskHandle, server.binding.VMID); err != nil { |
| 475 | 481 | return err |
| 476 | 482 | } |
| 477 | 删除: if err = managerProtectVMMetadata(dirHandle, server.binding.HostSID, false); err != nil { | |
| 478 | 删除: return err | |
| 479 | 删除: } | |
| 480 | 483 | if err = server.applyStorage(ctx, journal, *journal.After, *journal.NewLayout); err != nil { |
| 481 | 484 | return err |
| 482 | 485 | } |
| @@ -488,7 +491,7 @@ func (server *windowsHostManagerServer) applyStorage(ctx context.Context, journa | ||
| 488 | 491 | if err != nil { |
| 489 | 492 | return err |
| 490 | 493 | } |
| 491 | 删除: handle, err := windows.CreateFile(name, windows.FILE_READ_ATTRIBUTES, windows.FILE_SHARE_READ|windows.FILE_SHARE_WRITE, nil, windows.OPEN_EXISTING, windows.FILE_FLAG_OPEN_REPARSE_POINT, 0) | |
| 494 | 新增: handle, err := windows.CreateFile(name, windows.GENERIC_READ, windows.FILE_SHARE_READ|windows.FILE_SHARE_WRITE, nil, windows.OPEN_EXISTING, windows.FILE_FLAG_OPEN_REPARSE_POINT, 0) | |
| 492 | 495 | if err != nil { |
| 493 | 496 | return err |
| 494 | 497 | } |
| @@ -511,7 +514,11 @@ func (server *windowsHostManagerServer) applyStorage(ctx context.Context, journa | ||
| 511 | 514 | var result struct { |
| 512 | 515 | Applied bool `json:"applied"` |
| 513 | 516 | } |
| 514 | 删除: if err = managerStorageCommand(ctx, server.binding.VMID, "apply", map[string]any{"old": journal.OldLayout, "next": journal.NewLayout, "target": layout, "old_disk": journal.OldDisk, "source_disk": journal.Before.DiskPath, "new_disk": journal.After.DiskPath, "disk": binding.DiskPath}, &result); err != nil || !result.Applied { | |
| 517 | 新增: newDisk := journal.Before.DiskPath | |
| 518 | 新增: if journal.After != nil { | |
| 519 | 新增: newDisk = journal.After.DiskPath | |
| 520 | 新增: } | |
| 521 | 新增: if err = managerStorageCommand(ctx, server.binding.VMID, "apply", map[string]any{"old": journal.OldLayout, "next": journal.NewLayout, "target": layout, "old_disk": journal.OldDisk, "source_disk": journal.Before.DiskPath, "new_disk": newDisk, "disk": binding.DiskPath}, &result); err != nil || !result.Applied { | |
| 515 | 522 | return errors.Join(err, errors.New("storage_operation_failed")) |
| 516 | 523 | } |
| 517 | 524 | return managerRequireStopped(ctx, binding) |
| @@ -541,8 +548,8 @@ func (server *windowsHostManagerServer) finishStorage(ctx context.Context, journ | ||
| 541 | 548 | return err |
| 542 | 549 | } |
| 543 | 550 | } else { |
| 544 | 删除: if journal.After != nil { | |
| 545 | 删除: if err := server.applyStorage(ctx, journal, journal.Before, journal.OldLayout); err != nil { | |
| 551 | 新增: if journal.RegistrationStarted { | |
| 552 | 新增: if err := server.applyStorage(ctx, journal, journal.Before, *journal.NewLayout); err != nil { | |
| 546 | 553 | return err |
| 547 | 554 | } |
| 548 | 555 | } else if err := managerRequireStopped(ctx, journal.Before); err != nil { |
| @@ -551,28 +558,6 @@ func (server *windowsHostManagerServer) finishStorage(ctx context.Context, journ | ||
| 551 | 558 | if err := server.saveStorageBinding(journal.Before); err != nil { |
| 552 | 559 | return err |
| 553 | 560 | } |
| 554 | 删除: if journal.After != nil { | |
| 555 | 删除: // Return the verified metadata directory to its original owner after | |
| 556 | 删除: // Hyper-V moves back. Cleanup then runs with that user's permissions. | |
| 557 | 删除: real, err := paths.Resolve(journal.Directory.Path) | |
| 558 | 删除: if err == nil && strings.EqualFold(real, journal.Directory.Path) { | |
| 559 | 删除: name, _ := windows.UTF16PtrFromString(real) | |
| 560 | 删除: handle, openErr := windows.CreateFile(name, windows.FILE_READ_ATTRIBUTES|windows.WRITE_DAC|windows.WRITE_OWNER, windows.FILE_SHARE_READ|windows.FILE_SHARE_WRITE, nil, windows.OPEN_EXISTING, windows.FILE_FLAG_OPEN_REPARSE_POINT|windows.FILE_FLAG_BACKUP_SEMANTICS, 0) | |
| 561 | 删除: if openErr != nil { | |
| 562 | 删除: return openErr | |
| 563 | 删除: } | |
| 564 | 删除: defer windows.CloseHandle(handle) | |
| 565 | 删除: identity, identityErr := managerStorageObject(handle, true) | |
| 566 | 删除: if identityErr != nil || identity != journal.Directory { | |
| 567 | 删除: return errors.New("vm_changed") | |
| 568 | 删除: } | |
| 569 | 删除: if err := managerProtectVMMetadata(handle, server.binding.HostSID, true); err != nil { | |
| 570 | 删除: return err | |
| 571 | 删除: } | |
| 572 | 删除: } else if !errors.Is(err, os.ErrNotExist) { | |
| 573 | 删除: return errors.New("vm_changed") | |
| 574 | 删除: } | |
| 575 | 删除: } | |
| 576 | 561 | } |
| 577 | 562 | journal.Phase = action |
| 578 | 563 | return managerWriteStorageJSON(server.storageJournalPath(), server.binding.HostSID, journal) |
| @@ -18,6 +18,7 @@ type windowsStorageSnapshot struct { | ||
| 18 | 18 | Profile WindowsProfile `json:"profile"` |
| 19 | 19 | Instance string `json:"instance"` |
| 20 | 20 | Disk windowsStorageDisk `json:"disk"` |
| 21 | 新增: Excluded []string `json:"excluded,omitempty"` | |
| 21 | 22 | } |
| 22 | 23 | |
| 23 | 24 | type windowsStorageRuntime struct { |
| @@ -48,7 +49,7 @@ func (runtime *windowsStorageRuntime) Snapshot(ctx context.Context, source strin | ||
| 48 | 49 | } |
| 49 | 50 | state, err := runtime.call(ctx, binding.VMID, windowsHostStorageRequest{Action: "status"}) |
| 50 | 51 | if err != nil { |
| 51 | 删除: return snapshot, fmt.Errorf("请先更新或恢复 Windows 系统管理助手,再迁移环境存储:%w", err) | |
| 52 | 新增: return snapshot, fmt.Errorf("请先在设置的环境页选择“同步环境组件”,完成 Windows 系统授权后再迁移:%w", err) | |
| 52 | 53 | } |
| 53 | 54 | if state.Pending != "" { |
| 54 | 55 | return snapshot, errors.New("这台 Windows 客机仍有待恢复的存储迁移,请打开发起迁移的原工作台") |
| @@ -57,7 +58,7 @@ func (runtime *windowsStorageRuntime) Snapshot(ctx context.Context, source strin | ||
| 57 | 58 | if err != nil { |
| 58 | 59 | return snapshot, err |
| 59 | 60 | } |
| 60 | 删除: snapshot.State, err = json.Marshal(windowsStorageSnapshot{Profile: *binding, Instance: instance, Disk: state.Disk}) | |
| 61 | 新增: runtimeState := windowsStorageSnapshot{Profile: *binding, Instance: instance, Disk: state.Disk} | |
| 61 | 62 | if !cage.StorageContains(source, instance) { |
| 62 | 63 | snapshot.Backups = append(snapshot.Backups, instance) |
| 63 | 64 | } |
| @@ -74,9 +75,12 @@ func (runtime *windowsStorageRuntime) Snapshot(ctx context.Context, source strin | ||
| 74 | 75 | } |
| 75 | 76 | if cage.StorageContains(source, physical) && !cage.StorageContains(physical, state.Disk.Path) { |
| 76 | 77 | snapshot.Excluded = append(snapshot.Excluded, physical) |
| 78 | 新增: } else if cage.StorageContains(instance, physical) && !cage.StorageContains(physical, state.Disk.Path) { | |
| 79 | 新增: runtimeState.Excluded = append(runtimeState.Excluded, physical) | |
| 77 | 80 | } |
| 78 | 81 | } |
| 79 | 82 | } |
| 83 | 新增: snapshot.State, err = json.Marshal(runtimeState) | |
| 80 | 84 | return snapshot, err |
| 81 | 85 | } |
| 82 | 86 | |
| @@ -89,13 +93,13 @@ func windowsMoveSnapshot(move cage.StorageTransition) (windowsStorageSnapshot, e | ||
| 89 | 93 | return snapshot, nil |
| 90 | 94 | } |
| 91 | 95 | |
| 92 | 删除:func (runtime *windowsStorageRuntime) action(ctx context.Context, move cage.StorageTransition, action, disk, directory string) error { | |
| 96 | 新增:func (runtime *windowsStorageRuntime) action(ctx context.Context, move cage.StorageTransition, action, disk string) error { | |
| 93 | 97 | snapshot, err := windowsMoveSnapshot(move) |
| 94 | 98 | if err != nil { |
| 95 | 99 | return err |
| 96 | 100 | } |
| 97 | 101 | state, err := runtime.call(ctx, snapshot.Profile.VMID, windowsHostStorageRequest{Action: action, ID: move.ID, |
| 98 | 删除: SourceVolume: snapshot.Disk.Volume, SourceFileID: snapshot.Disk.FileID, Disk: disk, Directory: directory}) | |
| 102 | 新增: SourceVolume: snapshot.Disk.Volume, SourceFileID: snapshot.Disk.FileID, Disk: disk}) | |
| 99 | 103 | if err != nil { |
| 100 | 104 | return err |
| 101 | 105 | } |
| @@ -110,7 +114,7 @@ func (runtime *windowsStorageRuntime) action(ctx context.Context, move cage.Stor | ||
| 110 | 114 | } |
| 111 | 115 | |
| 112 | 116 | func (runtime *windowsStorageRuntime) Begin(ctx context.Context, move cage.StorageTransition) error { |
| 113 | 删除: return runtime.action(ctx, move, "begin", "", "") | |
| 117 | 新增: return runtime.action(ctx, move, "begin", "") | |
| 114 | 118 | } |
| 115 | 119 | |
| 116 | 120 | func windowsMovedPath(value, source, target string) string { |
| @@ -126,25 +130,25 @@ func windowsMovedPath(value, source, target string) string { | ||
| 126 | 130 | |
| 127 | 131 | func (runtime *windowsStorageRuntime) movedProfile(move cage.StorageTransition, snapshot windowsStorageSnapshot) (WindowsProfile, string) { |
| 128 | 132 | logical := filepath.Join(runtime.profile, "state") |
| 129 | 删除: instance := filepath.Join(logical, "windows-"+strings.ReplaceAll(snapshot.Profile.VMID.String(), "-", "")) | |
| 133 | 新增: instance := filepath.Join(move.Destination, "windows-"+strings.ReplaceAll(snapshot.Profile.VMID.String(), "-", "")) | |
| 130 | 134 | if cage.StorageContains(move.Source, snapshot.Instance) { |
| 131 | 删除: instance = windowsMovedPath(snapshot.Instance, move.Source, logical) | |
| 135 | 新增: instance = windowsMovedPath(snapshot.Instance, move.Source, move.Destination) | |
| 132 | 136 | } |
| 133 | 137 | next := snapshot.Profile |
| 134 | 138 | next.InstanceDirectory = instance |
| 135 | 139 | remap := func(value string) string { |
| 136 | 140 | value = windowsMovedPath(value, snapshot.Profile.InstanceDirectory, instance) |
| 137 | 141 | value = windowsMovedPath(value, snapshot.Instance, instance) |
| 138 | 删除: return windowsMovedPath(value, move.Source, logical) | |
| 142 | 新增: value = windowsMovedPath(value, move.Source, move.Destination) | |
| 143 | 新增: return windowsMovedPath(value, logical, move.Destination) | |
| 139 | 144 | } |
| 140 | 145 | next.RelayExecutable = remap(next.RelayExecutable) |
| 141 | 146 | next.PairingFile = remap(next.PairingFile) |
| 142 | 147 | next.NetworkPairingFile = remap(next.NetworkPairingFile) |
| 143 | 删除: physicalInstance := windowsMovedPath(instance, logical, move.Destination) | |
| 144 | 删除: disk := windowsMovedPath(snapshot.Disk.Path, snapshot.Instance, physicalInstance) | |
| 148 | 新增: disk := windowsMovedPath(snapshot.Disk.Path, snapshot.Instance, instance) | |
| 145 | 149 | disk = windowsMovedPath(disk, move.Source, move.Destination) |
| 146 | 150 | if disk == snapshot.Disk.Path { |
| 147 | 删除: disk = filepath.Join(physicalInstance, filepath.Base(snapshot.Disk.Path)) | |
| 151 | 新增: disk = filepath.Join(instance, filepath.Base(snapshot.Disk.Path)) | |
| 148 | 152 | } |
| 149 | 153 | return next, disk |
| 150 | 154 | } |
| @@ -155,9 +159,9 @@ func (runtime *windowsStorageRuntime) Switch(ctx context.Context, move cage.Stor | ||
| 155 | 159 | return err |
| 156 | 160 | } |
| 157 | 161 | next, disk := runtime.movedProfile(move, snapshot) |
| 158 | 删除: physicalInstance := windowsMovedPath(next.InstanceDirectory, filepath.Join(runtime.profile, "state"), move.Destination) | |
| 162 | 新增: physicalInstance := next.InstanceDirectory | |
| 159 | 163 | if !cage.StorageContains(move.Source, snapshot.Instance) { |
| 160 | 删除: if err = cage.CopyStorage(ctx, snapshot.Instance, physicalInstance, nil); err != nil { | |
| 164 | 新增: if err = cage.CopyStorage(ctx, snapshot.Instance, physicalInstance, snapshot.Excluded, nil); err != nil { | |
| 161 | 165 | return err |
| 162 | 166 | } |
| 163 | 167 | } |
| @@ -169,11 +173,17 @@ func (runtime *windowsStorageRuntime) Switch(ctx context.Context, move cage.Stor | ||
| 169 | 173 | return err |
| 170 | 174 | } |
| 171 | 175 | } |
| 172 | 删除: directory := filepath.Join(move.Destination, "hyperv-"+snapshot.Profile.VMID.String()+"-"+move.ID) | |
| 173 | 删除: if err = os.Mkdir(directory, 0700); err != nil { | |
| 176 | 新增: if err = prepareWindowsStorageDisk(ctx, snapshot.Disk.Path, disk); err != nil { | |
| 174 | 177 | return err |
| 175 | 178 | } |
| 176 | 删除: if err = runtime.action(ctx, move, "attach", disk, directory); err != nil { | |
| 179 | 新增: for _, path := range []string{next.PairingFile, next.NetworkPairingFile} { | |
| 180 | 新增: if path != "" && cage.StorageContains(move.Destination, path) { | |
| 181 | 新增: if err = protectWindowsProfile(path); err != nil { | |
| 182 | 新增: return err | |
| 183 | 新增: } | |
| 184 | 新增: } | |
| 185 | 新增: } | |
| 186 | 新增: if err = runtime.action(ctx, move, "attach", disk); err != nil { | |
| 177 | 187 | return err |
| 178 | 188 | } |
| 179 | 189 | return runtime.writeProfile(snapshot.Profile, next, next) |
| @@ -189,7 +199,7 @@ func (runtime *windowsStorageRuntime) Recover(ctx context.Context, move cage.Sto | ||
| 189 | 199 | if committed { |
| 190 | 200 | chosen, action = next, "commit" |
| 191 | 201 | } |
| 192 | 删除: if err = runtime.action(ctx, move, action, "", ""); err != nil { | |
| 202 | 新增: if err = runtime.action(ctx, move, action, ""); err != nil { | |
| 193 | 203 | return err |
| 194 | 204 | } |
| 195 | 205 | return runtime.writeProfile(snapshot.Profile, next, chosen) |
| @@ -2,7 +2,9 @@ $ErrorActionPreference = 'Stop' | ||
| 2 | 2 | $ProgressPreference = 'SilentlyContinue' |
| 3 | 3 | $id = [guid]$inputData.vm_id |
| 4 | 4 | $vm = Get-VM -Id $id |
| 5 | 删除:if ($vm.State -ne 'Off' -or $vm.Generation -ne 2 -or | |
| 5 | 新增:$recoveringDisk = $inputData.action -eq 'apply' -and $inputData.disk -ieq $inputData.source_disk | |
| 6 | 新增:$stopped = $vm.State -eq 'Off' -or ($recoveringDisk -and $vm.State -eq 'OffCritical') | |
| 7 | 新增:if (!$stopped -or $vm.Generation -ne 2 -or | |
| 6 | 8 | @(Get-VMNetworkAdapter -VM $vm).Count -ne 0 -or |
| 7 | 9 | (Get-VMFirmware -VM $vm).SecureBoot -ne 'On' -or !(Get-VMSecurity -VM $vm).TpmEnabled) { |
| 8 | 10 | throw 'vm_changed' |
| @@ -62,7 +64,7 @@ if ($move.Count) { | ||
| 62 | 64 | } |
| 63 | 65 | $vm = Get-VM -Id $id |
| 64 | 66 | $disks = @(Get-VMHardDiskDrive -VM $vm) |
| 65 | 删除:if ($vm.State -ne 'Off' -or $disks.Count -ne 1) { throw 'vm_changed' } | |
| 67 | 新增:if (($vm.State -ne 'Off' -and !($recoveringDisk -and $vm.State -eq 'OffCritical')) -or $disks.Count -ne 1) { throw 'vm_changed' } | |
| 66 | 68 | if ($disks[0].Path -ine $inputData.disk) { |
| 67 | 69 | Set-VMHardDiskDrive -VMHardDiskDrive $disks[0] -Path ([string]$inputData.disk) |
| 68 | 70 | } |
| @@ -0,0 +1,15 @@ | ||
| 1 | 新增://go:build !windows | |
| 2 | 新增: | |
| 3 | 新增:package guestos | |
| 4 | 新增: | |
| 5 | 新增:import ( | |
| 6 | 新增: "os" | |
| 7 | 新增: "testing" | |
| 8 | 新增:) | |
| 9 | 新增: | |
| 10 | 新增:func createWindowsStorageFixtureDisk(t *testing.T, path string) { | |
| 11 | 新增: t.Helper() | |
| 12 | 新增: if err := os.WriteFile(path, []byte("synthetic persistent disk data"), 0600); err != nil { | |
| 13 | 新增: t.Fatal(err) | |
| 14 | 新增: } | |
| 15 | 新增:} | |
| @@ -0,0 +1,246 @@ | ||
| 1 | 新增://go:build windows | |
| 2 | 新增: | |
| 3 | 新增:package guestos | |
| 4 | 新增: | |
| 5 | 新增:import ( | |
| 6 | 新增: "context" | |
| 7 | 新增: "errors" | |
| 8 | 新增: "fmt" | |
| 9 | 新增: "os" | |
| 10 | 新增: "path/filepath" | |
| 11 | 新增: "runtime" | |
| 12 | 新增: "unsafe" | |
| 13 | 新增: | |
| 14 | 新增: "golang.org/x/sys/windows" | |
| 15 | 新增:) | |
| 16 | 新增: | |
| 17 | 新增:var storageVirtualDiskDLL = windows.NewLazySystemDLL("virtdisk.dll") | |
| 18 | 新增: | |
| 19 | 新增:type storageVirtualDiskType struct { | |
| 20 | 新增: Device uint32 | |
| 21 | 新增: Vendor windows.GUID | |
| 22 | 新增:} | |
| 23 | 新增: | |
| 24 | 新增:var storageVHDXType = storageVirtualDiskType{ | |
| 25 | 新增: Device: 3, | |
| 26 | 新增: Vendor: windows.GUID{Data1: 0xec984aec, Data2: 0xa0f9, Data3: 0x47e9, Data4: [8]byte{0x90, 0x1f, 0x71, 0x41, 0x5a, 0x66, 0x34, 0x5b}}, | |
| 27 | 新增:} | |
| 28 | 新增: | |
| 29 | 新增:// CREATE_VIRTUAL_DISK_PARAMETERS version 2 has an eight-byte aligned union. | |
| 30 | 新增:type storageVirtualDiskCreate struct { | |
| 31 | 新增: Version uint32 | |
| 32 | 新增: _ uint32 | |
| 33 | 新增: Identifier windows.GUID | |
| 34 | 新增: MaximumSize uint64 | |
| 35 | 新增: BlockSize uint32 | |
| 36 | 新增: SectorSize uint32 | |
| 37 | 新增: PhysicalSector uint32 | |
| 38 | 新增: ParentPath *uint16 | |
| 39 | 新增: SourcePath *uint16 | |
| 40 | 新增: OpenFlags uint32 | |
| 41 | 新增: ParentType storageVirtualDiskType | |
| 42 | 新增: SourceType storageVirtualDiskType | |
| 43 | 新增: Resiliency windows.GUID | |
| 44 | 新增:} | |
| 45 | 新增: | |
| 46 | 新增:type storageVirtualDiskMetadata struct { | |
| 47 | 新增: Subtype uint32 | |
| 48 | 新增: Identifier windows.GUID | |
| 49 | 新增: VirtualSize uint64 | |
| 50 | 新增: BlockSize uint32 | |
| 51 | 新增: SectorSize uint32 | |
| 52 | 新增: PhysicalSector uint32 | |
| 53 | 新增:} | |
| 54 | 新增: | |
| 55 | 新增:func readWindowsStorageDisk(path string) (storageVirtualDiskMetadata, error) { | |
| 56 | 新增: var metadata storageVirtualDiskMetadata | |
| 57 | 新增: name, err := windows.UTF16PtrFromString(path) | |
| 58 | 新增: if err != nil { | |
| 59 | 新增: return metadata, err | |
| 60 | 新增: } | |
| 61 | 新增: parameters := struct { | |
| 62 | 新增: Version uint32 | |
| 63 | 新增: InfoOnly int32 | |
| 64 | 新增: ReadOnly int32 | |
| 65 | 新增: Resiliency windows.GUID | |
| 66 | 新增: }{Version: 2, InfoOnly: 1, ReadOnly: 1} | |
| 67 | 新增: var handle windows.Handle | |
| 68 | 新增: status, _, _ := storageVirtualDiskDLL.NewProc("OpenVirtualDisk").Call( | |
| 69 | 新增: uintptr(unsafe.Pointer(&storageVHDXType)), uintptr(unsafe.Pointer(name)), 0, 0, | |
| 70 | 新增: uintptr(unsafe.Pointer(¶meters)), uintptr(unsafe.Pointer(&handle))) | |
| 71 | 新增: runtime.KeepAlive(name) | |
| 72 | 新增: if status != 0 { | |
| 73 | 新增: return metadata, fmt.Errorf("读取 Windows 客机磁盘失败:%w", windows.Errno(status)) | |
| 74 | 新增: } | |
| 75 | 新增: defer windows.CloseHandle(handle) | |
| 76 | 新增: for _, version := range []uint32{1, 2, 7, 10} { | |
| 77 | 新增: information := struct { | |
| 78 | 新增: Version uint32 | |
| 79 | 新增: _ uint32 | |
| 80 | 新增: Data [4]uint64 | |
| 81 | 新增: }{Version: version} | |
| 82 | 新增: size, used := uint32(unsafe.Sizeof(information)), uint32(0) | |
| 83 | 新增: status, _, _ = storageVirtualDiskDLL.NewProc("GetVirtualDiskInformation").Call( | |
| 84 | 新增: uintptr(handle), uintptr(unsafe.Pointer(&size)), uintptr(unsafe.Pointer(&information)), uintptr(unsafe.Pointer(&used))) | |
| 85 | 新增: if status != 0 { | |
| 86 | 新增: return metadata, fmt.Errorf("读取 Windows 客机磁盘属性失败:%w", windows.Errno(status)) | |
| 87 | 新增: } | |
| 88 | 新增: switch version { | |
| 89 | 新增: case 1: | |
| 90 | 新增: metadata.VirtualSize = information.Data[0] | |
| 91 | 新增: metadata.BlockSize = uint32(information.Data[2]) | |
| 92 | 新增: metadata.SectorSize = uint32(information.Data[2] >> 32) | |
| 93 | 新增: case 2: | |
| 94 | 新增: metadata.Identifier = *(*windows.GUID)(unsafe.Pointer(&information.Data[0])) | |
| 95 | 新增: case 7: | |
| 96 | 新增: metadata.Subtype = uint32(information.Data[0]) | |
| 97 | 新增: case 10: | |
| 98 | 新增: metadata.PhysicalSector = uint32(information.Data[0]) | |
| 99 | 新增: } | |
| 100 | 新增: } | |
| 101 | 新增: return metadata, nil | |
| 102 | 新增:} | |
| 103 | 新增: | |
| 104 | 新增:// Cancellation must finish native I/O before its pinned OVERLAPPED, file | |
| 105 | 新增:// handles, or source-disk protection can be released by the migration caller. | |
| 106 | 新增:func createWindowsStorageDisk(ctx context.Context, path string, parameters *storageVirtualDiskCreate, flags uint32) (err error) { | |
| 107 | 新增: if err := ctx.Err(); err != nil { | |
| 108 | 新增: return err | |
| 109 | 新增: } | |
| 110 | 新增: name, err := windows.UTF16PtrFromString(path) | |
| 111 | 新增: if err != nil { | |
| 112 | 新增: return err | |
| 113 | 新增: } | |
| 114 | 新增: event, err := windows.CreateEvent(nil, 1, 0, nil) | |
| 115 | 新增: if err != nil { | |
| 116 | 新增: return err | |
| 117 | 新增: } | |
| 118 | 新增: defer windows.CloseHandle(event) | |
| 119 | 新增: overlapped := &windows.Overlapped{HEvent: event} | |
| 120 | 新增: var pinned runtime.Pinner | |
| 121 | 新增: pinned.Pin(overlapped) | |
| 122 | 新增: pinned.Pin(parameters) | |
| 123 | 新增: pinned.Pin(name) | |
| 124 | 新增: if parameters.SourcePath != nil { | |
| 125 | 新增: pinned.Pin(parameters.SourcePath) | |
| 126 | 新增: } | |
| 127 | 新增: if parameters.ParentPath != nil { | |
| 128 | 新增: pinned.Pin(parameters.ParentPath) | |
| 129 | 新增: } | |
| 130 | 新增: defer pinned.Unpin() | |
| 131 | 新增: var handle windows.Handle | |
| 132 | 新增: status, _, _ := storageVirtualDiskDLL.NewProc("CreateVirtualDisk").Call( | |
| 133 | 新增: uintptr(unsafe.Pointer(&storageVHDXType)), uintptr(unsafe.Pointer(name)), 0, 0, uintptr(flags), 0, | |
| 134 | 新增: uintptr(unsafe.Pointer(parameters)), uintptr(unsafe.Pointer(overlapped)), uintptr(unsafe.Pointer(&handle))) | |
| 135 | 新增: if handle != 0 && handle != windows.InvalidHandle { | |
| 136 | 新增: defer func() { err = errors.Join(err, windows.CloseHandle(handle)) }() | |
| 137 | 新增: } | |
| 138 | 新增: if status != 0 && status != uintptr(windows.ERROR_IO_PENDING) { | |
| 139 | 新增: return fmt.Errorf("创建独立 Windows 客机磁盘失败:%w", windows.Errno(status)) | |
| 140 | 新增: } | |
| 141 | 新增: if status == 0 { | |
| 142 | 新增: return ctx.Err() | |
| 143 | 新增: } | |
| 144 | 新增: cancelDone := make(chan struct{}) | |
| 145 | 新增: var cancelErr error | |
| 146 | 新增: stopCancel := context.AfterFunc(ctx, func() { | |
| 147 | 新增: cancelErr = windows.CancelIoEx(handle, overlapped) | |
| 148 | 新增: close(cancelDone) | |
| 149 | 新增: }) | |
| 150 | 新增: wait, waitErr := windows.WaitForSingleObject(event, windows.INFINITE) | |
| 151 | 新增: if !stopCancel() { | |
| 152 | 新增: <-cancelDone | |
| 153 | 新增: } | |
| 154 | 新增: if waitErr != nil || wait != windows.WAIT_OBJECT_0 { | |
| 155 | 新增: // A wait failure must still drain the operation before releasing memory. | |
| 156 | 新增: _ = windows.CancelIoEx(handle, overlapped) | |
| 157 | 新增: var transferred uint32 | |
| 158 | 新增: drainErr := windows.GetOverlappedResult(handle, overlapped, &transferred, true) | |
| 159 | 新增: return errors.Join(fmt.Errorf("等待 Windows 磁盘复制完成失败 (%d)", wait), waitErr, drainErr) | |
| 160 | 新增: } | |
| 161 | 新增: if errors.Is(cancelErr, windows.ERROR_NOT_FOUND) { | |
| 162 | 新增: cancelErr = nil // Completion can win the cancellation race. | |
| 163 | 新增: } | |
| 164 | 新增: if err := ctx.Err(); err != nil { | |
| 165 | 新增: return errors.Join(err, cancelErr) | |
| 166 | 新增: } | |
| 167 | 新增: progress := struct { | |
| 168 | 新增: Status uint32 | |
| 169 | 新增: Current, Total uint64 | |
| 170 | 新增: }{} | |
| 171 | 新增: status, _, _ = storageVirtualDiskDLL.NewProc("GetVirtualDiskOperationProgress").Call( | |
| 172 | 新增: uintptr(handle), uintptr(unsafe.Pointer(overlapped)), uintptr(unsafe.Pointer(&progress))) | |
| 173 | 新增: if status != 0 { | |
| 174 | 新增: return fmt.Errorf("查询 Windows 磁盘复制结果失败:%w", windows.Errno(status)) | |
| 175 | 新增: } | |
| 176 | 新增: if progress.Status != 0 { | |
| 177 | 新增: return fmt.Errorf("Windows 磁盘复制失败:%w", windows.Errno(progress.Status)) | |
| 178 | 新增: } | |
| 179 | 新增: return nil | |
| 180 | 新增:} | |
| 181 | 新增: | |
| 182 | 新增:func prepareWindowsStorageDisk(ctx context.Context, source, copied string) (err error) { | |
| 183 | 新增: if err := ctx.Err(); err != nil { | |
| 184 | 新增: return err | |
| 185 | 新增: } | |
| 186 | 新增: before, err := readWindowsStorageDisk(source) | |
| 187 | 新增: if err != nil { | |
| 188 | 新增: return err | |
| 189 | 新增: } | |
| 190 | 新增: if before.Subtype == 2 || before.Subtype == 3 { | |
| 191 | 新增: return nil | |
| 192 | 新增: } | |
| 193 | 新增: if before.Subtype != 4 { | |
| 194 | 新增: return fmt.Errorf("Windows 客机磁盘类型无效 (%d)", before.Subtype) | |
| 195 | 新增: } | |
| 196 | 新增: original, err := os.Stat(source) | |
| 197 | 新增: if err != nil { | |
| 198 | 新增: return err | |
| 199 | 新增: } | |
| 200 | 新增: destination, err := os.Stat(copied) | |
| 201 | 新增: if err != nil { | |
| 202 | 新增: return err | |
| 203 | 新增: } | |
| 204 | 新增: if os.SameFile(original, destination) { | |
| 205 | 新增: return errors.New("独立磁盘副本与原磁盘必须使用不同文件") | |
| 206 | 新增: } | |
| 207 | 新增: folder, err := os.MkdirTemp(filepath.Dir(copied), ".windows-disk-*") | |
| 208 | 新增: if err != nil { | |
| 209 | 新增: return err | |
| 210 | 新增: } | |
| 211 | 新增: defer func() { err = errors.Join(err, os.RemoveAll(folder)) }() | |
| 212 | 新增: path := filepath.Join(folder, "disk.vhdx") | |
| 213 | 新增: name, err := windows.UTF16PtrFromString(source) | |
| 214 | 新增: if err != nil { | |
| 215 | 新增: return err | |
| 216 | 新增: } | |
| 217 | 新增: parameters := storageVirtualDiskCreate{ | |
| 218 | 新增: Version: 2, Identifier: before.Identifier, BlockSize: before.BlockSize, | |
| 219 | 新增: SectorSize: before.SectorSize, PhysicalSector: before.PhysicalSector, | |
| 220 | 新增: SourcePath: name, SourceType: storageVHDXType, | |
| 221 | 新增: } | |
| 222 | 新增: if err := createWindowsStorageDisk(ctx, path, ¶meters, 0); err != nil { | |
| 223 | 新增: return err | |
| 224 | 新增: } | |
| 225 | 新增: after, err := readWindowsStorageDisk(path) | |
| 226 | 新增: if err != nil { | |
| 227 | 新增: return err | |
| 228 | 新增: } | |
| 229 | 新增: expected := before | |
| 230 | 新增: expected.Subtype = 3 | |
| 231 | 新增: if after != expected { | |
| 232 | 新增: return errors.New("独立磁盘副本的标识或磁盘参数不一致") | |
| 233 | 新增: } | |
| 234 | 新增: if err := ctx.Err(); err != nil { | |
| 235 | 新增: return err | |
| 236 | 新增: } | |
| 237 | 新增: from, err := windows.UTF16PtrFromString(path) | |
| 238 | 新增: if err != nil { | |
| 239 | 新增: return err | |
| 240 | 新增: } | |
| 241 | 新增: to, err := windows.UTF16PtrFromString(copied) | |
| 242 | 新增: if err != nil { | |
| 243 | 新增: return err | |
| 244 | 新增: } | |
| 245 | 新增: return windows.MoveFileEx(from, to, windows.MOVEFILE_REPLACE_EXISTING|windows.MOVEFILE_WRITE_THROUGH) | |
| 246 | 新增:} | |
| @@ -0,0 +1,299 @@ | ||
| 1 | 新增://go:build windows | |
| 2 | 新增: | |
| 3 | 新增:package guestos | |
| 4 | 新增: | |
| 5 | 新增:import ( | |
| 6 | 新增: "bytes" | |
| 7 | 新增: "context" | |
| 8 | 新增: "crypto/sha256" | |
| 9 | 新增: "encoding/binary" | |
| 10 | 新增: "errors" | |
| 11 | 新增: "io" | |
| 12 | 新增: "os" | |
| 13 | 新增: "path/filepath" | |
| 14 | 新增: "reflect" | |
| 15 | 新增: "sync/atomic" | |
| 16 | 新增: "testing" | |
| 17 | 新增: "unsafe" | |
| 18 | 新增: | |
| 19 | 新增: "github.com/sylvinus/agent-vm/internal/cage" | |
| 20 | 新增: "golang.org/x/sys/windows" | |
| 21 | 新增:) | |
| 22 | 新增: | |
| 23 | 新增:func createWindowsStorageFixtureDisk(t *testing.T, path string) { | |
| 24 | 新增: t.Helper() | |
| 25 | 新增: createWindowsStorageTestDisk(t, path, "", 0) | |
| 26 | 新增:} | |
| 27 | 新增: | |
| 28 | 新增:func createWindowsStorageTestDisk(t *testing.T, path, parent string, flags uint32) { | |
| 29 | 新增: t.Helper() | |
| 30 | 新增: if unsafe.Sizeof(storageVirtualDiskCreate{}) != 128 { | |
| 31 | 新增: t.Fatal("unexpected native VHDX parameter layout") | |
| 32 | 新增: } | |
| 33 | 新增: parameters := storageVirtualDiskCreate{ | |
| 34 | 新增: Version: 2, MaximumSize: 8 << 20, BlockSize: 2 << 20, | |
| 35 | 新增: SectorSize: 512, PhysicalSector: 4096, | |
| 36 | 新增: } | |
| 37 | 新增: if parent != "" { | |
| 38 | 新增: var err error | |
| 39 | 新增: parameters.ParentPath, err = windows.UTF16PtrFromString(parent) | |
| 40 | 新增: if err != nil { | |
| 41 | 新增: t.Fatal(err) | |
| 42 | 新增: } | |
| 43 | 新增: parameters.MaximumSize, parameters.ParentType = 0, storageVHDXType | |
| 44 | 新增: } | |
| 45 | 新增: if err := createWindowsStorageDisk(context.Background(), path, ¶meters, flags); err != nil { | |
| 46 | 新增: t.Fatal(err) | |
| 47 | 新增: } | |
| 48 | 新增:} | |
| 49 | 新增: | |
| 50 | 新增:func windowsStorageDiskDigest(t *testing.T, path string) [32]byte { | |
| 51 | 新增: t.Helper() | |
| 52 | 新增: file, err := os.Open(path) | |
| 53 | 新增: if err != nil { | |
| 54 | 新增: t.Fatal(err) | |
| 55 | 新增: } | |
| 56 | 新增: defer file.Close() | |
| 57 | 新增: hash := sha256.New() | |
| 58 | 新增: if _, err := io.Copy(hash, file); err != nil { | |
| 59 | 新增: t.Fatal(err) | |
| 60 | 新增: } | |
| 61 | 新增: return [32]byte(hash.Sum(nil)) | |
| 62 | 新增:} | |
| 63 | 新增: | |
| 64 | 新增:func windowsStorageDiskEntries(t *testing.T, path string) []string { | |
| 65 | 新增: t.Helper() | |
| 66 | 新增: entries, err := os.ReadDir(path) | |
| 67 | 新增: if err != nil { | |
| 68 | 新增: t.Fatal(err) | |
| 69 | 新增: } | |
| 70 | 新增: names := make([]string, len(entries)) | |
| 71 | 新增: for index, entry := range entries { | |
| 72 | 新增: names[index] = entry.Name() | |
| 73 | 新增: } | |
| 74 | 新增: return names | |
| 75 | 新增:} | |
| 76 | 新增: | |
| 77 | 新增:func TestWindowsStorageDiskIndependentCopiesUntouched(t *testing.T) { | |
| 78 | 新增: for _, test := range []struct { | |
| 79 | 新增: name string | |
| 80 | 新增: flags uint32 | |
| 81 | 新增: }{{"dynamic", 0}, {"fixed", 1}} { | |
| 82 | 新增: t.Run(test.name, func(t *testing.T) { | |
| 83 | 新增: root := t.TempDir() | |
| 84 | 新增: source, copied := filepath.Join(root, "source.vhdx"), filepath.Join(root, "copied.vhdx") | |
| 85 | 新增: createWindowsStorageTestDisk(t, source, "", test.flags) | |
| 86 | 新增: digest := windowsStorageDiskDigest(t, source) | |
| 87 | 新增: if err := cage.CopyStorageFile(context.Background(), source, copied); err != nil { | |
| 88 | 新增: t.Fatal(err) | |
| 89 | 新增: } | |
| 90 | 新增: if err := prepareWindowsStorageDisk(context.Background(), source, copied); err != nil { | |
| 91 | 新增: t.Fatal(err) | |
| 92 | 新增: } | |
| 93 | 新增: if windowsStorageDiskDigest(t, source) != digest || windowsStorageDiskDigest(t, copied) != digest { | |
| 94 | 新增: t.Fatal("standalone disk bytes changed") | |
| 95 | 新增: } | |
| 96 | 新增: if _, err := readWindowsStorageDisk(copied); err != nil { | |
| 97 | 新增: t.Fatal("copied VHDX could not open with native flags NONE", err) | |
| 98 | 新增: } | |
| 99 | 新增: }) | |
| 100 | 新增: } | |
| 101 | 新增:} | |
| 102 | 新增: | |
| 103 | 新增:// These fixtures modify only payload blocks and BAT entries of freshly created | |
| 104 | 新增:// VHDX files. A fully present differencing block does not require a bitmap. | |
| 105 | 新增:func windowsStorageDiskPayload(t *testing.T, file *os.File, block uint64) (int64, uint64) { | |
| 106 | 新增: t.Helper() | |
| 107 | 新增: table := make([]byte, 64<<10) | |
| 108 | 新增: if _, err := file.ReadAt(table, 192<<10); err != nil { | |
| 109 | 新增: t.Fatal(err) | |
| 110 | 新增: } | |
| 111 | 新增: if string(table[:4]) != "regi" || binary.LittleEndian.Uint32(table[8:]) > 2047 { | |
| 112 | 新增: t.Fatal("invalid VHDX region table") | |
| 113 | 新增: } | |
| 114 | 新增: bat := []byte{0x66, 0x77, 0xc2, 0x2d, 0x23, 0xf6, 0x00, 0x42, 0x9d, 0x64, 0x11, 0x5e, 0x9b, 0xfd, 0x4a, 0x08} | |
| 115 | 新增: for index := uint32(0); index < binary.LittleEndian.Uint32(table[8:]); index++ { | |
| 116 | 新增: entry := table[16+int(index)*32:] | |
| 117 | 新增: if bytes.Equal(entry[:16], bat) { | |
| 118 | 新增: position := int64(binary.LittleEndian.Uint64(entry[16:])) + int64(block*8) | |
| 119 | 新增: var value [8]byte | |
| 120 | 新增: if _, err := file.ReadAt(value[:], position); err != nil { | |
| 121 | 新增: t.Fatal(err) | |
| 122 | 新增: } | |
| 123 | 新增: return position, binary.LittleEndian.Uint64(value[:]) | |
| 124 | 新增: } | |
| 125 | 新增: } | |
| 126 | 新增: t.Fatal("VHDX BAT region missing") | |
| 127 | 新增: return 0, 0 | |
| 128 | 新增:} | |
| 129 | 新增: | |
| 130 | 新增:func writeWindowsStorageDiskPayload(t *testing.T, path string, block uint64, data []byte) { | |
| 131 | 新增: t.Helper() | |
| 132 | 新增: file, err := os.OpenFile(path, os.O_RDWR, 0) | |
| 133 | 新增: if err != nil { | |
| 134 | 新增: t.Fatal(err) | |
| 135 | 新增: } | |
| 136 | 新增: defer file.Close() | |
| 137 | 新增: position, value := windowsStorageDiskPayload(t, file, block) | |
| 138 | 新增: offset := value & ^uint64((1<<20)-1) | |
| 139 | 新增: if value&7 != 6 { | |
| 140 | 新增: info, err := file.Stat() | |
| 141 | 新增: if err != nil { | |
| 142 | 新增: t.Fatal(err) | |
| 143 | 新增: } | |
| 144 | 新增: offset = uint64(info.Size()+(1<<20)-1) & ^uint64((1<<20)-1) | |
| 145 | 新增: } | |
| 146 | 新增: if _, err := file.WriteAt(data, int64(offset)); err != nil { | |
| 147 | 新增: t.Fatal(err) | |
| 148 | 新增: } | |
| 149 | 新增: var entry [8]byte | |
| 150 | 新增: binary.LittleEndian.PutUint64(entry[:], offset|6) | |
| 151 | 新增: if _, err := file.WriteAt(entry[:], position); err != nil { | |
| 152 | 新增: t.Fatal(err) | |
| 153 | 新增: } | |
| 154 | 新增: if err := file.Sync(); err != nil { | |
| 155 | 新增: t.Fatal(err) | |
| 156 | 新增: } | |
| 157 | 新增:} | |
| 158 | 新增: | |
| 159 | 新增:func readWindowsStorageDiskPayload(t *testing.T, path string, block uint64) []byte { | |
| 160 | 新增: t.Helper() | |
| 161 | 新增: file, err := os.Open(path) | |
| 162 | 新增: if err != nil { | |
| 163 | 新增: t.Fatal(err) | |
| 164 | 新增: } | |
| 165 | 新增: defer file.Close() | |
| 166 | 新增: _, value := windowsStorageDiskPayload(t, file, block) | |
| 167 | 新增: if value&7 != 6 { | |
| 168 | 新增: t.Fatal("materialized VHDX block is not fully present", block, value&7) | |
| 169 | 新增: } | |
| 170 | 新增: data := make([]byte, 2<<20) | |
| 171 | 新增: if _, err := file.ReadAt(data, int64(value & ^uint64((1<<20)-1))); err != nil { | |
| 172 | 新增: t.Fatal(err) | |
| 173 | 新增: } | |
| 174 | 新增: return data | |
| 175 | 新增:} | |
| 176 | 新增: | |
| 177 | 新增:func windowsStorageDifferencingFixture(t *testing.T) (root, parent, source, copied string, parentData, childData []byte) { | |
| 178 | 新增: t.Helper() | |
| 179 | 新增: root = t.TempDir() | |
| 180 | 新增: parent, source, copied = filepath.Join(root, "parent.vhdx"), filepath.Join(root, "child.vhdx"), filepath.Join(root, "copied.vhdx") | |
| 181 | 新增: createWindowsStorageTestDisk(t, parent, "", 1) | |
| 182 | 新增: parentData, childData = make([]byte, 2<<20), make([]byte, 2<<20) | |
| 183 | 新增: copy(parentData[4096:], []byte("parent inherited user data")) | |
| 184 | 新增: copy(childData[8192:], []byte("child changed user data")) | |
| 185 | 新增: writeWindowsStorageDiskPayload(t, parent, 0, parentData) | |
| 186 | 新增: createWindowsStorageTestDisk(t, source, parent, 0) | |
| 187 | 新增: writeWindowsStorageDiskPayload(t, source, 1, childData) | |
| 188 | 新增: if err := cage.CopyStorageFile(context.Background(), source, copied); err != nil { | |
| 189 | 新增: t.Fatal(err) | |
| 190 | 新增: } | |
| 191 | 新增: return | |
| 192 | 新增:} | |
| 193 | 新增: | |
| 194 | 新增:func TestWindowsStorageDiskDifferencingCopyIndependent(t *testing.T) { | |
| 195 | 新增: root, parent, source, copied, parentData, childData := windowsStorageDifferencingFixture(t) | |
| 196 | 新增: beforeEntries := windowsStorageDiskEntries(t, root) | |
| 197 | 新增: sourceHash, parentHash := windowsStorageDiskDigest(t, source), windowsStorageDiskDigest(t, parent) | |
| 198 | 新增: before, err := readWindowsStorageDisk(source) | |
| 199 | 新增: if err != nil { | |
| 200 | 新增: t.Fatal(err) | |
| 201 | 新增: } | |
| 202 | 新增: if err := prepareWindowsStorageDisk(context.Background(), source, copied); err != nil { | |
| 203 | 新增: t.Fatal(err) | |
| 204 | 新增: } | |
| 205 | 新增: after, err := readWindowsStorageDisk(copied) | |
| 206 | 新增: if err != nil || before.Subtype != 4 || after.Subtype != 3 || after.Identifier != before.Identifier { | |
| 207 | 新增: t.Fatal("differencing disk identity was lost", before, after, err) | |
| 208 | 新增: } | |
| 209 | 新增: if !bytes.Equal(readWindowsStorageDiskPayload(t, copied, 0), parentData) || !bytes.Equal(readWindowsStorageDiskPayload(t, copied, 1), childData) { | |
| 210 | 新增: t.Fatal("materialization changed logical disk data") | |
| 211 | 新增: } | |
| 212 | 新增: if sourceHash != windowsStorageDiskDigest(t, source) || parentHash != windowsStorageDiskDigest(t, parent) { | |
| 213 | 新增: t.Fatal("materialization modified original disk chain") | |
| 214 | 新增: } | |
| 215 | 新增: if !reflect.DeepEqual(beforeEntries, windowsStorageDiskEntries(t, root)) { | |
| 216 | 新增: t.Fatal("materialization left temporary files") | |
| 217 | 新增: } | |
| 218 | 新增: moved := parent + ".moved" | |
| 219 | 新增: if err := os.Rename(parent, moved); err != nil { | |
| 220 | 新增: t.Fatal(err) | |
| 221 | 新增: } | |
| 222 | 新增: defer func() { | |
| 223 | 新增: if err := os.Rename(moved, parent); err != nil { | |
| 224 | 新增: t.Error(err) | |
| 225 | 新增: } | |
| 226 | 新增: }() | |
| 227 | 新增: if _, err := readWindowsStorageDisk(source); err == nil { | |
| 228 | 新增: t.Fatal("missing-parent fixture still opened") | |
| 229 | 新增: } | |
| 230 | 新增: if _, err := readWindowsStorageDisk(copied); err != nil { | |
| 231 | 新增: t.Fatal("materialized disk retained original parent dependency", err) | |
| 232 | 新增: } | |
| 233 | 新增:} | |
| 234 | 新增: | |
| 235 | 新增:// The context cancels when the production function registers native-I/O | |
| 236 | 新增:// cancellation, after CreateVirtualDisk has returned ERROR_IO_PENDING. | |
| 237 | 新增:type windowsStorageCancelAtWait struct { | |
| 238 | 新增: context.Context | |
| 239 | 新增: done chan struct{} | |
| 240 | 新增: cancelled atomic.Bool | |
| 241 | 新增:} | |
| 242 | 新增: | |
| 243 | 新增:func (ctx *windowsStorageCancelAtWait) Done() <-chan struct{} { return ctx.done } | |
| 244 | 新增:func (ctx *windowsStorageCancelAtWait) Err() error { | |
| 245 | 新增: if ctx.cancelled.Load() { | |
| 246 | 新增: return context.Canceled | |
| 247 | 新增: } | |
| 248 | 新增: return nil | |
| 249 | 新增:} | |
| 250 | 新增:func (ctx *windowsStorageCancelAtWait) AfterFunc(callback func()) func() bool { | |
| 251 | 新增: ctx.cancelled.Store(true) | |
| 252 | 新增: close(ctx.done) | |
| 253 | 新增: go callback() | |
| 254 | 新增: return func() bool { return false } | |
| 255 | 新增:} | |
| 256 | 新增: | |
| 257 | 新增:func TestWindowsStorageDiskCancellationAndReplacementFailure(t *testing.T) { | |
| 258 | 新增: for _, mode := range []string{"cancel_before_start", "cancel_native_copy", "replacement_denied"} { | |
| 259 | 新增: t.Run(mode, func(t *testing.T) { | |
| 260 | 新增: root, parent, source, copied, _, _ := windowsStorageDifferencingFixture(t) | |
| 261 | 新增: entries := windowsStorageDiskEntries(t, root) | |
| 262 | 新增: sourceHash, copiedHash, parentHash := windowsStorageDiskDigest(t, source), windowsStorageDiskDigest(t, copied), windowsStorageDiskDigest(t, parent) | |
| 263 | 新增: ctx := context.Background() | |
| 264 | 新增: if mode == "cancel_before_start" { | |
| 265 | 新增: cancelled, cancel := context.WithCancel(ctx) | |
| 266 | 新增: cancel() | |
| 267 | 新增: ctx = cancelled | |
| 268 | 新增: } | |
| 269 | 新增: if mode == "cancel_native_copy" { | |
| 270 | 新增: ctx = &windowsStorageCancelAtWait{Context: ctx, done: make(chan struct{})} | |
| 271 | 新增: } | |
| 272 | 新增: if mode == "replacement_denied" { | |
| 273 | 新增: name, err := windows.UTF16PtrFromString(copied) | |
| 274 | 新增: if err != nil { | |
| 275 | 新增: t.Fatal(err) | |
| 276 | 新增: } | |
| 277 | 新增: handle, err := windows.CreateFile(name, windows.GENERIC_READ, windows.FILE_SHARE_READ|windows.FILE_SHARE_WRITE, nil, windows.OPEN_EXISTING, 0, 0) | |
| 278 | 新增: if err != nil { | |
| 279 | 新增: t.Fatal(err) | |
| 280 | 新增: } | |
| 281 | 新增: defer windows.CloseHandle(handle) | |
| 282 | 新增: } | |
| 283 | 新增: err := prepareWindowsStorageDisk(ctx, source, copied) | |
| 284 | 新增: if mode == "replacement_denied" { | |
| 285 | 新增: if !errors.Is(err, windows.ERROR_SHARING_VIOLATION) && !errors.Is(err, windows.ERROR_ACCESS_DENIED) { | |
| 286 | 新增: t.Fatal("replacement failure was not reported", err) | |
| 287 | 新增: } | |
| 288 | 新增: } else if !errors.Is(err, context.Canceled) { | |
| 289 | 新增: t.Fatal("native disk cancellation was not reported", err) | |
| 290 | 新增: } | |
| 291 | 新增: if windowsStorageDiskDigest(t, source) != sourceHash || windowsStorageDiskDigest(t, copied) != copiedHash || windowsStorageDiskDigest(t, parent) != parentHash { | |
| 292 | 新增: t.Fatal("failed materialization modified a retained disk") | |
| 293 | 新增: } | |
| 294 | 新增: if !reflect.DeepEqual(entries, windowsStorageDiskEntries(t, root)) { | |
| 295 | 新增: t.Fatal("failed materialization left temporary files") | |
| 296 | 新增: } | |
| 297 | 新增: }) | |
| 298 | 新增: } | |
| 299 | 新增:} | |
| @@ -5,6 +5,7 @@ package guestos | ||
| 5 | 5 | import ( |
| 6 | 6 | "context" |
| 7 | 7 | "errors" |
| 8 | 新增: "io" | |
| 8 | 9 | "os" |
| 9 | 10 | "path/filepath" |
| 10 | 11 | |
| @@ -15,6 +16,14 @@ func windowsHostStorage(context.Context, uuid.UUID, windowsHostStorageRequest) ( | ||
| 15 | 16 | return windowsHostStorageState{}, errors.New("Windows 客机存储迁移需要 Windows Hyper-V 主机") |
| 16 | 17 | } |
| 17 | 18 | |
| 19 | 新增:func WindowsPrivateStoragePaths() []string { return nil } | |
| 20 | 新增: | |
| 21 | 新增:func prepareWindowsStorageDisk(context.Context, string, string) error { return nil } | |
| 22 | 新增: | |
| 23 | 新增:func RepairWindowsHostManager(context.Context, string, string, io.Writer, io.Writer) error { | |
| 24 | 新增: return errors.New("Windows 系统助手需要在原 Windows 主机上恢复") | |
| 25 | 新增:} | |
| 26 | 新增: | |
| 18 | 27 | func replaceWindowsStorageProfile(path string, data []byte) error { |
| 19 | 28 | file, err := os.CreateTemp(filepath.Dir(path), ".windows-storage-*") |
| 20 | 29 | if err != nil { |
| @@ -0,0 +1,32 @@ | ||
| 1 | 新增:package guestos | |
| 2 | 新增: | |
| 3 | 新增:import ( | |
| 4 | 新增: "os/exec" | |
| 5 | 新增: "path/filepath" | |
| 6 | 新增: "runtime" | |
| 7 | 新增: "testing" | |
| 8 | 新增:) | |
| 9 | 新增: | |
| 10 | 新增:func TestWindowsStoragePowerShellTransition(t *testing.T) { | |
| 11 | 新增: command := "pwsh" | |
| 12 | 新增: if runtime.GOOS == "windows" { | |
| 13 | 新增: command = "powershell.exe" | |
| 14 | 新增: } | |
| 15 | 新增: powershell, err := exec.LookPath(command) | |
| 16 | 新增: if err != nil { | |
| 17 | 新增: t.Skip("requires PowerShell for the native storage command contract") | |
| 18 | 新增: } | |
| 19 | 新增: source, err := filepath.Abs("windows_storage.ps1") | |
| 20 | 新增: if err != nil { | |
| 21 | 新增: t.Fatal(err) | |
| 22 | 新增: } | |
| 23 | 新增: test, err := filepath.Abs(filepath.Join("testdata", "windows_storage.ps1")) | |
| 24 | 新增: if err != nil { | |
| 25 | 新增: t.Fatal(err) | |
| 26 | 新增: } | |
| 27 | 新增: output, err := exec.Command(powershell, "-NoLogo", "-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-File", test, "-Implementation", source).CombinedOutput() | |
| 28 | 新增: if err != nil { | |
| 29 | 新增: t.Fatalf("native storage contract: %v\n%s", err, output) | |
| 30 | 新增: } | |
| 31 | 新增: t.Log(string(output)) | |
| 32 | 新增:} | |
| @@ -0,0 +1,245 @@ | ||
| 1 | 新增:package guestos | |
| 2 | 新增: | |
| 3 | 新增:import ( | |
| 4 | 新增: "bytes" | |
| 5 | 新增: "context" | |
| 6 | 新增: "errors" | |
| 7 | 新增: "os" | |
| 8 | 新增: "path/filepath" | |
| 9 | 新增: "reflect" | |
| 10 | 新增: "testing" | |
| 11 | 新增: | |
| 12 | 新增: "github.com/google/uuid" | |
| 13 | 新增: "github.com/sylvinus/agent-vm/internal/cage" | |
| 14 | 新增:) | |
| 15 | 新增: | |
| 16 | 新增:type windowsStorageBrokerFixture struct { | |
| 17 | 新增: t *testing.T | |
| 18 | 新增: vm uuid.UUID | |
| 19 | 新增: disk windowsStorageDisk | |
| 20 | 新增: layout *windowsVMStorageLayout | |
| 21 | 新增: before windowsStorageDisk | |
| 22 | 新增: pending string | |
| 23 | 新增: events []string | |
| 24 | 新增: failAttach bool | |
| 25 | 新增: failRecovery bool | |
| 26 | 新增:} | |
| 27 | 新增: | |
| 28 | 新增:func (broker *windowsStorageBrokerFixture) call(_ context.Context, id uuid.UUID, input windowsHostStorageRequest) (windowsHostStorageState, error) { | |
| 29 | 新增: broker.t.Helper() | |
| 30 | 新增: if id != broker.vm || input.validate() != nil { | |
| 31 | 新增: broker.t.Fatal("invalid fixed-VM request", input) | |
| 32 | 新增: } | |
| 33 | 新增: broker.events = append(broker.events, input.Action) | |
| 34 | 新增: switch input.Action { | |
| 35 | 新增: case "status": | |
| 36 | 新增: return windowsHostStorageState{Disk: broker.disk, Pending: broker.pending, Layout: broker.layout}, nil | |
| 37 | 新增: case "begin": | |
| 38 | 新增: broker.before, broker.pending = broker.disk, input.ID | |
| 39 | 新增: case "attach": | |
| 40 | 新增: if input.ID != broker.pending { | |
| 41 | 新增: broker.t.Fatal("attachment lost migration identity") | |
| 42 | 新增: } | |
| 43 | 新增: old, err := os.ReadFile(broker.before.Path) | |
| 44 | 新增: if err != nil { | |
| 45 | 新增: broker.t.Fatal(err) | |
| 46 | 新增: } | |
| 47 | 新增: copied, err := os.ReadFile(input.Disk) | |
| 48 | 新增: if err != nil || !bytes.Equal(old, copied) { | |
| 49 | 新增: broker.t.Fatal("runtime attached unverified disk bytes", err) | |
| 50 | 新增: } | |
| 51 | 新增: broker.disk = windowsStorageDisk{Path: input.Disk, Volume: 2, FileID: broker.before.FileID + 1} | |
| 52 | 新增: if broker.failAttach { | |
| 53 | 新增: return windowsHostStorageState{}, errors.New("response lost after attachment") | |
| 54 | 新增: } | |
| 55 | 新增: case "commit", "rollback": | |
| 56 | 新增: if broker.failRecovery { | |
| 57 | 新增: return windowsHostStorageState{}, errors.New("helper unavailable during recovery") | |
| 58 | 新增: } | |
| 59 | 新增: if input.Action == "rollback" { | |
| 60 | 新增: if _, err := os.Stat(broker.before.Path); err != nil { | |
| 61 | 新增: broker.t.Fatal("old stable directory was not restored before VM rollback", err) | |
| 62 | 新增: } | |
| 63 | 新增: if _, err := os.Stat(broker.disk.Path); err != nil { | |
| 64 | 新增: broker.t.Fatal("new disk deleted before VM rollback", err) | |
| 65 | 新增: } | |
| 66 | 新增: broker.disk = broker.before | |
| 67 | 新增: } | |
| 68 | 新增: broker.pending = "" | |
| 69 | 新增: } | |
| 70 | 新增: return windowsHostStorageState{Disk: broker.disk, Pending: broker.pending, Outcome: input.Action}, nil | |
| 71 | 新增:} | |
| 72 | 新增: | |
| 73 | 新增:func windowsStorageFixture(t *testing.T, external bool) (string, *windowsStorageRuntime, *windowsStorageBrokerFixture, WindowsProfile) { | |
| 74 | 新增: t.Helper() | |
| 75 | 新增: root, err := filepath.EvalSymlinks(t.TempDir()) | |
| 76 | 新增: if err != nil { | |
| 77 | 新增: t.Fatal(err) | |
| 78 | 新增: } | |
| 79 | 新增: profile := filepath.Join(root, "profile") | |
| 80 | 新增: instance := filepath.Join(profile, "state", "windows-existing") | |
| 81 | 新增: if external { | |
| 82 | 新增: instance = filepath.Join(root, "existing VM outside profile") | |
| 83 | 新增: } | |
| 84 | 新增: if err := os.MkdirAll(instance, 0700); err != nil { | |
| 85 | 新增: t.Fatal(err) | |
| 86 | 新增: } | |
| 87 | 新增: if err := os.MkdirAll(profile, 0700); err != nil { | |
| 88 | 新增: t.Fatal(err) | |
| 89 | 新增: } | |
| 90 | 新增: binding := windowsBindingFixture(profile) | |
| 91 | 新增: binding.InstanceDirectory = instance | |
| 92 | 新增: binding.RelayExecutable = filepath.Join(instance, "relay.exe") | |
| 93 | 新增: binding.PairingFile = filepath.Join(instance, "pairing.dpapi") | |
| 94 | 新增: binding.NetworkPairingFile = filepath.Join(instance, "network.dpapi") | |
| 95 | 新增: for _, path := range []string{binding.RelayExecutable, binding.PairingFile, binding.NetworkPairingFile} { | |
| 96 | 新增: if err := os.WriteFile(path, []byte("synthetic pairing bytes"), 0600); err != nil { | |
| 97 | 新增: t.Fatal(err) | |
| 98 | 新增: } | |
| 99 | 新增: } | |
| 100 | 新增: disk := filepath.Join(instance, "system.vhdx") | |
| 101 | 新增: createWindowsStorageFixtureDisk(t, disk) | |
| 102 | 新增: if err := BindWindowsProfile(profile, binding); err != nil { | |
| 103 | 新增: t.Fatal(err) | |
| 104 | 新增: } | |
| 105 | 新增: broker := &windowsStorageBrokerFixture{t: t, vm: binding.VMID, disk: windowsStorageDisk{Path: disk, Volume: 1, FileID: 11}} | |
| 106 | 新增: return profile, &windowsStorageRuntime{profile: profile, call: broker.call}, broker, binding | |
| 107 | 新增:} | |
| 108 | 新增: | |
| 109 | 新增:func TestWindowsStorageMigrationPreservesPairingAndPriorDisks(t *testing.T) { | |
| 110 | 新增: for _, external := range []bool{false, true} { | |
| 111 | 新增: name := "managed_instance" | |
| 112 | 新增: if external { | |
| 113 | 新增: name = "existing_external_instance" | |
| 114 | 新增: } | |
| 115 | 新增: t.Run(name, func(t *testing.T) { | |
| 116 | 新增: profile, runtime, broker, original := windowsStorageFixture(t, external) | |
| 117 | 新增: originalDisk, err := os.ReadFile(broker.disk.Path) | |
| 118 | 新增: if err != nil { | |
| 119 | 新增: t.Fatal(err) | |
| 120 | 新增: } | |
| 121 | 新增: for attempt := 0; attempt < 2; attempt++ { | |
| 122 | 新增: location, err := cage.GetStorageLocation(profile) | |
| 123 | 新增: if err != nil || !location.HasEnvironment { | |
| 124 | 新增: t.Fatal("Windows environment not detected", location, err) | |
| 125 | 新增: } | |
| 126 | 新增: target := filepath.Join(t.TempDir(), "环境存储") | |
| 127 | 新增: moved, err := cage.MoveStorageWithRuntime(context.Background(), profile, target, location, runtime, nil) | |
| 128 | 新增: if err != nil { | |
| 129 | 新增: t.Fatal(err) | |
| 130 | 新增: } | |
| 131 | 新增: actual, err := LoadWindowsProfile(profile) | |
| 132 | 新增: if err != nil || actual == nil || actual.VMID != original.VMID || actual.GUIUserSID != original.GUIUserSID { | |
| 133 | 新增: t.Fatal("migration changed VM or GUI identity", err) | |
| 134 | 新增: } | |
| 135 | 新增: for _, path := range []string{actual.RelayExecutable, actual.PairingFile, actual.NetworkPairingFile} { | |
| 136 | 新增: data, err := os.ReadFile(path) | |
| 137 | 新增: if err != nil || string(data) != "synthetic pairing bytes" { | |
| 138 | 新增: t.Fatal("pairing changed or lost its stable path", path, err) | |
| 139 | 新增: } | |
| 140 | 新增: } | |
| 141 | 新增: if broker.pending != "" || !moved.Custom || moved.Backup == "" { | |
| 142 | 新增: t.Fatal("migration did not finish or retain backup", moved, broker.pending) | |
| 143 | 新增: } | |
| 144 | 新增: if data, err := os.ReadFile(broker.disk.Path); err != nil || !bytes.Equal(data, originalDisk) { | |
| 145 | 新增: t.Fatal("new disk unavailable", err) | |
| 146 | 新增: } | |
| 147 | 新增: if external && attempt == 0 { | |
| 148 | 新增: private, err := cage.StoragePrivatePaths(profile) | |
| 149 | 新增: if err != nil { | |
| 150 | 新增: t.Fatal(err) | |
| 151 | 新增: } | |
| 152 | 新增: found := false | |
| 153 | 新增: for _, path := range private { | |
| 154 | 新增: found = found || path == original.InstanceDirectory | |
| 155 | 新增: } | |
| 156 | 新增: if !found { | |
| 157 | 新增: t.Fatal("external retained disk lost private-data protection", private) | |
| 158 | 新增: } | |
| 159 | 新增: } | |
| 160 | 新增: } | |
| 161 | 新增: if !reflect.DeepEqual(broker.events, []string{"status", "begin", "attach", "commit", "status", "begin", "attach", "commit"}) { | |
| 162 | 新增: t.Fatal(broker.events) | |
| 163 | 新增: } | |
| 164 | 新增: }) | |
| 165 | 新增: } | |
| 166 | 新增:} | |
| 167 | 新增: | |
| 168 | 新增:func TestWindowsStorageAttachmentFailureRollsBackAndRetries(t *testing.T) { | |
| 169 | 新增: profile, runtime, broker, original := windowsStorageFixture(t, false) | |
| 170 | 新增: location, err := cage.GetStorageLocation(profile) | |
| 171 | 新增: if err != nil { | |
| 172 | 新增: t.Fatal(err) | |
| 173 | 新增: } | |
| 174 | 新增: target := filepath.Join(t.TempDir(), "destination") | |
| 175 | 新增: broker.failAttach, broker.failRecovery = true, true | |
| 176 | 新增: if _, err := cage.MoveStorageWithRuntime(context.Background(), profile, target, location, runtime, nil); err == nil { | |
| 177 | 新增: t.Fatal("lost native response treated as success") | |
| 178 | 新增: } | |
| 179 | 新增: if _, err := os.Stat(broker.disk.Path); err != nil { | |
| 180 | 新增: t.Fatal("unresolved native disk was removed", err) | |
| 181 | 新增: } | |
| 182 | 新增: if _, err := cage.GetStorageLocation(profile); !errors.Is(err, cage.ErrStorageRuntimeRecovery) { | |
| 183 | 新增: t.Fatal("shared loader bypassed native recovery", err) | |
| 184 | 新增: } | |
| 185 | 新增: broker.failRecovery = false | |
| 186 | 新增: if err := cage.RecoverStorage(context.Background(), profile, runtime); err != nil { | |
| 187 | 新增: t.Fatal(err) | |
| 188 | 新增: } | |
| 189 | 新增: actual, err := LoadWindowsProfile(profile) | |
| 190 | 新增: if err != nil || actual == nil || *actual != original { | |
| 191 | 新增: t.Fatal("rollback changed original pairing", err) | |
| 192 | 新增: } | |
| 193 | 新增: if _, err := os.Stat(filepath.Join(target, "state")); !errors.Is(err, os.ErrNotExist) { | |
| 194 | 新增: t.Fatal("resolved failed copy not removed", err) | |
| 195 | 新增: } | |
| 196 | 新增: broker.failAttach = false | |
| 197 | 新增: if _, err := cage.MoveStorageWithRuntime(context.Background(), profile, target, location, runtime, nil); err != nil { | |
| 198 | 新增: t.Fatal("retry failed", err) | |
| 199 | 新增: } | |
| 200 | 新增:} | |
| 201 | 新增: | |
| 202 | 新增:func TestWindowsStorageCannotUseFilesystemOnlyMove(t *testing.T) { | |
| 203 | 新增: profile, _, _, _ := windowsStorageFixture(t, false) | |
| 204 | 新增: location, err := cage.GetStorageLocation(profile) | |
| 205 | 新增: if err != nil { | |
| 206 | 新增: t.Fatal(err) | |
| 207 | 新增: } | |
| 208 | 新增: target := filepath.Join(t.TempDir(), "destination") | |
| 209 | 新增: if _, err := cage.MoveStorage(context.Background(), profile, target, location, nil); err == nil { | |
| 210 | 新增: t.Fatal("filesystem migration left registered VM bound to its old inode") | |
| 211 | 新增: } | |
| 212 | 新增: if _, err := os.Stat(target); !errors.Is(err, os.ErrNotExist) { | |
| 213 | 新增: t.Fatal("rejected move touched destination", err) | |
| 214 | 新增: } | |
| 215 | 新增:} | |
| 216 | 新增: | |
| 217 | 新增:func TestWindowsStorageExternalMetadataIsOwnedByHyperV(t *testing.T) { | |
| 218 | 新增: profile, runtime, broker, original := windowsStorageFixture(t, true) | |
| 219 | 新增: metadata := filepath.Join(original.InstanceDirectory, "Virtual Machines") | |
| 220 | 新增: if err := os.Mkdir(metadata, 0700); err != nil { | |
| 221 | 新增: t.Fatal(err) | |
| 222 | 新增: } | |
| 223 | 新增: if err := os.WriteFile(filepath.Join(metadata, original.VMID.String()+".vmcx"), []byte("Hyper-V managed configuration"), 0600); err != nil { | |
| 224 | 新增: t.Fatal(err) | |
| 225 | 新增: } | |
| 226 | 新增: if err := os.Chmod(metadata, 0000); err != nil { | |
| 227 | 新增: t.Fatal(err) | |
| 228 | 新增: } | |
| 229 | 新增: t.Cleanup(func() { _ = os.Chmod(metadata, 0700) }) | |
| 230 | 新增: broker.layout = &windowsVMStorageLayout{Configuration: original.InstanceDirectory, Snapshots: original.InstanceDirectory, Paging: original.InstanceDirectory} | |
| 231 | 新增: location, err := cage.GetStorageLocation(profile) | |
| 232 | 新增: if err != nil { | |
| 233 | 新增: t.Fatal(err) | |
| 234 | 新增: } | |
| 235 | 新增: if _, err := cage.MoveStorageWithRuntime(context.Background(), profile, filepath.Join(t.TempDir(), "target"), location, runtime, nil); err != nil { | |
| 236 | 新增: t.Fatal("ordinary cold copy traversed native metadata", err) | |
| 237 | 新增: } | |
| 238 | 新增: next, err := LoadWindowsProfile(profile) | |
| 239 | 新增: if err != nil { | |
| 240 | 新增: t.Fatal(err) | |
| 241 | 新增: } | |
| 242 | 新增: if _, err := os.Stat(filepath.Join(next.InstanceDirectory, "Virtual Machines")); !errors.Is(err, os.ErrNotExist) { | |
| 243 | 新增: t.Fatal("unregistered metadata duplicate copied into user storage", err) | |
| 244 | 新增: } | |
| 245 | 新增:} | |
| @@ -18,6 +18,10 @@ func windowsHostStorage(ctx context.Context, id uuid.UUID, input windowsHostStor | ||
| 18 | 18 | return state, err |
| 19 | 19 | } |
| 20 | 20 | |
| 21 | 新增:func WindowsPrivateStoragePaths() []string { | |
| 22 | 新增: return []string{filepath.Join(managerKnownFolder(windows.FOLDERID_ProgramData), "Cage", "HyperVManager")} | |
| 23 | 新增:} | |
| 24 | 新增: | |
| 21 | 25 | func replaceWindowsStorageProfile(path string, data []byte) error { |
| 22 | 26 | file, err := os.CreateTemp(filepath.Dir(path), ".windows-storage-*") |
| 23 | 27 | if err != nil { |
| @@ -0,0 +1,173 @@ | ||
| 1 | 新增://go:build windows | |
| 2 | 新增: | |
| 3 | 新增:package guestos | |
| 4 | 新增: | |
| 5 | 新增:import ( | |
| 6 | 新增: "context" | |
| 7 | 新增: "errors" | |
| 8 | 新增: "net" | |
| 9 | 新增: "os" | |
| 10 | 新增: "path/filepath" | |
| 11 | 新增: "testing" | |
| 12 | 新增: "time" | |
| 13 | 新增: | |
| 14 | 新增: "github.com/Microsoft/go-winio" | |
| 15 | 新增: "github.com/google/uuid" | |
| 16 | 新增: "github.com/sylvinus/agent-vm/internal/cage" | |
| 17 | 新增: "golang.org/x/sys/windows" | |
| 18 | 新增:) | |
| 19 | 新增: | |
| 20 | 新增:func storagePipeFixture(t *testing.T, impersonation winio.PipeImpLevel, run func(net.Conn, string)) { | |
| 21 | 新增: t.Helper() | |
| 22 | 新增: user, err := windows.GetCurrentProcessToken().GetTokenUser() | |
| 23 | 新增: if err != nil { | |
| 24 | 新增: t.Fatal(err) | |
| 25 | 新增: } | |
| 26 | 新增: sid := user.User.Sid.String() | |
| 27 | 新增: name := `\\.\pipe\Cage.StorageTest.` + uuid.NewString() | |
| 28 | 新增: listener, err := winio.ListenPipe(name, &winio.PipeConfig{SecurityDescriptor: "D:P(A;;GA;;;" + sid + ")"}) | |
| 29 | 新增: if err != nil { | |
| 30 | 新增: t.Fatal(err) | |
| 31 | 新增: } | |
| 32 | 新增: defer listener.Close() | |
| 33 | 新增: done := make(chan struct{}) | |
| 34 | 新增: go func() { | |
| 35 | 新增: defer close(done) | |
| 36 | 新增: connection, err := listener.Accept() | |
| 37 | 新增: if err != nil { | |
| 38 | 新增: t.Error(err) | |
| 39 | 新增: return | |
| 40 | 新增: } | |
| 41 | 新增: defer connection.Close() | |
| 42 | 新增: var request [1]byte | |
| 43 | 新增: if _, err := connection.Read(request[:]); err != nil { | |
| 44 | 新增: t.Error(err) | |
| 45 | 新增: return | |
| 46 | 新增: } | |
| 47 | 新增: run(connection, sid) | |
| 48 | 新增: }() | |
| 49 | 新增: ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) | |
| 50 | 新增: defer cancel() | |
| 51 | 新增: client, err := winio.DialPipeAccessImpLevel(ctx, name, 0x120003, impersonation) | |
| 52 | 新增: if err != nil { | |
| 53 | 新增: t.Fatal(err) | |
| 54 | 新增: } | |
| 55 | 新增: defer client.Close() | |
| 56 | 新增: if _, err := client.Write([]byte("x")); err != nil { | |
| 57 | 新增: t.Fatal(err) | |
| 58 | 新增: } | |
| 59 | 新增: select { | |
| 60 | 新增: case <-done: | |
| 61 | 新增: case <-ctx.Done(): | |
| 62 | 新增: t.Fatal("private storage pipe test timed out") | |
| 63 | 新增: } | |
| 64 | 新增:} | |
| 65 | 新增: | |
| 66 | 新增:func TestWindowsStorageDestinationUsesCallerAccess(t *testing.T) { | |
| 67 | 新增: root := t.TempDir() | |
| 68 | 新增: path := filepath.Join(root, "system.vhdx") | |
| 69 | 新增: if err := os.WriteFile(path, []byte("synthetic VHDX identity"), 0600); err != nil { | |
| 70 | 新增: t.Fatal(err) | |
| 71 | 新增: } | |
| 72 | 新增: if err := protectWindowsProfile(path); err != nil { | |
| 73 | 新增: t.Fatal(err) | |
| 74 | 新增: } | |
| 75 | 新增: storagePipeFixture(t, winio.PipeImpLevelImpersonation, func(connection net.Conn, sid string) { | |
| 76 | 新增: handle, identity, err := managerOpenStorageDestination(connection, path, sid, false) | |
| 77 | 新增: if err != nil { | |
| 78 | 新增: t.Error(err) | |
| 79 | 新增: return | |
| 80 | 新增: } | |
| 81 | 新增: defer windows.CloseHandle(handle) | |
| 82 | 新增: volume, id, err := managerDiskIdentity(path) | |
| 83 | 新增: if err != nil || identity.Volume != volume || identity.FileID != id { | |
| 84 | 新增: t.Error("destination object identity changed", err) | |
| 85 | 新增: } | |
| 86 | 新增: if err := os.Rename(path, path+".replaced"); err == nil { | |
| 87 | 新增: t.Error("verified disk was replaceable during privileged operation") | |
| 88 | 新增: } | |
| 89 | 新增: if _, _, err := managerOpenStorageDestination(connection, path, "S-1-5-21-1-2-3-999", false); err == nil { | |
| 90 | 新增: t.Error("different user gained destination authority") | |
| 91 | 新增: } | |
| 92 | 新增: }) | |
| 93 | 新增: storagePipeFixture(t, winio.PipeImpLevelIdentification, func(connection net.Conn, sid string) { | |
| 94 | 新增: if handle, _, err := managerOpenStorageDestination(connection, path, sid, false); err == nil { | |
| 95 | 新增: windows.CloseHandle(handle) | |
| 96 | 新增: t.Error("identity-only pipe was used for a privileged destination open") | |
| 97 | 新增: } | |
| 98 | 新增: }) | |
| 99 | 新增: user, err := windows.GetCurrentProcessToken().GetTokenUser() | |
| 100 | 新增: if err != nil { | |
| 101 | 新增: t.Fatal(err) | |
| 102 | 新增: } | |
| 103 | 新增: sd, err := windows.SecurityDescriptorFromString("D:P(D;;FW;;;" + user.User.Sid.String() + ")(A;;FR;;;" + user.User.Sid.String() + ")(A;;FA;;;SY)(A;;FA;;;BA)") | |
| 104 | 新增: if err != nil { | |
| 105 | 新增: t.Fatal(err) | |
| 106 | 新增: } | |
| 107 | 新增: acl, _, err := sd.DACL() | |
| 108 | 新增: if err != nil { | |
| 109 | 新增: t.Fatal(err) | |
| 110 | 新增: } | |
| 111 | 新增: if err := windows.SetNamedSecurityInfo(path, windows.SE_FILE_OBJECT, windows.DACL_SECURITY_INFORMATION|windows.PROTECTED_DACL_SECURITY_INFORMATION, nil, nil, acl, nil); err != nil { | |
| 112 | 新增: t.Fatal(err) | |
| 113 | 新增: } | |
| 114 | 新增: t.Cleanup(func() { _ = protectWindowsProfile(path) }) | |
| 115 | 新增: storagePipeFixture(t, winio.PipeImpLevelImpersonation, func(connection net.Conn, sid string) { | |
| 116 | 新增: if handle, _, err := managerOpenStorageDestination(connection, path, sid, false); err == nil { | |
| 117 | 新增: windows.CloseHandle(handle) | |
| 118 | 新增: t.Error("read-only caller selected a disk for privileged mutation") | |
| 119 | 新增: } | |
| 120 | 新增: }) | |
| 121 | 新增:} | |
| 122 | 新增: | |
| 123 | 新增:func TestWindowsStoragePinsDirectoryIdentity(t *testing.T) { | |
| 124 | 新增: root := t.TempDir() | |
| 125 | 新增: parent := filepath.Join(root, "parent") | |
| 126 | 新增: if err := os.Mkdir(parent, 0700); err != nil { | |
| 127 | 新增: t.Fatal(err) | |
| 128 | 新增: } | |
| 129 | 新增: path := filepath.Join(parent, "system.vhdx") | |
| 130 | 新增: if err := os.WriteFile(path, []byte("disk"), 0600); err != nil { | |
| 131 | 新增: t.Fatal(err) | |
| 132 | 新增: } | |
| 133 | 新增: closeParents, err := managerPinStorageParents(path) | |
| 134 | 新增: if err != nil { | |
| 135 | 新增: t.Fatal(err) | |
| 136 | 新增: } | |
| 137 | 新增: defer closeParents() | |
| 138 | 新增: if err := os.Rename(parent, parent+"-renamed"); err == nil { | |
| 139 | 新增: t.Fatal("ancestor could be replaced while VM storage paths were pinned") | |
| 140 | 新增: } | |
| 141 | 新增: closeParents() | |
| 142 | 新增: if err := os.Rename(parent, parent+"-renamed"); err != nil { | |
| 143 | 新增: t.Fatal("parent pin leaked after operation", err) | |
| 144 | 新增: } | |
| 145 | 新增:} | |
| 146 | 新增: | |
| 147 | 新增:func TestWindowsStorageCopiedPairingKeepsProtectedACL(t *testing.T) { | |
| 148 | 新增: profile, runtime, _, _ := windowsStorageFixture(t, false) | |
| 149 | 新增: before, err := cage.GetStorageLocation(profile) | |
| 150 | 新增: if err != nil { | |
| 151 | 新增: t.Fatal(err) | |
| 152 | 新增: } | |
| 153 | 新增: if _, err := cage.MoveStorageWithRuntime(context.Background(), profile, filepath.Join(t.TempDir(), "new"), before, runtime, nil); err != nil { | |
| 154 | 新增: t.Fatal(err) | |
| 155 | 新增: } | |
| 156 | 新增: binding, err := LoadWindowsProfile(profile) | |
| 157 | 新增: if err != nil { | |
| 158 | 新增: t.Fatal(err) | |
| 159 | 新增: } | |
| 160 | 新增: for _, path := range []string{binding.PairingFile, binding.NetworkPairingFile} { | |
| 161 | 新增: sd, err := windows.GetNamedSecurityInfo(path, windows.SE_FILE_OBJECT, windows.DACL_SECURITY_INFORMATION) | |
| 162 | 新增: if err != nil { | |
| 163 | 新增: t.Fatal(err) | |
| 164 | 新增: } | |
| 165 | 新增: control, _, err := sd.Control() | |
| 166 | 新增: if err != nil || control&windows.SE_DACL_PROTECTED == 0 { | |
| 167 | 新增: t.Fatal("copied pairing is rejected by production PrivateFile", path, err) | |
| 168 | 新增: } | |
| 169 | 新增: if _, err := os.Stat(path); errors.Is(err, os.ErrNotExist) { | |
| 170 | 新增: t.Fatal("pairing disappeared after migration") | |
| 171 | 新增: } | |
| 172 | 新增: } | |
| 173 | 新增:} | |
| @@ -4,6 +4,8 @@ void cageLoginLoop(void *machine); | ||
| 4 | 4 | void cageLoginStop(void); |
| 5 | 5 | void cageLoginEnable(bool enabled); |
| 6 | 6 | void *cageLoginImage(int *size); |
| 7 | 新增:void *cageLoginImageRegion(int x, int y, int width, int height, int *size); | |
| 7 | 8 | bool cageLoginClick(int x, int y); |
| 8 | 9 | bool cageLoginScroll(int x, int y, int deltaX, int deltaY); |
| 9 | 10 | bool cageLoginKey(int code, bool shift); |
| 11 | 新增:bool cageLoginSelectAll(void); | |
| @@ -46,6 +46,30 @@ void *cageLoginImage(int *size) { | ||
| 46 | 46 | }); |
| 47 | 47 | return copy; |
| 48 | 48 | } |
| 49 | 新增:void *cageLoginImageRegion(int x, int y, int width, int height, int *size) { | |
| 50 | 新增: if (x < 0 || y < 0 || width <= 0 || height <= 0 || x + width > 1024 || y + height > 640) return NULL; | |
| 51 | 新增: __block void *copy = NULL; | |
| 52 | 新增: dispatch_sync(dispatch_get_main_queue(), ^{ | |
| 53 | 新增: @autoreleasepool { | |
| 54 | 新增: NSData *frame = [loginView snapshotJPEG]; | |
| 55 | 新增: if (!frame.length) return; | |
| 56 | 新增: NSBitmapImageRep *source = [NSBitmapImageRep imageRepWithData:frame]; | |
| 57 | 新增: if (!source.CGImage) return; | |
| 58 | 新增: CGRect region = CGRectMake(x * source.pixelsWide / 1024.0, y * source.pixelsHigh / 640.0, | |
| 59 | 新增: width * source.pixelsWide / 1024.0, height * source.pixelsHigh / 640.0); | |
| 60 | 新增: CGImageRef cropped = CGImageCreateWithImageInRect(source.CGImage, region); | |
| 61 | 新增: if (!cropped) return; | |
| 62 | 新增: NSBitmapImageRep *output = [[NSBitmapImageRep alloc] initWithCGImage:cropped]; | |
| 63 | 新增: CGImageRelease(cropped); | |
| 64 | 新增: NSData *image = [output representationUsingType:NSBitmapImageFileTypeJPEG properties:@{NSImageCompressionFactor:@0.92}]; | |
| 65 | 新增: if (image.length && image.length <= (4<<20)) { | |
| 66 | 新增: copy = malloc(image.length); | |
| 67 | 新增: if (copy) { memcpy(copy, image.bytes, image.length); *size = (int)image.length; } | |
| 68 | 新增: } | |
| 69 | 新增: } | |
| 70 | 新增: }); | |
| 71 | 新增: return copy; | |
| 72 | 新增:} | |
| 49 | 73 | bool cageLoginClick(int x, int y) { |
| 50 | 74 | __block BOOL ok = NO; |
| 51 | 75 | dispatch_sync(dispatch_get_main_queue(), ^{ ok = [loginView clickAtX:x * scanWidth / 1024.0 y:y * scanHeight / 640.0]; }); |
| @@ -74,6 +98,23 @@ bool cageLoginKey(int code, bool shift) { | ||
| 74 | 98 | }); |
| 75 | 99 | return ok; |
| 76 | 100 | } |
| 101 | 新增:bool cageLoginSelectAll(void) { | |
| 102 | 新增: __block BOOL ok = NO; | |
| 103 | 新增: dispatch_sync(dispatch_get_main_queue(), ^{ | |
| 104 | 新增: if (!loginView) return; | |
| 105 | 新增: NSEventModifierFlags command = NSEventModifierFlagCommand | NX_DEVICELCMDKEYMASK; | |
| 106 | 新增: NSEvent *(^event)(NSEventType, int, NSEventModifierFlags) = ^NSEvent *(NSEventType kind, int key, NSEventModifierFlags flags) { | |
| 107 | 新增: return [NSEvent keyEventWithType:kind location:NSZeroPoint modifierFlags:flags timestamp:NSProcessInfo.processInfo.systemUptime | |
| 108 | 新增: windowNumber:0 context:nil characters:@"" charactersIgnoringModifiers:@"" isARepeat:NO keyCode:(unsigned short)key]; | |
| 109 | 新增: }; | |
| 110 | 新增: [loginView sendKey:event(NSEventTypeFlagsChanged,55,command)]; | |
| 111 | 新增: [loginView sendKey:event(NSEventTypeKeyDown,55,command)]; | |
| 112 | 新增: ok = [loginView sendKey:event(NSEventTypeKeyDown,0,command)] && [loginView sendKey:event(NSEventTypeKeyUp,0,command)]; | |
| 113 | 新增: [loginView sendKey:event(NSEventTypeKeyUp,55,0)]; | |
| 114 | 新增: [loginView sendKey:event(NSEventTypeFlagsChanged,55,0)]; | |
| 115 | 新增: }); | |
| 116 | 新增: return ok; | |
| 117 | 新增:} | |
| 77 | 118 | bool cageLoginScroll(int x, int y, int deltaX, int deltaY) { |
| 78 | 119 | __block BOOL ok = NO; |
| 79 | 120 | dispatch_sync(dispatch_get_main_queue(), ^{ |
| @@ -0,0 +1,48 @@ | ||
| 1 | 新增://go:build darwin && arm64 && cgo && !no_vz | |
| 2 | 新增: | |
| 3 | 新增:package maclogin | |
| 4 | 新增: | |
| 5 | 新增:import ( | |
| 6 | 新增: "context" | |
| 7 | 新增: "os/exec" | |
| 8 | 新增: | |
| 9 | 新增: "al.essio.dev/pkg/shellescape" | |
| 10 | 新增: "github.com/sylvinus/agent-vm/internal/guestos" | |
| 11 | 新增:) | |
| 12 | 新增: | |
| 13 | 新增:// Read authorization state from the installed, root-owned executable. The | |
| 14 | 新增:// ordinary GUI user's writable socket and shell startup files are not trusted | |
| 15 | 新增:// to identify a destination for an administrator password. | |
| 16 | 新增:func guestGUIProbeCommand(ctx context.Context, profile, administrator, user string, arguments ...string) (*exec.Cmd, error) { | |
| 17 | 新增: args, err := guestos.MacOSSSHArgs(profile, administrator) | |
| 18 | 新增: if err != nil { | |
| 19 | 新增: return nil, err | |
| 20 | 新增: } | |
| 21 | 新增: rootScript := `set -eu | |
| 22 | 新增:app='/Applications/Cage Guest Window.app' | |
| 23 | 新增:for file in "$app" "$app/Contents" "$app/Contents/MacOS" "$app/Contents/MacOS/CageGuestWindow"; do | |
| 24 | 新增: test ! -L "$file" && test "$(/usr/bin/stat -f %u "$file")" = 0 || exit 72 | |
| 25 | 新增: mode=$(/usr/bin/stat -f %Lp "$file") | |
| 26 | 新增: test "$((0$mode & 022))" = 0 || exit 72 | |
| 27 | 新增:done | |
| 28 | 新增:/usr/bin/codesign --verify --strict -R '=identifier "dev.cage.GuestClaudeWindow"' "$app" || exit 72 | |
| 29 | 新增:uid=$(/usr/bin/id -u ` + shellescape.Quote(user) + `) | |
| 30 | 新增:test "$(/usr/bin/stat -f %u /dev/console)" = "$uid" || exit 73 | |
| 31 | 新增:exec /bin/launchctl asuser "$uid" /usr/bin/sudo -Hu ` + shellescape.Quote(user) + ` /usr/bin/env -i HOME=` + shellescape.Quote("/Users/"+user) + ` PATH=/usr/bin:/bin ` + | |
| 32 | 新增: shellescape.QuoteCommand(append([]string{"/Applications/Cage Guest Window.app/Contents/MacOS/CageGuestWindow"}, arguments...)) | |
| 33 | 新增: // An askpass helper keeps SSH stdin available to the probe. Its private | |
| 34 | 新增: // script contains only the existing credential's path, and is removed when | |
| 35 | 新增: // this invocation ends. Credentials remain inside the guest. | |
| 36 | 新增: loginScript := `set -eu | |
| 37 | 新增:umask 077 | |
| 38 | 新增:probe_dir=$(/usr/bin/mktemp -d ` + shellescape.Quote("/Users/"+administrator+"/.cage-probe.XXXXXXXX") + `) | |
| 39 | 新增:trap '/bin/rm -f "$probe_dir/askpass"; /bin/rmdir "$probe_dir"' EXIT | |
| 40 | 新增:trap 'exit 1' HUP INT TERM | |
| 41 | 新增:/usr/bin/printf '%s\n' '#!/bin/sh' ` + shellescape.Quote("exec /bin/cat "+shellescape.Quote("/Users/"+administrator+"/password")) + ` > "$probe_dir/askpass" | |
| 42 | 新增:/bin/chmod 700 "$probe_dir/askpass" | |
| 43 | 新增:SUDO_ASKPASS="$probe_dir/askpass" /usr/bin/sudo -A -p '' /bin/sh -c ` + shellescape.Quote(rootScript) | |
| 44 | 新增: command := "exec /bin/sh -c " + shellescape.Quote(loginScript) | |
| 45 | 新增: cmd := exec.CommandContext(ctx, "/usr/bin/ssh", append(args, "-T", "cage-macos", "--", command)...) | |
| 46 | 新增: cmd.Env = []string{"PATH=/usr/bin:/bin", "LC_ALL=C"} | |
| 47 | 新增: return cmd, nil | |
| 48 | 新增:} | |
| @@ -58,14 +58,26 @@ type request = guestos.MacLoginRequest | ||
| 58 | 58 | type reply = guestos.MacLoginReply |
| 59 | 59 | |
| 60 | 60 | type loginSession struct { |
| 61 | 删除: profile string | |
| 62 | 删除: token string | |
| 63 | 删除: expires time.Time | |
| 64 | 删除: screenID string | |
| 65 | 删除: setup bool | |
| 61 | 新增: profile string | |
| 62 | 新增: token string | |
| 63 | 新增: expires time.Time | |
| 64 | 新增: screenID string | |
| 65 | 新增: setup bool | |
| 66 | 新增: maintenance string | |
| 67 | 新增: maintenanceFrame string | |
| 68 | 新增: maintenanceMachineID string | |
| 69 | 新增: maintenanceAdministrator string | |
| 70 | 新增: passwordSelection passwordSelection | |
| 66 | 71 | } |
| 67 | 72 | |
| 68 | 73 | func (s *loginSession) currentScreen() string { |
| 74 | 新增: if s.maintenance != "" { | |
| 75 | 新增: surface, err := s.maintenanceProbe(false) | |
| 76 | 新增: if err != nil { | |
| 77 | 新增: return "" | |
| 78 | 新增: } | |
| 79 | 新增: return "maintenance-" + surface.Session | |
| 80 | 新增: } | |
| 69 | 81 | // Check via the separate provisioning account. Guest development files |
| 70 | 82 | // and the standard user's shell initialization cannot grant this view. |
| 71 | 83 | bound, err := guestos.LoadMacOSProfile(s.profile) |
| @@ -78,7 +90,11 @@ func (s *loginSession) currentScreen() string { | ||
| 78 | 90 | } |
| 79 | 91 | return "setup-" + bound.SetupID |
| 80 | 92 | } |
| 81 | 删除: args, err := guestos.MacOSSSHArgs(s.profile, "cage") | |
| 93 | 新增: user, err := guestos.MacOSProvisionUser(s.profile) | |
| 94 | 新增: if err != nil { | |
| 95 | 新增: return "" | |
| 96 | 新增: } | |
| 97 | 新增: args, err := guestos.MacOSSSHArgs(s.profile, user) | |
| 82 | 98 | if err != nil { |
| 83 | 99 | return "" |
| 84 | 100 | } |
| @@ -114,9 +130,17 @@ func (s *loginSession) close() { | ||
| 114 | 130 | s.token = "" |
| 115 | 131 | s.screenID = "" |
| 116 | 132 | s.setup = false |
| 133 | 新增: s.maintenance = "" | |
| 134 | 新增: s.maintenanceFrame = "" | |
| 135 | 新增: s.maintenanceMachineID = "" | |
| 136 | 新增: s.maintenanceAdministrator = "" | |
| 137 | 新增: s.passwordSelection = passwordSelection{} | |
| 117 | 138 | } |
| 118 | 139 | |
| 119 | 140 | func (s *loginSession) handle(in request) reply { |
| 141 | 新增: if in.Maintenance != "" || (s.maintenance != "" && in.Action != "open") { | |
| 142 | 新增: return s.handleMaintenance(in) | |
| 143 | 新增: } | |
| 120 | 144 | if in.Action == "finish" && in.Setup { |
| 121 | 145 | bound, err := guestos.LoadMacOSProfile(s.profile) |
| 122 | 146 | if err != nil || bound == nil || bound.SetupID == "" { |
| @@ -152,14 +176,8 @@ func (s *loginSession) handle(in request) reply { | ||
| 152 | 176 | } |
| 153 | 177 | switch in.Action { |
| 154 | 178 | case "fill-password": |
| 155 | 删除: sequence, valid := passwordKeys(in.Password) | |
| 156 | 删除: if !s.setup || !valid || !s.authorizationDialog() { | |
| 157 | 删除: return reply{Error: "请先打开系统授权对话框,并选中密码输入框"} | |
| 158 | 删除: } | |
| 159 | 删除: for _, key := range sequence { | |
| 160 | 删除: if !bool(C.cageLoginKey(C.int(key.code), C.bool(key.shift))) { | |
| 161 | 删除: return reply{Error: "授权密码未能填写,请重试"} | |
| 162 | 删除: } | |
| 179 | 新增: if err := s.fillSetupPassword(in.Password); err != nil { | |
| 180 | 新增: return reply{Error: err.Error()} | |
| 163 | 181 | } |
| 164 | 182 | case "frame": |
| 165 | 183 | var n C.int |
| @@ -174,20 +192,22 @@ func (s *loginSession) handle(in request) reply { | ||
| 174 | 192 | } |
| 175 | 193 | return reply{Image: C.GoBytes(p, n), MIME: "image/jpeg"} |
| 176 | 194 | case "click": |
| 195 | 新增: s.passwordSelection = passwordSelection{} | |
| 177 | 196 | if in.X < 0 || in.Y < 0 || in.X >= 1024 || in.Y >= 640 || !bool(C.cageLoginClick(C.int(in.X), C.int(in.Y))) { |
| 178 | 197 | return reply{Error: "无效的登录位置"} |
| 179 | 198 | } |
| 199 | 新增: if s.setup { | |
| 200 | 新增: s.selectPasswordPosition(in.X, in.Y) | |
| 201 | 新增: } | |
| 180 | 202 | case "key": |
| 203 | 新增: s.passwordSelection = passwordSelection{} | |
| 181 | 204 | // ANSI printable keys, Return, Tab, Escape and Backspace. No global shortcuts. |
| 182 | 205 | setupNavigation := s.setup && (in.Code >= 123 && in.Code <= 126 || in.Code == 116 || in.Code == 121) |
| 183 | 206 | if in.Code < 0 || (in.Code > 53 && !setupNavigation) || !bool(C.cageLoginKey(C.int(in.Code), C.bool(in.Shift))) { |
| 184 | 207 | return reply{Error: "不支持此登录按键"} |
| 185 | 208 | } |
| 186 | 删除: if in.Code == 36 && !s.setup { | |
| 187 | 删除: s.close() | |
| 188 | 删除: return reply{Closed: true} | |
| 189 | 删除: } | |
| 190 | 209 | case "scroll": |
| 210 | 新增: s.passwordSelection = passwordSelection{} | |
| 191 | 211 | if !s.setup || in.X < 0 || in.Y < 0 || in.X >= 1024 || in.Y >= 640 || |
| 192 | 212 | in.DeltaX < -512 || in.DeltaX > 512 || in.DeltaY < -512 || in.DeltaY > 512 || |
| 193 | 213 | !bool(C.cageLoginScroll(C.int(in.X), C.int(in.Y), C.int(in.DeltaX), C.int(in.DeltaY))) { |
| @@ -199,26 +219,6 @@ func (s *loginSession) handle(in request) reply { | ||
| 199 | 219 | return reply{} |
| 200 | 220 | } |
| 201 | 221 | |
| 202 | 删除:func (s *loginSession) authorizationDialog() bool { | |
| 203 | 删除: ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) | |
| 204 | 删除: defer cancel() | |
| 205 | 删除: bound, err := guestos.LoadMacOSProfile(s.profile) | |
| 206 | 删除: if err != nil || bound == nil { | |
| 207 | 删除: return false | |
| 208 | 删除: } | |
| 209 | 删除: args, err := guestos.MacOSSSHArgs(s.profile, bound.User) | |
| 210 | 删除: if err != nil { | |
| 211 | 删除: return false | |
| 212 | 删除: } | |
| 213 | 删除: cmd := exec.CommandContext(ctx, "/usr/bin/ssh", append(args, "-T", "cage-macos", "--", `printf '%s\n' '{"action":"setup-password-focus"}' | /usr/bin/nc -U "$HOME/Library/Caches/dev.cage.GuestClaudeWindow/window.sock"`)...) | |
| 214 | 删除: cmd.Env = []string{"PATH=/usr/bin:/bin", "LC_ALL=C"} | |
| 215 | 删除: data, err := cmd.Output() | |
| 216 | 删除: var result struct { | |
| 217 | 删除: Focused bool `json:"focused"` | |
| 218 | 删除: } | |
| 219 | 删除: return err == nil && json.Unmarshal(data, &result) == nil && result.Focused | |
| 220 | 删除:} | |
| 221 | 删除: | |
| 222 | 222 | func run(ctx context.Context, machine *apple.VirtualMachine, dir string) error { |
| 223 | 223 | if !driver.OwnsOffscreenView(dir) { |
| 224 | 224 | return errors.New("invalid local macOS login view") |
| @@ -264,7 +264,13 @@ func run(ctx context.Context, machine *apple.VirtualMachine, dir string) error { | ||
| 264 | 264 | _ = conn.SetDeadline(time.Now().Add(10 * time.Second)) |
| 265 | 265 | var input request |
| 266 | 266 | if json.NewDecoder(io.LimitReader(conn, 4096)).Decode(&input) == nil { |
| 267 | 删除: _ = json.NewEncoder(conn).Encode(s.handle(input)) | |
| 267 | 新增: if input.Maintenance != "" { | |
| 268 | 新增: _ = conn.SetDeadline(time.Now().Add(15 * time.Second)) | |
| 269 | 新增: } | |
| 270 | 新增: result := s.handle(input) | |
| 271 | 新增: if err := json.NewEncoder(conn).Encode(result); err != nil && result.Session != "" { | |
| 272 | 新增: s.close() | |
| 273 | 新增: } | |
| 268 | 274 | } |
| 269 | 275 | _ = conn.Close() |
| 270 | 276 | } |
| @@ -0,0 +1,81 @@ | ||
| 1 | 新增:package maclogin | |
| 2 | 新增: | |
| 3 | 新增:import ( | |
| 4 | 新增: "crypto/sha256" | |
| 5 | 新增: "encoding/hex" | |
| 6 | 新增: "encoding/json" | |
| 7 | 新增: "math" | |
| 8 | 新增: "time" | |
| 9 | 新增: | |
| 10 | 新增: "github.com/google/uuid" | |
| 11 | 新增:) | |
| 12 | 新增: | |
| 13 | 新增:type maintenanceWindow struct { | |
| 14 | 新增: Version int `json:"version"` | |
| 15 | 新增: Session string `json:"session"` | |
| 16 | 新增: User string `json:"user"` | |
| 17 | 新增: PID int32 `json:"pid"` | |
| 18 | 新增: Window uint32 `json:"window"` | |
| 19 | 新增: Bundle string `json:"bundle"` | |
| 20 | 新增: Rect [4]float64 `json:"rect"` | |
| 21 | 新增: Display [4]float64 `json:"display"` | |
| 22 | 新增: Error string `json:"error"` | |
| 23 | 新增: PasswordFocused bool `json:"password_focused"` | |
| 24 | 新增:} | |
| 25 | 新增: | |
| 26 | 新增:func (w maintenanceWindow) valid(user string) bool { | |
| 27 | 新增: if w.Version != 1 || w.Error != "" || w.User != user || w.PID <= 0 || w.Window == 0 || | |
| 28 | 新增: (w.Bundle != "com.apple.systempreferences" && w.Bundle != "com.apple.authorizationhost") { | |
| 29 | 新增: return false | |
| 30 | 新增: } | |
| 31 | 新增: id, err := uuid.Parse(w.Session) | |
| 32 | 新增: if err != nil || id == uuid.Nil { | |
| 33 | 新增: return false | |
| 34 | 新增: } | |
| 35 | 新增: for _, value := range append(w.Rect[:], w.Display[:]...) { | |
| 36 | 新增: if math.IsNaN(value) || math.IsInf(value, 0) || math.Abs(value) > 32768 { | |
| 37 | 新增: return false | |
| 38 | 新增: } | |
| 39 | 新增: } | |
| 40 | 新增: return w.Display[2] > 0 && w.Display[3] > 0 && math.Abs(w.Display[2]/w.Display[3]-1.6) < 0.001 && w.Rect[2] >= 80 && w.Rect[3] >= 40 && | |
| 41 | 新增: w.Rect[0] >= w.Display[0] && w.Rect[1] >= w.Display[1] && | |
| 42 | 新增: w.Rect[0]+w.Rect[2] <= w.Display[0]+w.Display[2] && w.Rect[1]+w.Rect[3] <= w.Display[1]+w.Display[3] | |
| 43 | 新增:} | |
| 44 | 新增: | |
| 45 | 新增:func (w maintenanceWindow) geometry() string { | |
| 46 | 新增: w.PasswordFocused = false | |
| 47 | 新增: data, _ := json.Marshal(w) | |
| 48 | 新增: digest := sha256.Sum256(data) | |
| 49 | 新增: return hex.EncodeToString(digest[:16]) | |
| 50 | 新增:} | |
| 51 | 新增: | |
| 52 | 新增:// Round inward so the image and accepted coordinates remain inside the window. | |
| 53 | 新增:func (w maintenanceWindow) region() [4]int { | |
| 54 | 新增: x := int(math.Ceil((w.Rect[0] - w.Display[0]) / w.Display[2] * 1024)) | |
| 55 | 新增: y := int(math.Ceil((w.Rect[1] - w.Display[1]) / w.Display[3] * 640)) | |
| 56 | 新增: right := int(math.Floor((w.Rect[0] + w.Rect[2] - w.Display[0]) / w.Display[2] * 1024)) | |
| 57 | 新增: bottom := int(math.Floor((w.Rect[1] + w.Rect[3] - w.Display[1]) / w.Display[3] * 640)) | |
| 58 | 新增: return [4]int{x, y, right - x, bottom - y} | |
| 59 | 新增:} | |
| 60 | 新增: | |
| 61 | 新增:func (w maintenanceWindow) contains(x, y int) bool { | |
| 62 | 新增: r := w.region() | |
| 63 | 新增: return x >= r[0] && y >= r[1] && x < r[0]+r[2] && y < r[1]+r[3] | |
| 64 | 新增:} | |
| 65 | 新增: | |
| 66 | 新增:func (selection *passwordSelection) selectMaintenance(window maintenanceWindow, target passwordTarget, user string, x, y int, now time.Time) { | |
| 67 | 新增: *selection = passwordSelection{} | |
| 68 | 新增: if target.valid(user) && target.SelectionRequired && window.geometry() == target.geometry() && target.contains(x, y) { | |
| 69 | 新增: *selection = passwordSelection{Geometry: target.geometry(), X: x, Y: y, Clicked: now} | |
| 70 | 新增: } | |
| 71 | 新增:} | |
| 72 | 新增: | |
| 73 | 新增:func (selection *passwordSelection) consumeMaintenance(window maintenanceWindow, target passwordTarget, user string, now time.Time) (passwordSelection, bool) { | |
| 74 | 新增: selected := *selection | |
| 75 | 新增: *selection = passwordSelection{} | |
| 76 | 新增: return selected, window.permitsPassword(target, selected, user, now) | |
| 77 | 新增:} | |
| 78 | 新增: | |
| 79 | 新增:func (window maintenanceWindow) permitsPassword(target passwordTarget, selection passwordSelection, user string, now time.Time) bool { | |
| 80 | 新增: return window.geometry() == target.geometry() && selection.permits(target, user, now) | |
| 81 | 新增:} | |
| @@ -0,0 +1,341 @@ | ||
| 1 | 新增://go:build darwin && arm64 && cgo && !no_vz | |
| 2 | 新增: | |
| 3 | 新增:package maclogin | |
| 4 | 新增: | |
| 5 | 新增:/* | |
| 6 | 新增:#include "bridge.h" | |
| 7 | 新增:*/ | |
| 8 | 新增:import "C" | |
| 9 | 新增: | |
| 10 | 新增:import ( | |
| 11 | 新增: "bufio" | |
| 12 | 新增: "bytes" | |
| 13 | 新增: "context" | |
| 14 | 新增: "crypto/rand" | |
| 15 | 新增: "crypto/subtle" | |
| 16 | 新增: "encoding/json" | |
| 17 | 新增: "errors" | |
| 18 | 新增: "io" | |
| 19 | 新增: "os/exec" | |
| 20 | 新增: "strings" | |
| 21 | 新增: "time" | |
| 22 | 新增: | |
| 23 | 新增: "al.essio.dev/pkg/shellescape" | |
| 24 | 新增: "github.com/sylvinus/agent-vm/internal/guestos" | |
| 25 | 新增:) | |
| 26 | 新增: | |
| 27 | 新增:func (s *loginSession) maintenanceCommand(ctx context.Context, operation string) (*exec.Cmd, string, error) { | |
| 28 | 新增: open := operation == "--maintenance-open" | |
| 29 | 新增: if !guestos.ValidMacMaintenancePurpose(s.maintenance) { | |
| 30 | 新增: return nil, "", errors.New("维护用途无效") | |
| 31 | 新增: } | |
| 32 | 新增: bound, err := guestos.LoadMacOSProfile(s.profile) | |
| 33 | 新增: if err != nil || bound == nil || bound.SetupID != "" { | |
| 34 | 新增: return nil, "", errors.New("请先完成虚拟 Mac 的首次设置") | |
| 35 | 新增: } | |
| 36 | 新增: if open { | |
| 37 | 新增: s.maintenanceMachineID = bound.MachineID | |
| 38 | 新增: } else if s.maintenanceMachineID != bound.MachineID { | |
| 39 | 新增: return nil, "", errors.New("虚拟 Mac 身份已变化,请重新打开维护画面") | |
| 40 | 新增: } | |
| 41 | 新增: user, err := guestos.MacOSProvisionUser(s.profile) | |
| 42 | 新增: if err != nil { | |
| 43 | 新增: return nil, "", err | |
| 44 | 新增: } | |
| 45 | 新增: if open { | |
| 46 | 新增: s.maintenanceAdministrator = user | |
| 47 | 新增: } else if s.maintenanceAdministrator != user { | |
| 48 | 新增: return nil, "", errors.New("客机安装身份已变化,请重新打开维护画面") | |
| 49 | 新增: } | |
| 50 | 新增: cmd, err := guestGUIProbeCommand(ctx, s.profile, user, bound.User, operation, s.maintenance) | |
| 51 | 新增: return cmd, bound.User, err | |
| 52 | 新增:} | |
| 53 | 新增: | |
| 54 | 新增:func (s *loginSession) maintenanceProbe(open bool) (maintenanceWindow, error) { | |
| 55 | 新增: var result maintenanceWindow | |
| 56 | 新增: operation := "--maintenance-probe" | |
| 57 | 新增: if open { | |
| 58 | 新增: operation = "--maintenance-open" | |
| 59 | 新增: } | |
| 60 | 新增: ctx, cancel := context.WithTimeout(context.Background(), 4*time.Second) | |
| 61 | 新增: defer cancel() | |
| 62 | 新增: cmd, user, err := s.maintenanceCommand(ctx, operation) | |
| 63 | 新增: if err != nil { | |
| 64 | 新增: return result, err | |
| 65 | 新增: } | |
| 66 | 新增: pipe, err := cmd.StdoutPipe() | |
| 67 | 新增: if err != nil || cmd.Start() != nil { | |
| 68 | 新增: result.Error = "component_update_required" | |
| 69 | 新增: return result, errors.New("客机维护组件尚未连接,请更新环境组件后重试") | |
| 70 | 新增: } | |
| 71 | 新增: data, readErr := io.ReadAll(io.LimitReader(pipe, 8193)) | |
| 72 | 新增: if readErr != nil || len(data) > 8192 { | |
| 73 | 新增: cancel() | |
| 74 | 新增: } | |
| 75 | 新增: if err = cmd.Wait(); err != nil { | |
| 76 | 新增: var exit *exec.ExitError | |
| 77 | 新增: if errors.As(err, &exit) && exit.ExitCode() == 73 { | |
| 78 | 新增: result.Error = "requires_gui_login" | |
| 79 | 新增: return result, errors.New("请先登录并解锁虚拟 Mac 的客机账户") | |
| 80 | 新增: } | |
| 81 | 新增: result.Error = "component_update_required" | |
| 82 | 新增: return result, errors.New("客机维护组件需要更新,请在环境设置中更新组件") | |
| 83 | 新增: } | |
| 84 | 新增: if readErr != nil || len(data) > 8192 || json.Unmarshal(data, &result) != nil { | |
| 85 | 新增: result.Error = "component_update_required" | |
| 86 | 新增: return result, errors.New("客机维护组件需要更新,请在环境设置中更新组件") | |
| 87 | 新增: } | |
| 88 | 新增: if result.Error != "" { | |
| 89 | 新增: message := "请保持系统设置或系统授权窗口位于客机前台,再重新打开维护画面" | |
| 90 | 新增: if result.Error == "requires_gui_login" { | |
| 91 | 新增: message = "请先登录并解锁虚拟 Mac 的客机账户" | |
| 92 | 新增: } else if strings.Contains(result.Error, "obscured") { | |
| 93 | 新增: message = "授权窗口被其他窗口遮挡,请关闭遮挡窗口后重新打开维护画面" | |
| 94 | 新增: } | |
| 95 | 新增: return result, errors.New(message) | |
| 96 | 新增: } | |
| 97 | 新增: if !open && !result.valid(user) { | |
| 98 | 新增: return result, errors.New("客机授权窗口身份无法确认,请重新打开维护画面") | |
| 99 | 新增: } | |
| 100 | 新增: return result, nil | |
| 101 | 新增:} | |
| 102 | 新增: | |
| 103 | 新增:func maintenanceFailure(surface maintenanceWindow, err error, closed bool) reply { | |
| 104 | 新增: result := reply{Closed: closed, Error: err.Error()} | |
| 105 | 新增: if surface.Error == "component_update_required" { | |
| 106 | 新增: result.Recovery = "environment-update" | |
| 107 | 新增: } else if surface.Error == "requires_gui_login" { | |
| 108 | 新增: result.Recovery = "guest-login" | |
| 109 | 新增: } | |
| 110 | 新增: return result | |
| 111 | 新增:} | |
| 112 | 新增: | |
| 113 | 新增:func (s *loginSession) handleMaintenance(in request) (result reply) { | |
| 114 | 新增: defer func() { result.MaintenanceVersion = 1 }() | |
| 115 | 新增: if in.Setup || !guestos.ValidMacMaintenancePurpose(in.Maintenance) || len(in.Geometry) > 64 { | |
| 116 | 新增: return reply{Closed: true, Error: "维护用途无效"} | |
| 117 | 新增: } | |
| 118 | 新增: if in.Action == "open" { | |
| 119 | 新增: s.close() | |
| 120 | 新增: s.maintenance = in.Maintenance | |
| 121 | 新增: surface, err := s.maintenanceProbe(true) | |
| 122 | 新增: if err != nil { | |
| 123 | 新增: s.close() | |
| 124 | 新增: return maintenanceFailure(surface, err, true) | |
| 125 | 新增: } | |
| 126 | 新增: deadline := time.Now().Add(3 * time.Second) | |
| 127 | 新增: for { | |
| 128 | 新增: surface, err = s.maintenanceProbe(false) | |
| 129 | 新增: if err == nil || time.Now().After(deadline) { | |
| 130 | 新增: break | |
| 131 | 新增: } | |
| 132 | 新增: time.Sleep(100 * time.Millisecond) | |
| 133 | 新增: } | |
| 134 | 新增: if err != nil { | |
| 135 | 新增: s.close() | |
| 136 | 新增: return maintenanceFailure(surface, err, true) | |
| 137 | 新增: } | |
| 138 | 新增: s.token, s.screenID = rand.Text(), "maintenance-"+surface.Session | |
| 139 | 新增: s.expires = time.Now().Add(5 * time.Minute) | |
| 140 | 新增: C.cageLoginEnable(true) | |
| 141 | 新增: return reply{Session: s.token, Administrator: s.maintenanceAdministrator} | |
| 142 | 新增: } | |
| 143 | 新增: if s.token == "" || s.maintenance != in.Maintenance || subtle.ConstantTimeCompare([]byte(in.Session), []byte(s.token)) != 1 { | |
| 144 | 新增: return reply{Closed: true} | |
| 145 | 新增: } | |
| 146 | 新增: if in.Action == "close" || time.Now().After(s.expires) { | |
| 147 | 新增: s.close() | |
| 148 | 新增: return reply{Closed: true} | |
| 149 | 新增: } | |
| 150 | 新增: surface, err := s.maintenanceProbe(false) | |
| 151 | 新增: if err != nil || s.screenID != "maintenance-"+surface.Session { | |
| 152 | 新增: s.close() | |
| 153 | 新增: if err == nil { | |
| 154 | 新增: err = errors.New("客机登录会话已变化,请重新打开维护画面") | |
| 155 | 新增: } | |
| 156 | 新增: return maintenanceFailure(surface, err, true) | |
| 157 | 新增: } | |
| 158 | 新增: if in.Action == "frame" { | |
| 159 | 新增: region := surface.region() | |
| 160 | 新增: var size C.int | |
| 161 | 新增: data := C.cageLoginImageRegion(C.int(region[0]), C.int(region[1]), C.int(region[2]), C.int(region[3]), &size) | |
| 162 | 新增: if data == nil { | |
| 163 | 新增: return reply{Error: "正在等待系统设置窗口画面"} | |
| 164 | 新增: } | |
| 165 | 新增: defer C.free(data) | |
| 166 | 新增: after, err := s.maintenanceProbe(false) | |
| 167 | 新增: if err != nil { | |
| 168 | 新增: s.close() | |
| 169 | 新增: return maintenanceFailure(after, err, true) | |
| 170 | 新增: } | |
| 171 | 新增: if after != surface { | |
| 172 | 新增: return reply{Error: "授权窗口已变化,正在刷新画面"} | |
| 173 | 新增: } | |
| 174 | 新增: s.maintenanceFrame = surface.geometry() | |
| 175 | 新增: return reply{Image: C.GoBytes(data, size), MIME: "image/jpeg", Geometry: s.maintenanceFrame, Region: region[:]} | |
| 176 | 新增: } | |
| 177 | 新增: if in.Geometry == "" || in.Geometry != s.maintenanceFrame || in.Geometry != surface.geometry() { | |
| 178 | 新增: return reply{Error: "授权窗口已变化,请等待新画面后重试"} | |
| 179 | 新增: } | |
| 180 | 新增: switch in.Action { | |
| 181 | 新增: case "fill-password": | |
| 182 | 新增: if err := s.fillMaintenancePassword(surface); err != nil { | |
| 183 | 新增: return reply{Closed: s.token == "", Error: err.Error()} | |
| 184 | 新增: } | |
| 185 | 新增: case "select-all": | |
| 186 | 新增: s.passwordSelection = passwordSelection{} | |
| 187 | 新增: if !bool(C.cageLoginSelectAll()) { | |
| 188 | 新增: return reply{Error: "授权窗口尚未准备好"} | |
| 189 | 新增: } | |
| 190 | 新增: case "click": | |
| 191 | 新增: s.passwordSelection = passwordSelection{} | |
| 192 | 新增: if !surface.contains(in.X, in.Y) || !bool(C.cageLoginClick(C.int(in.X), C.int(in.Y))) { | |
| 193 | 新增: return reply{Error: "点击位置超出当前授权窗口"} | |
| 194 | 新增: } | |
| 195 | 新增: if probe, err := s.openMaintenancePasswordProbe(); err == nil { | |
| 196 | 新增: target, err := probe.target() | |
| 197 | 新增: if err == nil { | |
| 198 | 新增: s.passwordSelection.selectMaintenance(surface, target, probe.user, in.X, in.Y, time.Now()) | |
| 199 | 新增: } | |
| 200 | 新增: probe.close() | |
| 201 | 新增: } | |
| 202 | 新增: case "key": | |
| 203 | 新增: s.passwordSelection = passwordSelection{} | |
| 204 | 新增: navigation := in.Code >= 123 && in.Code <= 126 || in.Code == 116 || in.Code == 121 | |
| 205 | 新增: if in.Code < 0 || (in.Code > 53 && !navigation) || !bool(C.cageLoginKey(C.int(in.Code), C.bool(in.Shift))) { | |
| 206 | 新增: return reply{Error: "此按键不能用于授权窗口"} | |
| 207 | 新增: } | |
| 208 | 新增: case "scroll": | |
| 209 | 新增: s.passwordSelection = passwordSelection{} | |
| 210 | 新增: if !surface.contains(in.X, in.Y) || in.DeltaX < -512 || in.DeltaX > 512 || in.DeltaY < -512 || in.DeltaY > 512 || | |
| 211 | 新增: !bool(C.cageLoginScroll(C.int(in.X), C.int(in.Y), C.int(in.DeltaX), C.int(in.DeltaY))) { | |
| 212 | 新增: return reply{Error: "滚动位置超出当前授权窗口"} | |
| 213 | 新增: } | |
| 214 | 新增: default: | |
| 215 | 新增: return reply{Error: "维护操作无效"} | |
| 216 | 新增: } | |
| 217 | 新增: return reply{} | |
| 218 | 新增:} | |
| 219 | 新增: | |
| 220 | 新增:func (s *loginSession) openMaintenancePasswordProbe() (*passwordProbe, error) { | |
| 221 | 新增: ctx, cancel := context.WithTimeout(context.Background(), 7*time.Second) | |
| 222 | 新增: command, user, err := s.maintenanceCommand(ctx, "--maintenance-password-probe") | |
| 223 | 新增: if err != nil { | |
| 224 | 新增: cancel() | |
| 225 | 新增: return nil, err | |
| 226 | 新增: } | |
| 227 | 新增: input, err := command.StdinPipe() | |
| 228 | 新增: if err != nil { | |
| 229 | 新增: cancel() | |
| 230 | 新增: return nil, err | |
| 231 | 新增: } | |
| 232 | 新增: output, err := command.StdoutPipe() | |
| 233 | 新增: if err != nil { | |
| 234 | 新增: input.Close() | |
| 235 | 新增: cancel() | |
| 236 | 新增: return nil, err | |
| 237 | 新增: } | |
| 238 | 新增: if err = command.Start(); err != nil { | |
| 239 | 新增: input.Close() | |
| 240 | 新增: output.Close() | |
| 241 | 新增: cancel() | |
| 242 | 新增: return nil, err | |
| 243 | 新增: } | |
| 244 | 新增: scanner := bufio.NewScanner(output) | |
| 245 | 新增: scanner.Buffer(make([]byte, 4096), 32<<10) | |
| 246 | 新增: return &passwordProbe{command: command, input: input, output: output, scanner: scanner, cancel: cancel, user: user}, nil | |
| 247 | 新增:} | |
| 248 | 新增: | |
| 249 | 新增:func (s *loginSession) fillMaintenancePassword(window maintenanceWindow) error { | |
| 250 | 新增: selected := s.passwordSelection | |
| 251 | 新增: s.passwordSelection = passwordSelection{} | |
| 252 | 新增: probe, err := s.openMaintenancePasswordProbe() | |
| 253 | 新增: if err != nil { | |
| 254 | 新增: return err | |
| 255 | 新增: } | |
| 256 | 新增: defer probe.close() | |
| 257 | 新增: target, err := probe.target() | |
| 258 | 新增: if err != nil { | |
| 259 | 新增: return err | |
| 260 | 新增: } | |
| 261 | 新增: selection, permitted := selected.consumeMaintenance(window, target, probe.user, time.Now()) | |
| 262 | 新增: if !permitted { | |
| 263 | 新增: return errors.New("请先选中系统授权窗口的密码框,再点击填写管理员密码") | |
| 264 | 新增: } | |
| 265 | 新增: password, err := s.maintenancePassword() | |
| 266 | 新增: if err != nil { | |
| 267 | 新增: return err | |
| 268 | 新增: } | |
| 269 | 新增: defer func() { clear(password) }() | |
| 270 | 新增: sequence, valid := passwordKeys(string(bytes.TrimRight(password, "\r\n"))) | |
| 271 | 新增: if !valid { | |
| 272 | 新增: return errors.New("安装管理员凭据格式无效,请检查安装记录") | |
| 273 | 新增: } | |
| 274 | 新增: check := func() error { | |
| 275 | 新增: current, err := probe.target() | |
| 276 | 新增: if err != nil { | |
| 277 | 新增: return err | |
| 278 | 新增: } | |
| 279 | 新增: if time.Now().After(s.expires) || s.screenID != "maintenance-"+current.Session { | |
| 280 | 新增: s.close() | |
| 281 | 新增: return errors.New("客机授权会话已结束,请重新打开维护画面") | |
| 282 | 新增: } | |
| 283 | 新增: if !window.permitsPassword(current, selection, probe.user, time.Now()) { | |
| 284 | 新增: return errors.New("系统授权窗口或密码框已变化,填写已停止,请重新选中密码框") | |
| 285 | 新增: } | |
| 286 | 新增: return nil | |
| 287 | 新增: } | |
| 288 | 新增: if err = check(); err != nil { | |
| 289 | 新增: return err | |
| 290 | 新增: } | |
| 291 | 新增: if !target.Accessibility && !bool(C.cageLoginClick(C.int(selection.X), C.int(selection.Y))) { | |
| 292 | 新增: return errors.New("所选密码框已变化,请重新点选") | |
| 293 | 新增: } | |
| 294 | 新增: if err = check(); err != nil { | |
| 295 | 新增: return err | |
| 296 | 新增: } | |
| 297 | 新增: if !bool(C.cageLoginSelectAll()) { | |
| 298 | 新增: return errors.New("系统密码框尚未准备好,请重试") | |
| 299 | 新增: } | |
| 300 | 新增: for _, key := range sequence { | |
| 301 | 新增: if err = check(); err != nil { | |
| 302 | 新增: return err | |
| 303 | 新增: } | |
| 304 | 新增: if !bool(C.cageLoginKey(C.int(key.code), C.bool(key.shift))) { | |
| 305 | 新增: return errors.New("管理员密码未能填写,请重新选中密码框后重试") | |
| 306 | 新增: } | |
| 307 | 新增: } | |
| 308 | 新增: return nil | |
| 309 | 新增:} | |
| 310 | 新增: | |
| 311 | 新增:func (s *loginSession) maintenancePassword() ([]byte, error) { | |
| 312 | 新增: user, err := guestos.MacOSProvisionUser(s.profile) | |
| 313 | 新增: if err != nil || user != s.maintenanceAdministrator { | |
| 314 | 新增: return nil, errors.New("客机安装身份已变化,请重新打开维护画面") | |
| 315 | 新增: } | |
| 316 | 新增: args, err := guestos.MacOSSSHArgs(s.profile, user) | |
| 317 | 新增: if err != nil { | |
| 318 | 新增: return nil, err | |
| 319 | 新增: } | |
| 320 | 新增: script := `set -eu; p=` + shellescape.Quote("/Users/"+user+"/password") + ` | |
| 321 | 新增:test ! -L "$p" && test "$(/usr/bin/stat -f %u "$p")" = "$(/usr/bin/id -u)" | |
| 322 | 新增:mode=$(/usr/bin/stat -f %Lp "$p"); test "$((0$mode & 077))" = 0 | |
| 323 | 新增:exec /bin/cat "$p"` | |
| 324 | 新增: ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) | |
| 325 | 新增: defer cancel() | |
| 326 | 新增: cmd := exec.CommandContext(ctx, "/usr/bin/ssh", append(args, "-T", "cage-macos", "--", "exec /bin/sh -c "+shellescape.Quote(script))...) | |
| 327 | 新增: cmd.Env = []string{"PATH=/usr/bin:/bin", "LC_ALL=C"} | |
| 328 | 新增: pipe, err := cmd.StdoutPipe() | |
| 329 | 新增: if err != nil || cmd.Start() != nil { | |
| 330 | 新增: return nil, errors.New("安装管理员凭据暂时不可用") | |
| 331 | 新增: } | |
| 332 | 新增: data, readErr := io.ReadAll(io.LimitReader(pipe, 1025)) | |
| 333 | 新增: if readErr != nil || len(data) > 1024 { | |
| 334 | 新增: cancel() | |
| 335 | 新增: } | |
| 336 | 新增: if err = cmd.Wait(); err != nil || readErr != nil || len(data) == 0 || len(data) > 1024 { | |
| 337 | 新增: clear(data) | |
| 338 | 新增: return nil, errors.New("安装管理员凭据不可用,请核对安装记录") | |
| 339 | 新增: } | |
| 340 | 新增: return data, nil | |
| 341 | 新增:} | |
| @@ -0,0 +1,128 @@ | ||
| 1 | 新增:package maclogin | |
| 2 | 新增: | |
| 3 | 新增:import ( | |
| 4 | 新增: "math" | |
| 5 | 新增: "testing" | |
| 6 | 新增: "time" | |
| 7 | 新增:) | |
| 8 | 新增: | |
| 9 | 新增:func maintenanceFixture() maintenanceWindow { | |
| 10 | 新增: return maintenanceWindow{Version: 1, Session: "607bceb6-c53f-4253-bad4-9c22b4ae7325", User: "trial", PID: 42, Window: 7, | |
| 11 | 新增: Bundle: "com.apple.systempreferences", Rect: [4]float64{300, 150, 1200, 900}, Display: [4]float64{0, 0, 1920, 1200}} | |
| 12 | 新增:} | |
| 13 | 新增: | |
| 14 | 新增:func TestMaintenanceWindowRequiresBoundIdentityAndVisibleRegion(t *testing.T) { | |
| 15 | 新增: valid := maintenanceFixture() | |
| 16 | 新增: if !valid.valid("trial") || valid.region() != [4]int{160, 80, 640, 480} { | |
| 17 | 新增: t.Fatal("verified settings window was rejected") | |
| 18 | 新增: } | |
| 19 | 新增: for _, change := range []func(*maintenanceWindow){ | |
| 20 | 新增: func(w *maintenanceWindow) { w.User = "another-user" }, | |
| 21 | 新增: func(w *maintenanceWindow) { w.Version = 0 }, | |
| 22 | 新增: func(w *maintenanceWindow) { w.PID = 0 }, | |
| 23 | 新增: func(w *maintenanceWindow) { w.Window = 0 }, | |
| 24 | 新增: func(w *maintenanceWindow) { w.Bundle = "com.apple.finder" }, | |
| 25 | 新增: func(w *maintenanceWindow) { w.Bundle = "com.example.authorizationhost" }, | |
| 26 | 新增: func(w *maintenanceWindow) { w.Session = "" }, | |
| 27 | 新增: func(w *maintenanceWindow) { w.Error = "requires_gui_login" }, | |
| 28 | 新增: func(w *maintenanceWindow) { w.Error = "maintenance_window_obscured" }, | |
| 29 | 新增: func(w *maintenanceWindow) { w.Rect[0] = -1 }, | |
| 30 | 新增: func(w *maintenanceWindow) { w.Rect[2] = 80_000 }, | |
| 31 | 新增: func(w *maintenanceWindow) { w.Rect[3] = math.NaN() }, | |
| 32 | 新增: func(w *maintenanceWindow) { w.Display[2] = math.Inf(1) }, | |
| 33 | 新增: func(w *maintenanceWindow) { w.Display[3] = 1080 }, | |
| 34 | 新增: } { | |
| 35 | 新增: invalid := valid | |
| 36 | 新增: change(&invalid) | |
| 37 | 新增: if invalid.valid("trial") { | |
| 38 | 新增: t.Fatalf("accepted unverified maintenance target: %+v", invalid) | |
| 39 | 新增: } | |
| 40 | 新增: } | |
| 41 | 新增: if !valid.contains(160, 80) || !valid.contains(799, 559) || valid.contains(159, 80) || valid.contains(800, 559) || valid.contains(160, 560) { | |
| 42 | 新增: t.Fatal("maintenance input escaped the shown crop") | |
| 43 | 新增: } | |
| 44 | 新增:} | |
| 45 | 新增: | |
| 46 | 新增:func TestMaintenanceGeometryChangesWithWindowAndSession(t *testing.T) { | |
| 47 | 新增: first := maintenanceFixture() | |
| 48 | 新增: focused := first | |
| 49 | 新增: focused.PasswordFocused = true | |
| 50 | 新增: if focused.geometry() != first.geometry() { | |
| 51 | 新增: t.Fatal("a click that focuses a field invalidated ordinary typing") | |
| 52 | 新增: } | |
| 53 | 新增: for _, change := range []func(*maintenanceWindow){ | |
| 54 | 新增: func(w *maintenanceWindow) { w.Window++ }, | |
| 55 | 新增: func(w *maintenanceWindow) { w.PID++ }, | |
| 56 | 新增: func(w *maintenanceWindow) { w.Rect[0]++ }, | |
| 57 | 新增: func(w *maintenanceWindow) { w.Session = "1e128373-fcb9-42fd-88b2-2a6ca58cf3a1" }, | |
| 58 | 新增: } { | |
| 59 | 新增: next := first | |
| 60 | 新增: change(&next) | |
| 61 | 新增: if next.geometry() == first.geometry() { | |
| 62 | 新增: t.Fatal("stale window input retained its authorization") | |
| 63 | 新增: } | |
| 64 | 新增: } | |
| 65 | 新增:} | |
| 66 | 新增: | |
| 67 | 新增:func TestMaintenancePasswordSelectionWorksOnceBeforeAccessibility(t *testing.T) { | |
| 68 | 新增: now := time.Now() | |
| 69 | 新增: window := maintenanceFixture() | |
| 70 | 新增: target := passwordTarget{maintenanceWindow: window, SelectionRequired: true} | |
| 71 | 新增: var selection passwordSelection | |
| 72 | 新增: if _, allowed := selection.consumeMaintenance(window, target, "trial", now); allowed { | |
| 73 | 新增: t.Fatal("maintenance password accepted without the user's selection") | |
| 74 | 新增: } | |
| 75 | 新增: selection.selectMaintenance(window, target, "trial", 200, 200, now) | |
| 76 | 新增: chosen, allowed := selection.consumeMaintenance(window, target, "trial", now.Add(time.Second)) | |
| 77 | 新增: if !allowed || !window.permitsPassword(target, chosen, "trial", now.Add(2*time.Second)) { | |
| 78 | 新增: t.Fatal("AX-disabled maintenance could not use the selected Apple authorization panel") | |
| 79 | 新增: } | |
| 80 | 新增: if _, allowed := selection.consumeMaintenance(window, target, "trial", now.Add(2*time.Second)); allowed { | |
| 81 | 新增: t.Fatal("the same manual password selection was consumed twice") | |
| 82 | 新增: } | |
| 83 | 新增: if window.permitsPassword(target, chosen, "trial", now.Add(31*time.Second)) { | |
| 84 | 新增: t.Fatal("expired manual selection remained valid during password entry") | |
| 85 | 新增: } | |
| 86 | 新增:} | |
| 87 | 新增: | |
| 88 | 新增:func TestMaintenancePasswordRejectsChangedPanelAndSecureFocus(t *testing.T) { | |
| 89 | 新增: now := time.Now() | |
| 90 | 新增: window := maintenanceFixture() | |
| 91 | 新增: target := passwordTarget{maintenanceWindow: window, SelectionRequired: true} | |
| 92 | 新增: var selection passwordSelection | |
| 93 | 新增: selection.selectMaintenance(window, target, "trial", 200, 200, now) | |
| 94 | 新增: chosen, allowed := selection.consumeMaintenance(window, target, "trial", now) | |
| 95 | 新增: if !allowed { | |
| 96 | 新增: t.Fatal("could not establish the manual selection fixture") | |
| 97 | 新增: } | |
| 98 | 新增: for _, change := range []func(*passwordTarget){ | |
| 99 | 新增: func(w *passwordTarget) { w.SelectionRequired = false }, | |
| 100 | 新增: func(w *passwordTarget) { w.Window++ }, | |
| 101 | 新增: func(w *passwordTarget) { w.PID++ }, | |
| 102 | 新增: func(w *passwordTarget) { w.Rect[0]++ }, | |
| 103 | 新增: func(w *passwordTarget) { w.Session = "1e128373-fcb9-42fd-88b2-2a6ca58cf3a1" }, | |
| 104 | 新增: func(w *passwordTarget) { w.User = "another-user" }, | |
| 105 | 新增: func(w *passwordTarget) { w.Bundle = "com.apple.finder" }, | |
| 106 | 新增: func(w *passwordTarget) { w.Accessibility = true }, | |
| 107 | 新增: } { | |
| 108 | 新增: changed := target | |
| 109 | 新增: change(&changed) | |
| 110 | 新增: if window.permitsPassword(changed, chosen, "trial", now.Add(time.Second)) { | |
| 111 | 新增: t.Fatal("a changed panel, session or known non-password focus accepted password input") | |
| 112 | 新增: } | |
| 113 | 新增: } | |
| 114 | 新增: ordinary := target | |
| 115 | 新增: ordinary.SelectionRequired = false | |
| 116 | 新增: selection.selectMaintenance(window, ordinary, "trial", 200, 200, now) | |
| 117 | 新增: if _, allowed := selection.consumeMaintenance(window, ordinary, "trial", now); allowed { | |
| 118 | 新增: t.Fatal("an ordinary System Settings window accepted manual password selection") | |
| 119 | 新增: } | |
| 120 | 新增: selection.selectMaintenance(window, target, "trial", 159, 80, now) | |
| 121 | 新增: if _, allowed := selection.consumeMaintenance(window, target, "trial", now); allowed { | |
| 122 | 新增: t.Fatal("a click outside the published window accepted password entry") | |
| 123 | 新增: } | |
| 124 | 新增: target.Accessibility, target.PasswordFocused = true, true | |
| 125 | 新增: if _, allowed := selection.consumeMaintenance(window, target, "trial", now); !allowed { | |
| 126 | 新增: t.Fatal("verified secure focus required an unnecessary manual selection") | |
| 127 | 新增: } | |
| 128 | 新增:} | |
| @@ -0,0 +1,41 @@ | ||
| 1 | 新增://go:build darwin && arm64 && cgo && !no_vz | |
| 2 | 新增: | |
| 3 | 新增:package maclogin | |
| 4 | 新增: | |
| 5 | 新增:import ( | |
| 6 | 新增: "bufio" | |
| 7 | 新增: "bytes" | |
| 8 | 新增: "encoding/json" | |
| 9 | 新增: "testing" | |
| 10 | 新增:) | |
| 11 | 新增: | |
| 12 | 新增:type passwordProbeInput struct{ bytes.Buffer } | |
| 13 | 新增: | |
| 14 | 新增:func (*passwordProbeInput) Close() error { return nil } | |
| 15 | 新增: | |
| 16 | 新增:func TestMaintenancePasswordProbeUsesFixedPrivateStreamRequest(t *testing.T) { | |
| 17 | 新增: target := passwordTarget{maintenanceWindow: maintenanceFixture(), SelectionRequired: true} | |
| 18 | 新增: first, err := json.Marshal(target) | |
| 19 | 新增: if err != nil { | |
| 20 | 新增: t.Fatal(err) | |
| 21 | 新增: } | |
| 22 | 新增: target.Window++ | |
| 23 | 新增: second, err := json.Marshal(target) | |
| 24 | 新增: if err != nil { | |
| 25 | 新增: t.Fatal(err) | |
| 26 | 新增: } | |
| 27 | 新增: input := &passwordProbeInput{} | |
| 28 | 新增: output := append(append(append(first, '\n'), second...), '\n') | |
| 29 | 新增: probe := passwordProbe{input: input, scanner: bufio.NewScanner(bytes.NewReader(output)), user: "trial"} | |
| 30 | 新增: before, err := probe.target() | |
| 31 | 新增: if err != nil || before.Accessibility || !before.SelectionRequired { | |
| 32 | 新增: t.Fatal("private probe lost the AX-disabled authorization target") | |
| 33 | 新增: } | |
| 34 | 新增: after, err := probe.target() | |
| 35 | 新增: if err != nil || before.geometry() == after.geometry() { | |
| 36 | 新增: t.Fatal("per-key probe failed to observe a changed authorization panel") | |
| 37 | 新增: } | |
| 38 | 新增: if input.String() != "{\"action\":\"probe\"}\n{\"action\":\"probe\"}\n" { | |
| 39 | 新增: t.Fatal("maintenance probe used a GUI socket command or extra request fields") | |
| 40 | 新增: } | |
| 41 | 新增:} | |
| @@ -0,0 +1,30 @@ | ||
| 1 | 新增:package maclogin | |
| 2 | 新增: | |
| 3 | 新增:import "time" | |
| 4 | 新增: | |
| 5 | 新增:type passwordTarget struct { | |
| 6 | 新增: maintenanceWindow | |
| 7 | 新增: Accessibility bool `json:"accessibility"` | |
| 8 | 新增: SelectionRequired bool `json:"selection_required"` | |
| 9 | 新增:} | |
| 10 | 新增: | |
| 11 | 新增:// Before Accessibility is granted, the user selects the input position in | |
| 12 | 新增:// Apple's system panel. The host binds that click to the current GUI session | |
| 13 | 新增:// and panel, and consumes it when the user requests password entry. | |
| 14 | 新增:type passwordSelection struct { | |
| 15 | 新增: Geometry string | |
| 16 | 新增: X, Y int | |
| 17 | 新增: Clicked time.Time | |
| 18 | 新增:} | |
| 19 | 新增: | |
| 20 | 新增:func (selection passwordSelection) permits(target passwordTarget, user string, now time.Time) bool { | |
| 21 | 新增: if !target.valid(user) { | |
| 22 | 新增: return false | |
| 23 | 新增: } | |
| 24 | 新增: if target.Accessibility { | |
| 25 | 新增: return target.PasswordFocused | |
| 26 | 新增: } | |
| 27 | 新增: return target.SelectionRequired && selection.Geometry == target.geometry() && | |
| 28 | 新增: now.Sub(selection.Clicked) >= 0 && now.Sub(selection.Clicked) <= 30*time.Second && | |
| 29 | 新增: target.contains(selection.X, selection.Y) | |
| 30 | 新增:} | |
| @@ -0,0 +1,150 @@ | ||
| 1 | 新增://go:build darwin && arm64 && cgo && !no_vz | |
| 2 | 新增: | |
| 3 | 新增:package maclogin | |
| 4 | 新增: | |
| 5 | 新增:/* | |
| 6 | 新增:#include "bridge.h" | |
| 7 | 新增:*/ | |
| 8 | 新增:import "C" | |
| 9 | 新增: | |
| 10 | 新增:import ( | |
| 11 | 新增: "bufio" | |
| 12 | 新增: "context" | |
| 13 | 新增: "encoding/json" | |
| 14 | 新增: "errors" | |
| 15 | 新增: "io" | |
| 16 | 新增: "os/exec" | |
| 17 | 新增: "time" | |
| 18 | 新增: | |
| 19 | 新增: "github.com/sylvinus/agent-vm/internal/guestos" | |
| 20 | 新增:) | |
| 21 | 新增: | |
| 22 | 新增:type passwordProbe struct { | |
| 23 | 新增: command *exec.Cmd | |
| 24 | 新增: input io.WriteCloser | |
| 25 | 新增: output io.ReadCloser | |
| 26 | 新增: scanner *bufio.Scanner | |
| 27 | 新增: cancel context.CancelFunc | |
| 28 | 新增: user string | |
| 29 | 新增:} | |
| 30 | 新增: | |
| 31 | 新增:func (s *loginSession) openPasswordProbe() (*passwordProbe, error) { | |
| 32 | 新增: bound, err := guestos.LoadMacOSProfile(s.profile) | |
| 33 | 新增: if err != nil || bound == nil || bound.SetupID == "" { | |
| 34 | 新增: return nil, errors.New("首次设置身份已变化,请重新打开授权画面") | |
| 35 | 新增: } | |
| 36 | 新增: administrator, err := guestos.MacOSProvisionUser(s.profile) | |
| 37 | 新增: if err != nil { | |
| 38 | 新增: return nil, err | |
| 39 | 新增: } | |
| 40 | 新增: ctx, cancel := context.WithTimeout(context.Background(), 7*time.Second) | |
| 41 | 新增: command, err := guestGUIProbeCommand(ctx, s.profile, administrator, bound.User, "--setup-password-probe") | |
| 42 | 新增: if err != nil { | |
| 43 | 新增: cancel() | |
| 44 | 新增: return nil, err | |
| 45 | 新增: } | |
| 46 | 新增: input, err := command.StdinPipe() | |
| 47 | 新增: if err != nil { | |
| 48 | 新增: cancel() | |
| 49 | 新增: return nil, err | |
| 50 | 新增: } | |
| 51 | 新增: output, err := command.StdoutPipe() | |
| 52 | 新增: if err != nil { | |
| 53 | 新增: input.Close() | |
| 54 | 新增: cancel() | |
| 55 | 新增: return nil, err | |
| 56 | 新增: } | |
| 57 | 新增: if err = command.Start(); err != nil { | |
| 58 | 新增: input.Close() | |
| 59 | 新增: output.Close() | |
| 60 | 新增: cancel() | |
| 61 | 新增: return nil, err | |
| 62 | 新增: } | |
| 63 | 新增: scanner := bufio.NewScanner(output) | |
| 64 | 新增: scanner.Buffer(make([]byte, 4096), 32<<10) | |
| 65 | 新增: return &passwordProbe{command: command, input: input, output: output, scanner: scanner, cancel: cancel, user: bound.User}, nil | |
| 66 | 新增:} | |
| 67 | 新增: | |
| 68 | 新增:func (probe *passwordProbe) close() { | |
| 69 | 新增: probe.input.Close() | |
| 70 | 新增: probe.output.Close() | |
| 71 | 新增: probe.cancel() | |
| 72 | 新增: _ = probe.command.Wait() | |
| 73 | 新增:} | |
| 74 | 新增: | |
| 75 | 新增:func (probe *passwordProbe) target() (passwordTarget, error) { | |
| 76 | 新增: var target passwordTarget | |
| 77 | 新增: if _, err := io.WriteString(probe.input, "{\"action\":\"probe\"}\n"); err != nil { | |
| 78 | 新增: return target, err | |
| 79 | 新增: } | |
| 80 | 新增: if !probe.scanner.Scan() { | |
| 81 | 新增: return target, errors.New("无法确认系统授权窗口,请重新打开授权画面") | |
| 82 | 新增: } | |
| 83 | 新增: if json.Unmarshal(probe.scanner.Bytes(), &target) != nil || !target.valid(probe.user) { | |
| 84 | 新增: return target, errors.New("请打开 Apple 系统授权窗口,再选中需要填写的密码框") | |
| 85 | 新增: } | |
| 86 | 新增: return target, nil | |
| 87 | 新增:} | |
| 88 | 新增: | |
| 89 | 新增:func (s *loginSession) selectPasswordPosition(x, y int) { | |
| 90 | 新增: s.passwordSelection = passwordSelection{} | |
| 91 | 新增: probe, err := s.openPasswordProbe() | |
| 92 | 新增: if err != nil { | |
| 93 | 新增: return | |
| 94 | 新增: } | |
| 95 | 新增: defer probe.close() | |
| 96 | 新增: target, err := probe.target() | |
| 97 | 新增: if err == nil && target.SelectionRequired && target.contains(x, y) { | |
| 98 | 新增: s.passwordSelection = passwordSelection{Geometry: target.geometry(), X: x, Y: y, Clicked: time.Now()} | |
| 99 | 新增: } | |
| 100 | 新增:} | |
| 101 | 新增: | |
| 102 | 新增:func (s *loginSession) fillSetupPassword(password string) error { | |
| 103 | 新增: selection := s.passwordSelection | |
| 104 | 新增: s.passwordSelection = passwordSelection{} | |
| 105 | 新增: sequence, valid := passwordKeys(password) | |
| 106 | 新增: if !s.setup || !valid { | |
| 107 | 新增: return errors.New("首次设置凭据不可用,请重新打开授权画面") | |
| 108 | 新增: } | |
| 109 | 新增: probe, err := s.openPasswordProbe() | |
| 110 | 新增: if err != nil { | |
| 111 | 新增: return err | |
| 112 | 新增: } | |
| 113 | 新增: defer probe.close() | |
| 114 | 新增: target, err := probe.target() | |
| 115 | 新增: if err != nil { | |
| 116 | 新增: return err | |
| 117 | 新增: } | |
| 118 | 新增: if !selection.permits(target, probe.user, time.Now()) { | |
| 119 | 新增: return errors.New("请先点选系统授权窗口的密码框,再点击填写授权密码") | |
| 120 | 新增: } | |
| 121 | 新增: if !target.Accessibility && !bool(C.cageLoginClick(C.int(selection.X), C.int(selection.Y))) { | |
| 122 | 新增: return errors.New("所选密码框已变化,请重新点选") | |
| 123 | 新增: } | |
| 124 | 新增: geometry := target.geometry() | |
| 125 | 新增: check := func() error { | |
| 126 | 新增: current, err := probe.target() | |
| 127 | 新增: if err != nil { | |
| 128 | 新增: return err | |
| 129 | 新增: } | |
| 130 | 新增: if current.geometry() != geometry || !selection.permits(current, probe.user, time.Now()) { | |
| 131 | 新增: return errors.New("系统授权窗口或密码框已变化,填写已停止,请重新选择") | |
| 132 | 新增: } | |
| 133 | 新增: return nil | |
| 134 | 新增: } | |
| 135 | 新增: if err = check(); err != nil { | |
| 136 | 新增: return err | |
| 137 | 新增: } | |
| 138 | 新增: if !bool(C.cageLoginSelectAll()) { | |
| 139 | 新增: return errors.New("系统密码框尚未准备好,请重试") | |
| 140 | 新增: } | |
| 141 | 新增: for _, key := range sequence { | |
| 142 | 新增: if err = check(); err != nil { | |
| 143 | 新增: return err | |
| 144 | 新增: } | |
| 145 | 新增: if !bool(C.cageLoginKey(C.int(key.code), C.bool(key.shift))) { | |
| 146 | 新增: return errors.New("授权密码未能填写,请重新选择密码框后重试") | |
| 147 | 新增: } | |
| 148 | 新增: } | |
| 149 | 新增: return nil | |
| 150 | 新增:} | |
| @@ -0,0 +1,53 @@ | ||
| 1 | 新增:package maclogin | |
| 2 | 新增: | |
| 3 | 新增:import ( | |
| 4 | 新增: "testing" | |
| 5 | 新增: "time" | |
| 6 | 新增:) | |
| 7 | 新增: | |
| 8 | 新增:func TestFirstAuthorizationUsesFreshSelectedSystemPanelBeforeAccessibility(t *testing.T) { | |
| 9 | 新增: now := time.Now() | |
| 10 | 新增: target := passwordTarget{maintenanceWindow: maintenanceFixture(), SelectionRequired: true} | |
| 11 | 新增: selected := passwordSelection{Geometry: target.geometry(), X: 200, Y: 200, Clicked: now} | |
| 12 | 新增: if !selected.permits(target, "trial", now.Add(time.Second)) { | |
| 13 | 新增: t.Fatal("first authorization required the permission it is preparing") | |
| 14 | 新增: } | |
| 15 | 新增: for _, test := range []struct { | |
| 16 | 新增: name string | |
| 17 | 新增: change func(*passwordTarget, *passwordSelection) | |
| 18 | 新增: }{ | |
| 19 | 新增: {"no selection", func(_ *passwordTarget, s *passwordSelection) { *s = passwordSelection{} }}, | |
| 20 | 新增: {"expired selection", func(_ *passwordTarget, s *passwordSelection) { s.Clicked = now.Add(-31 * time.Second) }}, | |
| 21 | 新增: {"future selection", func(_ *passwordTarget, s *passwordSelection) { s.Clicked = now.Add(time.Second) }}, | |
| 22 | 新增: {"outside panel", func(_ *passwordTarget, s *passwordSelection) { s.X = 159 }}, | |
| 23 | 新增: {"replaced window", func(w *passwordTarget, _ *passwordSelection) { w.Window++ }}, | |
| 24 | 新增: {"moved window", func(w *passwordTarget, _ *passwordSelection) { w.Rect[0]++ }}, | |
| 25 | 新增: {"another process", func(w *passwordTarget, _ *passwordSelection) { w.PID++ }}, | |
| 26 | 新增: {"another GUI session", func(w *passwordTarget, _ *passwordSelection) { w.Session = "1e128373-fcb9-42fd-88b2-2a6ca58cf3a1" }}, | |
| 27 | 新增: {"another app", func(w *passwordTarget, _ *passwordSelection) { w.Bundle = "com.apple.finder" }}, | |
| 28 | 新增: {"ordinary settings window", func(w *passwordTarget, _ *passwordSelection) { w.SelectionRequired = false }}, | |
| 29 | 新增: {"known non-password focus", func(w *passwordTarget, _ *passwordSelection) { w.Accessibility = true }}, | |
| 30 | 新增: } { | |
| 31 | 新增: t.Run(test.name, func(t *testing.T) { | |
| 32 | 新增: current, selection := target, selected | |
| 33 | 新增: test.change(¤t, &selection) | |
| 34 | 新增: if selection.permits(current, "trial", now) { | |
| 35 | 新增: t.Fatal("unverified password target accepted") | |
| 36 | 新增: } | |
| 37 | 新增: }) | |
| 38 | 新增: } | |
| 39 | 新增:} | |
| 40 | 新增: | |
| 41 | 新增:func TestAuthorizedAccessibilityRequiresSecureFocusForBothAppleHosts(t *testing.T) { | |
| 42 | 新增: for _, bundle := range []string{"com.apple.systempreferences", "com.apple.authorizationhost"} { | |
| 43 | 新增: target := passwordTarget{maintenanceWindow: maintenanceFixture(), Accessibility: true} | |
| 44 | 新增: target.Bundle, target.PasswordFocused = bundle, true | |
| 45 | 新增: if !(passwordSelection{}).permits(target, "trial", time.Now()) { | |
| 46 | 新增: t.Fatalf("verified secure field rejected in %s", bundle) | |
| 47 | 新增: } | |
| 48 | 新增: target.PasswordFocused = false | |
| 49 | 新增: if (passwordSelection{}).permits(target, "trial", time.Now()) { | |
| 50 | 新增: t.Fatal("non-password field accepted") | |
| 51 | 新增: } | |
| 52 | 新增: } | |
| 53 | 新增:} | |
| @@ -14,7 +14,7 @@ func (s *Server) browser(w http.ResponseWriter, r *http.Request) { | ||
| 14 | 14 | action = "tabs" |
| 15 | 15 | } |
| 16 | 16 | switch action { |
| 17 | 删除: case "tabs", "split", "new", "activate", "close", "navigate", "back", "forward", "reload", "editor", "editor-restart", "download-retry", "upload-finish", "upload-cancel", "resize", "insert-text", "copy-context", "cookies", "settings", "extensions", "internal-page", "info": | |
| 17 | 新增: case "tabs", "split", "new", "activate", "close", "navigate", "back", "forward", "reload", "editor", "editor-restart", "download-retry", "upload-finish", "upload-cancel", "resize", "insert-text", "copy-context", "copy", "cut", "cookies", "settings", "extensions", "internal-page", "info": | |
| 18 | 18 | default: |
| 19 | 19 | http.NotFound(w, r) |
| 20 | 20 | return |
| @@ -112,7 +112,7 @@ func (s *Server) browserAction(ctx context.Context, action string, input *browse | ||
| 112 | 112 | ((input.Mode == "delete" || input.Mode == "details") && len(input.CookieKey) != 64)) { |
| 113 | 113 | return nil, browserInputError{errors.New("Cookie 操作或目标标签无效")} |
| 114 | 114 | } |
| 115 | 删除: if action == "copy-context" && (input.ID == "" || !validInputToken(input.Context)) { | |
| 115 | 新增: if (action == "copy-context" || action == "copy" || action == "cut") && (input.ID == "" || !validInputToken(input.Context)) { | |
| 116 | 116 | return nil, browserInputError{errors.New("复制操作或目标标签无效")} |
| 117 | 117 | } |
| 118 | 118 | if action == "insert-text" && (input.ID == "" || input.Text == "" || len(input.Text) > 8192) { |
| @@ -128,7 +128,12 @@ func (s *Server) desktopFileOpenAction(w http.ResponseWriter, r *http.Request) { | ||
| 128 | 128 | guest, _ := result["path"].(string) |
| 129 | 129 | action, _ := result["action"].(string) |
| 130 | 130 | var target string |
| 131 | 删除: if download, _ := result["download_id"].(string); download != "" && (s.macosGuest != nil || s.windowsGuest != nil) { | |
| 131 | 新增: download, _ := result["download_id"].(string) | |
| 132 | 新增: if message, _ := result["error"].(string); message != "" { | |
| 133 | 新增: err = errors.New(message) | |
| 134 | 新增: } else if action != "open" && action != "reveal" { | |
| 135 | 新增: err = errors.New("文件打开操作无效") | |
| 136 | 新增: } else if download != "" && (s.macosGuest != nil || s.windowsGuest != nil) { | |
| 132 | 137 | var saved browserDownloadInfo |
| 133 | 138 | saved, err = s.downloadInfo(ctx, download) |
| 134 | 139 | if err == nil && saved.State != "saved" { |
| @@ -145,12 +150,6 @@ func (s *Server) desktopFileOpenAction(w http.ResponseWriter, r *http.Request) { | ||
| 145 | 150 | target, err = s.resolveDesktopProjectFile(guest, projects) |
| 146 | 151 | } |
| 147 | 152 | } |
| 148 | 删除: if action != "open" && action != "reveal" { | |
| 149 | 删除: err = errors.New("文件打开操作无效") | |
| 150 | 删除: } | |
| 151 | 删除: if message, _ := result["error"].(string); message != "" { | |
| 152 | 删除: err = errors.New(message) | |
| 153 | 删除: } | |
| 154 | 153 | if err != nil { |
| 155 | 154 | body, _ = json.Marshal(map[string]string{"id": input.ID, "error": err.Error()}) |
| 156 | 155 | cleanup, cancelCleanup := context.WithTimeout(context.WithoutCancel(ctx), 5*time.Second) |
| @@ -67,7 +67,9 @@ func (s *Server) diagnosticExport(w http.ResponseWriter, r *http.Request) { | ||
| 67 | 67 | defer s.diagnosticMu.Unlock() |
| 68 | 68 | guestState := "environment unavailable" |
| 69 | 69 | var guest []byte |
| 70 | 删除: if s.vmRunning() { | |
| 70 | 新增: if s.storageRecoveryStatus().Required { | |
| 71 | 新增: guestState = "environment storage recovery pending" | |
| 72 | 新增: } else if s.vmRunning() { | |
| 71 | 73 | ctx, cancel := context.WithTimeout(r.Context(), 8*time.Second) |
| 72 | 74 | defer cancel() |
| 73 | 75 | var err error |
| @@ -1,8 +1,10 @@ | ||
| 1 | 1 | package workbench |
| 2 | 2 | |
| 3 | 3 | import ( |
| 4 | 新增: "bytes" | |
| 4 | 5 | "encoding/json" |
| 5 | 6 | "github.com/sylvinus/agent-vm/internal/cage" |
| 7 | 新增: "github.com/sylvinus/agent-vm/internal/guestos" | |
| 6 | 8 | "io" |
| 7 | 9 | "net/http" |
| 8 | 10 | "os" |
| @@ -11,6 +13,64 @@ import ( | ||
| 11 | 13 | "testing" |
| 12 | 14 | ) |
| 13 | 15 | |
| 16 | 新增:func TestEnvironmentUpgradeSeparatesPrivateLegacyWorkspaceFromVMIdentity(t *testing.T) { | |
| 17 | 新增: home, err := filepath.EvalSymlinks(t.TempDir()) | |
| 18 | 新增: if err != nil { | |
| 19 | 新增: t.Fatal(err) | |
| 20 | 新增: } | |
| 21 | 新增: t.Setenv("HOME", home) | |
| 22 | 新增: t.Setenv("USERPROFILE", home) | |
| 23 | 新增: for _, system := range []string{"linux", "macos", "windows"} { | |
| 24 | 新增: t.Run(system, func(t *testing.T) { | |
| 25 | 新增: s := testServer(t) | |
| 26 | 新增: s.profile = filepath.Join(home, ".claude-cage", system) | |
| 27 | 新增: legacy := s.profile + "-workspace" | |
| 28 | 新增: selected := filepath.Join(home, "projects", system) | |
| 29 | 新增: for _, path := range []string{s.profile, legacy, selected} { | |
| 30 | 新增: if err := os.MkdirAll(path, 0700); err != nil { | |
| 31 | 新增: t.Fatal(err) | |
| 32 | 新增: } | |
| 33 | 新增: } | |
| 34 | 新增: s.preferences.Workspace = selected | |
| 35 | 新增: if system == "macos" { | |
| 36 | 新增: s.macosGuest = &guestos.MacOSProfile{Instance: "mac", User: "guest"} | |
| 37 | 新增: } else if system == "windows" { | |
| 38 | 新增: s.windowsGuest = &guestos.WindowsProfile{} | |
| 39 | 新增: } | |
| 40 | 新增: if err := writePrivate(filepath.Join(s.profile, "environment.json"), map[string]string{"directory": legacy}); err != nil { | |
| 41 | 新增: t.Fatal(err) | |
| 42 | 新增: } | |
| 43 | 新增: identity := cage.InstanceName(s.profile, legacy) | |
| 44 | 新增: disk := filepath.Join(s.profile, "state", "lima", identity, "disk") | |
| 45 | 新增: if err := writePrivate(filepath.Join(filepath.Dir(disk), "lima.yaml"), map[string]string{}); err != nil { | |
| 46 | 新增: t.Fatal(err) | |
| 47 | 新增: } | |
| 48 | 新增: original := []byte("persistent disk and existing project data") | |
| 49 | 新增: for _, file := range []string{disk, filepath.Join(legacy, "project.txt"), filepath.Join(s.profile, "account.json")} { | |
| 50 | 新增: if err := os.WriteFile(file, original, 0600); err != nil { | |
| 51 | 新增: t.Fatal(err) | |
| 52 | 新增: } | |
| 53 | 新增: } | |
| 54 | 新增: for restart := 0; restart < 2; restart++ { | |
| 55 | 新增: if err := s.prepareEnvironment(); err != nil { | |
| 56 | 新增: t.Fatal(err) | |
| 57 | 新增: } | |
| 58 | 新增: if s.environmentDir() != selected || s.workspace() != selected || cage.InstanceName(s.profile, selected) != identity { | |
| 59 | 新增: t.Fatal("startup changed the VM identity or selected project") | |
| 60 | 新增: } | |
| 61 | 新增: if _, err := validateWorkspace(legacy, s.profile); err == nil { | |
| 62 | 新增: t.Fatal("legacy location bypassed private-profile protection") | |
| 63 | 新增: } | |
| 64 | 新增: for _, file := range []string{disk, filepath.Join(legacy, "project.txt"), filepath.Join(s.profile, "account.json")} { | |
| 65 | 新增: if data, err := os.ReadFile(file); err != nil || !bytes.Equal(data, original) { | |
| 66 | 新增: t.Fatalf("startup changed existing personal data: %s %v", file, err) | |
| 67 | 新增: } | |
| 68 | 新增: } | |
| 69 | 新增: } | |
| 70 | 新增: }) | |
| 71 | 新增: } | |
| 72 | 新增:} | |
| 73 | 新增: | |
| 14 | 74 | type browserTransport func(*http.Request) (*http.Response, error) |
| 15 | 75 | |
| 16 | 76 | func (f browserTransport) RoundTrip(r *http.Request) (*http.Response, error) { return f(r) } |
| @@ -146,6 +146,11 @@ func (s *Server) synchronizeEnvironment() error { | ||
| 146 | 146 | if err := s.closeProxyGate("正在更新环境组件,外网暂时关闭"); err != nil { |
| 147 | 147 | return err |
| 148 | 148 | } |
| 149 | 新增: // Publish the new guest-only binary before runCage restarts its controller; | |
| 150 | 新增: // otherwise updated JavaScript would keep talking to the old protocol. | |
| 151 | 新增: if err := s.refreshInstalledTailnet(); err != nil { | |
| 152 | 新增: return err | |
| 153 | 新增: } | |
| 149 | 154 | s.mu.Lock() |
| 150 | 155 | s.ready = false |
| 151 | 156 | s.guestUpdateRequired = true |
| @@ -20,6 +20,15 @@ func executionFailure(action string, err error, output string) error { | ||
| 20 | 20 | patterns []string |
| 21 | 21 | reason, next string |
| 22 | 22 | }{ |
| 23 | 新增: {[]string{"cage_windows_maintenance_authorization_canceled"}, "已取消 Windows 管理员授权", "请重新发起原操作,并在 Windows 系统授权窗口中确认。"}, | |
| 24 | 新增: {[]string{"cage_windows_maintenance_authorization"}, "Windows 管理员授权窗口未能打开", "请从本机 Cage 重新发起操作,并使用可完成管理员授权的 Windows 账户。"}, | |
| 25 | 新增: {[]string{"cage_windows_maintenance_validation"}, "Windows 环境绑定或组件清单未通过校验", "请重新发起原操作,组件包仍无法核验时重新安装完整 Cage 应用。"}, | |
| 26 | 新增: {[]string{"cage_windows_maintenance_host_manager"}, "Windows 系统管理助手安装未完成", "请重试修复系统助手,仍失败时检查系统服务或安全软件记录并导出诊断包。"}, | |
| 27 | 新增: {[]string{"cage_windows_maintenance_guest_connection"}, "Windows 客机连接未完成", "请启动并登录已绑定客机,使用该客机的管理员账户重试。"}, | |
| 28 | 新增: {[]string{"cage_windows_maintenance_guest_components"}, "Windows 客机组件安装未完成", "请保持原客机运行,重试同步环境组件,仍失败时导出诊断包。"}, | |
| 29 | 新增: {[]string{"cage_windows_maintenance_host_relay"}, "Windows 主机连接组件更新未完成", "请关闭占用连接组件的程序,再重试同步环境组件。"}, | |
| 30 | 新增: {[]string{"cage_windows_maintenance_package_preparation"}, "Windows 组件包准备未完成", "请检查应用目录和系统盘空间后重试,更新工具时同时检查已选代理。"}, | |
| 31 | 新增: {[]string{"cage_windows_maintenance_failed"}, "Windows 维护未完成", "请从 Cage 重新发起原操作,仍失败时导出诊断包。"}, | |
| 23 | 32 | {[]string{"desktop file service state=failed"}, "Claude Desktop 的文件服务已经退出", "请从 Cage 重新打开 Claude Desktop;若应用反复退出,请在设置中查看资源用量并导出诊断包。"}, |
| 24 | 33 | {[]string{"curl: (7)", "connection refused"}, "目标服务没有接受连接", "请确认环境及所选代理已启动;文件传递时请重新打开接收文件的应用,再重试。"}, |
| 25 | 34 | {[]string{"no space left on device", "not enough space on the disk"}, "磁盘空间不足,无法继续写入", "请释放环境所在磁盘的空间后继续;不要删除 Cage 的个人数据目录。"}, |
| @@ -74,7 +74,7 @@ func (s *Server) guestFiles(ctx context.Context, target, method, path string, bo | ||
| 74 | 74 | switch { |
| 75 | 75 | case method == "GET" && parsed.Path == "/requests": |
| 76 | 76 | input.Action = "files-poll" |
| 77 | 删除: case method == "POST" && (parsed.Path == "/start" || parsed.Path == "/finish" || parsed.Path == "/finish-image" || parsed.Path == "/cancel" || parsed.Path == "/directory" || parsed.Path == "/download-retry" || parsed.Path == "/open-claim" || parsed.Path == "/open-complete"): | |
| 77 | 新增: case method == "POST" && (parsed.Path == "/start" || parsed.Path == "/finish" || parsed.Path == "/finish-image" || parsed.Path == "/cancel" || parsed.Path == "/directory" || parsed.Path == "/download-retry" || parsed.Path == "/download-ack" || parsed.Path == "/open-claim" || parsed.Path == "/open-complete"): | |
| 78 | 78 | input.Action = "files-" + strings.TrimPrefix(parsed.Path, "/") |
| 79 | 79 | default: |
| 80 | 80 | return nil, errors.New("虚拟 Mac 文件操作无效") |
| @@ -97,7 +97,7 @@ func (s *Server) guestFiles(ctx context.Context, target, method, path string, bo | ||
| 97 | 97 | switch { |
| 98 | 98 | case method == "GET" && parsed.Path == "/requests": |
| 99 | 99 | action = "files-poll" |
| 100 | 删除: case method == "POST" && (parsed.Path == "/start" || parsed.Path == "/finish" || parsed.Path == "/finish-image" || parsed.Path == "/cancel" || parsed.Path == "/directory" || parsed.Path == "/download-retry" || parsed.Path == "/open-claim" || parsed.Path == "/open-complete"): | |
| 100 | 新增: case method == "POST" && (parsed.Path == "/start" || parsed.Path == "/finish" || parsed.Path == "/finish-image" || parsed.Path == "/cancel" || parsed.Path == "/directory" || parsed.Path == "/download-retry" || parsed.Path == "/download-ack" || parsed.Path == "/open-claim" || parsed.Path == "/open-complete"): | |
| 101 | 101 | action = "files-" + strings.TrimPrefix(parsed.Path, "/") |
| 102 | 102 | default: |
| 103 | 103 | return nil, errors.New("Windows 原生文件选择框与桌面下载尚未接通") |
| @@ -316,9 +316,35 @@ func (s *Server) desktopFileRequests(w http.ResponseWriter, r *http.Request) { | ||
| 316 | 316 | requestError(w, err) |
| 317 | 317 | return |
| 318 | 318 | } |
| 319 | 新增: s.acknowledgeDesktopDownloads(ctx, result) | |
| 319 | 320 | jsonReply(w, result) |
| 320 | 321 | } |
| 321 | 322 | |
| 323 | 新增:func (s *Server) acknowledgeDesktopDownloads(ctx context.Context, result map[string]any) { | |
| 324 | 新增: if result["downloadAck"] != true || (s.macosGuest == nil && s.windowsGuest == nil) { | |
| 325 | 新增: return | |
| 326 | 新增: } | |
| 327 | 新增: var ids []string | |
| 328 | 新增: items, _ := result["downloads"].([]any) | |
| 329 | 新增: for _, value := range items { | |
| 330 | 新增: item, ok := value.(map[string]any) | |
| 331 | 新增: if !ok || item["state"] != "saved" || item["acknowledged"] == true { | |
| 332 | 新增: continue | |
| 333 | 新增: } | |
| 334 | 新增: id, _ := item["id"].(string) | |
| 335 | 新增: ids = append(ids, id) | |
| 336 | 新增: } | |
| 337 | 新增: if len(ids) == 0 { | |
| 338 | 新增: return | |
| 339 | 新增: } | |
| 340 | 新增: // rememberDesktopDownloads has resolved every saved state from its durable | |
| 341 | 新增: // host receipt. A failed acknowledgment keeps the guest copy for the next poll. | |
| 342 | 新增: body, _ := json.Marshal(map[string]any{"ids": ids}) | |
| 343 | 新增: if _, err := s.guestFiles(ctx, "desktop", "POST", "/download-ack", bytes.NewReader(body), ""); err != nil { | |
| 344 | 新增: diagnostics.Log("warn", "desktop-files", "主机文件已保存,客机保留副本并等待下次确认:"+err.Error()) | |
| 345 | 新增: } | |
| 346 | 新增:} | |
| 347 | 新增: | |
| 322 | 348 | // Register completed exports before the UI can ask a native bridge to save them. |
| 323 | 349 | // Guest paths are never accepted as arbitrary host paths. |
| 324 | 350 | func (s *Server) rememberDesktopDownloads(result map[string]any) error { |
| @@ -36,7 +36,7 @@ func (s *Server) pasteInputStart(w http.ResponseWriter, r *http.Request) { | ||
| 36 | 36 | return |
| 37 | 37 | } |
| 38 | 38 | if !s.fileTargetReady(input.Target, input.ID) { |
| 39 | 删除: http.Error(w, "图片接收位置已关闭,请重新点击输入框", http.StatusConflict) | |
| 39 | 新增: http.Error(w, "粘贴接收位置已关闭,请重新点击输入框", http.StatusConflict) | |
| 40 | 40 | return |
| 41 | 41 | } |
| 42 | 42 | ctx, cancel := context.WithTimeout(r.Context(), 10*time.Second) |
| @@ -50,7 +50,7 @@ func (s *Server) pasteInputStart(w http.ResponseWriter, r *http.Request) { | ||
| 50 | 50 | result, err := s.guestFiles(ctx, "desktop", "POST", "/start", bytes.NewReader(body), "") |
| 51 | 51 | id, _ := result["id"].(string) |
| 52 | 52 | if err != nil || !browserFileID.MatchString(id) { |
| 53 | 删除: http.Error(w, "图片目标未能绑定,请重新点击输入框;旧客机需要先同步环境组件", http.StatusConflict) | |
| 53 | 新增: http.Error(w, "粘贴目标未能绑定,请重新点击输入框。旧客机需要先同步环境组件", http.StatusConflict) | |
| 54 | 54 | return |
| 55 | 55 | } |
| 56 | 56 | jsonReply(w, map[string]any{"available": true, "transfer": id}) |
| @@ -62,7 +62,7 @@ func (s *Server) pasteInputStart(w http.ResponseWriter, r *http.Request) { | ||
| 62 | 62 | Transfer string `json:"transfer"` |
| 63 | 63 | } |
| 64 | 64 | if err != nil || json.Unmarshal(data, &result) != nil || !validInputToken(result.Transfer) { |
| 65 | 删除: http.Error(w, "图片目标未能绑定,请重新点击输入框;旧客机需要先同步环境组件", http.StatusConflict) | |
| 65 | 新增: http.Error(w, "粘贴目标未能绑定,请重新点击输入框。旧客机需要先同步环境组件", http.StatusConflict) | |
| 66 | 66 | return |
| 67 | 67 | } |
| 68 | 68 | jsonReply(w, map[string]any{"available": true, "transfer": result.Transfer}) |
| @@ -26,7 +26,7 @@ type initializationView struct { | ||
| 26 | 26 | } |
| 27 | 27 | |
| 28 | 28 | func (s *Server) initializationState() (initializationView, error) { |
| 29 | 删除: if !s.localVMStorage() { | |
| 29 | 新增: if !s.localVMStorage() || s.storageRecoveryStatus().Required { | |
| 30 | 30 | return initializationView{}, nil |
| 31 | 31 | } |
| 32 | 32 | data, err := os.ReadFile(filepath.Join(s.profile, "initialization.json")) |
| @@ -1,6 +1,9 @@ | ||
| 1 | 1 | package workbench |
| 2 | 2 | |
| 3 | 删除:import "context" | |
| 3 | 新增:import ( | |
| 4 | 新增: "context" | |
| 5 | 新增: "fmt" | |
| 6 | 新增:) | |
| 4 | 7 | |
| 5 | 8 | func (s *Server) busy() bool { return s.jobs.snapshot().Running } |
| 6 | 9 | |
| @@ -12,6 +15,11 @@ func (s *Server) submitJob(kind string, run func() error) (Job, error) { | ||
| 12 | 15 | s.mu.Unlock() |
| 13 | 16 | return Job{}, errJobsClosed |
| 14 | 17 | } |
| 18 | 新增: if s.storageRecoveryError != "" && kind != "storage-recovery" { | |
| 19 | 新增: err := fmt.Errorf("环境存储待恢复,请在设置中恢复后继续。%s", s.storageRecoveryError) | |
| 20 | 新增: s.mu.Unlock() | |
| 21 | 新增: return Job{}, err | |
| 22 | 新增: } | |
| 15 | 23 | var afterSuccess func() error |
| 16 | 24 | if kind == "logout" { |
| 17 | 25 | kind = "stop" |
| @@ -56,6 +56,7 @@ type macOSWindowRequest struct { | ||
| 56 | 56 | Wait bool `json:"wait,omitempty"` |
| 57 | 57 | Binary bool `json:"binary,omitempty"` |
| 58 | 58 | ID string `json:"id,omitempty"` |
| 59 | 新增: IDs []string `json:"ids,omitempty"` | |
| 59 | 60 | Kind string `json:"kind,omitempty"` |
| 60 | 61 | Transfer string `json:"transfer,omitempty"` |
| 61 | 62 | Sequence int `json:"sequence"` |
| @@ -27,7 +27,7 @@ func macOSWorkbenchRoute(path string) bool { | ||
| 27 | 27 | return id == "requests" || id == "open" || browserFileID.MatchString(id) |
| 28 | 28 | } |
| 29 | 29 | switch path { |
| 30 | 删除: case "/api/macos/first-setup", "/api/appearance/codex", "/api/macos/project-approval", "/api/macos/exit-policy", "/api/macos/login": | |
| 30 | 新增: case "/api/macos/first-setup", "/api/appearance/codex", "/api/macos/project-approval", "/api/macos/exit-policy", "/api/macos/login", "/api/macos/maintenance": | |
| 31 | 31 | return true |
| 32 | 32 | } |
| 33 | 33 | return strings.HasPrefix(path, "/api/macos/claude/") || strings.HasPrefix(path, "/api/macos-browser/") |
| @@ -114,6 +114,8 @@ func (s *Server) attachMacOSGuest() error { | ||
| 114 | 114 | if checkAfterReconnect { |
| 115 | 115 | _, _ = s.submitJob("network-recovery", s.checkNetworkIfWanted) |
| 116 | 116 | } |
| 117 | 新增: } else if err == nil && !s.macSetupPending() { | |
| 118 | 新增: s.retryMacOSProjectShares(ctx) | |
| 117 | 119 | } |
| 118 | 120 | return err |
| 119 | 121 | } |
| @@ -82,7 +82,7 @@ func TestMacOSWindowInputRoutesPreserveCompositionSequence(t *testing.T) { | ||
| 82 | 82 | for sequence, mode := range []string{"begin", "update", "commit"} { |
| 83 | 83 | input := macOSWindowRequest{Action: "ime", PID: 42, Window: 7, Geometry: "geometry", Mode: mode, |
| 84 | 84 | Context: strings.Repeat("a", 32), Session: strings.Repeat("b", 32), Sequence: sequence, |
| 85 | 删除: Project: "ungranted", PhoneToken: "ungranted", Path: "ungranted", Transfer: "ungranted", KeepAlive: true, Wait: true, Binary: true} | |
| 85 | 新增: Project: "ungranted", PhoneToken: "ungranted", Path: "ungranted", Transfer: "ungranted", IDs: []string{"ungranted"}, KeepAlive: true, Wait: true, Binary: true} | |
| 86 | 86 | if mode == "commit" { |
| 87 | 87 | input.Text = strings.Repeat("\x01", 8192) |
| 88 | 88 | } |
| @@ -102,7 +102,7 @@ func TestMacOSWindowInputRoutesPreserveCompositionSequence(t *testing.T) { | ||
| 102 | 102 | if actual.Sequence != sequence || actual.Session != input.Session || actual.Text != input.Text || actual.Geometry != input.Geometry { |
| 103 | 103 | t.Fatalf("composition changed in transit for %s, sequence %d", mode, actual.Sequence) |
| 104 | 104 | } |
| 105 | 删除: if actual.Project != "" || actual.Path != "" || actual.PhoneToken != "" || actual.Transfer != "" || actual.Wait || actual.Binary || actual.KeepAlive != keepAlive { | |
| 105 | 新增: if actual.Project != "" || actual.Path != "" || actual.PhoneToken != "" || actual.Transfer != "" || actual.IDs != nil || actual.Wait || actual.Binary || actual.KeepAlive != keepAlive { | |
| 106 | 106 | t.Fatalf("public input retained privileged fields for %s", mode) |
| 107 | 107 | } |
| 108 | 108 | } |
| @@ -48,6 +48,65 @@ type macSetupPermissions struct { | ||
| 48 | 48 | ManagedCredential bool `json:"managed_credential,omitempty"` |
| 49 | 49 | } |
| 50 | 50 | |
| 51 | 新增:type macLoginLease struct { | |
| 52 | 新增: request guestos.MacLoginRequest | |
| 53 | 新增: stopAccount func() bool | |
| 54 | 新增: stopService func() bool | |
| 55 | 新增:} | |
| 56 | 新增: | |
| 57 | 新增:func (l *macLoginLease) stop() { | |
| 58 | 新增: if l == nil { | |
| 59 | 新增: return | |
| 60 | 新增: } | |
| 61 | 新增: l.stopAccount() | |
| 62 | 新增: l.stopService() | |
| 63 | 新增:} | |
| 64 | 新增: | |
| 65 | 新增:func (s *Server) revokeMacLogin(session string) { | |
| 66 | 新增: s.mu.Lock() | |
| 67 | 新增: lease := s.macLoginLease | |
| 68 | 新增: if lease == nil || lease.request.Session != session { | |
| 69 | 新增: s.mu.Unlock() | |
| 70 | 新增: return | |
| 71 | 新增: } | |
| 72 | 新增: s.macLoginLease = nil | |
| 73 | 新增: s.mu.Unlock() | |
| 74 | 新增: lease.stop() | |
| 75 | 新增: connection, err := net.DialTimeout("unix", filepath.Join(s.instanceDir(), "cage-login.sock"), 2*time.Second) | |
| 76 | 新增: if err != nil { | |
| 77 | 新增: return | |
| 78 | 新增: } | |
| 79 | 新增: defer connection.Close() | |
| 80 | 新增: _ = connection.SetWriteDeadline(time.Now().Add(2 * time.Second)) | |
| 81 | 新增: _ = json.NewEncoder(connection).Encode(lease.request) | |
| 82 | 新增:} | |
| 83 | 新增: | |
| 84 | 新增:func (s *Server) trackMacLogin(epoch context.Context, input guestos.MacLoginRequest, result guestos.MacLoginReply) { | |
| 85 | 新增: if input.Action == "open" && result.Session != "" { | |
| 86 | 新增: lifetime := s.lifetimeContext() | |
| 87 | 新增: lease := &macLoginLease{request: guestos.MacLoginRequest{Action: "close", Session: result.Session, Setup: input.Setup, Maintenance: input.Maintenance}} | |
| 88 | 新增: s.mu.Lock() | |
| 89 | 新增: previous := s.macLoginLease | |
| 90 | 新增: s.macLoginLease = lease | |
| 91 | 新增: lease.stopAccount = context.AfterFunc(epoch, func() { s.revokeMacLogin(result.Session) }) | |
| 92 | 新增: lease.stopService = context.AfterFunc(lifetime, func() { s.revokeMacLogin(result.Session) }) | |
| 93 | 新增: s.mu.Unlock() | |
| 94 | 新增: previous.stop() | |
| 95 | 新增: return | |
| 96 | 新增: } | |
| 97 | 新增: if input.Action == "close" || result.Closed { | |
| 98 | 新增: s.mu.Lock() | |
| 99 | 新增: lease := s.macLoginLease | |
| 100 | 新增: if lease != nil && lease.request.Session == input.Session { | |
| 101 | 新增: s.macLoginLease = nil | |
| 102 | 新增: } else { | |
| 103 | 新增: lease = nil | |
| 104 | 新增: } | |
| 105 | 新增: s.mu.Unlock() | |
| 106 | 新增: lease.stop() | |
| 107 | 新增: } | |
| 108 | 新增:} | |
| 109 | 新增: | |
| 51 | 110 | func (s *Server) macSetupPermissions(ctx context.Context) (macSetupPermissions, error) { |
| 52 | 111 | var status macSetupPermissions |
| 53 | 112 | data, err := s.macOSWindowCall(ctx, macOSWindowRequest{Action: "setup-status"}) |
| @@ -88,6 +147,20 @@ func (s *Server) macOSLoginWindow(w http.ResponseWriter, r *http.Request) { | ||
| 88 | 147 | return |
| 89 | 148 | } |
| 90 | 149 | input.Setup = r.URL.Path == "/api/macos/first-setup" |
| 150 | 新增: if r.URL.Path == "/api/macos/maintenance" { | |
| 151 | 新增: if !guestos.ValidMacMaintenancePurpose(input.Maintenance) { | |
| 152 | 新增: http.Error(w, "请选择需要恢复的客机系统权限", http.StatusBadRequest) | |
| 153 | 新增: return | |
| 154 | 新增: } | |
| 155 | 新增: switch input.Action { | |
| 156 | 新增: case "open", "close", "frame", "click", "key", "scroll", "select-all", "fill-password": | |
| 157 | 新增: default: | |
| 158 | 新增: http.Error(w, "维护画面只接受窗口查看与局部输入", http.StatusBadRequest) | |
| 159 | 新增: return | |
| 160 | 新增: } | |
| 161 | 新增: } else { | |
| 162 | 新增: input.Maintenance = "" | |
| 163 | 新增: } | |
| 91 | 164 | if input.Setup && !s.macSetupPending() { |
| 92 | 165 | http.Error(w, "首次设置入口已关闭", http.StatusGone) |
| 93 | 166 | return |
| @@ -191,7 +264,12 @@ func (s *Server) macOSLoginWindow(w http.ResponseWriter, r *http.Request) { | ||
| 191 | 264 | http.Error(w, "无效的登录会话", 400) |
| 192 | 265 | return |
| 193 | 266 | } |
| 194 | 删除: ctx, cancel := context.WithTimeout(r.Context(), 8*time.Second) | |
| 267 | 新增: timeout := 8 * time.Second | |
| 268 | 新增: if input.Maintenance != "" { | |
| 269 | 新增: timeout = 15 * time.Second | |
| 270 | 新增: } | |
| 271 | 新增: epoch, _ := s.account.accessFor(true) | |
| 272 | 新增: ctx, cancel := context.WithTimeout(r.Context(), timeout) | |
| 195 | 273 | defer cancel() |
| 196 | 274 | var dial net.Dialer |
| 197 | 275 | conn, err := dial.DialContext(ctx, "unix", filepath.Join(s.instanceDir(), "cage-login.sock")) |
| @@ -200,17 +278,30 @@ func (s *Server) macOSLoginWindow(w http.ResponseWriter, r *http.Request) { | ||
| 200 | 278 | return |
| 201 | 279 | } |
| 202 | 280 | defer conn.Close() |
| 203 | 删除: _ = conn.SetDeadline(time.Now().Add(8 * time.Second)) | |
| 281 | 新增: stop := context.AfterFunc(ctx, func() { conn.Close() }) | |
| 282 | 新增: defer stop() | |
| 283 | 新增: _ = conn.SetDeadline(time.Now().Add(timeout)) | |
| 204 | 284 | var result guestos.MacLoginReply |
| 205 | 285 | if json.NewEncoder(conn).Encode(input) != nil || json.NewDecoder(io.LimitReader(conn, 6<<20)).Decode(&result) != nil { |
| 206 | 286 | http.Error(w, "客机登录界面无法响应", 503) |
| 207 | 287 | return |
| 208 | 288 | } |
| 289 | 新增: if input.Maintenance != "" && result.MaintenanceVersion != 1 { | |
| 290 | 新增: result = guestos.MacLoginReply{Closed: true, Recovery: "environment-restart", Error: "虚拟 Mac 运行器需要重新加载。请保存工作,在环境设置中停止并重新启动虚拟 Mac,再打开授权设置。"} | |
| 291 | 新增: } | |
| 292 | 新增: s.trackMacLogin(epoch, input, result) | |
| 293 | 新增: if input.Action == "open" && ctx.Err() != nil { | |
| 294 | 新增: s.revokeMacLogin(result.Session) | |
| 295 | 新增: return | |
| 296 | 新增: } | |
| 209 | 297 | if input.Setup && input.Action == "finish" && result.Error == "" && !s.macSetupPending() { |
| 210 | 298 | s.restoreProjectShares() |
| 211 | 299 | } |
| 212 | 300 | w.Header().Set("Cache-Control", "no-store") |
| 213 | 删除: jsonReply(w, result) | |
| 301 | 新增: w.Header().Set("Content-Type", "application/json; charset=utf-8") | |
| 302 | 新增: if err := json.NewEncoder(w).Encode(result); err != nil && input.Action == "open" { | |
| 303 | 新增: s.revokeMacLogin(result.Session) | |
| 304 | 新增: } | |
| 214 | 305 | } |
| 215 | 306 | |
| 216 | 307 | func (s *Server) macOSSetupAdminCommand(ctx context.Context) *exec.Cmd { |
| @@ -0,0 +1,158 @@ | ||
| 1 | 新增://go:build !windows | |
| 2 | 新增: | |
| 3 | 新增:package workbench | |
| 4 | 新增: | |
| 5 | 新增:import ( | |
| 6 | 新增: "encoding/json" | |
| 7 | 新增: "io" | |
| 8 | 新增: "net" | |
| 9 | 新增: "net/http" | |
| 10 | 新增: "net/http/httptest" | |
| 11 | 新增: "os" | |
| 12 | 新增: "path/filepath" | |
| 13 | 新增: "strings" | |
| 14 | 新增: "sync/atomic" | |
| 15 | 新增: "testing" | |
| 16 | 新增: "time" | |
| 17 | 新增: | |
| 18 | 新增: "github.com/sylvinus/agent-vm/internal/guestos" | |
| 19 | 新增:) | |
| 20 | 新增: | |
| 21 | 新增:type disconnectedMacLoginResponse struct{ *httptest.ResponseRecorder } | |
| 22 | 新增: | |
| 23 | 新增:func (disconnectedMacLoginResponse) Write([]byte) (int, error) { return 0, io.ErrClosedPipe } | |
| 24 | 新增: | |
| 25 | 新增:func TestMacOSMaintenanceHTTPBoundaryAndRunnerUpgrade(t *testing.T) { | |
| 26 | 新增: s := testServer(t) | |
| 27 | 新增: profile, err := os.MkdirTemp("/tmp", "cage-maint-") | |
| 28 | 新增: if err != nil { | |
| 29 | 新增: t.Fatal(err) | |
| 30 | 新增: } | |
| 31 | 新增: defer os.RemoveAll(profile) | |
| 32 | 新增: s.profile = profile | |
| 33 | 新增: s.macosGuest = &guestos.MacOSProfile{Instance: "mac", User: "trial"} | |
| 34 | 新增: s.ready = true | |
| 35 | 新增: if err := os.MkdirAll(s.instanceDir(), 0700); err != nil { | |
| 36 | 新增: t.Fatal(err) | |
| 37 | 新增: } | |
| 38 | 新增: listener, err := net.Listen("unix", filepath.Join(s.instanceDir(), "cage-login.sock")) | |
| 39 | 新增: if err != nil { | |
| 40 | 新增: t.Fatal(err) | |
| 41 | 新增: } | |
| 42 | 新增: requests := make(chan guestos.MacLoginRequest, 4) | |
| 43 | 新增: var legacy atomic.Bool | |
| 44 | 新增: done := make(chan struct{}) | |
| 45 | 新增: go func() { | |
| 46 | 新增: defer close(done) | |
| 47 | 新增: for { | |
| 48 | 新增: connection, err := listener.Accept() | |
| 49 | 新增: if err != nil { | |
| 50 | 新增: return | |
| 51 | 新增: } | |
| 52 | 新增: var input guestos.MacLoginRequest | |
| 53 | 新增: if json.NewDecoder(connection).Decode(&input) == nil { | |
| 54 | 新增: requests <- input | |
| 55 | 新增: response := guestos.MacLoginReply{MaintenanceVersion: 1, Session: "fixture-session"} | |
| 56 | 新增: if legacy.Load() { | |
| 57 | 新增: response = guestos.MacLoginReply{Closed: true} | |
| 58 | 新增: } | |
| 59 | 新增: _ = json.NewEncoder(connection).Encode(response) | |
| 60 | 新增: } | |
| 61 | 新增: _ = connection.Close() | |
| 62 | 新增: } | |
| 63 | 新增: }() | |
| 64 | 新增: defer func() { listener.Close(); <-done }() | |
| 65 | 新增: post := func(path, body string, trusted bool) *httptest.ResponseRecorder { | |
| 66 | 新增: t.Helper() | |
| 67 | 新增: request := httptest.NewRequest(http.MethodPost, s.origin+path, strings.NewReader(body)) | |
| 68 | 新增: request.Header.Set("Origin", s.origin) | |
| 69 | 新增: request.Header.Set("Content-Type", "application/json") | |
| 70 | 新增: request.AddCookie(&http.Cookie{Name: s.cookieName(), Value: s.session}) | |
| 71 | 新增: if trusted { | |
| 72 | 新增: request.AddCookie(&http.Cookie{Name: s.cookieName() + "-desktop", Value: trustedViewProof(s.token)}) | |
| 73 | 新增: } | |
| 74 | 新增: response := httptest.NewRecorder() | |
| 75 | 新增: s.handler().ServeHTTP(response, request) | |
| 76 | 新增: return response | |
| 77 | 新增: } | |
| 78 | 新增: body := `{"action":"fill-password","maintenance":"projects","session":"fixture-session","geometry":"verified-window","password":"untrusted-input","initial_setup":true}` | |
| 79 | 新增: if response := post("/api/macos/maintenance", body, false); response.Code != http.StatusForbidden { | |
| 80 | 新增: t.Fatalf("untrusted maintenance accepted: %d", response.Code) | |
| 81 | 新增: } | |
| 82 | 新增: if response := post("/api/macos/maintenance", body, true); response.Code != http.StatusOK { | |
| 83 | 新增: t.Fatalf("trusted maintenance failed: %d %s", response.Code, response.Body.String()) | |
| 84 | 新增: } | |
| 85 | 新增: input := <-requests | |
| 86 | 新增: if input.Setup || input.Password != "" || input.Maintenance != "projects" || input.Geometry != "verified-window" || input.Action != "fill-password" { | |
| 87 | 新增: t.Fatalf("maintenance boundary changed: action=%s purpose=%s setup=%v", input.Action, input.Maintenance, input.Setup) | |
| 88 | 新增: } | |
| 89 | 新增: for _, body := range []string{ | |
| 90 | 新增: `{"action":"open","maintenance":"desktop"}`, | |
| 91 | 新增: `{"action":"show-password","maintenance":"projects"}`, | |
| 92 | 新增: `{"action":"finish","maintenance":"projects"}`, | |
| 93 | 新增: } { | |
| 94 | 新增: if response := post("/api/macos/maintenance", body, true); response.Code != http.StatusBadRequest { | |
| 95 | 新增: t.Fatalf("invalid maintenance request returned %d", response.Code) | |
| 96 | 新增: } | |
| 97 | 新增: } | |
| 98 | 新增: if response := post("/api/macos/first-setup", `{"action":"open"}`, true); response.Code != http.StatusGone { | |
| 99 | 新增: t.Fatalf("completed initial setup was reopened: %d", response.Code) | |
| 100 | 新增: } | |
| 101 | 新增: legacy.Store(true) | |
| 102 | 新增: response := post("/api/macos/maintenance", `{"action":"open","maintenance":"projects"}`, true) | |
| 103 | 新增: <-requests | |
| 104 | 新增: var result guestos.MacLoginReply | |
| 105 | 新增: if response.Code != http.StatusOK || json.Unmarshal(response.Body.Bytes(), &result) != nil || result.Recovery != "environment-restart" || !result.Closed { | |
| 106 | 新增: t.Fatalf("old runner did not request a safe restart: %d %s", response.Code, response.Body.String()) | |
| 107 | 新增: } | |
| 108 | 新增: legacy.Store(false) | |
| 109 | 新增: if response := post("/api/macos/maintenance", `{"action":"open","maintenance":"projects"}`, true); response.Code != http.StatusOK { | |
| 110 | 新增: t.Fatal("could not open the current maintenance runner") | |
| 111 | 新增: } | |
| 112 | 新增: <-requests | |
| 113 | 新增: s.account.lock() | |
| 114 | 新增: select { | |
| 115 | 新增: case close := <-requests: | |
| 116 | 新增: if close.Action != "close" || close.Session != "fixture-session" || close.Maintenance != "projects" { | |
| 117 | 新增: t.Fatal("Cage lock did not revoke its maintenance session") | |
| 118 | 新增: } | |
| 119 | 新增: case <-time.After(3 * time.Second): | |
| 120 | 新增: t.Fatal("Cage lock retained the maintenance view") | |
| 121 | 新增: } | |
| 122 | 新增: | |
| 123 | 新增: // An open request can finish after the user locks and unlocks the workbench. | |
| 124 | 新增: // Its lease must belong to the account epoch that admitted that request. | |
| 125 | 新增: previousEpoch, _ := s.account.accessFor(true) | |
| 126 | 新增: s.account.mu.Lock() | |
| 127 | 新增: s.account.setKey(make([]byte, 32)) | |
| 128 | 新增: s.account.mu.Unlock() | |
| 129 | 新增: s.trackMacLogin(previousEpoch, | |
| 130 | 新增: guestos.MacLoginRequest{Action: "open", Maintenance: "projects"}, | |
| 131 | 新增: guestos.MacLoginReply{Session: "late-session"}) | |
| 132 | 新增: select { | |
| 133 | 新增: case close := <-requests: | |
| 134 | 新增: if close.Action != "close" || close.Session != "late-session" { | |
| 135 | 新增: t.Fatal("a late open response attached to the new account epoch") | |
| 136 | 新增: } | |
| 137 | 新增: case <-time.After(3 * time.Second): | |
| 138 | 新增: t.Fatal("a late open response retained its cancelled maintenance view") | |
| 139 | 新增: } | |
| 140 | 新增: | |
| 141 | 新增: request := httptest.NewRequest(http.MethodPost, s.origin+"/api/macos/maintenance", strings.NewReader(`{"action":"open","maintenance":"projects"}`)) | |
| 142 | 新增: request.Header.Set("Origin", s.origin) | |
| 143 | 新增: request.Header.Set("Content-Type", "application/json") | |
| 144 | 新增: request.AddCookie(&http.Cookie{Name: s.cookieName(), Value: s.session}) | |
| 145 | 新增: request.AddCookie(&http.Cookie{Name: s.cookieName() + "-desktop", Value: trustedViewProof(s.token)}) | |
| 146 | 新增: s.handler().ServeHTTP(disconnectedMacLoginResponse{httptest.NewRecorder()}, request) | |
| 147 | 新增: if open := <-requests; open.Action != "open" { | |
| 148 | 新增: t.Fatal("disconnected response fixture did not open the maintenance view") | |
| 149 | 新增: } | |
| 150 | 新增: select { | |
| 151 | 新增: case close := <-requests: | |
| 152 | 新增: if close.Action != "close" || close.Session != "fixture-session" { | |
| 153 | 新增: t.Fatal("a failed HTTP reply did not close its newly opened view") | |
| 154 | 新增: } | |
| 155 | 新增: case <-time.After(3 * time.Second): | |
| 156 | 新增: t.Fatal("an undelivered HTTP response retained its maintenance view") | |
| 157 | 新增: } | |
| 158 | 新增:} | |
| @@ -0,0 +1,85 @@ | ||
| 1 | 新增:package workbench | |
| 2 | 新增: | |
| 3 | 新增:import ( | |
| 4 | 新增: "bytes" | |
| 5 | 新增: "encoding/json" | |
| 6 | 新增: "net/http" | |
| 7 | 新增: "net/http/httptest" | |
| 8 | 新增: "strings" | |
| 9 | 新增: "sync/atomic" | |
| 10 | 新增: "testing" | |
| 11 | 新增: | |
| 12 | 新增: "golang.org/x/crypto/ssh" | |
| 13 | 新增:) | |
| 14 | 新增: | |
| 15 | 新增:func TestMacOSProjectWaitsForLoginAndRestoresAutomatically(t *testing.T) { | |
| 16 | 新增: var loggedIn atomic.Bool | |
| 17 | 新增: guest := newMacWorkspaceGuest(t, func(channel ssh.Channel, command string) (uint32, bool) { | |
| 18 | 新增: if strings.Contains(command, "/dev/console") && !loggedIn.Load() { | |
| 19 | 新增: return 73, true | |
| 20 | 新增: } | |
| 21 | 新增: return 0, false | |
| 22 | 新增: }) | |
| 23 | 新增: guest.approved.Store(true) | |
| 24 | 新增: s := guest.s | |
| 25 | 新增: s.restoreProjectShares() | |
| 26 | 新增: if len(s.projectErrors) != 1 || s.projectErrors[0].Recovery != "guest-login" || len(s.projectShares) != 0 { | |
| 27 | 新增: t.Fatalf("missing actionable login state: %+v", s.projectErrors) | |
| 28 | 新增: } | |
| 29 | 新增: data, _ := json.Marshal(map[string]any{"workspace": guest.hostPath, "add": false}) | |
| 30 | 新增: recorder := httptest.NewRecorder() | |
| 31 | 新增: request := httptest.NewRequest(http.MethodPost, "/api/projects/open", bytes.NewReader(data)) | |
| 32 | 新增: request.Header.Set("Content-Type", "application/json") | |
| 33 | 新增: s.openProject(recorder, request) | |
| 34 | 新增: if recorder.Code != http.StatusBadRequest || recorder.Header().Get("X-Cage-Recovery") != "guest-login" { | |
| 35 | 新增: t.Fatalf("project open lost its recovery action: %d %s", recorder.Code, recorder.Body.String()) | |
| 36 | 新增: } | |
| 37 | 新增: s.retryMacOSProjectShares(t.Context()) | |
| 38 | 新增: if len(s.projectShares) != 0 { | |
| 39 | 新增: t.Fatal("mount started before guest GUI login") | |
| 40 | 新增: } | |
| 41 | 新增: loggedIn.Store(true) | |
| 42 | 新增: s.retryMacOSProjectShares(t.Context()) | |
| 43 | 新增: defer s.closeProjectShares() | |
| 44 | 新增: if len(s.projectErrors) != 0 || s.projectShares[guest.hostPath] == nil { | |
| 45 | 新增: t.Fatalf("login did not restore the saved project: %+v", s.projectErrors) | |
| 46 | 新增: } | |
| 47 | 新增:} | |
| 48 | 新增: | |
| 49 | 新增:func TestMacOSProjectPrepareReportsSpecificRecovery(t *testing.T) { | |
| 50 | 新增: for _, sample := range []struct { | |
| 51 | 新增: exit uint32 | |
| 52 | 新增: recovery string | |
| 53 | 新增: }{ | |
| 54 | 新增: {73, "guest-login"}, {74, "environment-update"}, {76, "environment-restart"}, | |
| 55 | 新增: {77, "project-directory"}, {78, "project-directory"}, {79, "environment-update"}, {255, "project-retry"}, | |
| 56 | 新增: } { | |
| 57 | 新增: t.Run(sample.recovery, func(t *testing.T) { | |
| 58 | 新增: guest := newMacWorkspaceGuest(t, func(channel ssh.Channel, command string) (uint32, bool) { | |
| 59 | 新增: if strings.Contains(command, "/dev/console") { | |
| 60 | 新增: return sample.exit, true | |
| 61 | 新增: } | |
| 62 | 新增: return 0, false | |
| 63 | 新增: }) | |
| 64 | 新增: guest.s.restoreProjectShares() | |
| 65 | 新增: if len(guest.s.projectErrors) != 1 || guest.s.projectErrors[0].Recovery != sample.recovery { | |
| 66 | 新增: t.Fatalf("exit %d: %+v", sample.exit, guest.s.projectErrors) | |
| 67 | 新增: } | |
| 68 | 新增: }) | |
| 69 | 新增: } | |
| 70 | 新增:} | |
| 71 | 新增: | |
| 72 | 新增:func TestMacOSFailedUnsavedProjectDoesNotBecomeBackgroundGrant(t *testing.T) { | |
| 73 | 新增: guest := newMacWorkspaceGuest(t, func(channel ssh.Channel, command string) (uint32, bool) { | |
| 74 | 新增: if strings.Contains(command, "/dev/console") { | |
| 75 | 新增: return 73, true | |
| 76 | 新增: } | |
| 77 | 新增: return 0, false | |
| 78 | 新增: }) | |
| 79 | 新增: if _, err := guest.s.connectProject(t.TempDir(), true); err == nil { | |
| 80 | 新增: t.Fatal("expected the guest login precondition") | |
| 81 | 新增: } | |
| 82 | 新增: if len(guest.s.projectErrors) != 0 || len(guest.s.projectShares) != 0 { | |
| 83 | 新增: t.Fatal("an uncompleted new project was scheduled for background sharing") | |
| 84 | 新增: } | |
| 85 | 新增:} | |
| @@ -13,6 +13,7 @@ import ( | ||
| 13 | 13 | "time" |
| 14 | 14 | |
| 15 | 15 | "github.com/google/uuid" |
| 16 | 新增: "github.com/sylvinus/agent-vm/internal/diagnostics" | |
| 16 | 17 | |
| 17 | 18 | "al.essio.dev/pkg/shellescape" |
| 18 | 19 | ) |
| @@ -25,9 +26,27 @@ func macOSProjectPath(user, hostDirectory string) string { | ||
| 25 | 26 | // A mount which is ready in FSKit can still be unreadable by the guest app. |
| 26 | 27 | // Keep the live restricted connection while macOS waits for the user's folder |
| 27 | 28 | // approval; do not accept an APFS directory or a stale mount as this project. |
| 28 | 删除:var errMacOSProjectApproval = errors.New("请在虚拟 Mac 的项目授权窗口中选中此项目,然后重新打开") | |
| 29 | 新增:var errMacOSProjectApproval = &projectShareError{Recovery: "project-approval", Message: "请在 Cage 显示的客机授权窗口中允许此项目,然后验证授权。"} | |
| 29 | 30 | |
| 30 | 31 | const macProjectAgent = "/Applications/CageProjectAccess.app/Contents/MacOS/CageProjectAccess" |
| 32 | 新增:const macProjectLoginCheck = `test "$(/usr/bin/stat -f %u /dev/console)" = "$(/usr/bin/id -u)" && /bin/launchctl print "gui/$(/usr/bin/id -u)" >/dev/null 2>&1` | |
| 33 | 新增: | |
| 34 | 新增:func macOSProjectPrepareError(err error) error { | |
| 35 | 新增: var exit *exec.ExitError | |
| 36 | 新增: if errors.As(err, &exit) { | |
| 37 | 新增: switch exit.ExitCode() { | |
| 38 | 新增: case 73: | |
| 39 | 新增: return &projectShareError{Recovery: "guest-login", Message: "请先登录虚拟 Mac 的客机账户。登录完成后,Cage 会自动连接项目。"} | |
| 40 | 新增: case 74, 79: | |
| 41 | 新增: return &projectShareError{Recovery: "environment-update", Message: "客机项目共享组件尚未就绪。请同步环境组件,完成后重新连接项目。"} | |
| 42 | 新增: case 76: | |
| 43 | 新增: return &projectShareError{Recovery: "environment-restart", Message: "此项目还保留着旧的客机挂载。请保存工作,在环境设置中停止并重新启动虚拟 Mac,再连接项目。"} | |
| 44 | 新增: case 77, 78: | |
| 45 | 新增: return &projectShareError{Recovery: "project-directory", Message: "客机的项目挂载位置包含文件、链接或权限异常。请先保留其中的文件,再通过诊断记录检查该位置。"} | |
| 46 | 新增: } | |
| 47 | 新增: } | |
| 48 | 新增: return &projectShareError{Recovery: "project-retry", Message: "工作台暂时无法连接客机项目服务。连接恢复后会自动重试,也可以重新连接项目。"} | |
| 49 | 新增:} | |
| 31 | 50 | |
| 32 | 51 | func (s *Server) ensureMacOSProjectShare(hostDir string) error { |
| 33 | 52 | ctx, cancel := context.WithTimeout(s.operationContext(), 18*time.Second) |
| @@ -86,27 +105,33 @@ func (s *Server) ensureMacOSProjectShare(hostDir string) error { | ||
| 86 | 105 | func (s *Server) startMacOSProjectShare(ctx context.Context, hostDir, guestDir string) (*projectShare, error) { |
| 87 | 106 | folder := shellescape.Quote(guestDir) |
| 88 | 107 | |
| 89 | 删除: prepare := `set -e; test "$(/usr/bin/stat -f %u /dev/console)" = "$(/usr/bin/id -u)" || exit 73 | |
| 90 | 删除: /bin/launchctl print "gui/$(/usr/bin/id -u)" >/dev/null 2>&1 || exit 73 | |
| 91 | 删除: test -x /usr/local/libexec/cage-sshfs; test -x ` + macProjectAgent + | |
| 92 | 删除: `; p=` + folder + `; if /sbin/mount | /usr/bin/grep -Fq " on $p ("; then exit 2; fi; for d in "$HOME/Cage" "$HOME/Cage/Projects" "$p"; do | |
| 93 | 删除: test ! -L "$d"; if test ! -e "$d"; then /bin/mkdir -m 700 "$d"; fi; test -d "$d" && test -O "$d" || exit 1 | |
| 94 | 删除: done; test -z "$(/bin/ls -A "$p")"; /usr/bin/open -gj -a /Applications/CageProjectAccess.app` | |
| 95 | 删除: _, err := s.guestControl(ctx, prepare, "macos-project-prepare") | |
| 108 | 新增: prepare := `set -e; ` + macProjectLoginCheck + ` || exit 73 | |
| 109 | 新增: test -x /usr/local/libexec/cage-sshfs && test -x ` + macProjectAgent + ` || exit 74 | |
| 110 | 新增: p=` + folder + `; if /sbin/mount | /usr/bin/grep -Fq " on $p ("; then exit 76; fi; for d in "$HOME/Cage" "$HOME/Cage/Projects" "$p"; do | |
| 111 | 新增: test ! -L "$d" || exit 77; if test ! -e "$d"; then /bin/mkdir -m 700 "$d" || exit 78; fi; test -d "$d" && test -O "$d" || exit 77 | |
| 112 | 新增: done; entries=$(/bin/ls -A "$p") || exit 78; test -z "$entries" || exit 77 | |
| 113 | 新增: /usr/bin/open -gj -a /Applications/CageProjectAccess.app || exit 79 | |
| 114 | 新增: if /usr/local/libexec/cage-sshfs --help 2>/dev/null | /usr/bin/grep -Fq 'cage_openwith='; then | |
| 115 | 新增: printf '\nCAGE_SSHFS_OPENWITH\n' | |
| 116 | 新增: fi` | |
| 117 | 新增: capabilities, err := s.guestControl(ctx, prepare, "macos-project-prepare") | |
| 96 | 118 | if err != nil { |
| 97 | 删除: var exit *exec.ExitError | |
| 98 | 删除: if errors.As(err, &exit) && exit.ExitCode() == 73 { | |
| 99 | 删除: return nil, errors.New("请先在虚拟 Mac 中登录已绑定的普通账户,再重新打开项目") | |
| 100 | 删除: } | |
| 101 | 删除: return nil, errors.New("无法准备 macOS 实时挂载。请检查客机项目助手、SSHFS 及目标目录") | |
| 119 | 新增: return nil, macOSProjectPrepareError(err) | |
| 102 | 120 | } |
| 103 | 121 | command := "exec /usr/local/libexec/cage-sshfs " + shellescape.Quote(":"+filepath.ToSlash(hostDir)) + " " + folder + |
| 104 | 122 | " -f -o slave,backend=fskit,nodev,nosuid,dir_cache=no" |
| 105 | 删除: conn, err := startProjectTransport(s.sshCommand(s.lifetimeContext(), "-T", s.sshTarget(), "--", command), hostDir) | |
| 123 | 新增: if strings.Contains("\n"+string(capabilities)+"\n", "\nCAGE_SSHFS_OPENWITH\n") { | |
| 124 | 新增: metadata := path.Join("/Users", s.macosGuest.User, "Library/Caches/dev.cage.GuestClaudeWindow/openwith.data") | |
| 125 | 新增: command += " -o " + shellescape.Quote("cage_openwith="+metadata) | |
| 126 | 新增: } | |
| 127 | 新增: cmd := s.sshCommand(s.lifetimeContext(), "-T", s.sshTarget(), "--", command) | |
| 128 | 新增: stderr := &fileControlStderr{} | |
| 129 | 新增: cmd.Stderr = stderr | |
| 130 | 新增: conn, err := startProjectTransport(cmd, hostDir) | |
| 106 | 131 | if err != nil { |
| 107 | 132 | return nil, err |
| 108 | 133 | } |
| 109 | 删除: | |
| 134 | 新增: conn.stderr = stderr | |
| 110 | 135 | return conn, nil |
| 111 | 136 | } |
| 112 | 137 | |
| @@ -151,10 +176,60 @@ func (s *Server) probeMacOSProject(ctx context.Context, hostDir, guestDir string | ||
| 151 | 176 | } |
| 152 | 177 | select { |
| 153 | 178 | case <-ctx.Done(): |
| 154 | 删除: return errors.New("虚拟 Mac 的项目助手未能读回宿主项目文件") | |
| 179 | 新增: return &projectShareError{Recovery: "project-retry", Message: "客机项目助手尚未确认此文件夹可用。请重新连接项目,持续失败时可查看诊断记录。"} | |
| 155 | 180 | case <-share.done: |
| 156 | 删除: return errors.New("macOS 实时挂载已断开,请检查客机文件系统扩展授权") | |
| 181 | 新增: if share.stderr != nil && len(share.stderr.data) > 0 { | |
| 182 | 新增: message := string(share.stderr.data) | |
| 183 | 新增: _ = diagnostics.New(s.profile).Record("warn", "macos-project-mount", message) | |
| 184 | 新增: if strings.Contains(strings.ToLower(message), "not enabled") { | |
| 185 | 新增: return &projectShareError{Recovery: "filesystem-permission", Message: "虚拟 Mac 的文件系统扩展尚未启用。请在客机系统设置中同时启用 macFUSE 和 macFUSE (local),然后重新连接项目。"} | |
| 186 | 新增: } | |
| 187 | 新增: } | |
| 188 | 新增: return &projectShareError{Recovery: "project-retry", Message: "客机文件共享连接已中断。Cage 会自动重试,持续失败时可查看诊断记录。"} | |
| 157 | 189 | case <-time.After(200 * time.Millisecond): |
| 158 | 190 | } |
| 159 | 191 | } |
| 160 | 192 | } |
| 193 | 新增: | |
| 194 | 新增:// The existing lifecycle monitor retries only failed or ended project streams. | |
| 195 | 新增:// A login check precedes retry so startup does not repeatedly open guest prompts. | |
| 196 | 新增:func (s *Server) retryMacOSProjectShares(ctx context.Context) { | |
| 197 | 新增: s.mu.Lock() | |
| 198 | 新增: pending := make(map[string]bool) | |
| 199 | 新增: waitingForLogin := false | |
| 200 | 新增: waitingForFilesystem := false | |
| 201 | 新增: for _, failure := range s.projectErrors { | |
| 202 | 新增: if failure.Recovery == "guest-login" || failure.Recovery == "project-retry" || failure.Recovery == "filesystem-permission" { | |
| 203 | 新增: pending[failure.Path] = true | |
| 204 | 新增: waitingForLogin = waitingForLogin || failure.Recovery == "guest-login" | |
| 205 | 新增: waitingForFilesystem = waitingForFilesystem || failure.Recovery == "filesystem-permission" | |
| 206 | 新增: } | |
| 207 | 新增: } | |
| 208 | 新增: for path, share := range s.projectShares { | |
| 209 | 新增: select { | |
| 210 | 新增: case <-share.done: | |
| 211 | 新增: pending[path] = true | |
| 212 | 新增: default: | |
| 213 | 新增: } | |
| 214 | 新增: } | |
| 215 | 新增: retryAt := s.macProjectsRetryAt | |
| 216 | 新增: s.mu.Unlock() | |
| 217 | 新增: if len(pending) == 0 || (!waitingForLogin && time.Now().Before(retryAt)) { | |
| 218 | 新增: return | |
| 219 | 新增: } | |
| 220 | 新增: if _, err := s.guest(ctx, "set -e; "+macProjectLoginCheck+" || exit 73"); err != nil { | |
| 221 | 新增: for path := range pending { | |
| 222 | 新增: s.setProjectError(path, macOSProjectPrepareError(err)) | |
| 223 | 新增: } | |
| 224 | 新增: return | |
| 225 | 新增: } | |
| 226 | 新增: s.mu.Lock() | |
| 227 | 新增: s.macProjectsRetryAt = time.Now().Add(15 * time.Second) | |
| 228 | 新增: s.mu.Unlock() | |
| 229 | 新增: if waitingForFilesystem && s.checkMacOSSetupProjects(s.lifetimeContext()) != nil { | |
| 230 | 新增: return | |
| 231 | 新增: } | |
| 232 | 新增: for path := range pending { | |
| 233 | 新增: _ = s.ensureProjectShare(path) | |
| 234 | 新增: } | |
| 235 | 新增:} | |
| @@ -60,6 +60,7 @@ func macOSWindowClientRequest(input macOSWindowRequest, keepAlive bool) macOSWin | ||
| 60 | 60 | input.Project, input.Nonce = "", "" |
| 61 | 61 | input.Phone, input.PhoneToken = nil, "" |
| 62 | 62 | input.Transfer, input.Path, input.Error = "", "", "" |
| 63 | 新增: input.IDs = nil | |
| 63 | 64 | input.Wait, input.Binary, input.KeepAlive = false, false, keepAlive |
| 64 | 65 | if input.Action != "ime" { |
| 65 | 66 | input.Sequence = 0 |
| @@ -266,6 +266,53 @@ func (g *macWorkspaceGuest) execute(channel ssh.Channel, command string) uint32 | ||
| 266 | 266 | } |
| 267 | 267 | } |
| 268 | 268 | |
| 269 | 新增:func TestMacOSProjectOpenWithRequiresSSHFSCapability(t *testing.T) { | |
| 270 | 新增: for _, capability := range []struct { | |
| 271 | 新增: name string | |
| 272 | 新增: output string | |
| 273 | 新增: want bool | |
| 274 | 新增: }{ | |
| 275 | 新增: {name: "legacy helper"}, | |
| 276 | 新增: {name: "supported helper", output: "\nCAGE_SSHFS_OPENWITH\n", want: true}, | |
| 277 | 新增: {name: "unrelated diagnostic", output: "unknown CAGE_SSHFS_OPENWITH option\n"}, | |
| 278 | 新增: } { | |
| 279 | 新增: t.Run(capability.name, func(t *testing.T) { | |
| 280 | 新增: mounts := make(chan string, 1) | |
| 281 | 新增: guest := newMacWorkspaceGuest(t, func(channel ssh.Channel, command string) (uint32, bool) { | |
| 282 | 新增: if strings.Contains(command, "CAGE_SSHFS_OPENWITH") { | |
| 283 | 新增: fmt.Fprint(channel, capability.output) | |
| 284 | 新增: return 0, true | |
| 285 | 新增: } | |
| 286 | 新增: if strings.HasPrefix(command, "exec /usr/local/libexec/cage-sshfs ") { | |
| 287 | 新增: mounts <- command | |
| 288 | 新增: } | |
| 289 | 新增: return 0, false | |
| 290 | 新增: }) | |
| 291 | 新增: guest.approved.Store(true) | |
| 292 | 新增: if err := guest.s.ensureMacOSProjectShare(guest.hostPath); err != nil { | |
| 293 | 新增: t.Fatal(err) | |
| 294 | 新增: } | |
| 295 | 新增: command := <-mounts | |
| 296 | 新增: args, err := shellquote.Split(command) | |
| 297 | 新增: if err != nil { | |
| 298 | 新增: t.Fatal(err) | |
| 299 | 新增: } | |
| 300 | 新增: found := false | |
| 301 | 新增: for _, arg := range args { | |
| 302 | 新增: if strings.HasPrefix(arg, "cage_openwith=") { | |
| 303 | 新增: found = true | |
| 304 | 新增: if arg != "cage_openwith=/Users/cage/Library/Caches/dev.cage.GuestClaudeWindow/openwith.data" { | |
| 305 | 新增: t.Fatalf("unexpected guest metadata path %q", arg) | |
| 306 | 新增: } | |
| 307 | 新增: } | |
| 308 | 新增: } | |
| 309 | 新增: if found != capability.want { | |
| 310 | 新增: t.Fatalf("OpenWith option present = %v, want %v", found, capability.want) | |
| 311 | 新增: } | |
| 312 | 新增: }) | |
| 313 | 新增: } | |
| 314 | 新增:} | |
| 315 | 新增: | |
| 269 | 316 | func TestMacOSDefaultWorkspaceUsesApprovedSharedProject(t *testing.T) { |
| 270 | 317 | guest := newMacWorkspaceGuest(t) |
| 271 | 318 | s := guest.s |
| @@ -117,6 +117,14 @@ func desktopDownloadFailure(reason string) error { | ||
| 117 | 117 | return errors.New("Claude Desktop 下载文件在传输中发生变化,请重新下载") |
| 118 | 118 | case "desktop_download_unavailable", "desktop_download_transfer_invalid": |
| 119 | 119 | return errors.New("Claude Desktop 下载文件已不可用,请确认客机已解锁后重新下载") |
| 120 | 新增: case "desktop_download_limit": | |
| 121 | 新增: return errors.New("待保存的 Claude Desktop 文件过多,请先完成现有下载后重试") | |
| 122 | 新增: case "file_open_target_changed": | |
| 123 | 新增: return errors.New("文件或 Claude 窗口已变化,请回到原窗口重新打开文件") | |
| 124 | 新增: case "file_open_request_invalid", "file_open_request_unavailable": | |
| 125 | 新增: return errors.New("文件打开请求已失效,请确认客机已解锁后重新操作") | |
| 126 | 新增: case "file_open_request_limit": | |
| 127 | 新增: return errors.New("正在处理的文件打开请求过多,请稍后重试") | |
| 120 | 128 | default: |
| 121 | 129 | return nil |
| 122 | 130 | } |
| @@ -41,6 +41,7 @@ func serveDesktopDownloadFixture(input io.Reader, output io.Writer, directory st | ||
| 41 | 41 | for reader.Scan() { |
| 42 | 42 | var request struct { |
| 43 | 43 | Action, ID, Transfer string |
| 44 | 新增: IDs []string | |
| 44 | 45 | Sequence int |
| 45 | 46 | KeepAlive bool |
| 46 | 47 | } |
| @@ -62,6 +63,25 @@ func serveDesktopDownloadFixture(input io.Reader, output io.Writer, directory st | ||
| 62 | 63 | switch request.Action { |
| 63 | 64 | case "files-poll": |
| 64 | 65 | reply = map[string]any{"available": true, "uploads": []any{}, "opens": []any{}, "downloads": []browserDownloadInfo{record}} |
| 66 | 新增: if _, err := os.Stat(filepath.Join(directory, "supports-ack")); err == nil { | |
| 67 | 新增: var item map[string]any | |
| 68 | 新增: _ = json.Unmarshal(data, &item) | |
| 69 | 新增: _, err := os.Stat(filepath.Join(directory, "acknowledged")) | |
| 70 | 新增: item["acknowledged"] = err == nil | |
| 71 | 新增: reply = map[string]any{"available": true, "downloadAck": true, "downloads": []any{item}} | |
| 72 | 新增: } | |
| 73 | 新增: case "files-download-ack": | |
| 74 | 新增: if len(request.IDs) != 1 || request.IDs[0] != record.ID { | |
| 75 | 新增: return | |
| 76 | 新增: } | |
| 77 | 新增: if _, err := os.Stat(filepath.Join(directory, "fail-ack")); err == nil { | |
| 78 | 新增: reply = map[string]string{"error": "desktop_download_manifest_failed"} | |
| 79 | 新增: } else { | |
| 80 | 新增: if os.WriteFile(filepath.Join(directory, "acknowledged"), nil, 0600) != nil { | |
| 81 | 新增: return | |
| 82 | 新增: } | |
| 83 | 新增: reply = map[string]bool{"ok": true} | |
| 84 | 新增: } | |
| 65 | 85 | case "files-download-open": |
| 66 | 86 | if request.ID != record.ID { |
| 67 | 87 | return |
| @@ -95,6 +115,69 @@ func serveDesktopDownloadFixture(input io.Reader, output io.Writer, directory st | ||
| 95 | 115 | } |
| 96 | 116 | } |
| 97 | 117 | |
| 118 | 新增:func TestNativeDesktopDownloadAcknowledgesOnlySavedHostReceipts(t *testing.T) { | |
| 119 | 新增: for _, system := range []string{"macos", "windows"} { | |
| 120 | 新增: t.Run(system, func(t *testing.T) { | |
| 121 | 新增: s, record, _, directory := nativeDesktopDownloadFixture(t, system) | |
| 122 | 新增: poll := func() { | |
| 123 | 新增: t.Helper() | |
| 124 | 新增: response := windowsBrowserRequestForTest(s, http.MethodGet, "/api/input/files/desktop/requests", nil) | |
| 125 | 新增: if response.Code != http.StatusOK { | |
| 126 | 新增: t.Fatalf("poll failed: %d %s", response.Code, response.Body.String()) | |
| 127 | 新增: } | |
| 128 | 新增: } | |
| 129 | 新增: marker := func(name string) { | |
| 130 | 新增: t.Helper() | |
| 131 | 新增: if err := os.WriteFile(filepath.Join(directory, name), nil, 0600); err != nil { | |
| 132 | 新增: t.Fatal(err) | |
| 133 | 新增: } | |
| 134 | 新增: } | |
| 135 | 新增: ackCount := func() int { | |
| 136 | 新增: t.Helper() | |
| 137 | 新增: trace, err := os.ReadFile(filepath.Join(directory, "requests.jsonl")) | |
| 138 | 新增: if err != nil { | |
| 139 | 新增: t.Fatal(err) | |
| 140 | 新增: } | |
| 141 | 新增: return bytes.Count(trace, []byte(`"action":"files-download-ack"`)) | |
| 142 | 新增: } | |
| 143 | 新增: marker("supports-ack") | |
| 144 | 新增: poll() | |
| 145 | 新增: if ackCount() != 0 { | |
| 146 | 新增: t.Fatal("guest-only saved state acknowledged before a durable host copy") | |
| 147 | 新增: } | |
| 148 | 新增: if _, err := s.downloadInfo(t.Context(), record.ID); err != nil { | |
| 149 | 新增: t.Fatal(err) | |
| 150 | 新增: } | |
| 151 | 新增: marker("fail-ack") | |
| 152 | 新增: poll() | |
| 153 | 新增: if ackCount() != 1 { | |
| 154 | 新增: t.Fatal("saved host receipt was not acknowledged") | |
| 155 | 新增: } | |
| 156 | 新增: if saved, err := readSavedDownload(s.profile, record.ID); err != nil || saved.Path == "" { | |
| 157 | 新增: t.Fatal("failed acknowledgment invalidated the host receipt", err) | |
| 158 | 新增: } | |
| 159 | 新增: if err := os.Remove(filepath.Join(directory, "fail-ack")); err != nil { | |
| 160 | 新增: t.Fatal(err) | |
| 161 | 新增: } | |
| 162 | 新增: poll() | |
| 163 | 新增: if ackCount() != 2 { | |
| 164 | 新增: t.Fatal("failed acknowledgment was not retried") | |
| 165 | 新增: } | |
| 166 | 新增: poll() | |
| 167 | 新增: if ackCount() != 2 { | |
| 168 | 新增: t.Fatal("acknowledged guest record generated another acknowledgment") | |
| 169 | 新增: } | |
| 170 | 新增: if err := os.Remove(filepath.Join(directory, "supports-ack")); err != nil { | |
| 171 | 新增: t.Fatal(err) | |
| 172 | 新增: } | |
| 173 | 新增: poll() | |
| 174 | 新增: if ackCount() != 2 { | |
| 175 | 新增: t.Fatal("legacy helper received an unsupported acknowledgment") | |
| 176 | 新增: } | |
| 177 | 新增: }) | |
| 178 | 新增: } | |
| 179 | 新增:} | |
| 180 | 新增: | |
| 98 | 181 | func nativeDesktopDownloadFixture(t *testing.T, system string) (*Server, browserDownloadInfo, []byte, string) { |
| 99 | 182 | t.Helper() |
| 100 | 183 | directory := t.TempDir() |
| @@ -15,6 +15,7 @@ func nativeWorkbenchRoute(path string) bool { | ||
| 15 | 15 | "/api/appearance", "/api/favorites", "/api/status", "/api/settings", "/api/settings/probe", |
| 16 | 16 | "/api/start", "/api/stop", "/api/restore", "/api/host/git", "/api/projects/open", "/api/projects/directories", |
| 17 | 17 | "/api/environment/initialization", "/api/environment/versions", "/api/environment/update", "/api/environment/tools", "/api/environment/resources", "/api/environment/storage", |
| 18 | 新增: "/api/environment/storage/recover", | |
| 18 | 19 | "/api/terminals", "/api/claude-accounts", "/api/cli/sessions", "/api/proxy", "/api/vault", "/api/vault/browser", "/api/client/browser-extensions", |
| 19 | 20 | "/api/input", "/api/input/text", "/api/input/image", "/api/input/paste/start", "/api/input/paste/cancel", "/api/input/files/start", "/api/input/files/finish", "/api/input/files/cancel", "/api/input/files/directory", "/api/input/files/download-retry", |
| 20 | 21 | "/api/vnc", "/api/vnc-credentials", "/api/audio", "/api/clipboard", "/api/clipboard/copy", "/api/clipboard/files", |
| @@ -0,0 +1,73 @@ | ||
| 1 | 新增:package workbench | |
| 2 | 新增: | |
| 3 | 新增:import ( | |
| 4 | 新增: "encoding/json" | |
| 5 | 新增: "net/http" | |
| 6 | 新增: "os" | |
| 7 | 新增: "path/filepath" | |
| 8 | 新增: "testing" | |
| 9 | 新增: | |
| 10 | 新增: "github.com/sylvinus/agent-vm/internal/guestos" | |
| 11 | 新增:) | |
| 12 | 新增: | |
| 13 | 新增:func TestNativeStatusExposesMaintenanceFailureAndRestoreRoute(t *testing.T) { | |
| 14 | 新增: for _, system := range []string{guestos.MacOS, guestos.Windows11} { | |
| 15 | 新增: t.Run(system, func(t *testing.T) { | |
| 16 | 新增: s := testServer(t) | |
| 17 | 新增: if system == guestos.MacOS { | |
| 18 | 新增: s.macosGuest = &guestos.MacOSProfile{Instance: "mac"} | |
| 19 | 新增: } else { | |
| 20 | 新增: s.windowsGuest = &guestos.WindowsProfile{} | |
| 21 | 新增: } | |
| 22 | 新增: cfg, err := loadConfig(s.configPath) | |
| 23 | 新增: if err != nil { | |
| 24 | 新增: t.Fatal(err) | |
| 25 | 新增: } | |
| 26 | 新增: previous := savedProfile{Config: cfg, Preferences: s.preferences} | |
| 27 | 新增: previous.Preferences.Keyboard = "native" | |
| 28 | 新增: if err := writePrivate(filepath.Join(s.profile, "previous-profile.json"), previous); err != nil { | |
| 29 | 新增: t.Fatal(err) | |
| 30 | 新增: } | |
| 31 | 新增: s.guestUpdateRequired = true | |
| 32 | 新增: s.guestUpdateError = "同步未完成,可保留原环境重试" | |
| 33 | 新增: response := windowsBrowserRequestForTest(s, "GET", "/api/status", nil) | |
| 34 | 新增: var state struct { | |
| 35 | 新增: System string `json:"guest_system"` | |
| 36 | 新增: CanRestore bool `json:"can_restore"` | |
| 37 | 新增: UpdateRequired bool `json:"environment_update_required"` | |
| 38 | 新增: UpdateError string `json:"environment_update_error"` | |
| 39 | 新增: LocalStorage bool `json:"local_vm_storage"` | |
| 40 | 新增: } | |
| 41 | 新增: if response.Code != http.StatusOK || json.Unmarshal(response.Body.Bytes(), &state) != nil { | |
| 42 | 新增: t.Fatal(response.Code, response.Body.String()) | |
| 43 | 新增: } | |
| 44 | 新增: if state.System != system || !state.CanRestore || !state.UpdateRequired || state.UpdateError != s.guestUpdateError || !state.LocalStorage { | |
| 45 | 新增: t.Fatalf("native state diverged from executable operations: %+v", state) | |
| 46 | 新增: } | |
| 47 | 新增: if storage := windowsBrowserRequestForTest(s, "GET", "/api/environment/storage", nil); storage.Code != http.StatusOK { | |
| 48 | 新增: t.Fatal("advertised storage operation rejected by route", storage.Code, storage.Body.String()) | |
| 49 | 新增: } | |
| 50 | 新增: response = windowsBrowserRequestForTest(s, "POST", "/api/restore", []byte(`{}`)) | |
| 51 | 新增: if response.Code != http.StatusOK { | |
| 52 | 新增: t.Fatal("advertised restore rejected by native route", response.Code, response.Body.String()) | |
| 53 | 新增: } | |
| 54 | 新增: job := awaitJobIdle(t, &s.jobs) | |
| 55 | 新增: if job.Kind != "restore" { | |
| 56 | 新增: t.Fatal("restore did not use the common operation", job) | |
| 57 | 新增: } | |
| 58 | 新增: var restored Preferences | |
| 59 | 新增: data, err := os.ReadFile(filepath.Join(s.profile, "workbench.json")) | |
| 60 | 新增: if err != nil { | |
| 61 | 新增: t.Fatal(err) | |
| 62 | 新增: } | |
| 63 | 新增: if err := json.Unmarshal(data, &restored); err != nil { | |
| 64 | 新增: t.Fatal(err) | |
| 65 | 新增: } | |
| 66 | 新增: if restored.Keyboard != "native" { | |
| 67 | 新增: t.Fatal("normal restore route did not persist the prior preference") | |
| 68 | 新增: } | |
| 69 | 新增: // There is deliberately no VM in this fixture. Starting it may fail, | |
| 70 | 新增: // after the requested configuration has reached its normal entry point. | |
| 71 | 新增: }) | |
| 72 | 新增: } | |
| 73 | 新增:} | |
| @@ -90,6 +90,10 @@ func (s *Server) openProject(w http.ResponseWriter, r *http.Request) { | ||
| 90 | 90 | } |
| 91 | 91 | } |
| 92 | 92 | if err != nil { |
| 93 | 新增: var failure *projectShareError | |
| 94 | 新增: if errors.As(err, &failure) && failure.Recovery != "" { | |
| 95 | 新增: w.Header().Set("X-Cage-Recovery", failure.Recovery) | |
| 96 | 新增: } | |
| 93 | 97 | requestError(w, err) |
| 94 | 98 | return |
| 95 | 99 | } |
| @@ -132,6 +136,7 @@ type projectShare struct { | ||
| 132 | 136 | approval string |
| 133 | 137 | approvalTimer *time.Timer |
| 134 | 138 | windowsProject *windowsProjectBinding |
| 139 | 新增: stderr *fileControlStderr | |
| 135 | 140 | } |
| 136 | 141 | |
| 137 | 142 | func (p *projectShare) stop() { |
| @@ -193,15 +198,18 @@ func (s *Server) ensureProjectShare(path string) (returned error) { | ||
| 193 | 198 | if closing { |
| 194 | 199 | return errJobsClosed |
| 195 | 200 | } |
| 196 | 删除: defer func() { | |
| 197 | 删除: if returned == nil { | |
| 198 | 删除: s.clearProjectError(path) | |
| 199 | 删除: } | |
| 200 | 删除: }() | |
| 201 | 201 | path, err := validateWorkspace(path, s.profile) |
| 202 | 202 | if err != nil { |
| 203 | 203 | return err |
| 204 | 204 | } |
| 205 | 新增: defer func() { | |
| 206 | 新增: if returned != nil { | |
| 207 | 新增: if _, err := s.projectWorkspace(path); err != nil { | |
| 208 | 新增: return | |
| 209 | 新增: } | |
| 210 | 新增: } | |
| 211 | 新增: s.setProjectError(path, returned) | |
| 212 | 新增: }() | |
| 205 | 213 | if s.windowsGuest != nil { |
| 206 | 214 | return s.ensureWindowsProjectShare(path) |
| 207 | 215 | } |
| @@ -280,19 +288,38 @@ type sharedProjects struct { | ||
| 280 | 288 | } |
| 281 | 289 | |
| 282 | 290 | type projectShareError struct { |
| 283 | 删除: Path string `json:"path"` | |
| 284 | 删除: Message string `json:"message"` | |
| 291 | 新增: Path string `json:"path"` | |
| 292 | 新增: Message string `json:"message"` | |
| 293 | 新增: Recovery string `json:"recovery,omitempty"` | |
| 294 | 新增:} | |
| 295 | 新增: | |
| 296 | 新增:func (e *projectShareError) Error() string { return e.Message } | |
| 297 | 新增: | |
| 298 | 新增:func projectShareFailure(path string, err error) projectShareError { | |
| 299 | 新增: value := projectShareError{Path: path, Message: err.Error()} | |
| 300 | 新增: var failure *projectShareError | |
| 301 | 新增: if errors.As(err, &failure) { | |
| 302 | 新增: value.Recovery = failure.Recovery | |
| 303 | 新增: } | |
| 304 | 新增: return value | |
| 285 | 305 | } |
| 286 | 306 | |
| 287 | 删除:func (s *Server) clearProjectError(path string) { | |
| 307 | 新增:func (s *Server) setProjectError(path string, err error) { | |
| 288 | 308 | s.mu.Lock() |
| 289 | 309 | defer s.mu.Unlock() |
| 290 | 310 | for i, failure := range s.projectErrors { |
| 291 | 311 | if failure.Path == path { |
| 292 | 删除: s.projectErrors = append(s.projectErrors[:i], s.projectErrors[i+1:]...) | |
| 312 | 新增: if err == nil { | |
| 313 | 新增: s.projectErrors = append(s.projectErrors[:i], s.projectErrors[i+1:]...) | |
| 314 | 新增: } else { | |
| 315 | 新增: s.projectErrors[i] = projectShareFailure(path, err) | |
| 316 | 新增: } | |
| 293 | 317 | return |
| 294 | 318 | } |
| 295 | 319 | } |
| 320 | 新增: if err != nil { | |
| 321 | 新增: s.projectErrors = append(s.projectErrors, projectShareFailure(path, err)) | |
| 322 | 新增: } | |
| 296 | 323 | } |
| 297 | 324 | |
| 298 | 325 | // The saved directory grants are the project list. Include the default and |
| @@ -384,7 +411,7 @@ func (s *Server) restoreProjectShares() { | ||
| 384 | 411 | var failures []projectShareError |
| 385 | 412 | for _, path := range saved.Paths { |
| 386 | 413 | if err := s.ensureProjectShare(path); err != nil { |
| 387 | 删除: failures = append(failures, projectShareError{Path: path, Message: err.Error()}) | |
| 414 | 新增: failures = append(failures, projectShareFailure(path, err)) | |
| 388 | 415 | } else if err := s.rememberSharedProject(path); err != nil { |
| 389 | 416 | failures = append(failures, projectShareError{Path: path, Message: "项目已连接,但未能保存项目记录:" + err.Error()}) |
| 390 | 417 | } |
| @@ -2,6 +2,7 @@ package workbench | ||
| 2 | 2 | |
| 3 | 3 | import ( |
| 4 | 4 | "context" |
| 5 | 新增: "errors" | |
| 5 | 6 | "fmt" |
| 6 | 7 | "net/http" |
| 7 | 8 | "net/http/httptest" |
| @@ -9,6 +10,38 @@ import ( | ||
| 9 | 10 | "testing" |
| 10 | 11 | ) |
| 11 | 12 | |
| 13 | 新增:func TestWindowsMaintenanceFailureRetainsStageForBothJobs(t *testing.T) { | |
| 14 | 新增: cause := errors.New("synthetic maintenance process failed") | |
| 15 | 新增: for _, action := range []string{"修复 Windows 系统助手", "更新原生客机组件"} { | |
| 16 | 新增: for _, test := range []struct { | |
| 17 | 新增: phase, reason, next string | |
| 18 | 新增: }{ | |
| 19 | 新增: {"AUTHORIZATION_CANCELED", "已取消 Windows 管理员授权", "系统授权窗口"}, | |
| 20 | 新增: {"AUTHORIZATION", "授权窗口未能打开", "本机 Cage"}, | |
| 21 | 新增: {"VALIDATION", "绑定或组件清单", "重新安装完整 Cage"}, | |
| 22 | 新增: {"HOST_MANAGER", "系统管理助手安装", "修复系统助手"}, | |
| 23 | 新增: {"GUEST_CONNECTION", "客机连接未完成", "管理员账户"}, | |
| 24 | 新增: {"GUEST_COMPONENTS", "客机组件安装", "同步环境组件"}, | |
| 25 | 新增: {"HOST_RELAY", "主机连接组件更新", "占用连接组件"}, | |
| 26 | 新增: {"PACKAGE_PREPARATION", "组件包准备", "系统盘空间"}, | |
| 27 | 新增: {"FAILED", "Windows 维护未完成", "导出诊断包"}, | |
| 28 | 新增: } { | |
| 29 | 新增: t.Run(action+"/"+test.phase, func(t *testing.T) { | |
| 30 | 新增: output := "CAGE_WINDOWS_MAINTENANCE_" + test.phase + " synthetic stage\naccess is denied token=private-stage-secret" | |
| 31 | 新增: err := executionFailure(action, cause, output) | |
| 32 | 新增: for _, want := range []string{action, test.reason, test.next} { | |
| 33 | 新增: if !strings.Contains(err.Error(), want) { | |
| 34 | 新增: t.Fatalf("lost maintenance stage or next action %q: %v", want, err) | |
| 35 | 新增: } | |
| 36 | 新增: } | |
| 37 | 新增: if !errors.Is(err, cause) || strings.Contains(err.Error(), "private-stage-secret") { | |
| 38 | 新增: t.Fatal("stage handling lost the cause or exposed arbitrary process output", err) | |
| 39 | 新增: } | |
| 40 | 新增: }) | |
| 41 | 新增: } | |
| 42 | 新增: } | |
| 43 | 新增:} | |
| 44 | 新增: | |
| 12 | 45 | func TestBrowserFailureExplainsOperationAndKnownCause(t *testing.T) { |
| 13 | 46 | for _, tc := range []struct { |
| 14 | 47 | status int |
| @@ -271,7 +271,7 @@ func (s *Server) routeRemote(w http.ResponseWriter, r *http.Request) bool { | ||
| 271 | 271 | http.NotFound(w, r) |
| 272 | 272 | return true |
| 273 | 273 | } |
| 274 | 删除: if remote && r.URL.Path == "/api/environment/storage" { | |
| 274 | 新增: if remote && (r.URL.Path == "/api/environment/storage" || r.URL.Path == "/api/environment/storage/recover") { | |
| 275 | 275 | http.Error(w, "请在虚拟机所在电脑上调整环境存储", http.StatusForbidden) |
| 276 | 276 | return true |
| 277 | 277 | } |
| @@ -134,6 +134,9 @@ func (s *Server) guestControl(ctx context.Context, script, diagnosticSource stri | ||
| 134 | 134 | return data, nil |
| 135 | 135 | } |
| 136 | 136 | func (s *Server) attach() error { |
| 137 | 新增: if err := s.requireStorageReady(); err != nil { | |
| 138 | 新增: return err | |
| 139 | 新增: } | |
| 137 | 140 | if s.windowsGuest != nil { |
| 138 | 141 | return s.attachWindowsGuest() |
| 139 | 142 | } |
| @@ -304,6 +307,9 @@ func (s *Server) runCage(args ...string) error { | ||
| 304 | 307 | return nil |
| 305 | 308 | } |
| 306 | 309 | func (s *Server) startEnvironment(syncTimezone bool) error { |
| 310 | 新增: if err := s.requireStorageReady(); err != nil { | |
| 311 | 新增: return err | |
| 312 | 新增: } | |
| 307 | 313 | if s.macosGuest != nil { |
| 308 | 314 | return s.startMacOSGuest() |
| 309 | 315 | } |
| @@ -622,6 +628,10 @@ func (s *Server) apply(v savedProfile, validate bool) error { | ||
| 622 | 628 | func (s *Server) monitorNetworkTick() { |
| 623 | 629 | timing := s.startMonitorTiming() |
| 624 | 630 | defer s.recordMonitorTiming("network", timing) |
| 631 | 新增: if s.storageRecoveryStatus().Required { | |
| 632 | 新增: timing.result = "storage_recovery_pending" | |
| 633 | 新增: return | |
| 634 | 新增: } | |
| 625 | 635 | if s.macSetupPending() { |
| 626 | 636 | timing.result = "setup_pending" |
| 627 | 637 | return |
| @@ -41,6 +41,8 @@ func TestRunCageExplainsCommonFailure(t *testing.T) { | ||
| 41 | 41 | {"curl: (28) Operation timed out", "超时"}, |
| 42 | 42 | {"E: No space left on device", "空间不足"}, |
| 43 | 43 | {"curl: (60) certificate verify failed", "证书验证"}, |
| 44 | 新增: {"CAGE_WINDOWS_MAINTENANCE_HOST_MANAGER synthetic stage token=private-error-secret", "系统管理助手安装未完成"}, | |
| 45 | 新增: {"CAGE_WINDOWS_MAINTENANCE_GUEST_CONNECTION synthetic stage token=private-error-secret", "客机连接未完成"}, | |
| 44 | 46 | {"unrecognized failure token=private-error-secret", "退出码 7"}, |
| 45 | 47 | } { |
| 46 | 48 | t.Run(tc.want, func(t *testing.T) { |
| @@ -45,6 +45,8 @@ type Server struct { | ||
| 45 | 45 | agentNativeQueue agentNativeQueue |
| 46 | 46 | macSetupProjectsChecked time.Time |
| 47 | 47 | macSetupProjectsAttempt time.Time |
| 48 | 新增: macProjectsRetryAt time.Time | |
| 49 | 新增: macLoginLease *macLoginLease | |
| 48 | 50 | macosGuest *guestos.MacOSProfile |
| 49 | 51 | macResources macOSResourceObserver |
| 50 | 52 | windowsGuest *guestos.WindowsProfile |
| @@ -65,6 +67,7 @@ type Server struct { | ||
| 65 | 67 | guestManifest *cage.GuestManifest |
| 66 | 68 | guestUpdateRequired bool |
| 67 | 69 | guestUpdateError string |
| 70 | 新增: storageRecoveryError string | |
| 68 | 71 | closing bool |
| 69 | 72 | shutdown func() |
| 70 | 73 | claudeAccounts claudeAccountManager |
| @@ -198,7 +201,7 @@ func serve(configPath string, clientOnly bool, fullConfigPath string) (returned | ||
| 198 | 201 | defer s.remote.close() |
| 199 | 202 | if workload { |
| 200 | 203 | if err = guestos.RecoverWindowsStorage(context.Background(), profile); err != nil { |
| 201 | 删除: return err | |
| 204 | 新增: s.failStorageRecovery(err) | |
| 202 | 205 | } |
| 203 | 206 | s.macosGuest, err = guestos.LoadMacOSProfile(profile) |
| 204 | 207 | if err != nil { |
| @@ -235,8 +238,13 @@ func serve(configPath string, clientOnly bool, fullConfigPath string) (returned | ||
| 235 | 238 | s.preferences.AutoLanguage = false |
| 236 | 239 | _ = json.Unmarshal(b, &s.preferences) |
| 237 | 240 | } |
| 238 | 删除: if err = s.prepareEnvironment(); err != nil { | |
| 239 | 删除: return err | |
| 241 | 新增: if !s.storageRecoveryStatus().Required { | |
| 242 | 新增: if err = s.prepareEnvironment(); err != nil { | |
| 243 | 新增: if s.windowsGuest == nil { | |
| 244 | 新增: return err | |
| 245 | 新增: } | |
| 246 | 新增: s.failStorageRecovery(err) | |
| 247 | 新增: } | |
| 240 | 248 | } |
| 241 | 249 | // Invalid intent keeps the gate paused and its error visible in status. |
| 242 | 250 | s.restoreNetworkIntent() |
| @@ -382,6 +390,7 @@ func (s *Server) handler() http.Handler { | ||
| 382 | 390 | mux.HandleFunc("POST /api/environment/guest-systems/activate", s.guestInstallation) |
| 383 | 391 | mux.HandleFunc("GET /api/environment/storage", s.environmentStorage) |
| 384 | 392 | mux.HandleFunc("POST /api/environment/storage", s.environmentStorage) |
| 393 | 新增: mux.HandleFunc("POST /api/environment/storage/recover", s.recoverEnvironmentStorage) | |
| 385 | 394 | mux.HandleFunc("GET /api/environment/resources", s.resourceStatus) |
| 386 | 395 | mux.HandleFunc("POST /api/environment/resources", s.applyResources) |
| 387 | 396 | mux.HandleFunc("POST /api/environment/update", s.updateEnvironment) |
| @@ -447,6 +456,7 @@ func (s *Server) handler() http.Handler { | ||
| 447 | 456 | if s.macosGuest != nil { |
| 448 | 457 | mux.HandleFunc("POST /api/macos/first-setup", s.macOSLoginWindow) |
| 449 | 458 | mux.HandleFunc("POST /api/macos/login", s.macOSLoginWindow) |
| 459 | 新增: mux.HandleFunc("POST /api/macos/maintenance", s.macOSLoginWindow) | |
| 450 | 460 | s.registerMacOSClaudeRoutes(mux) |
| 451 | 461 | s.registerMacOSBrowserRoutes(mux) |
| 452 | 462 | mux.HandleFunc("POST /api/macos/project-approval", s.macOSProjectApproval) |
| @@ -581,6 +591,12 @@ func (s *Server) handler() http.Handler { | ||
| 581 | 591 | panic(failure) |
| 582 | 592 | } |
| 583 | 593 | }() |
| 594 | 新增: if !storageRecoveryRoute(r) { | |
| 595 | 新增: if err := s.requireStorageReady(); err != nil { | |
| 596 | 新增: http.Error(w, err.Error(), http.StatusConflict) | |
| 597 | 新增: return | |
| 598 | 新增: } | |
| 599 | 新增: } | |
| 584 | 600 | mux.ServeHTTP(w, r) |
| 585 | 601 | }) |
| 586 | 602 | } |
| @@ -615,7 +631,7 @@ func requestError(w http.ResponseWriter, err error) { | ||
| 615 | 631 | http.Error(w, err.Error(), http.StatusBadRequest) |
| 616 | 632 | } |
| 617 | 633 | func (s *Server) status(w http.ResponseWriter, r *http.Request) { |
| 618 | 删除: if s.windowsGuest != nil { | |
| 634 | 新增: if s.windowsGuest != nil && !s.storageRecoveryStatus().Required { | |
| 619 | 635 | s.refreshWindowsComponents() |
| 620 | 636 | } |
| 621 | 637 | projects, err := s.projectPaths() |
| @@ -637,8 +653,10 @@ func (s *Server) status(w http.ResponseWriter, r *http.Request) { | ||
| 637 | 653 | view := map[string]any{ |
| 638 | 654 | "projects": projects, "ready": s.ready, "vm_running": running, |
| 639 | 655 | "workspace": s.workspaceLocked(), "environment_workspace": s.workspaceLocked() == s.environmentDir(), "environment_directory": s.environmentDir(), |
| 640 | 删除: "local_vm_storage": s.localVMStorage(), "project_error": projectError, "project_errors": s.projectErrors, | |
| 641 | 删除: "keyboard": s.preferences.Keyboard, "auto_timezone": s.preferences.AutoTimezone, "job": s.jobs.snapshot(), | |
| 656 | 新增: "environment_identity_directory": cage.EnvironmentIdentityDir(s.profile), | |
| 657 | 新增: "local_vm_storage": s.localVMStorage(), "project_error": projectError, "project_errors": s.projectErrors, | |
| 658 | 新增: "storage_recovery": s.storageRecoveryStatusLocked(), | |
| 659 | 新增: "keyboard": s.preferences.Keyboard, "auto_timezone": s.preferences.AutoTimezone, "job": s.jobs.snapshot(), | |
| 642 | 660 | "location": s.location, "network_error": s.currentNetworkErrorLocked(), "can_restore": e == nil, |
| 643 | 661 | "safety": s.safety, "environment_update_required": s.guestUpdateRequired, "environment_update_error": s.guestUpdateError, |
| 644 | 662 | } |
| @@ -810,6 +828,10 @@ func (s *Server) stop(w http.ResponseWriter, r *http.Request) { | ||
| 810 | 828 | } |
| 811 | 829 | |
| 812 | 830 | func (s *Server) requestStop(w http.ResponseWriter, logout bool) { |
| 831 | 新增: if err := s.requireStorageReady(); err != nil { | |
| 832 | 新增: http.Error(w, err.Error(), http.StatusConflict) | |
| 833 | 新增: return | |
| 834 | 新增: } | |
| 813 | 835 | for _, name := range []string{cage.InstanceName(s.profile, s.environmentDir()), "base-building"} { |
| 814 | 836 | if owner := cage.InstanceJobID(filepath.Join(s.profile, "state"), name); owner != "" { |
| 815 | 837 | _ = cage.RequestJobStop(s.profile, owner) |
| @@ -54,24 +54,13 @@ func environmentWorkspace(profile string) string { return cage.EnvironmentDir(pr | ||
| 54 | 54 | func guestPath(path string) string { return paths.Guest(paths.Host(path)) } |
| 55 | 55 | |
| 56 | 56 | func (s *Server) prepareEnvironment() error { |
| 57 | 删除: if s.windowsGuest != nil { | |
| 58 | 删除: path := s.environmentDir() | |
| 59 | 删除: if err := os.MkdirAll(path, 0700); err != nil { | |
| 60 | 删除: return err | |
| 61 | 删除: } | |
| 62 | 删除: if _, err := validateWorkspace(path, s.profile); err != nil { | |
| 63 | 删除: return err | |
| 64 | 删除: } | |
| 65 | 删除: if err := writePrivate(filepath.Join(s.profile, "environment.json"), map[string]string{"directory": path}); err != nil { | |
| 66 | 删除: return err | |
| 67 | 删除: } | |
| 68 | 删除: s.mu.Lock() | |
| 69 | 删除: if s.preferences.Workspace == "" { | |
| 70 | 删除: s.preferences.Workspace = s.environmentDir() | |
| 71 | 删除: } | |
| 72 | 删除: s.mu.Unlock() | |
| 73 | 删除: return nil | |
| 57 | 新增: record, err := cage.LoadEnvironmentRecord(s.profile) | |
| 58 | 新增: if err != nil { | |
| 59 | 新增: return err | |
| 74 | 60 | } |
| 61 | 新增: s.mu.Lock() | |
| 62 | 新增: p := s.preferences | |
| 63 | 新增: s.mu.Unlock() | |
| 75 | 64 | path := environmentWorkspace(s.profile) |
| 76 | 65 | // Promote an existing installation's VM once, preserving its disk and login state. |
| 77 | 66 | if _, err := os.Stat(filepath.Join(s.profile, "environment.json")); os.IsNotExist(err) { |
| @@ -85,17 +74,33 @@ func (s *Server) prepareEnvironment() error { | ||
| 85 | 74 | if err := os.MkdirAll(path, 0700); err != nil { |
| 86 | 75 | return err |
| 87 | 76 | } |
| 88 | 删除: path, err := validateWorkspace(path, s.profile) | |
| 77 | 新增: previous := path | |
| 78 | 新增: path, err = validateWorkspace(path, s.profile) | |
| 89 | 79 | if err != nil { |
| 90 | 删除: return err | |
| 80 | 新增: // Older independent profiles generated their default workspace inside | |
| 81 | 新增: // the default profile. Keep its files and VM identity while selecting a | |
| 82 | 新增: // shareable workspace through the same admission used for every project. | |
| 83 | 新增: path, err = validateWorkspace(p.Workspace, s.profile) | |
| 84 | 新增: if p.Workspace == "" || err != nil { | |
| 85 | 新增: path = cage.DefaultEnvironmentDir(s.profile) | |
| 86 | 新增: if err = os.MkdirAll(path, 0700); err != nil { | |
| 87 | 新增: return err | |
| 88 | 新增: } | |
| 89 | 新增: path, err = validateWorkspace(path, s.profile) | |
| 90 | 新增: if err != nil { | |
| 91 | 新增: return err | |
| 92 | 新增: } | |
| 93 | 新增: } | |
| 94 | 新增: if record.IdentityDirectory == "" { | |
| 95 | 新增: record.IdentityDirectory = previous | |
| 96 | 新增: } | |
| 91 | 97 | } |
| 92 | 删除: if err = writePrivate(filepath.Join(s.profile, "environment.json"), map[string]string{"directory": path}); err != nil { | |
| 98 | 新增: record.Directory = path | |
| 99 | 新增: if err = writePrivate(filepath.Join(s.profile, "environment.json"), record); err != nil { | |
| 93 | 100 | return err |
| 94 | 101 | } |
| 95 | 删除: s.mu.Lock() | |
| 96 | 删除: p := s.preferences | |
| 97 | 删除: s.mu.Unlock() | |
| 98 | 删除: if p.Workspace == "" { | |
| 102 | 新增: if p.Workspace == "" || paths.Equal(paths.Host(p.Workspace), paths.Host(previous)) || | |
| 103 | 新增: record.IdentityDirectory != "" && paths.Equal(paths.Host(p.Workspace), paths.Host(record.IdentityDirectory)) { | |
| 99 | 104 | p.Workspace = path |
| 100 | 105 | } |
| 101 | 106 | if err := writePrivate(filepath.Join(s.profile, "workbench.json"), p); err != nil { |
| @@ -9,7 +9,6 @@ import ( | ||
| 9 | 9 | "io" |
| 10 | 10 | "net/http" |
| 11 | 11 | "net/url" |
| 12 | 删除: "os" | |
| 13 | 12 | "os/exec" |
| 14 | 13 | "path/filepath" |
| 15 | 14 | "slices" |
| @@ -494,8 +493,8 @@ func readClipboardArchive(input io.Reader) ([]string, error) { | ||
| 494 | 493 | |
| 495 | 494 | // A tar EOF only ends the archive, not the guest process. Drain the HTTP body |
| 496 | 495 | // before checking the producer's completion trailer or publishing local paths. |
| 497 | 删除:func receiveClipboardArchive(response *http.Response) ([]string, error) { | |
| 498 | 删除: paths, err := readClipboardArchive(response.Body) | |
| 496 | 新增:func receiveClipboardArchive(response *http.Response, cache clipboardfiles.CacheStore) (clipboardfiles.CachedSelection, error) { | |
| 497 | 新增: selection, err := cache.Read(response.Body) | |
| 499 | 498 | if err == nil { |
| 500 | 499 | _, err = io.Copy(io.Discard, response.Body) |
| 501 | 500 | } |
| @@ -503,12 +502,12 @@ func receiveClipboardArchive(response *http.Response) ([]string, error) { | ||
| 503 | 502 | err = errors.New("剪贴板文件传递中断,请重新复制") |
| 504 | 503 | } |
| 505 | 504 | if err != nil { |
| 506 | 删除: if len(paths) != 0 { | |
| 507 | 删除: _ = os.RemoveAll(filepath.Dir(paths[0])) | |
| 505 | 新增: if selection.ID != "" { | |
| 506 | 新增: _ = cache.Release(selection.ID) | |
| 508 | 507 | } |
| 509 | 删除: return nil, err | |
| 508 | 新增: return clipboardfiles.CachedSelection{}, err | |
| 510 | 509 | } |
| 511 | 删除: return paths, nil | |
| 510 | 新增: return selection, nil | |
| 512 | 511 | } |
| 513 | 512 | |
| 514 | 513 | // Native helpers stream bytes directly, keeping host paths out of the WebView. |
| @@ -571,16 +570,11 @@ func ClipboardFilesForConnection(configPath, connectionID, operation string, arg | ||
| 571 | 570 | return nil, errors.New("剪贴板文件传递失败,请重新复制") |
| 572 | 571 | } |
| 573 | 572 | if method == "GET" { |
| 574 | 删除: paths, err := receiveClipboardArchive(response) | |
| 575 | 删除: if err != nil { | |
| 576 | 删除: return nil, err | |
| 577 | 删除: } | |
| 578 | 删除: selection, err := cache.Register(paths) | |
| 573 | 新增: selection, err := receiveClipboardArchive(response, cache) | |
| 579 | 574 | if err != nil { |
| 580 | 删除: _ = os.RemoveAll(filepath.Dir(paths[0])) | |
| 581 | 575 | return nil, err |
| 582 | 576 | } |
| 583 | 删除: return map[string]any{"paths": paths, "cache_id": selection.ID}, nil | |
| 577 | 新增: return map[string]any{"paths": selection.Paths, "cache_id": selection.ID}, nil | |
| 584 | 578 | } |
| 585 | 579 | var result map[string]any |
| 586 | 580 | err = json.NewDecoder(io.LimitReader(response.Body, 65537)).Decode(&result) |
| @@ -15,6 +15,7 @@ import ( | ||
| 15 | 15 | "time" |
| 16 | 16 | |
| 17 | 17 | "github.com/gorilla/websocket" |
| 18 | 新增: "github.com/sylvinus/agent-vm/internal/clipboardfiles" | |
| 18 | 19 | "github.com/sylvinus/agent-vm/internal/guestos" |
| 19 | 20 | ) |
| 20 | 21 | |
| @@ -94,12 +95,14 @@ func TestClipboardReceiveRequiresProducerCompletion(t *testing.T) { | ||
| 94 | 95 | t.Fatal(err) |
| 95 | 96 | } |
| 96 | 97 | defer response.Body.Close() |
| 97 | 删除: paths, err := receiveClipboardArchive(response) | |
| 98 | 新增: cache := clipboardfiles.CacheStore{Directory: filepath.Join(t.TempDir(), "records")} | |
| 99 | 新增: selection, err := receiveClipboardArchive(response, cache) | |
| 100 | 新增: paths := selection.Paths | |
| 98 | 101 | if status == "ok" { |
| 99 | 102 | if err != nil || len(paths) != 1 { |
| 100 | 103 | t.Fatalf("completed transfer failed: %v", err) |
| 101 | 104 | } |
| 102 | 删除: defer os.RemoveAll(filepath.Dir(paths[0])) | |
| 105 | 新增: defer cache.Release(selection.ID) | |
| 103 | 106 | data, _ := os.ReadFile(paths[0]) |
| 104 | 107 | if string(data) != "complete bytes" { |
| 105 | 108 | t.Fatal("file content changed") |
| @@ -117,7 +120,8 @@ func TestClipboardReceiveRequiresProducerCompletion(t *testing.T) { | ||
| 117 | 120 | } |
| 118 | 121 | // Losing the connection before all file bytes arrive must not create a file. |
| 119 | 122 | response := &http.Response{Body: io.NopCloser(bytes.NewReader(archive.Bytes()[:520])), Trailer: http.Header{"X-Cage-Clipboard-Status": {"ok"}}} |
| 120 | 删除: if paths, err := receiveClipboardArchive(response); err == nil || len(paths) != 0 { | |
| 123 | 新增: cache := clipboardfiles.CacheStore{Directory: filepath.Join(t.TempDir(), "records")} | |
| 124 | 新增: if selection, err := receiveClipboardArchive(response, cache); err == nil || len(selection.Paths) != 0 { | |
| 121 | 125 | t.Fatal("truncated archive succeeded") |
| 122 | 126 | } |
| 123 | 127 | } |
| @@ -5,9 +5,12 @@ import ( | ||
| 5 | 5 | "fmt" |
| 6 | 6 | "net/http" |
| 7 | 7 | "os" |
| 8 | 新增: "runtime" | |
| 9 | 新增: "strings" | |
| 8 | 10 | |
| 9 | 11 | "github.com/sylvinus/agent-vm/internal/cage" |
| 10 | 12 | "github.com/sylvinus/agent-vm/internal/containerenv" |
| 13 | 新增: "github.com/sylvinus/agent-vm/internal/diagnostics" | |
| 11 | 14 | "github.com/sylvinus/agent-vm/internal/guestos" |
| 12 | 15 | ) |
| 13 | 16 | |
| @@ -15,18 +18,129 @@ func (s *Server) localVMStorage() bool { | ||
| 15 | 18 | return !s.clientOnly && !containerenv.Configured(s.profile) |
| 16 | 19 | } |
| 17 | 20 | |
| 21 | 新增:type storageRecoveryView struct { | |
| 22 | 新增: Required bool `json:"required"` | |
| 23 | 新增: Error string `json:"error,omitempty"` | |
| 24 | 新增: RepairAllowed bool `json:"repair_allowed"` | |
| 25 | 新增:} | |
| 26 | 新增: | |
| 27 | 新增:func (s *Server) storageRecoveryStatusLocked() storageRecoveryView { | |
| 28 | 新增: return storageRecoveryView{ | |
| 29 | 新增: Required: s.storageRecoveryError != "", Error: s.storageRecoveryError, | |
| 30 | 新增: RepairAllowed: s.storageRecoveryError != "" && s.windowsGuest != nil && runtime.GOOS == "windows", | |
| 31 | 新增: } | |
| 32 | 新增:} | |
| 33 | 新增: | |
| 34 | 新增:func (s *Server) storageRecoveryStatus() storageRecoveryView { | |
| 35 | 新增: s.mu.Lock() | |
| 36 | 新增: defer s.mu.Unlock() | |
| 37 | 新增: return s.storageRecoveryStatusLocked() | |
| 38 | 新增:} | |
| 39 | 新增: | |
| 40 | 新增:func (s *Server) requireStorageReady() error { | |
| 41 | 新增: state := s.storageRecoveryStatus() | |
| 42 | 新增: if state.Required { | |
| 43 | 新增: return fmt.Errorf("环境存储待恢复,请在设置中恢复后继续。%s", state.Error) | |
| 44 | 新增: } | |
| 45 | 新增: return nil | |
| 46 | 新增:} | |
| 47 | 新增: | |
| 48 | 新增:func (s *Server) failStorageRecovery(err error) error { | |
| 49 | 新增: s.mu.Lock() | |
| 50 | 新增: s.storageRecoveryError = err.Error() | |
| 51 | 新增: s.ready = false | |
| 52 | 新增: s.mu.Unlock() | |
| 53 | 新增: diagnostics.Log("error", "storage", "environment storage recovery failed: "+err.Error()) | |
| 54 | 新增: return err | |
| 55 | 新增:} | |
| 56 | 新增: | |
| 57 | 新增:// Recovery keeps local account access and host diagnostics available. Guest | |
| 58 | 新增:// reads can also create sessions, so admission names the host-only reads. | |
| 59 | 新增:func storageRecoveryRoute(r *http.Request) bool { | |
| 60 | 新增: path := r.URL.Path | |
| 61 | 新增: if !strings.HasPrefix(path, "/api/") || strings.HasPrefix(path, "/api/account/") || strings.HasPrefix(path, "/api/diagnostics") { | |
| 62 | 新增: return true | |
| 63 | 新增: } | |
| 64 | 新增: switch path { | |
| 65 | 新增: case "/api/account", "/api/session", "/api/launch", "/api/handoff", "/api/remote/manifest", "/api/environment/storage/recover": | |
| 66 | 新增: return true | |
| 67 | 新增: } | |
| 68 | 新增: if r.Method == http.MethodGet { | |
| 69 | 新增: switch path { | |
| 70 | 新增: case "/api/status", "/api/settings", "/api/appearance", "/api/favorites", "/api/proxy", "/api/agent/routes", "/api/environment/storage", "/api/environment/initialization": | |
| 71 | 新增: return true | |
| 72 | 新增: } | |
| 73 | 新增: } | |
| 74 | 新增: return false | |
| 75 | 新增:} | |
| 76 | 新增: | |
| 77 | 新增:func (s *Server) recoverEnvironmentStorage(w http.ResponseWriter, r *http.Request) { | |
| 78 | 新增: if !s.localVMStorage() { | |
| 79 | 新增: http.Error(w, "请在虚拟机所在电脑上恢复环境存储", http.StatusConflict) | |
| 80 | 新增: return | |
| 81 | 新增: } | |
| 82 | 新增: if !s.storageRecoveryStatus().Required { | |
| 83 | 新增: http.Error(w, "当前环境存储无需恢复", http.StatusConflict) | |
| 84 | 新增: return | |
| 85 | 新增: } | |
| 86 | 新增: var input struct { | |
| 87 | 新增: Repair bool `json:"repair"` | |
| 88 | 新增: } | |
| 89 | 新增: if !readJSON(w, r, &input) { | |
| 90 | 新增: return | |
| 91 | 新增: } | |
| 92 | 新增: s.launch(w, "storage-recovery", func() error { | |
| 93 | 新增: if input.Repair { | |
| 94 | 新增: s.setMessage("正在修复 Windows 系统助手,请完成系统授权…") | |
| 95 | 新增: kit, _ := s.nativeComponentKit() | |
| 96 | 新增: if err := guestos.RepairWindowsHostManager(s.operationContext(), s.profile, kit, s.jobs.execution(), s.jobs.execution()); err != nil { | |
| 97 | 新增: return s.failStorageRecovery(executionFailure("修复 Windows 系统助手", err, s.jobs.snapshot().Log)) | |
| 98 | 新增: } | |
| 99 | 新增: } | |
| 100 | 新增: s.setMessage("正在恢复环境存储并检查数据位置…") | |
| 101 | 新增: if err := guestos.RecoverWindowsStorage(s.operationContext(), s.profile); err != nil { | |
| 102 | 新增: return s.failStorageRecovery(err) | |
| 103 | 新增: } | |
| 104 | 新增: if _, err := cage.GetStorageLocation(s.profile); err != nil { | |
| 105 | 新增: return s.failStorageRecovery(err) | |
| 106 | 新增: } | |
| 107 | 新增: if s.windowsGuest != nil { | |
| 108 | 新增: binding, err := guestos.LoadWindowsProfile(s.profile) | |
| 109 | 新增: if err != nil { | |
| 110 | 新增: return s.failStorageRecovery(err) | |
| 111 | 新增: } | |
| 112 | 新增: if binding == nil || binding.VMID != s.windowsGuest.VMID || binding.GUIUserSID != s.windowsGuest.GUIUserSID { | |
| 113 | 新增: return s.failStorageRecovery(errors.New("Windows 客机绑定已改变,请重新打开原工作台后恢复")) | |
| 114 | 新增: } | |
| 115 | 新增: } | |
| 116 | 新增: if err := s.prepareEnvironment(); err != nil { | |
| 117 | 新增: return s.failStorageRecovery(err) | |
| 118 | 新增: } | |
| 119 | 新增: s.mu.Lock() | |
| 120 | 新增: s.storageRecoveryError = "" | |
| 121 | 新增: s.mu.Unlock() | |
| 122 | 新增: s.setMessage("环境存储已恢复,可以启动环境") | |
| 123 | 新增: return nil | |
| 124 | 新增: }) | |
| 125 | 新增:} | |
| 126 | 新增: | |
| 18 | 127 | func (s *Server) environmentStorage(w http.ResponseWriter, r *http.Request) { |
| 19 | 128 | if !s.localVMStorage() { |
| 20 | 129 | http.Error(w, "仅本机虚拟机支持调整存储位置", http.StatusConflict) |
| 21 | 130 | return |
| 22 | 131 | } |
| 23 | 132 | if r.Method == http.MethodGet { |
| 24 | 删除: if err := guestos.RecoverWindowsStorage(r.Context(), s.profile); err != nil { | |
| 25 | 删除: requestError(w, err) | |
| 133 | 新增: if recovery := s.storageRecoveryStatus(); recovery.Required { | |
| 134 | 新增: jsonReply(w, map[string]any{"recovery": recovery}) | |
| 26 | 135 | return |
| 27 | 136 | } |
| 28 | 137 | location, err := cage.GetStorageLocation(s.profile) |
| 29 | 138 | if err != nil { |
| 139 | 新增: if errors.Is(err, cage.ErrStorageRuntimeRecovery) { | |
| 140 | 新增: s.failStorageRecovery(err) | |
| 141 | 新增: jsonReply(w, map[string]any{"recovery": s.storageRecoveryStatus()}) | |
| 142 | 新增: return | |
| 143 | 新增: } | |
| 30 | 144 | requestError(w, err) |
| 31 | 145 | return |
| 32 | 146 | } |
| @@ -58,7 +172,7 @@ func (s *Server) environmentStorage(w http.ResponseWriter, r *http.Request) { | ||
| 58 | 172 | } |
| 59 | 173 | s.launch(w, "storage", func() error { |
| 60 | 174 | if err := guestos.RecoverWindowsStorage(s.operationContext(), s.profile); err != nil { |
| 61 | 删除: return err | |
| 175 | 新增: return s.failStorageRecovery(err) | |
| 62 | 176 | } |
| 63 | 177 | current, err := cage.GetStorageLocation(s.profile) |
| 64 | 178 | if err != nil { |
| @@ -89,6 +203,11 @@ func (s *Server) environmentStorage(w http.ResponseWriter, r *http.Request) { | ||
| 89 | 203 | _, err = cage.MoveStorageWithRuntime(s.operationContext(), s.profile, input.Directory, current, runtime, func(copied, total int64) { |
| 90 | 204 | s.setMessage(fmt.Sprintf("正在迁移环境数据 · %.1f / %.1f GiB", float64(copied)/(1<<30), float64(total)/(1<<30))) |
| 91 | 205 | }) |
| 206 | 新增: if err != nil { | |
| 207 | 新增: if _, recoveryErr := cage.GetStorageLocation(s.profile); errors.Is(recoveryErr, cage.ErrStorageRuntimeRecovery) { | |
| 208 | 新增: return s.failStorageRecovery(err) | |
| 209 | 新增: } | |
| 210 | 新增: } | |
| 92 | 211 | if errors.Is(err, os.ErrPermission) { |
| 93 | 212 | return errors.New("无法写入所选存储目录。请在当前页面选择有写入权限的本地文件夹后重试,已有数据已保留") |
| 94 | 213 | } |
| @@ -6,6 +6,7 @@ import ( | ||
| 6 | 6 | "path/filepath" |
| 7 | 7 | |
| 8 | 8 | "github.com/sylvinus/agent-vm/internal/cage" |
| 9 | 新增: "github.com/sylvinus/agent-vm/internal/guestos" | |
| 9 | 10 | "github.com/sylvinus/agent-vm/internal/mounts" |
| 10 | 11 | "github.com/sylvinus/agent-vm/internal/paths" |
| 11 | 12 | ) |
| @@ -40,6 +41,7 @@ func privateProjectDirectories(profile string) ([]string, error) { | ||
| 40 | 41 | return nil, err |
| 41 | 42 | } |
| 42 | 43 | directories = append(directories, profile) |
| 44 | 新增: directories = append(directories, guestos.WindowsPrivateStoragePaths()...) | |
| 43 | 45 | for _, directory := range directories { |
| 44 | 46 | physical, err := cage.StoragePhysicalPath(directory) |
| 45 | 47 | if os.IsNotExist(err) { |
| @@ -0,0 +1,406 @@ | ||
| 1 | 新增:package workbench | |
| 2 | 新增: | |
| 3 | 新增:import ( | |
| 4 | 新增: "archive/zip" | |
| 5 | 新增: "bytes" | |
| 6 | 新增: "context" | |
| 7 | 新增: "encoding/json" | |
| 8 | 新增: "errors" | |
| 9 | 新增: "fmt" | |
| 10 | 新增: "io" | |
| 11 | 新增: "net/http" | |
| 12 | 新增: "net/http/cookiejar" | |
| 13 | 新增: "net/url" | |
| 14 | 新增: "os" | |
| 15 | 新增: "os/exec" | |
| 16 | 新增: "path/filepath" | |
| 17 | 新增: "runtime" | |
| 18 | 新增: "strings" | |
| 19 | 新增: "testing" | |
| 20 | 新增: "time" | |
| 21 | 新增: | |
| 22 | 新增: "github.com/google/uuid" | |
| 23 | 新增: "github.com/sylvinus/agent-vm/internal/guestos" | |
| 24 | 新增:) | |
| 25 | 新增: | |
| 26 | 新增:func storageRecoveryServer(t *testing.T) *Server { | |
| 27 | 新增: t.Helper() | |
| 28 | 新增: s := testServer(t) | |
| 29 | 新增: workspace := filepath.Join(t.TempDir(), "workspace") | |
| 30 | 新增: if err := writePrivate(filepath.Join(s.profile, "environment.json"), map[string]string{"directory": workspace}); err != nil { | |
| 31 | 新增: t.Fatal(err) | |
| 32 | 新增: } | |
| 33 | 新增: instance := filepath.Join(s.profile, "state", "guest-os", "synthetic-vm") | |
| 34 | 新增: if err := os.MkdirAll(instance, 0700); err != nil { | |
| 35 | 新增: t.Fatal(err) | |
| 36 | 新增: } | |
| 37 | 新增: binding := guestos.WindowsProfile{ | |
| 38 | 新增: Version: 1, VMID: uuid.New(), GUIUserSID: "S-1-5-21-1-2-3-1001", | |
| 39 | 新增: InstanceDirectory: instance, RelayExecutable: filepath.Join(instance, "missing-relay.exe"), | |
| 40 | 新增: PairingFile: filepath.Join(instance, "synthetic-pairing.dpapi"), | |
| 41 | 新增: } | |
| 42 | 新增: if err := guestos.BindWindowsProfile(s.profile, binding); err != nil { | |
| 43 | 新增: t.Fatal(err) | |
| 44 | 新增: } | |
| 45 | 新增: s.windowsGuest = &binding | |
| 46 | 新增: return s | |
| 47 | 新增:} | |
| 48 | 新增: | |
| 49 | 新增:func storageRecoveryJournal(t *testing.T, s *Server) string { | |
| 50 | 新增: t.Helper() | |
| 51 | 新增: id := strings.Repeat("a", 32) | |
| 52 | 新增: target := filepath.Join(t.TempDir(), "destination") | |
| 53 | 新增: journal := filepath.Join(s.profile, "environment-storage-pending.json") | |
| 54 | 新增: if err := writePrivate(journal, map[string]any{ | |
| 55 | 新增: "Next": map[string]any{"Directory": target, "ID": id}, | |
| 56 | 新增: "Runtime": "windows-hyperv", | |
| 57 | 新增: "Transition": map[string]any{ | |
| 58 | 新增: "id": id, "source": filepath.Join(s.profile, "state"), | |
| 59 | 新增: "destination": filepath.Join(target, "state"), "backup": filepath.Join(s.profile, "state-backup-"+id), | |
| 60 | 新增: "state": map[string]any{ | |
| 61 | 新增: "profile": s.windowsGuest, "instance": s.windowsGuest.InstanceDirectory, | |
| 62 | 新增: "disk": map[string]any{"path": filepath.Join(s.windowsGuest.InstanceDirectory, "disk.vhdx"), "volume": 1, "file_id": 2}, | |
| 63 | 新增: }, | |
| 64 | 新增: }, | |
| 65 | 新增: }); err != nil { | |
| 66 | 新增: t.Fatal(err) | |
| 67 | 新增: } | |
| 68 | 新增: return journal | |
| 69 | 新增:} | |
| 70 | 新增: | |
| 71 | 新增:func TestStorageRecoveryKeepsHostAccessAndBlocksEnvironmentMutations(t *testing.T) { | |
| 72 | 新增: s := storageRecoveryServer(t) | |
| 73 | 新增: s.ready = true | |
| 74 | 新增: s.windowsState.Running = true | |
| 75 | 新增: s.networkIntentError = "synthetic independent network failure" | |
| 76 | 新增: s.failStorageRecovery(errors.New("synthetic system manager unavailable")) | |
| 77 | 新增: for _, endpoint := range []string{"/api/account", "/api/status", "/api/settings", "/api/environment/storage", "/api/environment/initialization", "/api/diagnostics", "/api/diagnostics/export"} { | |
| 78 | 新增: response := windowsBrowserRequestForTest(s, http.MethodGet, endpoint, nil) | |
| 79 | 新增: if response.Code != http.StatusOK { | |
| 80 | 新增: t.Fatalf("host access %s returned %d %s", endpoint, response.Code, response.Body.String()) | |
| 81 | 新增: } | |
| 82 | 新增: if endpoint == "/api/status" { | |
| 83 | 新增: var view struct { | |
| 84 | 新增: Ready bool `json:"ready"` | |
| 85 | 新增: NetworkError string `json:"network_error"` | |
| 86 | 新增: StorageRecovery storageRecoveryView `json:"storage_recovery"` | |
| 87 | 新增: } | |
| 88 | 新增: if err := json.Unmarshal(response.Body.Bytes(), &view); err != nil { | |
| 89 | 新增: t.Fatal(err) | |
| 90 | 新增: } | |
| 91 | 新增: if view.Ready || !view.StorageRecovery.Required || view.StorageRecovery.Error != "synthetic system manager unavailable" || view.NetworkError != s.networkIntentError { | |
| 92 | 新增: t.Fatal("recovery did not preserve the independent causes", view) | |
| 93 | 新增: } | |
| 94 | 新增: } | |
| 95 | 新增: if endpoint == "/api/diagnostics/export" { | |
| 96 | 新增: if _, err := zip.NewReader(bytes.NewReader(response.Body.Bytes()), int64(response.Body.Len())); err != nil { | |
| 97 | 新增: t.Fatal("pending recovery prevented a valid diagnostic export", err) | |
| 98 | 新增: } | |
| 99 | 新增: } | |
| 100 | 新增: } | |
| 101 | 新增: for _, endpoint := range []string{ | |
| 102 | 新增: "/api/start", "/api/stop", "/api/settings", "/api/projects/open", "/api/environment/resources", | |
| 103 | 新增: "/api/environment/storage", "/api/environment/update", "/api/environment/initialization", | |
| 104 | 新增: "/api/browser/open", "/api/input", "/api/input/paste/start", "/api/clipboard/copy", "/api/account/logout", | |
| 105 | 新增: } { | |
| 106 | 新增: response := windowsBrowserRequestForTest(s, http.MethodPost, endpoint, []byte(`{}`)) | |
| 107 | 新增: if response.Code != http.StatusConflict || !strings.Contains(response.Body.String(), "synthetic system manager unavailable") { | |
| 108 | 新增: t.Fatalf("mutation %s reached its receiver: %d %s", endpoint, response.Code, response.Body.String()) | |
| 109 | 新增: } | |
| 110 | 新增: } | |
| 111 | 新增: for _, endpoint := range []string{"/api/browser/state", "/api/vnc", "/api/terminals", "/api/audio"} { | |
| 112 | 新增: if response := windowsBrowserRequestForTest(s, http.MethodGet, endpoint, nil); response.Code != http.StatusConflict { | |
| 113 | 新增: t.Fatalf("guest session %s was admitted: %d", endpoint, response.Code) | |
| 114 | 新增: } | |
| 115 | 新增: } | |
| 116 | 新增: if err := s.attachWindowsGuestContext(context.Background()); err == nil || !strings.Contains(err.Error(), "synthetic system manager unavailable") { | |
| 117 | 新增: t.Fatal("periodic attach bypassed recovery", err) | |
| 118 | 新增: } | |
| 119 | 新增: if err := s.startWindowsGuest(); err == nil || !strings.Contains(err.Error(), "synthetic system manager unavailable") { | |
| 120 | 新增: t.Fatal("direct start bypassed recovery", err) | |
| 121 | 新增: } | |
| 122 | 新增: if _, err := s.submitJob("network-recovery", func() error { t.Error("background mutation ran"); return nil }); err == nil { | |
| 123 | 新增: t.Fatal("background job bypassed recovery") | |
| 124 | 新增: } | |
| 125 | 新增: s.monitorNetworkTick() | |
| 126 | 新增: if s.jobs.snapshot().ID != "" { | |
| 127 | 新增: t.Fatal("recovery gate created an environment job") | |
| 128 | 新增: } | |
| 129 | 新增:} | |
| 130 | 新增: | |
| 131 | 新增:func TestStorageRecoverySuccessfulRetryPreparesEnvironmentAndPreservesBinding(t *testing.T) { | |
| 132 | 新增: s := storageRecoveryServer(t) | |
| 133 | 新增: original, err := os.ReadFile(guestos.WindowsProfilePath(s.profile)) | |
| 134 | 新增: if err != nil { | |
| 135 | 新增: t.Fatal(err) | |
| 136 | 新增: } | |
| 137 | 新增: s.failStorageRecovery(errors.New("previous attempt lost its helper connection")) | |
| 138 | 新增: response := windowsBrowserRequestForTest(s, http.MethodPost, "/api/environment/storage/recover", []byte(`{}`)) | |
| 139 | 新增: if response.Code != http.StatusOK { | |
| 140 | 新增: t.Fatal(response.Code, response.Body.String()) | |
| 141 | 新增: } | |
| 142 | 新增: job := awaitJobIdle(t, &s.jobs) | |
| 143 | 新增: if job.Error != "" || job.Kind != "storage-recovery" || s.storageRecoveryStatus().Required || s.ready { | |
| 144 | 新增: t.Fatal("successful retry failed to restore admission without starting a VM", job, s.storageRecoveryStatus()) | |
| 145 | 新增: } | |
| 146 | 新增: if info, err := os.Stat(s.environmentDir()); err != nil || !info.IsDir() { | |
| 147 | 新增: t.Fatal("normal environment preparation did not run", err) | |
| 148 | 新增: } | |
| 149 | 新增: if current, err := os.ReadFile(guestos.WindowsProfilePath(s.profile)); err != nil || !bytes.Equal(current, original) { | |
| 150 | 新增: t.Fatal("retry changed VM or pairing identity", err) | |
| 151 | 新增: } | |
| 152 | 新增: if response := windowsBrowserRequestForTest(s, http.MethodGet, "/api/environment/storage", nil); response.Code != http.StatusOK || !strings.Contains(response.Body.String(), `"directory"`) { | |
| 153 | 新增: t.Fatal("recovered storage form remained unavailable", response.Code, response.Body.String()) | |
| 154 | 新增: } | |
| 155 | 新增: admitted := false | |
| 156 | 新增: if _, err := s.submitJob("start", func() error { admitted = true; return nil }); err != nil { | |
| 157 | 新增: t.Fatal("successful recovery kept normal start admission closed", err) | |
| 158 | 新增: } | |
| 159 | 新增: awaitJobIdle(t, &s.jobs) | |
| 160 | 新增: if !admitted { | |
| 161 | 新增: t.Fatal("normal start was not executed") | |
| 162 | 新增: } | |
| 163 | 新增:} | |
| 164 | 新增: | |
| 165 | 新增:func TestStorageRecoveryFailureAndReadOnlyLocationPreserveJournal(t *testing.T) { | |
| 166 | 新增: if runtime.GOOS == "windows" { | |
| 167 | 新增: t.Skip("the synthetic native journal uses the non-Windows rejection without contacting a real Hyper-V service") | |
| 168 | 新增: } | |
| 169 | 新增: s := storageRecoveryServer(t) | |
| 170 | 新增: journal := storageRecoveryJournal(t, s) | |
| 171 | 新增: original, err := os.ReadFile(journal) | |
| 172 | 新增: if err != nil { | |
| 173 | 新增: t.Fatal(err) | |
| 174 | 新增: } | |
| 175 | 新增: response := windowsBrowserRequestForTest(s, http.MethodGet, "/api/environment/storage", nil) | |
| 176 | 新增: if response.Code != http.StatusOK || !s.storageRecoveryStatus().Required { | |
| 177 | 新增: t.Fatal("location did not expose native recovery", response.Code, response.Body.String()) | |
| 178 | 新增: } | |
| 179 | 新增: for _, repair := range []bool{false, true} { | |
| 180 | 新增: response = windowsBrowserRequestForTest(s, http.MethodPost, "/api/environment/storage/recover", []byte(fmt.Sprintf(`{"repair":%t}`, repair))) | |
| 181 | 新增: if response.Code != http.StatusOK { | |
| 182 | 新增: t.Fatal(response.Code, response.Body.String()) | |
| 183 | 新增: } | |
| 184 | 新增: job := awaitJobIdle(t, &s.jobs) | |
| 185 | 新增: state := s.storageRecoveryStatus() | |
| 186 | 新增: if job.Error == "" || !state.Required || state.Error != job.Error || s.ready { | |
| 187 | 新增: t.Fatal("failed recovery cleared the cause or resumed writes", repair, job, state) | |
| 188 | 新增: } | |
| 189 | 新增: if current, err := os.ReadFile(journal); err != nil || !bytes.Equal(current, original) { | |
| 190 | 新增: t.Fatal("failed native recovery changed its durable ownership record", repair, err) | |
| 191 | 新增: } | |
| 192 | 新增: } | |
| 193 | 新增:} | |
| 194 | 新增: | |
| 195 | 新增:func TestStorageRecoveryPreparationFailureKeepsWritesClosed(t *testing.T) { | |
| 196 | 新增: s := storageRecoveryServer(t) | |
| 197 | 新增: if err := os.WriteFile(s.environmentDir(), []byte("synthetic occupied workspace path"), 0600); err != nil { | |
| 198 | 新增: t.Fatal(err) | |
| 199 | 新增: } | |
| 200 | 新增: s.failStorageRecovery(errors.New("previous native recovery failure")) | |
| 201 | 新增: response := windowsBrowserRequestForTest(s, http.MethodPost, "/api/environment/storage/recover", []byte(`{}`)) | |
| 202 | 新增: if response.Code != http.StatusOK { | |
| 203 | 新增: t.Fatal(response.Code, response.Body.String()) | |
| 204 | 新增: } | |
| 205 | 新增: job := awaitJobIdle(t, &s.jobs) | |
| 206 | 新增: if job.Error == "" || !s.storageRecoveryStatus().Required || s.ready { | |
| 207 | 新增: t.Fatal("failed workspace preparation resumed environment writes", job) | |
| 208 | 新增: } | |
| 209 | 新增: if response := windowsBrowserRequestForTest(s, http.MethodPost, "/api/start", []byte(`{}`)); response.Code != http.StatusConflict { | |
| 210 | 新增: t.Fatal("preparation failure opened start admission", response.Code) | |
| 211 | 新增: } | |
| 212 | 新增:} | |
| 213 | 新增: | |
| 214 | 新增:func TestStorageRecoveryRejectsChangedBindingAndKeepsAuthentication(t *testing.T) { | |
| 215 | 新增: s := storageRecoveryServer(t) | |
| 216 | 新增: s.failStorageRecovery(errors.New("synthetic pending migration")) | |
| 217 | 新增: if response := request(s, http.MethodPost, "/api/environment/storage/recover", s.origin, `{}`, false); response.Code != http.StatusUnauthorized { | |
| 218 | 新增: t.Fatal("unauthenticated recovery was admitted", response.Code) | |
| 219 | 新增: } | |
| 220 | 新增: if response := request(s, http.MethodPost, "/api/environment/storage/recover", s.origin, `{}`, true); response.Code != http.StatusForbidden { | |
| 221 | 新增: t.Fatal("untrusted native recovery was admitted", response.Code) | |
| 222 | 新增: } | |
| 223 | 新增: s.account.lock() | |
| 224 | 新增: if response := windowsBrowserRequestForTest(s, http.MethodPost, "/api/environment/storage/recover", []byte(`{}`)); response.Code != http.StatusLocked { | |
| 225 | 新增: t.Fatal("locked account could recover storage", response.Code) | |
| 226 | 新增: } | |
| 227 | 新增: s.account.setKey(make([]byte, 32)) | |
| 228 | 新增: changed := *s.windowsGuest | |
| 229 | 新增: changed.VMID = uuid.New() | |
| 230 | 新增: if err := writePrivate(guestos.WindowsProfilePath(s.profile), changed); err != nil { | |
| 231 | 新增: t.Fatal(err) | |
| 232 | 新增: } | |
| 233 | 新增: if response := windowsBrowserRequestForTest(s, http.MethodPost, "/api/environment/storage/recover", []byte(`{}`)); response.Code != http.StatusOK { | |
| 234 | 新增: t.Fatal(response.Code, response.Body.String()) | |
| 235 | 新增: } | |
| 236 | 新增: job := awaitJobIdle(t, &s.jobs) | |
| 237 | 新增: if job.Error == "" || !s.storageRecoveryStatus().Required { | |
| 238 | 新增: t.Fatal("recovery switched to an unrelated VM", job) | |
| 239 | 新增: } | |
| 240 | 新增: if _, err := os.Stat(s.environmentDir()); !errors.Is(err, os.ErrNotExist) { | |
| 241 | 新增: t.Fatal("identity mismatch reached environment preparation", err) | |
| 242 | 新增: } | |
| 243 | 新增: local := testServer(t) | |
| 244 | 新增: local.remote = newRemoteGateway(local.profile) | |
| 245 | 新增: defer local.remote.manager.Close() | |
| 246 | 新增: local.remote.setRemote(true) | |
| 247 | 新增: if response := request(local, http.MethodPost, "/api/environment/storage/recover", local.origin, `{}`, true); response.Code != http.StatusForbidden { | |
| 248 | 新增: t.Fatal("remote connection could dispatch local recovery", response.Code) | |
| 249 | 新增: } | |
| 250 | 新增:} | |
| 251 | 新增: | |
| 252 | 新增:func TestStorageRecoveryDoesNotCaptureUnrelatedNetworkFailure(t *testing.T) { | |
| 253 | 新增: s := storageRecoveryServer(t) | |
| 254 | 新增: s.networkIntentError = "synthetic proxy connection failure" | |
| 255 | 新增: response := windowsBrowserRequestForTest(s, http.MethodGet, "/api/status", nil) | |
| 256 | 新增: if response.Code != http.StatusOK || s.storageRecoveryStatus().Required || !strings.Contains(response.Body.String(), s.networkIntentError) { | |
| 257 | 新增: t.Fatal("network failure became a storage failure", response.Code, response.Body.String()) | |
| 258 | 新增: } | |
| 259 | 新增:} | |
| 260 | 新增: | |
| 261 | 新增:func TestStorageRecoveryProductionStartupKeepsLoginAndDiagnostics(t *testing.T) { | |
| 262 | 新增: if runtime.GOOS == "windows" { | |
| 263 | 新增: t.Skip("isolated production startup uses a non-Windows native rejection and never contacts Hyper-V") | |
| 264 | 新增: } | |
| 265 | 新增: const helper = "CAGE_TEST_STORAGE_RECOVERY_CONFIG" | |
| 266 | 新增: if config := os.Getenv(helper); config != "" { | |
| 267 | 新增: if err := Serve(config); err != nil { | |
| 268 | 新增: t.Fatal(err) | |
| 269 | 新增: } | |
| 270 | 新增: return | |
| 271 | 新增: } | |
| 272 | 新增: for _, pending := range []bool{true, false} { | |
| 273 | 新增: t.Run(fmt.Sprintf("native_pending=%t", pending), func(t *testing.T) { | |
| 274 | 新增: testStorageRecoveryProductionStartup(t, pending) | |
| 275 | 新增: }) | |
| 276 | 新增: } | |
| 277 | 新增:} | |
| 278 | 新增: | |
| 279 | 新增:func testStorageRecoveryProductionStartup(t *testing.T, pending bool) { | |
| 280 | 新增: s := storageRecoveryServer(t) | |
| 281 | 新增: var journal string | |
| 282 | 新增: var original []byte | |
| 283 | 新增: if pending { | |
| 284 | 新增: journal = storageRecoveryJournal(t, s) | |
| 285 | 新增: var err error | |
| 286 | 新增: original, err = os.ReadFile(journal) | |
| 287 | 新增: if err != nil { | |
| 288 | 新增: t.Fatal(err) | |
| 289 | 新增: } | |
| 290 | 新增: } else if err := os.WriteFile(s.environmentDir(), []byte("synthetic occupied workspace path"), 0600); err != nil { | |
| 291 | 新增: t.Fatal(err) | |
| 292 | 新增: } | |
| 293 | 新增: if err := writePrivate(filepath.Join(s.profile, "initialization.json"), initializationRecord{Version: 1, Started: true}); err != nil { | |
| 294 | 新增: t.Fatal(err) | |
| 295 | 新增: } | |
| 296 | 新增: account, err := loadLocalAccount(s.profile) | |
| 297 | 新增: if err != nil { | |
| 298 | 新增: t.Fatal(err) | |
| 299 | 新增: } | |
| 300 | 新增: if err := account.create("Storage QA", "synthetic-recovery-password", ""); err != nil { | |
| 301 | 新增: t.Fatal(err) | |
| 302 | 新增: } | |
| 303 | 新增: account.lock() | |
| 304 | 新增: ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second) | |
| 305 | 新增: defer cancel() | |
| 306 | 新增: command := exec.CommandContext(ctx, os.Args[0], "-test.run=^TestStorageRecoveryProductionStartupKeepsLoginAndDiagnostics$", "-test.timeout=20s") | |
| 307 | 新增: command.Env = append(os.Environ(), "CAGE_TEST_STORAGE_RECOVERY_CONFIG="+s.configPath) | |
| 308 | 新增: var output bytes.Buffer | |
| 309 | 新增: command.Stdout, command.Stderr = &output, &output | |
| 310 | 新增: if err := command.Start(); err != nil { | |
| 311 | 新增: t.Fatal(err) | |
| 312 | 新增: } | |
| 313 | 新增: done := make(chan error, 1) | |
| 314 | 新增: go func() { done <- command.Wait() }() | |
| 315 | 新增: finished := false | |
| 316 | 新增: t.Cleanup(func() { | |
| 317 | 新增: if !finished { | |
| 318 | 新增: _ = command.Process.Kill() | |
| 319 | 新增: <-done | |
| 320 | 新增: } | |
| 321 | 新增: if t.Failed() { | |
| 322 | 新增: t.Log(output.String()) | |
| 323 | 新增: } | |
| 324 | 新增: }) | |
| 325 | 新增: var control controlFile | |
| 326 | 新增: deadline := time.Now().Add(5 * time.Second) | |
| 327 | 新增: for time.Now().Before(deadline) { | |
| 328 | 新增: data, err := os.ReadFile(filepath.Join(s.profile, "control.json")) | |
| 329 | 新增: if err == nil && json.Unmarshal(data, &control) == nil && control.PID == command.Process.Pid { | |
| 330 | 新增: break | |
| 331 | 新增: } | |
| 332 | 新增: select { | |
| 333 | 新增: case err := <-done: | |
| 334 | 新增: finished = true | |
| 335 | 新增: t.Fatalf("storage recovery terminated the production workbench: %v", err) | |
| 336 | 新增: default: | |
| 337 | 新增: } | |
| 338 | 新增: time.Sleep(10 * time.Millisecond) | |
| 339 | 新增: } | |
| 340 | 新增: if control.PID != command.Process.Pid { | |
| 341 | 新增: t.Fatal("pending recovery did not publish a reachable workbench") | |
| 342 | 新增: } | |
| 343 | 新增: origin := fmt.Sprintf("http://localhost:%d", control.Port) | |
| 344 | 新增: base, _ := url.Parse(origin) | |
| 345 | 新增: jar, _ := cookiejar.New(nil) | |
| 346 | 新增: jar.SetCookies(base, []*http.Cookie{{Name: cookieName + "_" + base.Port() + "-desktop", Value: trustedViewProof(control.Token), Path: "/"}}) | |
| 347 | 新增: client := &http.Client{Jar: jar, Timeout: 3 * time.Second} | |
| 348 | 新增: call := func(method, path, body string, expected int) []byte { | |
| 349 | 新增: t.Helper() | |
| 350 | 新增: request, err := http.NewRequestWithContext(ctx, method, origin+path, strings.NewReader(body)) | |
| 351 | 新增: if err != nil { | |
| 352 | 新增: t.Fatal(err) | |
| 353 | 新增: } | |
| 354 | 新增: request.Header.Set("Origin", origin) | |
| 355 | 新增: request.Header.Set("Content-Type", "application/json") | |
| 356 | 新增: response, err := client.Do(request) | |
| 357 | 新增: if err != nil { | |
| 358 | 新增: t.Fatal(err) | |
| 359 | 新增: } | |
| 360 | 新增: defer response.Body.Close() | |
| 361 | 新增: data, err := io.ReadAll(io.LimitReader(response.Body, 1<<20)) | |
| 362 | 新增: if err != nil || response.StatusCode != expected { | |
| 363 | 新增: t.Fatalf("%s %s returned %d %s (%v)", method, path, response.StatusCode, data, err) | |
| 364 | 新增: } | |
| 365 | 新增: return data | |
| 366 | 新增: } | |
| 367 | 新增: var launch launchResponse | |
| 368 | 新增: if err := json.Unmarshal(call(http.MethodPost, "/api/launch", fmt.Sprintf(`{"token":%q}`, control.Token), http.StatusOK), &launch); err != nil { | |
| 369 | 新增: t.Fatal(err) | |
| 370 | 新增: } | |
| 371 | 新增: entry, err := url.Parse(launch.URL) | |
| 372 | 新增: if err != nil || entry.Fragment == "" { | |
| 373 | 新增: t.Fatal("launcher did not issue a workbench ticket", err) | |
| 374 | 新增: } | |
| 375 | 新增: call(http.MethodPost, "/api/session", fmt.Sprintf(`{"token":%q}`, entry.Fragment), http.StatusOK) | |
| 376 | 新增: call(http.MethodGet, "/api/account", "", http.StatusOK) | |
| 377 | 新增: call(http.MethodGet, "/api/status", "", http.StatusLocked) | |
| 378 | 新增: call(http.MethodPost, "/api/account/unlock", `{"password":"synthetic-recovery-password"}`, http.StatusOK) | |
| 379 | 新增: var status struct { | |
| 380 | 新增: Ready bool `json:"ready"` | |
| 381 | 新增: Recovery storageRecoveryView `json:"storage_recovery"` | |
| 382 | 新增: } | |
| 383 | 新增: if err := json.Unmarshal(call(http.MethodGet, "/api/status", "", http.StatusOK), &status); err != nil || status.Ready || !status.Recovery.Required || status.Recovery.Error == "" || pending && !strings.Contains(status.Recovery.Error, "Hyper-V") { | |
| 384 | 新增: t.Fatal("startup did not retain the actual native failure", status, err) | |
| 385 | 新增: } | |
| 386 | 新增: call(http.MethodGet, "/api/settings", "", http.StatusOK) | |
| 387 | 新增: var initialization initializationView | |
| 388 | 新增: if err := json.Unmarshal(call(http.MethodGet, "/api/environment/initialization", "", http.StatusOK), &initialization); err != nil || initialization.Required { | |
| 389 | 新增: t.Fatal("old initialization record hid the storage recovery screen", initialization, err) | |
| 390 | 新增: } | |
| 391 | 新增: call(http.MethodPost, "/api/start", `{}`, http.StatusConflict) | |
| 392 | 新增: bundle := call(http.MethodGet, "/api/diagnostics/export", "", http.StatusOK) | |
| 393 | 新增: if _, err := zip.NewReader(bytes.NewReader(bundle), int64(len(bundle))); err != nil { | |
| 394 | 新增: t.Fatal("live workbench did not export a valid diagnostic bundle", err) | |
| 395 | 新增: } | |
| 396 | 新增: if pending { | |
| 397 | 新增: if current, err := os.ReadFile(journal); err != nil || !bytes.Equal(current, original) { | |
| 398 | 新增: t.Fatal("workbench access changed the pending native transaction", err) | |
| 399 | 新增: } | |
| 400 | 新增: if _, err := os.Stat(s.environmentDir()); !errors.Is(err, os.ErrNotExist) { | |
| 401 | 新增: t.Fatal("pending startup wrote environment data", err) | |
| 402 | 新增: } | |
| 403 | 新增: } else if current, err := os.ReadFile(s.environmentDir()); err != nil || string(current) != "synthetic occupied workspace path" { | |
| 404 | 新增: t.Fatal("workspace preparation failure changed the occupied file", err) | |
| 405 | 新增: } | |
| 406 | 新增:} | |
| @@ -8,9 +8,27 @@ import ( | ||
| 8 | 8 | "errors" |
| 9 | 9 | "github.com/sylvinus/agent-vm/internal/tailnetassets" |
| 10 | 10 | "io" |
| 11 | 新增: "strings" | |
| 11 | 12 | "time" |
| 12 | 13 | ) |
| 13 | 14 | |
| 15 | 新增:// Stage beside the installed executable so a running node can finish on its old | |
| 16 | 新增:// inode. Identity and user data live elsewhere and are never part of installation. | |
| 17 | 新增:const tailnetInstallScript = `set -eu; tmp=$(mktemp /tmp/cage-tailnet.XXXXXX); stage=; trap 'rm -f "$tmp"; if test -n "$stage"; then sudo rm -f "$stage"; fi' EXIT; cat > "$tmp"; stage=$(sudo mktemp /usr/local/bin/.cage-tailnet.XXXXXX); sudo install -m 0755 "$tmp" "$stage"; sudo mv -f "$stage" /usr/local/bin/cage-tailnet; printf 'cage-browser ALL=(cage) NOPASSWD: /usr/local/bin/cage-tailnet\n' | sudo tee /etc/sudoers.d/cage-tailnet >/dev/null; sudo chmod 0440 /etc/sudoers.d/cage-tailnet` | |
| 18 | 新增: | |
| 19 | 新增:func (s *Server) refreshInstalledTailnet() error { | |
| 20 | 新增: ctx, cancel := context.WithTimeout(s.operationContext(), 15*time.Second) | |
| 21 | 新增: defer cancel() | |
| 22 | 新增: installed, err := s.guest(ctx, "if test -x /usr/local/bin/cage-tailnet; then printf installed; fi") | |
| 23 | 新增: if err != nil { | |
| 24 | 新增: return err | |
| 25 | 新增: } | |
| 26 | 新增: if strings.TrimSpace(string(installed)) == "installed" { | |
| 27 | 新增: return s.installTailnet() | |
| 28 | 新增: } | |
| 29 | 新增: return nil | |
| 30 | 新增:} | |
| 31 | 新增: | |
| 14 | 32 | func (s *Server) installTailnet() error { |
| 15 | 33 | if s.macosGuest != nil || s.windowsGuest != nil { |
| 16 | 34 | return errTailnetNativeInstall |
| @@ -40,8 +58,7 @@ func (s *Server) installTailnet() error { | ||
| 40 | 58 | return err |
| 41 | 59 | } |
| 42 | 60 | defer reader.Close() |
| 43 | 删除: script := `set -eu; tmp=$(mktemp /tmp/cage-tailnet.XXXXXX); trap 'rm -f "$tmp"' EXIT; cat > "$tmp"; sudo install -m 0755 "$tmp" /usr/local/bin/cage-tailnet; printf 'cage-browser ALL=(cage) NOPASSWD: /usr/local/bin/cage-tailnet\n' | sudo tee /etc/sudoers.d/cage-tailnet >/dev/null; sudo chmod 0440 /etc/sudoers.d/cage-tailnet` | |
| 44 | 删除: cmd := s.sshCommand(ctx, "-T", s.sshTarget(), "--", "/bin/bash -c "+shellescape.Quote(script)) | |
| 61 | 新增: cmd := s.sshCommand(ctx, "-T", s.sshTarget(), "--", "/bin/bash -c "+shellescape.Quote(tailnetInstallScript)) | |
| 45 | 62 | cmd.Stdin = reader |
| 46 | 63 | cmd.Stdout = io.Discard |
| 47 | 64 | cmd.Stderr = io.Discard |
| @@ -0,0 +1,84 @@ | ||
| 1 | 新增:package workbench | |
| 2 | 新增: | |
| 3 | 新增:import ( | |
| 4 | 新增: "bytes" | |
| 5 | 新增: "os" | |
| 6 | 新增: "os/exec" | |
| 7 | 新增: "path/filepath" | |
| 8 | 新增: "strings" | |
| 9 | 新增: "testing" | |
| 10 | 新增:) | |
| 11 | 新增: | |
| 12 | 新增:func TestTailnetInstallAtomicallyReplacesRunningPayloadAndPreservesIdentity(t *testing.T) { | |
| 13 | 新增: if os.PathSeparator != '/' { | |
| 14 | 新增: t.Skip("guest installation executes on Unix") | |
| 15 | 新增: } | |
| 16 | 新增: root := t.TempDir() | |
| 17 | 新增: bin := filepath.Join(root, "bin") | |
| 18 | 新增: sudoers := filepath.Join(root, "sudoers") | |
| 19 | 新增: if err := os.MkdirAll(bin, 0700); err != nil { | |
| 20 | 新增: t.Fatal(err) | |
| 21 | 新增: } | |
| 22 | 新增: if err := os.MkdirAll(sudoers, 0700); err != nil { | |
| 23 | 新增: t.Fatal(err) | |
| 24 | 新增: } | |
| 25 | 新增: old, err := os.ReadFile("/bin/sleep") | |
| 26 | 新增: if err != nil { | |
| 27 | 新增: t.Fatal(err) | |
| 28 | 新增: } | |
| 29 | 新增: executable := filepath.Join(bin, "cage-tailnet") | |
| 30 | 新增: if err = os.WriteFile(executable, old, 0755); err != nil { | |
| 31 | 新增: t.Fatal(err) | |
| 32 | 新增: } | |
| 33 | 新增: identity := filepath.Join(root, "identity.json") | |
| 34 | 新增: if err = os.WriteFile(identity, []byte("saved-node-and-keys"), 0600); err != nil { | |
| 35 | 新增: t.Fatal(err) | |
| 36 | 新增: } | |
| 37 | 新增: // This is a real open executable inode, rather than a mocked install result. | |
| 38 | 新增: running := exec.Command(executable, "60") | |
| 39 | 新增: if err = running.Start(); err != nil { | |
| 40 | 新增: t.Fatal(err) | |
| 41 | 新增: } | |
| 42 | 新增: defer func() { _ = running.Process.Kill(); _ = running.Wait() }() | |
| 43 | 新增: if err = os.WriteFile(filepath.Join(bin, "sudo"), []byte("#!/bin/sh\nexec \"$@\"\n"), 0755); err != nil { | |
| 44 | 新增: t.Fatal(err) | |
| 45 | 新增: } | |
| 46 | 新增: script := strings.ReplaceAll(tailnetInstallScript, "/usr/local/bin", bin) | |
| 47 | 新增: script = strings.ReplaceAll(script, "/etc/sudoers.d", sudoers) | |
| 48 | 新增: fresh := []byte("#!/bin/sh\nprintf updated-tailnet\n") | |
| 49 | 新增: install := exec.Command("/bin/bash", "-c", script) | |
| 50 | 新增: install.Env = append(os.Environ(), "PATH="+bin+":/usr/bin:/bin") | |
| 51 | 新增: install.Stdin = bytes.NewReader(fresh) | |
| 52 | 新增: if output, err := install.CombinedOutput(); err != nil { | |
| 53 | 新增: t.Fatalf("running binary replacement failed: %v %s", err, output) | |
| 54 | 新增: } | |
| 55 | 新增: output, err := exec.Command(executable).Output() | |
| 56 | 新增: if err != nil || string(output) != "updated-tailnet" { | |
| 57 | 新增: t.Fatalf("new process uses old payload: %q %v", output, err) | |
| 58 | 新增: } | |
| 59 | 新增: if data, err := os.ReadFile(identity); err != nil || string(data) != "saved-node-and-keys" { | |
| 60 | 新增: t.Fatal("installation touched identity", err) | |
| 61 | 新增: } | |
| 62 | 新增: if entries, err := filepath.Glob(filepath.Join(bin, ".cage-tailnet.*")); err != nil || len(entries) != 0 { | |
| 63 | 新增: t.Fatal("staged payload left behind", entries, err) | |
| 64 | 新增: } | |
| 65 | 新增: // A failed staged copy must leave the working binary and identity in place. | |
| 66 | 新增: if err = os.WriteFile(filepath.Join(bin, "sudo"), []byte("#!/bin/sh\nif test \"$1\" = install; then exit 42; fi\nexec \"$@\"\n"), 0755); err != nil { | |
| 67 | 新增: t.Fatal(err) | |
| 68 | 新增: } | |
| 69 | 新增: failed := exec.Command("/bin/bash", "-c", script) | |
| 70 | 新增: failed.Env = install.Env | |
| 71 | 新增: failed.Stdin = strings.NewReader("broken candidate") | |
| 72 | 新增: if output, err := failed.CombinedOutput(); err == nil { | |
| 73 | 新增: t.Fatalf("failed staged copy reported success: %s", output) | |
| 74 | 新增: } | |
| 75 | 新增: if actual, err := os.ReadFile(executable); err != nil || !bytes.Equal(actual, fresh) { | |
| 76 | 新增: t.Fatal("failed installation replaced the working binary", err) | |
| 77 | 新增: } | |
| 78 | 新增: if actual, err := os.ReadFile(identity); err != nil || string(actual) != "saved-node-and-keys" { | |
| 79 | 新增: t.Fatal("failed installation touched identity", err) | |
| 80 | 新增: } | |
| 81 | 新增: if entries, err := filepath.Glob(filepath.Join(bin, ".cage-tailnet.*")); err != nil || len(entries) != 0 { | |
| 82 | 新增: t.Fatal("failed installation leaked its stage", entries, err) | |
| 83 | 新增: } | |
| 84 | 新增:} | |
| @@ -261,7 +261,7 @@ func (s *Server) nativeBrowserVNC(w http.ResponseWriter, r *http.Request) { | ||
| 261 | 261 | client = newWindowsBrowserClient(ctx, s.profile) |
| 262 | 262 | release = client.close |
| 263 | 263 | } |
| 264 | 删除: defer release() | |
| 264 | 新增: defer func() { release() }() | |
| 265 | 265 | var current windowsWindowFrame |
| 266 | 266 | request := func(input map[string]any, output any) error { |
| 267 | 267 | var data []byte |
| @@ -308,6 +308,16 @@ func (s *Server) nativeBrowserVNC(w http.ResponseWriter, r *http.Request) { | ||
| 308 | 308 | http.Error(w, err.Error(), 409) |
| 309 | 309 | return |
| 310 | 310 | } |
| 311 | 新增: if s.macosGuest != nil { | |
| 312 | 新增: owner := client | |
| 313 | 新增: client, release = owner.viewer(ctx) | |
| 314 | 新增: if client != owner { | |
| 315 | 新增: if err := request(map[string]any{"action": "frame"}, ¤t); err != nil { | |
| 316 | 新增: http.Error(w, err.Error(), 409) | |
| 317 | 新增: return | |
| 318 | 新增: } | |
| 319 | 新增: } | |
| 320 | 新增: } | |
| 311 | 321 | local, remote := net.Pipe() |
| 312 | 322 | defer local.Close() |
| 313 | 323 | done := make(chan struct{}) |
| @@ -43,6 +43,19 @@ func newWindowsBrowserClient(parent context.Context, profile string) *windowsBro | ||
| 43 | 43 | }} |
| 44 | 44 | } |
| 45 | 45 | |
| 46 | 新增:// A modern guest service owns the browser. Its viewers use separate relay | |
| 47 | 新增:// connections so cancellation also releases each viewer's held input. | |
| 48 | 新增:func (c *windowsBrowserClient) viewer(parent context.Context) (*windowsBrowserClient, func()) { | |
| 49 | 新增: c.mu.Lock() | |
| 50 | 新增: defer c.mu.Unlock() | |
| 51 | 新增: if c.ownsBrowser { | |
| 52 | 新增: return c, func() {} | |
| 53 | 新增: } | |
| 54 | 新增: ctx, cancel := context.WithCancel(parent) | |
| 55 | 新增: viewer := &windowsBrowserClient{ctx: ctx, cancel: cancel, start: c.start, ownsBrowser: true} | |
| 56 | 新增: return viewer, viewer.close | |
| 57 | 新增:} | |
| 58 | 新增: | |
| 46 | 59 | var windowsBrowserRoutes = map[string]bool{ |
| 47 | 60 | "tailnet": true, "health": true, "tabs": true, "events": true, "frame": true, "new": true, "activate": true, "close": true, |
| 48 | 61 | "navigate": true, "back": true, "forward": true, "reload": true, "homepage": true, "resize": true, |
| @@ -6,6 +6,7 @@ import ( | ||
| 6 | 6 | "context" |
| 7 | 7 | "encoding/base64" |
| 8 | 8 | "encoding/json" |
| 9 | 新增: "fmt" | |
| 9 | 10 | "io" |
| 10 | 11 | "os" |
| 11 | 12 | "os/exec" |
| @@ -115,6 +116,9 @@ func TestWindowsBrowserRelayHelper(t *testing.T) { | ||
| 115 | 116 | } |
| 116 | 117 | result = map[string]any{"data": base64.StdEncoding.EncodeToString(downloaded[start : start+remaining]), "sequence": request.Input.Sequence + 1, "eof": start+remaining == len(downloaded)} |
| 117 | 118 | } |
| 119 | 新增: if os.Getenv("CAGE_BROWSER_PERSISTENT_FIXTURE") == "1" { | |
| 120 | 新增: result.(map[string]any)["service"] = map[string]any{"version": 1, "persistent": true} | |
| 121 | 新增: } | |
| 118 | 122 | data, _ := json.Marshal(result) |
| 119 | 123 | _, _ = os.Stdout.Write(append(data, '\n')) |
| 120 | 124 | } |
| @@ -216,3 +220,34 @@ func TestNativeBrowserEventsPreserveCopyContextAndSequence(t *testing.T) { | ||
| 216 | 220 | } |
| 217 | 221 | } |
| 218 | 222 | } |
| 223 | 新增: | |
| 224 | 新增:func TestNativeBrowserViewerOwnershipUsesServiceCapability(t *testing.T) { | |
| 225 | 新增: for _, persistent := range []bool{false, true} { | |
| 226 | 新增: t.Run(fmt.Sprint(persistent), func(t *testing.T) { | |
| 227 | 新增: client := fixtureWindowsBrowserClient(t) | |
| 228 | 新增: client.ownsBrowser = true | |
| 229 | 新增: start := client.start | |
| 230 | 新增: client.start = func(ctx context.Context) (*exec.Cmd, error) { | |
| 231 | 新增: cmd, err := start(ctx) | |
| 232 | 新增: if persistent { | |
| 233 | 新增: cmd.Env = append(cmd.Env, "CAGE_BROWSER_PERSISTENT_FIXTURE=1") | |
| 234 | 新增: } | |
| 235 | 新增: return cmd, err | |
| 236 | 新增: } | |
| 237 | 新增: if _, err := client.request(t.Context(), "GET", "/tabs", nil); err != nil { | |
| 238 | 新增: t.Fatal(err) | |
| 239 | 新增: } | |
| 240 | 新增: viewer, release := client.viewer(t.Context()) | |
| 241 | 新增: if (viewer != client) != persistent { | |
| 242 | 新增: t.Fatal("viewer ownership did not follow guest capability") | |
| 243 | 新增: } | |
| 244 | 新增: if _, err := viewer.request(t.Context(), "GET", "/tabs", nil); err != nil { | |
| 245 | 新增: t.Fatal(err) | |
| 246 | 新增: } | |
| 247 | 新增: release() | |
| 248 | 新增: if _, err := client.request(t.Context(), "GET", "/tabs", nil); err != nil { | |
| 249 | 新增: t.Fatalf("closing a viewer closed the owning connection: %v", err) | |
| 250 | 新增: } | |
| 251 | 新增: }) | |
| 252 | 新增: } | |
| 253 | 新增:} | |
| @@ -19,6 +19,7 @@ import ( | ||
| 19 | 19 | "time" |
| 20 | 20 | |
| 21 | 21 | "github.com/gorilla/websocket" |
| 22 | 新增: "github.com/sylvinus/agent-vm/internal/clipboardfiles" | |
| 22 | 23 | "github.com/sylvinus/agent-vm/internal/guestos" |
| 23 | 24 | ) |
| 24 | 25 | |
| @@ -120,11 +121,13 @@ func TestWindowsGuestClipboardWorkbench(t *testing.T) { | ||
| 120 | 121 | if response.StatusCode != 200 { |
| 121 | 122 | t.Fatal("public file export failed") |
| 122 | 123 | } |
| 123 | 删除: paths, err := receiveClipboardArchive(response) | |
| 124 | 新增: cache := clipboardfiles.CacheStore{Directory: filepath.Join(t.TempDir(), "clipboard-receipts")} | |
| 125 | 新增: selection, err := receiveClipboardArchive(response, cache) | |
| 124 | 126 | if err != nil { |
| 125 | 127 | t.Fatal(err) |
| 126 | 128 | } |
| 127 | 删除: defer os.RemoveAll(filepath.Dir(paths[0])) | |
| 129 | 新增: defer cache.Release(selection.ID) | |
| 130 | 新增: paths := selection.Paths | |
| 128 | 131 | actual, err := os.ReadFile(filepath.Join(paths[0], "内容.bin")) |
| 129 | 132 | if err != nil || !bytes.Equal(actual, content) { |
| 130 | 133 | t.Fatal("public file bytes changed") |
| @@ -132,9 +132,15 @@ func (s *Server) attachWindowsGuest() error { | ||
| 132 | 132 | } |
| 133 | 133 | |
| 134 | 134 | func (s *Server) attachWindowsGuestContext(parent context.Context) error { |
| 135 | 新增: if err := s.requireStorageReady(); err != nil { | |
| 136 | 新增: return err | |
| 137 | 新增: } | |
| 135 | 138 | ctx, cancel := context.WithTimeout(parent, 15*time.Second) |
| 136 | 139 | defer cancel() |
| 137 | 140 | state, err := s.windowsStatus(ctx) |
| 141 | 新增: if err == nil { | |
| 142 | 新增: err = s.requireStorageReady() | |
| 143 | 新增: } | |
| 138 | 144 | restartedNetwork := false |
| 139 | 145 | if err == nil && s.windowsGuest.NetworkPairingFile != "" { |
| 140 | 146 | // An alive helper alone does not prove its packet connection survived. |
| @@ -154,6 +160,11 @@ func (s *Server) attachWindowsGuestContext(parent context.Context) error { | ||
| 154 | 160 | err = s.ensureProjectShare(s.environmentDir()) |
| 155 | 161 | } |
| 156 | 162 | s.mu.Lock() |
| 163 | 新增: if s.storageRecoveryError != "" { | |
| 164 | 新增: err = errors.New(s.storageRecoveryError) | |
| 165 | 新增: s.mu.Unlock() | |
| 166 | 新增: return err | |
| 167 | 新增: } | |
| 157 | 168 | s.windowsState = state |
| 158 | 169 | newlyReady := !s.ready && err == nil |
| 159 | 170 | s.ready = err == nil |
| @@ -200,6 +211,9 @@ func waitWindowsBoot(ctx context.Context, interval time.Duration, attach func(co | ||
| 200 | 211 | } |
| 201 | 212 | |
| 202 | 213 | func (s *Server) startWindowsGuest() error { |
| 214 | 新增: if err := s.requireStorageReady(); err != nil { | |
| 215 | 新增: return err | |
| 216 | 新增: } | |
| 203 | 217 | if err := requireHostGit(s.operationContext()); err != nil { |
| 204 | 218 | return err |
| 205 | 219 | } |
| @@ -15,11 +15,17 @@ cat > "$app/Contents/Info.plist" <<'PLIST' | ||
| 15 | 15 | <key>CFBundleShortVersionString</key><string>1.0</string> |
| 16 | 16 | <key>CFBundleVersion</key><string>1</string> |
| 17 | 17 | <key>LSUIElement</key><true/> |
| 18 | 新增:<key>CFBundleDocumentTypes</key><array><dict> | |
| 19 | 新增:<key>CFBundleTypeName</key><string>Cage project file</string> | |
| 20 | 新增:<key>CFBundleTypeRole</key><string>Viewer</string> | |
| 21 | 新增:<key>LSHandlerRank</key><string>None</string> | |
| 22 | 新增:<key>LSItemContentTypes</key><array><string>public.data</string></array> | |
| 23 | 新增:</dict></array> | |
| 18 | 24 | </dict></plist> |
| 19 | 25 | PLIST |
| 20 | 26 | objects=$(mktemp -d) |
| 21 | 27 | trap 'rm -rf "$objects"' EXIT |
| 22 | 28 | xcrun clang -target arm64-apple-macos14.0 -Wall -Wextra -Werror -O2 -c "$src/macos-file-writers.c" -o "$objects/file-writers.o" |
| 23 | 删除:xcrun swiftc -parse-as-library -D GUEST_WINDOW_APP -O -target arm64-apple-macos14.0 "$src/../../desktop/MacKeyboard.swift" "$src/claude-window-macos.swift" "$src/macos-diagnostics.swift" "$src/macos-claude-window-app.swift" "$src/macos-window-input.swift" "$src/macos-project-panel.swift" "$src/macos-claude-canvas.swift" "$src/macos-window-stream.swift" "$src/macos-audio.swift" "$src/macos-gui-session.swift" "$src/macos-phone-desktop.swift" "$src/macos-desktop-files.swift" "$src/macos-desktop-downloads.swift" "$objects/file-writers.o" -o "$app/Contents/MacOS/CageGuestWindow" | |
| 29 | 新增:xcrun swiftc -parse-as-library -D GUEST_WINDOW_APP -O -target arm64-apple-macos14.0 "$src/../../desktop/MacKeyboard.swift" "$src/claude-window-macos.swift" "$src/macos-diagnostics.swift" "$src/macos-claude-window-app.swift" "$src/macos-window-input.swift" "$src/macos-maintenance.swift" "$src/macos-setup-password.swift" "$src/macos-project-panel.swift" "$src/macos-claude-canvas.swift" "$src/macos-window-stream.swift" "$src/macos-audio.swift" "$src/macos-gui-session.swift" "$src/macos-phone-desktop.swift" "$src/macos-desktop-files.swift" "$src/macos-desktop-downloads.swift" "$src/macos-native-open.swift" "$objects/file-writers.o" -lbsm -o "$app/Contents/MacOS/CageGuestWindow" | |
| 24 | 30 | codesign --force --sign "${CAGE_GUEST_SIGN_IDENTITY:-${CAGE_SIGNING_IDENTITY:--}}" --identifier dev.cage.GuestClaudeWindow "$app" |
| 25 | 31 | codesign --verify --strict "$app" |
| @@ -5,6 +5,7 @@ set -euo pipefail | ||
| 5 | 5 | [[ $# == 2 && $(uname -sm) == 'Darwin arm64' ]] || { echo 'Usage: build-macos-sshfs.sh /absolute/macfuse-sdk/usr/local /absolute/cage-sshfs' >&2; exit 2; } |
| 6 | 6 | sdk=$1 |
| 7 | 7 | output=$2 |
| 8 | 新增:script_dir=$(cd "$(dirname "$0")" && pwd) | |
| 8 | 9 | [[ $sdk == /* && $output == /* && -f $sdk/include/fuse3/fuse.h && ! -e $output ]] |
| 9 | 10 | src=$(mktemp -d) |
| 10 | 11 | trap 'rm -rf "$src"' EXIT |
| @@ -13,6 +14,7 @@ curl -fLsS --retry 2 "https://codeload.github.com/libfuse/sshfs/tar.gz/$commit" | ||
| 13 | 14 | cd "$src" |
| 14 | 15 | echo '9be20256ac841c6e5b4cd8aefbf57c325f93e9ff01f7c7691edfe9f02700338b sshfs.tgz' | shasum -a 256 -c - >/dev/null |
| 15 | 16 | tar xzf sshfs.tgz --strip-components 1 |
| 17 | 新增:patch -p1 < "$script_dir/sshfs-openwith.patch" | |
| 16 | 18 | cat > config.h <<'HEADER' |
| 17 | 19 | #define PACKAGE_VERSION "3.7.6" |
| 18 | 20 | #define IDMAP_DEFAULT "user" |
| @@ -292,9 +292,12 @@ private final class ClipboardAgent: @unchecked Sendable { | ||
| 292 | 292 | process.arguments = ["cache", String(data: try JSONSerialization.data(withJSONObject: ["action": action, "cache_id": id]), encoding: .utf8)!] |
| 293 | 293 | process.standardInput = FileHandle.nullDevice; process.standardOutput = output; process.standardError = FileHandle.nullDevice |
| 294 | 294 | try process.run() |
| 295 | 新增: let timeout = DispatchWorkItem { if process.isRunning { process.terminate() } } | |
| 296 | 新增: DispatchQueue.global().asyncAfter(deadline: .now() + 10, execute: timeout) | |
| 297 | 新增: defer { timeout.cancel() } | |
| 295 | 298 | let data = try output.fileHandleForReading.readToEnd() ?? Data() |
| 296 | 299 | process.waitUntilExit() |
| 297 | 删除: guard process.terminationStatus == 0, data.count <= 1 << 20 else { throw ClipboardFailure("clipboard_cache_failed") } | |
| 300 | 新增: guard process.terminationStatus == 0, data.count <= wireLimit else { throw ClipboardFailure("clipboard_cache_failed") } | |
| 298 | 301 | return try json(data) |
| 299 | 302 | } |
| 300 | 303 | private func rememberCopy(_ result: [String: Any], clipboard: Bool) { |
| @@ -365,17 +368,19 @@ private final class ClipboardAgent: @unchecked Sendable { | ||
| 365 | 368 | } |
| 366 | 369 | private func fileJSON(_ operation: String, values: [String]) throws -> [String] { |
| 367 | 370 | let reader = UUID() |
| 371 | 新增: var recorded = false | |
| 368 | 372 | onGUI { fileReaders[reader] = values } |
| 369 | 删除: defer { onGUI { fileReaders.removeValue(forKey: reader); collectCopies() } } | |
| 373 | 新增: defer { onGUI { fileReaders.removeValue(forKey: reader); if !recorded { copiesLoaded = false }; collectCopies() } } | |
| 370 | 374 | let input = Pipe() |
| 371 | 375 | let (process, output, id, epoch) = try beginTransfer(operation, input: input.fileHandleForReading) |
| 372 | 删除: defer { try? input.fileHandleForWriting.close(); if process.isRunning { process.terminate() }; onGUI { _ = transfers.removeValue(forKey: id) } } | |
| 376 | 新增: defer { try? input.fileHandleForWriting.close(); if process.isRunning { process.terminate() }; process.waitUntilExit(); onGUI { _ = transfers.removeValue(forKey: id) } } | |
| 373 | 377 | try input.fileHandleForWriting.write(contentsOf: JSONSerialization.data(withJSONObject: values)); try input.fileHandleForWriting.close() |
| 374 | 378 | let data = try output.fileHandleForReading.readToEnd() ?? Data() |
| 375 | 379 | guard data.count <= 65536 else { throw ClipboardFailure("invalid_files") } |
| 376 | 380 | let response = try json(data) |
| 377 | 381 | let result = try paths(response["paths"]) |
| 378 | 382 | onGUI { record(result, copied: true); rememberCopy(response, clipboard: operation == "copy") } |
| 383 | 新增: recorded = true | |
| 379 | 384 | do { try finishTransfer(process, id: id, epoch: epoch) } |
| 380 | 385 | catch { onGUI { retireCopies(result) }; throw error } |
| 381 | 386 | return result |
| @@ -530,18 +535,33 @@ private final class ClipboardAgent: @unchecked Sendable { | ||
| 530 | 535 | } |
| 531 | 536 | try writeAll(fd, jsonData(["ok": true])) |
| 532 | 537 | case "import", "upload": |
| 538 | 新增: let capturedStreams = onGUI { Set(streams.values.map(ObjectIdentifier.init)) } | |
| 533 | 539 | let name = operation == "upload" ? request["name"] as? String : nil |
| 534 | 540 | if operation == "upload" && (name == nil || name!.utf8.count > 255) { throw ClipboardFailure("invalid_files") } |
| 535 | 541 | let input = Pipe() |
| 536 | 542 | let (process, output, id, epoch) = try beginTransfer(operation == "upload" ? "save" : "import", input: input.fileHandleForReading, name: name) |
| 537 | 删除: defer { try? input.fileHandleForWriting.close(); if process.isRunning { process.terminate() }; onGUI { _ = transfers.removeValue(forKey: id) } } | |
| 543 | 新增: var recorded = false | |
| 544 | 新增: defer { | |
| 545 | 新增: try? input.fileHandleForWriting.close() | |
| 546 | 新增: if process.isRunning { process.terminate() } | |
| 547 | 新增: process.waitUntilExit() | |
| 548 | 新增: onGUI { transfers.removeValue(forKey: id); if !recorded { copiesLoaded = false }; collectCopies() } | |
| 549 | 新增: } | |
| 538 | 550 | try reader.copy(to: input.fileHandleForWriting); try input.fileHandleForWriting.close() |
| 539 | 551 | let data = try output.fileHandleForReading.readToEnd() ?? Data() |
| 540 | 552 | guard data.count <= 65536 else { throw ClipboardFailure("invalid_files") } |
| 541 | 553 | let response = try json(data) |
| 542 | 554 | let imported = try paths(response["paths"]) |
| 543 | 555 | onGUI { record(imported, copied: true); rememberCopy(response, clipboard: operation == "import") } |
| 544 | 删除: do { try finishTransfer(process, id: id, epoch: epoch); try writeAll(fd, jsonData(["paths": imported])) } | |
| 556 | 新增: recorded = true | |
| 557 | 新增: do { | |
| 558 | 新增: try finishTransfer(process, id: id, epoch: epoch) | |
| 559 | 新增: try onGUI { | |
| 560 | 新增: if operation == "import", !capturedStreams.isEmpty, | |
| 561 | 新增: capturedStreams.isDisjoint(with: streams.values.map(ObjectIdentifier.init)) { throw ClipboardFailure("connection_closed") } | |
| 562 | 新增: } | |
| 563 | 新增: try writeAll(fd, jsonData(["paths": imported])) | |
| 564 | 新增: } | |
| 545 | 565 | catch { onGUI { retireCopies(imported) }; throw error } |
| 546 | 566 | case "export": |
| 547 | 567 | let selected = try paths(request["paths"]) |
| @@ -189,7 +189,7 @@ internal static class ClaudeWindowRpc | ||
| 189 | 189 | { |
| 190 | 190 | if (!available()) throw new InvalidDataException("requires_gui_login"); |
| 191 | 191 | var action = value["action"]?.GetValue<string>() ?? ""; |
| 192 | 删除: if (action is "files-download-open" or "files-download-read" or "files-download-close" or "files-download-retry") | |
| 192 | 新增: if (action is "files-download-open" or "files-download-read" or "files-download-close" or "files-download-retry" or "files-download-ack") | |
| 193 | 193 | { |
| 194 | 194 | await Protocol.Write(stream, WindowsDesktopDownloads.Read(value), token); continue; |
| 195 | 195 | } |
| @@ -213,7 +213,7 @@ internal static class ClaudeWindowRpc | ||
| 213 | 213 | } |
| 214 | 214 | if(action=="files-poll" && executable is null) |
| 215 | 215 | { |
| 216 | 删除: await Protocol.Write(stream,new JsonObject{["available"]=false,["uploads"]=new JsonArray(),["downloads"]=WindowsDesktopDownloads.Snapshot(),["opens"]=WindowsDesktopFiles.OpenSnapshot()},token);continue; | |
| 216 | 新增: await Protocol.Write(stream,new JsonObject{["available"]=false,["uploads"]=new JsonArray(),["downloads"]=WindowsDesktopDownloads.Snapshot(),["opens"]=WindowsDesktopFiles.OpenSnapshot(),["downloadAck"]=true},token);continue; | |
| 217 | 217 | } |
| 218 | 218 | if (executable is null) throw new InvalidDataException("desktop_not_installed"); |
| 219 | 219 | if (action == "start") |
| @@ -227,7 +227,7 @@ internal static class ClaudeWindowRpc | ||
| 227 | 227 | try { found = Find(executable); } |
| 228 | 228 | catch (InvalidDataException) { } |
| 229 | 229 | if (found is null) |
| 230 | 删除: await Protocol.Write(stream,new JsonObject{["available"]=false,["uploads"]=new JsonArray(),["downloads"]=WindowsDesktopDownloads.Snapshot(),["opens"]=WindowsDesktopFiles.OpenSnapshot()},token); | |
| 230 | 新增: await Protocol.Write(stream,new JsonObject{["available"]=false,["uploads"]=new JsonArray(),["downloads"]=WindowsDesktopDownloads.Snapshot(),["opens"]=WindowsDesktopFiles.OpenSnapshot(),["downloadAck"]=true},token); | |
| 231 | 231 | else |
| 232 | 232 | { |
| 233 | 233 | using var owner = found.Process; |
| @@ -268,7 +268,7 @@ internal sealed class ClipboardAgent : Control | ||
| 268 | 268 | _ = child.StandardError.BaseStream.CopyToAsync(Stream.Null); |
| 269 | 269 | using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(10)); |
| 270 | 270 | using var cancellation = timeout.Token.Register(() => { try { child.Kill(true); } catch { } }); |
| 271 | 删除: var result = await Protocol.Read(child.StandardOutput.BaseStream, Protocol.PathLimit, timeout.Token) ?? throw new IOException("clipboard_cache_failed"); | |
| 271 | 新增: var result = await Protocol.Read(child.StandardOutput.BaseStream, Protocol.WireLimit, timeout.Token) ?? throw new IOException("clipboard_cache_failed"); | |
| 272 | 272 | await child.WaitForExitAsync(timeout.Token); |
| 273 | 273 | if (child.ExitCode != 0) throw new IOException("clipboard_cache_failed"); |
| 274 | 274 | return result; |
| @@ -281,13 +281,13 @@ internal sealed class ClipboardAgent : Control | ||
| 281 | 281 | { |
| 282 | 282 | if (!copiesLoaded) |
| 283 | 283 | { |
| 284 | 删除: copiesLoaded = true; | |
| 285 | 284 | var previous = await Cache("list"); |
| 286 | 285 | foreach (var item in previous["selections"]!.AsArray()) |
| 287 | 286 | { |
| 288 | 287 | var id = item!["cache_id"]!.GetValue<string>(); |
| 289 | 288 | copies.TryAdd(id, new CachedCopy(id, Protocol.Paths(item["paths"]), false)); |
| 290 | 289 | } |
| 290 | 新增: copiesLoaded = true; | |
| 291 | 291 | } |
| 292 | 292 | foreach (var copy in copies.Values.ToArray()) |
| 293 | 293 | { |
| @@ -332,9 +332,10 @@ internal sealed class ClipboardAgent : Control | ||
| 332 | 332 | var reader = Guid.NewGuid(); |
| 333 | 333 | if (paths != null) await GUI(() => { fileReaders[reader] = paths; return true; }); |
| 334 | 334 | string[]? created = null; |
| 335 | 新增: Process? child = null; | |
| 335 | 336 | try |
| 336 | 337 | { |
| 337 | 删除: using var child = StartHelper(operation); | |
| 338 | 新增: child = StartHelper(operation); | |
| 338 | 339 | using var cancellation = token.Register(() => { try { child.Kill(true); } catch { } }); |
| 339 | 340 | if (paths != null) await JsonSerializer.SerializeAsync(child.StandardInput.BaseStream, paths, cancellationToken: token); |
| 340 | 341 | child.StandardInput.Close(); |
| @@ -347,26 +348,40 @@ internal sealed class ClipboardAgent : Control | ||
| 347 | 348 | } |
| 348 | 349 | catch |
| 349 | 350 | { |
| 350 | 删除: if (created != null) await GUI(() => { RetireCopies(created); return true; }); | |
| 351 | 新增: if (child != null && !child.HasExited) { child.Kill(true); await child.WaitForExitAsync(); } | |
| 352 | 新增: await GUI(() => { if (created != null) RetireCopies(created); else copiesLoaded = false; return true; }); | |
| 351 | 353 | throw; |
| 352 | 354 | } |
| 353 | 删除: finally { await GUI(() => { fileReaders.Remove(reader); CollectCopies(); return true; }); } | |
| 355 | 新增: finally { child?.Dispose(); await GUI(() => { fileReaders.Remove(reader); CollectCopies(); return true; }); } | |
| 354 | 356 | } |
| 355 | 357 | internal async Task Import(Stream stream, CancellationToken token) |
| 356 | 358 | { |
| 359 | 新增: var capturedSubscriber = await GUI(() => subscriber); | |
| 360 | 新增: var capturedSession = SessionEpoch; | |
| 357 | 361 | using var child = StartHelper("import"); |
| 358 | 362 | using var cancellation = token.Register(() => { try { child.Kill(true); } catch { } }); |
| 359 | 删除: await Protocol.ReceiveFrames(stream, child.StandardInput.BaseStream, token); child.StandardInput.Close(); | |
| 360 | 删除: var result = await Protocol.Read(child.StandardOutput.BaseStream, Protocol.PathLimit, token) ?? throw new IOException("file_helper_failed"); | |
| 361 | 删除: var paths = Protocol.Paths(result["paths"]); | |
| 362 | 删除: await GUI(() => { RememberCopy(result); return true; }); | |
| 363 | 新增: string[]? paths = null; | |
| 363 | 364 | try |
| 364 | 365 | { |
| 366 | 新增: await Protocol.ReceiveFrames(stream, child.StandardInput.BaseStream, token); child.StandardInput.Close(); | |
| 367 | 新增: var result = await Protocol.Read(child.StandardOutput.BaseStream, Protocol.PathLimit, token) ?? throw new IOException("file_helper_failed"); | |
| 368 | 新增: paths = Protocol.Paths(result["paths"]); | |
| 369 | 新增: await GUI(() => { RememberCopy(result); return true; }); | |
| 365 | 370 | await child.WaitForExitAsync(token); |
| 366 | 371 | if (child.ExitCode != 0) throw new IOException("file_helper_failed"); |
| 367 | 删除: await GUI(() => { SessionGuard.Assert(); Approve(paths); return true; }); | |
| 372 | 新增: await GUI(() => { | |
| 373 | 新增: SessionGuard.Assert(); | |
| 374 | 新增: if (SessionEpoch != capturedSession || capturedSubscriber != null && subscriber != capturedSubscriber) throw new IOException("clipboard_session_changed"); | |
| 375 | 新增: Approve(paths); return true; | |
| 376 | 新增: }); | |
| 368 | 377 | await Protocol.Write(stream, new() { ["paths"] = JsonSerializer.SerializeToNode(paths) }, token); |
| 369 | 删除: } catch { await GUI(() => { RetireCopies(paths); return true; }); throw; } | |
| 378 | 新增: } | |
| 379 | 新增: catch | |
| 380 | 新增: { | |
| 381 | 新增: if (!child.HasExited) { child.Kill(true); await child.WaitForExitAsync(); } | |
| 382 | 新增: await GUI(() => { if (paths != null) RetireCopies(paths); else copiesLoaded = false; CollectCopies(); return true; }); | |
| 383 | 新增: throw; | |
| 384 | 新增: } | |
| 370 | 385 | } |
| 371 | 386 | internal async Task Export(Stream stream, JsonNode? selection, CancellationToken token) |
| 372 | 387 | { |
| @@ -19,13 +19,16 @@ internal static class WindowsDesktopDownloads | ||
| 19 | 19 | public string Name { get; set; } = ""; |
| 20 | 20 | public string State { get; set; } = "downloading"; |
| 21 | 21 | public string Error { get; set; } = ""; |
| 22 | 新增: public bool Acknowledged { get; set; } | |
| 23 | 新增: public string? Identity { get; set; } | |
| 22 | 24 | public long Size { get; set; } |
| 23 | 25 | public long Written { get; set; } |
| 24 | 26 | public DateTimeOffset Started { get; set; } = DateTimeOffset.UtcNow; |
| 25 | 27 | } |
| 26 | 删除: private sealed class Transfer(FileStream file, string session, long epoch) | |
| 28 | 新增: private sealed class Transfer(FileStream file, string id, string session, long epoch) | |
| 27 | 29 | { |
| 28 | 30 | internal readonly FileStream File = file; |
| 31 | 新增: internal readonly string ID = id; | |
| 29 | 32 | internal bool SessionValid => ClipboardAgent.Current is { SessionEventsRegistered: true } agent && agent.Session == session && agent.SessionEpoch == epoch; |
| 30 | 33 | internal int Sequence; |
| 31 | 34 | internal DateTimeOffset Used = DateTimeOffset.UtcNow; |
| @@ -33,6 +36,7 @@ internal static class WindowsDesktopDownloads | ||
| 33 | 36 | private static readonly object Gate = new(); |
| 34 | 37 | private static readonly Dictionary<string, Download> Downloads = new(); |
| 35 | 38 | private static readonly Dictionary<string, Transfer> Transfers = new(); |
| 39 | 新增: private static readonly HashSet<string> Watching = new(); | |
| 36 | 40 | private static readonly System.Threading.Timer TransferExpiry = new(_ => |
| 37 | 41 | { |
| 38 | 42 | lock (Gate) |
| @@ -48,6 +52,34 @@ internal static class WindowsDesktopDownloads | ||
| 48 | 52 | private static string? directory; |
| 49 | 53 | [DllImport("kernel32.dll", CharSet = CharSet.Unicode, ExactSpelling = true, SetLastError = true)] |
| 50 | 54 | private static extern uint GetFinalPathNameByHandleW(SafeFileHandle handle, StringBuilder path, uint length, uint flags); |
| 55 | 新增: [StructLayout(LayoutKind.Sequential)] | |
| 56 | 新增: private struct FileInformation | |
| 57 | 新增: { | |
| 58 | 新增: internal uint Attributes; | |
| 59 | 新增: internal System.Runtime.InteropServices.ComTypes.FILETIME Creation, Access, Written; | |
| 60 | 新增: internal uint Volume, SizeHigh, SizeLow, Links, IndexHigh, IndexLow; | |
| 61 | 新增: } | |
| 62 | 新增: [DllImport("kernel32.dll", SetLastError = true)] | |
| 63 | 新增: [return: MarshalAs(UnmanagedType.Bool)] | |
| 64 | 新增: private static extern bool GetFileInformationByHandle(SafeFileHandle handle, out FileInformation information); | |
| 65 | 新增: [DllImport("kernel32.dll", CharSet = CharSet.Unicode, ExactSpelling = true, SetLastError = true)] | |
| 66 | 新增: private static extern SafeFileHandle CreateFileW(string path, uint access, uint share, IntPtr security, uint creation, uint flags, IntPtr template); | |
| 67 | 新增: [DllImport("kernel32.dll", SetLastError = true)] | |
| 68 | 新增: [return: MarshalAs(UnmanagedType.Bool)] | |
| 69 | 新增: private static extern bool SetFileInformationByHandle(SafeFileHandle handle, int kind, ref byte information, uint size); | |
| 70 | 新增: | |
| 71 | 新增: private static string FileIdentity(SafeFileHandle handle) | |
| 72 | 新增: { | |
| 73 | 新增: if (!GetFileInformationByHandle(handle, out var info)) throw new IOException("desktop_download_file_invalid"); | |
| 74 | 新增: return $"{info.Volume:x8}:{info.IndexHigh:x8}{info.IndexLow:x8}"; | |
| 75 | 新增: } | |
| 76 | 新增: | |
| 77 | 新增: private static bool MatchesPath(SafeFileHandle handle, string path) | |
| 78 | 新增: { | |
| 79 | 新增: var actual = new StringBuilder(32768); | |
| 80 | 新增: var length = GetFinalPathNameByHandleW(handle, actual, (uint)actual.Capacity, 0); | |
| 81 | 新增: return length > 0 && length < actual.Capacity && string.Equals(actual.ToString(), @"\\?\" + Path.GetFullPath(path), StringComparison.OrdinalIgnoreCase); | |
| 82 | 新增: } | |
| 51 | 83 | |
| 52 | 84 | private static FileStream OpenSource(Download item) |
| 53 | 85 | { |
| @@ -85,7 +117,8 @@ internal static class WindowsDesktopDownloads | ||
| 85 | 117 | var info = new FileInfo(manifest); |
| 86 | 118 | if (info.Attributes.HasFlag(FileAttributes.ReparsePoint) || info.Length > 1 << 20) throw new InvalidDataException("desktop_download_catalog_invalid"); |
| 87 | 119 | var saved = JsonSerializer.Deserialize<Download[]>(File.ReadAllBytes(manifest)) ?? []; |
| 88 | 删除: foreach (var item in saved.TakeLast(100)) | |
| 120 | 新增: if (saved.Length > 100) throw new InvalidDataException("desktop_download_catalog_invalid"); | |
| 121 | 新增: foreach (var item in saved) | |
| 89 | 122 | { |
| 90 | 123 | if (!Guid.TryParseExact(item.ID, "D", out _) || !AttachmentsRpc.NameValid(item.Name)) continue; |
| 91 | 124 | if (item.State == "downloading") { item.State = "failed"; item.Error = "保存过程被中断,请从 Claude Desktop 重新下载。"; } |
| @@ -104,7 +137,7 @@ internal static class WindowsDesktopDownloads | ||
| 104 | 137 | { |
| 105 | 138 | using (var stream = new FileStream(temporary, FileMode.CreateNew, FileAccess.Write, FileShare.None)) |
| 106 | 139 | { |
| 107 | 删除: JsonSerializer.Serialize(stream, Downloads.Values.TakeLast(100).ToArray()); | |
| 140 | 新增: JsonSerializer.Serialize(stream, Downloads.Values.ToArray()); | |
| 108 | 141 | stream.Flush(true); |
| 109 | 142 | } |
| 110 | 143 | File.Move(temporary, file, true); |
| @@ -112,6 +145,51 @@ internal static class WindowsDesktopDownloads | ||
| 112 | 145 | finally { if (File.Exists(temporary)) File.Delete(temporary); } |
| 113 | 146 | } |
| 114 | 147 | |
| 148 | 新增: private static void RemoveSource(Download item) | |
| 149 | 新增: { | |
| 150 | 新增: var path = Source(item); | |
| 151 | 新增: var folder = Path.GetDirectoryName(path)!; | |
| 152 | 新增: using var parent = CreateFileW(folder, 0x10000 | 0x80, 1 | 2, IntPtr.Zero, 3, 0x02000000 | 0x00200000, IntPtr.Zero); | |
| 153 | 新增: if (parent.IsInvalid && Marshal.GetLastWin32Error() is 2 or 3) return; | |
| 154 | 新增: if (parent.IsInvalid || !MatchesPath(parent, folder) || !GetFileInformationByHandle(parent, out var parentInfo) || | |
| 155 | 新增: (parentInfo.Attributes & 0x410) != 0x10) throw new IOException("desktop_download_directory_invalid"); | |
| 156 | 新增: using (var file = CreateFileW(path, 0x80000000 | 0x10000, 1, IntPtr.Zero, 3, 0x00200000, IntPtr.Zero)) | |
| 157 | 新增: { | |
| 158 | 新增: if (file.IsInvalid) | |
| 159 | 新增: { | |
| 160 | 新增: if (Marshal.GetLastWin32Error() is not (2 or 3)) throw new IOException("desktop_download_cleanup_failed"); | |
| 161 | 新增: } | |
| 162 | 新增: else | |
| 163 | 新增: { | |
| 164 | 新增: if (item.State != "saved" || !MatchesPath(file, path) || !GetFileInformationByHandle(file, out var info) || (info.Attributes & 0x410) != 0 || | |
| 165 | 新增: FileIdentity(file) != item.Identity || ((long)info.SizeHigh << 32 | info.SizeLow) != item.Size || | |
| 166 | 新增: DateTime.FromFileTimeUtc((long)(uint)info.Written.dwHighDateTime << 32 | (uint)info.Written.dwLowDateTime).Ticks != item.Written) | |
| 167 | 新增: throw new IOException("desktop_download_changed"); | |
| 168 | 新增: byte delete = 1; | |
| 169 | 新增: if (!SetFileInformationByHandle(file, 4, ref delete, 1)) throw new IOException("desktop_download_cleanup_failed"); | |
| 170 | 新增: } | |
| 171 | 新增: } | |
| 172 | 新增: // The kernel removes this exact open directory only when it is empty. | |
| 173 | 新增: // Unrecorded sibling files keep their directory and contents. | |
| 174 | 新增: byte removeDirectory = 1; | |
| 175 | 新增: var removed = SetFileInformationByHandle(parent, 4, ref removeDirectory, 1); | |
| 176 | 新增: if (item.State == "failed" && !removed) throw new IOException("desktop_download_cleanup_failed"); | |
| 177 | 新增: } | |
| 178 | 新增: | |
| 179 | 新增: private static void MakeRoom() | |
| 180 | 新增: { | |
| 181 | 新增: if (Downloads.Count < 100) return; | |
| 182 | 新增: foreach (var item in Downloads.Values.ToArray()) | |
| 183 | 新增: { | |
| 184 | 新增: var eligible = (item.State == "saved" && item.Acknowledged) || (item.State == "failed" && !Watching.Contains(item.ID)); | |
| 185 | 新增: if (!eligible || Transfers.Values.Any(transfer => transfer.ID == item.ID)) continue; | |
| 186 | 新增: try { RemoveSource(item); Downloads.Remove(item.ID); return; } | |
| 187 | 新增: catch (IOException) { /* Retain changed, in-use, or unowned source receipts. */ } | |
| 188 | 新增: catch (UnauthorizedAccessException) { } | |
| 189 | 新增: } | |
| 190 | 新增: throw new InvalidDataException("desktop_download_limit"); | |
| 191 | 新增: } | |
| 192 | 新增: | |
| 115 | 193 | internal static string Reserve(string name, Action<string> submit) |
| 116 | 194 | { |
| 117 | 195 | if (!AttachmentsRpc.NameValid(name)) throw new InvalidDataException("desktop_download_name_invalid"); |
| @@ -119,6 +197,7 @@ internal static class WindowsDesktopDownloads | ||
| 119 | 197 | { |
| 120 | 198 | DirectoryPath(); |
| 121 | 199 | if (Downloads.Values.Count(item => item.State == "downloading") >= 12) throw new InvalidDataException("desktop_download_limit"); |
| 200 | 新增: MakeRoom(); | |
| 122 | 201 | var item = new Download { ID = Guid.NewGuid().ToString("D"), Name = name }; |
| 123 | 202 | var folder = Path.GetDirectoryName(Source(item))!; |
| 124 | 203 | Directory.CreateDirectory(folder); |
| @@ -129,18 +208,12 @@ internal static class WindowsDesktopDownloads | ||
| 129 | 208 | watcher.Renamed += (_, eventArgs) => { if (eventArgs.Name == name) { Interlocked.Exchange(ref renamed, 1); changed.TrySetResult(); } }; |
| 130 | 209 | watcher.Error += (_, _) => changed.TrySetException(new InvalidDataException("desktop_download_watch_failed")); |
| 131 | 210 | watcher.EnableRaisingEvents = true; |
| 132 | 删除: while (Downloads.Count >= 100) | |
| 133 | 删除: { | |
| 134 | 删除: var oldest = Downloads.Values.FirstOrDefault(value => value.State != "downloading"); | |
| 135 | 删除: if (oldest is null) break; | |
| 136 | 删除: Downloads.Remove(oldest.ID); | |
| 137 | 删除: } | |
| 211 | 新增: Watching.Add(item.ID); | |
| 138 | 212 | Downloads.Add(item.ID, item); |
| 139 | 删除: Persist(); | |
| 140 | 删除: try { submit(Source(item)); } | |
| 213 | 新增: try { Persist(); submit(Source(item)); } | |
| 141 | 214 | catch |
| 142 | 215 | { |
| 143 | 删除: watcher.Dispose(); item.State = "failed"; item.Error = "客机保存窗口未接收文件位置,请重新下载。"; Persist(); throw; | |
| 216 | 新增: watcher.Dispose(); Watching.Remove(item.ID); item.State = "failed"; item.Error = "客机保存窗口未接收文件位置,请重新下载。"; Persist(); throw; | |
| 144 | 217 | } |
| 145 | 218 | _ = Task.Run(async () => |
| 146 | 219 | { |
| @@ -162,6 +235,7 @@ internal static class WindowsDesktopDownloads | ||
| 162 | 235 | lock (Gate) |
| 163 | 236 | { |
| 164 | 237 | item.Size = source.Length; item.Written = File.GetLastWriteTimeUtc(Source(item)).Ticks; |
| 238 | 新增: item.Identity = FileIdentity(source.SafeFileHandle); | |
| 165 | 239 | item.State = "saved"; Persist(); |
| 166 | 240 | } |
| 167 | 241 | return; |
| @@ -175,6 +249,7 @@ internal static class WindowsDesktopDownloads | ||
| 175 | 249 | { |
| 176 | 250 | lock (Gate) { item.State = "failed"; item.Error = "未能确认文件保存完成,请从 Claude Desktop 重新下载。"; Persist(); } |
| 177 | 251 | } |
| 252 | 新增: finally { watcher.Dispose(); lock (Gate) Watching.Remove(item.ID); } | |
| 178 | 253 | } |
| 179 | 254 | }); |
| 180 | 255 | return item.ID; |
| @@ -189,6 +264,7 @@ internal static class WindowsDesktopDownloads | ||
| 189 | 264 | return new JsonArray(Downloads.Values.TakeLast(100).Reverse().Select(item => (JsonNode)new JsonObject |
| 190 | 265 | { |
| 191 | 266 | ["id"] = item.ID, ["name"] = item.Name, ["state"] = item.State, ["target"] = "desktop", |
| 267 | 新增: ["acknowledged"] = item.Acknowledged, | |
| 192 | 268 | ["receivedBytes"] = item.Size, ["totalBytes"] = item.Size, ["retryable"] = false, |
| 193 | 269 | ["error"] = item.Error, ["startedAt"] = item.Started.ToString("O"), |
| 194 | 270 | }).ToArray()); |
| @@ -218,6 +294,34 @@ internal static class WindowsDesktopDownloads | ||
| 218 | 294 | foreach (var pair in Transfers.ToArray()) |
| 219 | 295 | if (!pair.Value.SessionValid || DateTimeOffset.UtcNow - pair.Value.Used > TimeSpan.FromMinutes(2)) { pair.Value.File.Dispose(); Transfers.Remove(pair.Key); } |
| 220 | 296 | var action = input["action"]?.GetValue<string>(); |
| 297 | 新增: if (action == "files-download-ack") | |
| 298 | 新增: { | |
| 299 | 新增: var ids = input["ids"] as JsonArray; | |
| 300 | 新增: if (ids is null || ids.Count > 100 || ids.Any(value => value is not JsonValue scalar || !scalar.TryGetValue<string>(out var id) || !Guid.TryParseExact(id, "D", out _))) | |
| 301 | 新增: throw new InvalidDataException("desktop_download_ack_invalid"); | |
| 302 | 新增: var changed = new List<Download>(); | |
| 303 | 新增: try | |
| 304 | 新增: { | |
| 305 | 新增: foreach (var value in ids) | |
| 306 | 新增: { | |
| 307 | 新增: if (!Downloads.TryGetValue(value!.GetValue<string>(), out var item) || item.State != "saved" || item.Acknowledged) continue; | |
| 308 | 新增: if (item.Identity is null) | |
| 309 | 新增: { | |
| 310 | 新增: try | |
| 311 | 新增: { | |
| 312 | 新增: using var file = OpenSource(item); | |
| 313 | 新增: if (file.Length == item.Size && File.GetLastWriteTimeUtc(Source(item)).Ticks == item.Written) item.Identity = FileIdentity(file.SafeFileHandle); | |
| 314 | 新增: } | |
| 315 | 新增: catch (IOException) { } | |
| 316 | 新增: catch (UnauthorizedAccessException) { } | |
| 317 | 新增: } | |
| 318 | 新增: item.Acknowledged = true; changed.Add(item); | |
| 319 | 新增: } | |
| 320 | 新增: if (changed.Count > 0) Persist(); | |
| 321 | 新增: } | |
| 322 | 新增: catch { foreach (var item in changed) item.Acknowledged = false; throw; } | |
| 323 | 新增: return new JsonObject { ["ok"] = true }; | |
| 324 | 新增: } | |
| 221 | 325 | if (action == "files-download-retry") |
| 222 | 326 | { |
| 223 | 327 | var id = input["id"]?.GetValue<string>() ?? ""; |
| @@ -236,7 +340,7 @@ internal static class WindowsDesktopDownloads | ||
| 236 | 340 | if (file.Length != item.Size || File.GetLastWriteTimeUtc(Source(item)).Ticks != item.Written) |
| 237 | 341 | { file.Dispose(); throw new InvalidDataException("desktop_download_changed"); } |
| 238 | 342 | var key = Convert.ToHexString(RandomNumberGenerator.GetBytes(32)).ToLowerInvariant(); |
| 239 | 删除: Transfers.Add(key, new Transfer(file, agent.Session, agent.SessionEpoch)); | |
| 343 | 新增: Transfers.Add(key, new Transfer(file, item.ID, agent.Session, agent.SessionEpoch)); | |
| 240 | 344 | return new JsonObject { ["transfer"] = key, ["size"] = file.Length, ["name"] = item.Name }; |
| 241 | 345 | } |
| 242 | 346 | var transfer = input["transfer"]?.GetValue<string>() ?? ""; |
| @@ -145,7 +145,7 @@ internal static class WindowsDesktopFiles | ||
| 145 | 145 | { |
| 146 | 146 | ["id"] = value.ID, ["target"] = "desktop", ["kind"] = "chooser", ["multiple"] = value.Multiple, ["directory"] = value.Directory, |
| 147 | 147 | }).ToArray()), |
| 148 | 删除: ["downloads"] = WindowsDesktopDownloads.Snapshot(), ["opens"] = OpenSnapshot(), | |
| 148 | 新增: ["downloads"] = WindowsDesktopDownloads.Snapshot(), ["downloadAck"] = true, ["opens"] = OpenSnapshot(), | |
| 149 | 149 | }; |
| 150 | 150 | } |
| 151 | 151 | } |
| @@ -162,14 +162,26 @@ internal static class WindowsDesktopFiles | ||
| 162 | 162 | |
| 163 | 163 | internal static void QueueOpen(string path, string action, Action validate) |
| 164 | 164 | { |
| 165 | 删除: if (!Path.IsPathFullyQualified(path) || path.Length > 32767 || path.Contains('\0') || action is not ("open" or "reveal")) | |
| 165 | 新增: QueueOpen([path], action, validate); | |
| 166 | 新增: } | |
| 167 | 新增: | |
| 168 | 新增: internal static void QueueOpen(string[] paths, string action, Action validate) | |
| 169 | 新增: { | |
| 170 | 新增: if (paths.Length is < 1 or > 32 || action is not ("open" or "reveal") || | |
| 171 | 新增: paths.Any(path => string.IsNullOrEmpty(path) || !Path.IsPathFullyQualified(path) || path.Length > 32767 || path.Contains('\0'))) | |
| 166 | 172 | throw new InvalidDataException("file_open_request_invalid"); |
| 173 | 新增: var normalized = paths.Select(Path.GetFullPath).ToArray(); | |
| 167 | 174 | lock (Gate) |
| 168 | 175 | { |
| 169 | 删除: SessionGuard.Assert(); ExpireOpens(); validate(); | |
| 176 | 新增: SessionGuard.Assert(); ExpireOpens(); | |
| 170 | 177 | var agent = ClipboardAgent.Current; |
| 171 | 删除: if (agent is null || !agent.SessionEventsRegistered || Opens.Count >= 32) throw new InvalidDataException("file_open_request_unavailable"); | |
| 172 | 删除: Opens.Add(Guid.NewGuid().ToString("D"), new OpenRequest(Path.GetFullPath(path), action, agent.Session, agent.SessionEpoch, validate)); | |
| 178 | 新增: if (agent is null || !agent.SessionEventsRegistered) throw new InvalidDataException("file_open_request_unavailable"); | |
| 179 | 新增: var epoch = agent.SessionEpoch; | |
| 180 | 新增: validate(); | |
| 181 | 新增: if (ClipboardAgent.Current != agent || agent.SessionEpoch != epoch) throw new InvalidDataException("file_open_target_changed"); | |
| 182 | 新增: if (Opens.Count + normalized.Length > 32) throw new InvalidDataException("file_open_request_limit"); | |
| 183 | 新增: foreach (var path in normalized) | |
| 184 | 新增: Opens.Add(Guid.NewGuid().ToString("D"), new OpenRequest(path, action, agent.Session, epoch, validate)); | |
| 173 | 185 | } |
| 174 | 186 | } |
| 175 | 187 | |
| @@ -55,9 +55,11 @@ if($service){ | ||
| 55 | 55 | $existing=Get-CimInstance Win32_Service -Filter ("Name='"+$name+"'") |
| 56 | 56 | if($existing.PathName -cne $binary -or $existing.StartName -notin @('LocalSystem','NT AUTHORITY\SYSTEM')){throw 'An unrelated service already uses this name.'} |
| 57 | 57 | } |
| 58 | 删除:# Verify the retained VM before stopping the existing helper. Prepare uses the | |
| 59 | 删除:# checked protected copy in the installing administrator's token. | |
| 60 | 删除:$raw=& $payload.FullName prepare --vm-id $VMId.ToString('D') --host-sid $HostSID | |
| 58 | 新增:# Existing installations retain their protected authority and recovery journal. | |
| 59 | 新增:# They can repair a stopped helper while its bound data volume is disconnected. | |
| 60 | 新增:# Fresh registration verifies the actual VM using the protected payload copy. | |
| 61 | 新增:$operation=if(Test-Path -LiteralPath $bindingPath){'binding'}else{'prepare'} | |
| 62 | 新增:$raw=& $payload.FullName $operation --vm-id $VMId.ToString('D') --host-sid $HostSID | |
| 61 | 63 | if($LASTEXITCODE -ne 0){throw 'The exact VM/disk binding could not be verified.'} |
| 62 | 64 | $binding=$raw|ConvertFrom-Json |
| 63 | 65 | if($binding.version -ne 1 -or [guid]$binding.vm_id -ne $VMId -or $binding.host_sid -cne $HostSID){throw 'The prepared manager binding does not match.'} |
| @@ -111,11 +111,13 @@ export async function serveMacOSBrowser({ directory, dispatch, close, disconnect | ||
| 111 | 111 | if (!stopping) stopping = (async () => { |
| 112 | 112 | const closed = new Promise(resolve => server.close(resolve)); |
| 113 | 113 | for (const client of clients) client.destroy(); |
| 114 | 删除: await close(); | |
| 115 | 删除: await queue; | |
| 116 | 删除: await closed; | |
| 117 | 删除: const current = await fs.lstat(address).catch(() => null); | |
| 118 | 删除: if (current?.ino === owned.ino) await fs.unlink(address); | |
| 114 | 新增: try { await close(); } | |
| 115 | 新增: finally { | |
| 116 | 新增: await closed; | |
| 117 | 新增: await queue; | |
| 118 | 新增: const current = await fs.lstat(address).catch(() => null); | |
| 119 | 新增: if (current?.ino === owned.ino) await fs.unlink(address); | |
| 120 | 新增: } | |
| 119 | 121 | })(); |
| 120 | 122 | return stopping; |
| 121 | 123 | }; |
| @@ -26,6 +26,7 @@ struct Request: Decodable { | ||
| 26 | 26 | var refresh: Bool? |
| 27 | 27 | var wait, binary: Bool? |
| 28 | 28 | var id, kind: String? |
| 29 | 新增: var ids: [String]? | |
| 29 | 30 | var transfer: String? |
| 30 | 31 | var sequence: Int? |
| 31 | 32 | var path: String? |
| @@ -246,7 +247,7 @@ private func handle(_ input: Request, inputSession: MacWindowInputSession) async | ||
| 246 | 247 | return await MacDesktopFiles.shared.cancel(input.id ?? "") |
| 247 | 248 | case "files-poll": |
| 248 | 249 | return try await MacDesktopFiles.shared.poll() |
| 249 | 删除: case "files-download-open", "files-download-read", "files-download-close", "files-download-retry": | |
| 250 | 新增: case "files-download-open", "files-download-read", "files-download-close", "files-download-retry", "files-download-ack": | |
| 250 | 251 | return try MacDesktopDownloads.shared.read(input) |
| 251 | 252 | case "files-open-claim", "files-open-complete": |
| 252 | 253 | return try MacDesktopFiles.shared.openAction(input.id ?? "", complete: input.action == "files-open-complete") |
| @@ -255,20 +256,7 @@ private func handle(_ input: Request, inputSession: MacWindowInputSession) async | ||
| 255 | 256 | case "setup-status": |
| 256 | 257 | return ["screen": CGPreflightScreenCaptureAccess(), "input": AXIsProcessTrusted()] |
| 257 | 258 | case "setup-password-focus": |
| 258 | 删除: guard AXIsProcessTrusted(), let app = NSWorkspace.shared.frontmostApplication, | |
| 259 | 删除: app.bundleIdentifier == "com.apple.authorizationhost" else { return ["focused":false] } | |
| 260 | 删除: var code: SecCode? | |
| 261 | 删除: var rule: SecRequirement? | |
| 262 | 删除: guard SecCodeCopyGuestWithAttributes(nil, [kSecGuestAttributePid as String:app.processIdentifier] as CFDictionary, [], &code) == errSecSuccess, | |
| 263 | 删除: SecRequirementCreateWithString("anchor apple and identifier com.apple.authorizationhost" as CFString, [], &rule) == errSecSuccess, | |
| 264 | 删除: let code, let rule, SecCodeCheckValidity(code, [], rule) == errSecSuccess else { return ["focused":false] } | |
| 265 | 删除: var value: CFTypeRef? | |
| 266 | 删除: let element = AXUIElementCreateApplication(app.processIdentifier) | |
| 267 | 删除: guard AXUIElementCopyAttributeValue(element,kAXFocusedUIElementAttribute as CFString,&value) == .success, | |
| 268 | 删除: let value, CFGetTypeID(value) == AXUIElementGetTypeID() else { return ["focused":false] } | |
| 269 | 删除: var subrole: CFTypeRef? | |
| 270 | 删除: guard AXUIElementCopyAttributeValue(value as! AXUIElement,kAXSubroleAttribute as CFString,&subrole) == .success else { return ["focused":false] } | |
| 271 | 删除: return ["focused":subrole as? String == kAXSecureTextFieldSubrole] | |
| 259 | 新增: return try MacSetupPassword.probe() | |
| 272 | 260 | case "setup-screen", "setup-input", "setup-projects": |
| 273 | 261 | let pane: String |
| 274 | 262 | if input.action == "setup-screen" { |
| @@ -453,6 +441,27 @@ private func respondConnection(_ fd: Int32, inputSession: MacWindowInputSession) | ||
| 453 | 441 | @main |
| 454 | 442 | struct ClaudeWindowService { |
| 455 | 443 | static func main() { |
| 444 | 新增: let arguments = Array(CommandLine.arguments.dropFirst()) | |
| 445 | 新增: if arguments == ["--setup-password-probe"] { MacSetupPassword.runStream() } | |
| 446 | 新增: if arguments.count == 2 && ["--maintenance-open", "--maintenance-probe", "--maintenance-password-probe"].contains(arguments[0]) { | |
| 447 | 新增: if arguments[0] == "--maintenance-password-probe" { MacMaintenance.runPasswordProbe(purpose: arguments[1]) } | |
| 448 | 新增: let result: [String: Any] | |
| 449 | 新增: do { result = try MacMaintenance.run(arguments[0] == "--maintenance-open" ? "open" : "probe", purpose: arguments[1]) } | |
| 450 | 新增: catch { result = ["error": (error as? Failure)?.message ?? "maintenance_unavailable"] } | |
| 451 | 新增: if let data = try? JSONSerialization.data(withJSONObject: result) { | |
| 452 | 新增: FileHandle.standardOutput.write(data) | |
| 453 | 新增: FileHandle.standardOutput.write(Data([10])) | |
| 454 | 新增: } | |
| 455 | 新增: return | |
| 456 | 新增: } | |
| 457 | 新增: if CommandLine.arguments.dropFirst() == ["--setup-password-self-test"] { | |
| 458 | 新增: do { try MacSetupPassword.selfTest(); return } | |
| 459 | 新增: catch { fputs("macOS setup password self-test failed\n", stderr); exit(1) } | |
| 460 | 新增: } | |
| 461 | 新增: if CommandLine.arguments.dropFirst() == ["--native-open-self-test"] { | |
| 462 | 新增: do { try MacNativeOpen.selfTest(); return } | |
| 463 | 新增: catch { fputs("macOS native open self-test failed (\((error as? Failure)?.message ?? "unknown error"))\n", stderr); exit(1) } | |
| 464 | 新增: } | |
| 456 | 465 | if CommandLine.arguments.dropFirst() == ["--phone-self-test"] { |
| 457 | 466 | do { try MacPhoneDesktop.selfTest(); return } |
| 458 | 467 | catch { fputs("macOS phone desktop self-test failed\n", stderr); exit(1) } |
| @@ -472,6 +481,11 @@ struct ClaudeWindowService { | ||
| 472 | 481 | free(sockets) |
| 473 | 482 | GuestDiagnostic.record("window", "started") |
| 474 | 483 | NSApplication.shared.setActivationPolicy(.accessory) |
| 484 | 新增: MacNativeOpen.shared.install() | |
| 485 | 新增: Task { @MainActor in | |
| 486 | 新增: do { try await MacNativeOpen.shared.prepareMetadata() } | |
| 487 | 新增: catch { GuestDiagnostic.record("files", (error as? Failure)?.message ?? "file_open_metadata_failed") } | |
| 488 | 新增: } | |
| 475 | 489 | DispatchQueue.global(qos: .userInitiated).async { |
| 476 | 490 | let connections = DispatchSemaphore(value: 16) |
| 477 | 491 | while true { |
| @@ -11,6 +11,10 @@ final class MacDesktopDownloads { | ||
| 11 | 11 | let name: String |
| 12 | 12 | var state = "downloading" |
| 13 | 13 | var error = "" |
| 14 | 新增: var openError: String? | |
| 15 | 新增: var acknowledged: Bool? | |
| 16 | 新增: var device: UInt64? | |
| 17 | 新增: var inode: UInt64? | |
| 14 | 18 | var size: Int64 = 0 |
| 15 | 19 | var modified: Int64 = 0 |
| 16 | 20 | var started = Date() |
| @@ -30,6 +34,8 @@ final class MacDesktopDownloads { | ||
| 30 | 34 | private let baseDirectory: URL |
| 31 | 35 | private var transferTimer: Timer? |
| 32 | 36 | private let timestamp = ISO8601DateFormatter() |
| 37 | 新增: private var openMetadata: Data? | |
| 38 | 新增: private var metadataBound = Set<String>() | |
| 33 | 39 | |
| 34 | 40 | init(directory: URL) { baseDirectory = directory } |
| 35 | 41 | deinit { |
| @@ -59,7 +65,9 @@ final class MacDesktopDownloads { | ||
| 59 | 65 | } |
| 60 | 66 | let data = try Data(contentsOf: manifest, options: .mappedIfSafe) |
| 61 | 67 | guard data.count <= 1 << 20 else { throw Failure(8, "desktop_download_catalog_invalid") } |
| 62 | 删除: records = try JSONDecoder().decode([Record].self, from: data).suffix(100).filter { UUID(uuidString: $0.id) != nil && Self.validName($0.name) } | |
| 68 | 新增: let saved = try JSONDecoder().decode([Record].self, from: data) | |
| 69 | 新增: guard saved.count <= 100 else { throw Failure(8, "desktop_download_catalog_invalid") } | |
| 70 | 新增: records = saved.filter { UUID(uuidString: $0.id) != nil && Self.validName($0.name) } | |
| 63 | 71 | for index in records.indices where records[index].state == "downloading" { |
| 64 | 72 | records[index].state = "failed" |
| 65 | 73 | records[index].error = "保存过程被中断,请从 Claude Desktop 重新下载。" |
| @@ -71,7 +79,7 @@ final class MacDesktopDownloads { | ||
| 71 | 79 | private func source(_ record: Record) throws -> URL { try directory().appendingPathComponent(record.id, isDirectory: true).appendingPathComponent(record.name) } |
| 72 | 80 | private func persist() throws { |
| 73 | 81 | let path = try directory().appendingPathComponent("downloads.json") |
| 74 | 删除: try JSONEncoder().encode(Array(records.suffix(100))).write(to: path, options: .atomic) | |
| 82 | 新增: try JSONEncoder().encode(records).write(to: path, options: .atomic) | |
| 75 | 83 | try FileManager.default.setAttributes([.posixPermissions: 0o600], ofItemAtPath: path.path) |
| 76 | 84 | } |
| 77 | 85 | private func openSource(_ record: Record) throws -> (Int32, stat) { |
| @@ -87,6 +95,86 @@ final class MacDesktopDownloads { | ||
| 87 | 95 | } |
| 88 | 96 | private func modified(_ info: stat) -> Int64 { Int64(info.st_mtimespec.tv_sec) * 1_000_000_000 + Int64(info.st_mtimespec.tv_nsec) } |
| 89 | 97 | |
| 98 | 新增: private func removeSource(_ record: Record) throws { | |
| 99 | 新增: let path = try source(record) | |
| 100 | 新增: let folder = path.deletingLastPathComponent().path | |
| 101 | 新增: let parent = open(folder, O_RDONLY | O_DIRECTORY | O_NOFOLLOW) | |
| 102 | 新增: if parent < 0 && errno == ENOENT { return } | |
| 103 | 新增: guard parent >= 0 else { throw Failure(8, "desktop_download_cleanup_failed") } | |
| 104 | 新增: defer { close(parent) } | |
| 105 | 新增: var directoryInfo = stat(), actual = [CChar](repeating: 0, count: Int(MAXPATHLEN)) | |
| 106 | 新增: guard fstat(parent, &directoryInfo) == 0, directoryInfo.st_uid == getuid(), | |
| 107 | 新增: fcntl(parent, F_GETPATH, &actual) == 0, String(cString: actual) == folder else { throw Failure(8, "desktop_download_directory_invalid") } | |
| 108 | 新增: var info = stat() | |
| 109 | 新增: let found = fstatat(parent, record.name, &info, AT_SYMLINK_NOFOLLOW) | |
| 110 | 新增: if found != 0 && errno != ENOENT { throw Failure(8, "desktop_download_cleanup_failed") } | |
| 111 | 新增: if found == 0 { | |
| 112 | 新增: guard record.state == "saved", info.st_mode & S_IFMT == S_IFREG, info.st_uid == getuid(), info.st_size == record.size, | |
| 113 | 新增: modified(info) == record.modified, record.device == UInt64(UInt32(bitPattern: info.st_dev)), | |
| 114 | 新增: record.inode == UInt64(info.st_ino) else { throw Failure(8, "desktop_download_changed") } | |
| 115 | 新增: guard unlinkat(parent, record.name, 0) == 0 else { throw Failure(8, "desktop_download_cleanup_failed") } | |
| 116 | 新增: } | |
| 117 | 新增: // rmdir preserves any unrecorded sibling, and the open parent prevents | |
| 118 | 新增: // following a replacement directory while removing the recorded leaf. | |
| 119 | 新增: var current = stat() | |
| 120 | 新增: guard lstat(folder, ¤t) == 0, current.st_dev == directoryInfo.st_dev, current.st_ino == directoryInfo.st_ino else { throw Failure(8, "desktop_download_directory_invalid") } | |
| 121 | 新增: let removed = rmdir(folder) | |
| 122 | 新增: if record.state == "failed" && removed != 0 { throw Failure(8, "desktop_download_cleanup_failed") } | |
| 123 | 新增: } | |
| 124 | 新增: | |
| 125 | 新增: private func makeRoom() throws { | |
| 126 | 新增: expireTransfers() | |
| 127 | 新增: guard records.count >= 100 else { return } | |
| 128 | 新增: for record in records { | |
| 129 | 新增: let eligible = (record.state == "saved" && record.acknowledged == true) || (record.state == "failed" && watches[record.id] == nil) | |
| 130 | 新增: guard eligible, !transfers.values.contains(where: { $0.record.id == record.id }) else { continue } | |
| 131 | 新增: do { | |
| 132 | 新增: try removeSource(record) | |
| 133 | 新增: records.removeAll { $0.id == record.id } | |
| 134 | 新增: metadataBound.remove(record.id) | |
| 135 | 新增: return | |
| 136 | 新增: } catch { /* Keep the receipt when ownership, contents, or permissions changed. */ } | |
| 137 | 新增: } | |
| 138 | 新增: throw Failure(8, "desktop_download_limit") | |
| 139 | 新增: } | |
| 140 | 新增: | |
| 141 | 新增: private func bindOpenMetadata(_ metadata: Data, fd: Int32, info: stat) throws { | |
| 142 | 新增: let name = "com.apple.LaunchServices.OpenWith" | |
| 143 | 新增: guard !metadata.isEmpty, metadata.count <= 1 << 20 else { throw Failure(8, "desktop_download_open_metadata_failed") } | |
| 144 | 新增: if fgetxattr(fd, name, nil, 0, 0, 0) == metadata.count { | |
| 145 | 新增: var current = Data(count: metadata.count) | |
| 146 | 新增: let count = current.withUnsafeMutableBytes { fgetxattr(fd, name, $0.baseAddress, $0.count, 0, 0) } | |
| 147 | 新增: if count == metadata.count && current == metadata { return } | |
| 148 | 新增: } | |
| 149 | 新增: let written = metadata.withUnsafeBytes { fsetxattr(fd, name, $0.baseAddress, $0.count, 0, 0) } | |
| 150 | 新增: var current = Data(count: metadata.count), after = stat() | |
| 151 | 新增: let count = current.withUnsafeMutableBytes { fgetxattr(fd, name, $0.baseAddress, $0.count, 0, 0) } | |
| 152 | 新增: guard written == 0, count == metadata.count, current == metadata else { throw Failure(8, "desktop_download_open_metadata_failed") } | |
| 153 | 新增: guard fstat(fd, &after) == 0, after.st_dev == info.st_dev, after.st_ino == info.st_ino, | |
| 154 | 新增: after.st_size == info.st_size, modified(after) == modified(info) else { throw Failure(8, "desktop_download_changed") } | |
| 155 | 新增: } | |
| 156 | 新增: | |
| 157 | 新增: private func refreshOpenMetadata() throws { | |
| 158 | 新增: guard let metadata = MacNativeOpen.shared.openWithMetadata else { return } | |
| 159 | 新增: if openMetadata != metadata { openMetadata = metadata; metadataBound.removeAll() } | |
| 160 | 新增: var changed = false | |
| 161 | 新增: for index in records.indices where records[index].state == "saved" && !metadataBound.contains(records[index].id) { | |
| 162 | 新增: let previous = records[index].openError | |
| 163 | 新增: do { | |
| 164 | 新增: let (fd, info) = try openSource(records[index]) | |
| 165 | 新增: defer { close(fd) } | |
| 166 | 新增: guard info.st_size == records[index].size, modified(info) == records[index].modified else { throw Failure(8, "desktop_download_changed") } | |
| 167 | 新增: try bindOpenMetadata(metadata, fd: fd, info: info) | |
| 168 | 新增: metadataBound.insert(records[index].id) | |
| 169 | 新增: records[index].openError = nil | |
| 170 | 新增: } catch { | |
| 171 | 新增: records[index].openError = "文件打开关联未能完成,请在 Cage 下载列表中打开文件。" | |
| 172 | 新增: } | |
| 173 | 新增: changed = changed || previous != records[index].openError | |
| 174 | 新增: } | |
| 175 | 新增: if changed { try persist() } | |
| 176 | 新增: } | |
| 177 | 新增: | |
| 90 | 178 | private func expireTransfers() { |
| 91 | 179 | let epoch = try? MacGUISession.shared.validate() |
| 92 | 180 | for (key, transfer) in transfers where epoch != transfer.epoch || Date().timeIntervalSince(transfer.used) > 120 { |
| @@ -98,6 +186,7 @@ final class MacDesktopDownloads { | ||
| 98 | 186 | func reserve(name: String, pid: Int32, submit: (String) async throws -> Void) async throws { |
| 99 | 187 | _ = try directory() |
| 100 | 188 | guard Self.validName(name), records.filter({ $0.state == "downloading" }).count < 12 else { throw Failure(8, "desktop_download_limit") } |
| 189 | 新增: try makeRoom() | |
| 101 | 190 | let record = Record(id: UUID().uuidString.lowercased(), name: name) |
| 102 | 191 | let path = try source(record) |
| 103 | 192 | try FileManager.default.createDirectory(at: path.deletingLastPathComponent(), withIntermediateDirectories: false, attributes: [.posixPermissions: 0o700]) |
| @@ -107,7 +196,6 @@ final class MacDesktopDownloads { | ||
| 107 | 196 | else { self?.fail(record.id, message: "保存通知已中断,请从 Claude Desktop 重新下载。") } |
| 108 | 197 | } |
| 109 | 198 | } |
| 110 | 删除: while records.count >= 100, let oldest = records.firstIndex(where: { $0.state != "downloading" }) { records.remove(at: oldest) } | |
| 111 | 199 | records.append(record); watches[record.id] = watcher |
| 112 | 200 | do { try persist(); try await submit(path.path) } |
| 113 | 201 | catch { fail(record.id, message: "客机保存窗口未接收文件位置,请重新下载。"); throw error } |
| @@ -140,6 +228,12 @@ final class MacDesktopDownloads { | ||
| 140 | 228 | defer { close(fd) } |
| 141 | 229 | guard let index = records.firstIndex(where: { $0.id == id }) else { return } |
| 142 | 230 | records[index].size = info.st_size; records[index].modified = modified(info); records[index].state = "saved" |
| 231 | 新增: records[index].device = UInt64(UInt32(bitPattern: info.st_dev)); records[index].inode = UInt64(info.st_ino) | |
| 232 | 新增: if let metadata = MacNativeOpen.shared.openWithMetadata { | |
| 233 | 新增: if openMetadata != metadata { openMetadata = metadata; metadataBound.removeAll() } | |
| 234 | 新增: do { try bindOpenMetadata(metadata, fd: fd, info: info); metadataBound.insert(id) } | |
| 235 | 新增: catch { records[index].openError = "文件打开关联未能完成,请在 Cage 下载列表中打开文件。" } | |
| 236 | 新增: } | |
| 143 | 237 | try persist(); watches.removeValue(forKey: id)?.stop(); return |
| 144 | 238 | } |
| 145 | 239 | } catch { } |
| @@ -149,10 +243,12 @@ final class MacDesktopDownloads { | ||
| 149 | 243 | } |
| 150 | 244 | func snapshot() throws -> [[String: Any]] { |
| 151 | 245 | _ = try directory() |
| 246 | 新增: try refreshOpenMetadata() | |
| 152 | 247 | return records.suffix(100).reversed().map { record in |
| 153 | 248 | ["id": record.id, "name": record.name, "target": "desktop", "state": record.state, |
| 249 | 新增: "acknowledged": record.acknowledged ?? false, | |
| 154 | 250 | "receivedBytes": record.size, "totalBytes": record.size, "retryable": false, |
| 155 | 删除: "error": record.error, "startedAt": timestamp.string(from: record.started)] | |
| 251 | 新增: "error": record.error, "openError": record.openError ?? "", "startedAt": timestamp.string(from: record.started)] | |
| 156 | 252 | } |
| 157 | 253 | } |
| 158 | 254 | func find(path: String) throws -> (id: String, directory: Bool)? { |
| @@ -170,6 +266,27 @@ final class MacDesktopDownloads { | ||
| 170 | 266 | for (key, transfer) in transfers where transfer.epoch != epoch || Date().timeIntervalSince(transfer.used) > 120 { |
| 171 | 267 | close(transfer.fd); transfers.removeValue(forKey: key) |
| 172 | 268 | } |
| 269 | 新增: if input.action == "files-download-ack" { | |
| 270 | 新增: guard let ids = input.ids, ids.count <= 100, ids.allSatisfy({ UUID(uuidString: $0) != nil }) else { throw Failure(8, "desktop_download_ack_invalid") } | |
| 271 | 新增: let previous = records | |
| 272 | 新增: var changed = false | |
| 273 | 新增: do { | |
| 274 | 新增: for index in records.indices where ids.contains(records[index].id) && records[index].state == "saved" && records[index].acknowledged != true { | |
| 275 | 新增: if records[index].device == nil || records[index].inode == nil { | |
| 276 | 新增: if let (fd, info) = try? openSource(records[index]) { | |
| 277 | 新增: defer { close(fd) } | |
| 278 | 新增: if info.st_size == records[index].size && modified(info) == records[index].modified { | |
| 279 | 新增: records[index].device = UInt64(UInt32(bitPattern: info.st_dev)); records[index].inode = UInt64(info.st_ino) | |
| 280 | 新增: } | |
| 281 | 新增: } | |
| 282 | 新增: } | |
| 283 | 新增: records[index].acknowledged = true | |
| 284 | 新增: changed = true | |
| 285 | 新增: } | |
| 286 | 新增: if changed { try persist() } | |
| 287 | 新增: } catch { records = previous; throw error } | |
| 288 | 新增: return ["ok": true] | |
| 289 | 新增: } | |
| 173 | 290 | if input.action == "files-download-retry" { |
| 174 | 291 | guard let record = records.first(where: { $0.id == input.id }), record.state == "saved" else { throw Failure(8, "desktop_download_incomplete") } |
| 175 | 292 | let (fd, info) = try openSource(record) |
| @@ -493,7 +493,7 @@ final class MacDesktopFiles { | ||
| 493 | 493 | if !value.files.isEmpty { Task { _ = try? await clipboardRequest(["operation": "discard", "files": value.files]) } } |
| 494 | 494 | } |
| 495 | 495 | guard AXIsProcessTrusted(), let pid = try? claudePIDs().first else { |
| 496 | 删除: return ["available": false, "uploads": [], "downloads": try MacDesktopDownloads.shared.snapshot(), "opens": openSnapshot()] | |
| 496 | 新增: return ["available": false, "uploads": [], "downloads": try MacDesktopDownloads.shared.snapshot(), "downloadAck": true, "opens": openSnapshot()] | |
| 497 | 497 | } |
| 498 | 498 | if let (panel, field) = saveFilePanel(pid) { |
| 499 | 499 | if savingPanel == nil || !CFEqual(savingPanel!, panel) { |
| @@ -509,7 +509,7 @@ final class MacDesktopFiles { | ||
| 509 | 509 | batches.removeValue(forKey: id) |
| 510 | 510 | if !value.files.isEmpty { Task { _ = try? await clipboardRequest(["operation": "discard", "files": value.files]) } } |
| 511 | 511 | } |
| 512 | 删除: return ["available": true, "uploads": [], "downloads": try MacDesktopDownloads.shared.snapshot(), "opens": openSnapshot()] | |
| 512 | 新增: return ["available": true, "uploads": [], "downloads": try MacDesktopDownloads.shared.snapshot(), "downloadAck": true, "opens": openSnapshot()] | |
| 513 | 513 | } |
| 514 | 514 | let existing = batches.first { $0.value.pid == pid && $0.value.panel.map { CFEqual($0, panel) } == true } |
| 515 | 515 | let id: String |
| @@ -519,7 +519,7 @@ final class MacDesktopFiles { | ||
| 519 | 519 | id = UUID().uuidString.lowercased() |
| 520 | 520 | batches[id] = Batch(pid: pid, window: 0, kind: "chooser", epoch: try MacGUISession.shared.validate(), panel: panel) |
| 521 | 521 | } |
| 522 | 删除: return ["available": true, "uploads": [["id": id, "kind": "chooser", "multiple": true, "directory": false, "target": "desktop"]], "downloads": try MacDesktopDownloads.shared.snapshot(), "opens": openSnapshot()] | |
| 522 | 新增: return ["available": true, "uploads": [["id": id, "kind": "chooser", "multiple": true, "directory": false, "target": "desktop"]], "downloads": try MacDesktopDownloads.shared.snapshot(), "downloadAck": true, "opens": openSnapshot()] | |
| 523 | 523 | } |
| 524 | 524 | |
| 525 | 525 | func pasteImage(_ data: Data, window: SCWindow) async throws -> [String: Any] { |
| @@ -0,0 +1,114 @@ | ||
| 1 | 新增:import AppKit | |
| 2 | 新增:import IOKit | |
| 3 | 新增:import Security | |
| 4 | 新增: | |
| 5 | 新增:// Invoked directly by the installation identity after verifying this bundle. | |
| 6 | 新增:// Only Apple system settings and its authorization UI can supply a target. | |
| 7 | 新增:@MainActor | |
| 8 | 新增:enum MacMaintenance { | |
| 9 | 新增: private static let applications: Set<String> = ["com.apple.systempreferences", "com.apple.authorizationhost"] | |
| 10 | 新增: private static let panes = [ | |
| 11 | 新增: "projects": "x-apple.systempreferences:com.apple.LoginItems-Settings.extension", | |
| 12 | 新增: "screen": "x-apple.systempreferences:com.apple.preference.security?Privacy_ScreenCapture", | |
| 13 | 新增: "input": "x-apple.systempreferences:com.apple.preference.security?Privacy_Accessibility", | |
| 14 | 新增: ] | |
| 15 | 新增: | |
| 16 | 新增: static func runPasswordProbe(purpose: String) -> Never { | |
| 17 | 新增: guard panes[purpose] != nil else { exit(2) } | |
| 18 | 新增: MacSetupPassword.runStream() | |
| 19 | 新增: } | |
| 20 | 新增: | |
| 21 | 新增: private static func consoleSession() throws -> String { | |
| 22 | 新增: try consoleUser() | |
| 23 | 新增: let entry = IORegistryGetRootEntry(kIOMainPortDefault) | |
| 24 | 新增: guard entry != 0 else { throw Failure(4, "requires_gui_login") } | |
| 25 | 新增: defer { IOObjectRelease(entry) } | |
| 26 | 新增: guard let property = IORegistryEntryCreateCFProperty(entry, "IOConsoleUsers" as CFString, kCFAllocatorDefault, 0)?.takeRetainedValue(), | |
| 27 | 新增: let sessions = property as? [[String: Any]] else { throw Failure(4, "requires_gui_login") } | |
| 28 | 新增: let active = sessions.filter { $0["kCGSSessionOnConsoleKey"] as? Bool == true } | |
| 29 | 新增: guard active.count == 1, let current = active.first, | |
| 30 | 新增: current["kCGSessionLoginDoneKey"] as? Bool == true, | |
| 31 | 新增: current["CGSSessionScreenIsLocked"] as? Bool != true, | |
| 32 | 新增: current["kCGSSessionUserIDKey"] as? UInt32 == getuid(), | |
| 33 | 新增: current["kCGSSessionUserNameKey"] as? String == NSUserName(), | |
| 34 | 新增: let session = current["CGSSessionUniqueSessionUUID"] as? String, | |
| 35 | 新增: UUID(uuidString: session) != nil else { throw Failure(4, "requires_gui_login") } | |
| 36 | 新增: return session | |
| 37 | 新增: } | |
| 38 | 新增: | |
| 39 | 新增: private static func verified(_ app: NSRunningApplication) -> Bool { | |
| 40 | 新增: guard let bundle = app.bundleIdentifier, applications.contains(bundle) else { return false } | |
| 41 | 新增: var code: SecCode?, requirement: SecRequirement? | |
| 42 | 新增: return SecRequirementCreateWithString("anchor apple and identifier \"\(bundle)\"" as CFString, [], &requirement) == errSecSuccess && | |
| 43 | 新增: SecCodeCopyGuestWithAttributes(nil, [kSecGuestAttributePid as String: app.processIdentifier] as CFDictionary, [], &code) == errSecSuccess && | |
| 44 | 新增: code != nil && requirement != nil && SecCodeCheckValidity(code!, [], requirement!) == errSecSuccess | |
| 45 | 新增: } | |
| 46 | 新增: | |
| 47 | 新增: private static func passwordFocused(_ app: NSRunningApplication, window: CGRect) -> Bool { | |
| 48 | 新增: guard let bundle = app.bundleIdentifier, applications.contains(bundle), AXIsProcessTrusted() else { return false } | |
| 49 | 新增: let application = AXUIElementCreateApplication(app.processIdentifier) | |
| 50 | 新增: AXUIElementSetMessagingTimeout(application, 0.5) | |
| 51 | 新增: func attribute(_ element: AXUIElement, _ name: String) -> CFTypeRef? { | |
| 52 | 新增: var value: CFTypeRef? | |
| 53 | 新增: return AXUIElementCopyAttributeValue(element, name as CFString, &value) == .success ? value : nil | |
| 54 | 新增: } | |
| 55 | 新增: guard let value = attribute(application, kAXFocusedUIElementAttribute), CFGetTypeID(value) == AXUIElementGetTypeID() else { return false } | |
| 56 | 新增: let field = value as! AXUIElement | |
| 57 | 新增: var pid: pid_t = 0 | |
| 58 | 新增: guard AXUIElementGetPid(field, &pid) == .success, pid == app.processIdentifier, | |
| 59 | 新增: attribute(field, kAXSubroleAttribute) as? String == kAXSecureTextFieldSubrole, | |
| 60 | 新增: attribute(field, kAXEnabledAttribute) as? Bool == true, | |
| 61 | 新增: let rawWindow = attribute(field, kAXWindowAttribute), CFGetTypeID(rawWindow) == AXUIElementGetTypeID() else { return false } | |
| 62 | 新增: let owner = rawWindow as! AXUIElement | |
| 63 | 新增: var origin = CGPoint.zero, size = CGSize.zero | |
| 64 | 新增: guard let position = attribute(owner, kAXPositionAttribute), let extent = attribute(owner, kAXSizeAttribute), | |
| 65 | 新增: CFGetTypeID(position) == AXValueGetTypeID(), CFGetTypeID(extent) == AXValueGetTypeID(), | |
| 66 | 新增: AXValueGetValue(position as! AXValue, .cgPoint, &origin), AXValueGetValue(extent as! AXValue, .cgSize, &size) else { return false } | |
| 67 | 新增: return abs(origin.x - window.minX) < 1 && abs(origin.y - window.minY) < 1 && | |
| 68 | 新增: abs(size.width - window.width) < 1 && abs(size.height - window.height) < 1 | |
| 69 | 新增: } | |
| 70 | 新增: | |
| 71 | 新增: static func run(_ operation: String, purpose: String) throws -> [String: Any] { | |
| 72 | 新增: try requireGuest() | |
| 73 | 新增: let session = try consoleSession() | |
| 74 | 新增: guard let pane = panes[purpose] else { throw Failure(8, "maintenance_purpose_invalid") } | |
| 75 | 新增: if operation == "open" { | |
| 76 | 新增: if purpose == "projects" { | |
| 77 | 新增: let configuration = NSWorkspace.OpenConfiguration() | |
| 78 | 新增: configuration.activates = false | |
| 79 | 新增: NSWorkspace.shared.openApplication(at: URL(fileURLWithPath: "/Applications/macFUSE.app"), configuration: configuration) | |
| 80 | 新增: } | |
| 81 | 新增: guard let url = URL(string: pane), NSWorkspace.shared.open(url) else { throw Failure(8, "maintenance_open_failed") } | |
| 82 | 新增: return ["opened": true] | |
| 83 | 新增: } | |
| 84 | 新增: guard operation == "probe", let front = NSWorkspace.shared.frontmostApplication, verified(front) else { | |
| 85 | 新增: throw Failure(7, "maintenance_foreground_changed") | |
| 86 | 新增: } | |
| 87 | 新增: guard let windows = CGWindowListCopyWindowInfo([.optionOnScreenOnly, .excludeDesktopElements], kCGNullWindowID) as? [[String: Any]] else { | |
| 88 | 新增: throw Failure(7, "maintenance_window_unavailable") | |
| 89 | 新增: } | |
| 90 | 新增: let display = CGDisplayBounds(CGMainDisplayID()) | |
| 91 | 新增: var covering: [CGRect] = [] | |
| 92 | 新增: for window in windows { | |
| 93 | 新增: guard let raw = window[kCGWindowBounds as String] as? [String: Any], | |
| 94 | 新增: let bounds = CGRect(dictionaryRepresentation: raw as CFDictionary), bounds.width > 0, bounds.height > 0, | |
| 95 | 新增: (window[kCGWindowAlpha as String] as? Double ?? 1) > 0 else { continue } | |
| 96 | 新增: let owner = window[kCGWindowOwnerPID as String] as? Int32 | |
| 97 | 新增: if owner == front.processIdentifier && bounds.width >= 100 && bounds.height >= 60 { | |
| 98 | 新增: let region = bounds.intersection(display) | |
| 99 | 新增: guard !region.isNull, region.width >= 80, region.height >= 40, | |
| 100 | 新增: !covering.contains(where: { $0.intersects(region) }), | |
| 101 | 新增: let id = window[kCGWindowNumber as String] as? UInt32, | |
| 102 | 新增: NSWorkspace.shared.frontmostApplication?.processIdentifier == front.processIdentifier, | |
| 103 | 新增: try consoleSession() == session else { throw Failure(7, "maintenance_window_obscured") } | |
| 104 | 新增: return ["version": 1, "session": session, "user": NSUserName(), "pid": front.processIdentifier, | |
| 105 | 新增: "window": id, "bundle": front.bundleIdentifier!, | |
| 106 | 新增: "password_focused": passwordFocused(front, window: bounds), | |
| 107 | 新增: "rect": [region.minX, region.minY, region.width, region.height], | |
| 108 | 新增: "display": [display.minX, display.minY, display.width, display.height]] | |
| 109 | 新增: } | |
| 110 | 新增: if owner != front.processIdentifier { covering.append(bounds) } | |
| 111 | 新增: } | |
| 112 | 新增: throw Failure(7, "maintenance_window_unavailable") | |
| 113 | 新增: } | |
| 114 | 新增:} | |
| @@ -1,4 +1,4 @@ | ||
| 1 | 删除:// Started by Cage through the bound ordinary user's SSH connection. | |
| 1 | 新增:// The bound guest user's LaunchAgent owns the browser. SSH callers attach as clients. | |
| 2 | 2 | import { installMacOSCLIBrowser } from "./macos-cli-browser.mjs"; |
| 3 | 3 | import { spawn } from "node:child_process"; |
| 4 | 4 | import { randomBytes } from "node:crypto"; |
| @@ -120,7 +120,10 @@ if (process.argv[2] !== "--service") { | ||
| 120 | 120 | let closeLogin; |
| 121 | 121 | try { closeLogin = await installMacOSCLIBrowser(data, message => server.request(message)); } |
| 122 | 122 | catch (error) { await server.close(); throw error; } |
| 123 | 删除: const shutdown = async () => { await server.close(); await closeLogin(); }; | |
| 123 | 新增: const shutdown = async () => { | |
| 124 | 新增: try { await server.close(); } | |
| 125 | 新增: finally { await closeLogin(); } | |
| 126 | 新增: }; | |
| 124 | 127 | process.once("SIGTERM", () => { void shutdown().catch(() => { process.exitCode = 1; }); }); |
| 125 | 128 | process.once("SIGINT", () => { void shutdown().catch(() => { process.exitCode = 1; }); }); |
| 126 | 129 | } |
| @@ -0,0 +1,194 @@ | ||
| 1 | 新增:import AppKit | |
| 2 | 新增:import ApplicationServices | |
| 3 | 新增:import Carbon | |
| 4 | 新增:import Security | |
| 5 | 新增:import UniformTypeIdentifiers | |
| 6 | 新增: | |
| 7 | 新增:// These attributes come from the AppleEvent manager, never from the socket RPC. | |
| 8 | 新增:struct MacOpenSender { | |
| 9 | 新增: let audit: Data | |
| 10 | 新增: let pid: pid_t | |
| 11 | 新增: | |
| 12 | 新增: init?(_ event: NSAppleEventDescriptor) { | |
| 13 | 新增: guard let data = event.attributeDescriptor(forKeyword: AEKeyword(keySenderAuditTokenAttr))?.data, | |
| 14 | 新增: data.count == MemoryLayout<audit_token_t>.size else { return nil } | |
| 15 | 新增: var token = audit_token_t() | |
| 16 | 新增: _ = withUnsafeMutableBytes(of: &token) { data.copyBytes(to: $0) } | |
| 17 | 新增: let process = audit_token_to_pid(token) | |
| 18 | 新增: guard process > 0, audit_token_to_euid(token) == geteuid(), | |
| 19 | 新增: event.attributeDescriptor(forKeyword: AEKeyword(keySenderPIDAttr))?.int32Value == process else { return nil } | |
| 20 | 新增: audit = data | |
| 21 | 新增: pid = process | |
| 22 | 新增: } | |
| 23 | 新增: | |
| 24 | 新增: func isOfficialClaude() -> Bool { | |
| 25 | 新增: guard let application = NSRunningApplication(processIdentifier: pid), !application.isTerminated, | |
| 26 | 新增: application.bundleIdentifier == "com.anthropic.claudefordesktop", | |
| 27 | 新增: application.bundleURL?.resolvingSymlinksInPath() == URL(fileURLWithPath: "/Applications/Claude.app").resolvingSymlinksInPath(), | |
| 28 | 新增: let requirement = try? claudeSigningRequirement() else { return false } | |
| 29 | 新增: var code: SecCode? | |
| 30 | 新增: guard SecCodeCopyGuestWithAttributes(nil, [kSecGuestAttributeAudit as String: audit] as CFDictionary, [], &code) == errSecSuccess, | |
| 31 | 新增: let code else { return false } | |
| 32 | 新增: return SecCodeCheckValidity(code, [], requirement) == errSecSuccess | |
| 33 | 新增: } | |
| 34 | 新增:} | |
| 35 | 新增: | |
| 36 | 新增:@MainActor | |
| 37 | 新增:final class MacNativeOpen: NSObject { | |
| 38 | 新增: static let shared = MacNativeOpen() | |
| 39 | 新增: private(set) var openWithMetadata: Data? | |
| 40 | 新增: | |
| 41 | 新增: func install() { | |
| 42 | 新增: NSAppleEventManager.shared().setEventHandler(self, andSelector: #selector(openDocuments(_:reply:)), | |
| 43 | 新增: forEventClass: AEEventClass(kCoreEventClass), andEventID: AEEventID(kAEOpenDocuments)) | |
| 44 | 新增: } | |
| 45 | 新增: | |
| 46 | 新增: static func fileURLs(_ event: NSAppleEventDescriptor) throws -> [URL] { | |
| 47 | 新增: guard let direct = event.paramDescriptor(forKeyword: AEKeyword(keyDirectObject)), | |
| 48 | 新增: (1...32).contains(direct.numberOfItems) else { throw Failure(8, "file_open_request_invalid") } | |
| 49 | 新增: return try (1...direct.numberOfItems).map { index in | |
| 50 | 新增: guard let descriptor = direct.atIndex(index)?.coerce(toDescriptorType: DescType(typeFileURL)), | |
| 51 | 新增: descriptor.data.count <= 98304, | |
| 52 | 新增: let url = URL(dataRepresentation: descriptor.data, relativeTo: nil), url.isFileURL, | |
| 53 | 新增: url.host == nil || url.host == "" || url.host == "localhost", | |
| 54 | 新增: url.user == nil, url.password == nil, url.query == nil, url.fragment == nil, | |
| 55 | 新增: let encodedPath = URLComponents(url: url, resolvingAgainstBaseURL: false)?.percentEncodedPath, | |
| 56 | 新增: let decodedPath = encodedPath.removingPercentEncoding, !decodedPath.contains("\0"), | |
| 57 | 新增: url.path.hasPrefix("/"), url.path.utf8.count <= 32768 else { | |
| 58 | 新增: throw Failure(8, "file_open_request_invalid") | |
| 59 | 新增: } | |
| 60 | 新增: return url.standardizedFileURL | |
| 61 | 新增: } | |
| 62 | 新增: } | |
| 63 | 新增: | |
| 64 | 新增: static func selfTest() throws { | |
| 65 | 新增: func event(_ values: [String]) -> NSAppleEventDescriptor { | |
| 66 | 新增: let request = NSAppleEventDescriptor.appleEvent(withEventClass: AEEventClass(kCoreEventClass), | |
| 67 | 新增: eventID: AEEventID(kAEOpenDocuments), targetDescriptor: nil, | |
| 68 | 新增: returnID: AEReturnID(kAutoGenerateReturnID), transactionID: AETransactionID(kAnyTransactionID)) | |
| 69 | 新增: let list = NSAppleEventDescriptor.list() | |
| 70 | 新增: for (index, value) in values.enumerated() { | |
| 71 | 新增: list.insert(NSAppleEventDescriptor(descriptorType: DescType(typeFileURL), data: Data(value.utf8))!, at: index + 1) | |
| 72 | 新增: } | |
| 73 | 新增: request.setParam(list, forKeyword: AEKeyword(keyDirectObject)) | |
| 74 | 新增: return request | |
| 75 | 新增: } | |
| 76 | 新增: let valid = event(["file:///tmp/cage-open-self-test/a%20b.txt", "file://localhost/tmp/cage-open-self-test/c.txt"]) | |
| 77 | 新增: guard try fileURLs(valid).map(\.path) == ["/tmp/cage-open-self-test/a b.txt", "/tmp/cage-open-self-test/c.txt"], | |
| 78 | 新增: MacOpenSender(valid) == nil else { throw Failure(8, "file_open_self_test_valid_paths") } | |
| 79 | 新增: let invalid = [[], ["https://example.invalid/file"], ["file://example.invalid/tmp/a"], | |
| 80 | 新增: ["file:///tmp/a?query=1"], ["file:///tmp/a#fragment"], ["file:///tmp/a%00b"], | |
| 81 | 新增: Array(repeating: "file:///tmp/cage-open-self-test/a", count: 33)] | |
| 82 | 新增: for (index, values) in invalid.enumerated() { | |
| 83 | 新增: if (try? fileURLs(event(values))) != nil { throw Failure(8, "file_open_self_test_invalid_\(index)") } | |
| 84 | 新增: } | |
| 85 | 新增: guard try fileURLs(event(Array(repeating: "file:///tmp/cage-open-self-test/a", count: 32))).count == 32 else { | |
| 86 | 新增: throw Failure(8, "file_open_self_test_failed") | |
| 87 | 新增: } | |
| 88 | 新增: valid.setAttribute(NSAppleEventDescriptor(int32: getpid()), forKeyword: AEKeyword(keySenderPIDAttr)) | |
| 89 | 新增: valid.setAttribute(NSAppleEventDescriptor(descriptorType: DescType(typeAuditToken), data: Data(repeating: 0, count: 32))!, | |
| 90 | 新增: forKeyword: AEKeyword(keySenderAuditTokenAttr)) | |
| 91 | 新增: guard MacOpenSender(valid) == nil else { throw Failure(8, "file_open_self_test_failed") } | |
| 92 | 新增: print("macOS native open parser and untrusted-event checks passed") | |
| 93 | 新增: } | |
| 94 | 新增: | |
| 95 | 新增: private static func focusedWindow(_ pid: pid_t) -> AXUIElement? { | |
| 96 | 新增: var value: CFTypeRef? | |
| 97 | 新增: guard AXUIElementCopyAttributeValue(AXUIElementCreateApplication(pid), kAXFocusedWindowAttribute as CFString, &value) == .success, | |
| 98 | 新增: let value, CFGetTypeID(value) == AXUIElementGetTypeID() else { return nil } | |
| 99 | 新增: return (value as! AXUIElement) | |
| 100 | 新增: } | |
| 101 | 新增: | |
| 102 | 新增: @objc private func openDocuments(_ event: NSAppleEventDescriptor, reply: NSAppleEventDescriptor) { | |
| 103 | 新增: do { | |
| 104 | 新增: let urls = try Self.fileURLs(event) | |
| 105 | 新增: guard let sender = MacOpenSender(event), sender.isOfficialClaude() else { | |
| 106 | 新增: for url in urls { try forwardToGuestApplication(url) } | |
| 107 | 新增: return | |
| 108 | 新增: } | |
| 109 | 新增: let epoch = try MacGUISession.shared.validate() | |
| 110 | 新增: guard AXIsProcessTrusted(), let window = Self.focusedWindow(sender.pid) else { throw Failure(7, "file_open_target_changed") } | |
| 111 | 新增: let validate = { | |
| 112 | 新增: try MacGUISession.shared.validate(epoch) | |
| 113 | 新增: guard sender.isOfficialClaude(), let current = Self.focusedWindow(sender.pid), CFEqual(current, window) else { | |
| 114 | 新增: throw Failure(7, "file_open_target_changed") | |
| 115 | 新增: } | |
| 116 | 新增: } | |
| 117 | 新增: try MacDesktopFiles.shared.queueOpen(paths: urls.map(\.path), action: "open", validate: validate) | |
| 118 | 新增: let restoreFocus = { | |
| 119 | 新增: guard (try? validate()) != nil, | |
| 120 | 新增: NSWorkspace.shared.frontmostApplication?.processIdentifier == getpid() else { return } | |
| 121 | 新增: if NSRunningApplication(processIdentifier: sender.pid)?.activate(options: []) != true { | |
| 122 | 新增: GuestDiagnostic.record("files", "file_open_focus_restore_failed") | |
| 123 | 新增: } | |
| 124 | 新增: } | |
| 125 | 新增: restoreFocus() | |
| 126 | 新增: DispatchQueue.main.async { restoreFocus() } | |
| 127 | 新增: } catch { | |
| 128 | 新增: let reason = (error as? Failure)?.message ?? "file_open_failed" | |
| 129 | 新增: GuestDiagnostic.record("files", reason) | |
| 130 | 新增: reply.setParam(NSAppleEventDescriptor(int32: Int32(errAEEventFailed)), forKeyword: AEKeyword(keyErrorNumber)) | |
| 131 | 新增: reply.setParam(NSAppleEventDescriptor(string: reason), forKeyword: AEKeyword(keyErrorString)) | |
| 132 | 新增: } | |
| 133 | 新增: } | |
| 134 | 新增: | |
| 135 | 新增: private func forwardToGuestApplication(_ url: URL) throws { | |
| 136 | 新增: let values = try url.resourceValues(forKeys: [.contentTypeKey, .isDirectoryKey]) | |
| 137 | 新增: let type = values.isDirectory == true ? UTType.folder : values.contentType ?? UTType.data | |
| 138 | 新增: let current = Bundle.main.bundleURL.resolvingSymlinksInPath() | |
| 139 | 新增: let preferred = NSWorkspace.shared.urlForApplication(toOpen: type) | |
| 140 | 新增: let candidates = [preferred].compactMap { $0 } + NSWorkspace.shared.urlsForApplications(toOpen: type) | |
| 141 | 新增: guard let target = candidates.first(where: { | |
| 142 | 新增: $0.resolvingSymlinksInPath() != current && Bundle(url: $0)?.bundleIdentifier != Bundle.main.bundleIdentifier | |
| 143 | 新增: }) else { throw Failure(8, "file_open_application_unavailable") } | |
| 144 | 新增: // An explicit target avoids resolving this file's OpenWith attribute again. | |
| 145 | 新增: let configuration = NSWorkspace.OpenConfiguration() | |
| 146 | 新增: configuration.addsToRecentItems = false | |
| 147 | 新增: NSWorkspace.shared.open([url], withApplicationAt: target, configuration: configuration) { _, error in | |
| 148 | 新增: if error != nil { GuestDiagnostic.record("files", "file_open_application_failed") } | |
| 149 | 新增: } | |
| 150 | 新增: } | |
| 151 | 新增: | |
| 152 | 新增: func prepareMetadata() async throws { | |
| 153 | 新增: let bundle = Bundle.main.bundleURL.resolvingSymlinksInPath() | |
| 154 | 新增: guard bundle.path == "/Applications/Cage Guest Window.app", Bundle.main.bundleIdentifier == "dev.cage.GuestClaudeWindow", | |
| 155 | 新增: LSRegisterURL(bundle as CFURL, true) == noErr else { throw Failure(8, "file_open_registration_failed") } | |
| 156 | 新增: let cache = URL(fileURLWithPath: NSHomeDirectory()).appendingPathComponent("Library/Caches/dev.cage.GuestClaudeWindow", isDirectory: true) | |
| 157 | 新增: var attributes = stat() | |
| 158 | 新增: guard lstat(cache.path, &attributes) == 0, attributes.st_mode & S_IFMT == S_IFDIR, | |
| 159 | 新增: attributes.st_uid == geteuid(), attributes.st_mode & 0o077 == 0 else { throw Failure(8, "file_open_cache_invalid") } | |
| 160 | 新增: let fixture = cache.appendingPathComponent("openwith-\(UUID().uuidString.lowercased()).txt") | |
| 161 | 新增: let fd = open(fixture.path, O_CREAT | O_EXCL | O_WRONLY | O_NOFOLLOW, 0o600) | |
| 162 | 新增: guard fd >= 0 else { throw Failure(8, "file_open_metadata_failed") } | |
| 163 | 新增: close(fd) | |
| 164 | 新增: defer { try? FileManager.default.removeItem(at: fixture) } | |
| 165 | 新增: try await withCheckedThrowingContinuation { (continuation: CheckedContinuation<Void, Error>) in | |
| 166 | 新增: NSWorkspace.shared.setDefaultApplication(at: bundle, toOpenFileAt: fixture) { error in | |
| 167 | 新增: if let error { continuation.resume(throwing: error) } | |
| 168 | 新增: else { continuation.resume() } | |
| 169 | 新增: } | |
| 170 | 新增: } | |
| 171 | 新增: guard NSWorkspace.shared.urlForApplication(toOpen: fixture)?.resolvingSymlinksInPath() == bundle else { | |
| 172 | 新增: throw Failure(8, "file_open_registration_failed") | |
| 173 | 新增: } | |
| 174 | 新增: let name = "com.apple.LaunchServices.OpenWith" | |
| 175 | 新增: let length = getxattr(fixture.path, name, nil, 0, 0, XATTR_NOFOLLOW) | |
| 176 | 新增: guard (1...8192).contains(length) else { throw Failure(8, "file_open_metadata_failed") } | |
| 177 | 新增: var bytes = [UInt8](repeating: 0, count: length) | |
| 178 | 新增: guard getxattr(fixture.path, name, &bytes, bytes.count, 0, XATTR_NOFOLLOW) == length else { | |
| 179 | 新增: throw Failure(8, "file_open_metadata_failed") | |
| 180 | 新增: } | |
| 181 | 新增: let temporary = cache.appendingPathComponent("openwith-\(UUID().uuidString.lowercased()).data") | |
| 182 | 新增: let output = open(temporary.path, O_WRONLY | O_CREAT | O_EXCL | O_NOFOLLOW, 0o600) | |
| 183 | 新增: guard output >= 0 else { throw Failure(8, "file_open_metadata_failed") } | |
| 184 | 新增: let file = FileHandle(fileDescriptor: output, closeOnDealloc: true) | |
| 185 | 新增: defer { try? FileManager.default.removeItem(at: temporary) } | |
| 186 | 新增: try file.write(contentsOf: Data(bytes)) | |
| 187 | 新增: try file.synchronize() | |
| 188 | 新增: try file.close() | |
| 189 | 新增: guard rename(temporary.path, cache.appendingPathComponent("openwith.data").path) == 0 else { | |
| 190 | 新增: throw Failure(8, "file_open_metadata_failed") | |
| 191 | 新增: } | |
| 192 | 新增: openWithMetadata = Data(bytes) | |
| 193 | 新增: } | |
| 194 | 新增:} | |
| @@ -0,0 +1,191 @@ | ||
| 1 | 新增:import AppKit | |
| 2 | 新增:import IOKit | |
| 3 | 新增:import Security | |
| 4 | 新增: | |
| 5 | 新增:@MainActor | |
| 6 | 新增:enum MacSetupPassword { | |
| 7 | 新增: private static func validateRequest(_ data: Data) throws { | |
| 8 | 新增: guard data.count <= 4096, let value = try? JSONSerialization.jsonObject(with: data) as? [String: Any], | |
| 9 | 新增: value.isEmpty || (value.count == 1 && value["action"] as? String == "probe") else { | |
| 10 | 新增: throw Failure(8, "setup_password_probe_request_invalid") | |
| 11 | 新增: } | |
| 12 | 新增: } | |
| 13 | 新增: | |
| 14 | 新增: nonisolated private static func nextLine() -> Data? { | |
| 15 | 新增: var data = Data() | |
| 16 | 新增: var oversized = false | |
| 17 | 新增: while true { | |
| 18 | 新增: let byte = fgetc(stdin) | |
| 19 | 新增: if byte == EOF { return data.isEmpty && !oversized ? nil : (oversized ? Data() : data) } | |
| 20 | 新增: if byte == 10 { return oversized ? Data() : data } | |
| 21 | 新增: if data.count < 4096 { data.append(UInt8(byte)) } | |
| 22 | 新增: else { oversized = true } | |
| 23 | 新增: } | |
| 24 | 新增: } | |
| 25 | 新增: | |
| 26 | 新增: static func runStream() -> Never { | |
| 27 | 新增: _ = signal(SIGPIPE, SIG_IGN) | |
| 28 | 新增: NSApplication.shared.setActivationPolicy(.prohibited) | |
| 29 | 新增: DispatchQueue.global(qos: .userInitiated).async { | |
| 30 | 新增: while let data = nextLine() { | |
| 31 | 新增: let finished = DispatchSemaphore(value: 0) | |
| 32 | 新增: DispatchQueue.main.async { | |
| 33 | 新增: let response: [String: Any] | |
| 34 | 新增: do { | |
| 35 | 新增: try validateRequest(data) | |
| 36 | 新增: response = try probe() | |
| 37 | 新增: } catch { response = ["error": (error as? Failure)?.message ?? "setup_password_probe_failed"] } | |
| 38 | 新增: do { | |
| 39 | 新增: var encoded = try JSONSerialization.data(withJSONObject: response) | |
| 40 | 新增: encoded.append(10) | |
| 41 | 新增: try FileHandle.standardOutput.write(contentsOf: encoded) | |
| 42 | 新增: } catch { exit(0) } | |
| 43 | 新增: finished.signal() | |
| 44 | 新增: } | |
| 45 | 新增: finished.wait() | |
| 46 | 新增: } | |
| 47 | 新增: DispatchQueue.main.async { exit(0) } | |
| 48 | 新增: } | |
| 49 | 新增: NSApplication.shared.run() | |
| 50 | 新增: exit(0) | |
| 51 | 新增: } | |
| 52 | 新增: | |
| 53 | 新增: struct Window { | |
| 54 | 新增: let id: UInt32 | |
| 55 | 新增: let pid: pid_t | |
| 56 | 新增: let bounds: CGRect | |
| 57 | 新增: let layer: Int | |
| 58 | 新增: var systemSurface = false | |
| 59 | 新增: } | |
| 60 | 新增: | |
| 61 | 新增: private static func signed(_ app: NSRunningApplication, bundle: String) -> Bool { | |
| 62 | 新增: guard app.bundleIdentifier == bundle else { return false } | |
| 63 | 新增: var code: SecCode?, requirement: SecRequirement? | |
| 64 | 新增: return SecRequirementCreateWithString("anchor apple and identifier \"\(bundle)\"" as CFString, [], &requirement) == errSecSuccess && | |
| 65 | 新增: SecCodeCopyGuestWithAttributes(nil, [kSecGuestAttributePid as String: app.processIdentifier] as CFDictionary, [], &code) == errSecSuccess && | |
| 66 | 新增: code != nil && requirement != nil && SecCodeCheckValidity(code!, [], requirement!) == errSecSuccess | |
| 67 | 新增: } | |
| 68 | 新增: | |
| 69 | 新增: private static func consoleSession() throws -> String { | |
| 70 | 新增: try consoleUser() | |
| 71 | 新增: let entry = IORegistryGetRootEntry(kIOMainPortDefault) | |
| 72 | 新增: guard entry != 0 else { throw Failure(4, "requires_gui_login") } | |
| 73 | 新增: defer { IOObjectRelease(entry) } | |
| 74 | 新增: guard let property = IORegistryEntryCreateCFProperty(entry, "IOConsoleUsers" as CFString, kCFAllocatorDefault, 0)?.takeRetainedValue(), | |
| 75 | 新增: let sessions = property as? [[String: Any]] else { throw Failure(4, "requires_gui_login") } | |
| 76 | 新增: let active = sessions.filter { $0["kCGSSessionOnConsoleKey"] as? Bool == true } | |
| 77 | 新增: guard active.count == 1, let current = active.first, | |
| 78 | 新增: current["kCGSessionLoginDoneKey"] as? Bool == true, | |
| 79 | 新增: current["CGSSessionScreenIsLocked"] as? Bool != true, | |
| 80 | 新增: current["kCGSSessionUserIDKey"] as? UInt32 == getuid(), | |
| 81 | 新增: current["kCGSSessionUserNameKey"] as? String == NSUserName(), | |
| 82 | 新增: let session = current["CGSSessionUniqueSessionUUID"] as? String, | |
| 83 | 新增: UUID(uuidString: session) != nil else { throw Failure(4, "requires_gui_login") } | |
| 84 | 新增: return session | |
| 85 | 新增: } | |
| 86 | 新增: | |
| 87 | 新增: static func select(windows: [Window], pid: pid_t, bundle: String, display: CGRect, accessibility: Bool) throws -> Window { | |
| 88 | 新增: guard ["com.apple.systempreferences", "com.apple.authorizationhost"].contains(bundle), | |
| 89 | 新增: let index = windows.firstIndex(where: { $0.pid == pid && $0.layer == 0 && $0.bounds.width >= 80 && $0.bounds.height >= 40 }) else { | |
| 90 | 新增: throw Failure(7, "setup_password_window_unavailable") | |
| 91 | 新增: } | |
| 92 | 新增: let target = windows[index] | |
| 93 | 新增: guard display.contains(target.bounds), target.id != 0 else { throw Failure(7, "setup_password_window_unavailable") } | |
| 94 | 新增: if !accessibility && bundle == "com.apple.systempreferences" { | |
| 95 | 新增: let parent = windows.dropFirst(index + 1).contains { window in | |
| 96 | 新增: window.pid == pid && window.layer == 0 && window.bounds.contains(target.bounds) && | |
| 97 | 新增: window.bounds.width > target.bounds.width && window.bounds.height > target.bounds.height && | |
| 98 | 新增: target.bounds.width * target.bounds.height < window.bounds.width * window.bounds.height * 0.75 | |
| 99 | 新增: } | |
| 100 | 新增: guard parent else { throw Failure(7, "setup_password_window_unavailable") } | |
| 101 | 新增: } | |
| 102 | 新增: for window in windows.prefix(index) where !window.systemSurface && window.bounds.intersects(target.bounds) { | |
| 103 | 新增: throw Failure(7, "setup_password_window_obscured") | |
| 104 | 新增: } | |
| 105 | 新增: return target | |
| 106 | 新增: } | |
| 107 | 新增: | |
| 108 | 新增: private static func passwordFocused(_ app: NSRunningApplication, window: CGRect) -> Bool { | |
| 109 | 新增: let application = AXUIElementCreateApplication(app.processIdentifier) | |
| 110 | 新增: AXUIElementSetMessagingTimeout(application, 0.25) | |
| 111 | 新增: func attribute(_ element: AXUIElement, _ key: String) -> CFTypeRef? { | |
| 112 | 新增: var value: CFTypeRef? | |
| 113 | 新增: return AXUIElementCopyAttributeValue(element, key as CFString, &value) == .success ? value : nil | |
| 114 | 新增: } | |
| 115 | 新增: guard let value = attribute(application, kAXFocusedUIElementAttribute), CFGetTypeID(value) == AXUIElementGetTypeID() else { return false } | |
| 116 | 新增: let field = value as! AXUIElement | |
| 117 | 新增: var pid: pid_t = 0 | |
| 118 | 新增: guard AXUIElementGetPid(field, &pid) == .success, pid == app.processIdentifier, | |
| 119 | 新增: attribute(field, kAXSubroleAttribute) as? String == kAXSecureTextFieldSubrole, | |
| 120 | 新增: attribute(field, kAXEnabledAttribute) as? Bool == true, | |
| 121 | 新增: let owner = attribute(field, kAXWindowAttribute), CFGetTypeID(owner) == AXUIElementGetTypeID() else { return false } | |
| 122 | 新增: var origin = CGPoint.zero, size = CGSize.zero | |
| 123 | 新增: guard let position = attribute(owner as! AXUIElement, kAXPositionAttribute), let extent = attribute(owner as! AXUIElement, kAXSizeAttribute), | |
| 124 | 新增: CFGetTypeID(position) == AXValueGetTypeID(), CFGetTypeID(extent) == AXValueGetTypeID(), | |
| 125 | 新增: AXValueGetValue(position as! AXValue, .cgPoint, &origin), AXValueGetValue(extent as! AXValue, .cgSize, &size) else { return false } | |
| 126 | 新增: return abs(origin.x - window.minX) < 1 && abs(origin.y - window.minY) < 1 && | |
| 127 | 新增: abs(size.width - window.width) < 1 && abs(size.height - window.height) < 1 | |
| 128 | 新增: } | |
| 129 | 新增: | |
| 130 | 新增: static func probe() throws -> [String: Any] { | |
| 131 | 新增: try requireGuest() | |
| 132 | 新增: let session = try consoleSession() | |
| 133 | 新增: guard let front = NSWorkspace.shared.frontmostApplication, let bundle = front.bundleIdentifier, | |
| 134 | 新增: ["com.apple.systempreferences", "com.apple.authorizationhost"].contains(bundle), signed(front, bundle: bundle) else { | |
| 135 | 新增: throw Failure(7, "setup_password_foreground_changed") | |
| 136 | 新增: } | |
| 137 | 新增: guard let raw = CGWindowListCopyWindowInfo([.optionOnScreenOnly, .excludeDesktopElements], kCGNullWindowID) as? [[String: Any]] else { | |
| 138 | 新增: throw Failure(7, "setup_password_window_unavailable") | |
| 139 | 新增: } | |
| 140 | 新增: let display = CGDisplayBounds(CGMainDisplayID()) | |
| 141 | 新增: var trustedSurfaces: [pid_t: Bool] = [:] | |
| 142 | 新增: let windows = raw.compactMap { item -> Window? in | |
| 143 | 新增: guard let id = item[kCGWindowNumber as String] as? UInt32, let pid = item[kCGWindowOwnerPID as String] as? Int32, | |
| 144 | 新增: let rectangle = item[kCGWindowBounds as String] as? [String: Any], let bounds = CGRect(dictionaryRepresentation: rectangle as CFDictionary), | |
| 145 | 新增: bounds.width > 0, bounds.height > 0, (item[kCGWindowAlpha as String] as? Double ?? 1) > 0, | |
| 146 | 新增: let layer = item[kCGWindowLayer as String] as? Int else { return nil } | |
| 147 | 新增: var surface = false | |
| 148 | 新增: if layer > 0, abs(bounds.minX - display.minX) < 1, abs(bounds.minY - display.minY) < 1, | |
| 149 | 新增: abs(bounds.width - display.width) < 1, abs(bounds.height - display.height) < 1 { | |
| 150 | 新增: if let cached = trustedSurfaces[pid] { surface = cached } | |
| 151 | 新增: else { | |
| 152 | 新增: if let app = NSRunningApplication(processIdentifier: pid), let owner = app.bundleIdentifier, | |
| 153 | 新增: ["com.apple.dock", "com.apple.notificationcenterui"].contains(owner) { surface = signed(app, bundle: owner) } | |
| 154 | 新增: trustedSurfaces[pid] = surface | |
| 155 | 新增: } | |
| 156 | 新增: } | |
| 157 | 新增: return Window(id: id, pid: pid, bounds: bounds, layer: layer, systemSurface: surface) | |
| 158 | 新增: } | |
| 159 | 新增: let accessibility = AXIsProcessTrusted() | |
| 160 | 新增: let target = try select(windows: windows, pid: front.processIdentifier, bundle: bundle, display: display, accessibility: accessibility) | |
| 161 | 新增: let focused = accessibility && passwordFocused(front, window: target.bounds) | |
| 162 | 新增: guard NSWorkspace.shared.frontmostApplication?.processIdentifier == front.processIdentifier, | |
| 163 | 新增: try consoleSession() == session else { throw Failure(7, "setup_password_foreground_changed") } | |
| 164 | 新增: return ["version": 1, "session": session, "user": NSUserName(), "pid": front.processIdentifier, | |
| 165 | 新增: "window": target.id, "bundle": bundle, "rect": [target.bounds.minX, target.bounds.minY, target.bounds.width, target.bounds.height], | |
| 166 | 新增: "display": [display.minX, display.minY, display.width, display.height], "accessibility": accessibility, | |
| 167 | 新增: "password_focused": focused, "selection_required": !accessibility] | |
| 168 | 新增: } | |
| 169 | 新增: | |
| 170 | 新增: static func selfTest() throws { | |
| 171 | 新增: try validateRequest(Data("{}".utf8)) | |
| 172 | 新增: try validateRequest(Data("{\"action\":\"probe\"}".utf8)) | |
| 173 | 新增: for request in ["", "[]", "{\"action\":\"other\"}", "{\"action\":\"probe\",\"text\":\"test-secret\"}"] { | |
| 174 | 新增: do { try validateRequest(Data(request.utf8)); throw Failure(1, "setup_password_test_request") } | |
| 175 | 新增: catch let error as Failure where error.message == "setup_password_probe_request_invalid" { } | |
| 176 | 新增: } | |
| 177 | 新增: let display = CGRect(x: 0, y: 0, width: 1920, height: 1200) | |
| 178 | 新增: let parent = Window(id: 38, pid: 2338, bounds: CGRect(x: 598, y: 258, width: 723, height: 625), layer: 0) | |
| 179 | 新增: let panel = Window(id: 49, pid: 2338, bounds: CGRect(x: 830, y: 376, width: 260, height: 389), layer: 0) | |
| 180 | 新增: let overlay = Window(id: 8, pid: 613, bounds: display, layer: 20, systemSurface: true) | |
| 181 | 新增: guard try select(windows: [overlay, panel, parent], pid: panel.pid, bundle: "com.apple.systempreferences", display: display, accessibility: false).id == panel.id else { throw Failure(1, "setup_password_test_selection") } | |
| 182 | 新增: let ordinary = Window(id: 9, pid: 999, bounds: panel.bounds, layer: 0) | |
| 183 | 新增: for windows in [[parent], [ordinary, panel, parent], [Window(id: 9, pid: 999, bounds: display, layer: 20), panel, parent], [panel]] { | |
| 184 | 新增: do { _ = try select(windows: windows, pid: panel.pid, bundle: "com.apple.systempreferences", display: display, accessibility: false); throw Failure(1, "setup_password_test_accepted_invalid") } | |
| 185 | 新增: catch let error as Failure where error.code == 7 { } | |
| 186 | 新增: } | |
| 187 | 新增: guard try select(windows: [panel], pid: panel.pid, bundle: "com.apple.authorizationhost", display: display, accessibility: false).id == panel.id, | |
| 188 | 新增: try select(windows: [parent], pid: panel.pid, bundle: "com.apple.systempreferences", display: display, accessibility: true).id == parent.id else { throw Failure(1, "setup_password_test_accessibility") } | |
| 189 | 新增: print("macOS setup password window selection, system surfaces, obscuration and first-permission cases passed") | |
| 190 | 新增: } | |
| 191 | 新增:} | |
| @@ -5,38 +5,82 @@ param( | ||
| 5 | 5 | [Parameter(Mandatory)][string]$ManifestPath, |
| 6 | 6 | [Parameter(Mandatory)][ValidatePattern('^[0-9A-Fa-f]{64}$')][string]$ManifestSHA256, |
| 7 | 7 | [switch]$Tools, |
| 8 | 新增: [switch]$HostOnly, | |
| 8 | 9 | [string]$BindingSHA256, |
| 9 | 10 | [pscredential]$GuestAdministrator |
| 10 | 11 | ) |
| 11 | 12 | $ErrorActionPreference='Stop' |
| 12 | 13 | $ProgressPreference='SilentlyContinue' |
| 13 | 14 | [Console]::OutputEncoding=[Text.UTF8Encoding]::new($false) |
| 15 | 新增:# Fixed process exits carry the failed stage across RunAs without a writable | |
| 16 | 新增:# result file. The ordinary parent reports the same stage to the workbench. | |
| 17 | 新增:$maintenanceFailures=@{ | |
| 18 | 新增: 1=@('FAILED','Windows 维护未完成。请从 Cage 重新发起原操作,仍失败时导出诊断包。') | |
| 19 | 新增: 41=@('VALIDATION','Windows 环境绑定或组件清单未通过校验。请重新发起原操作,组件包仍无法核验时重新安装完整 Cage 应用。') | |
| 20 | 新增: 42=@('HOST_MANAGER','Windows 系统管理助手安装未完成。请重试修复系统助手,仍失败时检查系统服务或安全软件记录并导出诊断包。') | |
| 21 | 新增: 43=@('GUEST_CONNECTION','Windows 客机连接未完成。请启动并登录已绑定客机,使用该客机的管理员账户重试。') | |
| 22 | 新增: 44=@('GUEST_COMPONENTS','Windows 客机组件安装未完成。请保持原客机运行,重试同步环境组件,仍失败时导出诊断包。') | |
| 23 | 新增: 45=@('HOST_RELAY','Windows 主机连接组件更新未完成。请关闭占用连接组件的程序,再重试同步环境组件。') | |
| 24 | 新增: 46=@('PACKAGE_PREPARATION','Windows 组件包准备未完成。请检查应用目录和系统盘空间后重试,更新工具时同时检查已选代理。') | |
| 25 | 新增: 47=@('AUTHORIZATION','Windows 管理员授权窗口未能打开。请从本机 Cage 重新发起操作,并使用可完成管理员授权的 Windows 账户。') | |
| 26 | 新增: 48=@('AUTHORIZATION_CANCELED','已取消 Windows 管理员授权。请重新发起原操作,并在 Windows 系统授权窗口中确认。') | |
| 27 | 新增:} | |
| 28 | 新增:$maintenanceExitCode=41 | |
| 29 | 新增:trap { | |
| 30 | 新增: if ($maintenanceExitCode -eq 47) { | |
| 31 | 新增: for ($cause=$_.Exception; $cause; $cause=$cause.InnerException) { | |
| 32 | 新增: if ($cause -is [ComponentModel.Win32Exception] -and $cause.NativeErrorCode -eq 1223) { $maintenanceExitCode=48; break } | |
| 33 | 新增: } | |
| 34 | 新增: } | |
| 35 | 新增: if (!$maintenanceFailures.ContainsKey($maintenanceExitCode)) { $maintenanceExitCode=1 } | |
| 36 | 新增: $failure=$maintenanceFailures[$maintenanceExitCode] | |
| 37 | 新增: [Console]::Error.WriteLine(('CAGE_WINDOWS_MAINTENANCE_'+$failure[0]+' '+$failure[1])) | |
| 38 | 新增: [Console]::Error.WriteLine($_.Exception.Message) | |
| 39 | 新增: exit $maintenanceExitCode | |
| 40 | 新增:} | |
| 41 | 新增: | |
| 42 | 新增:function Invoke-CageMaintenanceElevation([string]$ScriptPath,[hashtable]$Parameters) { | |
| 43 | 新增: $payload=[Convert]::ToBase64String([Text.Encoding]::UTF8.GetBytes(($Parameters|ConvertTo-Json -Compress))) | |
| 44 | 新增: $script=[Convert]::ToBase64String([Text.Encoding]::UTF8.GetBytes($ScriptPath)) | |
| 45 | 新增: $command='$ErrorActionPreference=''Stop'';$p=[Text.Encoding]::UTF8.GetString([Convert]::FromBase64String('''+$payload+'''))|ConvertFrom-Json;$a=@{};$p.PSObject.Properties|ForEach-Object{$a[$_.Name]=$_.Value};$s=[Text.Encoding]::UTF8.GetString([Convert]::FromBase64String('''+$script+'''));try{$global:LASTEXITCODE=0;& $s @a;exit $LASTEXITCODE}catch{Write-Error $_ -ErrorAction Continue;exit 1}' | |
| 46 | 新增: $encoded=[Convert]::ToBase64String([Text.Encoding]::Unicode.GetBytes($command)) | |
| 47 | 新增: $process=Start-Process -FilePath (Join-Path ([Environment]::GetFolderPath('System')) 'WindowsPowerShell/v1.0/powershell.exe') -ArgumentList @('-NoLogo','-NoProfile','-ExecutionPolicy','RemoteSigned','-EncodedCommand',$encoded) -Verb RunAs -PassThru | |
| 48 | 新增: try { | |
| 49 | 新增: # Retain the native handle before waiting. Windows PowerShell 5.1 can | |
| 50 | 新增: # otherwise return a null ExitCode after a successful child exit. | |
| 51 | 新增: $null=$process.Handle | |
| 52 | 新增: $process.WaitForExit() | |
| 53 | 新增: if ($null -eq $process.ExitCode) { throw '无法读取系统授权进程的退出状态,请重新发起操作。' } | |
| 54 | 新增: return [int]$process.ExitCode | |
| 55 | 新增: } finally { $process.Dispose() } | |
| 56 | 新增:} | |
| 57 | 新增: | |
| 14 | 58 | $bindingPath=Join-Path $Profile 'windows-guest.json' |
| 15 | 59 | $item=Get-Item -LiteralPath $bindingPath -Force |
| 16 | 60 | if ($item -isnot [IO.FileInfo] -or $item.Length -gt 16384 -or $item.Attributes -band [IO.FileAttributes]::ReparsePoint) { throw '已绑定的 Windows 环境记录无法核验。' } |
| 17 | 61 | $bindingHash=(Get-FileHash -LiteralPath $bindingPath -Algorithm SHA256).Hash |
| 18 | 62 | if ($BindingSHA256 -and $BindingSHA256 -ne $bindingHash) { throw 'Windows 环境绑定已变化,请重新发起更新。' } |
| 19 | 63 | if ((Get-FileHash -LiteralPath $ManifestPath -Algorithm SHA256).Hash -ne $ManifestSHA256) { throw '组件清单已变化,请重新发起更新。' } |
| 64 | 新增:$maintenanceExitCode=47 | |
| 20 | 65 | $identity=[Security.Principal.WindowsIdentity]::GetCurrent() |
| 21 | 66 | if (![Security.Principal.WindowsPrincipal]::new($identity).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) { |
| 22 | 删除: $parameters=@{Profile=$Profile;ManifestPath=$ManifestPath;ManifestSHA256=$ManifestSHA256;BindingSHA256=$bindingHash;Tools=[bool]$Tools} | |
| 23 | 删除: $payload=[Convert]::ToBase64String([Text.Encoding]::UTF8.GetBytes(($parameters|ConvertTo-Json -Compress))) | |
| 24 | 删除: $script=[Convert]::ToBase64String([Text.Encoding]::UTF8.GetBytes($PSCommandPath)) | |
| 25 | 删除: $command='$ErrorActionPreference=''Stop'';$p=[Text.Encoding]::UTF8.GetString([Convert]::FromBase64String('''+$payload+'''))|ConvertFrom-Json;$a=@{};$p.PSObject.Properties|ForEach-Object{$a[$_.Name]=$_.Value};$s=[Text.Encoding]::UTF8.GetString([Convert]::FromBase64String('''+$script+'''));try{& $s @a;exit 0}catch{Write-Error $_;exit 1}' | |
| 26 | 删除: $encoded=[Convert]::ToBase64String([Text.Encoding]::Unicode.GetBytes($command)) | |
| 27 | 删除: $process=Start-Process -FilePath (Join-Path ([Environment]::GetFolderPath('System')) 'WindowsPowerShell/v1.0/powershell.exe') -ArgumentList @('-NoLogo','-NoProfile','-ExecutionPolicy','RemoteSigned','-EncodedCommand',$encoded) -Verb RunAs -PassThru | |
| 28 | 删除: try { | |
| 29 | 删除: $process.WaitForExit() | |
| 30 | 删除: if ($process.ExitCode -ne 0) { throw 'Windows 组件更新未完成。系统磁盘和账户已保留,请在系统窗口查看原因后重试。' } | |
| 31 | 删除: } finally { $process.Dispose() } | |
| 32 | 删除: return | |
| 67 | 新增: $parameters=@{Profile=$Profile;ManifestPath=$ManifestPath;ManifestSHA256=$ManifestSHA256;BindingSHA256=$bindingHash;Tools=[bool]$Tools;HostOnly=[bool]$HostOnly} | |
| 68 | 新增: $maintenanceExitCode=Invoke-CageMaintenanceElevation -ScriptPath $PSCommandPath -Parameters $parameters | |
| 69 | 新增: if ($maintenanceExitCode -ne 0) { throw '提升权限后的 Windows 维护进程未完成。' } | |
| 70 | 新增: exit 0 | |
| 33 | 71 | } |
| 72 | 新增:$maintenanceExitCode=41 | |
| 34 | 73 | $binding=Get-Content -LiteralPath $bindingPath -Raw | ConvertFrom-Json |
| 74 | 新增:if ($binding.version -ne 1 -or [guid]$binding.vm_id -eq [guid]::Empty) { throw 'Windows 客机绑定无法核验。' } | |
| 75 | 新增:if (!$HostOnly) { | |
| 76 | 新增:$maintenanceExitCode=43 | |
| 35 | 77 | $vm=Hyper-V\Get-VM -Id ([guid]$binding.vm_id) |
| 78 | 新增:if ($vm.State -ne 'Running') { throw '请先启动并登录已绑定的 Windows 客机。' } | |
| 79 | 新增:$maintenanceExitCode=41 | |
| 36 | 80 | $disks=@($vm | Hyper-V\Get-VMHardDiskDrive) |
| 37 | 81 | $pairDirectory=[IO.Path]::GetDirectoryName($binding.relay_executable) |
| 38 | 82 | $stagedPairDirectory=Join-Path $binding.instance_directory 'cage-workbench\pair' |
| 39 | 删除:if ($binding.version -ne 1 -or $vm.Id -eq [guid]::Empty -or $vm.State -ne 'Running' -or | |
| 83 | 新增:if ($binding.version -ne 1 -or $vm.Id -eq [guid]::Empty -or | |
| 40 | 84 | $binding.gui_user_sid -notmatch '^S-1-5-21-' -or @(Hyper-V\Get-VMNetworkAdapter -VM $vm).Count -ne 0 -or |
| 41 | 85 | $disks.Count -ne 1 -or $disks[0].Path -ine (Join-Path $binding.instance_directory 'system.vhdx') -or |
| 42 | 86 | ($pairDirectory -ine $stagedPairDirectory -and $pairDirectory -ine $item.Directory.FullName) -or |
| @@ -47,6 +91,9 @@ if ($binding.version -ne 1 -or $vm.Id -eq [guid]::Empty -or $vm.State -ne 'Runni | ||
| 47 | 91 | for ($entry=Get-Item -LiteralPath $binding.relay_executable -Force; $entry; $entry=if ($entry -is [IO.FileInfo]) {$entry.Directory} else {$entry.Parent}) { |
| 48 | 92 | if ($entry.Attributes -band [IO.FileAttributes]::ReparsePoint) { throw '主机连接组件路径包含文件链接。' } |
| 49 | 93 | } |
| 94 | 新增:} else { | |
| 95 | 新增: $vm=[pscustomobject]@{Id=[guid]$binding.vm_id} | |
| 96 | 新增:} | |
| 50 | 97 | $manifest=Get-Content -LiteralPath $ManifestPath -Raw | ConvertFrom-Json |
| 51 | 98 | if ($manifest.protocol -ne 1 -or $manifest.system -cne 'windows-11' -or $manifest.revision -notmatch '^[a-f0-9]{64}$' -or @($manifest.files).Count -notin 1..10000) { throw '原生组件清单无效。' } |
| 52 | 99 | $kit=[IO.Path]::GetFullPath($PSScriptRoot).TrimEnd('\')+'\' |
| @@ -55,6 +102,22 @@ foreach ($entry in $manifest.files) { | ||
| 55 | 102 | if (!$source.StartsWith($kit,[StringComparison]::OrdinalIgnoreCase) -or (Get-Item -LiteralPath $source -Force).Attributes -band [IO.FileAttributes]::ReparsePoint -or |
| 56 | 103 | (Get-FileHash -LiteralPath $source -Algorithm SHA256).Hash -ne $entry.sha256) { throw '应用组件包已变化,请重新安装完整 Cage 应用。' } |
| 57 | 104 | } |
| 105 | 新增:# The native host helper is part of the same checked component package. Update | |
| 106 | 新增:# its fixed-VM service during the existing administrator-authorized maintenance. | |
| 107 | 新增:# The protected registration supplies the original host user across UAC. | |
| 108 | 新增:$managerBindingPath=Join-Path ([Environment]::GetFolderPath('CommonApplicationData')) ('Cage\HyperVManager\'+$vm.Id.ToString('D')+'\binding.json') | |
| 109 | 新增:$managerBindingFile=Get-Item -LiteralPath $managerBindingPath -Force | |
| 110 | 新增:if ($managerBindingFile.Attributes -band [IO.FileAttributes]::ReparsePoint -or $managerBindingFile.Length -gt 65536) { throw 'Windows 管理助手的登记文件无法核验。' } | |
| 111 | 新增:$managerBinding=Get-Content -LiteralPath $managerBindingPath -Raw | ConvertFrom-Json | |
| 112 | 新增:if ([guid]$managerBinding.vm_id -ne $vm.Id -or $managerBinding.host_sid -notmatch '^S-1-(5-21|12-1)-(\d+-){3}\d+$') { throw 'Windows 管理助手的用户或客机身份不匹配。' } | |
| 113 | 新增:$managerPayload=Join-Path $kit 'payload/Cage.HyperVManager.exe' | |
| 114 | 新增:$maintenanceExitCode=42 | |
| 115 | 新增:& (Join-Path $kit 'install-windows-host-manager.ps1') -VMId $vm.Id -HostSID $managerBinding.host_sid -PayloadExecutable $managerPayload -PayloadSHA256 (Get-FileHash -LiteralPath $managerPayload -Algorithm SHA256).Hash -Confirm:$false | Out-Null | |
| 116 | 新增:if ($HostOnly) { | |
| 117 | 新增: Write-Output 'Windows 系统管理助手已恢复,可以继续恢复存储迁移。' | |
| 118 | 新增: exit 0 | |
| 119 | 新增:} | |
| 120 | 新增:$maintenanceExitCode=46 | |
| 58 | 121 | $work=Join-Path ([Environment]::GetFolderPath('CommonApplicationData')) ('Cage\ComponentMaintenance\'+$vm.Id.ToString('D')) |
| 59 | 122 | for ($parent=$work; $parent; $parent=[IO.Path]::GetDirectoryName($parent)) { |
| 60 | 123 | if ((Test-Path -LiteralPath $parent) -and (Get-Item -LiteralPath $parent -Force).Attributes -band [IO.FileAttributes]::ReparsePoint) { throw '组件维护目录包含文件链接。' } |
| @@ -107,6 +170,7 @@ try { | ||
| 107 | 170 | & (Join-Path $env:SystemRoot 'System32/tar.exe') -a -cf (Join-Path $toolStage 'extras.zip') -C $bridge . |
| 108 | 171 | if ($LASTEXITCODE) { throw '无法准备经过校验的环境工具包。' } |
| 109 | 172 | } |
| 173 | 新增: $maintenanceExitCode=43 | |
| 110 | 174 | if (!$GuestAdministrator) { $GuestAdministrator=Get-Credential -Message 'Cage:请输入当前 Windows 客机的管理员账户以更新组件。' } |
| 111 | 175 | if (!$GuestAdministrator) { throw '已取消 Windows 组件更新。' } |
| 112 | 176 | $session=New-PSSession -VMId $vm.Id -Credential $GuestAdministrator |
| @@ -120,6 +184,7 @@ try { | ||
| 120 | 184 | Set-Acl -LiteralPath $path -AclObject $acl |
| 121 | 185 | $path |
| 122 | 186 | } |
| 187 | 新增: $maintenanceExitCode=44 | |
| 123 | 188 | $archive=Join-Path $work ([guid]::NewGuid().ToString('N')+'.zip') |
| 124 | 189 | try { |
| 125 | 190 | $entries=@('files','native-components.json') |
| @@ -132,15 +197,17 @@ try { | ||
| 132 | 197 | Copy-Item -LiteralPath (Join-Path $kit 'install-windows-workbench-components.ps1') -Destination $remote -ToSession $session |
| 133 | 198 | Invoke-Command -Session $session -FilePath (Join-Path $kit 'update-windows-workbench-components.ps1') -ArgumentList $vm.Id,$binding.gui_user_sid,$remote,$hash,([bool]$Tools),($packages|ConvertTo-Json -Depth 6 -Compress),($cli|ConvertTo-Json -Depth 6 -Compress) |
| 134 | 199 | # The host relay is an application file. Pairing bytes and the binding are retained. |
| 200 | 新增: $maintenanceExitCode=45 | |
| 135 | 201 | $relayStage=$binding.relay_executable+'.'+[guid]::NewGuid().ToString('N')+'.tmp' |
| 136 | 202 | try { |
| 137 | 203 | Copy-Item -LiteralPath (Join-Path $files 'bridge/Cage.GuestClipboard.exe') -Destination $relayStage |
| 138 | 204 | Set-Acl -LiteralPath $relayStage -AclObject (Get-Acl -LiteralPath $binding.relay_executable) |
| 139 | 205 | [IO.File]::Replace($relayStage,$binding.relay_executable,[Management.Automation.Language.NullString]::Value) |
| 140 | 206 | } finally { if (Test-Path -LiteralPath $relayStage) { Remove-Item -LiteralPath $relayStage } } |
| 207 | 新增: $maintenanceExitCode=41 | |
| 141 | 208 | if (@(Hyper-V\Get-VMNetworkAdapter -VM (Hyper-V\Get-VM -Id $vm.Id)).Count -ne 0) { throw '更新期间客机网络配置发生变化。' } |
| 209 | 新增: $maintenanceExitCode=44 | |
| 142 | 210 | $completed=$true |
| 143 | 删除: Write-Output 'Windows 客机组件已完成文件核验,已保留账户、项目和配对资料。' | |
| 144 | 211 | } finally { |
| 145 | 212 | if ($session) { |
| 146 | 213 | if ($remote -and $completed) { Invoke-Command -Session $session -ArgumentList $remote -ScriptBlock { param($path) Remove-Item -LiteralPath $path -Recurse -Force } -ErrorAction Continue } |
| @@ -150,3 +217,5 @@ try { | ||
| 150 | 217 | if (Test-Path -LiteralPath $stage) { Remove-Item -LiteralPath $stage -Recurse -Force } |
| 151 | 218 | $lock.Dispose() |
| 152 | 219 | } |
| 220 | 新增:Write-Output 'Windows 客机组件已完成文件核验,已保留账户、项目和配对资料。' | |
| 221 | 新增:exit 0 | |
| @@ -0,0 +1,140 @@ | ||
| 1 | 新增:#requires -Version 5.1 | |
| 2 | 新增:param([string]$Implementation=(Join-Path $PSScriptRoot 'maintain-windows-workbench.ps1')) | |
| 3 | 新增:$ErrorActionPreference='Stop' | |
| 4 | 新增:$source=[IO.File]::ReadAllText($Implementation) | |
| 5 | 新增:$parseErrors=$null | |
| 6 | 新增:$ast=[Management.Automation.Language.Parser]::ParseInput($source,[ref]$null,[ref]$parseErrors) | |
| 7 | 新增:if ($parseErrors.Count) { throw $parseErrors[0] } | |
| 8 | 新增:$bindingStart=$source.IndexOf('$bindingPath=Join-Path') | |
| 9 | 新增:if ($bindingStart -lt 0) { throw 'Maintenance preflight entry missing.' } | |
| 10 | 新增:$prelude=$source.Substring(0,$bindingStart) | |
| 11 | 新增:$elevation=$ast.Find({param($node) | |
| 12 | 新增: $node -is [Management.Automation.Language.IfStatementAst] -and $node.Clauses[0].Item1.Extent.Text.Contains('WindowsPrincipal') | |
| 13 | 新增:},$true) | |
| 14 | 新增:if (!$elevation) { throw 'Production elevation entry missing.' } | |
| 15 | 新增:$elevationBody=$elevation.Clauses[0].Item2.Extent.Text | |
| 16 | 新增:$elevationBody=$elevationBody.Substring(1,$elevationBody.Length-2).Replace('-ScriptPath $PSCommandPath','-ScriptPath $fixtureChild') | |
| 17 | 新增:$hostOnly=$ast.Find({param($node) | |
| 18 | 新增: $node -is [Management.Automation.Language.IfStatementAst] -and $node.Clauses[0].Item1.Extent.Text -eq '$HostOnly' | |
| 19 | 新增:},$true) | |
| 20 | 新增:if (!$hostOnly -or !$hostOnly.Extent.Text.Contains('exit 0') -or $hostOnly.Extent.Text.Contains('New-PSSession') -or $hostOnly.Extent.StartOffset -gt $source.IndexOf('Get-Credential -Message')) { throw 'HostOnly must finish after host installation.' } | |
| 21 | 新增: | |
| 22 | 新增:function Assert-Stage([string]$Command,[int]$Code) { | |
| 23 | 新增: $offset=$source.IndexOf($Command) | |
| 24 | 新增: if ($offset -lt 0) { throw "Stage receiver missing $Command" } | |
| 25 | 新增: $assignments=@($ast.FindAll({param($node) | |
| 26 | 新增: if ($node -isnot [Management.Automation.Language.AssignmentStatementAst] -or $node.Left.Extent.Text -ne '$maintenanceExitCode' -or $node.Right.Extent.Text -notmatch '^\d+$') { return $false } | |
| 27 | 新增: for ($parent=$node.Parent; $parent; $parent=$parent.Parent) { | |
| 28 | 新增: if ($parent -is [Management.Automation.Language.TrapStatementAst] -or $parent -is [Management.Automation.Language.FunctionDefinitionAst]) { return $false } | |
| 29 | 新增: } | |
| 30 | 新增: $true | |
| 31 | 新增: },$true) | Where-Object {$_.Extent.StartOffset -lt $offset} | Sort-Object {$_.Extent.StartOffset}) | |
| 32 | 新增: if (!$assignments.Count -or [int]$assignments[-1].Right.Extent.Text -ne $Code) { throw "Wrong production failure stage for $Command" } | |
| 33 | 新增:} | |
| 34 | 新增:Assert-Stage 'Get-FileHash -LiteralPath $ManifestPath' 41 | |
| 35 | 新增:Assert-Stage "& (Join-Path `$kit 'install-windows-host-manager.ps1')" 42 | |
| 36 | 新增:Assert-Stage 'Get-PinnedPackage $spec.Value $cache' 46 | |
| 37 | 新增:Assert-Stage 'New-PSSession -VMId' 43 | |
| 38 | 新增:Assert-Stage "Invoke-Command -Session `$session -FilePath (Join-Path `$kit 'update-windows-workbench-components.ps1')" 44 | |
| 39 | 新增:Assert-Stage '[IO.File]::Replace' 45 | |
| 40 | 新增: | |
| 41 | 新增:$shell=(Get-Process -Id $PID).Path | |
| 42 | 新增:$temporary=Join-Path ([IO.Path]::GetTempPath()) ('cage-maintenance-feedback-'+[guid]::NewGuid().ToString('N')) | |
| 43 | 新增:$null=New-Item -ItemType Directory -Path $temporary | |
| 44 | 新增:$encoding=[Text.UTF8Encoding]::new($true) | |
| 45 | 新增:function Quote-Literal([string]$Value) { "'"+$Value.Replace("'","''")+"'" } | |
| 46 | 新增:function Run-Script([string]$Path,[hashtable]$Parameters) { | |
| 47 | 新增: $payload=[Convert]::ToBase64String([Text.Encoding]::UTF8.GetBytes(($Parameters|ConvertTo-Json -Compress))) | |
| 48 | 新增: $command='$p=[Text.Encoding]::UTF8.GetString([Convert]::FromBase64String('''+$payload+'''))|ConvertFrom-Json;$a=@{};$p.PSObject.Properties|ForEach-Object{$a[$_.Name]=$_.Value};& '+(Quote-Literal $Path)+' @a;exit $LASTEXITCODE' | |
| 49 | 新增: $encoded=[Convert]::ToBase64String([Text.Encoding]::Unicode.GetBytes($command)) | |
| 50 | 新增: $start=[Diagnostics.ProcessStartInfo]::new() | |
| 51 | 新增: $start.FileName=$shell | |
| 52 | 新增: $start.Arguments='-NoLogo -NoProfile -NonInteractive -ExecutionPolicy Bypass -EncodedCommand '+$encoded | |
| 53 | 新增: $start.UseShellExecute=$false | |
| 54 | 新增: $start.RedirectStandardOutput=$true | |
| 55 | 新增: $start.RedirectStandardError=$true | |
| 56 | 新增: $process=[Diagnostics.Process]::new() | |
| 57 | 新增: $process.StartInfo=$start | |
| 58 | 新增: try { | |
| 59 | 新增: if (!$process.Start()) { throw 'Fixture process did not start.' } | |
| 60 | 新增: $stdout=$process.StandardOutput.ReadToEndAsync() | |
| 61 | 新增: $stderr=$process.StandardError.ReadToEndAsync() | |
| 62 | 新增: if (!$process.WaitForExit(15000)) { $process.Kill(); throw 'Fixture process timed out.' } | |
| 63 | 新增: [pscustomobject]@{Code=$process.ExitCode;Output=$stdout.GetAwaiter().GetResult();Error=$stderr.GetAwaiter().GetResult()} | |
| 64 | 新增: } finally { $process.Dispose() } | |
| 65 | 新增:} | |
| 66 | 新增: | |
| 67 | 新增:try { | |
| 68 | 新增: $profile=Join-Path $temporary "profile's 中文" | |
| 69 | 新增: $null=New-Item -ItemType Directory -Path $profile | |
| 70 | 新增: $binding=Join-Path $profile 'windows-guest.json' | |
| 71 | 新增: $manifest=Join-Path $temporary 'manifest.json' | |
| 72 | 新增: [IO.File]::WriteAllText($binding,'{}',$encoding) | |
| 73 | 新增: [IO.File]::WriteAllText($manifest,'{}',$encoding) | |
| 74 | 新增: $parameters=@{Profile=$profile;ManifestPath=$manifest;ManifestSHA256=(Get-FileHash $manifest).Hash} | |
| 75 | 新增: foreach ($name in @('binding','manifest')) { | |
| 76 | 新增: $requestParameters=$parameters.Clone() | |
| 77 | 新增: if ($name -eq 'binding') { $requestParameters.BindingSHA256='a'*64 } else { $requestParameters.ManifestSHA256='b'*64 } | |
| 78 | 新增: $result=Run-Script $Implementation $requestParameters | |
| 79 | 新增: if ($result.Code -ne 41 -or !$result.Error.Contains('CAGE_WINDOWS_MAINTENANCE_VALIDATION')) { throw "Real $name preflight lost its phase $($result | ConvertTo-Json -Compress)" } | |
| 80 | 新增: } | |
| 81 | 新增: | |
| 82 | 新增: # The production RunAs block launches real isolated PowerShell children. | |
| 83 | 新增: # Only the OS elevation call is replaced, so these tests require no UAC, | |
| 84 | 新增: # VM, administrator credential or protected Windows directory. | |
| 85 | 新增: $mock=@' | |
| 86 | 新增:function Join-Path($Path,$ChildPath) { | |
| 87 | 新增: if ($ChildPath -eq 'WindowsPowerShell/v1.0/powershell.exe') { return $fixtureShell } | |
| 88 | 新增: Microsoft.PowerShell.Management\Join-Path -Path $Path -ChildPath $ChildPath | |
| 89 | 新增:} | |
| 90 | 新增:function Start-Process($FilePath,$ArgumentList,$Verb,[switch]$PassThru) { | |
| 91 | 新增: if ($FilePath -ne $fixtureShell -or $Verb -ne 'RunAs' -or !$PassThru) { throw 'Incorrect elevation contract.' } | |
| 92 | 新增: if ($fixtureCancel) { throw [InvalidOperationException]::new('synthetic nested launch error',[ComponentModel.Win32Exception]::new(1223)) } | |
| 93 | 新增: if ($fixtureLaunchFailure) { throw [ComponentModel.Win32Exception]::new(5) } | |
| 94 | 新增: Microsoft.PowerShell.Management\Start-Process -FilePath $FilePath -ArgumentList $ArgumentList -PassThru -NoNewWindow | |
| 95 | 新增:} | |
| 96 | 新增:'@ | |
| 97 | 新增: $cases=@( | |
| 98 | 新增: @{Name='regular-success';Code=0;Phase='';HostOnly=$false;Tools=$true}, | |
| 99 | 新增: @{Name='host-success';Code=0;Phase='';HostOnly=$true;Tools=$false}, | |
| 100 | 新增: @{Name='validation';Code=41;Phase='VALIDATION';HostOnly=$true}, | |
| 101 | 新增: @{Name='manager';Code=42;Phase='HOST_MANAGER';HostOnly=$true}, | |
| 102 | 新增: @{Name='guest-connection';Code=43;Phase='GUEST_CONNECTION';HostOnly=$false}, | |
| 103 | 新增: @{Name='guest-components';Code=44;Phase='GUEST_COMPONENTS';HostOnly=$false}, | |
| 104 | 新增: @{Name='host-relay';Code=45;Phase='HOST_RELAY';HostOnly=$false}, | |
| 105 | 新增: @{Name='prepare-tools';Code=46;Phase='PACKAGE_PREPARATION';HostOnly=$false;Tools=$true}, | |
| 106 | 新增: @{Name='launch-failed';Code=47;Phase='AUTHORIZATION';HostOnly=$true;LaunchFailure=$true}, | |
| 107 | 新增: @{Name='uac-canceled';Code=48;Phase='AUTHORIZATION_CANCELED';HostOnly=$true;Cancel=$true}, | |
| 108 | 新增: @{Name='legacy-failed';Code=1;Phase='FAILED';HostOnly=$true;Legacy=$true}, | |
| 109 | 新增: @{Name='unknown-exit';Code=1;Phase='FAILED';HostOnly=$false;Unknown=$true} | |
| 110 | 新增: ) | |
| 111 | 新增: foreach ($case in $cases) { | |
| 112 | 新增: $child=Join-Path $temporary ($case.Name+"-child's 中文.ps1") | |
| 113 | 新增: $expectedHost=([bool]$case.HostOnly).ToString().ToLowerInvariant() | |
| 114 | 新增: $expectedTools=([bool]$case.Tools).ToString().ToLowerInvariant() | |
| 115 | 新增: $childBody="`nif ([bool]`$HostOnly -ne `$$expectedHost -or [bool]`$Tools -ne `$$expectedTools -or `$GuestAdministrator -or `$BindingSHA256 -ne ('c'*64)) { exit 92 }`n" | |
| 116 | 新增: if ($case.Unknown) { $childBody+='exit 77' } | |
| 117 | 新增: elseif ($case.Legacy) { $childBody+='throw ''synthetic legacy error''' } | |
| 118 | 新增: elseif ($case.Code -eq 0) { | |
| 119 | 新增: $childBody+=$hostOnly.Extent.Text+"`nWrite-Output 'synthetic regular success'`nexit 0" | |
| 120 | 新增: } else { $childBody+="`$maintenanceExitCode=$($case.Code)`nthrow 'synthetic stage error'" } | |
| 121 | 新增: if ($case.Legacy) { | |
| 122 | 新增: [IO.File]::WriteAllText($child,$ast.ParamBlock.Extent.Text+$childBody,$encoding) | |
| 123 | 新增: } else { [IO.File]::WriteAllText($child,$prelude+$childBody,$encoding) } | |
| 124 | 新增: $parentScript=Join-Path $temporary ($case.Name+'-parent.ps1') | |
| 125 | 新增: $config="`n`$fixtureShell="+(Quote-Literal $shell)+"`n`$fixtureChild="+(Quote-Literal $child)+"`n`$fixtureCancel=`$"+([bool]$case.Cancel).ToString().ToLowerInvariant()+"`n`$fixtureLaunchFailure=`$"+([bool]$case.LaunchFailure).ToString().ToLowerInvariant()+"`n`$bindingHash='c'*64`n`$maintenanceExitCode=47`n" | |
| 126 | 新增: $config+="`$GuestAdministrator=[pscredential]::new('synthetic-maintenance-user',(ConvertTo-SecureString 'synthetic-credential' -AsPlainText -Force))`n" | |
| 127 | 新增: [IO.File]::WriteAllText($parentScript,$prelude+$config+$mock+"`n"+$elevationBody,$encoding) | |
| 128 | 新增: $requestParameters=$parameters.Clone() | |
| 129 | 新增: $requestParameters.HostOnly=[bool]$case.HostOnly | |
| 130 | 新增: $requestParameters.Tools=[bool]$case.Tools | |
| 131 | 新增: $result=Run-Script $parentScript $requestParameters | |
| 132 | 新增: if ($result.Code -ne $case.Code -or ($case.Code -ne 0 -and !$result.Error.Contains('CAGE_WINDOWS_MAINTENANCE_'+$case.Phase))) { | |
| 133 | 新增: throw "RunAs stage lost for $($case.Name) $($result | ConvertTo-Json -Compress)" | |
| 134 | 新增: } | |
| 135 | 新增: Write-Output ("Passed {0} with exit {1}" -f $case.Name,$result.Code) | |
| 136 | 新增: } | |
| 137 | 新增: Write-Output 'Passed real binding/manifest preflight, production stage ownership, HostOnly, regular Tools, explicit child exits, legacy errors and nested UAC cancellation (isolated processes, simulated elevation).' | |
| 138 | 新增:} finally { | |
| 139 | 新增: Remove-Item -LiteralPath $temporary -Recurse -Force | |
| 140 | 新增:} | |
没有文字改动(可能只改了权限)。
| @@ -0,0 +1,109 @@ | ||
| 1 | 新增:--- a/sshfs.c | |
| 2 | 新增:+++ b/sshfs.c | |
| 3 | 新增:@@ -324,6 +324,9 @@ | |
| 4 | 新增: }; | |
| 5 | 新增: | |
| 6 | 新增: struct sshfs { | |
| 7 | 新增:+#ifdef __APPLE__ | |
| 8 | 新增:+ char *cage_openwith; | |
| 9 | 新增:+#endif | |
| 10 | 新增: char *directport; | |
| 11 | 新增: char *ssh_command; | |
| 12 | 新增: char *sftp_server; | |
| 13 | 新增:@@ -497,6 +500,9 @@ | |
| 14 | 新增: #define SSHFS_OPT(t, p, v) { t, offsetof(struct sshfs, p), v } | |
| 15 | 新增: | |
| 16 | 新增: static struct fuse_opt sshfs_opts[] = { | |
| 17 | 新增:+#ifdef __APPLE__ | |
| 18 | 新增:+ SSHFS_OPT("cage_openwith=%s", cage_openwith, 0), | |
| 19 | 新增:+#endif | |
| 20 | 新增: SSHFS_OPT("directport=%s", directport, 0), | |
| 21 | 新增: SSHFS_OPT("ssh_command=%s", ssh_command, 0), | |
| 22 | 新增: SSHFS_OPT("sftp_server=%s", sftp_server, 0), | |
| 23 | 新增:@@ -3829,7 +3835,76 @@ | |
| 24 | 新增: return 0; | |
| 25 | 新增: } | |
| 26 | 新增: | |
| 27 | 新增:+#ifdef __APPLE__ | |
| 28 | 新增:+/* Present guest-local LaunchServices metadata without creating host xattrs | |
| 29 | 新增:+ * or AppleDouble files in a shared project. The GUI helper publishes this | |
| 30 | 新增:+ * opaque value with the supported NSWorkspace per-file association API. */ | |
| 31 | 新增:+static int cage_getxattr(const char *path, const char *name, char *value, | |
| 32 | 新增:+ size_t size) | |
| 33 | 新增:+{ | |
| 34 | 新增:+ if (!sshfs.cage_openwith || strcmp(name, "com.apple.LaunchServices.OpenWith")) | |
| 35 | 新增:+ return -ENOTSUP; | |
| 36 | 新增:+ | |
| 37 | 新增:+ struct stat target; | |
| 38 | 新增:+ int status = sshfs_getattr(path, &target, NULL); | |
| 39 | 新增:+ if (status != 0) | |
| 40 | 新增:+ return status; | |
| 41 | 新增:+ if (!S_ISREG(target.st_mode)) | |
| 42 | 新增:+ return -ENOATTR; | |
| 43 | 新增:+ | |
| 44 | 新增:+ int fd = open(sshfs.cage_openwith, O_RDONLY | O_CLOEXEC | O_NOFOLLOW); | |
| 45 | 新增:+ if (fd < 0) | |
| 46 | 新增:+ return errno == ENOENT ? -ENOATTR : -errno; | |
| 47 | 新增:+ struct stat st; | |
| 48 | 新增:+ int result; | |
| 49 | 新增:+ if (fstat(fd, &st) != 0) { | |
| 50 | 新增:+ result = -errno; | |
| 51 | 新增:+ } else if (!S_ISREG(st.st_mode) || st.st_size <= 0 || st.st_size > 65536) { | |
| 52 | 新增:+ result = -EIO; | |
| 53 | 新增:+ } else if (!size) { | |
| 54 | 新增:+ result = (int)st.st_size; | |
| 55 | 新增:+ } else if (size < (size_t)st.st_size) { | |
| 56 | 新增:+ result = -ERANGE; | |
| 57 | 新增:+ } else { | |
| 58 | 新增:+ size_t copied = 0; | |
| 59 | 新增:+ result = (int)st.st_size; | |
| 60 | 新增:+ while (copied < (size_t)st.st_size) { | |
| 61 | 新增:+ ssize_t count = read(fd, value + copied, (size_t)st.st_size - copied); | |
| 62 | 新增:+ if (count < 0 && errno == EINTR) | |
| 63 | 新增:+ continue; | |
| 64 | 新增:+ if (count <= 0) { | |
| 65 | 新增:+ result = count < 0 ? -errno : -EIO; | |
| 66 | 新增:+ break; | |
| 67 | 新增:+ } | |
| 68 | 新增:+ copied += (size_t)count; | |
| 69 | 新增:+ } | |
| 70 | 新增:+ } | |
| 71 | 新增:+ close(fd); | |
| 72 | 新增:+ return result; | |
| 73 | 新增:+} | |
| 74 | 新增:+ | |
| 75 | 新增:+static int cage_listxattr(const char *path, char *list, size_t size) | |
| 76 | 新增:+{ | |
| 77 | 新增:+ const char name[] = "com.apple.LaunchServices.OpenWith"; | |
| 78 | 新增:+ int available = cage_getxattr(path, name, NULL, 0); | |
| 79 | 新增:+ if (available == -ENOATTR) | |
| 80 | 新增:+ return 0; | |
| 81 | 新增:+ if (available < 0) | |
| 82 | 新增:+ return available; | |
| 83 | 新增:+ if (!size) | |
| 84 | 新增:+ return sizeof(name); | |
| 85 | 新增:+ if (size < sizeof(name)) | |
| 86 | 新增:+ return -ERANGE; | |
| 87 | 新增:+ memcpy(list, name, sizeof(name)); | |
| 88 | 新增:+ return sizeof(name); | |
| 89 | 新增:+} | |
| 90 | 新增:+#endif | |
| 91 | 新增:+ | |
| 92 | 新增: static struct fuse_operations sshfs_oper = { | |
| 93 | 新增:+#ifdef __APPLE__ | |
| 94 | 新增:+ .getxattr = cage_getxattr, | |
| 95 | 新增:+ .listxattr = cage_listxattr, | |
| 96 | 新增:+#endif | |
| 97 | 新增: .init = sshfs_init, | |
| 98 | 新增: .getattr = sshfs_getattr, | |
| 99 | 新增: .access = sshfs_access, | |
| 100 | 新增:@@ -3862,6 +3937,9 @@ | |
| 101 | 新增: { | |
| 102 | 新增: printf( | |
| 103 | 新增: "usage: %s [user@]host:[dir] mountpoint [options]\n" | |
| 104 | 新增:+#ifdef __APPLE__ | |
| 105 | 新增:+" -o cage_openwith=FILE read guest-local file-opening metadata\n" | |
| 106 | 新增:+#endif | |
| 107 | 新增: "\n" | |
| 108 | 新增: " -h --help print help\n" | |
| 109 | 新增: " -V --version print version\n" | |
| @@ -7,6 +7,7 @@ import { tmpdir } from "node:os"; | ||
| 7 | 7 | import path from "node:path"; |
| 8 | 8 | import { createInterface } from "node:readline"; |
| 9 | 9 | import { serveMacOSBrowser, relayMacOSBrowser } from "../macos-browser-service.mjs"; |
| 10 | 新增:const unixService = process.platform === "win32" ? test.skip : test; | |
| 10 | 11 | |
| 11 | 12 | async function fixture(t, dispatch) { |
| 12 | 13 | const directory = await mkdtemp(path.join(tmpdir(), "cage-bs-")); |
| @@ -29,7 +30,7 @@ async function fixture(t, dispatch) { | ||
| 29 | 30 | return { directory, connect, service, stopped: () => stopped }; |
| 30 | 31 | } |
| 31 | 32 | |
| 32 | 删除:test("Mac browser connections retain owned state and publish service ownership", async t => { | |
| 33 | 新增:unixService("Mac browser connections retain owned state and publish service ownership", async t => { | |
| 33 | 34 | let value = ""; |
| 34 | 35 | const f = await fixture(t, async request => { |
| 35 | 36 | if (request.text !== undefined) value = request.text; |
| @@ -47,7 +48,7 @@ test("Mac browser connections retain owned state and publish service ownership", | ||
| 47 | 48 | await assert.rejects(serveMacOSBrowser({ directory: f.directory, dispatch: async () => ({}), close: async () => {} }), /already running/); |
| 48 | 49 | }); |
| 49 | 50 | |
| 50 | 删除:test("Mac browser service drops a disconnected caller's queued mutation", async t => { | |
| 51 | 新增:unixService("Mac browser service drops a disconnected caller's queued mutation", async t => { | |
| 51 | 52 | let release, began; |
| 52 | 53 | const started = new Promise(resolve => { began = resolve; }); |
| 53 | 54 | const wait = new Promise(resolve => { release = resolve; }); |
| @@ -69,7 +70,7 @@ test("Mac browser service drops a disconnected caller's queued mutation", async | ||
| 69 | 70 | assert.deepEqual(applied, ["first", "last"]); |
| 70 | 71 | }); |
| 71 | 72 | |
| 72 | 删除:test("Mac browser service refuses insecure directories and unrelated socket paths", async t => { | |
| 73 | 新增:unixService("Mac browser service refuses insecure directories and unrelated socket paths", async t => { | |
| 73 | 74 | const directory = await mkdtemp(path.join(tmpdir(), "cage-bs-")); |
| 74 | 75 | t.after(() => rm(directory, { recursive: true, force: true })); |
| 75 | 76 | await chmod(directory, 0o755); |
| @@ -80,3 +81,13 @@ test("Mac browser service refuses insecure directories and unrelated socket path | ||
| 80 | 81 | await assert.rejects(serveMacOSBrowser({ directory, dispatch: async () => ({}), close: async () => {} }), /socket/); |
| 81 | 82 | assert.equal((await stat(path.join(directory, "browser.sock"))).isFile(), true); |
| 82 | 83 | }); |
| 84 | 新增: | |
| 85 | 新增:unixService("Mac browser service releases its endpoint when owned browser shutdown fails", async t => { | |
| 86 | 新增: const directory = await mkdtemp(path.join(tmpdir(), "cage-bs-")); | |
| 87 | 新增: t.after(() => rm(directory, { recursive: true, force: true })); | |
| 88 | 新增: const service = await serveMacOSBrowser({ directory, dispatch: async () => ({}), close: async () => { throw new Error("fixture shutdown failure"); } }); | |
| 89 | 新增: await assert.rejects(service.close(), /fixture shutdown failure/); | |
| 90 | 新增: await assert.rejects(stat(path.join(directory, "browser.sock")), { code: "ENOENT" }); | |
| 91 | 新增: const replacement = await serveMacOSBrowser({ directory, dispatch: async () => ({}), close: async () => {} }); | |
| 92 | 新增: await replacement.close(); | |
| 93 | 新增:}); | |
| @@ -133,7 +133,7 @@ integration("actual Chromium tabs restore and project switching retains unsaved | ||
| 133 | 133 | await assert.rejects(f.call("insert-text", { id: editor.id, text: "迟到输入" }), { code: "project_grant_unavailable" }); |
| 134 | 134 | } |
| 135 | 135 | }); |
| 136 | 删除:integration("private editor connection applies only the issued alias's HTML defaults through loopback", async t => { | |
| 136 | 新增:(process.env.CAGE_BROWSER_TEST_PLATFORM === "darwin" ? test.skip : integration)("Windows private editor connection applies only the issued alias's HTML defaults through loopback", async t => { | |
| 137 | 137 | const f = await fixture(t), project = "d".repeat(16), connection = "e".repeat(32); |
| 138 | 138 | const url = new URL(f.url); url.hostname = project + ".cage-editor.localhost"; url.search = "?editor=" + project; |
| 139 | 139 | const input = { workspace: project, connection, url: url.href, folder: f.root, trust_default: false }; |
| @@ -451,6 +451,11 @@ macImages("Mac image preparation rejects a changed field before accepting bytes" | ||
| 451 | 451 | |
| 452 | 452 | macImages("Mac clipboard text uses one bounded transfer and one final insertion", async t => { |
| 453 | 453 | const f = await fixture(t), one = await f.open(); |
| 454 | 新增: await one.page.evaluate(() => { | |
| 455 | 新增: document.querySelector("#first").addEventListener("paste", event => { | |
| 456 | 新增: window.textPaste = { trusted: event.isTrusted, text: event.clipboardData.getData("text/plain") }; | |
| 457 | 新增: }); | |
| 458 | 新增: }); | |
| 454 | 459 | await f.click(one.id, one.page, "#first"); |
| 455 | 460 | assert.equal(f.launchOptions().ignoreDefaultArgs.includes("--mute-audio"), true); |
| 456 | 461 | const text = "中".repeat(Math.floor((2 << 20) / 3)) + "ab", bytes = Buffer.from(text); |
| @@ -466,11 +471,33 @@ macImages("Mac clipboard text uses one bounded transfer and one final insertion" | ||
| 466 | 471 | const actual = await one.page.locator("#first").inputValue(); |
| 467 | 472 | assert.equal(Buffer.byteLength(actual), bytes.length); |
| 468 | 473 | assert.equal(createHash("sha256").update(actual).digest("hex"), createHash("sha256").update(text).digest("hex")); |
| 474 | 新增: const pasted = await one.page.evaluate(() => window.textPaste); | |
| 475 | 新增: assert.equal(pasted.trusted, true); | |
| 476 | 新增: assert.equal(pasted.text, text); | |
| 469 | 477 | const tooLarge = await f.call("paste-start", { id: one.id }); |
| 470 | 478 | await assert.rejects(f.call("paste-chunk", { transfer: tooLarge.transfer, sequence: 0, length: bytes.length + 1, mime: "text/plain", data: "YQ==" }), /大小/); |
| 471 | 479 | }); |
| 472 | 480 | |
| 473 | 481 | const macImagePaste = playwrightPath && executablePath && process.env.CAGE_BROWSER_TEST_PLATFORM === "darwin" && process.env.CAGE_BROWSER_TEST_PNG_PASTE === "1" ? test : test.skip; |
| 482 | 新增:integration("native paste preparation rejects a field switch inside a child frame", async t => { | |
| 483 | 新增: const f = await fixture(t), one = await f.open(); | |
| 484 | 新增: for (const origin of [f.url, f.url.replace("127.0.0.1", "localhost")]) { | |
| 485 | 新增: await one.page.evaluate(url => { | |
| 486 | 新增: document.querySelector("#child")?.remove(); | |
| 487 | 新增: const frame = document.createElement("iframe"); frame.id = "child"; frame.src = url; | |
| 488 | 新增: document.body.append(frame); | |
| 489 | 新增: }, origin + "/child"); | |
| 490 | 新增: const child = one.page.frameLocator("#child"); | |
| 491 | 新增: await child.locator("#first").click(); | |
| 492 | 新增: const before = await f.call("focus-proof", {}, "GET"); | |
| 493 | 新增: const prepared = await f.call("paste-start", { id: one.id }); | |
| 494 | 新增: await child.locator("#second").focus(); | |
| 495 | 新增: const after = await f.call("focus-proof", {}, "GET"); | |
| 496 | 新增: assert.notEqual(after.focus, before.focus); | |
| 497 | 新增: await assert.rejects(f.call("paste-chunk", { transfer: prepared.transfer, sequence: 0, mime: "text/plain", length: 1, data: "YQ==" }), /target changed/i); | |
| 498 | 新增: } | |
| 499 | 新增:}); | |
| 500 | 新增: | |
| 474 | 501 | macImagePaste("Mac headless image transfer delivers an actual PNG paste event", async t => { |
| 475 | 502 | const f = await fixture(t), one = await f.open(); |
| 476 | 503 | await one.page.evaluate(() => { |
| @@ -497,6 +524,88 @@ macImagePaste("Mac headless image transfer delivers an actual PNG paste event", | ||
| 497 | 524 | await assert.rejects(f.call("image-finish", { transfer: prepared.transfer, sequence }), /已关闭|顺序/); |
| 498 | 525 | }); |
| 499 | 526 | |
| 527 | 新增:async function readClipboardReference(f, copied) { | |
| 528 | 新增: assert.match(copied.clipboard.id, /^[a-f0-9-]{36}$/); | |
| 529 | 新增: const opened = await f.call("file-open", { direction: "download", id: copied.clipboard.id, tab: copied.id, context: copied.context, document: copied.document }); | |
| 530 | 新增: assert.equal(opened.mime, copied.clipboard.mime); | |
| 531 | 新增: assert.equal(opened.size, copied.clipboard.size); | |
| 532 | 新增: const chunks = []; | |
| 533 | 新增: let sequence = 0, result; | |
| 534 | 新增: do { | |
| 535 | 新增: result = await f.call("file-read", { transfer: opened.transfer, sequence }); | |
| 536 | 新增: assert.equal(result.sequence, ++sequence); | |
| 537 | 新增: chunks.push(Buffer.from(result.data, "base64")); | |
| 538 | 新增: } while (!result.eof); | |
| 539 | 新增: const bytes = Buffer.concat(chunks); | |
| 540 | 新增: assert.equal(bytes.length, opened.size); | |
| 541 | 新增: return bytes; | |
| 542 | 新增:} | |
| 543 | 新增: | |
| 544 | 新增:macImagePaste("Mac webpage PNG copy exports a bound reference with the original pixels", async t => { | |
| 545 | 新增: const f = await fixture(t), one = await f.open(); | |
| 546 | 新增: await one.page.evaluate(() => { | |
| 547 | 新增: document.querySelector("#copy").onclick = async () => { | |
| 548 | 新增: const canvas = document.createElement("canvas"); | |
| 549 | 新增: canvas.width = 8; canvas.height = 4; | |
| 550 | 新增: const context = canvas.getContext("2d"); | |
| 551 | 新增: context.fillStyle = "#d82931"; context.fillRect(0, 0, 4, 4); | |
| 552 | 新增: context.fillStyle = "#264dc6"; context.fillRect(4, 0, 4, 4); | |
| 553 | 新增: const blob = await new Promise(resolve => canvas.toBlob(resolve, "image/png")); | |
| 554 | 新增: await navigator.clipboard.write([new ClipboardItem({ "image/png": blob })]); | |
| 555 | 新增: }; | |
| 556 | 新增: }); | |
| 557 | 新增: const context = "b".repeat(32); | |
| 558 | 新增: await f.call("copy-context", { id: one.id, context }); | |
| 559 | 新增: await f.click(one.id, one.page, "#copy"); | |
| 560 | 新增: let copied; | |
| 561 | 新增: for (let attempt = 0; attempt < 100 && !copied; attempt++) { | |
| 562 | 新增: const state = await f.call("events", {}, "GET"); | |
| 563 | 新增: copied = state.events.find(event => event.type === "clipboard" && event.value.context === context)?.value; | |
| 564 | 新增: if (!copied) await new Promise(resolve => setTimeout(resolve, 20)); | |
| 565 | 新增: } | |
| 566 | 新增: assert.equal(copied?.clipboard?.mime, "image/png", JSON.stringify(copied)); | |
| 567 | 新增: assert.equal(copied.png, undefined); | |
| 568 | 新增: assert.equal(copied.text, undefined); | |
| 569 | 新增: assert.equal((await f.call("tabs", {}, "GET")).tabs.some(tab => tab.url.includes("cage-clipboard.localhost")), false); | |
| 570 | 新增: await assert.rejects(f.call("file-open", { direction: "download", id: copied.clipboard.id }), { code: "copy_changed" }); | |
| 571 | 新增: const bytes = await readClipboardReference(f, copied); | |
| 572 | 新增: const pixels = await one.page.evaluate(async encoded => { | |
| 573 | 新增: const bytes = Uint8Array.from(atob(encoded), value => value.charCodeAt(0)); | |
| 574 | 新增: const bitmap = await createImageBitmap(new Blob([bytes], { type: "image/png" })); | |
| 575 | 新增: const canvas = document.createElement("canvas"); canvas.width = bitmap.width; canvas.height = bitmap.height; | |
| 576 | 新增: const context = canvas.getContext("2d"); context.drawImage(bitmap, 0, 0); | |
| 577 | 新增: const result = { width: bitmap.width, height: bitmap.height, left: [...context.getImageData(1, 1, 1, 1).data], right: [...context.getImageData(6, 1, 1, 1).data] }; | |
| 578 | 新增: bitmap.close(); | |
| 579 | 新增: return result; | |
| 580 | 新增: }, bytes.toString("base64")); | |
| 581 | 新增: assert.deepEqual(pixels, { width: 8, height: 4, left: [216, 41, 49, 255], right: [38, 77, 198, 255] }); | |
| 582 | 新增: await f.call("copy-context", { id: one.id, context: "c".repeat(32) }); | |
| 583 | 新增: await assert.rejects(readClipboardReference(f, copied), { code: "copy_changed" }); | |
| 584 | 新增:}); | |
| 585 | 新增: | |
| 586 | 新增:macImagePaste("Mac native copy and cut preserve 2 MiB UTF-8 text and reject superseded reads", async t => { | |
| 587 | 新增: const f = await fixture(t), one = await f.open(); | |
| 588 | 新增: const text = "中".repeat(Math.floor((2 << 20) / 3)) + "ab"; | |
| 589 | 新增: await one.page.locator("#first").fill(text); | |
| 590 | 新增: await one.page.locator("#first").selectText(); | |
| 591 | 新增: const copied = await f.call("copy", { id: one.id, context: "1".repeat(32) }); | |
| 592 | 新增: assert.equal(copied.clipboard.mime, "text/plain"); | |
| 593 | 新增: assert.equal(copied.clipboard.size, 2 << 20); | |
| 594 | 新增: assert.equal((await readClipboardReference(f, copied)).toString("utf8"), text); | |
| 595 | 新增: assert.equal(await one.page.locator("#first").inputValue(), text); | |
| 596 | 新增: const opened = await f.call("file-open", { direction: "download", id: copied.clipboard.id, tab: copied.id, context: copied.context, document: copied.document }); | |
| 597 | 新增: const first = await f.call("file-read", { transfer: opened.transfer, sequence: 0 }); | |
| 598 | 新增: assert.equal(first.eof, false); | |
| 599 | 新增: await f.call("copy-context", { id: one.id, context: "2".repeat(32) }); | |
| 600 | 新增: await assert.rejects(f.call("file-read", { transfer: opened.transfer, sequence: 1 }), { code: "copy_changed" }); | |
| 601 | 新增: const cut = await f.call("cut", { id: one.id, context: "3".repeat(32) }); | |
| 602 | 新增: assert.equal((await readClipboardReference(f, cut)).toString("utf8"), text); | |
| 603 | 新增: assert.equal(await one.page.locator("#first").inputValue(), ""); | |
| 604 | 新增: const state = await f.call("events", {}, "GET"); | |
| 605 | 新增: assert.equal(state.events.some(event => event.type === "clipboard" && [copied.context, cut.context].includes(event.value.context)), false, "explicit copy results must have one consumer"); | |
| 606 | 新增: await assert.rejects(f.call("copy", { id: one.id, context: "4".repeat(32) }), { code: "copy_unavailable" }); | |
| 607 | 新增:}); | |
| 608 | 新增: | |
| 500 | 609 | const nativeExtensions = playwrightPath && executablePath && process.env.CAGE_BROWSER_TEST_EXTENSIONS === "1" ? test : test.skip; |
| 501 | 610 | nativeExtensions("native extension preview, disabled import, activation and restart preserve the selected state", async t => { |
| 502 | 611 | const f = await fixture(t), one = await f.open(); |
| @@ -1,7 +1,7 @@ | ||
| 1 | 1 | import { createTailnetClient } from "./tailnet-client.mjs"; |
| 2 | 2 | // The GUI-session broker owns this process. Playwright uses inherited DevTools |
| 3 | 3 | // pipes; neither the controller nor DevTools opens a guest network listener. |
| 4 | 删除:import { randomBytes } from "node:crypto"; | |
| 4 | 新增:import { randomBytes, randomUUID } from "node:crypto"; | |
| 5 | 5 | import { constants, createReadStream, existsSync } from "node:fs"; |
| 6 | 6 | import { mkdir, open, readFile, rename, rm, stat, writeFile } from "node:fs/promises"; |
| 7 | 7 | import { homedir } from "node:os"; |
| @@ -98,8 +98,8 @@ export function browserExecutable() { | ||
| 98 | 98 | throw failure("browser_unavailable", "请先在 Windows 客机安装受支持的 Chrome 或 Edge"); |
| 99 | 99 | } |
| 100 | 100 | |
| 101 | 删除:// Test dependencies are explicit. Production never falls back to headless mode, | |
| 102 | 删除:// another OS, an arbitrary executable from PATH, or the user's existing profile. | |
| 101 | 新增:// Tests provide their dependencies explicitly. Production uses the selected | |
| 102 | 新增:// guest's browser mode, fixed executable, and Cage-owned profile. | |
| 103 | 103 | export function createNativeBrowserService(options = {}) { |
| 104 | 104 | const mac = options.platform === "darwin"; |
| 105 | 105 | const directory = options.directory ?? path.join(process.env.LOCALAPPDATA || path.join(homedir(), "AppData", "Local"), "Cage", "Browser"); |
| @@ -113,6 +113,8 @@ export function createNativeBrowserService(options = {}) { | ||
| 113 | 113 | const tabs = new Map(), byPage = new WeakMap(), sessions = new Map(), frameSessions = new WeakMap(), internalPages = new WeakSet(); |
| 114 | 114 | const captures = new Map(); |
| 115 | 115 | const events = [], transfers = new Map(), privateContexts = new Set(), editorConnections = new Map(), logins = new Map(); |
| 116 | 新增: const clipboardCopies = new Map(); | |
| 117 | 新增: let clipboardHelper, copyVersion = 0, pendingCopy, copying; | |
| 116 | 118 | let eventSequence = 0, uploads, downloads, clipboard, pointer, composition, clipboardAvailable = false, cookieActions, extensions, controller, internalCreation, vault; |
| 117 | 119 | let stateVersion = 0, snapshotVersion = -1, snapshotAt = 0, snapshotCache; |
| 118 | 120 | let rfbTarget = "", rfbMask = 0, lastClick, rfbPointer; |
| @@ -125,6 +127,131 @@ export function createNativeBrowserService(options = {}) { | ||
| 125 | 127 | events.push({ sequence: ++eventSequence, type, value }); |
| 126 | 128 | while (events.length > 64 || JSON.stringify(events).length > 350000) events.shift(); |
| 127 | 129 | } |
| 130 | 新增: | |
| 131 | 新增: function invalidateCopies() { | |
| 132 | 新增: copyVersion++; | |
| 133 | 新增: pendingCopy = undefined; | |
| 134 | 新增: for (const copy of clipboardCopies.values()) void rm(copy.file, { force: true }).catch(() => {}); | |
| 135 | 新增: clipboardCopies.clear(); | |
| 136 | 新增: } | |
| 137 | 新增: | |
| 138 | 新增: function copyTarget(proof) { | |
| 139 | 新增: const tab = target(proof); | |
| 140 | 新增: if (closing || tab.copyContext !== proof.context || proof.version !== copyVersion) | |
| 141 | 新增: throw failure("copy_changed", "复制来源已切换,请重新复制"); | |
| 142 | 新增: return tab; | |
| 143 | 新增: } | |
| 144 | 新增: | |
| 145 | 新增: async function privateClipboardPage() { | |
| 146 | 新增: if (closing) throw failure("copy_unavailable", "浏览器已关闭"); | |
| 147 | 新增: if (!clipboardHelper) { | |
| 148 | 新增: clipboardHelper = (async () => { | |
| 149 | 新增: const isolated = await owner.newContext({ permissions: ["clipboard-read", "clipboard-write"] }); | |
| 150 | 新增: privateContexts.add(isolated); | |
| 151 | 新增: isolated.on("close", () => { privateContexts.delete(isolated); clipboardHelper = undefined; }); | |
| 152 | 新增: try { | |
| 153 | 新增: const page = await isolated.newPage(); | |
| 154 | 新增: await page.route("http://cage-clipboard.localhost/", route => route.fulfill({ contentType: "text/html", body: "<!doctype html><title>Cage clipboard</title>" })); | |
| 155 | 新增: await page.goto("http://cage-clipboard.localhost/", { waitUntil: "domcontentloaded" }); | |
| 156 | 新增: return page; | |
| 157 | 新增: } catch (error) { await isolated.close(); throw error; } | |
| 158 | 新增: })(); | |
| 159 | 新增: } | |
| 160 | 新增: return clipboardHelper; | |
| 161 | 新增: } | |
| 162 | 新增: | |
| 163 | 新增: async function readPrivateClipboard() { | |
| 164 | 新增: const helper = await privateClipboardPage(); | |
| 165 | 新增: const value = await helper.evaluate(async ({ imageLimit, textLimit }) => { | |
| 166 | 新增: const items = await navigator.clipboard.read(); | |
| 167 | 新增: const mime = items.some(item => item.types.includes("image/png")) ? "image/png" : "text/plain"; | |
| 168 | 新增: const item = items.find(item => item.types.includes(mime)); | |
| 169 | 新增: if (!item) throw new Error("Clipboard format unavailable"); | |
| 170 | 新增: const blob = await item.getType(mime); | |
| 171 | 新增: if (blob.size > (mime === "image/png" ? imageLimit : textLimit)) throw new Error("Clipboard size exceeded"); | |
| 172 | 新增: if (mime === "text/plain") return { text: await blob.text() }; | |
| 173 | 新增: return new Promise((resolve, reject) => { | |
| 174 | 新增: const reader = new FileReader(); | |
| 175 | 新增: reader.onerror = reject; | |
| 176 | 新增: reader.onload = () => resolve({ png: reader.result.slice(reader.result.indexOf(",") + 1) }); | |
| 177 | 新增: reader.readAsDataURL(blob); | |
| 178 | 新增: }); | |
| 179 | 新增: }, { imageLimit, textLimit }); | |
| 180 | 新增: return value; | |
| 181 | 新增: } | |
| 182 | 新增: | |
| 183 | 新增: async function copiedPayload(proof, value) { | |
| 184 | 新增: copyTarget(proof); | |
| 185 | 新增: const payload = { id: proof.id, context: proof.context, document: proof.document }; | |
| 186 | 新增: if (typeof value.text === "string" && Buffer.byteLength(value.text) <= textLimit && Buffer.byteLength(JSON.stringify(value.text)) <= chunkSize) | |
| 187 | 新增: return { ...payload, text: value.text }; | |
| 188 | 新增: const mime = typeof value.text === "string" ? "text/plain" : "image/png"; | |
| 189 | 新增: const bytes = Buffer.from(mime === "text/plain" ? value.text : value.png, mime === "text/plain" ? "utf8" : "base64"); | |
| 190 | 新增: if (bytes.length > (mime === "text/plain" ? textLimit : imageLimit)) throw failure("copy_limit", "复制内容超过大小限制"); | |
| 191 | 新增: if (mime === "image/png" && (bytes.length < 33 || !bytes.subarray(0, 8).equals(Buffer.from([137,80,78,71,13,10,26,10])) || bytes.toString("ascii", 12, 16) !== "IHDR" || | |
| 192 | 新增: !bytes.readUInt32BE(16) || !bytes.readUInt32BE(20) || bytes.readUInt32BE(16) * bytes.readUInt32BE(20) > 40_000_000)) | |
| 193 | 新增: throw failure("copy_image_invalid", "复制的 PNG 图片无效"); | |
| 194 | 新增: const id = randomUUID(), file = path.join(uploadDirectory, "clipboard", id); | |
| 195 | 新增: await mkdir(path.dirname(file), { recursive: true, mode: 0o700 }); | |
| 196 | 新增: await writeFile(file, bytes, { mode: 0o600, flag: "wx" }); | |
| 197 | 新增: try { copyTarget(proof); } | |
| 198 | 新增: catch (error) { await rm(file, { force: true }); throw error; } | |
| 199 | 新增: clipboardCopies.set(id, { ...proof, reference: id, file, mime, size: bytes.length, created: Date.now() }); | |
| 200 | 新增: return { ...payload, clipboard: { id, mime, size: bytes.length } }; | |
| 201 | 新增: } | |
| 202 | 新增: | |
| 203 | 新增: function observeCopy(value) { | |
| 204 | 新增: if (closing) return; | |
| 205 | 新增: const tab = tabs.get(value.id); | |
| 206 | 新增: if (value.id !== active || tab?.copyContext !== value.context) return; | |
| 207 | 新增: if (!mac) { emit("clipboard", { ...value, document: tab.document }); return; } | |
| 208 | 新增: if (tab.explicitCopyContext === value.context) { tab.copyCompletion?.(value); return; } | |
| 209 | 新增: invalidateCopies(); | |
| 210 | 新增: pendingCopy = { value, proof: { id: tab.id, context: value.context, document: tab.document, version: copyVersion } }; | |
| 211 | 新增: if (copying) return; | |
| 212 | 新增: copying = (async () => { | |
| 213 | 新增: while (pendingCopy) { | |
| 214 | 新增: const current = pendingCopy; | |
| 215 | 新增: pendingCopy = undefined; | |
| 216 | 新增: try { | |
| 217 | 新增: const value = current.value.changed ? await readPrivateClipboard() : current.value; | |
| 218 | 新增: emit("clipboard", await copiedPayload(current.proof, value)); | |
| 219 | 新增: } catch { | |
| 220 | 新增: try { copyTarget(current.proof); emit("clipboard", { id: current.proof.id, context: current.proof.context, document: current.proof.document, error: "copy_failed" }); } | |
| 221 | 新增: catch {} | |
| 222 | 新增: } | |
| 223 | 新增: } | |
| 224 | 新增: })().finally(() => { copying = undefined; }); | |
| 225 | 新增: } | |
| 226 | 新增: | |
| 227 | 新增: async function copyAction(tab, input, action, signal) { | |
| 228 | 新增: if (!tokenPattern.test(input.context || "")) throw failure("invalid_input", "复制上下文无效"); | |
| 229 | 新增: const document = tab.document; | |
| 230 | 新增: await privateClipboardPage(); | |
| 231 | 新增: await tab.page.bringToFront(); | |
| 232 | 新增: target({ id: tab.id, document }); | |
| 233 | 新增: invalidateCopies(); | |
| 234 | 新增: tab.copyContext = input.context; | |
| 235 | 新增: tab.explicitCopyContext = input.context; | |
| 236 | 新增: await clipboard.setContext(tab.id, input.context); | |
| 237 | 新增: const proof = { id: tab.id, context: input.context, document, version: copyVersion }; | |
| 238 | 新增: let timeout; | |
| 239 | 新增: const completed = new Promise((resolve, reject) => { | |
| 240 | 新增: tab.copyCompletion = resolve; | |
| 241 | 新增: timeout = setTimeout(() => reject(failure("copy_unavailable", "未收到新的复制内容,请重新选择后复制")), 5000); | |
| 242 | 新增: }); | |
| 243 | 新增: completed.catch(() => {}); | |
| 244 | 新增: try { | |
| 245 | 新增: signal?.throwIfAborted(); | |
| 246 | 新增: await tab.page.keyboard.press(action === "cut" ? "Meta+X" : "Meta+C"); | |
| 247 | 新增: await completed; | |
| 248 | 新增: signal?.throwIfAborted(); | |
| 249 | 新增: copyTarget(proof); | |
| 250 | 新增: const value = await readPrivateClipboard(); | |
| 251 | 新增: signal?.throwIfAborted(); | |
| 252 | 新增: return await copiedPayload(proof, value); | |
| 253 | 新增: } finally { clearTimeout(timeout); tab.copyCompletion = undefined; } | |
| 254 | 新增: } | |
| 128 | 255 | function remember() { |
| 129 | 256 | if (!context || closing) return; |
| 130 | 257 | const value = [...tabs.values()].filter(t => !t.incognito && !t.login && t.kind !== "editor").map(t => ({ id: t.id, url: t.page.url(), ...(t.kind === "browser-settings" ? { kind: t.kind, publicURL: t.publicURL } : {}) })); |
| @@ -243,6 +370,7 @@ export function createNativeBrowserService(options = {}) { | ||
| 243 | 370 | page.on("close", () => { |
| 244 | 371 | void stopCapture(page); |
| 245 | 372 | tabs.delete(id); clipboard?.detachTab(id); uploads?.cancelTab(id); |
| 373 | 新增: if (active === id) invalidateCopies(); | |
| 246 | 374 | if (vault) for (const [sid, entry] of vault.sessions) if (entry.tab === id) vault.sessions.delete(sid); |
| 247 | 375 | if (active === id) active = [...tabs.keys()].at(-1) || ""; |
| 248 | 376 | if (pointer?.id === id) pointer = undefined; |
| @@ -253,6 +381,7 @@ export function createNativeBrowserService(options = {}) { | ||
| 253 | 381 | }); |
| 254 | 382 | page.on("framenavigated", frame => { |
| 255 | 383 | if (frame === page.mainFrame()) { |
| 384 | 新增: if (active === id) invalidateCopies(); | |
| 256 | 385 | if (tab.kind !== "editor") { |
| 257 | 386 | try { |
| 258 | 387 | const address = new URL(page.url()), project = /^([a-f0-9]{16}(?:[a-f0-9]{8})?)\.cage-editor\.localhost$/.exec(address.hostname)?.[1]; |
| @@ -353,10 +482,7 @@ export function createNativeBrowserService(options = {}) { | ||
| 353 | 482 | context.setDefaultTimeout(7000); owner = context.browser(); |
| 354 | 483 | if (!owner) throw failure("browser_unavailable", "Windows 客机浏览器控制连接未就绪"); |
| 355 | 484 | browserCDP = await owner.newBrowserCDPSession(); |
| 356 | 删除: clipboard = new modules.BrowserClipboard(cdp, value => { | |
| 357 | 删除: const tab = tabs.get(value.id); | |
| 358 | 删除: if (value.id === active && tab?.copyContext === value.context) emit("clipboard", { ...value, document: tab.document }); | |
| 359 | 删除: }); | |
| 485 | 新增: clipboard = new modules.BrowserClipboard(cdp, observeCopy, { includeChanges: mac }); | |
| 360 | 486 | clipboardAvailable = true; |
| 361 | 487 | if (modules.BrowserVault) vault = new modules.BrowserVault({ cdp, active: () => active, tab: id => { const tab = tabs.get(id); return tab ? { ...tab, url: tab.page.url() } : undefined; } }); |
| 362 | 488 | cookieActions = modules.browserCookies; |
| @@ -452,7 +578,7 @@ export function createNativeBrowserService(options = {}) { | ||
| 452 | 578 | } |
| 453 | 579 | async function activate(id) { |
| 454 | 580 | const tab = tabs.get(id); if (!tab) throw failure("target_changed", "Tab no longer exists"); |
| 455 | 删除: if (active !== id) { pointer = undefined; composition = undefined; tab.geometry = token(); } | |
| 581 | 新增: if (active !== id) { invalidateCopies(); pointer = undefined; composition = undefined; tab.geometry = token(); } | |
| 456 | 582 | if (split && ![split.left, split.right].includes(id)) { split = undefined; await applyViewport(); } |
| 457 | 583 | active = id; await tab.page.bringToFront(); changed(); return { ok: true }; |
| 458 | 584 | } |
| @@ -530,13 +656,28 @@ export function createNativeBrowserService(options = {}) { | ||
| 530 | 656 | await syncNativeFrontTab(); |
| 531 | 657 | const tab = target({ id: active }); |
| 532 | 658 | const tree = await cdp("Page.getFrameTree", {}, tab.session); |
| 533 | 删除: const isolated = await cdp("Page.createIsolatedWorld", { frameId: tree.frameTree.frame.id, worldName: "cage-native-paste-proof" }, tab.session); | |
| 534 | 删除: const result = await cdp("Runtime.evaluate", { expression: `(() => { let e=Object.getOwnPropertyDescriptor(Document.prototype,'activeElement').get.call(document); while(e){const root=Object.getOwnPropertyDescriptor(Element.prototype,'shadowRoot').get.call(e); if(!root)break; const next=Object.getOwnPropertyDescriptor(ShadowRoot.prototype,'activeElement').get.call(root);if(!next)break;e=next;}return e; })()`, contextId: isolated.executionContextId, objectGroup: "cage-paste-proof" }, tab.session); | |
| 535 | 删除: try { | |
| 536 | 删除: if (!result.result?.objectId) throw failure("target_changed", "Input target changed"); | |
| 537 | 删除: const node = await cdp("DOM.describeNode", { objectId: result.result.objectId }, tab.session); | |
| 538 | 删除: return { focus: `${tab.document}:${isolated.executionContextId}:${node.node.backendNodeId}` }; | |
| 539 | 删除: } finally { await cdp("Runtime.releaseObjectGroup", { objectGroup: "cage-paste-proof" }, tab.session); } | |
| 659 | 新增: const roots = new Map([[tree.frameTree.frame.id, tab.session]]); | |
| 660 | 新增: for (const session of new Set(tab.page.frames().map(frame => frameSessions.get(frame)))) { | |
| 661 | 新增: if (!session || session === tab.session) continue; | |
| 662 | 新增: const child = await cdp("Page.getFrameTree", {}, session).catch(() => null); | |
| 663 | 新增: if (child) roots.set(child.frameTree.frame.id, session); | |
| 664 | 新增: } | |
| 665 | 新增: const nodes = [], visited = new Set(); | |
| 666 | 新增: let frameId = tree.frameTree.frame.id, session = tab.session; | |
| 667 | 新增: while (frameId) { | |
| 668 | 新增: if (visited.has(frameId)) throw failure("target_changed", "Input target changed"); | |
| 669 | 新增: visited.add(frameId); | |
| 670 | 新增: session = roots.get(frameId) || session; | |
| 671 | 新增: const isolated = await cdp("Page.createIsolatedWorld", { frameId, worldName: "cage-native-paste-proof" }, session); | |
| 672 | 新增: try { | |
| 673 | 新增: const result = await cdp("Runtime.evaluate", { expression: `(() => { let e=Object.getOwnPropertyDescriptor(Document.prototype,'activeElement').get.call(document); while(e){const root=Object.getOwnPropertyDescriptor(Element.prototype,'shadowRoot').get.call(e); if(!root)break; const next=Object.getOwnPropertyDescriptor(ShadowRoot.prototype,'activeElement').get.call(root);if(!next)break;e=next;}return e; })()`, contextId: isolated.executionContextId, objectGroup: "cage-paste-proof" }, session); | |
| 674 | 新增: if (!result.result?.objectId) throw failure("target_changed", "Input target changed"); | |
| 675 | 新增: const { node } = await cdp("DOM.describeNode", { objectId: result.result.objectId }, session); | |
| 676 | 新增: nodes.push(`${frameId}:${isolated.executionContextId}:${node.backendNodeId}`); | |
| 677 | 新增: frameId = node.frameId; | |
| 678 | 新增: } finally { await cdp("Runtime.releaseObjectGroup", { objectGroup: "cage-paste-proof" }, session); } | |
| 679 | 新增: } | |
| 680 | 新增: return { focus: `${tab.document}:${nodes.join("/")}` }; | |
| 540 | 681 | } |
| 541 | 682 | function point(input, size = viewport) { |
| 542 | 683 | if (![input.x, input.y].every(v => Number.isFinite(v) && v >= 0 && v <= 1)) throw failure("invalid_input", "指针位置无效"); |
| @@ -604,6 +745,10 @@ export function createNativeBrowserService(options = {}) { | ||
| 604 | 745 | const request = uploads.request(transfer.id), tab = tabs.get(request.tabId); |
| 605 | 746 | if (request !== transfer.request || active !== request.tabId || tab?.document !== transfer.document) throw failure("target_changed", "文件接收网页已切换,请返回原网页重试"); |
| 606 | 747 | } |
| 748 | 新增: if (transfer.copy) { | |
| 749 | 新增: copyTarget(transfer.copy); | |
| 750 | 新增: if (clipboardCopies.get(transfer.copy.reference) !== transfer.copy) throw failure("copy_changed", "复制内容已过期,请重新复制"); | |
| 751 | 新增: } | |
| 607 | 752 | return transfer; |
| 608 | 753 | } |
| 609 | 754 | async function closeTransfer(id) { |
| @@ -621,6 +766,10 @@ export function createNativeBrowserService(options = {}) { | ||
| 621 | 766 | input.mime && !["image/png", "text/plain"].includes(input.mime)) |
| 622 | 767 | throw failure("image_target_invalid", "图片目标或大小无效"); |
| 623 | 768 | const document = tab.document, geometry = tab.geometry; |
| 769 | 新增: if (mac) { | |
| 770 | 新增: invalidateCopies(); tab.copyContext = ""; | |
| 771 | 新增: await clipboard.setContext(tab.id, ""); | |
| 772 | 新增: } | |
| 624 | 773 | const focus = await nativeFocusProof(); |
| 625 | 774 | signal?.throwIfAborted(); |
| 626 | 775 | if (target(input) !== tab || tab.document !== document || tab.geometry !== geometry) throw failure("image_target_changed", "Image target changed"); |
| @@ -656,29 +805,29 @@ export function createNativeBrowserService(options = {}) { | ||
| 656 | 805 | let text; |
| 657 | 806 | if (transfer.mime === "text/plain") { |
| 658 | 807 | text = new TextDecoder("utf-8", { fatal: true }).decode(bytes); |
| 808 | 新增: if (mac) { | |
| 809 | 新增: const helper = await privateClipboardPage(); | |
| 810 | 新增: signal?.throwIfAborted(); | |
| 811 | 新增: await helper.evaluate(text => navigator.clipboard.writeText(text), text); | |
| 812 | 新增: } | |
| 659 | 813 | } else { |
| 660 | 814 | if (bytes.length < 33 || !bytes.subarray(0, 8).equals(Buffer.from([137,80,78,71,13,10,26,10])) || bytes.toString("ascii", 12, 16) !== "IHDR" || |
| 661 | 815 | !bytes.readUInt32BE(16) || !bytes.readUInt32BE(20) || bytes.readUInt32BE(16) * bytes.readUInt32BE(20) > 40_000_000) |
| 662 | 816 | throw failure("image_invalid", "PNG 图片无效"); |
| 663 | 817 | // A private, local helper origin writes Chromium's clipboard. The site |
| 664 | 818 | // receives an ordinary paste event without gaining clipboard permissions. |
| 665 | 删除: const isolated = await owner.newContext({ permissions: ["clipboard-write"] }); | |
| 666 | 删除: try { | |
| 667 | 删除: const helper = await isolated.newPage(); | |
| 668 | 删除: await helper.route("http://cage-image.localhost/", route => route.fulfill({ contentType: "text/html", body: "<!doctype html><title>Cage image input</title>" })); | |
| 669 | 删除: await helper.goto("http://cage-image.localhost/", { waitUntil: "domcontentloaded" }); | |
| 670 | 删除: signal?.throwIfAborted(); | |
| 671 | 删除: await helper.evaluate(async encoded => { | |
| 672 | 删除: const bytes = Uint8Array.from(atob(encoded), value => value.charCodeAt(0)); | |
| 673 | 删除: await navigator.clipboard.write([new ClipboardItem({ "image/png": new Blob([bytes], { type: "image/png" }) })]); | |
| 674 | 删除: }, bytes.toString("base64")); | |
| 675 | 删除: } finally { await isolated.close(); } | |
| 819 | 新增: const helper = await privateClipboardPage(); | |
| 820 | 新增: signal?.throwIfAborted(); | |
| 821 | 新增: await helper.evaluate(async encoded => { | |
| 822 | 新增: const bytes = Uint8Array.from(atob(encoded), value => value.charCodeAt(0)); | |
| 823 | 新增: await navigator.clipboard.write([new ClipboardItem({ "image/png": new Blob([bytes], { type: "image/png" }) })]); | |
| 824 | 新增: }, bytes.toString("base64")); | |
| 676 | 825 | } |
| 677 | 826 | await tab.page.bringToFront(); |
| 678 | 827 | if (target({ id: transfer.id, document: transfer.document }) !== tab || tab.geometry !== transfer.geometry || (await nativeFocusProof()).focus !== transfer.focus) |
| 679 | 828 | throw failure("image_target_changed", "Image target changed"); |
| 680 | 829 | signal?.throwIfAborted(); |
| 681 | 删除: if (text !== undefined) await tab.page.keyboard.insertText(text); | |
| 830 | 新增: if (text !== undefined && !mac) await tab.page.keyboard.insertText(text); | |
| 682 | 831 | else await tab.page.keyboard.press(mac ? "Meta+V" : "Control+V"); |
| 683 | 832 | transfers.delete(input.transfer); |
| 684 | 833 | return { ok: true }; |
| @@ -704,12 +853,21 @@ export function createNativeBrowserService(options = {}) { | ||
| 704 | 853 | transfers.set(transferID, transfer); return { transfer: transferID }; |
| 705 | 854 | } |
| 706 | 855 | if (input.direction === "download") { |
| 707 | 删除: const source = downloads.sourceFile(input.id), file = await open(source, constants.O_RDONLY | (constants.O_NOFOLLOW || 0)); | |
| 856 | 新增: const copy = clipboardCopies.get(input.id); | |
| 857 | 新增: if (copy || input.context || input.document || input.tab) { | |
| 858 | 新增: if (!copy || input.tab !== copy.id || input.context !== copy.context || input.document !== copy.document) throw failure("copy_changed", "复制来源已切换,请重新复制"); | |
| 859 | 新增: copyTarget(copy); | |
| 860 | 新增: } | |
| 861 | 新增: const source = copy ? copy.file : downloads.sourceFile(input.id), file = await open(source, constants.O_RDONLY | (constants.O_NOFOLLOW || 0)); | |
| 708 | 862 | const info = await file.stat(); |
| 709 | 863 | if (!info.isFile()) { await file.close(); throw failure("download_unavailable", "下载文件不可用"); } |
| 710 | 删除: const record = downloads.snapshot().find(d => d.id === input.id); | |
| 711 | 删除: transfers.set(transferID, { direction: "download", id: input.id, file, length: info.size, received: 0, sequence: 0, used: Date.now() }); | |
| 712 | 删除: return { transfer: transferID, size: info.size, name: record.name }; | |
| 864 | 新增: if (copy) { | |
| 865 | 新增: try { copyTarget(copy); if (info.size !== copy.size) throw failure("copy_changed", "复制内容已变化"); } | |
| 866 | 新增: catch (error) { await file.close(); throw error; } | |
| 867 | 新增: } | |
| 868 | 新增: const name = copy ? "clipboard." + (copy.mime === "image/png" ? "png" : "txt") : downloads.snapshot().find(d => d.id === input.id).name; | |
| 869 | 新增: transfers.set(transferID, { direction: "download", id: input.id, copy, file, length: info.size, received: 0, sequence: 0, used: Date.now() }); | |
| 870 | 新增: return { transfer: transferID, size: info.size, name, ...(copy ? { mime: copy.mime } : {}) }; | |
| 713 | 871 | } |
| 714 | 872 | throw failure("invalid_input", "文件传递方向无效"); |
| 715 | 873 | } |
| @@ -730,6 +888,7 @@ export function createNativeBrowserService(options = {}) { | ||
| 730 | 888 | } |
| 731 | 889 | if (action === "file-read" && transfer.direction === "download") { |
| 732 | 890 | const data = Buffer.alloc(chunkSize), { bytesRead } = await transfer.file.read(data, 0, data.length, transfer.received); |
| 891 | 新增: if (transfer.copy) checkTransfer(input); | |
| 733 | 892 | transfer.received += bytesRead; transfer.sequence++; |
| 734 | 893 | const eof = transfer.received === transfer.length; |
| 735 | 894 | if (!bytesRead && !eof) throw failure("download_unavailable", "下载文件没有完整返回"); |
| @@ -1037,8 +1196,10 @@ export function createNativeBrowserService(options = {}) { | ||
| 1037 | 1196 | if (action === "forward") { await page.goForward({ waitUntil: "commit", timeout: 8000 }); return { ok: true }; } |
| 1038 | 1197 | if (action === "copy-context") { |
| 1039 | 1198 | if (!tokenPattern.test(input.context || "")) throw failure("invalid_input", "Copy target changed"); |
| 1199 | 新增: if (tab.copyContext !== input.context) { invalidateCopies(); tab.explicitCopyContext = undefined; } | |
| 1040 | 1200 | tab.copyContext = input.context; await clipboard.setContext(tab.id, input.context); return { ok: true }; |
| 1041 | 1201 | } |
| 1202 | 新增: if (mac && (action === "copy" || action === "cut")) return copyAction(tab, input, action, signal); | |
| 1042 | 1203 | if (action === "insert-text") { |
| 1043 | 1204 | if (typeof input.text !== "string" || !input.text || Buffer.byteLength(input.text) > 8192) throw failure("invalid_input", "Input target or text is invalid"); |
| 1044 | 1205 | await page.bringToFront(); signal?.throwIfAborted(); await page.keyboard.insertText(input.text); return { ok: true }; |
| @@ -1075,13 +1236,20 @@ export function createNativeBrowserService(options = {}) { | ||
| 1075 | 1236 | if (closing) return closing; |
| 1076 | 1237 | remember(); |
| 1077 | 1238 | closing = (async () => { |
| 1239 | 新增: invalidateCopies(); | |
| 1078 | 1240 | for (const id of transfers.keys()) await closeTransfer(id); |
| 1241 | 新增: await copying; | |
| 1079 | 1242 | for (const privateContext of privateContexts) await privateContext.close().catch(() => {}); |
| 1080 | 1243 | for (const login of logins.values()) clearTimeout(login.expiry); |
| 1081 | 1244 | await persistQueue.catch(() => {}); await context?.close().catch(() => {}); |
| 1082 | 1245 | })(); return closing; |
| 1083 | 1246 | } |
| 1084 | 删除: const expiry = setInterval(() => { for (const [id, t] of transfers) if (Date.now() - t.used > 120000) void closeTransfer(id); }, 10000); | |
| 1247 | 新增: const expiry = setInterval(() => { | |
| 1248 | 新增: for (const [id, t] of transfers) if (Date.now() - t.used > 120000) void closeTransfer(id); | |
| 1249 | 新增: for (const [id, copy] of clipboardCopies) if (Date.now() - copy.created > 120000) { | |
| 1250 | 新增: clipboardCopies.delete(id); void rm(copy.file, { force: true }).catch(() => {}); | |
| 1251 | 新增: } | |
| 1252 | 新增: }, 10000); | |
| 1085 | 1253 | expiry.unref(); |
| 1086 | 1254 | return { request, releaseInput, close: async () => { tailnet.close(); clearInterval(expiry); await close(); } }; |
| 1087 | 1255 | } |
| @@ -40,18 +40,19 @@ cat > "$stage/安装说明 - Read Me.txt" <<'EOF' | ||
| 40 | 40 | Cage — 本机隔离编码工作区 |
| 41 | 41 | |
| 42 | 42 | 1. 将 Cage.app 拖入 Applications(应用程序)。 |
| 43 | 删除:2. 从应用程序打开 Cage;首次启动在“网络与代理”添加自己的 Clash/Mihomo YAML 订阅或配置。 | |
| 44 | 删除:3. 选择节点,启动 Cage 环境。首次需要下载 Linux 镜像和工具,请保持网络连接。 | |
| 43 | 新增:2. 从应用程序打开 Cage,设置本地账户,并按首次引导选择客机系统、存储位置和代理。 | |
| 44 | 新增:3. 添加自己的 Clash/Mihomo YAML 订阅或配置并选择节点,创建和启动环境。首次需下载系统镜像和工具,请保持网络连接。 | |
| 45 | 45 | 4. 打开项目或新建终端,输入 claude,并在 Cage 浏览器内登录自己的 Claude 账户。 |
| 46 | 46 | |
| 47 | 47 | 需要 Apple Silicon Mac、macOS 14 或更新版本。无需安装 Go、Node.js 或 Clash。 |
| 48 | 删除:代理服务与 Claude 账户需自行准备。此版本为 Alpha。 | |
| 48 | 新增:代理服务与 Claude 账户需自行准备。具体版本与发布状态以发行说明为准。 | |
| 49 | 49 | 共享项目中的文件修改会直接写回 Mac;请备份重要项目。 |
| 50 | 50 | 升级前请退出 Cage 并停止环境,再替换应用程序;配置与项目文件会保留。 |
| 51 | 51 | |
| 52 | 52 | Drag Cage.app into Applications, then open it from Applications. |
| 53 | 删除:Add your own Clash/Mihomo YAML subscription or configuration, select a node, | |
| 54 | 删除:and start the environment. Initial setup downloads Linux and developer tools. | |
| 53 | 新增:Complete the local account and environment setup, add your own Clash/Mihomo | |
| 54 | 新增:YAML subscription or configuration, select a node, and start the environment. | |
| 55 | 新增:Initial setup downloads the selected guest system and developer tools. | |
| 55 | 56 | Requires Apple Silicon and macOS 14+. Your own proxy and Claude account are required. |
| 56 | 57 | |
| 57 | 58 | 入门 / Getting started: |
| @@ -10,6 +10,7 @@ const notice = "此历史会话仍使用原来的客机目录,文件保留在 | ||
| 10 | 10 | let allowed = false; |
| 11 | 11 | let screenAllowed = false, frameReads = 0, frameReadsAtClick = 0; |
| 12 | 12 | const actions = []; |
| 13 | 新增:const maintenance = []; | |
| 13 | 14 | const fixture = await createWorkbench({ |
| 14 | 15 | beforeNavigate: async (page, state) => { |
| 15 | 16 | const panelImage = await page.evaluate(() => { |
| @@ -43,13 +44,22 @@ const fixture = await createWorkbench({ | ||
| 43 | 44 | ? { image: panelImage, window: 1, pid: 5, nonce: "fixture" } |
| 44 | 45 | : { error: "project_screen_permission" } }); |
| 45 | 46 | }); |
| 47 | 新增: await page.route("**/api/macos/maintenance", route => { | |
| 48 | 新增: const request = route.request().postDataJSON(); | |
| 49 | 新增: maintenance.push(request); | |
| 50 | 新增: if (request.action === "open") return route.fulfill({ json: { session: "permission-fixture", maintenance_version: 1 } }); | |
| 51 | 新增: if (request.action === "frame") return route.fulfill({ json: { | |
| 52 | 新增: image: panelImage, mime: "image/png", geometry: "permission-window", region: [100, 80, 480, 260], maintenance_version: 1, | |
| 53 | 新增: } }); | |
| 54 | 新增: return route.fulfill({ json: { maintenance_version: 1 } }); | |
| 55 | 新增: }); | |
| 46 | 56 | await page.route("**/api/cli/sessions/*/account", route => route.fulfill({ json: { supported: false, candidates: [], session: {} } })); |
| 47 | 57 | await page.routeWebSocket("**/api/terminals/**", socket => socket.send(Buffer.from("隔离测试终端\r\n/Users/cage/.local/share/cage/workspace $ "))); |
| 48 | 58 | }, |
| 49 | 59 | }); |
| 50 | 60 | const { page, state, browser, errors } = fixture; |
| 51 | 61 | try { |
| 52 | 删除: await page.getByRole("button", { name: "连接项目", exact: true }).click(); | |
| 62 | 新增: await page.getByRole("button", { name: "重新连接项目", exact: true }).click(); | |
| 53 | 63 | const project = page.getByRole("dialog", { name: "打开项目", exact: true }); |
| 54 | 64 | await project.waitFor(); |
| 55 | 65 | assert.equal(await project.getByRole("textbox", { name: "新项目文件夹", exact: true }).inputValue(), state.settings.workspace); |
| @@ -59,6 +69,12 @@ try { | ||
| 59 | 69 | await permission.getByText(state.settings.workspace, { exact: true }).waitFor(); |
| 60 | 70 | await permission.getByRole("status").filter({ hasText: "屏幕与系统音频录制" }).waitFor(); |
| 61 | 71 | await page.screenshot({ path: join(output, "default-workspace-approval.png"), animations: "disabled" }); |
| 72 | 新增: await permission.getByRole("button", { name: "打开客机授权设置", exact: true }).click(); | |
| 73 | 新增: const recovery = page.getByRole("dialog", { name: "恢复客机系统权限", exact: true }); | |
| 74 | 新增: await recovery.getByRole("img").waitFor(); | |
| 75 | 新增: assert.equal(maintenance.find(request => request.action === "open").maintenance, "screen"); | |
| 76 | 新增: await recovery.getByRole("button", { name: "返回工作台", exact: true }).click(); | |
| 77 | 新增: await recovery.waitFor({ state: "detached" }); | |
| 62 | 78 | screenAllowed = true; |
| 63 | 79 | await permission.getByRole("img").click(); |
| 64 | 80 | const inputError = permission.getByRole("alert").filter({ hasText: "辅助功能" }); |
| @@ -66,6 +82,11 @@ try { | ||
| 66 | 82 | await permission.getByRole("img").waitFor(); |
| 67 | 83 | assert.ok(frameReads > frameReadsAtClick, "next guest frame was fetched"); |
| 68 | 84 | assert.ok(await inputError.isVisible(), "polling must retain the failed click"); |
| 85 | 新增: await permission.getByRole("button", { name: "打开客机授权设置", exact: true }).click(); | |
| 86 | 新增: await recovery.getByRole("img").waitFor(); | |
| 87 | 新增: assert.equal(maintenance.filter(request => request.action === "open").at(-1).maintenance, "input"); | |
| 88 | 新增: await recovery.getByRole("button", { name: "返回工作台", exact: true }).click(); | |
| 89 | 新增: await recovery.waitFor({ state: "detached" }); | |
| 69 | 90 | allowed = true; |
| 70 | 91 | await permission.getByRole("button", { name: "验证授权", exact: true }).click(); |
| 71 | 92 | await permission.waitFor({ state: "hidden" }); |
| @@ -79,7 +100,7 @@ try { | ||
| 79 | 100 | await page.getByRole("status").filter({ hasText: notice }).waitFor(); |
| 80 | 101 | await page.screenshot({ path: join(output, "default-workspace-legacy-notice.png"), animations: "disabled" }); |
| 81 | 102 | assert.deepEqual(errors, []); |
| 82 | 删除: const result = { passed: true, browser: browser.browserType().name(), actions, checks: ["default workspace reconnect opens existing project authorization", "missing screen permission shows the macOS settings path", "click permission error survives the next frame", "permission retry keeps the same host directory", "legacy guest-private workspace notice is visible in the terminal"] }; | |
| 103 | 新增: const result = { passed: true, browser: browser.browserType().name(), actions, checks: ["default workspace reconnect opens existing project authorization", "missing screen permission opens its restricted recovery view", "click permission error survives the next frame and opens input recovery", "permission retry keeps the same host directory", "legacy guest-private workspace notice is visible in the terminal"] }; | |
| 83 | 104 | await writeFile(join(output, "result.json"), JSON.stringify(result, null, 2)); |
| 84 | 105 | console.log(JSON.stringify(result)); |
| 85 | 106 | } finally { await browser.close(); } |
| @@ -95,6 +95,7 @@ for (const viewport of [{ width: 1280, height: 900 }, { width: 1920, height: 108 | ||
| 95 | 95 | assert.equal(inputs[1].x,Math.floor((x-pan.x)*1024/pan.width)); |
| 96 | 96 | assert.equal(inputs[1].y,Math.floor((y-pan.y)*640/pan.height)); |
| 97 | 97 | await input.press("Enter"); await waitInput(3); assert.equal(inputs[2].code,36); |
| 98 | 新增: assert.equal(await screen.isVisible(), true, "Return must wait for the guest to confirm login"); | |
| 98 | 99 | await input.evaluate((el) => { |
| 99 | 100 | const data=new DataTransfer(); data.setData("text/plain","Z7"); |
| 100 | 101 | el.dispatchEvent(new ClipboardEvent("paste",{bubbles:true,cancelable:true,clipboardData:data})); |
| @@ -121,3 +122,76 @@ for (const viewport of [{ width: 1280, height: 900 }, { width: 1920, height: 108 | ||
| 121 | 122 | console.log(`${viewport.width}×${viewport.height}: default login crop, compact panel, coordinate mapping, fit, pan, paste, native close and completion passed.`); |
| 122 | 123 | } catch (error) { console.error("page:",(await page.locator("body").innerText()).slice(0,700), "errors:", errors); throw error; } finally { await browser.close(); } |
| 123 | 124 | } |
| 125 | 新增: | |
| 126 | 新增:// Exercise the first-setup password button through the normal page entry. | |
| 127 | 新增:// Frame polling must preserve an operation error until a user action succeeds. | |
| 128 | 新增:{ | |
| 129 | 新增: let operationError = "请先点选系统授权窗口的密码框,再点击填写授权密码"; | |
| 130 | 新增: let frameError = "", frames = 0, latestFrame = ""; | |
| 131 | 新增: const fixture = await createWorkbench({ | |
| 132 | 新增: async beforeNavigate(page, state) { | |
| 133 | 新增: Object.assign(state.account, {initial_mac_setup:true, guest_system:"macos", macos_guest_user:"cage"}); | |
| 134 | 新增: Object.assign(state.status, {ready:true, vm_running:true}); | |
| 135 | 新增: const images = await page.evaluate(() => { | |
| 136 | 新增: const canvas = document.createElement("canvas"); | |
| 137 | 新增: canvas.width = 160; canvas.height = 100; | |
| 138 | 新增: const paint = canvas.getContext("2d"); | |
| 139 | 新增: return ["#526482", "#627492"].map(color => { | |
| 140 | 新增: paint.fillStyle = color; paint.fillRect(0, 0, canvas.width, canvas.height); | |
| 141 | 新增: return canvas.toDataURL("image/png").split(",")[1]; | |
| 142 | 新增: }); | |
| 143 | 新增: }); | |
| 144 | 新增: await page.route("**/api/macos/first-setup", async route => { | |
| 145 | 新增: const request = route.request().postDataJSON(); | |
| 146 | 新增: if (request.action === "permissions") return route.fulfill({json:{screen:false, input:false, projects:false, managed_credential:true}}); | |
| 147 | 新增: if (request.action === "open") return route.fulfill({json:{session:"error-persistence-fixture"}}); | |
| 148 | 新增: if (request.action === "frame") { | |
| 149 | 新增: frames++; | |
| 150 | 新增: if (frameError) return route.fulfill({json:{error:frameError}}); | |
| 151 | 新增: latestFrame = images[frames % images.length]; | |
| 152 | 新增: return route.fulfill({json:{image:latestFrame}}); | |
| 153 | 新增: } | |
| 154 | 新增: if (request.action === "fill-password") { | |
| 155 | 新增: assert.equal(request.password, undefined, "browser supplied a credential"); | |
| 156 | 新增: return route.fulfill({json:operationError ? {error:operationError} : {}}); | |
| 157 | 新增: } | |
| 158 | 新增: return route.fulfill({json:{}}); | |
| 159 | 新增: }); | |
| 160 | 新增: }, | |
| 161 | 新增: }); | |
| 162 | 新增: const {page, browser, errors} = fixture; | |
| 163 | 新增: try { | |
| 164 | 新增: const screen = page.getByRole("dialog", {name:"首次设置虚拟 Mac"}); | |
| 165 | 新增: const fill = screen.getByRole("button", {name:"填写授权密码", exact:true}); | |
| 166 | 新增: await screen.getByRole("img").waitFor(); | |
| 167 | 新增: await fill.click(); | |
| 168 | 新增: await screen.getByRole("alert").filter({hasText:operationError}).waitFor(); | |
| 169 | 新增: const observed = frames; | |
| 170 | 新增: for (let attempts = 0; frames < observed + 2 && attempts < 150; attempts++) | |
| 171 | 新增: await new Promise(resolve => setTimeout(resolve, 20)); | |
| 172 | 新增: assert.ok(frames >= observed + 2, "frame polling stopped after an input error"); | |
| 173 | 新增: await page.waitForFunction(image => document.querySelector(".mac-login-canvas img")?.src.endsWith(image), latestFrame); | |
| 174 | 新增: assert.equal(await screen.getByRole("alert").isVisible(), true, "a successful frame erased the password error"); | |
| 175 | 新增: assert.equal(await screen.getByRole("alert").innerText(), operationError); | |
| 176 | 新增: | |
| 177 | 新增: frameError = "授权画面暂时无法读取"; | |
| 178 | 新增: await page.waitForResponse(async response => response.url().endsWith("/api/macos/first-setup") && | |
| 179 | 新增: response.request().postDataJSON()?.action === "frame" && (await response.json()).error === frameError); | |
| 180 | 新增: operationError = ""; | |
| 181 | 新增: await fill.click(); | |
| 182 | 新增: await screen.getByRole("alert").filter({hasText:frameError}).waitFor(); | |
| 183 | 新增: frameError = ""; | |
| 184 | 新增: await screen.getByRole("alert").waitFor({state:"hidden"}); | |
| 185 | 新增: | |
| 186 | 新增: operationError = "系统授权窗口或密码框已变化,填写已停止,请重新选择"; | |
| 187 | 新增: await fill.click(); | |
| 188 | 新增: await screen.getByRole("alert").filter({hasText:operationError}).waitFor(); | |
| 189 | 新增: await screen.getByRole("button", {name:"返回设置指引"}).click(); | |
| 190 | 新增: await screen.waitFor({state:"detached"}); | |
| 191 | 新增: await page.getByRole("button", {name:"打开客机系统设置", exact:true}).click(); | |
| 192 | 新增: await screen.getByRole("img").waitFor(); | |
| 193 | 新增: assert.equal(await screen.getByRole("alert").count(), 0, "reopening retained an old operation error"); | |
| 194 | 新增: assert.deepEqual(errors, []); | |
| 195 | 新增: console.log("First-setup password error persistence, independent frame recovery and close/reopen cleanup passed."); | |
| 196 | 新增: } finally { await browser.close(); } | |
| 197 | 新增:} | |
| @@ -0,0 +1,133 @@ | ||
| 1 | 新增:import assert from "node:assert/strict"; | |
| 2 | 新增:import { fileURLToPath } from "node:url"; | |
| 3 | 新增:import { createWorkbench } from "./workbench-fixture.mjs"; | |
| 4 | 新增: | |
| 5 | 新增:const project = "/Users/fixture/Cage Projects/macOS 示例"; | |
| 6 | 新增:const calls = []; | |
| 7 | 新增:let loggedIn = false, maintenanceClosed = false, geometry = "maintenance-frame-a", images; | |
| 8 | 新增:const { page, browser, state, errors } = await createWorkbench({ | |
| 9 | 新增: viewport: { width: 1280, height: 900 }, | |
| 10 | 新增: async beforeNavigate(page, state) { | |
| 11 | 新增: state.status.vm_running = state.status.ready = true; | |
| 12 | 新增: state.account.guest_system = state.status.guest_system = "macos"; | |
| 13 | 新增: state.status.projects = [project]; | |
| 14 | 新增: state.status.workspace = state.settings.workspace = project; | |
| 15 | 新增: state.status.project_error = "部分项目文件夹尚未连接,环境和浏览器可继续使用。"; | |
| 16 | 新增: state.status.project_errors = [{ path: project, recovery: "guest-login", message: "请先登录虚拟 Mac 的客机账户。登录完成后,Cage 会自动连接项目。" }]; | |
| 17 | 新增: images = await page.evaluate(() => { | |
| 18 | 新增: const make = (width, height, color) => { | |
| 19 | 新增: const canvas = document.createElement("canvas"); | |
| 20 | 新增: canvas.width = width; canvas.height = height; | |
| 21 | 新增: const context = canvas.getContext("2d"); | |
| 22 | 新增: context.fillStyle = color; context.fillRect(0, 0, width, height); | |
| 23 | 新增: context.fillStyle = "#fff"; context.font = "22px sans-serif"; | |
| 24 | 新增: context.fillText("Synthetic Apple authorization window", 20, 45); | |
| 25 | 新增: return canvas.toDataURL("image/jpeg").split(",")[1]; | |
| 26 | 新增: }; | |
| 27 | 新增: return { login: make(1920, 1200, "#485570"), a: make(600, 400, "#334252"), b: make(480, 360, "#465835") }; | |
| 28 | 新增: }); | |
| 29 | 新增: await page.route("**/api/macos/login", route => { | |
| 30 | 新增: const request = route.request().postDataJSON(); | |
| 31 | 新增: calls.push({ mode: "login", ...request }); | |
| 32 | 新增: if (request.action === "open") return route.fulfill({ json: { session: "login-fixture" } }); | |
| 33 | 新增: if (request.action === "close") return route.fulfill({ json: { closed: true } }); | |
| 34 | 新增: if (request.action === "frame") { | |
| 35 | 新增: if (loggedIn) { | |
| 36 | 新增: state.status.project_errors = []; state.status.project_error = ""; | |
| 37 | 新增: return route.fulfill({ json: { closed: true } }); | |
| 38 | 新增: } | |
| 39 | 新增: return route.fulfill({ json: { image: images.login, mime: "image/jpeg" } }); | |
| 40 | 新增: } | |
| 41 | 新增: return route.fulfill({ json: {} }); | |
| 42 | 新增: }); | |
| 43 | 新增: await page.route("**/api/projects/open", route => { | |
| 44 | 新增: if (!loggedIn) return route.fulfill({ status: 400, contentType: "text/plain; charset=utf-8", headers: { "X-Cage-Recovery": "guest-login" }, body: "请先登录虚拟 Mac 的客机账户。" }); | |
| 45 | 新增: return route.fulfill({ json: { workspace: project } }); | |
| 46 | 新增: }); | |
| 47 | 新增: await page.route("**/api/macos/maintenance", route => { | |
| 48 | 新增: const request = route.request().postDataJSON(); | |
| 49 | 新增: calls.push({ mode: "maintenance", ...request }); | |
| 50 | 新增: assert(["projects", "screen", "input"].includes(request.maintenance)); | |
| 51 | 新增: assert.equal(request.initial_setup, undefined); | |
| 52 | 新增: assert.equal(request.password, undefined); | |
| 53 | 新增: if (request.action === "open") return route.fulfill({ json: { session: "maintenance-fixture", maintenance_version: 1, administrator: "cageprovision" } }); | |
| 54 | 新增: if (request.action === "close") return route.fulfill({ json: { closed: true, maintenance_version: 1 } }); | |
| 55 | 新增: if (request.action === "frame") return route.fulfill({ json: maintenanceClosed | |
| 56 | 新增: ? { closed: true, maintenance_version: 1, error: "客机前台应用已变化" } | |
| 57 | 新增: : { image: geometry.endsWith("a") ? images.a : images.b, mime: "image/jpeg", geometry, | |
| 58 | 新增: region: geometry.endsWith("a") ? [120, 90, 600, 400] : [240, 150, 480, 360], maintenance_version: 1 } }); | |
| 59 | 新增: return route.fulfill({ json: { maintenance_version: 1 } }); | |
| 60 | 新增: }); | |
| 61 | 新增: }, | |
| 62 | 新增:}); | |
| 63 | 新增:page.setDefaultTimeout(12000); | |
| 64 | 新增:async function until(predicate) { | |
| 65 | 新增: for (let attempt = 0; attempt < 150; attempt++) { | |
| 66 | 新增: if (predicate()) return; | |
| 67 | 新增: await page.waitForTimeout(20); | |
| 68 | 新增: } | |
| 69 | 新增: assert(predicate(), "expected recovery operation did not arrive"); | |
| 70 | 新增:} | |
| 71 | 新增:try { | |
| 72 | 新增: const failures = page.locator(".project-connection-errors"); | |
| 73 | 新增: await failures.getByRole("button", { name: "登录客机账户", exact: true }).click(); | |
| 74 | 新增: const login = page.getByRole("dialog", { name: "登录虚拟 Mac", exact: true }); | |
| 75 | 新增: await login.getByAltText("Apple 客机登录屏幕").waitFor(); | |
| 76 | 新增: await login.getByLabel(/^客机登录键盘/).press("Enter"); | |
| 77 | 新增: await until(() => calls.some(call => call.mode === "login" && call.action === "key" && call.code === 36)); | |
| 78 | 新增: assert(await login.isVisible(), "Return closed the view before macOS reported a completed login"); | |
| 79 | 新增: loggedIn = true; | |
| 80 | 新增: await login.waitFor({ state: "detached" }); | |
| 81 | 新增: await failures.waitFor({ state: "detached" }); | |
| 82 | 新增: | |
| 83 | 新增: state.status.project_error = "部分项目文件夹尚未连接,环境和浏览器可继续使用。"; | |
| 84 | 新增: state.status.project_errors = [{ path: project, recovery: "filesystem-permission", message: "虚拟 Mac 的文件系统扩展尚未启用。" }]; | |
| 85 | 新增: await page.reload(); | |
| 86 | 新增: await failures.getByRole("button", { name: "打开客机授权设置", exact: true }).click(); | |
| 87 | 新增: const maintenance = page.getByRole("dialog", { name: "恢复客机系统权限", exact: true }); | |
| 88 | 新增: const image = maintenance.getByAltText("客机系统设置或授权窗口"); | |
| 89 | 新增: await page.waitForFunction(() => document.querySelector('[data-mode="maintenance"] img')?.naturalWidth === 600); | |
| 90 | 新增: const first = await image.boundingBox(); | |
| 91 | 新增: await image.click({ position: { x: first.width / 2, y: first.height / 2 } }); | |
| 92 | 新增: await until(() => calls.some(call => call.mode === "maintenance" && call.action === "click")); | |
| 93 | 新增: const click = calls.find(call => call.mode === "maintenance" && call.action === "click"); | |
| 94 | 新增: assert.equal(click.geometry, "maintenance-frame-a"); | |
| 95 | 新增: assert(Math.abs(click.x - 420) <= 1 && Math.abs(click.y - 290) <= 1); | |
| 96 | 新增: await maintenance.getByLabel(/^客机登录键盘/).press("Meta+a"); | |
| 97 | 新增: await maintenance.getByRole("button", { name: "填写管理员密码", exact: true }).click(); | |
| 98 | 新增: await until(() => calls.some(call => call.action === "select-all") && calls.some(call => call.action === "fill-password")); | |
| 99 | 新增: assert(calls.filter(call => call.mode === "maintenance" && ["select-all", "fill-password"].includes(call.action)) | |
| 100 | 新增: .every(call => call.geometry === "maintenance-frame-a" && call.session === "maintenance-fixture")); | |
| 101 | 新增: assert(!calls.some(call => call.mode === "maintenance" && call.action === "key" && call.code === 36), "password fill submitted authorization without the user"); | |
| 102 | 新增: await page.screenshot({ path: fileURLToPath(new URL("../../docs/test-reports/2026-11-09-architecture-fixes/evidence/mac-maintenance-ui.png", import.meta.url)) }); | |
| 103 | 新增: | |
| 104 | 新增: geometry = "maintenance-frame-b"; | |
| 105 | 新增: await page.waitForFunction(() => document.querySelector('[data-mode="maintenance"] img')?.naturalWidth === 480); | |
| 106 | 新增: const next = await image.boundingBox(); | |
| 107 | 新增: await image.click({ position: { x: next.width / 2, y: next.height / 2 } }); | |
| 108 | 新增: await until(() => calls.some(call => call.action === "click" && call.geometry === geometry)); | |
| 109 | 新增: const moved = calls.find(call => call.action === "click" && call.geometry === geometry); | |
| 110 | 新增: assert(Math.abs(moved.x - 480) <= 1 && Math.abs(moved.y - 330) <= 1); | |
| 111 | 新增: maintenanceClosed = true; | |
| 112 | 新增: await maintenance.waitFor({ state: "detached" }); | |
| 113 | 新增: assert.equal(await page.locator('[data-mode="maintenance"] img').count(), 0); | |
| 114 | 新增: | |
| 115 | 新增: maintenanceClosed = false; | |
| 116 | 新增: state.status.project_error = ""; | |
| 117 | 新增: state.status.project_errors = []; | |
| 118 | 新增: await page.reload(); | |
| 119 | 新增: await page.getByRole("button", { name: "设置", exact: true }).click(); | |
| 120 | 新增: await page.getByRole("navigation", { name: "设置分组" }).getByRole("button", { name: "环境与恢复", exact: true }).click(); | |
| 121 | 新增: const permissions = page.getByRole("region", { name: "客机系统权限", exact: true }); | |
| 122 | 新增: for (const [label, purpose] of [["文件共享权限", "projects"], ["屏幕录制权限", "screen"], ["辅助功能权限", "input"]]) { | |
| 123 | 新增: const start = calls.length; | |
| 124 | 新增: await permissions.getByRole("button", { name: label, exact: true }).click(); | |
| 125 | 新增: await image.waitFor(); | |
| 126 | 新增: assert(calls.slice(start).some(call => call.action === "open" && call.maintenance === purpose)); | |
| 127 | 新增: await maintenance.getByRole("button", { name: "返回工作台", exact: true }).click(); | |
| 128 | 新增: await maintenance.waitFor({ state: "detached" }); | |
| 129 | 新增: await until(() => calls.slice(start).some(call => call.action === "close" && call.maintenance === purpose)); | |
| 130 | 新增: } | |
| 131 | 新增: assert.deepEqual(errors, []); | |
| 132 | 新增: console.log(JSON.stringify({ result: "PASS", browser: browser.version(), checks: ["actionable project login", "Return waits for macOS", "restored project removes warning", "separate maintenance purpose", "cropped window input coordinates", "published geometry binding", "explicit administrator fill intent without password data or submission", "geometry change rebinds crop", "foreground change removes maintenance image", "three permission recovery entries remain available without a project error"] })); | |
| 133 | 新增:} finally { await browser.close(); } | |
| @@ -0,0 +1,97 @@ | ||
| 1 | 新增:import assert from "node:assert/strict"; | |
| 2 | 新增:import { createWorkbench } from "./workbench-fixture.mjs"; | |
| 3 | 新增: | |
| 4 | 新增:let exports = 0; | |
| 5 | 新增:const { browser, page, state, errors } = await createWorkbench({ | |
| 6 | 新增: viewport: { width: Number(process.env.CAGE_STORAGE_WIDTH || 1280), height: 850 }, | |
| 7 | 新增: clientContext: { mode: "local", connection_id: "local", client_platform: "windows", server_platform: "windows", connection: { state: "disconnected" } }, | |
| 8 | 新增: nativeRequest: async ({ action }) => { | |
| 9 | 新增: if (action === "exportDiagnostics") { exports++; return { saved: true }; } | |
| 10 | 新增: return null; | |
| 11 | 新增: }, | |
| 12 | 新增:}); | |
| 13 | 新增:try { | |
| 14 | 新增: const attempts = []; | |
| 15 | 新增: let location = null; | |
| 16 | 新增: state.account.guest_system = "windows-11"; | |
| 17 | 新增: state.account.unlocked = false; | |
| 18 | 新增: state.account.require_authentication = true; | |
| 19 | 新增: Object.assign(state.status, { | |
| 20 | 新增: local_vm_storage: true, guest_system: "windows-11", ready: false, vm_running: false, | |
| 21 | 新增: storage_recovery: { required: true, error: "系统管理服务尚未完成旧磁盘恢复", repair_allowed: true }, | |
| 22 | 新增: }); | |
| 23 | 新增: await page.route("**/api/environment/storage", route => { | |
| 24 | 新增: assert.equal(route.request().method(), "GET", "pending recovery admitted a migration"); | |
| 25 | 新增: return route.fulfill({ json: location || { recovery: state.status.storage_recovery } }); | |
| 26 | 新增: }); | |
| 27 | 新增: await page.route("**/api/environment/storage/recover", route => { | |
| 28 | 新增: attempts.push(route.request().postDataJSON()); | |
| 29 | 新增: state.status.job = { | |
| 30 | 新增: id: `storage-recovery-${attempts.length}`, kind: "storage-recovery", running: true, | |
| 31 | 新增: message: attempts.at(-1).repair ? "正在修复 Windows 系统助手,请完成系统授权…" : "正在恢复环境存储并检查数据位置…", | |
| 32 | 新增: }; | |
| 33 | 新增: return route.fulfill({ json: state.status.job }); | |
| 34 | 新增: }); | |
| 35 | 新增: await page.route("**/api/diagnostics", route => route.fulfill({ json: { bytes: 2048, files: 2 } })); | |
| 36 | 新增: await page.reload(); | |
| 37 | 新增: await page.getByRole("region", { name: "解锁 Cage", exact: true }).waitFor(); | |
| 38 | 新增: await page.getByLabel("账户密码", { exact: true }).fill("fixture-password"); | |
| 39 | 新增: await page.getByRole("button", { name: "解锁 Cage", exact: true }).click(); | |
| 40 | 新增: await page.getByRole("heading", { name: "环境存储需要恢复", exact: true }).waitFor(); | |
| 41 | 新增: assert.equal(await page.getByRole("button", { name: "启动 Cage 环境", exact: true }).count(), 0); | |
| 42 | 新增: await page.getByRole("button", { name: "恢复环境存储", exact: true }).click(); | |
| 43 | 新增: const panel = page.getByRole("region", { name: "本机环境存储", exact: true }); | |
| 44 | 新增: const retry = panel.getByRole("button", { name: "重试恢复", exact: true }); | |
| 45 | 新增: const repair = panel.getByRole("button", { name: "修复系统助手并恢复", exact: true }); | |
| 46 | 新增: await retry.waitFor(); | |
| 47 | 新增: await panel.getByText(state.status.storage_recovery.error, { exact: true }).waitFor(); | |
| 48 | 新增: assert.equal(await panel.getByLabel("新存储位置").count(), 0); | |
| 49 | 新增: assert.equal(await page.getByRole("region", { name: "环境版本", exact: true }).count(), 0); | |
| 50 | 新增: | |
| 51 | 新增: await retry.click(); | |
| 52 | 新增: await panel.getByRole("status").waitFor(); | |
| 53 | 新增: assert.deepEqual(attempts, [{ repair: false }]); | |
| 54 | 新增: assert.equal(await retry.isDisabled(), true); | |
| 55 | 新增: assert.equal(await repair.isDisabled(), true); | |
| 56 | 新增: await retry.evaluate(button => { button.click(); button.click(); }); | |
| 57 | 新增: assert.equal(attempts.length, 1, "disabled recovery button submitted the same operation twice"); | |
| 58 | 新增: await page.getByRole("button", { name: "导出诊断包", exact: true }).click(); | |
| 59 | 新增: await page.getByText("诊断包已保存。分享前请检查其中内容。", { exact: true }).waitFor(); | |
| 60 | 新增: assert.equal(exports, 1, "recovery blocked diagnostic export"); | |
| 61 | 新增: | |
| 62 | 新增: state.status.storage_recovery.error = "系统管理服务协议需要更新,旧磁盘仍待恢复"; | |
| 63 | 新增: state.status.job = { ...state.status.job, running: false, error: state.status.storage_recovery.error }; | |
| 64 | 新增: await panel.getByText(state.status.storage_recovery.error, { exact: true }).waitFor(); | |
| 65 | 新增: await page.waitForFunction(() => [...document.querySelectorAll(".environment-storage button")].every(button => !button.disabled)); | |
| 66 | 新增: await repair.click(); | |
| 67 | 新增: await panel.getByRole("status").waitFor(); | |
| 68 | 新增: assert.deepEqual(attempts, [{ repair: false }, { repair: true }]); | |
| 69 | 新增: assert.equal(await retry.isDisabled(), true); | |
| 70 | 新增: assert.equal(await repair.isDisabled(), true); | |
| 71 | 新增: const geometry = await panel.evaluate(element => { | |
| 72 | 新增: const actions = element.querySelector(".storage-actions").getBoundingClientRect(); | |
| 73 | 新增: const help = element.querySelector(".storage-repair-help").getBoundingClientRect(); | |
| 74 | 新增: const progress = element.querySelector('[role="status"]').getBoundingClientRect(); | |
| 75 | 新增: return { actionsBottom: actions.bottom, helpTop: help.top, progressTop: progress.top }; | |
| 76 | 新增: }); | |
| 77 | 新增: assert.ok(geometry.helpTop >= geometry.actionsBottom + 8, "repair instruction overlaps its controls"); | |
| 78 | 新增: assert.ok(geometry.progressTop >= geometry.actionsBottom + 8, "recovery progress overlaps its controls"); | |
| 79 | 新增: if (process.env.CAGE_STORAGE_SCREENSHOT) { | |
| 80 | 新增: await panel.scrollIntoViewIfNeeded(); | |
| 81 | 新增: await page.screenshot({ path: process.env.CAGE_STORAGE_SCREENSHOT }); | |
| 82 | 新增: } | |
| 83 | 新增: assert.equal(state.requests.filter(request => request.path === "/start").length, 0); | |
| 84 | 新增: | |
| 85 | 新增: location = { directory: "D:\\Cage 环境", has_environment: true, custom: true, backup: "C:\\Users\\demo\\.claude-cage\\state" }; | |
| 86 | 新增: state.status.storage_recovery = { required: false, repair_allowed: false }; | |
| 87 | 新增: state.status.job = { ...state.status.job, running: false, error: "", message: "环境存储已恢复,可以启动环境" }; | |
| 88 | 新增: await panel.getByText(location.directory, { exact: true }).waitFor(); | |
| 89 | 新增: await page.waitForFunction(() => !document.querySelector(".environment-storage input")?.disabled); | |
| 90 | 新增: assert.equal(await retry.count(), 0); | |
| 91 | 新增: await page.getByRole("button", { name: "返回工作台", exact: true }).first().click(); | |
| 92 | 新增: await page.getByRole("button", { name: "启动 Cage 环境", exact: true }).click(); | |
| 93 | 新增: await page.waitForFunction(() => document.querySelector(".welcome h1")?.textContent === "Cage 环境已就绪"); | |
| 94 | 新增: assert.equal(state.requests.filter(request => request.path === "/start").length, 1); | |
| 95 | 新增: assert.deepEqual(errors, []); | |
| 96 | 新增: console.log(`Storage recovery login, settings, failure cause, duplicate rejection, diagnostics, repair, preparation and normal start passed (${page.viewportSize().width}px)`); | |
| 97 | 新增:} finally { await browser.close(); } | |
| @@ -8,6 +8,7 @@ async function responseError(response, path, method = "GET") { | ||
| 8 | 8 | httpErrorMessage(path, response.status, await response.text(), response.headers.get("Content-Type") || "", method), |
| 9 | 9 | ); |
| 10 | 10 | error.status = response.status; |
| 11 | 新增: error.recovery = response.headers.get("X-Cage-Recovery") || ""; | |
| 11 | 12 | return error; |
| 12 | 13 | } |
| 13 | 14 | async function renewSession() { |
| @@ -16,6 +16,7 @@ import { | ||
| 16 | 16 | } from "lucide-react"; |
| 17 | 17 | import { api, native, nativeAvailable } from "./api"; |
| 18 | 18 | import { |
| 19 | 新增: assertConnection, | |
| 19 | 20 | getClientContext, |
| 20 | 21 | isRemoteClient, |
| 21 | 22 | runtimeURL, |
| @@ -88,6 +89,7 @@ export function useDesktopFiles(ready, onStatus) { | ||
| 88 | 89 | let disposed = false, |
| 89 | 90 | timer, |
| 90 | 91 | failures = 0; |
| 92 | 新增: const handled = new Set(); | |
| 91 | 93 | const poll = async () => { |
| 92 | 94 | try { |
| 93 | 95 | const value = await api("/input/files/desktop/requests"); |
| @@ -97,7 +99,26 @@ export function useDesktopFiles(ready, onStatus) { | ||
| 97 | 99 | uploads: value.uploads || [], |
| 98 | 100 | downloads: value.downloads || [], |
| 99 | 101 | }); |
| 100 | 删除: | |
| 102 | 新增: for (const request of value.opens || []) { | |
| 103 | 新增: if (disposed || handled.has(request.id)) continue; | |
| 104 | 新增: handled.add(request.id); | |
| 105 | 新增: try { | |
| 106 | 新增: assertConnection(connection); | |
| 107 | 新增: if (!nativeAvailable()) { | |
| 108 | 新增: await api("/input/files/desktop/open", { | |
| 109 | 新增: id: request.id, | |
| 110 | 新增: stage: "complete", | |
| 111 | 新增: error: "请在 Cage 桌面应用中打开文件", | |
| 112 | 新增: }); | |
| 113 | 新增: throw new Error( | |
| 114 | 新增: "请在 Cage 桌面应用中打开文件,或从下载列表保存文件", | |
| 115 | 新增: ); | |
| 116 | 新增: } | |
| 117 | 新增: await native("desktopFileAction", { id: request.id }); | |
| 118 | 新增: } catch (error) { | |
| 119 | 新增: if (!disposed) status.current?.(error.message); | |
| 120 | 新增: } | |
| 121 | 新增: } | |
| 101 | 122 | } catch (error) { |
| 102 | 123 | // Closing Desktop invalidates its outstanding file choosers. |
| 103 | 124 | if (!disposed) { |
| @@ -10,25 +10,27 @@ export function EnvironmentStorage({ status, onConfirm }) { | ||
| 10 | 10 | const [submitting, setSubmitting] = useState(false); |
| 11 | 11 | const [error, setError] = useState(""); |
| 12 | 12 | const job = status.job; |
| 13 | 新增: const recovery = status.storage_recovery?.required ? status.storage_recovery : location?.recovery; | |
| 14 | 新增: const storageJob = job?.kind === "storage" || job?.kind === "storage-recovery"; | |
| 13 | 15 | const busy = submitting || Boolean(pending) || Boolean(job?.running); |
| 14 | 16 | useEffect(() => { |
| 15 | 17 | let live = true; |
| 16 | 18 | if (pending && job?.id === pending.previousJob) return; |
| 17 | 删除: if (job?.kind === "storage" && job.running) return; | |
| 19 | 新增: if (storageJob && job.running) return; | |
| 18 | 20 | api("/environment/storage").then((next) => { |
| 19 | 21 | if (!live) return; |
| 20 | 22 | setLocation(next); |
| 21 | 23 | if (pending) { |
| 22 | 24 | setPending(null); |
| 23 | 25 | if (job?.id === pending.id && job.error) setError(job.error); |
| 24 | 删除: else if (job?.id === pending.id || next.directory === pending.path) { setDirectory(""); setError(""); } | |
| 26 | 新增: else if (job?.id === pending.id || next.directory && next.directory === pending.path) { setDirectory(""); setError(""); } | |
| 25 | 27 | else setError("操作已结束,请核对当前环境目录后重试。"); |
| 26 | 28 | } |
| 27 | 29 | }).catch((e) => { |
| 28 | 30 | if (live) { setError(e.message); setPending(null); } |
| 29 | 31 | }); |
| 30 | 32 | return () => { live = false; }; |
| 31 | 删除: }, [pending, job?.id, job?.running]); | |
| 33 | 新增: }, [pending, job?.id, job?.running, storageJob, status.storage_recovery?.required]); | |
| 32 | 34 | |
| 33 | 35 | const choose = async () => { |
| 34 | 36 | setError(""); |
| @@ -38,7 +40,7 @@ export function EnvironmentStorage({ status, onConfirm }) { | ||
| 38 | 40 | } catch { setError("未能选择文件夹,请直接填写绝对路径。"); } |
| 39 | 41 | }; |
| 40 | 42 | const apply = async () => { |
| 41 | 删除: if (!location || busy) return; | |
| 43 | 新增: if (!location?.directory || busy || recovery?.required) return; | |
| 42 | 44 | const path = directory.trim(); |
| 43 | 45 | if (location.has_environment && !(await onConfirm({ |
| 44 | 46 | title: "迁移本机环境?", |
| @@ -55,22 +57,44 @@ export function EnvironmentStorage({ status, onConfirm }) { | ||
| 55 | 57 | } catch (e) { setError(e.message); } |
| 56 | 58 | finally { setSubmitting(false); } |
| 57 | 59 | }; |
| 60 | 新增: const recover = async (repair) => { | |
| 61 | 新增: if (busy) return; | |
| 62 | 新增: setSubmitting(true); | |
| 63 | 新增: setError(""); | |
| 64 | 新增: try { | |
| 65 | 新增: const accepted = await api("/environment/storage/recover", { repair }); | |
| 66 | 新增: setPending({ id: accepted.id, previousJob: job?.id }); | |
| 67 | 新增: } catch (e) { setError(e.message); } | |
| 68 | 新增: finally { setSubmitting(false); } | |
| 69 | 新增: }; | |
| 58 | 70 | return <section className="environment-versions environment-storage" aria-label="本机环境存储"> |
| 59 | 71 | <h4>本机环境存储</h4> |
| 72 | 新增: {recovery?.required ? <> | |
| 73 | 新增: <p className="field-help">环境存储需要恢复。请连接迁移使用的磁盘后重试。恢复完成后可以启动环境。</p> | |
| 74 | 新增: <p role="alert" className="error-message"><SafetyMessage message={recovery.error} /></p> | |
| 75 | 新增: <div className="storage-actions"> | |
| 76 | 新增: <button type="button" disabled={busy} onClick={() => recover(false)}>重试恢复</button> | |
| 77 | 新增: {recovery.repair_allowed && <button type="button" disabled={busy} onClick={() => recover(true)}>修复系统助手并恢复</button>} | |
| 78 | 新增: </div> | |
| 79 | 新增: {recovery.repair_allowed && <p className="field-help storage-repair-help">修复系统助手需要 Windows 系统授权。完成后会继续恢复原环境。</p>} | |
| 80 | 新增: </> : <> | |
| 60 | 81 | <p className="field-help">系统镜像、下载缓存和虚拟磁盘可以放在另一块本地磁盘。项目文件保存在各自的项目文件夹。</p> |
| 61 | 82 | <div className="setting-summary-row"><span>当前环境目录</span><strong>{location?.directory || "正在读取…"}</strong></div> |
| 83 | 新增: {status.environment_identity_directory && status.environment_identity_directory !== status.environment_directory && | |
| 84 | 新增: <p className="field-help">升级前的默认项目文件位于 <code>{status.environment_identity_directory}</code>,当前默认项目位于 <code>{status.environment_directory}</code>。如需使用旧目录中的项目,请在主机文件管理器中将项目移到 Cage 配置目录之外,再从工作台打开。</p>} | |
| 62 | 85 | {location?.backup && <p className="field-help">迁移前的备份保存在 <code>{location.backup}</code>。确认新环境能正常启动、文件和登录状态齐全后,可自行清理备份。</p>} |
| 63 | 86 | <label>新存储位置 |
| 64 | 87 | <input value={directory} onChange={(e) => { setDirectory(e.target.value); setError(""); }} spellCheck="false" |
| 65 | 删除: disabled={busy || !location} placeholder="本地磁盘上专用空文件夹的完整路径" /> | |
| 88 | 新增: disabled={busy || !location?.directory} placeholder="本地磁盘上专用空文件夹的完整路径" /> | |
| 66 | 89 | </label> |
| 67 | 90 | <div className="storage-actions"> |
| 68 | 删除: {nativeAvailable() && <button type="button" disabled={busy || !location} onClick={choose}><FolderOpen size={15} />选择文件夹</button>} | |
| 69 | 删除: <button type="button" disabled={busy || !location || !directory.trim() || directory.trim() === location.directory} onClick={apply}> | |
| 91 | 新增: {nativeAvailable() && <button type="button" disabled={busy || !location?.directory} onClick={choose}><FolderOpen size={15} />选择文件夹</button>} | |
| 92 | 新增: <button type="button" disabled={busy || !location?.directory || !directory.trim() || directory.trim() === location.directory} onClick={apply}> | |
| 70 | 93 | {location?.has_environment ? "迁移到此位置" : "使用此位置"} |
| 71 | 94 | </button> |
| 72 | 95 | </div> |
| 73 | 删除: {job?.kind === "storage" && job.running && <p role="status" className="field-help">{job.message}</p>} | |
| 74 | 删除: {error && <p role="alert" className="error-message"><SafetyMessage message={error} /></p>} | |
| 96 | 新增: </>} | |
| 97 | 新增: {storageJob && job.running && <p role="status" className="field-help">{job.message}</p>} | |
| 98 | 新增: {error && error !== recovery?.error && <p role="alert" className="error-message"><SafetyMessage message={error} /></p>} | |
| 75 | 99 | </section>; |
| 76 | 100 | } |
| @@ -90,15 +90,15 @@ export function prepareClipboardPaste(target, id, { windowTarget, valid = () => | ||
| 90 | 90 | let disposed = false, sent = false; |
| 91 | 91 | const destination = { target, id, pid: windowTarget?.pid, window: windowTarget?.window }; |
| 92 | 92 | const check = () => { |
| 93 | 删除: if (disposed || !valid()) throw new Error("图片接收位置已切换,请重新粘贴"); | |
| 93 | 新增: if (disposed || !valid()) throw new Error("粘贴接收位置已切换,请重新粘贴"); | |
| 94 | 94 | }; |
| 95 | 95 | const prepared = api("/input/paste/start", destination).then(result => { |
| 96 | 96 | if (result?.available !== true || typeof result.transfer !== "string" && typeof result.context !== "string") |
| 97 | 删除: throw new Error("客机尚未确认图片接收位置,请同步环境组件后重试"); | |
| 97 | 新增: throw new Error("客机尚未确认粘贴接收位置,请同步环境组件后重试"); | |
| 98 | 98 | return { transfer: result.transfer, context: result.context }; |
| 99 | 99 | }); |
| 100 | 删除: // The clipboard can turn out to contain text or files. The image-specific | |
| 101 | 删除: // preparation error is observed only when this gesture supplies an image. | |
| 100 | 新增: // Source reading starts independently. A sender using this binding observes | |
| 101 | 新增: // preparation errors, and every content path disposes its preparation. | |
| 102 | 102 | void prepared.catch(() => {}); |
| 103 | 103 | const dispose = () => { |
| 104 | 104 | if (disposed) return; |
| @@ -110,7 +110,7 @@ export function prepareClipboardPaste(target, id, { windowTarget, valid = () => | ||
| 110 | 110 | check(); |
| 111 | 111 | const binding = await prepared; |
| 112 | 112 | check(); |
| 113 | 删除: if (sent) throw new Error("本次图片已经提交,请核对接收结果"); | |
| 113 | 新增: if (sent) throw new Error("本次粘贴已经提交,请核对接收结果"); | |
| 114 | 114 | sent = true; |
| 115 | 115 | try { return await api(typeof payload.text === "string" ? "/input/text" : "/input/image", { ...payload, ...destination, ...binding }); } |
| 116 | 116 | finally { dispose(); } |
| @@ -136,3 +136,10 @@ | ||
| 136 | 136 | .mac-first-setup li + li { margin-top: 10px; } |
| 137 | 137 | .mac-setup-hint p { margin: 0; } |
| 138 | 138 | .mac-setup-hint p + p { margin-top: 4px; } |
| 139 | 新增:.mac-login-fullscreen[data-mode="maintenance"] { display: grid; place-items: center; padding: 16px; background: #0008; } | |
| 140 | 新增:[data-mode="maintenance"] .mac-login-panel { position: relative; inset: auto; display: flex; flex-direction: column; width: min(1100px, 100%); height: min(900px, calc(100dvh - 32px)); overflow: hidden; border: 1px solid #ffffff32; border-radius: 16px; background: #17191e; } | |
| 141 | 新增:[data-mode="maintenance"] .mac-login-tools { position: relative; inset: auto; align-self: flex-start; flex-shrink: 0; margin: 0 12px 8px; box-shadow: none; } | |
| 142 | 新增:[data-mode="maintenance"] .mac-login-stage { position: relative; flex: 1; min-height: 0; overflow: hidden; } | |
| 143 | 新增:[data-mode="maintenance"] .mac-setup-hint { position: relative; inset: auto; pointer-events: auto; margin: 0 12px 8px; } | |
| 144 | 新增:[data-mode="maintenance"] .mac-login-status { position: relative; inset: auto; flex-shrink: 0; margin: 8px 12px; } | |
| 145 | 新增:.project-recovery-actions { display: flex; flex-wrap: wrap; gap: 8px; align-items: center; } | |
| @@ -75,18 +75,23 @@ const setupKeys = {ArrowLeft:123, ArrowRight:124, ArrowDown:125, ArrowUp:126, Pa | ||
| 75 | 75 | const guestWidth = 1024; |
| 76 | 76 | const guestHeight = 640; |
| 77 | 77 | |
| 78 | 删除:function closeSession(session, endpoint) { | |
| 79 | 删除: if (session) api(endpoint, { action: "close", session }).catch(() => {}); | |
| 78 | 新增:function closeSession(session, endpoint, maintenance) { | |
| 79 | 新增: if (session) api(endpoint, { action: "close", session, ...(maintenance ? { maintenance } : {}) }).catch(() => {}); | |
| 80 | 80 | } |
| 81 | 81 | |
| 82 | 删除:export function MacOSLogin({ disabled, initialSetup = false, setupActions, setupHint, setupStatus, setupError, autoOpen = false, managedCredential = false }) { | |
| 83 | 删除: const endpoint = initialSetup ? "/macos/first-setup" : "/macos/login"; | |
| 82 | 新增:export function MacOSLogin({ disabled, initialSetup = false, maintenance = "", label, setupActions, setupHint, setupStatus, setupError, autoOpen = false, managedCredential = false, onSessionClosed, onSettings }) { | |
| 83 | 新增: const endpoint = initialSetup ? "/macos/first-setup" : maintenance ? "/macos/maintenance" : "/macos/login"; | |
| 84 | 新增: const scope = maintenance ? { maintenance } : {}; | |
| 84 | 85 | const [opened, setOpened] = useState(false); |
| 85 | 86 | const [session, setSession] = useState(""); |
| 86 | 87 | const [frame, setFrame] = useState(""); |
| 87 | 88 | const [message, setMessage] = useState(""); |
| 89 | 新增: const [frameError, setFrameError] = useState(""); | |
| 90 | 新增: const [recovery, setRecovery] = useState(""); | |
| 91 | 新增: const [administrator, setAdministrator] = useState(""); | |
| 92 | 新增: const [frameTarget, setFrameTarget] = useState(null); | |
| 88 | 93 | const [authorizationPassword, setAuthorizationPassword] = useState(""); |
| 89 | 删除: const [zoomed, setZoomed] = useState(!initialSetup); | |
| 94 | 新增: const [zoomed, setZoomed] = useState(!initialSetup && !maintenance); | |
| 90 | 95 | const [size, setSize] = useState({ width: 0, height: 0 }); |
| 91 | 96 | const [aspect, setAspect] = useState(guestWidth / guestHeight); |
| 92 | 97 | const lease = useRef(null); |
| @@ -99,24 +104,29 @@ export function MacOSLogin({ disabled, initialSetup = false, setupActions, setup | ||
| 99 | 104 | const drag = useRef(null); |
| 100 | 105 | const dragged = useRef(false); |
| 101 | 106 | const autoOpened = useRef(false); |
| 107 | 新增: const shown = useRef({ region: [0, 0, guestWidth, guestHeight], geometry: "" }); | |
| 102 | 108 | |
| 103 | 109 | const fitWidth = Math.min(size.width, size.height * aspect); |
| 104 | 110 | // Keep a 320 × 200 logical region around the account controls visible. |
| 105 | 删除: const imageWidth = !zoomed ? fitWidth : initialSetup ? fitWidth * 2 : | |
| 111 | 新增: const imageWidth = !zoomed ? fitWidth : initialSetup || maintenance ? fitWidth * 2 : | |
| 106 | 112 | Math.min(size.width * guestWidth / 320, size.height * aspect * guestHeight / 200); |
| 107 | 113 | const imageHeight = imageWidth / aspect; |
| 108 | 114 | const hasFrame = Boolean(frame); |
| 115 | 新增: const visibleMessage = message || frameError; | |
| 109 | 116 | |
| 110 | 117 | function end(show = "") { |
| 111 | 118 | if (!lease.current) return; |
| 112 | 119 | const old = lease.current; |
| 113 | 120 | lease.current = null; |
| 114 | 删除: closeSession(old.session, endpoint); | |
| 121 | 新增: closeSession(old.session, endpoint, maintenance); | |
| 115 | 122 | setOpened(false); |
| 116 | 123 | setSession(""); |
| 117 | 124 | setFrame(""); |
| 125 | 新增: setFrameTarget(null); | |
| 126 | 新增: shown.current = { region: [0, 0, guestWidth, guestHeight], geometry: "" }; | |
| 118 | 127 | setAuthorizationPassword(""); |
| 119 | 128 | setMessage(show); |
| 129 | 新增: setFrameError(""); | |
| 120 | 130 | } |
| 121 | 131 | |
| 122 | 132 | async function open() { |
| @@ -125,15 +135,18 @@ export function MacOSLogin({ disabled, initialSetup = false, setupActions, setup | ||
| 125 | 135 | lease.current = next; |
| 126 | 136 | chain.current = Promise.resolve(); |
| 127 | 137 | setMessage(""); |
| 128 | 删除: setZoomed(!initialSetup); | |
| 138 | 新增: setFrameError(""); | |
| 139 | 新增: setRecovery(""); | |
| 140 | 新增: setZoomed(!initialSetup && !maintenance); | |
| 129 | 141 | setOpened(true); |
| 130 | 142 | try { |
| 131 | 删除: const r = await api(endpoint, { action: "open" }); | |
| 143 | 新增: const r = await api(endpoint, { action: "open", ...scope }); | |
| 132 | 144 | if (lease.current !== next) { |
| 133 | 删除: closeSession(r.session, endpoint); | |
| 145 | 新增: closeSession(r.session, endpoint, maintenance); | |
| 134 | 146 | return; |
| 135 | 147 | } |
| 136 | 删除: if (!r.session) throw new Error(r.error || "暂时无法打开客机登录界面"); | |
| 148 | 新增: if (!r.session) { setRecovery(r.recovery || ""); throw new Error(r.error || "暂时无法打开客机登录界面"); } | |
| 149 | 新增: setAdministrator(r.administrator || ""); | |
| 137 | 150 | next.session = r.session; |
| 138 | 151 | setSession(r.session); |
| 139 | 152 | } catch (e) { |
| @@ -156,7 +169,7 @@ export function MacOSLogin({ disabled, initialSetup = false, setupActions, setup | ||
| 156 | 169 | |
| 157 | 170 | useEffect(() => () => { |
| 158 | 171 | if (lease.current) { |
| 159 | 删除: closeSession(lease.current.session, endpoint); | |
| 172 | 新增: closeSession(lease.current.session, endpoint, maintenance); | |
| 160 | 173 | lease.current = null; |
| 161 | 174 | } |
| 162 | 175 | }, []); |
| @@ -193,7 +206,7 @@ export function MacOSLogin({ disabled, initialSetup = false, setupActions, setup | ||
| 193 | 206 | useLayoutEffect(() => { |
| 194 | 207 | if (!opened || !stage.current) return; |
| 195 | 208 | stage.current.scrollLeft = zoomed ? Math.max(0, (imageWidth - size.width) / 2) : 0; |
| 196 | 删除: stage.current.scrollTop = zoomed ? Math.max(0, imageHeight * 0.85 - size.height * 0.5) : 0; | |
| 209 | 新增: stage.current.scrollTop = zoomed ? Math.max(0, imageHeight * (maintenance ? 0.5 : 0.85) - size.height * 0.5) : 0; | |
| 197 | 210 | }, [opened, hasFrame, zoomed, imageWidth, imageHeight, size.width, size.height]); |
| 198 | 211 | |
| 199 | 212 | useEffect(() => { |
| @@ -202,11 +215,17 @@ export function MacOSLogin({ disabled, initialSetup = false, setupActions, setup | ||
| 202 | 215 | let alive = true; |
| 203 | 216 | const poll = async () => { |
| 204 | 217 | try { |
| 205 | 删除: const r = await api(endpoint, { action: "frame", session }); | |
| 218 | 新增: const r = await api(endpoint, { action: "frame", session, ...scope }); | |
| 206 | 219 | if (!alive || lease.current?.session !== session) return; |
| 207 | 删除: if (r.closed) return end(); | |
| 208 | 删除: if (r.image) setFrame(`data:${r.mime === "image/jpeg" ? "image/jpeg" : "image/png"};base64,${r.image}`); | |
| 209 | 删除: if (r.error) setMessage(r.error); | |
| 220 | 新增: if (r.closed) { setRecovery(r.recovery || ""); end(r.error || ""); onSessionClosed?.(); return; } | |
| 221 | 新增: if (r.image) { | |
| 222 | 新增: if (maintenance && (!r.geometry || !Array.isArray(r.region) || r.region.length !== 4 || !r.region.every(Number.isInteger))) | |
| 223 | 新增: throw new Error("客机维护画面缺少窗口定位,请更新组件后重试"); | |
| 224 | 新增: setFrameTarget(maintenance ? { geometry: r.geometry, region: r.region } : null); | |
| 225 | 新增: setFrame(`data:${r.mime === "image/jpeg" ? "image/jpeg" : "image/png"};base64,${r.image}`); | |
| 226 | 新增: setFrameError(""); | |
| 227 | 新增: } | |
| 228 | 新增: if (r.error) setFrameError(r.error); | |
| 210 | 229 | timer = setTimeout(poll, 550); |
| 211 | 230 | } catch (e) { |
| 212 | 231 | if (alive && lease.current?.session === session) end(e.message); |
| @@ -219,12 +238,14 @@ export function MacOSLogin({ disabled, initialSetup = false, setupActions, setup | ||
| 219 | 238 | function enqueue(action, data) { |
| 220 | 239 | const owner = lease.current; |
| 221 | 240 | if (!owner?.session) return; |
| 241 | 新增: const geometry = shown.current.geometry; | |
| 242 | 新增: if (maintenance && !geometry) { setMessage("请等待授权窗口画面后再操作"); return; } | |
| 222 | 243 | chain.current = chain.current.then(async () => { |
| 223 | 244 | if (lease.current !== owner) return; |
| 224 | 删除: const r = await api(endpoint, { action, session: owner.session, ...data }); | |
| 245 | 新增: const r = await api(endpoint, { action, session: owner.session, ...scope, ...(maintenance ? { geometry } : {}), ...data }); | |
| 225 | 246 | if (lease.current !== owner) return; |
| 226 | 删除: if (r.closed) end(); | |
| 227 | 删除: else if (r.error) setMessage(r.error); | |
| 247 | 新增: if (r.closed) { end(r.error || ""); onSessionClosed?.(); } | |
| 248 | 新增: else setMessage(r.error || ""); | |
| 228 | 249 | }).catch((e) => { if (lease.current === owner) end(e.message); }); |
| 229 | 250 | } |
| 230 | 251 | |
| @@ -234,14 +255,18 @@ export function MacOSLogin({ disabled, initialSetup = false, setupActions, setup | ||
| 234 | 255 | if (!rect || !rect.width || !rect.height || e.clientX < rect.left || e.clientX >= rect.right || |
| 235 | 256 | e.clientY < rect.top || e.clientY >= rect.bottom) return; |
| 236 | 257 | keyboard.current?.focus({ preventScroll: true }); |
| 258 | 新增: const [x, y, width, height] = shown.current.region; | |
| 237 | 259 | enqueue("click", { |
| 238 | 删除: x: Math.floor((e.clientX - rect.left) * guestWidth / rect.width), | |
| 239 | 删除: y: Math.floor((e.clientY - rect.top) * guestHeight / rect.height), | |
| 260 | 新增: x: x + Math.floor((e.clientX - rect.left) * width / rect.width), | |
| 261 | 新增: y: y + Math.floor((e.clientY - rect.top) * height / rect.height), | |
| 240 | 262 | }); |
| 241 | 263 | } |
| 242 | 264 | |
| 243 | 265 | function guestKey(e) { |
| 244 | 删除: const code = keys[e.code] ?? (initialSetup ? setupKeys[e.code] : undefined); | |
| 266 | 新增: if (maintenance && (e.metaKey || e.ctrlKey) && !e.altKey && e.code === "KeyA") { | |
| 267 | 新增: e.preventDefault(); enqueue("select-all", {}); return; | |
| 268 | 新增: } | |
| 269 | 新增: const code = keys[e.code] ?? (initialSetup || maintenance ? setupKeys[e.code] : undefined); | |
| 245 | 270 | if (e.metaKey || e.ctrlKey || e.altKey || code === undefined) return; |
| 246 | 271 | e.preventDefault(); |
| 247 | 272 | enqueue("key", { code, shift: e.shiftKey }); |
| @@ -249,7 +274,7 @@ export function MacOSLogin({ disabled, initialSetup = false, setupActions, setup | ||
| 249 | 274 | |
| 250 | 275 | useEffect(() => { |
| 251 | 276 | const element = stage.current; |
| 252 | 删除: if (!opened || !initialSetup || !element) return; | |
| 277 | 新增: if (!opened || (!initialSetup && !maintenance) || !element) return; | |
| 253 | 278 | const scroll = (event) => { |
| 254 | 279 | const rect = imageRef.current?.getBoundingClientRect(); |
| 255 | 280 | if (!rect?.width || !rect.height || event.clientX < rect.left || event.clientX >= rect.right || |
| @@ -257,16 +282,17 @@ export function MacOSLogin({ disabled, initialSetup = false, setupActions, setup | ||
| 257 | 282 | event.preventDefault(); |
| 258 | 283 | const unit = event.deltaMode === 1 ? 16 : event.deltaMode === 2 ? rect.height : 1; |
| 259 | 284 | const bounded = (delta, scale) => Math.max(-512, Math.min(512, Math.round(delta * unit * scale))); |
| 285 | 新增: const [x, y, width, height] = shown.current.region; | |
| 260 | 286 | enqueue("scroll", { |
| 261 | 删除: x: Math.floor((event.clientX - rect.left) * guestWidth / rect.width), | |
| 262 | 删除: y: Math.floor((event.clientY - rect.top) * guestHeight / rect.height), | |
| 263 | 删除: delta_x: bounded(event.deltaX, guestWidth / rect.width), | |
| 264 | 删除: delta_y: bounded(event.deltaY, guestHeight / rect.height), | |
| 287 | 新增: x: x + Math.floor((event.clientX - rect.left) * width / rect.width), | |
| 288 | 新增: y: y + Math.floor((event.clientY - rect.top) * height / rect.height), | |
| 289 | 新增: delta_x: bounded(event.deltaX, width / rect.width), | |
| 290 | 新增: delta_y: bounded(event.deltaY, height / rect.height), | |
| 265 | 291 | }); |
| 266 | 292 | }; |
| 267 | 293 | element.addEventListener("wheel", scroll, { passive: false }); |
| 268 | 294 | return () => element.removeEventListener("wheel", scroll); |
| 269 | 删除: }, [opened, initialSetup, session]); | |
| 295 | 新增: }, [opened, initialSetup, maintenance, session]); | |
| 270 | 296 | |
| 271 | 297 | function changeZoom(zoom) { |
| 272 | 298 | setZoomed(zoom); |
| @@ -274,10 +300,12 @@ export function MacOSLogin({ disabled, initialSetup = false, setupActions, setup | ||
| 274 | 300 | } |
| 275 | 301 | |
| 276 | 302 | return <> |
| 277 | 删除: <button ref={opener} disabled={disabled || opened} onClick={open}>{initialSetup ? "打开客机系统设置" : "登录客机账户"}</button> | |
| 303 | 新增: <button type="button" ref={opener} disabled={disabled || opened} onClick={open}>{label || (initialSetup ? "打开客机系统设置" : maintenance ? "打开客机授权设置" : "登录客机账户")}</button> | |
| 278 | 304 | {!opened && message && <span role="status">{message}</span>} |
| 305 | 新增: {!opened && ["environment-update", "environment-restart"].includes(recovery) && onSettings && | |
| 306 | 新增: <button type="button" onClick={onSettings}>{recovery === "environment-update" ? "查看环境组件" : "打开环境设置"}</button>} | |
| 279 | 307 | {opened && createPortal( |
| 280 | 删除: <div className="mac-login-fullscreen" data-mode={initialSetup ? "setup" : "login"} role="dialog" aria-modal="true" aria-label={initialSetup ? "首次设置虚拟 Mac" : "登录虚拟 Mac"} | |
| 308 | 新增: <div className="mac-login-fullscreen" data-mode={initialSetup ? "setup" : maintenance ? "maintenance" : "login"} role="dialog" aria-modal="true" aria-label={initialSetup ? "首次设置虚拟 Mac" : maintenance ? "恢复客机系统权限" : "登录虚拟 Mac"} | |
| 281 | 309 | onKeyDownCapture={(e) => { |
| 282 | 310 | if (e.key === "F6") { |
| 283 | 311 | e.preventDefault(); |
| @@ -292,21 +320,31 @@ export function MacOSLogin({ disabled, initialSetup = false, setupActions, setup | ||
| 292 | 320 | }}> |
| 293 | 321 | <div className="mac-login-panel"> |
| 294 | 322 | {!initialSetup && <header className="mac-login-heading"> |
| 295 | 删除: <h2>登录 macOS 客机</h2> | |
| 296 | 删除: <p>输入客机账户密码,按回车登录。</p> | |
| 323 | 新增: <h2>{maintenance ? "恢复客机系统权限" : "登录 macOS 客机"}</h2> | |
| 324 | 新增: <p>{maintenance ? "在当前系统设置窗口中完成授权。切换到其他客机应用或锁定后,画面会结束。" : "输入客机账户密码,按回车登录。"}</p> | |
| 297 | 325 | </header>} |
| 298 | 326 | <div className="mac-login-tools" role="toolbar" aria-label="画面工具"> |
| 299 | 327 | <button ref={back} onClick={() => end()}><ArrowLeft size={16} aria-hidden="true" />{initialSetup ? "返回设置指引" : "返回工作台"}</button> |
| 300 | 删除: <button aria-pressed={!zoomed} onClick={() => changeZoom(false)}><Maximize size={16} aria-hidden="true" />{initialSetup ? "适配" : "完整画面"}</button> | |
| 301 | 删除: <button aria-pressed={zoomed} onClick={() => changeZoom(true)}><ZoomIn size={16} aria-hidden="true" />{initialSetup ? "放大" : "登录区域"}</button> | |
| 328 | 新增: <button aria-pressed={!zoomed} onClick={() => changeZoom(false)}><Maximize size={16} aria-hidden="true" />{initialSetup || maintenance ? "适配" : "完整画面"}</button> | |
| 329 | 新增: <button aria-pressed={zoomed} onClick={() => changeZoom(true)}><ZoomIn size={16} aria-hidden="true" />{initialSetup || maintenance ? "放大" : "登录区域"}</button> | |
| 302 | 330 | {initialSetup && setupActions} |
| 303 | 331 | {initialSetup && managedCredential && <button disabled={!session} onClick={() => enqueue("fill-password",{})}>填写授权密码</button>} |
| 304 | 删除: {(!initialSetup || managedCredential) && <button onClick={async () => { | |
| 305 | 删除: try { const result = await api(endpoint,{action:"show-password"}); setAuthorizationPassword(result.password); } | |
| 306 | 删除: catch (e) { setMessage(e.message); } | |
| 332 | 新增: {!maintenance && (!initialSetup || managedCredential) && <button onClick={async () => { | |
| 333 | 新增: const owner = lease.current; | |
| 334 | 新增: try { | |
| 335 | 新增: const result = await api(endpoint,{action:"show-password"}); | |
| 336 | 新增: if (lease.current !== owner) return; | |
| 337 | 新增: setAuthorizationPassword(result.password); setMessage(""); | |
| 338 | 新增: } | |
| 339 | 新增: catch (e) { if (lease.current === owner) setMessage(e.message); } | |
| 307 | 340 | }}>{initialSetup ? "查看授权密码" : "查看客机密码"}</button>} |
| 308 | 341 | {authorizationPassword && <span className="mac-login-password">{authorizationPassword}<button onClick={() => setAuthorizationPassword("")}>隐藏</button></span>} |
| 309 | 342 | </div> |
| 343 | 新增: {maintenance && <div className="mac-setup-hint"> | |
| 344 | 新增: {maintenance === "projects" && <p>进入「文件系统扩展」,同时启用 macFUSE 和 macFUSE (local)。授权后 Cage 会自动检查并重新连接项目。</p>} | |
| 345 | 新增: {administrator && <p>系统要求管理员时,用户名填写 {administrator}。选中系统授权窗口的密码框后,点击「填写管理员密码」,再由你确认授权。</p>} | |
| 346 | 新增: {administrator && <button type="button" onClick={() => enqueue("fill-password", {})}>填写管理员密码</button>} | |
| 347 | 新增: </div>} | |
| 310 | 348 | {initialSetup && setupHint && <div className="mac-setup-hint"> |
| 311 | 349 | <p>{setupHint}</p> |
| 312 | 350 | <p role={setupError ? "alert" : "status"}>{setupStatus} 查看完整步骤或进入工作台时,点击「返回设置指引」。</p> |
| @@ -353,17 +391,18 @@ export function MacOSLogin({ disabled, initialSetup = false, setupActions, setup | ||
| 353 | 391 | {frame && <div className="mac-login-canvas" style={{ |
| 354 | 392 | width: Math.max(size.width, imageWidth), height: Math.max(size.height, imageHeight), |
| 355 | 393 | }}> |
| 356 | 删除: <img ref={imageRef} alt={initialSetup ? "Apple 客机首次系统设置" : "Apple 客机登录屏幕"} draggable={false} src={frame} | |
| 394 | 新增: <img ref={imageRef} key={maintenance ? frameTarget?.geometry : undefined} alt={initialSetup ? "Apple 客机首次系统设置" : maintenance ? "客机系统设置或授权窗口" : "Apple 客机登录屏幕"} draggable={false} src={frame} | |
| 357 | 395 | style={{ width: imageWidth, height: imageHeight }} |
| 358 | 396 | onLoad={(e) => { |
| 359 | 397 | if (e.currentTarget.naturalHeight) setAspect(e.currentTarget.naturalWidth / e.currentTarget.naturalHeight); |
| 398 | 新增: if (maintenance && frameTarget) shown.current = frameTarget; | |
| 360 | 399 | }} onClick={sendClick} /> |
| 361 | 400 | </div>} |
| 362 | 401 | </div> |
| 363 | 删除: {(message || !frame) && <p className="mac-login-status" role={message ? "alert" : "status"}> | |
| 364 | 删除: {message || (initialSetup ? "正在读取客机首次设置画面…" : "正在确认客机登录画面…")} | |
| 402 | 新增: {(visibleMessage || !frame) && <p className="mac-login-status" role={visibleMessage ? "alert" : "status"}> | |
| 403 | 新增: {visibleMessage || (initialSetup ? "正在读取客机首次设置画面…" : maintenance ? "正在确认系统授权窗口…" : "正在确认客机登录画面…")} | |
| 365 | 404 | </p>} |
| 366 | 删除: {!initialSetup && <p className="mac-login-help">拖动画面可查看其他账户或提示</p>} | |
| 405 | 新增: {!initialSetup && !maintenance && <p className="mac-login-help">拖动画面可查看其他账户或提示</p>} | |
| 367 | 406 | </div> |
| 368 | 407 | </div>, document.body)} |
| 369 | 408 | </>; |
| @@ -1,6 +1,7 @@ | ||
| 1 | 1 | import React, { useEffect, useRef, useState } from "react"; |
| 2 | 2 | import { api } from "./api"; |
| 3 | 3 | import { Modal } from "./modal"; |
| 4 | 新增:import { MacOSLogin } from "./macos-login"; | |
| 4 | 5 | import "./macos-project-approval.css"; |
| 5 | 6 | |
| 6 | 7 | const permissionMessages = { |
| @@ -9,11 +10,12 @@ const permissionMessages = { | ||
| 9 | 10 | requires_gui_login: "请先登录并解锁虚拟 Mac 的普通账户,然后重新打开项目。", |
| 10 | 11 | }; |
| 11 | 12 | |
| 12 | 删除:export function MacOSProjectApproval({ pending, onCheck, onClose }) { | |
| 13 | 新增:export function MacOSProjectApproval({ pending, onCheck, onClose, onSettings }) { | |
| 13 | 14 | const [frame, setFrame] = useState(null), |
| 14 | 15 | [notice, setNotice] = useState(""); |
| 15 | 16 | const [busy, setBusy] = useState(false); |
| 16 | 17 | const [actionError, setActionError] = useState(""); |
| 18 | 新增: const [maintenance, setMaintenance] = useState(""); | |
| 17 | 19 | const active = useRef(false), |
| 18 | 20 | inFlight = useRef(null); |
| 19 | 21 | const call = (action, fields = {}) => |
| @@ -34,6 +36,8 @@ export function MacOSProjectApproval({ pending, onCheck, onClose }) { | ||
| 34 | 36 | inFlight.current = request; |
| 35 | 37 | const result = await request; |
| 36 | 38 | if (live && !active.current) { |
| 39 | 新增: if (result.error === "project_screen_permission") setMaintenance("screen"); | |
| 40 | 新增: if (result.error === "accessibility_permission") setMaintenance("input"); | |
| 37 | 41 | const valid = Boolean( |
| 38 | 42 | !result.error && |
| 39 | 43 | result.image && |
| @@ -104,6 +108,7 @@ export function MacOSProjectApproval({ pending, onCheck, onClose }) { | ||
| 104 | 108 | y, |
| 105 | 109 | }); |
| 106 | 110 | setFrame(null); |
| 111 | 新增: if (result.error === "accessibility_permission") setMaintenance("input"); | |
| 107 | 112 | if (result.error) throw new Error(permissionMessages[result.error] || "客机授权窗口已变化,请等待新画面。"); |
| 108 | 113 | await onCheck(); |
| 109 | 114 | }); |
| @@ -135,6 +140,7 @@ export function MacOSProjectApproval({ pending, onCheck, onClose }) { | ||
| 135 | 140 | /> |
| 136 | 141 | )} |
| 137 | 142 | {notice && <p role="status">{notice}</p>} |
| 143 | 新增: {maintenance && <MacOSLogin maintenance={maintenance} onSettings={onSettings} onSessionClosed={() => void act(onCheck)} />} | |
| 138 | 144 | {actionError && <p role="alert">{actionError}</p>} |
| 139 | 145 | </Modal> |
| 140 | 146 | ); |
| @@ -32,6 +32,7 @@ import { TerminalMenu } from "./terminal-menu"; | ||
| 32 | 32 | import { InitializationGate } from "./initialization"; |
| 33 | 33 | import { MacOSLogin } from "./macos-login"; |
| 34 | 34 | import { MacOSClaudeWindow } from "./macos-claude-window"; |
| 35 | 新增:import { ProjectRecovery } from "./project-recovery"; | |
| 35 | 36 | import { ClaudeDesktop } from "./claude-desktop"; |
| 36 | 37 | import { useClaudeAccounts } from "./claude-accounts"; |
| 37 | 38 | import { AccountProvider, AccountGate, useAccount } from "./account"; |
| @@ -140,12 +141,21 @@ function App() { | ||
| 140 | 141 | quitAfterStop = useRef(null); |
| 141 | 142 | activeRef.current = active; |
| 142 | 143 | readyRef.current = Boolean(status?.ready); |
| 144 | 新增: const storageRecovery = status?.storage_recovery?.required; | |
| 143 | 145 | const current = tabs.find((t) => t.id === active), |
| 144 | 146 | terminal = !desktopOpen && current?.kind === "terminal", |
| 145 | 147 | busy = Boolean(status?.job?.running), |
| 146 | 删除: showHome = !desktopOpen && (home || !status?.vm_running || !current); | |
| 148 | 新增: showHome = storageRecovery || !desktopOpen && (home || !status?.vm_running || !current); | |
| 147 | 149 | const setupProgress = status?.job?.setup_progress && (busy || status.job.error); |
| 148 | 删除: const cliSessions = useCLISessions(Boolean(status && !busy), windowVisible); | |
| 150 | 新增: const cliSessions = useCLISessions(Boolean(status && !busy && !storageRecovery), windowVisible); | |
| 151 | 新增: useEffect(() => { | |
| 152 | 新增: if (storageRecovery) { | |
| 153 | 新增: setDesktopOpen(false); | |
| 154 | 新增: setHome(true); | |
| 155 | 新增: setStartOptions(null); | |
| 156 | 新增: setStartRequest(null); | |
| 157 | 新增: } | |
| 158 | 新增: }, [storageRecovery]); | |
| 149 | 159 | const other = tabs.find(tab => tab.id === layout.other); |
| 150 | 160 | const split = Boolean(other && current && !showHome && !desktopOpen); |
| 151 | 161 | const panes = !split ? [current].filter(Boolean) |
| @@ -240,7 +250,7 @@ function App() { | ||
| 240 | 250 | useEffect(() => { |
| 241 | 251 | if (finishedLogins) claudeProfiles.load(); |
| 242 | 252 | }, [finishedLogins, claudeProfiles.load]); |
| 243 | 删除: const audio = useAudioOutput(running && !status?.environment_update_required && !connectionError); | |
| 253 | 新增: const audio = useAudioOutput(running && !storageRecovery && !status?.environment_update_required && !connectionError); | |
| 244 | 254 | useEffect(() => { |
| 245 | 255 | if (audio.error) setToast(audio.error); |
| 246 | 256 | }, [audio.error]); |
| @@ -639,7 +649,7 @@ function App() { | ||
| 639 | 649 | ]); |
| 640 | 650 | if (!live) return; |
| 641 | 651 | const b = browserResult || browserSnapshot.current; |
| 642 | 删除: const legacyMetadata = readLocal(clientStorageKey("cage-tab-layout"), {})[next.environment_directory || next.workspace] || {}; | |
| 652 | 新增: const legacyMetadata = readLocal(clientStorageKey("cage-tab-layout"), {})[next.environment_identity_directory || next.environment_directory || next.workspace] || {}; | |
| 643 | 653 | for (const item of t) { |
| 644 | 654 | const saved = legacyMetadata["terminal:" + item.id]; |
| 645 | 655 | if (!item.cli_session_id || item.metadata_set || !saved || (!saved.title && !saved.pinned)) continue; |
| @@ -940,6 +950,10 @@ function App() { | ||
| 940 | 950 | if (!projectDialog && !rename && !dialog) openSettings(); |
| 941 | 951 | return; |
| 942 | 952 | } |
| 953 | 新增: if (storageRecovery && ["openProject", "newTab", "newTerminal"].includes(command)) { | |
| 954 | 新增: openSettings("project"); | |
| 955 | 新增: return; | |
| 956 | 新增: } | |
| 943 | 957 | if (command === "openProject") { |
| 944 | 958 | if ( |
| 945 | 959 | !busy && |
| @@ -1034,7 +1048,7 @@ function App() { | ||
| 1034 | 1048 | terminalChoice, |
| 1035 | 1049 | ]); |
| 1036 | 1050 | const project = projectName(contentWorkspace, status?.environment_directory); |
| 1037 | 删除: const tabLayoutKey = status?.environment_directory || status?.workspace; | |
| 1051 | 新增: const tabLayoutKey = status?.environment_identity_directory || status?.environment_directory || status?.workspace; | |
| 1038 | 1052 | const metadata = { ...(savedTabs[tabLayoutKey] || {}), ...(privateTabMetadata[tabLayoutKey] || {}) }; |
| 1039 | 1053 | for (const tab of tabs) { |
| 1040 | 1054 | if (tab.cli_session_id && tab.metadata_set) metadata[tab.id] = { |
| @@ -1318,7 +1332,7 @@ function App() { | ||
| 1318 | 1332 | saved={metadata} |
| 1319 | 1333 | active={active} |
| 1320 | 1334 | home={showHome} |
| 1321 | 删除: busy={busy} | |
| 1335 | 新增: busy={busy || storageRecovery} | |
| 1322 | 1336 | ready={status.ready} |
| 1323 | 1337 | running={running} |
| 1324 | 1338 | runtimeLabel={runtimeLabel} |
| @@ -1372,10 +1386,10 @@ function App() { | ||
| 1372 | 1386 | <main className={`workspace ${split ? "workspace-split" : ""}`} ref={workspaceBox} |
| 1373 | 1387 | style={{ "--split-left": `${100 * (dualBrowser && nativeSplit?.fraction || 0.5)}%` }}> |
| 1374 | 1388 | {dropSide && <div aria-hidden="true" className={`split-drop split-${dropSide}`}>{dropSide === "left" ? "放到左侧" : "放到右侧"}</div>} |
| 1375 | 删除: {desktopOpen && macGuest && <MacOSClaudeWindow uploads={desktopFiles.uploads} keyboard={status.keyboard} remoteRef={remote} | |
| 1389 | 新增: {!storageRecovery && desktopOpen && macGuest && <MacOSClaudeWindow uploads={desktopFiles.uploads} keyboard={status.keyboard} remoteRef={remote} | |
| 1376 | 1390 | onStatus={notify} onFallback={(text, message) => setTransfer({ text, message })} visible={!settingsOpen} onConfirm={confirm} |
| 1377 | 1391 | sidebarCollapsed={sidebarCollapsed} onExpand={() => persist("cage-sidebar-collapsed", false, setSidebarCollapsed)} />} |
| 1378 | 删除: {desktopOpen && !macGuest && <ClaudeDesktop | |
| 1392 | 新增: {!storageRecovery && desktopOpen && !macGuest && <ClaudeDesktop | |
| 1379 | 1393 | uploads={desktopFiles.uploads} |
| 1380 | 1394 | onProjectOpened={() => refreshStatus.current?.()} |
| 1381 | 1395 | status={status} visible={!settingsOpen} remoteRef={remote} |
| @@ -1390,7 +1404,7 @@ function App() { | ||
| 1390 | 1404 | <button onClick={() => openSettings("project")}>查看并更新</button> |
| 1391 | 1405 | </div> |
| 1392 | 1406 | )} |
| 1393 | 删除: {(status.vm_running || terminal) && ( | |
| 1407 | 新增: {!storageRecovery && (status.vm_running || terminal) && ( | |
| 1394 | 1408 | <> |
| 1395 | 1409 | {!desktopOpen && !showHome && webPanes.length > 0 && ( |
| 1396 | 1410 | <section className={`pane-lane browser-lane ${browserTabLayout === "vertical" ? "vertical-browser" : ""} ${dualBrowser ? "" : "split-" + paneSide(webPanes[0].id)}`}> |
| @@ -1457,7 +1471,12 @@ function App() { | ||
| 1457 | 1471 | <div className="welcome"> |
| 1458 | 1472 | <div className="welcome-content"> |
| 1459 | 1473 | <img className="welcome-logo" src={logo} alt="Cage" /> |
| 1460 | 删除: {setupProgress ? <> | |
| 1474 | 新增: {storageRecovery ? <> | |
| 1475 | 新增: <h1>环境存储需要恢复</h1> | |
| 1476 | 新增: <p className="welcome-subtitle"><SafetyMessage message={status.storage_recovery.error} /></p> | |
| 1477 | 新增: <p className="field-help">在设置中恢复环境存储后,再启动浏览器和终端。诊断包可以从同一页面导出。</p> | |
| 1478 | 新增: <button className="primary" onClick={() => openSettings("project")}>恢复环境存储</button> | |
| 1479 | 新增: </> : setupProgress ? <> | |
| 1461 | 1480 | <h1>{status.job.error ? "环境安装未完成" : "正在安装 Cage 环境"}</h1> |
| 1462 | 1481 | <SetupProgress job={status.job} onDetails={() => setDetails(true)} |
| 1463 | 1482 | onStop={stop} onRetry={() => setStartOptions(status.job.kind === "guest-install" ? { guest_system: status.job.setup_progress.system } : {})} disconnected={Boolean(connectionError)} /> |
| @@ -1629,19 +1648,20 @@ function App() { | ||
| 1629 | 1648 | <p>环境和浏览器可继续使用。</p> |
| 1630 | 1649 | {status.project_errors?.length ? ( |
| 1631 | 1650 | <ul className="project-connection-errors"> |
| 1632 | 删除: {status.project_errors.map(({ path, message }) => ( | |
| 1651 | 新增: {status.project_errors.map(({ path, message, recovery }) => ( | |
| 1633 | 1652 | <li key={path}> |
| 1634 | 1653 | <strong>{projectName(path, status.environment_directory)}</strong> |
| 1635 | 1654 | <span className="project-error-path">{path}</span> |
| 1636 | 1655 | <p>{message}</p> |
| 1637 | 删除: <button disabled={!status.ready || busy} onClick={() => setProjectDialog({ path })}>连接项目</button> | |
| 1656 | 新增: <ProjectRecovery recovery={recovery} disabled={!status.ready || busy} | |
| 1657 | 新增: onRetry={() => setProjectDialog({ path })} onSettings={() => openSettings("project")} /> | |
| 1638 | 1658 | </li> |
| 1639 | 1659 | ))} |
| 1640 | 1660 | </ul> |
| 1641 | 1661 | ) : <p>{status.project_error}</p>} |
| 1642 | 1662 | </div> |
| 1643 | 1663 | )} |
| 1644 | 删除: {!setupProgress && status.job?.error && ( | |
| 1664 | 新增: {!storageRecovery && !setupProgress && status.job?.error && ( | |
| 1645 | 1665 | <div className="start-error" role="alert"> |
| 1646 | 1666 | <strong>{status.job.message || "本次操作未完成"}</strong> |
| 1647 | 1667 | <p><SafetyMessage message={status.job.error} /></p> |
| @@ -1761,6 +1781,7 @@ function App() { | ||
| 1761 | 1781 | status={status} |
| 1762 | 1782 | initialPath={projectDialog.path} |
| 1763 | 1783 | onClose={() => setProjectDialog(null)} |
| 1784 | 新增: onSettings={() => { setProjectDialog(null); openSettings("project"); }} | |
| 1764 | 1785 | onOpened={openedProject} |
| 1765 | 1786 | /> |
| 1766 | 1787 | )} |
| @@ -5,6 +5,7 @@ import { api, native, nativeAvailable } from "./api"; | ||
| 5 | 5 | import { SafetyMessage } from "./safety-message"; |
| 6 | 6 | import { Modal } from "./views"; |
| 7 | 7 | import { MacOSProjectApproval } from "./macos-project-approval"; |
| 8 | 新增:import { ProjectRecovery } from "./project-recovery"; | |
| 8 | 9 | import { projectName, rememberClientProjectName } from "./workspace-state.mjs"; |
| 9 | 10 | import { getClientContext, isRemoteClient } from "./client-context.mjs"; |
| 10 | 11 | |
| @@ -14,11 +15,13 @@ export function ProjectDialog({ | ||
| 14 | 15 | activate = true, |
| 15 | 16 | onClose, |
| 16 | 17 | onOpened, |
| 18 | 新增: onSettings, | |
| 17 | 19 | }) { |
| 18 | 20 | const projects = status.projects || []; |
| 19 | 21 | const [adding, setAdding] = useState(Boolean(initialPath) || projects.length === 0); |
| 20 | 22 | const [path, setPath] = useState(initialPath || status.workspace || projects[0] || ""); |
| 21 | 23 | const [error, setError] = useState(""); |
| 24 | 新增: const [recovery, setRecovery] = useState(""); | |
| 22 | 25 | const [pending, setPending] = useState(null); |
| 23 | 26 | const [submitting, setSubmitting] = useState(false); |
| 24 | 27 | const [directories, setDirectories] = useState(null); |
| @@ -91,10 +94,11 @@ export function ProjectDialog({ | ||
| 91 | 94 | else if (nativeAvailable()) void choose(); |
| 92 | 95 | }; |
| 93 | 96 | const open = async (event) => { |
| 94 | 删除: event.preventDefault(); | |
| 97 | 新增: event?.preventDefault(); | |
| 95 | 98 | if (busy || sharing || !path.trim()) return; |
| 96 | 99 | setSubmitting(true); |
| 97 | 100 | setError(""); |
| 101 | 新增: setRecovery(""); | |
| 98 | 102 | try { |
| 99 | 103 | const result = await api("/projects/open", { |
| 100 | 104 | workspace: path.trim(), |
| @@ -105,11 +109,12 @@ export function ProjectDialog({ | ||
| 105 | 109 | else await onOpened(result.workspace); |
| 106 | 110 | } catch (e) { |
| 107 | 111 | setError(e.message); |
| 112 | 新增: setRecovery(e.recovery || ""); | |
| 108 | 113 | } finally { |
| 109 | 114 | setSubmitting(false); |
| 110 | 115 | } |
| 111 | 116 | }; |
| 112 | 删除: if (pending) return <MacOSProjectApproval pending={pending} onClose={onClose} onCheck={async () => { | |
| 117 | 新增: if (pending) return <MacOSProjectApproval pending={pending} onClose={onClose} onSettings={onSettings} onCheck={async () => { | |
| 113 | 118 | const result = await api("/projects/open", { workspace: pending.workspace, add: adding, activate }); |
| 114 | 119 | if (result.approval) { |
| 115 | 120 | setPending({workspace: result.workspace, grant: result.approval}); |
| @@ -219,6 +224,8 @@ export function ProjectDialog({ | ||
| 219 | 224 | {error && ( |
| 220 | 225 | <div className="error-message" role="alert"> |
| 221 | 226 | <SafetyMessage message={error} /> |
| 227 | 新增: {recovery && <ProjectRecovery recovery={recovery} disabled={busy} onRetry={() => void open()} | |
| 228 | 新增: onSettings={onSettings} onSessionClosed={() => void open()} />} | |
| 222 | 229 | </div> |
| 223 | 230 | )} |
| 224 | 231 | </form> |
| @@ -0,0 +1,15 @@ | ||
| 1 | 新增:import React from "react"; | |
| 2 | 新增:import { MacOSLogin } from "./macos-login"; | |
| 3 | 新增: | |
| 4 | 新增:export function ProjectRecovery({ recovery, disabled, onRetry, onSettings, onSessionClosed }) { | |
| 5 | 新增: return <div className="project-recovery-actions"> | |
| 6 | 新增: {recovery === "guest-login" && <MacOSLogin disabled={disabled} onSessionClosed={onSessionClosed} />} | |
| 7 | 新增: {recovery === "filesystem-permission" && <MacOSLogin disabled={disabled} maintenance="projects" | |
| 8 | 新增: onSessionClosed={onSessionClosed} onSettings={onSettings} />} | |
| 9 | 新增: {["environment-update", "environment-restart"].includes(recovery) && onSettings && | |
| 10 | 新增: <button type="button" disabled={disabled} onClick={onSettings}>{recovery === "environment-update" ? "查看环境组件" : "打开环境设置"}</button>} | |
| 11 | 新增: {recovery === "project-directory" && onSettings && | |
| 12 | 新增: <button type="button" disabled={disabled} onClick={onSettings}>查看诊断记录</button>} | |
| 13 | 新增: <button type="button" disabled={disabled} onClick={onRetry}>{recovery === "project-approval" ? "完成项目授权" : "重新连接项目"}</button> | |
| 14 | 新增: </div>; | |
| 15 | 新增:} | |
| @@ -313,12 +313,20 @@ export function installRemoteInput( | ||
| 313 | 313 | await writeClipboard(content.text); |
| 314 | 314 | } |
| 315 | 315 | if (valid()) say("已复制到本机"); |
| 316 | 删除: } catch { | |
| 316 | 新增: } catch (error) { | |
| 317 | 317 | if (!valid()) return; |
| 318 | 318 | if (typeof content.text === "string") onFallback(content.text, "请在这里复制到本机。"); |
| 319 | 删除: else say("浏览器未允许写入图片剪贴板,请允许剪贴板访问后重试。"); | |
| 319 | 新增: else say(error.name === "NotAllowedError" ? "浏览器未允许写入图片剪贴板,请允许剪贴板访问后重试。" : error.message || "复制内容读取失败,请重试。"); | |
| 320 | 320 | } |
| 321 | 321 | }; |
| 322 | 新增: const waitForCopy = () => { | |
| 323 | 新增: if (!copyRequested) return; | |
| 324 | 新增: clearTimeout(copyTimer); | |
| 325 | 新增: copyTimer = setTimeout(() => { | |
| 326 | 新增: copyRequested = false; | |
| 327 | 新增: onFallback(lastText, "未收到新的选中文本,可在这里复制 Cage 剪贴板。"); | |
| 328 | 新增: }, 1600); | |
| 329 | 新增: }; | |
| 322 | 330 | const copy = (key = "c") => { |
| 323 | 331 | if (disposed || !isActive()) return; |
| 324 | 332 | copyRequested = true; |
| @@ -332,20 +340,19 @@ export function installRemoteInput( | ||
| 332 | 340 | document.visibilityState !== "hidden" && document.hasFocus(); |
| 333 | 341 | return transport.runKeyAction(async sendKey => { |
| 334 | 342 | const before = await caretRect?.(); |
| 335 | 删除: const content = await copyText(async () => { | |
| 343 | 新增: const sendCopy = async () => { | |
| 336 | 344 | if (!valid()) throw new Error("复制窗口已变化,请重新选择文本。"); |
| 337 | 345 | for (const value of shortcutKeys(key)) await sendKey(...value); |
| 338 | 删除: }, valid, { id, context, key }); | |
| 346 | 新增: }; | |
| 347 | 新增: const content = await copyText(sendCopy, valid, { id, context, key }); | |
| 348 | 新增: if (content === undefined) { await sendCopy(); waitForCopy(); return; } | |
| 339 | 349 | const after = await caretRect?.(); |
| 340 | 350 | if (before?.available && (!after?.available || before.context !== after.context)) throw new Error("复制位置已变化,请重新选择文本。"); |
| 341 | 351 | if (valid()) await receiveCopy({ ...content, id, context }); |
| 342 | 352 | }).catch(error => { if (valid()) say(error.message || "未收到新的选中文本,请重新选择后复制。"); }); |
| 343 | 353 | } |
| 344 | 354 | chord(key); |
| 345 | 删除: copyTimer = setTimeout(() => { | |
| 346 | 删除: copyRequested = false; | |
| 347 | 删除: onFallback(lastText, "未收到新的选中文本,可在这里复制 Cage 剪贴板。"); | |
| 348 | 删除: }, 1600); | |
| 355 | 新增: waitForCopy(); | |
| 349 | 356 | }; |
| 350 | 357 | const paste = (text) => { |
| 351 | 358 | if (disposed) return; |
| @@ -577,6 +577,25 @@ test("explicit desktop copy preserves the queued native copy keys", async () => | ||
| 577 | 577 | } finally { f.controller.dispose(); } |
| 578 | 578 | }); |
| 579 | 579 | |
| 580 | 新增:test("a late browser capability can switch copying from native events to its private adapter", async () => { | |
| 581 | 新增: let available = false; | |
| 582 | 新增: const f = fixture(false, false, { copyText: () => available ? Promise.resolve({ text: "private copy" }) : undefined }); | |
| 583 | 新增: try { | |
| 584 | 新增: await f.controller.copy(); | |
| 585 | 新增: assert.equal(f.keys.length, 4); | |
| 586 | 新增: const event = new Event("clipboard"); | |
| 587 | 新增: event.detail = { text: "native event" }; | |
| 588 | 新增: f.rfb.dispatchEvent(event); | |
| 589 | 新增: await new Promise(resolve => setImmediate(resolve)); | |
| 590 | 新增: assert.deepEqual(f.writes, ["native event"]); | |
| 591 | 新增: available = true; | |
| 592 | 新增: f.keys.length = 0; | |
| 593 | 新增: await f.controller.copy(); | |
| 594 | 新增: assert.deepEqual(f.keys, []); | |
| 595 | 新增: assert.deepEqual(f.writes, ["native event", "private copy"]); | |
| 596 | 新增: } finally { f.controller.dispose(); } | |
| 597 | 新增:}); | |
| 598 | 新增: | |
| 580 | 599 | test("copied text supports two MiB in UTF-8 and rejects larger content", async () => { |
| 581 | 600 | const f = fixture(); |
| 582 | 601 | try { |
| @@ -31,6 +31,7 @@ import { EnvironmentVersions } from "./environment-versions"; | ||
| 31 | 31 | import { EnvironmentStorage } from "./environment-storage"; |
| 32 | 32 | import { ResourceSettings } from "./resources"; |
| 33 | 33 | import { DiagnosticSettings } from "./diagnostics.jsx"; |
| 34 | 新增:import { MacOSLogin } from "./macos-login"; | |
| 34 | 35 | import { AccountSettings } from "./account"; |
| 35 | 36 | import { ClaudeAccountsPanel } from "./claude-accounts"; |
| 36 | 37 | const sections = [ |
| @@ -94,7 +95,7 @@ export function SettingsPanel({ | ||
| 94 | 95 | : draft[k] !== current[k], |
| 95 | 96 | ); |
| 96 | 97 | const busy = |
| 97 | 删除: Boolean(status.job?.running) || probing || submitting || Boolean(jobId); | |
| 98 | 新增: Boolean(status.job?.running) || Boolean(status.storage_recovery?.required) || probing || submitting || Boolean(jobId); | |
| 98 | 99 | const update = (key, value) => { |
| 99 | 100 | setDraft((p) => ({ ...p, [key]: value })); |
| 100 | 101 | if (["dns_url"].includes(key)) setProbe(null); |
| @@ -251,7 +252,7 @@ export function SettingsPanel({ | ||
| 251 | 252 | await onClaudeLogin(id); |
| 252 | 253 | onClose(); |
| 253 | 254 | }} />} |
| 254 | 删除: <fieldset className="settings-fields" disabled={busy}> | |
| 255 | 新增: <fieldset className="settings-fields" disabled={busy && !(section === "project" && status.storage_recovery?.required)}> | |
| 255 | 256 | {section === "mobile" && (isRemoteClient() |
| 256 | 257 | ? <section className="section-title"><h3>连接这台电脑</h3><p>请先切换到这台电脑的本机环境,再生成或管理手机配对码。</p></section> |
| 257 | 258 | : <MobilePairSettings relay={draft.mobile_relay ?? ""} savedRelay={current.mobile_relay ?? ""} onChange={value => update("mobile_relay",value)} onConfirm={onConfirm} />)} |
| @@ -599,8 +600,17 @@ export function SettingsPanel({ | ||
| 599 | 600 | <p className="footnote"> |
| 600 | 601 | 切换项目只改变新终端和文件编辑器的起始位置;已有终端、网页和登录态会保留。 |
| 601 | 602 | </p> |
| 602 | 删除: <EnvironmentVersions status={status} onConfirm={onConfirm} /> | |
| 603 | 删除: <ResourceSettings status={status} onConfirm={onConfirm} onDirtyChange={setResourceDirty} /> | |
| 603 | 新增: {!status.storage_recovery?.required && <EnvironmentVersions status={status} onConfirm={onConfirm} />} | |
| 604 | 新增: {status.guest_system === "macos" && <section aria-label="客机系统权限"> | |
| 605 | 新增: <h4>客机系统权限</h4> | |
| 606 | 新增: <p className="field-help">在受限的客机系统设置窗口中完成授权,Cage 会自动检查并重新连接项目。</p> | |
| 607 | 新增: <div className="project-recovery-actions"> | |
| 608 | 新增: <MacOSLogin maintenance="projects" label="文件共享权限" disabled={!status.ready || busy} /> | |
| 609 | 新增: <MacOSLogin maintenance="screen" label="屏幕录制权限" disabled={!status.ready || busy} /> | |
| 610 | 新增: <MacOSLogin maintenance="input" label="辅助功能权限" disabled={!status.ready || busy} /> | |
| 611 | 新增: </div> | |
| 612 | 新增: </section>} | |
| 613 | 新增: {!status.storage_recovery?.required && <ResourceSettings status={status} onConfirm={onConfirm} onDirtyChange={setResourceDirty} />} | |
| 604 | 614 | <DiagnosticSettings /> |
| 605 | 615 | {status.can_restore && ( |
| 606 | 616 | <button |
| @@ -2716,5 +2716,6 @@ svg { | ||
| 2716 | 2716 | .environment-storage .field-help code { overflow-wrap: anywhere; } |
| 2717 | 2717 | .environment-storage .storage-actions { display: flex; flex-wrap: wrap; gap: 8px; } |
| 2718 | 2718 | .environment-storage .storage-actions button:disabled { opacity: 1; color: var(--muted); background: var(--chrome); } |
| 2719 | 新增:.environment-storage .storage-repair-help { margin: 8px 0 0; } | |
| 2719 | 2720 | .environment-storage > [role="status"] { margin: 12px 0 20px; overflow-wrap: anywhere; } |
| 2720 | 2721 | .start-project-box .storage-entry { justify-self: start; margin: 0 16px 8px; } |
| @@ -128,8 +128,9 @@ export const RemoteView = forwardRef(function RemoteView( | ||
| 128 | 128 | }, container, { |
| 129 | 129 | guestPlatform: () => current.current.guestPlatform, |
| 130 | 130 | systemClipboard: () => current.current.systemClipboard, |
| 131 | 删除: copyText: !desktop && !current.current.systemClipboard | |
| 131 | 新增: copyText: !desktop | |
| 132 | 132 | ? (_sendCopy, valid, { id, context, key }) => { |
| 133 | 新增: if (current.current.systemClipboard !== false) return undefined; | |
| 133 | 134 | if (!valid()) throw new Error("复制位置已切换,请重新复制"); |
| 134 | 135 | return api("/browser/" + (key === "x" ? "cut" : "copy"), { id, context }); |
| 135 | 136 | } |

