提交记录新增internal/guestos/maintenance_macos.go+149 −0看文件
新增scripts/guest-os/build-macos-claude-window.sh+25 −0看文件
新增scripts/guest-os/build-macos-clipboard.sh+25 −0看文件
新增scripts/guest-os/build-macos-guest-core.sh+30 −0看文件
新增scripts/guest-os/build-macos-project-access.sh+25 −0看文件
新增scripts/guest-os/build-macos-setup-probe.py+90 −0看文件
新增scripts/guest-os/build-macos-sshfs.sh+28 −0看文件
新增scripts/guest-os/build-windows-workbench-payload.ps1+42 −0看文件
新增scripts/guest-os/cage-macos-editor+8 −0看文件
新增scripts/guest-os/claude-desktop-macos.sh+125 −0看文件
新增scripts/guest-os/claude-desktop-windows.ps1+168 −0看文件
新增scripts/guest-os/claude-desktop-windows.tests.ps1+101 −0看文件
新增scripts/guest-os/claude-window-macos.swift+140 −0看文件
新增scripts/guest-os/claude-window-windows.ps1+160 −0看文件
新增scripts/guest-os/claude-window-windows.tests.ps1+32 −0看文件
新增scripts/guest-os/complete-windows-guest.ps1+322 −0看文件
新增scripts/guest-os/configure-macos-session.sh+75 −0看文件
新增scripts/guest-os/guest-clipboard-macos.swift+785 −0看文件
新增scripts/guest-os/guest-clipboard-windows/.gitignore+2 −0看文件
新增scripts/guest-os/guest-clipboard-windows/AttachmentsRpc.cs+156 −0看文件
新增scripts/guest-os/guest-clipboard-windows/BrowserPasteInput.cs+68 −0看文件
新增scripts/guest-os/guest-clipboard-windows/BrowserRpc.cs+510 −0看文件
新增scripts/guest-os/guest-clipboard-windows/BrowserWindowCapture.cs+436 −0看文件
新增scripts/guest-os/guest-clipboard-windows/Cage.GuestClipboard.csproj+25 −0看文件
新增scripts/guest-os/guest-clipboard-windows/ClaudeGraphicsCapture.cs+323 −0看文件
新增scripts/guest-os/guest-clipboard-windows/ClaudeWindowRpc.cs+526 −0看文件
新增scripts/guest-os/guest-clipboard-windows/ClipboardAgent.cs+387 −0看文件
新增scripts/guest-os/guest-clipboard-windows/GlobalUsings.cs+1 −0看文件
新增scripts/guest-os/guest-clipboard-windows/GuestDiagnostics.cs+121 −0看文件
新增scripts/guest-os/guest-clipboard-windows/GuestProcessJob.cs+31 −0看文件
新增scripts/guest-os/guest-clipboard-windows/GuestVersions.cs+154 −0看文件
新增scripts/guest-os/guest-clipboard-windows/GuestWindowCapture.cs+9 −0看文件
新增scripts/guest-os/guest-clipboard-windows/NativeGuestInput.cs+112 −0看文件
新增scripts/guest-os/guest-clipboard-windows/NativeSafetyRpc.cs+114 −0看文件
新增scripts/guest-os/guest-clipboard-windows/NetworkRuntime.cs+255 −0看文件
新增scripts/guest-os/guest-clipboard-windows/Program.cs+194 −0看文件
新增scripts/guest-os/guest-clipboard-windows/ProjectRpc.cs+154 −0看文件
新增scripts/guest-os/guest-clipboard-windows/Protocol.cs+137 −0看文件
新增scripts/guest-os/guest-clipboard-windows/Relay.cs+110 −0看文件
新增scripts/guest-os/guest-clipboard-windows/ResourcesRpc.cs+41 −0看文件
新增scripts/guest-os/guest-clipboard-windows/Security.cs+208 −0看文件
新增scripts/guest-os/guest-clipboard-windows/SelfTest.cs+110 −0看文件
新增scripts/guest-os/guest-clipboard-windows/TerminalRpc.cs+241 −0看文件
新增scripts/guest-os/guest-clipboard-windows/WindowsAudioRpc.cs+294 −0看文件
新增scripts/guest-os/guest-clipboard-windows/WindowsCliRpc.cs+300 −0看文件
新增scripts/guest-os/guest-clipboard-windows/WindowsComponentStatus.cs+94 −0看文件
新增scripts/guest-os/guest-clipboard-windows/WindowsDesktopDownloads.cs+258 −0看文件
新增scripts/guest-os/guest-clipboard-windows/WindowsDesktopFiles.cs+262 −0看文件
新增scripts/guest-os/guest-clipboard-windows/WindowsEditorPreferences.cs+53 −0看文件
新增scripts/guest-os/guest-clipboard-windows/WindowsEditorServer.cs+146 −0看文件
新增scripts/guest-os/guest-clipboard-windows/WindowsFileDialogNative.cs+140 −0看文件
新增scripts/guest-os/guest-clipboard-windows/WindowsFilePublication.cs+29 −0看文件
新增scripts/guest-os/guest-clipboard-windows/WindowsIme.cs+85 −0看文件
新增scripts/guest-os/guest-clipboard-windows/WindowsPhoneBrowser.cs+103 −0看文件
新增scripts/guest-os/guest-clipboard-windows/WindowsSystemSettings.cs+80 −0看文件
新增scripts/guest-os/guest-clipboard-windows/ccs-runtime/package-lock.json+2222 −0看文件
新增scripts/guest-os/guest-clipboard-windows/ccs-runtime/package.json+8 −0看文件
新增scripts/guest-os/guest-clipboard-windows/cli-dependencies.json+28 −0看文件
新增scripts/guest-os/guest-clipboard-windows/install-ccs.ps1+84 −0看文件
新增scripts/guest-os/guest-clipboard-windows/install-cli.ps1+122 −0看文件
新增scripts/guest-os/guest-clipboard-windows/install-network.ps1+76 −0看文件
新增scripts/guest-os/guest-clipboard-windows/install.ps1+124 −0看文件
新增scripts/guest-os/guest-clipboard-windows/qa-browser.ps1+184 −0看文件
新增scripts/guest-os/guest-clipboard-windows/qa-large-file.ps1+25 −0看文件
新增scripts/guest-os/guest-clipboard-windows/qa-local-browser.ps1+100 −0看文件
新增scripts/guest-os/guest-clipboard-windows/qa.ps1+73 −0看文件
新增scripts/guest-os/guest-clipboard-windows/update.ps1+87 −0看文件
新增scripts/guest-os/initialize-windows-test-accounts.ps1+120 −0看文件
新增scripts/guest-os/initialize-windows-workbench-user.ps1+126 −0看文件
新增scripts/guest-os/install-guest-powershell.cmd+45 −0看文件
新增scripts/guest-os/install-guest-powershell.tests.ps1+93 −0看文件
新增scripts/guest-os/install-macos-browser.sh+76 −0看文件
新增scripts/guest-os/install-macos-cli.sh+114 −0看文件
新增scripts/guest-os/install-macos-node.sh+23 −0看文件
新增scripts/guest-os/install-macos-project-tools.sh+94 −0看文件
新增scripts/guest-os/install-windows-host-manager.ps1+99 −0看文件
新增scripts/guest-os/install-windows-workbench-components.ps1+127 −0看文件
新增scripts/guest-os/install-windows-workbench-user-tools.ps1+10 −0看文件
新增scripts/guest-os/macos-audio.swift+241 −0看文件
新增scripts/guest-os/macos-browser-service.mjs+123 −0看文件
新增scripts/guest-os/macos-browser.mjs+316 −0看文件
新增scripts/guest-os/macos-claude-canvas.swift+169 −0看文件
新增scripts/guest-os/macos-claude-window-app.swift+486 −0看文件
新增scripts/guest-os/macos-cli-browser.mjs+47 −0看文件
新增scripts/guest-os/macos-cli.py+55 −0看文件
新增scripts/guest-os/macos-desktop-downloads.swift+256 −0看文件
新增scripts/guest-os/macos-desktop-files.swift+557 −0看文件
新增scripts/guest-os/macos-diagnostics.swift+61 −0看文件
新增scripts/guest-os/macos-file-writers.c+52 −0看文件
新增scripts/guest-os/macos-fuse-media.sh+19 −0看文件
新增scripts/guest-os/macos-gui-session.swift+39 −0看文件
新增scripts/guest-os/macos-ipv6-check.c+78 −0看文件
新增scripts/guest-os/macos-native-browser.mjs+126 −0看文件
新增scripts/guest-os/macos-phone-browser.mjs+78 −0看文件
新增scripts/guest-os/macos-phone-desktop.swift+253 −0看文件
新增scripts/guest-os/macos-project-access.m+502 −0看文件
新增scripts/guest-os/macos-project-panel.swift+80 −0看文件
新增scripts/guest-os/macos-project-terminal.m+168 −0看文件
新增scripts/guest-os/macos-setup-account.m+170 −0看文件
新增scripts/guest-os/macos-setup-bridge.h+5 −0看文件
新增scripts/guest-os/macos-setup-bridge.m+47 −0看文件
新增scripts/guest-os/macos-setup-view.h+22 −0看文件
新增scripts/guest-os/macos-setup-view.m+117 −0看文件
新增scripts/guest-os/macos-window-input.swift+262 −0看文件
新增scripts/guest-os/macos-window-stream.swift+131 −0看文件
新增scripts/guest-os/maintain-macos-workbench.sh+186 −0看文件
新增scripts/guest-os/maintain-windows-workbench.ps1+152 −0看文件 新增scripts/guest-os/new-windows-test-vm.ps1+172 −0看文件 新增scripts/guest-os/new-windows-test-vm.tests.ps1+33 −0看文件 新增scripts/guest-os/package-macos-browser.sh+14 −0看文件 新增scripts/guest-os/package-macos-guest.sh+35 −0看文件 新增scripts/guest-os/prepare-macos-cli-kit.sh+40 −0看文件 新增scripts/guest-os/prepare-macos-media.sh+59 −0看文件 新增scripts/guest-os/provision-claude-offline-windows.ps1+212 −0看文件 新增scripts/guest-os/provision-claude-offline-windows.tests.ps1+62 −0看文件 新增scripts/guest-os/provision-macos-workbench.sh+79 −0看文件 新增scripts/guest-os/publish-windows-component-manifest.ps1+53 −0看文件 新增scripts/guest-os/register-macos-browser.sh+35 −0看文件 新增scripts/guest-os/register-macos-claude-window.sh+53 −0看文件 新增scripts/guest-os/register-macos-clipboard.sh+36 −0看文件 新增scripts/guest-os/setup-windows-guest.ps1+128 −0看文件 新增scripts/guest-os/start-windows-evaluation-setup.ps1+182 −0看文件 新增scripts/guest-os/tailnet-client.mjs+2 −0看文件 新增scripts/guest-os/test-macos-claude-trial.py+109 −0看文件 新增scripts/guest-os/test-native-debugger.mjs+74 −0看文件 新增scripts/guest-os/test-windows-guest-powershell.cmd+23 −0看文件 新增scripts/guest-os/tests/editor-preferences/EditorPreferences.csproj+12 −0看文件 新增scripts/guest-os/tests/editor-preferences/Program.cs+25 −0看文件 新增scripts/guest-os/tests/macos-browser-service.test.mjs+82 −0看文件 新增scripts/guest-os/tests/macos-cli-login.py+111 −0看文件 新增scripts/guest-os/tests/macos-diagnostics-test.swift+33 −0看文件 新增scripts/guest-os/tests/macos-phone-browser.test.mjs+129 −0看文件 新增scripts/guest-os/tests/native-display-fixture.mjs+76 −0看文件 新增scripts/guest-os/tests/native-download-host-fixture.mjs+50 −0看文件 新增scripts/guest-os/tests/native-input-leases/NativeInputLeases.csproj+12 −0看文件 新增scripts/guest-os/tests/native-input-leases/Program.cs+58 −0看文件 新增scripts/guest-os/tests/native-maintenance.py+269 −0看文件 新增scripts/guest-os/tests/windows-browser-deny-proxy.mjs+34 −0看文件 新增scripts/guest-os/tests/windows-browser-extensions.test.mjs+63 −0看文件 新增scripts/guest-os/tests/windows-browser-fixtures.mjs+12 −0看文件 新增scripts/guest-os/tests/windows-browser.test.mjs+535 −0看文件 新增scripts/guest-os/tests/windows-maintenance.ps1+112 −0看文件 新增scripts/guest-os/tests/windows-native-browser-fixture.mjs+50 −0看文件 新增scripts/guest-os/update-windows-workbench-components.ps1+139 −0看文件 新增scripts/guest-os/windows-browser-extensions.mjs+92 −0看文件 新增scripts/guest-os/windows-browser.mjs+1118 −0看文件 新增scripts/guest-os/windows-evaluation-autounattend.xml+44 −0看文件 新增scripts/guest-os/windows-evaluation.tests.ps1+195 −0看文件 新增scripts/guest-os/windows-file-dialog-qa/WindowsFileDialogProbe.cs+184 −0看文件 新增scripts/guest-os/windows-file-dialog-qa/WindowsFileDialogQA.csproj+18 −0看文件 新增scripts/guest-os/windows-guest-media.ps1+156 −0看文件 新增scripts/guest-os/windows-host-enrollment-smoke.ps1+62 −0看文件 新增scripts/guest-os/windows-host-enrollment.ps1+117 −0看文件 新增scripts/guest-os/windows-host-image.ps1+162 −0看文件 新增scripts/guest-os/windows-host-image.tests.ps1+73 −0看文件 新增scripts/guest-os/windows-phone-browser.mjs+90 −0看文件 新增scripts/guest-os/windows-powershell-media.smoke.ps1+44 −0看文件 新增scripts/guest-os/windows-workbench-packages.json+11 −0看文件 新增scripts/guest-os/windows-workbench-packages.ps1+25 −0看文件
| @@ -0,0 +1,149 @@ | ||
| 1 | 新增:package guestos | |
| 2 | 新增: | |
| 3 | 新增:import ( | |
| 4 | 新增: "bytes" | |
| 5 | 新增: "context" | |
| 6 | 新增: "encoding/json" | |
| 7 | 新增: "errors" | |
| 8 | 新增: "fmt" | |
| 9 | 新增: "io" | |
| 10 | 新增: "os" | |
| 11 | 新增: "os/exec" | |
| 12 | 新增: "path/filepath" | |
| 13 | 新增: "reflect" | |
| 14 | 新增: "regexp" | |
| 15 | 新增: "runtime" | |
| 16 | 新增: "strings" | |
| 17 | 新增: "time" | |
| 18 | 新增: | |
| 19 | 新增: "al.essio.dev/pkg/shellescape" | |
| 20 | 新增:) | |
| 21 | 新增: | |
| 22 | 新增:// MaintainMacOSComponents operates only on an already bound VZ identity. Its | |
| 23 | 新增:// staging and installers are independent of account creation and OS restoration. | |
| 24 | 新增:func MaintainMacOSComponents(ctx context.Context, profile, kit, manifestPath string, tools bool, stdout, stderr io.Writer) error { | |
| 25 | 新增: if runtime.GOOS != "darwin" { | |
| 26 | 新增: return errors.New("macOS 客机维护需要其 Mac 主机") | |
| 27 | 新增: } | |
| 28 | 新增: binding, err := LoadMacOSProfile(profile) | |
| 29 | 新增: if err != nil { | |
| 30 | 新增: return err | |
| 31 | 新增: } | |
| 32 | 新增: if binding == nil { | |
| 33 | 新增: return errors.New("此配置尚未绑定 macOS 客机") | |
| 34 | 新增: } | |
| 35 | 新增: required, err := RequiredNativeComponents(kit, MacOS) | |
| 36 | 新增: if err != nil { | |
| 37 | 新增: return err | |
| 38 | 新增: } | |
| 39 | 新增: data, err := os.ReadFile(manifestPath) | |
| 40 | 新增: if err != nil { | |
| 41 | 新增: return err | |
| 42 | 新增: } | |
| 43 | 新增: var selected NativeComponentManifest | |
| 44 | 新增: if json.Unmarshal(data, &selected) != nil || selected.Validate() != nil || !reflect.DeepEqual(required, selected) { | |
| 45 | 新增: return errors.New("当前应用组件包已变化,请重新发起更新") | |
| 46 | 新增: } | |
| 47 | 新增: provision, err := MacOSProvisionUser(profile) | |
| 48 | 新增: if err != nil { | |
| 49 | 新增: return err | |
| 50 | 新增: } | |
| 51 | 新增: args, err := MacOSSSHArgs(profile, provision) | |
| 52 | 新增: if err != nil { | |
| 53 | 新增: return err | |
| 54 | 新增: } | |
| 55 | 新增: guest := func(callctx context.Context, script string) *exec.Cmd { | |
| 56 | 新增: argv := append(append([]string{}, args...), "-T", "cage-macos", "--", "exec /bin/bash -ec "+shellescape.Quote(script)) | |
| 57 | 新增: command := exec.CommandContext(callctx, "/usr/bin/ssh", argv...) | |
| 58 | 新增: command.Stderr = stderr | |
| 59 | 新增: return command | |
| 60 | 新增: } | |
| 61 | 新增: mode := "components" | |
| 62 | 新增: cache := filepath.Join(profile, "state", "guest-media", MacOS) | |
| 63 | 新增: if tools { | |
| 64 | 新增: mode = "tools" | |
| 65 | 新增: command := exec.CommandContext(ctx, "/bin/bash", filepath.Join(kit, "prepare-macos-media.sh"), cache) | |
| 66 | 新增: command.Env = append(os.Environ(), "CAGE_REFRESH_TOOLS=1") | |
| 67 | 新增: command.Stdout, command.Stderr = stdout, stderr | |
| 68 | 新增: if err = command.Run(); err != nil { | |
| 69 | 新增: return fmt.Errorf("准备原生工具包失败:%w", err) | |
| 70 | 新增: } | |
| 71 | 新增: } | |
| 72 | 新增: local, err := os.MkdirTemp("", "cage-native-components-") | |
| 73 | 新增: if err != nil { | |
| 74 | 新增: return err | |
| 75 | 新增: } | |
| 76 | 新增: defer os.RemoveAll(local) | |
| 77 | 新增: if err = os.WriteFile(filepath.Join(local, "native-components.json"), data, 0600); err != nil { | |
| 78 | 新增: return err | |
| 79 | 新增: } | |
| 80 | 新增: output, err := guest(ctx, `umask 077; test "$(id -un)" = `+shellescape.Quote(provision)+`; mktemp -d /private/var/tmp/cage-components.XXXXXXXX`).Output() | |
| 81 | 新增: remote := strings.TrimSpace(string(output)) | |
| 82 | 新增: if err != nil || !regexp.MustCompile(`^/private/var/tmp/cage-components\.[A-Za-z0-9]{8}$`).MatchString(remote) { | |
| 83 | 新增: return errors.New("无法在已绑定客机中准备组件维护目录") | |
| 84 | 新增: } | |
| 85 | 新增: passwordInput := ` < /Users/` + provision + `/password` | |
| 86 | 新增: defer func() { | |
| 87 | 新增: cleanup, cancel := context.WithTimeout(context.Background(), 10*time.Second) | |
| 88 | 新增: defer cancel() | |
| 89 | 新增: _ = guest(cleanup, `sudo -S -p '' /bin/rm -rf `+remote+passwordInput).Run() | |
| 90 | 新增: }() | |
| 91 | 新增: archiveArgs := []string{"--no-mac-metadata", "-cf", "-", "-C", kit, ".", "-C", local, "native-components.json"} | |
| 92 | 新增: if tools { | |
| 93 | 新增: archiveArgs = append(archiveArgs, "-C", cache, "node.tgz", "editor.tgz", "playwright.tgz", "chrome.dmg", "cli") | |
| 94 | 新增: } | |
| 95 | 新增: archive := exec.CommandContext(ctx, "/usr/bin/tar", archiveArgs...) | |
| 96 | 新增: archive.Env = append(os.Environ(), "COPYFILE_DISABLE=1") | |
| 97 | 新增: var archiveErrors bytes.Buffer | |
| 98 | 新增: archive.Stderr = &archiveErrors | |
| 99 | 新增: pipe, err := archive.StdoutPipe() | |
| 100 | 新增: if err != nil { | |
| 101 | 新增: return err | |
| 102 | 新增: } | |
| 103 | 新增: receiver := guest(ctx, `umask 077; cd `+remote+`; /usr/bin/tar -xf -`) | |
| 104 | 新增: receiver.Stdin = pipe | |
| 105 | 新增: if err = archive.Start(); err != nil { | |
| 106 | 新增: return err | |
| 107 | 新增: } | |
| 108 | 新增: receiveErr := receiver.Run() | |
| 109 | 新增: pipe.Close() | |
| 110 | 新增: archiveErr := archive.Wait() | |
| 111 | 新增: if archiveErrors.Len() > 0 { | |
| 112 | 新增: _, _ = stderr.Write(archiveErrors.Bytes()) | |
| 113 | 新增: } | |
| 114 | 新增: if err = errors.Join(receiveErr, archiveErr); err != nil { | |
| 115 | 新增: return fmt.Errorf("传递原生组件失败:%w", err) | |
| 116 | 新增: } | |
| 117 | 新增: takeOwnership := guest(ctx, `sudo -S -p '' /usr/sbin/chown -R root:wheel `+remote+passwordInput) | |
| 118 | 新增: if err = takeOwnership.Run(); err != nil { | |
| 119 | 新增: return errors.New("无法取得已绑定客机的组件维护权限") | |
| 120 | 新增: } | |
| 121 | 新增: script := shellescape.QuoteCommand([]string{"/bin/bash", remote + "/maintain-macos-workbench.sh", remote, binding.User, mode}) | |
| 122 | 新增: command := guest(ctx, `sudo -S -p '' `+script+passwordInput) | |
| 123 | 新增: command.Stdout = stdout | |
| 124 | 新增: if err = command.Run(); err != nil { | |
| 125 | 新增: return fmt.Errorf("原生组件维护未完成,原系统和账户已保留,可重试更新:%w", err) | |
| 126 | 新增: } | |
| 127 | 新增: return nil | |
| 128 | 新增:} | |
| 129 | 新增: | |
| 130 | 新增:func WriteNativeComponentManifest(filename string, manifest NativeComponentManifest) error { | |
| 131 | 新增: if err := manifest.Validate(); err != nil { | |
| 132 | 新增: return err | |
| 133 | 新增: } | |
| 134 | 新增: data, err := json.Marshal(manifest) | |
| 135 | 新增: if err != nil { | |
| 136 | 新增: return err | |
| 137 | 新增: } | |
| 138 | 新增: file, err := os.CreateTemp(filepath.Dir(filename), ".native-components-*.json") | |
| 139 | 新增: if err != nil { | |
| 140 | 新增: return err | |
| 141 | 新增: } | |
| 142 | 新增: defer os.Remove(file.Name()) | |
| 143 | 新增: _, writeErr := file.Write(append(bytes.TrimSpace(data), '\n')) | |
| 144 | 新增: err = errors.Join(writeErr, file.Sync(), file.Close()) | |
| 145 | 新增: if err != nil { | |
| 146 | 新增: return err | |
| 147 | 新增: } | |
| 148 | 新增: return os.Rename(file.Name(), filename) | |
| 149 | 新增:} | |
| @@ -0,0 +1,25 @@ | ||
| 1 | 新增:#!/bin/bash | |
| 2 | 新增:# Build the GUI-session helper for an Apple-silicon guest (macOS 14+). | |
| 3 | 新增:set -euo pipefail | |
| 4 | 新增:src=$(cd "$(dirname "$0")" && pwd) | |
| 5 | 新增:app=${1:?Specify a new output .app path} | |
| 6 | 新增:[[ $app == *.app && ! -e $app ]] || { echo 'Choose a new .app path.' >&2; exit 2; } | |
| 7 | 新增:mkdir -p "$app/Contents/MacOS" | |
| 8 | 新增:cat > "$app/Contents/Info.plist" <<'PLIST' | |
| 9 | 新增:<?xml version="1.0" encoding="UTF-8"?> | |
| 10 | 新增:<plist version="1.0"><dict> | |
| 11 | 新增:<key>CFBundleIdentifier</key><string>dev.cage.GuestClaudeWindow</string> | |
| 12 | 新增:<key>CFBundleName</key><string>Cage Guest Window</string> | |
| 13 | 新增:<key>CFBundleExecutable</key><string>CageGuestWindow</string> | |
| 14 | 新增:<key>CFBundlePackageType</key><string>APPL</string> | |
| 15 | 新增:<key>CFBundleShortVersionString</key><string>1.0</string> | |
| 16 | 新增:<key>CFBundleVersion</key><string>1</string> | |
| 17 | 新增:<key>LSUIElement</key><true/> | |
| 18 | 新增:</dict></plist> | |
| 19 | 新增:PLIST | |
| 20 | 新增:objects=$(mktemp -d) | |
| 21 | 新增:trap 'rm -rf "$objects"' EXIT | |
| 22 | 新增: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" | |
| 24 | 新增:codesign --force --sign "${CAGE_GUEST_SIGN_IDENTITY:-${CAGE_SIGNING_IDENTITY:--}}" --identifier dev.cage.GuestClaudeWindow "$app" | |
| 25 | 新增:codesign --verify --strict "$app" | |
| @@ -0,0 +1,25 @@ | ||
| 1 | 新增:#!/bin/bash | |
| 2 | 新增:# Build the per-user clipboard agent and its bounded file-transfer helper. | |
| 3 | 新增:set -euo pipefail | |
| 4 | 新增:src=$(cd "$(dirname "$0")" && pwd) | |
| 5 | 新增:app=${1:?Specify a new output .app path} | |
| 6 | 新增:[[ $app == /*.app && ! -e $app ]] || { echo 'Choose a new absolute .app path.' >&2; exit 2; } | |
| 7 | 新增:mkdir -p "$app/Contents/MacOS" "$app/Contents/Resources" | |
| 8 | 新增:cat > "$app/Contents/Info.plist" <<'PLIST' | |
| 9 | 新增:<?xml version="1.0" encoding="UTF-8"?> | |
| 10 | 新增:<plist version="1.0"><dict> | |
| 11 | 新增:<key>CFBundleIdentifier</key><string>dev.cage.GuestClipboard</string> | |
| 12 | 新增:<key>CFBundleName</key><string>Cage Guest Clipboard</string> | |
| 13 | 新增:<key>CFBundleExecutable</key><string>CageGuestClipboard</string> | |
| 14 | 新增:<key>CFBundlePackageType</key><string>APPL</string> | |
| 15 | 新增:<key>CFBundleShortVersionString</key><string>1.0</string> | |
| 16 | 新增:<key>CFBundleVersion</key><string>1</string> | |
| 17 | 新增:<key>LSUIElement</key><true/> | |
| 18 | 新增:</dict></plist> | |
| 19 | 新增:PLIST | |
| 20 | 新增:xcrun swiftc -parse-as-library -O -target arm64-apple-macos14.0 "$src/guest-clipboard-macos.swift" "$src/macos-diagnostics.swift" -o "$app/Contents/MacOS/CageGuestClipboard" | |
| 21 | 新增:(cd "$src/../.." && CGO_ENABLED=0 GOOS=darwin GOARCH=arm64 go build -trimpath -ldflags '-s -w' -o "$app/Contents/Resources/cage-guest-files" ./cmd/cage-guest-files) | |
| 22 | 新增:identity=${CAGE_GUEST_SIGN_IDENTITY:-${CAGE_SIGNING_IDENTITY:--}} | |
| 23 | 新增:codesign --force --sign "$identity" "$app/Contents/Resources/cage-guest-files" | |
| 24 | 新增:codesign --force --sign "$identity" --identifier dev.cage.GuestClipboard "$app" | |
| 25 | 新增:codesign --verify --deep --strict "$app" | |
| @@ -0,0 +1,30 @@ | ||
| 1 | 新增:#!/bin/bash | |
| 2 | 新增:# Add the small raw-object accessor needed by the hostagent's AppKit view to a | |
| 3 | 新增:# private copy of the pinned VZ binding. The Go module cache stays read-only. | |
| 4 | 新增:set -euo pipefail | |
| 5 | 新增:cd "$(dirname "$0")/../.." | |
| 6 | 新增:work=$(mktemp -d) | |
| 7 | 新增:trap 'rm -rf "$work"' EXIT | |
| 8 | 新增:mod=github.com/Code-Hex/vz/v3 | |
| 9 | 新增:version=$(go list -m -f '{{.Version}}' "$mod") | |
| 10 | 新增:[[ $version == v3.7.1 ]] || { echo "Review the login view against VZ binding $version" >&2; exit 1; } | |
| 11 | 新增:dir=$(go list -m -f '{{.Dir}}' "$mod") | |
| 12 | 新增:cp -R "$dir" "$work/vz" | |
| 13 | 新增:chmod -R u+w "$work/vz" | |
| 14 | 新增:cat > "$work/vz/cage_view_object_darwin.go" <<'GO' | |
| 15 | 新增://go:build darwin && cgo | |
| 16 | 新增: | |
| 17 | 新增:package vz | |
| 18 | 新增: | |
| 19 | 新增:import ( | |
| 20 | 新增: "unsafe" | |
| 21 | 新增: "github.com/Code-Hex/vz/v3/internal/objc" | |
| 22 | 新增:) | |
| 23 | 新增: | |
| 24 | 新增:// CageViewObject borrows the VZVirtualMachine for the duration of RunGUI. | |
| 25 | 新增:func (v *VirtualMachine) CageViewObject() unsafe.Pointer { return objc.Ptr(v) } | |
| 26 | 新增:GO | |
| 27 | 新增:cp go.mod "$work/trial.mod" | |
| 28 | 新增:cp go.sum "$work/trial.sum" | |
| 29 | 新增:go mod edit -modfile "$work/trial.mod" -replace "$mod=$work/vz" | |
| 30 | 新增:GOFLAGS="${GOFLAGS:-} -modfile=$work/trial.mod" make cage VERSION="$1" | |
| @@ -0,0 +1,25 @@ | ||
| 1 | 新增:#!/bin/sh | |
| 2 | 新增:# Build the scoped project-access application for the native arm64 guest. | |
| 3 | 新增:set -eu | |
| 4 | 新增:[ "$#" = 1 ] || { echo "usage: $0 /path/to/CageProjectAccess.app" >&2; exit 2; } | |
| 5 | 新增:bundle=$1 | |
| 6 | 新增:[ ! -e "$bundle" ] || { echo "Choose a new output path." >&2; exit 1; } | |
| 7 | 新增:mkdir -p "$bundle/Contents/MacOS" | |
| 8 | 新增:cat > "$bundle/Contents/Info.plist" <<'PLIST' | |
| 9 | 新增:<?xml version="1.0" encoding="UTF-8"?> | |
| 10 | 新增:<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> | |
| 11 | 新增:<plist version="1.0"><dict> | |
| 12 | 新增:<key>CFBundleIdentifier</key><string>dev.cage.guest.project-access</string> | |
| 13 | 新增:<key>CFBundleDisplayName</key><string>Cage Project Access</string> | |
| 14 | 新增:<key>CFBundleName</key><string>Cage Project Access</string> | |
| 15 | 新增:<key>CFBundleExecutable</key><string>CageProjectAccess</string> | |
| 16 | 新增:<key>CFBundlePackageType</key><string>APPL</string> | |
| 17 | 新增:<key>CFBundleVersion</key><string>1</string> | |
| 18 | 新增:<key>CFBundleShortVersionString</key><string>1.0</string> | |
| 19 | 新增:<key>LSUIElement</key><true/> | |
| 20 | 新增:<key>NSNetworkVolumesUsageDescription</key><string>Open the mounted project you selected in Cage.</string> | |
| 21 | 新增:</dict></plist> | |
| 22 | 新增:PLIST | |
| 23 | 新增:xcrun clang -arch arm64 -mmacosx-version-min=14.0 -fobjc-arc -O2 -framework AppKit \ | |
| 24 | 新增: "$(dirname "$0")/macos-project-access.m" -o "$bundle/Contents/MacOS/CageProjectAccess" | |
| 25 | 新增:codesign --force --sign "${CAGE_SIGNING_IDENTITY:--}" "$bundle" | |
| @@ -0,0 +1,90 @@ | ||
| 1 | 新增:"""Build a QA-only Go runner with the Apple VM setup view bound to one temporary instance.""" | |
| 2 | 新增: | |
| 3 | 新增:import argparse | |
| 4 | 新增:import json | |
| 5 | 新增:import shutil | |
| 6 | 新增:import subprocess | |
| 7 | 新增:import tempfile | |
| 8 | 新增:from pathlib import Path | |
| 9 | 新增: | |
| 10 | 新增: | |
| 11 | 新增:SCRIPTS = Path(__file__).resolve().parent | |
| 12 | 新增:REPO = SCRIPTS.parents[1] | |
| 13 | 新增:VZ = "github.com/Code-Hex/vz/v3" | |
| 14 | 新增: | |
| 15 | 新增: | |
| 16 | 新增:def run(*command): | |
| 17 | 新增: subprocess.run(command, check=True, cwd=REPO) | |
| 18 | 新增: | |
| 19 | 新增: | |
| 20 | 新增:def replace_once(text, old, new): | |
| 21 | 新增: if text.count(old) != 1: | |
| 22 | 新增: raise SystemExit(f"Upstream hook changed. Inspect the source containing {old!r}.") | |
| 23 | 新增: return text.replace(old, new) | |
| 24 | 新增: | |
| 25 | 新增: | |
| 26 | 新增:def main(): | |
| 27 | 新增: parser = argparse.ArgumentParser(description=__doc__) | |
| 28 | 新增: parser.add_argument("instance", type=Path, help="Directory of the disposable Lima macOS instance") | |
| 29 | 新增: parser.add_argument("output", type=Path, help="New directory for the signed QA runner and its library") | |
| 30 | 新增: parser.add_argument("--runner", default="./cmd/cage", help="Go main package which owns the fixture runtime") | |
| 31 | 新增: args = parser.parse_args() | |
| 32 | 新增: instance = args.instance.resolve(strict=True) | |
| 33 | 新增: temp_roots = {Path(tempfile.gettempdir()).resolve(), Path("/private/tmp").resolve()} | |
| 34 | 新增: if not instance.is_dir() or not any(root in instance.parents for root in temp_roots): | |
| 35 | 新增: parser.error("Select an instance inside a disposable temporary directory.") | |
| 36 | 新增: out = args.output.resolve() | |
| 37 | 新增: out.mkdir(mode=0o700) | |
| 38 | 新增: dylib = out / "libcagesetup.dylib" | |
| 39 | 新增: run("xcrun", "clang", "-target", "arm64-apple-macos14.0", "-fobjc-arc", "-Wall", "-Wextra", "-Werror", | |
| 40 | 新增: "-dynamiclib", SCRIPTS / "macos-setup-view.m", SCRIPTS / "macos-setup-bridge.m", | |
| 41 | 新增: "-framework", "AppKit", "-framework", "Virtualization", "-o", dylib) | |
| 42 | 新增: with tempfile.TemporaryDirectory(prefix="cage-setup-build-") as scratch: | |
| 43 | 新增: work = Path(scratch) | |
| 44 | 新增: module = json.loads(subprocess.check_output(["go", "list", "-m", "-json", VZ], cwd=REPO)) | |
| 45 | 新增: if module.get("Version") != "v3.7.1": | |
| 46 | 新增: raise SystemExit("Review the native bridge for the current Code-Hex/vz version.") | |
| 47 | 新增: source = Path(module["Dir"]) | |
| 48 | 新增: copy = work / "vz" | |
| 49 | 新增: shutil.copytree(source, copy) | |
| 50 | 新增: copy.chmod(0o700) | |
| 51 | 新增: shutil.copyfile(SCRIPTS / "macos-setup-bridge.h", copy / "cage_setup_bridge.h") | |
| 52 | 新增: (copy / dylib.name).symlink_to(dylib) | |
| 53 | 新增: binding = copy / "virtualization.go" | |
| 54 | 新增: text = replace_once(binding.read_text(), '# include "virtualization_15.h"', | |
| 55 | 新增: '# include "virtualization_15.h"\n# include "cage_setup_bridge.h"') | |
| 56 | 新增: text = replace_once(text, "#cgo darwin LDFLAGS: -lobjc", | |
| 57 | 新增: "#cgo darwin LDFLAGS: -L${SRCDIR} -lcagesetup -lobjc") | |
| 58 | 新增: binding.chmod(0o600) | |
| 59 | 新增: binding.write_text(replace_once(text, "C.startVirtualMachineWindow(", "C.CageRunSetupBridge(")) | |
| 60 | 新增: | |
| 61 | 新增: driver = REPO / "third_party/lima/pkg/driver/vz/vz_driver_darwin.go" | |
| 62 | 新增: contents = driver.read_text() | |
| 63 | 新增: start = contents.index("func (l *LimaVzDriver) canRunGUI() bool {") | |
| 64 | 新增: end = contents.index("\n}", start) | |
| 65 | 新增: selected = json.dumps(str(instance), ensure_ascii=False) | |
| 66 | 新增: hook = ("func (l *LimaVzDriver) canRunGUI() bool {\n" | |
| 67 | 新增: f"\treturn l.Instance.Dir == {selected} && *l.Instance.Config.OS == limatype.DARWIN " | |
| 68 | 新增: '&& *l.Instance.Config.Video.Display == "offscreen"') | |
| 69 | 新增: modified = work / "driver.go" | |
| 70 | 新增: modified.write_text(contents[:start] + hook + contents[end:]) | |
| 71 | 新增: runner = json.loads(subprocess.check_output(["go", "list", "-json", args.runner], cwd=REPO)) | |
| 72 | 新增: runner_dir = Path(runner["Dir"]).resolve() | |
| 73 | 新增: if runner["Name"] != "main" or REPO not in runner_dir.parents: | |
| 74 | 新增: parser.error("Choose a main package in this checkout.") | |
| 75 | 新增: startup = work / "setup_thread.go" | |
| 76 | 新增: startup.write_text('package main\nimport "runtime"\nfunc init() { runtime.LockOSThread() }\n') | |
| 77 | 新增: overlay = work / "overlay.json" | |
| 78 | 新增: overlay.write_text(json.dumps({"Replace": { | |
| 79 | 新增: str(driver): str(modified), str(runner_dir / "cage_setup_qa_thread_darwin.go"): str(startup), | |
| 80 | 新增: }})) | |
| 81 | 新增: mod = work / "qa.mod" | |
| 82 | 新增: shutil.copyfile(REPO / "go.mod", mod) | |
| 83 | 新增: shutil.copyfile(REPO / "go.sum", work / "qa.sum") | |
| 84 | 新增: run("go", "mod", "edit", "-modfile", mod, "-replace", f"{VZ}={copy}") | |
| 85 | 新增: run("go", "build", "-modfile", mod, "-overlay", overlay, "-o", out / "qa-runner", args.runner) | |
| 86 | 新增: run("codesign", "-f", "-s", "-", "--entitlements", REPO / "third_party/lima/vz.entitlements", out / "qa-runner") | |
| 87 | 新增: | |
| 88 | 新增: | |
| 89 | 新增:if __name__ == "__main__": | |
| 90 | 新增: main() | |
| @@ -0,0 +1,28 @@ | ||
| 1 | 新增:#!/bin/bash | |
| 2 | 新增:# Build the FSKit-compatible SSHFS against the SDK from the signed macFUSE | |
| 3 | 新增:# installer. Pass its extracted usr/local directory; no host driver is installed. | |
| 4 | 新增:set -euo pipefail | |
| 5 | 新增:[[ $# == 2 && $(uname -sm) == 'Darwin arm64' ]] || { echo 'Usage: build-macos-sshfs.sh /absolute/macfuse-sdk/usr/local /absolute/cage-sshfs' >&2; exit 2; } | |
| 6 | 新增:sdk=$1 | |
| 7 | 新增:output=$2 | |
| 8 | 新增:[[ $sdk == /* && $output == /* && -f $sdk/include/fuse3/fuse.h && ! -e $output ]] | |
| 9 | 新增:src=$(mktemp -d) | |
| 10 | 新增:trap 'rm -rf "$src"' EXIT | |
| 11 | 新增:commit=9b68e5f1b978c1d3c6ef7632b68d580a52ec0232 | |
| 12 | 新增:curl -fLsS --retry 2 "https://codeload.github.com/libfuse/sshfs/tar.gz/$commit" -o "$src/sshfs.tgz" | |
| 13 | 新增:cd "$src" | |
| 14 | 新增:echo '9be20256ac841c6e5b4cd8aefbf57c325f93e9ff01f7c7691edfe9f02700338b sshfs.tgz' | shasum -a 256 -c - >/dev/null | |
| 15 | 新增:tar xzf sshfs.tgz --strip-components 1 | |
| 16 | 新增:cat > config.h <<'HEADER' | |
| 17 | 新增:#define PACKAGE_VERSION "3.7.6" | |
| 18 | 新增:#define IDMAP_DEFAULT "user" | |
| 19 | 新增:HEADER | |
| 20 | 新增:glib=$(brew --prefix glib) | |
| 21 | 新增:intl=$(brew --prefix gettext) | |
| 22 | 新增:pcre=$(brew --prefix pcre2) | |
| 23 | 新增:clang -arch arm64 -O2 -D_REENTRANT -DHAVE_CONFIG_H -DFUSE_DARWIN_ENABLE_EXTENSIONS=0 -DFUSE_USE_VERSION=31 \ | |
| 24 | 新增: -I. -Icompat -I"$sdk/include/fuse3" -I"$glib/include/glib-2.0" -I"$glib/lib/glib-2.0/include" -I"$intl/include" \ | |
| 25 | 新增: sshfs.c cache.c compat/darwin_compat.c "$glib/lib/libgthread-2.0.a" "$glib/lib/libglib-2.0.a" "$intl/lib/libintl.a" "$pcre/lib/libpcre2-8.a" \ | |
| 26 | 新增: -L"$sdk/lib" -lfuse3 -liconv -framework Foundation -framework CoreFoundation -framework AppKit -framework Carbon -o cage-sshfs | |
| 27 | 新增:codesign -s - --force cage-sshfs | |
| 28 | 新增:install -m 755 cage-sshfs "$output" | |
| @@ -0,0 +1,42 @@ | ||
| 1 | 新增:# Build Cage-owned assets only. Third-party Windows packages are fetched when | |
| 2 | 新增:# Windows is selected, with the digests in windows-workbench-packages.json. | |
| 3 | 新增:[CmdletBinding()] | |
| 4 | 新增:param([Parameter(Mandatory)][string]$Destination) | |
| 5 | 新增:$ErrorActionPreference='Stop' | |
| 6 | 新增:$root=(Resolve-Path (Join-Path $PSScriptRoot '../..')).Path | |
| 7 | 新增:$dest=[IO.Path]::GetFullPath($Destination) | |
| 8 | 新增:$null=New-Item -ItemType Directory -Force $dest | |
| 9 | 新增:$build=Join-Path ([IO.Path]::GetTempPath()) ('cage-windows-publish-'+[guid]::NewGuid()) | |
| 10 | 新增:Push-Location $root | |
| 11 | 新增:$oldOS=$env:GOOS; $oldArch=$env:GOARCH; $oldCGO=$env:CGO_ENABLED | |
| 12 | 新增:try { | |
| 13 | 新增: dotnet publish scripts/guest-os/guest-clipboard-windows/Cage.GuestClipboard.csproj -c Release -r win-x64 --self-contained true -p:PublishSingleFile=true -p:IncludeNativeLibrariesForSelfExtract=true -o $build | |
| 14 | 新增: if ($LASTEXITCODE) {throw 'Could not publish the native Windows guest bridge.'} | |
| 15 | 新增: Copy-Item -LiteralPath (Join-Path $build 'Cage.GuestClipboard.exe') -Destination $dest | |
| 16 | 新增: $env:GOOS='windows'; $env:GOARCH='amd64'; $env:CGO_ENABLED='0' | |
| 17 | 新增: go build -trimpath -o (Join-Path $dest 'cage-guest-files.exe') ./cmd/cage-guest-files | |
| 18 | 新增: if ($LASTEXITCODE) {throw 'Could not build the Windows guest file helper.'} | |
| 19 | 新增: go build -trimpath -o (Join-Path $dest 'cage-guest-boot.exe') ./cmd/cage-guest-boot | |
| 20 | 新增: if ($LASTEXITCODE) {throw 'Could not build the Windows guest boot service.'} | |
| 21 | 新增: go build -trimpath -o (Join-Path $dest 'Cage.HyperVManager.exe') ./cmd/cage-hyperv-manager | |
| 22 | 新增: if ($LASTEXITCODE) {throw 'Could not build the scoped Windows host manager.'} | |
| 23 | 新增: Push-Location (Join-Path $root 'tools/tailnet') | |
| 24 | 新增: try { go build -trimpath -ldflags '-s -w' -o (Join-Path $dest 'cage-tailnet.exe') .; if ($LASTEXITCODE) { throw 'Could not build Cage Tailscale.' } } finally { Pop-Location } | |
| 25 | 新增: Copy-Item -LiteralPath (Join-Path $root 'internal/cage/tailnet-client.mjs') -Destination $dest | |
| 26 | 新增: foreach ($file in @('windows-browser.mjs','windows-browser-extensions.mjs','windows-phone-browser.mjs','windows-workbench-packages.json','install-windows-workbench-user-tools.ps1')) { | |
| 27 | 新增: Copy-Item -LiteralPath (Join-Path $PSScriptRoot $file) -Destination $dest | |
| 28 | 新增: } | |
| 29 | 新增: foreach ($file in @('install-cli.ps1','cli-dependencies.json')) { | |
| 30 | 新增: Copy-Item -LiteralPath (Join-Path $PSScriptRoot ('guest-clipboard-windows/'+$file)) -Destination $dest | |
| 31 | 新增: } | |
| 32 | 新增: $moduleDir=Join-Path $dest 'modules' | |
| 33 | 新增: $null=New-Item -ItemType Directory -Force $moduleDir | |
| 34 | 新增: foreach ($name in @('clipboard','uploads','downloads','cookies','extensions','vault','phone','phone-network')) { | |
| 35 | 新增: Copy-Item -LiteralPath (Join-Path $root "internal/cage/browser-$name.mjs") -Destination $moduleDir | |
| 36 | 新增: } | |
| 37 | 新增: Copy-Item -LiteralPath (Join-Path $root 'internal/cage/split-extension') -Destination $dest -Recurse -Force | |
| 38 | 新增:} finally { | |
| 39 | 新增: $env:GOOS=$oldOS; $env:GOARCH=$oldArch; $env:CGO_ENABLED=$oldCGO | |
| 40 | 新增: Pop-Location | |
| 41 | 新增: if (Test-Path -LiteralPath $build) { Remove-Item -LiteralPath $build -Recurse -Force } | |
| 42 | 新增:} | |
| @@ -0,0 +1,8 @@ | ||
| 1 | 新增:#!/bin/bash | |
| 2 | 新增:# The project authorization helper starts this fixed executable inside the mount. | |
| 3 | 新增:set -euo pipefail | |
| 4 | 新增:project=${PWD##*/} | |
| 5 | 新增:[[ $project =~ ^[a-f0-9]{24}$ && $PWD == "$HOME/Cage/Projects/$project" ]] | |
| 6 | 新增:config="$HOME/Library/Application Support/Cage/EditorSessions/$project.yaml" | |
| 7 | 新增:[[ -f $config && ! -L $config && $(/usr/bin/stat -f %u "$config") == "$(id -u)" ]] | |
| 8 | 新增:exec /usr/local/libexec/cage-workbench-browser-4.145.0-pw1.65.0/editor/bin/code-server --config "$config" --disable-telemetry --disable-update-check "$PWD" | |
| @@ -0,0 +1,125 @@ | ||
| 1 | 新增:#!/bin/bash | |
| 2 | 新增:# Run inside a Cage macOS guest. Install accepts a local official DMG. | |
| 3 | 新增:set -euo pipefail | |
| 4 | 新增:export PATH=/usr/bin:/bin:/usr/sbin:/sbin | |
| 5 | 新增: | |
| 6 | 新增:fail() { printf '%s\n' "$*" >&2; exit 1; } | |
| 7 | 新增: | |
| 8 | 新增:case "${1:-}" in | |
| 9 | 新增: inspect|launch) [[ $# == 1 ]] || fail "Usage: $0 $1" ;; | |
| 10 | 新增: install) [[ $# == 2 ]] || fail "Usage: $0 install /path/to/Claude.dmg" ;; | |
| 11 | 新增: *) fail "Usage: $0 inspect | install /path/to/Claude.dmg | launch" ;; | |
| 12 | 新增:esac | |
| 13 | 新增: | |
| 14 | 新增:[[ $(uname -s) == Darwin ]] || fail "This helper requires a Cage macOS guest." | |
| 15 | 新增:model=$(sysctl -n hw.model) | |
| 16 | 新增:[[ $model =~ ^VirtualMac[0-9]+,[0-9]+$ ]] || fail "This Mac is not a virtual Mac. Run this helper inside the Cage guest." | |
| 17 | 新增:marker=/var/db/cage-guest-os | |
| 18 | 新增:[[ -f $marker && ! -L $marker && $(stat -f '%u' "$marker") == 0 ]] || | |
| 19 | 新增: fail "Missing root-owned Cage guest marker." | |
| 20 | 新增:mode=$(stat -f '%OLp' "$marker") | |
| 21 | 新增:(( (8#$mode & 022) == 0 )) && [[ $(cat "$marker") == macos ]] || | |
| 22 | 新增: fail "Invalid Cage guest marker." | |
| 23 | 新增: | |
| 24 | 新增:app=/Applications/Claude.app | |
| 25 | 新增:bundle_id=com.anthropic.claudefordesktop | |
| 26 | 新增:team=Q6L2SF6YDW | |
| 27 | 新增:requirement="anchor apple generic and identifier \"$bundle_id\" and certificate leaf[subject.OU] = \"$team\" and certificate 1[field.1.2.840.113635.100.6.2.6] exists and certificate leaf[field.1.2.840.113635.100.6.1.13] exists" | |
| 28 | 新增: | |
| 29 | 新增:info() { | |
| 30 | 新增: plutil -extract "$2" raw -o - "$1/Contents/Info.plist" | |
| 31 | 新增:} | |
| 32 | 新增: | |
| 33 | 新增:verify_app() { | |
| 34 | 新增: [[ -d $1 && ! -L $1 ]] || fail "Expected a Claude.app directory at $1." | |
| 35 | 新增: [[ $(info "$1" CFBundleIdentifier) == "$bundle_id" ]] || fail "Unexpected Claude bundle identifier." | |
| 36 | 新增: codesign --verify --deep --strict "$1" | |
| 37 | 新增: codesign --verify --strict -R "=$requirement" "$1" | |
| 38 | 新增:} | |
| 39 | 新增: | |
| 40 | 新增:report() { | |
| 41 | 新增: printf 'status=%s\nversion=%s\nbuild=%s\nbundle_id=%s\nteam=%s\n' \ | |
| 42 | 新增: "$1" "$(info "$app" CFBundleShortVersionString)" "$(info "$app" CFBundleVersion)" "$bundle_id" "$team" | |
| 43 | 新增:} | |
| 44 | 新增: | |
| 45 | 新增:case "$1" in | |
| 46 | 新增: inspect) | |
| 47 | 新增: [[ -e $app || -L $app ]] || { printf 'status=absent\n'; exit 3; } | |
| 48 | 新增: verify_app "$app" | |
| 49 | 新增: report installed | |
| 50 | 新增: ;; | |
| 51 | 新增: install) | |
| 52 | 新增: [[ $EUID == 0 ]] || fail "Run install as root inside the guest." | |
| 53 | 新增: dmg=$2 | |
| 54 | 新增: [[ $dmg == /* && -f $dmg ]] || fail "Supply the absolute path of the downloaded Claude DMG." | |
| 55 | 新增: exec 9>/var/run/cage-claude-install.lock | |
| 56 | 新增: lockf -s -t 0 9 || fail "A Claude installation is in progress." | |
| 57 | 新增: stage=$(mktemp -d /Applications/.cage-claude.XXXXXXXX) | |
| 58 | 新增: mountdir="$stage/media" | |
| 59 | 新增: mkdir "$mountdir" | |
| 60 | 新增: cleanup() { | |
| 61 | 新增: # Mounts are read-only. Keep the directory if the system cannot detach. | |
| 62 | 新增: if [[ $(stat -f '%d' "$mountdir") != "$(stat -f '%d' "$stage")" ]]; then | |
| 63 | 新增: hdiutil detach "$mountdir" >/dev/null || { printf 'Unable to detach %s\n' "$mountdir" >&2; return; } | |
| 64 | 新增: fi | |
| 65 | 新增: rm -rf "$stage" | |
| 66 | 新增: } | |
| 67 | 新增: trap cleanup EXIT | |
| 68 | 新增: trap 'exit 1' HUP INT TERM | |
| 69 | 新增: hdiutil attach -readonly -nobrowse -noautoopen -mountpoint "$mountdir" "$dmg" >/dev/null | |
| 70 | 新增: source_app="$mountdir/Claude.app" | |
| 71 | 新增: verify_app "$source_app" | |
| 72 | 新增: # renamex_np publishes the verified copy on the same filesystem. With an | |
| 73 | 新增: # existing app, RENAME_SWAP retains it in staging until the swap succeeds. | |
| 74 | 新增: rename_flag=4 # RENAME_EXCL | |
| 75 | 新增: if [[ -e $app || -L $app ]]; then | |
| 76 | 新增: verify_app "$app" | |
| 77 | 新增: if [[ $(info "$source_app" CFBundleVersion) == "$(info "$app" CFBundleVersion)" && | |
| 78 | 新增: $(info "$source_app" CFBundleShortVersionString) == "$(info "$app" CFBundleShortVersionString)" ]]; then | |
| 79 | 新增: report installed | |
| 80 | 新增: exit 0 | |
| 81 | 新增: fi | |
| 82 | 新增: if pgrep -f '^/Applications/Claude\.app/Contents/MacOS/Claude([[:space:]]|$)' >/dev/null; then | |
| 83 | 新增: fail "Quit the running guest Claude app before installing another version." | |
| 84 | 新增: fi | |
| 85 | 新增: rename_flag=2 # RENAME_SWAP | |
| 86 | 新增: fi | |
| 87 | 新增: staged_app="$stage/Claude.app" | |
| 88 | 新增: ditto "$source_app" "$staged_app" | |
| 89 | 新增: chown -R -P root:wheel "$staged_app" | |
| 90 | 新增: verify_app "$staged_app" | |
| 91 | 新增: /usr/bin/osascript -l JavaScript - "$staged_app" "$app" "$rename_flag" <<'JXA' | |
| 92 | 新增:ObjC.bindFunction("renamex_np", ["int", ["char *", "char *", "uint32_t"]]); | |
| 93 | 新增:function run(args) { | |
| 94 | 新增: if ($.renamex_np(args[0], args[1], Number(args[2])) !== 0) { | |
| 95 | 新增: throw Error("Could not publish Claude.app; previous installation preserved."); | |
| 96 | 新增: } | |
| 97 | 新增:} | |
| 98 | 新增:JXA | |
| 99 | 新增: report installed | |
| 100 | 新增: ;; | |
| 101 | 新增: launch) | |
| 102 | 新增: verify_app "$app" | |
| 103 | 新增: gui_uid=$(stat -f '%u' /dev/console) | |
| 104 | 新增: if (( gui_uid < 500 )) || ! launchctl print "gui/$gui_uid" >/dev/null 2>&1; then | |
| 105 | 新增: printf 'status=requires_gui_login\nLog in to the guest macOS desktop first.\n' >&2 | |
| 106 | 新增: exit 4 | |
| 107 | 新增: fi | |
| 108 | 新增: if [[ $EUID == 0 ]]; then | |
| 109 | 新增: launchctl asuser "$gui_uid" sudo -n -H -u "#$gui_uid" -- /usr/bin/open "$app" | |
| 110 | 新增: elif [[ $EUID == "$gui_uid" ]]; then | |
| 111 | 新增: /usr/bin/open "$app" | |
| 112 | 新增: else | |
| 113 | 新增: fail "Run launch as root or the guest console user." | |
| 114 | 新增: fi | |
| 115 | 新增: for ((attempt=0; attempt<20; attempt++)); do | |
| 116 | 新增: if pid=$(pgrep -o -U "$gui_uid" -f '^/Applications/Claude\.app/Contents/MacOS/Claude([[:space:]]|$)'); then | |
| 117 | 新增: report running | |
| 118 | 新增: printf 'pid=%s\n' "$pid" | |
| 119 | 新增: exit 0 | |
| 120 | 新增: fi | |
| 121 | 新增: sleep 1 | |
| 122 | 新增: done | |
| 123 | 新增: fail "The Claude application process did not start in the guest GUI session." | |
| 124 | 新增: ;; | |
| 125 | 新增:esac | |
| @@ -0,0 +1,168 @@ | ||
| 1 | 新增:#requires -Version 5.1 | |
| 2 | 新增:<# | |
| 3 | 新增:.SYNOPSIS | |
| 4 | 新增:Inspect, install or launch the official x64 Claude Desktop MSIX as the current user. | |
| 5 | 新增:.DESCRIPTION | |
| 6 | 新增:Run with 64-bit Windows PowerShell inside the target VM. For Install and Launch, | |
| 7 | 新增:pass the Id obtained independently from Get-VM on the Hyper-V host. | |
| 8 | 新增:The full MSIX includes a service. Register it in an elevated session for the | |
| 9 | 新增:target guest user, or provision it in the guest image before that user signs in. | |
| 10 | 新增:Launch in the user's normal interactive session. | |
| 11 | 新增:Download the local MSIX from https://support.claude.com/en/articles/12622703 . | |
| 12 | 新增:#> | |
| 13 | 新增:[CmdletBinding()] | |
| 14 | 新增:param( | |
| 15 | 新增: [ValidateSet('Inspect', 'Install', 'Launch')][string]$Action = 'Inspect', | |
| 16 | 新增: [Guid]$ExpectedVMId = [Guid]::Empty, | |
| 17 | 新增: [string]$MsixPath | |
| 18 | 新增:) | |
| 19 | 新增:$ErrorActionPreference = 'Stop' | |
| 20 | 新增: | |
| 21 | 新增:# Verified against AppxManifest.xml and AppxSignature.p7x in the official | |
| 22 | 新增:# Windows x64 4.23118.0.0 MSIX. The package also contains helper applications. | |
| 23 | 新增:$publisher = 'CN="Anthropic, PBC", O="Anthropic, PBC", L=San Francisco, S=California, C=US, SERIALNUMBER=4860621, OID.2.5.4.15=Private Organization, OID.1.3.6.1.4.1.311.60.2.1.2=Delaware, OID.1.3.6.1.4.1.311.60.2.1.3=US' | |
| 24 | 新增:$packageFamily = 'Claude_pzs8sxrjxfjjc' | |
| 25 | 新增: | |
| 26 | 新增:function Assert-TargetGuest([Guid]$expected) { | |
| 27 | 新增: if ($expected -eq [Guid]::Empty) { | |
| 28 | 新增: throw 'Pass -ExpectedVMId with the target VM Id from Get-VM on the Hyper-V host.' | |
| 29 | 新增: } | |
| 30 | 新增: $system = Get-CimInstance Win32_ComputerSystem | |
| 31 | 新增: if ($system.Manufacturer -ne 'Microsoft Corporation' -or $system.Model -ne 'Virtual Machine') { | |
| 32 | 新增: throw 'This operation requires a Hyper-V guest.' | |
| 33 | 新增: } | |
| 34 | 新增: $kvp = Get-ItemProperty -LiteralPath 'HKLM:\SOFTWARE\Microsoft\Virtual Machine\Guest\Parameters' -Name VirtualMachineId | |
| 35 | 新增: $actual = [Guid]::Empty | |
| 36 | 新增: if (![Guid]::TryParse($kvp.VirtualMachineId, [ref]$actual) -or $expected -ne $actual) { | |
| 37 | 新增: throw 'The Hyper-V guest VM Id does not match the host-provided target.' | |
| 38 | 新增: } | |
| 39 | 新增:} | |
| 40 | 新增: | |
| 41 | 新增:function Assert-ClaudeManifest([xml]$manifest) { | |
| 42 | 新增: $ns = [Xml.XmlNamespaceManager]::new($manifest.NameTable) | |
| 43 | 新增: $ns.AddNamespace('m', 'http://schemas.microsoft.com/appx/manifest/foundation/windows10') | |
| 44 | 新增: $identity = $manifest.SelectSingleNode('/m:Package/m:Identity', $ns) | |
| 45 | 新增: $app = $manifest.SelectSingleNode('/m:Package/m:Applications/m:Application[@Id="Claude"]', $ns) | |
| 46 | 新增: if (!$identity -or $identity.GetAttribute('Name') -cne 'Claude' -or | |
| 47 | 新增: $identity.GetAttribute('Publisher') -cne $publisher -or | |
| 48 | 新增: $identity.GetAttribute('ProcessorArchitecture') -ne 'x64' -or !$app -or | |
| 49 | 新增: $app.GetAttribute('Executable') -ine 'app\Claude.exe' -or | |
| 50 | 新增: $app.GetAttribute('EntryPoint') -cne 'Windows.FullTrustApplication') { | |
| 51 | 新增: throw 'Unexpected Claude x64 package identity or application entry point.' | |
| 52 | 新增: } | |
| 53 | 新增: return [version]$identity.GetAttribute('Version') | |
| 54 | 新增:} | |
| 55 | 新增: | |
| 56 | 新增:function Assert-ClaudeSignature($signature) { | |
| 57 | 新增: if ($signature.Status -ne 'Valid' -or !$signature.SignerCertificate) { | |
| 58 | 新增: throw 'Windows did not validate the MSIX signature.' | |
| 59 | 新增: } | |
| 60 | 新增: # Decode both subjects with the same Windows formatter, including the | |
| 61 | 新增: # organization registration number. A matching common name alone is insufficient. | |
| 62 | 新增: $expected = [Security.Cryptography.X509Certificates.X500DistinguishedName]::new($publisher) | |
| 63 | 新增: $format = [Security.Cryptography.X509Certificates.X500DistinguishedNameFlags]::Reversed | |
| 64 | 新增: if ($signature.SignerCertificate.SubjectName.Decode($format) -cne $expected.Decode($format)) { | |
| 65 | 新增: throw 'The trusted signing certificate does not match the Anthropic publisher.' | |
| 66 | 新增: } | |
| 67 | 新增:} | |
| 68 | 新增: | |
| 69 | 新增:function Get-RegisteredClaude { | |
| 70 | 新增: $packages = @(Get-AppxPackage -Name Claude | Where-Object PackageFamilyName -ceq $packageFamily) | |
| 71 | 新增: if ($packages.Count -eq 0) { return } | |
| 72 | 新增: if ($packages.Count -ne 1) { throw 'Multiple registrations found for the Claude package family.' } | |
| 73 | 新增: $pkg = $packages[0] | |
| 74 | 新增: if ($pkg.Publisher -cne $publisher -or $pkg.IsDevelopmentMode -or $pkg.IsPartiallyStaged -or | |
| 75 | 新增: $pkg.SignatureKind -notin 'Developer','Store','Enterprise' -or $pkg.Status -ne 'Ok') { | |
| 76 | 新增: throw 'The registered Claude package is unsigned, unhealthy or has an unexpected publisher.' | |
| 77 | 新增: } | |
| 78 | 新增: $version = Assert-ClaudeManifest (Get-AppxPackageManifest -Package $pkg.PackageFullName) | |
| 79 | 新增: return [pscustomobject]@{ | |
| 80 | 新增: Registered = $true | |
| 81 | 新增: Version = $version.ToString() | |
| 82 | 新增: Aumid = "$packageFamily!Claude" | |
| 83 | 新增: Executable = Join-Path $pkg.InstallLocation 'app\Claude.exe' | |
| 84 | 新增: } | |
| 85 | 新增:} | |
| 86 | 新增: | |
| 87 | 新增:function Get-VerifiedClaudeMsixVersion([IO.FileInfo]$file, [IO.Stream]$handle) { | |
| 88 | 新增: Assert-ClaudeSignature (Get-AuthenticodeSignature -LiteralPath $file.FullName) | |
| 89 | 新增: Add-Type -AssemblyName System.IO.Compression | |
| 90 | 新增: $zip = [IO.Compression.ZipArchive]::new($handle, 'Read', $true) | |
| 91 | 新增: try { | |
| 92 | 新增: $entry = $zip.GetEntry('AppxManifest.xml') | |
| 93 | 新增: if (!$entry) { throw 'The MSIX is missing AppxManifest.xml.' } | |
| 94 | 新增: $stream = $entry.Open() | |
| 95 | 新增: try { | |
| 96 | 新增: $manifest = [xml]::new() | |
| 97 | 新增: $manifest.XmlResolver = $null | |
| 98 | 新增: $manifest.Load($stream) | |
| 99 | 新增: return (Assert-ClaudeManifest $manifest) | |
| 100 | 新增: } finally { $stream.Dispose() } | |
| 101 | 新增: } finally { $zip.Dispose() } | |
| 102 | 新增:} | |
| 103 | 新增: | |
| 104 | 新增:function Install-ClaudeMsix([string]$path) { | |
| 105 | 新增: if (!$path) { throw 'Install requires -MsixPath with a locally downloaded x64 MSIX.' } | |
| 106 | 新增: $file = Get-Item -LiteralPath $path | |
| 107 | 新增: if ($file -isnot [IO.FileInfo] -or $file.Extension -ne '.msix' -or | |
| 108 | 新增: $file.FullName.StartsWith('\\') -or | |
| 109 | 新增: [IO.DriveInfo]::new($file.Directory.Root.FullName).DriveType -eq 'Network') { | |
| 110 | 新增: throw 'Select a local .msix file on the guest.' | |
| 111 | 新增: } | |
| 112 | 新增: # Keep the file read-locked while Windows checks and registers the package. | |
| 113 | 新增: $handle = [IO.File]::Open($file.FullName, 'Open', 'Read', 'Read') | |
| 114 | 新增: try { | |
| 115 | 新增: $version = Get-VerifiedClaudeMsixVersion $file $handle | |
| 116 | 新增: $registered = Get-RegisteredClaude | |
| 117 | 新增: if ($registered -and [version]$registered.Version -ge $version) { return $registered } | |
| 118 | 新增: try { Add-AppxPackage -Path $file.FullName } catch { | |
| 119 | 新增: if ($_.Exception.HResult.ToString('X8') -eq '80073D28' -or $_.ToString() -match '\b0x80073D28\b') { | |
| 120 | 新增: throw '0x80073D28: The Claude MSIX service requires guest administrator rights. Register it elevated as this guest user, or provision it in the guest image for standard users.' | |
| 121 | 新增: } | |
| 122 | 新增: throw | |
| 123 | 新增: } | |
| 124 | 新增: $registered = Get-RegisteredClaude | |
| 125 | 新增: if (!$registered -or [version]$registered.Version -lt $version) { | |
| 126 | 新增: throw 'Windows did not register the expected version for this user.' | |
| 127 | 新增: } | |
| 128 | 新增: return $registered | |
| 129 | 新增: } finally { $handle.Dispose() } | |
| 130 | 新增:} | |
| 131 | 新增: | |
| 132 | 新增:function Open-ClaudeWindow($registered) { | |
| 133 | 新增: if (!$registered) { throw 'Claude Desktop is not registered for this user.' } | |
| 134 | 新增: $session = [Diagnostics.Process]::GetCurrentProcess().SessionId | |
| 135 | 新增: $shell = Get-Process -Name explorer -ErrorAction SilentlyContinue | Where-Object SessionId -eq $session | |
| 136 | 新增: if ($session -eq 0 -or !$shell -or ![Environment]::UserInteractive) { | |
| 137 | 新增: throw 'Launch requires a signed-in desktop session. Open PowerShell in the guest console.' | |
| 138 | 新增: } | |
| 139 | 新增: $explorer = Join-Path ([Environment]::GetFolderPath('Windows')) 'explorer.exe' | |
| 140 | 新增: Start-Process -FilePath $explorer -ArgumentList ('shell:AppsFolder\' + $registered.Aumid) | |
| 141 | 新增: $timer = [Diagnostics.Stopwatch]::StartNew() | |
| 142 | 新增: do { | |
| 143 | 新增: $window = Get-Process -Name Claude -ErrorAction SilentlyContinue | Where-Object { | |
| 144 | 新增: $_.SessionId -eq $session -and $_.MainWindowHandle -ne 0 -and $_.Path -eq $registered.Executable | |
| 145 | 新增: } | Select-Object -First 1 | |
| 146 | 新增: if ($window) { | |
| 147 | 新增: return [pscustomobject]@{ Aumid = $registered.Aumid; WindowProcessId = $window.Id } | |
| 148 | 新增: } | |
| 149 | 新增: Start-Sleep -Milliseconds 400 | |
| 150 | 新增: } while ($timer.Elapsed.TotalSeconds -lt 30) | |
| 151 | 新增: throw 'Activation was requested, but no window from the registered Claude executable appeared within 30 seconds.' | |
| 152 | 新增:} | |
| 153 | 新增: | |
| 154 | 新增:if ($MyInvocation.InvocationName -eq '.') { return } # Allow isolated validation tests to load the checks. | |
| 155 | 新增:if ([Environment]::OSVersion.Platform -ne 'Win32NT' -or ![Environment]::Is64BitProcess) { | |
| 156 | 新增: throw 'Run this script in 64-bit Windows PowerShell.' | |
| 157 | 新增:} | |
| 158 | 新增:if ($Action -ne 'Install' -and $MsixPath) { throw 'Only Install accepts -MsixPath.' } | |
| 159 | 新增:if ($Action -ne 'Inspect') { Assert-TargetGuest $ExpectedVMId } | |
| 160 | 新增:switch ($Action) { | |
| 161 | 新增: 'Inspect' { | |
| 162 | 新增: $registered = Get-RegisteredClaude | |
| 163 | 新增: if (!$registered) { $registered = [pscustomobject]@{ Registered = $false } } | |
| 164 | 新增: $registered | ConvertTo-Json | |
| 165 | 新增: } | |
| 166 | 新增: 'Install' { Install-ClaudeMsix $MsixPath | ConvertTo-Json } | |
| 167 | 新增: 'Launch' { Open-ClaudeWindow (Get-RegisteredClaude) | ConvertTo-Json } | |
| 168 | 新增:} | |
| @@ -0,0 +1,101 @@ | ||
| 1 | 新增:#requires -Version 5.1 | |
| 2 | 新增:# Run on any platform with PowerShell. The tests never call Windows deployment APIs. | |
| 3 | 新增:$ErrorActionPreference = 'Stop' | |
| 4 | 新增:. (Join-Path $PSScriptRoot 'claude-desktop-windows.ps1') | |
| 5 | 新增: | |
| 6 | 新增:function Expect-Failure([scriptblock]$action, [string]$reason) { | |
| 7 | 新增: try { & $action } catch { | |
| 8 | 新增: if ($_.Exception.Message.Contains($reason)) { return } | |
| 9 | 新增: throw | |
| 10 | 新增: } | |
| 11 | 新增: throw "Expected rejection: $reason" | |
| 12 | 新增:} | |
| 13 | 新增: | |
| 14 | 新增:$subject = [Security.Cryptography.X509Certificates.X500DistinguishedName]::new($publisher) | |
| 15 | 新增:$signature = [pscustomobject]@{ Status = 'Valid'; SignerCertificate = @{ SubjectName = $subject } } | |
| 16 | 新增:Assert-ClaudeSignature $signature | |
| 17 | 新增:$signature.Status = 'HashMismatch' | |
| 18 | 新增:Expect-Failure { Assert-ClaudeSignature $signature } 'did not validate' | |
| 19 | 新增:$signature.Status = 'Valid' | |
| 20 | 新增:$lookalike = $publisher.Replace('4860621', '1234567') | |
| 21 | 新增:$signature.SignerCertificate.SubjectName = [Security.Cryptography.X509Certificates.X500DistinguishedName]::new($lookalike) | |
| 22 | 新增:Expect-Failure { Assert-ClaudeSignature $signature } 'does not match' | |
| 23 | 新增: | |
| 24 | 新增:$manifest = [xml]@' | |
| 25 | 新增:<Package xmlns="http://schemas.microsoft.com/appx/manifest/foundation/windows10"> | |
| 26 | 新增: <Identity Name="Claude" Version="4.23118.0.0" ProcessorArchitecture="x64"/> | |
| 27 | 新增: <Applications> | |
| 28 | 新增: <Application Id="SshProxy" Executable="app\resources\claude-ssh-proxy.exe"/> | |
| 29 | 新增: <Application Id="Claude" Executable="app\Claude.exe" EntryPoint="Windows.FullTrustApplication"/> | |
| 30 | 新增: </Applications> | |
| 31 | 新增:</Package> | |
| 32 | 新增:'@ | |
| 33 | 新增:$manifest.Package.Identity.SetAttribute('Publisher', $publisher) | |
| 34 | 新增:if ((Assert-ClaudeManifest $manifest) -ne [version]'4.23118.0.0') { throw 'Version mismatch.' } | |
| 35 | 新增:$wrongApp = $manifest.Clone() | |
| 36 | 新增:$wrongApp.Package.Applications.Application[1].SetAttribute('Executable', 'app\helper.exe') | |
| 37 | 新增:Expect-Failure { Assert-ClaudeManifest $wrongApp } 'entry point' | |
| 38 | 新增: | |
| 39 | 新增:function Get-AppxPackage { $pkg } | |
| 40 | 新增:function Get-AppxPackageManifest { $manifest } | |
| 41 | 新增:$pkg = [pscustomobject]@{ | |
| 42 | 新增: PackageFamilyName = 'OtherFamily'; IsDevelopmentMode = $false; IsPartiallyStaged = $false | |
| 43 | 新增: SignatureKind = 'Developer'; Status = 'Ok'; Publisher = $publisher | |
| 44 | 新增: PackageFullName = 'test-fixture'; InstallLocation = $PSScriptRoot | |
| 45 | 新增:} | |
| 46 | 新增:if (Get-RegisteredClaude) { throw 'An unrelated package was accepted.' } | |
| 47 | 新增:$pkg.PackageFamilyName = $packageFamily | |
| 48 | 新增:if ((Get-RegisteredClaude).Aumid -cne 'Claude_pzs8sxrjxfjjc!Claude') { throw 'Incorrect AUMID.' } | |
| 49 | 新增:$pkg.IsDevelopmentMode = $true | |
| 50 | 新增:Expect-Failure { Get-RegisteredClaude } 'registered Claude package' | |
| 51 | 新增: | |
| 52 | 新增:# Execute the actual install path against a local archive. Mock just the | |
| 53 | 新增:# operating-system signature and registration results, never deploy this fixture. | |
| 54 | 新增:$fixture = Join-Path ([IO.Path]::GetTempPath()) (([Guid]::NewGuid().ToString()) + '.msix') | |
| 55 | 新增:$installedCount = 0 | |
| 56 | 新增:function Get-AuthenticodeSignature { $signature } | |
| 57 | 新增:function Add-AppxPackage { | |
| 58 | 新增: if ($deploymentError) { throw $deploymentError } | |
| 59 | 新增: $script:installedCount++ | |
| 60 | 新增: $script:pkg.PackageFamilyName = $packageFamily | |
| 61 | 新增:} | |
| 62 | 新增:try { | |
| 63 | 新增: Add-Type -AssemblyName System.IO.Compression | |
| 64 | 新增: $handle = [IO.File]::Open($fixture, 'CreateNew', 'Write', 'None') | |
| 65 | 新增: try { | |
| 66 | 新增: $zip = [IO.Compression.ZipArchive]::new($handle, 'Create', $true) | |
| 67 | 新增: try { | |
| 68 | 新增: $stream = $zip.CreateEntry('AppxManifest.xml').Open() | |
| 69 | 新增: try { $manifest.Save($stream) } finally { $stream.Dispose() } | |
| 70 | 新增: } finally { $zip.Dispose() } | |
| 71 | 新增: } finally { $handle.Dispose() } | |
| 72 | 新增: $signature.Status = 'NotSigned' | |
| 73 | 新增: Expect-Failure { Install-ClaudeMsix $fixture } 'did not validate' | |
| 74 | 新增: $signature.Status = 'Valid' | |
| 75 | 新增: Expect-Failure { Install-ClaudeMsix $fixture } 'does not match' | |
| 76 | 新增: if ($installedCount -ne 0) { throw 'An untrusted package reached Add-AppxPackage.' } | |
| 77 | 新增: $signature.SignerCertificate.SubjectName = $subject | |
| 78 | 新增: $pkg.IsDevelopmentMode = $false | |
| 79 | 新增: $pkg.PackageFamilyName = 'absent' | |
| 80 | 新增: $deploymentError = 'Deployment failed: 0x80073D28' | |
| 81 | 新增: Expect-Failure { Install-ClaudeMsix $fixture } 'requires guest administrator rights' | |
| 82 | 新增: $deploymentError = 'Deployment failed: 0x80073CF6' | |
| 83 | 新增: Expect-Failure { Install-ClaudeMsix $fixture } '0x80073CF6' | |
| 84 | 新增: $deploymentError = $null | |
| 85 | 新增: $first = Install-ClaudeMsix $fixture | |
| 86 | 新增: $again = Install-ClaudeMsix $fixture | |
| 87 | 新增: if (!$first.Registered -or !$again.Registered -or $installedCount -ne 1) { | |
| 88 | 新增: throw 'Expected exactly one registration after two Install actions.' | |
| 89 | 新增: } | |
| 90 | 新增:} finally { if ([IO.File]::Exists($fixture)) { [IO.File]::Delete($fixture) } } | |
| 91 | 新增: | |
| 92 | 新增:$target = [Guid]::NewGuid() | |
| 93 | 新增:$kvpId = $target.ToString() | |
| 94 | 新增:$computer = @{ Manufacturer = 'Microsoft Corporation'; Model = 'Virtual Machine' } | |
| 95 | 新增:function Get-CimInstance { $computer } | |
| 96 | 新增:function Get-ItemProperty { @{ VirtualMachineId = $kvpId } } | |
| 97 | 新增:Assert-TargetGuest $target | |
| 98 | 新增:Expect-Failure { Assert-TargetGuest ([Guid]::NewGuid()) } 'does not match' | |
| 99 | 新增:$computer.Model = 'Surface' | |
| 100 | 新增:Expect-Failure { Assert-TargetGuest $target } 'requires a Hyper-V guest' | |
| 101 | 新增:Write-Output 'Passed Claude manifest, signing, repeat install, registration and Hyper-V guest identity checks (simulated).' | |
| @@ -0,0 +1,140 @@ | ||
| 1 | 新增:// Capture one visible Claude Desktop window to stdout inside a Cage macOS VM. | |
| 2 | 新增:// Build with swiftc -parse-as-library -target arm64-apple-macos14.0. | |
| 3 | 新增:import AppKit | |
| 4 | 新增:import ImageIO | |
| 5 | 新增:import ScreenCaptureKit | |
| 6 | 新增:import Security | |
| 7 | 新增:import UniformTypeIdentifiers | |
| 8 | 新增: | |
| 9 | 新增:private let bundleID = "com.anthropic.claudefordesktop" | |
| 10 | 新增: | |
| 11 | 新增:struct Failure: Error { | |
| 12 | 新增: let code: Int32 | |
| 13 | 新增: let message: String | |
| 14 | 新增: init(_ code: Int32, _ message: String) { | |
| 15 | 新增: self.code = code | |
| 16 | 新增: self.message = message | |
| 17 | 新增: } | |
| 18 | 新增:} | |
| 19 | 新增: | |
| 20 | 新增:func requireGuest() throws { | |
| 21 | 新增: var model = [CChar](repeating: 0, count: 256) | |
| 22 | 新增: var count = model.count | |
| 23 | 新增: guard sysctlbyname("hw.model", &model, &count, nil, 0) == 0, | |
| 24 | 新增: String(cString: model).range(of: #"^VirtualMac[0-9]+,[0-9]+$"#, options: .regularExpression) != nil else { | |
| 25 | 新增: throw Failure(2, "not_cage_guest: Run inside a Cage virtual Mac.") | |
| 26 | 新增: } | |
| 27 | 新增: let fd = open("/var/db/cage-guest-os", O_RDONLY | O_NOFOLLOW | O_NONBLOCK) | |
| 28 | 新增: guard fd >= 0 else { throw Failure(2, "not_cage_guest: Missing guest marker.") } | |
| 29 | 新增: let marker = FileHandle(fileDescriptor: fd, closeOnDealloc: true) | |
| 30 | 新增: var metadata = stat() | |
| 31 | 新增: guard fstat(fd, &metadata) == 0, metadata.st_mode & S_IFMT == S_IFREG, | |
| 32 | 新增: metadata.st_uid == 0, metadata.st_mode & 0o022 == 0, | |
| 33 | 新增: (5...6).contains(metadata.st_size), | |
| 34 | 新增: let bytes = try marker.read(upToCount: 6), [Data("macos".utf8), Data("macos\n".utf8)].contains(bytes) else { | |
| 35 | 新增: throw Failure(2, "not_cage_guest: Invalid guest marker.") | |
| 36 | 新增: } | |
| 37 | 新增:} | |
| 38 | 新增: | |
| 39 | 新增:func claudeSigningRequirement() throws -> SecRequirement { | |
| 40 | 新增: let expression = #"anchor apple generic and identifier "com.anthropic.claudefordesktop" and certificate leaf[subject.OU] = "Q6L2SF6YDW" and certificate 1[field.1.2.840.113635.100.6.2.6] exists and certificate leaf[field.1.2.840.113635.100.6.1.13] exists"# | |
| 41 | 新增: var requirement: SecRequirement? | |
| 42 | 新增: guard SecRequirementCreateWithString(expression as CFString, [], &requirement) == errSecSuccess, let requirement else { | |
| 43 | 新增: throw Failure(5, "identity_error: Could not construct the Claude signing requirement.") | |
| 44 | 新增: } | |
| 45 | 新增: return requirement | |
| 46 | 新增:} | |
| 47 | 新增: | |
| 48 | 新增:func claudePIDs() throws -> Set<pid_t> { | |
| 49 | 新增: var console = stat() | |
| 50 | 新增: var attributes: SessionAttributeBits = [] | |
| 51 | 新增: guard lstat("/dev/console", &console) == 0, console.st_uid >= 500, console.st_uid == geteuid(), | |
| 52 | 新增: SessionGetInfo(callerSecuritySession, nil, &attributes) == errSecSuccess, | |
| 53 | 新增: attributes.contains(.sessionHasGraphicAccess) else { | |
| 54 | 新增: throw Failure(4, "requires_gui_login: Run as the logged-in guest desktop user in their GUI session.") | |
| 55 | 新增: } | |
| 56 | 新增: let path = URL(fileURLWithPath: "/Applications/Claude.app").resolvingSymlinksInPath() | |
| 57 | 新增: let apps = NSRunningApplication.runningApplications(withBundleIdentifier: bundleID).filter { | |
| 58 | 新增: $0.bundleURL?.resolvingSymlinksInPath() == path && !$0.isTerminated | |
| 59 | 新增: } | |
| 60 | 新增: guard !apps.isEmpty else { throw Failure(3, "not_running: Launch /Applications/Claude.app in the guest.") } | |
| 61 | 新增: let requirement = try claudeSigningRequirement() | |
| 62 | 新增: let validPIDs = apps.compactMap { app -> pid_t? in | |
| 63 | 新增: let attributes = [kSecGuestAttributePid: app.processIdentifier] as CFDictionary | |
| 64 | 新增: var code: SecCode? | |
| 65 | 新增: guard SecCodeCopyGuestWithAttributes(nil, attributes, [], &code) == errSecSuccess, let code, | |
| 66 | 新增: SecCodeCheckValidity(code, [], requirement) == errSecSuccess else { return nil } | |
| 67 | 新增: return app.processIdentifier | |
| 68 | 新增: } | |
| 69 | 新增: guard !validPIDs.isEmpty else { throw Failure(5, "identity_error: The running app failed Anthropic signature verification.") } | |
| 70 | 新增: return Set(validPIDs) | |
| 71 | 新增:} | |
| 72 | 新增: | |
| 73 | 新增:func claudeWindow() async throws -> SCWindow { | |
| 74 | 新增: try requireGuest() | |
| 75 | 新增: let pids = try claudePIDs() | |
| 76 | 新增: guard CGPreflightScreenCaptureAccess() else { | |
| 77 | 新增: throw Failure(6, "screen_recording_permission: Authorize this capture tool in the guest's Privacy & Security settings.") | |
| 78 | 新增: } | |
| 79 | 新增: let content = try await SCShareableContent.excludingDesktopWindows(true, onScreenWindowsOnly: true) | |
| 80 | 新增: let windows = content.windows.filter { window in | |
| 81 | 新增: guard window.isOnScreen, window.windowLayer == 0, !window.frame.isEmpty, | |
| 82 | 新增: let owner = window.owningApplication else { return false } | |
| 83 | 新增: return owner.bundleIdentifier == bundleID && pids.contains(owner.processID) | |
| 84 | 新增: } | |
| 85 | 新增: guard let window = windows.max(by: { $0.frame.width * $0.frame.height < $1.frame.width * $1.frame.height }) else { | |
| 86 | 新增: throw Failure(7, "no_visible_window: Open a Claude window on the guest desktop.") | |
| 87 | 新增: } | |
| 88 | 新增: return window | |
| 89 | 新增:} | |
| 90 | 新增: | |
| 91 | 新增:func screenshot(_ window: SCWindow, filter selected: SCContentFilter? = nil) async throws -> Data { | |
| 92 | 新增: let filter = selected ?? SCContentFilter(desktopIndependentWindow: window) | |
| 93 | 新增: let config = SCStreamConfiguration() | |
| 94 | 新增: config.width = max(1, Int((filter.contentRect.width * CGFloat(filter.pointPixelScale)).rounded())) | |
| 95 | 新增: config.height = max(1, Int((filter.contentRect.height * CGFloat(filter.pointPixelScale)).rounded())) | |
| 96 | 新增: config.ignoreShadowsSingleWindow = true | |
| 97 | 新增: config.showsCursor = false | |
| 98 | 新增: if #available(macOS 14.2, *) { config.includeChildWindows = false } | |
| 99 | 新增: let image = try await SCScreenshotManager.captureImage(contentFilter: filter, configuration: config) | |
| 100 | 新增: return try pngData(image) | |
| 101 | 新增:} | |
| 102 | 新增: | |
| 103 | 新增:func pngData(_ image: CGImage) throws -> Data { | |
| 104 | 新增: try encodedImage(image, type: .png) | |
| 105 | 新增:} | |
| 106 | 新增: | |
| 107 | 新增:func encodedImage(_ image: CGImage, type: UTType, properties: CFDictionary? = nil) throws -> Data { | |
| 108 | 新增: let data = NSMutableData() | |
| 109 | 新增: guard let encoder = CGImageDestinationCreateWithData(data, type.identifier as CFString, 1, nil) else { | |
| 110 | 新增: throw Failure(8, "capture_failed: Could not create an image encoder.") | |
| 111 | 新增: } | |
| 112 | 新增: CGImageDestinationAddImage(encoder, image, properties) | |
| 113 | 新增: guard CGImageDestinationFinalize(encoder) else { throw Failure(8, "capture_failed: Could not encode the window.") } | |
| 114 | 新增: return data as Data | |
| 115 | 新增:} | |
| 116 | 新增: | |
| 117 | 新增:#if !GUEST_WINDOW_APP | |
| 118 | 新增:@main | |
| 119 | 新增:struct ClaudeWindow { | |
| 120 | 新增: static func main() async { | |
| 121 | 新增: do { | |
| 122 | 新增: let png = try await screenshot(claudeWindow()) | |
| 123 | 新增: try FileHandle.standardOutput.write(contentsOf: png) | |
| 124 | 新增: } catch { | |
| 125 | 新增: let failure: Failure | |
| 126 | 新增: if let known = error as? Failure { | |
| 127 | 新增: failure = known | |
| 128 | 新增: } else if (error as NSError).domain == SCStreamErrorDomain && | |
| 129 | 新增: (error as NSError).code == SCStreamError.userDeclined.rawValue { | |
| 130 | 新增: failure = Failure(6, "screen_recording_permission: The guest user declined screen capture.") | |
| 131 | 新增: } else { | |
| 132 | 新增: failure = Failure(8, "capture_failed: \(error.localizedDescription)") | |
| 133 | 新增: } | |
| 134 | 新增: FileHandle.standardError.write(Data("\(failure.message)\n".utf8)) | |
| 135 | 新增: exit(failure.code) | |
| 136 | 新增: } | |
| 137 | 新增: } | |
| 138 | 新增:} | |
| 139 | 新增: | |
| 140 | 新增:#endif | |
| @@ -0,0 +1,160 @@ | ||
| 1 | 新增:#requires -Version 5.1 | |
| 2 | 新增:<# | |
| 3 | 新增:.SYNOPSIS | |
| 4 | 新增:Save one PNG of the signed-in guest user's registered Claude Desktop window. | |
| 5 | 新增:.DESCRIPTION | |
| 6 | 新增:Run in 64-bit Windows PowerShell in an unlocked Hyper-V guest desktop session. | |
| 7 | 新增:Pass the VM ID obtained independently on the host. OutputPath must name a new | |
| 8 | 新增:.png directly inside this guest user's temporary directory. A failed capture | |
| 9 | 新增:does not publish a PNG. | |
| 10 | 新增:#> | |
| 11 | 新增:[CmdletBinding()] | |
| 12 | 新增:param([Guid]$ExpectedVMId = [Guid]::Empty, [string]$OutputPath) | |
| 13 | 新增:$ErrorActionPreference = 'Stop' | |
| 14 | 新增:. (Join-Path $PSScriptRoot 'claude-desktop-windows.ps1') -ExpectedVMId $ExpectedVMId | |
| 15 | 新增: | |
| 16 | 新增:$cageWindowSource = @' | |
| 17 | 新增:using System; | |
| 18 | 新增:using System.Collections.Generic; | |
| 19 | 新增:using System.Drawing; | |
| 20 | 新增:using System.Drawing.Imaging; | |
| 21 | 新增:using System.IO; | |
| 22 | 新增:using System.Runtime.InteropServices; | |
| 23 | 新增:using System.Text; | |
| 24 | 新增:using System.Threading.Tasks; | |
| 25 | 新增: | |
| 26 | 新增:public static class CageClaudeWindow { | |
| 27 | 新增: [StructLayout(LayoutKind.Sequential)] | |
| 28 | 新增: private struct Rect { public int left, top, right, bottom; } | |
| 29 | 新增: | |
| 30 | 新增: [DllImport("user32.dll")] private static extern bool IsWindowVisible(IntPtr window); | |
| 31 | 新增: [DllImport("user32.dll")] private static extern bool IsIconic(IntPtr window); | |
| 32 | 新增: [DllImport("user32.dll")] private static extern bool GetClientRect(IntPtr window, out Rect rect); | |
| 33 | 新增: [DllImport("user32.dll")] private static extern uint GetWindowThreadProcessId(IntPtr window, out uint process); | |
| 34 | 新增: [DllImport("user32.dll")] private static extern bool PrintWindow(IntPtr window, IntPtr dc, uint flags); | |
| 35 | 新增: [DllImport("dwmapi.dll")] private static extern int DwmGetWindowAttribute(IntPtr window, int attr, out int value, int bytes); | |
| 36 | 新增: [DllImport("user32.dll")] private static extern IntPtr SetThreadDpiAwarenessContext(IntPtr context); | |
| 37 | 新增: [DllImport("user32.dll")] private static extern IntPtr OpenInputDesktop(uint flags, bool inherit, uint access); | |
| 38 | 新增: [DllImport("user32.dll")] private static extern bool CloseDesktop(IntPtr desktop); | |
| 39 | 新增: [DllImport("user32.dll", CharSet=CharSet.Unicode)] | |
| 40 | 新增: private static extern bool GetUserObjectInformation(IntPtr obj, int index, StringBuilder name, int size, out int needed); | |
| 41 | 新增: | |
| 42 | 新增: public static bool IsDefaultInputDesktop() { | |
| 43 | 新增: IntPtr desktop = OpenInputDesktop(0, false, 1); // DESKTOP_READOBJECTS | |
| 44 | 新增: if (desktop == IntPtr.Zero) return false; | |
| 45 | 新增: try { | |
| 46 | 新增: var name = new StringBuilder(256); | |
| 47 | 新增: int needed; | |
| 48 | 新增: return GetUserObjectInformation(desktop, 2, name, name.Capacity * 2, out needed) | |
| 49 | 新增: && String.Equals(name.ToString(), "Default", StringComparison.OrdinalIgnoreCase); | |
| 50 | 新增: } finally { CloseDesktop(desktop); } | |
| 51 | 新增: } | |
| 52 | 新增: | |
| 53 | 新增: private static bool IsClaudeWindow(IntPtr window, uint pid) { | |
| 54 | 新增: uint owner; | |
| 55 | 新增: int cloaked; | |
| 56 | 新增: return GetWindowThreadProcessId(window, out owner) != 0 && owner == pid | |
| 57 | 新增: && IsWindowVisible(window) && !IsIconic(window) | |
| 58 | 新增: && DwmGetWindowAttribute(window, 14, out cloaked, 4) == 0 && cloaked == 0; | |
| 59 | 新增: } | |
| 60 | 新增: | |
| 61 | 新增: public static string FrameProblem(int[] rgb) { | |
| 62 | 新增: if (rgb.Length == 0) return "empty_frame"; | |
| 63 | 新增: int first = rgb[0]; | |
| 64 | 新增: bool black = true, varied = false; | |
| 65 | 新增: foreach (int pixel in rgb) { | |
| 66 | 新增: for (int shift = 0; shift <= 16; shift += 8) { | |
| 67 | 新增: int value = (pixel >> shift) & 255; | |
| 68 | 新增: if (value > 4) black = false; | |
| 69 | 新增: if (Math.Abs(value - ((first >> shift) & 255)) > 4) varied = true; | |
| 70 | 新增: } | |
| 71 | 新增: } | |
| 72 | 新增: return black ? "black_frame" : (varied ? null : "uniform_frame"); | |
| 73 | 新增: } | |
| 74 | 新增: | |
| 75 | 新增: private static byte[] Capture(IntPtr window, uint pid) { | |
| 76 | 新增: if (!IsClaudeWindow(window, pid)) throw new InvalidOperationException("no_visible_window"); | |
| 77 | 新增: IntPtr previousDpi = SetThreadDpiAwarenessContext(new IntPtr(-4)); // Per-monitor aware V2 | |
| 78 | 新增: try { | |
| 79 | 新增: Rect bounds; | |
| 80 | 新增: if (!GetClientRect(window, out bounds) || bounds.right <= 0 || bounds.bottom <= 0) | |
| 81 | 新增: throw new InvalidOperationException("no_visible_window"); | |
| 82 | 新增: using (var bitmap = new Bitmap(bounds.right, bounds.bottom, PixelFormat.Format24bppRgb)) { | |
| 83 | 新增: using (var graphics = Graphics.FromImage(bitmap)) { | |
| 84 | 新增: graphics.Clear(Color.Black); | |
| 85 | 新增: IntPtr dc = graphics.GetHdc(); | |
| 86 | 新增: try { | |
| 87 | 新增: // PW_CLIENTONLY | PW_RENDERFULLCONTENT, also used by Chromium | |
| 88 | 新增: // for its DirectComposition windows. Never read the desktop DC. | |
| 89 | 新增: if (!PrintWindow(window, dc, 3)) throw new InvalidOperationException("window_render_failed"); | |
| 90 | 新增: } finally { graphics.ReleaseHdc(dc); } | |
| 91 | 新增: } | |
| 92 | 新增: if (!IsClaudeWindow(window, pid) || !IsDefaultInputDesktop()) | |
| 93 | 新增: throw new InvalidOperationException("window_or_desktop_changed_during_capture"); | |
| 94 | 新增: var samples = new List<int>(); | |
| 95 | 新增: for (int y = bitmap.Height / 20; y < bitmap.Height - bitmap.Height / 20; y += Math.Max(1, bitmap.Height / 128)) | |
| 96 | 新增: for (int x = bitmap.Width / 20; x < bitmap.Width - bitmap.Width / 20; x += Math.Max(1, bitmap.Width / 128)) | |
| 97 | 新增: samples.Add(bitmap.GetPixel(x, y).ToArgb()); | |
| 98 | 新增: var problem = FrameProblem(samples.ToArray()); | |
| 99 | 新增: if (problem != null) throw new InvalidOperationException(problem); | |
| 100 | 新增: using (var png = new MemoryStream()) { | |
| 101 | 新增: bitmap.Save(png, ImageFormat.Png); | |
| 102 | 新增: return png.ToArray(); | |
| 103 | 新增: } | |
| 104 | 新增: } | |
| 105 | 新增: } finally { if (previousDpi != IntPtr.Zero) SetThreadDpiAwarenessContext(previousDpi); } | |
| 106 | 新增: } | |
| 107 | 新增: | |
| 108 | 新增: public static byte[] CaptureWithTimeout(IntPtr window, uint pid) { | |
| 109 | 新增: // PrintWindow waits synchronously for the window owner. A late render | |
| 110 | 新增: // has no filesystem side effects and cannot publish a stale PNG. | |
| 111 | 新增: var task = Task.Run(() => Capture(window, pid)); | |
| 112 | 新增: if (Task.WaitAny(new Task[] { task }, 10000) < 0) throw new TimeoutException("window_render_timeout"); | |
| 113 | 新增: return task.GetAwaiter().GetResult(); | |
| 114 | 新增: } | |
| 115 | 新增:} | |
| 116 | 新增:'@ | |
| 117 | 新增: | |
| 118 | 新增:function Get-ClaudeCapturePath([string]$path) { | |
| 119 | 新增: if (!$path -or ![IO.Path]::IsPathRooted($path)) { throw 'Supply an absolute guest temporary .png path.' } | |
| 120 | 新增: $full = [IO.Path]::GetFullPath($path) | |
| 121 | 新增: $temp = [IO.Path]::GetTempPath().TrimEnd([IO.Path]::DirectorySeparatorChar) | |
| 122 | 新增: if ([IO.Path]::GetDirectoryName($full) -ine $temp -or [IO.Path]::GetExtension($full) -ine '.png' -or | |
| 123 | 新增: [IO.Path]::GetFileName($full).IndexOfAny([IO.Path]::GetInvalidFileNameChars()) -ge 0) { | |
| 124 | 新增: throw 'OutputPath must be a PNG directly inside this guest user''s temporary directory.' | |
| 125 | 新增: } | |
| 126 | 新增: if (Test-Path -LiteralPath $full) { throw 'Select a new PNG path.' } | |
| 127 | 新增: if ([Environment]::OSVersion.Platform -eq 'Win32NT' -and | |
| 128 | 新增: [IO.DriveInfo]::new([IO.Path]::GetPathRoot($full)).DriveType -ne 'Fixed') { | |
| 129 | 新增: throw 'Use the guest user''s local temporary drive.' | |
| 130 | 新增: } | |
| 131 | 新增: return $full | |
| 132 | 新增:} | |
| 133 | 新增: | |
| 134 | 新增:if ($MyInvocation.InvocationName -eq '.') { return } | |
| 135 | 新增:if ([Environment]::OSVersion.Platform -ne 'Win32NT' -or ![Environment]::Is64BitProcess -or $PSVersionTable.PSEdition -ne 'Desktop') { | |
| 136 | 新增: throw 'Run this script in 64-bit Windows PowerShell 5.1 inside the guest.' | |
| 137 | 新增:} | |
| 138 | 新增:Assert-TargetGuest $ExpectedVMId | |
| 139 | 新增:$file = Get-ClaudeCapturePath $OutputPath | |
| 140 | 新增:$session = [Diagnostics.Process]::GetCurrentProcess().SessionId | |
| 141 | 新增:if ($session -eq 0 -or ![Environment]::UserInteractive -or | |
| 142 | 新增: !(Get-Process -Name explorer -ErrorAction SilentlyContinue | Where-Object SessionId -eq $session)) { | |
| 143 | 新增: throw 'requires_gui_login: Run in the signed-in guest user''s desktop session.' | |
| 144 | 新增:} | |
| 145 | 新增:if (!('CageClaudeWindow' -as [type])) { Add-Type -TypeDefinition $cageWindowSource -ReferencedAssemblies System.Drawing } | |
| 146 | 新增:if (![CageClaudeWindow]::IsDefaultInputDesktop()) { throw 'requires_gui_login: Unlock the guest desktop.' } | |
| 147 | 新增:$registered = Get-RegisteredClaude | |
| 148 | 新增:if (!$registered) { throw 'not_registered: Install the official x64 Claude MSIX for this guest user.' } | |
| 149 | 新增:$target = Get-Process -Name Claude -ErrorAction SilentlyContinue | Where-Object { | |
| 150 | 新增: $_.SessionId -eq $session -and $_.MainWindowHandle -ne 0 -and $_.Path -eq $registered.Executable | |
| 151 | 新增:} | Select-Object -First 1 | |
| 152 | 新增:if (!$target) { throw 'no_visible_window: Open Claude Desktop for this guest user.' } | |
| 153 | 新增:$png = [CageClaudeWindow]::CaptureWithTimeout($target.MainWindowHandle, $target.Id) | |
| 154 | 新增:$staged = Join-Path ([IO.Path]::GetDirectoryName($file)) ([IO.Path]::GetRandomFileName()) | |
| 155 | 新增:$stream = [IO.File]::Open($staged, 'CreateNew', 'Write', 'None') | |
| 156 | 新增:try { | |
| 157 | 新增: try { $stream.Write($png, 0, $png.Length) } finally { $stream.Dispose() } | |
| 158 | 新增: [IO.File]::Move($staged, $file) | |
| 159 | 新增:} finally { [IO.File]::Delete($staged) } | |
| 160 | 新增:[pscustomobject]@{ Path = $file; Bytes = $png.Length; ProcessId = $target.Id; Version = $registered.Version } | ConvertTo-Json | |
| @@ -0,0 +1,32 @@ | ||
| 1 | 新增:#requires -Version 5.1 | |
| 2 | 新增:# Test frame rejection and output handling without accessing any desktop. | |
| 3 | 新增:$ErrorActionPreference = 'Stop' | |
| 4 | 新增:. (Join-Path $PSScriptRoot 'claude-window-windows.ps1') | |
| 5 | 新增: | |
| 6 | 新增:if ($PSVersionTable.PSEdition -eq 'Desktop') { | |
| 7 | 新增: Add-Type -TypeDefinition $cageWindowSource -ReferencedAssemblies System.Drawing | |
| 8 | 新增:} else { | |
| 9 | 新增: $references = @((Get-ChildItem "$PSHOME/ref/*.dll").FullName) + @([Drawing.Bitmap].Assembly.Location) | |
| 10 | 新增: $references += @((Get-ChildItem "$PSHOME/System.Private.Windows.*.dll").FullName) | |
| 11 | 新增: Add-Type -TypeDefinition $cageWindowSource -ReferencedAssemblies $references | |
| 12 | 新增:} | |
| 13 | 新增: | |
| 14 | 新增:if ([CageClaudeWindow]::FrameProblem([int[]]@()) -ne 'empty_frame' -or | |
| 15 | 新增: [CageClaudeWindow]::FrameProblem([int[]]@(0, 0x010204)) -ne 'black_frame' -or | |
| 16 | 新增: [CageClaudeWindow]::FrameProblem([int[]]@(0xFAFAFA, 0xFBFBFB)) -ne 'uniform_frame' -or | |
| 17 | 新增: [CageClaudeWindow]::FrameProblem([int[]]@(0xFAFAFA, 0x111111))) { | |
| 18 | 新增: throw 'Blank or nonuniform frame classification failed.' | |
| 19 | 新增:} | |
| 20 | 新增: | |
| 21 | 新增:$output = Join-Path ([IO.Path]::GetTempPath()) ("cage-window-" + [guid]::NewGuid() + ".png") | |
| 22 | 新增:if ((Get-ClaudeCapturePath $output) -ne [IO.Path]::GetFullPath($output)) { throw 'Failed to accept a temporary PNG.' } | |
| 23 | 新增:try { | |
| 24 | 新增: [IO.File]::WriteAllText($output, 'preserve') | |
| 25 | 新增: foreach ($bad in @($output, "$output.txt", [IO.Path]::Combine([IO.Path]::GetDirectoryName($output), '..', 'outside.png'))) { | |
| 26 | 新增: $rejected = $false | |
| 27 | 新增: try { $null = Get-ClaudeCapturePath $bad } catch { $rejected = $true } | |
| 28 | 新增: if (!$rejected) { throw "Accepted invalid output: $bad" } | |
| 29 | 新增: } | |
| 30 | 新增: if ([IO.File]::ReadAllText($output) -cne 'preserve') { throw 'Existing output was changed.' } | |
| 31 | 新增:} finally { [IO.File]::Delete($output) } | |
| 32 | 新增:Write-Output 'Passed simulated Claude window frame and output-path checks.' | |
| @@ -0,0 +1,322 @@ | ||
| 1 | 新增:#requires -Version 5.1 | |
| 2 | 新增:#requires -RunAsAdministrator | |
| 3 | 新增:[CmdletBinding()] | |
| 4 | 新增:param( | |
| 5 | 新增: [Parameter(Mandatory)][guid]$VMId, | |
| 6 | 新增: [Parameter(Mandatory)][string]$InstanceDirectory, | |
| 7 | 新增: [Parameter(Mandatory)][string]$HostProfileDirectory, | |
| 8 | 新增: [pscredential]$GuestAdministrator, | |
| 9 | 新增: [string]$HostUserSID = ([Security.Principal.WindowsIdentity]::GetCurrent().User.Value), | |
| 10 | 新增: [string]$StateDirectory, | |
| 11 | 新增: [string]$ManifestPath, | |
| 12 | 新增: [string]$ManifestSHA256, | |
| 13 | 新增: [object]$HostEnrollment | |
| 14 | 新增:) | |
| 15 | 新增:$ErrorActionPreference = 'Stop' | |
| 16 | 新增:$ProgressPreference = 'SilentlyContinue' | |
| 17 | 新增:$payload = Join-Path $PSScriptRoot 'payload' | |
| 18 | 新增:$bridgeScripts = Join-Path $PSScriptRoot 'guest-clipboard-windows' | |
| 19 | 新增:$componentManifest=$null | |
| 20 | 新增:if ($ManifestPath) { | |
| 21 | 新增: $manifestFile=Get-Item -LiteralPath $ManifestPath -Force | |
| 22 | 新增: if ($ManifestSHA256 -notmatch '^[a-fA-F0-9]{64}$' -or $manifestFile -isnot [IO.FileInfo] -or $manifestFile.Length -gt 4MB -or | |
| 23 | 新增: $manifestFile.Attributes -band [IO.FileAttributes]::ReparsePoint -or (Get-FileHash -LiteralPath $ManifestPath).Hash -ne $ManifestSHA256) { | |
| 24 | 新增: throw '组件清单无法核验,请从 Cage 重新继续安装。' | |
| 25 | 新增: } | |
| 26 | 新增: $componentManifest=Get-Content -LiteralPath $ManifestPath -Raw | ConvertFrom-Json | |
| 27 | 新增: if ($componentManifest.protocol -ne 1 -or $componentManifest.system -cne 'windows-11' -or $componentManifest.revision -notmatch '^[a-f0-9]{64}$') { throw '原生组件清单无效。' } | |
| 28 | 新增: $kitRoot=[IO.Path]::GetFullPath($PSScriptRoot).TrimEnd('\')+'\' | |
| 29 | 新增: foreach ($entry in $componentManifest.files) { | |
| 30 | 新增: $source=[IO.Path]::GetFullPath((Join-Path $kitRoot $entry.source)) | |
| 31 | 新增: if (!$source.StartsWith($kitRoot,[StringComparison]::OrdinalIgnoreCase) -or (Get-FileHash -LiteralPath $source).Hash -ne $entry.sha256) { | |
| 32 | 新增: throw '当前应用组件包已变化,请重新继续安装。' | |
| 33 | 新增: } | |
| 34 | 新增: } | |
| 35 | 新增:} | |
| 36 | 新增: | |
| 37 | 新增:function Get-LocalDirectory([string]$Path) { | |
| 38 | 新增: $dir = Get-Item -LiteralPath $Path -Force | |
| 39 | 新增: if ($dir -isnot [IO.DirectoryInfo] -or $dir.FullName.StartsWith('\\') -or | |
| 40 | 新增: [IO.DriveInfo]::new($dir.Root.FullName).DriveType -ne 'Fixed') { throw 'A local fixed-disk directory is required.' } | |
| 41 | 新增: for ($parent=$dir; $parent; $parent=$parent.Parent) { | |
| 42 | 新增: if ($parent.Attributes -band [IO.FileAttributes]::ReparsePoint) { throw 'The installation path crosses a filesystem link.' } | |
| 43 | 新增: } | |
| 44 | 新增: return $dir.FullName | |
| 45 | 新增:} | |
| 46 | 新增: | |
| 47 | 新增:. (Join-Path $PSScriptRoot 'windows-workbench-packages.ps1') | |
| 48 | 新增:. (Join-Path $PSScriptRoot 'windows-host-image.ps1') | |
| 49 | 新增: | |
| 50 | 新增:function Read-CageBinding([string]$Path) { | |
| 51 | 新增: $item=Get-Item -LiteralPath $Path -Force | |
| 52 | 新增: if ($item -isnot [IO.FileInfo] -or $item.Attributes -band [IO.FileAttributes]::ReparsePoint -or $item.Length -gt 16384) { throw 'Invalid existing Windows guest binding.' } | |
| 53 | 新增: $data=Get-Content -LiteralPath $item.FullName -Raw | ConvertFrom-Json | |
| 54 | 新增: if ($data.version -ne 1 -or [guid]$data.vm_id -ne $VMId -or $data.instance_directory -ne $instance -or | |
| 55 | 新增: $data.relay_executable -ne (Join-Path $pairDirectory 'Cage.GuestClipboard.exe') -or | |
| 56 | 新增: $data.pairing_file -ne (Join-Path $pairDirectory 'pairing.dpapi') -or | |
| 57 | 新增: ($data.network_pairing_file -and $data.network_pairing_file -ne (Join-Path $pairDirectory 'packet.dpapi'))) { | |
| 58 | 新增: throw 'A different guest is already bound. Its disk and pairing were preserved.' | |
| 59 | 新增: } | |
| 60 | 新增: return $data | |
| 61 | 新增:} | |
| 62 | 新增: | |
| 63 | 新增:# The current package's own relay performs the proof, regardless of the path | |
| 64 | 新增:# stored in the staged profile. A cold bridge may need a few seconds after its | |
| 65 | 新增:# logon task restarts. Never turn a missing registration into a ready profile. | |
| 66 | 新增:function Ensure-HostManager { | |
| 67 | 新增: $manager=Join-Path $payload 'Cage.HyperVManager.exe' | |
| 68 | 新增: if(!(Test-Path -LiteralPath $manager -PathType Leaf)){throw 'The complete Windows host-manager payload is required.'} | |
| 69 | 新增: & (Join-Path $PSScriptRoot 'install-windows-host-manager.ps1') -VMId $VMId -HostSID $HostUserSID -PayloadExecutable $manager -PayloadSHA256 (Get-FileHash -LiteralPath $manager -Algorithm SHA256).Hash -Confirm:$false | Out-Null | |
| 70 | 新增:} | |
| 71 | 新增: | |
| 72 | 新增:function Restore-MissingHostEnrollmentKeys($Binding) { | |
| 73 | 新增: if(!$HostEnrollment){return} | |
| 74 | 新增: . (Join-Path $PSScriptRoot 'windows-host-enrollment.ps1') | |
| 75 | 新增: foreach($kind in @('gui','packet')){ | |
| 76 | 新增: $path=if($kind -ceq 'gui'){$Binding.pairing_file}else{$Binding.network_pairing_file} | |
| 77 | 新增: if(!$path -or (Test-Path -LiteralPath $path)){continue} | |
| 78 | 新增: # Only this fresh VM's fixed Cage keys are recovered. Existing host | |
| 79 | 新增: # DPAPI bytes and model credentials are never replaced or read here. | |
| 80 | 新增: $key=Invoke-Command -Session $session -ArgumentList $VMId,$Binding.gui_user_sid,$kind -ScriptBlock { | |
| 81 | 新增: param($expected,$sid,$kind) | |
| 82 | 新增: if([guid](Get-ItemProperty -LiteralPath 'HKLM:\SOFTWARE\Microsoft\Virtual Machine\Guest\Parameters').VirtualMachineId -ne $expected){throw 'guest_identity_mismatch'} | |
| 83 | 新增: $name=if($kind -ceq 'gui'){'GuestBridge'}else{'GuestNetwork'} | |
| 84 | 新增: $file=if($kind -ceq 'gui'){'pairing.bin'}else{'packet.bin'} | |
| 85 | 新增: $path=Join-Path (Join-Path (Join-Path $env:ProgramData 'Cage') $name) ($expected.ToString('D')+'\'+$file) | |
| 86 | 新增: $item=Get-Item -LiteralPath $path -Force | |
| 87 | 新增: if($item -isnot [IO.FileInfo] -or $item.Length -ne 32 -or $item.Attributes -band [IO.FileAttributes]::ReparsePoint){throw 'fresh_pairing_invalid'} | |
| 88 | 新增: [IO.File]::ReadAllBytes($path) | |
| 89 | 新增: } | |
| 90 | 新增: $bytes=[byte[]]$key | |
| 91 | 新增: try{if($bytes.Length -ne 32){throw 'The retained fresh Cage pairing is invalid.'};Send-CageHostEnrollmentKey $HostEnrollment $kind $Binding.gui_user_sid $bytes}finally{[Array]::Clear($bytes,0,$bytes.Length)} | |
| 92 | 新增: } | |
| 93 | 新增:} | |
| 94 | 新增: | |
| 95 | 新增:function Complete-CloneSetup([string]$Binding) { | |
| 96 | 新增: if ($choice.source.host.system -cne 'windows-11') { return } | |
| 97 | 新增: $answerPath = Join-Path $instance 'windows-guest-tools.iso' | |
| 98 | 新增: $vm | Hyper-V\Get-VMDvdDrive | Where-Object Path -eq $answerPath | Hyper-V\Remove-VMDvdDrive | |
| 99 | 新增: [IO.File]::Delete($answerPath) | |
| 100 | 新增: Remove-CageSetupCredential $VMId $GuestAdministrator $profile $installID $Binding | |
| 101 | 新增:} | |
| 102 | 新增: | |
| 103 | 新增:function Publish-ReadyBinding { | |
| 104 | 新增: $binding=Read-CageBinding $stageBinding | |
| 105 | 新增: if (!$binding.network_pairing_file) { throw 'The protected packet pairing is unavailable.' } | |
| 106 | 新增: if($HostEnrollment){ | |
| 107 | 新增: Ensure-HostManager | |
| 108 | 新增: . (Join-Path $PSScriptRoot 'windows-host-enrollment.ps1') | |
| 109 | 新增: Complete-CloneSetup $stageBinding | |
| 110 | 新增: Complete-CageHostEnrollment $HostEnrollment $binding.gui_user_sid | |
| 111 | 新增: return | |
| 112 | 新增: } | |
| 113 | 新增: $relay=Join-Path $payload 'Cage.GuestClipboard.exe' | |
| 114 | 新增: $deadline=[DateTime]::UtcNow.AddSeconds(30) | |
| 115 | 新增: $ready=$false | |
| 116 | 新增: do { | |
| 117 | 新增: # Windows PowerShell 5.1 turns native stderr into a terminating error | |
| 118 | 新增: # under Stop, even when redirected. A cold relay must reach the retry. | |
| 119 | 新增: $savedPreference=$ErrorActionPreference | |
| 120 | 新增: try { $ErrorActionPreference='Continue'; $raw=& $relay --relay-profile $stageBinding status 2>$null } | |
| 121 | 新增: finally { $ErrorActionPreference=$savedPreference } | |
| 122 | 新增: if ($LASTEXITCODE -eq 0 -and $raw) { | |
| 123 | 新增: $state=$raw | ConvertFrom-Json | |
| 124 | 新增: if ($state.available -and [guid]$state.vm_id -eq $VMId -and $state.gui_user_sid -eq $binding.gui_user_sid -and | |
| 125 | 新增: $state.browser.installed -and $state.browser.editor_installed -and | |
| 126 | 新增: $state.capabilities -contains 'cli' -and $state.capabilities -contains 'project-mount' -and $state.capabilities -contains 'desktop') { | |
| 127 | 新增: try { $ErrorActionPreference='Continue'; $raw='{"action":"status"}' | & $relay --relay-profile $stageBinding desktop 2>$null } | |
| 128 | 新增: finally { $ErrorActionPreference=$savedPreference } | |
| 129 | 新增: if ($LASTEXITCODE -eq 0 -and $raw -and ($raw | ConvertFrom-Json).installed) { $ready=$true; break } | |
| 130 | 新增: } | |
| 131 | 新增: } | |
| 132 | 新增: Start-Sleep -Seconds 1 | |
| 133 | 新增: } while ([DateTime]::UtcNow -lt $deadline) | |
| 134 | 新增: if (!$ready) { throw 'Sign out and sign back in to the paired standard guest account to finish Windows app registration. Resume setup from Cage.' } | |
| 135 | 新增: # The ordinary host controller uses only this protected fixed-VM service. | |
| 136 | 新增: # Host identity is distinct from the GUI account inside the Windows guest. | |
| 137 | 新增: Ensure-HostManager | |
| 138 | 新增: # Complete retirement before exposing a ready profile. The staged pairing | |
| 139 | 新增: # proves an already retired account when a prior publish was interrupted. | |
| 140 | 新增: Complete-CloneSetup $stageBinding | |
| 141 | 新增: $tempBinding=Join-Path $profile ('windows-guest.'+[guid]::NewGuid()+'.tmp') | |
| 142 | 新增: try { | |
| 143 | 新增: [IO.File]::Copy($stageBinding,$tempBinding,$false) | |
| 144 | 新增: Set-Acl -LiteralPath $tempBinding -AclObject (Get-Acl -LiteralPath $stageBinding) | |
| 145 | 新增: [IO.File]::Move($tempBinding,$finalBinding) | |
| 146 | 新增: } finally { if ([IO.File]::Exists($tempBinding)) { [IO.File]::Delete($tempBinding) } } | |
| 147 | 新增:} | |
| 148 | 新增: | |
| 149 | 新增:$instance=Get-LocalDirectory $InstanceDirectory | |
| 150 | 新增:$profile=Get-LocalDirectory $HostProfileDirectory | |
| 151 | 新增:$null=Get-LocalDirectory $payload | |
| 152 | 新增:$choice=Get-Content -LiteralPath (Join-Path $profile 'guest-install.json') -Raw | ConvertFrom-Json | |
| 153 | 新增:$installID=[guid]$choice.id | |
| 154 | 新增:$anchor=Get-Item -LiteralPath (Join-Path $profile 'state') -Force | |
| 155 | 新增:if(!$StateDirectory){$StateDirectory=if($anchor.Attributes -band [IO.FileAttributes]::ReparsePoint){$targets=@($anchor.Target);if($targets.Count -ne 1){throw 'The selected physical state directory changed.'};$targets[0]}else{$anchor.FullName}} | |
| 156 | 新增:$physicalState=Get-LocalDirectory $StateDirectory | |
| 157 | 新增:if($anchor.Attributes -band [IO.FileAttributes]::ReparsePoint){$targets=@($anchor.Target);if($targets.Count -ne 1 -or [IO.Path]::GetFullPath($targets[0]) -ine $physicalState){throw 'The selected physical state directory changed.'}} | |
| 158 | 新增:elseif($anchor.FullName -ine $physicalState){throw 'The selected physical state directory changed.'} | |
| 159 | 新增:if ($installID -eq [guid]::Empty -or $choice.system -ne 'windows-11' -or $choice.editor_terms -ne $true -or | |
| 160 | 新增: [guid][IO.File]::ReadAllText((Join-Path $profile 'windows-install-vm.txt')) -ne $VMId -or | |
| 161 | 新增: $instance -ine (Join-Path $physicalState ('windows-'+$installID.ToString('N')))) { | |
| 162 | 新增: throw 'Automatic boot sign-in is restricted to the new VM in this first-run installation.' | |
| 163 | 新增:} | |
| 164 | 新增:if($HostEnrollment -and ($HostEnrollment.HostSID -cne $HostUserSID -or [guid]$HostEnrollment.VMID -ne $VMId -or [guid]$HostEnrollment.InstallationID -ne $installID -or | |
| 165 | 新增: [IO.Path]::GetFullPath($HostEnrollment.Profile) -ine $profile -or [IO.Path]::GetFullPath($HostEnrollment.State) -ine $physicalState)){throw 'Original user enrollment does not match this fixed installation.'} | |
| 166 | 新增:$vm=Hyper-V\Get-VM -Id $VMId | |
| 167 | 新增:if ($VMId -eq [guid]::Empty -or $vm.Name -cne ('Cage-'+$installID.ToString('N')) -or $vm.Id -ne $VMId -or $vm.State -ne 'Running' -or $vm.Generation -ne 2 -or | |
| 168 | 新增: !($vm.ConfigurationLocation -eq $instance -or $vm.ConfigurationLocation.StartsWith($instance.TrimEnd('\')+'\',[StringComparison]::OrdinalIgnoreCase)) -or | |
| 169 | 新增: @(Hyper-V\Get-VMNetworkAdapter -VM $vm).Count -ne 0 -or @($vm | Hyper-V\Get-VMHardDiskDrive).Count -ne 1 -or | |
| 170 | 新增: ($vm | Hyper-V\Get-VMHardDiskDrive).Path -ne (Join-Path $instance 'system.vhdx')) { | |
| 171 | 新增: throw 'Start the selected, isolated Windows guest and finish Windows Setup in its console.' | |
| 172 | 新增:} | |
| 173 | 新增: | |
| 174 | 新增:$workRoot=Join-Path $instance 'cage-workbench' | |
| 175 | 新增:$pairDirectory=Join-Path $workRoot 'pair' | |
| 176 | 新增:$stageBinding=Join-Path $pairDirectory 'windows-guest.json' | |
| 177 | 新增:$completionMarker=Join-Path $pairDirectory 'workbench-components-ready' | |
| 178 | 新增:$finalBinding=Join-Path $profile 'windows-guest.json' | |
| 179 | 新增:if (Test-Path -LiteralPath $finalBinding) { | |
| 180 | 新增: $existing=Read-CageBinding $finalBinding | |
| 181 | 新增: if (!$existing.network_pairing_file) { throw 'The existing published profile is missing its network pairing.' } | |
| 182 | 新增: if (Test-Path -LiteralPath (Join-Path $profile ('windows-setup-'+$installID.ToString('N')+'.dpapi'))) { | |
| 183 | 新增: Complete-CloneSetup $finalBinding | |
| 184 | 新增: } | |
| 185 | 新增: Ensure-HostManager | |
| 186 | 新增: return | |
| 187 | 新增:} | |
| 188 | 新增:if([Security.Principal.WindowsIdentity]::GetCurrent().User.Value -cne $HostUserSID -and !$HostEnrollment){throw 'Fresh setup for another host user requires the original user enrollment process.'} | |
| 189 | 新增: | |
| 190 | 新增:$null=New-Item -ItemType Directory -Force $workRoot | |
| 191 | 新增:$null=Get-LocalDirectory $workRoot | |
| 192 | 新增:$lockPath=Join-Path $workRoot 'setup.lock' | |
| 193 | 新增:if ((Test-Path -LiteralPath $lockPath) -and ((Get-Item -LiteralPath $lockPath -Force).Attributes -band [IO.FileAttributes]::ReparsePoint)) { throw 'Invalid setup lock.' } | |
| 194 | 新增:$lock=[IO.File]::Open($lockPath,'OpenOrCreate','ReadWrite','None') | |
| 195 | 新增:$session=$null | |
| 196 | 新增:$scratch=$null | |
| 197 | 新增:try { | |
| 198 | 新增: if ((Test-Path -LiteralPath $completionMarker) -and (Test-Path -LiteralPath $stageBinding)) { | |
| 199 | 新增: Publish-ReadyBinding | |
| 200 | 新增: return | |
| 201 | 新增: } | |
| 202 | 新增: if (!$GuestAdministrator) { $GuestAdministrator=Get-Credential -Message 'Cage: enter an administrator account of the selected virtual Windows machine.' } | |
| 203 | 新增: if (!$GuestAdministrator) { throw 'Windows guest setup canceled.' } | |
| 204 | 新增: $session=New-PSSession -VMId $VMId -Credential $GuestAdministrator | |
| 205 | 新增: $target=Invoke-Command -Session $session -FilePath (Join-Path $PSScriptRoot 'initialize-windows-workbench-user.ps1') -ArgumentList $VMId | |
| 206 | 新增: $firstBoot=Join-Path $pairDirectory 'first-account-boot' | |
| 207 | 新增: if (!$target.AlreadySignedIn -and (Test-Path -LiteralPath $firstBoot) -and [IO.File]::ReadAllText($firstBoot) -ne $target.BootID) { | |
| 208 | 新增: throw 'The guest has rebooted. Wait for the dedicated workbench account to sign in, or use the Windows sign-in screen if it was manually locked.' | |
| 209 | 新增: } | |
| 210 | 新增: | |
| 211 | 新增: if (Test-Path -LiteralPath $stageBinding) { | |
| 212 | 新增: $staged=Read-CageBinding $stageBinding | |
| 213 | 新增: if ($staged.gui_user_sid -ne $target.SID) { throw 'Sign in to the already paired Windows guest account to resume.' } | |
| 214 | 新增: } | |
| 215 | 新增: $cache=Join-Path $workRoot 'downloads' | |
| 216 | 新增: $null=New-Item -ItemType Directory -Force $cache | |
| 217 | 新增: $null=Get-LocalDirectory $cache | |
| 218 | 新增: $packages=Get-Content -LiteralPath (Join-Path $payload 'windows-workbench-packages.json') -Raw | ConvertFrom-Json | |
| 219 | 新增: $cli=Get-Content -LiteralPath (Join-Path $payload 'cli-dependencies.json') -Raw | ConvertFrom-Json | |
| 220 | 新增: $files=@{} | |
| 221 | 新增: foreach ($spec in @($packages.PSObject.Properties)+@($cli.PSObject.Properties)) { | |
| 222 | 新增: $files[$spec.Name]=Get-PinnedPackage $spec.Value $cache | |
| 223 | 新增: } | |
| 224 | 新增: | |
| 225 | 新增: $scratch=Join-Path $workRoot ('stage-'+[guid]::NewGuid()) | |
| 226 | 新增: $null=New-Item -ItemType Directory $scratch | |
| 227 | 新增: $core=Join-Path $scratch 'core' | |
| 228 | 新增: $null=New-Item -ItemType Directory $core | |
| 229 | 新增: foreach ($name in @('Cage.GuestClipboard.exe','cage-guest-files.exe','cage-guest-boot.exe')) { Copy-Item -LiteralPath (Join-Path $payload $name) -Destination $core } | |
| 230 | 新增: if (!(Test-Path -LiteralPath $stageBinding)) { | |
| 231 | 新增: $null=& (Join-Path $bridgeScripts 'install.ps1') -VMId $VMId -InstanceDirectory $instance -GUIUserSID $target.SID -GuestAdministrator $GuestAdministrator -PayloadDirectory $core -HostProfileDirectory $pairDirectory -HostUserSID $HostUserSID -HostEnrollment $HostEnrollment -Confirm:$false | |
| 232 | 新增: } | |
| 233 | 新增: $staged=Read-CageBinding $stageBinding | |
| 234 | 新增: if ($staged.gui_user_sid -ne $target.SID) { throw 'The staged bridge belongs to another user.' } | |
| 235 | 新增: | |
| 236 | 新增: Add-Type -AssemblyName System.IO.Compression.FileSystem | |
| 237 | 新增: if (!$staged.network_pairing_file) { | |
| 238 | 新增: $driver=Join-Path $scratch 'driver' | |
| 239 | 新增: [IO.Compression.ZipFile]::ExtractToDirectory($files.wintun,$driver) | |
| 240 | 新增: $null=& (Join-Path $bridgeScripts 'install-network.ps1') -ProfilePath $stageBinding -GuestAdministrator $GuestAdministrator -AgentPath (Join-Path $core 'Cage.GuestClipboard.exe') -WintunPath (Join-Path $driver 'wintun/bin/amd64/wintun.dll') -WintunLicense (Join-Path $driver 'wintun/LICENSE.txt') -HostEnrollment $HostEnrollment -Confirm:$false | |
| 241 | 新增: } | |
| 242 | 新增: $staged=Read-CageBinding $stageBinding | |
| 243 | 新增: Restore-MissingHostEnrollmentKeys $staged | |
| 244 | 新增: | |
| 245 | 新增: $extras=Join-Path $scratch 'extras' | |
| 246 | 新增: $null=New-Item -ItemType Directory $extras | |
| 247 | 新增: foreach ($name in @('modules','split-extension','windows-browser.mjs','windows-browser-extensions.mjs','windows-phone-browser.mjs','install-windows-workbench-user-tools.ps1','install-cli.ps1','cli-dependencies.json')) { | |
| 248 | 新增: Copy-Item -LiteralPath (Join-Path $payload $name) -Destination $extras -Recurse | |
| 249 | 新增: } | |
| 250 | 新增: if ($componentManifest) { | |
| 251 | 新增: foreach ($entry in $componentManifest.files) { | |
| 252 | 新增: if (!$entry.target -or !$entry.target.StartsWith('bridge/')) { continue } | |
| 253 | 新增: $relative=$entry.target.Substring(7) | |
| 254 | 新增: if ($relative -in @('Cage.GuestClipboard.exe','cage-guest-files.exe','cage-guest-boot.exe')) { continue } | |
| 255 | 新增: if ($entry.source -cne ('payload/'+$relative) -or $relative -match '(^|/)\.\.?(/|$)|[:\\]') { throw '组件安装位置无效。' } | |
| 256 | 新增: $targetFile=Join-Path $extras $relative | |
| 257 | 新增: $null=New-Item -ItemType Directory -Path ([IO.Path]::GetDirectoryName($targetFile)) -Force | |
| 258 | 新增: Copy-Item -LiteralPath (Join-Path $PSScriptRoot $entry.source) -Destination $targetFile -Force | |
| 259 | 新增: if ((Get-FileHash -LiteralPath $targetFile).Hash -ne $entry.installed_sha256) { throw '复制后的组件摘要不匹配。' } | |
| 260 | 新增: } | |
| 261 | 新增: } | |
| 262 | 新增: $nodeArchive=[IO.Compression.ZipFile]::OpenRead($files.node) | |
| 263 | 新增: try { [IO.Compression.ZipFileExtensions]::ExtractToFile($nodeArchive.GetEntry('node-v24.22.2-win-x64/node.exe'),(Join-Path $extras 'node.exe')) } finally { $nodeArchive.Dispose() } | |
| 264 | 新增: Expand-PinnedTar $files.playwright (Join-Path $extras 'playwright') | |
| 265 | 新增: Expand-PinnedTar $files.playwrightCore (Join-Path $extras 'playwright/node_modules/playwright-core') | |
| 266 | 新增: [IO.Compression.ZipFile]::ExtractToDirectory($files.editorCLI,(Join-Path $extras 'vscode-cli')) | |
| 267 | 新增: Expand-PinnedTar $files.editorServer (Join-Path $extras 'vscode-server') | |
| 268 | 新增: [IO.File]::WriteAllText((Join-Path $extras 'editor-runtime.json'),'{"commit":"261c84cb1eddf11235f9e2c921425e9663fbe556"}') | |
| 269 | 新增: [IO.File]::WriteAllText((Join-Path $extras 'guest-config.json'),'{"network_mode":"packet"}') | |
| 270 | 新增: # Transfer large trees in one archive over the authenticated VM session. | |
| 271 | 新增: $zipPath=Join-Path $scratch 'extras.zip' | |
| 272 | 新增: & (Join-Path $env:SystemRoot 'System32/tar.exe') -a -cf $zipPath -C $extras . | |
| 273 | 新增: if ($LASTEXITCODE -ne 0) { throw 'Could not stage the guest application archive.' } | |
| 274 | 新增: $guestStage=Invoke-Command -Session $session -ArgumentList $target.Program -ScriptBlock { | |
| 275 | 新增: param($program) | |
| 276 | 新增: $path=Join-Path $program 'setup-packages' | |
| 277 | 新增: if (Test-Path -LiteralPath $path) { if ((Get-Item -LiteralPath $path -Force).Attributes -band [IO.FileAttributes]::ReparsePoint) { throw 'Invalid protected staging directory.' } } | |
| 278 | 新增: else { $null=New-Item -ItemType Directory $path } | |
| 279 | 新增: $path | |
| 280 | 新增: } | |
| 281 | 新增: foreach ($file in @($zipPath,$files.desktop,$files.winfsp,$files.sshfs,$files.uv,$files.python,$files.claude,$files.git)) { | |
| 282 | 新增: Copy-Item -LiteralPath $file -Destination $guestStage -ToSession $session -Force | |
| 283 | 新增: } | |
| 284 | 新增: $installer=Join-Path $PSScriptRoot 'install-windows-workbench-components.ps1' | |
| 285 | 新增: $options=@($VMId,$target.SID,$target.Program,$guestStage,($packages | ConvertTo-Json -Depth 6 -Compress),($cli | ConvertTo-Json -Depth 6 -Compress),(Get-FileHash -LiteralPath $zipPath).Hash) | |
| 286 | 新增: $null=Invoke-Command -Session $session -FilePath $installer -ArgumentList ($options+@('Prepare')) | |
| 287 | 新增: if (!$target.AlreadySignedIn) { | |
| 288 | 新增: # Only this named new VM is rebooted, once. A later manual lock is | |
| 289 | 新增: # never treated as a request to restart or unlock Windows. | |
| 290 | 新增: [IO.File]::WriteAllText($firstBoot,$target.BootID) | |
| 291 | 新增: Remove-PSSession $session; $session=$null | |
| 292 | 新增: Hyper-V\Stop-VM -VM $vm -ErrorAction Stop | |
| 293 | 新增: Hyper-V\Start-VM -VM $vm -ErrorAction Stop | |
| 294 | 新增: $deadline=[DateTime]::UtcNow.AddMinutes(4) | |
| 295 | 新增: do { | |
| 296 | 新增: try { | |
| 297 | 新增: $session=New-PSSession -VMId $VMId -Credential $GuestAdministrator -ErrorAction Stop | |
| 298 | 新增: $logged=Invoke-Command -Session $session -ArgumentList $VMId,$target.Name -ScriptBlock { | |
| 299 | 新增: param($expected,$name) | |
| 300 | 新增: if ([guid](Get-ItemProperty 'HKLM:\SOFTWARE\Microsoft\Virtual Machine\Guest\Parameters').VirtualMachineId -ne $expected) {throw 'wrong VM'} | |
| 301 | 新增: (Get-CimInstance Win32_ComputerSystem).UserName -eq ($env:COMPUTERNAME+'\'+$name) | |
| 302 | 新增: } | |
| 303 | 新增: if ($logged) {break} | |
| 304 | 新增: } catch { $logged=$false } | |
| 305 | 新增: if ($session) { Remove-PSSession $session; $session=$null } | |
| 306 | 新增: Start-Sleep -Seconds 2 | |
| 307 | 新增: } while ([DateTime]::UtcNow -lt $deadline) | |
| 308 | 新增: if (!$session -or !$logged) { throw 'Windows did not finish its first sign-in to the dedicated workbench account. Its account and disk are preserved.' } | |
| 309 | 新增: } | |
| 310 | 新增: $null=Invoke-Command -Session $session -FilePath $installer -ArgumentList ($options+@('UserTools')) | |
| 311 | 新增: if (@(Hyper-V\Get-VMNetworkAdapter -VM (Hyper-V\Get-VM -Id $VMId)).Count -ne 0) { throw 'The Windows guest networking has changed.' } | |
| 312 | 新增: if ($componentManifest) { | |
| 313 | 新增: $null=Invoke-Command -Session $session -FilePath (Join-Path $PSScriptRoot 'publish-windows-component-manifest.ps1') -ArgumentList $VMId,$target.SID,($componentManifest|ConvertTo-Json -Depth 8 -Compress) | |
| 314 | 新增: } | |
| 315 | 新增: | |
| 316 | 新增: [IO.File]::WriteAllText($completionMarker,$target.SID) | |
| 317 | 新增: Publish-ReadyBinding | |
| 318 | 新增:} finally { | |
| 319 | 新增: if ($session) { Remove-PSSession $session } | |
| 320 | 新增: if ($scratch -and (Test-Path -LiteralPath $scratch)) { Remove-Item -LiteralPath $scratch -Recurse -Force } | |
| 321 | 新增: $lock.Dispose() | |
| 322 | 新增:} | |
| @@ -0,0 +1,75 @@ | ||
| 1 | 新增:#!/bin/bash | |
| 2 | 新增:# Root configures only the installer-bound ordinary account inside a Cage VM. | |
| 3 | 新增:set -euo pipefail | |
| 4 | 新增:export PATH=/usr/bin:/bin:/usr/sbin:/sbin | |
| 5 | 新增:[[ $# == 2 && $EUID == 0 && $(uname -sm) == 'Darwin arm64' && $(sysctl -n hw.model) =~ ^VirtualMac[0-9]+,[0-9]+$ ]] | |
| 6 | 新增:user=$1 | |
| 7 | 新增:installation=$2 | |
| 8 | 新增:[[ $user == cage ]] | |
| 9 | 新增:[[ -f /var/db/cage-guest-os && ! -L /var/db/cage-guest-os && $(stat -f %u /var/db/cage-guest-os) == 0 && $(cat /var/db/cage-guest-os) == macos ]] | |
| 10 | 新增:receipt=/var/db/cage-initial-setup/account.json | |
| 11 | 新增:[[ -f $receipt && ! -L $receipt && $(stat -f %u "$receipt") == 0 && $(plutil -extract installation raw "$receipt") == "$installation" ]] | |
| 12 | 新增:phase=$(plutil -extract state raw "$receipt") | |
| 13 | 新增:[[ $phase == ready ]] | |
| 14 | 新增:[[ $(dscl . -read /Users/$user NFSHomeDirectory) == "NFSHomeDirectory: /Users/$user" && " $(id -Gn "$user") " != *' admin '* ]] | |
| 15 | 新增:IFS= read -r password | |
| 16 | 新增:[[ -n $password ]] | |
| 17 | 新增:printf '%s\n' "$password" | dscl /Local/Default -authonly "$user" >/dev/null | |
| 18 | 新增:# FileVault prevents system automatic login; retain its protection and report it. | |
| 19 | 新增:if fdesetup status | grep -q 'FileVault is On'; then | |
| 20 | 新增: echo 'FileVault 已启用,请使用客机密码登录。' >&2 | |
| 21 | 新增: exit 1 | |
| 22 | 新增:fi | |
| 23 | 新增:existing=$(defaults read /Library/Preferences/com.apple.loginwindow autoLoginUser 2>/dev/null || true) | |
| 24 | 新增:[[ -z $existing || $existing == "$user" ]] | |
| 25 | 新增:umask 077 | |
| 26 | 新增:tmp=$(mktemp /etc/cage-autologin.XXXXXXXX) | |
| 27 | 新增:trap 'rm -f "$tmp"' EXIT | |
| 28 | 新增:# macOS's system auto-login record is reversible and root-readable. The host | |
| 29 | 新增:# copy is separately encrypted with the Cage account key. No password argument. | |
| 30 | 新增:printf '%s\n' "$password" | /usr/bin/perl -e ' | |
| 31 | 新增: use strict; use warnings; | |
| 32 | 新增: my $password = <STDIN>; chomp $password; | |
| 33 | 新增: my @key = (0x7d,0x89,0x52,0x23,0xd2,0xbc,0xdd,0xea,0xa3,0xb9,0x1f); | |
| 34 | 新增: my $plain = $password . "\0"; | |
| 35 | 新增: $plain .= "\0" while length($plain) % 12; | |
| 36 | 新增: print pack("C*", map { ord(substr($plain,$_,1)) ^ $key[$_ % @key] } 0..length($plain)-1); | |
| 37 | 新增:' > "$tmp" | |
| 38 | 新增:unset password | |
| 39 | 新增:[[ ! -L /etc/kcpassword ]] | |
| 40 | 新增:chmod 600 "$tmp" | |
| 41 | 新增:mv -f "$tmp" /etc/kcpassword | |
| 42 | 新增:defaults write /Library/Preferences/com.apple.loginwindow autoLoginUser -string "$user" | |
| 43 | 新增:defaults write /Library/Preferences/com.apple.loginwindow autoLoginUserUID -int "$(id -u "$user")" | |
| 44 | 新增:# Match Lima's first-login suppression for the ordinary account. Its generated | |
| 45 | 新增:# plist contains the current OS build/version stamps and no credentials. | |
| 46 | 新增:provision=cageprovision | |
| 47 | 新增:source=/Users/$provision/Library/Preferences/com.apple.SetupAssistant.plist | |
| 48 | 新增:if [[ -f $source && ! -L $source ]]; then | |
| 49 | 新增: cat "$source" | sudo -Hu "$user" /bin/bash -ec ' | |
| 50 | 新增: umask 077 | |
| 51 | 新增: mkdir -p "$HOME/Library/Preferences" | |
| 52 | 新增: target="$HOME/Library/Preferences/com.apple.SetupAssistant.plist" | |
| 53 | 新增: [[ ! -L $target ]] | |
| 54 | 新增: cat > "$target" | |
| 55 | 新增: plutil -lint "$target" >/dev/null | |
| 56 | 新增: ' | |
| 57 | 新增:fi | |
| 58 | 新增:# Write the current OS stamps directly through the account's preference service. | |
| 59 | 新增:sudo -Hu "$user" /bin/bash -ec ' | |
| 60 | 新增: domain=com.apple.SetupAssistant | |
| 61 | 新增: version=$(sw_vers -productVersion) | |
| 62 | 新增: build=$(sw_vers -buildVersion) | |
| 63 | 新增: for key in DidSeeAccessibility DidSeeActivationLock DidSeeAppStore DidSeeAppearanceSetup DidSeeApplePaySetup DidSeeCloudSetup DidSeeLockdownMode DidSeePrivacy DidSeeScreenTime DidSeeSetupSequence DidSeeSiriSetup DidSeeSyncSetup DidSeeSyncSetup2 DidSeeTermsOfAddress DidSeeTouchIDSetup DidSeeiCloudLoginForStorageServices SkipExpressSettingsUpdating SkipFirstLoginOptimization; do | |
| 64 | 新增: defaults write "$domain" "$key" -bool true | |
| 65 | 新增: done | |
| 66 | 新增: for key in LastPreLoginTasksPerformedBuild LastSeenBuddyBuildVersion; do defaults write "$domain" "$key" -string "$build"; done | |
| 67 | 新增: for key in LastPreLoginTasksPerformedVersion LastSeenAgeRangeSelectionProductVersion LastSeenCloudProductVersion LastSeenDiagnosticsProductVersion; do defaults write "$domain" "$key" -string "$version"; done | |
| 68 | 新增: defaults write "$domain" MiniBuddyLaunchReason -int 0 | |
| 69 | 新增: defaults write "$domain" MiniBuddyShouldLaunchToResumeSetup -bool false | |
| 70 | 新增: defaults -currentHost write com.apple.screensaver idleTime -int 0 | |
| 71 | 新增:' | |
| 72 | 新增:# Cage owns guest lifetime; the hidden desktop should not sleep while the | |
| 73 | 新增:# workbench is running. These settings affect only this virtual Mac. | |
| 74 | 新增:pmset -a sleep 0 displaysleep 0 | |
| 75 | 新增:echo '客机自动登录与首次设置已准备。' | |
| @@ -0,0 +1,785 @@ | ||
| 1 | 新增:// Per-user GUI clipboard agent and its private SSH client for a Cage macOS guest. | |
| 2 | 新增:import AppKit | |
| 3 | 新增:import ApplicationServices | |
| 4 | 新增:import ImageIO | |
| 5 | 新增:import Security | |
| 6 | 新增:import UniformTypeIdentifiers | |
| 7 | 新增: | |
| 8 | 新增:private let wireLimit = 30 * 1024 * 1024 | |
| 9 | 新增:private let textLimit = 2 * 1024 * 1024 | |
| 10 | 新增:private let imageLimit = 20 * 1024 * 1024 | |
| 11 | 新增:private let label = "dev.cage.GuestClipboard" | |
| 12 | 新增: | |
| 13 | 新增:private struct ClipboardFailure: Error { | |
| 14 | 新增: let reason: String | |
| 15 | 新增: init(_ reason: String) { self.reason = reason } | |
| 16 | 新增:} | |
| 17 | 新增: | |
| 18 | 新增:private func requireGuest() throws { | |
| 19 | 新增: var model = [CChar](repeating: 0, count: 256), size = 256 | |
| 20 | 新增: guard sysctlbyname("hw.model", &model, &size, nil, 0) == 0, | |
| 21 | 新增: String(cString: model).range(of: #"^VirtualMac[0-9]+,[0-9]+$"#, options: .regularExpression) != nil, | |
| 22 | 新增: getuid() >= 500 else { throw ClipboardFailure("not_guest") } | |
| 23 | 新增: let fd = open("/var/db/cage-guest-os", O_RDONLY | O_NOFOLLOW | O_NONBLOCK) | |
| 24 | 新增: guard fd >= 0 else { throw ClipboardFailure("not_guest") } | |
| 25 | 新增: defer { close(fd) } | |
| 26 | 新增: var info = stat() | |
| 27 | 新增: guard fstat(fd, &info) == 0, info.st_mode & S_IFMT == S_IFREG, info.st_uid == 0, | |
| 28 | 新增: info.st_mode & 0o022 == 0, (5...6).contains(info.st_size) else { throw ClipboardFailure("not_guest") } | |
| 29 | 新增: let data = try FileHandle(fileDescriptor: fd, closeOnDealloc: false).read(upToCount: 6) ?? Data() | |
| 30 | 新增: guard [Data("macos".utf8), Data("macos\n".utf8)].contains(data) else { throw ClipboardFailure("not_guest") } | |
| 31 | 新增:} | |
| 32 | 新增: | |
| 33 | 新增:private func guiAvailable() -> Bool { | |
| 34 | 新增: var info = stat(), attributes: SessionAttributeBits = [] | |
| 35 | 新增: return stat("/dev/console", &info) == 0 && info.st_uid == getuid() && info.st_uid >= 500 && | |
| 36 | 新增: SessionGetInfo(callerSecuritySession, nil, &attributes) == errSecSuccess && attributes.contains(.sessionHasGraphicAccess) && | |
| 37 | 新增: (CGSessionCopyCurrentDictionary() as? [String: Any])?["CGSSessionScreenIsLocked"] as? Bool != true | |
| 38 | 新增:} | |
| 39 | 新增: | |
| 40 | 新增:private func onGUI<T>(_ body: () throws -> T) rethrows -> T { | |
| 41 | 新增: if Thread.isMainThread { return try body() } | |
| 42 | 新增: return try DispatchQueue.main.sync(execute: body) | |
| 43 | 新增:} | |
| 44 | 新增: | |
| 45 | 新增:private func writeAll(_ fd: Int32, _ data: Data) throws { | |
| 46 | 新增: try data.withUnsafeBytes { bytes in | |
| 47 | 新增: var position = 0 | |
| 48 | 新增: while position < bytes.count { | |
| 49 | 新增: let count = Darwin.write(fd, bytes.baseAddress!.advanced(by: position), bytes.count - position) | |
| 50 | 新增: if count < 0 && errno == EINTR { continue } | |
| 51 | 新增: guard count > 0 else { throw ClipboardFailure("connection_closed") } | |
| 52 | 新增: position += count | |
| 53 | 新增: } | |
| 54 | 新增: } | |
| 55 | 新增:} | |
| 56 | 新增: | |
| 57 | 新增:private final class Reader { | |
| 58 | 新增: let fd: Int32 | |
| 59 | 新增: private var buffer = Data() | |
| 60 | 新增: init(_ fd: Int32) { self.fd = fd } | |
| 61 | 新增: func line(limit: Int = wireLimit) throws -> Data? { | |
| 62 | 新增: while true { | |
| 63 | 新增: if let newline = buffer.firstIndex(of: 10) { | |
| 64 | 新增: let value = Data(buffer[..<newline]) | |
| 65 | 新增: buffer.removeSubrange(...newline) | |
| 66 | 新增: guard value.count <= limit else { throw ClipboardFailure("message_too_large") } | |
| 67 | 新增: return value | |
| 68 | 新增: } | |
| 69 | 新增: guard buffer.count <= limit else { throw ClipboardFailure("message_too_large") } | |
| 70 | 新增: var bytes = [UInt8](repeating: 0, count: min(65536, limit + 1 - buffer.count)) | |
| 71 | 新增: let count = Darwin.read(fd, &bytes, bytes.count) | |
| 72 | 新增: if count < 0 && errno == EINTR { continue } | |
| 73 | 新增: if count == 0 { if buffer.isEmpty { return nil }; throw ClipboardFailure("incomplete_message") } | |
| 74 | 新增: guard count > 0 else { throw ClipboardFailure("connection_closed") } | |
| 75 | 新增: buffer.append(contentsOf: bytes.prefix(count)) | |
| 76 | 新增: } | |
| 77 | 新增: } | |
| 78 | 新增: func exact(_ length: Int) throws -> Data { | |
| 79 | 新增: var output = Data() | |
| 80 | 新增: if !buffer.isEmpty { | |
| 81 | 新增: let count = min(length, buffer.count) | |
| 82 | 新增: output.append(buffer.prefix(count)); buffer.removeFirst(count) | |
| 83 | 新增: } | |
| 84 | 新增: while output.count < length { | |
| 85 | 新增: var bytes = [UInt8](repeating: 0, count: min(65536, length - output.count)) | |
| 86 | 新增: let count = Darwin.read(fd, &bytes, bytes.count) | |
| 87 | 新增: if count < 0 && errno == EINTR { continue } | |
| 88 | 新增: guard count > 0 else { throw ClipboardFailure("incomplete_message") } | |
| 89 | 新增: output.append(contentsOf: bytes.prefix(count)) | |
| 90 | 新增: } | |
| 91 | 新增: return output | |
| 92 | 新增: } | |
| 93 | 新增: func copy(to output: FileHandle) throws { | |
| 94 | 新增: if !buffer.isEmpty { try output.write(contentsOf: buffer); buffer.removeAll() } | |
| 95 | 新增: while true { | |
| 96 | 新增: var bytes = [UInt8](repeating: 0, count: 65536) | |
| 97 | 新增: let count = Darwin.read(fd, &bytes, bytes.count) | |
| 98 | 新增: if count < 0 && errno == EINTR { continue } | |
| 99 | 新增: if count == 0 { return } | |
| 100 | 新增: guard count > 0 else { throw ClipboardFailure("connection_closed") } | |
| 101 | 新增: try output.write(contentsOf: Data(bytes.prefix(count))) | |
| 102 | 新增: } | |
| 103 | 新增: } | |
| 104 | 新增:} | |
| 105 | 新增: | |
| 106 | 新增:private func json(_ data: Data) throws -> [String: Any] { | |
| 107 | 新增: guard let value = try JSONSerialization.jsonObject(with: data) as? [String: Any] else { throw ClipboardFailure("invalid_message") } | |
| 108 | 新增: return value | |
| 109 | 新增:} | |
| 110 | 新增: | |
| 111 | 新增:private func jsonData(_ value: [String: Any]) throws -> Data { | |
| 112 | 新增: var data = try JSONSerialization.data(withJSONObject: value, options: [.sortedKeys]) | |
| 113 | 新增: guard data.count <= wireLimit else { throw ClipboardFailure("message_too_large") } | |
| 114 | 新增: data.append(10) | |
| 115 | 新增: return data | |
| 116 | 新增:} | |
| 117 | 新增: | |
| 118 | 新增:private func paths(_ value: Any?) throws -> [String] { | |
| 119 | 新增: guard let values = value as? [String], (1...100).contains(values.count) else { throw ClipboardFailure("invalid_files") } | |
| 120 | 新增: for path in values { | |
| 121 | 新增: guard path.hasPrefix("/"), !path.contains("\0"), URL(fileURLWithPath: path).standardizedFileURL.path == path else { throw ClipboardFailure("invalid_files") } | |
| 122 | 新增: } | |
| 123 | 新增: return values | |
| 124 | 新增:} | |
| 125 | 新增: | |
| 126 | 新增:private func image(_ data: Data, requirePNG: Bool = false) throws -> CGImage { | |
| 127 | 新增: if requirePNG { | |
| 128 | 新增: guard data.count <= imageLimit, data.starts(with: [137, 80, 78, 71, 13, 10, 26, 10]) else { throw ClipboardFailure("invalid_image") } | |
| 129 | 新增: } | |
| 130 | 新增: guard let source = CGImageSourceCreateWithData(data as CFData, nil), | |
| 131 | 新增: let properties = CGImageSourceCopyPropertiesAtIndex(source, 0, nil) as? [CFString: Any], | |
| 132 | 新增: let width = properties[kCGImagePropertyPixelWidth] as? Int, let height = properties[kCGImagePropertyPixelHeight] as? Int, | |
| 133 | 新增: width > 0, height > 0, width <= 40_000_000 / height, | |
| 134 | 新增: let image = CGImageSourceCreateImageAtIndex(source, 0, nil) else { throw ClipboardFailure("invalid_image") } | |
| 135 | 新增: return image | |
| 136 | 新增:} | |
| 137 | 新增: | |
| 138 | 新增:private func png(_ image: CGImage) throws -> Data { | |
| 139 | 新增: let data = NSMutableData() | |
| 140 | 新增: guard let output = CGImageDestinationCreateWithData(data, UTType.png.identifier as CFString, 1, nil) else { throw ClipboardFailure("invalid_image") } | |
| 141 | 新增: CGImageDestinationAddImage(output, image, nil) | |
| 142 | 新增: guard CGImageDestinationFinalize(output), data.length <= imageLimit else { throw ClipboardFailure("image_too_large") } | |
| 143 | 新增: return data as Data | |
| 144 | 新增:} | |
| 145 | 新增: | |
| 146 | 新增:private func boardContent(_ board: NSPasteboard) throws -> [String: Any] { | |
| 147 | 新增: if let urls = board.readObjects(forClasses: [NSURL.self], options: [.urlReadingFileURLsOnly: true]) as? [URL], !urls.isEmpty { | |
| 148 | 新增: guard urls.allSatisfy({ $0.isFileURL && ($0.host == nil || $0.host == "" || $0.host == "localhost") }) else { throw ClipboardFailure("invalid_files") } | |
| 149 | 新增: return ["files": try paths(urls.map(\.path))] | |
| 150 | 新增: } | |
| 151 | 新增: if let value = board.data(forType: .png) { | |
| 152 | 新增: _ = try image(value, requirePNG: true) | |
| 153 | 新增: return ["png": value.base64EncodedString()] | |
| 154 | 新增: } | |
| 155 | 新增: if let value = board.data(forType: .tiff) { return ["png": try png(image(value)).base64EncodedString()] } | |
| 156 | 新增: let value = board.string(forType: .string) ?? "" | |
| 157 | 新增: guard value.utf8.count <= textLimit else { throw ClipboardFailure("text_too_large") } | |
| 158 | 新增: return ["text": value] | |
| 159 | 新增:} | |
| 160 | 新增: | |
| 161 | 新增:private func setBoard(_ board: NSPasteboard, _ value: [String: Any]) throws { | |
| 162 | 新增: if let text = value["text"] as? String { | |
| 163 | 新增: guard text.utf8.count <= textLimit else { throw ClipboardFailure("text_too_large") } | |
| 164 | 新增: board.clearContents() | |
| 165 | 新增: guard board.setString(text, forType: .string) else { throw ClipboardFailure("clipboard_write_failed") } | |
| 166 | 新增: } else if value["png"] != nil { | |
| 167 | 新增: guard let encoded = value["png"] as? String, let data = Data(base64Encoded: encoded) else { throw ClipboardFailure("invalid_image") } | |
| 168 | 新增: let bitmap = try image(data, requirePNG: true) | |
| 169 | 新增: let native = NSImage(cgImage: bitmap, size: .zero) | |
| 170 | 新增: board.clearContents() | |
| 171 | 新增: guard board.writeObjects([native]) else { throw ClipboardFailure("clipboard_write_failed") } | |
| 172 | 新增: } else { | |
| 173 | 新增: let files = try paths(value["files"]) | |
| 174 | 新增: board.clearContents() | |
| 175 | 新增: guard board.writeObjects(files.map { NSURL(fileURLWithPath: $0) }) else { throw ClipboardFailure("clipboard_write_failed") } | |
| 176 | 新增: } | |
| 177 | 新增:} | |
| 178 | 新增: | |
| 179 | 新增:private final class Stream: @unchecked Sendable { | |
| 180 | 新增: private struct Snapshot { let data: Data; let completed: (Bool) -> Void } | |
| 181 | 新增: let fd: Int32 | |
| 182 | 新增: private let outputLock = NSLock() | |
| 183 | 新增: private let stateLock = NSLock() | |
| 184 | 新增: private var closed = false | |
| 185 | 新增: private var publishing = false | |
| 186 | 新增: private var pending: Snapshot? | |
| 187 | 新增: var initialized = false // GUI-thread owned | |
| 188 | 新增: init(_ fd: Int32) { self.fd = fd } | |
| 189 | 新增: func send(_ value: [String: Any]) throws { | |
| 190 | 新增: try sendData(jsonData(value)) | |
| 191 | 新增: } | |
| 192 | 新增: private func sendData(_ data: Data) throws { | |
| 193 | 新增: outputLock.lock(); defer { outputLock.unlock() } | |
| 194 | 新增: stateLock.lock(); let ended = closed; stateLock.unlock() | |
| 195 | 新增: guard !ended else { throw ClipboardFailure("connection_closed") } | |
| 196 | 新增: try writeAll(fd, data) | |
| 197 | 新增: } | |
| 198 | 新增: // Keep only the latest unsent snapshot. A slow client cannot block the GUI | |
| 199 | 新增: // thread or accumulate a queue of full-resolution clipboard images. | |
| 200 | 新增: func publish(_ value: [String: Any], completed: @escaping (Bool) -> Void = { _ in }) { | |
| 201 | 新增: guard let data = try? jsonData(value) else { completed(false); return } | |
| 202 | 新增: stateLock.lock() | |
| 203 | 新增: guard !closed else { stateLock.unlock(); completed(false); return } | |
| 204 | 新增: let superseded = pending | |
| 205 | 新增: pending = Snapshot(data: data, completed: completed) | |
| 206 | 新增: let start = !publishing | |
| 207 | 新增: publishing = true | |
| 208 | 新增: stateLock.unlock() | |
| 209 | 新增: superseded?.completed(false) | |
| 210 | 新增: guard start else { return } | |
| 211 | 新增: DispatchQueue.global(qos: .userInitiated).async { | |
| 212 | 新增: while true { | |
| 213 | 新增: self.stateLock.lock() | |
| 214 | 新增: guard let next = self.pending, !self.closed else { | |
| 215 | 新增: self.publishing = false; self.stateLock.unlock(); return | |
| 216 | 新增: } | |
| 217 | 新增: self.pending = nil | |
| 218 | 新增: self.stateLock.unlock() | |
| 219 | 新增: do { try self.sendData(next.data); next.completed(true) } | |
| 220 | 新增: catch { next.completed(false); self.close(); return } | |
| 221 | 新增: } | |
| 222 | 新增: } | |
| 223 | 新增: } | |
| 224 | 新增: func close() { | |
| 225 | 新增: outputLock.lock() | |
| 226 | 新增: stateLock.lock() | |
| 227 | 新增: let discarded = pending | |
| 228 | 新增: if !closed { closed = true; pending = nil; shutdown(fd, SHUT_RDWR) } | |
| 229 | 新增: stateLock.unlock() | |
| 230 | 新增: outputLock.unlock() | |
| 231 | 新增: discarded?.completed(false) | |
| 232 | 新增: } | |
| 233 | 新增:} | |
| 234 | 新增: | |
| 235 | 新增:private final class SnapshotDelivery: @unchecked Sendable { | |
| 236 | 新增: var remaining: Int | |
| 237 | 新增: var published = false | |
| 238 | 新增: init(_ count: Int) { remaining = count } | |
| 239 | 新增:} | |
| 240 | 新增: | |
| 241 | 新增:private final class ClipboardAgent: @unchecked Sendable { | |
| 242 | 新增: private var streams: [Int32: Stream] = [:] | |
| 243 | 新增: private var records: [[String]] = [] | |
| 244 | 新增: private var known = Set<String>() | |
| 245 | 新增: private var owned = Set<String>() | |
| 246 | 新增: private struct CachedCopy { let id: String; let paths: [String]; var pinned: Bool; let clipboard: Bool } | |
| 247 | 新增: private var copies: [String: CachedCopy] = [:] | |
| 248 | 新增: private var fileReaders: [UUID: [String]] = [:] | |
| 249 | 新增: private var copiesLoaded = false | |
| 250 | 新增: private var collectingCopies = false | |
| 251 | 新增: private var copiesNeedCollection = false | |
| 252 | 新增: private let cacheQueue = DispatchQueue(label: "cage.clipboard.cache") | |
| 253 | 新增: private var session = UUID().uuidString.lowercased() | |
| 254 | 新增: private let board: NSPasteboard | |
| 255 | 新增: private let gui: () -> Bool | |
| 256 | 新增: private let diagnostic: (String) -> Void | |
| 257 | 新增: private var available: Bool | |
| 258 | 新增: private var revision: Int | |
| 259 | 新增: private var snapshotPending = false | |
| 260 | 新增: private var transfers: [UUID: Process] = [:] | |
| 261 | 新增: private let helper: URL | |
| 262 | 新增: init(board: NSPasteboard = .general, gui: @escaping () -> Bool = guiAvailable, | |
| 263 | 新增: diagnostic: @escaping (String) -> Void = { GuestDiagnostic.record("clipboard", $0) }) { | |
| 264 | 新增: self.board = board | |
| 265 | 新增: self.gui = gui | |
| 266 | 新增: self.diagnostic = diagnostic | |
| 267 | 新增: available = gui() | |
| 268 | 新增: revision = board.changeCount | |
| 269 | 新增: helper = Bundle.main.bundleURL.appendingPathComponent("Contents/Resources/cage-guest-files") | |
| 270 | 新增: } | |
| 271 | 新增: private func check(_ expectedSession: String? = nil) throws { | |
| 272 | 新增: guard gui(), available, expectedSession == nil || expectedSession == session else { throw ClipboardFailure("requires_gui_login") } | |
| 273 | 新增: guard FileManager.default.isExecutableFile(atPath: helper.path) else { throw ClipboardFailure("files_helper_missing") } | |
| 274 | 新增: } | |
| 275 | 新增: private func hello() -> [String: Any] { | |
| 276 | 新增: let gui = self.gui() | |
| 277 | 新增: let files = FileManager.default.isExecutableFile(atPath: helper.path) | |
| 278 | 新增: return ["hello": ["version": 1, "os": "darwin", "session": session, "formats": ["text", "png", "files"], | |
| 279 | 新增: "available": gui && files, | |
| 280 | 新增: "file_release": true, | |
| 281 | 新增: "reason": !gui ? "requires_gui_login" : (!files ? "files_helper_missing" : "")]] | |
| 282 | 新增: } | |
| 283 | 新增: private func record(_ files: [String], copied: Bool = false) { | |
| 284 | 新增: records.append(files) | |
| 285 | 新增: if records.count > 128 { records.removeFirst(); known = Set(records.flatMap { $0 }) } | |
| 286 | 新增: else { known.formUnion(files) } | |
| 287 | 新增: if copied { owned.formUnion(files) } | |
| 288 | 新增: } | |
| 289 | 新增: private func cacheControl(_ action: String, id: String = "") throws -> [String: Any] { | |
| 290 | 新增: let process = Process(), output = Pipe() | |
| 291 | 新增: process.executableURL = helper | |
| 292 | 新增: process.arguments = ["cache", String(data: try JSONSerialization.data(withJSONObject: ["action": action, "cache_id": id]), encoding: .utf8)!] | |
| 293 | 新增: process.standardInput = FileHandle.nullDevice; process.standardOutput = output; process.standardError = FileHandle.nullDevice | |
| 294 | 新增: try process.run() | |
| 295 | 新增: let data = try output.fileHandleForReading.readToEnd() ?? Data() | |
| 296 | 新增: process.waitUntilExit() | |
| 297 | 新增: guard process.terminationStatus == 0, data.count <= 1 << 20 else { throw ClipboardFailure("clipboard_cache_failed") } | |
| 298 | 新增: return try json(data) | |
| 299 | 新增: } | |
| 300 | 新增: private func rememberCopy(_ result: [String: Any], clipboard: Bool) { | |
| 301 | 新增: guard let id = result["cache_id"] as? String, let paths = result["paths"] as? [String], !paths.isEmpty else { return } | |
| 302 | 新增: copies[id] = CachedCopy(id: id, paths: paths, pinned: true, clipboard: clipboard) | |
| 303 | 新增: cacheQueue.async { _ = try? self.cacheControl("publish", id: id) } | |
| 304 | 新增: } | |
| 305 | 新增: private func retireCopies(_ paths: [String]) { | |
| 306 | 新增: let selected = Set(paths) | |
| 307 | 新增: for (id, copy) in copies where !selected.isDisjoint(with: copy.paths) { copies[id]?.pinned = false } | |
| 308 | 新增: collectCopies() | |
| 309 | 新增: } | |
| 310 | 新增: private func collectCopies() { | |
| 311 | 新增: guard !collectingCopies else { copiesNeedCollection = true; return } | |
| 312 | 新增: collectingCopies = true | |
| 313 | 新增: cacheQueue.async { | |
| 314 | 新增: defer { | |
| 315 | 新增: onGUI { | |
| 316 | 新增: self.collectingCopies = false | |
| 317 | 新增: if self.copiesNeedCollection { self.copiesNeedCollection = false; self.collectCopies() } | |
| 318 | 新增: } | |
| 319 | 新增: } | |
| 320 | 新增: if !onGUI({ self.copiesLoaded }) { | |
| 321 | 新增: let previous = try? self.cacheControl("list") | |
| 322 | 新增: onGUI { | |
| 323 | 新增: self.copiesLoaded = true | |
| 324 | 新增: for item in previous?["selections"] as? [[String: Any]] ?? [] { | |
| 325 | 新增: if let id = item["cache_id"] as? String, let paths = item["paths"] as? [String], !paths.isEmpty, self.copies[id] == nil { | |
| 326 | 新增: self.copies[id] = CachedCopy(id: id, paths: paths, pinned: false, clipboard: true) | |
| 327 | 新增: } | |
| 328 | 新增: } | |
| 329 | 新增: } | |
| 330 | 新增: } | |
| 331 | 新增: for copy in onGUI({ Array(self.copies.values) }) { | |
| 332 | 新增: let retain = onGUI { () -> Bool in | |
| 333 | 新增: guard self.copies[copy.id]?.pinned == false else { return true } | |
| 334 | 新增: let selected = (self.board.readObjects(forClasses: [NSURL.self], options: [.urlReadingFileURLsOnly: true]) as? [URL] ?? []).map(\.path) | |
| 335 | 新增: let root = URL(fileURLWithPath: copy.paths[0]).deletingLastPathComponent().standardizedFileURL.path | |
| 336 | 新增: return (selected + self.fileReaders.values.flatMap { $0 }).contains { value in | |
| 337 | 新增: let path = URL(fileURLWithPath: value).standardizedFileURL.path | |
| 338 | 新增: return path == root || path.hasPrefix(root + "/") || root.hasPrefix(path + "/") | |
| 339 | 新增: } | |
| 340 | 新增: } | |
| 341 | 新增: if retain { continue } | |
| 342 | 新增: if (try? self.cacheControl("release", id: copy.id)) != nil { | |
| 343 | 新增: onGUI { self.copies.removeValue(forKey: copy.id); self.owned.subtract(copy.paths); self.known.subtract(copy.paths) } | |
| 344 | 新增: } | |
| 345 | 新增: } | |
| 346 | 新增: } | |
| 347 | 新增: } | |
| 348 | 新增: private func beginTransfer(_ operation: String, input: FileHandle?, name: String? = nil) throws -> (Process, Pipe, UUID, String) { | |
| 349 | 新增: let epoch = try onGUI { () -> String in try check(); return session } | |
| 350 | 新增: let process = Process(); process.executableURL = helper | |
| 351 | 新增: process.arguments = [operation] + (name.map { [$0] } ?? (operation == "import" ? [] : ["--paths-stdin"])) | |
| 352 | 新增: let output = Pipe(); process.standardOutput = output; process.standardError = FileHandle.nullDevice | |
| 353 | 新增: process.standardInput = input ?? FileHandle.nullDevice | |
| 354 | 新增: let id = UUID() | |
| 355 | 新增: try onGUI { | |
| 356 | 新增: try check(epoch); transfers[id] = process | |
| 357 | 新增: do { try process.run() } catch { transfers.removeValue(forKey: id); throw error } | |
| 358 | 新增: } | |
| 359 | 新增: return (process, output, id, epoch) | |
| 360 | 新增: } | |
| 361 | 新增: private func finishTransfer(_ process: Process, id: UUID, epoch: String) throws { | |
| 362 | 新增: process.waitUntilExit() | |
| 363 | 新增: try onGUI { transfers.removeValue(forKey: id); try check(epoch) } | |
| 364 | 新增: guard process.terminationStatus == 0 else { throw ClipboardFailure("file_transfer_failed") } | |
| 365 | 新增: } | |
| 366 | 新增: private func fileJSON(_ operation: String, values: [String]) throws -> [String] { | |
| 367 | 新增: let reader = UUID() | |
| 368 | 新增: onGUI { fileReaders[reader] = values } | |
| 369 | 新增: defer { onGUI { fileReaders.removeValue(forKey: reader); collectCopies() } } | |
| 370 | 新增: let input = Pipe() | |
| 371 | 新增: 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) } } | |
| 373 | 新增: try input.fileHandleForWriting.write(contentsOf: JSONSerialization.data(withJSONObject: values)); try input.fileHandleForWriting.close() | |
| 374 | 新增: let data = try output.fileHandleForReading.readToEnd() ?? Data() | |
| 375 | 新增: guard data.count <= 65536 else { throw ClipboardFailure("invalid_files") } | |
| 376 | 新增: let response = try json(data) | |
| 377 | 新增: let result = try paths(response["paths"]) | |
| 378 | 新增: onGUI { record(result, copied: true); rememberCopy(response, clipboard: operation == "copy") } | |
| 379 | 新增: do { try finishTransfer(process, id: id, epoch: epoch) } | |
| 380 | 新增: catch { onGUI { retireCopies(result) }; throw error } | |
| 381 | 新增: return result | |
| 382 | 新增: } | |
| 383 | 新增: private func snapshot() throws -> [String: Any] { | |
| 384 | 新增: let (epoch, captured, content) = try onGUI { () -> (String, Int, [String: Any]) in | |
| 385 | 新增: try check(); return (session, board.changeCount, try boardContent(board)) | |
| 386 | 新增: } | |
| 387 | 新增: var result = content | |
| 388 | 新增: if let selected = content["files"] as? [String] { | |
| 389 | 新增: onGUI { record(selected) } | |
| 390 | 新增: // File snapshots are frozen in the GUI agent's readable cache. | |
| 391 | 新增: result["files"] = try fileJSON("copy", values: selected) | |
| 392 | 新增: } | |
| 393 | 新增: do { try onGUI { try check(epoch); guard board.changeCount == captured else { throw ClipboardFailure("superseded") } } } | |
| 394 | 新增: catch { if let files = result["files"] as? [String] { onGUI { retireCopies(files) } }; throw error } | |
| 395 | 新增: result["revision"] = captured | |
| 396 | 新增: result["source"] = "guest" | |
| 397 | 新增: return result | |
| 398 | 新增: } | |
| 399 | 新增: private func apply(_ value: [String: Any], echo: Bool) throws -> [String: Any] { | |
| 400 | 新增: try onGUI { | |
| 401 | 新增: if value["release"] != nil { retireCopies(try paths(value["release"])); return ["released": true] } | |
| 402 | 新增: try check() | |
| 403 | 新增: if let expected = value["revision"] as? Int, expected != board.changeCount { throw ClipboardFailure("superseded") } | |
| 404 | 新增: if value["files"] != nil { | |
| 405 | 新增: let selected = try paths(value["files"]) | |
| 406 | 新增: guard selected.allSatisfy({ known.contains($0) }) else { throw ClipboardFailure("unregistered_files") } | |
| 407 | 新增: } | |
| 408 | 新增: try setBoard(board, value) | |
| 409 | 新增: if !echo { revision = board.changeCount } | |
| 410 | 新增: return ["ack": value["serial"] as? Int ?? 0, "revision": board.changeCount] | |
| 411 | 新增: } | |
| 412 | 新增: } | |
| 413 | 新增: private func copiedText(_ request: [String: Any]) throws -> [String: Any] { | |
| 414 | 新增: guard let expected = request["revision"] as? Int, let epoch = request["session"] as? String else { throw ClipboardFailure("invalid_copy_request") } | |
| 415 | 新增: let deadline = Date().addingTimeInterval(2) | |
| 416 | 新增: repeat { | |
| 417 | 新增: let value = try onGUI { () -> [String: Any]? in | |
| 418 | 新增: try check(epoch) | |
| 419 | 新增: let captured = board.changeCount | |
| 420 | 新增: guard captured != expected else { return nil } | |
| 421 | 新增: guard let text = board.string(forType: .string), text.utf8.count <= textLimit else { throw ClipboardFailure("clipboard_text_unavailable") } | |
| 422 | 新增: guard board.changeCount == captured else { return nil } | |
| 423 | 新增: return ["text": text, "revision": captured, "session": session] | |
| 424 | 新增: } | |
| 425 | 新增: if let value { return value } | |
| 426 | 新增: Thread.sleep(forTimeInterval: 0.025) | |
| 427 | 新增: } while Date() < deadline | |
| 428 | 新增: throw ClipboardFailure("clipboard_copy_not_observed") | |
| 429 | 新增: } | |
| 430 | 新增: func poll() { | |
| 431 | 新增: collectCopies() | |
| 432 | 新增: let current = gui() | |
| 433 | 新增: if current != available { | |
| 434 | 新增: available = current; session = UUID().uuidString.lowercased() | |
| 435 | 新增: revision = board.changeCount | |
| 436 | 新增: if !current { for process in transfers.values where process.isRunning { process.terminate() } } | |
| 437 | 新增: // Reconnect under a fresh GUI-session hello. Unsent snapshots from | |
| 438 | 新增: // the previous login must not cross the session transition. | |
| 439 | 新增: for stream in streams.values { stream.close() } | |
| 440 | 新增: } | |
| 441 | 新增: guard current, !snapshotPending, streams.values.contains(where: { $0.initialized }), revision != board.changeCount else { return } | |
| 442 | 新增: revision = board.changeCount | |
| 443 | 新增: snapshotPending = true | |
| 444 | 新增: let capturedSession = session | |
| 445 | 新增: DispatchQueue.global(qos: .userInitiated).async { | |
| 446 | 新增: let result: [String: Any] | |
| 447 | 新增: do { result = try self.snapshot() } | |
| 448 | 新增: catch { result = (error as? ClipboardFailure)?.reason == "superseded" ? [:] : ["error": (error as? ClipboardFailure)?.reason ?? "clipboard_read_failed"] } | |
| 449 | 新增: onGUI { | |
| 450 | 新增: self.snapshotPending = false | |
| 451 | 新增: guard !result.isEmpty else { return } | |
| 452 | 新增: let files = result["files"] as? [String] ?? [] | |
| 453 | 新增: let recipients = self.streams.values.filter { $0.initialized } | |
| 454 | 新增: guard self.session == capturedSession, !recipients.isEmpty else { self.retireCopies(files); return } | |
| 455 | 新增: let delivery = SnapshotDelivery(recipients.count) | |
| 456 | 新增: for stream in recipients { | |
| 457 | 新增: stream.publish(result) { sent in | |
| 458 | 新增: DispatchQueue.main.async { | |
| 459 | 新增: delivery.remaining -= 1 | |
| 460 | 新增: delivery.published = delivery.published || sent | |
| 461 | 新增: if delivery.remaining == 0 && !delivery.published { self.retireCopies(files) } | |
| 462 | 新增: } | |
| 463 | 新增: } | |
| 464 | 新增: } | |
| 465 | 新增: } | |
| 466 | 新增: } | |
| 467 | 新增: } | |
| 468 | 新增: func serve(_ fd: Int32) { | |
| 469 | 新增: var stream: Stream? | |
| 470 | 新增: defer { | |
| 471 | 新增: stream?.close() | |
| 472 | 新增: onGUI { | |
| 473 | 新增: _ = streams.removeValue(forKey: fd) | |
| 474 | 新增: if stream != nil && streams.isEmpty { for (id, copy) in copies where copy.clipboard { copies[id]?.pinned = false }; collectCopies() } | |
| 475 | 新增: } | |
| 476 | 新增: close(fd) | |
| 477 | 新增: } | |
| 478 | 新增: var user = uid_t(), group = gid_t() | |
| 479 | 新增: guard getpeereid(fd, &user, &group) == 0, user == getuid() else { return } | |
| 480 | 新增: var timeout = timeval(tv_sec: 1800, tv_usec: 0) | |
| 481 | 新增: setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, &timeout, socklen_t(MemoryLayout.size(ofValue: timeout))) | |
| 482 | 新增: var outputTimeout = timeval(tv_sec: 2, tv_usec: 0) | |
| 483 | 新增: setsockopt(fd, SOL_SOCKET, SO_SNDTIMEO, &outputTimeout, socklen_t(MemoryLayout.size(ofValue: outputTimeout))) | |
| 484 | 新增: let reader = Reader(fd) | |
| 485 | 新增: do { | |
| 486 | 新增: guard let first = try reader.line(), let operation = try json(first)["operation"] as? String else { return } | |
| 487 | 新增: let request = try json(first) | |
| 488 | 新增: switch operation { | |
| 489 | 新增: case "copy-prepare": | |
| 490 | 新增: let value = try onGUI { () -> [String: Any] in try check(); return ["revision": board.changeCount, "session": session] } | |
| 491 | 新增: try writeAll(fd, jsonData(value)) | |
| 492 | 新增: case "copy-read": | |
| 493 | 新增: try writeAll(fd, jsonData(copiedText(request))) | |
| 494 | 新增: case "stream": | |
| 495 | 新增: let connection = Stream(fd) | |
| 496 | 新增: stream = connection | |
| 497 | 新增: onGUI { streams[fd] = connection } | |
| 498 | 新增: try connection.send(onGUI { hello() }) | |
| 499 | 新增: while let line = try reader.line() { | |
| 500 | 新增: do { | |
| 501 | 新增: let reply = try apply(json(line), echo: false) | |
| 502 | 新增: onGUI { connection.initialized = true } | |
| 503 | 新增: try connection.send(reply) | |
| 504 | 新增: } catch { try connection.send(["error": (error as? ClipboardFailure)?.reason ?? "clipboard_write_failed"]) } | |
| 505 | 新增: } | |
| 506 | 新增: case "read": | |
| 507 | 新增: let value = try snapshot() | |
| 508 | 新增: do { try writeAll(fd, jsonData(value)) } | |
| 509 | 新增: catch { if let files = value["files"] as? [String] { onGUI { retireCopies(files) } }; throw error } | |
| 510 | 新增: case "write": | |
| 511 | 新增: try writeAll(fd, jsonData(apply(request, echo: true))) | |
| 512 | 新增: case "prepare-files": | |
| 513 | 新增: let selected = try paths(request["files"]) | |
| 514 | 新增: try onGUI { try check(); guard selected.allSatisfy({ owned.contains($0) && known.contains($0) }) else { throw ClipboardFailure("unregistered_files") } } | |
| 515 | 新增: let copied = try fileJSON("link-cached", values: selected) | |
| 516 | 新增: do { try writeAll(fd, jsonData(["paths": copied])) } | |
| 517 | 新增: catch { onGUI { retireCopies(copied) }; throw error } | |
| 518 | 新增: case "discard": | |
| 519 | 新增: let selected = try paths(request["files"]) | |
| 520 | 新增: try onGUI { | |
| 521 | 新增: guard selected.allSatisfy({ owned.contains($0) }) else { throw ClipboardFailure("unregistered_files") } | |
| 522 | 新增: retireCopies(selected) | |
| 523 | 新增: let tracked = Set(copies.values.flatMap(\.paths)) | |
| 524 | 新增: for file in selected where !tracked.contains(file) { | |
| 525 | 新增: try? FileManager.default.removeItem(atPath: file) | |
| 526 | 新增: owned.remove(file); known.remove(file) | |
| 527 | 新增: // Remove only an empty cache directory owned by this transfer. | |
| 528 | 新增: _ = rmdir((file as NSString).deletingLastPathComponent) | |
| 529 | 新增: } | |
| 530 | 新增: } | |
| 531 | 新增: try writeAll(fd, jsonData(["ok": true])) | |
| 532 | 新增: case "import", "upload": | |
| 533 | 新增: let name = operation == "upload" ? request["name"] as? String : nil | |
| 534 | 新增: if operation == "upload" && (name == nil || name!.utf8.count > 255) { throw ClipboardFailure("invalid_files") } | |
| 535 | 新增: let input = Pipe() | |
| 536 | 新增: 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) } } | |
| 538 | 新增: try reader.copy(to: input.fileHandleForWriting); try input.fileHandleForWriting.close() | |
| 539 | 新增: let data = try output.fileHandleForReading.readToEnd() ?? Data() | |
| 540 | 新增: guard data.count <= 65536 else { throw ClipboardFailure("invalid_files") } | |
| 541 | 新增: let response = try json(data) | |
| 542 | 新增: let imported = try paths(response["paths"]) | |
| 543 | 新增: 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])) } | |
| 545 | 新增: catch { onGUI { retireCopies(imported) }; throw error } | |
| 546 | 新增: case "export": | |
| 547 | 新增: let selected = try paths(request["paths"]) | |
| 548 | 新增: let readerID = UUID() | |
| 549 | 新增: try onGUI { try check(); guard selected.allSatisfy({ known.contains($0) }) else { throw ClipboardFailure("unregistered_files") }; fileReaders[readerID] = selected } | |
| 550 | 新增: defer { onGUI { fileReaders.removeValue(forKey: readerID); collectCopies() } } | |
| 551 | 新增: let input = Pipe() | |
| 552 | 新增: let (process, output, id, epoch) = try beginTransfer("export", input: input.fileHandleForReading) | |
| 553 | 新增: defer { if process.isRunning { process.terminate() }; onGUI { _ = transfers.removeValue(forKey: id) } } | |
| 554 | 新增: try input.fileHandleForWriting.write(contentsOf: JSONSerialization.data(withJSONObject: selected)); try input.fileHandleForWriting.close() | |
| 555 | 新增: while let data = try output.fileHandleForReading.read(upToCount: 65536), !data.isEmpty { | |
| 556 | 新增: var count = UInt32(data.count).bigEndian | |
| 557 | 新增: try writeAll(fd, Data(bytes: &count, count: 4)); try writeAll(fd, data) | |
| 558 | 新增: } | |
| 559 | 新增: var zero: UInt32 = 0 | |
| 560 | 新增: try writeAll(fd, Data(bytes: &zero, count: 4)) | |
| 561 | 新增: do { try finishTransfer(process, id: id, epoch: epoch); try writeAll(fd, jsonData(["ok": true])) } | |
| 562 | 新增: catch { try writeAll(fd, jsonData(["error": "file_transfer_failed"])) } | |
| 563 | 新增: default: | |
| 564 | 新增: throw ClipboardFailure("unknown_operation") | |
| 565 | 新增: } | |
| 566 | 新增: } catch { | |
| 567 | 新增: let reason = (error as? ClipboardFailure)?.reason ?? "clipboard_operation_failed" | |
| 568 | 新增: diagnostic(reason) | |
| 569 | 新增: try? writeAll(fd, jsonData(["error": reason])) | |
| 570 | 新增: } | |
| 571 | 新增: } | |
| 572 | 新增:} | |
| 573 | 新增: | |
| 574 | 新增:private func connect() throws -> Int32 { | |
| 575 | 新增: let folder = FileManager.default.homeDirectoryForCurrentUser.appendingPathComponent("Library/Caches/" + label) | |
| 576 | 新增: var info = stat() | |
| 577 | 新增: guard lstat(folder.path, &info) == 0, info.st_uid == getuid(), info.st_mode & S_IFMT == S_IFDIR, info.st_mode & 0o077 == 0 else { throw ClipboardFailure("clipboard_service_unavailable") } | |
| 578 | 新增: let path = folder.appendingPathComponent("clipboard.sock").path | |
| 579 | 新增: guard lstat(path, &info) == 0, info.st_uid == getuid(), info.st_mode & S_IFMT == S_IFSOCK, info.st_mode & 0o077 == 0 else { throw ClipboardFailure("clipboard_service_unavailable") } | |
| 580 | 新增: var address = sockaddr_un(); address.sun_family = sa_family_t(AF_UNIX) | |
| 581 | 新增: let bytes = Array(path.utf8) + [UInt8(0)] | |
| 582 | 新增: guard bytes.count <= MemoryLayout.size(ofValue: address.sun_path) else { throw ClipboardFailure("clipboard_service_unavailable") } | |
| 583 | 新增: withUnsafeMutableBytes(of: &address.sun_path) { $0.copyBytes(from: bytes) } | |
| 584 | 新增: let fd = socket(AF_UNIX, SOCK_STREAM, 0) | |
| 585 | 新增: guard fd >= 0 else { throw ClipboardFailure("clipboard_service_unavailable") } | |
| 586 | 新增: let result = withUnsafePointer(to: &address) { $0.withMemoryRebound(to: sockaddr.self, capacity: 1) { Darwin.connect(fd, $0, socklen_t(MemoryLayout<sockaddr_un>.size)) } } | |
| 587 | 新增: guard result == 0 else { close(fd); throw ClipboardFailure("clipboard_service_unavailable") } | |
| 588 | 新增: return fd | |
| 589 | 新增:} | |
| 590 | 新增: | |
| 591 | 新增:private func client(_ operation: String) throws { | |
| 592 | 新增: try requireGuest() | |
| 593 | 新增: let fd = try connect(); defer { close(fd) } | |
| 594 | 新增: let reader = Reader(fd) | |
| 595 | 新增: switch operation { | |
| 596 | 新增: case "stream": | |
| 597 | 新增: try writeAll(fd, jsonData(["operation": "stream"])) | |
| 598 | 新增: DispatchQueue.global().async { | |
| 599 | 新增: do { try Reader(fd).copy(to: .standardOutput); exit(0) } | |
| 600 | 新增: catch { exit(1) } | |
| 601 | 新增: } | |
| 602 | 新增: try Reader(STDIN_FILENO).copy(to: FileHandle(fileDescriptor: fd, closeOnDealloc: false)) | |
| 603 | 新增: shutdown(fd, SHUT_WR) | |
| 604 | 新增: dispatchMain() | |
| 605 | 新增: case "import": | |
| 606 | 新增: try writeAll(fd, jsonData(["operation": "import"])) | |
| 607 | 新增: try Reader(STDIN_FILENO).copy(to: FileHandle(fileDescriptor: fd, closeOnDealloc: false)); shutdown(fd, SHUT_WR) | |
| 608 | 新增: guard let line = try reader.line(), try json(line)["error"] == nil else { throw ClipboardFailure("file_transfer_failed") } | |
| 609 | 新增: try writeAll(STDOUT_FILENO, line + Data([10])) | |
| 610 | 新增: case "upload": | |
| 611 | 新增: let input = Reader(STDIN_FILENO) | |
| 612 | 新增: guard let line = try input.line(limit: 4096), let name = try json(line)["name"] as? String, name.utf8.count <= 255 else { | |
| 613 | 新增: throw ClipboardFailure("invalid_files") | |
| 614 | 新增: } | |
| 615 | 新增: try writeAll(fd, jsonData(["operation": "upload", "name": name])) | |
| 616 | 新增: try input.copy(to: FileHandle(fileDescriptor: fd, closeOnDealloc: false)); shutdown(fd, SHUT_WR) | |
| 617 | 新增: guard let reply = try reader.line(), try json(reply)["error"] == nil else { throw ClipboardFailure("file_transfer_failed") } | |
| 618 | 新增: try writeAll(STDOUT_FILENO, reply + Data([10])) | |
| 619 | 新增: case "export": | |
| 620 | 新增: var data = Data() | |
| 621 | 新增: while let chunk = try FileHandle.standardInput.read(upToCount: 65536), !chunk.isEmpty { | |
| 622 | 新增: data.append(chunk) | |
| 623 | 新增: guard data.count <= 1 << 20 else { throw ClipboardFailure("invalid_files") } | |
| 624 | 新增: } | |
| 625 | 新增: let selected = try paths(JSONSerialization.jsonObject(with: data)) | |
| 626 | 新增: try writeAll(fd, jsonData(["operation": "export", "paths": selected])); shutdown(fd, SHUT_WR) | |
| 627 | 新增: while true { | |
| 628 | 新增: let length = try reader.exact(4).reduce(UInt32(0)) { ($0 << 8) | UInt32($1) } | |
| 629 | 新增: if length == 0 { break } | |
| 630 | 新增: guard length <= 65536 else { throw ClipboardFailure("file_transfer_failed") } | |
| 631 | 新增: try writeAll(STDOUT_FILENO, reader.exact(Int(length))) | |
| 632 | 新增: } | |
| 633 | 新增: guard let line = try reader.line(), try json(line)["ok"] as? Bool == true else { throw ClipboardFailure("file_transfer_failed") } | |
| 634 | 新增: case "request": | |
| 635 | 新增: guard let line = try Reader(STDIN_FILENO).line(), let action = try json(line)["operation"] as? String, ["read", "write", "prepare-files", "discard", "copy-prepare", "copy-read"].contains(action) else { throw ClipboardFailure("unknown_operation") } | |
| 636 | 新增: try writeAll(fd, line + Data([10])); shutdown(fd, SHUT_WR) | |
| 637 | 新增: guard let reply = try reader.line() else { throw ClipboardFailure("clipboard_service_unavailable") } | |
| 638 | 新增: try writeAll(STDOUT_FILENO, reply + Data([10])) | |
| 639 | 新增: if try json(reply)["error"] != nil { throw ClipboardFailure("clipboard_operation_failed") } | |
| 640 | 新增: default: throw ClipboardFailure("unknown_operation") | |
| 641 | 新增: } | |
| 642 | 新增:} | |
| 643 | 新增: | |
| 644 | 新增:private final class ClipboardTestState: @unchecked Sendable { | |
| 645 | 新增: var available = true // Used only on the GUI thread. | |
| 646 | 新增: let lock = NSLock() | |
| 647 | 新增: var failure: Error? | |
| 648 | 新增:} | |
| 649 | 新增: | |
| 650 | 新增:private func testAgentTransport(_ board: NSPasteboard) throws { | |
| 651 | 新增: let root = FileManager.default.temporaryDirectory.appendingPathComponent("cage-clipboard-selftest-" + UUID().uuidString) | |
| 652 | 新增: try FileManager.default.createDirectory(at: root, withIntermediateDirectories: false) | |
| 653 | 新增: let previousTemp = getenv("TMPDIR").map { String(cString: $0) } | |
| 654 | 新增: setenv("TMPDIR", root.path, 1) | |
| 655 | 新增: defer { | |
| 656 | 新增: if let previousTemp { setenv("TMPDIR", previousTemp, 1) } else { unsetenv("TMPDIR") } | |
| 657 | 新增: try? FileManager.default.removeItem(at: root) | |
| 658 | 新增: } | |
| 659 | 新增: let state = ClipboardTestState() | |
| 660 | 新增: let agent = ClipboardAgent(board: board, gui: { state.available }, diagnostic: { _ in }) | |
| 661 | 新增: let done = DispatchGroup() | |
| 662 | 新增: done.enter() | |
| 663 | 新增: DispatchQueue.global(qos: .userInitiated).async { | |
| 664 | 新增: defer { done.leave() } | |
| 665 | 新增: func connection() throws -> (Int32, DispatchGroup) { | |
| 666 | 新增: var sockets: [Int32] = [0, 0] | |
| 667 | 新增: guard socketpair(AF_UNIX, SOCK_STREAM, 0, &sockets) == 0 else { throw ClipboardFailure("test_socket_failed") } | |
| 668 | 新增: var timeout = timeval(tv_sec: 5, tv_usec: 0) | |
| 669 | 新增: setsockopt(sockets[1], SOL_SOCKET, SO_RCVTIMEO, &timeout, socklen_t(MemoryLayout.size(ofValue: timeout))) | |
| 670 | 新增: let ended = DispatchGroup() | |
| 671 | 新增: ended.enter() | |
| 672 | 新增: let server = sockets[0] | |
| 673 | 新增: DispatchQueue.global().async { agent.serve(server); ended.leave() } | |
| 674 | 新增: return (sockets[1], ended) | |
| 675 | 新增: } | |
| 676 | 新增: func rpc(_ value: [String: Any], bytes: Data = Data()) throws -> [String: Any] { | |
| 677 | 新增: let (fd, ended) = try connection() | |
| 678 | 新增: defer { close(fd); ended.wait() } | |
| 679 | 新增: try writeAll(fd, jsonData(value)) | |
| 680 | 新增: try writeAll(fd, bytes) | |
| 681 | 新增: shutdown(fd, SHUT_WR) | |
| 682 | 新增: guard let line = try Reader(fd).line() else { throw ClipboardFailure("test_reply_missing") } | |
| 683 | 新增: return try json(line) | |
| 684 | 新增: } | |
| 685 | 新增: do { | |
| 686 | 新增: let prepared = try rpc(["operation": "copy-prepare"]) | |
| 687 | 新增: let unchanged = try rpc(["operation": "copy-read", "revision": prepared["revision"]!, "session": prepared["session"]!]) | |
| 688 | 新增: guard unchanged["error"] as? String == "clipboard_copy_not_observed" else { throw ClipboardFailure("test_old_text_returned") } | |
| 689 | 新增: let largeText = String(repeating: "x", count: textLimit) | |
| 690 | 新增: onGUI { board.clearContents(); board.setString(largeText, forType: .string) } | |
| 691 | 新增: let fresh = try rpc(["operation": "copy-read", "revision": prepared["revision"]!, "session": prepared["session"]!]) | |
| 692 | 新增: guard fresh["text"] as? String == largeText, fresh["session"] as? String == prepared["session"] as? String else { throw ClipboardFailure("test_web_copy_failed") } | |
| 693 | 新增: let (fd, ended) = try connection() | |
| 694 | 新增: defer { close(fd); ended.wait() } | |
| 695 | 新增: let reader = Reader(fd) | |
| 696 | 新增: try writeAll(fd, jsonData(["operation": "stream"])) | |
| 697 | 新增: guard let first = try reader.line(), let hello = try json(first)["hello"] as? [String: Any], | |
| 698 | 新增: hello["os"] as? String == "darwin", hello["available"] as? Bool == true else { throw ClipboardFailure("test_hello_failed") } | |
| 699 | 新增: try writeAll(fd, jsonData(["text": "stream text 中文", "serial": 9])) | |
| 700 | 新增: guard let acknowledged = try reader.line(), try json(acknowledged)["ack"] as? Int == 9 else { throw ClipboardFailure("test_ack_failed") } | |
| 701 | 新增: onGUI { board.clearContents(); board.setString("guest pushed text", forType: .string); agent.poll() } | |
| 702 | 新增: guard let pushed = try reader.line(), try json(pushed)["text"] as? String == "guest pushed text" else { throw ClipboardFailure("test_push_failed") } | |
| 703 | 新增: | |
| 704 | 新增: var bytes = Data([0, 255, 128, 10]) | |
| 705 | 新增: var length = UInt32(bytes.count).littleEndian | |
| 706 | 新增: bytes = Data(bytes: &length, count: 4) + bytes + Data(repeating: 0, count: 4) | |
| 707 | 新增: let saved = try rpc(["operation": "upload", "name": "中文 ' .bin"], bytes: bytes) | |
| 708 | 新增: guard let files = saved["paths"] as? [String], files.count == 1, | |
| 709 | 新增: try Data(contentsOf: URL(fileURLWithPath: files[0])) == Data([0, 255, 128, 10]) else { throw ClipboardFailure("test_upload_failed") } | |
| 710 | 新增: let accepted = try rpc(["operation": "write", "files": files, "serial": 10]) | |
| 711 | 新增: guard accepted["ack"] as? Int == 10 else { throw ClipboardFailure("test_file_paste_failed") } | |
| 712 | 新增: let copied = try rpc(["operation": "prepare-files", "files": files]) | |
| 713 | 新增: guard let duplicates = copied["paths"] as? [String], duplicates.count == 1, | |
| 714 | 新增: try Data(contentsOf: URL(fileURLWithPath: duplicates[0])) == Data([0, 255, 128, 10]) else { throw ClipboardFailure("test_copy_failed") } | |
| 715 | 新增: let denied = try rpc(["operation": "write", "files": ["/etc/passwd"]]) | |
| 716 | 新增: guard denied["error"] as? String == "unregistered_files" else { throw ClipboardFailure("test_unregistered_file_accepted") } | |
| 717 | 新增: let discarded = try rpc(["operation": "discard", "files": duplicates]) | |
| 718 | 新增: let cleanupDeadline = Date().addingTimeInterval(5) | |
| 719 | 新增: while FileManager.default.fileExists(atPath: duplicates[0]), Date() < cleanupDeadline { | |
| 720 | 新增: Thread.sleep(forTimeInterval: 0.01) | |
| 721 | 新增: } | |
| 722 | 新增: guard discarded["ok"] as? Bool == true, !FileManager.default.fileExists(atPath: duplicates[0]) else { throw ClipboardFailure("test_discard_failed") } | |
| 723 | 新增: onGUI { state.available = false; agent.poll() } | |
| 724 | 新增: guard try reader.line() == nil else { throw ClipboardFailure("test_old_session_survived") } | |
| 725 | 新增: } catch { | |
| 726 | 新增: state.lock.lock(); state.failure = error; state.lock.unlock() | |
| 727 | 新增: } | |
| 728 | 新增: } | |
| 729 | 新增: let deadline = Date().addingTimeInterval(30) | |
| 730 | 新增: while done.wait(timeout: .now()) != .success && Date() < deadline { | |
| 731 | 新增: _ = RunLoop.current.run(mode: .default, before: Date().addingTimeInterval(0.01)) | |
| 732 | 新增: } | |
| 733 | 新增: guard done.wait(timeout: .now()) == .success else { throw ClipboardFailure("test_transport_timeout") } | |
| 734 | 新增: state.lock.lock(); let error = state.failure; state.lock.unlock() | |
| 735 | 新增: if let error { throw error } | |
| 736 | 新增:} | |
| 737 | 新增: | |
| 738 | 新增:private func selfTest() throws { | |
| 739 | 新增: let board = NSPasteboard(name: NSPasteboard.Name("cage-clipboard-qa-" + UUID().uuidString)) | |
| 740 | 新增: defer { board.releaseGlobally() } | |
| 741 | 新增: let text = "中文🙂\nexact text" | |
| 742 | 新增: try setBoard(board, ["text": text]); guard try boardContent(board)["text"] as? String == text else { throw ClipboardFailure("text_test_failed") } | |
| 743 | 新增: let bitmap = NSBitmapImageRep(bitmapDataPlanes: nil, pixelsWide: 11, pixelsHigh: 7, bitsPerSample: 8, samplesPerPixel: 4, hasAlpha: true, isPlanar: false, colorSpaceName: .deviceRGB, bytesPerRow: 0, bitsPerPixel: 0)! | |
| 744 | 新增: let value = bitmap.representation(using: .png, properties: [:])! | |
| 745 | 新增: try setBoard(board, ["png": value.base64EncodedString()]); let actual = try boardContent(board) | |
| 746 | 新增: guard let encoded = actual["png"] as? String, let data = Data(base64Encoded: encoded), try image(data).width == 11 else { throw ClipboardFailure("image_test_failed") } | |
| 747 | 新增: do { try setBoard(board, ["png": "not-png"]); throw ClipboardFailure("invalid_image_accepted") } catch let error as ClipboardFailure { guard error.reason == "invalid_image" else { throw error } } | |
| 748 | 新增: do { _ = try paths(["/tmp/../escape"]); throw ClipboardFailure("invalid_files_accepted") } catch let error as ClipboardFailure { guard error.reason == "invalid_files" else { throw error } } | |
| 749 | 新增: try testAgentTransport(board) | |
| 750 | 新增: print("macOS clipboard: named pasteboard text/image, private socket stream, framed file upload, registered-file checks, cleanup and GUI-session revocation passed") | |
| 751 | 新增:} | |
| 752 | 新增: | |
| 753 | 新增:@main | |
| 754 | 新增:struct GuestClipboard { | |
| 755 | 新增: static func main() { | |
| 756 | 新增: _ = signal(SIGPIPE, SIG_IGN) | |
| 757 | 新增: do { | |
| 758 | 新增: if CommandLine.arguments.dropFirst() == ["--self-test"] { try selfTest(); return } | |
| 759 | 新增: if CommandLine.arguments.count == 3 && CommandLine.arguments[1] == "--client" { try client(CommandLine.arguments[2]); return } | |
| 760 | 新增: try requireGuest() | |
| 761 | 新增: let storage = UnsafeMutablePointer<UnsafeMutablePointer<Int32>>.allocate(capacity: 1) | |
| 762 | 新增: var count = 0 | |
| 763 | 新增: guard launch_activate_socket("Clipboard", storage, &count) == 0, count == 1 else { throw ClipboardFailure("clipboard_service_unavailable") } | |
| 764 | 新增: let sockets = storage.pointee; storage.deallocate(); let listener = sockets[0]; free(sockets) | |
| 765 | 新增: GuestDiagnostic.record("clipboard", "started") | |
| 766 | 新增: NSApplication.shared.setActivationPolicy(.accessory) | |
| 767 | 新增: let agent = ClipboardAgent() | |
| 768 | 新增: let timer = Timer.scheduledTimer(withTimeInterval: 0.15, repeats: true) { _ in agent.poll() } | |
| 769 | 新增: DispatchQueue.global(qos: .userInitiated).async { | |
| 770 | 新增: let connections = DispatchSemaphore(value: 16) | |
| 771 | 新增: while true { | |
| 772 | 新增: connections.wait() | |
| 773 | 新增: let fd = accept(listener, nil, nil) | |
| 774 | 新增: if fd < 0 { connections.signal(); if errno == EINTR { continue }; exit(2) } | |
| 775 | 新增: DispatchQueue.global(qos: .userInitiated).async { agent.serve(fd); connections.signal() } | |
| 776 | 新增: } | |
| 777 | 新增: } | |
| 778 | 新增: NSApplication.shared.run(); timer.invalidate() | |
| 779 | 新增: } catch { | |
| 780 | 新增: GuestDiagnostic.record("clipboard", (error as? ClipboardFailure)?.reason ?? "clipboard_operation_failed") | |
| 781 | 新增: try? writeAll(STDOUT_FILENO, jsonData(["error": (error as? ClipboardFailure)?.reason ?? "clipboard_operation_failed"])) | |
| 782 | 新增: exit(1) | |
| 783 | 新增: } | |
| 784 | 新增: } | |
| 785 | 新增:} | |
| @@ -0,0 +1,2 @@ | ||
| 1 | 新增:/bin/ | |
| 2 | 新增:/obj/ | |
| @@ -0,0 +1,156 @@ | ||
| 1 | 新增:using System.Runtime.CompilerServices; | |
| 2 | 新增:using System.Collections.Concurrent; | |
| 3 | 新增:using System.Security.AccessControl; | |
| 4 | 新增:using System.Security.Principal; | |
| 5 | 新增:using System.Text.Json.Nodes; | |
| 6 | 新增: | |
| 7 | 新增:namespace Cage.GuestClipboard; | |
| 8 | 新增: | |
| 9 | 新增:// Bytes enter a fixed directory owned by the logged-in guest user. Neither a | |
| 10 | 新增:// guest path nor a command is accepted from the controller. | |
| 11 | 新增:internal static class AttachmentsRpc | |
| 12 | 新增:{ | |
| 13 | 新增: private static readonly SemaphoreSlim Slots = new(12, 12); | |
| 14 | 新增: private sealed record Batch(string Directory, string Target, string Kind, double X, double Y) | |
| 15 | 新增: { | |
| 16 | 新增: internal readonly List<string> Paths = []; | |
| 17 | 新增: internal readonly DateTimeOffset Created = DateTimeOffset.UtcNow; | |
| 18 | 新增: internal readonly long Epoch = ClipboardAgent.Current?.SessionEpoch ?? 0; | |
| 19 | 新增: internal bool Receiving; | |
| 20 | 新增: internal Action? AssertChooser; | |
| 21 | 新增: } | |
| 22 | 新增: private static readonly ConcurrentDictionary<string, Batch> Batches = new(); | |
| 23 | 新增: internal const long FileLimit = 2L << 30; | |
| 24 | 新增: [ModuleInitializer] internal static void Register() => GuestOperations.Register("attachments", Run); | |
| 25 | 新增: internal static bool NameValid(string name) => name.Length is > 0 and <= 255 && name is not "." and not ".." && | |
| 26 | 新增: !name.EndsWith(' ') && !name.EndsWith('.') && name.IndexOfAny(Path.GetInvalidFileNameChars()) < 0 && | |
| 27 | 新增: !new[] { "CON", "PRN", "AUX", "NUL", "COM1", "COM2", "COM3", "COM4", "COM5", "COM6", "COM7", "COM8", "COM9", "LPT1", "LPT2", "LPT3", "LPT4", "LPT5", "LPT6", "LPT7", "LPT8", "LPT9" }.Contains(name.Split('.')[0], StringComparer.OrdinalIgnoreCase); | |
| 28 | 新增: internal static string NewDirectory() | |
| 29 | 新增: { | |
| 30 | 新增: var home = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile); | |
| 31 | 新增: using var identity = WindowsIdentity.GetCurrent(); | |
| 32 | 新增: var parent = Path.Combine(home, "Cage", "Attachments"); | |
| 33 | 新增: var directory = Path.Combine(parent, Guid.NewGuid().ToString("N")); | |
| 34 | 新增: foreach (var path in new[] { Path.Combine(home, "Cage"), parent, directory }) | |
| 35 | 新增: { | |
| 36 | 新增: Directory.CreateDirectory(path); | |
| 37 | 新增: var info = new DirectoryInfo(path); | |
| 38 | 新增: if (info.Attributes.HasFlag(FileAttributes.ReparsePoint) || info.GetAccessControl().GetOwner(typeof(SecurityIdentifier))?.Value != identity.User?.Value) | |
| 39 | 新增: throw new InvalidDataException("attachment_directory_invalid"); | |
| 40 | 新增: } | |
| 41 | 新增: return directory; | |
| 42 | 新增: } | |
| 43 | 新增: internal static JsonObject StartBatch(string target, string kind, double x, double y) | |
| 44 | 新增: { | |
| 45 | 新增: foreach(var pair in Batches.Where(pair=>DateTimeOffset.UtcNow-pair.Value.Created>TimeSpan.FromMinutes(30))) CancelBatch(pair.Key); | |
| 46 | 新增: if(Batches.Count>=12 || kind is not ("paste" or "drop" or "image") || kind=="drop" && (!double.IsFinite(x) || !double.IsFinite(y) || x<0 || x>1 || y<0 || y>1))throw new InvalidDataException("attachment_request_invalid"); | |
| 47 | 新增: var id=Guid.NewGuid().ToString("D"); var batch=new Batch(NewDirectory(),target,kind,x,y); | |
| 48 | 新增: if(!Batches.TryAdd(id,batch))throw new InvalidDataException("attachment_request_invalid"); | |
| 49 | 新增: return new JsonObject { ["ok"]=true,["id"]=id }; | |
| 50 | 新增: } | |
| 51 | 新增: // Only the authenticated dialog broker can supply this capability. The | |
| 52 | 新增: // JSON files-start endpoint continues to accept paste/drop alone. | |
| 53 | 新增: internal static JsonObject StartChooserBatch(string target,Action assertChooser) | |
| 54 | 新增: { | |
| 55 | 新增: assertChooser(); | |
| 56 | 新增: foreach(var pair in Batches.Where(pair=>DateTimeOffset.UtcNow-pair.Value.Created>TimeSpan.FromMinutes(30)))CancelBatch(pair.Key); | |
| 57 | 新增: if(Batches.Count>=12)throw new InvalidDataException("attachment_request_limit"); | |
| 58 | 新增: var id=Guid.NewGuid().ToString("D");var batch=new Batch(NewDirectory(),target,"chooser",0,0){AssertChooser=assertChooser}; | |
| 59 | 新增: if(!Batches.TryAdd(id,batch))throw new InvalidDataException("attachment_request_invalid"); | |
| 60 | 新增: try{assertChooser();return new JsonObject{["ok"]=true,["id"]=id};}catch{CancelBatch(id);throw;} | |
| 61 | 新增: } | |
| 62 | 新增: internal static void CancelBatch(string id) | |
| 63 | 新增: { | |
| 64 | 新增: if(!Batches.TryRemove(id,out var batch))return; | |
| 65 | 新增: lock(batch) { if(!batch.Receiving) try { Directory.Delete(batch.Directory,true); } catch { } } | |
| 66 | 新增: } | |
| 67 | 新增: internal static async Task FinishBatch(string id, Func<string,string,string[],double,double,Task> deliver) | |
| 68 | 新增: { | |
| 69 | 新增: if(!Batches.TryGetValue(id,out var batch))throw new InvalidDataException("attachment_request_invalid"); | |
| 70 | 新增: string[] paths; | |
| 71 | 新增: lock(batch) { if(batch.Receiving || batch.Paths.Count==0 || batch.Epoch!=ClipboardAgent.Current?.SessionEpoch)throw new InvalidDataException("attachment_incomplete");batch.AssertChooser?.Invoke(); batch.Receiving=true;paths=batch.Paths.ToArray(); } | |
| 72 | 新增: try | |
| 73 | 新增: { | |
| 74 | 新增: await deliver(batch.Target,batch.Kind,paths,batch.X,batch.Y); | |
| 75 | 新增: Batches.TryRemove(id,out _); // Completed attachments remain user data. | |
| 76 | 新增: if(batch.Kind=="image")Directory.Delete(batch.Directory,true); | |
| 77 | 新增: } | |
| 78 | 新增: finally { lock(batch)batch.Receiving=false; } | |
| 79 | 新增: } | |
| 80 | 新增: private static async Task Run(Stream stream, CancellationToken token, Func<bool> available) | |
| 81 | 新增: { | |
| 82 | 新增: if (!available()) throw new InvalidDataException("requires_gui_login"); | |
| 83 | 新增: if (!await Slots.WaitAsync(0, token)) throw new InvalidDataException("attachment_limit"); | |
| 84 | 新增: string? directory = null; bool completed = false, ownsReceiving=false; Batch? batch=null; | |
| 85 | 新增: try | |
| 86 | 新增: { | |
| 87 | 新增: var request = await Protocol.Read(stream, 4096, token) ?? throw new EndOfStreamException(); | |
| 88 | 新增: var name = request["name"]?.GetValue<string>() ?? ""; | |
| 89 | 新增: if (request["action"]?.GetValue<string>() != "save" || !NameValid(name)) throw new InvalidDataException("attachment_request_invalid"); | |
| 90 | 新增: var id=request["id"]?.GetValue<string>(); | |
| 91 | 新增: if(id!=null) | |
| 92 | 新增: { | |
| 93 | 新增: if(!Batches.TryGetValue(id,out batch))throw new InvalidDataException("attachment_request_invalid"); | |
| 94 | 新增: lock(batch) { if(batch.Receiving || batch.Paths.Count>=100)throw new InvalidDataException("attachment_limit");batch.AssertChooser?.Invoke();batch.Receiving=true;ownsReceiving=true; } | |
| 95 | 新增: directory=batch.Directory; | |
| 96 | 新增: } | |
| 97 | 新增: else directory = NewDirectory(); | |
| 98 | 新增: var fileDirectory=directory; | |
| 99 | 新增: if(batch?.Kind=="chooser") | |
| 100 | 新增: { | |
| 101 | 新增: // Different selected host folders may contain the same name. | |
| 102 | 新增: // Each chooser file retains its original name in its own fixed | |
| 103 | 新增: // child directory; no uploaded path controls this location. | |
| 104 | 新增: fileDirectory=Path.Combine(directory,Guid.NewGuid().ToString("N")); | |
| 105 | 新增: Directory.CreateDirectory(fileDirectory); | |
| 106 | 新增: using var identity=WindowsIdentity.GetCurrent();var info=new DirectoryInfo(fileDirectory); | |
| 107 | 新增: if(info.Attributes.HasFlag(FileAttributes.ReparsePoint)||info.GetAccessControl().GetOwner(typeof(SecurityIdentifier))?.Value!=identity.User?.Value) | |
| 108 | 新增: throw new InvalidDataException("attachment_directory_invalid"); | |
| 109 | 新增: batch.AssertChooser?.Invoke(); | |
| 110 | 新增: } | |
| 111 | 新增: var path = Path.Combine(fileDirectory, name); | |
| 112 | 新增: await using (var file = new FileStream(path, FileMode.CreateNew, FileAccess.Write, FileShare.None, 64 << 10, FileOptions.Asynchronous)) | |
| 113 | 新增: { | |
| 114 | 新增: using var bounded = new LimitedWriteStream(file, FileLimit); | |
| 115 | 新增: await Protocol.ReceiveFrames(stream, bounded, token); | |
| 116 | 新增: if (!available()) throw new InvalidDataException("requires_gui_login"); | |
| 117 | 新增: await file.FlushAsync(token); file.Flush(true); | |
| 118 | 新增: batch?.AssertChooser?.Invoke(); | |
| 119 | 新增: } | |
| 120 | 新增: if(batch!=null) | |
| 121 | 新增: { | |
| 122 | 新增: if(!Batches.TryGetValue(id!,out var current) || !ReferenceEquals(batch,current))throw new InvalidDataException("attachment_cancelled"); | |
| 123 | 新增: lock(batch)batch.Paths.Add(path); | |
| 124 | 新增: } | |
| 125 | 新增: await Protocol.Write(stream, new JsonObject { ["ok"] = true, ["scope"] = "attachments", ["path"] = path }, token); | |
| 126 | 新增: completed = true; | |
| 127 | 新增: } | |
| 128 | 新增: finally | |
| 129 | 新增: { | |
| 130 | 新增: // This random directory was created for this transfer. Failed bytes | |
| 131 | 新增: // cannot appear as a completed attachment or replace an older file. | |
| 132 | 新增: if(ownsReceiving && batch!=null)lock(batch)batch.Receiving=false; | |
| 133 | 新增: var cancelled=ownsReceiving && batch!=null && !Batches.Values.Any(current=>ReferenceEquals(current,batch)); | |
| 134 | 新增: if ((!completed || cancelled) && directory != null) | |
| 135 | 新增: { | |
| 136 | 新增: foreach(var pair in Batches.Where(pair=>ReferenceEquals(pair.Value,batch)))Batches.TryRemove(pair.Key,out _); | |
| 137 | 新增: try { Directory.Delete(directory, true); } catch { } | |
| 138 | 新增: } | |
| 139 | 新增: Slots.Release(); | |
| 140 | 新增: } | |
| 141 | 新增: } | |
| 142 | 新增: internal sealed class LimitedWriteStream(Stream inner, long limit) : Stream | |
| 143 | 新增: { | |
| 144 | 新增: private long written; | |
| 145 | 新增: public override bool CanRead => false; public override bool CanSeek => false; public override bool CanWrite => true; | |
| 146 | 新增: public override long Length => written; public override long Position { get => written; set => throw new NotSupportedException(); } | |
| 147 | 新增: public override void Flush() => inner.Flush(); | |
| 148 | 新增: public override Task FlushAsync(CancellationToken token) => inner.FlushAsync(token); | |
| 149 | 新增: public override void Write(byte[] buffer, int offset, int count) { Check(count); inner.Write(buffer, offset, count); } | |
| 150 | 新增: public override async ValueTask WriteAsync(ReadOnlyMemory<byte> buffer, CancellationToken token = default) { Check(buffer.Length); await inner.WriteAsync(buffer, token); } | |
| 151 | 新增: private void Check(int count) { if (count < 0 || written > limit - count) throw new InvalidDataException("attachment_size_limit"); written += count; } | |
| 152 | 新增: public override int Read(byte[] buffer, int offset, int count) => throw new NotSupportedException(); | |
| 153 | 新增: public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException(); | |
| 154 | 新增: public override void SetLength(long value) => throw new NotSupportedException(); | |
| 155 | 新增: } | |
| 156 | 新增:} | |
| @@ -0,0 +1,68 @@ | ||
| 1 | 新增:using System.Text.Json.Nodes; | |
| 2 | 新增: | |
| 3 | 新增:namespace Cage.GuestClipboard; | |
| 4 | 新增: | |
| 5 | 新增:// Browser clipboard staging. It accepts bytes and an already focused tab proof, | |
| 6 | 新增:// never a filename, HWND, clipboard path or a general clipboard write command. | |
| 7 | 新增:internal static class BrowserPasteInput | |
| 8 | 新增:{ | |
| 9 | 新增: private sealed record Pending(string Tab,string Target,string Focus,uint Revision,int Length,DateTime Created,MemoryStream Bytes) | |
| 10 | 新增: { internal int Sequence; internal string Mime = ""; internal readonly long Epoch = ClipboardAgent.Current?.SessionEpoch ?? 0; } | |
| 11 | 新增: private static readonly Dictionary<string,Pending> Transfers = new(StringComparer.Ordinal); | |
| 12 | 新增: internal static async Task<JsonObject> Start(JsonObject input,JsonObject proof,JsonObject focus) | |
| 13 | 新增: { | |
| 14 | 新增: Expire(); | |
| 15 | 新增: var tab=input["id"]?.GetValue<string>()??"";var length=input["length"]?.GetValue<int>()??0; | |
| 16 | 新增: var mime=input["mime"]?.GetValue<string>()??""; | |
| 17 | 新增: if(Transfers.Count>=4||tab!=proof["id"]?.GetValue<string>()||length<0||length>(mime=="text/plain"?Protocol.TextLimit:Protocol.PngLimit)||mime is not ("" or "text/plain" or "image/png"))throw new InvalidDataException("image_target_invalid"); | |
| 18 | 新增: var clipboard=ClipboardAgent.Current??throw new InvalidDataException("clipboard_unavailable"); | |
| 19 | 新增: var revision=await clipboard.Revision(); | |
| 20 | 新增: var id=Guid.NewGuid().ToString("N"); | |
| 21 | 新增: Transfers[id]=new Pending(tab,proof["target"]!.GetValue<string>(),focus["focus"]!.GetValue<string>(),revision,length,DateTime.UtcNow,new MemoryStream(Math.Min(length,64<<10))){Mime=mime}; | |
| 22 | 新增: return new JsonObject{["transfer"]=id}; | |
| 23 | 新增: } | |
| 24 | 新增: internal static JsonObject Chunk(JsonObject input) | |
| 25 | 新增: { | |
| 26 | 新增: var pending=Get(input);var text=input["data"]?.GetValue<string>()??""; | |
| 27 | 新增: if(pending.Sequence==0&&pending.Mime=="")pending.Mime=input["mime"]?.GetValue<string>()??""; | |
| 28 | 新增: if(pending.Mime is not ("text/plain" or "image/png")||input["mime"] is not null&&input["mime"]!.GetValue<string>()!=pending.Mime)throw new InvalidDataException("image_chunk_invalid"); | |
| 29 | 新增: var limit=pending.Mime=="text/plain"?Protocol.TextLimit:Protocol.PngLimit; | |
| 30 | 新增: if(pending.Length==0&&pending.Sequence==0) | |
| 31 | 新增: { | |
| 32 | 新增: var length=input["length"]?.GetValue<int>()??0; | |
| 33 | 新增: if(length<1||length>limit)throw new InvalidDataException("image_chunk_invalid"); | |
| 34 | 新增: pending=pending with {Length=length};Transfers[input["transfer"]!.GetValue<string>()]=pending; | |
| 35 | 新增: } | |
| 36 | 新增: if(pending.Length>limit)throw new InvalidDataException("image_chunk_invalid"); | |
| 37 | 新增: if(text.Length>87384||text.Any(char.IsWhiteSpace))throw new InvalidDataException("image_chunk_invalid"); | |
| 38 | 新增: var bytes=Convert.FromBase64String(text); | |
| 39 | 新增: if(bytes.Length is <1 or >65536||pending.Bytes.Length+bytes.Length>pending.Length)throw new InvalidDataException("image_chunk_invalid"); | |
| 40 | 新增: pending.Bytes.Write(bytes);pending.Sequence++; | |
| 41 | 新增: return new JsonObject{["ack"]=pending.Sequence}; | |
| 42 | 新增: } | |
| 43 | 新增: internal static async Task<JsonObject> Finish(JsonObject input,JsonObject proof,JsonObject focus,Func<Task<JsonObject>> paste) | |
| 44 | 新增: { | |
| 45 | 新增: var pending=Get(input);Transfers.Remove(input["transfer"]!.GetValue<string>()); | |
| 46 | 新增: using(pending.Bytes) | |
| 47 | 新增: { | |
| 48 | 新增: if(pending.Bytes.Length!=pending.Length||pending.Tab!=proof["id"]?.GetValue<string>()||pending.Target!=proof["target"]?.GetValue<string>()||pending.Focus!=focus["focus"]?.GetValue<string>())throw new InvalidDataException("image_target_changed"); | |
| 49 | 新增: var clipboard=ClipboardAgent.Current??throw new InvalidDataException("clipboard_unavailable"); | |
| 50 | 新增: var bytes=pending.Bytes.ToArray(); | |
| 51 | 新增: JsonObject receipt; | |
| 52 | 新增: if(pending.Mime=="text/plain")receipt=await clipboard.WriteBrowserText(pending.Revision,Protocol.Utf8.GetString(bytes)); | |
| 53 | 新增: else {Protocol.Png(bytes);receipt=await clipboard.WriteBrowserPng(pending.Revision,bytes);} | |
| 54 | 新增: await clipboard.PreparePaste(); | |
| 55 | 新增: var result=await paste(); | |
| 56 | 新增: if(result["error"] is not null)throw new InvalidDataException("image_paste_failed"); | |
| 57 | 新增: result["clipboard"]=receipt;return result; | |
| 58 | 新增: } | |
| 59 | 新增: } | |
| 60 | 新增: internal static void Cancel(string id){if(Transfers.Remove(id,out var pending))pending.Bytes.Dispose();} | |
| 61 | 新增: private static Pending Get(JsonObject input) | |
| 62 | 新增: { | |
| 63 | 新增: Expire();var id=input["transfer"]?.GetValue<string>()??""; | |
| 64 | 新增: if(!Transfers.TryGetValue(id,out var pending)||input["sequence"]?.GetValue<int>()!=pending.Sequence||pending.Epoch!=ClipboardAgent.Current?.SessionEpoch)throw new InvalidDataException("image_transfer_changed");return pending; | |
| 65 | 新增: } | |
| 66 | 新增: private static void Expire(){foreach(var item in Transfers.ToArray())if(DateTime.UtcNow-item.Value.Created>TimeSpan.FromMinutes(2))Cancel(item.Key);} | |
| 67 | 新增: internal static void Close(){foreach(var item in Transfers.Values)item.Bytes.Dispose();Transfers.Clear();} | |
| 68 | 新增:} | |
| @@ -0,0 +1,510 @@ | ||
| 1 | 新增:using System.Diagnostics; | |
| 2 | 新增:using System.Collections.Concurrent; | |
| 3 | 新增:using System.Runtime.CompilerServices; | |
| 4 | 新增:using System.Security.AccessControl; | |
| 5 | 新增:using System.Security.Principal; | |
| 6 | 新增:using System.Text.Json.Nodes; | |
| 7 | 新增: | |
| 8 | 新增:namespace Cage.GuestClipboard; | |
| 9 | 新增: | |
| 10 | 新增:// A viewer connection owns its requests. The GUI agent owns the persistent | |
| 11 | 新增:// browser process, so reconnecting or locking the desktop preserves its tabs. | |
| 12 | 新增:internal static class BrowserRpc | |
| 13 | 新增:{ | |
| 14 | 新增: private static readonly SemaphoreSlim Gate = new(1, 1); | |
| 15 | 新增: private static Process? browser; | |
| 16 | 新增: private static GuestProcessJob? browserJob; | |
| 17 | 新增: private static Stream? replies; | |
| 18 | 新增: private static Task? errors; | |
| 19 | 新增: private static bool ready; | |
| 20 | 新增: private static bool wirePending; | |
| 21 | 新增: private static JsonObject? cachedPageFrame; | |
| 22 | 新增: private static NativeInputCoordinator.Lease? pagePointerOwner; | |
| 23 | 新增: private static bool pagePointerReleasePending; | |
| 24 | 新增: private static JsonObject features = new(); | |
| 25 | 新增: private static Func<bool>? packetReadiness; | |
| 26 | 新增: private static string active = ""; | |
| 27 | 新增: private static readonly ConcurrentDictionary<string, WindowsEditorServer.Connection> EditorTabs = new(StringComparer.Ordinal); | |
| 28 | 新增: private static readonly ConcurrentDictionary<string, WindowsEditorServer.Connection> EditorConnections = new(StringComparer.Ordinal); | |
| 29 | 新增: private static readonly ConcurrentDictionary<string, uint> CopyRevisions = new(StringComparer.Ordinal); | |
| 30 | 新增: private static readonly HashSet<string> Routes = ["health", "tabs", "events", "frame", "new", "activate", "close", "navigate", "back", "forward", "reload", "homepage", "resize", "insert-text", "copy-context", "ime", "copy", "cut", "paste", "select-all", "key", "pointer", "click", "wheel", "input", "editor", "editor-restart", "upload-start", "upload-finish", "upload-cancel", "download-retry", "info", "cookies", "settings", "internal-page", "extensions", "split", "audit", "vault", "login-open", "login-finish", "file-open", "file-chunk", "file-finish", "file-read", "file-close", "image-start", "image-chunk", "image-finish", "image-cancel"]; | |
| 31 | 新增: | |
| 32 | 新增: [ModuleInitializer] | |
| 33 | 新增: internal static void Register() | |
| 34 | 新增: { | |
| 35 | 新增: Routes.UnionWith(["paste-start", "paste-chunk", "paste-finish", "paste-cancel", "tailnet", "phone-browser/open", "phone-browser/frame", "phone-browser/action", "phone-browser/close"]); | |
| 36 | 新增: GuestOperations.Register("browser", Run); | |
| 37 | 新增: ProjectRpc.Revoked += (project, grant) => | |
| 38 | 新增: { | |
| 39 | 新增: WindowsEditorServer.Revoke(project, grant); | |
| 40 | 新增: _ = RevokeNode(project, grant); | |
| 41 | 新增: }; | |
| 42 | 新增: AppDomain.CurrentDomain.ProcessExit += (_, _) => { WindowsPhoneBrowser.Close(); WindowsEditorServer.Close(); Close(); }; | |
| 43 | 新增: } | |
| 44 | 新增: // The packet runtime supplies its System-owned receipt verifier. A config | |
| 45 | 新增: // string alone can never enable direct TCP access in a fresh browser. | |
| 46 | 新增: internal static void RegisterPacketReadiness(Func<bool> verifier) | |
| 47 | 新增: { | |
| 48 | 新增: if (Interlocked.CompareExchange(ref packetReadiness, verifier, null) is not null) throw new InvalidOperationException("packet_verifier_already_registered"); | |
| 49 | 新增: } | |
| 50 | 新增: private static bool PacketReady() | |
| 51 | 新增: { | |
| 52 | 新增: if (packetReadiness is not null) return packetReadiness(); | |
| 53 | 新增: try | |
| 54 | 新增: { | |
| 55 | 新增: var vm = GuestContext.VM; | |
| 56 | 新增: if (vm == Guid.Empty || GuestContext.SID.Length == 0) return false; | |
| 57 | 新增: var root = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles), "Cage Guest Network", vm.ToString("D")); | |
| 58 | 新增: var file = new FileInfo(Path.Combine(root, "network-ready.json")); | |
| 59 | 新增: if (!file.Exists || file.Length is < 1 or > 16384 || file.Attributes.HasFlag(FileAttributes.ReparsePoint) || new DirectoryInfo(root).Attributes.HasFlag(FileAttributes.ReparsePoint)) return false; | |
| 60 | 新增: var acl = file.GetAccessControl(); | |
| 61 | 新增: var owner = acl.GetOwner(typeof(SecurityIdentifier))?.Value; | |
| 62 | 新增: if (owner is not ("S-1-5-18" or "S-1-5-32-544")) return false; | |
| 63 | 新增: const FileSystemRights writes = FileSystemRights.WriteData | FileSystemRights.AppendData | FileSystemRights.WriteAttributes | FileSystemRights.WriteExtendedAttributes | FileSystemRights.Delete | FileSystemRights.ChangePermissions | FileSystemRights.TakeOwnership; | |
| 64 | 新增: foreach (FileSystemAccessRule rule in acl.GetAccessRules(true, true, typeof(SecurityIdentifier))) | |
| 65 | 新增: if (rule.AccessControlType == AccessControlType.Allow && (rule.FileSystemRights & writes) != 0 && rule.IdentityReference.Value is not ("S-1-5-18" or "S-1-5-32-544")) return false; | |
| 66 | 新增: // The SYSTEM writer atomically replaces this file every second. | |
| 67 | 新增: // Keep one immutable snapshot while permitting that replacement; | |
| 68 | 新增: // File.ReadAllText's default sharing can block the writer on NTFS. | |
| 69 | 新增: using var snapshot = new FileStream(file.FullName, FileMode.Open, FileAccess.Read, FileShare.Read | FileShare.Delete); | |
| 70 | 新增: if (snapshot.Length is < 1 or > 16384) return false; | |
| 71 | 新增: using var reader = new StreamReader(snapshot); | |
| 72 | 新增: var receipt = JsonNode.Parse(reader.ReadToEnd()) as JsonObject; | |
| 73 | 新增: var updated = receipt?["updated_at"]?.GetValue<long>() ?? 0; | |
| 74 | 新增: var age = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds() - updated; | |
| 75 | 新增: return receipt?["version"]?.GetValue<int>() == 1 && Guid.TryParse(receipt["vm_id"]?.GetValue<string>(), out var receivedVM) && receivedVM == vm && | |
| 76 | 新增: receipt["gui_user_sid"]?.GetValue<string>() == GuestContext.SID && receipt["network"]?.GetValue<string>() == "packet" && | |
| 77 | 新增: receipt["adapter"]?.GetValue<string>() == "Cage-" + vm.ToString("N")[..8] && receipt["interface_index"]?.GetValue<int>() > 0 && | |
| 78 | 新增: receipt["session"]?.GetValue<string>() is { Length: > 0 and <= 128 } && age is >= -1000 and <= 5000; | |
| 79 | 新增: } | |
| 80 | 新增: catch { return false; } | |
| 81 | 新增: } | |
| 82 | 新增: | |
| 83 | 新增: internal static async Task Run(Stream stream, CancellationToken token, Func<bool> sessionAvailable) | |
| 84 | 新增: { | |
| 85 | 新增: var lease=BrowserWindowCapture.OpenLease();Task<JsonObject>? transaction=null; | |
| 86 | 新增: try | |
| 87 | 新增: { | |
| 88 | 新增: while (await Protocol.Read(stream, 128 << 10, token) is { } request) | |
| 89 | 新增: { | |
| 90 | 新增: if (!sessionAvailable()) throw new InvalidDataException("requires_gui_login"); | |
| 91 | 新增: Validate(request); | |
| 92 | 新增: // A canceled viewer leaves the reply drain running. Otherwise its | |
| 93 | 新增: // pending reply could become the next viewer's browser response. | |
| 94 | 新增: transaction = Exchange(request, token, lease); | |
| 95 | 新增: JsonObject result; | |
| 96 | 新增: try { result = await transaction.WaitAsync(token); } | |
| 97 | 新增: catch (OperationCanceledException) | |
| 98 | 新增: { | |
| 99 | 新增: throw; | |
| 100 | 新增: } | |
| 101 | 新增: catch (InvalidDataException error) | |
| 102 | 新增: { | |
| 103 | 新增: var known = new HashSet<string> { "project_grant_unavailable", "editor_components_missing", "editor_start_failed", "editor_start_busy", "clipboard_copy_not_observed", "selection_not_authorized", "browser_network_unavailable", "browser_components_missing", "requires_gui_login", "editor_package_invalid", "browser_unavailable", "browser_response_timeout", "browser_target_changed", "browser_window_unavailable", "browser_process_unavailable", "browser_capture_surface_unavailable", "browser_focus_required", "browser_frame_limit", "desktop_target_changed", "desktop_empty_frame", "desktop_capture_buffer_invalid", "desktop_graphics_device_unavailable", "desktop_capture_permission_required", "desktop_capture_geometry_invalid" }; | |
| 104 | 新增: var code = known.Contains(error.Message) ? error.Message : "browser_operation_failed"; | |
| 105 | 新增: GuestDiagnostics.Record("browser", code); | |
| 106 | 新增: result = new JsonObject { ["error"] = code, ["code"] = code }; | |
| 107 | 新增: } | |
| 108 | 新增: if (!sessionAvailable()) throw new InvalidDataException("requires_gui_login"); | |
| 109 | 新增: await Protocol.Write(stream, result, token); | |
| 110 | 新增: } | |
| 111 | 新增: } | |
| 112 | 新增: finally | |
| 113 | 新增: { | |
| 114 | 新增: // No transaction may inject a late down after this lease is closed. | |
| 115 | 新增: if(transaction is not null)await Observe(transaction); | |
| 116 | 新增: await Gate.WaitAsync(); | |
| 117 | 新增: try | |
| 118 | 新增: { | |
| 119 | 新增: if (pagePointerOwner == lease) | |
| 120 | 新增: { | |
| 121 | 新增: pagePointerOwner = null; | |
| 122 | 新增: pagePointerReleasePending = true; | |
| 123 | 新增: if (sessionAvailable()) | |
| 124 | 新增: { | |
| 125 | 新增: using var releaseTimeout = new CancellationTokenSource(TimeSpan.FromSeconds(5)); | |
| 126 | 新增: try { await ReleasePagePointer(releaseTimeout.Token); } | |
| 127 | 新增: catch { Close(); } | |
| 128 | 新增: } | |
| 129 | 新增: } | |
| 130 | 新增: BrowserWindowCapture.CloseLease(lease); | |
| 131 | 新增: } | |
| 132 | 新增: finally { Gate.Release(); } | |
| 133 | 新增: await WindowsPhoneBrowser.Release(lease); | |
| 134 | 新增: } | |
| 135 | 新增: } | |
| 136 | 新增: | |
| 137 | 新增: private static void Validate(JsonObject value) | |
| 138 | 新增: { | |
| 139 | 新增: var method = value["method"]?.GetValue<string>(); | |
| 140 | 新增: var path = value["path"]?.GetValue<string>() ?? ""; | |
| 141 | 新增: if (value.ContainsKey("operation") || method is not ("GET" or "POST") || | |
| 142 | 新增: path.Length < 2 || !path.StartsWith('/') || !Routes.Contains(path[1..]) || | |
| 143 | 新增: value["input"] is not (null or JsonObject) || | |
| 144 | 新增: method == "GET" && path is not ("/health" or "/tabs" or "/events" or "/frame")) | |
| 145 | 新增: throw new InvalidDataException("browser_request_invalid"); | |
| 146 | 新增: } | |
| 147 | 新增: | |
| 148 | 新增: private static void AssertEditorTab(string? id) | |
| 149 | 新增: { | |
| 150 | 新增: if(id is not null && EditorTabs.TryGetValue(id,out var bound) && ProjectRpc.Resolve(bound.Project,bound.Grant)!=bound.Folder) | |
| 151 | 新增: throw new InvalidDataException("project_grant_unavailable"); | |
| 152 | 新增: } | |
| 153 | 新增: private static void AssertFrameEditors(JsonObject frame) | |
| 154 | 新增: { | |
| 155 | 新增: AssertEditorTab(frame["id"]?.GetValue<string>()); | |
| 156 | 新增: AssertEditorTab((frame["native"] as JsonObject)?["id"]?.GetValue<string>()); | |
| 157 | 新增: if(frame["panes"] is JsonArray panes)foreach(var pane in panes.OfType<JsonObject>())AssertEditorTab(pane["id"]?.GetValue<string>()); | |
| 158 | 新增: } | |
| 159 | 新增: private static void AssertRequestedTab(JsonObject input,JsonObject proof) | |
| 160 | 新增: {AssertEditorTab(proof["id"]?.GetValue<string>());if(input["id"]?.GetValue<string>() is {Length:>0} id&&id!=proof["id"]?.GetValue<string>())throw new InvalidDataException("browser_target_changed");} | |
| 161 | 新增: | |
| 162 | 新增: private static async Task ReleasePagePointer(CancellationToken token) | |
| 163 | 新增: { | |
| 164 | 新增: if (browser is not null && !browser.HasExited) | |
| 165 | 新增: await Control(new JsonObject { ["operation"] = "input-release-pointer" }, token); | |
| 166 | 新增: pagePointerOwner = null; | |
| 167 | 新增: pagePointerReleasePending = false; | |
| 168 | 新增: } | |
| 169 | 新增: | |
| 170 | 新增: private static async Task<JsonObject> Exchange(JsonObject request, CancellationToken connection, NativeInputCoordinator.Lease lease) | |
| 171 | 新增: { | |
| 172 | 新增: if (request["path"]?.GetValue<string>()?.StartsWith("/phone-browser/", StringComparison.Ordinal) == true) | |
| 173 | 新增: return await WindowsPhoneBrowser.Exchange(request, connection, lease); | |
| 174 | 新增: await Gate.WaitAsync(connection); | |
| 175 | 新增: try | |
| 176 | 新增: { | |
| 177 | 新增: // The connection token must not interrupt the child's reply drain. | |
| 178 | 新增: using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(35)); | |
| 179 | 新增: var route = request["path"]?.GetValue<string>() ?? ""; | |
| 180 | 新增: var input = request["input"] as JsonObject ?? new JsonObject(); | |
| 181 | 新增: if(route is "/paste-cancel" or "/image-cancel") | |
| 182 | 新增: { | |
| 183 | 新增: BrowserPasteInput.Cancel(input["transfer"]?.GetValue<string>() ?? ""); | |
| 184 | 新增: return new JsonObject { ["ok"] = true }; | |
| 185 | 新增: } | |
| 186 | 新增: if(route=="/input"&&BrowserWindowCapture.ReleaseInput(lease,input))return new JsonObject { ["ok"] = true }; | |
| 187 | 新增: await Start(timeout.Token); | |
| 188 | 新增: if (pagePointerReleasePending) await ReleasePagePointer(timeout.Token); | |
| 189 | 新增: if (pagePointerOwner is not null && route is "/resize" or "/navigate" or "/new" or "/close" or "/activate" or "/split" or "/back" or "/forward" or "/reload" or "/paste" or "/cut" or "/copy" or "/select-all" or "/insert-text") | |
| 190 | 新增: await ReleasePagePointer(timeout.Token); | |
| 191 | 新增: connection.ThrowIfCancellationRequested(); | |
| 192 | 新增: WindowsEditorServer.Connection? editor = null; | |
| 193 | 新增: if (route is "/editor" or "/editor-restart") | |
| 194 | 新增: { | |
| 195 | 新增: var project = input["project_id"]?.GetValue<string>() ?? ""; | |
| 196 | 新增: var grant = input["grant"]?.GetValue<string>() ?? ""; | |
| 197 | 新增: editor = await WindowsEditorServer.Open(project, grant, route == "/editor-restart", timeout.Token); | |
| 198 | 新增: connection.ThrowIfCancellationRequested(); | |
| 199 | 新增: EditorConnections[editor.ID] = editor; | |
| 200 | 新增: await Control(new JsonObject { ["operation"] = "editor-connect", ["input"] = new JsonObject | |
| 201 | 新增: { | |
| 202 | 新增: ["workspace"] = project, ["folder"] = editor.Folder, ["url"] = editor.URL, ["connection"] = editor.ID, | |
| 203 | 新增: ["trust_default"] = editor.TrustDefault.HasValue ? JsonValue.Create(editor.TrustDefault.Value) : null, | |
| 204 | 新增: } }, timeout.Token); | |
| 205 | 新增: // Authorization uses only Resolve; a wire Workspace never selects | |
| 206 | 新增: // an executable, path or browser URL. | |
| 207 | 新增: input = new JsonObject { ["workspace"] = project }; | |
| 208 | 新增: request = new JsonObject { ["method"] = "POST", ["path"] = route, ["input"] = input }; | |
| 209 | 新增: } | |
| 210 | 新增: var selected = input["id"]?.GetValue<string>() ?? active; | |
| 211 | 新增: if (route is not ("/tabs" or "/events" or "/audit" or "/close" or "/new" or "/settings" or "/extensions" or "/internal-page" or "/editor" or "/editor-restart"))AssertEditorTab(selected); | |
| 212 | 新增: if(route=="/split" && input["left"] is not null){AssertEditorTab(input["left"]?.GetValue<string>());AssertEditorTab(input["right"]?.GetValue<string>());} | |
| 213 | 新增: if (route.StartsWith("/image-", StringComparison.Ordinal) || route.StartsWith("/paste-", StringComparison.Ordinal)) | |
| 214 | 新增: { | |
| 215 | 新增: if(route=="/image-start")input["mime"]="image/png"; | |
| 216 | 新增: route=route.Replace("/paste-","/image-",StringComparison.Ordinal); | |
| 217 | 新增: if (route == "/image-cancel") { BrowserPasteInput.Cancel(input["transfer"]?.GetValue<string>() ?? ""); return new JsonObject { ["ok"] = true }; } | |
| 218 | 新增: if (route == "/image-chunk") return BrowserPasteInput.Chunk(input); | |
| 219 | 新增: var proof = await Control(new JsonObject { ["method"] = "GET", ["path"] = "/frame-proof" }, timeout.Token); | |
| 220 | 新增: AssertEditorTab(proof["id"]?.GetValue<string>()); | |
| 221 | 新增: var focus = await Control(new JsonObject { ["method"] = "GET", ["path"] = "/focus-proof" }, timeout.Token); | |
| 222 | 新增: if (route == "/image-start") return await BrowserPasteInput.Start(input, proof, focus); | |
| 223 | 新增: if (route == "/image-finish") return await BrowserPasteInput.Finish(input, proof, focus, async () => | |
| 224 | 新增: { | |
| 225 | 新增: var current = await Control(new JsonObject { ["method"] = "GET", ["path"] = "/frame-proof" }, timeout.Token); | |
| 226 | 新增: AssertEditorTab(current["id"]?.GetValue<string>()); | |
| 227 | 新增: var field = await Control(new JsonObject { ["method"] = "GET", ["path"] = "/focus-proof" }, timeout.Token); | |
| 228 | 新增: if (current["target"]?.GetValue<string>() != proof["target"]?.GetValue<string>() || current["id"]?.GetValue<string>() != proof["id"]?.GetValue<string>() || field["focus"]?.GetValue<string>() != focus["focus"]?.GetValue<string>()) throw new InvalidDataException("image_target_changed"); | |
| 229 | 新增: if (BrowserWindowCapture.Edit(browser!, proof, "paste")) return new JsonObject { ["ok"] = true }; | |
| 230 | 新增: return await Control(new JsonObject { ["method"] = "POST", ["path"] = "/paste", ["input"] = new JsonObject { ["id"] = proof["id"]!.DeepClone(), ["document"] = proof["document"]!.DeepClone() } }, timeout.Token); | |
| 231 | 新增: }); | |
| 232 | 新增: throw new InvalidDataException("image_request_invalid"); | |
| 233 | 新增: } | |
| 234 | 新增: var clipboard = ClipboardAgent.Current; | |
| 235 | 新增: uint? previous = null; | |
| 236 | 新增: if (clipboard is not null && route is "/copy" or "/cut" or "/copy-context") previous = await clipboard.Revision(); | |
| 237 | 新增: if (clipboard is not null && route == "/paste") await clipboard.PreparePaste(); | |
| 238 | 新增: if (route == "/copy-context" && previous.HasValue && input["context"]?.GetValue<string>() is { } copyContext) | |
| 239 | 新增: { | |
| 240 | 新增: if (CopyRevisions.Count > 200) CopyRevisions.Clear(); | |
| 241 | 新增: CopyRevisions[copyContext] = previous.Value; | |
| 242 | 新增: } | |
| 243 | 新增: connection.ThrowIfCancellationRequested(); | |
| 244 | 新增: if (route == "/input") | |
| 245 | 新增: { | |
| 246 | 新增: if (input["kind"]?.GetValue<string>() == "pointer" && pagePointerOwner is not null) | |
| 247 | 新增: { | |
| 248 | 新增: if (pagePointerOwner != lease) throw new InvalidDataException("browser_target_changed"); | |
| 249 | 新增: if (input["mask"]?.GetValue<int>() == 0) | |
| 250 | 新增: { | |
| 251 | 新增: await ReleasePagePointer(timeout.Token); | |
| 252 | 新增: return new JsonObject{["ok"]=true}; | |
| 253 | 新增: } | |
| 254 | 新增: } | |
| 255 | 新增: var proof = await Control(new JsonObject { ["method"] = "GET", ["path"] = "/frame-proof" }, timeout.Token); | |
| 256 | 新增: AssertEditorTab(proof["id"]?.GetValue<string>()); | |
| 257 | 新增: if(BrowserWindowCapture.FocusRenderer(browser!,proof)) | |
| 258 | 新增: {proof=await Control(new JsonObject{["method"]="GET",["path"]="/frame-proof"},timeout.Token);AssertEditorTab(proof["id"]?.GetValue<string>());} | |
| 259 | 新增: if (pagePointerOwner != lease && BrowserWindowCapture.SelectPane(browser!, lease, input, proof)) | |
| 260 | 新增: { | |
| 261 | 新增: await Control(new JsonObject { ["operation"] = "input-select-pane", ["input"] = new JsonObject { ["target"] = proof["target"]!.DeepClone(), ["x"] = input["x"]!.DeepClone() } }, timeout.Token); | |
| 262 | 新增: proof = await Control(new JsonObject { ["method"] = "GET", ["path"] = "/frame-proof" }, timeout.Token); | |
| 263 | 新增: AssertEditorTab(proof["id"]?.GetValue<string>()); | |
| 264 | 新增: BrowserWindowCapture.Transition(browser!, proof); | |
| 265 | 新增: } | |
| 266 | 新增: if (BrowserWindowCapture.HandleInput(browser!, lease, input, proof, pagePointerOwner == lease)) | |
| 267 | 新增: { | |
| 268 | 新增: if (input["kind"]?.GetValue<string>() == "pointer") | |
| 269 | 新增: await Control(new JsonObject { ["operation"] = "input-reset" }, timeout.Token); | |
| 270 | 新增: BrowserWindowCapture.Transition(browser!, await Control(new JsonObject { ["method"] = "GET", ["path"] = "/frame-proof" }, timeout.Token)); | |
| 271 | 新增: active = proof["id"]?.GetValue<string>() ?? active; | |
| 272 | 新增: return new JsonObject { ["ok"] = true, ["active"] = active }; | |
| 273 | 新增: } | |
| 274 | 新增: if (input["kind"]?.GetValue<string>() == "pointer" && ((input["mask"]?.GetValue<int>() ?? 0) & 7) != 0) | |
| 275 | 新增: pagePointerOwner = lease; | |
| 276 | 新增: } | |
| 277 | 新增: if (route is "/paste" or "/copy" or "/cut" or "/select-all" or "/insert-text") | |
| 278 | 新增: { | |
| 279 | 新增: var proof = await Control(new JsonObject { ["method"] = "GET", ["path"] = "/frame-proof" }, timeout.Token); | |
| 280 | 新增: AssertRequestedTab(input,proof); | |
| 281 | 新增: if (BrowserWindowCapture.Edit(browser!, proof, route[1..], input["text"]?.GetValue<string>() ?? "")) | |
| 282 | 新增: { | |
| 283 | 新增: await Control(new JsonObject { ["operation"] = "input-reset" }, timeout.Token); | |
| 284 | 新增: var receipt = new JsonObject { ["ok"] = true }; | |
| 285 | 新增: if (previous.HasValue && route is "/copy" or "/cut") receipt["clipboard"] = await clipboard!.Receipt(previous.Value, true); | |
| 286 | 新增: return receipt; | |
| 287 | 新增: } | |
| 288 | 新增: } | |
| 289 | 新增: if (route == "/ime") | |
| 290 | 新增: { | |
| 291 | 新增: var proof = await Control(new JsonObject { ["method"] = "GET", ["path"] = "/frame-proof" }, timeout.Token); | |
| 292 | 新增: AssertRequestedTab(input,proof); | |
| 293 | 新增: if (input["id"]?.GetValue<string>() != proof["id"]?.GetValue<string>()) throw new InvalidDataException("browser_target_changed"); | |
| 294 | 新增: var native = await BrowserWindowCapture.Ime(browser!, proof, input, timeout.Token); | |
| 295 | 新增: if (native is not null) return native; | |
| 296 | 新增: } | |
| 297 | 新增: var afterFrame = route == "/frame" ? input["after"]?.GetValue<string>() : null; | |
| 298 | 新增: if (route == "/frame") | |
| 299 | 新增: { | |
| 300 | 新增: // Cached page pixels and the current native-window proof have | |
| 301 | 新增: // separate lifetimes. Native menus are inspected on every call. | |
| 302 | 新增: input["after"] = cachedPageFrame?["sequence"]?.DeepClone(); | |
| 303 | 新增: input["nativeProof"] = true; | |
| 304 | 新增: if (request["input"] is null) request["input"] = input; | |
| 305 | 新增: } | |
| 306 | 新增: var result = await Control(request, timeout.Token); | |
| 307 | 新增: if (route == "/frame" && result["error"] is null) | |
| 308 | 新增: { | |
| 309 | 新增: if (result["unchanged"]?.GetValue<bool>() == true) | |
| 310 | 新增: { | |
| 311 | 新增: if (cachedPageFrame is null || result["sequence"]?.GetValue<string>() != cachedPageFrame["sequence"]?.GetValue<string>()) | |
| 312 | 新增: throw new InvalidDataException("browser_target_changed"); | |
| 313 | 新增: var proof = result["native"]?.DeepClone() ?? await Control(new JsonObject { ["method"] = "GET", ["path"] = "/frame-proof" }, timeout.Token); | |
| 314 | 新增: result = (JsonObject)cachedPageFrame.DeepClone(); | |
| 315 | 新增: result["native"] = proof; | |
| 316 | 新增: } | |
| 317 | 新增: else | |
| 318 | 新增: { | |
| 319 | 新增: AssertFrameEditors(result); | |
| 320 | 新增: cachedPageFrame = (JsonObject)result.DeepClone(); | |
| 321 | 新增: } | |
| 322 | 新增: AssertFrameEditors(result); | |
| 323 | 新增: await BrowserWindowCapture.Decorate(browser!, result, async ()=>{var current=await Control(new JsonObject { ["method"] = "GET", ["path"] = "/frame-proof" }, timeout.Token);AssertEditorTab(current["id"]?.GetValue<string>());return current;}); | |
| 324 | 新增: AssertFrameEditors(result); | |
| 325 | 新增: result = BrowserWindowCapture.FrameReply(result, afterFrame); | |
| 326 | 新增: } | |
| 327 | 新增: if (result["error"] is null) | |
| 328 | 新增: { | |
| 329 | 新增: ready = true; | |
| 330 | 新增: if (result["capabilities"] is JsonObject capability) features = (JsonObject)capability.DeepClone(); | |
| 331 | 新增: else if (result["state"]?["capabilities"] is JsonObject stateCapability) features = (JsonObject)stateCapability.DeepClone(); | |
| 332 | 新增: if (result["active"]?.GetValue<string>() is { } current) active = current; | |
| 333 | 新增: if (route is "/activate" or "/new" or "/editor" or "/editor-restart") active = result["id"]?.GetValue<string>() ?? input["id"]?.GetValue<string>() ?? active; | |
| 334 | 新增: if (editor is not null && result["id"]?.GetValue<string>() is { } tabID) | |
| 335 | 新增: { | |
| 336 | 新增: if (ProjectRpc.Resolve(editor.Project, editor.Grant) != editor.Folder) throw new InvalidDataException("project_grant_unavailable"); | |
| 337 | 新增: EditorTabs[tabID] = editor; | |
| 338 | 新增: } | |
| 339 | 新增: if (route == "/close") EditorTabs.TryRemove(selected, out _); | |
| 340 | 新增: if (clipboard is not null && previous.HasValue && route is "/copy" or "/cut") | |
| 341 | 新增: result["clipboard"] = await clipboard.Receipt(previous.Value, true); | |
| 342 | 新增: if (clipboard is not null && result["events"] is JsonArray events) | |
| 343 | 新增: { | |
| 344 | 新增: foreach (var value in events.OfType<JsonObject>()) if (value["type"]?.GetValue<string>() == "clipboard") | |
| 345 | 新增: { | |
| 346 | 新增: var payload = value["value"] as JsonObject; | |
| 347 | 新增: var context = payload?["context"]?.GetValue<string>() ?? ""; | |
| 348 | 新增: payload?.Remove("text"); value["type"] = "native-clipboard"; | |
| 349 | 新增: try | |
| 350 | 新增: { | |
| 351 | 新增: if (!CopyRevisions.TryGetValue(context, out var revision)) throw new InvalidDataException("copy_context_expired"); | |
| 352 | 新增: payload!["receipt"] = await clipboard.Receipt(revision, true); | |
| 353 | 新增: } | |
| 354 | 新增: catch { value["type"] = "copy-expired"; } | |
| 355 | 新增: } | |
| 356 | 新增: } | |
| 357 | 新增: } | |
| 358 | 新增: return result; | |
| 359 | 新增: } | |
| 360 | 新增: catch (OperationCanceledException) | |
| 361 | 新增: { if (wirePending) Close(); throw new InvalidDataException("browser_response_timeout"); } | |
| 362 | 新增: catch (EndOfStreamException) { Close(); throw new InvalidDataException("browser_unavailable"); } | |
| 363 | 新增: finally { Gate.Release(); } | |
| 364 | 新增: } | |
| 365 | 新增: | |
| 366 | 新增: internal static async Task<JsonObject> ReadConfiguration(CancellationToken token, bool packetOnly = false) | |
| 367 | 新增: { | |
| 368 | 新增: var root = AppContext.BaseDirectory; | |
| 369 | 新增: var configPath = Path.Combine(root, "guest-config.json"); | |
| 370 | 新增: var info = new FileInfo(configPath); | |
| 371 | 新增: if (!info.Exists || info.Length is <= 0 or > 16384 || info.Attributes.HasFlag(FileAttributes.ReparsePoint)) | |
| 372 | 新增: throw new InvalidDataException("browser_network_unavailable"); | |
| 373 | 新增: using var snapshot = OpenPublishedFile(configPath); | |
| 374 | 新增: using var reader = new StreamReader(snapshot); | |
| 375 | 新增: var config = JsonNode.Parse(await reader.ReadToEndAsync(token)) as JsonObject | |
| 376 | 新增: ?? throw new InvalidDataException("browser_network_unavailable"); | |
| 377 | 新增: var packet = config["network_mode"]?.GetValue<string>() == "packet"; | |
| 378 | 新增: if (packetOnly && !packet) throw new InvalidDataException("browser_network_unavailable"); | |
| 379 | 新增: var proxy = config["browser_proxy"]?.GetValue<string>(); | |
| 380 | 新增: Uri? address = null; | |
| 381 | 新增: if (packet ? !PacketReady() : !Uri.TryCreate(proxy, UriKind.Absolute, out address) || address.Scheme != "http" || | |
| 382 | 新增: address.Host != "127.0.0.1" || address.IsDefaultPort || address.UserInfo != "" || | |
| 383 | 新增: address.AbsolutePath != "/" || address.Query != "" || address.Fragment != "") | |
| 384 | 新增: throw new InvalidDataException("browser_network_unavailable"); | |
| 385 | 新增: var settings = packet ? new JsonObject { ["networkMode"] = "packet" } : new JsonObject { ["proxy"] = address!.GetLeftPart(UriPartial.Authority) }; | |
| 386 | 新增: if (config["timezone"] is JsonValue zone) settings["timezone"] = zone.DeepClone(); | |
| 387 | 新增: if (config["language"] is JsonValue lang) settings["language"] = lang.DeepClone(); | |
| 388 | 新增: return settings; | |
| 389 | 新增: } | |
| 390 | 新增: private static async Task Start(CancellationToken token) | |
| 391 | 新增: { | |
| 392 | 新增: if (browser is { HasExited: false }) return; | |
| 393 | 新增: Close(); | |
| 394 | 新增: var root = AppContext.BaseDirectory; | |
| 395 | 新增: var executable = Path.Combine(root, "node.exe"); | |
| 396 | 新增: var script = Path.Combine(root, "windows-browser.mjs"); | |
| 397 | 新增: if (!File.Exists(executable) || !File.Exists(script)) throw new InvalidDataException("browser_components_missing"); | |
| 398 | 新增: var settings = await ReadConfiguration(token); | |
| 399 | 新增: var start = new ProcessStartInfo(executable) | |
| 400 | 新增: { | |
| 401 | 新增: UseShellExecute = false, RedirectStandardInput = true, RedirectStandardOutput = true, | |
| 402 | 新增: RedirectStandardError = true, CreateNoWindow = true, WorkingDirectory = root, | |
| 403 | 新增: StandardInputEncoding = Protocol.Utf8, StandardOutputEncoding = Protocol.Utf8, StandardErrorEncoding = Protocol.Utf8, | |
| 404 | 新增: }; | |
| 405 | 新增: start.ArgumentList.Add(script); | |
| 406 | 新增: browser = Process.Start(start) ?? throw new InvalidDataException("browser_unavailable"); | |
| 407 | 新增: var process = browser; | |
| 408 | 新增: try { browserJob = new GuestProcessJob(process); } | |
| 409 | 新增: catch { Close(); throw new InvalidDataException("browser_process_unavailable"); } | |
| 410 | 新增: replies = new ReadAheadStream(process.StandardOutput.BaseStream); | |
| 411 | 新增: errors = Task.Run(async () => | |
| 412 | 新增: { | |
| 413 | 新增: var discard = new char[4096]; | |
| 414 | 新增: try { while (await process.StandardError.ReadAsync(discard) != 0) { } } | |
| 415 | 新增: catch (ObjectDisposedException) { } | |
| 416 | 新增: }); | |
| 417 | 新增: var result = await Control(new JsonObject | |
| 418 | 新增: { | |
| 419 | 新增: ["operation"] = "configure", ["input"] = settings, | |
| 420 | 新增: }, token); | |
| 421 | 新增: if (result?["ok"]?.GetValue<bool>() != true) { Close(); throw new InvalidDataException("browser_network_unavailable"); } | |
| 422 | 新增: } | |
| 423 | 新增: | |
| 424 | 新增: private static async Task<JsonObject> Control(JsonObject value, CancellationToken token) | |
| 425 | 新增: { | |
| 426 | 新增: wirePending = true; | |
| 427 | 新增: await Protocol.Write(browser!.StandardInput.BaseStream, value, token); | |
| 428 | 新增: var result = await Protocol.Read(replies!, Protocol.WireLimit, token) ?? throw new EndOfStreamException(); | |
| 429 | 新增: wirePending = false; | |
| 430 | 新增: return result; | |
| 431 | 新增: } | |
| 432 | 新增: | |
| 433 | 新增: private static async Task RevokeNode(string project, string grant) | |
| 434 | 新增: { | |
| 435 | 新增: await Gate.WaitAsync(); | |
| 436 | 新增: try | |
| 437 | 新增: { | |
| 438 | 新增: if (browser is not { HasExited: false }) return; | |
| 439 | 新增: using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(5)); | |
| 440 | 新增: foreach (var editor in EditorConnections.Values.Where(e => e.Project == project && e.Grant == grant)) | |
| 441 | 新增: { | |
| 442 | 新增: await Control(new JsonObject { ["operation"] = "editor-revoke", ["input"] = new JsonObject { ["workspace"] = project, ["connection"] = editor.ID } }, timeout.Token); | |
| 443 | 新增: EditorConnections.TryRemove(editor.ID, out _); | |
| 444 | 新增: } | |
| 445 | 新增: } | |
| 446 | 新增: catch { /* Every editor request also checks the live project resolver. */ } | |
| 447 | 新增: finally { Gate.Release(); } | |
| 448 | 新增: } | |
| 449 | 新增: | |
| 450 | 新增: internal static bool BrowserExecutableInstalled() => | |
| 451 | 新增: File.Exists(Path.Combine(AppContext.BaseDirectory, "chrome", "chrome.exe")) || | |
| 452 | 新增: new[] { Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles), Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86) } | |
| 453 | 新增: .Any(basePath => new[] { "Google/Chrome/Application/chrome.exe", "Microsoft/Edge/Application/msedge.exe" }.Any(relative => File.Exists(Path.Combine(basePath, relative)))); | |
| 454 | 新增: | |
| 455 | 新增: internal static JsonObject Status() | |
| 456 | 新增: { | |
| 457 | 新增: var root = AppContext.BaseDirectory; | |
| 458 | 新增: var installed = new[] { "node.exe", "windows-browser.mjs", "windows-browser-extensions.mjs", "playwright/index.mjs", "modules/browser-clipboard.mjs", "modules/browser-uploads.mjs", "modules/browser-downloads.mjs", "modules/browser-cookies.mjs", "modules/browser-extensions.mjs", "modules/browser-vault.mjs", "split-extension/manifest.json", "split-extension/control.html", "split-extension/control.js" }.All(file => File.Exists(Path.Combine(root, file))); | |
| 459 | 新增: installed &= BrowserExecutableInstalled(); | |
| 460 | 新增: var network = false;var phoneNetwork = false; | |
| 461 | 新增: try | |
| 462 | 新增: { | |
| 463 | 新增: var file = new FileInfo(Path.Combine(root, "guest-config.json")); | |
| 464 | 新增: JsonObject? config = null; | |
| 465 | 新增: if (file.Exists && file.Length is > 0 and <= 16384) | |
| 466 | 新增: { | |
| 467 | 新增: using var snapshot = OpenPublishedFile(file.FullName); | |
| 468 | 新增: using var reader = new StreamReader(snapshot); | |
| 469 | 新增: config = JsonNode.Parse(reader.ReadToEnd()) as JsonObject; | |
| 470 | 新增: } | |
| 471 | 新增: phoneNetwork = config?["network_mode"]?.GetValue<string>() == "packet" && PacketReady(); | |
| 472 | 新增: network = config?["network_mode"]?.GetValue<string>() == "packet" ? phoneNetwork : Uri.TryCreate(config?["browser_proxy"]?.GetValue<string>(), UriKind.Absolute, out var proxy) && proxy.Scheme == "http" && proxy.Host == "127.0.0.1" && !proxy.IsDefaultPort && proxy.UserInfo == "" && proxy.AbsolutePath == "/" && proxy.Query == "" && proxy.Fragment == ""; | |
| 473 | 新增: } | |
| 474 | 新增: catch { } | |
| 475 | 新增: return new JsonObject { ["installed"] = installed, ["network_configured"] = network, ["ready"] = ready && browser is { HasExited: false } && SessionGuard.Available(), ["editor_installed"] = WindowsEditorServer.Installed(), ["phone_installed"] = WindowsPhoneBrowser.Installed(), ["phone_network_configured"] = phoneNetwork, ["capabilities"] = features.DeepClone() }; | |
| 476 | 新增: } | |
| 477 | 新增: | |
| 478 | 新增: private static async Task Observe(Task task) { try { await task; } catch { /* reply drain owns cleanup */ } } | |
| 479 | 新增: | |
| 480 | 新增: private static FileStream OpenPublishedFile(string path) | |
| 481 | 新增: { | |
| 482 | 新增: var snapshot = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read | FileShare.Delete); | |
| 483 | 新增: if (snapshot.Length is > 0 and <= 16384) return snapshot; | |
| 484 | 新增: snapshot.Dispose(); | |
| 485 | 新增: throw new InvalidDataException("browser_network_unavailable"); | |
| 486 | 新增: } | |
| 487 | 新增: | |
| 488 | 新增: internal static void Close() | |
| 489 | 新增: { | |
| 490 | 新增: ready = false; | |
| 491 | 新增: wirePending = false; | |
| 492 | 新增: cachedPageFrame = null; | |
| 493 | 新增: pagePointerOwner = null; | |
| 494 | 新增: pagePointerReleasePending = false; | |
| 495 | 新增: BrowserWindowCapture.Close(); | |
| 496 | 新增: BrowserPasteInput.Close(); | |
| 497 | 新增: var process = Interlocked.Exchange(ref browser, null); | |
| 498 | 新增: if (process is null) return; | |
| 499 | 新增: try | |
| 500 | 新增: { | |
| 501 | 新增: process.StandardInput.Close(); | |
| 502 | 新增: if (!process.WaitForExit(2000)) process.Kill(true); | |
| 503 | 新增: process.WaitForExit(2000); | |
| 504 | 新增: } | |
| 505 | 新增: catch (InvalidOperationException) { } | |
| 506 | 新增: finally { browserJob?.Dispose(); browserJob = null; replies?.Dispose(); replies = null; process.Dispose(); } | |
| 507 | 新增: if (errors is { IsCompleted: true }) { try { errors.GetAwaiter().GetResult(); } catch { } } | |
| 508 | 新增: errors = null; | |
| 509 | 新增: } | |
| 510 | 新增:} | |
| @@ -0,0 +1,436 @@ | ||
| 1 | 新增:using System.Diagnostics; | |
| 2 | 新增:using System.Drawing.Drawing2D; | |
| 3 | 新增:using System.Drawing.Imaging; | |
| 4 | 新增:using System.Runtime.InteropServices; | |
| 5 | 新增:using System.Security.Cryptography; | |
| 6 | 新增:using System.Security.Principal; | |
| 7 | 新增:using System.Text; | |
| 8 | 新增:using System.Text.Json.Nodes; | |
| 9 | 新增:using InputLease = Cage.GuestClipboard.NativeInputCoordinator.Lease; | |
| 10 | 新增: | |
| 11 | 新增:namespace Cage.GuestClipboard; | |
| 12 | 新增: | |
| 13 | 新增:// Only the current Node child's Chrome UI is eligible. Public requests never | |
| 14 | 新增:// supply a PID, HWND, screen rectangle or executable path. | |
| 15 | 新增:internal static class BrowserWindowCapture | |
| 16 | 新增:{ | |
| 17 | 新增: private static readonly SemaphoreSlim Captures = new(1, 1); | |
| 18 | 新增: private static readonly Dictionary<int, Pin> Windows = new(); | |
| 19 | 新增: private static View? last; | |
| 20 | 新增: private static string publicTarget=""; | |
| 21 | 新增: private sealed record OverlayCache(byte[] Pixels, Rectangle Crop, Rectangle Destination, JsonObject Image); | |
| 22 | 新增: private static OverlayCache? cachedOverlay; | |
| 23 | 新增: private static JsonObject? lastFrame; | |
| 24 | 新增: private static string lastSequence = ""; | |
| 25 | 新增: private static readonly HashSet<InputLease> browserLeases = []; | |
| 26 | 新增: internal static InputLease OpenLease(){var lease=NativeGuestInput.OpenLease();lock(browserLeases)browserLeases.Add(lease);return lease;} | |
| 27 | 新增: internal static void CloseLease(InputLease lease){lock(browserLeases)browserLeases.Remove(lease);NativeGuestInput.CloseLease(lease);} | |
| 28 | 新增: internal static bool ReleaseInput(InputLease lease,JsonObject input) | |
| 29 | 新增: { | |
| 30 | 新增: if(input["kind"]?.GetValue<string>()=="key"&&input["down"]?.GetValue<bool>()==false) | |
| 31 | 新增: { | |
| 32 | 新增: if(lease.Symbols.Remove(input["keysym"]?.GetValue<uint>()??0,out var strokes))NativeGuestInput.ReleaseInputs(lease,strokes); | |
| 33 | 新增: return true; | |
| 34 | 新增: } | |
| 35 | 新增: var buttons=NativeGuestInput.PressedButtons(lease); | |
| 36 | 新增: if(buttons!=0&&input["kind"]?.GetValue<string>()=="pointer"&&input["mask"]?.GetValue<int>()==0) | |
| 37 | 新增: { | |
| 38 | 新增: NativeGuestInput.ReleaseInputs(lease,new[]{1,2,4}.Where(bit=>(buttons&bit)!=0).Select(bit=>InputStroke.Button(bit,true)).ToArray());return true; | |
| 39 | 新增: } | |
| 40 | 新增: return false; | |
| 41 | 新增: } | |
| 42 | 新增: internal static bool FocusRenderer(Process node,JsonObject proof) | |
| 43 | 新增: {var view=Resolve(node,proof);if(view.NativeUI)return false;Focus(view);return true;} | |
| 44 | 新增: private sealed record Pin(Process Process, DateTime Started, string Executable, IntPtr Window); | |
| 45 | 新增: private sealed record Popup(IntPtr Window, Rectangle Bounds, Rectangle Client); | |
| 46 | 新增: private sealed record View(Pin Pin, Rectangle Window, Rectangle Client, Rectangle Surface, Popup[] Popups, bool NativeUI, bool InlineUI, | |
| 47 | 新增: string NodeTarget, string Document, string ID, string Token, int X, int Y, int Width, int Height); | |
| 48 | 新增: [StructLayout(LayoutKind.Sequential)] private struct Rect { internal int Left, Top, Right, Bottom; internal readonly Rectangle Box => Rectangle.FromLTRB(Left, Top, Right, Bottom); } | |
| 49 | 新增: [StructLayout(LayoutKind.Sequential)] private struct Point { internal int X,Y; } | |
| 50 | 新增: [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Unicode)] private struct ProcessEntry { internal uint Size,Usage,ID;internal nuint Heap;internal uint Module,Threads,Parent;internal int Priority;internal uint Flags;[MarshalAs(UnmanagedType.ByValTStr,SizeConst=260)]internal string File; } | |
| 51 | 新增: [StructLayout(LayoutKind.Sequential)] private struct GuiThread { internal uint Size,Flags;internal IntPtr Active,Focus,Capture,MenuOwner,MoveSize,Caret;internal Rect CaretRect; } | |
| 52 | 新增: private delegate bool Enumerate(IntPtr window, IntPtr data); | |
| 53 | 新增: | |
| 54 | 新增: private static void ValidateNode(Process node) | |
| 55 | 新增: { if (!SessionGuard.Available() || node.HasExited || node.SessionId != Process.GetCurrentProcess().SessionId) throw new InvalidDataException("browser_target_changed"); } | |
| 56 | 新增: private static void Validate(Pin pin) | |
| 57 | 新增: { | |
| 58 | 新增: if (!SessionGuard.Available() || pin.Process.HasExited || pin.Process.StartTime.ToUniversalTime() != pin.Started || !IsWindowVisible(pin.Window) || IsIconic(pin.Window) || | |
| 59 | 新增: GetWindowThreadProcessId(pin.Window,out var pid)==0 || pid!=pin.Process.Id || !string.Equals(pin.Process.MainModule?.FileName,pin.Executable,StringComparison.OrdinalIgnoreCase)) throw new InvalidDataException("browser_target_changed"); | |
| 60 | 新增: } | |
| 61 | 新增: private static Process Chrome(Process node) | |
| 62 | 新增: { | |
| 63 | 新增: ValidateNode(node); | |
| 64 | 新增: var choices = new[] { | |
| 65 | 新增: Path.Combine(AppContext.BaseDirectory,"chrome","chrome.exe"), | |
| 66 | 新增: Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles),"Google","Chrome","Application","chrome.exe"), | |
| 67 | 新增: Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86),"Google","Chrome","Application","chrome.exe"), | |
| 68 | 新增: Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles),"Microsoft","Edge","Application","msedge.exe"), | |
| 69 | 新增: Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86),"Microsoft","Edge","Application","msedge.exe"), | |
| 70 | 新增: }; | |
| 71 | 新增: var snapshot=CreateToolhelp32Snapshot(2,0); | |
| 72 | 新增: if(snapshot==new IntPtr(-1))throw new InvalidDataException("browser_process_unavailable"); | |
| 73 | 新增: var found=new List<Process>(); | |
| 74 | 新增: try | |
| 75 | 新增: { | |
| 76 | 新增: var entry=new ProcessEntry{Size=(uint)Marshal.SizeOf<ProcessEntry>(),File=""}; | |
| 77 | 新增: if(Process32First(snapshot,ref entry))do | |
| 78 | 新增: { | |
| 79 | 新增: if(entry.Parent!=node.Id)continue; | |
| 80 | 新增: Process? process=null; | |
| 81 | 新增: try | |
| 82 | 新增: { | |
| 83 | 新增: process=Process.GetProcessById((int)entry.ID); | |
| 84 | 新增: var executable=process.MainModule?.FileName; | |
| 85 | 新增: if(process.SessionId!=node.SessionId || process.StartTime<node.StartTime || executable is null || !choices.Contains(executable,StringComparer.OrdinalIgnoreCase))continue; | |
| 86 | 新增: if(!SessionGuard.OwnsProcess(process))continue; | |
| 87 | 新增: found.Add(process);process=null; | |
| 88 | 新增: } | |
| 89 | 新增: catch { } | |
| 90 | 新增: finally {process?.Dispose();} | |
| 91 | 新增: }while(Process32Next(snapshot,ref entry)); | |
| 92 | 新增: } | |
| 93 | 新增: finally {CloseHandle(snapshot);} | |
| 94 | 新增: if(found.Count!=1){foreach(var p in found)p.Dispose();throw new InvalidDataException("browser_process_unavailable");} | |
| 95 | 新增: return found[0]; | |
| 96 | 新增: } | |
| 97 | 新增: private static Rectangle Client(IntPtr window) | |
| 98 | 新增: { | |
| 99 | 新增: if(!GetClientRect(window,out var client))throw new InvalidDataException("browser_target_changed"); | |
| 100 | 新增: var point=new Point();if(!ClientToScreen(window,ref point))throw new InvalidDataException("browser_target_changed"); | |
| 101 | 新增: return new Rectangle(point.X,point.Y,client.Right-client.Left,client.Bottom-client.Top); | |
| 102 | 新增: } | |
| 103 | 新增: private static string Class(IntPtr window){var text=new StringBuilder(128);return GetClassName(window,text,text.Capacity)>0?text.ToString():"";} | |
| 104 | 新增: private static Rectangle RendererSurface(IntPtr window,Rectangle client) | |
| 105 | 新增: { | |
| 106 | 新增: // Chrome can retain visible renderer HWNDs for background documents. | |
| 107 | 新增: // Hit testing follows native child z-order; the largest old rectangle | |
| 108 | 新增: // is not evidence that its document is the one on screen. | |
| 109 | 新增: var screen=new Point{X=client.X+client.Width/2,Y=client.Y+client.Height/2}; | |
| 110 | 新增: var parent=window;Rectangle surface=default; | |
| 111 | 新增: for(var depth=0;depth<32;depth++) | |
| 112 | 新增: { | |
| 113 | 新增: var point=screen;if(!ScreenToClient(parent,ref point))throw new InvalidDataException("browser_target_changed"); | |
| 114 | 新增: // Chromium's legacy renderer HWND can be transparent/disabled | |
| 115 | 新增: // while still representing the visible compositor surface. | |
| 116 | 新增: var child=ChildWindowFromPointEx(parent,point,1); | |
| 117 | 新增: if(child==IntPtr.Zero||child==parent)break; | |
| 118 | 新增: if(!IsWindowVisible(child)||GetAncestor(child,2)!=window)throw new InvalidDataException("browser_target_changed"); | |
| 119 | 新增: // CDP can render a viewport larger than the native window. Keep | |
| 120 | 新增: // that complete surface for coordinate conversion and clip only | |
| 121 | 新增: // the native pixels we actually capture below. | |
| 122 | 新增: if(Class(child)=="Chrome_RenderWidgetHostHWND"&&GetWindowRect(child,out var rect))surface=rect.Box; | |
| 123 | 新增: parent=child; | |
| 124 | 新增: } | |
| 125 | 新增: if(surface.Width<1||surface.Height<1)throw new InvalidDataException("browser_capture_surface_unavailable"); | |
| 126 | 新增: return surface; | |
| 127 | 新增: } | |
| 128 | 新增: private static bool Matches(IntPtr window,JsonObject bounds) | |
| 129 | 新增: { | |
| 130 | 新增: if(!GetWindowRect(window,out var rectangle))return false; | |
| 131 | 新增: var box=rectangle.Box; | |
| 132 | 新增: foreach(var scale in new[]{1.0,GetDpiForWindow(window)/96.0}) | |
| 133 | 新增: { | |
| 134 | 新增: int left=(int)Math.Round((bounds["left"]?.GetValue<double>()??double.NaN)*scale),top=(int)Math.Round((bounds["top"]?.GetValue<double>()??double.NaN)*scale); | |
| 135 | 新增: int width=(int)Math.Round((bounds["width"]?.GetValue<double>()??0)*scale),height=(int)Math.Round((bounds["height"]?.GetValue<double>()??0)*scale); | |
| 136 | 新增: if(Math.Abs(box.Left-left)<=12 && Math.Abs(box.Top-top)<=12 && Math.Abs(box.Width-width)<=24 && Math.Abs(box.Height-height)<=24)return true; | |
| 137 | 新增: } | |
| 138 | 新增: return false; | |
| 139 | 新增: } | |
| 140 | 新增: private static View Resolve(Process node,JsonObject proof) | |
| 141 | 新增: { | |
| 142 | 新增: ValidateNode(node); | |
| 143 | 新增: var old=SetThreadDpiAwarenessContext(new IntPtr(-4)); | |
| 144 | 新增: try | |
| 145 | 新增: { | |
| 146 | 新增: var windowInfo=proof["window"] as JsonObject??throw new InvalidDataException("browser_window_proof_invalid"); | |
| 147 | 新增: var id=windowInfo["windowId"]?.GetValue<int>()??0; | |
| 148 | 新增: var bounds=windowInfo["bounds"] as JsonObject??throw new InvalidDataException("browser_window_proof_invalid"); | |
| 149 | 新增: Pin? pin=null; | |
| 150 | 新增: if(Windows.TryGetValue(id,out var existing)) | |
| 151 | 新增: { | |
| 152 | 新增: try {Validate(existing);if(Matches(existing.Window,bounds))pin=existing;else{Windows.Remove(id);existing.Process.Dispose();}} | |
| 153 | 新增: catch {Windows.Remove(id);existing.Process.Dispose();} | |
| 154 | 新增: } | |
| 155 | 新增: if(pin is null) | |
| 156 | 新增: { | |
| 157 | 新增: var process=Chrome(node);var candidates=new List<IntPtr>(); | |
| 158 | 新增: EnumWindows((window,_)=>{if(GetWindowThreadProcessId(window,out var pid)!=0 && pid==process.Id && IsWindowVisible(window) && !IsIconic(window) && GetWindow(window,4)==IntPtr.Zero && Class(window)=="Chrome_WidgetWin_1" && Matches(window,bounds))candidates.Add(window);return true;},IntPtr.Zero); | |
| 159 | 新增: var foreground=GetAncestor(GetForegroundWindow(),3); | |
| 160 | 新增: if(proof["documentFocused"]?.GetValue<bool>()==true && candidates.Contains(foreground))candidates=[foreground]; | |
| 161 | 新增: if(candidates.Count!=1){process.Dispose();throw new InvalidDataException("browser_window_unavailable");} | |
| 162 | 新增: pin=new Pin(process,process.StartTime.ToUniversalTime(),process.MainModule!.FileName,candidates[0]);Windows[id]=pin; | |
| 163 | 新增: } | |
| 164 | 新增: Validate(pin); | |
| 165 | 新增: if(!GetWindowRect(pin.Window,out var outside))throw new InvalidDataException("browser_target_changed"); | |
| 166 | 新增: var client=Client(pin.Window);var surface=RendererSurface(pin.Window,client); | |
| 167 | 新增: var popups=new List<Popup>(); | |
| 168 | 新增: EnumWindows((window,_)=>{if(window!=pin.Window && GetWindowThreadProcessId(window,out var pid)!=0 && pid==pin.Process.Id && GetAncestor(window,3)==pin.Window && IsWindowVisible(window) && !IsIconic(window) && GetWindowRect(window,out var rect)) | |
| 169 | 新增: {var c=Client(window);if(c.Width>0&&c.Height>0&&(long)c.Width*c.Height<=40_000_000)popups.Add(new Popup(window,rect.Box,c));}return true;},IntPtr.Zero); | |
| 170 | 新增: var thread=GetWindowThreadProcessId(pin.Window,out _);var info=new GuiThread{Size=(uint)Marshal.SizeOf<GuiThread>()}; | |
| 171 | 新增: var inlineUI=GetGUIThreadInfo(thread,ref info) && info.Focus!=IntPtr.Zero && GetAncestor(info.Focus,2)==pin.Window && proof["documentFocused"]?.GetValue<bool>()!=true && Class(info.Focus)!="Chrome_RenderWidgetHostHWND"; | |
| 172 | 新增: var ui=popups.Count>0 || inlineUI; | |
| 173 | 新增: var target=proof["target"]?.GetValue<string>()??"";var document=proof["document"]?.GetValue<string>()??""; | |
| 174 | 新增: var signature=new JsonArray(target,document,id,pin.Window.ToInt64(),outside.Left,outside.Top,outside.Right,outside.Bottom,surface.X,surface.Y,surface.Width,surface.Height,ui,inlineUI, | |
| 175 | 新增: new JsonArray(popups.Select(p=>(JsonNode)new JsonArray(p.Window.ToInt64(),p.Bounds.X,p.Bounds.Y,p.Bounds.Width,p.Bounds.Height)).ToArray())).ToJsonString(); | |
| 176 | 新增: var opaque=Convert.ToHexString(SHA256.HashData(Protocol.Utf8.GetBytes(signature))).ToLowerInvariant()[..32]; | |
| 177 | 新增: return new View(pin,outside.Box,client,surface,popups.ToArray(),ui,inlineUI,target,document,proof["id"]?.GetValue<string>()??"",opaque, | |
| 178 | 新增: proof["x"]?.GetValue<int>()??0,proof["y"]?.GetValue<int>()??0,proof["width"]?.GetValue<int>()??0,proof["height"]?.GetValue<int>()??0); | |
| 179 | 新增: } | |
| 180 | 新增: finally {if(old!=IntPtr.Zero)SetThreadDpiAwarenessContext(old);} | |
| 181 | 新增: } | |
| 182 | 新增: internal static async Task Decorate(Process node,JsonObject frame,Func<Task<JsonObject>> currentProof) | |
| 183 | 新增: { | |
| 184 | 新增: var proof=frame["native"] as JsonObject??throw new InvalidDataException("browser_window_proof_invalid"); | |
| 185 | 新增: if(proof["target"]?.GetValue<string>()!=frame["target"]?.GetValue<string>())throw new InvalidDataException("browser_target_changed"); | |
| 186 | 新增: var view=Resolve(node,proof); | |
| 187 | 新增: var overlays=new JsonArray(); | |
| 188 | 新增: if(view.NativeUI) | |
| 189 | 新增: { | |
| 190 | 新增: await Captures.WaitAsync(); | |
| 191 | 新增: try | |
| 192 | 新增: { | |
| 193 | 新增: // An independent popup has its own validated capture below. | |
| 194 | 新增: // Keep the underlying CDP page instead of duplicating Edge's | |
| 195 | 新增: // window controls and tab strip inside the Cage browser pane. | |
| 196 | 新增: if (view.Popups.Length == 0) | |
| 197 | 新增: { | |
| 198 | 新增: var bytes=await GuestWindowCapture.Capture(view.Pin.Window,view.Pin.Process.Id,view.Client.Width,view.Client.Height, | |
| 199 | 新增: ()=>Validate(view.Pin),allowSolid:proof["blankDocument"]?.GetValue<bool>()==true); | |
| 200 | 新增: var visible = Rectangle.Intersect(view.Surface, view.Client); | |
| 201 | 新增: var crop = new Rectangle(visible.X - view.Client.X, visible.Y - view.Client.Y, visible.Width, visible.Height); | |
| 202 | 新增: var sx = (double)view.Width / view.Surface.Width; | |
| 203 | 新增: var sy = (double)view.Height / view.Surface.Height; | |
| 204 | 新增: overlays.Add(Image(bytes, crop, | |
| 205 | 新增: view.X + (int)Math.Round((visible.X - view.Surface.X) * sx), | |
| 206 | 新增: view.Y + (int)Math.Round((visible.Y - view.Surface.Y) * sy), | |
| 207 | 新增: (int)Math.Round(visible.Width * sx), (int)Math.Round(visible.Height * sy))); | |
| 208 | 新增: } | |
| 209 | 新增: foreach(var popup in view.Popups.Reverse()) | |
| 210 | 新增: { | |
| 211 | 新增: void Check(){Validate(view.Pin);if(GetWindowThreadProcessId(popup.Window,out var pid)==0||pid!=view.Pin.Process.Id||GetAncestor(popup.Window,3)!=view.Pin.Window||!GetWindowRect(popup.Window,out var rect)||rect.Box!=popup.Bounds||Client(popup.Window)!=popup.Client)throw new InvalidDataException("browser_target_changed");} | |
| 212 | 新增: var png=await GuestWindowCapture.Capture(popup.Window,view.Pin.Process.Id,popup.Client.Width,popup.Client.Height,Check,preserveAlpha:true); | |
| 213 | 新增: var sx=(double)view.Width/view.Surface.Width;var sy=(double)view.Height/view.Surface.Height; | |
| 214 | 新增: var destination=new Rectangle(view.X+(int)Math.Round((popup.Client.X-view.Surface.X)*sx),view.Y+(int)Math.Round((popup.Client.Y-view.Surface.Y)*sy),(int)Math.Round(popup.Client.Width*sx),(int)Math.Round(popup.Client.Height*sy)); | |
| 215 | 新增: var clipped=Rectangle.Intersect(destination,new Rectangle(0,0,frame["width"]!.GetValue<int>(),frame["height"]!.GetValue<int>())); | |
| 216 | 新增: if(clipped.Width<1||clipped.Height<1)continue; | |
| 217 | 新增: var sectionX=(int)Math.Round((clipped.X-destination.X)/sx);var sectionY=(int)Math.Round((clipped.Y-destination.Y)/sy); | |
| 218 | 新增: var section=new Rectangle(sectionX,sectionY,Math.Min(popup.Client.Width-sectionX,(int)Math.Round(clipped.Width/sx)),Math.Min(popup.Client.Height-sectionY,(int)Math.Round(clipped.Height/sy))); | |
| 219 | 新增: overlays.Add(Image(png,section,clipped.X,clipped.Y,clipped.Width,clipped.Height)); | |
| 220 | 新增: } | |
| 221 | 新增: var after=Resolve(node,await currentProof());if(after.Token!=view.Token)throw new InvalidDataException("browser_target_changed"); | |
| 222 | 新增: } | |
| 223 | 新增: finally {Captures.Release();} | |
| 224 | 新增: } | |
| 225 | 新增: last=view;publicTarget=view.Token;frame["target"]=view.Token;frame.Remove("native");if(overlays.Count>0)frame["overlays"]=overlays; | |
| 226 | 新增: } | |
| 227 | 新增: internal static JsonObject FrameReply(JsonObject frame, string? after) | |
| 228 | 新增: { | |
| 229 | 新增: frame.Remove("sequence"); | |
| 230 | 新增: if (lastFrame is null || !JsonNode.DeepEquals(lastFrame, frame)) | |
| 231 | 新增: { | |
| 232 | 新增: var bytes = System.Text.Json.JsonSerializer.SerializeToUtf8Bytes(frame); | |
| 233 | 新增: if (bytes.Length > Protocol.WireLimit) throw new InvalidDataException("browser_frame_limit"); | |
| 234 | 新增: lastSequence = Convert.ToHexString(SHA256.HashData(bytes)); | |
| 235 | 新增: lastFrame = (JsonObject)frame.DeepClone(); | |
| 236 | 新增: } | |
| 237 | 新增: var sequence = lastSequence; | |
| 238 | 新增: if (sequence == after) return new JsonObject { ["unchanged"] = true, ["sequence"] = sequence }; | |
| 239 | 新增: frame["sequence"] = sequence; | |
| 240 | 新增: return frame; | |
| 241 | 新增: } | |
| 242 | 新增: | |
| 243 | 新增: private static JsonObject Image(byte[] pixels,Rectangle region,int x,int y,int width,int height) | |
| 244 | 新增: { | |
| 245 | 新增: var destination = new Rectangle(x, y, width, height); | |
| 246 | 新增: if (cachedOverlay is { } cached && ReferenceEquals(cached.Pixels, pixels) && cached.Crop == region && cached.Destination == destination) | |
| 247 | 新增: return (JsonObject)cached.Image.DeepClone(); | |
| 248 | 新增: using var input = new MemoryStream(pixels, false); | |
| 249 | 新增: using var source = new Bitmap(input); | |
| 250 | 新增: if(width<1||height<1||(long)width*height>40_000_000||region.X<0||region.Y<0||region.Right>source.Width||region.Bottom>source.Height)throw new InvalidDataException("browser_frame_limit"); | |
| 251 | 新增: using var output=new Bitmap(width,height,PixelFormat.Format32bppArgb);using(var g=Graphics.FromImage(output)){g.InterpolationMode=InterpolationMode.HighQualityBicubic;g.DrawImage(source,new Rectangle(0,0,width,height),region,GraphicsUnit.Pixel);} | |
| 252 | 新增: using var bytes=new MemoryStream();output.Save(bytes,ImageFormat.Png);if(bytes.Length>Protocol.PngLimit)throw new InvalidDataException("browser_frame_limit"); | |
| 253 | 新增: var image = new JsonObject{["png"]=Convert.ToBase64String(bytes.ToArray()),["x"]=x,["y"]=y,["width"]=width,["height"]=height}; | |
| 254 | 新增: cachedOverlay = new OverlayCache(pixels, region, destination, (JsonObject)image.DeepClone()); | |
| 255 | 新增: return image; | |
| 256 | 新增: } | |
| 257 | 新增: internal static bool HandleInput(Process node,InputLease lease,JsonObject input,JsonObject proof,bool pagePointerHeld=false) | |
| 258 | 新增: { | |
| 259 | 新增: var prior=SetThreadDpiAwarenessContext(new IntPtr(-4)); | |
| 260 | 新增: try{return HandleInputCore(node,lease,input,proof,pagePointerHeld);}finally{if(prior!=IntPtr.Zero)SetThreadDpiAwarenessContext(prior);} | |
| 261 | 新增: } | |
| 262 | 新增: private static bool HandleInputCore(Process node,InputLease lease,JsonObject input,JsonObject proof,bool pagePointerHeld) | |
| 263 | 新增: { | |
| 264 | 新增: var before=last??throw new InvalidDataException("browser_target_changed");var now=Resolve(node,proof); | |
| 265 | 新增: if(pagePointerHeld && now.InlineUI && input["kind"]?.GetValue<string>()=="pointer")throw new InvalidDataException("browser_target_changed"); | |
| 266 | 新增: if(proof["focusAmbiguous"]?.GetValue<bool>()==true)throw new InvalidDataException("browser_target_changed"); | |
| 267 | 新增: if(!now.NativeUI&&proof["documentFocused"]?.GetValue<bool>()!=true)throw new InvalidDataException("browser_target_changed"); | |
| 268 | 新增: var mouseMask=NativeGuestInput.PressedButtons(lease); | |
| 269 | 新增: var released=input["kind"]?.GetValue<string>()=="key"&&input["down"]?.GetValue<bool>()==false || mouseMask!=0&&input["kind"]?.GetValue<string>()=="pointer"&&input["mask"]?.GetValue<int>()==0; | |
| 270 | 新增: if(input["target"]?.GetValue<string>()!=publicTarget || now.Token!=before.Token && !released)throw new InvalidDataException("browser_target_changed"); | |
| 271 | 新增: input["target"]=now.NodeTarget; | |
| 272 | 新增: if(input["kind"]?.GetValue<string>()=="pointer") | |
| 273 | 新增: { | |
| 274 | 新增: var x=input["x"]?.GetValue<int>()??-1;var y=input["y"]?.GetValue<int>()??-1; | |
| 275 | 新增: if(x<now.X||x>=now.X+now.Width||y<now.Y||y>=now.Y+now.Height) | |
| 276 | 新增: { | |
| 277 | 新增: if(mouseMask!=0){input["x"]=Math.Clamp(x,now.X,now.X+now.Width-1);input["y"]=Math.Clamp(y,now.Y,now.Y+now.Height-1);} | |
| 278 | 新增: else | |
| 279 | 新增: { | |
| 280 | 新增: // A click into another split pane first dismisses our own | |
| 281 | 新增: // chrome UI, then lets CDP activate that existing webpage. | |
| 282 | 新增: if(now.NativeUI){Focus(now);Tap(now,[InputStroke.Key(27,false),InputStroke.Key(27,true)]);} | |
| 283 | 新增: var modifiers=(NativeGuestInput.PressedKey(18)?1:0)|(NativeGuestInput.PressedKey(17)?2:0)|(NativeGuestInput.PressedKey(91)||NativeGuestInput.PressedKey(92)?4:0)|(NativeGuestInput.PressedKey(16)?8:0); | |
| 284 | 新增: input["modifiers"]=modifiers;return false; | |
| 285 | 新增: } | |
| 286 | 新增: } | |
| 287 | 新增: } | |
| 288 | 新增: Focus(now); | |
| 289 | 新增: if(input["kind"]?.GetValue<string>()=="pointer" && !now.InlineUI && mouseMask==0) | |
| 290 | 新增: { | |
| 291 | 新增: var x=input["x"]?.GetValue<int>()??-1; | |
| 292 | 新增: var y=input["y"]?.GetValue<int>()??-1; | |
| 293 | 新增: var screenX=now.Surface.X+(int)Math.Round((x-now.X)*(double)now.Surface.Width/now.Width); | |
| 294 | 新增: var screenY=now.Surface.Y+(int)Math.Round((y-now.Y)*(double)now.Surface.Height/now.Height); | |
| 295 | 新增: if(pagePointerHeld || !now.Popups.Any(p=>p.Client.Contains(screenX,screenY))) | |
| 296 | 新增: { | |
| 297 | 新增: // CDP page coordinates remain valid beyond the guest desktop. | |
| 298 | 新增: input["modifiers"]=(NativeGuestInput.PressedKey(18)?1:0)|(NativeGuestInput.PressedKey(17)?2:0)|(NativeGuestInput.PressedKey(91)||NativeGuestInput.PressedKey(92)?4:0)|(NativeGuestInput.PressedKey(16)?8:0); | |
| 299 | 新增: return false; | |
| 300 | 新增: } | |
| 301 | 新增: } | |
| 302 | 新增: if(input["kind"]?.GetValue<string>()=="pointer")Pointer(now,lease,input); | |
| 303 | 新增: else if(input["kind"]?.GetValue<string>()=="key")Keyboard(now,lease,input); | |
| 304 | 新增: else throw new InvalidDataException("browser_input_invalid"); | |
| 305 | 新增: return true; | |
| 306 | 新增: } | |
| 307 | 新增: internal static bool SelectPane(Process node,InputLease lease,JsonObject input,JsonObject proof) | |
| 308 | 新增: { | |
| 309 | 新增: if(input["kind"]?.GetValue<string>()!="pointer"||NativeGuestInput.PressedButtons(lease)!=0||((input["mask"]?.GetValue<int>()??0)&7)==0)return false; | |
| 310 | 新增: var view=Resolve(node,proof);if(last is null||input["target"]?.GetValue<string>()!=publicTarget||view.Token!=last.Token)throw new InvalidDataException("browser_target_changed"); | |
| 311 | 新增: var x=input["x"]?.GetValue<int>()??-1; | |
| 312 | 新增: if(x>=view.X&&x<view.X+view.Width)return false; | |
| 313 | 新增: if(view.NativeUI){Focus(view);Tap(view,[InputStroke.Key(27,false),InputStroke.Key(27,true)]);} | |
| 314 | 新增: return true; | |
| 315 | 新增: } | |
| 316 | 新增: internal static void Transition(Process node,JsonObject proof) | |
| 317 | 新增: { | |
| 318 | 新增: var view=Resolve(node,proof); | |
| 319 | 新增: if(last is not null&&last.NodeTarget==view.NodeTarget&&last.Pin.Window==view.Pin.Window&&last.Pin.Started==view.Pin.Started)last=view; | |
| 320 | 新增: } | |
| 321 | 新增: internal static bool Edit(Process node,JsonObject proof,string action,string text="") | |
| 322 | 新增: { | |
| 323 | 新增: var view=Resolve(node,proof);if(!view.NativeUI)return false;Focus(view); | |
| 324 | 新增: if(action=="insert-text") | |
| 325 | 新增: {if(Protocol.Utf8.GetByteCount(text)>8192)throw new InvalidDataException("browser_input_invalid");Tap(view,text.SelectMany(c=>new[]{InputStroke.Key(c,false,true),InputStroke.Key(c,true,true)}).ToArray());} | |
| 326 | 新增: else | |
| 327 | 新增: { | |
| 328 | 新增: ushort key=action switch{"paste"=>86,"copy"=>67,"cut"=>88,"select-all"=>65,_=>throw new InvalidDataException("browser_input_invalid")}; | |
| 329 | 新增: Tap(view,[InputStroke.Key(17,false),InputStroke.Key(key,false),InputStroke.Key(key,true),InputStroke.Key(17,true)]); | |
| 330 | 新增: } | |
| 331 | 新增: return true; | |
| 332 | 新增: } | |
| 333 | 新增: internal static async Task<JsonObject?> Ime(Process node,JsonObject proof,JsonObject input,CancellationToken token) | |
| 334 | 新增: { | |
| 335 | 新增: var view=Resolve(node,proof);if(!view.NativeUI)return null;Focus(view); | |
| 336 | 新增: var result=await WindowsIme.Handle(input,view.Pin.Process.Id,view.Token,view.Surface.X,view.Surface.Y, | |
| 337 | 新增: text=>Tap(view,text.SelectMany(c=>new[]{InputStroke.Key(c,false,true),InputStroke.Key(c,true,true)}).ToArray()),token); | |
| 338 | 新增: if(result["rect"] is JsonArray rect && rect.Count==4) | |
| 339 | 新增: { | |
| 340 | 新增: var sx=(double)view.Width/view.Surface.Width;var sy=(double)view.Height/view.Surface.Height; | |
| 341 | 新增: result["rect"]=new JsonArray(view.X+rect[0]!.GetValue<double>()*sx,view.Y+rect[1]!.GetValue<double>()*sy,rect[2]!.GetValue<double>()*sx,rect[3]!.GetValue<double>()*sy); | |
| 342 | 新增: } | |
| 343 | 新增: return result; | |
| 344 | 新增: } | |
| 345 | 新增: private static void Focus(View view) | |
| 346 | 新增: { | |
| 347 | 新增: Validate(view.Pin);if(GetAncestor(GetForegroundWindow(),3)!=view.Pin.Window)SetForegroundWindow(view.Pin.Window); | |
| 348 | 新增: if(GetAncestor(GetForegroundWindow(),3)!=view.Pin.Window)throw new InvalidDataException("browser_focus_required"); | |
| 349 | 新增: } | |
| 350 | 新增: private static Func<bool> ReleaseAllowed(View view) | |
| 351 | 新增: { | |
| 352 | 新增: var pid=view.Pin.Process.Id;var started=view.Pin.Started;var executable=view.Pin.Executable;var window=view.Pin.Window;var session=view.Pin.Process.SessionId; | |
| 353 | 新增: return ()=> | |
| 354 | 新增: { | |
| 355 | 新增: if(!SessionGuard.Available())return false; | |
| 356 | 新增: try | |
| 357 | 新增: { | |
| 358 | 新增: using var process=Process.GetProcessById(pid); | |
| 359 | 新增: if(process.HasExited)return true; | |
| 360 | 新增: if(process.StartTime.ToUniversalTime()!=started||process.SessionId!=session||!string.Equals(process.MainModule?.FileName,executable,StringComparison.OrdinalIgnoreCase))return false; | |
| 361 | 新增: return !IsWindow(window)||GetWindowThreadProcessId(window,out var owner)!=0&&owner==pid; | |
| 362 | 新增: } | |
| 363 | 新增: catch(ArgumentException){return true;} // The verified owning process has exited. | |
| 364 | 新增: catch(InvalidOperationException){return true;} | |
| 365 | 新增: catch{return false;} | |
| 366 | 新增: }; | |
| 367 | 新增: } | |
| 368 | 新增: private static void Emit(View view,InputLease lease,InputStroke[] strokes) | |
| 369 | 新增: { | |
| 370 | 新增: NativeGuestInput.Emit(lease,strokes,()=>{Validate(view.Pin);if(GetAncestor(GetForegroundWindow(),3)!=view.Pin.Window)throw new InvalidDataException("browser_focus_required");},ReleaseAllowed(view)); | |
| 371 | 新增: } | |
| 372 | 新增: private static void Tap(View view,InputStroke[] strokes) | |
| 373 | 新增: { | |
| 374 | 新增: var lease=NativeGuestInput.OpenLease();try{Emit(view,lease,strokes);}finally{NativeGuestInput.CloseLease(lease);} | |
| 375 | 新增: } | |
| 376 | 新增: private static void Pointer(View view,InputLease lease,JsonObject input) | |
| 377 | 新增: { | |
| 378 | 新增: var x=input["x"]?.GetValue<int>()??-1;var y=input["y"]?.GetValue<int>()??-1;var mask=input["mask"]?.GetValue<int>()??-1; | |
| 379 | 新增: if(mask<0||mask>127||x<0||y<0)throw new InvalidDataException("browser_input_invalid"); | |
| 380 | 新增: var screenX=view.Surface.X+(int)Math.Round((x-view.X)*(double)view.Surface.Width/view.Width);var screenY=view.Surface.Y+(int)Math.Round((y-view.Y)*(double)view.Surface.Height/view.Height); | |
| 381 | 新增: if(!view.Client.Contains(screenX,screenY)&&!view.Popups.Any(p=>p.Client.Contains(screenX,screenY)))throw new InvalidDataException("browser_input_invalid"); | |
| 382 | 新增: if(!SetCursorPos(screenX,screenY))throw new InvalidDataException("browser_input_failed"); | |
| 383 | 新增: var mouseMask=NativeGuestInput.PressedButtons(lease);var inputs=new List<InputStroke>(); | |
| 384 | 新增: foreach(var bit in new[]{1,2,4})if((mask&bit)!=(mouseMask&bit))inputs.Add(InputStroke.Button(bit,(mask&bit)==0)); | |
| 385 | 新增: if((mask&24)!=0)inputs.Add(InputStroke.Wheel((mask&8)!=0?120:-120)); | |
| 386 | 新增: if((mask&96)!=0)inputs.Add(InputStroke.Wheel((mask&32)!=0?-120:120,true)); | |
| 387 | 新增: if(inputs.Count>0)Emit(view,lease,inputs.ToArray()); | |
| 388 | 新增: } | |
| 389 | 新增: private static void Keyboard(View view,InputLease lease,JsonObject input) | |
| 390 | 新增: { | |
| 391 | 新增: var sym=input["keysym"]?.GetValue<uint>()??0;var down=input["down"]?.GetValue<bool>()??false; | |
| 392 | 新增: var special=new Dictionary<uint,ushort>{{0xff08,8},{0xff09,9},{0xff0d,13},{0xff1b,27},{0xff50,36},{0xff51,37},{0xff52,38},{0xff53,39},{0xff54,40},{0xff55,33},{0xff56,34},{0xff57,35},{0xffff,46},{0xffe1,16},{0xffe2,16},{0xffe3,17},{0xffe4,17},{0xffe9,18},{0xffea,18},{0xffe7,91},{0xffe8,92},{0xffeb,91},{0xffec,92}}; | |
| 393 | 新增: if(sym>=0xffbe&&sym<=0xffc9)special[sym]=(ushort)(112+sym-0xffbe); | |
| 394 | 新增: if(!down) | |
| 395 | 新增: { | |
| 396 | 新增: if(lease.Symbols.Remove(sym,out var prior))Emit(view,lease,prior.Select(stroke=>stroke with{Up=true}).ToArray()); | |
| 397 | 新增: return; | |
| 398 | 新增: } | |
| 399 | 新增: if(lease.Symbols.TryGetValue(sym,out var repeated)){Emit(view,lease,repeated);return;} | |
| 400 | 新增: if(special.TryGetValue(sym,out var key)){var strokes=new[]{InputStroke.Key(key,false)};lease.Symbols[sym]=strokes;Emit(view,lease,strokes);return;} | |
| 401 | 新增: var cp=(sym&0xff000000)==0x01000000?sym&0xffffff:sym; | |
| 402 | 新增: if(cp<32||cp>0x10ffff||cp is >=0xd800 and <=0xdfff)throw new InvalidDataException("browser_input_invalid"); | |
| 403 | 新增: InputStroke[] characters; | |
| 404 | 新增: if(cp<=0xffff && (NativeGuestInput.PressedKey(17)||NativeGuestInput.PressedKey(18))) | |
| 405 | 新增: {var mapped=VkKeyScan((char)cp);if(mapped<0)throw new InvalidDataException("browser_input_invalid");characters=[InputStroke.Key((ushort)(mapped&255),false)];} | |
| 406 | 新增: else characters=char.ConvertFromUtf32((int)cp).Select(c=>InputStroke.Key(c,false,true)).ToArray(); | |
| 407 | 新增: lease.Symbols[sym]=characters;Emit(view,lease,characters); | |
| 408 | 新增: } | |
| 409 | 新增: internal static void Close(){InputLease[] leases;lock(browserLeases)leases=browserLeases.ToArray();foreach(var lease in leases)NativeGuestInput.ResetLease(lease);foreach(var p in Windows.Values)p.Process.Dispose();Windows.Clear();last=null;publicTarget="";cachedOverlay=null;lastFrame=null;lastSequence="";} | |
| 410 | 新增: | |
| 411 | 新增: [DllImport("kernel32.dll",SetLastError=true)]private static extern IntPtr CreateToolhelp32Snapshot(uint flags,uint process); | |
| 412 | 新增: [DllImport("kernel32.dll",CharSet=CharSet.Unicode,EntryPoint="Process32FirstW")]private static extern bool Process32First(IntPtr snapshot,ref ProcessEntry entry); | |
| 413 | 新增: [DllImport("kernel32.dll",CharSet=CharSet.Unicode,EntryPoint="Process32NextW")]private static extern bool Process32Next(IntPtr snapshot,ref ProcessEntry entry); | |
| 414 | 新增: [DllImport("kernel32.dll")]private static extern bool CloseHandle(IntPtr handle); | |
| 415 | 新增: [DllImport("user32.dll")]private static extern bool EnumWindows(Enumerate callback,IntPtr data); | |
| 416 | 新增: [DllImport("user32.dll")]private static extern bool EnumChildWindows(IntPtr window,Enumerate callback,IntPtr data); | |
| 417 | 新增: [DllImport("user32.dll")]private static extern uint GetWindowThreadProcessId(IntPtr window,out uint process); | |
| 418 | 新增: [DllImport("user32.dll")]private static extern bool GetWindowRect(IntPtr window,out Rect rectangle); | |
| 419 | 新增: [DllImport("user32.dll")]private static extern bool GetClientRect(IntPtr window,out Rect rectangle); | |
| 420 | 新增: [DllImport("user32.dll")]private static extern bool ClientToScreen(IntPtr window,ref Point point); | |
| 421 | 新增: [DllImport("user32.dll")]private static extern bool ScreenToClient(IntPtr window,ref Point point); | |
| 422 | 新增: [DllImport("user32.dll")]private static extern IntPtr ChildWindowFromPointEx(IntPtr parent,Point point,uint flags); | |
| 423 | 新增: [DllImport("user32.dll",CharSet=CharSet.Unicode,EntryPoint="GetClassNameW")]private static extern int GetClassName(IntPtr window,StringBuilder name,int length); | |
| 424 | 新增: [DllImport("user32.dll")]private static extern IntPtr GetWindow(IntPtr window,uint command); | |
| 425 | 新增: [DllImport("user32.dll")]private static extern IntPtr GetAncestor(IntPtr window,uint flags); | |
| 426 | 新增: [DllImport("user32.dll")]private static extern bool IsWindowVisible(IntPtr window); | |
| 427 | 新增: [DllImport("user32.dll")]private static extern bool IsIconic(IntPtr window); | |
| 428 | 新增: [DllImport("user32.dll")]private static extern IntPtr GetForegroundWindow(); | |
| 429 | 新增: [DllImport("user32.dll")]private static extern bool SetForegroundWindow(IntPtr window); | |
| 430 | 新增: [DllImport("user32.dll")]private static extern uint GetDpiForWindow(IntPtr window); | |
| 431 | 新增: [DllImport("user32.dll")]private static extern IntPtr SetThreadDpiAwarenessContext(IntPtr context); | |
| 432 | 新增: [DllImport("user32.dll")]private static extern bool GetGUIThreadInfo(uint thread,ref GuiThread info); | |
| 433 | 新增: [DllImport("user32.dll")]private static extern bool SetCursorPos(int x,int y); | |
| 434 | 新增: [DllImport("user32.dll")]private static extern bool IsWindow(IntPtr window); | |
| 435 | 新增: [DllImport("user32.dll",CharSet=CharSet.Unicode,EntryPoint="VkKeyScanW")]private static extern short VkKeyScan(char key); | |
| 436 | 新增:} | |
| @@ -0,0 +1,25 @@ | ||
| 1 | 新增:<Project Sdk="Microsoft.NET.Sdk"> | |
| 2 | 新增: <PropertyGroup> | |
| 3 | 新增: <OutputType>Exe</OutputType> | |
| 4 | 新增: <TargetFramework>net10.0-windows10.0.19041.0</TargetFramework> | |
| 5 | 新增: <UseWindowsForms>true</UseWindowsForms> | |
| 6 | 新增: <UseWPF>true</UseWPF> | |
| 7 | 新增: <EnableWindowsTargeting>true</EnableWindowsTargeting> | |
| 8 | 新增: <Nullable>enable</Nullable> | |
| 9 | 新增: <ImplicitUsings>enable</ImplicitUsings> | |
| 10 | 新增: <AllowUnsafeBlocks>true</AllowUnsafeBlocks> | |
| 11 | 新增: <RuntimeIdentifier>win-x64</RuntimeIdentifier> | |
| 12 | 新增: <SelfContained>true</SelfContained> | |
| 13 | 新增: <PublishSingleFile>true</PublishSingleFile> | |
| 14 | 新增: <AssemblyName>Cage.GuestClipboard</AssemblyName> | |
| 15 | 新增: </PropertyGroup> | |
| 16 | 新增: <ItemGroup> | |
| 17 | 新增: <EmbeddedResource Include="../../../internal/workbench/cli_channel.py" LogicalName="Cage.CliChannel" /> | |
| 18 | 新增: <EmbeddedResource Include="../../../internal/cage/claude-account.py" LogicalName="Cage.CliAccount" /> | |
| 19 | 新增: <EmbeddedResource Include="../../../internal/workbench/windows_cli_platform.py" LogicalName="Cage.CliPlatform" /> | |
| 20 | 新增: <EmbeddedResource Include="../../../internal/workbench/windows_ccs_launch.cjs" LogicalName="Cage.CliCCS" /> | |
| 21 | 新增: <EmbeddedResource Include="../../../internal/workbench/mobile_cli_identity.py" LogicalName="Cage.CliIdentity" /> | |
| 22 | 新增: <EmbeddedResource Include="../../../internal/workbench/cli_channel.resume.md" LogicalName="Cage.CliResume" /> | |
| 23 | 新增: <EmbeddedResource Include="../../../internal/workbench/claude_account_resume.md" LogicalName="Cage.CliAccountResume" /> | |
| 24 | 新增: </ItemGroup> | |
| 25 | 新增:</Project> | |
| @@ -0,0 +1,323 @@ | ||
| 1 | 新增:using System.Runtime.InteropServices; | |
| 2 | 新增:using Windows.Foundation; | |
| 3 | 新增:using Windows.Graphics.Capture; | |
| 4 | 新增:using Windows.Graphics.DirectX; | |
| 5 | 新增:using Windows.Graphics.DirectX.Direct3D11; | |
| 6 | 新增:using Windows.Graphics.Imaging; | |
| 7 | 新增:using Windows.Storage.Streams; | |
| 8 | 新增:using WinRT; | |
| 9 | 新增: | |
| 10 | 新增:namespace Cage.GuestClipboard; | |
| 11 | 新增: | |
| 12 | 新增:// Capture items are created exclusively for the caller's validated Claude HWND. | |
| 13 | 新增:// No monitor item, desktop duplication or screen BitBlt is available here. | |
| 14 | 新增:internal static class ClaudeGraphicsCapture | |
| 15 | 新增:{ | |
| 16 | 新增: private static readonly Guid ItemInterop = new("3628e81b-3cac-4c60-b7f4-23ce0e0c3356"); | |
| 17 | 新增: private static readonly Guid ItemInterface = new("79c3f95b-31f7-4ec2-a464-632ef5d30760"); | |
| 18 | 新增: private static readonly Guid DxgiDevice = new("54ec77fa-1377-44e6-8c32-88fd5f44c84c"); | |
| 19 | 新增: private static readonly SemaphoreSlim CaptureGate = new(1, 1); | |
| 20 | 新增: private static readonly System.Threading.Timer Idle = new(state => { _ = Expire(); }); | |
| 21 | 新增: private static CaptureSession? current; | |
| 22 | 新增: | |
| 23 | 新增: private static async Task Expire() | |
| 24 | 新增: { | |
| 25 | 新增: if (!await CaptureGate.WaitAsync(0)) return; | |
| 26 | 新增: try { current?.Dispose(); current = null; } | |
| 27 | 新增: finally { CaptureGate.Release(); } | |
| 28 | 新增: } | |
| 29 | 新增: | |
| 30 | 新增: internal static async Task<byte[]> Capture(IntPtr window, int pid, int width, int height, Action validate, bool allowSolid = false, bool preserveAlpha = false) | |
| 31 | 新增: { | |
| 32 | 新增: await CaptureGate.WaitAsync(); | |
| 33 | 新增: Idle.Change(Timeout.Infinite, Timeout.Infinite); | |
| 34 | 新增: try | |
| 35 | 新增: { | |
| 36 | 新增: validate(); | |
| 37 | 新增: try { if (!GraphicsCaptureSession.IsSupported()) throw new InvalidDataException("desktop_graphics_capture_unavailable"); } | |
| 38 | 新增: catch (COMException error) when ((uint)error.HResult == 0x80070005) | |
| 39 | 新增: { throw new InvalidDataException("desktop_capture_permission_required", error); } | |
| 40 | 新增: Exception? hardware = null; | |
| 41 | 新增: foreach (uint driver in new uint[] { 1, 5 }) // hardware, then WARP | |
| 42 | 新增: { | |
| 43 | 新增: try { return await CaptureDevice(window, pid, width, height, validate, driver, allowSolid, preserveAlpha); } | |
| 44 | 新增: catch (COMException error) when ((uint)error.HResult == 0x80070005) | |
| 45 | 新增: { throw new InvalidDataException("desktop_capture_permission_required", error); } | |
| 46 | 新增: catch (Exception error) when (error is COMException || error is TimeoutException || error is InvalidDataException { Message: "desktop_empty_frame" }) | |
| 47 | 新增: { | |
| 48 | 新增: current?.Dispose(); | |
| 49 | 新增: current = null; | |
| 50 | 新增: hardware = error; | |
| 51 | 新增: } | |
| 52 | 新增: } | |
| 53 | 新增: throw new InvalidDataException(hardware is InvalidDataException ? "desktop_empty_frame" : "desktop_graphics_device_unavailable", hardware); | |
| 54 | 新增: } | |
| 55 | 新增: finally { Idle.Change(1500, Timeout.Infinite); CaptureGate.Release(); } | |
| 56 | 新增: } | |
| 57 | 新增: private static async Task<byte[]> CaptureDevice(IntPtr window, int pid, int width, int height, Action validate, uint driver, bool allowSolid, bool preserveAlpha) | |
| 58 | 新增: { | |
| 59 | 新增: if (current is null || !current.Matches(window, pid, width, height, allowSolid, preserveAlpha)) | |
| 60 | 新增: { | |
| 61 | 新增: current?.Dispose(); current = null; | |
| 62 | 新增: current = new CaptureSession(window, pid, width, height, driver, allowSolid, preserveAlpha); | |
| 63 | 新增: } | |
| 64 | 新增: return await current.Read(validate); | |
| 65 | 新增: } | |
| 66 | 新增: | |
| 67 | 新增: private sealed class CaptureSession : IDisposable | |
| 68 | 新增: { | |
| 69 | 新增: private readonly IntPtr window; | |
| 70 | 新增: private readonly int pid, width, height; | |
| 71 | 新增: private readonly bool allowSolid, preserveAlpha; | |
| 72 | 新增: private readonly GraphicsCaptureItem item; | |
| 73 | 新增: private readonly IDirect3DDevice device; | |
| 74 | 新增: private Direct3D11CaptureFramePool? pool; | |
| 75 | 新增: private GraphicsCaptureSession? capture; | |
| 76 | 新增: private readonly object frames = new(); | |
| 77 | 新增: private TaskCompletionSource<bool> arrived = new(TaskCreationOptions.RunContinuationsAsynchronously); | |
| 78 | 新增: private Direct3D11CaptureFrame? latest; | |
| 79 | 新增: private byte[]? encoded; | |
| 80 | 新增: private Windows.Storage.Streams.Buffer? pixelBuffer; | |
| 81 | 新增: private byte[] pixelsRead = []; | |
| 82 | 新增: private byte[]? previousPixels; | |
| 83 | 新增: private TimeSpan? timestamp; | |
| 84 | 新增: private bool closed; | |
| 85 | 新增: | |
| 86 | 新增: internal CaptureSession(IntPtr window, int pid, int width, int height, uint driver, bool allowSolid, bool preserveAlpha) | |
| 87 | 新增: { | |
| 88 | 新增: this.window = window; this.pid = pid; this.width = width; this.height = height; this.allowSolid = allowSolid; this.preserveAlpha = preserveAlpha; | |
| 89 | 新增: item = Item(window); | |
| 90 | 新增: if (item.Size.Width < width || item.Size.Height < height || (long)item.Size.Width * item.Size.Height > 40_000_000) | |
| 91 | 新增: throw new InvalidDataException("desktop_target_changed"); | |
| 92 | 新增: device = Device(driver); | |
| 93 | 新增: try | |
| 94 | 新增: { | |
| 95 | 新增: pool = Direct3D11CaptureFramePool.CreateFreeThreaded(device, DirectXPixelFormat.B8G8R8A8UIntNormalized, 2, item.Size); | |
| 96 | 新增: capture = pool.CreateCaptureSession(item); | |
| 97 | 新增: capture.IsCursorCaptureEnabled = false; | |
| 98 | 新增: pool.FrameArrived += OnFrame; | |
| 99 | 新增: item.Closed += OnClosed; | |
| 100 | 新增: capture.StartCapture(); | |
| 101 | 新增: } | |
| 102 | 新增: catch { Dispose(); throw; } | |
| 103 | 新增: } | |
| 104 | 新增: | |
| 105 | 新增: internal bool Matches(IntPtr handle, int process, int w, int h, bool solid, bool alpha) | |
| 106 | 新增: { | |
| 107 | 新增: lock (frames) return !closed && window == handle && pid == process && width == w && height == h && allowSolid == solid && preserveAlpha == alpha; | |
| 108 | 新增: } | |
| 109 | 新增: | |
| 110 | 新增: private void OnFrame(Direct3D11CaptureFramePool sender, object args) | |
| 111 | 新增: { | |
| 112 | 新增: try | |
| 113 | 新增: { | |
| 114 | 新增: var frame = sender.TryGetNextFrame(); | |
| 115 | 新增: if (frame is null) return; | |
| 116 | 新增: lock (frames) | |
| 117 | 新增: { | |
| 118 | 新增: if (closed) { frame.Dispose(); return; } | |
| 119 | 新增: latest?.Dispose(); | |
| 120 | 新增: latest = frame; | |
| 121 | 新增: arrived.TrySetResult(true); | |
| 122 | 新增: } | |
| 123 | 新增: } | |
| 124 | 新增: catch (Exception error) | |
| 125 | 新增: { | |
| 126 | 新增: lock (frames) | |
| 127 | 新增: { | |
| 128 | 新增: closed = true; | |
| 129 | 新增: latest?.Dispose(); latest = null; | |
| 130 | 新增: arrived.TrySetException(error); | |
| 131 | 新增: } | |
| 132 | 新增: } | |
| 133 | 新增: } | |
| 134 | 新增: | |
| 135 | 新增: private void OnClosed(GraphicsCaptureItem sender, object args) | |
| 136 | 新增: { | |
| 137 | 新增: lock (frames) { closed = true; arrived.TrySetException(new InvalidDataException("desktop_target_changed")); } | |
| 138 | 新增: } | |
| 139 | 新增: | |
| 140 | 新增: internal async Task<byte[]> Read(Action validate) | |
| 141 | 新增: { | |
| 142 | 新增: validate(); | |
| 143 | 新增: var geometry = Geometry(window, pid, width, height); | |
| 144 | 新增: Task ready; | |
| 145 | 新增: lock (frames) | |
| 146 | 新增: { | |
| 147 | 新增: if (closed) throw new InvalidDataException("desktop_target_changed"); | |
| 148 | 新增: if (latest is null && encoded is not null) return encoded; | |
| 149 | 新增: ready = arrived.Task; | |
| 150 | 新增: } | |
| 151 | 新增: await ready.WaitAsync(TimeSpan.FromSeconds(3)); | |
| 152 | 新增: Direct3D11CaptureFrame frame; | |
| 153 | 新增: lock (frames) | |
| 154 | 新增: { | |
| 155 | 新增: if (closed || latest is null) throw new InvalidDataException("desktop_target_changed"); | |
| 156 | 新增: frame = latest; latest = null; | |
| 157 | 新增: arrived = new(TaskCreationOptions.RunContinuationsAsynchronously); | |
| 158 | 新增: } | |
| 159 | 新增: using (frame) | |
| 160 | 新增: { | |
| 161 | 新增: if (encoded is not null && timestamp == frame.SystemRelativeTime) return encoded; | |
| 162 | 新增: using var bitmap = await SoftwareBitmap.CreateCopyFromSurfaceAsync(frame.Surface, preserveAlpha ? BitmapAlphaMode.Premultiplied : BitmapAlphaMode.Ignore); | |
| 163 | 新增: validate(); | |
| 164 | 新增: var after = Geometry(window, pid, width, height); | |
| 165 | 新增: if (after != geometry) throw new InvalidDataException("desktop_target_changed"); | |
| 166 | 新增: var source = geometry.Source(frame.ContentSize.Width, frame.ContentSize.Height); | |
| 167 | 新增: using var pixels = SoftwareBitmap.Convert(bitmap, BitmapPixelFormat.Bgra8, preserveAlpha ? BitmapAlphaMode.Straight : BitmapAlphaMode.Ignore); | |
| 168 | 新增: var byteCount = checked(pixels.PixelWidth * pixels.PixelHeight * 4); | |
| 169 | 新增: if (pixelsRead.Length != byteCount) | |
| 170 | 新增: { | |
| 171 | 新增: pixelsRead = new byte[byteCount]; | |
| 172 | 新增: pixelBuffer = new Windows.Storage.Streams.Buffer((uint)byteCount); | |
| 173 | 新增: } | |
| 174 | 新增: pixels.CopyToBuffer(pixelBuffer!); | |
| 175 | 新增: using (var reader = DataReader.FromBuffer(pixelBuffer!)) reader.ReadBytes(pixelsRead); | |
| 176 | 新增: var rowBytes = checked(width * 4); | |
| 177 | 新增: var identical = previousPixels is not null; | |
| 178 | 新增: for (var row = 0; identical && row < height; row++) | |
| 179 | 新增: { | |
| 180 | 新增: var offset = ((source.Y + row) * pixels.PixelWidth + source.X) * 4; | |
| 181 | 新增: identical = pixelsRead.AsSpan(offset, rowBytes).SequenceEqual(previousPixels!.AsSpan(row * rowBytes, rowBytes)); | |
| 182 | 新增: } | |
| 183 | 新增: if (identical) | |
| 184 | 新增: { | |
| 185 | 新增: validate(); | |
| 186 | 新增: timestamp = frame.SystemRelativeTime; | |
| 187 | 新增: return encoded!; | |
| 188 | 新增: } | |
| 189 | 新增: var png = await EncodeClient(pixels, source.X, source.Y, width, height); | |
| 190 | 新增: validate(); | |
| 191 | 新增: using var input = new MemoryStream(png, false); | |
| 192 | 新增: using var client = new Bitmap(input); | |
| 193 | 新增: if (client.Width != width || client.Height != height || (!allowSolid && !HasContent(client))) throw new InvalidDataException("desktop_empty_frame"); | |
| 194 | 新增: // Publish the comparison pixels only after encoding and target | |
| 195 | 新增: // validation succeed, so a failed frame cannot reuse old PNGs. | |
| 196 | 新增: previousPixels ??= new byte[checked(rowBytes * height)]; | |
| 197 | 新增: for (var row = 0; row < height; row++) | |
| 198 | 新增: { | |
| 199 | 新增: var offset = ((source.Y + row) * pixels.PixelWidth + source.X) * 4; | |
| 200 | 新增: pixelsRead.AsSpan(offset, rowBytes).CopyTo(previousPixels.AsSpan(row * rowBytes, rowBytes)); | |
| 201 | 新增: } | |
| 202 | 新增: timestamp = frame.SystemRelativeTime; | |
| 203 | 新增: encoded = png; | |
| 204 | 新增: return png; | |
| 205 | 新增: } | |
| 206 | 新增: } | |
| 207 | 新增: | |
| 208 | 新增: public void Dispose() | |
| 209 | 新增: { | |
| 210 | 新增: lock (frames) | |
| 211 | 新增: { | |
| 212 | 新增: closed = true; | |
| 213 | 新增: latest?.Dispose(); latest = null; | |
| 214 | 新增: arrived.TrySetCanceled(); | |
| 215 | 新增: } | |
| 216 | 新增: if (pool is not null) pool.FrameArrived -= OnFrame; | |
| 217 | 新增: item.Closed -= OnClosed; | |
| 218 | 新增: capture?.Dispose(); pool?.Dispose(); device.Dispose(); | |
| 219 | 新增: } | |
| 220 | 新增: } | |
| 221 | 新增: internal static bool HasContent(Bitmap bitmap) | |
| 222 | 新增: { | |
| 223 | 新增: // A white/black client plus custom title buttons is still an empty frame. | |
| 224 | 新增: int left = bitmap.Width / 12, right = bitmap.Width - left; | |
| 225 | 新增: int top = bitmap.Height * 15 / 100, bottom = bitmap.Height * 95 / 100; | |
| 226 | 新增: var first = bitmap.GetPixel(left, top); int varied = 0; | |
| 227 | 新增: for (int y = top; y < bottom; y += Math.Max(1, (bottom-top)/64)) | |
| 228 | 新增: for (int x = left; x < right; x += Math.Max(1, (right-left)/64)) | |
| 229 | 新增: { | |
| 230 | 新增: var pixel = bitmap.GetPixel(x, y); | |
| 231 | 新增: if (Math.Abs(pixel.R-first.R)>8 || Math.Abs(pixel.G-first.G)>8 || Math.Abs(pixel.B-first.B)>8) varied++; | |
| 232 | 新增: } | |
| 233 | 新增: return varied >= 8; | |
| 234 | 新增: } | |
| 235 | 新增: private static async Task<byte[]> EncodeClient(SoftwareBitmap source, int x, int y, int width, int height) | |
| 236 | 新增: { | |
| 237 | 新增: if (x < 0 || y < 0 || x + width > source.PixelWidth || y + height > source.PixelHeight) | |
| 238 | 新增: throw new InvalidDataException("desktop_target_changed"); | |
| 239 | 新增: using var output = new InMemoryRandomAccessStream(); | |
| 240 | 新增: var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, output); | |
| 241 | 新增: encoder.SetSoftwareBitmap(source); | |
| 242 | 新增: encoder.BitmapTransform.Bounds = new BitmapBounds { X = (uint)x, Y = (uint)y, Width = (uint)width, Height = (uint)height }; | |
| 243 | 新增: await encoder.FlushAsync(); | |
| 244 | 新增: if (output.Size is 0 or > Protocol.PngLimit) throw new InvalidDataException("desktop_frame_limit"); | |
| 245 | 新增: using var input = output.GetInputStreamAt(0); | |
| 246 | 新增: using var reader = new DataReader(input); | |
| 247 | 新增: var length = checked((uint)output.Size); | |
| 248 | 新增: if (await reader.LoadAsync(length) != length) throw new InvalidDataException("desktop_capture_buffer_invalid"); | |
| 249 | 新增: var bytes = new byte[length]; | |
| 250 | 新增: reader.ReadBytes(bytes); | |
| 251 | 新增: return bytes; | |
| 252 | 新增: } | |
| 253 | 新增: | |
| 254 | 新增: private static GraphicsCaptureItem Item(IntPtr window) | |
| 255 | 新增: { | |
| 256 | 新增: using var factory = ActivationFactory.Get("Windows.Graphics.Capture.GraphicsCaptureItem", ItemInterop); | |
| 257 | 新增: var function = Marshal.ReadIntPtr(Marshal.ReadIntPtr(factory.ThisPtr),3*IntPtr.Size); | |
| 258 | 新增: var create = Marshal.GetDelegateForFunctionPointer<CreateWindow>(function); | |
| 259 | 新增: var iid = ItemInterface; | |
| 260 | 新增: Marshal.ThrowExceptionForHR(create(factory.ThisPtr,window,ref iid,out var value)); | |
| 261 | 新增: try { return MarshalInterface<GraphicsCaptureItem>.FromAbi(value); } finally { Marshal.Release(value); } | |
| 262 | 新增: } | |
| 263 | 新增: private static IDirect3DDevice Device(uint driver) | |
| 264 | 新增: { | |
| 265 | 新增: IntPtr native=IntPtr.Zero, context=IntPtr.Zero, dxgi=IntPtr.Zero, wrapped=IntPtr.Zero; | |
| 266 | 新增: try | |
| 267 | 新增: { | |
| 268 | 新增: Marshal.ThrowExceptionForHR(D3D11CreateDevice(IntPtr.Zero,driver,IntPtr.Zero,0x20,IntPtr.Zero,0,7,out native,out _,out context)); | |
| 269 | 新增: var iid=DxgiDevice;Marshal.ThrowExceptionForHR(Marshal.QueryInterface(native,in iid,out dxgi)); | |
| 270 | 新增: Marshal.ThrowExceptionForHR(CreateDirect3D11DeviceFromDXGIDevice(dxgi,out wrapped)); | |
| 271 | 新增: return MarshalInterface<IDirect3DDevice>.FromAbi(wrapped); | |
| 272 | 新增: } | |
| 273 | 新增: finally | |
| 274 | 新增: { | |
| 275 | 新增: if(wrapped!=IntPtr.Zero)Marshal.Release(wrapped);if(dxgi!=IntPtr.Zero)Marshal.Release(dxgi); | |
| 276 | 新增: if(context!=IntPtr.Zero)Marshal.Release(context);if(native!=IntPtr.Zero)Marshal.Release(native); | |
| 277 | 新增: } | |
| 278 | 新增: } | |
| 279 | 新增: private readonly record struct Snapshot(Rect Window,Rect Visible,int ClientX,int ClientY,int Width,int Height) | |
| 280 | 新增: { | |
| 281 | 新增: internal Point Source(int width,int height) | |
| 282 | 新增: { | |
| 283 | 新增: Rect frame; | |
| 284 | 新增: if(Visible.Right-Visible.Left==width && Visible.Bottom-Visible.Top==height)frame=Visible; | |
| 285 | 新增: else if(Window.Right-Window.Left==width && Window.Bottom-Window.Top==height)frame=Window; | |
| 286 | 新增: else throw new InvalidDataException("desktop_target_changed"); | |
| 287 | 新增: return new(ClientX-frame.Left,ClientY-frame.Top); | |
| 288 | 新增: } | |
| 289 | 新增: } | |
| 290 | 新增: private static Snapshot Geometry(IntPtr window,int pid,int width,int height) | |
| 291 | 新增: { | |
| 292 | 新增: var prior=SetThreadDpiAwarenessContext(new IntPtr(-4)); | |
| 293 | 新增: try | |
| 294 | 新增: { | |
| 295 | 新增: if(!SessionGuard.Available() || GetWindowThreadProcessId(window,out var actual)==0 || actual!=pid || | |
| 296 | 新增: !GetWindowRect(window,out var rectangle) || !GetClientRect(window,out var client) || client.Right!=width || client.Bottom!=height) | |
| 297 | 新增: throw new InvalidDataException("desktop_target_changed"); | |
| 298 | 新增: var visible=rectangle;if(DwmGetWindowAttribute(window,9,out var drawn,Marshal.SizeOf<Rect>())==0)visible=drawn; | |
| 299 | 新增: var origin=new Point();if(!ClientToScreen(window,ref origin))throw new InvalidDataException("desktop_target_changed"); | |
| 300 | 新增: return new(rectangle,visible,origin.X,origin.Y,width,height); | |
| 301 | 新增: } | |
| 302 | 新增: finally {if(prior!=IntPtr.Zero)SetThreadDpiAwarenessContext(prior);} | |
| 303 | 新增: } | |
| 304 | 新增: [StructLayout(LayoutKind.Sequential)] private readonly record struct Rect(int Left,int Top,int Right,int Bottom); | |
| 305 | 新增: [StructLayout(LayoutKind.Sequential)] private struct Point {internal int X,Y;internal Point(int x,int y){X=x;Y=y;}} | |
| 306 | 新增: [UnmanagedFunctionPointer(CallingConvention.StdCall)] private delegate int CreateWindow(IntPtr factory,IntPtr window,ref Guid iid,out IntPtr item); | |
| 307 | 新增: [DefaultDllImportSearchPaths(DllImportSearchPath.System32)] | |
| 308 | 新增: [DllImport("d3d11.dll")] private static extern int D3D11CreateDevice(IntPtr adapter,uint driver,IntPtr software,uint flags,IntPtr features,uint featureCount,uint sdk,out IntPtr device,out uint level,out IntPtr context); | |
| 309 | 新增: [DefaultDllImportSearchPaths(DllImportSearchPath.System32)] | |
| 310 | 新增: [DllImport("d3d11.dll")] private static extern int CreateDirect3D11DeviceFromDXGIDevice(IntPtr dxgi,out IntPtr device); | |
| 311 | 新增: [DefaultDllImportSearchPaths(DllImportSearchPath.System32)] | |
| 312 | 新增: [DllImport("user32.dll")] private static extern uint GetWindowThreadProcessId(IntPtr window,out uint pid); | |
| 313 | 新增: [DefaultDllImportSearchPaths(DllImportSearchPath.System32)] | |
| 314 | 新增: [DllImport("user32.dll")] private static extern bool GetClientRect(IntPtr window,out Rect rect); | |
| 315 | 新增: [DefaultDllImportSearchPaths(DllImportSearchPath.System32)] | |
| 316 | 新增: [DllImport("user32.dll")] private static extern bool GetWindowRect(IntPtr window,out Rect rect); | |
| 317 | 新增: [DefaultDllImportSearchPaths(DllImportSearchPath.System32)] | |
| 318 | 新增: [DllImport("user32.dll")] private static extern bool ClientToScreen(IntPtr window,ref Point point); | |
| 319 | 新增: [DefaultDllImportSearchPaths(DllImportSearchPath.System32)] | |
| 320 | 新增: [DllImport("user32.dll")] private static extern IntPtr SetThreadDpiAwarenessContext(IntPtr context); | |
| 321 | 新增: [DefaultDllImportSearchPaths(DllImportSearchPath.System32)] | |
| 322 | 新增: [DllImport("dwmapi.dll")] private static extern int DwmGetWindowAttribute(IntPtr window,uint attribute,out Rect rect,int size); | |
| 323 | 新增:} | |
| @@ -0,0 +1,526 @@ | ||
| 1 | 新增:using System.Diagnostics; | |
| 2 | 新增:using System.Drawing.Imaging; | |
| 3 | 新增:using System.Runtime.CompilerServices; | |
| 4 | 新增:using System.Runtime.InteropServices; | |
| 5 | 新增:using System.Security.Cryptography; | |
| 6 | 新增:using System.Text.Json.Nodes; | |
| 7 | 新增:using System.Xml.Linq; | |
| 8 | 新增:using System.Windows.Automation; | |
| 9 | 新增:using Windows.Management.Deployment; | |
| 10 | 新增: | |
| 11 | 新增:namespace Cage.GuestClipboard; | |
| 12 | 新增: | |
| 13 | 新增:// This endpoint contains one registered Claude app window. It never captures | |
| 14 | 新增:// the desktop or accepts a path, process ID or window handle from its client. | |
| 15 | 新增:internal static class ClaudeWindowRpc | |
| 16 | 新增:{ | |
| 17 | 新增: private const string Family = "Claude_pzs8sxrjxfjjc"; | |
| 18 | 新增: private const string Publisher = "CN=\"Anthropic, PBC\", O=\"Anthropic, PBC\", L=San Francisco, S=California, C=US, SERIALNUMBER=4860621, OID.2.5.4.15=Private Organization, OID.1.3.6.1.4.1.311.60.2.1.2=Delaware, OID.1.3.6.1.4.1.311.60.2.1.3=US"; | |
| 19 | 新增: private static readonly SemaphoreSlim Operations = new(1, 1); | |
| 20 | 新增: private static readonly SemaphoreSlim Captures = new(1, 1); | |
| 21 | 新增: [ModuleInitializer] internal static void Register() => GuestOperations.Register("desktop", Run); | |
| 22 | 新增: | |
| 23 | 新增: private sealed record Registration(string Executable, string Version); | |
| 24 | 新增: private sealed record Window(Process Process, IntPtr Handle, Rect Bounds, string Executable); | |
| 25 | 新增: [StructLayout(LayoutKind.Sequential)] private struct Rect { public int Left, Top, Right, Bottom; } | |
| 26 | 新增: [StructLayout(LayoutKind.Sequential)] private struct Point { public int X, Y; } | |
| 27 | 新增: [StructLayout(LayoutKind.Sequential)] private struct Keyboard { public ushort Key, Scan; public uint Flags, Time; public UIntPtr Extra; } | |
| 28 | 新增: [StructLayout(LayoutKind.Sequential)] private struct Mouse { public int X, Y; public uint Data, Flags, Time; public UIntPtr Extra; } | |
| 29 | 新增: [StructLayout(LayoutKind.Explicit)] private struct InputData { [FieldOffset(0)] public Keyboard Keyboard; [FieldOffset(0)] public Mouse Mouse; } | |
| 30 | 新增: [StructLayout(LayoutKind.Sequential)] private struct Input { public uint Type; public InputData Data; } | |
| 31 | 新增: [DllImport("user32.dll")] private static extern short VkKeyScanW(char key); | |
| 32 | 新增: [DllImport("user32.dll")] private static extern bool PostMessageW(IntPtr window, uint message, IntPtr wparam, IntPtr lparam); | |
| 33 | 新增: [DllImport("user32.dll")] private static extern bool GetClientRect(IntPtr window, out Rect rect); | |
| 34 | 新增: [DllImport("user32.dll")] private static extern bool ClientToScreen(IntPtr window, ref Point point); | |
| 35 | 新增: [DllImport("user32.dll")] private static extern bool IsWindowVisible(IntPtr window); | |
| 36 | 新增: [DllImport("user32.dll")] private static extern bool IsIconic(IntPtr window); | |
| 37 | 新增: [DllImport("user32.dll")] private static extern uint GetWindowThreadProcessId(IntPtr window, out uint pid); | |
| 38 | 新增: [DllImport("user32.dll")] private static extern IntPtr GetForegroundWindow(); | |
| 39 | 新增: [DllImport("user32.dll")] private static extern bool SetForegroundWindow(IntPtr window); | |
| 40 | 新增: [DllImport("user32.dll")] private static extern bool SetCursorPos(int x, int y); | |
| 41 | 新增: [DllImport("user32.dll")] private static extern bool PrintWindow(IntPtr window, IntPtr dc, uint flags); | |
| 42 | 新增: [DllImport("user32.dll")] private static extern uint SendInput(uint count, Input[] input, int size); | |
| 43 | 新增: [DllImport("user32.dll")] private static extern IntPtr SetThreadDpiAwarenessContext(IntPtr context); | |
| 44 | 新增: [DllImport("user32.dll")] private static extern uint GetDpiForWindow(IntPtr window); | |
| 45 | 新增: [DllImport("user32.dll")] private static extern bool GetWindowRect(IntPtr window, out Rect rect); | |
| 46 | 新增: [DllImport("user32.dll")] private static extern bool GetCursorPos(out Point point); | |
| 47 | 新增: [DllImport("user32.dll")] private static extern IntPtr MonitorFromWindow(IntPtr window, uint flags); | |
| 48 | 新增: [StructLayout(LayoutKind.Sequential)] private struct MonitorInfo { public uint Size; public Rect Monitor, Work; public uint Flags; } | |
| 49 | 新增: [DllImport("user32.dll", EntryPoint="GetMonitorInfoW", ExactSpelling=true)] private static extern bool GetMonitorInfo(IntPtr monitor, ref MonitorInfo info); | |
| 50 | 新增: [DllImport("user32.dll")] private static extern bool SetWindowPos(IntPtr window, IntPtr after, int x, int y, int width, int height, uint flags); | |
| 51 | 新增: [DllImport("user32.dll",CharSet=CharSet.Unicode)] private static extern int GetWindowTextW(IntPtr window,System.Text.StringBuilder text,int count); | |
| 52 | 新增: [DllImport("user32.dll")] private static extern IntPtr WindowFromPoint(Point point); | |
| 53 | 新增: [DllImport("user32.dll")] private static extern IntPtr GetAncestor(IntPtr window,uint flags); | |
| 54 | 新增: [ComVisible(true),Guid("00000121-0000-0000-C000-000000000046"),InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] | |
| 55 | 新增: private interface IDropSource | |
| 56 | 新增: { | |
| 57 | 新增: [PreserveSig] int QueryContinueDrag([MarshalAs(UnmanagedType.Bool)] bool escape,uint state); | |
| 58 | 新增: [PreserveSig] int GiveFeedback(uint effect); | |
| 59 | 新增: } | |
| 60 | 新增: [ComVisible(true),ClassInterface(ClassInterfaceType.None)] | |
| 61 | 新增: private sealed class DropSource(Action guard) : IDropSource | |
| 62 | 新增: { | |
| 63 | 新增: public int QueryContinueDrag(bool escape,uint state) { try { guard();return escape?0x40101:0x40100; } catch { return 0x40101; } } | |
| 64 | 新增: public int GiveFeedback(uint effect)=>0x40102; | |
| 65 | 新增: } | |
| 66 | 新增: [DllImport("ole32.dll")] private static extern int DoDragDrop([MarshalAs(UnmanagedType.Interface)] System.Runtime.InteropServices.ComTypes.IDataObject data,IDropSource source,uint effects,out uint effect); | |
| 67 | 新增: [DllImport("ole32.dll")] private static extern int OleInitialize(IntPtr reserved); | |
| 68 | 新增: [DllImport("ole32.dll")] private static extern void OleUninitialize(); | |
| 69 | 新增: | |
| 70 | 新增: private static Registration? RegisteredExecutable() | |
| 71 | 新增: { | |
| 72 | 新增: var packages = new PackageManager().FindPackagesForUser("").Where(p => p.Id.FamilyName == Family).ToArray(); | |
| 73 | 新增: if (packages.Length == 0) return null; | |
| 74 | 新增: if (packages.Length != 1) throw new InvalidDataException("desktop_registration_invalid"); | |
| 75 | 新增: var p = packages[0]; | |
| 76 | 新增: if (p.Id.Name != "Claude" || p.Id.Publisher != Publisher || p.IsDevelopmentMode || !p.Status.VerifyIsOK() || | |
| 77 | 新增: p.SignatureKind is not (Windows.ApplicationModel.PackageSignatureKind.Developer or Windows.ApplicationModel.PackageSignatureKind.Store or Windows.ApplicationModel.PackageSignatureKind.Enterprise)) | |
| 78 | 新增: throw new InvalidDataException("desktop_registration_invalid"); | |
| 79 | 新增: var manifest = XDocument.Load(Path.Combine(p.InstalledPath, "AppxManifest.xml")); | |
| 80 | 新增: var app = manifest.Descendants().SingleOrDefault(e => e.Name.LocalName == "Application" && (string?)e.Attribute("Id") == "Claude"); | |
| 81 | 新增: if (app is null || (string?)app.Attribute("Executable") != "app\\Claude.exe" || (string?)app.Attribute("EntryPoint") != "Windows.FullTrustApplication") | |
| 82 | 新增: throw new InvalidDataException("desktop_registration_invalid"); | |
| 83 | 新增: var version = p.Id.Version; | |
| 84 | 新增: return new Registration(Path.Combine(p.InstalledPath, "app", "Claude.exe"), $"{version.Major}.{version.Minor}.{version.Build}.{version.Revision}"); | |
| 85 | 新增: } | |
| 86 | 新增: | |
| 87 | 新增: private static Window Find(string executable) | |
| 88 | 新增: { | |
| 89 | 新增: var session = Process.GetCurrentProcess().SessionId; | |
| 90 | 新增: foreach (var p in Process.GetProcessesByName("Claude")) | |
| 91 | 新增: { | |
| 92 | 新增: try | |
| 93 | 新增: { | |
| 94 | 新增: if (p.SessionId != session || !string.Equals(p.MainModule?.FileName, executable, StringComparison.OrdinalIgnoreCase)) { p.Dispose(); continue; } | |
| 95 | 新增: var handle = p.MainWindowHandle; | |
| 96 | 新增: var w = new Window(p, handle, default, executable); | |
| 97 | 新增: Validate(w, false); | |
| 98 | 新增: if (!GetClientRect(handle, out var bounds) || bounds.Right < 1 || bounds.Bottom < 1 || (long)bounds.Right * bounds.Bottom > 40_000_000) | |
| 99 | 新增: throw new InvalidDataException("desktop_size_invalid"); | |
| 100 | 新增: return w with { Bounds = bounds }; | |
| 101 | 新增: } | |
| 102 | 新增: catch { p.Dispose(); } | |
| 103 | 新增: } | |
| 104 | 新增: throw new InvalidDataException("desktop_not_running"); | |
| 105 | 新增: } | |
| 106 | 新增: | |
| 107 | 新增: internal static JsonObject ComponentStatus() | |
| 108 | 新增: { | |
| 109 | 新增: try | |
| 110 | 新增: { | |
| 111 | 新增: var registration=RegisteredExecutable(); | |
| 112 | 新增: return new JsonObject{["installed"]=registration!=null,["ready"]=registration!=null,["reason"]=registration==null?"desktop_not_installed":""}; | |
| 113 | 新增: } | |
| 114 | 新增: catch{return new JsonObject{["installed"]=false,["ready"]=false,["reason"]="desktop_registration_unavailable"};} | |
| 115 | 新增: } | |
| 116 | 新增: | |
| 117 | 新增: private static void Validate(Window w, bool focus) | |
| 118 | 新增: { | |
| 119 | 新增: if (!SessionGuard.Available() || !SessionGuard.OwnsProcess(w.Process) || !IsWindowVisible(w.Handle) || IsIconic(w.Handle) || | |
| 120 | 新增: GetWindowThreadProcessId(w.Handle, out var pid) == 0 || pid != w.Process.Id || | |
| 121 | 新增: !string.Equals(w.Process.MainModule?.FileName, w.Executable, StringComparison.OrdinalIgnoreCase) || | |
| 122 | 新增: focus && GetForegroundWindow() != w.Handle) throw new InvalidDataException("desktop_target_changed"); | |
| 123 | 新增: } | |
| 124 | 新增: | |
| 125 | 新增: // WGC can capture the part of our own window outside the guest monitor, | |
| 126 | 新增: // whereas SendInput clamps the system pointer to its physical screen. | |
| 127 | 新增: // Bring only the requested part of this window into the guest work area. | |
| 128 | 新增: private static Point PositionPointer(Window w, int x, int y) | |
| 129 | 新增: { | |
| 130 | 新增: Validate(w,true); | |
| 131 | 新增: var point=new Point {X=x, Y=y}; | |
| 132 | 新增: var monitor=new MonitorInfo {Size=(uint)Marshal.SizeOf<MonitorInfo>()}; | |
| 133 | 新增: if (!ClientToScreen(w.Handle,ref point) || !GetMonitorInfo(MonitorFromWindow(w.Handle,2),ref monitor) || | |
| 134 | 新增: monitor.Work.Right<=monitor.Work.Left || monitor.Work.Bottom<=monitor.Work.Top) | |
| 135 | 新增: throw new InvalidDataException("desktop_pointer_failed"); | |
| 136 | 新增: var dx=Math.Clamp(point.X,monitor.Work.Left,monitor.Work.Right-1)-point.X; | |
| 137 | 新增: var dy=Math.Clamp(point.Y,monitor.Work.Top,monitor.Work.Bottom-1)-point.Y; | |
| 138 | 新增: if(dx!=0 || dy!=0) | |
| 139 | 新增: { | |
| 140 | 新增: if(!GetWindowRect(w.Handle,out var outer) || | |
| 141 | 新增: !SetWindowPos(w.Handle,IntPtr.Zero,outer.Left+dx,outer.Top+dy,0,0,0x0001|0x0004|0x0010)) | |
| 142 | 新增: throw new InvalidDataException("desktop_pointer_failed"); | |
| 143 | 新增: point=new Point {X=x,Y=y}; | |
| 144 | 新增: if(!ClientToScreen(w.Handle,ref point)) throw new InvalidDataException("desktop_pointer_failed"); | |
| 145 | 新增: } | |
| 146 | 新增: Validate(w,true); | |
| 147 | 新增: if(!SetCursorPos(point.X,point.Y) || !GetCursorPos(out var actual) || actual.X!=point.X || actual.Y!=point.Y || | |
| 148 | 新增: GetAncestor(WindowFromPoint(actual),2)!=w.Handle) throw new InvalidDataException("desktop_target_changed"); | |
| 149 | 新增: return actual; | |
| 150 | 新增: } | |
| 151 | 新增: | |
| 152 | 新增: // A cropped WGC window can display an onboarding button beneath the | |
| 153 | 新增: // guest taskbar or another guest app. UI Automation invokes only the | |
| 154 | 新增: // authenticated app's visible button without using the global pointer. | |
| 155 | 新增: private static AutomationElement? WelcomeButton(Window w, int x, int y) | |
| 156 | 新增: { | |
| 157 | 新增: Validate(w,false); | |
| 158 | 新增: var point=new Point {X=x,Y=y}; | |
| 159 | 新增: if(!ClientToScreen(w.Handle,ref point)) return null; | |
| 160 | 新增: var root=AutomationElement.FromHandle(w.Handle); | |
| 161 | 新增: if(root.Current.ProcessId!=w.Process.Id) return null; | |
| 162 | 新增: var buttons=root.FindAll(TreeScope.Descendants,new PropertyCondition(AutomationElement.ControlTypeProperty,ControlType.Button)); | |
| 163 | 新增: if(buttons.Count>128) return null; | |
| 164 | 新增: AutomationElement? selected=null; | |
| 165 | 新增: foreach(AutomationElement element in buttons) | |
| 166 | 新增: { | |
| 167 | 新增: var current=element.Current; | |
| 168 | 新增: if(current.ProcessId!=w.Process.Id || !current.IsEnabled || current.IsOffscreen || | |
| 169 | 新增: !current.BoundingRectangle.Contains(point.X,point.Y)) continue; | |
| 170 | 新增: if(selected!=null || current.Name is not ("Get started" or "开始使用" or "開始使用")) return null; | |
| 171 | 新增: if(!element.TryGetCurrentPattern(InvokePattern.Pattern,out _)) return null; | |
| 172 | 新增: selected=element; | |
| 173 | 新增: } | |
| 174 | 新增: return selected; | |
| 175 | 新增: } | |
| 176 | 新增: | |
| 177 | 新增: internal static async Task Run(Stream stream, CancellationToken token, Func<bool> available) | |
| 178 | 新增: { | |
| 179 | 新增: int mask = 0; | |
| 180 | 新增: AutomationElement? welcomeDown = null; | |
| 181 | 新增: var inputLease = NativeGuestInput.OpenLease(); | |
| 182 | 新增: try | |
| 183 | 新增: { | |
| 184 | 新增: while (await Protocol.Read(stream, Protocol.WireLimit, token) is { } value) | |
| 185 | 新增: { | |
| 186 | 新增: await Operations.WaitAsync(token); | |
| 187 | 新增: var dpi = SetThreadDpiAwarenessContext(new IntPtr(-4)); | |
| 188 | 新增: try | |
| 189 | 新增: { | |
| 190 | 新增: if (!available()) throw new InvalidDataException("requires_gui_login"); | |
| 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") | |
| 193 | 新增: { | |
| 194 | 新增: await Protocol.Write(stream, WindowsDesktopDownloads.Read(value), token); continue; | |
| 195 | 新增: } | |
| 196 | 新增: if (action is "files-open-claim" or "files-open-complete") | |
| 197 | 新增: { | |
| 198 | 新增: await Protocol.Write(stream, WindowsDesktopFiles.OpenAction(value["id"]?.GetValue<string>() ?? "", action == "files-open-complete"), token); continue; | |
| 199 | 新增: } | |
| 200 | 新增: var registered = RegisteredExecutable(); | |
| 201 | 新增: var executable = registered?.Executable; | |
| 202 | 新增: if (action == "status") | |
| 203 | 新增: { | |
| 204 | 新增: bool running = false; double density = 1; | |
| 205 | 新增: if (executable is not null) { try { var window = Find(executable); using var owner = window.Process; density = GetDpiForWindow(window.Handle) / 96.0; running = true; } catch (InvalidDataException) { } } | |
| 206 | 新增: await Protocol.Write(stream, new JsonObject { ["installed"] = executable is not null, ["running"] = running, ["version"] = registered?.Version ?? "", ["native_user_session"] = true, ["display_scale"] = density, ["phone_supported"] = true }, token); continue; | |
| 207 | 新增: } | |
| 208 | 新增: if(action=="files-cancel") | |
| 209 | 新增: { | |
| 210 | 新增: WindowsDesktopFiles.Cancel(value["id"]?.GetValue<string>() ?? ""); | |
| 211 | 新增: AttachmentsRpc.CancelBatch(value["id"]?.GetValue<string>() ?? ""); | |
| 212 | 新增: await Protocol.Write(stream,new JsonObject{["ok"]=true},token);continue; | |
| 213 | 新增: } | |
| 214 | 新增: if(action=="files-poll" && executable is null) | |
| 215 | 新增: { | |
| 216 | 新增: await Protocol.Write(stream,new JsonObject{["available"]=false,["uploads"]=new JsonArray(),["downloads"]=WindowsDesktopDownloads.Snapshot(),["opens"]=WindowsDesktopFiles.OpenSnapshot()},token);continue; | |
| 217 | 新增: } | |
| 218 | 新增: if (executable is null) throw new InvalidDataException("desktop_not_installed"); | |
| 219 | 新增: if (action == "start") | |
| 220 | 新增: { | |
| 221 | 新增: Process.Start(new ProcessStartInfo(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Windows), "explorer.exe"), "shell:AppsFolder\\" + Family + "!Claude") { UseShellExecute = false }); | |
| 222 | 新增: await Protocol.Write(stream, new JsonObject { ["ok"] = true }, token); continue; | |
| 223 | 新增: } | |
| 224 | 新增: if(action=="files-poll") | |
| 225 | 新增: { | |
| 226 | 新增: Window? found = null; | |
| 227 | 新增: try { found = Find(executable); } | |
| 228 | 新增: catch (InvalidDataException) { } | |
| 229 | 新增: if (found is null) | |
| 230 | 新增: await Protocol.Write(stream,new JsonObject{["available"]=false,["uploads"]=new JsonArray(),["downloads"]=WindowsDesktopDownloads.Snapshot(),["opens"]=WindowsDesktopFiles.OpenSnapshot()},token); | |
| 231 | 新增: else | |
| 232 | 新增: { | |
| 233 | 新增: using var owner = found.Process; | |
| 234 | 新增: var binding = new WindowsFileDialogNative.Owner(owner.Id, owner.StartTime.ToUniversalTime().Ticks, | |
| 235 | 新增: owner.SessionId, found.Handle, executable, process => SessionGuard.Available() && SessionGuard.OwnsProcess(process)); | |
| 236 | 新增: await Protocol.Write(stream, WindowsDesktopFiles.Poll(binding), token); | |
| 237 | 新增: } | |
| 238 | 新增: continue; | |
| 239 | 新增: } | |
| 240 | 新增: var w = Find(executable); | |
| 241 | 新增: using var process = w.Process; | |
| 242 | 新增: if(action=="files-start") | |
| 243 | 新增: { | |
| 244 | 新增: Validate(w,true); | |
| 245 | 新增: var kind=value["kind"]?.GetValue<string>() ?? ""; | |
| 246 | 新增: var binding=await AttachmentTarget(w,kind,token); | |
| 247 | 新增: var result=AttachmentsRpc.StartBatch(binding,kind,value["x"]?.GetValue<double>() ?? 0,value["y"]?.GetValue<double>() ?? 0); | |
| 248 | 新增: await Protocol.Write(stream,result,token);continue; | |
| 249 | 新增: } | |
| 250 | 新增: if(action is "files-finish" or "files-finish-image") | |
| 251 | 新增: { | |
| 252 | 新增: var id = value["id"]?.GetValue<string>() ?? ""; | |
| 253 | 新增: if (WindowsDesktopFiles.Contains(id)) | |
| 254 | 新增: { | |
| 255 | 新增: await AttachmentsRpc.FinishBatch(id, (_, kind, paths, _, _) => | |
| 256 | 新增: { | |
| 257 | 新增: if (kind != "chooser") throw new InvalidDataException("file_dialog_selection_invalid"); | |
| 258 | 新增: return WindowsDesktopFiles.Finish(id, paths, token); | |
| 259 | 新增: }); | |
| 260 | 新增: await Protocol.Write(stream,new JsonObject{["ok"]=true},token);continue; | |
| 261 | 新增: } | |
| 262 | 新增: await AttachmentsRpc.FinishBatch(value["id"]?.GetValue<string>() ?? "",async(binding,kind,paths,x,y)=> | |
| 263 | 新增: { | |
| 264 | 新增: Validate(w,true); | |
| 265 | 新增: if(binding!=await AttachmentTarget(w,kind,token))throw new InvalidDataException("desktop_target_changed"); | |
| 266 | 新增: var agent=ClipboardAgent.Current ?? throw new InvalidDataException("clipboard_agent_unavailable"); | |
| 267 | 新增: if(action=="files-finish-image") | |
| 268 | 新增: { | |
| 269 | 新增: if(kind!="image"||paths.Length!=1)throw new InvalidDataException("attachment_request_invalid"); | |
| 270 | 新增: await using var file=new FileStream(paths[0],FileMode.Open,FileAccess.Read,FileShare.Read); | |
| 271 | 新增: if(file.Length<33||file.Length>Protocol.PngLimit)throw new InvalidDataException("image_limit"); | |
| 272 | 新增: var bytes=new byte[checked((int)file.Length)];await file.ReadExactlyAsync(bytes,token);Protocol.Png(bytes); | |
| 273 | 新增: if(binding!=await AttachmentTarget(w,kind,token))throw new InvalidDataException("desktop_target_changed"); | |
| 274 | 新增: await agent.PasteImage(bytes,()=>Emit(w,[KeyInput(0x11,true),KeyInput(0x56,true),KeyInput(0x56,false),KeyInput(0x11,false)])); | |
| 275 | 新增: } | |
| 276 | 新增: else if(kind=="paste")await agent.PasteFiles(paths,()=>Emit(w,[KeyInput(0x11,true),KeyInput(0x56,true),KeyInput(0x56,false),KeyInput(0x11,false)])); | |
| 277 | 新增: else if(kind=="image")throw new InvalidDataException("attachment_request_invalid"); | |
| 278 | 新增: else await agent.GUI(()=>{DropFiles(w,paths,x,y);return true;}); | |
| 279 | 新增: }); | |
| 280 | 新增: await Protocol.Write(stream,new JsonObject{["ok"]=true},token);continue; | |
| 281 | 新增: } | |
| 282 | 新增: if (action == "files-directory") | |
| 283 | 新增: { | |
| 284 | 新增: var id = value["id"]?.GetValue<string>() ?? ""; | |
| 285 | 新增: var folder = ProjectRpc.Resolve(value["project_id"]?.GetValue<string>() ?? "", value["grant"]?.GetValue<string>() ?? ""); | |
| 286 | 新增: await WindowsDesktopFiles.Finish(id, [folder], token); | |
| 287 | 新增: await Protocol.Write(stream, new JsonObject { ["ok"] = true }, token); continue; | |
| 288 | 新增: } | |
| 289 | 新增: if (action == "paste-image") | |
| 290 | 新增: { | |
| 291 | 新增: Validate(w, true); | |
| 292 | 新增: var bytes = Convert.FromBase64String(value["png"]?.GetValue<string>() ?? ""); Protocol.Png(bytes); | |
| 293 | 新增: var agent = ClipboardAgent.Current ?? throw new InvalidDataException("clipboard_agent_unavailable"); | |
| 294 | 新增: await agent.PasteImage(bytes, () => Emit(w, [KeyInput(0x11, true), KeyInput(0x56, true), KeyInput(0x56, false), KeyInput(0x11, false)])); | |
| 295 | 新增: await Protocol.Write(stream, new JsonObject { ["ok"] = true }, token); continue; | |
| 296 | 新增: } | |
| 297 | 新增: if (action == "ime") | |
| 298 | 新增: { | |
| 299 | 新增: Validate(w, true); | |
| 300 | 新增: var origin = new Point(); | |
| 301 | 新增: if (!ClientToScreen(w.Handle, ref origin)) throw new InvalidDataException("desktop_target_changed"); | |
| 302 | 新增: var result = await WindowsIme.Handle(value, w.Process.Id, Target(w), origin.X, origin.Y, | |
| 303 | 新增: content => Emit(w, content.SelectMany(c => new[] { Unicode(c, false), Unicode(c, true) }).ToArray()), token); | |
| 304 | 新增: await Protocol.Write(stream, result, token); continue; | |
| 305 | 新增: } | |
| 306 | 新增: if (action == "frame") | |
| 307 | 新增: { | |
| 308 | 新增: if (!await Captures.WaitAsync(0, token)) throw new InvalidDataException("desktop_capture_busy"); | |
| 309 | 新增: // A driver timeout retains one capture slot until its native | |
| 310 | 新增: // copy finishes. Later requests do not accumulate workers. | |
| 311 | 新增: Process? retainedProcess=null; | |
| 312 | 新增: Window retained; | |
| 313 | 新增: try{ | |
| 314 | 新增: retainedProcess=Process.GetProcessById(w.Process.Id); | |
| 315 | 新增: if(retainedProcess.StartTime!=w.Process.StartTime)throw new InvalidDataException("desktop_target_changed"); | |
| 316 | 新增: retained=w with { Process=retainedProcess }; | |
| 317 | 新增: }catch{retainedProcess?.Dispose();Captures.Release();throw;} | |
| 318 | 新增: var capture = Task.Run(() => { | |
| 319 | 新增: using var owner=retained.Process; | |
| 320 | 新增: try { return Capture(retained); } finally { Captures.Release(); } | |
| 321 | 新增: }); | |
| 322 | 新增: var bytes = await capture.WaitAsync(TimeSpan.FromSeconds(10), token); | |
| 323 | 新增: var target = Target(w); | |
| 324 | 新增: var sequence = target + Convert.ToHexString(SHA256.HashData(bytes)); | |
| 325 | 新增: if (value["after"]?.GetValue<string>() == sequence) | |
| 326 | 新增: await Protocol.Write(stream, new JsonObject { ["unchanged"] = true, ["sequence"] = sequence }, token); | |
| 327 | 新增: else | |
| 328 | 新增: await Protocol.Write(stream, new JsonObject { ["png"] = Convert.ToBase64String(bytes), ["sequence"] = sequence, ["width"] = w.Bounds.Right, ["height"] = w.Bounds.Bottom, ["target"] = target, ["density"] = GetDpiForWindow(w.Handle) / 96.0 }, token); | |
| 329 | 新增: continue; | |
| 330 | 新增: } | |
| 331 | 新增: if (action == "resize") | |
| 332 | 新增: { | |
| 333 | 新增: int width = value["width"]?.GetValue<int>() ?? 0, height = value["height"]?.GetValue<int>() ?? 0; | |
| 334 | 新增: if (width < 320 || height < 240 || width > 8192 || height > 8192 || (long)width * height > 40_000_000) throw new InvalidDataException("desktop_size_invalid"); | |
| 335 | 新增: // Electron's custom title bar occupies its client area. Measure | |
| 336 | 新增: // the actual window decorations instead of assuming stock chrome. | |
| 337 | 新增: if (!GetWindowRect(w.Handle,out var outer) || | |
| 338 | 新增: !SetWindowPos(w.Handle,IntPtr.Zero,0,0,width+outer.Right-outer.Left-w.Bounds.Right, | |
| 339 | 新增: height+outer.Bottom-outer.Top-w.Bounds.Bottom,0x0002|0x0004|0x0010)) | |
| 340 | 新增: throw new InvalidDataException("desktop_resize_failed"); | |
| 341 | 新增: await Protocol.Write(stream, new JsonObject { ["ok"] = true }, token); continue; | |
| 342 | 新增: } | |
| 343 | 新增: if (action == "stop") { | |
| 344 | 新增: Validate(w, false); | |
| 345 | 新增: if (!PostMessageW(w.Handle, 0x0010, IntPtr.Zero, IntPtr.Zero)) throw new InvalidDataException("desktop_close_failed"); | |
| 346 | 新增: await Protocol.Write(stream, new JsonObject { ["ok"] = true }, token); continue; | |
| 347 | 新增: } | |
| 348 | 新增: if (value["target"]?.GetValue<string>() != Target(w)) throw new InvalidDataException("desktop_target_changed"); | |
| 349 | 新增: await WindowsIme.RequirePhoneFocus(value, w.Process.Id, Target(w), token); | |
| 350 | 新增: if (action == "pointer") | |
| 351 | 新增: { | |
| 352 | 新增: int x = value["x"]?.GetValue<int>() ?? -1, y = value["y"]?.GetValue<int>() ?? -1, next = value["mask"]?.GetValue<int>() ?? -1; | |
| 353 | 新增: if (x < 0 || y < 0 || x >= w.Bounds.Right || y >= w.Bounds.Bottom || next < 0 || next > 127) throw new InvalidDataException("desktop_pointer_invalid"); | |
| 354 | 新增: if (welcomeDown!=null) | |
| 355 | 新增: { | |
| 356 | 新增: var down=welcomeDown; | |
| 357 | 新增: if(next!=1) welcomeDown=null; | |
| 358 | 新增: if(next==0) | |
| 359 | 新增: { | |
| 360 | 新增: var up=WelcomeButton(w,x,y); | |
| 361 | 新增: if(up==null || !Automation.Compare(down,up) || !up.TryGetCurrentPattern(InvokePattern.Pattern,out var command)) | |
| 362 | 新增: throw new InvalidDataException("desktop_target_changed"); | |
| 363 | 新增: Validate(w,false); | |
| 364 | 新增: ((InvokePattern)command).Invoke(); | |
| 365 | 新增: await Protocol.Write(stream,new JsonObject{["ok"]=true,["invoked"]=true},token);continue; | |
| 366 | 新增: } | |
| 367 | 新增: await Protocol.Write(stream,new JsonObject{["ok"]=true},token);continue; | |
| 368 | 新增: } | |
| 369 | 新增: if(next==1 && mask==0) | |
| 370 | 新增: { | |
| 371 | 新增: try { welcomeDown=WelcomeButton(w,x,y); } | |
| 372 | 新增: catch(ElementNotAvailableException) { welcomeDown=null; } | |
| 373 | 新增: if(welcomeDown!=null) {await Protocol.Write(stream,new JsonObject{["ok"]=true},token);continue;} | |
| 374 | 新增: } | |
| 375 | 新增: if (GetForegroundWindow() != w.Handle && next == 0) | |
| 376 | 新增: { | |
| 377 | 新增: Validate(w,false); | |
| 378 | 新增: NativeGuestInput.ResetLease(inputLease); | |
| 379 | 新增: mask=NativeGuestInput.PressedButtons(inputLease); | |
| 380 | 新增: await Protocol.Write(stream,new JsonObject{["ok"]=true},token);continue; | |
| 381 | 新增: } | |
| 382 | 新增: if (GetForegroundWindow() != w.Handle && next != 0) SetForegroundWindow(w.Handle); | |
| 383 | 新增: Validate(w, true); | |
| 384 | 新增: PositionPointer(w, x, y); | |
| 385 | 新增: var inputs = new List<Input>(); | |
| 386 | 新增: uint[] downs = [2, 0x20, 8], ups = [4, 0x40, 0x10]; | |
| 387 | 新增: for (int i=0; i<3; i++) if (((mask ^ next) & (1 << i)) != 0) inputs.Add(new Input { Data = new InputData { Mouse = new Mouse { Flags = (next & (1 << i)) != 0 ? downs[i] : ups[i] } } }); | |
| 388 | 新增: if ((next & 8) != 0) inputs.Add(Wheel(120)); if ((next & 16) != 0) inputs.Add(Wheel(-120)); | |
| 389 | 新增: if ((next & 32) != 0) inputs.Add(Wheel(-120, true)); if ((next & 64) != 0) inputs.Add(Wheel(120, true)); | |
| 390 | 新增: Emit(w, inputs.ToArray(), inputLease); mask = NativeGuestInput.PressedButtons(inputLease); | |
| 391 | 新增: } | |
| 392 | 新增: else if (action == "key") | |
| 393 | 新增: { | |
| 394 | 新增: var keysym = value["keysym"]?.GetValue<uint>() ?? 0; var down = value["down"]?.GetValue<bool>() ?? false; | |
| 395 | 新增: ushort key = Key(keysym); | |
| 396 | 新增: if (key == 0) throw new InvalidDataException("desktop_key_invalid"); | |
| 397 | 新增: var stroke=InputStroke.Key(key,!down); | |
| 398 | 新增: if(down)inputLease.Symbols[keysym]=[stroke]; | |
| 399 | 新增: else if(inputLease.Symbols.TryGetValue(keysym,out var original))stroke=original[0] with {Up=true}; | |
| 400 | 新增: EmitStrokes(w,[stroke],inputLease); | |
| 401 | 新增: if(!down)inputLease.Symbols.Remove(keysym); | |
| 402 | 新增: } | |
| 403 | 新增: else if (action == "text") | |
| 404 | 新增: { | |
| 405 | 新增: var text = value["text"]?.GetValue<string>() ?? ""; | |
| 406 | 新增: if (Protocol.Utf8.GetByteCount(text) > 8192) throw new InvalidDataException("desktop_text_limit"); | |
| 407 | 新增: var inputs = text.SelectMany(c => new[] { Unicode(c, false), Unicode(c, true) }).ToArray(); Emit(w, inputs); | |
| 408 | 新增: } | |
| 409 | 新增: else throw new InvalidDataException("desktop_request_invalid"); | |
| 410 | 新增: await Protocol.Write(stream, new JsonObject { ["ok"] = true }, token); | |
| 411 | 新增: } | |
| 412 | 新增: catch (Exception e) when (e is not OperationCanceledException) | |
| 413 | 新增: { | |
| 414 | 新增: // Only a type and HRESULT cross the trust boundary. Exception | |
| 415 | 新增: // messages from Windows can include user-controlled strings. | |
| 416 | 新增: await Protocol.Write(stream, new JsonObject { | |
| 417 | 新增: ["error"] = e is InvalidDataException ? e.Message : "desktop_operation_failed", | |
| 418 | 新增: ["exception_type"] = e.GetType().Name, ["native_code"] = e.HResult.ToString("X8"), | |
| 419 | 新增: }, token); | |
| 420 | 新增: } | |
| 421 | 新增: finally { if (dpi != IntPtr.Zero) SetThreadDpiAwarenessContext(dpi); Operations.Release(); } | |
| 422 | 新增: } | |
| 423 | 新增: } | |
| 424 | 新增: finally | |
| 425 | 新增: { | |
| 426 | 新增: NativeGuestInput.CloseLease(inputLease); | |
| 427 | 新增: } | |
| 428 | 新增: } | |
| 429 | 新增: private static string Target(Window w) { | |
| 430 | 新增: Validate(w, false); | |
| 431 | 新增: var title=new System.Text.StringBuilder(4096);GetWindowTextW(w.Handle,title,title.Capacity); | |
| 432 | 新增: var data = Protocol.Utf8.GetBytes($"{w.Process.Id}:{w.Process.StartTime.ToUniversalTime().Ticks}:{w.Handle.ToInt64()}:{w.Bounds.Right}:{w.Bounds.Bottom}:{GetDpiForWindow(w.Handle)}:{title}"); | |
| 433 | 新增: return Convert.ToHexString(SHA256.HashData(data).AsSpan(0,16)).ToLowerInvariant(); | |
| 434 | 新增: } | |
| 435 | 新增: private static async Task<string> AttachmentTarget(Window w,string kind,CancellationToken token) | |
| 436 | 新增: { | |
| 437 | 新增: var target=Target(w);if(kind=="drop")return target; | |
| 438 | 新增: if(kind is not ("paste" or "image"))throw new InvalidDataException("attachment_request_invalid"); | |
| 439 | 新增: var origin=new Point();if(!ClientToScreen(w.Handle,ref origin))throw new InvalidDataException("desktop_target_changed"); | |
| 440 | 新增: var focus=await WindowsIme.Handle(new JsonObject{["mode"]="status"},w.Process.Id,target,origin.X,origin.Y,_=>throw new InvalidDataException("attachment_request_invalid"),token); | |
| 441 | 新增: if(focus["available"]?.GetValue<bool>()!=true)throw new InvalidDataException("desktop_input_not_focused"); | |
| 442 | 新增: return target+":"+focus["context"]!.GetValue<string>(); | |
| 443 | 新增: } | |
| 444 | 新增: private static void DropFiles(Window w,string[] paths,double x,double y) | |
| 445 | 新增: { | |
| 446 | 新增: Validate(w,true); | |
| 447 | 新增: var point=PositionPointer(w,Math.Clamp((int)(x*w.Bounds.Right),0,w.Bounds.Right-1),Math.Clamp((int)(y*w.Bounds.Bottom),0,w.Bounds.Bottom-1)); | |
| 448 | 新增: void Guard(){Validate(w,true);if(GetAncestor(WindowFromPoint(point),2)!=w.Handle)throw new InvalidDataException("desktop_target_changed");} | |
| 449 | 新增: Guard(); | |
| 450 | 新增: var initialized=OleInitialize(IntPtr.Zero);Marshal.ThrowExceptionForHR(initialized); | |
| 451 | 新增: try | |
| 452 | 新增: { | |
| 453 | 新增: var data=new DataObject();data.SetData(DataFormats.FileDrop,true,paths); | |
| 454 | 新增: using var release=new System.Windows.Forms.Timer{Interval=100}; | |
| 455 | 新增: release.Tick+=(_,_)=>{try{Emit(w,[KeyInput(17,true),KeyInput(17,false)]);}catch{release.Stop();}}; | |
| 456 | 新增: release.Start(); | |
| 457 | 新增: var result=DoDragDrop((System.Runtime.InteropServices.ComTypes.IDataObject)data,new DropSource(Guard),1,out var effect); | |
| 458 | 新增: if(result!=0x40100 || (effect&1)==0)throw new InvalidDataException("desktop_drop_not_accepted"); | |
| 459 | 新增: } | |
| 460 | 新增: finally{OleUninitialize();} | |
| 461 | 新增: } | |
| 462 | 新增: internal static WindowsAudioRpc.Target? AudioTarget() | |
| 463 | 新增: { | |
| 464 | 新增: if (!SessionGuard.Available()) throw new InvalidDataException("requires_gui_login"); | |
| 465 | 新增: var registered = RegisteredExecutable(); if (registered is null) return null; | |
| 466 | 新增: var session = Process.GetCurrentProcess().SessionId; WindowsAudioRpc.Target? first = null; | |
| 467 | 新增: foreach (var process in Process.GetProcessesByName("Claude")) | |
| 468 | 新增: { | |
| 469 | 新增: var owned = false; | |
| 470 | 新增: try | |
| 471 | 新增: { | |
| 472 | 新增: if (process.SessionId != session || !string.Equals(process.MainModule?.FileName, registered.Executable, StringComparison.OrdinalIgnoreCase)) continue; | |
| 473 | 新增: var target = new WindowsAudioRpc.Target(process, registered.Executable); owned = true; | |
| 474 | 新增: if (first is null || target.Started < first.Started) { first?.Dispose(); first = target; } | |
| 475 | 新增: else target.Dispose(); | |
| 476 | 新增: } | |
| 477 | 新增: catch (Exception e) when (e is InvalidDataException or InvalidOperationException or System.ComponentModel.Win32Exception) { } | |
| 478 | 新增: finally { if (!owned) process.Dispose(); } | |
| 479 | 新增: } | |
| 480 | 新增: return first; | |
| 481 | 新增: } | |
| 482 | 新增: private static byte[] Capture(Window w) => ClaudeGraphicsCapture.Capture(w.Handle,w.Process.Id,w.Bounds.Right,w.Bounds.Bottom,()=>Validate(w,false)).GetAwaiter().GetResult(); | |
| 483 | 新增: private static Input Wheel(int amount, bool horizontal = false) => new() { Data = new InputData { Mouse = new Mouse { Flags = horizontal ? 0x1000u : 0x800u, Data = unchecked((uint)amount) } } }; | |
| 484 | 新增: private static Input Unicode(char c, bool up) => new() { Type = 1, Data = new InputData { Keyboard = new Keyboard { Scan = c, Flags = 4u | (up ? 2u : 0u) } } }; | |
| 485 | 新增: private static Input KeyInput(ushort key, bool down) => new() { Type = 1, Data = new InputData { Keyboard = new Keyboard { Key = key, Flags = down ? 0u : 2u } } }; | |
| 486 | 新增: private static void Emit(Window w, Input[] inputs, NativeInputCoordinator.Lease? lease=null) | |
| 487 | 新增: { | |
| 488 | 新增: var strokes=inputs.Select(input=>input.Type==1 | |
| 489 | 新增: ? InputStroke.Key((input.Data.Keyboard.Flags&4)!=0?input.Data.Keyboard.Scan:input.Data.Keyboard.Key,(input.Data.Keyboard.Flags&2)!=0,(input.Data.Keyboard.Flags&4)!=0) | |
| 490 | 新增: : input.Data.Mouse.Flags switch | |
| 491 | 新增: { | |
| 492 | 新增: 2=>InputStroke.Button(1,false),4=>InputStroke.Button(1,true),32=>InputStroke.Button(2,false),64=>InputStroke.Button(2,true),8=>InputStroke.Button(4,false),16=>InputStroke.Button(4,true), | |
| 493 | 新增: 0x800=>InputStroke.Wheel(unchecked((int)input.Data.Mouse.Data)),0x1000=>InputStroke.Wheel(unchecked((int)input.Data.Mouse.Data),true), | |
| 494 | 新增: _=>throw new InvalidDataException("desktop_input_failed") | |
| 495 | 新增: }).ToArray(); | |
| 496 | 新增: var own=lease is null;lease??=NativeGuestInput.OpenLease(); | |
| 497 | 新增: try{EmitStrokes(w,strokes,lease);}finally{if(own)NativeGuestInput.CloseLease(lease);} | |
| 498 | 新增: } | |
| 499 | 新增: private static void EmitStrokes(Window w,InputStroke[] strokes,NativeInputCoordinator.Lease lease) | |
| 500 | 新增: { | |
| 501 | 新增: var id=w.Process.Id;var started=w.Process.StartTime.ToUniversalTime();var session=w.Process.SessionId;var handle=w.Handle;var executable=w.Executable; | |
| 502 | 新增: bool ReleaseAllowed() | |
| 503 | 新增: { | |
| 504 | 新增: if(!SessionGuard.Available() || Process.GetCurrentProcess().SessionId!=session)return false; | |
| 505 | 新增: try | |
| 506 | 新增: { | |
| 507 | 新增: using var process=Process.GetProcessById(id); | |
| 508 | 新增: if(process.HasExited)return true; | |
| 509 | 新增: if(process.StartTime.ToUniversalTime()!=started || process.SessionId!=session || !string.Equals(process.MainModule?.FileName,executable,StringComparison.OrdinalIgnoreCase))return false; | |
| 510 | 新增: var thread=GetWindowThreadProcessId(handle,out var current); | |
| 511 | 新增: return thread==0 || current==id; | |
| 512 | 新增: } | |
| 513 | 新增: catch(ArgumentException){return true;} | |
| 514 | 新增: catch{return false;} | |
| 515 | 新增: } | |
| 516 | 新增: NativeGuestInput.Emit(lease,strokes,()=>Validate(w,true),ReleaseAllowed); | |
| 517 | 新增: } | |
| 518 | 新增: private static ushort Key(uint sym) => sym switch | |
| 519 | 新增: { | |
| 520 | 新增: 0xff08 => 8, 0xff09 => 9, 0xff0d => 13, 0xff1b => 27, 0xffff => 46, | |
| 521 | 新增: 0xff50 => 36, 0xff51 => 37, 0xff52 => 38, 0xff53 => 39, 0xff54 => 40, 0xff55 => 33, 0xff56 => 34, 0xff57 => 35, 0xff63 => 45, | |
| 522 | 新增: 0xffe1 or 0xffe2 => 16, 0xffe3 or 0xffe4 => 17, 0xffe9 or 0xffea => 18, 0xffe7 or 0xffe8 or 0xffeb or 0xffec => 91, | |
| 523 | 新增: >= 0xffbe and <= 0xffc9 => (ushort)(112 + sym - 0xffbe), | |
| 524 | 新增: >= 32 and <= 126 => (ushort)(VkKeyScanW((char)sym) & 0xff), _ => 0 | |
| 525 | 新增: }; | |
| 526 | 新增:} | |
| @@ -0,0 +1,387 @@ | ||
| 1 | 新增:using System.Collections.Specialized; | |
| 2 | 新增:using System.Diagnostics; | |
| 3 | 新增:using System.Drawing.Imaging; | |
| 4 | 新增:using System.Runtime.InteropServices; | |
| 5 | 新增:using System.Text.Json; | |
| 6 | 新增:using System.Text.Json.Nodes; | |
| 7 | 新增:using System.Threading.Channels; | |
| 8 | 新增: | |
| 9 | 新增:namespace Cage.GuestClipboard; | |
| 10 | 新增: | |
| 11 | 新增:internal sealed class ClipboardAgent : Control | |
| 12 | 新增:{ | |
| 13 | 新增: internal static ClipboardAgent? Current { get; private set; } | |
| 14 | 新增: [DllImport("user32.dll")] static extern bool AddClipboardFormatListener(IntPtr window); | |
| 15 | 新增: [DllImport("user32.dll")] static extern bool RemoveClipboardFormatListener(IntPtr window); | |
| 16 | 新增: [DllImport("user32.dll")] static extern uint GetClipboardSequenceNumber(); | |
| 17 | 新增: [DllImport("wtsapi32.dll", SetLastError = true)] private static extern bool WTSRegisterSessionNotification(IntPtr window, uint flags); | |
| 18 | 新增: [DllImport("wtsapi32.dll")] private static extern bool WTSUnRegisterSessionNotification(IntPtr window); | |
| 19 | 新增: internal readonly string Session = Guid.NewGuid().ToString("N"); | |
| 20 | 新增: private long sessionEpoch = 1; | |
| 21 | 新增: internal long SessionEpoch => Interlocked.Read(ref sessionEpoch); | |
| 22 | 新增: internal bool SessionEventsRegistered { get; private set; } | |
| 23 | 新增: readonly string helper; | |
| 24 | 新增: readonly HashSet<string> approved = new(StringComparer.OrdinalIgnoreCase); | |
| 25 | 新增: readonly Queue<string[]> selections = new(); | |
| 26 | 新增: sealed class CachedCopy(string id, string[] paths, bool pinned) | |
| 27 | 新增: { | |
| 28 | 新增: internal readonly string ID = id; | |
| 29 | 新增: internal readonly string[] Paths = paths; | |
| 30 | 新增: internal bool Pinned = pinned; | |
| 31 | 新增: } | |
| 32 | 新增: readonly Dictionary<string, CachedCopy> copies = new(); | |
| 33 | 新增: readonly Dictionary<Guid, string[]> fileReaders = new(); | |
| 34 | 新增: bool copiesLoaded, collectingCopies; | |
| 35 | 新增: DateTime nextCacheCheck; | |
| 36 | 新增: readonly System.Windows.Forms.Timer timer = new() { Interval = 250 }; | |
| 37 | 新增: Channel<JsonObject>? subscriber; | |
| 38 | 新增: uint observed; | |
| 39 | 新增: bool seeded, reading, lastAvailable; | |
| 40 | 新增: CancellationTokenSource? selectionCopy; | |
| 41 | 新增: internal ClipboardAgent(string filesHelper) | |
| 42 | 新增: { | |
| 43 | 新增: Current = this; | |
| 44 | 新增: helper = filesHelper; | |
| 45 | 新增: CreateControl(); _ = Handle; | |
| 46 | 新增: if (!File.Exists(helper) || !AddClipboardFormatListener(Handle)) throw new InvalidOperationException("clipboard_agent_unavailable"); | |
| 47 | 新增: SessionEventsRegistered = WTSRegisterSessionNotification(Handle, 0); | |
| 48 | 新增: lastAvailable = SessionGuard.Available(); observed = GetClipboardSequenceNumber(); | |
| 49 | 新增: timer.Tick += (_, _) => Tick(); timer.Start(); | |
| 50 | 新增: } | |
| 51 | 新增: protected override void WndProc(ref Message m) | |
| 52 | 新增: { | |
| 53 | 新增: if (m.Msg == 0x031D) Tick(); // WM_CLIPBOARDUPDATE | |
| 54 | 新增: if (m.Msg == 0x02B1) { Interlocked.Increment(ref sessionEpoch); Tick(); } | |
| 55 | 新增: base.WndProc(ref m); | |
| 56 | 新增: } | |
| 57 | 新增: protected override void Dispose(bool disposing) | |
| 58 | 新增: { | |
| 59 | 新增: if (disposing) { timer.Stop(); timer.Dispose(); RemoveClipboardFormatListener(Handle); if (SessionEventsRegistered) WTSUnRegisterSessionNotification(Handle); subscriber?.Writer.TryComplete(); } | |
| 60 | 新增: base.Dispose(disposing); | |
| 61 | 新增: } | |
| 62 | 新增: internal Task<T> GUI<T>(Func<T> action) | |
| 63 | 新增: { | |
| 64 | 新增: var result = new TaskCompletionSource<T>(TaskCreationOptions.RunContinuationsAsynchronously); | |
| 65 | 新增: BeginInvoke(() => { try { result.SetResult(action()); } catch (Exception ex) { result.SetException(ex); } }); | |
| 66 | 新增: return result.Task; | |
| 67 | 新增: } | |
| 68 | 新增: internal Task<uint> Revision() => GUI(() => { SessionGuard.Assert(); return GetClipboardSequenceNumber(); }); | |
| 69 | 新增: internal Task<bool> PasteImage(byte[] bytes, Action paste) => GUI(() => | |
| 70 | 新增: { | |
| 71 | 新增: SessionGuard.Assert(); Protocol.Png(bytes); | |
| 72 | 新增: using var input = new MemoryStream(bytes); using var image = Image.FromStream(input, false, true); | |
| 73 | 新增: using var bitmap = new Bitmap(image); | |
| 74 | 新增: var data = new DataObject(); data.SetData("PNG", false, new MemoryStream(bytes)); data.SetImage(bitmap); | |
| 75 | 新增: Clipboard.SetDataObject(data, true); paste(); return true; | |
| 76 | 新增: }); | |
| 77 | 新增: internal Task<bool> PasteFiles(string[] paths, Action paste) => GUI(() => | |
| 78 | 新增: { | |
| 79 | 新增: SessionGuard.Assert(); Protocol.Paths(JsonSerializer.SerializeToNode(paths)); | |
| 80 | 新增: Approve(paths); var list=new StringCollection();list.AddRange(paths); | |
| 81 | 新增: Clipboard.SetFileDropList(list);paste();return true; | |
| 82 | 新增: }); | |
| 83 | 新增: // Private browser receipts confirm native Windows clipboard ownership. | |
| 84 | 新增: // Content still travels through the single observer, preserving PNG and | |
| 85 | 新增: // file selections instead of rewriting a browser's text-only result. | |
| 86 | 新增: internal Task<JsonObject> Receipt(uint previous, bool requireChange) => GUI(() => | |
| 87 | 新增: { | |
| 88 | 新增: SessionGuard.Assert(); var revision = GetClipboardSequenceNumber(); | |
| 89 | 新增: if (requireChange && revision == previous) throw new InvalidDataException("clipboard_copy_not_observed"); | |
| 90 | 新增: return new JsonObject { ["revision"] = revision, ["changed"] = revision != previous, ["available"] = true }; | |
| 91 | 新增: }); | |
| 92 | 新增: internal Task<JsonObject> PreparePaste() => GUI(() => | |
| 93 | 新增: { | |
| 94 | 新增: SessionGuard.Assert(); var revision = GetClipboardSequenceNumber(); | |
| 95 | 新增: if (Clipboard.ContainsFileDropList()) { var paths = Protocol.Paths(JsonSerializer.SerializeToNode(Clipboard.GetFileDropList().Cast<string>().ToArray())); AssertApproved(paths); } | |
| 96 | 新增: else if (Clipboard.TryGetData<MemoryStream>("PNG", out var png) && png != null) Protocol.Png(png.ToArray()); | |
| 97 | 新增: else if (Clipboard.ContainsImage()) | |
| 98 | 新增: { | |
| 99 | 新增: using var image = Clipboard.GetImage() ?? throw new InvalidDataException("clipboard_image_unavailable"); | |
| 100 | 新增: if ((long)image.Width * image.Height > 40_000_000) throw new InvalidDataException("image_limit"); | |
| 101 | 新增: using var bytes = new MemoryStream(); image.Save(bytes, ImageFormat.Png); Protocol.Png(bytes.ToArray()); | |
| 102 | 新增: } | |
| 103 | 新增: else if (Clipboard.ContainsText() && Protocol.Utf8.GetByteCount(Clipboard.GetText(TextDataFormat.UnicodeText)) > Protocol.TextLimit) throw new InvalidDataException("text_limit"); | |
| 104 | 新增: if (GetClipboardSequenceNumber() != revision) throw new InvalidDataException("clipboard_selection_changed"); | |
| 105 | 新增: return new JsonObject { ["revision"] = revision, ["available"] = true }; | |
| 106 | 新增: }); | |
| 107 | 新增: internal Task<JsonObject> WriteBrowserPng(uint expectedRevision, byte[] png) => GUI(() => | |
| 108 | 新增: { | |
| 109 | 新增: SessionGuard.Assert(); Protocol.Png(png); | |
| 110 | 新增: if (GetClipboardSequenceNumber() != expectedRevision) throw new InvalidDataException("clipboard_selection_changed"); | |
| 111 | 新增: using var input = new MemoryStream(png); using var image = Image.FromStream(input, false, true); using var bitmap = new Bitmap(image); | |
| 112 | 新增: if (GetClipboardSequenceNumber() != expectedRevision) throw new InvalidDataException("clipboard_selection_changed"); | |
| 113 | 新增: var data = new DataObject(); data.SetData("PNG", false, new MemoryStream(png)); data.SetImage(bitmap); Clipboard.SetDataObject(data, true); | |
| 114 | 新增: observed = GetClipboardSequenceNumber(); seeded = true; | |
| 115 | 新增: Publish(new JsonObject { ["png"] = Convert.ToBase64String(png), ["source"] = "guest" }); | |
| 116 | 新增: return new JsonObject { ["revision"] = observed, ["available"] = true }; | |
| 117 | 新增: }); | |
| 118 | 新增: internal Task<JsonObject> WriteBrowserText(uint expectedRevision, string text) => GUI(() => | |
| 119 | 新增: { | |
| 120 | 新增: SessionGuard.Assert(); | |
| 121 | 新增: if (Protocol.Utf8.GetByteCount(text) > Protocol.TextLimit) throw new InvalidDataException("text_limit"); | |
| 122 | 新增: if (GetClipboardSequenceNumber() != expectedRevision) throw new InvalidDataException("clipboard_selection_changed"); | |
| 123 | 新增: if (text.Length == 0) Clipboard.Clear(); else Clipboard.SetText(text, TextDataFormat.UnicodeText); | |
| 124 | 新增: observed = GetClipboardSequenceNumber(); seeded = true; | |
| 125 | 新增: Publish(new JsonObject { ["text"] = text, ["source"] = "guest" }); | |
| 126 | 新增: return new JsonObject { ["revision"] = observed, ["available"] = true }; | |
| 127 | 新增: }); | |
| 128 | 新增: internal JsonObject Hello() => new() { ["version"] = 1, ["os"] = "windows", ["session"] = Session, ["formats"] = new JsonArray("text", "png", "files"), ["available"] = SessionGuard.Available(), ["file_release"] = true }; | |
| 129 | 新增: internal Task<ChannelReader<JsonObject>> Subscribe() => GUI(() => | |
| 130 | 新增: { | |
| 131 | 新增: if (subscriber != null) throw new InvalidOperationException("clipboard_busy"); | |
| 132 | 新增: subscriber = Channel.CreateBounded<JsonObject>(new BoundedChannelOptions(16) { SingleReader = true, FullMode = BoundedChannelFullMode.Wait }); | |
| 133 | 新增: seeded = false; observed = GetClipboardSequenceNumber(); | |
| 134 | 新增: return subscriber.Reader; | |
| 135 | 新增: }); | |
| 136 | 新增: internal Task<bool> Unsubscribe() => GUI(() => { | |
| 137 | 新增: subscriber?.Writer.TryComplete(); subscriber = null; seeded = false; | |
| 138 | 新增: foreach (var copy in copies.Values) copy.Pinned = false; | |
| 139 | 新增: CollectCopies(); return true; | |
| 140 | 新增: }); | |
| 141 | 新增: void Publish(JsonObject message) | |
| 142 | 新增: { | |
| 143 | 新增: if (subscriber != null && subscriber.Writer.TryWrite(message)) return; | |
| 144 | 新增: if (message["files"] is not null) RetireCopies(Protocol.Paths(message["files"])); | |
| 145 | 新增: subscriber?.Writer.TryComplete(new IOException("clipboard_consumer_slow")); | |
| 146 | 新增: } | |
| 147 | 新增: internal void ReportError() => Publish(new() { ["error"] = SessionGuard.Available() ? "clipboard_selection_unavailable" : "requires_gui_login" }); | |
| 148 | 新增: void Tick() | |
| 149 | 新增: { | |
| 150 | 新增: if (DateTime.UtcNow >= nextCacheCheck) { nextCacheCheck = DateTime.UtcNow.AddSeconds(1); CollectCopies(); } | |
| 151 | 新增: var available = SessionGuard.Available(); | |
| 152 | 新增: if (available != lastAvailable) { Interlocked.Increment(ref sessionEpoch); lastAvailable = available; Publish(Protocol.PublicHello(Hello())); } | |
| 153 | 新增: if (!available) selectionCopy?.Cancel(); | |
| 154 | 新增: if (!available || !seeded || subscriber == null || reading) return; | |
| 155 | 新增: var sequence = GetClipboardSequenceNumber(); | |
| 156 | 新增: if (sequence == observed) return; | |
| 157 | 新增: ReadSelection(sequence); | |
| 158 | 新增: } | |
| 159 | 新增: async void ReadSelection(uint sequence) | |
| 160 | 新增: { | |
| 161 | 新增: reading = true; | |
| 162 | 新增: var capturedSubscriber = subscriber; | |
| 163 | 新增: var capturedSession = SessionEpoch; | |
| 164 | 新增: try | |
| 165 | 新增: { | |
| 166 | 新增: SessionGuard.Assert(); | |
| 167 | 新增: JsonObject payload; | |
| 168 | 新增: if (Clipboard.ContainsFileDropList()) | |
| 169 | 新增: { | |
| 170 | 新增: var paths = Clipboard.GetFileDropList().Cast<string>().ToArray(); | |
| 171 | 新增: Protocol.Paths(JsonSerializer.SerializeToNode(paths)); | |
| 172 | 新增: Approve(paths); // The native GUI selection itself is an explicit source grant. | |
| 173 | 新增: // This child inherits the actual GUI token, never Session0 or a | |
| 174 | 新增: // management administrator's access to the selected files. | |
| 175 | 新增: using var copying = new CancellationTokenSource(TimeSpan.FromMinutes(30)); selectionCopy = copying; | |
| 176 | 新增: string[] copied; | |
| 177 | 新增: try { copied = await FilePaths("copy", paths, copying.Token); } | |
| 178 | 新增: finally { if (selectionCopy == copying) selectionCopy = null; } | |
| 179 | 新增: if (!SessionGuard.Available() || GetClipboardSequenceNumber() != sequence || subscriber != capturedSubscriber || SessionEpoch != capturedSession || !seeded) { RetireCopies(copied); return; } | |
| 180 | 新增: Approve(copied); | |
| 181 | 新增: payload = new() { ["files"] = JsonSerializer.SerializeToNode(copied) }; | |
| 182 | 新增: } | |
| 183 | 新增: else if (Clipboard.ContainsData("PNG") || Clipboard.ContainsImage()) | |
| 184 | 新增: { | |
| 185 | 新增: byte[] bytes; | |
| 186 | 新增: if (Clipboard.TryGetData<MemoryStream>("PNG", out var png) && png != null) bytes = png.ToArray(); | |
| 187 | 新增: else | |
| 188 | 新增: { | |
| 189 | 新增: using var image = Clipboard.GetImage() ?? throw new InvalidDataException("clipboard_image_unavailable"); | |
| 190 | 新增: if ((long)image.Width * image.Height > 40_000_000) throw new InvalidDataException("image_limit"); | |
| 191 | 新增: using var output = new MemoryStream(); image.Save(output, ImageFormat.Png); bytes = output.ToArray(); | |
| 192 | 新增: } | |
| 193 | 新增: Protocol.Png(bytes); payload = new() { ["png"] = Convert.ToBase64String(bytes) }; | |
| 194 | 新增: } | |
| 195 | 新增: else | |
| 196 | 新增: { | |
| 197 | 新增: var text = Clipboard.ContainsText() ? Clipboard.GetText(TextDataFormat.UnicodeText) : ""; | |
| 198 | 新增: if (Protocol.Utf8.GetByteCount(text) > Protocol.TextLimit) throw new InvalidDataException("text_limit"); | |
| 199 | 新增: payload = new() { ["text"] = text }; | |
| 200 | 新增: } | |
| 201 | 新增: if (!SessionGuard.Available() || GetClipboardSequenceNumber() != sequence) return; | |
| 202 | 新增: observed = sequence; payload["source"] = "guest"; Publish(payload); | |
| 203 | 新增: } | |
| 204 | 新增: catch { if (SessionGuard.Available()) { observed = sequence; Publish(new() { ["error"] = "clipboard_selection_unavailable" }); } } | |
| 205 | 新增: finally { reading = false; } | |
| 206 | 新增: } | |
| 207 | 新增: internal Task<bool> Apply(JsonObject message) => GUI(() => | |
| 208 | 新增: { | |
| 209 | 新增: if (message["release"] is not null) { RetireCopies(Protocol.Paths(message["release"])); return true; } | |
| 210 | 新增: SessionGuard.Assert(); | |
| 211 | 新增: selectionCopy?.Cancel(); | |
| 212 | 新增: var serial = message["serial"]?.GetValue<long>() ?? 0; | |
| 213 | 新增: if (serial < 1 || new[] { "text", "png", "files" }.Count(message.ContainsKey) != 1) throw new InvalidDataException("clipboard_message_invalid"); | |
| 214 | 新增: if (message["files"] != null) | |
| 215 | 新增: { | |
| 216 | 新增: var paths = Protocol.Paths(message["files"]); AssertApproved(paths); | |
| 217 | 新增: var list = new StringCollection(); list.AddRange(paths); Clipboard.SetFileDropList(list); | |
| 218 | 新增: } | |
| 219 | 新增: else if (message["png"] != null) | |
| 220 | 新增: { | |
| 221 | 新增: var bytes = Convert.FromBase64String(message["png"]!.GetValue<string>()); Protocol.Png(bytes); | |
| 222 | 新增: using var input = new MemoryStream(bytes); using var image = Image.FromStream(input, false, true); | |
| 223 | 新增: using var bitmap = new Bitmap(image); | |
| 224 | 新增: var data = new DataObject(); data.SetData("PNG", false, new MemoryStream(bytes)); data.SetImage(bitmap); | |
| 225 | 新增: Clipboard.SetDataObject(data, true); | |
| 226 | 新增: } | |
| 227 | 新增: else | |
| 228 | 新增: { | |
| 229 | 新增: var text = message["text"]!.GetValue<string>(); | |
| 230 | 新增: if (Protocol.Utf8.GetByteCount(text) > Protocol.TextLimit) throw new InvalidDataException("text_limit"); | |
| 231 | 新增: if (text.Length == 0) Clipboard.Clear(); else Clipboard.SetText(text, TextDataFormat.UnicodeText); | |
| 232 | 新增: } | |
| 233 | 新增: // The revision is saved on the STA before queued clipboard notifications | |
| 234 | 新增: // run. Only a completed host write receives an acknowledgement. | |
| 235 | 新增: observed = GetClipboardSequenceNumber(); seeded = true; Publish(new() { ["ack"] = serial }); return true; | |
| 236 | 新增: }); | |
| 237 | 新增: void RememberCopy(JsonObject result) | |
| 238 | 新增: { | |
| 239 | 新增: var id = result["cache_id"]?.GetValue<string>(); | |
| 240 | 新增: if (string.IsNullOrEmpty(id)) return; | |
| 241 | 新增: var paths = Protocol.Paths(result["paths"]); | |
| 242 | 新增: copies[id] = new CachedCopy(id, paths, true); | |
| 243 | 新增: _ = PublishCopy(id); | |
| 244 | 新增: } | |
| 245 | 新增: async Task PublishCopy(string id) | |
| 246 | 新增: { | |
| 247 | 新增: try { await Cache("publish", id); } catch { } | |
| 248 | 新增: } | |
| 249 | 新增: void RetireCopies(string[] paths) | |
| 250 | 新增: { | |
| 251 | 新增: foreach (var copy in copies.Values) | |
| 252 | 新增: if (copy.Paths.Any(path => paths.Contains(path, StringComparer.OrdinalIgnoreCase))) copy.Pinned = false; | |
| 253 | 新增: CollectCopies(); | |
| 254 | 新增: } | |
| 255 | 新增: static bool References(string[] paths, string[] owned) | |
| 256 | 新增: { | |
| 257 | 新增: var root = Path.GetDirectoryName(owned[0])!; | |
| 258 | 新增: return paths.Any(path => Path.GetFullPath(path).Equals(root, StringComparison.OrdinalIgnoreCase) | |
| 259 | 新增: || Path.GetFullPath(path).StartsWith(root + Path.DirectorySeparatorChar, StringComparison.OrdinalIgnoreCase) | |
| 260 | 新增: || root.StartsWith(Path.GetFullPath(path).TrimEnd(Path.DirectorySeparatorChar) + Path.DirectorySeparatorChar, StringComparison.OrdinalIgnoreCase)); | |
| 261 | 新增: } | |
| 262 | 新增: async Task<JsonObject> Cache(string action, string id = "") | |
| 263 | 新增: { | |
| 264 | 新增: var start = new ProcessStartInfo(helper) { UseShellExecute = false, CreateNoWindow = true, RedirectStandardInput = true, RedirectStandardOutput = true, RedirectStandardError = true }; | |
| 265 | 新增: start.ArgumentList.Add("cache"); start.ArgumentList.Add(JsonSerializer.Serialize(new { action, cache_id = id })); | |
| 266 | 新增: using var child = Process.Start(start) ?? throw new IOException("clipboard_cache_unavailable"); | |
| 267 | 新增: child.StandardInput.Close(); | |
| 268 | 新增: _ = child.StandardError.BaseStream.CopyToAsync(Stream.Null); | |
| 269 | 新增: using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(10)); | |
| 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"); | |
| 272 | 新增: await child.WaitForExitAsync(timeout.Token); | |
| 273 | 新增: if (child.ExitCode != 0) throw new IOException("clipboard_cache_failed"); | |
| 274 | 新增: return result; | |
| 275 | 新增: } | |
| 276 | 新增: async void CollectCopies() | |
| 277 | 新增: { | |
| 278 | 新增: if (collectingCopies || IsDisposed) return; | |
| 279 | 新增: collectingCopies = true; | |
| 280 | 新增: try | |
| 281 | 新增: { | |
| 282 | 新增: if (!copiesLoaded) | |
| 283 | 新增: { | |
| 284 | 新增: copiesLoaded = true; | |
| 285 | 新增: var previous = await Cache("list"); | |
| 286 | 新增: foreach (var item in previous["selections"]!.AsArray()) | |
| 287 | 新增: { | |
| 288 | 新增: var id = item!["cache_id"]!.GetValue<string>(); | |
| 289 | 新增: copies.TryAdd(id, new CachedCopy(id, Protocol.Paths(item["paths"]), false)); | |
| 290 | 新增: } | |
| 291 | 新增: } | |
| 292 | 新增: foreach (var copy in copies.Values.ToArray()) | |
| 293 | 新增: { | |
| 294 | 新增: var selected = Clipboard.ContainsFileDropList() ? Clipboard.GetFileDropList().Cast<string>().ToArray() : []; | |
| 295 | 新增: if (copy.Pinned || References(selected, copy.Paths) || fileReaders.Values.Any(paths => References(paths, copy.Paths))) continue; | |
| 296 | 新增: try | |
| 297 | 新增: { | |
| 298 | 新增: await Cache("release", copy.ID); | |
| 299 | 新增: copies.Remove(copy.ID); | |
| 300 | 新增: foreach (var path in copy.Paths) approved.Remove(path); | |
| 301 | 新增: } | |
| 302 | 新增: catch { /* Keep its creation receipt for an ownership-change retry. */ } | |
| 303 | 新增: } | |
| 304 | 新增: } | |
| 305 | 新增: catch { /* An unreadable clipboard retains its currently referenced files. */ } | |
| 306 | 新增: finally { collectingCopies = false; } | |
| 307 | 新增: } | |
| 308 | 新增: void Approve(string[] paths) | |
| 309 | 新增: { | |
| 310 | 新增: selections.Enqueue(paths); | |
| 311 | 新增: foreach (var path in paths) approved.Add(Path.GetFullPath(path)); | |
| 312 | 新增: while (selections.Count > 100) | |
| 313 | 新增: { | |
| 314 | 新增: var old = selections.Dequeue(); | |
| 315 | 新增: foreach (var path in old) if (!selections.Any(s => s.Contains(path, StringComparer.OrdinalIgnoreCase))) approved.Remove(Path.GetFullPath(path)); | |
| 316 | 新增: } | |
| 317 | 新增: } | |
| 318 | 新增: void AssertApproved(string[] paths) | |
| 319 | 新增: { | |
| 320 | 新增: if (paths.Any(path => !approved.Contains(Path.GetFullPath(path)))) throw new InvalidDataException("selection_not_authorized"); | |
| 321 | 新增: } | |
| 322 | 新增: Process StartHelper(string operation) | |
| 323 | 新增: { | |
| 324 | 新增: SessionGuard.Assert(); | |
| 325 | 新增: var start = new ProcessStartInfo(helper) { UseShellExecute = false, CreateNoWindow = true, RedirectStandardInput = true, RedirectStandardOutput = true, RedirectStandardError = true }; | |
| 326 | 新增: start.ArgumentList.Add(operation); if (operation != "import") start.ArgumentList.Add("--paths-stdin"); | |
| 327 | 新增: var process = Process.Start(start) ?? throw new IOException("file_helper_unavailable"); | |
| 328 | 新增: _ = process.StandardError.BaseStream.CopyToAsync(Stream.Null); return process; | |
| 329 | 新增: } | |
| 330 | 新增: internal async Task<string[]> FilePaths(string operation, string[]? paths, CancellationToken token) | |
| 331 | 新增: { | |
| 332 | 新增: var reader = Guid.NewGuid(); | |
| 333 | 新增: if (paths != null) await GUI(() => { fileReaders[reader] = paths; return true; }); | |
| 334 | 新增: string[]? created = null; | |
| 335 | 新增: try | |
| 336 | 新增: { | |
| 337 | 新增: using var child = StartHelper(operation); | |
| 338 | 新增: using var cancellation = token.Register(() => { try { child.Kill(true); } catch { } }); | |
| 339 | 新增: if (paths != null) await JsonSerializer.SerializeAsync(child.StandardInput.BaseStream, paths, cancellationToken: token); | |
| 340 | 新增: child.StandardInput.Close(); | |
| 341 | 新增: var result = await Protocol.Read(child.StandardOutput.BaseStream, Protocol.PathLimit, token) ?? throw new IOException("file_helper_failed"); | |
| 342 | 新增: created = Protocol.Paths(result["paths"]); | |
| 343 | 新增: await GUI(() => { RememberCopy(result); return true; }); | |
| 344 | 新增: await child.WaitForExitAsync(token); | |
| 345 | 新增: if (child.ExitCode != 0) throw new IOException("file_helper_failed"); | |
| 346 | 新增: return created; | |
| 347 | 新增: } | |
| 348 | 新增: catch | |
| 349 | 新增: { | |
| 350 | 新增: if (created != null) await GUI(() => { RetireCopies(created); return true; }); | |
| 351 | 新增: throw; | |
| 352 | 新增: } | |
| 353 | 新增: finally { await GUI(() => { fileReaders.Remove(reader); CollectCopies(); return true; }); } | |
| 354 | 新增: } | |
| 355 | 新增: internal async Task Import(Stream stream, CancellationToken token) | |
| 356 | 新增: { | |
| 357 | 新增: using var child = StartHelper("import"); | |
| 358 | 新增: 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 | 新增: try | |
| 364 | 新增: { | |
| 365 | 新增: await child.WaitForExitAsync(token); | |
| 366 | 新增: if (child.ExitCode != 0) throw new IOException("file_helper_failed"); | |
| 367 | 新增: await GUI(() => { SessionGuard.Assert(); Approve(paths); return true; }); | |
| 368 | 新增: await Protocol.Write(stream, new() { ["paths"] = JsonSerializer.SerializeToNode(paths) }, token); | |
| 369 | 新增: } catch { await GUI(() => { RetireCopies(paths); return true; }); throw; } | |
| 370 | 新增: } | |
| 371 | 新增: internal async Task Export(Stream stream, JsonNode? selection, CancellationToken token) | |
| 372 | 新增: { | |
| 373 | 新增: var paths = Protocol.Paths(selection); | |
| 374 | 新增: var reader = Guid.NewGuid(); | |
| 375 | 新增: await GUI(() => { SessionGuard.Assert(); AssertApproved(paths); fileReaders[reader] = paths; return true; }); | |
| 376 | 新增: try | |
| 377 | 新增: { | |
| 378 | 新增: using var child = StartHelper("export"); | |
| 379 | 新增: using var cancellation = token.Register(() => { try { child.Kill(true); } catch { } }); | |
| 380 | 新增: await JsonSerializer.SerializeAsync(child.StandardInput.BaseStream, paths, cancellationToken: token); child.StandardInput.Close(); | |
| 381 | 新增: await Protocol.SendFrames(child.StandardOutput.BaseStream, stream, token); | |
| 382 | 新增: await child.WaitForExitAsync(token); SessionGuard.Assert(); | |
| 383 | 新增: await Protocol.Write(stream, new() { ["complete"] = child.ExitCode == 0 }, token); | |
| 384 | 新增: } | |
| 385 | 新增: finally { await GUI(() => { fileReaders.Remove(reader); CollectCopies(); return true; }); } | |
| 386 | 新增: } | |
| 387 | 新增:} | |
| @@ -0,0 +1 @@ | ||
| 1 | 新增:global using System.IO; | |
| @@ -0,0 +1,121 @@ | ||
| 1 | 新增:using System.Security.AccessControl; | |
| 2 | 新增:using System.Runtime.CompilerServices; | |
| 3 | 新增:using System.Security.Principal; | |
| 4 | 新增:using System.Text.Json; | |
| 5 | 新增:using System.Text.RegularExpressions; | |
| 6 | 新增: | |
| 7 | 新增:namespace Cage.GuestClipboard; | |
| 8 | 新增: | |
| 9 | 新增:internal static class GuestDiagnostics | |
| 10 | 新增:{ | |
| 11 | 新增: private const long FileBytes = 1 << 20; | |
| 12 | 新增: private static readonly object Sync = new(); | |
| 13 | 新增: private static readonly Regex Code = new("^[a-zA-Z][a-zA-Z0-9_]{0,95}$", RegexOptions.CultureInvariant); | |
| 14 | 新增: private static string last = ""; | |
| 15 | 新增: private static DateTime lastAt; | |
| 16 | 新增: | |
| 17 | 新增: private static IEnumerable<string> Files(string directory) => Enumerable.Range(0, 10) | |
| 18 | 新增: .Select(index => Path.Combine(directory, index == 0 ? "events.jsonl" : $"events-{index}.jsonl")) | |
| 19 | 新增: .Where(File.Exists); | |
| 20 | 新增: | |
| 21 | 新增: [ModuleInitializer] | |
| 22 | 新增: internal static void Register() => GuestOperations.Register("diagnostics", Read); | |
| 23 | 新增: | |
| 24 | 新增: private static string DirectoryPath() | |
| 25 | 新增: { | |
| 26 | 新增: var directory = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "Cage", "Diagnostics"); | |
| 27 | 新增: foreach (var current in new[] { Path.GetDirectoryName(directory)!, directory }) | |
| 28 | 新增: { | |
| 29 | 新增: Directory.CreateDirectory(current); | |
| 30 | 新增: if (new DirectoryInfo(current).Attributes.HasFlag(FileAttributes.ReparsePoint)) throw new IOException("diagnostic_path_invalid"); | |
| 31 | 新增: } | |
| 32 | 新增: using var identity = WindowsIdentity.GetCurrent(); | |
| 33 | 新增: var acl = new DirectorySecurity(); | |
| 34 | 新增: acl.SetAccessRuleProtection(true, false); | |
| 35 | 新增: foreach (var sid in new[] { identity.User!, new SecurityIdentifier(WellKnownSidType.LocalSystemSid, null) }) | |
| 36 | 新增: acl.AddAccessRule(new FileSystemAccessRule(sid, FileSystemRights.FullControl, | |
| 37 | 新增: InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit, PropagationFlags.None, AccessControlType.Allow)); | |
| 38 | 新增: new DirectoryInfo(directory).SetAccessControl(acl); | |
| 39 | 新增: return directory; | |
| 40 | 新增: } | |
| 41 | 新增: | |
| 42 | 新增: private static void Clean(string directory) | |
| 43 | 新增: { | |
| 44 | 新增: foreach (var file in Files(directory)) | |
| 45 | 新增: { | |
| 46 | 新增: var info = new FileInfo(file); | |
| 47 | 新增: if (info.Attributes.HasFlag(FileAttributes.ReparsePoint)) throw new IOException("diagnostic_path_invalid"); | |
| 48 | 新增: if (info.LastWriteTimeUtc < DateTime.UtcNow.AddDays(-14)) File.Delete(file); | |
| 49 | 新增: } | |
| 50 | 新增: } | |
| 51 | 新增: | |
| 52 | 新增: internal static void Record(string source, string reason) | |
| 53 | 新增: { | |
| 54 | 新增: if (!Code.IsMatch(source) || !Code.IsMatch(reason)) return; | |
| 55 | 新增: try | |
| 56 | 新增: { | |
| 57 | 新增: lock (Sync) | |
| 58 | 新增: { | |
| 59 | 新增: var now = DateTime.UtcNow; | |
| 60 | 新增: var key = source + "/" + reason; | |
| 61 | 新增: if (key == last && now - lastAt < TimeSpan.FromSeconds(5)) return; | |
| 62 | 新增: var directory = DirectoryPath(); | |
| 63 | 新增: Clean(directory); | |
| 64 | 新增: var file = Path.Combine(directory, "events.jsonl"); | |
| 65 | 新增: var entry = JsonSerializer.Serialize(new { time = now, source, reason }) + "\n"; | |
| 66 | 新增: if (File.Exists(file) && (new FileInfo(file).Length + Protocol.Utf8.GetByteCount(entry) > FileBytes || File.GetCreationTimeUtc(file).Date != now.Date)) | |
| 67 | 新增: { | |
| 68 | 新增: for (var index = 9; index >= 1; index--) | |
| 69 | 新增: { | |
| 70 | 新增: var old = Path.Combine(directory, index == 1 ? "events.jsonl" : $"events-{index - 1}.jsonl"); | |
| 71 | 新增: var target = Path.Combine(directory, $"events-{index}.jsonl"); | |
| 72 | 新增: if (File.Exists(old)) File.Move(old, target, true); | |
| 73 | 新增: } | |
| 74 | 新增: } | |
| 75 | 新增: File.AppendAllText(file, entry, Protocol.Utf8); | |
| 76 | 新增: last = key; | |
| 77 | 新增: lastAt = now; | |
| 78 | 新增: } | |
| 79 | 新增: } | |
| 80 | 新增: catch { /* Diagnostic storage failure must preserve the original operation. */ } | |
| 81 | 新增: } | |
| 82 | 新增: | |
| 83 | 新增: internal static void Failure(string source, Exception error) => Record(source, error.GetType().Name); | |
| 84 | 新增: | |
| 85 | 新增: private static async Task Read(Stream stream, CancellationToken token, Func<bool> available) | |
| 86 | 新增: { | |
| 87 | 新增: var request = await Protocol.Read(stream, 1024, token); | |
| 88 | 新增: if (request?["action"]?.GetValue<string>() != "read") throw new InvalidDataException("diagnostic_request_invalid"); | |
| 89 | 新增: var lines = new Queue<string>(); | |
| 90 | 新增: var bytes = 0; | |
| 91 | 新增: lock (Sync) | |
| 92 | 新增: { | |
| 93 | 新增: var directory = DirectoryPath(); | |
| 94 | 新增: Clean(directory); | |
| 95 | 新增: // Rotation numbers preserve the write order even when file timestamps tie. | |
| 96 | 新增: foreach (var file in Files(directory).Reverse()) | |
| 97 | 新增: { | |
| 98 | 新增: if (new FileInfo(file).Length > FileBytes + 4096) continue; | |
| 99 | 新增: foreach (var line in File.ReadLines(file, Protocol.Utf8)) | |
| 100 | 新增: { | |
| 101 | 新增: if (line.Length > 4096) continue; | |
| 102 | 新增: try | |
| 103 | 新增: { | |
| 104 | 新增: using var item = JsonDocument.Parse(line); | |
| 105 | 新增: var value = item.RootElement; | |
| 106 | 新增: var source = value.GetProperty("source").GetString() ?? ""; | |
| 107 | 新增: var reason = value.GetProperty("reason").GetString() ?? ""; | |
| 108 | 新增: var time = value.GetProperty("time").GetDateTime(); | |
| 109 | 新增: if (!Code.IsMatch(source) || !Code.IsMatch(reason) || time < DateTime.UtcNow.AddDays(-14)) continue; | |
| 110 | 新增: var safe = JsonSerializer.Serialize(new { time, source, reason }) + "\n"; | |
| 111 | 新增: lines.Enqueue(safe); | |
| 112 | 新增: bytes += Protocol.Utf8.GetByteCount(safe); | |
| 113 | 新增: while (lines.Count > 150 || bytes > 48 << 10) bytes -= Protocol.Utf8.GetByteCount(lines.Dequeue()); | |
| 114 | 新增: } | |
| 115 | 新增: catch (Exception error) when (error is JsonException or InvalidOperationException or KeyNotFoundException or FormatException) { } | |
| 116 | 新增: } | |
| 117 | 新增: } | |
| 118 | 新增: } | |
| 119 | 新增: await Protocol.Write(stream, new() { ["version"] = 1, ["lines"] = string.Concat(lines) }, token); | |
| 120 | 新增: } | |
| 121 | 新增:} | |
| @@ -0,0 +1,31 @@ | ||
| 1 | 新增:using System.ComponentModel; | |
| 2 | 新增:using System.Diagnostics; | |
| 3 | 新增:using System.Runtime.InteropServices; | |
| 4 | 新增: | |
| 5 | 新增:namespace Cage.GuestClipboard; | |
| 6 | 新增: | |
| 7 | 新增:// Attach before the controller sends its first request. Chrome and editor | |
| 8 | 新增:// children then inherit this non-inheritable, kill-on-owner-exit job. | |
| 9 | 新增:internal sealed class GuestProcessJob : IDisposable | |
| 10 | 新增:{ | |
| 11 | 新增: private IntPtr handle; | |
| 12 | 新增: internal GuestProcessJob(Process process) | |
| 13 | 新增: { | |
| 14 | 新增: handle=CreateJobObject(IntPtr.Zero,null); | |
| 15 | 新增: if(handle==IntPtr.Zero)throw new Win32Exception(); | |
| 16 | 新增: try | |
| 17 | 新增: { | |
| 18 | 新增: var limits=new Limits();limits.Basic.Flags=0x2000; | |
| 19 | 新增: if(!SetInformationJobObject(handle,9,ref limits,(uint)Marshal.SizeOf<Limits>())||!AssignProcessToJobObject(handle,process.Handle))throw new Win32Exception(); | |
| 20 | 新增: } | |
| 21 | 新增: catch{Dispose();throw;} | |
| 22 | 新增: } | |
| 23 | 新增: public void Dispose(){var job=Interlocked.Exchange(ref handle,IntPtr.Zero);if(job!=IntPtr.Zero)CloseHandle(job);} | |
| 24 | 新增: [StructLayout(LayoutKind.Sequential)]private struct Basic{internal long ProcessTime,JobTime;internal uint Flags;internal nuint MinWorking,MaxWorking;internal uint Active;internal nuint Affinity;internal uint Priority,Scheduling;} | |
| 25 | 新增: [StructLayout(LayoutKind.Sequential)]private struct IO{internal ulong ReadOperations,WriteOperations,OtherOperations,ReadBytes,WriteBytes,OtherBytes;} | |
| 26 | 新增: [StructLayout(LayoutKind.Sequential)]private struct Limits{internal Basic Basic;internal IO IO;internal nuint ProcessMemory,JobMemory,PeakProcessMemory,PeakJobMemory;} | |
| 27 | 新增: [DllImport("kernel32.dll",CharSet=CharSet.Unicode,EntryPoint="CreateJobObjectW",SetLastError=true)]private static extern IntPtr CreateJobObject(IntPtr attributes,string? name); | |
| 28 | 新增: [DllImport("kernel32.dll",SetLastError=true)]private static extern bool SetInformationJobObject(IntPtr job,int type,ref Limits limits,uint size); | |
| 29 | 新增: [DllImport("kernel32.dll",SetLastError=true)]private static extern bool AssignProcessToJobObject(IntPtr job,IntPtr process); | |
| 30 | 新增: [DllImport("kernel32.dll")]private static extern bool CloseHandle(IntPtr handle); | |
| 31 | 新增:} | |
| @@ -0,0 +1,154 @@ | ||
| 1 | 新增:using System.Diagnostics; | |
| 2 | 新增:using System.Runtime.CompilerServices; | |
| 3 | 新增:using System.Security.AccessControl; | |
| 4 | 新增:using System.Security.Cryptography; | |
| 5 | 新增:using System.Security.Principal; | |
| 6 | 新增:using System.Text.Json.Nodes; | |
| 7 | 新增: | |
| 8 | 新增:namespace Cage.GuestClipboard; | |
| 9 | 新增: | |
| 10 | 新增:internal static class GuestVersions | |
| 11 | 新增:{ | |
| 12 | 新增: [ModuleInitializer] | |
| 13 | 新增: internal static void Register() => GuestOperations.Register("versions", Read); | |
| 14 | 新增: | |
| 15 | 新增: private static async Task Read(Stream stream, CancellationToken token, Func<bool> available) | |
| 16 | 新增: { | |
| 17 | 新增: var result = Snapshot(); | |
| 18 | 新增: var tools = new JsonObject(); | |
| 19 | 新增: tools["node"] = await Version(Path.Combine(AppContext.BaseDirectory, "node.exe"), token); | |
| 20 | 新增: tools["code_server"] = await Version(Path.Combine(AppContext.BaseDirectory, "vscode-cli", "code.exe"), token); | |
| 21 | 新增: var chrome = new[] { | |
| 22 | 新增: Path.Combine(AppContext.BaseDirectory, "chrome", "chrome.exe"), | |
| 23 | 新增: Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles), "Google", "Chrome", "Application", "chrome.exe"), | |
| 24 | 新增: Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86), "Microsoft", "Edge", "Application", "msedge.exe") | |
| 25 | 新增: }.FirstOrDefault(File.Exists); | |
| 26 | 新增: tools["chromium"] = chrome is null ? "" : FileVersionInfo.GetVersionInfo(chrome).ProductVersion ?? ""; | |
| 27 | 新增: try | |
| 28 | 新增: { | |
| 29 | 新增: var receipt = Path.Combine(AppContext.BaseDirectory, "cli-tools.json"); | |
| 30 | 新增: Pairing.PrivateFile(receipt); | |
| 31 | 新增: var cli = JsonNode.Parse(File.ReadAllBytes(receipt)) as JsonObject; | |
| 32 | 新增: foreach (var name in new[] { "python", "claude", "git_bash" }) | |
| 33 | 新增: { | |
| 34 | 新增: var filename = cli?[name]?.GetValue<string>(); | |
| 35 | 新增: var expected = cli?[name + "_sha256"]?.GetValue<string>(); | |
| 36 | 新增: if (filename is null || expected is null || !Path.IsPathRooted(filename)) continue; | |
| 37 | 新增: using (var file = File.OpenRead(filename)) | |
| 38 | 新增: if (!Convert.ToHexString(SHA256.HashData(file)).Equals(expected, StringComparison.OrdinalIgnoreCase)) continue; | |
| 39 | 新增: if (name == "git_bash") | |
| 40 | 新增: tools["git"] = await Version(Path.Combine(Path.GetDirectoryName(Path.GetDirectoryName(filename))!, "cmd", "git.exe"), token); | |
| 41 | 新增: else tools[name] = await Version(filename, token); | |
| 42 | 新增: } | |
| 43 | 新增: } | |
| 44 | 新增: catch (IOException) { } | |
| 45 | 新增: catch (UnauthorizedAccessException) { } | |
| 46 | 新增: catch (System.Text.Json.JsonException) { } | |
| 47 | 新增: result["tools"] = tools; | |
| 48 | 新增: await Protocol.Write(stream, result, token); | |
| 49 | 新增: } | |
| 50 | 新增: | |
| 51 | 新增: internal static JsonObject Snapshot() | |
| 52 | 新增: { | |
| 53 | 新增: var result = new JsonObject { ["manifest"] = null, ["installed"] = false, ["missing"] = new JsonArray() }; | |
| 54 | 新增: try | |
| 55 | 新增: { | |
| 56 | 新增: var path = Path.Combine(AppContext.BaseDirectory, "native-components.json"); | |
| 57 | 新增: CheckReceipt(path); | |
| 58 | 新增: var manifest = JsonNode.Parse(File.ReadAllText(path)) as JsonObject; | |
| 59 | 新增: if (manifest?["protocol"]?.GetValue<int>() != 1 || manifest["system"]?.GetValue<string>() != "windows-11" || manifest["files"] is not JsonArray files || files.Count > 10000) | |
| 60 | 新增: throw new InvalidDataException("component_manifest_invalid"); | |
| 61 | 新增: var missing = new JsonArray(); | |
| 62 | 新增: foreach (var entry in files.OfType<JsonObject>()) | |
| 63 | 新增: { | |
| 64 | 新增: var target = entry["target"]?.GetValue<string>() ?? ""; | |
| 65 | 新增: if (target.Length == 0) continue; | |
| 66 | 新增: var filename = Target(target); | |
| 67 | 新增: try | |
| 68 | 新增: { | |
| 69 | 新增: using var file = File.OpenRead(filename); | |
| 70 | 新增: var hash = Convert.ToHexString(SHA256.HashData(file)); | |
| 71 | 新增: if (!hash.Equals(entry["installed_sha256"]?.GetValue<string>(), StringComparison.OrdinalIgnoreCase) && missing.Count < 20) missing.Add(target); | |
| 72 | 新增: } | |
| 73 | 新增: catch (IOException) { if (missing.Count < 20) missing.Add(target); } | |
| 74 | 新增: } | |
| 75 | 新增: result["manifest"] = new JsonObject { | |
| 76 | 新增: ["protocol"] = 1, ["revision"] = missing.Count == 0 ? manifest["revision"]?.DeepClone() : "", | |
| 77 | 新增: ["app_version"] = manifest["app_version"]?.DeepClone() | |
| 78 | 新增: }; | |
| 79 | 新增: result["installed"] = missing.Count == 0; | |
| 80 | 新增: result["missing"] = missing; | |
| 81 | 新增: } | |
| 82 | 新增: catch (Exception error) when (error is IOException or UnauthorizedAccessException or System.Text.Json.JsonException or InvalidOperationException) | |
| 83 | 新增: { | |
| 84 | 新增: result["error"] = "客机尚无可核验的组件记录,请同步环境组件。"; | |
| 85 | 新增: } | |
| 86 | 新增: return result; | |
| 87 | 新增: } | |
| 88 | 新增: | |
| 89 | 新增: private static void CheckReceipt(string path) | |
| 90 | 新增: { | |
| 91 | 新增: var file = new FileInfo(path); | |
| 92 | 新增: if (!file.Exists || file.Length is < 1 or > 4 << 20 || file.Attributes.HasFlag(FileAttributes.ReparsePoint)) | |
| 93 | 新增: throw new InvalidDataException("component_manifest_invalid"); | |
| 94 | 新增: for (var parent = file.Directory; parent is not null; parent = parent.Parent) | |
| 95 | 新增: if (parent.Attributes.HasFlag(FileAttributes.ReparsePoint)) throw new InvalidDataException("component_manifest_invalid"); | |
| 96 | 新增: var acl = file.GetAccessControl(); | |
| 97 | 新增: var administrators = new HashSet<string> { "S-1-5-18", "S-1-5-32-544" }; | |
| 98 | 新增: var owner = acl.GetOwner(typeof(SecurityIdentifier))?.Value; | |
| 99 | 新增: if (!acl.AreAccessRulesProtected || owner is null || !administrators.Contains(owner)) | |
| 100 | 新增: throw new InvalidDataException("component_permissions_invalid"); | |
| 101 | 新增: var read = FileSystemRights.ReadAndExecute | FileSystemRights.Synchronize; | |
| 102 | 新增: foreach (FileSystemAccessRule rule in acl.GetAccessRules(true, true, typeof(SecurityIdentifier))) | |
| 103 | 新增: { | |
| 104 | 新增: if (rule.AccessControlType != AccessControlType.Allow || administrators.Contains(rule.IdentityReference.Value)) continue; | |
| 105 | 新增: if (rule.IdentityReference.Value != GuestContext.SID || (rule.FileSystemRights & ~read) != 0) | |
| 106 | 新增: throw new InvalidDataException("component_permissions_invalid"); | |
| 107 | 新增: } | |
| 108 | 新增: } | |
| 109 | 新增: | |
| 110 | 新增: private static string Target(string target) | |
| 111 | 新增: { | |
| 112 | 新增: var parts = target.Split('/'); | |
| 113 | 新增: if (parts.Length < 2 || parts.Any(part => part.Length == 0 || part is "." or ".." || part.Contains('\\') || part.Contains(':'))) | |
| 114 | 新增: throw new InvalidDataException("component_target_invalid"); | |
| 115 | 新增: var root = parts[0] switch { | |
| 116 | 新增: "bridge" => AppContext.BaseDirectory, | |
| 117 | 新增: "network" => Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles), "Cage Guest Network", GuestContext.VM.ToString("D")), | |
| 118 | 新增: _ => throw new InvalidDataException("component_target_invalid") | |
| 119 | 新增: }; | |
| 120 | 新增: return Path.Combine([root, .. parts.Skip(1)]); | |
| 121 | 新增: } | |
| 122 | 新增: | |
| 123 | 新增: private static async Task<string> Version(string executable, CancellationToken parent) | |
| 124 | 新增: { | |
| 125 | 新增: if (!File.Exists(executable)) return ""; | |
| 126 | 新增: using var timeout = CancellationTokenSource.CreateLinkedTokenSource(parent); | |
| 127 | 新增: timeout.CancelAfter(TimeSpan.FromSeconds(3)); | |
| 128 | 新增: var start = new ProcessStartInfo(executable) { UseShellExecute = false, CreateNoWindow = true, RedirectStandardInput = true, RedirectStandardOutput = true, RedirectStandardError = true }; | |
| 129 | 新增: start.ArgumentList.Add("--version"); | |
| 130 | 新增: start.Environment["DISABLE_AUTOUPDATER"] = "1"; | |
| 131 | 新增: Process? launched; | |
| 132 | 新增: try { launched = Process.Start(start); } | |
| 133 | 新增: catch (Exception error) when (error is System.ComponentModel.Win32Exception or IOException) { return ""; } | |
| 134 | 新增: using var process = launched; | |
| 135 | 新增: if (process is null) return ""; | |
| 136 | 新增: process.StandardInput.Close(); | |
| 137 | 新增: using var cancel = timeout.Token.Register(() => { | |
| 138 | 新增: try { process.Kill(true); } | |
| 139 | 新增: catch (Exception error) when (error is InvalidOperationException or System.ComponentModel.Win32Exception) { } | |
| 140 | 新增: }); | |
| 141 | 新增: try | |
| 142 | 新增: { | |
| 143 | 新增: var errors = process.StandardError.BaseStream.CopyToAsync(Stream.Null, timeout.Token); | |
| 144 | 新增: var output = new char[512]; | |
| 145 | 新增: var count = await process.StandardOutput.ReadAsync(output, timeout.Token); | |
| 146 | 新增: await process.StandardOutput.BaseStream.CopyToAsync(Stream.Null, timeout.Token); | |
| 147 | 新增: await process.WaitForExitAsync(timeout.Token); | |
| 148 | 新增: await errors; | |
| 149 | 新增: var line = new string(output, 0, count).Split('\n')[0].Trim(); | |
| 150 | 新增: return process.ExitCode == 0 ? line[..Math.Min(line.Length, 200)] : ""; | |
| 151 | 新增: } | |
| 152 | 新增: catch (OperationCanceledException) { return ""; } | |
| 153 | 新增: } | |
| 154 | 新增:} | |
| @@ -0,0 +1,9 @@ | ||
| 1 | 新增:namespace Cage.GuestClipboard; | |
| 2 | 新增: | |
| 3 | 新增:// The caller pins one owned HWND/PID and supplies its lifetime validation. | |
| 4 | 新增:// The shared worker provides only WGC CreateForWindow, never monitor capture. | |
| 5 | 新增:internal static class GuestWindowCapture | |
| 6 | 新增:{ | |
| 7 | 新增: internal static Task<byte[]> Capture(IntPtr window, int pid, int width, int height, Action validate, bool allowSolid = false, bool preserveAlpha = false) | |
| 8 | 新增: => ClaudeGraphicsCapture.Capture(window, pid, width, height, validate, allowSolid, preserveAlpha); | |
| 9 | 新增:} | |
| @@ -0,0 +1,112 @@ | ||
| 1 | 新增:using System.Runtime.InteropServices; | |
| 2 | 新增: | |
| 3 | 新增:namespace Cage.GuestClipboard; | |
| 4 | 新增: | |
| 5 | 新增:internal readonly record struct InputStroke(ushort Value, bool Up, bool Unicode = false, int MouseButton = 0, int WheelDelta = 0, bool Horizontal = false) | |
| 6 | 新增:{ | |
| 7 | 新增: internal static InputStroke Key(ushort value, bool up, bool unicode = false) => new(value, up, unicode); | |
| 8 | 新增: internal static InputStroke Button(int bit, bool up) => new(0, up, false, bit); | |
| 9 | 新增: internal static InputStroke Wheel(int delta, bool horizontal = false) => new(0, false, false, 0, delta, horizontal); | |
| 10 | 新增: internal InputStroke Press => this with { Up = false }; | |
| 11 | 新增:} | |
| 12 | 新增: | |
| 13 | 新增:// One coordinator covers the GUI process's kernel input state. A lease never | |
| 14 | 新增:// appears on the wire. Callbacks contain immutable, server-verified ownership; | |
| 15 | 新增:// release callbacks must not acquire an RPC lock or focus a window. | |
| 16 | 新增:internal sealed class NativeInputCoordinator(Func<InputStroke, bool> inject) | |
| 17 | 新增:{ | |
| 18 | 新增: internal sealed class Lease | |
| 19 | 新增: { | |
| 20 | 新增: internal readonly Dictionary<InputStroke, Func<bool>> Pressed = []; | |
| 21 | 新增: internal readonly Dictionary<uint, InputStroke[]> Symbols = []; | |
| 22 | 新增: internal readonly HashSet<InputStroke> Releasing = []; | |
| 23 | 新增: internal bool Closed, Resetting; | |
| 24 | 新增: } | |
| 25 | 新增: private readonly object sync = new(); | |
| 26 | 新增: private readonly HashSet<Lease> leases = []; | |
| 27 | 新增: private readonly Dictionary<InputStroke, HashSet<Lease>> owners = []; | |
| 28 | 新增: internal Lease Open() { lock(sync) { var lease = new Lease(); leases.Add(lease); return lease; } } | |
| 29 | 新增: internal bool KeyHeld(ushort key) { lock(sync) return owners.ContainsKey(InputStroke.Key(key, false)); } | |
| 30 | 新增: internal int Buttons(Lease lease) { lock(sync) return lease.Pressed.Keys.Aggregate(0, (mask, key) => mask | key.MouseButton); } | |
| 31 | 新增: internal bool Owns(Lease lease, InputStroke stroke) { lock(sync) return lease.Pressed.ContainsKey(stroke.Press); } | |
| 32 | 新增: internal void Emit(Lease lease, InputStroke[] strokes, Action validate, Func<bool> releaseAllowed) | |
| 33 | 新增: { | |
| 34 | 新增: lock(sync) | |
| 35 | 新增: { | |
| 36 | 新增: if(!leases.Contains(lease) || lease.Closed || lease.Resetting) throw new InvalidDataException("native_input_lease_closed"); | |
| 37 | 新增: validate(); | |
| 38 | 新增: foreach(var stroke in strokes) | |
| 39 | 新增: { | |
| 40 | 新增: var key = stroke.Press; | |
| 41 | 新增: if(stroke.WheelDelta == 0 && stroke.Up) | |
| 42 | 新增: { | |
| 43 | 新增: // A viewer cannot release another viewer's input. When both | |
| 44 | 新增: // pressed the same key, the last owner sends the physical up. | |
| 45 | 新增: if(!lease.Pressed.ContainsKey(key)) continue; | |
| 46 | 新增: if(owners[key].Count > 1) { Forget(lease, key); continue; } | |
| 47 | 新增: } | |
| 48 | 新增: if(!inject(stroke)) throw new InvalidDataException("native_input_failed"); | |
| 49 | 新增: if(stroke.WheelDelta != 0) continue; | |
| 50 | 新增: if(stroke.Up) Forget(lease, key); | |
| 51 | 新增: else | |
| 52 | 新增: { | |
| 53 | 新增: if(!owners.TryGetValue(key, out var set)) owners[key] = set = []; | |
| 54 | 新增: set.Add(lease); lease.Pressed[key] = releaseAllowed; lease.Releasing.Remove(key); | |
| 55 | 新增: } | |
| 56 | 新增: } | |
| 57 | 新增: validate(); | |
| 58 | 新增: } | |
| 59 | 新增: } | |
| 60 | 新增: internal void Close(Lease lease) { lock(sync) { lease.Closed = true; Release(lease); } } | |
| 61 | 新增: internal void Reset(Lease lease) { lock(sync) { lease.Resetting = true; Release(lease); } } | |
| 62 | 新增: internal void ReleaseInputs(Lease lease,InputStroke[] strokes){lock(sync){foreach(var stroke in strokes)if(lease.Pressed.ContainsKey(stroke.Press))lease.Releasing.Add(stroke.Press);Release(lease);}} | |
| 63 | 新增: internal void Retry() { lock(sync) foreach(var lease in leases.Where(l => l.Closed || l.Resetting || l.Releasing.Count>0).ToArray()) Release(lease); } | |
| 64 | 新增: internal void CloseAll() { lock(sync) foreach(var lease in leases.ToArray()) { lease.Closed = true; Release(lease); } } | |
| 65 | 新增: private void Release(Lease lease) | |
| 66 | 新增: { | |
| 67 | 新增: foreach(var item in lease.Pressed.Where(item=>lease.Closed||lease.Resetting||lease.Releasing.Contains(item.Key)).ToArray()) | |
| 68 | 新增: { | |
| 69 | 新增: if(owners[item.Key].Count > 1) { Forget(lease, item.Key); continue; } | |
| 70 | 新增: try { if(item.Value() && inject(item.Key with { Up = true })) Forget(lease, item.Key); } | |
| 71 | 新增: catch { /* Keep the successful down until this GUI can release it. */ } | |
| 72 | 新增: } | |
| 73 | 新增: if(lease.Pressed.Count == 0) | |
| 74 | 新增: { | |
| 75 | 新增: lease.Symbols.Clear(); lease.Resetting = false; | |
| 76 | 新增: if(lease.Closed) leases.Remove(lease); | |
| 77 | 新增: } | |
| 78 | 新增: } | |
| 79 | 新增: private void Forget(Lease lease, InputStroke key) | |
| 80 | 新增: { | |
| 81 | 新增: lease.Pressed.Remove(key);lease.Releasing.Remove(key); | |
| 82 | 新增: if(owners.TryGetValue(key, out var set) && set.Remove(lease) && set.Count == 0) owners.Remove(key); | |
| 83 | 新增: } | |
| 84 | 新增:} | |
| 85 | 新增: | |
| 86 | 新增:internal static class NativeGuestInput | |
| 87 | 新增:{ | |
| 88 | 新增: private static readonly NativeInputCoordinator State = new(Inject); | |
| 89 | 新增: private static readonly System.Threading.Timer Retry = new(_ => State.Retry(), null, 250, 250); | |
| 90 | 新增: static NativeGuestInput() => AppDomain.CurrentDomain.ProcessExit += (_, _) => { Retry.Dispose(); State.CloseAll(); }; | |
| 91 | 新增: internal static NativeInputCoordinator.Lease OpenLease() => State.Open(); | |
| 92 | 新增: internal static void CloseLease(NativeInputCoordinator.Lease lease) => State.Close(lease); | |
| 93 | 新增: internal static void ResetLease(NativeInputCoordinator.Lease lease) => State.Reset(lease); | |
| 94 | 新增: internal static void ReleaseInputs(NativeInputCoordinator.Lease lease,InputStroke[] strokes)=>State.ReleaseInputs(lease,strokes); | |
| 95 | 新增: internal static bool PressedKey(ushort key) => State.KeyHeld(key); | |
| 96 | 新增: internal static int PressedButtons(NativeInputCoordinator.Lease lease) => State.Buttons(lease); | |
| 97 | 新增: internal static bool Owns(NativeInputCoordinator.Lease lease, InputStroke stroke) => State.Owns(lease, stroke); | |
| 98 | 新增: internal static void Emit(NativeInputCoordinator.Lease lease, InputStroke[] strokes, Action validateBeforeAfter, Func<bool> releaseAllowed) => State.Emit(lease, strokes, validateBeforeAfter, releaseAllowed); | |
| 99 | 新增: private static bool Inject(InputStroke stroke) | |
| 100 | 新增: { | |
| 101 | 新增: var input = new Input(); | |
| 102 | 新增: if(stroke.WheelDelta != 0) input.Data.Mouse = new Mouse { Flags = stroke.Horizontal ? 0x1000u : 0x800u, Data = unchecked((uint)stroke.WheelDelta) }; | |
| 103 | 新增: else if(stroke.MouseButton != 0) input.Data.Mouse = new Mouse { Flags = (stroke.MouseButton, stroke.Up) switch { (1,false) => 2u, (1,true) => 4u, (2,false) => 32u, (2,true) => 64u, (4,false) => 8u, (4,true) => 16u, _ => throw new InvalidDataException("native_input_invalid") } }; | |
| 104 | 新增: else { input.Type = 1; input.Data.Key = new Key { Virtual = stroke.Unicode ? (ushort)0 : stroke.Value, Scan = stroke.Unicode ? stroke.Value : (ushort)0, Flags = (stroke.Unicode ? 4u : 0) | (stroke.Up ? 2u : 0) }; } | |
| 105 | 新增: return SendInput(1, [input], Marshal.SizeOf<Input>()) == 1; | |
| 106 | 新增: } | |
| 107 | 新增: [StructLayout(LayoutKind.Sequential)] private struct Mouse { internal int X,Y; internal uint Data,Flags,Time; internal UIntPtr Extra; } | |
| 108 | 新增: [StructLayout(LayoutKind.Sequential)] private struct Key { internal ushort Virtual,Scan; internal uint Flags,Time; internal UIntPtr Extra; } | |
| 109 | 新增: [StructLayout(LayoutKind.Explicit)] private struct Data { [FieldOffset(0)] internal Mouse Mouse; [FieldOffset(0)] internal Key Key; } | |
| 110 | 新增: [StructLayout(LayoutKind.Sequential)] private struct Input { internal uint Type; internal Data Data; } | |
| 111 | 新增: [DllImport("user32.dll")] private static extern uint SendInput(uint count, Input[] inputs, int size); | |
| 112 | 新增:} | |
| @@ -0,0 +1,114 @@ | ||
| 1 | 新增:using System.Globalization; | |
| 2 | 新增:using System.Net; | |
| 3 | 新增:using System.Net.Http; | |
| 4 | 新增:using System.Net.NetworkInformation; | |
| 5 | 新增:using System.Net.Sockets; | |
| 6 | 新增:using System.Runtime.CompilerServices; | |
| 7 | 新增:using System.Runtime.InteropServices; | |
| 8 | 新增:using System.Security.Cryptography; | |
| 9 | 新增:using System.Text.Json.Nodes; | |
| 10 | 新增: | |
| 11 | 新增:namespace Cage.GuestClipboard; | |
| 12 | 新增: | |
| 13 | 新增:// Bounded probes use fixed destinations. The host accepts their results only | |
| 14 | 新增:// alongside the current packet gate's own denial and diagnostic counters. | |
| 15 | 新增:internal static class NativeSafetyRpc | |
| 16 | 新增:{ | |
| 17 | 新增: [ModuleInitializer] internal static void Register() => GuestOperations.Register("safety",Run); | |
| 18 | 新增: [DllImport("kernel32.dll",CharSet=CharSet.Unicode)] private static extern int GetSystemDefaultLocaleName(char[] value,int capacity); | |
| 19 | 新增: private sealed class Progress { internal string Stage="request"; } | |
| 20 | 新增: internal static async Task Run(Stream stream,CancellationToken token,Func<bool> available) | |
| 21 | 新增: { | |
| 22 | 新增: var progress=new Progress(); | |
| 23 | 新增: try{await RunCore(stream,token,available,progress);} | |
| 24 | 新增: catch(Exception error) when(error is not OperationCanceledException) | |
| 25 | 新增: { | |
| 26 | 新增: var code=error switch { InvalidDataException=>"invalid_probe",UnauthorizedAccessException=>"access_denied",IOException=>"file_io",SocketException=>"socket",_=>"probe_failed" }; | |
| 27 | 新增: await Protocol.Write(stream,new JsonObject{["error"]="safety_probe_failed",["stage"]=progress.Stage,["error_code"]=code,["hresult"]=unchecked((uint)error.HResult).ToString("x8"),["native_code"]=error is SocketException socket ? socket.NativeErrorCode : 0},token); | |
| 28 | 新增: } | |
| 29 | 新增: } | |
| 30 | 新增: private static async Task RunCore(Stream stream,CancellationToken token,Func<bool> available,Progress progress) | |
| 31 | 新增: { | |
| 32 | 新增: var input=await Protocol.Read(stream,16384,token) ?? throw new EndOfStreamException(); | |
| 33 | 新增: if(!available())throw new InvalidDataException("requires_gui_login"); | |
| 34 | 新增: var stage=input["stage"]?.GetValue<string>(); | |
| 35 | 新增: if(stage is not ("environment" or "boundary" or "network"))throw new InvalidDataException("safety_request_invalid"); | |
| 36 | 新增: progress.Stage="environment";TimeZoneInfo.ClearCachedData(); | |
| 37 | 新增: var timezone=ObservedTimezone(TimeZoneInfo.Local.Id,input["timezone"]?.GetValue<string>()); | |
| 38 | 新增: var system=new char[85];var count=GetSystemDefaultLocaleName(system,system.Length); | |
| 39 | 新增: var result=new JsonObject{["tz"]=timezone,["system_timezone"]=timezone,["process_locale"]=CultureInfo.CurrentCulture.Name,["system_locale"]=count>0 ? new string(system,0,count-1) : "",["locale_valid"]=count>0}; | |
| 40 | 新增: if(stage=="network") | |
| 41 | 新增: { | |
| 42 | 新增: progress.Stage="network"; | |
| 43 | 新增: result["egress"]=await Probe("egress",token);result["dns"]=await Probe("dns",token); | |
| 44 | 新增: } | |
| 45 | 新增: if(stage=="boundary") | |
| 46 | 新增: { | |
| 47 | 新增: var port=input["control_port"]?.GetValue<int>() ?? 0; | |
| 48 | 新增: if(port is <1 or >65535)throw new InvalidDataException("safety_request_invalid"); | |
| 49 | 新增: progress.Stage="public-tcp";result["public_connected"]=await Connect("1.1.1.1",443,AddressFamily.InterNetwork,token); | |
| 50 | 新增: result["management_connected"]=await Connect("192.168.5.2",port,AddressFamily.InterNetwork,token); | |
| 51 | 新增: result["ipv6_connected"]=await Connect("2606:4700:4700::1111",443,AddressFamily.InterNetworkV6,token); | |
| 52 | 新增: result["ipv6_default_routes"]=NetworkInterface.GetAllNetworkInterfaces().Sum(n=>n.GetIPProperties().GatewayAddresses.Count(g=>g.Address.AddressFamily==AddressFamily.InterNetworkV6)); | |
| 53 | 新增: var nonce=Convert.ToHexString(RandomNumberGenerator.GetBytes(8)).ToLowerInvariant(); | |
| 54 | 新增: progress.Stage="udp"; | |
| 55 | 新增: using(var udp=new UdpClient(AddressFamily.InterNetwork)) | |
| 56 | 新增: { | |
| 57 | 新增: await udp.SendAsync(new byte[]{1,2,3},new IPEndPoint(IPAddress.Parse("8.8.8.8"),53),token);result["udp_attempted"]=true; | |
| 58 | 新增: } | |
| 59 | 新增: progress.Stage="dns";result["public_dns_answered"]=await PublicDNS(nonce,token); | |
| 60 | 新增: var id=input["project_id"]?.GetValue<string>() ?? "";var grant=input["grant"]?.GetValue<string>() ?? ""; | |
| 61 | 新增: progress.Stage="project-grant";var directory=ProjectRpc.Resolve(id,grant); | |
| 62 | 新增: var name=input["shared_name"]?.GetValue<string>() ?? ""; | |
| 63 | 新增: var challenge=input["challenge"]?.GetValue<string>() ?? ""; | |
| 64 | 新增: if(name.Length is <1 or >255 || Path.GetFileName(name)!=name || !name.StartsWith(".cage-share-probe-",StringComparison.Ordinal) || challenge.Length!=64 || challenge.Any(c=>!char.IsAsciiHexDigit(c)))throw new InvalidDataException("safety_file_invalid"); | |
| 65 | 新增: var file=Path.Combine(directory,name); | |
| 66 | 新增: progress.Stage="shared-read";var original=await File.ReadAllTextAsync(file,token); | |
| 67 | 新增: result["shared_file"]=original==challenge; | |
| 68 | 新增: progress.Stage="shared-write";if(original==challenge)await File.WriteAllTextAsync(file,challenge+":guest",token); | |
| 69 | 新增: // Probe the host's private sibling through the confined virtual root. | |
| 70 | 新增: // The client can select no absolute path or content to retrieve. | |
| 71 | 新增: progress.Stage="private-scope";var privateName=input["private_name"]?.GetValue<string>() ?? ""; | |
| 72 | 新增: if(Path.GetFileName(privateName)!=privateName || !privateName.StartsWith(".cage-private-probe-",StringComparison.Ordinal))throw new InvalidDataException("safety_file_invalid"); | |
| 73 | 新增: result["private_file"]=File.Exists(Path.Combine(directory,privateName)) ? "reachable" : "unreachable"; | |
| 74 | 新增: } | |
| 75 | 新增: if(!available())throw new InvalidDataException("requires_gui_login"); | |
| 76 | 新增: await Protocol.Write(stream,result,token); | |
| 77 | 新增: } | |
| 78 | 新增: internal static string ObservedTimezone(string windowsZone,string? requested) | |
| 79 | 新增: { | |
| 80 | 新增: // Several IANA names share one Windows zone. Keep the requested label | |
| 81 | 新增: // only when it maps to the zone that the OS actually reports. | |
| 82 | 新增: if(requested is { Length: >0 and <=128 } && TimeZoneInfo.TryConvertIanaIdToWindowsId(requested,out var expected) && string.Equals(expected,windowsZone,StringComparison.OrdinalIgnoreCase))return requested; | |
| 83 | 新增: return TimeZoneInfo.TryConvertWindowsIdToIanaId(windowsZone,out var iana) ? iana! : windowsZone; | |
| 84 | 新增: } | |
| 85 | 新增: private static async Task<bool> Connect(string host,int port,AddressFamily family,CancellationToken token) | |
| 86 | 新增: { | |
| 87 | 新增: using var timeout=CancellationTokenSource.CreateLinkedTokenSource(token);timeout.CancelAfter(TimeSpan.FromSeconds(3)); | |
| 88 | 新增: using var client=new TcpClient(family); | |
| 89 | 新增: try{await client.ConnectAsync(IPAddress.Parse(host),port,timeout.Token);return true;}catch(SocketException){return false;}catch(OperationCanceledException)when(!token.IsCancellationRequested){return false;} | |
| 90 | 新增: } | |
| 91 | 新增: private static async Task<JsonObject> Probe(string path,CancellationToken token) | |
| 92 | 新增: { | |
| 93 | 新增: using var handler=new HttpClientHandler{UseProxy=false,AllowAutoRedirect=false};using var client=new HttpClient(handler){Timeout=TimeSpan.FromSeconds(15)}; | |
| 94 | 新增: try | |
| 95 | 新增: { | |
| 96 | 新增: using var response=await client.GetAsync("http://198.18.0.254/"+path,HttpCompletionOption.ResponseHeadersRead,token); | |
| 97 | 新增: using var body=await response.Content.ReadAsStreamAsync(token);using var buffer=new MemoryStream();var chunk=new byte[1024];int n; | |
| 98 | 新增: while((n=await body.ReadAsync(chunk,token))!=0){if(buffer.Length+n>4096)throw new InvalidDataException("safety_response_limit");buffer.Write(chunk,0,n);} | |
| 99 | 新增: var data=JsonNode.Parse(buffer.ToArray()) as JsonObject; | |
| 100 | 新增: return new JsonObject{["status"]=(int)response.StatusCode,["ip"]=data?["ip"]?.GetValue<string>() ?? ""}; | |
| 101 | 新增: } | |
| 102 | 新增: catch(HttpRequestException){return new JsonObject{["status"]=0,["ip"]=""};} | |
| 103 | 新增: catch(TaskCanceledException)when(!token.IsCancellationRequested){return new JsonObject{["status"]=0,["ip"]=""};} | |
| 104 | 新增: } | |
| 105 | 新增: private static async Task<bool> PublicDNS(string nonce,CancellationToken token) | |
| 106 | 新增: { | |
| 107 | 新增: using var timeout=CancellationTokenSource.CreateLinkedTokenSource(token);timeout.CancelAfter(TimeSpan.FromSeconds(2)); | |
| 108 | 新增: using var client=new UdpClient(AddressFamily.InterNetwork);var query=new List<byte>{1,2,1,0,0,1,0,0,0,0,0,0}; | |
| 109 | 新增: foreach(var label in (nonce+".example.com").Split('.')){query.Add((byte)label.Length);query.AddRange(Protocol.Utf8.GetBytes(label));}query.AddRange(new byte[]{0,0,1,0,1}); | |
| 110 | 新增: await client.SendAsync(query.ToArray(),new IPEndPoint(IPAddress.Parse("192.168.127.1"),53),token); | |
| 111 | 新增: try{var reply=await client.ReceiveAsync(timeout.Token);return reply.Buffer.Length>=12 && (reply.Buffer[6]!=0 || reply.Buffer[7]!=0);} | |
| 112 | 新增: catch(SocketException){return false;}catch(OperationCanceledException)when(!token.IsCancellationRequested){return false;} | |
| 113 | 新增: } | |
| 114 | 新增:} | |
| @@ -0,0 +1,255 @@ | ||
| 1 | 新增:using System.Buffers.Binary; | |
| 2 | 新增:using System.ComponentModel; | |
| 3 | 新增:using System.Diagnostics; | |
| 4 | 新增:using System.Net.Sockets; | |
| 5 | 新增:using System.Runtime.InteropServices; | |
| 6 | 新增:using System.Security.Cryptography; | |
| 7 | 新增:using System.Security.Principal; | |
| 8 | 新增:using System.Text.Json.Nodes; | |
| 9 | 新增: | |
| 10 | 新增:namespace Cage.GuestClipboard; | |
| 11 | 新增: | |
| 12 | 新增:// This SYSTEM process owns only the Cage virtual packet interface. The GUI | |
| 13 | 新增:// clipboard, browser, files and input endpoints run in the ordinary user agent. | |
| 14 | 新增:internal static class NetworkRuntime | |
| 15 | 新增:{ | |
| 16 | 新增: internal static readonly Guid Service = new("f4a4c1ce-3c9f-49f1-b7bf-82df6592c0fb"); | |
| 17 | 新增: internal const string IP = "192.168.127.2", Gateway = "192.168.127.1"; | |
| 18 | 新增: private static readonly SemaphoreSlim PacketSlot = new(1,1); | |
| 19 | 新增: private static readonly byte[] GuestMac = [0x5a,0x94,0xef,0xe4,0x0c,0xee], GatewayMac = [0x5a,0x94,0xef,0xe4,0x0c,0xdd]; | |
| 20 | 新增: internal static async Task Run(Guid vm, string sid, string keyPath, CancellationToken token) | |
| 21 | 新增: { | |
| 22 | 新增: if (WindowsIdentity.GetCurrent().User?.Value != "S-1-5-18") throw new InvalidDataException("network_requires_system"); | |
| 23 | 新增: var parameters = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Virtual Machine\Guest\Parameters"); | |
| 24 | 新增: if (!Guid.TryParse(parameters?.GetValue("VirtualMachineId")?.ToString(), out var actual) || actual != vm || !sid.StartsWith("S-1-5-21-",StringComparison.Ordinal)) throw new InvalidDataException("network_vm_invalid"); | |
| 25 | 新增: var secret = Pairing.Load(keyPath,vm,sid,false); | |
| 26 | 新增: using var listener = HyperVEndPoint.Socket(); | |
| 27 | 新增: using var interrupt = token.Register(listener.Dispose); | |
| 28 | 新增: listener.Bind(new HyperVEndPoint(Protocol.Parent,Service)); listener.Listen(1); | |
| 29 | 新增: using var slots = new SemaphoreSlim(4,4); | |
| 30 | 新增: var active = new HashSet<Task>(); | |
| 31 | 新增: try | |
| 32 | 新增: { | |
| 33 | 新增: while (!token.IsCancellationRequested) | |
| 34 | 新增: { | |
| 35 | 新增: await slots.WaitAsync(token); | |
| 36 | 新增: Socket socket; | |
| 37 | 新增: try { socket = await Task.Run(listener.Accept,CancellationToken.None).WaitAsync(token); } | |
| 38 | 新增: catch { slots.Release();throw; } | |
| 39 | 新增: lock(active) | |
| 40 | 新增: { | |
| 41 | 新增: Task? task = null; | |
| 42 | 新增: task = Task.Run(async()=>{ | |
| 43 | 新增: try { await Connection(socket,vm,sid,secret,token); } | |
| 44 | 新增: catch(Exception error) { | |
| 45 | 新增: // Stage-free native code only: never serialize request, | |
| 46 | 新增: // packet bytes, paths, identity secrets or exception text. | |
| 47 | 新增: try { File.WriteAllText(Path.Combine(AppContext.BaseDirectory,"network-error.json"),new JsonObject { ["error_type"]=error.GetType().Name,["hresult"]=error.HResult.ToString("X8"),["stage"]=(error as NetworkFailure)?.Stage ?? "handshake-or-stream",["native_code"]=(error.InnerException as Win32Exception)?.NativeErrorCode ?? (error as Win32Exception)?.NativeErrorCode ?? 0,["updated_at"]=DateTimeOffset.UtcNow.ToUnixTimeMilliseconds() }.ToJsonString()); } catch { } | |
| 48 | 新增: } | |
| 49 | 新增: finally { socket.Dispose();slots.Release();lock(active)active.Remove(task!); } | |
| 50 | 新增: },CancellationToken.None); | |
| 51 | 新增: active.Add(task); | |
| 52 | 新增: } | |
| 53 | 新增: } | |
| 54 | 新增: } | |
| 55 | 新增: catch(OperationCanceledException)when(token.IsCancellationRequested){ } | |
| 56 | 新增: catch(ObjectDisposedException)when(token.IsCancellationRequested){ } | |
| 57 | 新增: finally { Task[] pending;lock(active)pending=active.ToArray();await Task.WhenAll(pending);CryptographicOperations.ZeroMemory(secret); } | |
| 58 | 新增: } | |
| 59 | 新增: | |
| 60 | 新增: private static async Task Connection(Socket socket,Guid vm,string sid,byte[] secret,CancellationToken token) | |
| 61 | 新增: { | |
| 62 | 新增: using var connection = CancellationTokenSource.CreateLinkedTokenSource(token); | |
| 63 | 新增: using var cancel = connection.Token.Register(socket.Dispose); | |
| 64 | 新增: using var network = new NetworkStream(socket,false); | |
| 65 | 新增: using var stream = new ReadAheadStream(network); | |
| 66 | 新增: using var handshake = CancellationTokenSource.CreateLinkedTokenSource(connection.Token); handshake.CancelAfter(TimeSpan.FromSeconds(10)); | |
| 67 | 新增: var nonce = Convert.ToBase64String(RandomNumberGenerator.GetBytes(32)); var session = Guid.NewGuid().ToString("N"); | |
| 68 | 新增: await Protocol.Write(stream,new JsonObject { ["nonce"] = nonce,["vm_id"] = vm.ToString("D"),["sid"] = sid,["session"] = session,["proof"] = Protocol.Proof(secret,"server",nonce,vm,sid,session,"",null) },handshake.Token); | |
| 69 | 新增: var request = await Protocol.Read(stream,4096,handshake.Token) ?? throw new EndOfStreamException(); | |
| 70 | 新增: var operation = request["operation"]?.GetValue<string>() ?? ""; | |
| 71 | 新增: if (operation is not ("network-stream" or "network-settings") || request["paths"] is not null || request["vm_id"]?.GetValue<string>() != vm.ToString("D") || request["sid"]?.GetValue<string>() != sid || | |
| 72 | 新增: !Protocol.EqualProof(Protocol.Proof(secret,"client",nonce,vm,sid,session,operation,null),request["proof"]?.GetValue<string>())) throw new InvalidDataException("pairing_invalid"); | |
| 73 | 新增: if (operation == "network-settings") | |
| 74 | 新增: { | |
| 75 | 新增: await Protocol.Write(stream,new JsonObject { ["version"] = 1,["session"] = session,["available"] = true },handshake.Token); | |
| 76 | 新增: var settings = await Protocol.Read(stream,4096,handshake.Token) ?? throw new EndOfStreamException(); | |
| 77 | 新增: await WindowsSystemSettings.Apply(settings,vm,sid,connection.Token); | |
| 78 | 新增: await Protocol.Write(stream,new JsonObject { ["ok"] = true },connection.Token); return; | |
| 79 | 新增: } | |
| 80 | 新增: if(!await PacketSlot.WaitAsync(0,connection.Token))throw new InvalidDataException("network_stream_already_connected"); | |
| 81 | 新增: try { | |
| 82 | 新增: handshake.CancelAfter(TimeSpan.FromSeconds(20)); | |
| 83 | 新增: using var tun = new Wintun(vm); | |
| 84 | 新增: // Adapter configuration is part of the bounded admission handshake. | |
| 85 | 新增: // A stalled PowerShell operation must release this packet slot so a | |
| 86 | 新增: // later authenticated host connection can retry. | |
| 87 | 新增: await tun.Configure(handshake.Token); | |
| 88 | 新增: await Protocol.Write(stream,new JsonObject { ["version"] = 1,["os"] = "windows",["vm_id"] = vm.ToString("D"),["gui_user_sid"] = sid,["session"] = session,["available"] = true,["network"] = "packet" },handshake.Token); | |
| 89 | 新增: using var writes = new SemaphoreSlim(1,1); | |
| 90 | 新增: async Task Send(byte[] frame) | |
| 91 | 新增: { | |
| 92 | 新增: await writes.WaitAsync(connection.Token); | |
| 93 | 新增: try { var length = new byte[4]; BinaryPrimitives.WriteUInt32BigEndian(length,(uint)frame.Length); await stream.WriteAsync(length,connection.Token); await stream.WriteAsync(frame,connection.Token); await stream.FlushAsync(connection.Token); } | |
| 94 | 新增: finally { writes.Release(); } | |
| 95 | 新增: } | |
| 96 | 新增: var readyPath = Path.Combine(AppContext.BaseDirectory,"network-ready.json"); | |
| 97 | 新增: var receipt = Task.Run(async () => | |
| 98 | 新增: { | |
| 99 | 新增: while(!connection.IsCancellationRequested) | |
| 100 | 新增: { | |
| 101 | 新增: var data = new JsonObject { ["version"] = 1,["vm_id"] = vm.ToString("D"),["gui_user_sid"] = sid,["adapter"] = tun.Name,["interface_index"] = tun.Index,["session"] = session,["updated_at"] = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(),["network"] = "packet" }; | |
| 102 | 新增: var stage = readyPath+"."+session; | |
| 103 | 新增: await PublishReceipt(stage,readyPath,data.ToJsonString(),connection.Token); | |
| 104 | 新增: await Task.Delay(1000,connection.Token); | |
| 105 | 新增: } | |
| 106 | 新增: },connection.Token); | |
| 107 | 新增: var outgoing = Task.Run(async () => | |
| 108 | 新增: { | |
| 109 | 新增: while(!connection.IsCancellationRequested) | |
| 110 | 新增: { | |
| 111 | 新增: var packet = tun.Receive(); | |
| 112 | 新增: if (packet is null) { await Task.Delay(5,connection.Token); continue; } | |
| 113 | 新增: var frame = new byte[14+packet.Length]; GatewayMac.CopyTo(frame,0); GuestMac.CopyTo(frame,6); | |
| 114 | 新增: frame[12] = packet[0]>>4 == 6 ? (byte)0x86 : (byte)0x08; frame[13] = packet[0]>>4 == 6 ? (byte)0xdd : (byte)0; | |
| 115 | 新增: packet.CopyTo(frame,14); await Send(frame); | |
| 116 | 新增: } | |
| 117 | 新增: },connection.Token); | |
| 118 | 新增: var incoming = Task.Run(async () => | |
| 119 | 新增: { | |
| 120 | 新增: var header = new byte[4]; | |
| 121 | 新增: while(!connection.IsCancellationRequested) | |
| 122 | 新增: { | |
| 123 | 新增: await stream.ReadExactlyAsync(header,connection.Token); var size = BinaryPrimitives.ReadUInt32BigEndian(header); | |
| 124 | 新增: if (size is < 14 or > 65549) throw new InvalidDataException("network_packet_invalid"); | |
| 125 | 新增: var frame = new byte[size]; await stream.ReadExactlyAsync(frame,connection.Token); | |
| 126 | 新增: if (frame[12]==8 && frame[13]==6) | |
| 127 | 新增: { | |
| 128 | 新增: var response = Arp(frame); if (response is not null) await Send(response); continue; | |
| 129 | 新增: } | |
| 130 | 新增: if (!(frame[12]==8 && frame[13]==0 || frame[12]==0x86 && frame[13]==0xdd)) continue; | |
| 131 | 新增: if (!frame.AsSpan(0,6).SequenceEqual(GuestMac) && !frame.AsSpan(0,6).SequenceEqual(new byte[]{255,255,255,255,255,255})) continue; | |
| 132 | 新增: tun.Send(frame.AsSpan(14)); | |
| 133 | 新增: } | |
| 134 | 新增: },connection.Token); | |
| 135 | 新增: Task completed; | |
| 136 | 新增: try { completed = await Task.WhenAny(incoming,outgoing,receipt); } | |
| 137 | 新增: finally | |
| 138 | 新增: { | |
| 139 | 新增: connection.Cancel(); socket.Dispose(); | |
| 140 | 新增: try { await Task.WhenAll(incoming,outgoing,receipt); } catch { } | |
| 141 | 新增: try { if (JsonNode.Parse(File.ReadAllText(readyPath))?["session"]?.GetValue<string>()==session) File.Delete(readyPath); } catch { } | |
| 142 | 新增: try { File.Delete(readyPath+"."+session); } catch { } | |
| 143 | 新增: } | |
| 144 | 新增: // Retire all workers before reporting the worker that ended the stream. | |
| 145 | 新增: // Awaiting WhenAny alone would discard its exception and leave only an | |
| 146 | 新增: // old diagnostic from an unrelated admission failure. | |
| 147 | 新增: if (!token.IsCancellationRequested) | |
| 148 | 新增: { | |
| 149 | 新增: var stage = completed == incoming ? "stream-incoming" : completed == outgoing ? "stream-outgoing" : "stream-receipt"; | |
| 150 | 新增: try { await completed; } | |
| 151 | 新增: catch (NetworkFailure) { throw; } | |
| 152 | 新增: catch (Exception error) { throw new NetworkFailure(stage,error); } | |
| 153 | 新增: throw new NetworkFailure(stage,new EndOfStreamException()); | |
| 154 | 新增: } | |
| 155 | 新增: } finally { PacketSlot.Release(); } | |
| 156 | 新增: } | |
| 157 | 新增: | |
| 158 | 新增: internal static async Task PublishReceipt(string stage,string destination,string contents,CancellationToken token) | |
| 159 | 新增: { | |
| 160 | 新增: try { await File.WriteAllTextAsync(stage,contents,token); } | |
| 161 | 新增: catch (Exception error) when (!token.IsCancellationRequested) { throw new NetworkFailure("receipt-write",error); } | |
| 162 | 新增: try { await WindowsFilePublication.Replace(stage,destination,token); } | |
| 163 | 新增: catch(Exception error) when(!token.IsCancellationRequested) { throw new NetworkFailure("receipt-replace",error); } | |
| 164 | 新增: } | |
| 165 | 新增: | |
| 166 | 新增: private static byte[]? Arp(byte[] frame) | |
| 167 | 新增: { | |
| 168 | 新增: if (frame.Length < 42 || frame[14]!=0 || frame[15]!=1 || frame[16]!=8 || frame[17]!=0 || frame[18]!=6 || frame[19]!=4 || frame[20]!=0 || frame[21]!=1 || !frame.AsSpan(38,4).SequenceEqual(new byte[]{192,168,127,2})) return null; | |
| 169 | 新增: var result = new byte[42]; frame.AsSpan(6,6).CopyTo(result); GuestMac.CopyTo(result,6); result[12]=8; result[13]=6; | |
| 170 | 新增: frame.AsSpan(14,8).CopyTo(result.AsSpan(14)); result[21]=2; GuestMac.CopyTo(result,22); new byte[]{192,168,127,2}.CopyTo(result,28); | |
| 171 | 新增: frame.AsSpan(22,10).CopyTo(result.AsSpan(32)); return result; | |
| 172 | 新增: } | |
| 173 | 新增: | |
| 174 | 新增: private sealed class Wintun : IDisposable | |
| 175 | 新增: { | |
| 176 | 新增: [UnmanagedFunctionPointer(CallingConvention.Winapi,CharSet=CharSet.Unicode,SetLastError=true)] private delegate IntPtr Create(string name,string type,ref Guid id); | |
| 177 | 新增: [UnmanagedFunctionPointer(CallingConvention.Winapi)] private delegate void Close(IntPtr handle); | |
| 178 | 新增: [UnmanagedFunctionPointer(CallingConvention.Winapi,SetLastError=true)] private delegate IntPtr Start(IntPtr adapter,uint capacity); | |
| 179 | 新增: [UnmanagedFunctionPointer(CallingConvention.Winapi,SetLastError=true)] private delegate IntPtr ReceivePacket(IntPtr session,out uint size); | |
| 180 | 新增: [UnmanagedFunctionPointer(CallingConvention.Winapi)] private delegate void ReleasePacket(IntPtr session,IntPtr packet); | |
| 181 | 新增: [UnmanagedFunctionPointer(CallingConvention.Winapi,SetLastError=true)] private delegate IntPtr AllocatePacket(IntPtr session,uint size); | |
| 182 | 新增: [UnmanagedFunctionPointer(CallingConvention.Winapi)] private delegate void Luid(IntPtr adapter,out ulong luid); | |
| 183 | 新增: [DllImport("iphlpapi.dll")] private static extern uint ConvertInterfaceLuidToIndex(ref ulong luid,out uint index); | |
| 184 | 新增: private readonly IntPtr library,adapter,session; | |
| 185 | 新增: private readonly Close close,end; private readonly ReceivePacket receive; private readonly ReleasePacket release,send; private readonly AllocatePacket allocate; | |
| 186 | 新增: internal string Name { get; } | |
| 187 | 新增: internal uint Index { get; } | |
| 188 | 新增: private T Load<T>(string name) where T:Delegate => Marshal.GetDelegateForFunctionPointer<T>(NativeLibrary.GetExport(library,name)); | |
| 189 | 新增: internal Wintun(Guid vm) | |
| 190 | 新增: { | |
| 191 | 新增: Name = "Cage-"+vm.ToString("N")[..8]; | |
| 192 | 新增: library = NativeLibrary.Load(Path.Combine(AppContext.BaseDirectory,"wintun.dll")); | |
| 193 | 新增: close = Load<Close>("WintunCloseAdapter"); end = Load<Close>("WintunEndSession"); receive = Load<ReceivePacket>("WintunReceivePacket"); release = Load<ReleasePacket>("WintunReleaseReceivePacket"); send = Load<ReleasePacket>("WintunSendPacket"); allocate = Load<AllocatePacket>("WintunAllocateSendPacket"); | |
| 194 | 新增: try | |
| 195 | 新增: { | |
| 196 | 新增: adapter = Load<Create>("WintunCreateAdapter")(Name,"Cage",ref vm); | |
| 197 | 新增: if (adapter==IntPtr.Zero) throw new Win32Exception(Marshal.GetLastPInvokeError()); | |
| 198 | 新增: Load<Luid>("WintunGetAdapterLUID")(adapter,out var luid); | |
| 199 | 新增: if (ConvertInterfaceLuidToIndex(ref luid,out var index)!=0 || index==0) throw new InvalidDataException("network_adapter_invalid"); Index=index; | |
| 200 | 新增: session = Load<Start>("WintunStartSession")(adapter,4<<20); | |
| 201 | 新增: if (session==IntPtr.Zero) throw new Win32Exception(Marshal.GetLastPInvokeError()); | |
| 202 | 新增: } | |
| 203 | 新增: catch(Exception error) { Dispose(); throw new NetworkFailure("driver",error); } | |
| 204 | 新增: } | |
| 205 | 新增: internal async Task Configure(CancellationToken token) | |
| 206 | 新增: { | |
| 207 | 新增: var script = $"$ErrorActionPreference='Stop';$stage='adapter';try{{$i={Index};$a=Get-NetAdapter -Name '{Name}';if($a.ifIndex -ne $i -or $a.Name -cne '{Name}'){{throw 'network_adapter_invalid'}};$stage='ip';New-NetIPAddress -InterfaceIndex $i -IPAddress '{IP}' -PrefixLength 24 -DefaultGateway '{Gateway}' -AddressFamily IPv4 | Out-Null;$stage='dns';Set-DnsClientServerAddress -InterfaceIndex $i -ServerAddresses '{Gateway}';$stage='interface';Set-NetIPInterface -InterfaceIndex $i -AddressFamily IPv4 -InterfaceMetric 1 -NlMtuBytes 1500"; | |
| 208 | 新增: // New-NetIPAddress returns before Windows completes duplicate | |
| 209 | 新增: // address detection. A tentative address cannot send the probes. | |
| 210 | 新增: // Admit this exact adapter only when its real address and route | |
| 211 | 新增: // are usable; a timer by itself is never readiness evidence. | |
| 212 | 新增: script += $";$stage='preferred';$until=[DateTime]::UtcNow.AddSeconds(10);$ready=$false;while([DateTime]::UtcNow -lt $until){{$ip=Get-NetIPAddress -InterfaceIndex $i -AddressFamily IPv4 -IPAddress '{IP}' -ErrorAction SilentlyContinue;if($ip.AddressState -eq 'Duplicate'){{throw 'network_address_duplicate'}};$route=Get-NetRoute -InterfaceIndex $i -DestinationPrefix '0.0.0.0/0' -ErrorAction SilentlyContinue;$dns=Get-DnsClientServerAddress -InterfaceIndex $i -AddressFamily IPv4;$ready=($ip.AddressState -eq 'Preferred' -and (Get-NetAdapter -Name '{Name}').Status -eq 'Up' -and @($route|Where-Object {{$_.NextHop -eq '{Gateway}'}}).Count -gt 0 -and $dns.ServerAddresses -contains '{Gateway}');if($ready){{break}};Start-Sleep -Milliseconds 100}};if(!$ready){{throw 'network_address_not_ready'}}}}catch{{[Console]::Out.WriteLine((@{{stage=$stage;hresult=[int]$_.Exception.HResult;category=[string]$_.CategoryInfo.Category}}|ConvertTo-Json -Compress));exit 1}}"; | |
| 213 | 新增: var info = new ProcessStartInfo(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Windows),@"System32\WindowsPowerShell\v1.0\powershell.exe")) { UseShellExecute=false,RedirectStandardInput=true,RedirectStandardOutput=true,RedirectStandardError=true,CreateNoWindow=true }; | |
| 214 | 新增: foreach(var argument in new[]{"-NoLogo","-NoProfile","-NonInteractive","-Command","-"}) info.ArgumentList.Add(argument); | |
| 215 | 新增: using var process = Process.Start(info) ?? throw new InvalidDataException("network_configuration_failed"); | |
| 216 | 新增: using var cancel = token.Register(()=>{try{process.Kill(true);}catch{}}); | |
| 217 | 新增: var output = process.StandardOutput.ReadToEndAsync(token); var errors = process.StandardError.BaseStream.CopyToAsync(Stream.Null,token); | |
| 218 | 新增: await process.StandardInput.WriteLineAsync(script); process.StandardInput.Close(); await process.WaitForExitAsync(token); await Task.WhenAll(output,errors); | |
| 219 | 新增: if (process.ExitCode!=0) | |
| 220 | 新增: { | |
| 221 | 新增: var diagnostic=await output; | |
| 222 | 新增: try | |
| 223 | 新增: { | |
| 224 | 新增: if(diagnostic.Length>4096)throw new InvalidDataException("network_diagnostic_invalid"); | |
| 225 | 新增: var detail=JsonNode.Parse(diagnostic) as JsonObject; | |
| 226 | 新增: var stage=detail?["stage"]?.GetValue<string>(); | |
| 227 | 新增: if(stage is "adapter" or "ip" or "dns" or "interface" or "preferred") | |
| 228 | 新增: { | |
| 229 | 新增: var failure=new NetworkConfigurationFailure(detail?["hresult"]?.GetValue<int>() ?? 0); | |
| 230 | 新增: throw new NetworkFailure("configure-"+stage,failure); | |
| 231 | 新增: } | |
| 232 | 新增: } | |
| 233 | 新增: catch(NetworkFailure){throw;} | |
| 234 | 新增: catch(Exception error) when(error is System.Text.Json.JsonException or InvalidDataException or InvalidOperationException){ } | |
| 235 | 新增: throw new NetworkFailure("configure",new Win32Exception(process.ExitCode)); | |
| 236 | 新增: } | |
| 237 | 新增: } | |
| 238 | 新增: internal byte[]? Receive() | |
| 239 | 新增: { | |
| 240 | 新增: var pointer = receive(session,out var size); | |
| 241 | 新增: if(pointer==IntPtr.Zero) return null; | |
| 242 | 新增: try { if(size is <20 or >65535) throw new InvalidDataException("network_packet_invalid"); var data=new byte[size];Marshal.Copy(pointer,data,0,(int)size);return data; } | |
| 243 | 新增: finally { release(session,pointer); } | |
| 244 | 新增: } | |
| 245 | 新增: internal void Send(ReadOnlySpan<byte> data) | |
| 246 | 新增: { | |
| 247 | 新增: if(data.Length is <20 or >65535) throw new InvalidDataException("network_packet_invalid"); | |
| 248 | 新增: var pointer=allocate(session,(uint)data.Length);if(pointer==IntPtr.Zero)return; | |
| 249 | 新增: Marshal.Copy(data.ToArray(),0,pointer,data.Length);send(session,pointer); | |
| 250 | 新增: } | |
| 251 | 新增: public void Dispose() { if(session!=IntPtr.Zero)end(session);if(adapter!=IntPtr.Zero)close(adapter);NativeLibrary.Free(library); } | |
| 252 | 新增: } | |
| 253 | 新增: private sealed class NetworkConfigurationFailure:Exception{internal NetworkConfigurationFailure(int hresult):base("network_configuration_failed"){HResult=hresult;}} | |
| 254 | 新增: private sealed class NetworkFailure:Exception{internal NetworkFailure(string stage,Exception error):base("network_stage_failed",error){Stage=stage;HResult=error.HResult;}internal string Stage{get;}} | |
| 255 | 新增:} | |
| @@ -0,0 +1,194 @@ | ||
| 1 | 新增:using System.Net.Sockets; | |
| 2 | 新增:using System.ComponentModel; | |
| 3 | 新增:using System.Security.Cryptography; | |
| 4 | 新增:using System.Runtime.InteropServices; | |
| 5 | 新增:using System.Text.Json; | |
| 6 | 新增:using System.Text.Json.Nodes; | |
| 7 | 新增: | |
| 8 | 新增:namespace Cage.GuestClipboard; | |
| 9 | 新增: | |
| 10 | 新增:internal static class GuestOperations | |
| 11 | 新增:{ | |
| 12 | 新增: internal static readonly HashSet<string> Names = ["stream", "status", "import", "export", "terminal", "cli", "browser", "desktop", "attachments", "audio", "resources", "diagnostics", "versions", "safety", "project-mount", "network-stream", "network-settings"]; | |
| 13 | 新增: static readonly Dictionary<string, Func<Stream, CancellationToken, Func<bool>, Task>> handlers = new(StringComparer.Ordinal); | |
| 14 | 新增: internal static void Register(string name, Func<Stream, CancellationToken, Func<bool>, Task> handler) | |
| 15 | 新增: { | |
| 16 | 新增: if (!Names.Contains(name) || name is "stream" or "status" or "import" or "export" || !handlers.TryAdd(name, handler)) | |
| 17 | 新增: throw new InvalidOperationException("guest_operation_registration_invalid"); | |
| 18 | 新增: } | |
| 19 | 新增: internal static string[] Capabilities() => ["clipboard", .. handlers.Keys.Order()]; | |
| 20 | 新增: internal static Task Run(string name, Stream stream, CancellationToken token) => handlers.TryGetValue(name, out var handler) | |
| 21 | 新增: ? handler(stream, token, SessionGuard.Available) : throw new InvalidOperationException("guest_operation_unavailable"); | |
| 22 | 新增:} | |
| 23 | 新增: | |
| 24 | 新增:internal static class Program | |
| 25 | 新增:{ | |
| 26 | 新增: [DllImport("kernel32.dll")] static extern bool FreeConsole(); | |
| 27 | 新增: [STAThread] | |
| 28 | 新增: static int Main(string[] args) | |
| 29 | 新增: { | |
| 30 | 新增: try | |
| 31 | 新增: { | |
| 32 | 新增: if (args is ["self-test"]) { SelfTest.Run(); Console.WriteLine("Windows guest protocol tests passed."); return 0; } | |
| 33 | 新增: if (args.Length > 1 && args[0] == "--relay-profile") { Relay.Run(args).GetAwaiter().GetResult(); return 0; } | |
| 34 | 新增: if (args is ["pair", "--vm-id", var pairVM, "--sid", var pairSID, "--token-file", var source, "--output", var destination]) | |
| 35 | 新增: { Pairing.Protect(source, destination, Guid.Parse(pairVM), pairSID); return 0; } | |
| 36 | 新增: if (args is ["serve-network", "--vm-id", var networkVM, "--sid", var networkSID, "--token-file", var networkKey]) | |
| 37 | 新增: { | |
| 38 | 新增: using var networkLifetime = new CancellationTokenSource(); | |
| 39 | 新增: Console.CancelKeyPress += (_, e) => { e.Cancel = true; networkLifetime.Cancel(); }; | |
| 40 | 新增: NetworkRuntime.Run(Guid.Parse(networkVM), networkSID, networkKey, networkLifetime.Token).GetAwaiter().GetResult(); return 0; | |
| 41 | 新增: } | |
| 42 | 新增: if (args is not ["serve", "--vm-id", var vmText, "--sid", var sid, "--token-file", var tokenFile]) throw new InvalidDataException("command_invalid"); | |
| 43 | 新增: var vm = Guid.Parse(vmText); SessionGuard.Target(vm, sid); GuestContext.VM = vm; GuestContext.SID = sid; | |
| 44 | 新增: FreeConsole(); | |
| 45 | 新增: var secret = Pairing.Load(tokenFile, vm, sid, false); | |
| 46 | 新增: Application.SetHighDpiMode(HighDpiMode.SystemAware); | |
| 47 | 新增: using var lifetime = new CancellationTokenSource(); | |
| 48 | 新增: using var agent = new ClipboardAgent(Path.Combine(AppContext.BaseDirectory, "cage-guest-files.exe")); | |
| 49 | 新增: using var listener = HyperVEndPoint.Socket(); | |
| 50 | 新增: listener.Bind(new HyperVEndPoint(Protocol.Parent, Protocol.Service)); listener.Listen(64); | |
| 51 | 新增: GuestDiagnostics.Record("lifecycle", "started"); | |
| 52 | 新增: Application.ApplicationExit += (_, _) => { lifetime.Cancel(); listener.Dispose(); CryptographicOperations.ZeroMemory(secret); }; | |
| 53 | 新增: _ = Accept(listener, agent, vm, sid, secret, lifetime.Token); | |
| 54 | 新增: Application.Run(); return 0; | |
| 55 | 新增: } | |
| 56 | 新增: catch (Exception ex) | |
| 57 | 新增: { | |
| 58 | 新增: if (args.Length > 0 && args[0] is "serve" or "serve-network") GuestDiagnostics.Failure("startup", ex); | |
| 59 | 新增: var reason = ex switch | |
| 60 | 新增: { | |
| 61 | 新增: SocketException socketError => "socket_" + socketError.NativeErrorCode, | |
| 62 | 新增: Win32Exception nativeError => "win32_" + nativeError.NativeErrorCode, | |
| 63 | 新增: _ => ex.GetType().Name | |
| 64 | 新增: }; | |
| 65 | 新增: Console.Error.WriteLine("Windows guest channel unavailable (" + Relay.Phase + ":" + reason + "); check the bound VM, GUI login, pairing and deployed tools."); return 1; | |
| 66 | 新增: } | |
| 67 | 新增: } | |
| 68 | 新增: static async Task Accept(Socket listener, ClipboardAgent agent, Guid vm, string sid, byte[] secret, CancellationToken token) | |
| 69 | 新增: { | |
| 70 | 新增: using var slots = new SemaphoreSlim(64); | |
| 71 | 新增: try | |
| 72 | 新增: { | |
| 73 | 新增: while (!token.IsCancellationRequested) | |
| 74 | 新增: { | |
| 75 | 新增: await slots.WaitAsync(token); | |
| 76 | 新增: var socket = await Task.Run(listener.Accept, CancellationToken.None).WaitAsync(token); | |
| 77 | 新增: _ = Task.Run(async () => { try { await Connection(socket, agent, vm, sid, secret, token); } finally { socket.Dispose(); slots.Release(); } }, CancellationToken.None); | |
| 78 | 新增: } | |
| 79 | 新增: } | |
| 80 | 新增: catch (OperationCanceledException) { } | |
| 81 | 新增: catch (ObjectDisposedException) { } | |
| 82 | 新增: catch { Application.Exit(); } | |
| 83 | 新增: } | |
| 84 | 新增: static JsonObject Status(ClipboardAgent agent, Guid vm, string sid) | |
| 85 | 新增: { | |
| 86 | 新增: var status = agent.Hello(); status["vm_id"] = vm.ToString("D"); status["gui_user_sid"] = sid; | |
| 87 | 新增: status["reason"] = SessionGuard.Available() ? "" : "requires_gui_login"; | |
| 88 | 新增: status["capabilities"] = JsonSerializer.SerializeToNode(GuestOperations.Capabilities()); | |
| 89 | 新增: status["setup_account_disabled"] = SetupAccount.Disabled(); | |
| 90 | 新增: var browser=BrowserRpc.Status();status["browser"]=browser; | |
| 91 | 新增: status["components"]=WindowsComponentStatus.Snapshot(browser);return status; | |
| 92 | 新增: } | |
| 93 | 新增: static async Task Connection(Socket socket, ClipboardAgent agent, Guid vm, string sid, byte[] secret, CancellationToken lifetime) | |
| 94 | 新增: { | |
| 95 | 新增: using var network = new NetworkStream(socket, false); | |
| 96 | 新增: using var stream = new ReadAheadStream(network); | |
| 97 | 新增: using var handshake = CancellationTokenSource.CreateLinkedTokenSource(lifetime); handshake.CancelAfter(TimeSpan.FromSeconds(10)); | |
| 98 | 新增: var authenticated = false; var operation = ""; | |
| 99 | 新增: try | |
| 100 | 新增: { | |
| 101 | 新增: var nonce = Convert.ToBase64String(RandomNumberGenerator.GetBytes(32)); | |
| 102 | 新增: await Protocol.Write(stream, new() { ["nonce"] = nonce, ["vm_id"] = vm.ToString("D"), ["sid"] = sid, ["session"] = agent.Session, | |
| 103 | 新增: ["proof"] = Protocol.Proof(secret, "server", nonce, vm, sid, agent.Session, "", null) }, handshake.Token); | |
| 104 | 新增: var request = await Protocol.Read(stream, Protocol.PathLimit + 4096, handshake.Token) ?? throw new EndOfStreamException(); | |
| 105 | 新增: operation = request["operation"]?.GetValue<string>() ?? ""; | |
| 106 | 新增: if (!GuestOperations.Names.Contains(operation) || request["vm_id"]?.GetValue<string>() != vm.ToString("D") || request["sid"]?.GetValue<string>() != sid || | |
| 107 | 新增: !Protocol.EqualProof(Protocol.Proof(secret, "client", nonce, vm, sid, agent.Session, operation, request["paths"]), request["proof"]?.GetValue<string>())) | |
| 108 | 新增: throw new InvalidDataException("pairing_invalid"); | |
| 109 | 新增: authenticated = true; | |
| 110 | 新增: if (operation == "status") { await Protocol.Write(stream, Status(agent, vm, sid), lifetime); return; } | |
| 111 | 新增: await Protocol.Write(stream, agent.Hello(), lifetime); | |
| 112 | 新增: if (operation == "diagnostics") { await GuestOperations.Run(operation, stream, lifetime); return; } | |
| 113 | 新增: if (operation == "stream") { await ClipboardStream(stream, agent, lifetime); return; } | |
| 114 | 新增: SessionGuard.Assert(); | |
| 115 | 新增: using var activity = CancellationTokenSource.CreateLinkedTokenSource(lifetime); | |
| 116 | 新增: var guard = Task.Run(async () => { try { while (true) { await Task.Delay(100, activity.Token); if (!SessionGuard.Available()) { activity.Cancel(); return; } } } catch (OperationCanceledException) { } }); | |
| 117 | 新增: try | |
| 118 | 新增: { | |
| 119 | 新增: if (operation == "import") await agent.Import(stream, activity.Token); | |
| 120 | 新增: else if (operation == "export") await agent.Export(stream, request["paths"], activity.Token); | |
| 121 | 新增: else await GuestOperations.Run(operation, stream, activity.Token); | |
| 122 | 新增: } | |
| 123 | 新增: finally { activity.Cancel(); await guard; } | |
| 124 | 新增: } | |
| 125 | 新增: catch (Exception error) | |
| 126 | 新增: { | |
| 127 | 新增: if (authenticated && operation != "diagnostics") GuestDiagnostics.Failure(operation, error); | |
| 128 | 新增: // Export is framed: an early EOF is a failure. Never write an error | |
| 129 | 新增: // JSON object into the middle of its binary frame stream. | |
| 130 | 新增: if (authenticated && operation != "export") | |
| 131 | 新增: try { using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(1)); await Protocol.Write(stream, new() { ["error"] = SessionGuard.Available() ? "guest_operation_failed" : "requires_gui_login" }, timeout.Token); } catch { } | |
| 132 | 新增: } | |
| 133 | 新增: } | |
| 134 | 新增: static async Task ClipboardStream(Stream stream, ClipboardAgent agent, CancellationToken lifetime) | |
| 135 | 新增: { | |
| 136 | 新增: using var channel = CancellationTokenSource.CreateLinkedTokenSource(lifetime); | |
| 137 | 新增: var events = await agent.Subscribe(); | |
| 138 | 新增: var writer = Task.Run(async () => | |
| 139 | 新增: { | |
| 140 | 新增: try { await foreach (var message in events.ReadAllAsync(channel.Token)) await Protocol.Write(stream, message, channel.Token); } | |
| 141 | 新增: finally { channel.Cancel(); } | |
| 142 | 新增: }); | |
| 143 | 新增: try | |
| 144 | 新增: { | |
| 145 | 新增: while (await Protocol.Read(stream, Protocol.WireLimit, channel.Token) is { } request) | |
| 146 | 新增: try { await agent.Apply(request); } | |
| 147 | 新增: catch { await agent.GUI(() => { agent.ReportError(); return true; }); } | |
| 148 | 新增: } | |
| 149 | 新增: finally { channel.Cancel(); await agent.Unsubscribe(); try { await writer; } catch (OperationCanceledException) { } } | |
| 150 | 新增: } | |
| 151 | 新增:} | |
| 152 | 新增: | |
| 153 | 新增:internal static class GuestContext | |
| 154 | 新增:{ | |
| 155 | 新增: internal static Guid VM { get; set; } | |
| 156 | 新增: internal static string SID { get; set; } = ""; | |
| 157 | 新增:} | |
| 158 | 新增: | |
| 159 | 新增:// Read buffering is independent from writes, which is essential for a duplex | |
| 160 | 新增:// socket carrying JSON lines followed by binary archive frames. | |
| 161 | 新增:internal sealed class ReadAheadStream(Stream inner) : Stream | |
| 162 | 新增:{ | |
| 163 | 新增: readonly byte[] buffer = new byte[64 << 10]; int position, count; | |
| 164 | 新增: internal async Task<byte[]?> Line(int limit, CancellationToken token) | |
| 165 | 新增: { | |
| 166 | 新增: using var line = new MemoryStream(); | |
| 167 | 新增: while (true) | |
| 168 | 新增: { | |
| 169 | 新增: if (position == count) | |
| 170 | 新增: { | |
| 171 | 新增: count = await inner.ReadAsync(buffer, token); position = 0; | |
| 172 | 新增: if (count == 0) { if (line.Length == 0) return null; throw new EndOfStreamException(); } | |
| 173 | 新增: } | |
| 174 | 新增: var newline = buffer.AsSpan(position, count - position).IndexOf((byte)10); | |
| 175 | 新增: var n = newline < 0 ? count - position : newline; | |
| 176 | 新增: if (line.Length + n > limit) throw new InvalidDataException("message_limit"); | |
| 177 | 新增: line.Write(buffer, position, n); position += n; | |
| 178 | 新增: if (newline >= 0) { position++; return line.ToArray(); } | |
| 179 | 新增: } | |
| 180 | 新增: } | |
| 181 | 新增: public override bool CanRead => true; public override bool CanSeek => false; public override bool CanWrite => true; | |
| 182 | 新增: public override long Length => throw new NotSupportedException(); public override long Position { get => throw new NotSupportedException(); set => throw new NotSupportedException(); } | |
| 183 | 新增: public override async ValueTask<int> ReadAsync(Memory<byte> destination, CancellationToken token = default) | |
| 184 | 新增: { | |
| 185 | 新增: if (destination.Length == 0) return 0; | |
| 186 | 新增: if (position == count) { count = await inner.ReadAsync(buffer, token); position = 0; if (count == 0) return 0; } | |
| 187 | 新增: var n = Math.Min(destination.Length, count - position); buffer.AsMemory(position, n).CopyTo(destination); position += n; return n; | |
| 188 | 新增: } | |
| 189 | 新增: public override int Read(byte[] bytes, int offset, int size) => ReadAsync(bytes.AsMemory(offset, size)).AsTask().GetAwaiter().GetResult(); | |
| 190 | 新增: public override ValueTask WriteAsync(ReadOnlyMemory<byte> bytes, CancellationToken token = default) => inner.WriteAsync(bytes, token); | |
| 191 | 新增: public override void Write(byte[] bytes, int offset, int size) => inner.Write(bytes, offset, size); | |
| 192 | 新增: public override void Flush() => inner.Flush(); public override Task FlushAsync(CancellationToken token) => inner.FlushAsync(token); | |
| 193 | 新增: public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException(); public override void SetLength(long length) => throw new NotSupportedException(); | |
| 194 | 新增:} | |
| @@ -0,0 +1,154 @@ | ||
| 1 | 新增:using System.Collections.Concurrent; | |
| 2 | 新增:using System.Diagnostics; | |
| 3 | 新增:using System.Runtime.CompilerServices; | |
| 4 | 新增:using System.Security.Principal; | |
| 5 | 新增:using System.Text.Json.Nodes; | |
| 6 | 新增:using System.Text.RegularExpressions; | |
| 7 | 新增:using Microsoft.Win32; | |
| 8 | 新增: | |
| 9 | 新增:namespace Cage.GuestClipboard; | |
| 10 | 新增: | |
| 11 | 新增:internal static class ProjectRpc | |
| 12 | 新增:{ | |
| 13 | 新增: private static readonly ConcurrentDictionary<string, Mount> Mounts = new(StringComparer.Ordinal); | |
| 14 | 新增: private static readonly SemaphoreSlim Slots = new(32, 32); | |
| 15 | 新增: internal static event Action<string, string>? Revoked; | |
| 16 | 新增: private static readonly Regex ID = new("^[a-f0-9]{16}$", RegexOptions.CultureInvariant); | |
| 17 | 新增: private static readonly Regex Grant = new("^[a-f0-9]{64}$", RegexOptions.CultureInvariant); | |
| 18 | 新增: private static readonly Regex Probe = new("^\\.cage-mount-probe-[A-Za-z0-9_-]{1,100}$", RegexOptions.CultureInvariant); | |
| 19 | 新增: [ModuleInitializer] | |
| 20 | 新增: internal static void Register() { if (ToolsPresent()) GuestOperations.Register("project-mount", Run); } | |
| 21 | 新增: internal static bool ToolsPresent() | |
| 22 | 新增: { | |
| 23 | 新增: try | |
| 24 | 新增: { | |
| 25 | 新增: using var registry = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry32); | |
| 26 | 新增: using var key = registry.OpenSubKey(@"SOFTWARE\WinFsp"); | |
| 27 | 新增: var install = key?.GetValue("InstallDir") as string; | |
| 28 | 新增: return install is not null && File.Exists(Path.Combine(install, "bin", "winfsp-x64.dll")) && | |
| 29 | 新增: File.Exists(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles), "SSHFS-Win", "bin", "sshfs-win.exe")); | |
| 30 | 新增: } | |
| 31 | 新增: catch { return false; } | |
| 32 | 新增: } | |
| 33 | 新增: internal static string Resolve(string id, string grant) | |
| 34 | 新增: { | |
| 35 | 新增: if (!ID.IsMatch(id) || !Grant.IsMatch(grant) || !Mounts.TryGetValue(id, out var mount) || | |
| 36 | 新增: mount.Grant != grant || !mount.Ready || mount.Child.HasExited || mount.Lifetime.IsCancellationRequested) | |
| 37 | 新增: throw new InvalidDataException("project_grant_unavailable"); | |
| 38 | 新增: return mount.Path; | |
| 39 | 新增: } | |
| 40 | 新增: internal static async Task Run(Stream stream, CancellationToken token, Func<bool> available) | |
| 41 | 新增: { | |
| 42 | 新增: if (!available()) throw new InvalidDataException("requires_gui_login"); | |
| 43 | 新增: var value = await Protocol.Read(stream, 16384, token) ?? throw new EndOfStreamException(); | |
| 44 | 新增: var id = value["id"]?.GetValue<string>() ?? ""; | |
| 45 | 新增: var grant = value["grant"]?.GetValue<string>() ?? ""; | |
| 46 | 新增: if (!ID.IsMatch(id) || !Grant.IsMatch(grant)) throw new InvalidDataException("project_grant_invalid"); | |
| 47 | 新增: switch (value["action"]?.GetValue<string>()) | |
| 48 | 新增: { | |
| 49 | 新增: case "mount": await Start(stream, id, grant, token, available); break; | |
| 50 | 新增: case "probe": | |
| 51 | 新增: if (!Mounts.TryGetValue(id, out var mount) || mount.Grant != grant || mount.Child.HasExited) | |
| 52 | 新增: throw new InvalidDataException("project_grant_unavailable"); | |
| 53 | 新增: var name = value["probe_name"]?.GetValue<string>() ?? ""; | |
| 54 | 新增: if (!Probe.IsMatch(name)) throw new InvalidDataException("project_probe_invalid"); | |
| 55 | 新增: try | |
| 56 | 新增: { | |
| 57 | 新增: using var file = File.OpenRead(Path.Combine(mount.Path, name)); | |
| 58 | 新增: if (file.Length is < 1 or > 4096) throw new InvalidDataException("project_probe_invalid"); | |
| 59 | 新增: using var reader = new StreamReader(file, Protocol.Utf8); | |
| 60 | 新增: var proof = await reader.ReadToEndAsync(token); | |
| 61 | 新增: if (!available() || mount.Lifetime.IsCancellationRequested || mount.Child.HasExited) throw new InvalidDataException("requires_gui_login"); | |
| 62 | 新增: mount.Ready = true; | |
| 63 | 新增: await Protocol.Write(stream, new() { ["mounted"] = true, ["id"] = id, ["path"] = mount.Path, ["proof"] = proof }, token); | |
| 64 | 新增: } | |
| 65 | 新增: catch (IOException) { await Protocol.Write(stream, new() { ["mounted"] = false }, token); } | |
| 66 | 新增: break; | |
| 67 | 新增: case "unmount": | |
| 68 | 新增: if (!Mounts.TryGetValue(id, out var selected) || selected.Grant != grant) throw new InvalidDataException("project_grant_unavailable"); | |
| 69 | 新增: Revoke(id, selected); | |
| 70 | 新增: selected.Lifetime.Cancel(); | |
| 71 | 新增: await selected.Done.Task.WaitAsync(token); | |
| 72 | 新增: await Protocol.Write(stream, new() { ["unmounted"] = true }, token); break; | |
| 73 | 新增: default: throw new InvalidDataException("project_operation_invalid"); | |
| 74 | 新增: } | |
| 75 | 新增: } | |
| 76 | 新增: private static async Task Start(Stream stream, string id, string grant, CancellationToken token, Func<bool> available) | |
| 77 | 新增: { | |
| 78 | 新增: if (!await Slots.WaitAsync(0, token)) throw new InvalidDataException("project_limit"); | |
| 79 | 新增: try { await StartCore(stream, id, grant, token, available); } finally { Slots.Release(); } | |
| 80 | 新增: } | |
| 81 | 新增: private static async Task StartCore(Stream stream, string id, string grant, CancellationToken token, Func<bool> available) | |
| 82 | 新增: { | |
| 83 | 新增: if (Mounts.TryGetValue(id, out var previous)) | |
| 84 | 新增: { | |
| 85 | 新增: if (previous.Grant == grant) throw new InvalidDataException("project_mount_busy"); | |
| 86 | 新增: Revoke(id, previous); previous.Lifetime.Cancel(); | |
| 87 | 新增: await previous.Done.Task.WaitAsync(token); | |
| 88 | 新增: } | |
| 89 | 新增: var home = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile); | |
| 90 | 新增: using var identity = WindowsIdentity.GetCurrent(); | |
| 91 | 新增: var parent = Path.Combine(home, "Cage", "Projects"); | |
| 92 | 新增: foreach (var directory in new[] { Path.Combine(home, "Cage"), parent }) | |
| 93 | 新增: { | |
| 94 | 新增: Directory.CreateDirectory(directory); | |
| 95 | 新增: var info = new DirectoryInfo(directory); | |
| 96 | 新增: if (info.Attributes.HasFlag(FileAttributes.ReparsePoint) || info.GetAccessControl().GetOwner(typeof(SecurityIdentifier))?.Value != identity.User?.Value) | |
| 97 | 新增: throw new InvalidDataException("project_mount_parent_invalid"); | |
| 98 | 新增: } | |
| 99 | 新增: var path = Path.Combine(parent, id); | |
| 100 | 新增: // WinFsp owns mount-point creation and removal; never replace user files. | |
| 101 | 新增: if (Path.Exists(path)) throw new InvalidDataException("project_mount_path_exists"); | |
| 102 | 新增: var executable = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles), "SSHFS-Win", "bin", "sshfs-win.exe"); | |
| 103 | 新增: if (!File.Exists(executable)) throw new InvalidDataException("project_tools_missing"); | |
| 104 | 新增: var start = new ProcessStartInfo(executable) { UseShellExecute = false, CreateNoWindow = true, RedirectStandardInput = true, RedirectStandardOutput = true, RedirectStandardError = true }; | |
| 105 | 新增: foreach (var arg in new[] { "cmd", ":/", CygwinPath(path), "-f", "-o", "slave,uid=-1,gid=-1,cache=no,nodev,nosuid" }) start.ArgumentList.Add(arg); | |
| 106 | 新增: using var child = new Process { StartInfo = start }; | |
| 107 | 新增: using var lifetime = CancellationTokenSource.CreateLinkedTokenSource(token); | |
| 108 | 新增: var mount = new Mount(grant, path, child, lifetime); | |
| 109 | 新增: if (!Mounts.TryAdd(id, mount)) throw new InvalidDataException("project_mount_busy"); | |
| 110 | 新增: Task? input = null, output = null, stderr = null, exited = null; | |
| 111 | 新增: try | |
| 112 | 新增: { | |
| 113 | 新增: if (!available() || !child.Start()) throw new InvalidDataException("requires_gui_login"); | |
| 114 | 新增: using var stop = lifetime.Token.Register(() => { try { child.Kill(true); } catch { } }); | |
| 115 | 新增: await Protocol.Write(stream, new() { ["started"] = true, ["id"] = id, ["path"] = path }, lifetime.Token); | |
| 116 | 新增: input = stream.CopyToAsync(child.StandardInput.BaseStream, lifetime.Token); | |
| 117 | 新增: output = child.StandardOutput.BaseStream.CopyToAsync(stream, lifetime.Token); | |
| 118 | 新增: stderr = child.StandardError.BaseStream.CopyToAsync(Stream.Null, lifetime.Token); | |
| 119 | 新增: exited = child.WaitForExitAsync(lifetime.Token); | |
| 120 | 新增: await Task.WhenAny(input, output, exited); | |
| 121 | 新增: } | |
| 122 | 新增: finally | |
| 123 | 新增: { | |
| 124 | 新增: Revoke(id, mount); | |
| 125 | 新增: lifetime.Cancel(); | |
| 126 | 新增: try { child.StandardInput.Close(); } catch { } | |
| 127 | 新增: try { if (!child.HasExited) child.Kill(true); await child.WaitForExitAsync(); } catch { } | |
| 128 | 新增: foreach (var task in new[] { input, output, stderr, exited }) if (task is not null) try { await task; } catch { } | |
| 129 | 新增: mount.Done.TrySetResult(); | |
| 130 | 新增: } | |
| 131 | 新增: } | |
| 132 | 新增: private static void Revoke(string id, Mount mount) | |
| 133 | 新增: { | |
| 134 | 新增: mount.Ready = false; | |
| 135 | 新增: if (!((ICollection<KeyValuePair<string, Mount>>)Mounts).Remove(new(id, mount))) return; | |
| 136 | 新增: if (Revoked is { } handlers) | |
| 137 | 新增: foreach (Action<string, string> handler in handlers.GetInvocationList()) | |
| 138 | 新增: try { handler(id, mount.Grant); } catch { /* all consumers must receive revocation */ } | |
| 139 | 新增: } | |
| 140 | 新增: private static string CygwinPath(string path) | |
| 141 | 新增: { | |
| 142 | 新增: if (path.Length < 4 || !char.IsAsciiLetter(path[0]) || path[1] != ':' || path[2] != '\\') throw new InvalidDataException("project_mount_path_invalid"); | |
| 143 | 新增: return "/cygdrive/" + char.ToLowerInvariant(path[0]) + path[2..].Replace('\\', '/'); | |
| 144 | 新增: } | |
| 145 | 新增: private sealed class Mount(string grant, string path, Process child, CancellationTokenSource lifetime) | |
| 146 | 新增: { | |
| 147 | 新增: internal string Grant { get; } = grant; | |
| 148 | 新增: internal string Path { get; } = path; | |
| 149 | 新增: internal Process Child { get; } = child; | |
| 150 | 新增: internal CancellationTokenSource Lifetime { get; } = lifetime; | |
| 151 | 新增: internal readonly TaskCompletionSource Done = new(TaskCreationOptions.RunContinuationsAsynchronously); | |
| 152 | 新增: internal volatile bool Ready; | |
| 153 | 新增: } | |
| 154 | 新增:} | |
| @@ -0,0 +1,137 @@ | ||
| 1 | 新增:using System.Buffers.Binary; | |
| 2 | 新增:using System.Net; | |
| 3 | 新增:using System.Net.Sockets; | |
| 4 | 新增:using System.Security.Cryptography; | |
| 5 | 新增:using System.Text; | |
| 6 | 新增:using System.Text.Json; | |
| 7 | 新增:using System.Text.Json.Nodes; | |
| 8 | 新增: | |
| 9 | 新增:namespace Cage.GuestClipboard; | |
| 10 | 新增: | |
| 11 | 新增:internal static class Protocol | |
| 12 | 新增:{ | |
| 13 | 新增: internal static readonly Guid Service = new("f4a4c1ce-3c9f-49f1-b7bf-82df6592c0fa"); | |
| 14 | 新增: internal static readonly Guid Parent = new("a42e7cda-d03f-480c-9cc2-a4de20abb878"); | |
| 15 | 新增: internal const int WireLimit = 30 << 20, PathLimit = 1 << 20, TextLimit = 2 << 20, PngLimit = 20 << 20; | |
| 16 | 新增: internal static readonly UTF8Encoding Utf8 = new(false, true); | |
| 17 | 新增: internal static JsonObject PublicHello(JsonObject hello) => new() { ["hello"] = hello }; | |
| 18 | 新增: | |
| 19 | 新增: // Do not use StreamReader here: its read-ahead would consume archive frames | |
| 20 | 新增: // following a JSON handshake on the same bidirectional stream. | |
| 21 | 新增: internal static async Task<JsonObject?> Read(Stream input, int limit, CancellationToken token) | |
| 22 | 新增: { | |
| 23 | 新增: if (input is ReadAheadStream buffered) | |
| 24 | 新增: { | |
| 25 | 新增: var bytes = await buffered.Line(limit, token); | |
| 26 | 新增: if (bytes == null) return null; | |
| 27 | 新增: return JsonNode.Parse(Utf8.GetString(bytes)) as JsonObject ?? throw new InvalidDataException("message_invalid"); | |
| 28 | 新增: } | |
| 29 | 新增: using var line = new MemoryStream(); | |
| 30 | 新增: var one = new byte[1]; | |
| 31 | 新增: while (true) | |
| 32 | 新增: { | |
| 33 | 新增: if (await input.ReadAsync(one, token) == 0) | |
| 34 | 新增: { | |
| 35 | 新增: if (line.Length == 0) return null; | |
| 36 | 新增: throw new EndOfStreamException(); | |
| 37 | 新增: } | |
| 38 | 新增: if (one[0] == 10) break; | |
| 39 | 新增: if (line.Length >= limit) throw new InvalidDataException("message_limit"); | |
| 40 | 新增: line.WriteByte(one[0]); | |
| 41 | 新增: } | |
| 42 | 新增: return JsonNode.Parse(Utf8.GetString(line.GetBuffer(), 0, (int)line.Length)) as JsonObject | |
| 43 | 新增: ?? throw new InvalidDataException("message_invalid"); | |
| 44 | 新增: } | |
| 45 | 新增: | |
| 46 | 新增: internal static async Task Write(Stream output, JsonObject data, CancellationToken token) | |
| 47 | 新增: { | |
| 48 | 新增: var bytes = Utf8.GetBytes(data.ToJsonString()); | |
| 49 | 新增: if (bytes.Length > WireLimit) throw new InvalidDataException("message_limit"); | |
| 50 | 新增: await output.WriteAsync(bytes, token); | |
| 51 | 新增: await output.WriteAsync(new byte[] { 10 }, token); | |
| 52 | 新增: await output.FlushAsync(token); | |
| 53 | 新增: } | |
| 54 | 新增: | |
| 55 | 新增: internal static string[] Paths(JsonNode? value) | |
| 56 | 新增: { | |
| 57 | 新增: if (value is not JsonArray a || a.Count is < 1 or > 100) throw new InvalidDataException("selection_invalid"); | |
| 58 | 新增: var paths = a.Select(x => x?.GetValue<string>() ?? "").ToArray(); | |
| 59 | 新增: if (paths.Any(x => string.IsNullOrWhiteSpace(x) || x.Contains('\0') || !Path.IsPathFullyQualified(x)) || | |
| 60 | 新增: Utf8.GetByteCount(a.ToJsonString()) > PathLimit) | |
| 61 | 新增: throw new InvalidDataException("selection_invalid"); | |
| 62 | 新增: return paths; | |
| 63 | 新增: } | |
| 64 | 新增: | |
| 65 | 新增: internal static void Png(byte[] data) | |
| 66 | 新增: { | |
| 67 | 新增: ReadOnlySpan<byte> signature = [137, 80, 78, 71, 13, 10, 26, 10]; | |
| 68 | 新增: if (data.Length is < 33 or > PngLimit || !data.AsSpan(0, 8).SequenceEqual(signature) || | |
| 69 | 新增: !data.AsSpan(12, 4).SequenceEqual("IHDR"u8)) throw new InvalidDataException("image_invalid"); | |
| 70 | 新增: var w = BinaryPrimitives.ReadUInt32BigEndian(data.AsSpan(16, 4)); | |
| 71 | 新增: var h = BinaryPrimitives.ReadUInt32BigEndian(data.AsSpan(20, 4)); | |
| 72 | 新增: if (w == 0 || h == 0 || (ulong)w * h > 40_000_000) throw new InvalidDataException("image_limit"); | |
| 73 | 新增: } | |
| 74 | 新增: | |
| 75 | 新增: internal static string Proof(byte[] secret, string role, string nonce, Guid vm, string sid, string session, string operation, JsonNode? paths) | |
| 76 | 新增: { | |
| 77 | 新增: var content = new JsonArray(role, nonce, vm.ToString("D"), sid, session, operation, paths?.ToJsonString() ?? "").ToJsonString(); | |
| 78 | 新增: return Convert.ToBase64String(HMACSHA256.HashData(secret, Utf8.GetBytes(content))); | |
| 79 | 新增: } | |
| 80 | 新增: | |
| 81 | 新增: internal static bool EqualProof(string expected, string? actual) | |
| 82 | 新增: { | |
| 83 | 新增: try { return CryptographicOperations.FixedTimeEquals(Convert.FromBase64String(expected), Convert.FromBase64String(actual ?? "")); } | |
| 84 | 新增: catch (FormatException) { return false; } | |
| 85 | 新增: } | |
| 86 | 新增: | |
| 87 | 新增: // Archives use bounded frames internally. The zero frame is followed by a | |
| 88 | 新增: // result object, so a closed connection is never mistaken for a complete tar. | |
| 89 | 新增: internal static async Task SendFrames(Stream input, Stream output, CancellationToken token) | |
| 90 | 新增: { | |
| 91 | 新增: var buffer = new byte[64 << 10]; var header = new byte[4]; | |
| 92 | 新增: int n; | |
| 93 | 新增: while ((n = await input.ReadAsync(buffer, token)) != 0) | |
| 94 | 新增: { | |
| 95 | 新增: BinaryPrimitives.WriteUInt32LittleEndian(header, (uint)n); | |
| 96 | 新增: await output.WriteAsync(header, token); await output.WriteAsync(buffer.AsMemory(0, n), token); | |
| 97 | 新增: } | |
| 98 | 新增: Array.Clear(header); await output.WriteAsync(header, token); await output.FlushAsync(token); | |
| 99 | 新增: } | |
| 100 | 新增: | |
| 101 | 新增: internal static async Task ReceiveFrames(Stream input, Stream output, CancellationToken token) | |
| 102 | 新增: { | |
| 103 | 新增: var buffer = new byte[64 << 10]; var header = new byte[4]; | |
| 104 | 新增: while (true) | |
| 105 | 新增: { | |
| 106 | 新增: await input.ReadExactlyAsync(header, token); | |
| 107 | 新增: var n = BinaryPrimitives.ReadUInt32LittleEndian(header); | |
| 108 | 新增: if (n == 0) break; | |
| 109 | 新增: if (n > buffer.Length) throw new InvalidDataException("frame_invalid"); | |
| 110 | 新增: await input.ReadExactlyAsync(buffer.AsMemory(0, (int)n), token); | |
| 111 | 新增: await output.WriteAsync(buffer.AsMemory(0, (int)n), token); | |
| 112 | 新增: } | |
| 113 | 新增: await output.FlushAsync(token); | |
| 114 | 新增: } | |
| 115 | 新增:} | |
| 116 | 新增: | |
| 117 | 新增:internal sealed class HyperVEndPoint(Guid vm, Guid service) : EndPoint | |
| 118 | 新增:{ | |
| 119 | 新增: internal Guid VM { get; } = vm; | |
| 120 | 新增: internal Guid Service { get; } = service; | |
| 121 | 新增: public override AddressFamily AddressFamily => (AddressFamily)34; | |
| 122 | 新增: public override SocketAddress Serialize() | |
| 123 | 新增: { | |
| 124 | 新增: var address = new SocketAddress(AddressFamily, 36); | |
| 125 | 新增: var bytes = VM.ToByteArray().Concat(Service.ToByteArray()).ToArray(); | |
| 126 | 新增: for (var i = 0; i < bytes.Length; i++) address[i + 4] = bytes[i]; | |
| 127 | 新增: return address; | |
| 128 | 新增: } | |
| 129 | 新增: public override EndPoint Create(SocketAddress address) | |
| 130 | 新增: { | |
| 131 | 新增: if (address.Family != AddressFamily || address.Size != 36) throw new InvalidDataException("endpoint_invalid"); | |
| 132 | 新增: var vmBytes = new byte[16]; var serviceBytes = new byte[16]; | |
| 133 | 新增: for (var i = 0; i < 16; i++) { vmBytes[i] = address[i + 4]; serviceBytes[i] = address[i + 20]; } | |
| 134 | 新增: return new HyperVEndPoint(new Guid(vmBytes), new Guid(serviceBytes)); | |
| 135 | 新增: } | |
| 136 | 新增: internal static Socket Socket() => new((AddressFamily)34, SocketType.Stream, (ProtocolType)1); | |
| 137 | 新增:} | |
| @@ -0,0 +1,110 @@ | ||
| 1 | 新增:using System.Net.Sockets; | |
| 2 | 新增:using System.Security.Cryptography; | |
| 3 | 新增:using System.Text.Json; | |
| 4 | 新增:using System.Text.Json.Nodes; | |
| 5 | 新增:using System.Text.Json.Serialization; | |
| 6 | 新增: | |
| 7 | 新增:namespace Cage.GuestClipboard; | |
| 8 | 新增: | |
| 9 | 新增:internal sealed class WindowsProfile | |
| 10 | 新增:{ | |
| 11 | 新增: [JsonPropertyName("version")] public int Version { get; set; } | |
| 12 | 新增: [JsonPropertyName("vm_id")] public Guid VM { get; set; } | |
| 13 | 新增: [JsonPropertyName("gui_user_sid")] public string SID { get; set; } = ""; | |
| 14 | 新增: [JsonPropertyName("gui_user")] public string? User { get; set; } | |
| 15 | 新增: [JsonPropertyName("instance_directory")] public string Directory { get; set; } = ""; | |
| 16 | 新增: [JsonPropertyName("relay_executable")] public string Executable { get; set; } = ""; | |
| 17 | 新增: [JsonPropertyName("pairing_file")] public string Pairing { get; set; } = ""; | |
| 18 | 新增: [JsonPropertyName("network_pairing_file")] public string? NetworkPairing { get; set; } | |
| 19 | 新增: internal static WindowsProfile Load(string file) | |
| 20 | 新增: { | |
| 21 | 新增: PairingPrivate(file); | |
| 22 | 新增: var p = JsonSerializer.Deserialize<WindowsProfile>(File.ReadAllBytes(file), new JsonSerializerOptions { UnmappedMemberHandling = JsonUnmappedMemberHandling.Disallow }) ?? throw new InvalidDataException(); | |
| 23 | 新增: if (p.Version != 1 || p.VM == Guid.Empty || !p.SID.StartsWith("S-1-5-21-", StringComparison.Ordinal) || | |
| 24 | 新增: new[] { p.Directory, p.Executable, p.Pairing }.Any(path => !Path.IsPathFullyQualified(path) || path.IndexOfAny(['\0', '\r', '\n']) >= 0)) throw new InvalidDataException("profile_invalid"); | |
| 25 | 新增: if (p.NetworkPairing != null && (!Path.IsPathFullyQualified(p.NetworkPairing) || p.NetworkPairing.IndexOfAny(['\0', '\r', '\n']) >= 0)) throw new InvalidDataException("profile_invalid"); | |
| 26 | 新增: return p; | |
| 27 | 新增: } | |
| 28 | 新增: static void PairingPrivate(string file) => GuestClipboard.Pairing.PrivateFile(file); | |
| 29 | 新增:} | |
| 30 | 新增: | |
| 31 | 新增:internal static class Relay | |
| 32 | 新增:{ | |
| 33 | 新增: internal static string Phase { get; private set; } = "startup"; | |
| 34 | 新增: internal static async Task Run(string[] args) | |
| 35 | 新增: { | |
| 36 | 新增: if (args.Length is < 3 or > 4 || !GuestOperations.Names.Contains(args[2]) || args.Length == 4 && !(args[2] == "export" && args[3] == "--paths-stdin")) throw new InvalidDataException("command_invalid"); | |
| 37 | 新增: Phase = "profile"; var profile = WindowsProfile.Load(args[1]); var operation = args[2]; | |
| 38 | 新增: Phase = "pairing"; | |
| 39 | 新增: var privilegedNetwork = operation is "network-stream" or "network-settings"; | |
| 40 | 新增: var pairing = privilegedNetwork ? profile.NetworkPairing ?? throw new InvalidDataException("network_pairing_unavailable") : profile.Pairing; | |
| 41 | 新增: var service = privilegedNetwork ? NetworkRuntime.Service : Protocol.Service; | |
| 42 | 新增: var secret = Pairing.Load(pairing, profile.VM, profile.SID, true); | |
| 43 | 新增: using var socket = HyperVEndPoint.Socket(); | |
| 44 | 新增: using var lifetime = new CancellationTokenSource(); | |
| 45 | 新增: Console.CancelKeyPress += (_, e) => { e.Cancel = true; lifetime.Cancel(); socket.Dispose(); }; | |
| 46 | 新增: using var connect = CancellationTokenSource.CreateLinkedTokenSource(lifetime.Token); connect.CancelAfter(TimeSpan.FromSeconds(10)); | |
| 47 | 新增: try | |
| 48 | 新增: { | |
| 49 | 新增: Phase = "connect"; | |
| 50 | 新增: // ConnectEx used by Socket.ConnectAsync is not supported by the | |
| 51 | 新增: // Hyper-V provider. Basic Winsock Connect supports AF_HYPERV; close | |
| 52 | 新增: // the socket to interrupt the bounded connect when canceled. | |
| 53 | 新增: using (connect.Token.Register(socket.Dispose)) | |
| 54 | 新增: await Task.Run(() => socket.Connect(new HyperVEndPoint(profile.VM, service)), CancellationToken.None).WaitAsync(connect.Token); | |
| 55 | 新增: using var network = new NetworkStream(socket, false); using var stream = new ReadAheadStream(network); | |
| 56 | 新增: Phase = "server_proof"; var challenge = await Protocol.Read(stream, 4096, connect.Token) ?? throw new EndOfStreamException(); | |
| 57 | 新增: var nonce = challenge["nonce"]?.GetValue<string>() ?? ""; var session = challenge["session"]?.GetValue<string>() ?? ""; | |
| 58 | 新增: if (challenge["vm_id"]?.GetValue<string>() != profile.VM.ToString("D") || challenge["sid"]?.GetValue<string>() != profile.SID || | |
| 59 | 新增: !Protocol.EqualProof(Protocol.Proof(secret, "server", nonce, profile.VM, profile.SID, session, "", null), challenge["proof"]?.GetValue<string>())) throw new InvalidDataException("pairing_invalid"); | |
| 60 | 新增: JsonNode? paths = null; | |
| 61 | 新增: if (operation == "export") | |
| 62 | 新增: { | |
| 63 | 新增: using var input = new MemoryStream(); var buffer = new byte[64 << 10]; int n; | |
| 64 | 新增: var source = Console.OpenStandardInput(); | |
| 65 | 新增: while ((n = await source.ReadAsync(buffer, lifetime.Token)) > 0) | |
| 66 | 新增: { if (input.Length + n > Protocol.PathLimit) throw new InvalidDataException("selection_limit"); input.Write(buffer, 0, n); } | |
| 67 | 新增: paths = JsonNode.Parse(input.ToArray()); Protocol.Paths(paths); | |
| 68 | 新增: } | |
| 69 | 新增: Phase = "client_proof"; await Protocol.Write(stream, new() { ["vm_id"] = profile.VM.ToString("D"), ["sid"] = profile.SID, ["operation"] = operation, | |
| 70 | 新增: ["paths"] = paths, ["proof"] = Protocol.Proof(secret, "client", nonce, profile.VM, profile.SID, session, operation, paths) }, connect.Token); | |
| 71 | 新增: if (operation == "network-stream") connect.CancelAfter(TimeSpan.FromSeconds(20)); | |
| 72 | 新增: Phase = "hello"; var hello = await Protocol.Read(stream, 16384, connect.Token) ?? throw new EndOfStreamException(); | |
| 73 | 新增: if (hello["error"] != null || hello["version"]?.GetValue<int>() != 1 || hello["session"]?.GetValue<string>() != session) throw new IOException("guest_unavailable"); | |
| 74 | 新增: Phase = "transfer"; if (operation == "status") { await Protocol.Write(Console.OpenStandardOutput(), hello, lifetime.Token); return; } | |
| 75 | 新增: if (operation != "stream" && operation != "diagnostics" && hello["available"]?.GetValue<bool>() != true) throw new IOException("requires_gui_login"); | |
| 76 | 新增: if (operation == "import") | |
| 77 | 新增: { | |
| 78 | 新增: await Protocol.SendFrames(Console.OpenStandardInput(), stream, lifetime.Token); | |
| 79 | 新增: var result = await Protocol.Read(stream, Protocol.PathLimit, lifetime.Token) ?? throw new EndOfStreamException(); | |
| 80 | 新增: Protocol.Paths(result["paths"]); await Protocol.Write(Console.OpenStandardOutput(), result, lifetime.Token); | |
| 81 | 新增: } | |
| 82 | 新增: else if (operation == "export") | |
| 83 | 新增: { | |
| 84 | 新增: await Protocol.ReceiveFrames(stream, Console.OpenStandardOutput(), lifetime.Token); | |
| 85 | 新增: var result = await Protocol.Read(stream, 4096, lifetime.Token) ?? throw new EndOfStreamException(); | |
| 86 | 新增: if (result["complete"]?.GetValue<bool>() != true) throw new IOException("archive_incomplete"); | |
| 87 | 新增: } | |
| 88 | 新增: else | |
| 89 | 新增: { | |
| 90 | 新增: if (operation == "stream") await Protocol.Write(Console.OpenStandardOutput(), Protocol.PublicHello(hello), lifetime.Token); | |
| 91 | 新增: // Packet stdout stays exclusively binary. The host consumes | |
| 92 | 新增: // this bounded receipt before it publishes network readiness. | |
| 93 | 新增: // It follows the authenticated service's completed TUN setup. | |
| 94 | 新增: if (operation == "network-stream") | |
| 95 | 新增: { | |
| 96 | 新增: if (hello["os"]?.GetValue<string>() != "windows" || hello["network"]?.GetValue<string>() != "packet" || | |
| 97 | 新增: hello["vm_id"]?.GetValue<string>() != profile.VM.ToString("D") || hello["gui_user_sid"]?.GetValue<string>() != profile.SID) | |
| 98 | 新增: throw new IOException("network_identity_invalid"); | |
| 99 | 新增: await Protocol.Write(Console.OpenStandardError(), new() { ["network_ready"] = true, ["version"] = 1, | |
| 100 | 新增: ["vm_id"] = profile.VM.ToString("D"), ["gui_user_sid"] = profile.SID, | |
| 101 | 新增: ["session"] = session, ["network"] = "packet", ["available"] = true }, lifetime.Token); | |
| 102 | 新增: } | |
| 103 | 新增: var input = Task.Run(async () => { await Console.OpenStandardInput().CopyToAsync(stream, lifetime.Token); socket.Shutdown(SocketShutdown.Send); }); | |
| 104 | 新增: var output = stream.CopyToAsync(Console.OpenStandardOutput(), lifetime.Token); | |
| 105 | 新增: await output; lifetime.Cancel(); try { await input; } catch (OperationCanceledException) { } | |
| 106 | 新增: } | |
| 107 | 新增: } | |
| 108 | 新增: finally { CryptographicOperations.ZeroMemory(secret); } | |
| 109 | 新增: } | |
| 110 | 新增:} | |
| @@ -0,0 +1,41 @@ | ||
| 1 | 新增:using System.Diagnostics; | |
| 2 | 新增:using System.Runtime.CompilerServices; | |
| 3 | 新增:using System.Runtime.InteropServices; | |
| 4 | 新增:using System.Text.Json.Nodes; | |
| 5 | 新增: | |
| 6 | 新增:namespace Cage.GuestClipboard; | |
| 7 | 新增: | |
| 8 | 新增:internal static class ResourcesRpc | |
| 9 | 新增:{ | |
| 10 | 新增: [ModuleInitializer] | |
| 11 | 新增: internal static void Register() { if (GuestOperations.Names.Contains("resources")) GuestOperations.Register("resources", Run); } | |
| 12 | 新增: internal static async Task Run(Stream stream, CancellationToken token, Func<bool> available) | |
| 13 | 新增: { | |
| 14 | 新增: if (!available()) throw new InvalidDataException("requires_gui_login"); | |
| 15 | 新增: var input = await Protocol.Read(stream, 4096, token) ?? throw new EndOfStreamException(); | |
| 16 | 新增: if (input["action"]?.GetValue<string>() != "sample") throw new InvalidDataException("resource_operation_invalid"); | |
| 17 | 新增: if (!GetSystemTimes(out var idleBefore, out var kernelBefore, out var userBefore)) throw new InvalidDataException("resource_sample_failed"); | |
| 18 | 新增: await Task.Delay(150, token); | |
| 19 | 新增: if (!available() || !GetSystemTimes(out var idle, out var kernel, out var user)) throw new InvalidDataException("requires_gui_login"); | |
| 20 | 新增: var state = new MemoryStatus { Length = (uint)Marshal.SizeOf<MemoryStatus>() }; | |
| 21 | 新增: if (!GlobalMemoryStatusEx(ref state) || state.AvailablePhysical > state.TotalPhysical) throw new InvalidDataException("resource_sample_failed"); | |
| 22 | 新增: var total = kernel + user - kernelBefore - userBefore; | |
| 23 | 新增: var idleDelta = idle - idleBefore; | |
| 24 | 新增: var cpu = total == 0 ? 0 : Math.Clamp(100.0 * (total - Math.Min(total, idleDelta)) / total, 0, 100); | |
| 25 | 新增: var now = DateTimeOffset.UtcNow; | |
| 26 | 新增: await Protocol.Write(stream, new() | |
| 27 | 新增: { | |
| 28 | 新增: ["version"] = 1, ["pid"] = Environment.ProcessId, ["cpus"] = Environment.ProcessorCount, | |
| 29 | 新增: ["updated_at"] = now.ToString("O"), ["observed_at"] = now.ToString("O"), ["cpu_percent"] = cpu, | |
| 30 | 新增: ["guest"] = new JsonObject { ["total_bytes"] = state.TotalPhysical, ["available_bytes"] = state.AvailablePhysical }, | |
| 31 | 新增: ["unavailable_observations"] = new JsonArray("oom_kills", "memory_stall_percent", "swap_total_bytes", "swap_free_bytes", "host_pressure") | |
| 32 | 新增: }, token); | |
| 33 | 新增: } | |
| 34 | 新增: [StructLayout(LayoutKind.Sequential)] private struct MemoryStatus | |
| 35 | 新增: { | |
| 36 | 新增: internal uint Length, Load; | |
| 37 | 新增: internal ulong TotalPhysical, AvailablePhysical, TotalPageFile, AvailablePageFile, TotalVirtual, AvailableVirtual, AvailableExtendedVirtual; | |
| 38 | 新增: } | |
| 39 | 新增: [DllImport("kernel32.dll", SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] private static extern bool GlobalMemoryStatusEx(ref MemoryStatus status); | |
| 40 | 新增: [DllImport("kernel32.dll", SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] private static extern bool GetSystemTimes(out ulong idle, out ulong kernel, out ulong user); | |
| 41 | 新增:} | |
| @@ -0,0 +1,208 @@ | ||
| 1 | 新增:using System.ComponentModel; | |
| 2 | 新增:using System.Diagnostics; | |
| 3 | 新增:using System.Runtime.InteropServices; | |
| 4 | 新增:using System.Security.AccessControl; | |
| 5 | 新增:using System.Security.Cryptography; | |
| 6 | 新增:using System.Security.Principal; | |
| 7 | 新增:using Microsoft.Win32; | |
| 8 | 新增: | |
| 9 | 新增:namespace Cage.GuestClipboard; | |
| 10 | 新增: | |
| 11 | 新增:internal static class SetupAccount | |
| 12 | 新增:{ | |
| 13 | 新增: [StructLayout(LayoutKind.Sequential)] | |
| 14 | 新增: private struct UserInfo20 | |
| 15 | 新增: { | |
| 16 | 新增: public IntPtr Name, FullName, Comment; | |
| 17 | 新增: public uint Flags, UserID; | |
| 18 | 新增: } | |
| 19 | 新增: | |
| 20 | 新增: [DllImport("netapi32.dll", CharSet = CharSet.Unicode)] | |
| 21 | 新增: private static extern uint NetUserGetInfo(string? server, string user, uint level, out IntPtr buffer); | |
| 22 | 新增: [DllImport("netapi32.dll")] | |
| 23 | 新增: private static extern uint NetApiBufferFree(IntPtr buffer); | |
| 24 | 新增: | |
| 25 | 新增: // The authenticated guest status reports only the fixed setup account's | |
| 26 | 新增: // disable flag. A failed query stays unknown and cannot complete cleanup. | |
| 27 | 新增: internal static bool? Disabled() | |
| 28 | 新增: { | |
| 29 | 新增: uint result = NetUserGetInfo(null, "cagesetup", 20, out var buffer); | |
| 30 | 新增: try | |
| 31 | 新增: { | |
| 32 | 新增: if (result != 0 || buffer == IntPtr.Zero) return null; | |
| 33 | 新增: return (Marshal.PtrToStructure<UserInfo20>(buffer).Flags & 0x2) != 0; | |
| 34 | 新增: } | |
| 35 | 新增: finally { if (buffer != IntPtr.Zero) NetApiBufferFree(buffer); } | |
| 36 | 新增: } | |
| 37 | 新增:} | |
| 38 | 新增: | |
| 39 | 新增:internal static class SessionGuard | |
| 40 | 新增:{ | |
| 41 | 新增: private static readonly (int Session, SecurityIdentifier? User, bool Unprivileged) ProcessIdentity = ReadProcessIdentity(); | |
| 42 | 新增: | |
| 43 | 新增: private static (int Session, SecurityIdentifier? User, bool Unprivileged) ReadProcessIdentity() | |
| 44 | 新增: { | |
| 45 | 新增: using var identity = WindowsIdentity.GetCurrent(); | |
| 46 | 新增: using var process = Process.GetCurrentProcess(); | |
| 47 | 新增: return (process.SessionId, identity.User, | |
| 48 | 新增: !identity.IsSystem && !new WindowsPrincipal(identity).IsInRole(WindowsBuiltInRole.Administrator)); | |
| 49 | 新增: } | |
| 50 | 新增: [DllImport("user32.dll")] static extern IntPtr OpenInputDesktop(uint flags, bool inherit, uint access); | |
| 51 | 新增: [DllImport("user32.dll")] static extern bool CloseDesktop(IntPtr desktop); | |
| 52 | 新增: [DllImport("user32.dll", CharSet = CharSet.Unicode)] static extern bool GetUserObjectInformation(IntPtr handle, int index, char[] value, int bytes, out int needed); | |
| 53 | 新增: [DllImport("wtsapi32.dll", EntryPoint="WTSQuerySessionInformationW", ExactSpelling=true)] static extern bool WTSQuerySessionInformation(IntPtr server, int session, int field, out IntPtr buffer, out int bytes); | |
| 54 | 新增: [DllImport("wtsapi32.dll")] static extern void WTSFreeMemory(IntPtr buffer); | |
| 55 | 新增: [DllImport("advapi32.dll",SetLastError=true)] static extern bool OpenProcessToken(IntPtr process,uint access,out IntPtr token); | |
| 56 | 新增: [DllImport("kernel32.dll")] static extern bool CloseHandle(IntPtr handle); | |
| 57 | 新增: [DllImport("kernel32.dll", SetLastError=true)] static extern IntPtr OpenProcess(uint access, bool inherit, int pid); | |
| 58 | 新增: [DllImport("kernel32.dll", SetLastError=true)] static extern bool GetProcessTimes(IntPtr process, out long creation, out long exit, out long kernel, out long user); | |
| 59 | 新增: [DllImport("advapi32.dll", SetLastError=true)] static extern bool GetTokenInformation(IntPtr token, int field, IntPtr buffer, int size, out int needed); | |
| 60 | 新增: [DllImport("advapi32.dll")] static extern bool IsWellKnownSid(IntPtr sid, int kind); | |
| 61 | 新增: [StructLayout(LayoutKind.Sequential)] private struct Group { public IntPtr Sid; public uint Flags; } | |
| 62 | 新增: | |
| 63 | 新增: // Query only. Constructing WindowsIdentity from a TOKEN_QUERY-only foreign | |
| 64 | 新增: // handle requests a duplicate internally and can reject a standard user's | |
| 65 | 新增: // own window. Never duplicate or impersonate a process token here. | |
| 66 | 新增: private static bool InspectToken(IntPtr token, int field, Func<IntPtr, int, bool> inspect) | |
| 67 | 新增: { | |
| 68 | 新增: GetTokenInformation(token, field, IntPtr.Zero, 0, out int size); | |
| 69 | 新增: if (size <= 0 || size > 65536) return false; | |
| 70 | 新增: var buffer = Marshal.AllocHGlobal(size); | |
| 71 | 新增: try { return GetTokenInformation(token, field, buffer, size, out var used) && used > 0 && used <= size && inspect(buffer, used); } | |
| 72 | 新增: finally { Marshal.FreeHGlobal(buffer); } | |
| 73 | 新增: } | |
| 74 | 新增: | |
| 75 | 新增: internal static bool OwnsProcess(Process process) | |
| 76 | 新增: { | |
| 77 | 新增: try | |
| 78 | 新增: { | |
| 79 | 新增: if (process.HasExited || process.SessionId != ProcessIdentity.Session) return false; | |
| 80 | 新增: var handle = OpenProcess(0x1000, false, process.Id); // PROCESS_QUERY_LIMITED_INFORMATION | |
| 81 | 新增: if (handle == IntPtr.Zero) return false; | |
| 82 | 新增: try | |
| 83 | 新增: { | |
| 84 | 新增: if (!GetProcessTimes(handle, out var created, out _, out _, out _) || | |
| 85 | 新增: created != process.StartTime.ToUniversalTime().ToFileTimeUtc() || !OpenProcessToken(handle, 8, out var token)) return false; | |
| 86 | 新增: try | |
| 87 | 新增: { | |
| 88 | 新增: var user = ProcessIdentity.User; | |
| 89 | 新增: if (user == null || !InspectToken(token, 1, (p,n) => n >= IntPtr.Size && | |
| 90 | 新增: user.Equals(new SecurityIdentifier(Marshal.ReadIntPtr(p)))) || | |
| 91 | 新增: !InspectToken(token, 20, (p,n) => n == sizeof(int) && Marshal.ReadInt32(p) == 0)) return false; | |
| 92 | 新增: return InspectToken(token, 2, (p,n) => { | |
| 93 | 新增: var count = Marshal.ReadInt32(p); | |
| 94 | 新增: var offset = IntPtr.Size; | |
| 95 | 新增: var stride = Marshal.SizeOf<Group>(); | |
| 96 | 新增: if (count < 0 || count > (n-offset)/stride) return false; | |
| 97 | 新增: for (int i=0; i<count; i++) { | |
| 98 | 新增: var group=Marshal.PtrToStructure<Group>(p+offset+i*stride); | |
| 99 | 新增: if ((group.Flags & 4) != 0 && (group.Flags & 16) == 0 && IsWellKnownSid(group.Sid,26)) return false; | |
| 100 | 新增: } | |
| 101 | 新增: return true; | |
| 102 | 新增: }); | |
| 103 | 新增: } | |
| 104 | 新增: finally { CloseHandle(token); } | |
| 105 | 新增: } | |
| 106 | 新增: finally { CloseHandle(handle); } | |
| 107 | 新增: } | |
| 108 | 新增: catch { return false; } | |
| 109 | 新增: } | |
| 110 | 新增: internal static bool Available() | |
| 111 | 新增: { | |
| 112 | 新增: // Process identity is fixed at startup. Session and input-desktop | |
| 113 | 新增: // availability are still queried for each operation below. | |
| 114 | 新增: if (!Environment.UserInteractive || ProcessIdentity.Session == 0 || !ProcessIdentity.Unprivileged) return false; | |
| 115 | 新增: int session = ProcessIdentity.Session; | |
| 116 | 新增: // A locked Windows 11 console can remain WTSActive and its user | |
| 117 | 新增: // process can still see Default. Require explicit OS unlock as well. | |
| 118 | 新增: if (!WTSQuerySessionInformation(IntPtr.Zero, session, 25, out var state, out int bytes)) return false; // WTSSessionInfoEx | |
| 119 | 新增: try | |
| 120 | 新增: { | |
| 121 | 新增: // WTSINFOEXW.Data is 8-byte aligned on the win-x64 guest. Read | |
| 122 | 新增: // only the level-1 SessionId, SessionState and SessionFlags prefix. | |
| 123 | 新增: if (state == IntPtr.Zero || bytes < 20 || Marshal.ReadInt32(state) != 1 || | |
| 124 | 新增: Marshal.ReadInt32(state, 8) != session || Marshal.ReadInt32(state, 12) != 0 || | |
| 125 | 新增: Marshal.ReadInt32(state, 16) != 1) return false; // WTS_SESSIONSTATE_UNLOCK | |
| 126 | 新增: } | |
| 127 | 新增: finally { WTSFreeMemory(state); } | |
| 128 | 新增: var desktop = OpenInputDesktop(0, false, 1); | |
| 129 | 新增: if (desktop == IntPtr.Zero) return false; | |
| 130 | 新增: try { var name = new char[256]; return GetUserObjectInformation(desktop, 2, name, name.Length * 2, out _) && new string(name).TrimEnd('\0') == "Default"; } | |
| 131 | 新增: finally { CloseDesktop(desktop); } | |
| 132 | 新增: } | |
| 133 | 新增: internal static void Assert() { if (!Available()) throw new InvalidOperationException("requires_gui_login"); } | |
| 134 | 新增: internal static void Target(Guid expected, string sid) | |
| 135 | 新增: { | |
| 136 | 新增: using var identity = WindowsIdentity.GetCurrent(); | |
| 137 | 新增: if (identity.User?.Value != sid || !sid.StartsWith("S-1-5-21-", StringComparison.Ordinal)) throw new InvalidOperationException("gui_identity_mismatch"); | |
| 138 | 新增: using var key = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Virtual Machine\Guest\Parameters"); | |
| 139 | 新增: if (!Guid.TryParse(key?.GetValue("VirtualMachineId") as string, out var actual) || actual != expected || actual == Guid.Empty) | |
| 140 | 新增: throw new InvalidOperationException("guest_identity_mismatch"); | |
| 141 | 新增: Assert(); | |
| 142 | 新增: } | |
| 143 | 新增:} | |
| 144 | 新增: | |
| 145 | 新增:internal static class Pairing | |
| 146 | 新增:{ | |
| 147 | 新增: [StructLayout(LayoutKind.Sequential)] struct Blob { internal int Size; internal IntPtr Data; } | |
| 148 | 新增: [DllImport("crypt32.dll", SetLastError = true, CharSet = CharSet.Unicode)] static extern bool CryptProtectData(ref Blob input, string? description, ref Blob entropy, IntPtr reserved, IntPtr prompt, uint flags, out Blob output); | |
| 149 | 新增: [DllImport("crypt32.dll", SetLastError = true, CharSet = CharSet.Unicode)] static extern bool CryptUnprotectData(ref Blob input, IntPtr description, ref Blob entropy, IntPtr reserved, IntPtr prompt, uint flags, out Blob output); | |
| 150 | 新增: [DllImport("kernel32.dll")] static extern IntPtr LocalFree(IntPtr memory); | |
| 151 | 新增: | |
| 152 | 新增: internal static byte[] Crypt(byte[] data, Guid vm, string sid, bool protect) | |
| 153 | 新增: { | |
| 154 | 新增: var entropyBytes = SHA256.HashData(Protocol.Utf8.GetBytes("Cage.HyperV.v1:" + vm.ToString("D") + ":" + sid)); | |
| 155 | 新增: var input = new Blob { Size = data.Length, Data = Marshal.AllocHGlobal(data.Length) }; | |
| 156 | 新增: var entropy = new Blob { Size = entropyBytes.Length, Data = Marshal.AllocHGlobal(entropyBytes.Length) }; | |
| 157 | 新增: Blob output = default; | |
| 158 | 新增: try | |
| 159 | 新增: { | |
| 160 | 新增: Marshal.Copy(data, 0, input.Data, data.Length); Marshal.Copy(entropyBytes, 0, entropy.Data, entropyBytes.Length); | |
| 161 | 新增: var ok = protect ? CryptProtectData(ref input, "Cage guest pairing", ref entropy, IntPtr.Zero, IntPtr.Zero, 1, out output) | |
| 162 | 新增: : CryptUnprotectData(ref input, IntPtr.Zero, ref entropy, IntPtr.Zero, IntPtr.Zero, 1, out output); | |
| 163 | 新增: if (!ok) throw new Win32Exception(Marshal.GetLastWin32Error(), "pairing_unavailable"); | |
| 164 | 新增: var result = new byte[output.Size]; Marshal.Copy(output.Data, result, 0, result.Length); return result; | |
| 165 | 新增: } | |
| 166 | 新增: finally { if (output.Data != IntPtr.Zero) LocalFree(output.Data); Marshal.FreeHGlobal(input.Data); Marshal.FreeHGlobal(entropy.Data); } | |
| 167 | 新增: } | |
| 168 | 新增: | |
| 169 | 新增: internal static void PrivateFile(string path) | |
| 170 | 新增: { | |
| 171 | 新增: var file = new FileInfo(path); | |
| 172 | 新增: if (!file.Exists || file.Length is < 1 or > 16384 || file.Attributes.HasFlag(FileAttributes.ReparsePoint)) throw new InvalidDataException("pairing_file_invalid"); | |
| 173 | 新增: using var identity = WindowsIdentity.GetCurrent(); | |
| 174 | 新增: var allowed = new HashSet<string> { identity.User!.Value, "S-1-5-18", "S-1-5-32-544" }; | |
| 175 | 新增: var acl = file.GetAccessControl(); | |
| 176 | 新增: if (!acl.AreAccessRulesProtected) throw new InvalidDataException("pairing_permissions_invalid"); | |
| 177 | 新增: foreach (FileSystemAccessRule rule in acl.GetAccessRules(true, true, typeof(SecurityIdentifier))) | |
| 178 | 新增: if (rule.AccessControlType == AccessControlType.Allow && !allowed.Contains(rule.IdentityReference.Value)) throw new InvalidDataException("pairing_permissions_invalid"); | |
| 179 | 新增: } | |
| 180 | 新增: | |
| 181 | 新增: internal static byte[] Load(string path, Guid vm, string sid, bool encrypted) | |
| 182 | 新增: { | |
| 183 | 新增: PrivateFile(path); | |
| 184 | 新增: var bytes = File.ReadAllBytes(path); | |
| 185 | 新增: var secret = encrypted ? Crypt(bytes, vm, sid, false) : bytes; | |
| 186 | 新增: if (secret.Length != 32) throw new InvalidDataException("pairing_invalid"); | |
| 187 | 新增: return secret; | |
| 188 | 新增: } | |
| 189 | 新增: | |
| 190 | 新增: internal static void Protect(string source, string destination, Guid vm, string sid) | |
| 191 | 新增: { | |
| 192 | 新增: PrivateFile(source); | |
| 193 | 新增: var secret = File.ReadAllBytes(source); if (secret.Length != 32) throw new InvalidDataException("pairing_invalid"); | |
| 194 | 新增: try | |
| 195 | 新增: { | |
| 196 | 新增: var encrypted = Crypt(secret, vm, sid, true); | |
| 197 | 新增: using var file = new FileStream(destination, FileMode.CreateNew, FileAccess.Write, FileShare.None); | |
| 198 | 新增: var acl = new FileSecurity(); acl.SetAccessRuleProtection(true, false); | |
| 199 | 新增: using var identity = WindowsIdentity.GetCurrent(); | |
| 200 | 新增: acl.SetOwner(identity.User!); | |
| 201 | 新增: foreach (var owner in new[] { identity.User!.Value, "S-1-5-18", "S-1-5-32-544" }) | |
| 202 | 新增: acl.AddAccessRule(new FileSystemAccessRule(new SecurityIdentifier(owner), FileSystemRights.FullControl, AccessControlType.Allow)); | |
| 203 | 新增: new FileInfo(destination).SetAccessControl(acl); | |
| 204 | 新增: file.Write(encrypted); file.Flush(true); | |
| 205 | 新增: } | |
| 206 | 新增: finally { CryptographicOperations.ZeroMemory(secret); } | |
| 207 | 新增: } | |
| 208 | 新增:} | |
| @@ -0,0 +1,110 @@ | ||
| 1 | 新增:using System.Buffers.Binary; | |
| 2 | 新增:using System.Security.Cryptography; | |
| 3 | 新增:using System.Runtime.InteropServices; | |
| 4 | 新增:using System.Text.Json.Nodes; | |
| 5 | 新增: | |
| 6 | 新增:namespace Cage.GuestClipboard; | |
| 7 | 新增: | |
| 8 | 新增:internal static class SelfTest | |
| 9 | 新增:{ | |
| 10 | 新增: static void Assert(bool value) { if (!value) throw new Exception("self_test_failed"); } | |
| 11 | 新增: static void Reject(Action action) { try { action(); } catch { return; } throw new Exception("self_test_failed"); } | |
| 12 | 新增: internal static void Run() | |
| 13 | 新增: { | |
| 14 | 新增: ReceiptPublication(); | |
| 15 | 新增: var driver = Path.Combine(AppContext.BaseDirectory, "wintun.dll"); | |
| 16 | 新增: if (File.Exists(driver)) | |
| 17 | 新增: { | |
| 18 | 新增: var library = NativeLibrary.Load(driver); | |
| 19 | 新增: try | |
| 20 | 新增: { | |
| 21 | 新增: foreach (var symbol in new[] { "WintunCreateAdapter", "WintunCloseAdapter", "WintunGetAdapterLUID", "WintunStartSession", "WintunEndSession", "WintunReceivePacket", "WintunReleaseReceivePacket", "WintunAllocateSendPacket", "WintunSendPacket" }) | |
| 22 | 新增: Assert(NativeLibrary.GetExport(library, symbol) != IntPtr.Zero); | |
| 23 | 新增: } | |
| 24 | 新增: finally { NativeLibrary.Free(library); } | |
| 25 | 新增: } | |
| 26 | 新增: var vm = Guid.NewGuid(); var endpoint = new HyperVEndPoint(vm, Protocol.Service); | |
| 27 | 新增: Assert(WindowsSystemSettings.BrowserLanguage(new JsonObject { ["locale"]="zh_CN.UTF-8",["browser_language"]="en-GB" })=="en-GB"); | |
| 28 | 新增: Reject(()=>WindowsSystemSettings.BrowserLanguage(new JsonObject { ["browser_language"]="en-US';exit" })); | |
| 29 | 新增: Reject(()=>WindowsSystemSettings.BrowserLanguage(new JsonObject { ["locale"]="en_US.UTF-8" })); | |
| 30 | 新增: Assert(NativeSafetyRpc.ObservedTimezone("China Standard Time","Asia/Hong_Kong")=="Asia/Hong_Kong"); | |
| 31 | 新增: Assert(NativeSafetyRpc.ObservedTimezone("China Standard Time","America/New_York")!="America/New_York"); | |
| 32 | 新增: var publicHello = Protocol.PublicHello(new JsonObject { ["version"] = 1, ["os"] = "windows", ["available"] = true }); | |
| 33 | 新增: Assert(publicHello["hello"]?["os"]?.GetValue<string>() == "windows" && !publicHello.ContainsKey("version")); | |
| 34 | 新增: using var native = HyperVEndPoint.Socket(); | |
| 35 | 新增: var roundtrip = (HyperVEndPoint)endpoint.Create(endpoint.Serialize()); Assert(roundtrip.VM == vm && roundtrip.Service == Protocol.Service && endpoint.Serialize().Size == 36); | |
| 36 | 新增: var secret = RandomNumberGenerator.GetBytes(32); var sid = "S-1-5-21-1-2-3-1001"; | |
| 37 | 新增: var proof = Protocol.Proof(secret, "server", "nonce", vm, sid, "session", "", null); | |
| 38 | 新增: Assert(Protocol.EqualProof(proof, proof)); Assert(!Protocol.EqualProof(proof, "invalid")); | |
| 39 | 新增: Assert(!Protocol.EqualProof(proof, Protocol.Proof(secret, "client", "nonce", vm, sid, "session", "", null))); | |
| 40 | 新增: Assert(!Protocol.EqualProof(proof, Protocol.Proof(secret, "server", "nonce", Guid.NewGuid(), sid, "session", "", null))); | |
| 41 | 新增: Assert(!Protocol.EqualProof(proof, Protocol.Proof(secret, "server", "nonce", vm, sid + "2", "session", "", null))); | |
| 42 | 新增: var selection = new JsonArray(@"C:\test\中文😀.txt"); | |
| 43 | 新增: var first = Protocol.Proof(secret, "client", "nonce", vm, sid, "session", "export", selection); | |
| 44 | 新增: Assert(!Protocol.EqualProof(first, Protocol.Proof(secret, "client", "nonce", vm, sid, "session", "import", selection))); | |
| 45 | 新增: Assert(!Protocol.EqualProof(first, Protocol.Proof(secret, "client", "nonce", vm, sid, "session", "export", new JsonArray(@"C:\other.txt")))); | |
| 46 | 新增: Reject(() => Protocol.Paths(new JsonArray())); Reject(() => Protocol.Paths(new JsonArray("relative.txt"))); | |
| 47 | 新增: Assert(Protocol.Paths(selection).Length == 1); | |
| 48 | 新增: var image = new byte[33]; new byte[] { 137, 80, 78, 71, 13, 10, 26, 10 }.CopyTo(image, 0); "IHDR"u8.CopyTo(image.AsSpan(12)); | |
| 49 | 新增: BinaryPrimitives.WriteUInt32BigEndian(image.AsSpan(16, 4), 8000); BinaryPrimitives.WriteUInt32BigEndian(image.AsSpan(20, 4), 5000); Protocol.Png(image); | |
| 50 | 新增: BinaryPrimitives.WriteUInt32BigEndian(image.AsSpan(20, 4), 5001); Reject(() => Protocol.Png(image)); | |
| 51 | 新增: var data = RandomNumberGenerator.GetBytes(200_000); using var encoded = new MemoryStream(); | |
| 52 | 新增: Protocol.SendFrames(new MemoryStream(data), encoded, default).GetAwaiter().GetResult(); | |
| 53 | 新增: encoded.Position = 0; using var decoded = new MemoryStream(); Protocol.ReceiveFrames(encoded, decoded, default).GetAwaiter().GetResult(); Assert(data.SequenceEqual(decoded.ToArray())); | |
| 54 | 新增: Reject(() => Protocol.ReceiveFrames(new MemoryStream(encoded.ToArray()[..^1]), Stream.Null, default).GetAwaiter().GetResult()); | |
| 55 | 新增: Assert(AttachmentsRpc.NameValid("中文 O'Brien.txt")); | |
| 56 | 新增: foreach (var name in new[] { "../outside.txt", "CON.txt", "file.txt:stream", "trailing.", "C:\\private.txt", "bad\nname" }) Assert(!AttachmentsRpc.NameValid(name)); | |
| 57 | 新增: using (var limited = new AttachmentsRpc.LimitedWriteStream(Stream.Null, 3)) | |
| 58 | 新增: { limited.Write([1, 2, 3], 0, 3); Reject(() => limited.Write([4], 0, 1)); } | |
| 59 | 新增: using var json = new ReadAheadStream(new MemoryStream("{\"text\":\"中文😀\\nsecond\"}\n{\"ack\":2}\n"u8.ToArray())); | |
| 60 | 新增: Assert(Protocol.Read(json, 1024, default).GetAwaiter().GetResult()!["text"]!.GetValue<string>() == "中文😀\nsecond"); | |
| 61 | 新增: Assert(Protocol.Read(json, 1024, default).GetAwaiter().GetResult()!["ack"]!.GetValue<int>() == 2); | |
| 62 | 新增: using var blank=new Bitmap(240,240); | |
| 63 | 新增: using(var paint=Graphics.FromImage(blank)){paint.Clear(Color.White);paint.FillRectangle(Brushes.Black,210,0,25,16);} | |
| 64 | 新增: Assert(!ClaudeGraphicsCapture.HasContent(blank)); | |
| 65 | 新增: using(var paint=Graphics.FromImage(blank)){paint.FillRectangle(Brushes.Black,70,110,100,30);} | |
| 66 | 新增: Assert(ClaudeGraphicsCapture.HasContent(blank)); | |
| 67 | 新增: var browserFrame = new JsonObject { ["jpeg"] = "page-pixels", ["target"] = "native-window", ["sequence"] = "cdp-first", ["width"] = 800, ["height"] = 600 }; | |
| 68 | 新增: var published = BrowserWindowCapture.FrameReply((JsonObject)browserFrame.DeepClone(), null); | |
| 69 | 新增: var sequence = published["sequence"]!.GetValue<string>(); | |
| 70 | 新增: Assert(published["target"]!.GetValue<string>() == "native-window"); | |
| 71 | 新增: browserFrame["sequence"] = "cdp-next"; | |
| 72 | 新增: Assert(BrowserWindowCapture.FrameReply((JsonObject)browserFrame.DeepClone(), sequence)["unchanged"]?.GetValue<bool>() == true); | |
| 73 | 新增: browserFrame["overlays"] = new JsonArray(new JsonObject { ["png"] = "native-menu-pixels", ["x"] = 20, ["y"] = 30, ["width"] = 50, ["height"] = 60 }); | |
| 74 | 新增: var menu = BrowserWindowCapture.FrameReply((JsonObject)browserFrame.DeepClone(), sequence); | |
| 75 | 新增: Assert(menu["unchanged"] is null && menu["sequence"]!.GetValue<string>() != sequence); | |
| 76 | 新增: var withoutMenu = (JsonObject)browserFrame.DeepClone(); withoutMenu.Remove("overlays"); | |
| 77 | 新增: Assert(BrowserWindowCapture.FrameReply(withoutMenu, menu["sequence"]!.GetValue<string>())["unchanged"] is null); | |
| 78 | 新增: browserFrame["target"] = "resized-native-window"; | |
| 79 | 新增: Assert(BrowserWindowCapture.FrameReply(browserFrame, menu["sequence"]!.GetValue<string>())["unchanged"] is null); | |
| 80 | 新增: CryptographicOperations.ZeroMemory(secret); | |
| 81 | 新增: } | |
| 82 | 新增: | |
| 83 | 新增: private static void ReceiptPublication() | |
| 84 | 新增: { | |
| 85 | 新增: var directory=Path.Combine(Path.GetTempPath(),Guid.NewGuid().ToString("N")); | |
| 86 | 新增: Directory.CreateDirectory(directory); | |
| 87 | 新增: var destination=Path.Combine(directory,"receipt.json");var stage=Path.Combine(directory,"receipt.stage"); | |
| 88 | 新增: try | |
| 89 | 新增: { | |
| 90 | 新增: File.WriteAllText(destination,"old-complete"); | |
| 91 | 新增: using(var snapshot=new FileStream(destination,FileMode.Open,FileAccess.Read,FileShare.Read|FileShare.Delete)) | |
| 92 | 新增: { | |
| 93 | 新增: NetworkRuntime.PublishReceipt(stage,destination,"new-complete",default).GetAwaiter().GetResult(); | |
| 94 | 新增: using var reader=new StreamReader(snapshot); | |
| 95 | 新增: Assert(reader.ReadToEnd()=="old-complete" && File.ReadAllText(destination)=="new-complete"); | |
| 96 | 新增: } | |
| 97 | 新增: using(var blocker=File.OpenRead(destination)) | |
| 98 | 新增: { | |
| 99 | 新增: var release=Task.Run(async()=>{await Task.Delay(100);blocker.Dispose();}); | |
| 100 | 新增: try { NetworkRuntime.PublishReceipt(stage,destination,"after-short-reader",default).GetAwaiter().GetResult(); } | |
| 101 | 新增: finally { release.GetAwaiter().GetResult(); } | |
| 102 | 新增: } | |
| 103 | 新增: Assert(File.ReadAllText(destination)=="after-short-reader"); | |
| 104 | 新增: using(var blocker=File.OpenRead(destination)) | |
| 105 | 新增: Reject(()=>NetworkRuntime.PublishReceipt(stage,destination,"must-not-publish",default).GetAwaiter().GetResult()); | |
| 106 | 新增: Assert(File.ReadAllText(destination)=="after-short-reader"); | |
| 107 | 新增: } | |
| 108 | 新增: finally { Directory.Delete(directory,true); } | |
| 109 | 新增: } | |
| 110 | 新增:} | |
| @@ -0,0 +1,241 @@ | ||
| 1 | 新增:using System.ComponentModel; | |
| 2 | 新增:using System.Runtime.InteropServices; | |
| 3 | 新增:using System.Runtime.CompilerServices; | |
| 4 | 新增:using System.Text; | |
| 5 | 新增:using System.Text.Json.Nodes; | |
| 6 | 新增:using Microsoft.Win32.SafeHandles; | |
| 7 | 新增: | |
| 8 | 新增:namespace Cage.GuestClipboard; | |
| 9 | 新增: | |
| 10 | 新增:// The authenticated GUI relay owns this terminal. Commands and project paths are | |
| 11 | 新增:// never accepted from the wire; a future project grant must be resolved here. | |
| 12 | 新增:internal static class TerminalRpc | |
| 13 | 新增:{ | |
| 14 | 新增: internal sealed record Launch(string Executable, string[] Arguments, string Directory, Dictionary<string, string> Environment); | |
| 15 | 新增: private static readonly SemaphoreSlim Slots = new(12, 12); | |
| 16 | 新增: [ModuleInitializer] | |
| 17 | 新增: internal static void Register() => GuestOperations.Register("terminal", Run); | |
| 18 | 新增: internal static string PowerShellPath() | |
| 19 | 新增: { | |
| 20 | 新增: var pwsh=Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles),"PowerShell","7","pwsh.exe"); | |
| 21 | 新增: return File.Exists(pwsh)?pwsh:Path.Combine(Environment.SystemDirectory,"WindowsPowerShell","v1.0","powershell.exe"); | |
| 22 | 新增: } | |
| 23 | 新增: internal static Task Run(Stream stream, CancellationToken token, Func<bool> sessionAvailable) => RunCore(stream, token, sessionAvailable, null); | |
| 24 | 新增: internal static Task RunWithLaunch(Stream stream, CancellationToken token, Func<bool> sessionAvailable, Launch launch) => RunCore(stream, token, sessionAvailable, launch); | |
| 25 | 新增: private static async Task RunCore(Stream stream, CancellationToken token, Func<bool> sessionAvailable, Launch? launch) | |
| 26 | 新增: { | |
| 27 | 新增: if (!sessionAvailable()) throw new InvalidDataException("requires_gui_login"); | |
| 28 | 新增: if (!await Slots.WaitAsync(0, token)) throw new InvalidDataException("terminal_limit"); | |
| 29 | 新增: using var lifetime = CancellationTokenSource.CreateLinkedTokenSource(token); | |
| 30 | 新增: using var writes = new SemaphoreSlim(1, 1); | |
| 31 | 新增: NativeTerminal? terminal = null; | |
| 32 | 新增: Task? output = null, inputs = null, guard = null; | |
| 33 | 新增: Task<int>? exited = null; | |
| 34 | 新增: Action<string, string>? revoked = null; | |
| 35 | 新增: Action? projectAvailable = null; | |
| 36 | 新增: async Task Send(JsonObject value) | |
| 37 | 新增: { | |
| 38 | 新增: await writes.WaitAsync(lifetime.Token); | |
| 39 | 新增: try { await Protocol.Write(stream, value, lifetime.Token); } finally { writes.Release(); } | |
| 40 | 新增: } | |
| 41 | 新增: try | |
| 42 | 新增: { | |
| 43 | 新增: var open = await Protocol.Read(stream, 65536, lifetime.Token) ?? throw new EndOfStreamException(); | |
| 44 | 新增: if (open["action"]?.GetValue<string>() != "open" || open["shell"]?.GetValue<string>() != (launch is null ? "powershell" : "claude") || !sessionAvailable()) | |
| 45 | 新增: throw new InvalidDataException("terminal_request_invalid"); | |
| 46 | 新增: var directory = open["workspace"]?.GetValue<string>() switch | |
| 47 | 新增: { | |
| 48 | 新增: "home" => Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), | |
| 49 | 新增: "project" => ProjectRpc.Resolve(open["project_id"]?.GetValue<string>() ?? "", open["grant"]?.GetValue<string>() ?? ""), | |
| 50 | 新增: _ => throw new InvalidDataException("terminal_request_invalid") | |
| 51 | 新增: }; | |
| 52 | 新增: if (launch is not null && !Path.GetFullPath(launch.Directory).Equals(Path.GetFullPath(directory), StringComparison.OrdinalIgnoreCase)) throw new InvalidDataException("terminal_directory_invalid"); | |
| 53 | 新增: if (open["workspace"]?.GetValue<string>() == "project") | |
| 54 | 新增: { | |
| 55 | 新增: var id = open["project_id"]!.GetValue<string>(); var grant = open["grant"]!.GetValue<string>(); | |
| 56 | 新增: revoked = (removed, oldGrant) => { if (removed == id && oldGrant == grant) lifetime.Cancel(); }; | |
| 57 | 新增: ProjectRpc.Revoked += revoked; | |
| 58 | 新增: projectAvailable = () => ProjectRpc.Resolve(id, grant); | |
| 59 | 新增: projectAvailable(); | |
| 60 | 新增: } | |
| 61 | 新增: terminal = new NativeTerminal(Size(open, "cols"), Size(open, "rows"), directory, launch); | |
| 62 | 新增: await Send(new JsonObject { ["ready"] = true }); | |
| 63 | 新增: output = Task.Run(async () => | |
| 64 | 新增: { | |
| 65 | 新增: var buffer = new byte[32 << 10]; int count; | |
| 66 | 新增: // ConPTY shutdown needs a live drain even after the viewer stops. | |
| 67 | 新增: while ((count = await terminal.Output.ReadAsync(buffer, CancellationToken.None)) != 0) | |
| 68 | 新增: { | |
| 69 | 新增: if (lifetime.IsCancellationRequested) continue; | |
| 70 | 新增: try { await Send(new JsonObject { ["data"] = Convert.ToBase64String(buffer, 0, count) }); } | |
| 71 | 新增: catch { lifetime.Cancel(); } | |
| 72 | 新增: } | |
| 73 | 新增: }); | |
| 74 | 新增: inputs = Task.Run(async () => | |
| 75 | 新增: { | |
| 76 | 新增: while (await Protocol.Read(stream, 100 << 10, lifetime.Token) is { } value) | |
| 77 | 新增: { | |
| 78 | 新增: if (!sessionAvailable()) throw new InvalidDataException("requires_gui_login"); | |
| 79 | 新增: lifetime.Token.ThrowIfCancellationRequested(); projectAvailable?.Invoke(); | |
| 80 | 新增: switch (value["action"]?.GetValue<string>()) | |
| 81 | 新增: { | |
| 82 | 新增: case "input": | |
| 83 | 新增: var bytes = Convert.FromBase64String(value["data"]?.GetValue<string>() ?? ""); | |
| 84 | 新增: if (bytes.Length > 64 << 10) throw new InvalidDataException("terminal_input_limit"); | |
| 85 | 新增: await terminal.Input.WriteAsync(bytes, lifetime.Token); await terminal.Input.FlushAsync(lifetime.Token); break; | |
| 86 | 新增: case "resize": terminal.Resize(Size(value, "cols"), Size(value, "rows")); break; | |
| 87 | 新增: case "close": return; | |
| 88 | 新增: default: throw new InvalidDataException("terminal_request_invalid"); | |
| 89 | 新增: } | |
| 90 | 新增: } | |
| 91 | 新增: }, lifetime.Token); | |
| 92 | 新增: guard = Task.Run(async () => | |
| 93 | 新增: { | |
| 94 | 新增: while (!lifetime.IsCancellationRequested) | |
| 95 | 新增: { | |
| 96 | 新增: await Task.Delay(100, lifetime.Token); | |
| 97 | 新增: if (!sessionAvailable()) throw new InvalidDataException("requires_gui_login"); | |
| 98 | 新增: } | |
| 99 | 新增: }, lifetime.Token); | |
| 100 | 新增: exited = Task.Run(terminal.Wait); | |
| 101 | 新增: var first = await Task.WhenAny(inputs, exited, guard, output); | |
| 102 | 新增: if (first == exited || first == output) | |
| 103 | 新增: { | |
| 104 | 新增: if (first == output) { await output; terminal.KillOwnJob(); } | |
| 105 | 新增: var code = await exited; | |
| 106 | 新增: terminal.KillOwnJob(); | |
| 107 | 新增: terminal.CloseConsole(); | |
| 108 | 新增: await output; | |
| 109 | 新增: await Send(new JsonObject { ["exit"] = code }); | |
| 110 | 新增: } | |
| 111 | 新增: else await first; | |
| 112 | 新增: } | |
| 113 | 新增: finally | |
| 114 | 新增: { | |
| 115 | 新增: lifetime.Cancel(); terminal?.Stop(); | |
| 116 | 新增: if (revoked is not null) ProjectRpc.Revoked -= revoked; | |
| 117 | 新增: foreach (var task in new Task?[] { inputs, output, guard, exited }) | |
| 118 | 新增: if (task is not null) try { await task; } catch { /* teardown observes every worker */ } | |
| 119 | 新增: terminal?.Dispose(); Slots.Release(); | |
| 120 | 新增: } | |
| 121 | 新增: } | |
| 122 | 新增: private static short Size(JsonObject value, string name) | |
| 123 | 新增: { | |
| 124 | 新增: var size = value[name]?.GetValue<int>() ?? 0; | |
| 125 | 新增: var maximum = name == "cols" ? 599 : 500; | |
| 126 | 新增: if (size < 1 || size > maximum) throw new InvalidDataException("terminal_size_invalid"); | |
| 127 | 新增: return (short)size; | |
| 128 | 新增: } | |
| 129 | 新增: | |
| 130 | 新增: private sealed class NativeTerminal : IDisposable | |
| 131 | 新增: { | |
| 132 | 新增: internal FileStream Input { get; } | |
| 133 | 新增: internal FileStream Output { get; } | |
| 134 | 新增: private nint console, process, job; | |
| 135 | 新增: private readonly object gate = new(); | |
| 136 | 新增: private int disposed; | |
| 137 | 新增: internal NativeTerminal(short cols, short rows, string directory, Launch? launch) | |
| 138 | 新增: { | |
| 139 | 新增: SafeFileHandle? inputRead = null, inputWrite = null, outputRead = null, outputWrite = null; | |
| 140 | 新增: nint attributes = 0, environment = 0; | |
| 141 | 新增: try | |
| 142 | 新增: { | |
| 143 | 新增: Check(CreatePipe(out inputRead, out inputWrite, 0, 0)); | |
| 144 | 新增: Check(CreatePipe(out outputRead, out outputWrite, 0, 0)); | |
| 145 | 新增: Marshal.ThrowExceptionForHR(CreatePseudoConsole(new Coord(cols, rows), inputRead, outputWrite, 0, out console)); | |
| 146 | 新增: nuint bytes = 0; InitializeProcThreadAttributeList(0, 1, 0, ref bytes); | |
| 147 | 新增: attributes = Marshal.AllocHGlobal((nint)bytes); | |
| 148 | 新增: Check(InitializeProcThreadAttributeList(attributes, 1, 0, ref bytes)); | |
| 149 | 新增: Check(UpdateProcThreadAttribute(attributes, 0, 0x00020016, console, (nuint)IntPtr.Size, 0, 0)); | |
| 150 | 新增: var startup = new StartupInfoEx(); startup.Startup.cb = Marshal.SizeOf<StartupInfoEx>(); | |
| 151 | 新增: startup.Startup.flags = 0x100; startup.Attributes = attributes; | |
| 152 | 新增: var shell = PowerShellPath(); | |
| 153 | 新增: var arguments = new[] { "-NoLogo" }; | |
| 154 | 新增: if (launch is not null) | |
| 155 | 新增: { | |
| 156 | 新增: shell = launch.Executable; arguments = launch.Arguments; | |
| 157 | 新增: environment = Marshal.StringToHGlobalUni(string.Join('\0', launch.Environment.OrderBy(x => x.Key, StringComparer.OrdinalIgnoreCase).Select(x => x.Key + "=" + x.Value)) + "\0\0"); | |
| 158 | 新增: } | |
| 159 | 新增: if (!File.Exists(shell)) throw new InvalidDataException("terminal_shell_missing"); | |
| 160 | 新增: job = CreateJobObject(0, null); Check(job != 0); | |
| 161 | 新增: var limits = new JobLimits(); limits.Basic.flags = 0x2000; // KILL_ON_JOB_CLOSE | |
| 162 | 新增: Check(SetInformationJobObject(job, 9, ref limits, (uint)Marshal.SizeOf<JobLimits>())); | |
| 163 | 新增: Check(CreateProcess(shell, new StringBuilder(string.Join(' ', new[] { shell }.Concat(arguments).Select(QuoteArgument))), 0, 0, false, | |
| 164 | 新增: 0x00080000 | 0x00000400 | 0x00000004, environment, directory, ref startup, out var created)); | |
| 165 | 新增: process = created.Process; | |
| 166 | 新增: try | |
| 167 | 新增: { | |
| 168 | 新增: Check(AssignProcessToJobObject(job, process)); | |
| 169 | 新增: if (ResumeThread(created.Thread) == uint.MaxValue) throw new Win32Exception(); | |
| 170 | 新增: } | |
| 171 | 新增: catch { TerminateProcess(process, 1); throw; } | |
| 172 | 新增: finally { CloseHandle(created.Thread); } | |
| 173 | 新增: Input = new FileStream(inputWrite, FileAccess.Write, 65536, false); inputWrite = null; | |
| 174 | 新增: Output = new FileStream(outputRead, FileAccess.Read, 65536, false); outputRead = null; | |
| 175 | 新增: } | |
| 176 | 新增: catch { Dispose(); throw; } | |
| 177 | 新增: finally | |
| 178 | 新增: { | |
| 179 | 新增: inputRead?.Dispose(); inputWrite?.Dispose(); outputRead?.Dispose(); outputWrite?.Dispose(); | |
| 180 | 新增: if (attributes != 0) { DeleteProcThreadAttributeList(attributes); Marshal.FreeHGlobal(attributes); } | |
| 181 | 新增: if (environment != 0) Marshal.FreeHGlobal(environment); | |
| 182 | 新增: } | |
| 183 | 新增: } | |
| 184 | 新增: internal void Resize(short cols, short rows) { lock (gate) { if (console == 0) throw new ObjectDisposedException(nameof(NativeTerminal)); Marshal.ThrowExceptionForHR(ResizePseudoConsole(console, new Coord(cols, rows))); } } | |
| 185 | 新增: internal int Wait() | |
| 186 | 新增: { | |
| 187 | 新增: var handle = process; | |
| 188 | 新增: if (handle == 0 || WaitForSingleObject(handle, uint.MaxValue) != 0 || !GetExitCodeProcess(handle, out var code)) throw new Win32Exception(); | |
| 189 | 新增: return unchecked((int)code); | |
| 190 | 新增: } | |
| 191 | 新增: internal void CloseConsole() { lock (gate) { if (console != 0) { ClosePseudoConsole(console); console = 0; } } } | |
| 192 | 新增: internal void KillOwnJob() { lock (gate) { if (job != 0) { CloseHandle(job); job = 0; } } } | |
| 193 | 新增: internal void Stop() | |
| 194 | 新增: { | |
| 195 | 新增: if (Interlocked.Exchange(ref disposed, 1) != 0) return; | |
| 196 | 新增: KillOwnJob(); | |
| 197 | 新增: Input?.Dispose(); | |
| 198 | 新增: // Keep output readable until ConPTY flushes; the active output pump drains it. | |
| 199 | 新增: CloseConsole(); Output?.Dispose(); | |
| 200 | 新增: } | |
| 201 | 新增: public void Dispose() | |
| 202 | 新增: { | |
| 203 | 新增: Stop(); | |
| 204 | 新增: if (process != 0) { CloseHandle(process); process = 0; } | |
| 205 | 新增: } | |
| 206 | 新增: private static void Check(bool value) { if (!value) throw new Win32Exception(Marshal.GetLastWin32Error()); } | |
| 207 | 新增: } | |
| 208 | 新增: internal static string QuoteArgument(string value) | |
| 209 | 新增: { | |
| 210 | 新增: var result = new StringBuilder("\""); int slashes = 0; | |
| 211 | 新增: foreach (var c in value) | |
| 212 | 新增: { | |
| 213 | 新增: if (c == '\\') { slashes++; continue; } | |
| 214 | 新增: result.Append('\\', c == '"' ? slashes * 2 + 1 : slashes); result.Append(c); slashes = 0; | |
| 215 | 新增: } | |
| 216 | 新增: return result.Append('\\', slashes * 2).Append('"').ToString(); | |
| 217 | 新增: } | |
| 218 | 新增: [StructLayout(LayoutKind.Sequential)] private readonly struct Coord(short x, short y) { internal readonly short X = x, Y = y; } | |
| 219 | 新增: [StructLayout(LayoutKind.Sequential)] private struct StartupInfo { internal int cb; internal nint reserved, desktop, title; internal int x,y,xSize,ySize,xChars,yChars,fill,flags; internal short show,reserved2Size; internal nint reserved2,input,output,error; } | |
| 220 | 新增: [StructLayout(LayoutKind.Sequential)] private struct StartupInfoEx { internal StartupInfo Startup; internal nint Attributes; } | |
| 221 | 新增: [StructLayout(LayoutKind.Sequential)] private struct ProcessInfo { internal nint Process, Thread; internal uint ProcessId, ThreadId; } | |
| 222 | 新增: [StructLayout(LayoutKind.Sequential)] private struct BasicLimits { internal long processTime,jobTime; internal uint flags; internal nuint minWorkingSet,maxWorkingSet; internal uint activeProcessLimit; internal nuint affinity; internal uint priority,scheduling; } | |
| 223 | 新增: [StructLayout(LayoutKind.Sequential)] private struct IoCounters { internal ulong readOperations,writeOperations,otherOperations,readBytes,writeBytes,otherBytes; } | |
| 224 | 新增: [StructLayout(LayoutKind.Sequential)] private struct JobLimits { internal BasicLimits Basic; internal IoCounters Io; internal nuint processMemory,jobMemory,peakProcessMemory,peakJobMemory; } | |
| 225 | 新增: [DllImport("kernel32.dll",SetLastError=true)] [return:MarshalAs(UnmanagedType.Bool)] private static extern bool CreatePipe(out SafeFileHandle read,out SafeFileHandle write,nint attributes,uint size); | |
| 226 | 新增: [DllImport("kernel32.dll")] private static extern int CreatePseudoConsole(Coord size,SafeFileHandle input,SafeFileHandle output,uint flags,out nint console); | |
| 227 | 新增: [DllImport("kernel32.dll")] private static extern int ResizePseudoConsole(nint console,Coord size); | |
| 228 | 新增: [DllImport("kernel32.dll")] private static extern void ClosePseudoConsole(nint console); | |
| 229 | 新增: [DllImport("kernel32.dll",SetLastError=true)] [return:MarshalAs(UnmanagedType.Bool)] private static extern bool InitializeProcThreadAttributeList(nint list,int count,uint flags,ref nuint size); | |
| 230 | 新增: [DllImport("kernel32.dll",SetLastError=true)] [return:MarshalAs(UnmanagedType.Bool)] private static extern bool UpdateProcThreadAttribute(nint list,uint flags,nuint attribute,nint value,nuint size,nint previous,nint returned); | |
| 231 | 新增: [DllImport("kernel32.dll")] private static extern void DeleteProcThreadAttributeList(nint list); | |
| 232 | 新增: [DllImport("kernel32.dll",CharSet=CharSet.Unicode,SetLastError=true)] [return:MarshalAs(UnmanagedType.Bool)] private static extern bool CreateProcess(string app,StringBuilder command,nint processAttributes,nint threadAttributes,bool inherit,uint flags,nint environment,string directory,ref StartupInfoEx startup,out ProcessInfo process); | |
| 233 | 新增: [DllImport("kernel32.dll",CharSet=CharSet.Unicode,SetLastError=true)] private static extern nint CreateJobObject(nint attributes,string? name); | |
| 234 | 新增: [DllImport("kernel32.dll",SetLastError=true)] [return:MarshalAs(UnmanagedType.Bool)] private static extern bool SetInformationJobObject(nint job,int kind,ref JobLimits limits,uint size); | |
| 235 | 新增: [DllImport("kernel32.dll",SetLastError=true)] [return:MarshalAs(UnmanagedType.Bool)] private static extern bool AssignProcessToJobObject(nint job,nint process); | |
| 236 | 新增: [DllImport("kernel32.dll",SetLastError=true)] private static extern uint ResumeThread(nint thread); | |
| 237 | 新增: [DllImport("kernel32.dll",SetLastError=true)] [return:MarshalAs(UnmanagedType.Bool)] private static extern bool TerminateProcess(nint process,uint code); | |
| 238 | 新增: [DllImport("kernel32.dll",SetLastError=true)] private static extern uint WaitForSingleObject(nint handle,uint milliseconds); | |
| 239 | 新增: [DllImport("kernel32.dll",SetLastError=true)] [return:MarshalAs(UnmanagedType.Bool)] private static extern bool GetExitCodeProcess(nint process,out uint code); | |
| 240 | 新增: [DllImport("kernel32.dll")] [return:MarshalAs(UnmanagedType.Bool)] private static extern bool CloseHandle(nint handle); | |
| 241 | 新增:} | |
| @@ -0,0 +1,294 @@ | ||
| 1 | 新增:using System.Buffers.Binary; | |
| 2 | 新增:using System.Diagnostics; | |
| 3 | 新增:using System.Runtime.CompilerServices; | |
| 4 | 新增:using System.Runtime.InteropServices; | |
| 5 | 新增:using System.Text.Json.Nodes; | |
| 6 | 新增: | |
| 7 | 新增:namespace Cage.GuestClipboard; | |
| 8 | 新增: | |
| 9 | 新增:// Output-only PCM for the paired GUI agent's tree and the registered Claude | |
| 10 | 新增:// app. It never activates a microphone or system/endpoint-wide loopback. | |
| 11 | 新增:internal static class WindowsAudioRpc | |
| 12 | 新增:{ | |
| 13 | 新增: private static readonly SemaphoreSlim Slots = new(4, 4); | |
| 14 | 新增: private const int SampleRate = 48000, Channels = 2, Samples = 960 * Channels; | |
| 15 | 新增: [ModuleInitializer] internal static void Register() | |
| 16 | 新增: { | |
| 17 | 新增: if (GuestOperations.Names.Contains("audio") && Environment.OSVersion.Version.Build >= 20348) | |
| 18 | 新增: GuestOperations.Register("audio", Run); | |
| 19 | 新增: } | |
| 20 | 新增: internal sealed class Target : IDisposable | |
| 21 | 新增: { | |
| 22 | 新增: internal Process Process { get; } | |
| 23 | 新增: internal long Started { get; } | |
| 24 | 新增: private readonly string executable; | |
| 25 | 新增: private readonly int session; | |
| 26 | 新增: internal Target(Process process, string path) | |
| 27 | 新增: { | |
| 28 | 新增: Process = process; Started = process.StartTime.ToUniversalTime().Ticks; executable = path; | |
| 29 | 新增: using var current = System.Diagnostics.Process.GetCurrentProcess(); session = current.SessionId; | |
| 30 | 新增: try { Validate(); } catch { Process.Dispose(); throw; } | |
| 31 | 新增: } | |
| 32 | 新增: internal void Validate() | |
| 33 | 新增: { | |
| 34 | 新增: if (!SessionGuard.Available() || !SessionGuard.OwnsProcess(Process) || Process.HasExited || Process.StartTime.ToUniversalTime().Ticks != Started || | |
| 35 | 新增: Process.SessionId != session || | |
| 36 | 新增: !string.Equals(Process.MainModule?.FileName, executable, StringComparison.OrdinalIgnoreCase)) | |
| 37 | 新增: throw new InvalidDataException("audio_target_changed"); | |
| 38 | 新增: } | |
| 39 | 新增: public void Dispose() => Process.Dispose(); | |
| 40 | 新增: } | |
| 41 | 新增: internal static async Task Run(Stream stream, CancellationToken token, Func<bool> available) | |
| 42 | 新增: { | |
| 43 | 新增: var request = await Protocol.Read(stream, 4096, token) ?? throw new EndOfStreamException(); | |
| 44 | 新增: if (request.Count != 1 || request["action"]?.GetValue<string>() is not ("status" or "capture")) throw new InvalidDataException("audio_request_invalid"); | |
| 45 | 新增: if (!available()) throw new InvalidDataException("requires_gui_login"); | |
| 46 | 新增: if (!await Slots.WaitAsync(0, token)) throw new InvalidDataException("audio_capture_limit"); | |
| 47 | 新增: var began = false; | |
| 48 | 新增: try | |
| 49 | 新增: { | |
| 50 | 新增: // A native activation can finish late. This bounded worker retains | |
| 51 | 新增: // its slot and callback/parameters until Windows actually completes. | |
| 52 | 新增: await Task.Factory.StartNew(() => Worker(stream, request["action"]!.GetValue<string>(), token, available, () => began = true), | |
| 53 | 新增: CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default); | |
| 54 | 新增: } | |
| 55 | 新增: catch (Exception) when (began) { /* Close PCM without appending a JSON error as sound. */ } | |
| 56 | 新增: finally { Slots.Release(); } | |
| 57 | 新增: } | |
| 58 | 新增: private static void Worker(Stream output, string action, CancellationToken token, Func<bool> available, Action began) | |
| 59 | 新增: { | |
| 60 | 新增: if(action=="status"){StatusDiagnostic(output,token,available);return;} | |
| 61 | 新增: Marshal.ThrowExceptionForHR(CoInitializeEx(0, 0)); | |
| 62 | 新增: try | |
| 63 | 新增: { | |
| 64 | 新增: token.ThrowIfCancellationRequested(); if (!available()) throw new InvalidDataException("requires_gui_login"); | |
| 65 | 新增: var endpoints = RenderEndpoints(); | |
| 66 | 新增: using var process = Process.GetCurrentProcess(); | |
| 67 | 新增: using var owner = new Target(Process.GetProcessById(process.Id), process.MainModule!.FileName!); | |
| 68 | 新增: var sources = new List<Source>(); | |
| 69 | 新增: try | |
| 70 | 新增: { | |
| 71 | 新增: sources.Add(new Source(new Target(Process.GetProcessById(owner.Process.Id), owner.Process.MainModule!.FileName!), token)); | |
| 72 | 新增: RefreshClaude(sources, owner, token); | |
| 73 | 新增: Protocol.Write(output, new JsonObject { ["ready"] = true, ["format"] = "s16le", ["sample_rate"] = SampleRate, | |
| 74 | 新增: ["channels"] = Channels, ["render_endpoints"] = endpoints, ["requires_render_stream"] = true }, token).GetAwaiter().GetResult(); | |
| 75 | 新增: began(); | |
| 76 | 新增: var clock = Stopwatch.StartNew(); var next = 20L; var refresh = 1000L; | |
| 77 | 新增: var mixed = new int[Samples]; var packet = new byte[Samples * 2]; | |
| 78 | 新增: while (true) | |
| 79 | 新增: { | |
| 80 | 新增: token.ThrowIfCancellationRequested(); if (!available()) throw new InvalidDataException("requires_gui_login"); owner.Validate(); | |
| 81 | 新增: for (var i = sources.Count - 1; i >= 0; i--) | |
| 82 | 新增: { | |
| 83 | 新增: try { sources[i].Drain(); } | |
| 84 | 新增: catch (InvalidDataException) when (i != 0) { sources[i].Dispose(); sources.RemoveAt(i); refresh = 0; } | |
| 85 | 新增: } | |
| 86 | 新增: if (clock.ElapsedMilliseconds >= refresh) { RefreshClaude(sources, owner, token); refresh = clock.ElapsedMilliseconds + 1000; } | |
| 87 | 新增: var remaining = next - clock.ElapsedMilliseconds; | |
| 88 | 新增: if (remaining > 0 && token.WaitHandle.WaitOne((int)Math.Min(remaining, 20))) token.ThrowIfCancellationRequested(); | |
| 89 | 新增: if (clock.ElapsedMilliseconds < next) continue; | |
| 90 | 新增: Array.Clear(mixed); | |
| 91 | 新增: foreach (var source in sources) { source.Target.Validate(); source.Mix(mixed); } | |
| 92 | 新增: for (var i = 0; i < Samples; i++) BinaryPrimitives.WriteInt16LittleEndian(packet.AsSpan(i * 2), (short)Math.Clamp(mixed[i], short.MinValue, short.MaxValue)); | |
| 93 | 新增: owner.Validate(); output.WriteAsync(packet, token).GetAwaiter().GetResult(); | |
| 94 | 新增: next += 20; if (next < clock.ElapsedMilliseconds - 100) next = clock.ElapsedMilliseconds + 20; | |
| 95 | 新增: } | |
| 96 | 新增: } | |
| 97 | 新增: finally { foreach (var source in sources) source.Dispose(); } | |
| 98 | 新增: } | |
| 99 | 新增: finally { CoUninitialize(); } | |
| 100 | 新增: } | |
| 101 | 新增: private static void StatusDiagnostic(Stream output,CancellationToken token,Func<bool> available) | |
| 102 | 新增: { | |
| 103 | 新增: var stage="com_initialize";bool initialized=false; | |
| 104 | 新增: object? enumerator=null;IMMDeviceCollection? devices=null; | |
| 105 | 新增: try | |
| 106 | 新增: { | |
| 107 | 新增: Marshal.ThrowExceptionForHR(CoInitializeEx(0,0));initialized=true; | |
| 108 | 新增: token.ThrowIfCancellationRequested();if(!available())throw new InvalidDataException("requires_gui_login"); | |
| 109 | 新增: stage="render_activate";enumerator=Activator.CreateInstance(Type.GetTypeFromCLSID(new Guid("BCDE0395-E52F-467C-8E3D-C4579291692E"))!); | |
| 110 | 新增: stage="render_enumerate";Marshal.ThrowExceptionForHR(((IMMDeviceEnumerator)enumerator!).EnumAudioEndpoints(0,1,out devices)); | |
| 111 | 新增: stage="render_count";Marshal.ThrowExceptionForHR(devices.GetCount(out var count)); | |
| 112 | 新增: stage="audio_service";var audio=ServiceState("Audiosrv",out var audioCode); | |
| 113 | 新增: stage="endpoint_service";var endpoint=ServiceState("AudioEndpointBuilder",out var endpointCode); | |
| 114 | 新增: token.ThrowIfCancellationRequested();if(!available())throw new InvalidDataException("requires_gui_login"); | |
| 115 | 新增: stage="status_emit"; | |
| 116 | 新增: Protocol.Write(output,new JsonObject { ["supported"]=Environment.OSVersion.Version.Build>=20348,["format"]="s16le",["sample_rate"]=SampleRate,["channels"]=Channels,["render_endpoints"]=checked((int)count),["audio_service"]=audio,["endpoint_service"]=endpoint,["audio_service_native_code"]=audioCode.ToString("X8"),["endpoint_service_native_code"]=endpointCode.ToString("X8"),["requires_render_stream"]=true },token).GetAwaiter().GetResult(); | |
| 117 | 新增: } | |
| 118 | 新增: catch(Exception error) when(error is not OperationCanceledException) | |
| 119 | 新增: { | |
| 120 | 新增: Protocol.Write(output,new JsonObject { ["error"]="audio_status_unavailable",["stage"]=stage,["native_code"]=unchecked((uint)error.HResult).ToString("X8"),["exception_type"]=error.GetType().Name },token).GetAwaiter().GetResult(); | |
| 121 | 新增: } | |
| 122 | 新增: finally | |
| 123 | 新增: { | |
| 124 | 新增: if(devices!=null)Marshal.ReleaseComObject(devices); | |
| 125 | 新增: if(enumerator!=null)Marshal.ReleaseComObject(enumerator); | |
| 126 | 新增: if(initialized)CoUninitialize(); | |
| 127 | 新增: } | |
| 128 | 新增: } | |
| 129 | 新增: internal static JsonObject ComponentStatus() | |
| 130 | 新增: { | |
| 131 | 新增: var supported=Environment.OSVersion.Version.Build>=20348; | |
| 132 | 新增: if(!supported)return new JsonObject{["supported"]=false,["installed"]=false,["ready"]=false,["reason"]="audio_os_unsupported"}; | |
| 133 | 新增: using var memory=new MemoryStream();StatusDiagnostic(memory,CancellationToken.None,SessionGuard.Available); | |
| 134 | 新增: var state=JsonNode.Parse(memory.ToArray())as JsonObject??throw new InvalidDataException("audio_status_unavailable"); | |
| 135 | 新增: var result=new JsonObject{["supported"]=true,["installed"]=true,["ready"]=false,["reason"]="audio_status_unavailable"}; | |
| 136 | 新增: foreach(var field in new[]{"stage","native_code","audio_service_native_code","endpoint_service_native_code"}) | |
| 137 | 新增: if(state[field]!=null)result[field]=state[field]!.DeepClone(); | |
| 138 | 新增: if(state["supported"]?.GetValue<bool>()==true) | |
| 139 | 新增: { | |
| 140 | 新增: var services=state["audio_service"]?.GetValue<string>()=="running"&&state["endpoint_service"]?.GetValue<string>()=="running"; | |
| 141 | 新增: var endpoints=(state["render_endpoints"]?.GetValue<int>()??0)>0; | |
| 142 | 新增: result["ready"]=services&&endpoints;result["reason"]=!services?"audio_services_unavailable":!endpoints?"no_active_render_endpoint":""; | |
| 143 | 新增: } | |
| 144 | 新增: return result; | |
| 145 | 新增: } | |
| 146 | 新增: private static void RefreshClaude(List<Source> sources, Target owner, CancellationToken token) | |
| 147 | 新增: { | |
| 148 | 新增: var target = ClaudeWindowRpc.AudioTarget(); | |
| 149 | 新增: if (target is null) return; | |
| 150 | 新增: try | |
| 151 | 新增: { | |
| 152 | 新增: if (IsDescendant(target.Process, owner.Process) || sources.Any(s => s.Target.Process.Id == target.Process.Id && s.Target.Started == target.Started)) return; | |
| 153 | 新增: for (var i = sources.Count - 1; i > 0; i--) { sources[i].Dispose(); sources.RemoveAt(i); } | |
| 154 | 新增: sources.Add(new Source(target, token)); target = null; | |
| 155 | 新增: } | |
| 156 | 新增: finally { target?.Dispose(); } | |
| 157 | 新增: } | |
| 158 | 新增: private static bool IsDescendant(Process child, Process ancestor) | |
| 159 | 新增: { | |
| 160 | 新增: var seen = new HashSet<int>(); var pid = child.Id; var started = child.StartTime.ToUniversalTime(); | |
| 161 | 新增: while (seen.Add(pid)) | |
| 162 | 新增: { | |
| 163 | 新增: if (pid == ancestor.Id) return started == ancestor.StartTime.ToUniversalTime(); | |
| 164 | 新增: using var current = Process.GetProcessById(pid); | |
| 165 | 新增: if (NtQueryInformationProcess(current.Handle, 0, out var basic, (uint)Marshal.SizeOf<ProcessBasic>(), out _) != 0) throw new InvalidDataException("audio_target_ancestry_unavailable"); | |
| 166 | 新增: pid = checked((int)basic.Parent.ToInt64()); if (pid < 1) return false; | |
| 167 | 新增: try { using var parent = Process.GetProcessById(pid); if (parent.StartTime.ToUniversalTime() > started) throw new InvalidDataException("audio_target_ancestry_unavailable"); started = parent.StartTime.ToUniversalTime(); } | |
| 168 | 新增: catch (ArgumentException) { throw new InvalidDataException("audio_target_ancestry_unavailable"); } | |
| 169 | 新增: } | |
| 170 | 新增: return false; | |
| 171 | 新增: } | |
| 172 | 新增: private sealed class Source : IDisposable | |
| 173 | 新增: { | |
| 174 | 新增: internal Target Target { get; } | |
| 175 | 新增: private IAudioClient? client; private IAudioCaptureClient? capture; | |
| 176 | 新增: private readonly EventWaitHandle ready = new(false, EventResetMode.AutoReset); | |
| 177 | 新增: private readonly short[] ring = new short[SampleRate * Channels / 5]; | |
| 178 | 新增: private int read, count; private bool started; | |
| 179 | 新增: internal Source(Target target, CancellationToken token) | |
| 180 | 新增: { | |
| 181 | 新增: Target = target; | |
| 182 | 新增: try | |
| 183 | 新增: { | |
| 184 | 新增: target.Validate(); client = Activate(target.Process.Id); | |
| 185 | 新增: token.ThrowIfCancellationRequested(); target.Validate(); | |
| 186 | 新增: var format = new WaveFormat { Tag = 1, Channels = Channels, Rate = SampleRate, Average = SampleRate * Channels * 2, Align = Channels * 2, Bits = 16, Extra = 0 }; | |
| 187 | 新增: Check(client.Initialize(0, 0x80000000u | 0x00020000u | 0x00040000u, 0, 0, ref format, 0)); | |
| 188 | 新增: Check(client.SetEventHandle(ready.SafeWaitHandle.DangerousGetHandle())); | |
| 189 | 新增: Check(client.GetBufferSize(out var frames)); if (frames is < 1 or > SampleRate) throw new InvalidDataException("audio_buffer_invalid"); | |
| 190 | 新增: var id = typeof(IAudioCaptureClient).GUID; Check(client.GetService(ref id, out var service)); capture = (IAudioCaptureClient)service; | |
| 191 | 新增: target.Validate(); Check(client.Start()); started = true; | |
| 192 | 新增: } | |
| 193 | 新增: catch { Dispose(); throw; } | |
| 194 | 新增: } | |
| 195 | 新增: internal void Drain() | |
| 196 | 新增: { | |
| 197 | 新增: Target.Validate(); ready.WaitOne(0); var batches = 0; | |
| 198 | 新增: while (true) | |
| 199 | 新增: { | |
| 200 | 新增: Check(capture!.GetNextPacketSize(out var next)); if (next == 0) return; | |
| 201 | 新增: if (++batches > 100 || next > SampleRate) throw new InvalidDataException("audio_buffer_invalid"); | |
| 202 | 新增: Check(capture.GetBuffer(out var data, out var frames, out var flags, out _, out _)); | |
| 203 | 新增: try | |
| 204 | 新增: { | |
| 205 | 新增: if (frames > SampleRate || (data == 0 && (flags & 2) == 0)) throw new InvalidDataException("audio_buffer_invalid"); | |
| 206 | 新增: Target.Validate(); if ((flags & 1) != 0) { read = count = 0; } | |
| 207 | 新增: var values = new short[checked((int)frames * Channels)]; if ((flags & 2) == 0) Marshal.Copy(data, values, 0, values.Length); | |
| 208 | 新增: Target.Validate(); | |
| 209 | 新增: foreach (var value in values) { if (count == ring.Length) { read = (read + 1) % ring.Length; count--; } ring[(read + count++) % ring.Length] = value; } | |
| 210 | 新增: } | |
| 211 | 新增: finally { Check(capture.ReleaseBuffer(frames)); } | |
| 212 | 新增: } | |
| 213 | 新增: } | |
| 214 | 新增: internal void Mix(int[] output) | |
| 215 | 新增: { | |
| 216 | 新增: for (var i = 0; i < output.Length && count != 0; i++) { output[i] += ring[read]; read = (read + 1) % ring.Length; count--; } | |
| 217 | 新增: } | |
| 218 | 新增: public void Dispose() | |
| 219 | 新增: { | |
| 220 | 新增: if (started) { client?.Stop(); started = false; } | |
| 221 | 新增: if (capture is not null) { Marshal.ReleaseComObject(capture); capture = null; } | |
| 222 | 新增: if (client is not null) { Marshal.ReleaseComObject(client); client = null; } | |
| 223 | 新增: ready.Dispose(); Target.Dispose(); | |
| 224 | 新增: } | |
| 225 | 新增: } | |
| 226 | 新增: private static IAudioClient Activate(int pid) | |
| 227 | 新增: { | |
| 228 | 新增: var data = Marshal.AllocHGlobal(12); IActivateOperation? operation = null; | |
| 229 | 新增: var callback = new Completion(); | |
| 230 | 新增: try | |
| 231 | 新增: { | |
| 232 | 新增: Marshal.WriteInt32(data, 1); Marshal.WriteInt32(data, 4, pid); Marshal.WriteInt32(data, 8, 0); // include target tree only | |
| 233 | 新增: var value = new Variant { Type = 65, Bytes = 12, Data = data }; var iid = typeof(IAudioClient).GUID; | |
| 234 | 新增: Check(ActivateAudioInterfaceAsync("VAD\\Process_Loopback", ref iid, ref value, callback, out operation)); | |
| 235 | 新增: var result = callback.Done.Task.GetAwaiter().GetResult(); Check(result.Result); return result.Client ?? throw new InvalidDataException("audio_activation_failed"); | |
| 236 | 新增: } | |
| 237 | 新增: finally { GC.KeepAlive(callback); if (operation is not null) Marshal.ReleaseComObject(operation); Marshal.FreeHGlobal(data); } | |
| 238 | 新增: } | |
| 239 | 新增: [ComVisible(true), ClassInterface(ClassInterfaceType.None)] private sealed class Completion : ICompletion, IAgile | |
| 240 | 新增: { | |
| 241 | 新增: internal readonly TaskCompletionSource<(int Result, IAudioClient? Client)> Done = new(TaskCreationOptions.RunContinuationsAsynchronously); | |
| 242 | 新增: public int ActivateCompleted(IActivateOperation operation) | |
| 243 | 新增: { | |
| 244 | 新增: try { var result = operation.GetActivateResult(out var activated, out var audio); if (result >= 0) result = activated; Done.TrySetResult((result, result >= 0 ? (IAudioClient)audio : null)); } | |
| 245 | 新增: catch (Exception e) { Done.TrySetResult((Marshal.GetHRForException(e), null)); } | |
| 246 | 新增: return 0; | |
| 247 | 新增: } | |
| 248 | 新增: } | |
| 249 | 新增: private static int RenderEndpoints() | |
| 250 | 新增: { | |
| 251 | 新增: object? enumerator = null; IMMDeviceCollection? devices = null; | |
| 252 | 新增: try { enumerator = Activator.CreateInstance(Type.GetTypeFromCLSID(new Guid("BCDE0395-E52F-467C-8E3D-C4579291692E"))!); Check(((IMMDeviceEnumerator)enumerator!).EnumAudioEndpoints(0, 1, out devices)); Check(devices.GetCount(out var count)); return checked((int)count); } | |
| 253 | 新增: catch (COMException) { return -1; } | |
| 254 | 新增: finally { if (devices is not null) Marshal.ReleaseComObject(devices); if (enumerator is not null) Marshal.ReleaseComObject(enumerator); } | |
| 255 | 新增: } | |
| 256 | 新增: private static string ServiceState(string name,out uint code) | |
| 257 | 新增: { | |
| 258 | 新增: code=0;var manager = OpenSCManagerW(null, null, 1); if (manager == 0) { code=Win32Code();return "unknown"; } | |
| 259 | 新增: try { var service = OpenServiceW(manager, name, 4); if (service == 0) { code=Win32Code();return "unknown"; } try { if(!QueryServiceStatusEx(service, 0, out var state, (uint)Marshal.SizeOf<ServiceStatus>(), out _)){code=Win32Code();return "unknown";}return state.Current==4?"running":"stopped"; } finally { CloseServiceHandle(service); } } | |
| 260 | 新增: finally { CloseServiceHandle(manager); } | |
| 261 | 新增: } | |
| 262 | 新增: private static uint Win32Code() {var error=unchecked((uint)Marshal.GetLastWin32Error());return error==0?0x80004005:error|0x80070000;} | |
| 263 | 新增: private static void Check(int hr) { if (hr < 0) throw new InvalidDataException("audio_native_" + unchecked((uint)hr).ToString("x8")); } | |
| 264 | 新增: [StructLayout(LayoutKind.Sequential, Pack = 2)] private struct WaveFormat { public ushort Tag, Channels; public uint Rate, Average; public ushort Align, Bits, Extra; } | |
| 265 | 新增: [StructLayout(LayoutKind.Explicit, Size = 24)] private struct Variant { [FieldOffset(0)] public ushort Type; [FieldOffset(8)] public uint Bytes; [FieldOffset(16)] public nint Data; } | |
| 266 | 新增: [StructLayout(LayoutKind.Sequential)] private struct ProcessBasic { public nint Exit, Peb, Affinity, Priority, ID, Parent; } | |
| 267 | 新增: [StructLayout(LayoutKind.Sequential)] private struct ServiceStatus { public uint Type, Current, Controls, Exit, ServiceExit, Checkpoint, Hint, PID, Flags; } | |
| 268 | 新增: [ComImport, Guid("1CB9AD4C-DBFA-4C32-B178-C2F568A703B2"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] private interface IAudioClient | |
| 269 | 新增: { | |
| 270 | 新增: [PreserveSig] int Initialize(int mode, uint flags, long duration, long period, ref WaveFormat format, nint session); | |
| 271 | 新增: [PreserveSig] int GetBufferSize(out uint frames); [PreserveSig] int GetStreamLatency(out long latency); [PreserveSig] int GetCurrentPadding(out uint padding); | |
| 272 | 新增: [PreserveSig] int IsFormatSupported(int mode, nint format, out nint closest); [PreserveSig] int GetMixFormat(out nint format); [PreserveSig] int GetDevicePeriod(out long normal, out long minimum); | |
| 273 | 新增: [PreserveSig] int Start(); [PreserveSig] int Stop(); [PreserveSig] int Reset(); [PreserveSig] int SetEventHandle(nint handle); | |
| 274 | 新增: [PreserveSig] int GetService(ref Guid iid, [MarshalAs(UnmanagedType.IUnknown)] out object service); | |
| 275 | 新增: } | |
| 276 | 新增: [ComImport, Guid("C8ADBD64-E71E-48A0-A4DE-185C395CD317"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] private interface IAudioCaptureClient | |
| 277 | 新增: { [PreserveSig] int GetBuffer(out nint data, out uint frames, out uint flags, out ulong device, out ulong clock); [PreserveSig] int ReleaseBuffer(uint frames); [PreserveSig] int GetNextPacketSize(out uint frames); } | |
| 278 | 新增: [ComImport, Guid("72A22D78-CDE4-431D-B8CC-843A71199B6D"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] private interface IActivateOperation | |
| 279 | 新增: { [PreserveSig] int GetActivateResult(out int result, [MarshalAs(UnmanagedType.IUnknown)] out object audio); } | |
| 280 | 新增: [ComVisible(true), Guid("41D949AB-9862-444A-80F6-C261334DA5EB"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] private interface ICompletion | |
| 281 | 新增: { [PreserveSig] int ActivateCompleted(IActivateOperation operation); } | |
| 282 | 新增: [ComVisible(true), Guid("94EA2B94-E9CC-49E0-C0FF-EE64CA8F5B90"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] private interface IAgile { } | |
| 283 | 新增: [ComImport, Guid("A95664D2-9614-4F35-A746-DE8DB63617E6"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] private interface IMMDeviceEnumerator | |
| 284 | 新增: { [PreserveSig] int EnumAudioEndpoints(int flow, uint state, out IMMDeviceCollection devices); } | |
| 285 | 新增: [ComImport, Guid("0BD7A1BE-7A1A-44DB-8397-CC5392387B5E"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] private interface IMMDeviceCollection | |
| 286 | 新增: { [PreserveSig] int GetCount(out uint count); } | |
| 287 | 新增: [DllImport("mmdevapi.dll", ExactSpelling = true, CharSet = CharSet.Unicode)] private static extern int ActivateAudioInterfaceAsync(string device, ref Guid iid, ref Variant parameters, ICompletion callback, out IActivateOperation operation); | |
| 288 | 新增: [DllImport("ole32.dll")] private static extern int CoInitializeEx(nint reserved, uint mode); [DllImport("ole32.dll")] private static extern void CoUninitialize(); | |
| 289 | 新增: [DllImport("ntdll.dll")] private static extern int NtQueryInformationProcess(nint process, int kind, out ProcessBasic basic, uint bytes, out uint returned); | |
| 290 | 新增: [DllImport("advapi32.dll", ExactSpelling=true,CharSet = CharSet.Unicode,SetLastError=true)] private static extern nint OpenSCManagerW(string? machine, string? database, uint rights); | |
| 291 | 新增: [DllImport("advapi32.dll", ExactSpelling=true,CharSet = CharSet.Unicode,SetLastError=true)] private static extern nint OpenServiceW(nint manager, string name, uint rights); | |
| 292 | 新增: [DllImport("advapi32.dll", ExactSpelling=true,SetLastError=true)] private static extern bool QueryServiceStatusEx(nint service, int level, out ServiceStatus state, uint bytes, out uint needed); | |
| 293 | 新增: [DllImport("advapi32.dll")] private static extern bool CloseServiceHandle(nint handle); | |
| 294 | 新增:} | |
| @@ -0,0 +1,300 @@ | ||
| 1 | 新增:using System.Reflection; | |
| 2 | 新增:using System.Runtime.CompilerServices; | |
| 3 | 新增:using System.Security.AccessControl; | |
| 4 | 新增:using System.Security.Cryptography; | |
| 5 | 新增:using System.Security.Principal; | |
| 6 | 新增:using System.Text; | |
| 7 | 新增:using System.Text.Json.Nodes; | |
| 8 | 新增:using System.Text.RegularExpressions; | |
| 9 | 新增:using System.Diagnostics; | |
| 10 | 新增: | |
| 11 | 新增:namespace Cage.GuestClipboard; | |
| 12 | 新增: | |
| 13 | 新增:internal static class WindowsCliRpc | |
| 14 | 新增:{ | |
| 15 | 新增: private static readonly Regex ProfileID = new("^[a-f0-9]{16}$",RegexOptions.CultureInvariant); | |
| 16 | 新增: private static readonly Regex AccountID = new("^(default|[a-f0-9]{24})$",RegexOptions.CultureInvariant); | |
| 17 | 新增: private static readonly Regex Subject = new("^[a-f0-9]{64}$",RegexOptions.CultureInvariant); | |
| 18 | 新增: private static readonly Regex CCSProfile = new("^[a-zA-Z0-9][a-zA-Z0-9_-]{0,63}$",RegexOptions.CultureInvariant); | |
| 19 | 新增: private static readonly HashSet<string> Modes=["discover","view","rpc","active","handoff","purge","account-switch","account-switch-cancel"]; | |
| 20 | 新增: private static readonly object Gate=new(); | |
| 21 | 新增: private static readonly Dictionary<string,int> Active=new(StringComparer.OrdinalIgnoreCase); | |
| 22 | 新增: [ModuleInitializer] internal static void Register() | |
| 23 | 新增: { | |
| 24 | 新增: if(!GuestOperations.Names.Contains("cli"))return; | |
| 25 | 新增: try{LoadTools();}catch(Exception){return;} | |
| 26 | 新增: GuestOperations.Register("cli",Run); | |
| 27 | 新增: } | |
| 28 | 新增: private sealed record Tools(string Python,string Claude,string Bash); | |
| 29 | 新增: private sealed record Layout(string Profile,string Root,string Accounts,string State,string Shared,string Code,Tools Tools); | |
| 30 | 新增: internal static async Task Run(Stream stream,CancellationToken token,Func<bool> available) | |
| 31 | 新增: { | |
| 32 | 新增: if(!available())throw new InvalidDataException("requires_gui_login"); | |
| 33 | 新增: var request=await Protocol.Read(stream,4<<20,token)??throw new EndOfStreamException(); | |
| 34 | 新增: var profile=request["profile"]?.GetValue<string>()??""; | |
| 35 | 新增: if(!ProfileID.IsMatch(profile))throw new InvalidDataException("cli_profile_invalid"); | |
| 36 | 新增: var layout=Prepare(profile); | |
| 37 | 新增: var action=request["action"]?.GetValue<string>()??""; | |
| 38 | 新增: if(action=="terminal") | |
| 39 | 新增: { | |
| 40 | 新增: var kind=request["kind"]?.GetValue<string>()??""; | |
| 41 | 新增: if(kind is not ("claude" or "claude-login"))throw new InvalidDataException("cli_kind_invalid"); | |
| 42 | 新增: var account=request["account"]?.GetValue<string>()??"default"; | |
| 43 | 新增: if(!AccountID.IsMatch(account)||kind=="claude-login"&&account=="default")throw new InvalidDataException("cli_account_invalid"); | |
| 44 | 新增: var directory=Environment.GetFolderPath(Environment.SpecialFolder.UserProfile); | |
| 45 | 新增: var open=new JsonObject{["action"]="open",["cols"]=request["cols"]?.DeepClone()??100,["rows"]=request["rows"]?.DeepClone()??30,["workspace"]="home",["shell"]="claude"}; | |
| 46 | 新增: var arguments=new List<string>{"-X","utf8","-I"}; | |
| 47 | 新增: var env=EnvironmentFor(layout,account); | |
| 48 | 新增: using var lease=AccountLease(layout,account); | |
| 49 | 新增: if(kind=="claude-login")arguments.AddRange([Path.Combine(layout.Code,"cage-claude-account.py"),"login",account]); | |
| 50 | 新增: else | |
| 51 | 新增: { | |
| 52 | 新增: var id=request["project_id"]?.GetValue<string>()??"";var grant=request["grant"]?.GetValue<string>()??""; | |
| 53 | 新增: directory=ProjectRpc.Resolve(id,grant);open["workspace"]="project";open["project_id"]=id;open["grant"]=grant; | |
| 54 | 新增: var payload=request["conversation"]?.DeepClone() as JsonObject??throw new InvalidDataException("cli_conversation_invalid"); | |
| 55 | 新增: Guid.Parse(payload["id"]?.GetValue<string>()??"");Guid.Parse(payload["session_id"]?.GetValue<string>()??""); | |
| 56 | 新增: ValidatePaths(layout,payload); | |
| 57 | 新增: var subject=request["subject"]?.GetValue<string>()??""; | |
| 58 | 新增: if(subject!=""&&!Subject.IsMatch(subject))throw new InvalidDataException("cli_identity_invalid"); | |
| 59 | 新增: payload["account"]=account;payload["subject"]=subject;payload["prefix"]=new JsonArray(layout.Tools.Claude); | |
| 60 | 新增: if(request["ccs_profile"] is JsonValue c&&c.TryGetValue<string>(out var ccs)&&ccs!="") | |
| 61 | 新增: { | |
| 62 | 新增: if(!CCSProfile.IsMatch(ccs)||account!="default"||subject!="")throw new InvalidDataException("ccs_profile_invalid"); | |
| 63 | 新增: var tools=LoadCCSTools();env["CAGE_CCS_NODE"]=tools.Node;env["CAGE_CCS_MAIN"]=tools.Main; | |
| 64 | 新增: env["CAGE_CCS_PRELOAD"]=Path.Combine(layout.Code,"windows_ccs_launch.cjs"); | |
| 65 | 新增: env["CCS_CLAUDE_PATH"]=layout.Tools.Claude; | |
| 66 | 新增: env["CCS_DIR"]=Path.Combine(layout.Root,"ccs");env["CCS_HOME"]=Path.Combine(layout.Root,"ccs-home"); | |
| 67 | 新增: PrivateDirectory(env["CCS_DIR"]);PrivateDirectory(env["CCS_HOME"]);payload["ccs_profile"]=ccs; | |
| 68 | 新增: } | |
| 69 | 新增: arguments.AddRange([Path.Combine(layout.Code,"cli_channel.py"),"launch",payload.ToJsonString()]); | |
| 70 | 新增: } | |
| 71 | 新增: if(!available())throw new InvalidDataException("requires_gui_login"); | |
| 72 | 新增: using var prefixed=new PrefixStream(stream,Protocol.Utf8.GetBytes(open.ToJsonString()+"\n")); | |
| 73 | 新增: await TerminalRpc.RunWithLaunch(prefixed,token,available,new(layout.Tools.Python,arguments.ToArray(),directory,env)); | |
| 74 | 新增: return; | |
| 75 | 新增: } | |
| 76 | 新增: string script;string[] args;JsonNode? input=null;var selected="default"; | |
| 77 | 新增: if(action=="account") | |
| 78 | 新增: { | |
| 79 | 新增: var mode=request["mode"]?.GetValue<string>()??""; | |
| 80 | 新增: if(mode is not ("snapshot" or "usage" or "quotas"))throw new InvalidDataException("cli_account_operation_invalid"); | |
| 81 | 新增: selected=request["account"]?.GetValue<string>()??"default"; | |
| 82 | 新增: if(!AccountID.IsMatch(selected))throw new InvalidDataException("cli_account_invalid"); | |
| 83 | 新增: args=[mode,selected]; | |
| 84 | 新增: if(mode=="usage"){var subject=request["subject"]?.GetValue<string>()??"";if(!Subject.IsMatch(subject))throw new InvalidDataException("cli_identity_invalid");args=[mode,selected,subject];} | |
| 85 | 新增: if(mode=="quotas") | |
| 86 | 新增: { | |
| 87 | 新增: var ids=request["ids"] as JsonArray??throw new InvalidDataException("cli_account_invalid"); | |
| 88 | 新增: if(ids.Count is <1 or >100||ids.Any(x=>!AccountID.IsMatch(x?.GetValue<string>()??"")))throw new InvalidDataException("cli_account_invalid"); | |
| 89 | 新增: args=[mode,..ids.Select(x=>x!.GetValue<string>())]; | |
| 90 | 新增: } | |
| 91 | 新增: script=Path.Combine(layout.Code,"cage-claude-account.py"); | |
| 92 | 新增: } | |
| 93 | 新增: else if(action=="channel") | |
| 94 | 新增: { | |
| 95 | 新增: var mode=request["mode"]?.GetValue<string>()??"";if(!Modes.Contains(mode))throw new InvalidDataException("cli_channel_operation_invalid"); | |
| 96 | 新增: input=request["input"]?.DeepClone()??throw new InvalidDataException("cli_channel_input_invalid"); | |
| 97 | 新增: ValidatePaths(layout,input as JsonObject??throw new InvalidDataException("cli_channel_input_invalid")); | |
| 98 | 新增: if(input["config"] is JsonValue c&&c.TryGetValue<string>(out var config)&&config!="") | |
| 99 | 新增: { | |
| 100 | 新增: var relative=Path.GetRelativePath(layout.Accounts,Path.GetFullPath(config)).Split(Path.DirectorySeparatorChar); | |
| 101 | 新增: if(relative.Length==2&&AccountID.IsMatch(relative[0])&&relative[0]!="default"&&relative[1]=="config")selected=relative[0]; | |
| 102 | 新增: } | |
| 103 | 新增: script=Path.Combine(layout.Code,"cli_channel.py");args=[mode,"-"]; | |
| 104 | 新增: } | |
| 105 | 新增: else throw new InvalidDataException("cli_operation_invalid"); | |
| 106 | 新增: using var accountLease=AccountLease(layout,selected); | |
| 107 | 新增: var result=await Invoke(layout,selected,script,args,input,token,available); | |
| 108 | 新增: await Protocol.Write(stream,result,token); | |
| 109 | 新增: } | |
| 110 | 新增: private static Layout Prepare(string profile) | |
| 111 | 新增: { | |
| 112 | 新增: var tools=LoadTools(); | |
| 113 | 新增: var root=Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile),"Cage","CLI",profile); | |
| 114 | 新增: var accounts=Path.Combine(root,"accounts");var state=Path.Combine(root,"channels");var shared=Path.Combine(root,"shared"); | |
| 115 | 新增: foreach(var path in new[]{root,accounts,state,shared})PrivateDirectory(path); | |
| 116 | 新增: string Read(string resource){using var input=Assembly.GetExecutingAssembly().GetManifestResourceStream(resource)??throw new InvalidDataException("cli_helper_missing");using var reader=new StreamReader(input,Protocol.Utf8);return reader.ReadToEnd();} | |
| 117 | 新增: var files=new Dictionary<string,string>{{"cli_channel.py",Read("Cage.CliChannel")},{"cage-claude-account.py",Read("Cage.CliAccount")},{"windows_cli_platform.py",Read("Cage.CliPlatform")},{"windows_ccs_launch.cjs",Read("Cage.CliCCS")},{"mobile_cli_identity.py",Read("Cage.CliIdentity")},{"cli_channel.resume.md",Read("Cage.CliResume")},{"cli_channel.account-resume.md",Read("Cage.CliAccountResume")}}; | |
| 118 | 新增: var digest=Convert.ToHexString(SHA256.HashData(Protocol.Utf8.GetBytes(string.Join("\n",files.Values)))).ToLowerInvariant(); | |
| 119 | 新增: var code=Path.Combine(root,"code",digest);PrivateDirectory(code); | |
| 120 | 新增: foreach(var file in files){var path=Path.Combine(code,file.Key);if(!File.Exists(path))File.WriteAllText(path,file.Value,Protocol.Utf8);else if(File.ReadAllText(path,Protocol.Utf8)!=file.Value)throw new InvalidDataException("cli_helper_changed");} | |
| 121 | 新增: return new(profile,root,accounts,state,shared,code,tools); | |
| 122 | 新增: } | |
| 123 | 新增: private static readonly Dictionary<string,(long Size,DateTime Written,string Hash)> ToolHashes=new(StringComparer.OrdinalIgnoreCase); | |
| 124 | 新增: private static Tools LoadTools() | |
| 125 | 新增: { | |
| 126 | 新增: var toolsFile=Path.Combine(AppContext.BaseDirectory,"cli-tools.json");Pairing.PrivateFile(toolsFile); | |
| 127 | 新增: var tool=JsonNode.Parse(File.ReadAllBytes(toolsFile))as JsonObject??throw new InvalidDataException("cli_tools_invalid"); | |
| 128 | 新增: return new Tools(CheckTool(tool,"python"),CheckTool(tool,"claude"),CheckTool(tool,"git_bash")); | |
| 129 | 新增: } | |
| 130 | 新增: // Read only fixed tool receipts, without account preparation or execution. | |
| 131 | 新增: internal static JsonObject ComponentStatus() | |
| 132 | 新增: { | |
| 133 | 新增: var dependencies=new JsonObject{["python"]=false,["claude"]=false,["git_bash"]=false}; | |
| 134 | 新增: try | |
| 135 | 新增: { | |
| 136 | 新增: var receipt=Path.Combine(AppContext.BaseDirectory,"cli-tools.json");Pairing.PrivateFile(receipt); | |
| 137 | 新增: var info=new FileInfo(receipt);if(info.Length is <1 or >16384)throw new InvalidDataException("cli_tools_invalid"); | |
| 138 | 新增: var tools=JsonNode.Parse(File.ReadAllBytes(receipt))as JsonObject??throw new InvalidDataException("cli_tools_invalid"); | |
| 139 | 新增: foreach(var name in new[]{"python","claude","git_bash"}) | |
| 140 | 新增: try{CheckTool(tools,name);dependencies[name]=true;}catch{ } | |
| 141 | 新增: } | |
| 142 | 新增: catch{ } | |
| 143 | 新增: var installed=dependencies.All(pair=>pair.Value!.GetValue<bool>()); | |
| 144 | 新增: return new JsonObject{["installed"]=installed,["ready"]=installed,["reason"]=installed?"":"cli_tools_missing_or_invalid",["dependencies"]=dependencies}; | |
| 145 | 新增: } | |
| 146 | 新增: private static string CheckTool(JsonObject tool,string name) | |
| 147 | 新增: { | |
| 148 | 新增: var path=tool[name]?.GetValue<string>()??"";var hash=tool[name+"_sha256"]?.GetValue<string>()??""; | |
| 149 | 新增: if(!Path.IsPathFullyQualified(path)||!Subject.IsMatch(hash)||!File.Exists(path)||new FileInfo(path).Attributes.HasFlag(FileAttributes.ReparsePoint))throw new InvalidDataException("cli_tools_unverified"); | |
| 150 | 新增: var info=new FileInfo(path); | |
| 151 | 新增: lock(Gate) | |
| 152 | 新增: { | |
| 153 | 新增: if(!ToolHashes.TryGetValue(path,out var known)||known.Size!=info.Length||known.Written!=info.LastWriteTimeUtc||known.Hash!=hash) | |
| 154 | 新增: { | |
| 155 | 新增: using var file=File.OpenRead(path); | |
| 156 | 新增: if(Convert.ToHexString(SHA256.HashData(file)).ToLowerInvariant()!=hash)throw new InvalidDataException("cli_tools_unverified"); | |
| 157 | 新增: ToolHashes[path]=(info.Length,info.LastWriteTimeUtc,hash); | |
| 158 | 新增: } | |
| 159 | 新增: } | |
| 160 | 新增: return Path.GetFullPath(path); | |
| 161 | 新增: } | |
| 162 | 新增: private sealed record CCSTools(string Node,string Main); | |
| 163 | 新增: private static CCSTools LoadCCSTools() | |
| 164 | 新增: { | |
| 165 | 新增: var receipt=Path.Combine(AppContext.BaseDirectory,"ccs-tools.json");Pairing.PrivateFile(receipt); | |
| 166 | 新增: var value=JsonNode.Parse(File.ReadAllBytes(receipt))as JsonObject??throw new InvalidDataException("ccs_tools_invalid"); | |
| 167 | 新增: string Check(string name) | |
| 168 | 新增: { | |
| 169 | 新增: var path=value[name]?.GetValue<string>()??"";var hash=value[name+"_sha256"]?.GetValue<string>()??""; | |
| 170 | 新增: if(!Path.IsPathFullyQualified(path)||!Subject.IsMatch(hash)||!File.Exists(path)||new FileInfo(path).Attributes.HasFlag(FileAttributes.ReparsePoint))throw new InvalidDataException("ccs_tools_invalid"); | |
| 171 | 新增: using var data=File.OpenRead(path);if(Convert.ToHexString(SHA256.HashData(data)).ToLowerInvariant()!=hash)throw new InvalidDataException("ccs_tools_changed"); | |
| 172 | 新增: return Path.GetFullPath(path); | |
| 173 | 新增: } | |
| 174 | 新增: var node=Check("node");var main=Check("main");var manifest=Check("manifest"); | |
| 175 | 新增: if(new FileInfo(manifest).Length>2<<20)throw new InvalidDataException("ccs_manifest_invalid"); | |
| 176 | 新增: var files=System.Text.Json.JsonSerializer.Deserialize<Dictionary<string,string>>(File.ReadAllBytes(manifest))??throw new InvalidDataException("ccs_manifest_invalid"); | |
| 177 | 新增: if(files.Count is <1 or >20000)throw new InvalidDataException("ccs_manifest_invalid"); | |
| 178 | 新增: var root=Path.GetDirectoryName(manifest)!; | |
| 179 | 新增: foreach(var item in files) | |
| 180 | 新增: { | |
| 181 | 新增: var path=Path.GetFullPath(Path.Combine(root,item.Key.Replace('/',Path.DirectorySeparatorChar))); | |
| 182 | 新增: if(!path.StartsWith(root+Path.DirectorySeparatorChar,StringComparison.OrdinalIgnoreCase)||!Subject.IsMatch(item.Value)||new FileInfo(path).Attributes.HasFlag(FileAttributes.ReparsePoint))throw new InvalidDataException("ccs_manifest_invalid"); | |
| 183 | 新增: using var data=File.OpenRead(path);if(Convert.ToHexString(SHA256.HashData(data)).ToLowerInvariant()!=item.Value)throw new InvalidDataException("ccs_tools_changed"); | |
| 184 | 新增: } | |
| 185 | 新增: if(!main.StartsWith(root+Path.DirectorySeparatorChar,StringComparison.OrdinalIgnoreCase))throw new InvalidDataException("ccs_tools_invalid"); | |
| 186 | 新增: return new(node,main); | |
| 187 | 新增: } | |
| 188 | 新增: private static Dictionary<string,string> EnvironmentFor(Layout layout,string account) | |
| 189 | 新增: { | |
| 190 | 新增: var env=Environment.GetEnvironmentVariables().Cast<System.Collections.DictionaryEntry>().ToDictionary(x=>(string)x.Key,x=>x.Value?.ToString()??"",StringComparer.OrdinalIgnoreCase); | |
| 191 | 新增: env["CAGE_CLI_BINARY"]=layout.Tools.Claude;env["CAGE_CLI_STATE_ROOT"]=layout.State;env["CAGE_CLI_ACCOUNT_ROOT"]=layout.Accounts;env["CAGE_CLI_SHARED_ROOT"]=layout.Shared; | |
| 192 | 新增: env["CAGE_CLI_ACCOUNT_HELPER"]=Path.Combine(layout.Code,"cage-claude-account.py");env["CLAUDE_CODE_GIT_BASH_PATH"]=layout.Tools.Bash; | |
| 193 | 新增: env["CAGE_CLI_IDENTITY_HELPER"]=Path.Combine(layout.Code,"mobile_cli_identity.py"); | |
| 194 | 新增: env["CAGE_CLI_PYTHON"]=layout.Tools.Python;env["CAGE_CLI_SHELL"]=TerminalRpc.PowerShellPath();env["CAGE_CLAUDE_ACCOUNT_ID"]=account; | |
| 195 | 新增: env["PATH"]=Path.GetDirectoryName(layout.Tools.Claude)+";"+Path.Combine(Path.GetDirectoryName(Path.GetDirectoryName(layout.Tools.Bash))!,"cmd")+";"+env.GetValueOrDefault("PATH"); | |
| 196 | 新增: if(account!="default")env["CLAUDE_CONFIG_DIR"]=Path.Combine(layout.Accounts,account,"config"); | |
| 197 | 新增: else env.Remove("CLAUDE_CONFIG_DIR"); | |
| 198 | 新增: return env; | |
| 199 | 新增: } | |
| 200 | 新增: private static void ValidatePaths(Layout layout,JsonObject value) | |
| 201 | 新增: { | |
| 202 | 新增: if(value["workspace"] is JsonValue w&&w.TryGetValue<string>(out var workspace)&&workspace!="") | |
| 203 | 新增: { | |
| 204 | 新增: var resolved=ProjectRpc.Resolve(value["project_id"]?.GetValue<string>()??"",value["grant"]?.GetValue<string>()??""); | |
| 205 | 新增: if(!Path.GetFullPath(workspace).Equals(Path.GetFullPath(resolved),StringComparison.OrdinalIgnoreCase))throw new InvalidDataException("cli_project_unregistered"); | |
| 206 | 新增: } | |
| 207 | 新增: if(value["config"]is JsonValue c&&c.TryGetValue<string>(out var config)&&config!="") | |
| 208 | 新增: { | |
| 209 | 新增: var path=Path.GetFullPath(config);var home=Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile),".claude"); | |
| 210 | 新增: var relative=Path.GetRelativePath(layout.Accounts,path).Split(Path.DirectorySeparatorChar); | |
| 211 | 新增: var ccs=Path.GetRelativePath(layout.Root,path); | |
| 212 | 新增: var registeredCCS=(ccs.StartsWith("ccs-home"+Path.DirectorySeparatorChar,StringComparison.OrdinalIgnoreCase)||ccs.StartsWith("ccs"+Path.DirectorySeparatorChar,StringComparison.OrdinalIgnoreCase))&&Directory.Exists(path); | |
| 213 | 新增: if(!path.Equals(home,StringComparison.OrdinalIgnoreCase)&&!(relative.Length==2&&AccountID.IsMatch(relative[0])&&relative[0]!="default"&&relative[1]=="config")&&!registeredCCS)throw new InvalidDataException("cli_config_unregistered"); | |
| 214 | 新增: } | |
| 215 | 新增: if(value["resume_transcript"] is JsonValue t&&t.TryGetValue<string>(out var transcript)&&transcript!="") | |
| 216 | 新增: { | |
| 217 | 新增: var id=Guid.Parse(value["switch_id"]?.GetValue<string>()??""); | |
| 218 | 新增: var expected=Path.Combine(layout.Root,"cli-account-switches",id.ToString("D"),"history.jsonl"); | |
| 219 | 新增: if(!Path.GetFullPath(transcript).Equals(expected,StringComparison.OrdinalIgnoreCase))throw new InvalidDataException("cli_history_unregistered"); | |
| 220 | 新增: } | |
| 221 | 新增: } | |
| 222 | 新增: private static async Task<JsonObject> Invoke(Layout layout,string account,string script,string[] args,JsonNode? input,CancellationToken token,Func<bool> available) | |
| 223 | 新增: { | |
| 224 | 新增: var start=new ProcessStartInfo(layout.Tools.Python){UseShellExecute=false,CreateNoWindow=true,RedirectStandardInput=true,RedirectStandardOutput=true,RedirectStandardError=true}; | |
| 225 | 新增: foreach(var arg in new[]{"-X","utf8","-I",script}.Concat(args))start.ArgumentList.Add(arg); | |
| 226 | 新增: foreach(var pair in EnvironmentFor(layout,account))start.Environment[pair.Key]=pair.Value; | |
| 227 | 新增: start.WorkingDirectory=layout.Root; | |
| 228 | 新增: using var child=Process.Start(start)??throw new InvalidDataException("cli_process_failed"); | |
| 229 | 新增: using var cancel=token.Register(()=>{try{child.Kill(true);}catch{}}); | |
| 230 | 新增: var stderr=child.StandardError.BaseStream.CopyToAsync(Stream.Null,token); | |
| 231 | 新增: try | |
| 232 | 新增: { | |
| 233 | 新增: if(input is not null)await child.StandardInput.WriteLineAsync(input.ToJsonString().AsMemory(),token);child.StandardInput.Close(); | |
| 234 | 新增: using var output=new MemoryStream();var buffer=new byte[16384];int size; | |
| 235 | 新增: while((size=await child.StandardOutput.BaseStream.ReadAsync(buffer,token))!=0) | |
| 236 | 新增: { | |
| 237 | 新增: if(output.Length+size>4<<20)throw new InvalidDataException("cli_status_limit"); | |
| 238 | 新增: output.Write(buffer,0,size); | |
| 239 | 新增: } | |
| 240 | 新增: var raw=Protocol.Utf8.GetString(output.GetBuffer(),0,(int)output.Length);await child.WaitForExitAsync(token);await stderr; | |
| 241 | 新增: if(!available()||child.ExitCode!=0)throw new InvalidDataException("cli_status_unavailable"); | |
| 242 | 新增: var parsed=JsonNode.Parse(raw); | |
| 243 | 新增: return new JsonObject{["result"]=parsed}; | |
| 244 | 新增: } | |
| 245 | 新增: finally | |
| 246 | 新增: { | |
| 247 | 新增: if(!child.HasExited)try{child.Kill(true);}catch{} | |
| 248 | 新增: await child.WaitForExitAsync(CancellationToken.None); | |
| 249 | 新增: try{await stderr;}catch(OperationCanceledException){} | |
| 250 | 新增: } | |
| 251 | 新增: } | |
| 252 | 新增: private static void PrivateDirectory(string path) | |
| 253 | 新增: { | |
| 254 | 新增: var home=Path.GetFullPath(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile)); | |
| 255 | 新增: if(!Path.GetFullPath(path).StartsWith(home+Path.DirectorySeparatorChar,StringComparison.OrdinalIgnoreCase))throw new InvalidDataException("cli_directory_invalid"); | |
| 256 | 新增: for(var ancestor=new DirectoryInfo(path);ancestor.FullName!=home;ancestor=ancestor.Parent??throw new InvalidDataException("cli_directory_invalid")) | |
| 257 | 新增: if(ancestor.Exists&&ancestor.Attributes.HasFlag(FileAttributes.ReparsePoint))throw new InvalidDataException("cli_directory_invalid"); | |
| 258 | 新增: Directory.CreateDirectory(path);var info=new DirectoryInfo(path); | |
| 259 | 新增: if(info.Attributes.HasFlag(FileAttributes.ReparsePoint))throw new InvalidDataException("cli_directory_invalid"); | |
| 260 | 新增: using var user=WindowsIdentity.GetCurrent();var acl=new DirectorySecurity();acl.SetOwner(user.User!);acl.SetAccessRuleProtection(true,false); | |
| 261 | 新增: foreach(var sid in new[]{user.User!,new SecurityIdentifier("S-1-5-18"),new SecurityIdentifier("S-1-5-32-544")})acl.AddAccessRule(new(sid,FileSystemRights.FullControl,InheritanceFlags.ContainerInherit|InheritanceFlags.ObjectInherit,PropagationFlags.None,AccessControlType.Allow)); | |
| 262 | 新增: info.SetAccessControl(acl); | |
| 263 | 新增: } | |
| 264 | 新增: private static byte[] PrivateData(string path) | |
| 265 | 新增: { | |
| 266 | 新增: var info=new FileInfo(path); | |
| 267 | 新增: if(!info.Exists||info.Length is <1 or >16384||info.Attributes.HasFlag(FileAttributes.ReparsePoint))throw new InvalidDataException("cli_credentials_invalid"); | |
| 268 | 新增: using var user=WindowsIdentity.GetCurrent();var allowed=new HashSet<string>{user.User!.Value,"S-1-5-18","S-1-5-32-544"}; | |
| 269 | 新增: foreach(FileSystemAccessRule rule in info.GetAccessControl().GetAccessRules(true,true,typeof(SecurityIdentifier))) | |
| 270 | 新增: if(rule.AccessControlType==AccessControlType.Allow&&!allowed.Contains(rule.IdentityReference.Value))throw new InvalidDataException("cli_credentials_permissions_invalid"); | |
| 271 | 新增: return File.ReadAllBytes(path); | |
| 272 | 新增: } | |
| 273 | 新增: private static IDisposable AccountLease(Layout layout,string account) | |
| 274 | 新增: { | |
| 275 | 新增: if(account=="default")return new Release(()=>{}); | |
| 276 | 新增: var folder=Path.Combine(layout.Accounts,account,"config");PrivateDirectory(folder); | |
| 277 | 新增: var plain=Path.Combine(folder,".credentials.json");var encrypted=Path.Combine(folder,"credentials.dpapi"); | |
| 278 | 新增: lock(Gate) | |
| 279 | 新增: { | |
| 280 | 新增: if(!File.Exists(plain)&&File.Exists(encrypted)) | |
| 281 | 新增: { | |
| 282 | 新增: var restored=Pairing.Crypt(PrivateData(encrypted),GuestContext.VM,GuestContext.SID+":cli:"+layout.Profile+":"+account,false); | |
| 283 | 新增: try{using var file=new FileStream(plain,FileMode.CreateNew,FileAccess.Write,FileShare.None);file.Write(restored);file.Flush(true);}finally{CryptographicOperations.ZeroMemory(restored);} | |
| 284 | 新增: } | |
| 285 | 新增: Active[folder]=Active.GetValueOrDefault(folder)+1; | |
| 286 | 新增: } | |
| 287 | 新增: return new Release(()=>{lock(Gate){if(--Active[folder]!=0)return;Active.Remove(folder);if(File.Exists(plain)){var bytes=PrivateData(plain);try{var sealedBytes=Pairing.Crypt(bytes,GuestContext.VM,GuestContext.SID+":cli:"+layout.Profile+":"+account,true);var temporary=encrypted+"."+Guid.NewGuid().ToString("N");using(var file=new FileStream(temporary,FileMode.CreateNew,FileAccess.Write,FileShare.None)){file.Write(sealedBytes);file.Flush(true);}File.Move(temporary,encrypted,true);File.Delete(plain);}finally{CryptographicOperations.ZeroMemory(bytes);}}}}); | |
| 288 | 新增: } | |
| 289 | 新增: private sealed class Release(Action action):IDisposable{private Action? close=action;public void Dispose()=>Interlocked.Exchange(ref close,null)?.Invoke();} | |
| 290 | 新增: private sealed class PrefixStream(Stream inner,byte[] prefix):Stream | |
| 291 | 新增: { | |
| 292 | 新增: int position; | |
| 293 | 新增: public override async ValueTask<int> ReadAsync(Memory<byte> buffer,CancellationToken token=default){if(position<prefix.Length){var n=Math.Min(buffer.Length,prefix.Length-position);prefix.AsMemory(position,n).CopyTo(buffer);position+=n;return n;}return await inner.ReadAsync(buffer,token);} | |
| 294 | 新增: public override int Read(byte[] buffer,int offset,int count){if(position<prefix.Length){var n=Math.Min(count,prefix.Length-position);Array.Copy(prefix,position,buffer,offset,n);position+=n;return n;}return inner.Read(buffer,offset,count);} | |
| 295 | 新增: public override Task WriteAsync(byte[] buffer,int offset,int count,CancellationToken token)=>inner.WriteAsync(buffer,offset,count,token); | |
| 296 | 新增: public override ValueTask WriteAsync(ReadOnlyMemory<byte> buffer,CancellationToken token=default)=>inner.WriteAsync(buffer,token); | |
| 297 | 新增: public override void Write(byte[] buffer,int offset,int count)=>inner.Write(buffer,offset,count);public override void Flush()=>inner.Flush();public override Task FlushAsync(CancellationToken token)=>inner.FlushAsync(token); | |
| 298 | 新增: public override bool CanRead=>true;public override bool CanWrite=>true;public override bool CanSeek=>false;public override long Length=>throw new NotSupportedException();public override long Position{get=>throw new NotSupportedException();set=>throw new NotSupportedException();}public override long Seek(long a,SeekOrigin b)=>throw new NotSupportedException();public override void SetLength(long a)=>throw new NotSupportedException(); | |
| 299 | 新增: } | |
| 300 | 新增:} | |
| @@ -0,0 +1,94 @@ | ||
| 1 | 新增:using System.Text.Json.Nodes; | |
| 2 | 新增: | |
| 3 | 新增:namespace Cage.GuestClipboard; | |
| 4 | 新增: | |
| 5 | 新增:// Readiness describes verified installed prerequisites for on-demand use. It | |
| 6 | 新增:// does not start applications, inspect accounts, or record an audio sample. | |
| 7 | 新增:internal static class WindowsComponentStatus | |
| 8 | 新增:{ | |
| 9 | 新增: private sealed class Probe(Func<JsonObject> read) | |
| 10 | 新增: { | |
| 11 | 新增: internal readonly Func<JsonObject> Read=read; | |
| 12 | 新增: internal JsonObject? Value; | |
| 13 | 新增: internal bool Pending; | |
| 14 | 新增: internal long Checked; | |
| 15 | 新增: internal long CheckedTick; | |
| 16 | 新增: } | |
| 17 | 新增: private static readonly object Gate=new(); | |
| 18 | 新增: private static readonly Dictionary<string,Probe> Probes=new(StringComparer.Ordinal) | |
| 19 | 新增: { | |
| 20 | 新增: ["desktop"]=new(ClaudeWindowRpc.ComponentStatus), | |
| 21 | 新增: ["cli"]=new(WindowsCliRpc.ComponentStatus), | |
| 22 | 新增: ["audio"]=new(WindowsAudioRpc.ComponentStatus), | |
| 23 | 新增: ["terminal"]=new(()=>State(File.Exists(TerminalRpc.PowerShellPath()),"terminal_components_missing")), | |
| 24 | 新增: ["project-mount"]=new(()=>State(ProjectRpc.ToolsPresent(),"project_components_missing")), | |
| 25 | 新增: }; | |
| 26 | 新增: private static JsonObject State(bool installed,string reason)=>new(){["installed"]=installed,["ready"]=installed,["reason"]=installed?"":reason}; | |
| 27 | 新增: internal static JsonObject Snapshot(JsonObject browser) | |
| 28 | 新增: { | |
| 29 | 新增: var available=SessionGuard.Available(); | |
| 30 | 新增: var registered=GuestOperations.Capabilities().ToHashSet(StringComparer.Ordinal); | |
| 31 | 新增: var tick=Environment.TickCount64; | |
| 32 | 新增: var result=new JsonObject(); | |
| 33 | 新增: lock(Gate) | |
| 34 | 新增: { | |
| 35 | 新增: foreach(var pair in Probes) | |
| 36 | 新增: { | |
| 37 | 新增: var probe=pair.Value; | |
| 38 | 新增: if(available&&!probe.Pending&&(probe.Value==null||tick-probe.CheckedTick>=15000)) | |
| 39 | 新增: { | |
| 40 | 新增: probe.Pending=true; | |
| 41 | 新增: // Each category retains one worker until its native call | |
| 42 | 新增: // finishes. A stalled COM provider cannot queue more work | |
| 43 | 新增: // or block the authenticated GUI status reply. | |
| 44 | 新增: _=Task.Factory.StartNew(()=>Refresh(pair.Key,probe),CancellationToken.None,TaskCreationOptions.LongRunning,TaskScheduler.Default); | |
| 45 | 新增: } | |
| 46 | 新增: var state=(JsonObject?)probe.Value?.DeepClone()??new JsonObject{["installed"]=false,["ready"]=false,["reason"]="component_check_pending"}; | |
| 47 | 新增: if(pair.Key=="audio") | |
| 48 | 新增: { | |
| 49 | 新增: var supported=Environment.OSVersion.Version.Build>=20348; | |
| 50 | 新增: state["supported"]=supported; | |
| 51 | 新增: if(probe.Value==null)state["installed"]=supported&®istered.Contains("audio"); | |
| 52 | 新增: } | |
| 53 | 新增: state["registered"]=registered.Contains(pair.Key);state["checked_at_ms"]=probe.Checked; | |
| 54 | 新增: if(probe.Value!=null&&tick-probe.CheckedTick>30000){state["ready"]=false;state["reason"]="component_check_pending";} | |
| 55 | 新增: if(!registered.Contains(pair.Key)){state["ready"]=false;if(state["installed"]?.GetValue<bool>()==true)state["reason"]="component_restart_required";} | |
| 56 | 新增: if(!available){state["ready"]=false;state["reason"]="requires_gui_login";} | |
| 57 | 新增: result[pair.Key]=state; | |
| 58 | 新增: } | |
| 59 | 新增: } | |
| 60 | 新增: result["clipboard"]=new JsonObject{["registered"]=true,["installed"]=true,["ready"]=available,["reason"]=available?"":"requires_gui_login"}; | |
| 61 | 新增: foreach(var name in new[]{"attachments","resources"}) | |
| 62 | 新增: result[name]=new JsonObject{["registered"]=registered.Contains(name),["installed"]=registered.Contains(name),["ready"]=available&®istered.Contains(name),["reason"]=available?"":"requires_gui_login"}; | |
| 63 | 新增: bool Flag(string name)=>browser[name]?.GetValue<bool>()==true; | |
| 64 | 新增: var browserInstalled=Flag("installed");var browserReady=available&®istered.Contains("browser")&&browserInstalled&&Flag("network_configured"); | |
| 65 | 新增: result["browser"]=new JsonObject{["registered"]=registered.Contains("browser"),["installed"]=browserInstalled,["ready"]=browserReady,["reason"]=browserReady?"":!available?"requires_gui_login":!browserInstalled?"browser_components_missing":"browser_network_unavailable"}; | |
| 66 | 新增: var editorInstalled=Flag("editor_installed"); | |
| 67 | 新增: result["editor"]=new JsonObject{["registered"]=registered.Contains("browser"),["installed"]=editorInstalled,["ready"]=browserReady&&editorInstalled,["reason"]=!editorInstalled?"editor_components_missing":!browserReady?"browser_unavailable":""}; | |
| 68 | 新增: var phoneInstalled=Flag("phone_installed");var phoneReady=available&®istered.Contains("browser")&&phoneInstalled&&Flag("phone_network_configured"); | |
| 69 | 新增: result["phone-browser"]=new JsonObject{["supported"]=true,["registered"]=registered.Contains("browser"),["installed"]=phoneInstalled,["ready"]=phoneReady,["reason"]=!available?"requires_gui_login":!phoneInstalled?"phone_browser_components_missing":!Flag("phone_network_configured")?"browser_network_unavailable":!registered.Contains("browser")?"component_restart_required":""}; | |
| 70 | 新增: var phoneDesktop=(JsonObject)result["desktop"]!.DeepClone(); | |
| 71 | 新增: phoneDesktop["supported"]=true; | |
| 72 | 新增: result["phone-desktop"]=phoneDesktop; | |
| 73 | 新增: foreach (var name in new[] { "desktop-file-chooser", "desktop-downloads" }) | |
| 74 | 新增: { | |
| 75 | 新增: var files = (JsonObject)result["desktop"]!.DeepClone(); | |
| 76 | 新增: files["supported"] = true; | |
| 77 | 新增: if (files["ready"]?.GetValue<bool>() == true && ClipboardAgent.Current?.SessionEventsRegistered != true) | |
| 78 | 新增: { | |
| 79 | 新增: files["ready"] = false; | |
| 80 | 新增: files["reason"] = "component_restart_required"; | |
| 81 | 新增: } | |
| 82 | 新增: result[name] = files; | |
| 83 | 新增: } | |
| 84 | 新增: result["legacy-mobile-migration"]=new JsonObject{["registered"]=false,["installed"]=false,["ready"]=false,["reason"]="not_implemented"}; | |
| 85 | 新增: return result; | |
| 86 | 新增: } | |
| 87 | 新增: private static void Refresh(string name,Probe probe) | |
| 88 | 新增: { | |
| 89 | 新增: JsonObject value; | |
| 90 | 新增: try{value=probe.Read();} | |
| 91 | 新增: catch{value=new JsonObject{["installed"]=name=="audio"&&Environment.OSVersion.Version.Build>=20348,["ready"]=false,["reason"]=name+"_status_unavailable"};} | |
| 92 | 新增: lock(Gate){probe.Value=value;probe.Checked=DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();probe.CheckedTick=Environment.TickCount64;probe.Pending=false;} | |
| 93 | 新增: } | |
| 94 | 新增:} | |
| @@ -0,0 +1,258 @@ | ||
| 1 | 新增:using System.Security.AccessControl; | |
| 2 | 新增:using System.Security.Cryptography; | |
| 3 | 新增:using System.Security.Principal; | |
| 4 | 新增:using System.Runtime.InteropServices; | |
| 5 | 新增:using System.Text; | |
| 6 | 新增:using System.Text.Json; | |
| 7 | 新增:using System.Text.Json.Nodes; | |
| 8 | 新增:using Microsoft.Win32.SafeHandles; | |
| 9 | 新增: | |
| 10 | 新增:namespace Cage.GuestClipboard; | |
| 11 | 新增: | |
| 12 | 新增:// Only destinations reserved for a verified Claude Save dialog enter this | |
| 13 | 新增:// catalog. A wire request names an opaque receipt, never a filesystem path. | |
| 14 | 新增:internal static class WindowsDesktopDownloads | |
| 15 | 新增:{ | |
| 16 | 新增: private sealed class Download | |
| 17 | 新增: { | |
| 18 | 新增: public string ID { get; set; } = ""; | |
| 19 | 新增: public string Name { get; set; } = ""; | |
| 20 | 新增: public string State { get; set; } = "downloading"; | |
| 21 | 新增: public string Error { get; set; } = ""; | |
| 22 | 新增: public long Size { get; set; } | |
| 23 | 新增: public long Written { get; set; } | |
| 24 | 新增: public DateTimeOffset Started { get; set; } = DateTimeOffset.UtcNow; | |
| 25 | 新增: } | |
| 26 | 新增: private sealed class Transfer(FileStream file, string session, long epoch) | |
| 27 | 新增: { | |
| 28 | 新增: internal readonly FileStream File = file; | |
| 29 | 新增: internal bool SessionValid => ClipboardAgent.Current is { SessionEventsRegistered: true } agent && agent.Session == session && agent.SessionEpoch == epoch; | |
| 30 | 新增: internal int Sequence; | |
| 31 | 新增: internal DateTimeOffset Used = DateTimeOffset.UtcNow; | |
| 32 | 新增: } | |
| 33 | 新增: private static readonly object Gate = new(); | |
| 34 | 新增: private static readonly Dictionary<string, Download> Downloads = new(); | |
| 35 | 新增: private static readonly Dictionary<string, Transfer> Transfers = new(); | |
| 36 | 新增: private static readonly System.Threading.Timer TransferExpiry = new(_ => | |
| 37 | 新增: { | |
| 38 | 新增: lock (Gate) | |
| 39 | 新增: { | |
| 40 | 新增: if (Transfers.Count == 0) return; | |
| 41 | 新增: bool available; | |
| 42 | 新增: try { available = SessionGuard.Available(); } catch { available = false; } | |
| 43 | 新增: foreach (var pair in Transfers.ToArray()) | |
| 44 | 新增: if (!available || !pair.Value.SessionValid || DateTimeOffset.UtcNow - pair.Value.Used > TimeSpan.FromMinutes(2)) | |
| 45 | 新增: { pair.Value.File.Dispose(); Transfers.Remove(pair.Key); } | |
| 46 | 新增: } | |
| 47 | 新增: }, null, 2000, 2000); | |
| 48 | 新增: private static string? directory; | |
| 49 | 新增: [DllImport("kernel32.dll", CharSet = CharSet.Unicode, ExactSpelling = true, SetLastError = true)] | |
| 50 | 新增: private static extern uint GetFinalPathNameByHandleW(SafeFileHandle handle, StringBuilder path, uint length, uint flags); | |
| 51 | 新增: | |
| 52 | 新增: private static FileStream OpenSource(Download item) | |
| 53 | 新增: { | |
| 54 | 新增: var path = Source(item); | |
| 55 | 新增: var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read); | |
| 56 | 新增: try | |
| 57 | 新增: { | |
| 58 | 新增: var actual = new StringBuilder(32768); | |
| 59 | 新增: var length = GetFinalPathNameByHandleW(stream.SafeFileHandle, actual, (uint)actual.Capacity, 0); | |
| 60 | 新增: if (length == 0 || length >= actual.Capacity || | |
| 61 | 新增: !string.Equals(actual.ToString(), @"\\?\" + Path.GetFullPath(path), StringComparison.OrdinalIgnoreCase) || | |
| 62 | 新增: stream.Length > AttachmentsRpc.FileLimit) | |
| 63 | 新增: throw new InvalidDataException("desktop_download_file_invalid"); | |
| 64 | 新增: return stream; | |
| 65 | 新增: } | |
| 66 | 新增: catch { stream.Dispose(); throw; } | |
| 67 | 新增: } | |
| 68 | 新增: | |
| 69 | 新增: private static string DirectoryPath() | |
| 70 | 新增: { | |
| 71 | 新增: if (directory is not null) return directory; | |
| 72 | 新增: var home = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile); | |
| 73 | 新增: var root = Path.Combine(home, "Cage", "DesktopDownloads"); | |
| 74 | 新增: using var user = WindowsIdentity.GetCurrent(); | |
| 75 | 新增: foreach (var path in new[] { Path.Combine(home, "Cage"), root }) | |
| 76 | 新增: { | |
| 77 | 新增: Directory.CreateDirectory(path); | |
| 78 | 新增: var info = new DirectoryInfo(path); | |
| 79 | 新增: if (info.Attributes.HasFlag(FileAttributes.ReparsePoint) || info.GetAccessControl().GetOwner(typeof(SecurityIdentifier))?.Value != user.User?.Value) | |
| 80 | 新增: throw new InvalidDataException("desktop_download_directory_invalid"); | |
| 81 | 新增: } | |
| 82 | 新增: var manifest = Path.Combine(root, "downloads.json"); | |
| 83 | 新增: if (File.Exists(manifest)) | |
| 84 | 新增: { | |
| 85 | 新增: var info = new FileInfo(manifest); | |
| 86 | 新增: if (info.Attributes.HasFlag(FileAttributes.ReparsePoint) || info.Length > 1 << 20) throw new InvalidDataException("desktop_download_catalog_invalid"); | |
| 87 | 新增: var saved = JsonSerializer.Deserialize<Download[]>(File.ReadAllBytes(manifest)) ?? []; | |
| 88 | 新增: foreach (var item in saved.TakeLast(100)) | |
| 89 | 新增: { | |
| 90 | 新增: if (!Guid.TryParseExact(item.ID, "D", out _) || !AttachmentsRpc.NameValid(item.Name)) continue; | |
| 91 | 新增: if (item.State == "downloading") { item.State = "failed"; item.Error = "保存过程被中断,请从 Claude Desktop 重新下载。"; } | |
| 92 | 新增: Downloads[item.ID] = item; | |
| 93 | 新增: } | |
| 94 | 新增: } | |
| 95 | 新增: directory = root; | |
| 96 | 新增: return root; | |
| 97 | 新增: } | |
| 98 | 新增: private static string Source(Download item) => Path.Combine(DirectoryPath(), item.ID, item.Name); | |
| 99 | 新增: private static void Persist() | |
| 100 | 新增: { | |
| 101 | 新增: var file = Path.Combine(DirectoryPath(), "downloads.json"); | |
| 102 | 新增: var temporary = file + "." + Guid.NewGuid().ToString("N"); | |
| 103 | 新增: try | |
| 104 | 新增: { | |
| 105 | 新增: using (var stream = new FileStream(temporary, FileMode.CreateNew, FileAccess.Write, FileShare.None)) | |
| 106 | 新增: { | |
| 107 | 新增: JsonSerializer.Serialize(stream, Downloads.Values.TakeLast(100).ToArray()); | |
| 108 | 新增: stream.Flush(true); | |
| 109 | 新增: } | |
| 110 | 新增: File.Move(temporary, file, true); | |
| 111 | 新增: } | |
| 112 | 新增: finally { if (File.Exists(temporary)) File.Delete(temporary); } | |
| 113 | 新增: } | |
| 114 | 新增: | |
| 115 | 新增: internal static string Reserve(string name, Action<string> submit) | |
| 116 | 新增: { | |
| 117 | 新增: if (!AttachmentsRpc.NameValid(name)) throw new InvalidDataException("desktop_download_name_invalid"); | |
| 118 | 新增: lock (Gate) | |
| 119 | 新增: { | |
| 120 | 新增: DirectoryPath(); | |
| 121 | 新增: if (Downloads.Values.Count(item => item.State == "downloading") >= 12) throw new InvalidDataException("desktop_download_limit"); | |
| 122 | 新增: var item = new Download { ID = Guid.NewGuid().ToString("D"), Name = name }; | |
| 123 | 新增: var folder = Path.GetDirectoryName(Source(item))!; | |
| 124 | 新增: Directory.CreateDirectory(folder); | |
| 125 | 新增: var watcher = new FileSystemWatcher(folder) { NotifyFilter = NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.Size }; | |
| 126 | 新增: var changed = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); | |
| 127 | 新增: var renamed = 0; | |
| 128 | 新增: watcher.Changed += (_, eventArgs) => { if (eventArgs.Name == name) changed.TrySetResult(); }; | |
| 129 | 新增: watcher.Renamed += (_, eventArgs) => { if (eventArgs.Name == name) { Interlocked.Exchange(ref renamed, 1); changed.TrySetResult(); } }; | |
| 130 | 新增: watcher.Error += (_, _) => changed.TrySetException(new InvalidDataException("desktop_download_watch_failed")); | |
| 131 | 新增: 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 | 新增: } | |
| 138 | 新增: Downloads.Add(item.ID, item); | |
| 139 | 新增: Persist(); | |
| 140 | 新增: try { submit(Source(item)); } | |
| 141 | 新增: catch | |
| 142 | 新增: { | |
| 143 | 新增: watcher.Dispose(); item.State = "failed"; item.Error = "客机保存窗口未接收文件位置,请重新下载。"; Persist(); throw; | |
| 144 | 新增: } | |
| 145 | 新增: _ = Task.Run(async () => | |
| 146 | 新增: { | |
| 147 | 新增: using (watcher) | |
| 148 | 新增: using (var timeout = new CancellationTokenSource(TimeSpan.FromMinutes(30))) | |
| 149 | 新增: { | |
| 150 | 新增: try | |
| 151 | 新增: { | |
| 152 | 新增: await changed.Task.WaitAsync(timeout.Token); | |
| 153 | 新增: while (true) | |
| 154 | 新增: { | |
| 155 | 新增: timeout.Token.ThrowIfCancellationRequested(); | |
| 156 | 新增: if (!File.Exists(Source(item) + ".crdownload")) | |
| 157 | 新增: { | |
| 158 | 新增: try | |
| 159 | 新增: { | |
| 160 | 新增: using var source = OpenSource(item); | |
| 161 | 新增: if (source.Length == 0 && Volatile.Read(ref renamed) == 0) throw new IOException("empty reservation is waiting for completion"); | |
| 162 | 新增: lock (Gate) | |
| 163 | 新增: { | |
| 164 | 新增: item.Size = source.Length; item.Written = File.GetLastWriteTimeUtc(Source(item)).Ticks; | |
| 165 | 新增: item.State = "saved"; Persist(); | |
| 166 | 新增: } | |
| 167 | 新增: return; | |
| 168 | 新增: } | |
| 169 | 新增: catch (IOException) { } | |
| 170 | 新增: } | |
| 171 | 新增: await Task.Delay(100, timeout.Token); | |
| 172 | 新增: } | |
| 173 | 新增: } | |
| 174 | 新增: catch | |
| 175 | 新增: { | |
| 176 | 新增: lock (Gate) { item.State = "failed"; item.Error = "未能确认文件保存完成,请从 Claude Desktop 重新下载。"; Persist(); } | |
| 177 | 新增: } | |
| 178 | 新增: } | |
| 179 | 新增: }); | |
| 180 | 新增: return item.ID; | |
| 181 | 新增: } | |
| 182 | 新增: } | |
| 183 | 新增: | |
| 184 | 新增: internal static JsonArray Snapshot() | |
| 185 | 新增: { | |
| 186 | 新增: lock (Gate) | |
| 187 | 新增: { | |
| 188 | 新增: DirectoryPath(); | |
| 189 | 新增: return new JsonArray(Downloads.Values.TakeLast(100).Reverse().Select(item => (JsonNode)new JsonObject | |
| 190 | 新增: { | |
| 191 | 新增: ["id"] = item.ID, ["name"] = item.Name, ["state"] = item.State, ["target"] = "desktop", | |
| 192 | 新增: ["receivedBytes"] = item.Size, ["totalBytes"] = item.Size, ["retryable"] = false, | |
| 193 | 新增: ["error"] = item.Error, ["startedAt"] = item.Started.ToString("O"), | |
| 194 | 新增: }).ToArray()); | |
| 195 | 新增: } | |
| 196 | 新增: } | |
| 197 | 新增: | |
| 198 | 新增: internal static (string ID, bool Directory)? FindPath(string path) | |
| 199 | 新增: { | |
| 200 | 新增: lock (Gate) | |
| 201 | 新增: { | |
| 202 | 新增: DirectoryPath(); | |
| 203 | 新增: foreach (var item in Downloads.Values) | |
| 204 | 新增: { | |
| 205 | 新增: var source = Source(item); | |
| 206 | 新增: if (string.Equals(path, source, StringComparison.OrdinalIgnoreCase)) return (item.ID, false); | |
| 207 | 新增: if (string.Equals(path, Path.GetDirectoryName(source), StringComparison.OrdinalIgnoreCase)) return (item.ID, true); | |
| 208 | 新增: } | |
| 209 | 新增: return null; | |
| 210 | 新增: } | |
| 211 | 新增: } | |
| 212 | 新增: | |
| 213 | 新增: internal static JsonObject Read(JsonObject input) | |
| 214 | 新增: { | |
| 215 | 新增: lock (Gate) | |
| 216 | 新增: { | |
| 217 | 新增: SessionGuard.Assert(); DirectoryPath(); | |
| 218 | 新增: foreach (var pair in Transfers.ToArray()) | |
| 219 | 新增: if (!pair.Value.SessionValid || DateTimeOffset.UtcNow - pair.Value.Used > TimeSpan.FromMinutes(2)) { pair.Value.File.Dispose(); Transfers.Remove(pair.Key); } | |
| 220 | 新增: var action = input["action"]?.GetValue<string>(); | |
| 221 | 新增: if (action == "files-download-retry") | |
| 222 | 新增: { | |
| 223 | 新增: var id = input["id"]?.GetValue<string>() ?? ""; | |
| 224 | 新增: if (!Downloads.TryGetValue(id, out var item) || item.State != "saved") throw new InvalidDataException("desktop_download_incomplete"); | |
| 225 | 新增: using var file = OpenSource(item); | |
| 226 | 新增: if (file.Length != item.Size || File.GetLastWriteTimeUtc(Source(item)).Ticks != item.Written) throw new InvalidDataException("desktop_download_changed"); | |
| 227 | 新增: return new JsonObject { ["ok"] = true }; | |
| 228 | 新增: } | |
| 229 | 新增: if (action == "files-download-open") | |
| 230 | 新增: { | |
| 231 | 新增: var agent = ClipboardAgent.Current; | |
| 232 | 新增: if (agent is null || !agent.SessionEventsRegistered) throw new InvalidDataException("desktop_download_session_unavailable"); | |
| 233 | 新增: var id = input["id"]?.GetValue<string>() ?? ""; | |
| 234 | 新增: if (!Downloads.TryGetValue(id, out var item) || item.State != "saved" || Transfers.Count >= 12) throw new InvalidDataException("desktop_download_unavailable"); | |
| 235 | 新增: var file = OpenSource(item); | |
| 236 | 新增: if (file.Length != item.Size || File.GetLastWriteTimeUtc(Source(item)).Ticks != item.Written) | |
| 237 | 新增: { file.Dispose(); throw new InvalidDataException("desktop_download_changed"); } | |
| 238 | 新增: var key = Convert.ToHexString(RandomNumberGenerator.GetBytes(32)).ToLowerInvariant(); | |
| 239 | 新增: Transfers.Add(key, new Transfer(file, agent.Session, agent.SessionEpoch)); | |
| 240 | 新增: return new JsonObject { ["transfer"] = key, ["size"] = file.Length, ["name"] = item.Name }; | |
| 241 | 新增: } | |
| 242 | 新增: var transfer = input["transfer"]?.GetValue<string>() ?? ""; | |
| 243 | 新增: if (action == "files-download-close") | |
| 244 | 新增: { | |
| 245 | 新增: if (Transfers.Remove(transfer, out var old)) old.File.Dispose(); | |
| 246 | 新增: return new JsonObject { ["ok"] = true }; | |
| 247 | 新增: } | |
| 248 | 新增: if (action != "files-download-read" || !Transfers.TryGetValue(transfer, out var current) || current.Sequence != input["sequence"]?.GetValue<int>()) | |
| 249 | 新增: throw new InvalidDataException("desktop_download_transfer_invalid"); | |
| 250 | 新增: var data = new byte[64 << 10]; | |
| 251 | 新增: var count = current.File.Read(data); | |
| 252 | 新增: current.Used = DateTimeOffset.UtcNow; | |
| 253 | 新增: var result = new JsonObject { ["data"] = Convert.ToBase64String(data, 0, count), ["sequence"] = ++current.Sequence, ["eof"] = current.File.Position == current.File.Length }; | |
| 254 | 新增: if (current.File.Position == current.File.Length) { current.File.Dispose(); Transfers.Remove(transfer); } | |
| 255 | 新增: return result; | |
| 256 | 新增: } | |
| 257 | 新增: } | |
| 258 | 新增:} | |
| @@ -0,0 +1,262 @@ | ||
| 1 | 新增:using System.Diagnostics; | |
| 2 | 新增:using System.Runtime.InteropServices; | |
| 3 | 新增:using System.Text.Json.Nodes; | |
| 4 | 新增:using System.Windows.Automation; | |
| 5 | 新增: | |
| 6 | 新增:namespace Cage.GuestClipboard; | |
| 7 | 新增: | |
| 8 | 新增:internal static class WindowsDesktopFiles | |
| 9 | 新增:{ | |
| 10 | 新增: private sealed record Chooser(WindowsFileDialogNative.Owner Owner, IntPtr Window, IntPtr Stamp, | |
| 11 | 新增: bool Directory, bool Multiple, string Session, long Epoch, string SaveName = "") | |
| 12 | 新增: { | |
| 13 | 新增: internal string ID = ""; | |
| 14 | 新增: internal bool Submitting; | |
| 15 | 新增: internal readonly DateTimeOffset Created = DateTimeOffset.UtcNow; | |
| 16 | 新增: internal bool SessionValid => SessionGuard.Available() && ClipboardAgent.Current is { SessionEventsRegistered: true } agent && agent.Session == Session && agent.SessionEpoch == Epoch; | |
| 17 | 新增: internal void Assert(bool foreground = false) | |
| 18 | 新增: { | |
| 19 | 新增: if (!SessionValid) throw new InvalidDataException("file_dialog_changed"); | |
| 20 | 新增: WindowsFileDialogNative.Assert(Owner, Window, Stamp, foreground); | |
| 21 | 新增: } | |
| 22 | 新增: internal void AcceptSelection() | |
| 23 | 新增: { | |
| 24 | 新增: Assert(true); | |
| 25 | 新增: // Windows 11 can expose the native Open split button as a UIA | |
| 26 | 新增: // Pane without InvokePattern. BM_CLICK addresses that exact button. | |
| 27 | 新增: WindowsFileDialogNative.Accept(Owner, Window, Stamp); | |
| 28 | 新增: } | |
| 29 | 新增: } | |
| 30 | 新增: private static readonly object Gate = new(); | |
| 31 | 新增: private static readonly Dictionary<string, Chooser> Choosers = new(); | |
| 32 | 新增: private sealed record OpenRequest(string Path, string Action, string Session, long Epoch, Action Validate) | |
| 33 | 新增: { | |
| 34 | 新增: internal readonly DateTimeOffset Created = DateTimeOffset.UtcNow; | |
| 35 | 新增: internal bool Claimed; | |
| 36 | 新增: } | |
| 37 | 新增: private static readonly Dictionary<string, OpenRequest> Opens = new(); | |
| 38 | 新增: [DllImport("user32.dll", ExactSpelling = true)] private static extern bool PostMessageW(IntPtr window, uint message, IntPtr wparam, IntPtr lparam); | |
| 39 | 新增: | |
| 40 | 新增: private static string ButtonLabel(string name) => System.Text.RegularExpressions.Regex.Replace(name.Replace("&", ""), @"\s*\([A-Za-z]\)\s*$", "").Trim().TrimEnd('.', '…'); | |
| 41 | 新增: | |
| 42 | 新增: private static bool FilenameControl(AutomationElement element, IntPtr dialog) | |
| 43 | 新增: { | |
| 44 | 新增: AutomationElement? current = element; | |
| 45 | 新增: for (var depth = 0; current is not null && depth < 4; depth++, current = TreeWalker.ControlViewWalker.GetParent(current)) | |
| 46 | 新增: { | |
| 47 | 新增: var handle = new IntPtr(current.Current.NativeWindowHandle); | |
| 48 | 新增: if (handle == dialog) return false; | |
| 49 | 新增: var id = handle == IntPtr.Zero ? 0 : WindowsFileDialogNative.GetDlgCtrlID(handle); | |
| 50 | 新增: if (id is 1148 or 1152 || current.Current.AutomationId is "1148" or "1152" or "FileNameControlHost") return true; | |
| 51 | 新增: } | |
| 52 | 新增: return false; | |
| 53 | 新增: } | |
| 54 | 新增: | |
| 55 | 新增: private static IntPtr FilenameHandle(Chooser chooser) | |
| 56 | 新增: { | |
| 57 | 新增: chooser.Assert(true); | |
| 58 | 新增: // Windows Shell dialogs can replace their UIA edit provider | |
| 59 | 新增: // while uploads are in flight. Reacquire it inside the stamped dialog. | |
| 60 | 新增: var root = AutomationElement.FromHandle(chooser.Window); | |
| 61 | 新增: var fields = root.FindAll(TreeScope.Descendants, new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.Edit)); | |
| 62 | 新增: var result = IntPtr.Zero; | |
| 63 | 新增: foreach (AutomationElement element in fields) | |
| 64 | 新增: { | |
| 65 | 新增: var current = element.Current; | |
| 66 | 新增: if (current.ProcessId != chooser.Owner.PID || current.IsOffscreen || !FilenameControl(element, chooser.Window) || | |
| 67 | 新增: !element.TryGetCurrentPattern(ValuePattern.Pattern, out var candidate) || ((ValuePattern)candidate).Current.IsReadOnly) continue; | |
| 68 | 新增: if (result != IntPtr.Zero) throw new InvalidDataException("file_dialog_selection_invalid"); | |
| 69 | 新增: result = new IntPtr(current.NativeWindowHandle); | |
| 70 | 新增: } | |
| 71 | 新增: chooser.Assert(true); | |
| 72 | 新增: return result != IntPtr.Zero ? result : throw new InvalidDataException("file_dialog_selection_invalid"); | |
| 73 | 新增: } | |
| 74 | 新增: | |
| 75 | 新增: private static Chooser? Inspect(WindowsFileDialogNative.Owner owner, IntPtr window) | |
| 76 | 新增: { | |
| 77 | 新增: var root = AutomationElement.FromHandle(window); | |
| 78 | 新增: var elements = root.FindAll(TreeScope.Descendants, Condition.TrueCondition); | |
| 79 | 新增: if (elements.Count > 4096) throw new InvalidDataException("file_dialog_control_limit"); | |
| 80 | 新增: AutomationElement? accept = null, field = null; | |
| 81 | 新增: bool multiple = false; | |
| 82 | 新增: foreach (AutomationElement element in elements) | |
| 83 | 新增: { | |
| 84 | 新增: var current = element.Current; | |
| 85 | 新增: if (current.ProcessId != owner.PID || current.IsOffscreen) continue; | |
| 86 | 新增: var controlID = current.NativeWindowHandle == 0 ? 0 : WindowsFileDialogNative.GetDlgCtrlID(new IntPtr(current.NativeWindowHandle)); | |
| 87 | 新增: if ((controlID == 1 || current.AutomationId == "1") && | |
| 88 | 新增: (element.TryGetCurrentPattern(InvokePattern.Pattern, out _) || | |
| 89 | 新增: controlID == 1 && current.ClassName == "Button")) accept = element; | |
| 90 | 新增: if (current.ControlType == ControlType.Edit && FilenameControl(element, window) && | |
| 91 | 新增: element.TryGetCurrentPattern(ValuePattern.Pattern, out var editable) && !((ValuePattern)editable).Current.IsReadOnly) field = element; | |
| 92 | 新增: if (current.ControlType is { } type && (type == ControlType.List || type == ControlType.DataGrid) && | |
| 93 | 新增: element.TryGetCurrentPattern(SelectionPattern.Pattern, out var selection)) multiple |= ((SelectionPattern)selection).Current.CanSelectMultiple; | |
| 94 | 新增: } | |
| 95 | 新增: if (accept is null || field is null) return null; | |
| 96 | 新增: var label = ButtonLabel(accept.Current.Name); | |
| 97 | 新增: bool directory = label is "Select Folder" or "Choose Folder" or "选择文件夹" or "選擇資料夾"; | |
| 98 | 新增: bool save = label is "Save" or "保存" or "儲存" or "Enregistrer" or "Speichern" or "Guardar" or "Salvar" or "Salva" or "Сохранить" or "저장"; | |
| 99 | 新增: if (!directory && !save && label is not ("Open" or "打开" or "開啟" or "Ouvrir" or "Öffnen" or "Abrir" or "Apri" or "Openen" or "開く" or "Открыть" or "열기")) return null; | |
| 100 | 新增: var saveName = save ? ((ValuePattern)field.GetCurrentPattern(ValuePattern.Pattern)).Current.Value : ""; | |
| 101 | 新增: if (save && !AttachmentsRpc.NameValid(saveName)) return null; | |
| 102 | 新增: var agent = ClipboardAgent.Current; | |
| 103 | 新增: if (agent is null || !agent.SessionEventsRegistered) throw new InvalidDataException("file_dialog_session_unavailable"); | |
| 104 | 新增: var stamp = WindowsFileDialogNative.Stamp(owner, window); | |
| 105 | 新增: return new Chooser(owner, window, stamp, directory, multiple && !directory, agent.Session, agent.SessionEpoch, saveName); | |
| 106 | 新增: } | |
| 107 | 新增: | |
| 108 | 新增: internal static JsonObject Poll(WindowsFileDialogNative.Owner owner) | |
| 109 | 新增: { | |
| 110 | 新增: lock (Gate) | |
| 111 | 新增: { | |
| 112 | 新增: foreach (var pair in Choosers.ToArray()) | |
| 113 | 新增: if (DateTimeOffset.UtcNow - pair.Value.Created > TimeSpan.FromMinutes(30) || | |
| 114 | 新增: !pair.Value.SessionValid || | |
| 115 | 新增: !WindowsFileDialogNative.Alive(pair.Value.Owner, pair.Value.Window, pair.Value.Stamp)) Retire(pair.Key); | |
| 116 | 新增: foreach (var window in WindowsFileDialogNative.Candidates(owner)) | |
| 117 | 新增: { | |
| 118 | 新增: if (Choosers.Values.Any(value => value.Window == window)) continue; | |
| 119 | 新增: if (Choosers.Count >= 12) throw new InvalidDataException("file_dialog_request_limit"); | |
| 120 | 新增: var chooser = Inspect(owner, window); | |
| 121 | 新增: if (chooser is null) continue; | |
| 122 | 新增: try | |
| 123 | 新增: { | |
| 124 | 新增: if (chooser.SaveName != "") | |
| 125 | 新增: { | |
| 126 | 新增: chooser.ID = WindowsDesktopDownloads.Reserve(chooser.SaveName, path => | |
| 127 | 新增: { | |
| 128 | 新增: chooser.Assert(true); | |
| 129 | 新增: var field = FilenameHandle(chooser); | |
| 130 | 新增: WindowsFileDialogNative.SetFilename(chooser.Owner, chooser.Window, chooser.Stamp, field, path); | |
| 131 | 新增: chooser.Assert(true); | |
| 132 | 新增: chooser.AcceptSelection(); | |
| 133 | 新增: }); | |
| 134 | 新增: } | |
| 135 | 新增: else chooser.ID = chooser.Directory ? Guid.NewGuid().ToString("D") : | |
| 136 | 新增: AttachmentsRpc.StartChooserBatch(Guid.NewGuid().ToString("N"), () => chooser.Assert())["id"]!.GetValue<string>(); | |
| 137 | 新增: Choosers.Add(chooser.ID, chooser); | |
| 138 | 新增: } | |
| 139 | 新增: catch { WindowsFileDialogNative.Remove(window, chooser.Stamp); throw; } | |
| 140 | 新增: } | |
| 141 | 新增: return new JsonObject | |
| 142 | 新增: { | |
| 143 | 新增: ["available"] = true, | |
| 144 | 新增: ["uploads"] = new JsonArray(Choosers.Values.Where(value => !value.Submitting && value.SaveName == "").Select(value => (JsonNode)new JsonObject | |
| 145 | 新增: { | |
| 146 | 新增: ["id"] = value.ID, ["target"] = "desktop", ["kind"] = "chooser", ["multiple"] = value.Multiple, ["directory"] = value.Directory, | |
| 147 | 新增: }).ToArray()), | |
| 148 | 新增: ["downloads"] = WindowsDesktopDownloads.Snapshot(), ["opens"] = OpenSnapshot(), | |
| 149 | 新增: }; | |
| 150 | 新增: } | |
| 151 | 新增: } | |
| 152 | 新增: | |
| 153 | 新增: private static void ExpireOpens() | |
| 154 | 新增: { | |
| 155 | 新增: var agent = ClipboardAgent.Current; | |
| 156 | 新增: var available = SessionGuard.Available(); | |
| 157 | 新增: foreach (var pair in Opens.ToArray()) | |
| 158 | 新增: if (agent is null || !agent.SessionEventsRegistered || !available || | |
| 159 | 新增: pair.Value.Session != agent.Session || pair.Value.Epoch != agent.SessionEpoch || | |
| 160 | 新增: DateTimeOffset.UtcNow - pair.Value.Created >= (pair.Value.Claimed ? TimeSpan.FromMinutes(30) : TimeSpan.FromSeconds(60))) Opens.Remove(pair.Key); | |
| 161 | 新增: } | |
| 162 | 新增: | |
| 163 | 新增: internal static void QueueOpen(string path, string action, Action validate) | |
| 164 | 新增: { | |
| 165 | 新增: if (!Path.IsPathFullyQualified(path) || path.Length > 32767 || path.Contains('\0') || action is not ("open" or "reveal")) | |
| 166 | 新增: throw new InvalidDataException("file_open_request_invalid"); | |
| 167 | 新增: lock (Gate) | |
| 168 | 新增: { | |
| 169 | 新增: SessionGuard.Assert(); ExpireOpens(); validate(); | |
| 170 | 新增: 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)); | |
| 173 | 新增: } | |
| 174 | 新增: } | |
| 175 | 新增: | |
| 176 | 新增: internal static JsonArray OpenSnapshot() | |
| 177 | 新增: { | |
| 178 | 新增: lock (Gate) | |
| 179 | 新增: { | |
| 180 | 新增: ExpireOpens(); | |
| 181 | 新增: return new JsonArray(Opens.Where(pair => !pair.Value.Claimed).Select(pair => (JsonNode)new JsonObject { ["id"] = pair.Key }).ToArray()); | |
| 182 | 新增: } | |
| 183 | 新增: } | |
| 184 | 新增: | |
| 185 | 新增: internal static JsonObject OpenAction(string id, bool complete) | |
| 186 | 新增: { | |
| 187 | 新增: lock (Gate) | |
| 188 | 新增: { | |
| 189 | 新增: ExpireOpens(); | |
| 190 | 新增: if (!Opens.TryGetValue(id, out var request)) return new JsonObject { [complete ? "ok" : "handled"] = true }; | |
| 191 | 新增: if (complete) | |
| 192 | 新增: { | |
| 193 | 新增: Opens.Remove(id); | |
| 194 | 新增: try { request.Validate(); } catch { } | |
| 195 | 新增: return new JsonObject { ["ok"] = true }; | |
| 196 | 新增: } | |
| 197 | 新增: if (request.Claimed) return new JsonObject { ["handled"] = true }; | |
| 198 | 新增: try { request.Validate(); } | |
| 199 | 新增: catch { Opens.Remove(id); throw new InvalidDataException("file_open_target_changed"); } | |
| 200 | 新增: var result = new JsonObject { ["id"] = id, ["action"] = request.Action }; | |
| 201 | 新增: if (WindowsDesktopDownloads.FindPath(request.Path) is { } download) | |
| 202 | 新增: { result["download_id"] = download.ID; result["directory"] = download.Directory; } | |
| 203 | 新增: else result["path"] = request.Path; | |
| 204 | 新增: request.Claimed = true; | |
| 205 | 新增: return result; | |
| 206 | 新增: } | |
| 207 | 新增: } | |
| 208 | 新增: | |
| 209 | 新增: private static void Retire(string id) | |
| 210 | 新增: { | |
| 211 | 新增: if (!Choosers.Remove(id, out var chooser)) return; | |
| 212 | 新增: WindowsFileDialogNative.Remove(chooser.Window, chooser.Stamp); | |
| 213 | 新增: if (!chooser.Submitting) AttachmentsRpc.CancelBatch(id); | |
| 214 | 新增: } | |
| 215 | 新增: | |
| 216 | 新增: internal static bool Contains(string id) { lock (Gate) return Choosers.ContainsKey(id); } | |
| 217 | 新增: | |
| 218 | 新增: internal static void Cancel(string id) | |
| 219 | 新增: { | |
| 220 | 新增: lock (Gate) | |
| 221 | 新增: { | |
| 222 | 新增: if (!Choosers.TryGetValue(id, out var chooser)) return; | |
| 223 | 新增: if (chooser.SessionValid && WindowsFileDialogNative.Alive(chooser.Owner, chooser.Window, chooser.Stamp)) | |
| 224 | 新增: PostMessageW(chooser.Window, 0x0111, new IntPtr(2), IntPtr.Zero); | |
| 225 | 新增: Retire(id); | |
| 226 | 新增: AttachmentsRpc.CancelBatch(id); | |
| 227 | 新增: } | |
| 228 | 新增: } | |
| 229 | 新增: | |
| 230 | 新增: internal static async Task Finish(string id, string[] paths, CancellationToken token) | |
| 231 | 新增: { | |
| 232 | 新增: Chooser chooser; | |
| 233 | 新增: lock (Gate) | |
| 234 | 新增: { | |
| 235 | 新增: if (!Choosers.TryGetValue(id, out chooser!) || chooser.Submitting || paths.Length == 0 || | |
| 236 | 新增: paths.Length > (chooser.Multiple ? 100 : 1)) throw new InvalidDataException("file_dialog_selection_invalid"); | |
| 237 | 新增: chooser.Assert(true); | |
| 238 | 新增: chooser.Submitting = true; | |
| 239 | 新增: } | |
| 240 | 新增: try | |
| 241 | 新增: { | |
| 242 | 新增: foreach (var path in paths) | |
| 243 | 新增: if (!Path.IsPathFullyQualified(path) || path.Contains('"') || path.Contains('\0') || | |
| 244 | 新增: (chooser.Directory ? !Directory.Exists(path) : !File.Exists(path))) throw new InvalidDataException("file_dialog_selection_invalid"); | |
| 245 | 新增: string selection = paths.Length == 1 ? paths[0] : string.Join(" ", paths.Select(path => "\"" + path + "\"")); | |
| 246 | 新增: chooser.Assert(true); | |
| 247 | 新增: var field = FilenameHandle(chooser); | |
| 248 | 新增: WindowsFileDialogNative.SetFilename(chooser.Owner, chooser.Window, chooser.Stamp, field, selection); | |
| 249 | 新增: chooser.Assert(true); | |
| 250 | 新增: chooser.AcceptSelection(); | |
| 251 | 新增: var deadline = Stopwatch.StartNew(); | |
| 252 | 新增: while (WindowsFileDialogNative.Alive(chooser.Owner, chooser.Window, chooser.Stamp)) | |
| 253 | 新增: { | |
| 254 | 新增: chooser.Assert(); | |
| 255 | 新增: if (deadline.Elapsed > TimeSpan.FromSeconds(4)) throw new InvalidDataException("file_dialog_still_open"); | |
| 256 | 新增: await Task.Delay(50, token); | |
| 257 | 新增: } | |
| 258 | 新增: lock (Gate) Retire(id); | |
| 259 | 新增: } | |
| 260 | 新增: finally { lock (Gate) chooser.Submitting = false; } | |
| 261 | 新增: } | |
| 262 | 新增:} | |
| @@ -0,0 +1,53 @@ | ||
| 1 | 新增:using System.Text; | |
| 2 | 新增:using System.Text.Json; | |
| 3 | 新增: | |
| 4 | 新增:namespace Cage.GuestClipboard; | |
| 5 | 新增: | |
| 6 | 新增:// Cage owns this preference file. Official serve-web does not consume disk | |
| 7 | 新增:// User settings; the broker applies this one key as a low-priority web default. | |
| 8 | 新增:internal static class WindowsEditorPreferences | |
| 9 | 新增:{ | |
| 10 | 新增: internal const string TrustKey = "security.workspace.trust.enabled"; | |
| 11 | 新增: internal static bool? TrustDefault(string cageEditorHome) | |
| 12 | 新增: { | |
| 13 | 新增: var user = Path.Combine(cageEditorHome, "User"); | |
| 14 | 新增: if (Directory.Exists(cageEditorHome) && new DirectoryInfo(cageEditorHome).Attributes.HasFlag(FileAttributes.ReparsePoint) || Directory.Exists(user) && new DirectoryInfo(user).Attributes.HasFlag(FileAttributes.ReparsePoint)) | |
| 15 | 新增: throw new InvalidDataException("editor_package_invalid"); | |
| 16 | 新增: Directory.CreateDirectory(user); | |
| 17 | 新增: var file = Path.Combine(user, "settings.json"); | |
| 18 | 新增: var original = "{}"; | |
| 19 | 新增: if (File.Exists(file)) | |
| 20 | 新增: { | |
| 21 | 新增: var info = new FileInfo(file); | |
| 22 | 新增: if (info.Attributes.HasFlag(FileAttributes.ReparsePoint) || info.Length > 1 << 20) return null; | |
| 23 | 新增: using var snapshot = new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.Read | FileShare.Delete); | |
| 24 | 新增: if (snapshot.Length > 1 << 20) return null; | |
| 25 | 新增: using var reader = new StreamReader(snapshot); | |
| 26 | 新增: original = reader.ReadToEnd(); | |
| 27 | 新增: } | |
| 28 | 新增: try | |
| 29 | 新增: { | |
| 30 | 新增: using var document = JsonDocument.Parse(original, new JsonDocumentOptions { AllowTrailingCommas = true, CommentHandling = JsonCommentHandling.Skip }); | |
| 31 | 新增: if (document.RootElement.ValueKind != JsonValueKind.Object) return null; | |
| 32 | 新增: if (document.RootElement.TryGetProperty(TrustKey, out var existing)) | |
| 33 | 新增: return existing.ValueKind is JsonValueKind.True or JsonValueKind.False ? existing.GetBoolean() : null; | |
| 34 | 新增: // Insert after the opening brace, preserving comments, whitespace, | |
| 35 | 新增: // trailing commas and every existing setting value. | |
| 36 | 新增: var bytes = Encoding.UTF8.GetBytes(original); | |
| 37 | 新增: var reader = new Utf8JsonReader(bytes, new JsonReaderOptions { AllowTrailingCommas = true, CommentHandling = JsonCommentHandling.Skip }); | |
| 38 | 新增: if (!reader.Read() || reader.TokenType != JsonTokenType.StartObject) return null; | |
| 39 | 新增: var offset = Encoding.UTF8.GetCharCount(bytes.AsSpan(0, (int)reader.BytesConsumed)); | |
| 40 | 新增: var property = "\n \"" + TrustKey + "\": false" + (document.RootElement.EnumerateObject().Any() ? "," : "") + "\n"; | |
| 41 | 新增: var updated = original.Insert(offset, property); | |
| 42 | 新增: var temporary = file + "." + Guid.NewGuid().ToString("N") + ".tmp"; | |
| 43 | 新增: try | |
| 44 | 新增: { | |
| 45 | 新增: File.WriteAllText(temporary, updated, new UTF8Encoding(false)); | |
| 46 | 新增: WindowsFilePublication.Replace(temporary, file, default).GetAwaiter().GetResult(); | |
| 47 | 新增: } | |
| 48 | 新增: finally { if (File.Exists(temporary)) File.Delete(temporary); } | |
| 49 | 新增: return false; | |
| 50 | 新增: } | |
| 51 | 新增: catch (JsonException) { return null; } // Preserve a malformed user file rather than replacing it. | |
| 52 | 新增: } | |
| 53 | 新增:} | |
| @@ -0,0 +1,146 @@ | ||
| 1 | 新增:using System.Collections.Concurrent; | |
| 2 | 新增:using System.Diagnostics; | |
| 3 | 新增:using System.Security.Cryptography; | |
| 4 | 新增:using System.Text.Json.Nodes; | |
| 5 | 新增:using System.Text.RegularExpressions; | |
| 6 | 新增: | |
| 7 | 新增:namespace Cage.GuestClipboard; | |
| 8 | 新增: | |
| 9 | 新增:// Only the authenticated project resolver supplies a folder. The official CLI | |
| 10 | 新增:// serves a pinned, offline web-server package over authenticated loopback. | |
| 11 | 新增:internal static class WindowsEditorServer | |
| 12 | 新增:{ | |
| 13 | 新增: private static readonly ConcurrentDictionary<string, Editor> Editors = new(StringComparer.Ordinal); | |
| 14 | 新增: private static readonly Regex Commit = new("^[a-f0-9]{40}$", RegexOptions.CultureInvariant); | |
| 15 | 新增: private static readonly Regex Listening = new(@"Web UI available at (http://127\.0\.0\.1:[1-9][0-9]*)", RegexOptions.CultureInvariant); | |
| 16 | 新增: internal sealed record Connection(string ID, string Project, string Grant, string Folder, string URL, bool? TrustDefault = null); | |
| 17 | 新增: | |
| 18 | 新增: internal static bool Installed() | |
| 19 | 新增: { | |
| 20 | 新增: try | |
| 21 | 新增: { | |
| 22 | 新增: var root = AppContext.BaseDirectory; | |
| 23 | 新增: return File.Exists(Path.Combine(root, "vscode-cli", "code.exe")) && | |
| 24 | 新增: File.Exists(Path.Combine(root, "vscode-server", "bin", "code-server.cmd")) && | |
| 25 | 新增: Commit.IsMatch((JsonNode.Parse(File.ReadAllText(Path.Combine(root, "editor-runtime.json"))) as JsonObject)?["commit"]?.GetValue<string>() ?? ""); | |
| 26 | 新增: } | |
| 27 | 新增: catch { return false; } | |
| 28 | 新增: } | |
| 29 | 新增: | |
| 30 | 新增: internal static async Task<Connection> Open(string project, string grant, bool restart, CancellationToken token) | |
| 31 | 新增: { | |
| 32 | 新增: var folder = ProjectRpc.Resolve(project, grant); | |
| 33 | 新增: if (!Installed()) throw new InvalidDataException("editor_components_missing"); | |
| 34 | 新增: var home = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "Cage", "Editors"); | |
| 35 | 新增: var trustDefault = WindowsEditorPreferences.TrustDefault(home); | |
| 36 | 新增: if (Editors.TryGetValue(project, out var existing)) | |
| 37 | 新增: { | |
| 38 | 新增: if (existing.Grant == grant && !existing.Process.HasExited && existing.Folder == folder && !restart) return existing.Connection with { TrustDefault = trustDefault }; | |
| 39 | 新增: if (Editors.TryRemove(project, out var old)) old.Dispose(); | |
| 40 | 新增: } | |
| 41 | 新增: var root = AppContext.BaseDirectory; | |
| 42 | 新增: var commit = (JsonNode.Parse(await File.ReadAllTextAsync(Path.Combine(root, "editor-runtime.json"), token)) as JsonObject)?["commit"]?.GetValue<string>() ?? ""; | |
| 43 | 新增: if (!Commit.IsMatch(commit)) throw new InvalidDataException("editor_components_missing"); | |
| 44 | 新增: var runtime = Path.Combine(home, "runtime"); | |
| 45 | 新增: var cached = Path.Combine(runtime, "serve-web", commit); | |
| 46 | 新增: if (!Directory.Exists(cached)) | |
| 47 | 新增: { | |
| 48 | 新增: var stage = cached + "." + Guid.NewGuid().ToString("N"); | |
| 49 | 新增: try { CopyPackage(Path.Combine(root, "vscode-server"), stage, token); Directory.Move(stage, cached); } | |
| 50 | 新增: finally { if (Directory.Exists(stage)) Directory.Delete(stage, true); } | |
| 51 | 新增: } | |
| 52 | 新增: if (!File.Exists(Path.Combine(cached, "bin", "code-server.cmd"))) throw new InvalidDataException("editor_components_missing"); | |
| 53 | 新增: var profile = Path.Combine(home, "profiles", project); | |
| 54 | 新增: Directory.CreateDirectory(profile); | |
| 55 | 新增: var tokenFile = Path.Combine(profile, "connection-token"); | |
| 56 | 新增: var portFile = Path.Combine(profile, "port"); | |
| 57 | 新增: ushort port = 0; | |
| 58 | 新增: if (File.Exists(portFile) && new FileInfo(portFile).Length <= 16) ushort.TryParse(await File.ReadAllTextAsync(portFile, token), out port); | |
| 59 | 新增: var secret = Convert.ToHexString(RandomNumberGenerator.GetBytes(32)).ToLowerInvariant(); | |
| 60 | 新增: await File.WriteAllTextAsync(tokenFile, secret, Protocol.Utf8, token); | |
| 61 | 新增: var start = new ProcessStartInfo(Path.Combine(root, "vscode-cli", "code.exe")) | |
| 62 | 新增: { | |
| 63 | 新增: UseShellExecute = false, CreateNoWindow = true, RedirectStandardInput = true, | |
| 64 | 新增: RedirectStandardOutput = true, RedirectStandardError = true, WorkingDirectory = folder, | |
| 65 | 新增: }; | |
| 66 | 新增: foreach (var arg in new[] { "serve-web", "--host", "127.0.0.1", "--port", port.ToString(System.Globalization.CultureInfo.InvariantCulture), "--connection-token-file", tokenFile, | |
| 67 | 新增: "--default-folder", folder, "--server-data-dir", Path.Combine(home, "server"), "--cli-data-dir", runtime, | |
| 68 | 新增: "--commit-id", commit, "--disable-telemetry", "--accept-server-license-terms" }) start.ArgumentList.Add(arg); | |
| 69 | 新增: // An offline package and a pinned commit prevent the CLI's version | |
| 70 | 新增: // updater. Browser assets/extensions still use Cage's controlled proxy. | |
| 71 | 新增: var process = Process.Start(start) ?? throw new InvalidDataException("editor_start_failed"); | |
| 72 | 新增: var editor = new Editor(project, grant, folder, process); | |
| 73 | 新增: try | |
| 74 | 新增: { | |
| 75 | 新增: editor.Job = new GuestProcessJob(process); | |
| 76 | 新增: var address = new TaskCompletionSource<string>(TaskCreationOptions.RunContinuationsAsynchronously); | |
| 77 | 新增: editor.Output = Drain(process.StandardOutput, address); | |
| 78 | 新增: editor.Errors = Drain(process.StandardError, address); | |
| 79 | 新增: using var timeout = CancellationTokenSource.CreateLinkedTokenSource(token); timeout.CancelAfter(TimeSpan.FromSeconds(20)); | |
| 80 | 新增: var url = await address.Task.WaitAsync(timeout.Token); | |
| 81 | 新增: var endpoint = new Uri(url); | |
| 82 | 新增: await File.WriteAllTextAsync(portFile, endpoint.Port.ToString(System.Globalization.CultureInfo.InvariantCulture), Protocol.Utf8, token); | |
| 83 | 新增: editor.Connection = new Connection(Guid.NewGuid().ToString("N"), project, grant, folder, "http://" + project + ".cage-editor.localhost:" + endpoint.Port + "/?tkn=" + Uri.EscapeDataString(secret), trustDefault); | |
| 84 | 新增: if (ProjectRpc.Resolve(project, grant) != folder || process.HasExited) throw new InvalidDataException("project_grant_unavailable"); | |
| 85 | 新增: if (!Editors.TryAdd(project, editor)) throw new InvalidDataException("editor_start_busy"); | |
| 86 | 新增: return editor.Connection; | |
| 87 | 新增: } | |
| 88 | 新增: catch { editor.Dispose(); throw; } | |
| 89 | 新增: } | |
| 90 | 新增: | |
| 91 | 新增: private static async Task Drain(StreamReader reader, TaskCompletionSource<string> listening) | |
| 92 | 新增: { | |
| 93 | 新增: try | |
| 94 | 新增: { | |
| 95 | 新增: // Read bounded chunks, never logging a CLI line which can contain | |
| 96 | 新增: // the private connection token or an authorized project path. | |
| 97 | 新增: var buffer = new char[4096]; var recent = ""; int count; | |
| 98 | 新增: while ((count = await reader.ReadAsync(buffer)) != 0) | |
| 99 | 新增: { | |
| 100 | 新增: recent = (recent + new string(buffer, 0, count)); | |
| 101 | 新增: if (recent.Length > 8192) recent = recent[^8192..]; | |
| 102 | 新增: var match = Listening.Match(recent); | |
| 103 | 新增: if (match.Success) listening.TrySetResult(match.Groups[1].Value); | |
| 104 | 新增: } | |
| 105 | 新增: listening.TrySetException(new InvalidDataException("editor_start_failed")); | |
| 106 | 新增: } | |
| 107 | 新增: catch { listening.TrySetException(new InvalidDataException("editor_start_failed")); } | |
| 108 | 新增: } | |
| 109 | 新增: | |
| 110 | 新增: private static void CopyPackage(string source, string target, CancellationToken token) | |
| 111 | 新增: { | |
| 112 | 新增: var directory = new DirectoryInfo(source); | |
| 113 | 新增: if (directory.Attributes.HasFlag(FileAttributes.ReparsePoint)) throw new InvalidDataException("editor_package_invalid"); | |
| 114 | 新增: Directory.CreateDirectory(target); | |
| 115 | 新增: foreach (var file in directory.EnumerateFiles()) | |
| 116 | 新增: { | |
| 117 | 新增: token.ThrowIfCancellationRequested(); | |
| 118 | 新增: if (file.Attributes.HasFlag(FileAttributes.ReparsePoint)) throw new InvalidDataException("editor_package_invalid"); | |
| 119 | 新增: file.CopyTo(Path.Combine(target, file.Name), false); | |
| 120 | 新增: } | |
| 121 | 新增: foreach (var child in directory.EnumerateDirectories()) CopyPackage(child.FullName, Path.Combine(target, child.Name), token); | |
| 122 | 新增: } | |
| 123 | 新增: | |
| 124 | 新增: internal static void Revoke(string project, string grant) | |
| 125 | 新增: { | |
| 126 | 新增: if (Editors.TryGetValue(project, out var editor) && editor.Grant == grant && | |
| 127 | 新增: ((ICollection<KeyValuePair<string, Editor>>)Editors).Remove(new(project, editor))) editor.Dispose(); | |
| 128 | 新增: } | |
| 129 | 新增: internal static void Close() { foreach (var entry in Editors) if (Editors.TryRemove(entry.Key, out var editor)) editor.Dispose(); } | |
| 130 | 新增: | |
| 131 | 新增: private sealed class Editor(string project, string grant, string folder, Process process) : IDisposable | |
| 132 | 新增: { | |
| 133 | 新增: internal string Grant { get; } = grant; | |
| 134 | 新增: internal string Folder { get; } = folder; | |
| 135 | 新增: internal Process Process { get; } = process; | |
| 136 | 新增: internal Connection Connection { get; set; } = new("", project, grant, folder, ""); | |
| 137 | 新增: internal Task? Output, Errors; | |
| 138 | 新增: internal GuestProcessJob? Job; | |
| 139 | 新增: public void Dispose() | |
| 140 | 新增: { | |
| 141 | 新增: try { Process.StandardInput.Close(); if (!Process.HasExited) Process.Kill(true); Process.WaitForExit(2000); } catch (InvalidOperationException) { } | |
| 142 | 新增: Job?.Dispose();Process.Dispose(); | |
| 143 | 新增: // Profiles, tokens and VS Code hot-exit backups remain intact. | |
| 144 | 新增: } | |
| 145 | 新增: } | |
| 146 | 新增:} | |
| @@ -0,0 +1,140 @@ | ||
| 1 | 新增:using System.Diagnostics; | |
| 2 | 新增:using System.Collections.Concurrent; | |
| 3 | 新增:using System.IO; | |
| 4 | 新增:using System.Runtime.InteropServices; | |
| 5 | 新增:using System.Security.Cryptography; | |
| 6 | 新增:using System.Text; | |
| 7 | 新增: | |
| 8 | 新增:namespace Cage.GuestClipboard; | |
| 9 | 新增: | |
| 10 | 新增:// A private capability created from ClaudeWindowRpc's verified registration. | |
| 11 | 新增:// No process, handle, path, or authorization predicate comes from JSON. | |
| 12 | 新增:internal static class WindowsFileDialogNative | |
| 13 | 新增:{ | |
| 14 | 新增: internal sealed record Owner(int PID,long Started,int Session,IntPtr Window,string Executable,Func<Process,bool> Authorized) | |
| 15 | 新增: { | |
| 16 | 新增: internal void Assert() | |
| 17 | 新增: { | |
| 18 | 新增: using var process=Process.GetProcessById(PID); | |
| 19 | 新增: if(process.HasExited||process.StartTime.ToUniversalTime().Ticks!=Started||process.SessionId!=Session|| | |
| 20 | 新增: !string.Equals(process.MainModule?.FileName,Executable,StringComparison.OrdinalIgnoreCase)||!Authorized(process)|| | |
| 21 | 新增: !IsWindowVisible(Window)||GetWindowThreadProcessId(Window,out var pid)==0||pid!=PID) | |
| 22 | 新增: throw new InvalidDataException("file_dialog_owner_changed"); | |
| 23 | 新增: } | |
| 24 | 新增: } | |
| 25 | 新增: private static readonly string Property="Cage.FileDialog."+Guid.NewGuid().ToString("N"); | |
| 26 | 新增: private static readonly ConcurrentDictionary<IntPtr,Observer> Observers=new(); | |
| 27 | 新增: [UnmanagedFunctionPointer(CallingConvention.Winapi)] | |
| 28 | 新增: [return: MarshalAs(UnmanagedType.Bool)] | |
| 29 | 新增: private delegate bool WindowCallback(IntPtr window, IntPtr parameter); | |
| 30 | 新增: [DllImport("user32.dll")] | |
| 31 | 新增: [return: MarshalAs(UnmanagedType.Bool)] | |
| 32 | 新增: private static extern bool EnumWindows(WindowCallback callback,IntPtr parameter); | |
| 33 | 新增: [DllImport("user32.dll")] private static extern bool IsWindowVisible(IntPtr window); | |
| 34 | 新增: [DllImport("user32.dll")] private static extern uint GetWindowThreadProcessId(IntPtr window,out uint pid); | |
| 35 | 新增: [DllImport("user32.dll")] private static extern IntPtr GetWindow(IntPtr window,uint kind); | |
| 36 | 新增: [DllImport("user32.dll")] private static extern IntPtr GetForegroundWindow(); | |
| 37 | 新增: [DllImport("user32.dll",CharSet=CharSet.Unicode,ExactSpelling=true)] private static extern int GetClassNameW(IntPtr window,StringBuilder value,int length); | |
| 38 | 新增: [DllImport("user32.dll",CharSet=CharSet.Unicode,ExactSpelling=true,SetLastError=true)] private static extern bool SetPropW(IntPtr window,string name,IntPtr value); | |
| 39 | 新增: [DllImport("user32.dll",CharSet=CharSet.Unicode,ExactSpelling=true)] private static extern IntPtr GetPropW(IntPtr window,string name); | |
| 40 | 新增: [DllImport("user32.dll",CharSet=CharSet.Unicode,ExactSpelling=true)] private static extern IntPtr RemovePropW(IntPtr window,string name); | |
| 41 | 新增: [DllImport("user32.dll")] internal static extern int GetDlgCtrlID(IntPtr window); | |
| 42 | 新增: [DllImport("user32.dll")] internal static extern bool IsChild(IntPtr parent,IntPtr child); | |
| 43 | 新增: [DllImport("user32.dll")] private static extern IntPtr GetDlgItem(IntPtr dialog,int id); | |
| 44 | 新增: [DllImport("user32.dll")] private static extern bool IsWindowEnabled(IntPtr window); | |
| 45 | 新增: [DllImport("user32.dll",ExactSpelling=true)] private static extern bool PostMessageW(IntPtr window,uint message,IntPtr parameter,IntPtr data); | |
| 46 | 新增: [DllImport("user32.dll",CharSet=CharSet.Unicode,ExactSpelling=true)] private static extern IntPtr SendMessageTimeoutW(IntPtr window,uint message,IntPtr parameter,string data,uint flags,uint timeout,out IntPtr result); | |
| 47 | 新增: [DllImport("user32.dll",CharSet=CharSet.Unicode,ExactSpelling=true)] private static extern IntPtr SendMessageTimeoutW(IntPtr window,uint message,IntPtr parameter,StringBuilder data,uint flags,uint timeout,out IntPtr result); | |
| 48 | 新增: [DllImport("user32.dll",CharSet=CharSet.Unicode,ExactSpelling=true)] private static extern IntPtr SendMessageTimeoutW(IntPtr window,uint message,IntPtr parameter,IntPtr data,uint flags,uint timeout,out IntPtr result); | |
| 49 | 新增: private delegate void EventCallback(IntPtr hook,uint kind,IntPtr window,int objectID,int childID,uint thread,uint time); | |
| 50 | 新增: [DllImport("user32.dll")] private static extern IntPtr SetWinEventHook(uint first,uint last,IntPtr module,EventCallback callback,uint process,uint thread,uint flags); | |
| 51 | 新增: [DllImport("user32.dll")] private static extern bool UnhookWinEvent(IntPtr hook); | |
| 52 | 新增: // Install on the GUI message thread. Keep the delegate rooted until the | |
| 53 | 新增: // hook is removed; the callback only retires broker state, never clicks UI. | |
| 54 | 新增: internal sealed class Observer : IDisposable | |
| 55 | 新增: { | |
| 56 | 新增: private IntPtr hook; | |
| 57 | 新增: private readonly EventCallback callback; | |
| 58 | 新增: private readonly int thread=Environment.CurrentManagedThreadId; | |
| 59 | 新增: internal Observer(Owner owner,Action<IntPtr> destroyed) | |
| 60 | 新增: { | |
| 61 | 新增: owner.Assert(); | |
| 62 | 新增: callback=(_,kind,window,objectID,childID,_,_)=>{if(kind==0x8001&&objectID==0&&childID==0)destroyed(window);}; | |
| 63 | 新增: hook=SetWinEventHook(0x8001,0x8001,IntPtr.Zero,callback,(uint)owner.PID,0,0); | |
| 64 | 新增: if(hook==IntPtr.Zero)throw new InvalidDataException("file_dialog_observer_unavailable"); | |
| 65 | 新增: Observers[hook]=this; // A failed unhook cannot release the native delegate. | |
| 66 | 新增: } | |
| 67 | 新增: public void Dispose() | |
| 68 | 新增: { | |
| 69 | 新增: if(hook==IntPtr.Zero)return; | |
| 70 | 新增: if(Environment.CurrentManagedThreadId!=thread||!UnhookWinEvent(hook))throw new InvalidDataException("file_dialog_observer_cleanup_failed"); | |
| 71 | 新增: Observers.TryRemove(hook,out _);hook=IntPtr.Zero;GC.KeepAlive(callback); | |
| 72 | 新增: } | |
| 73 | 新增: } | |
| 74 | 新增: | |
| 75 | 新增: internal static bool Owned(Owner owner,IntPtr dialog) | |
| 76 | 新增: { | |
| 77 | 新增: if(!IsWindowVisible(dialog)||GetWindowThreadProcessId(dialog,out var pid)==0||pid!=owner.PID)return false; | |
| 78 | 新增: var name=new StringBuilder(128);GetClassNameW(dialog,name,name.Capacity);if(name.ToString()!="#32770")return false; | |
| 79 | 新增: var seen=new HashSet<IntPtr>();var parent=GetWindow(dialog,4); | |
| 80 | 新增: while(parent!=IntPtr.Zero&&seen.Add(parent)&&seen.Count<=8){if(parent==owner.Window)return true;parent=GetWindow(parent,4);} | |
| 81 | 新增: return false; | |
| 82 | 新增: } | |
| 83 | 新增: internal static IntPtr[] Candidates(Owner owner) | |
| 84 | 新增: { | |
| 85 | 新增: owner.Assert();var result=new List<IntPtr>(); | |
| 86 | 新增: EnumWindows((window,_)=>{if(Owned(owner,window))result.Add(window);return true;},IntPtr.Zero); | |
| 87 | 新增: owner.Assert();return result.ToArray(); | |
| 88 | 新增: } | |
| 89 | 新增: internal static IntPtr Stamp(Owner owner,IntPtr dialog) | |
| 90 | 新增: { | |
| 91 | 新增: owner.Assert();if(!Owned(owner,dialog))throw new InvalidDataException("file_dialog_owner_changed"); | |
| 92 | 新增: var bytes=RandomNumberGenerator.GetBytes(8); | |
| 93 | 新增: var stamp=new IntPtr((long)(BitConverter.ToUInt64(bytes)&0x7fffffffffffffffUL));if(stamp==IntPtr.Zero)stamp=new IntPtr(1); | |
| 94 | 新增: if(!SetPropW(dialog,Property,stamp))throw new InvalidDataException("file_dialog_binding_unavailable"); | |
| 95 | 新增: try{owner.Assert();if(!Owned(owner,dialog)||GetPropW(dialog,Property)!=stamp)throw new InvalidDataException("file_dialog_owner_changed");return stamp;} | |
| 96 | 新增: catch{Remove(dialog,stamp);throw;} | |
| 97 | 新增: } | |
| 98 | 新增: internal static bool Alive(Owner owner,IntPtr dialog,IntPtr stamp) | |
| 99 | 新增: { | |
| 100 | 新增: try{owner.Assert();return Owned(owner,dialog)&&GetPropW(dialog,Property)==stamp;} | |
| 101 | 新增: catch{return false;} | |
| 102 | 新增: } | |
| 103 | 新增: internal static void Assert(Owner owner,IntPtr dialog,IntPtr stamp,bool foreground) | |
| 104 | 新增: { | |
| 105 | 新增: if(!Alive(owner,dialog,stamp)||foreground&&GetForegroundWindow()!=dialog)throw new InvalidDataException("file_dialog_changed"); | |
| 106 | 新增: } | |
| 107 | 新增: internal static void Remove(IntPtr dialog,IntPtr stamp) | |
| 108 | 新增: {if(GetPropW(dialog,Property)==stamp)RemovePropW(dialog,Property);} | |
| 109 | 新增: | |
| 110 | 新增: internal static void Accept(Owner owner,IntPtr dialog,IntPtr stamp) | |
| 111 | 新增: { | |
| 112 | 新增: Assert(owner,dialog,stamp,true); | |
| 113 | 新增: var button=GetDlgItem(dialog,1); | |
| 114 | 新增: var name=new StringBuilder(128);GetClassNameW(button,name,name.Capacity); | |
| 115 | 新增: if(button==IntPtr.Zero||!IsChild(dialog,button)||!IsWindowEnabled(button)||name.ToString()!="Button"|| | |
| 116 | 新增: GetWindowThreadProcessId(button,out var pid)==0||pid!=owner.PID|| | |
| 117 | 新增: !PostMessageW(button,0x00F5,IntPtr.Zero,IntPtr.Zero))throw new InvalidDataException("file_dialog_selection_invalid"); | |
| 118 | 新增: } | |
| 119 | 新增: | |
| 120 | 新增: internal static void SetFilename(Owner owner,IntPtr dialog,IntPtr stamp,IntPtr field,string text) | |
| 121 | 新增: { | |
| 122 | 新增: Assert(owner,dialog,stamp,true); | |
| 123 | 新增: var name=new StringBuilder(128);GetClassNameW(field,name,name.Capacity); | |
| 124 | 新增: if(text.Length>1<<20||field==IntPtr.Zero||!IsChild(dialog,field)||name.ToString()!="Edit"|| | |
| 125 | 新增: GetWindowThreadProcessId(field,out var pid)==0||pid!=owner.PID) | |
| 126 | 新增: throw new InvalidDataException("file_dialog_selection_invalid"); | |
| 127 | 新增: // UIA ValuePattern rejects a multi-file value beyond the Edit control's | |
| 128 | 新增: // typing limit. WM_SETTEXT supports the native selection buffer. | |
| 129 | 新增: if(SendMessageTimeoutW(field,0x000C,IntPtr.Zero,text,0x22,2000,out var written)==IntPtr.Zero||written==IntPtr.Zero) | |
| 130 | 新增: throw new InvalidDataException("file_dialog_input_failed"); | |
| 131 | 新增: Assert(owner,dialog,stamp,true); | |
| 132 | 新增: if(SendMessageTimeoutW(field,0x000E,IntPtr.Zero,IntPtr.Zero,0x22,2000,out var textLength)==IntPtr.Zero||textLength.ToInt64()!=text.Length) | |
| 133 | 新增: throw new InvalidDataException("file_dialog_selection_invalid"); | |
| 134 | 新增: var actual=new StringBuilder(text.Length+1); | |
| 135 | 新增: if(SendMessageTimeoutW(field,0x000D,new IntPtr(actual.Capacity),actual,0x22,2000,out var length)==IntPtr.Zero|| | |
| 136 | 新增: length.ToInt64()!=text.Length||actual.ToString()!=text) | |
| 137 | 新增: throw new InvalidDataException("file_dialog_selection_invalid"); | |
| 138 | 新增: Assert(owner,dialog,stamp,true); | |
| 139 | 新增: } | |
| 140 | 新增:} | |
| @@ -0,0 +1,29 @@ | ||
| 1 | 新增:using System.Diagnostics; | |
| 2 | 新增: | |
| 3 | 新增:namespace Cage.GuestClipboard; | |
| 4 | 新增: | |
| 5 | 新增:// Callers own both paths and finish writing their protected stage first. | |
| 6 | 新增:// Publish one complete snapshot while retaining the old reader and its ACL. | |
| 7 | 新增:internal static class WindowsFilePublication | |
| 8 | 新增:{ | |
| 9 | 新增: internal static async Task Replace(string stage,string destination,CancellationToken token) | |
| 10 | 新增: { | |
| 11 | 新增: var elapsed=Stopwatch.StartNew(); | |
| 12 | 新增: for(;;) | |
| 13 | 新增: { | |
| 14 | 新增: token.ThrowIfCancellationRequested(); | |
| 15 | 新增: try | |
| 16 | 新增: { | |
| 17 | 新增: if(File.Exists(destination))File.Replace(stage,destination,null); | |
| 18 | 新增: else File.Move(stage,destination); | |
| 19 | 新增: return; | |
| 20 | 新增: } | |
| 21 | 新增: catch(Exception error) when(error is IOException or UnauthorizedAccessException) | |
| 22 | 新增: { | |
| 23 | 新增: var code=error.HResult&0xffff; | |
| 24 | 新增: if(code is not (5 or 32) || elapsed.Elapsed>=TimeSpan.FromSeconds(2))throw; | |
| 25 | 新增: await Task.Delay(25,token); | |
| 26 | 新增: } | |
| 27 | 新增: } | |
| 28 | 新增: } | |
| 29 | 新增:} | |
| @@ -0,0 +1,85 @@ | ||
| 1 | 新增:using System.Security.Cryptography; | |
| 2 | 新增:using System.Text.Json.Nodes; | |
| 3 | 新增:using System.Windows.Automation; | |
| 4 | 新增: | |
| 5 | 新增:namespace Cage.GuestClipboard; | |
| 6 | 新增: | |
| 7 | 新增:// The Claude window owner supplies a verified process and a Unicode committer. | |
| 8 | 新增:// UI Automation is read-only here; it never chooses an arbitrary application. | |
| 9 | 新增:internal static class WindowsIme | |
| 10 | 新增:{ | |
| 11 | 新增: private sealed record Focus(string Context, double[] Rect, bool Password); | |
| 12 | 新增: private sealed record Composition(string ID, string Context, int Sequence, DateTime Updated); | |
| 13 | 新增: private static readonly SemaphoreSlim Probes = new(1, 1); | |
| 14 | 新增: private static Composition? composition; | |
| 15 | 新增: | |
| 16 | 新增: private static Focus? Probe(int process, string windowTarget, double x, double y) | |
| 17 | 新增: { | |
| 18 | 新增: var element = AutomationElement.FocusedElement; | |
| 19 | 新增: if (element is null || element.Current.ProcessId != process || !element.Current.IsEnabled || element.Current.IsOffscreen) | |
| 20 | 新增: return null; | |
| 21 | 新增: bool editable = element.TryGetCurrentPattern(ValuePattern.Pattern, out var value) && !((ValuePattern)value).Current.IsReadOnly; | |
| 22 | 新增: if (!editable && element.TryGetCurrentPattern(TextPattern.Pattern, out var text)) | |
| 23 | 新增: { | |
| 24 | 新增: var readOnly = ((TextPattern)text).DocumentRange.GetAttributeValue(TextPattern.IsReadOnlyAttribute); | |
| 25 | 新增: editable = readOnly is bool b && !b; | |
| 26 | 新增: } | |
| 27 | 新增: if (!editable) return null; | |
| 28 | 新增: var bounds = element.Current.BoundingRectangle; | |
| 29 | 新增: var rect = new double[] { bounds.X-x, bounds.Y-y, Math.Max(1,bounds.Width), Math.Max(1,bounds.Height) }; | |
| 30 | 新增: if (element.TryGetCurrentPattern(TextPattern.Pattern, out var caret)) | |
| 31 | 新增: { | |
| 32 | 新增: var ranges = ((TextPattern)caret).GetSelection(); | |
| 33 | 新增: var geometry = ranges.Length == 1 ? ranges[0].GetBoundingRectangles() : []; | |
| 34 | 新增: if (geometry.Length != 0) rect = [geometry[0].X-x,geometry[0].Y-y,Math.Max(1,geometry[0].Width),Math.Max(1,geometry[0].Height)]; | |
| 35 | 新增: } | |
| 36 | 新增: var identity = windowTarget + ":" + string.Join(',',element.GetRuntimeId()); | |
| 37 | 新增: var context = Convert.ToHexString(SHA256.HashData(Protocol.Utf8.GetBytes(identity)).AsSpan(0,16)).ToLowerInvariant(); | |
| 38 | 新增: return new Focus(context,rect,element.Current.IsPassword); | |
| 39 | 新增: } | |
| 40 | 新增: | |
| 41 | 新增: internal static async Task RequirePhoneFocus(JsonObject input, int process, string windowTarget, CancellationToken token) | |
| 42 | 新增: { | |
| 43 | 新增: if (!input.ContainsKey("phone_focus")) return; | |
| 44 | 新增: var requested = input["phone_focus"]?.GetValue<string>() ?? ""; | |
| 45 | 新增: var focus = await Handle(new JsonObject { ["mode"] = "status" }, process, windowTarget, 0, 0, | |
| 46 | 新增: _ => throw new InvalidDataException("desktop_phone_focus_changed"), token); | |
| 47 | 新增: if (requested.Length == 0 || focus["available"]?.GetValue<bool>() != true || | |
| 48 | 新增: focus["password"]?.GetValue<bool>() == true || focus["context"]?.GetValue<string>() != requested) | |
| 49 | 新增: throw new InvalidDataException("desktop_phone_focus_changed"); | |
| 50 | 新增: } | |
| 51 | 新增: | |
| 52 | 新增: internal static async Task<JsonObject> Handle(JsonObject input, int process, string windowTarget, double x, double y, Action<string> commit, CancellationToken token) | |
| 53 | 新增: { | |
| 54 | 新增: var mode = input["mode"]?.GetValue<string>() ?? ""; | |
| 55 | 新增: var id = input["session"]?.GetValue<string>() ?? ""; | |
| 56 | 新增: var sequence = input["sequence"]?.GetValue<int>() ?? 0; | |
| 57 | 新增: if (mode is not ("status" or "begin" or "update" or "commit" or "cancel")) throw new InvalidDataException("input_mode_invalid"); | |
| 58 | 新增: if (mode != "status" && (id.Length != 32 || id.Any(c => !char.IsAsciiHexDigit(c)) || sequence < 0)) throw new InvalidDataException("input_session_invalid"); | |
| 59 | 新增: if (mode == "cancel") | |
| 60 | 新增: { | |
| 61 | 新增: if (composition?.ID == id && sequence > composition.Sequence) composition = null; | |
| 62 | 新增: return new JsonObject { ["available"] = false }; | |
| 63 | 新增: } | |
| 64 | 新增: if (!await Probes.WaitAsync(0,token)) return new JsonObject { ["available"] = false }; | |
| 65 | 新增: var probe = Task.Run(() => { try { return Probe(process,windowTarget,x,y); } finally { Probes.Release(); } }); | |
| 66 | 新增: Focus? focus; | |
| 67 | 新增: try { focus = await probe.WaitAsync(TimeSpan.FromSeconds(2),token); } | |
| 68 | 新增: catch (Exception e) when (e is not OperationCanceledException) { return new JsonObject { ["available"] = false }; } | |
| 69 | 新增: if (focus is null || !SessionGuard.Available()) { composition = null; return new JsonObject { ["available"] = false }; } | |
| 70 | 新增: if (composition is not null && (composition.Context != focus.Context || DateTime.UtcNow-composition.Updated > TimeSpan.FromSeconds(30))) composition = null; | |
| 71 | 新增: JsonObject Snapshot() => new() { ["available"] = true, ["context"] = focus.Context, ["rect"] = new JsonArray(focus.Rect.Select(v => (JsonNode?)JsonValue.Create(v)).ToArray()), ["preedit_supported"] = false, ["password"] = focus.Password }; | |
| 72 | 新增: if (mode == "status") { if (composition?.ID == id) composition = composition with { Updated = DateTime.UtcNow }; return Snapshot(); } | |
| 73 | 新增: if (mode == "begin") | |
| 74 | 新增: { | |
| 75 | 新增: if (input["context"]?.GetValue<string>() != focus.Context) return new JsonObject { ["available"] = false }; | |
| 76 | 新增: composition = new Composition(id,focus.Context,sequence,DateTime.UtcNow); return Snapshot(); | |
| 77 | 新增: } | |
| 78 | 新增: if (composition?.ID != id || sequence <= composition.Sequence) return new JsonObject { ["available"] = false }; | |
| 79 | 新增: var content = input["text"]?.GetValue<string>() ?? ""; | |
| 80 | 新增: if (Protocol.Utf8.GetByteCount(content) > 8192) throw new InvalidDataException("input_text_limit"); | |
| 81 | 新增: if (mode == "commit") { commit(content); composition = null; } | |
| 82 | 新增: else composition = composition with { Sequence = sequence, Updated = DateTime.UtcNow }; | |
| 83 | 新增: return Snapshot(); | |
| 84 | 新增: } | |
| 85 | 新增:} | |
| @@ -0,0 +1,103 @@ | ||
| 1 | 新增:using System.Diagnostics; | |
| 2 | 新增:using System.Text.Json.Nodes; | |
| 3 | 新增:using System.Text.RegularExpressions; | |
| 4 | 新增:using InputLease = Cage.GuestClipboard.NativeInputCoordinator.Lease; | |
| 5 | 新增: | |
| 6 | 新增:namespace Cage.GuestClipboard; | |
| 7 | 新增: | |
| 8 | 新增:// This subtree is separate from desktop Chrome. One enrollment owns the active | |
| 9 | 新增:// phone ID; a disconnected connection never closes another ID or desktop tab. | |
| 10 | 新增:internal static class WindowsPhoneBrowser | |
| 11 | 新增:{ | |
| 12 | 新增: private static readonly SemaphoreSlim Gate = new(1, 1); | |
| 13 | 新增: private static readonly Dictionary<InputLease, string> Owners = new(); | |
| 14 | 新增: private static readonly Regex ID = new("^[a-f0-9]{8}-[a-f0-9]{4}-4[a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$", RegexOptions.CultureInvariant); | |
| 15 | 新增: private static Process? process; | |
| 16 | 新增: private static GuestProcessJob? job; | |
| 17 | 新增: private static Stream? replies; | |
| 18 | 新增: private static string current = ""; | |
| 19 | 新增: internal static bool Installed() => BrowserRpc.BrowserExecutableInstalled() && new[] { "node.exe", "windows-browser.mjs", "windows-browser-extensions.mjs", "windows-phone-browser.mjs", "playwright/index.mjs", "modules/browser-phone.mjs", "modules/browser-phone-network.mjs" } | |
| 20 | 新增: .All(file => File.Exists(Path.Combine(AppContext.BaseDirectory, file))); | |
| 21 | 新增: | |
| 22 | 新增: private static JsonObject Error(int status) => new() { ["error"] = "phone_browser_unavailable", ["code"] = "phone_browser_error", ["status"] = status }; | |
| 23 | 新增: internal static async Task<JsonObject> Exchange(JsonObject request, CancellationToken connection, InputLease owner) | |
| 24 | 新增: { | |
| 25 | 新增: await Gate.WaitAsync(connection); | |
| 26 | 新增: try | |
| 27 | 新增: { | |
| 28 | 新增: var route = request["path"]?.GetValue<string>() ?? ""; | |
| 29 | 新增: var input = request["input"] as JsonObject ?? new JsonObject(); | |
| 30 | 新增: var id = input["id"]?.GetValue<string>() ?? ""; | |
| 31 | 新增: if (!ID.IsMatch(id)) return Error(400); | |
| 32 | 新增: if (route != "/phone-browser/open" && current != id) return Error(410); | |
| 33 | 新增: using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(35)); | |
| 34 | 新增: if (route == "/phone-browser/open") | |
| 35 | 新增: { | |
| 36 | 新增: if (!Installed()) return Error(501); | |
| 37 | 新增: var settings = await BrowserRpc.ReadConfiguration(timeout.Token, packetOnly: true); | |
| 38 | 新增: await Start(settings, timeout.Token); | |
| 39 | 新增: } | |
| 40 | 新增: if (process is not { HasExited: false }) return Error(410); | |
| 41 | 新增: var result = await Control(request, timeout.Token); | |
| 42 | 新增: if (result["error"] is null && route == "/phone-browser/open") { current = id; Owners[owner] = id; } | |
| 43 | 新增: if (result["error"] is null && route == "/phone-browser/close") { current = ""; foreach (var key in Owners.Where(p => p.Value == id).Select(p => p.Key).ToArray()) Owners.Remove(key); } | |
| 44 | 新增: return result; | |
| 45 | 新增: } | |
| 46 | 新增: catch (InvalidDataException) { return Error(503); } | |
| 47 | 新增: catch (Exception error) when (error is OperationCanceledException or EndOfStreamException or IOException) | |
| 48 | 新增: { Close(); return Error(503); } | |
| 49 | 新增: finally { Gate.Release(); } | |
| 50 | 新增: } | |
| 51 | 新增: internal static async Task Release(InputLease owner) | |
| 52 | 新增: { | |
| 53 | 新增: await Gate.WaitAsync(); | |
| 54 | 新增: try | |
| 55 | 新增: { | |
| 56 | 新增: if (!Owners.Remove(owner, out var id) || Owners.Values.Contains(id) || current != id) return; | |
| 57 | 新增: try | |
| 58 | 新增: { | |
| 59 | 新增: using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(5)); | |
| 60 | 新增: await Control(new JsonObject { ["method"] = "POST", ["path"] = "/phone-browser/close", ["input"] = new JsonObject { ["id"] = id } }, timeout.Token); | |
| 61 | 新增: current = ""; | |
| 62 | 新增: } | |
| 63 | 新增: catch { Close(); } | |
| 64 | 新增: } | |
| 65 | 新增: finally { Gate.Release(); } | |
| 66 | 新增: } | |
| 67 | 新增: private static async Task Start(JsonObject settings, CancellationToken token) | |
| 68 | 新增: { | |
| 69 | 新增: if (process is { HasExited: false }) return; | |
| 70 | 新增: Close(); | |
| 71 | 新增: var start = new ProcessStartInfo(Path.Combine(AppContext.BaseDirectory, "node.exe")) | |
| 72 | 新增: { | |
| 73 | 新增: UseShellExecute = false, CreateNoWindow = true, WorkingDirectory = AppContext.BaseDirectory, | |
| 74 | 新增: RedirectStandardInput = true, RedirectStandardOutput = true, RedirectStandardError = true, | |
| 75 | 新增: StandardInputEncoding = Protocol.Utf8, StandardOutputEncoding = Protocol.Utf8, StandardErrorEncoding = Protocol.Utf8, | |
| 76 | 新增: }; | |
| 77 | 新增: start.ArgumentList.Add(Path.Combine(AppContext.BaseDirectory, "windows-phone-browser.mjs")); | |
| 78 | 新增: process = Process.Start(start) ?? throw new InvalidDataException("browser_unavailable"); | |
| 79 | 新增: try | |
| 80 | 新增: { | |
| 81 | 新增: job = new GuestProcessJob(process); | |
| 82 | 新增: replies = new ReadAheadStream(process.StandardOutput.BaseStream); | |
| 83 | 新增: var source = process.StandardError; | |
| 84 | 新增: _ = Task.Run(async () => { try { var buffer = new char[4096]; while (await source.ReadAsync(buffer) != 0) { } } catch (ObjectDisposedException) { } }); | |
| 85 | 新增: var result = await Control(new JsonObject { ["operation"] = "configure", ["input"] = settings }, token); | |
| 86 | 新增: if (result["ok"]?.GetValue<bool>() != true) throw new InvalidDataException("browser_unavailable"); | |
| 87 | 新增: } | |
| 88 | 新增: catch { Close(); throw; } | |
| 89 | 新增: } | |
| 90 | 新增: private static async Task<JsonObject> Control(JsonObject input, CancellationToken token) | |
| 91 | 新增: { | |
| 92 | 新增: await Protocol.Write(process!.StandardInput.BaseStream, input, token); | |
| 93 | 新增: return await Protocol.Read(replies!, 3 << 20, token) ?? throw new EndOfStreamException(); | |
| 94 | 新增: } | |
| 95 | 新增: internal static void Close() | |
| 96 | 新增: { | |
| 97 | 新增: var owned = Interlocked.Exchange(ref process, null); current = ""; Owners.Clear(); | |
| 98 | 新增: try { if (owned is not null) { owned.StandardInput.Close(); if (!owned.WaitForExit(3000)) owned.Kill(true); owned.WaitForExit(2000); } } | |
| 99 | 新增: catch (InvalidOperationException) { } | |
| 100 | 新增: finally { job?.Dispose(); job = null; replies?.Dispose(); replies = null; owned?.Dispose(); } | |
| 101 | 新增: // Enrollment profile directories remain intact. | |
| 102 | 新增: } | |
| 103 | 新增:} | |
| @@ -0,0 +1,80 @@ | ||
| 1 | 新增:using System.Diagnostics; | |
| 2 | 新增:using System.Globalization; | |
| 3 | 新增:using System.Security.AccessControl; | |
| 4 | 新增:using System.Security.Principal; | |
| 5 | 新增:using System.Text.Json.Nodes; | |
| 6 | 新增:using System.Text.RegularExpressions; | |
| 7 | 新增: | |
| 8 | 新增:namespace Cage.GuestClipboard; | |
| 9 | 新增: | |
| 10 | 新增:// Only the paired host can apply these bounded platform settings. No command, | |
| 11 | 新增:// registry path, executable, account or file name is accepted from the wire. | |
| 12 | 新增:internal static class WindowsSystemSettings | |
| 13 | 新增:{ | |
| 14 | 新增: internal static async Task Apply(JsonObject settings,Guid vm,string sid,CancellationToken token) | |
| 15 | 新增: { | |
| 16 | 新增: if(settings.Count is not (3 or 4) || settings["action"]?.GetValue<string>()!="apply")throw new InvalidDataException("settings_invalid"); | |
| 17 | 新增: var iana=settings["timezone"]?.GetValue<string>() ?? "";var locale=settings["locale"]?.GetValue<string>() ?? ""; | |
| 18 | 新增: if(iana.Length>128 || !TimeZoneInfo.TryConvertIanaIdToWindowsId(iana,out var windowsZone) || | |
| 19 | 新增: !Regex.IsMatch(windowsZone!,@"^[A-Za-z0-9 ()._+-]+$") || !Regex.IsMatch(locale,@"^[a-zA-Z]{2,3}_[a-zA-Z]{2,3}\.UTF-8$") || !Regex.IsMatch(sid,@"^S-1-5-21-\d+-\d+-\d+-\d+$"))throw new InvalidDataException("settings_invalid"); | |
| 20 | 新增: var tag=locale[..^6].Replace('_','-');var culture=CultureInfo.GetCultureInfo(tag); | |
| 21 | 新增: _=TimeZoneInfo.FindSystemTimeZoneById(windowsZone!); | |
| 22 | 新增: var configPath=Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles),"Cage Guest Bridge",vm.ToString("D"),"guest-config.json"); | |
| 23 | 新增: var previous=ProtectedConfig(configPath); | |
| 24 | 新增: var config=JsonNode.Parse(previous) as JsonObject ?? throw new InvalidDataException("settings_config_invalid"); | |
| 25 | 新增: if(config["network_mode"]?.GetValue<string>()!="packet")throw new InvalidDataException("settings_config_invalid"); | |
| 26 | 新增: // Existing v1 controllers omit browser_language. Preserve the protected | |
| 27 | 新增: // selection during a component update; never derive it from locale. | |
| 28 | 新增: var language=settings.Count==4 ? BrowserLanguage(settings) : BrowserLanguage(new JsonObject{["browser_language"]=config["language"]?.DeepClone()}); | |
| 29 | 新增: config["timezone"]=iana;config["language"]=language; | |
| 30 | 新增: // Publish before applying the OS settings. A failed OS transaction | |
| 31 | 新增: // restores the protected browser configuration as well. | |
| 32 | 新增: PublishConfig(configPath,System.Text.Encoding.UTF8.GetBytes(config.ToJsonString())); | |
| 33 | 新增: var script=$"$ErrorActionPreference='Stop';$key='Registry::HKEY_USERS\\{sid}\\Control Panel\\International';if(!(Test-Path -LiteralPath $key)){{throw 'gui_profile_not_loaded'}};$before=Get-ItemProperty -LiteralPath $key;$zone=(Get-TimeZone).Id;$system=(Get-WinSystemLocale).Name;try{{Set-TimeZone -Id '{windowsZone}';Set-ItemProperty -LiteralPath $key -Name LocaleName -Value '{culture.Name}';Set-ItemProperty -LiteralPath $key -Name Locale -Value '{culture.LCID:X8}';Set-WinSystemLocale -SystemLocale '{culture.Name}'}}catch{{Set-TimeZone -Id $zone;Set-ItemProperty -LiteralPath $key -Name LocaleName -Value $before.LocaleName;Set-ItemProperty -LiteralPath $key -Name Locale -Value $before.Locale;Set-WinSystemLocale -SystemLocale $system;throw}}"; | |
| 34 | 新增: var start=new ProcessStartInfo(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Windows),@"System32\WindowsPowerShell\v1.0\powershell.exe")){UseShellExecute=false,RedirectStandardInput=true,RedirectStandardOutput=true,RedirectStandardError=true,CreateNoWindow=true}; | |
| 35 | 新增: foreach(var argument in new[]{"-NoLogo","-NoProfile","-NonInteractive","-Command","-"})start.ArgumentList.Add(argument); | |
| 36 | 新增: try | |
| 37 | 新增: { | |
| 38 | 新增: using var process=Process.Start(start) ?? throw new InvalidDataException("settings_apply_failed"); | |
| 39 | 新增: using var cancel=token.Register(()=>{try{process.Kill(true);}catch{}}); | |
| 40 | 新增: var output=process.StandardOutput.BaseStream.CopyToAsync(Stream.Null,token);var errors=process.StandardError.BaseStream.CopyToAsync(Stream.Null,token); | |
| 41 | 新增: await process.StandardInput.WriteLineAsync(script);process.StandardInput.Close();await process.WaitForExitAsync(token);await Task.WhenAll(output,errors); | |
| 42 | 新增: if(process.ExitCode!=0)throw new InvalidDataException("settings_apply_failed"); | |
| 43 | 新增: } | |
| 44 | 新增: catch { PublishConfig(configPath,previous);throw; } | |
| 45 | 新增: } | |
| 46 | 新增: | |
| 47 | 新增: internal static string BrowserLanguage(JsonObject settings) | |
| 48 | 新增: { | |
| 49 | 新增: var language=settings["browser_language"]?.GetValue<string>() ?? ""; | |
| 50 | 新增: if(language.Length>128 || !Regex.IsMatch(language,@"^[A-Za-z]{2,3}(-[A-Za-z0-9]{2,8})*$"))throw new InvalidDataException("settings_invalid"); | |
| 51 | 新增: return language; | |
| 52 | 新增: } | |
| 53 | 新增: | |
| 54 | 新增: private static byte[] ProtectedConfig(string path) | |
| 55 | 新增: { | |
| 56 | 新增: var file=new FileInfo(path); | |
| 57 | 新增: for(var directory=file.Directory;directory!=null;directory=directory.Parent) | |
| 58 | 新增: if(directory.Attributes.HasFlag(FileAttributes.ReparsePoint))throw new InvalidDataException("settings_config_invalid"); | |
| 59 | 新增: if(!file.Exists || file.Length is <=0 or >16384 || file.Attributes.HasFlag(FileAttributes.ReparsePoint))throw new InvalidDataException("settings_config_invalid"); | |
| 60 | 新增: var acl=file.GetAccessControl(); | |
| 61 | 新增: if(acl.GetOwner(typeof(SecurityIdentifier))?.Value is not ("S-1-5-18" or "S-1-5-32-544"))throw new InvalidDataException("settings_config_invalid"); | |
| 62 | 新增: const FileSystemRights writes=FileSystemRights.WriteData|FileSystemRights.AppendData|FileSystemRights.WriteAttributes|FileSystemRights.WriteExtendedAttributes|FileSystemRights.Delete|FileSystemRights.ChangePermissions|FileSystemRights.TakeOwnership; | |
| 63 | 新增: foreach(FileSystemAccessRule rule in acl.GetAccessRules(true,true,typeof(SecurityIdentifier))) | |
| 64 | 新增: if(rule.AccessControlType==AccessControlType.Allow && (rule.FileSystemRights&writes)!=0 && rule.IdentityReference.Value is not ("S-1-5-18" or "S-1-5-32-544"))throw new InvalidDataException("settings_config_invalid"); | |
| 65 | 新增: using var snapshot=new FileStream(path,FileMode.Open,FileAccess.Read,FileShare.Read|FileShare.Delete); | |
| 66 | 新增: if(snapshot.Length is <=0 or >16384)throw new InvalidDataException("settings_config_invalid"); | |
| 67 | 新增: using var data=new MemoryStream();snapshot.CopyTo(data);return data.ToArray(); | |
| 68 | 新增: } | |
| 69 | 新增: private static void PublishConfig(string path,byte[] data) | |
| 70 | 新增: { | |
| 71 | 新增: var stage=path+"."+Guid.NewGuid().ToString("N")+".part"; | |
| 72 | 新增: try | |
| 73 | 新增: { | |
| 74 | 新增: File.WriteAllBytes(stage,data); | |
| 75 | 新增: new FileInfo(stage).SetAccessControl(new FileInfo(path).GetAccessControl()); | |
| 76 | 新增: WindowsFilePublication.Replace(stage,path,default).GetAwaiter().GetResult(); | |
| 77 | 新增: } | |
| 78 | 新增: finally { if(File.Exists(stage))File.Delete(stage); } | |
| 79 | 新增: } | |
| 80 | 新增:} | |
| @@ -0,0 +1,2222 @@ | ||
| 1 | 新增:{ | |
| 2 | 新增: "name": "cage-windows-ccs-runtime", | |
| 3 | 新增: "version": "1.0.0", | |
| 4 | 新增: "lockfileVersion": 3, | |
| 5 | 新增: "requires": true, | |
| 6 | 新增: "packages": { | |
| 7 | 新增: "": { | |
| 8 | 新增: "name": "cage-windows-ccs-runtime", | |
| 9 | 新增: "version": "1.0.0", | |
| 10 | 新增: "dependencies": { | |
| 11 | 新增: "@kaitranntt/ccs": "8.11.0" | |
| 12 | 新增: } | |
| 13 | 新增: }, | |
| 14 | 新增: "node_modules/@colors/colors": { | |
| 15 | 新增: "version": "1.5.0", | |
| 16 | 新增: "resolved": "https://registry.npmjs.org/@colors/colors/-/colors-1.5.0.tgz", | |
| 17 | 新增: "integrity": "sha512-ooWCrlZP11i8GImSjTHYHLkvFDP48nS4+204nGb1RiX/WXYHmJA2III9/e2DWVabCESdW7hBAEzHRqUn9OUVvQ==", | |
| 18 | 新增: "license": "MIT", | |
| 19 | 新增: "optional": true, | |
| 20 | 新增: "engines": { | |
| 21 | 新增: "node": ">=0.1.90" | |
| 22 | 新增: } | |
| 23 | 新增: }, | |
| 24 | 新增: "node_modules/@fastify/busboy": { | |
| 25 | 新增: "version": "2.1.1", | |
| 26 | 新增: "resolved": "https://registry.npmjs.org/@fastify/busboy/-/busboy-2.1.1.tgz", | |
| 27 | 新增: "integrity": "sha512-vBZP4NlzfOlerQTnba4aqZoMhE/a9HY7HRqoOPaETQcSQuWEIyZMHGfVu6w9wGtGK5fED5qRs2DteVCjOH60sA==", | |
| 28 | 新增: "license": "MIT", | |
| 29 | 新增: "engines": { | |
| 30 | 新增: "node": ">=14" | |
| 31 | 新增: } | |
| 32 | 新增: }, | |
| 33 | 新增: "node_modules/@kaitranntt/ccs": { | |
| 34 | 新增: "version": "8.11.0", | |
| 35 | 新增: "resolved": "https://registry.npmjs.org/@kaitranntt/ccs/-/ccs-8.11.0.tgz", | |
| 36 | 新增: "integrity": "sha512-0NQs/rsLbFek7LVGL7a6cr+MTbdAwU9dBlHdMiXecB1dNyVKlEf8pBEko1ozkZv05jMaRcUYY+IaYDpS6n6YyQ==", | |
| 37 | 新增: "hasInstallScript": true, | |
| 38 | 新增: "license": "MIT", | |
| 39 | 新增: "os": [ | |
| 40 | 新增: "darwin", | |
| 41 | 新增: "linux", | |
| 42 | 新增: "win32" | |
| 43 | 新增: ], | |
| 44 | 新增: "dependencies": { | |
| 45 | 新增: "bcrypt": "^6.0.0", | |
| 46 | 新增: "boxen": "^5.1.2", | |
| 47 | 新增: "chalk": "^4.1.2", | |
| 48 | 新增: "chokidar": "^3.6.0", | |
| 49 | 新增: "cli-table3": "^0.6.5", | |
| 50 | 新增: "express": "^4.18.2", | |
| 51 | 新增: "express-rate-limit": "^8.2.1", | |
| 52 | 新增: "express-session": "^1.18.2", | |
| 53 | 新增: "get-port": "^5.1.1", | |
| 54 | 新增: "gradient-string": "^2.0.2", | |
| 55 | 新增: "http-proxy-agent": "^7.0.2", | |
| 56 | 新增: "https-proxy-agent": "^7.0.6", | |
| 57 | 新增: "js-yaml": "^4.1.1", | |
| 58 | 新增: "listr2": "^3.14.0", | |
| 59 | 新增: "open": "^8.4.2", | |
| 60 | 新增: "ora": "^5.4.1", | |
| 61 | 新增: "proper-lockfile": "^4.1.2", | |
| 62 | 新增: "smol-toml": "^1.6.1", | |
| 63 | 新增: "undici": "^5.29.0", | |
| 64 | 新增: "ws": "^8.16.0" | |
| 65 | 新增: }, | |
| 66 | 新增: "bin": { | |
| 67 | 新增: "ccs": "dist/ccs.js", | |
| 68 | 新增: "ccs-codex": "dist/bin/codex-runtime.js", | |
| 69 | 新增: "ccs-droid": "dist/bin/droid-runtime.js", | |
| 70 | 新增: "ccsd": "dist/bin/droid-runtime.js", | |
| 71 | 新增: "ccsx": "dist/bin/codex-runtime.js", | |
| 72 | 新增: "ccsxp": "dist/bin/ccsxp-runtime.js" | |
| 73 | 新增: }, | |
| 74 | 新增: "engines": { | |
| 75 | 新增: "bun": ">=1.0.0", | |
| 76 | 新增: "node": ">=18.0.0" | |
| 77 | 新增: } | |
| 78 | 新增: }, | |
| 79 | 新增: "node_modules/@types/tinycolor2": { | |
| 80 | 新增: "version": "1.4.6", | |
| 81 | 新增: "resolved": "https://registry.npmjs.org/@types/tinycolor2/-/tinycolor2-1.4.6.tgz", | |
| 82 | 新增: "integrity": "sha512-iEN8J0BoMnsWBqjVbWH/c0G0Hh7O21lpR2/+PrvAVgWdzL7eexIFm4JN/Wn10PTcmNdtS6U67r499mlWMXOxNw==", | |
| 83 | 新增: "license": "MIT" | |
| 84 | 新增: }, | |
| 85 | 新增: "node_modules/accepts": { | |
| 86 | 新增: "version": "1.3.8", | |
| 87 | 新增: "resolved": "https://registry.npmjs.org/accepts/-/accepts-1.3.8.tgz", | |
| 88 | 新增: "integrity": "sha512-PYAthTa2m2VKxuvSD3DPC/Gy+U+sOA1LAuT8mkmRuvw+NACSaeXEQ+NHcVF7rONl6qcaxV3Uuemwawk+7+SJLw==", | |
| 89 | 新增: "license": "MIT", | |
| 90 | 新增: "dependencies": { | |
| 91 | 新增: "mime-types": "~2.1.34", | |
| 92 | 新增: "negotiator": "0.6.3" | |
| 93 | 新增: }, | |
| 94 | 新增: "engines": { | |
| 95 | 新增: "node": ">= 0.6" | |
| 96 | 新增: } | |
| 97 | 新增: }, | |
| 98 | 新增: "node_modules/agent-base": { | |
| 99 | 新增: "version": "7.1.4", | |
| 100 | 新增: "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-7.1.4.tgz", | |
| 101 | 新增: "integrity": "sha512-MnA+YT8fwfJPgBx3m60MNqakm30XOkyIoH1y6huTQvC0PwZG7ki8NacLBcrPbNoo8vEZy7Jpuk7+jMO+CUovTQ==", | |
| 102 | 新增: "license": "MIT", | |
| 103 | 新增: "engines": { | |
| 104 | 新增: "node": ">= 14" | |
| 105 | 新增: } | |
| 106 | 新增: }, | |
| 107 | 新增: "node_modules/aggregate-error": { | |
| 108 | 新增: "version": "3.1.0", | |
| 109 | 新增: "resolved": "https://registry.npmjs.org/aggregate-error/-/aggregate-error-3.1.0.tgz", | |
| 110 | 新增: "integrity": "sha512-4I7Td01quW/RpocfNayFdFVk1qSuoh0E7JrbRJ16nH01HhKFQ88INq9Sd+nd72zqRySlr9BmDA8xlEJ6vJMrYA==", | |
| 111 | 新增: "license": "MIT", | |
| 112 | 新增: "dependencies": { | |
| 113 | 新增: "clean-stack": "^2.0.0", | |
| 114 | 新增: "indent-string": "^4.0.0" | |
| 115 | 新增: }, | |
| 116 | 新增: "engines": { | |
| 117 | 新增: "node": ">=8" | |
| 118 | 新增: } | |
| 119 | 新增: }, | |
| 120 | 新增: "node_modules/ansi-align": { | |
| 121 | 新增: "version": "3.0.1", | |
| 122 | 新增: "resolved": "https://registry.npmjs.org/ansi-align/-/ansi-align-3.0.1.tgz", | |
| 123 | 新增: "integrity": "sha512-IOfwwBF5iczOjp/WeY4YxyjqAFMQoZufdQWDd19SEExbVLNXqvpzSJ/M7Za4/sCPmQ0+GRquoA7bGcINcxew6w==", | |
| 124 | 新增: "license": "ISC", | |
| 125 | 新增: "dependencies": { | |
| 126 | 新增: "string-width": "^4.1.0" | |
| 127 | 新增: } | |
| 128 | 新增: }, | |
| 129 | 新增: "node_modules/ansi-escapes": { | |
| 130 | 新增: "version": "4.3.2", | |
| 131 | 新增: "resolved": "https://registry.npmjs.org/ansi-escapes/-/ansi-escapes-4.3.2.tgz", | |
| 132 | 新增: "integrity": "sha512-gKXj5ALrKWQLsYG9jlTRmR/xKluxHV+Z9QEwNIgCfM1/uwPMCuzVVnh5mwTd+OuBZcwSIMbqssNWRm1lE51QaQ==", | |
| 133 | 新增: "license": "MIT", | |
| 134 | 新增: "dependencies": { | |
| 135 | 新增: "type-fest": "^0.21.3" | |
| 136 | 新增: }, | |
| 137 | 新增: "engines": { | |
| 138 | 新增: "node": ">=8" | |
| 139 | 新增: }, | |
| 140 | 新增: "funding": { | |
| 141 | 新增: "url": "https://github.com/sponsors/sindresorhus" | |
| 142 | 新增: } | |
| 143 | 新增: }, | |
| 144 | 新增: "node_modules/ansi-escapes/node_modules/type-fest": { | |
| 145 | 新增: "version": "0.21.3", | |
| 146 | 新增: "resolved": "https://registry.npmjs.org/type-fest/-/type-fest-0.21.3.tgz", | |
| 147 | 新增: "integrity": "sha512-t0rzBq87m3fVcduHDUFhKmyyX+9eo6WQjZvf51Ea/M0Q7+T374Jp1aUiyUl0GKxp8M/OETVHSDvmkyPgvX+X2w==", | |
| 148 | 新增: "license": "(MIT OR CC0-1.0)", | |
| 149 | 新增: "engines": { | |
| 150 | 新增: "node": ">=10" | |
| 151 | 新增: }, | |
| 152 | 新增: "funding": { | |
| 153 | 新增: "url": "https://github.com/sponsors/sindresorhus" | |
| 154 | 新增: } | |
| 155 | 新增: }, | |
| 156 | 新增: "node_modules/ansi-regex": { | |
| 157 | 新增: "version": "5.0.1", | |
| 158 | 新增: "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", | |
| 159 | 新增: "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", | |
| 160 | 新增: "license": "MIT", | |
| 161 | 新增: "engines": { | |
| 162 | 新增: "node": ">=8" | |
| 163 | 新增: } | |
| 164 | 新增: }, | |
| 165 | 新增: "node_modules/ansi-styles": { | |
| 166 | 新增: "version": "4.3.0", | |
| 167 | 新增: "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", | |
| 168 | 新增: "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", | |
| 169 | 新增: "license": "MIT", | |
| 170 | 新增: "dependencies": { | |
| 171 | 新增: "color-convert": "^2.0.1" | |
| 172 | 新增: }, | |
| 173 | 新增: "engines": { | |
| 174 | 新增: "node": ">=8" | |
| 175 | 新增: }, | |
| 176 | 新增: "funding": { | |
| 177 | 新增: "url": "https://github.com/chalk/ansi-styles?sponsor=1" | |
| 178 | 新增: } | |
| 179 | 新增: }, | |
| 180 | 新增: "node_modules/anymatch": { | |
| 181 | 新增: "version": "3.1.3", | |
| 182 | 新增: "resolved": "https://registry.npmjs.org/anymatch/-/anymatch-3.1.3.tgz", | |
| 183 | 新增: "integrity": "sha512-KMReFUr0B4t+D+OBkjR3KYqvocp2XaSzO55UcB6mgQMd3KbcE+mWTyvVV7D/zsdEbNnV6acZUutkiHQXvTr1Rw==", | |
| 184 | 新增: "license": "ISC", | |
| 185 | 新增: "dependencies": { | |
| 186 | 新增: "normalize-path": "^3.0.0", | |
| 187 | 新增: "picomatch": "^2.0.4" | |
| 188 | 新增: }, | |
| 189 | 新增: "engines": { | |
| 190 | 新增: "node": ">= 8" | |
| 191 | 新增: } | |
| 192 | 新增: }, | |
| 193 | 新增: "node_modules/argparse": { | |
| 194 | 新增: "version": "2.0.1", | |
| 195 | 新增: "resolved": "https://registry.npmjs.org/argparse/-/argparse-2.0.1.tgz", | |
| 196 | 新增: "integrity": "sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q==", | |
| 197 | 新增: "license": "Python-2.0" | |
| 198 | 新增: }, | |
| 199 | 新增: "node_modules/array-flatten": { | |
| 200 | 新增: "version": "1.1.1", | |
| 201 | 新增: "resolved": "https://registry.npmjs.org/array-flatten/-/array-flatten-1.1.1.tgz", | |
| 202 | 新增: "integrity": "sha512-PCVAQswWemu6UdxsDFFX/+gVeYqKAod3D3UVm91jHwynguOwAvYPhx8nNlM++NqRcK6CxxpUafjmhIdKiHibqg==", | |
| 203 | 新增: "license": "MIT" | |
| 204 | 新增: }, | |
| 205 | 新增: "node_modules/astral-regex": { | |
| 206 | 新增: "version": "2.0.0", | |
| 207 | 新增: "resolved": "https://registry.npmjs.org/astral-regex/-/astral-regex-2.0.0.tgz", | |
| 208 | 新增: "integrity": "sha512-Z7tMw1ytTXt5jqMcOP+OQteU1VuNK9Y02uuJtKQ1Sv69jXQKKg5cibLwGJow8yzZP+eAc18EmLGPal0bp36rvQ==", | |
| 209 | 新增: "license": "MIT", | |
| 210 | 新增: "engines": { | |
| 211 | 新增: "node": ">=8" | |
| 212 | 新增: } | |
| 213 | 新增: }, | |
| 214 | 新增: "node_modules/base64-js": { | |
| 215 | 新增: "version": "1.5.1", | |
| 216 | 新增: "resolved": "https://registry.npmjs.org/base64-js/-/base64-js-1.5.1.tgz", | |
| 217 | 新增: "integrity": "sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==", | |
| 218 | 新增: "funding": [ | |
| 219 | 新增: { | |
| 220 | 新增: "type": "github", | |
| 221 | 新增: "url": "https://github.com/sponsors/feross" | |
| 222 | 新增: }, | |
| 223 | 新增: { | |
| 224 | 新增: "type": "patreon", | |
| 225 | 新增: "url": "https://www.patreon.com/feross" | |
| 226 | 新增: }, | |
| 227 | 新增: { | |
| 228 | 新增: "type": "consulting", | |
| 229 | 新增: "url": "https://feross.org/support" | |
| 230 | 新增: } | |
| 231 | 新增: ], | |
| 232 | 新增: "license": "MIT" | |
| 233 | 新增: }, | |
| 234 | 新增: "node_modules/bcrypt": { | |
| 235 | 新增: "version": "6.0.0", | |
| 236 | 新增: "resolved": "https://registry.npmjs.org/bcrypt/-/bcrypt-6.0.0.tgz", | |
| 237 | 新增: "integrity": "sha512-cU8v/EGSrnH+HnxV2z0J7/blxH8gq7Xh2JFT6Aroax7UohdmiJJlxApMxtKfuI7z68NvvVcmR78k2LbT6efhRg==", | |
| 238 | 新增: "hasInstallScript": true, | |
| 239 | 新增: "license": "MIT", | |
| 240 | 新增: "dependencies": { | |
| 241 | 新增: "node-addon-api": "^8.3.0", | |
| 242 | 新增: "node-gyp-build": "^4.8.4" | |
| 243 | 新增: }, | |
| 244 | 新增: "engines": { | |
| 245 | 新增: "node": ">= 18" | |
| 246 | 新增: } | |
| 247 | 新增: }, | |
| 248 | 新增: "node_modules/binary-extensions": { | |
| 249 | 新增: "version": "2.3.0", | |
| 250 | 新增: "resolved": "https://registry.npmjs.org/binary-extensions/-/binary-extensions-2.3.0.tgz", | |
| 251 | 新增: "integrity": "sha512-Ceh+7ox5qe7LJuLHoY0feh3pHuUDHAcRUeyL2VYghZwfpkNIy/+8Ocg0a3UuSoYzavmylwuLWQOf3hl0jjMMIw==", | |
| 252 | 新增: "license": "MIT", | |
| 253 | 新增: "engines": { | |
| 254 | 新增: "node": ">=8" | |
| 255 | 新增: }, | |
| 256 | 新增: "funding": { | |
| 257 | 新增: "url": "https://github.com/sponsors/sindresorhus" | |
| 258 | 新增: } | |
| 259 | 新增: }, | |
| 260 | 新增: "node_modules/bl": { | |
| 261 | 新增: "version": "4.1.0", | |
| 262 | 新增: "resolved": "https://registry.npmjs.org/bl/-/bl-4.1.0.tgz", | |
| 263 | 新增: "integrity": "sha512-1W07cM9gS6DcLperZfFSj+bWLtaPGSOHWhPiGzXmvVJbRLdG82sH/Kn8EtW1VqWVA54AKf2h5k5BbnIbwF3h6w==", | |
| 264 | 新增: "license": "MIT", | |
| 265 | 新增: "dependencies": { | |
| 266 | 新增: "buffer": "^5.5.0", | |
| 267 | 新增: "inherits": "^2.0.4", | |
| 268 | 新增: "readable-stream": "^3.4.0" | |
| 269 | 新增: } | |
| 270 | 新增: }, | |
| 271 | 新增: "node_modules/body-parser": { | |
| 272 | 新增: "version": "1.20.9", | |
| 273 | 新增: "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-1.20.9.tgz", | |
| 274 | 新增: "integrity": "sha512-FISIQxV5u91Y9gvuFq3q/tA/qTqLJn3AhRcEvyozyhJTh5OBFFtv827AdHU7Rbyct4r+Ba1/99oFa1Y3yuFsdw==", | |
| 275 | 新增: "license": "MIT", | |
| 276 | 新增: "dependencies": { | |
| 277 | 新增: "bytes": "~3.1.2", | |
| 278 | 新增: "content-type": "~1.0.5", | |
| 279 | 新增: "debug": "2.6.9", | |
| 280 | 新增: "depd": "2.0.0", | |
| 281 | 新增: "destroy": "~1.2.0", | |
| 282 | 新增: "http-errors": "~2.0.1", | |
| 283 | 新增: "iconv-lite": "~0.4.24", | |
| 284 | 新增: "on-finished": "~2.4.1", | |
| 285 | 新增: "qs": "~6.16.0", | |
| 286 | 新增: "raw-body": "~2.5.3", | |
| 287 | 新增: "type-is": "~1.6.18", | |
| 288 | 新增: "unpipe": "~1.0.0" | |
| 289 | 新增: }, | |
| 290 | 新增: "engines": { | |
| 291 | 新增: "node": ">= 0.8", | |
| 292 | 新增: "npm": "1.2.8000 || >= 1.4.16" | |
| 293 | 新增: } | |
| 294 | 新增: }, | |
| 295 | 新增: "node_modules/boxen": { | |
| 296 | 新增: "version": "5.1.2", | |
| 297 | 新增: "resolved": "https://registry.npmjs.org/boxen/-/boxen-5.1.2.tgz", | |
| 298 | 新增: "integrity": "sha512-9gYgQKXx+1nP8mP7CzFyaUARhg7D3n1dF/FnErWmu9l6JvGpNUN278h0aSb+QjoiKSWG+iZ3uHrcqk0qrY9RQQ==", | |
| 299 | 新增: "license": "MIT", | |
| 300 | 新增: "dependencies": { | |
| 301 | 新增: "ansi-align": "^3.0.0", | |
| 302 | 新增: "camelcase": "^6.2.0", | |
| 303 | 新增: "chalk": "^4.1.0", | |
| 304 | 新增: "cli-boxes": "^2.2.1", | |
| 305 | 新增: "string-width": "^4.2.2", | |
| 306 | 新增: "type-fest": "^0.20.2", | |
| 307 | 新增: "widest-line": "^3.1.0", | |
| 308 | 新增: "wrap-ansi": "^7.0.0" | |
| 309 | 新增: }, | |
| 310 | 新增: "engines": { | |
| 311 | 新增: "node": ">=10" | |
| 312 | 新增: }, | |
| 313 | 新增: "funding": { | |
| 314 | 新增: "url": "https://github.com/sponsors/sindresorhus" | |
| 315 | 新增: } | |
| 316 | 新增: }, | |
| 317 | 新增: "node_modules/braces": { | |
| 318 | 新增: "version": "3.0.3", | |
| 319 | 新增: "resolved": "https://registry.npmjs.org/braces/-/braces-3.0.3.tgz", | |
| 320 | 新增: "integrity": "sha512-yQbXgO/OSZVD2IsiLlro+7Hf6Q18EJrKSEsdoMzKePKXct3gvD8oLcOQdIzGupr5Fj+EDe8gO/lxc1BzfMpxvA==", | |
| 321 | 新增: "license": "MIT", | |
| 322 | 新增: "dependencies": { | |
| 323 | 新增: "fill-range": "^7.1.1" | |
| 324 | 新增: }, | |
| 325 | 新增: "engines": { | |
| 326 | 新增: "node": ">=8" | |
| 327 | 新增: } | |
| 328 | 新增: }, | |
| 329 | 新增: "node_modules/buffer": { | |
| 330 | 新增: "version": "5.7.1", | |
| 331 | 新增: "resolved": "https://registry.npmjs.org/buffer/-/buffer-5.7.1.tgz", | |
| 332 | 新增: "integrity": "sha512-EHcyIPBQ4BSGlvjB16k5KgAJ27CIsHY/2JBmCRReo48y9rQ3MaUzWX3KVlBa4U7MyX02HdVj0K7C3WaB3ju7FQ==", | |
| 333 | 新增: "funding": [ | |
| 334 | 新增: { | |
| 335 | 新增: "type": "github", | |
| 336 | 新增: "url": "https://github.com/sponsors/feross" | |
| 337 | 新增: }, | |
| 338 | 新增: { | |
| 339 | 新增: "type": "patreon", | |
| 340 | 新增: "url": "https://www.patreon.com/feross" | |
| 341 | 新增: }, | |
| 342 | 新增: { | |
| 343 | 新增: "type": "consulting", | |
| 344 | 新增: "url": "https://feross.org/support" | |
| 345 | 新增: } | |
| 346 | 新增: ], | |
| 347 | 新增: "license": "MIT", | |
| 348 | 新增: "dependencies": { | |
| 349 | 新增: "base64-js": "^1.3.1", | |
| 350 | 新增: "ieee754": "^1.1.13" | |
| 351 | 新增: } | |
| 352 | 新增: }, | |
| 353 | 新增: "node_modules/bytes": { | |
| 354 | 新增: "version": "3.1.2", | |
| 355 | 新增: "resolved": "https://registry.npmjs.org/bytes/-/bytes-3.1.2.tgz", | |
| 356 | 新增: "integrity": "sha512-/Nf7TyzTx6S3yRJObOAV7956r8cr2+Oj8AC5dt8wSP3BQAoeX58NoHyCU8P8zGkNXStjTSi6fzO6F0pBdcYbEg==", | |
| 357 | 新增: "license": "MIT", | |
| 358 | 新增: "engines": { | |
| 359 | 新增: "node": ">= 0.8" | |
| 360 | 新增: } | |
| 361 | 新增: }, | |
| 362 | 新增: "node_modules/call-bind-apply-helpers": { | |
| 363 | 新增: "version": "1.0.2", | |
| 364 | 新增: "resolved": "https://registry.npmjs.org/call-bind-apply-helpers/-/call-bind-apply-helpers-1.0.2.tgz", | |
| 365 | 新增: "integrity": "sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==", | |
| 366 | 新增: "license": "MIT", | |
| 367 | 新增: "dependencies": { | |
| 368 | 新增: "es-errors": "^1.3.0", | |
| 369 | 新增: "function-bind": "^1.1.2" | |
| 370 | 新增: }, | |
| 371 | 新增: "engines": { | |
| 372 | 新增: "node": ">= 0.4" | |
| 373 | 新增: } | |
| 374 | 新增: }, | |
| 375 | 新增: "node_modules/call-bound": { | |
| 376 | 新增: "version": "1.0.4", | |
| 377 | 新增: "resolved": "https://registry.npmjs.org/call-bound/-/call-bound-1.0.4.tgz", | |
| 378 | 新增: "integrity": "sha512-+ys997U96po4Kx/ABpBCqhA9EuxJaQWDQg7295H4hBphv3IZg0boBKuwYpt4YXp6MZ5AmZQnU/tyMTlRpaSejg==", | |
| 379 | 新增: "license": "MIT", | |
| 380 | 新增: "dependencies": { | |
| 381 | 新增: "call-bind-apply-helpers": "^1.0.2", | |
| 382 | 新增: "get-intrinsic": "^1.3.0" | |
| 383 | 新增: }, | |
| 384 | 新增: "engines": { | |
| 385 | 新增: "node": ">= 0.4" | |
| 386 | 新增: }, | |
| 387 | 新增: "funding": { | |
| 388 | 新增: "url": "https://github.com/sponsors/ljharb" | |
| 389 | 新增: } | |
| 390 | 新增: }, | |
| 391 | 新增: "node_modules/camelcase": { | |
| 392 | 新增: "version": "6.3.0", | |
| 393 | 新增: "resolved": "https://registry.npmjs.org/camelcase/-/camelcase-6.3.0.tgz", | |
| 394 | 新增: "integrity": "sha512-Gmy6FhYlCY7uOElZUSbxo2UCDH8owEk996gkbrpsgGtrJLM3J7jGxl9Ic7Qwwj4ivOE5AWZWRMecDdF7hqGjFA==", | |
| 395 | 新增: "license": "MIT", | |
| 396 | 新增: "engines": { | |
| 397 | 新增: "node": ">=10" | |
| 398 | 新增: }, | |
| 399 | 新增: "funding": { | |
| 400 | 新增: "url": "https://github.com/sponsors/sindresorhus" | |
| 401 | 新增: } | |
| 402 | 新增: }, | |
| 403 | 新增: "node_modules/chalk": { | |
| 404 | 新增: "version": "4.1.2", | |
| 405 | 新增: "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz", | |
| 406 | 新增: "integrity": "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==", | |
| 407 | 新增: "license": "MIT", | |
| 408 | 新增: "dependencies": { | |
| 409 | 新增: "ansi-styles": "^4.1.0", | |
| 410 | 新增: "supports-color": "^7.1.0" | |
| 411 | 新增: }, | |
| 412 | 新增: "engines": { | |
| 413 | 新增: "node": ">=10" | |
| 414 | 新增: }, | |
| 415 | 新增: "funding": { | |
| 416 | 新增: "url": "https://github.com/chalk/chalk?sponsor=1" | |
| 417 | 新增: } | |
| 418 | 新增: }, | |
| 419 | 新增: "node_modules/chokidar": { | |
| 420 | 新增: "version": "3.6.0", | |
| 421 | 新增: "resolved": "https://registry.npmjs.org/chokidar/-/chokidar-3.6.0.tgz", | |
| 422 | 新增: "integrity": "sha512-7VT13fmjotKpGipCW9JEQAusEPE+Ei8nl6/g4FBAmIm0GOOLMua9NDDo/DWp0ZAxCr3cPq5ZpBqmPAQgDda2Pw==", | |
| 423 | 新增: "license": "MIT", | |
| 424 | 新增: "dependencies": { | |
| 425 | 新增: "anymatch": "~3.1.2", | |
| 426 | 新增: "braces": "~3.0.2", | |
| 427 | 新增: "glob-parent": "~5.1.2", | |
| 428 | 新增: "is-binary-path": "~2.1.0", | |
| 429 | 新增: "is-glob": "~4.0.1", | |
| 430 | 新增: "normalize-path": "~3.0.0", | |
| 431 | 新增: "readdirp": "~3.6.0" | |
| 432 | 新增: }, | |
| 433 | 新增: "engines": { | |
| 434 | 新增: "node": ">= 8.10.0" | |
| 435 | 新增: }, | |
| 436 | 新增: "funding": { | |
| 437 | 新增: "url": "https://paulmillr.com/funding/" | |
| 438 | 新增: }, | |
| 439 | 新增: "optionalDependencies": { | |
| 440 | 新增: "fsevents": "~2.3.2" | |
| 441 | 新增: } | |
| 442 | 新增: }, | |
| 443 | 新增: "node_modules/clean-stack": { | |
| 444 | 新增: "version": "2.2.0", | |
| 445 | 新增: "resolved": "https://registry.npmjs.org/clean-stack/-/clean-stack-2.2.0.tgz", | |
| 446 | 新增: "integrity": "sha512-4diC9HaTE+KRAMWhDhrGOECgWZxoevMc5TlkObMqNSsVU62PYzXZ/SMTjzyGAFF1YusgxGcSWTEXBhp0CPwQ1A==", | |
| 447 | 新增: "license": "MIT", | |
| 448 | 新增: "engines": { | |
| 449 | 新增: "node": ">=6" | |
| 450 | 新增: } | |
| 451 | 新增: }, | |
| 452 | 新增: "node_modules/cli-boxes": { | |
| 453 | 新增: "version": "2.2.1", | |
| 454 | 新增: "resolved": "https://registry.npmjs.org/cli-boxes/-/cli-boxes-2.2.1.tgz", | |
| 455 | 新增: "integrity": "sha512-y4coMcylgSCdVinjiDBuR8PCC2bLjyGTwEmPb9NHR/QaNU6EUOXcTY/s6VjGMD6ENSEaeQYHCY0GNGS5jfMwPw==", | |
| 456 | 新增: "license": "MIT", | |
| 457 | 新增: "engines": { | |
| 458 | 新增: "node": ">=6" | |
| 459 | 新增: }, | |
| 460 | 新增: "funding": { | |
| 461 | 新增: "url": "https://github.com/sponsors/sindresorhus" | |
| 462 | 新增: } | |
| 463 | 新增: }, | |
| 464 | 新增: "node_modules/cli-cursor": { | |
| 465 | 新增: "version": "3.1.0", | |
| 466 | 新增: "resolved": "https://registry.npmjs.org/cli-cursor/-/cli-cursor-3.1.0.tgz", | |
| 467 | 新增: "integrity": "sha512-I/zHAwsKf9FqGoXM4WWRACob9+SNukZTd94DWF57E4toouRulbCxcUh6RKUEOQlYTHJnzkPMySvPNaaSLNfLZw==", | |
| 468 | 新增: "license": "MIT", | |
| 469 | 新增: "dependencies": { | |
| 470 | 新增: "restore-cursor": "^3.1.0" | |
| 471 | 新增: }, | |
| 472 | 新增: "engines": { | |
| 473 | 新增: "node": ">=8" | |
| 474 | 新增: } | |
| 475 | 新增: }, | |
| 476 | 新增: "node_modules/cli-spinners": { | |
| 477 | 新增: "version": "2.9.2", | |
| 478 | 新增: "resolved": "https://registry.npmjs.org/cli-spinners/-/cli-spinners-2.9.2.tgz", | |
| 479 | 新增: "integrity": "sha512-ywqV+5MmyL4E7ybXgKys4DugZbX0FC6LnwrhjuykIjnK9k8OQacQ7axGKnjDXWNhns0xot3bZI5h55H8yo9cJg==", | |
| 480 | 新增: "license": "MIT", | |
| 481 | 新增: "engines": { | |
| 482 | 新增: "node": ">=6" | |
| 483 | 新增: }, | |
| 484 | 新增: "funding": { | |
| 485 | 新增: "url": "https://github.com/sponsors/sindresorhus" | |
| 486 | 新增: } | |
| 487 | 新增: }, | |
| 488 | 新增: "node_modules/cli-table3": { | |
| 489 | 新增: "version": "0.6.5", | |
| 490 | 新增: "resolved": "https://registry.npmjs.org/cli-table3/-/cli-table3-0.6.5.tgz", | |
| 491 | 新增: "integrity": "sha512-+W/5efTR7y5HRD7gACw9yQjqMVvEMLBHmboM/kPWam+H+Hmyrgjh6YncVKK122YZkXrLudzTuAukUw9FnMf7IQ==", | |
| 492 | 新增: "license": "MIT", | |
| 493 | 新增: "dependencies": { | |
| 494 | 新增: "string-width": "^4.2.0" | |
| 495 | 新增: }, | |
| 496 | 新增: "engines": { | |
| 497 | 新增: "node": "10.* || >= 12.*" | |
| 498 | 新增: }, | |
| 499 | 新增: "optionalDependencies": { | |
| 500 | 新增: "@colors/colors": "1.5.0" | |
| 501 | 新增: } | |
| 502 | 新增: }, | |
| 503 | 新增: "node_modules/cli-truncate": { | |
| 504 | 新增: "version": "2.1.0", | |
| 505 | 新增: "resolved": "https://registry.npmjs.org/cli-truncate/-/cli-truncate-2.1.0.tgz", | |
| 506 | 新增: "integrity": "sha512-n8fOixwDD6b/ObinzTrp1ZKFzbgvKZvuz/TvejnLn1aQfC6r52XEx85FmuC+3HI+JM7coBRXUvNqEU2PHVrHpg==", | |
| 507 | 新增: "license": "MIT", | |
| 508 | 新增: "dependencies": { | |
| 509 | 新增: "slice-ansi": "^3.0.0", | |
| 510 | 新增: "string-width": "^4.2.0" | |
| 511 | 新增: }, | |
| 512 | 新增: "engines": { | |
| 513 | 新增: "node": ">=8" | |
| 514 | 新增: }, | |
| 515 | 新增: "funding": { | |
| 516 | 新增: "url": "https://github.com/sponsors/sindresorhus" | |
| 517 | 新增: } | |
| 518 | 新增: }, | |
| 519 | 新增: "node_modules/clone": { | |
| 520 | 新增: "version": "1.0.4", | |
| 521 | 新增: "resolved": "https://registry.npmjs.org/clone/-/clone-1.0.4.tgz", | |
| 522 | 新增: "integrity": "sha512-JQHZ2QMW6l3aH/j6xCqQThY/9OH4D/9ls34cgkUBiEeocRTU04tHfKPBsUK1PqZCUQM7GiA0IIXJSuXHI64Kbg==", | |
| 523 | 新增: "license": "MIT", | |
| 524 | 新增: "engines": { | |
| 525 | 新增: "node": ">=0.8" | |
| 526 | 新增: } | |
| 527 | 新增: }, | |
| 528 | 新增: "node_modules/color-convert": { | |
| 529 | 新增: "version": "2.0.1", | |
| 530 | 新增: "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", | |
| 531 | 新增: "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", | |
| 532 | 新增: "license": "MIT", | |
| 533 | 新增: "dependencies": { | |
| 534 | 新增: "color-name": "~1.1.4" | |
| 535 | 新增: }, | |
| 536 | 新增: "engines": { | |
| 537 | 新增: "node": ">=7.0.0" | |
| 538 | 新增: } | |
| 539 | 新增: }, | |
| 540 | 新增: "node_modules/color-name": { | |
| 541 | 新增: "version": "1.1.4", | |
| 542 | 新增: "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", | |
| 543 | 新增: "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", | |
| 544 | 新增: "license": "MIT" | |
| 545 | 新增: }, | |
| 546 | 新增: "node_modules/colorette": { | |
| 547 | 新增: "version": "2.0.20", | |
| 548 | 新增: "resolved": "https://registry.npmjs.org/colorette/-/colorette-2.0.20.tgz", | |
| 549 | 新增: "integrity": "sha512-IfEDxwoWIjkeXL1eXcDiow4UbKjhLdq6/EuSVR9GMN7KVH3r9gQ83e73hsz1Nd1T3ijd5xv1wcWRYO+D6kCI2w==", | |
| 550 | 新增: "license": "MIT" | |
| 551 | 新增: }, | |
| 552 | 新增: "node_modules/content-disposition": { | |
| 553 | 新增: "version": "0.5.4", | |
| 554 | 新增: "resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-0.5.4.tgz", | |
| 555 | 新增: "integrity": "sha512-FveZTNuGw04cxlAiWbzi6zTAL/lhehaWbTtgluJh4/E95DqMwTmha3KZN1aAWA8cFIhHzMZUvLevkw5Rqk+tSQ==", | |
| 556 | 新增: "license": "MIT", | |
| 557 | 新增: "dependencies": { | |
| 558 | 新增: "safe-buffer": "5.2.1" | |
| 559 | 新增: }, | |
| 560 | 新增: "engines": { | |
| 561 | 新增: "node": ">= 0.6" | |
| 562 | 新增: } | |
| 563 | 新增: }, | |
| 564 | 新增: "node_modules/content-type": { | |
| 565 | 新增: "version": "1.0.5", | |
| 566 | 新增: "resolved": "https://registry.npmjs.org/content-type/-/content-type-1.0.5.tgz", | |
| 567 | 新增: "integrity": "sha512-nTjqfcBFEipKdXCv4YDQWCfmcLZKm81ldF0pAopTvyrFGVbcR6P/VAAd5G7N+0tTr8QqiU0tFadD6FK4NtJwOA==", | |
| 568 | 新增: "license": "MIT", | |
| 569 | 新增: "engines": { | |
| 570 | 新增: "node": ">= 0.6" | |
| 571 | 新增: } | |
| 572 | 新增: }, | |
| 573 | 新增: "node_modules/cookie": { | |
| 574 | 新增: "version": "0.7.2", | |
| 575 | 新增: "resolved": "https://registry.npmjs.org/cookie/-/cookie-0.7.2.tgz", | |
| 576 | 新增: "integrity": "sha512-yki5XnKuf750l50uGTllt6kKILY4nQ1eNIQatoXEByZ5dWgnKqbnqmTrBE5B4N7lrMJKQ2ytWMiTO2o0v6Ew/w==", | |
| 577 | 新增: "license": "MIT", | |
| 578 | 新增: "engines": { | |
| 579 | 新增: "node": ">= 0.6" | |
| 580 | 新增: } | |
| 581 | 新增: }, | |
| 582 | 新增: "node_modules/cookie-signature": { | |
| 583 | 新增: "version": "1.0.7", | |
| 584 | 新增: "resolved": "https://registry.npmjs.org/cookie-signature/-/cookie-signature-1.0.7.tgz", | |
| 585 | 新增: "integrity": "sha512-NXdYc3dLr47pBkpUCHtKSwIOQXLVn8dZEuywboCOJY/osA0wFSLlSawr3KN8qXJEyX66FcONTH8EIlVuK0yyFA==", | |
| 586 | 新增: "license": "MIT" | |
| 587 | 新增: }, | |
| 588 | 新增: "node_modules/debug": { | |
| 589 | 新增: "version": "2.6.9", | |
| 590 | 新增: "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", | |
| 591 | 新增: "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==", | |
| 592 | 新增: "license": "MIT", | |
| 593 | 新增: "dependencies": { | |
| 594 | 新增: "ms": "2.0.0" | |
| 595 | 新增: } | |
| 596 | 新增: }, | |
| 597 | 新增: "node_modules/defaults": { | |
| 598 | 新增: "version": "1.0.4", | |
| 599 | 新增: "resolved": "https://registry.npmjs.org/defaults/-/defaults-1.0.4.tgz", | |
| 600 | 新增: "integrity": "sha512-eFuaLoy/Rxalv2kr+lqMlUnrDWV+3j4pljOIJgLIhI058IQfWJ7vXhyEIHu+HtC738klGALYxOKDO0bQP3tg8A==", | |
| 601 | 新增: "license": "MIT", | |
| 602 | 新增: "dependencies": { | |
| 603 | 新增: "clone": "^1.0.2" | |
| 604 | 新增: }, | |
| 605 | 新增: "funding": { | |
| 606 | 新增: "url": "https://github.com/sponsors/sindresorhus" | |
| 607 | 新增: } | |
| 608 | 新增: }, | |
| 609 | 新增: "node_modules/define-lazy-prop": { | |
| 610 | 新增: "version": "2.0.0", | |
| 611 | 新增: "resolved": "https://registry.npmjs.org/define-lazy-prop/-/define-lazy-prop-2.0.0.tgz", | |
| 612 | 新增: "integrity": "sha512-Ds09qNh8yw3khSjiJjiUInaGX9xlqZDY7JVryGxdxV7NPeuqQfplOpQ66yJFZut3jLa5zOwkXw1g9EI2uKh4Og==", | |
| 613 | 新增: "license": "MIT", | |
| 614 | 新增: "engines": { | |
| 615 | 新增: "node": ">=8" | |
| 616 | 新增: } | |
| 617 | 新增: }, | |
| 618 | 新增: "node_modules/depd": { | |
| 619 | 新增: "version": "2.0.0", | |
| 620 | 新增: "resolved": "https://registry.npmjs.org/depd/-/depd-2.0.0.tgz", | |
| 621 | 新增: "integrity": "sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw==", | |
| 622 | 新增: "license": "MIT", | |
| 623 | 新增: "engines": { | |
| 624 | 新增: "node": ">= 0.8" | |
| 625 | 新增: } | |
| 626 | 新增: }, | |
| 627 | 新增: "node_modules/destroy": { | |
| 628 | 新增: "version": "1.2.0", | |
| 629 | 新增: "resolved": "https://registry.npmjs.org/destroy/-/destroy-1.2.0.tgz", | |
| 630 | 新增: "integrity": "sha512-2sJGJTaXIIaR1w4iJSNoN0hnMY7Gpc/n8D4qSCJw8QqFWXf7cuAgnEHxBpweaVcPevC2l3KpjYCx3NypQQgaJg==", | |
| 631 | 新增: "license": "MIT", | |
| 632 | 新增: "engines": { | |
| 633 | 新增: "node": ">= 0.8", | |
| 634 | 新增: "npm": "1.2.8000 || >= 1.4.16" | |
| 635 | 新增: } | |
| 636 | 新增: }, | |
| 637 | 新增: "node_modules/dunder-proto": { | |
| 638 | 新增: "version": "1.0.1", | |
| 639 | 新增: "resolved": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz", | |
| 640 | 新增: "integrity": "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==", | |
| 641 | 新增: "license": "MIT", | |
| 642 | 新增: "dependencies": { | |
| 643 | 新增: "call-bind-apply-helpers": "^1.0.1", | |
| 644 | 新增: "es-errors": "^1.3.0", | |
| 645 | 新增: "gopd": "^1.2.0" | |
| 646 | 新增: }, | |
| 647 | 新增: "engines": { | |
| 648 | 新增: "node": ">= 0.4" | |
| 649 | 新增: } | |
| 650 | 新增: }, | |
| 651 | 新增: "node_modules/ee-first": { | |
| 652 | 新增: "version": "1.1.1", | |
| 653 | 新增: "resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz", | |
| 654 | 新增: "integrity": "sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow==", | |
| 655 | 新增: "license": "MIT" | |
| 656 | 新增: }, | |
| 657 | 新增: "node_modules/emoji-regex": { | |
| 658 | 新增: "version": "8.0.0", | |
| 659 | 新增: "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz", | |
| 660 | 新增: "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==", | |
| 661 | 新增: "license": "MIT" | |
| 662 | 新增: }, | |
| 663 | 新增: "node_modules/encodeurl": { | |
| 664 | 新增: "version": "2.0.1", | |
| 665 | 新增: "resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-2.0.1.tgz", | |
| 666 | 新增: "integrity": "sha512-Ev/hIyePLZtpL98x562lvPtenrUfGr0lfaf44HFZ+hDEwso7ccV9QAZrEVLg0hxNAzygaAFxy2dYaAKKM0G06A==", | |
| 667 | 新增: "license": "MIT", | |
| 668 | 新增: "engines": { | |
| 669 | 新增: "node": ">= 0.8" | |
| 670 | 新增: }, | |
| 671 | 新增: "funding": { | |
| 672 | 新增: "type": "opencollective", | |
| 673 | 新增: "url": "https://opencollective.com/express" | |
| 674 | 新增: } | |
| 675 | 新增: }, | |
| 676 | 新增: "node_modules/es-define-property": { | |
| 677 | 新增: "version": "1.0.1", | |
| 678 | 新增: "resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.1.tgz", | |
| 679 | 新增: "integrity": "sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==", | |
| 680 | 新增: "license": "MIT", | |
| 681 | 新增: "engines": { | |
| 682 | 新增: "node": ">= 0.4" | |
| 683 | 新增: } | |
| 684 | 新增: }, | |
| 685 | 新增: "node_modules/es-errors": { | |
| 686 | 新增: "version": "1.3.0", | |
| 687 | 新增: "resolved": "https://registry.npmjs.org/es-errors/-/es-errors-1.3.0.tgz", | |
| 688 | 新增: "integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==", | |
| 689 | 新增: "license": "MIT", | |
| 690 | 新增: "engines": { | |
| 691 | 新增: "node": ">= 0.4" | |
| 692 | 新增: } | |
| 693 | 新增: }, | |
| 694 | 新增: "node_modules/es-object-atoms": { | |
| 695 | 新增: "version": "1.1.2", | |
| 696 | 新增: "resolved": "https://registry.npmjs.org/es-object-atoms/-/es-object-atoms-1.1.2.tgz", | |
| 697 | 新增: "integrity": "sha512-HWcBoN6NileqtSydK2FqHbS/LoDd2pqrnQHLyJzBj4kOp/ky2MWMN694xOfkK8/SnUsW2DH7EfyVlydKCsm1Zw==", | |
| 698 | 新增: "license": "MIT", | |
| 699 | 新增: "dependencies": { | |
| 700 | 新增: "es-errors": "^1.3.0" | |
| 701 | 新增: }, | |
| 702 | 新增: "engines": { | |
| 703 | 新增: "node": ">= 0.4" | |
| 704 | 新增: } | |
| 705 | 新增: }, | |
| 706 | 新增: "node_modules/escape-html": { | |
| 707 | 新增: "version": "1.0.3", | |
| 708 | 新增: "resolved": "https://registry.npmjs.org/escape-html/-/escape-html-1.0.3.tgz", | |
| 709 | 新增: "integrity": "sha512-NiSupZ4OeuGwr68lGIeym/ksIZMJodUGOSCZ/FSnTxcrekbvqrgdUxlJOMpijaKZVjAJrWrGs/6Jy8OMuyj9ow==", | |
| 710 | 新增: "license": "MIT" | |
| 711 | 新增: }, | |
| 712 | 新增: "node_modules/etag": { | |
| 713 | 新增: "version": "1.8.1", | |
| 714 | 新增: "resolved": "https://registry.npmjs.org/etag/-/etag-1.8.1.tgz", | |
| 715 | 新增: "integrity": "sha512-aIL5Fx7mawVa300al2BnEE4iNvo1qETxLrPI/o05L7z6go7fCw1J6EQmbK4FmJ2AS7kgVF/KEZWufBfdClMcPg==", | |
| 716 | 新增: "license": "MIT", | |
| 717 | 新增: "engines": { | |
| 718 | 新增: "node": ">= 0.6" | |
| 719 | 新增: } | |
| 720 | 新增: }, | |
| 721 | 新增: "node_modules/express": { | |
| 722 | 新增: "version": "4.22.3", | |
| 723 | 新增: "resolved": "https://registry.npmjs.org/express/-/express-4.22.3.tgz", | |
| 724 | 新增: "integrity": "sha512-Bdcs4+3qlpVlx2NRn6fgX2Ue2/gGRaPeawebgclM0ERSCqDpA+owF1fdPwjJUTAJWMTuAaxjDf+hzb0/4eKvvw==", | |
| 725 | 新增: "license": "MIT", | |
| 726 | 新增: "dependencies": { | |
| 727 | 新增: "accepts": "~1.3.8", | |
| 728 | 新增: "array-flatten": "1.1.1", | |
| 729 | 新增: "body-parser": "~1.20.5", | |
| 730 | 新增: "content-disposition": "~0.5.4", | |
| 731 | 新增: "content-type": "~1.0.4", | |
| 732 | 新增: "cookie": "~0.7.1", | |
| 733 | 新增: "cookie-signature": "~1.0.6", | |
| 734 | 新增: "debug": "2.6.9", | |
| 735 | 新增: "depd": "2.0.0", | |
| 736 | 新增: "encodeurl": "~2.0.0", | |
| 737 | 新增: "escape-html": "~1.0.3", | |
| 738 | 新增: "etag": "~1.8.1", | |
| 739 | 新增: "finalhandler": "~1.3.1", | |
| 740 | 新增: "fresh": "~0.5.2", | |
| 741 | 新增: "http-errors": "~2.0.0", | |
| 742 | 新增: "merge-descriptors": "1.0.3", | |
| 743 | 新增: "methods": "~1.1.2", | |
| 744 | 新增: "on-finished": "~2.4.1", | |
| 745 | 新增: "parseurl": "~1.3.3", | |
| 746 | 新增: "path-to-regexp": "~0.1.13", | |
| 747 | 新增: "proxy-addr": "~2.0.7", | |
| 748 | 新增: "qs": "~6.16.0", | |
| 749 | 新增: "range-parser": "~1.2.1", | |
| 750 | 新增: "safe-buffer": "5.2.1", | |
| 751 | 新增: "send": "~0.19.0", | |
| 752 | 新增: "serve-static": "~1.16.2", | |
| 753 | 新增: "setprototypeof": "1.2.0", | |
| 754 | 新增: "statuses": "~2.0.1", | |
| 755 | 新增: "type-is": "~1.6.18", | |
| 756 | 新增: "utils-merge": "1.0.1", | |
| 757 | 新增: "vary": "~1.1.2" | |
| 758 | 新增: }, | |
| 759 | 新增: "engines": { | |
| 760 | 新增: "node": ">= 0.10.0" | |
| 761 | 新增: }, | |
| 762 | 新增: "funding": { | |
| 763 | 新增: "type": "opencollective", | |
| 764 | 新增: "url": "https://opencollective.com/express" | |
| 765 | 新增: } | |
| 766 | 新增: }, | |
| 767 | 新增: "node_modules/express-rate-limit": { | |
| 768 | 新增: "version": "8.7.3", | |
| 769 | 新增: "resolved": "https://registry.npmjs.org/express-rate-limit/-/express-rate-limit-8.7.3.tgz", | |
| 770 | 新增: "integrity": "sha512-zPLqDI2f0gV2WmGnacLf9XSSqn4VldRyP5LCzOwx0BKH40mO6+2PCFkoSsRO2jePx87/Kf6NUF6P2QOTKXHbQA==", | |
| 771 | 新增: "license": "MIT", | |
| 772 | 新增: "dependencies": { | |
| 773 | 新增: "debug": "^4.4.3", | |
| 774 | 新增: "ip-address": "^10.2.0" | |
| 775 | 新增: }, | |
| 776 | 新增: "engines": { | |
| 777 | 新增: "node": ">= 16" | |
| 778 | 新增: }, | |
| 779 | 新增: "funding": { | |
| 780 | 新增: "url": "https://github.com/sponsors/express-rate-limit" | |
| 781 | 新增: }, | |
| 782 | 新增: "peerDependencies": { | |
| 783 | 新增: "express": ">= 4.11" | |
| 784 | 新增: } | |
| 785 | 新增: }, | |
| 786 | 新增: "node_modules/express-rate-limit/node_modules/debug": { | |
| 787 | 新增: "version": "4.4.3", | |
| 788 | 新增: "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", | |
| 789 | 新增: "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==", | |
| 790 | 新增: "license": "MIT", | |
| 791 | 新增: "dependencies": { | |
| 792 | 新增: "ms": "^2.1.3" | |
| 793 | 新增: }, | |
| 794 | 新增: "engines": { | |
| 795 | 新增: "node": ">=6.0" | |
| 796 | 新增: }, | |
| 797 | 新增: "peerDependenciesMeta": { | |
| 798 | 新增: "supports-color": { | |
| 799 | 新增: "optional": true | |
| 800 | 新增: } | |
| 801 | 新增: } | |
| 802 | 新增: }, | |
| 803 | 新增: "node_modules/express-rate-limit/node_modules/ms": { | |
| 804 | 新增: "version": "2.1.3", | |
| 805 | 新增: "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", | |
| 806 | 新增: "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", | |
| 807 | 新增: "license": "MIT" | |
| 808 | 新增: }, | |
| 809 | 新增: "node_modules/express-session": { | |
| 810 | 新增: "version": "1.19.0", | |
| 811 | 新增: "resolved": "https://registry.npmjs.org/express-session/-/express-session-1.19.0.tgz", | |
| 812 | 新增: "integrity": "sha512-0csaMkGq+vaiZTmSMMGkfdCOabYv192VbytFypcvI0MANrp+4i/7yEkJ0sbAEhycQjntaKGzYfjfXQyVb7BHMA==", | |
| 813 | 新增: "license": "MIT", | |
| 814 | 新增: "dependencies": { | |
| 815 | 新增: "cookie": "~0.7.2", | |
| 816 | 新增: "cookie-signature": "~1.0.7", | |
| 817 | 新增: "debug": "~2.6.9", | |
| 818 | 新增: "depd": "~2.0.0", | |
| 819 | 新增: "on-headers": "~1.1.0", | |
| 820 | 新增: "parseurl": "~1.3.3", | |
| 821 | 新增: "safe-buffer": "~5.2.1", | |
| 822 | 新增: "uid-safe": "~2.1.5" | |
| 823 | 新增: }, | |
| 824 | 新增: "engines": { | |
| 825 | 新增: "node": ">= 0.8.0" | |
| 826 | 新增: }, | |
| 827 | 新增: "funding": { | |
| 828 | 新增: "type": "opencollective", | |
| 829 | 新增: "url": "https://opencollective.com/express" | |
| 830 | 新增: } | |
| 831 | 新增: }, | |
| 832 | 新增: "node_modules/fill-range": { | |
| 833 | 新增: "version": "7.1.1", | |
| 834 | 新增: "resolved": "https://registry.npmjs.org/fill-range/-/fill-range-7.1.1.tgz", | |
| 835 | 新增: "integrity": "sha512-YsGpe3WHLK8ZYi4tWDg2Jy3ebRz2rXowDxnld4bkQB00cc/1Zw9AWnC0i9ztDJitivtQvaI9KaLyKrc+hBW0yg==", | |
| 836 | 新增: "license": "MIT", | |
| 837 | 新增: "dependencies": { | |
| 838 | 新增: "to-regex-range": "^5.0.1" | |
| 839 | 新增: }, | |
| 840 | 新增: "engines": { | |
| 841 | 新增: "node": ">=8" | |
| 842 | 新增: } | |
| 843 | 新增: }, | |
| 844 | 新增: "node_modules/finalhandler": { | |
| 845 | 新增: "version": "1.3.2", | |
| 846 | 新增: "resolved": "https://registry.npmjs.org/finalhandler/-/finalhandler-1.3.2.tgz", | |
| 847 | 新增: "integrity": "sha512-aA4RyPcd3badbdABGDuTXCMTtOneUCAYH/gxoYRTZlIJdF0YPWuGqiAsIrhNnnqdXGswYk6dGujem4w80UJFhg==", | |
| 848 | 新增: "license": "MIT", | |
| 849 | 新增: "dependencies": { | |
| 850 | 新增: "debug": "2.6.9", | |
| 851 | 新增: "encodeurl": "~2.0.0", | |
| 852 | 新增: "escape-html": "~1.0.3", | |
| 853 | 新增: "on-finished": "~2.4.1", | |
| 854 | 新增: "parseurl": "~1.3.3", | |
| 855 | 新增: "statuses": "~2.0.2", | |
| 856 | 新增: "unpipe": "~1.0.0" | |
| 857 | 新增: }, | |
| 858 | 新增: "engines": { | |
| 859 | 新增: "node": ">= 0.8" | |
| 860 | 新增: } | |
| 861 | 新增: }, | |
| 862 | 新增: "node_modules/forwarded": { | |
| 863 | 新增: "version": "0.2.0", | |
| 864 | 新增: "resolved": "https://registry.npmjs.org/forwarded/-/forwarded-0.2.0.tgz", | |
| 865 | 新增: "integrity": "sha512-buRG0fpBtRHSTCOASe6hD258tEubFoRLb4ZNA6NxMVHNw2gOcwHo9wyablzMzOA5z9xA9L1KNjk/Nt6MT9aYow==", | |
| 866 | 新增: "license": "MIT", | |
| 867 | 新增: "engines": { | |
| 868 | 新增: "node": ">= 0.6" | |
| 869 | 新增: } | |
| 870 | 新增: }, | |
| 871 | 新增: "node_modules/fresh": { | |
| 872 | 新增: "version": "0.5.2", | |
| 873 | 新增: "resolved": "https://registry.npmjs.org/fresh/-/fresh-0.5.2.tgz", | |
| 874 | 新增: "integrity": "sha512-zJ2mQYM18rEFOudeV4GShTGIQ7RbzA7ozbU9I/XBpm7kqgMywgmylMwXHxZJmkVoYkna9d2pVXVXPdYTP9ej8Q==", | |
| 875 | 新增: "license": "MIT", | |
| 876 | 新增: "engines": { | |
| 877 | 新增: "node": ">= 0.6" | |
| 878 | 新增: } | |
| 879 | 新增: }, | |
| 880 | 新增: "node_modules/fsevents": { | |
| 881 | 新增: "version": "2.3.3", | |
| 882 | 新增: "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz", | |
| 883 | 新增: "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==", | |
| 884 | 新增: "hasInstallScript": true, | |
| 885 | 新增: "license": "MIT", | |
| 886 | 新增: "optional": true, | |
| 887 | 新增: "os": [ | |
| 888 | 新增: "darwin" | |
| 889 | 新增: ], | |
| 890 | 新增: "engines": { | |
| 891 | 新增: "node": "^8.16.0 || ^10.6.0 || >=11.0.0" | |
| 892 | 新增: } | |
| 893 | 新增: }, | |
| 894 | 新增: "node_modules/function-bind": { | |
| 895 | 新增: "version": "1.1.2", | |
| 896 | 新增: "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz", | |
| 897 | 新增: "integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==", | |
| 898 | 新增: "license": "MIT", | |
| 899 | 新增: "funding": { | |
| 900 | 新增: "url": "https://github.com/sponsors/ljharb" | |
| 901 | 新增: } | |
| 902 | 新增: }, | |
| 903 | 新增: "node_modules/get-intrinsic": { | |
| 904 | 新增: "version": "1.3.0", | |
| 905 | 新增: "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.3.0.tgz", | |
| 906 | 新增: "integrity": "sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ==", | |
| 907 | 新增: "license": "MIT", | |
| 908 | 新增: "dependencies": { | |
| 909 | 新增: "call-bind-apply-helpers": "^1.0.2", | |
| 910 | 新增: "es-define-property": "^1.0.1", | |
| 911 | 新增: "es-errors": "^1.3.0", | |
| 912 | 新增: "es-object-atoms": "^1.1.1", | |
| 913 | 新增: "function-bind": "^1.1.2", | |
| 914 | 新增: "get-proto": "^1.0.1", | |
| 915 | 新增: "gopd": "^1.2.0", | |
| 916 | 新增: "has-symbols": "^1.1.0", | |
| 917 | 新增: "hasown": "^2.0.2", | |
| 918 | 新增: "math-intrinsics": "^1.1.0" | |
| 919 | 新增: }, | |
| 920 | 新增: "engines": { | |
| 921 | 新增: "node": ">= 0.4" | |
| 922 | 新增: }, | |
| 923 | 新增: "funding": { | |
| 924 | 新增: "url": "https://github.com/sponsors/ljharb" | |
| 925 | 新增: } | |
| 926 | 新增: }, | |
| 927 | 新增: "node_modules/get-port": { | |
| 928 | 新增: "version": "5.1.1", | |
| 929 | 新增: "resolved": "https://registry.npmjs.org/get-port/-/get-port-5.1.1.tgz", | |
| 930 | 新增: "integrity": "sha512-g/Q1aTSDOxFpchXC4i8ZWvxA1lnPqx/JHqcpIw0/LX9T8x/GBbi6YnlN5nhaKIFkT8oFsscUKgDJYxfwfS6QsQ==", | |
| 931 | 新增: "license": "MIT", | |
| 932 | 新增: "engines": { | |
| 933 | 新增: "node": ">=8" | |
| 934 | 新增: }, | |
| 935 | 新增: "funding": { | |
| 936 | 新增: "url": "https://github.com/sponsors/sindresorhus" | |
| 937 | 新增: } | |
| 938 | 新增: }, | |
| 939 | 新增: "node_modules/get-proto": { | |
| 940 | 新增: "version": "1.0.1", | |
| 941 | 新增: "resolved": "https://registry.npmjs.org/get-proto/-/get-proto-1.0.1.tgz", | |
| 942 | 新增: "integrity": "sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g==", | |
| 943 | 新增: "license": "MIT", | |
| 944 | 新增: "dependencies": { | |
| 945 | 新增: "dunder-proto": "^1.0.1", | |
| 946 | 新增: "es-object-atoms": "^1.0.0" | |
| 947 | 新增: }, | |
| 948 | 新增: "engines": { | |
| 949 | 新增: "node": ">= 0.4" | |
| 950 | 新增: } | |
| 951 | 新增: }, | |
| 952 | 新增: "node_modules/glob-parent": { | |
| 953 | 新增: "version": "5.1.2", | |
| 954 | 新增: "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-5.1.2.tgz", | |
| 955 | 新增: "integrity": "sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow==", | |
| 956 | 新增: "license": "ISC", | |
| 957 | 新增: "dependencies": { | |
| 958 | 新增: "is-glob": "^4.0.1" | |
| 959 | 新增: }, | |
| 960 | 新增: "engines": { | |
| 961 | 新增: "node": ">= 6" | |
| 962 | 新增: } | |
| 963 | 新增: }, | |
| 964 | 新增: "node_modules/gopd": { | |
| 965 | 新增: "version": "1.2.0", | |
| 966 | 新增: "resolved": "https://registry.npmjs.org/gopd/-/gopd-1.2.0.tgz", | |
| 967 | 新增: "integrity": "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==", | |
| 968 | 新增: "license": "MIT", | |
| 969 | 新增: "engines": { | |
| 970 | 新增: "node": ">= 0.4" | |
| 971 | 新增: }, | |
| 972 | 新增: "funding": { | |
| 973 | 新增: "url": "https://github.com/sponsors/ljharb" | |
| 974 | 新增: } | |
| 975 | 新增: }, | |
| 976 | 新增: "node_modules/graceful-fs": { | |
| 977 | 新增: "version": "4.2.11", | |
| 978 | 新增: "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.11.tgz", | |
| 979 | 新增: "integrity": "sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ==", | |
| 980 | 新增: "license": "ISC" | |
| 981 | 新增: }, | |
| 982 | 新增: "node_modules/gradient-string": { | |
| 983 | 新增: "version": "2.0.2", | |
| 984 | 新增: "resolved": "https://registry.npmjs.org/gradient-string/-/gradient-string-2.0.2.tgz", | |
| 985 | 新增: "integrity": "sha512-rEDCuqUQ4tbD78TpzsMtt5OIf0cBCSDWSJtUDaF6JsAh+k0v9r++NzxNEG87oDZx9ZwGhD8DaezR2L/yrw0Jdw==", | |
| 986 | 新增: "license": "MIT", | |
| 987 | 新增: "dependencies": { | |
| 988 | 新增: "chalk": "^4.1.2", | |
| 989 | 新增: "tinygradient": "^1.1.5" | |
| 990 | 新增: }, | |
| 991 | 新增: "engines": { | |
| 992 | 新增: "node": ">=10" | |
| 993 | 新增: } | |
| 994 | 新增: }, | |
| 995 | 新增: "node_modules/has-flag": { | |
| 996 | 新增: "version": "4.0.0", | |
| 997 | 新增: "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz", | |
| 998 | 新增: "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==", | |
| 999 | 新增: "license": "MIT", | |
| 1000 | 新增: "engines": { | |
| 1001 | 新增: "node": ">=8" | |
| 1002 | 新增: } | |
| 1003 | 新增: }, | |
| 1004 | 新增: "node_modules/has-symbols": { | |
| 1005 | 新增: "version": "1.1.0", | |
| 1006 | 新增: "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.1.0.tgz", | |
| 1007 | 新增: "integrity": "sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==", | |
| 1008 | 新增: "license": "MIT", | |
| 1009 | 新增: "engines": { | |
| 1010 | 新增: "node": ">= 0.4" | |
| 1011 | 新增: }, | |
| 1012 | 新增: "funding": { | |
| 1013 | 新增: "url": "https://github.com/sponsors/ljharb" | |
| 1014 | 新增: } | |
| 1015 | 新增: }, | |
| 1016 | 新增: "node_modules/hasown": { | |
| 1017 | 新增: "version": "2.0.4", | |
| 1018 | 新增: "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.4.tgz", | |
| 1019 | 新增: "integrity": "sha512-T2UbfbBEF32wiepXIsMlTW9+dDYC6wMh/t/vYA4tuOMKqWz/n3vr1NFSxQiyP+zk2mXsoMA/i/7qV6LKut1t1A==", | |
| 1020 | 新增: "license": "MIT", | |
| 1021 | 新增: "dependencies": { | |
| 1022 | 新增: "function-bind": "^1.1.2" | |
| 1023 | 新增: }, | |
| 1024 | 新增: "engines": { | |
| 1025 | 新增: "node": ">= 0.4" | |
| 1026 | 新增: } | |
| 1027 | 新增: }, | |
| 1028 | 新增: "node_modules/http-errors": { | |
| 1029 | 新增: "version": "2.0.1", | |
| 1030 | 新增: "resolved": "https://registry.npmjs.org/http-errors/-/http-errors-2.0.1.tgz", | |
| 1031 | 新增: "integrity": "sha512-4FbRdAX+bSdmo4AUFuS0WNiPz8NgFt+r8ThgNWmlrjQjt1Q7ZR9+zTlce2859x4KSXrwIsaeTqDoKQmtP8pLmQ==", | |
| 1032 | 新增: "license": "MIT", | |
| 1033 | 新增: "dependencies": { | |
| 1034 | 新增: "depd": "~2.0.0", | |
| 1035 | 新增: "inherits": "~2.0.4", | |
| 1036 | 新增: "setprototypeof": "~1.2.0", | |
| 1037 | 新增: "statuses": "~2.0.2", | |
| 1038 | 新增: "toidentifier": "~1.0.1" | |
| 1039 | 新增: }, | |
| 1040 | 新增: "engines": { | |
| 1041 | 新增: "node": ">= 0.8" | |
| 1042 | 新增: }, | |
| 1043 | 新增: "funding": { | |
| 1044 | 新增: "type": "opencollective", | |
| 1045 | 新增: "url": "https://opencollective.com/express" | |
| 1046 | 新增: } | |
| 1047 | 新增: }, | |
| 1048 | 新增: "node_modules/http-proxy-agent": { | |
| 1049 | 新增: "version": "7.0.2", | |
| 1050 | 新增: "resolved": "https://registry.npmjs.org/http-proxy-agent/-/http-proxy-agent-7.0.2.tgz", | |
| 1051 | 新增: "integrity": "sha512-T1gkAiYYDWYx3V5Bmyu7HcfcvL7mUrTWiM6yOfa3PIphViJ/gFPbvidQ+veqSOHci/PxBcDabeUNCzpOODJZig==", | |
| 1052 | 新增: "license": "MIT", | |
| 1053 | 新增: "dependencies": { | |
| 1054 | 新增: "agent-base": "^7.1.0", | |
| 1055 | 新增: "debug": "^4.3.4" | |
| 1056 | 新增: }, | |
| 1057 | 新增: "engines": { | |
| 1058 | 新增: "node": ">= 14" | |
| 1059 | 新增: } | |
| 1060 | 新增: }, | |
| 1061 | 新增: "node_modules/http-proxy-agent/node_modules/debug": { | |
| 1062 | 新增: "version": "4.4.3", | |
| 1063 | 新增: "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", | |
| 1064 | 新增: "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==", | |
| 1065 | 新增: "license": "MIT", | |
| 1066 | 新增: "dependencies": { | |
| 1067 | 新增: "ms": "^2.1.3" | |
| 1068 | 新增: }, | |
| 1069 | 新增: "engines": { | |
| 1070 | 新增: "node": ">=6.0" | |
| 1071 | 新增: }, | |
| 1072 | 新增: "peerDependenciesMeta": { | |
| 1073 | 新增: "supports-color": { | |
| 1074 | 新增: "optional": true | |
| 1075 | 新增: } | |
| 1076 | 新增: } | |
| 1077 | 新增: }, | |
| 1078 | 新增: "node_modules/http-proxy-agent/node_modules/ms": { | |
| 1079 | 新增: "version": "2.1.3", | |
| 1080 | 新增: "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", | |
| 1081 | 新增: "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", | |
| 1082 | 新增: "license": "MIT" | |
| 1083 | 新增: }, | |
| 1084 | 新增: "node_modules/https-proxy-agent": { | |
| 1085 | 新增: "version": "7.0.6", | |
| 1086 | 新增: "resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-7.0.6.tgz", | |
| 1087 | 新增: "integrity": "sha512-vK9P5/iUfdl95AI+JVyUuIcVtd4ofvtrOr3HNtM2yxC9bnMbEdp3x01OhQNnjb8IJYi38VlTE3mBXwcfvywuSw==", | |
| 1088 | 新增: "license": "MIT", | |
| 1089 | 新增: "dependencies": { | |
| 1090 | 新增: "agent-base": "^7.1.2", | |
| 1091 | 新增: "debug": "4" | |
| 1092 | 新增: }, | |
| 1093 | 新增: "engines": { | |
| 1094 | 新增: "node": ">= 14" | |
| 1095 | 新增: } | |
| 1096 | 新增: }, | |
| 1097 | 新增: "node_modules/https-proxy-agent/node_modules/debug": { | |
| 1098 | 新增: "version": "4.4.3", | |
| 1099 | 新增: "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", | |
| 1100 | 新增: "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==", | |
| 1101 | 新增: "license": "MIT", | |
| 1102 | 新增: "dependencies": { | |
| 1103 | 新增: "ms": "^2.1.3" | |
| 1104 | 新增: }, | |
| 1105 | 新增: "engines": { | |
| 1106 | 新增: "node": ">=6.0" | |
| 1107 | 新增: }, | |
| 1108 | 新增: "peerDependenciesMeta": { | |
| 1109 | 新增: "supports-color": { | |
| 1110 | 新增: "optional": true | |
| 1111 | 新增: } | |
| 1112 | 新增: } | |
| 1113 | 新增: }, | |
| 1114 | 新增: "node_modules/https-proxy-agent/node_modules/ms": { | |
| 1115 | 新增: "version": "2.1.3", | |
| 1116 | 新增: "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", | |
| 1117 | 新增: "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", | |
| 1118 | 新增: "license": "MIT" | |
| 1119 | 新增: }, | |
| 1120 | 新增: "node_modules/iconv-lite": { | |
| 1121 | 新增: "version": "0.4.24", | |
| 1122 | 新增: "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.4.24.tgz", | |
| 1123 | 新增: "integrity": "sha512-v3MXnZAcvnywkTUEZomIActle7RXXeedOR31wwl7VlyoXO4Qi9arvSenNQWne1TcRwhCL1HwLI21bEqdpj8/rA==", | |
| 1124 | 新增: "license": "MIT", | |
| 1125 | 新增: "dependencies": { | |
| 1126 | 新增: "safer-buffer": ">= 2.1.2 < 3" | |
| 1127 | 新增: }, | |
| 1128 | 新增: "engines": { | |
| 1129 | 新增: "node": ">=0.10.0" | |
| 1130 | 新增: } | |
| 1131 | 新增: }, | |
| 1132 | 新增: "node_modules/ieee754": { | |
| 1133 | 新增: "version": "1.2.1", | |
| 1134 | 新增: "resolved": "https://registry.npmjs.org/ieee754/-/ieee754-1.2.1.tgz", | |
| 1135 | 新增: "integrity": "sha512-dcyqhDvX1C46lXZcVqCpK+FtMRQVdIMN6/Df5js2zouUsqG7I6sFxitIC+7KYK29KdXOLHdu9zL4sFnoVQnqaA==", | |
| 1136 | 新增: "funding": [ | |
| 1137 | 新增: { | |
| 1138 | 新增: "type": "github", | |
| 1139 | 新增: "url": "https://github.com/sponsors/feross" | |
| 1140 | 新增: }, | |
| 1141 | 新增: { | |
| 1142 | 新增: "type": "patreon", | |
| 1143 | 新增: "url": "https://www.patreon.com/feross" | |
| 1144 | 新增: }, | |
| 1145 | 新增: { | |
| 1146 | 新增: "type": "consulting", | |
| 1147 | 新增: "url": "https://feross.org/support" | |
| 1148 | 新增: } | |
| 1149 | 新增: ], | |
| 1150 | 新增: "license": "BSD-3-Clause" | |
| 1151 | 新增: }, | |
| 1152 | 新增: "node_modules/indent-string": { | |
| 1153 | 新增: "version": "4.0.0", | |
| 1154 | 新增: "resolved": "https://registry.npmjs.org/indent-string/-/indent-string-4.0.0.tgz", | |
| 1155 | 新增: "integrity": "sha512-EdDDZu4A2OyIK7Lr/2zG+w5jmbuk1DVBnEwREQvBzspBJkCEbRa8GxU1lghYcaGJCnRWibjDXlq779X1/y5xwg==", | |
| 1156 | 新增: "license": "MIT", | |
| 1157 | 新增: "engines": { | |
| 1158 | 新增: "node": ">=8" | |
| 1159 | 新增: } | |
| 1160 | 新增: }, | |
| 1161 | 新增: "node_modules/inherits": { | |
| 1162 | 新增: "version": "2.0.4", | |
| 1163 | 新增: "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", | |
| 1164 | 新增: "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==", | |
| 1165 | 新增: "license": "ISC" | |
| 1166 | 新增: }, | |
| 1167 | 新增: "node_modules/ip-address": { | |
| 1168 | 新增: "version": "10.7.6", | |
| 1169 | 新增: "resolved": "https://registry.npmjs.org/ip-address/-/ip-address-10.7.6.tgz", | |
| 1170 | 新增: "integrity": "sha512-00LYkM6byILa9eQIx6qoaXCM40xTLd56AZ4vyaPW3YTyb49VZYPo5xsiAq4tuQ54GH4R7gVdYScJ1B7B77PuTg==", | |
| 1171 | 新增: "license": "MIT", | |
| 1172 | 新增: "engines": { | |
| 1173 | 新增: "node": ">= 12" | |
| 1174 | 新增: } | |
| 1175 | 新增: }, | |
| 1176 | 新增: "node_modules/ipaddr.js": { | |
| 1177 | 新增: "version": "1.9.1", | |
| 1178 | 新增: "resolved": "https://registry.npmjs.org/ipaddr.js/-/ipaddr.js-1.9.1.tgz", | |
| 1179 | 新增: "integrity": "sha512-0KI/607xoxSToH7GjN1FfSbLoU0+btTicjsQSWQlh/hZykN8KpmMf7uYwPW3R+akZ6R/w18ZlXSHBYXiYUPO3g==", | |
| 1180 | 新增: "license": "MIT", | |
| 1181 | 新增: "engines": { | |
| 1182 | 新增: "node": ">= 0.10" | |
| 1183 | 新增: } | |
| 1184 | 新增: }, | |
| 1185 | 新增: "node_modules/is-binary-path": { | |
| 1186 | 新增: "version": "2.1.0", | |
| 1187 | 新增: "resolved": "https://registry.npmjs.org/is-binary-path/-/is-binary-path-2.1.0.tgz", | |
| 1188 | 新增: "integrity": "sha512-ZMERYes6pDydyuGidse7OsHxtbI7WVeUEozgR/g7rd0xUimYNlvZRE/K2MgZTjWy725IfelLeVcEM97mmtRGXw==", | |
| 1189 | 新增: "license": "MIT", | |
| 1190 | 新增: "dependencies": { | |
| 1191 | 新增: "binary-extensions": "^2.0.0" | |
| 1192 | 新增: }, | |
| 1193 | 新增: "engines": { | |
| 1194 | 新增: "node": ">=8" | |
| 1195 | 新增: } | |
| 1196 | 新增: }, | |
| 1197 | 新增: "node_modules/is-docker": { | |
| 1198 | 新增: "version": "2.2.1", | |
| 1199 | 新增: "resolved": "https://registry.npmjs.org/is-docker/-/is-docker-2.2.1.tgz", | |
| 1200 | 新增: "integrity": "sha512-F+i2BKsFrH66iaUFc0woD8sLy8getkwTwtOBjvs56Cx4CgJDeKQeqfz8wAYiSb8JOprWhHH5p77PbmYCvvUuXQ==", | |
| 1201 | 新增: "license": "MIT", | |
| 1202 | 新增: "bin": { | |
| 1203 | 新增: "is-docker": "cli.js" | |
| 1204 | 新增: }, | |
| 1205 | 新增: "engines": { | |
| 1206 | 新增: "node": ">=8" | |
| 1207 | 新增: }, | |
| 1208 | 新增: "funding": { | |
| 1209 | 新增: "url": "https://github.com/sponsors/sindresorhus" | |
| 1210 | 新增: } | |
| 1211 | 新增: }, | |
| 1212 | 新增: "node_modules/is-extglob": { | |
| 1213 | 新增: "version": "2.1.1", | |
| 1214 | 新增: "resolved": "https://registry.npmjs.org/is-extglob/-/is-extglob-2.1.1.tgz", | |
| 1215 | 新增: "integrity": "sha512-SbKbANkN603Vi4jEZv49LeVJMn4yGwsbzZworEoyEiutsN3nJYdbO36zfhGJ6QEDpOZIFkDtnq5JRxmvl3jsoQ==", | |
| 1216 | 新增: "license": "MIT", | |
| 1217 | 新增: "engines": { | |
| 1218 | 新增: "node": ">=0.10.0" | |
| 1219 | 新增: } | |
| 1220 | 新增: }, | |
| 1221 | 新增: "node_modules/is-fullwidth-code-point": { | |
| 1222 | 新增: "version": "3.0.0", | |
| 1223 | 新增: "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz", | |
| 1224 | 新增: "integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==", | |
| 1225 | 新增: "license": "MIT", | |
| 1226 | 新增: "engines": { | |
| 1227 | 新增: "node": ">=8" | |
| 1228 | 新增: } | |
| 1229 | 新增: }, | |
| 1230 | 新增: "node_modules/is-glob": { | |
| 1231 | 新增: "version": "4.0.3", | |
| 1232 | 新增: "resolved": "https://registry.npmjs.org/is-glob/-/is-glob-4.0.3.tgz", | |
| 1233 | 新增: "integrity": "sha512-xelSayHH36ZgE7ZWhli7pW34hNbNl8Ojv5KVmkJD4hBdD3th8Tfk9vYasLM+mXWOZhFkgZfxhLSnrwRr4elSSg==", | |
| 1234 | 新增: "license": "MIT", | |
| 1235 | 新增: "dependencies": { | |
| 1236 | 新增: "is-extglob": "^2.1.1" | |
| 1237 | 新增: }, | |
| 1238 | 新增: "engines": { | |
| 1239 | 新增: "node": ">=0.10.0" | |
| 1240 | 新增: } | |
| 1241 | 新增: }, | |
| 1242 | 新增: "node_modules/is-interactive": { | |
| 1243 | 新增: "version": "1.0.0", | |
| 1244 | 新增: "resolved": "https://registry.npmjs.org/is-interactive/-/is-interactive-1.0.0.tgz", | |
| 1245 | 新增: "integrity": "sha512-2HvIEKRoqS62guEC+qBjpvRubdX910WCMuJTZ+I9yvqKU2/12eSL549HMwtabb4oupdj2sMP50k+XJfB/8JE6w==", | |
| 1246 | 新增: "license": "MIT", | |
| 1247 | 新增: "engines": { | |
| 1248 | 新增: "node": ">=8" | |
| 1249 | 新增: } | |
| 1250 | 新增: }, | |
| 1251 | 新增: "node_modules/is-number": { | |
| 1252 | 新增: "version": "7.0.0", | |
| 1253 | 新增: "resolved": "https://registry.npmjs.org/is-number/-/is-number-7.0.0.tgz", | |
| 1254 | 新增: "integrity": "sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng==", | |
| 1255 | 新增: "license": "MIT", | |
| 1256 | 新增: "engines": { | |
| 1257 | 新增: "node": ">=0.12.0" | |
| 1258 | 新增: } | |
| 1259 | 新增: }, | |
| 1260 | 新增: "node_modules/is-unicode-supported": { | |
| 1261 | 新增: "version": "0.1.0", | |
| 1262 | 新增: "resolved": "https://registry.npmjs.org/is-unicode-supported/-/is-unicode-supported-0.1.0.tgz", | |
| 1263 | 新增: "integrity": "sha512-knxG2q4UC3u8stRGyAVJCOdxFmv5DZiRcdlIaAQXAbSfJya+OhopNotLQrstBhququ4ZpuKbDc/8S6mgXgPFPw==", | |
| 1264 | 新增: "license": "MIT", | |
| 1265 | 新增: "engines": { | |
| 1266 | 新增: "node": ">=10" | |
| 1267 | 新增: }, | |
| 1268 | 新增: "funding": { | |
| 1269 | 新增: "url": "https://github.com/sponsors/sindresorhus" | |
| 1270 | 新增: } | |
| 1271 | 新增: }, | |
| 1272 | 新增: "node_modules/is-wsl": { | |
| 1273 | 新增: "version": "2.2.0", | |
| 1274 | 新增: "resolved": "https://registry.npmjs.org/is-wsl/-/is-wsl-2.2.0.tgz", | |
| 1275 | 新增: "integrity": "sha512-fKzAra0rGJUUBwGBgNkHZuToZcn+TtXHpeCgmkMJMMYx1sQDYaCSyjJBSCa2nH1DGm7s3n1oBnohoVTBaN7Lww==", | |
| 1276 | 新增: "license": "MIT", | |
| 1277 | 新增: "dependencies": { | |
| 1278 | 新增: "is-docker": "^2.0.0" | |
| 1279 | 新增: }, | |
| 1280 | 新增: "engines": { | |
| 1281 | 新增: "node": ">=8" | |
| 1282 | 新增: } | |
| 1283 | 新增: }, | |
| 1284 | 新增: "node_modules/js-yaml": { | |
| 1285 | 新增: "version": "4.3.2", | |
| 1286 | 新增: "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.3.2.tgz", | |
| 1287 | 新增: "integrity": "sha512-SFNOvSJ+Dgf/9An904Yx+CgSlIPCkIpao4qo51lpee25TIRejdH3rhR4EZMGoNx3/TP3O+wzWuiTFl4sqbltzA==", | |
| 1288 | 新增: "funding": [ | |
| 1289 | 新增: { | |
| 1290 | 新增: "type": "github", | |
| 1291 | 新增: "url": "https://github.com/sponsors/puzrin" | |
| 1292 | 新增: }, | |
| 1293 | 新增: { | |
| 1294 | 新增: "type": "github", | |
| 1295 | 新增: "url": "https://github.com/sponsors/nodeca" | |
| 1296 | 新增: } | |
| 1297 | 新增: ], | |
| 1298 | 新增: "license": "MIT", | |
| 1299 | 新增: "dependencies": { | |
| 1300 | 新增: "argparse": "^2.0.1" | |
| 1301 | 新增: }, | |
| 1302 | 新增: "bin": { | |
| 1303 | 新增: "js-yaml": "bin/js-yaml.js" | |
| 1304 | 新增: } | |
| 1305 | 新增: }, | |
| 1306 | 新增: "node_modules/listr2": { | |
| 1307 | 新增: "version": "3.14.0", | |
| 1308 | 新增: "resolved": "https://registry.npmjs.org/listr2/-/listr2-3.14.0.tgz", | |
| 1309 | 新增: "integrity": "sha512-TyWI8G99GX9GjE54cJ+RrNMcIFBfwMPxc3XTFiAYGN4s10hWROGtOg7+O6u6LE3mNkyld7RSLE6nrKBvTfcs3g==", | |
| 1310 | 新增: "license": "MIT", | |
| 1311 | 新增: "dependencies": { | |
| 1312 | 新增: "cli-truncate": "^2.1.0", | |
| 1313 | 新增: "colorette": "^2.0.16", | |
| 1314 | 新增: "log-update": "^4.0.0", | |
| 1315 | 新增: "p-map": "^4.0.0", | |
| 1316 | 新增: "rfdc": "^1.3.0", | |
| 1317 | 新增: "rxjs": "^7.5.1", | |
| 1318 | 新增: "through": "^2.3.8", | |
| 1319 | 新增: "wrap-ansi": "^7.0.0" | |
| 1320 | 新增: }, | |
| 1321 | 新增: "engines": { | |
| 1322 | 新增: "node": ">=10.0.0" | |
| 1323 | 新增: }, | |
| 1324 | 新增: "peerDependencies": { | |
| 1325 | 新增: "enquirer": ">= 2.3.0 < 3" | |
| 1326 | 新增: }, | |
| 1327 | 新增: "peerDependenciesMeta": { | |
| 1328 | 新增: "enquirer": { | |
| 1329 | 新增: "optional": true | |
| 1330 | 新增: } | |
| 1331 | 新增: } | |
| 1332 | 新增: }, | |
| 1333 | 新增: "node_modules/log-symbols": { | |
| 1334 | 新增: "version": "4.1.0", | |
| 1335 | 新增: "resolved": "https://registry.npmjs.org/log-symbols/-/log-symbols-4.1.0.tgz", | |
| 1336 | 新增: "integrity": "sha512-8XPvpAA8uyhfteu8pIvQxpJZ7SYYdpUivZpGy6sFsBuKRY/7rQGavedeB8aK+Zkyq6upMFVL/9AW6vOYzfRyLg==", | |
| 1337 | 新增: "license": "MIT", | |
| 1338 | 新增: "dependencies": { | |
| 1339 | 新增: "chalk": "^4.1.0", | |
| 1340 | 新增: "is-unicode-supported": "^0.1.0" | |
| 1341 | 新增: }, | |
| 1342 | 新增: "engines": { | |
| 1343 | 新增: "node": ">=10" | |
| 1344 | 新增: }, | |
| 1345 | 新增: "funding": { | |
| 1346 | 新增: "url": "https://github.com/sponsors/sindresorhus" | |
| 1347 | 新增: } | |
| 1348 | 新增: }, | |
| 1349 | 新增: "node_modules/log-update": { | |
| 1350 | 新增: "version": "4.0.0", | |
| 1351 | 新增: "resolved": "https://registry.npmjs.org/log-update/-/log-update-4.0.0.tgz", | |
| 1352 | 新增: "integrity": "sha512-9fkkDevMefjg0mmzWFBW8YkFP91OrizzkW3diF7CpG+S2EYdy4+TVfGwz1zeF8x7hCx1ovSPTOE9Ngib74qqUg==", | |
| 1353 | 新增: "license": "MIT", | |
| 1354 | 新增: "dependencies": { | |
| 1355 | 新增: "ansi-escapes": "^4.3.0", | |
| 1356 | 新增: "cli-cursor": "^3.1.0", | |
| 1357 | 新增: "slice-ansi": "^4.0.0", | |
| 1358 | 新增: "wrap-ansi": "^6.2.0" | |
| 1359 | 新增: }, | |
| 1360 | 新增: "engines": { | |
| 1361 | 新增: "node": ">=10" | |
| 1362 | 新增: }, | |
| 1363 | 新增: "funding": { | |
| 1364 | 新增: "url": "https://github.com/sponsors/sindresorhus" | |
| 1365 | 新增: } | |
| 1366 | 新增: }, | |
| 1367 | 新增: "node_modules/log-update/node_modules/slice-ansi": { | |
| 1368 | 新增: "version": "4.0.0", | |
| 1369 | 新增: "resolved": "https://registry.npmjs.org/slice-ansi/-/slice-ansi-4.0.0.tgz", | |
| 1370 | 新增: "integrity": "sha512-qMCMfhY040cVHT43K9BFygqYbUPFZKHOg7K73mtTWJRb8pyP3fzf4Ixd5SzdEJQ6MRUg/WBnOLxghZtKKurENQ==", | |
| 1371 | 新增: "license": "MIT", | |
| 1372 | 新增: "dependencies": { | |
| 1373 | 新增: "ansi-styles": "^4.0.0", | |
| 1374 | 新增: "astral-regex": "^2.0.0", | |
| 1375 | 新增: "is-fullwidth-code-point": "^3.0.0" | |
| 1376 | 新增: }, | |
| 1377 | 新增: "engines": { | |
| 1378 | 新增: "node": ">=10" | |
| 1379 | 新增: }, | |
| 1380 | 新增: "funding": { | |
| 1381 | 新增: "url": "https://github.com/chalk/slice-ansi?sponsor=1" | |
| 1382 | 新增: } | |
| 1383 | 新增: }, | |
| 1384 | 新增: "node_modules/log-update/node_modules/wrap-ansi": { | |
| 1385 | 新增: "version": "6.2.0", | |
| 1386 | 新增: "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-6.2.0.tgz", | |
| 1387 | 新增: "integrity": "sha512-r6lPcBGxZXlIcymEu7InxDMhdW0KDxpLgoFLcguasxCaJ/SOIZwINatK9KY/tf+ZrlywOKU0UDj3ATXUBfxJXA==", | |
| 1388 | 新增: "license": "MIT", | |
| 1389 | 新增: "dependencies": { | |
| 1390 | 新增: "ansi-styles": "^4.0.0", | |
| 1391 | 新增: "string-width": "^4.1.0", | |
| 1392 | 新增: "strip-ansi": "^6.0.0" | |
| 1393 | 新增: }, | |
| 1394 | 新增: "engines": { | |
| 1395 | 新增: "node": ">=8" | |
| 1396 | 新增: } | |
| 1397 | 新增: }, | |
| 1398 | 新增: "node_modules/math-intrinsics": { | |
| 1399 | 新增: "version": "1.1.0", | |
| 1400 | 新增: "resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz", | |
| 1401 | 新增: "integrity": "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==", | |
| 1402 | 新增: "license": "MIT", | |
| 1403 | 新增: "engines": { | |
| 1404 | 新增: "node": ">= 0.4" | |
| 1405 | 新增: } | |
| 1406 | 新增: }, | |
| 1407 | 新增: "node_modules/media-typer": { | |
| 1408 | 新增: "version": "0.3.0", | |
| 1409 | 新增: "resolved": "https://registry.npmjs.org/media-typer/-/media-typer-0.3.0.tgz", | |
| 1410 | 新增: "integrity": "sha512-dq+qelQ9akHpcOl/gUVRTxVIOkAJ1wR3QAvb4RsVjS8oVoFjDGTc679wJYmUmknUF5HwMLOgb5O+a3KxfWapPQ==", | |
| 1411 | 新增: "license": "MIT", | |
| 1412 | 新增: "engines": { | |
| 1413 | 新增: "node": ">= 0.6" | |
| 1414 | 新增: } | |
| 1415 | 新增: }, | |
| 1416 | 新增: "node_modules/merge-descriptors": { | |
| 1417 | 新增: "version": "1.0.3", | |
| 1418 | 新增: "resolved": "https://registry.npmjs.org/merge-descriptors/-/merge-descriptors-1.0.3.tgz", | |
| 1419 | 新增: "integrity": "sha512-gaNvAS7TZ897/rVaZ0nMtAyxNyi/pdbjbAwUpFQpN70GqnVfOiXpeUUMKRBmzXaSQ8DdTX4/0ms62r2K+hE6mQ==", | |
| 1420 | 新增: "license": "MIT", | |
| 1421 | 新增: "funding": { | |
| 1422 | 新增: "url": "https://github.com/sponsors/sindresorhus" | |
| 1423 | 新增: } | |
| 1424 | 新增: }, | |
| 1425 | 新增: "node_modules/methods": { | |
| 1426 | 新增: "version": "1.1.2", | |
| 1427 | 新增: "resolved": "https://registry.npmjs.org/methods/-/methods-1.1.2.tgz", | |
| 1428 | 新增: "integrity": "sha512-iclAHeNqNm68zFtnZ0e+1L2yUIdvzNoauKU4WBA3VvH/vPFieF7qfRlwUZU+DA9P9bPXIS90ulxoUoCH23sV2w==", | |
| 1429 | 新增: "license": "MIT", | |
| 1430 | 新增: "engines": { | |
| 1431 | 新增: "node": ">= 0.6" | |
| 1432 | 新增: } | |
| 1433 | 新增: }, | |
| 1434 | 新增: "node_modules/mime": { | |
| 1435 | 新增: "version": "1.6.0", | |
| 1436 | 新增: "resolved": "https://registry.npmjs.org/mime/-/mime-1.6.0.tgz", | |
| 1437 | 新增: "integrity": "sha512-x0Vn8spI+wuJ1O6S7gnbaQg8Pxh4NNHb7KSINmEWKiPE4RKOplvijn+NkmYmmRgP68mc70j2EbeTFRsrswaQeg==", | |
| 1438 | 新增: "license": "MIT", | |
| 1439 | 新增: "bin": { | |
| 1440 | 新增: "mime": "cli.js" | |
| 1441 | 新增: }, | |
| 1442 | 新增: "engines": { | |
| 1443 | 新增: "node": ">=4" | |
| 1444 | 新增: } | |
| 1445 | 新增: }, | |
| 1446 | 新增: "node_modules/mime-db": { | |
| 1447 | 新增: "version": "1.52.0", | |
| 1448 | 新增: "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.52.0.tgz", | |
| 1449 | 新增: "integrity": "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==", | |
| 1450 | 新增: "license": "MIT", | |
| 1451 | 新增: "engines": { | |
| 1452 | 新增: "node": ">= 0.6" | |
| 1453 | 新增: } | |
| 1454 | 新增: }, | |
| 1455 | 新增: "node_modules/mime-types": { | |
| 1456 | 新增: "version": "2.1.35", | |
| 1457 | 新增: "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.35.tgz", | |
| 1458 | 新增: "integrity": "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==", | |
| 1459 | 新增: "license": "MIT", | |
| 1460 | 新增: "dependencies": { | |
| 1461 | 新增: "mime-db": "1.52.0" | |
| 1462 | 新增: }, | |
| 1463 | 新增: "engines": { | |
| 1464 | 新增: "node": ">= 0.6" | |
| 1465 | 新增: } | |
| 1466 | 新增: }, | |
| 1467 | 新增: "node_modules/mimic-fn": { | |
| 1468 | 新增: "version": "2.1.0", | |
| 1469 | 新增: "resolved": "https://registry.npmjs.org/mimic-fn/-/mimic-fn-2.1.0.tgz", | |
| 1470 | 新增: "integrity": "sha512-OqbOk5oEQeAZ8WXWydlu9HJjz9WVdEIvamMCcXmuqUYjTknH/sqsWvhQ3vgwKFRR1HpjvNBKQ37nbJgYzGqGcg==", | |
| 1471 | 新增: "license": "MIT", | |
| 1472 | 新增: "engines": { | |
| 1473 | 新增: "node": ">=6" | |
| 1474 | 新增: } | |
| 1475 | 新增: }, | |
| 1476 | 新增: "node_modules/ms": { | |
| 1477 | 新增: "version": "2.0.0", | |
| 1478 | 新增: "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", | |
| 1479 | 新增: "integrity": "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A==", | |
| 1480 | 新增: "license": "MIT" | |
| 1481 | 新增: }, | |
| 1482 | 新增: "node_modules/negotiator": { | |
| 1483 | 新增: "version": "0.6.3", | |
| 1484 | 新增: "resolved": "https://registry.npmjs.org/negotiator/-/negotiator-0.6.3.tgz", | |
| 1485 | 新增: "integrity": "sha512-+EUsqGPLsM+j/zdChZjsnX51g4XrHFOIXwfnCVPGlQk/k5giakcKsuxCObBRu6DSm9opw/O6slWbJdghQM4bBg==", | |
| 1486 | 新增: "license": "MIT", | |
| 1487 | 新增: "engines": { | |
| 1488 | 新增: "node": ">= 0.6" | |
| 1489 | 新增: } | |
| 1490 | 新增: }, | |
| 1491 | 新增: "node_modules/node-addon-api": { | |
| 1492 | 新增: "version": "8.9.2", | |
| 1493 | 新增: "resolved": "https://registry.npmjs.org/node-addon-api/-/node-addon-api-8.9.2.tgz", | |
| 1494 | 新增: "integrity": "sha512-VijLXbi3UACN69I0JVXJsX4tjACjNoQDgv2gTF6sx2wWEi8tkSg2eX8p5gSIFi8z2+DL3oHmY6OyKce38SDolg==", | |
| 1495 | 新增: "license": "MIT", | |
| 1496 | 新增: "engines": { | |
| 1497 | 新增: "node": "^18 || ^20 || >= 21" | |
| 1498 | 新增: } | |
| 1499 | 新增: }, | |
| 1500 | 新增: "node_modules/node-gyp-build": { | |
| 1501 | 新增: "version": "4.8.4", | |
| 1502 | 新增: "resolved": "https://registry.npmjs.org/node-gyp-build/-/node-gyp-build-4.8.4.tgz", | |
| 1503 | 新增: "integrity": "sha512-LA4ZjwlnUblHVgq0oBF3Jl/6h/Nvs5fzBLwdEF4nuxnFdsfajde4WfxtJr3CaiH+F6ewcIB/q4jQ4UzPyid+CQ==", | |
| 1504 | 新增: "license": "MIT", | |
| 1505 | 新增: "bin": { | |
| 1506 | 新增: "node-gyp-build": "bin.js", | |
| 1507 | 新增: "node-gyp-build-optional": "optional.js", | |
| 1508 | 新增: "node-gyp-build-test": "build-test.js" | |
| 1509 | 新增: } | |
| 1510 | 新增: }, | |
| 1511 | 新增: "node_modules/normalize-path": { | |
| 1512 | 新增: "version": "3.0.0", | |
| 1513 | 新增: "resolved": "https://registry.npmjs.org/normalize-path/-/normalize-path-3.0.0.tgz", | |
| 1514 | 新增: "integrity": "sha512-6eZs5Ls3WtCisHWp9S2GUy8dqkpGi4BVSz3GaqiE6ezub0512ESztXUwUB6C6IKbQkY2Pnb/mD4WYojCRwcwLA==", | |
| 1515 | 新增: "license": "MIT", | |
| 1516 | 新增: "engines": { | |
| 1517 | 新增: "node": ">=0.10.0" | |
| 1518 | 新增: } | |
| 1519 | 新增: }, | |
| 1520 | 新增: "node_modules/object-inspect": { | |
| 1521 | 新增: "version": "1.13.4", | |
| 1522 | 新增: "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.13.4.tgz", | |
| 1523 | 新增: "integrity": "sha512-W67iLl4J2EXEGTbfeHCffrjDfitvLANg0UlX3wFUUSTx92KXRFegMHUVgSqE+wvhAbi4WqjGg9czysTV2Epbew==", | |
| 1524 | 新增: "license": "MIT", | |
| 1525 | 新增: "engines": { | |
| 1526 | 新增: "node": ">= 0.4" | |
| 1527 | 新增: }, | |
| 1528 | 新增: "funding": { | |
| 1529 | 新增: "url": "https://github.com/sponsors/ljharb" | |
| 1530 | 新增: } | |
| 1531 | 新增: }, | |
| 1532 | 新增: "node_modules/on-finished": { | |
| 1533 | 新增: "version": "2.4.2", | |
| 1534 | 新增: "resolved": "https://registry.npmjs.org/on-finished/-/on-finished-2.4.2.tgz", | |
| 1535 | 新增: "integrity": "sha512-ATWUv387i+nLD49EiDoOft5scf32Vsdz3ktrQJG9bi7jRFmaXTssvyvj1EmeKVVgvesbqUtvQQvaS2TpTukAZQ==", | |
| 1536 | 新增: "license": "MIT", | |
| 1537 | 新增: "dependencies": { | |
| 1538 | 新增: "ee-first": "1.1.1" | |
| 1539 | 新增: }, | |
| 1540 | 新增: "engines": { | |
| 1541 | 新增: "node": ">= 0.8" | |
| 1542 | 新增: }, | |
| 1543 | 新增: "funding": { | |
| 1544 | 新增: "type": "opencollective", | |
| 1545 | 新增: "url": "https://opencollective.com/express" | |
| 1546 | 新增: } | |
| 1547 | 新增: }, | |
| 1548 | 新增: "node_modules/on-headers": { | |
| 1549 | 新增: "version": "1.1.0", | |
| 1550 | 新增: "resolved": "https://registry.npmjs.org/on-headers/-/on-headers-1.1.0.tgz", | |
| 1551 | 新增: "integrity": "sha512-737ZY3yNnXy37FHkQxPzt4UZ2UWPWiCZWLvFZ4fu5cueciegX0zGPnrlY6bwRg4FdQOe9YU8MkmJwGhoMybl8A==", | |
| 1552 | 新增: "license": "MIT", | |
| 1553 | 新增: "engines": { | |
| 1554 | 新增: "node": ">= 0.8" | |
| 1555 | 新增: } | |
| 1556 | 新增: }, | |
| 1557 | 新增: "node_modules/onetime": { | |
| 1558 | 新增: "version": "5.1.2", | |
| 1559 | 新增: "resolved": "https://registry.npmjs.org/onetime/-/onetime-5.1.2.tgz", | |
| 1560 | 新增: "integrity": "sha512-kbpaSSGJTWdAY5KPVeMOKXSrPtr8C8C7wodJbcsd51jRnmD+GZu8Y0VoU6Dm5Z4vWr0Ig/1NKuWRKf7j5aaYSg==", | |
| 1561 | 新增: "license": "MIT", | |
| 1562 | 新增: "dependencies": { | |
| 1563 | 新增: "mimic-fn": "^2.1.0" | |
| 1564 | 新增: }, | |
| 1565 | 新增: "engines": { | |
| 1566 | 新增: "node": ">=6" | |
| 1567 | 新增: }, | |
| 1568 | 新增: "funding": { | |
| 1569 | 新增: "url": "https://github.com/sponsors/sindresorhus" | |
| 1570 | 新增: } | |
| 1571 | 新增: }, | |
| 1572 | 新增: "node_modules/open": { | |
| 1573 | 新增: "version": "8.4.2", | |
| 1574 | 新增: "resolved": "https://registry.npmjs.org/open/-/open-8.4.2.tgz", | |
| 1575 | 新增: "integrity": "sha512-7x81NCL719oNbsq/3mh+hVrAWmFuEYUqrq/Iw3kUzH8ReypT9QQ0BLoJS7/G9k6N81XjW4qHWtjWwe/9eLy1EQ==", | |
| 1576 | 新增: "license": "MIT", | |
| 1577 | 新增: "dependencies": { | |
| 1578 | 新增: "define-lazy-prop": "^2.0.0", | |
| 1579 | 新增: "is-docker": "^2.1.1", | |
| 1580 | 新增: "is-wsl": "^2.2.0" | |
| 1581 | 新增: }, | |
| 1582 | 新增: "engines": { | |
| 1583 | 新增: "node": ">=12" | |
| 1584 | 新增: }, | |
| 1585 | 新增: "funding": { | |
| 1586 | 新增: "url": "https://github.com/sponsors/sindresorhus" | |
| 1587 | 新增: } | |
| 1588 | 新增: }, | |
| 1589 | 新增: "node_modules/ora": { | |
| 1590 | 新增: "version": "5.4.1", | |
| 1591 | 新增: "resolved": "https://registry.npmjs.org/ora/-/ora-5.4.1.tgz", | |
| 1592 | 新增: "integrity": "sha512-5b6Y85tPxZZ7QytO+BQzysW31HJku27cRIlkbAXaNx+BdcVi+LlRFmVXzeF6a7JCwJpyw5c4b+YSVImQIrBpuQ==", | |
| 1593 | 新增: "license": "MIT", | |
| 1594 | 新增: "dependencies": { | |
| 1595 | 新增: "bl": "^4.1.0", | |
| 1596 | 新增: "chalk": "^4.1.0", | |
| 1597 | 新增: "cli-cursor": "^3.1.0", | |
| 1598 | 新增: "cli-spinners": "^2.5.0", | |
| 1599 | 新增: "is-interactive": "^1.0.0", | |
| 1600 | 新增: "is-unicode-supported": "^0.1.0", | |
| 1601 | 新增: "log-symbols": "^4.1.0", | |
| 1602 | 新增: "strip-ansi": "^6.0.0", | |
| 1603 | 新增: "wcwidth": "^1.0.1" | |
| 1604 | 新增: }, | |
| 1605 | 新增: "engines": { | |
| 1606 | 新增: "node": ">=10" | |
| 1607 | 新增: }, | |
| 1608 | 新增: "funding": { | |
| 1609 | 新增: "url": "https://github.com/sponsors/sindresorhus" | |
| 1610 | 新增: } | |
| 1611 | 新增: }, | |
| 1612 | 新增: "node_modules/p-map": { | |
| 1613 | 新增: "version": "4.0.0", | |
| 1614 | 新增: "resolved": "https://registry.npmjs.org/p-map/-/p-map-4.0.0.tgz", | |
| 1615 | 新增: "integrity": "sha512-/bjOqmgETBYB5BoEeGVea8dmvHb2m9GLy1E9W43yeyfP6QQCZGFNa+XRceJEuDB6zqr+gKpIAmlLebMpykw/MQ==", | |
| 1616 | 新增: "license": "MIT", | |
| 1617 | 新增: "dependencies": { | |
| 1618 | 新增: "aggregate-error": "^3.0.0" | |
| 1619 | 新增: }, | |
| 1620 | 新增: "engines": { | |
| 1621 | 新增: "node": ">=10" | |
| 1622 | 新增: }, | |
| 1623 | 新增: "funding": { | |
| 1624 | 新增: "url": "https://github.com/sponsors/sindresorhus" | |
| 1625 | 新增: } | |
| 1626 | 新增: }, | |
| 1627 | 新增: "node_modules/parseurl": { | |
| 1628 | 新增: "version": "1.3.3", | |
| 1629 | 新增: "resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.3.3.tgz", | |
| 1630 | 新增: "integrity": "sha512-CiyeOxFT/JZyN5m0z9PfXw4SCBJ6Sygz1Dpl0wqjlhDEGGBP1GnsUVEL0p63hoG1fcj3fHynXi9NYO4nWOL+qQ==", | |
| 1631 | 新增: "license": "MIT", | |
| 1632 | 新增: "engines": { | |
| 1633 | 新增: "node": ">= 0.8" | |
| 1634 | 新增: } | |
| 1635 | 新增: }, | |
| 1636 | 新增: "node_modules/path-to-regexp": { | |
| 1637 | 新增: "version": "0.1.13", | |
| 1638 | 新增: "resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-0.1.13.tgz", | |
| 1639 | 新增: "integrity": "sha512-A/AGNMFN3c8bOlvV9RreMdrv7jsmF9XIfDeCd87+I8RNg6s78BhJxMu69NEMHBSJFxKidViTEdruRwEk/WIKqA==", | |
| 1640 | 新增: "license": "MIT" | |
| 1641 | 新增: }, | |
| 1642 | 新增: "node_modules/picomatch": { | |
| 1643 | 新增: "version": "2.3.2", | |
| 1644 | 新增: "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.3.2.tgz", | |
| 1645 | 新增: "integrity": "sha512-V7+vQEJ06Z+c5tSye8S+nHUfI51xoXIXjHQ99cQtKUkQqqO1kO/KCJUfZXuB47h/YBlDhah2H3hdUGXn8ie0oA==", | |
| 1646 | 新增: "license": "MIT", | |
| 1647 | 新增: "engines": { | |
| 1648 | 新增: "node": ">=8.6" | |
| 1649 | 新增: }, | |
| 1650 | 新增: "funding": { | |
| 1651 | 新增: "url": "https://github.com/sponsors/jonschlinkert" | |
| 1652 | 新增: } | |
| 1653 | 新增: }, | |
| 1654 | 新增: "node_modules/proper-lockfile": { | |
| 1655 | 新增: "version": "4.1.2", | |
| 1656 | 新增: "resolved": "https://registry.npmjs.org/proper-lockfile/-/proper-lockfile-4.1.2.tgz", | |
| 1657 | 新增: "integrity": "sha512-TjNPblN4BwAWMXU8s9AEz4JmQxnD1NNL7bNOY/AKUzyamc379FWASUhc/K1pL2noVb+XmZKLL68cjzLsiOAMaA==", | |
| 1658 | 新增: "license": "MIT", | |
| 1659 | 新增: "dependencies": { | |
| 1660 | 新增: "graceful-fs": "^4.2.4", | |
| 1661 | 新增: "retry": "^0.12.0", | |
| 1662 | 新增: "signal-exit": "^3.0.2" | |
| 1663 | 新增: } | |
| 1664 | 新增: }, | |
| 1665 | 新增: "node_modules/proxy-addr": { | |
| 1666 | 新增: "version": "2.0.8", | |
| 1667 | 新增: "resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-2.0.8.tgz", | |
| 1668 | 新增: "integrity": "sha512-5nnx0yGyVUcY6t9RnWcARWtwT9F1D8O9rt08htPvnd49W1IgZtmLkhu9WfMzQj1cFxjHIO6connUNVW5k7AVyQ==", | |
| 1669 | 新增: "license": "MIT", | |
| 1670 | 新增: "dependencies": { | |
| 1671 | 新增: "forwarded": "0.2.0", | |
| 1672 | 新增: "ipaddr.js": "1.9.1" | |
| 1673 | 新增: }, | |
| 1674 | 新增: "engines": { | |
| 1675 | 新增: "node": ">= 0.10" | |
| 1676 | 新增: }, | |
| 1677 | 新增: "funding": { | |
| 1678 | 新增: "type": "opencollective", | |
| 1679 | 新增: "url": "https://opencollective.com/express" | |
| 1680 | 新增: } | |
| 1681 | 新增: }, | |
| 1682 | 新增: "node_modules/qs": { | |
| 1683 | 新增: "version": "6.16.2", | |
| 1684 | 新增: "resolved": "https://registry.npmjs.org/qs/-/qs-6.16.2.tgz", | |
| 1685 | 新增: "integrity": "sha512-VYdnB5S7/0IeXzBacUtwNAaM6d7Y/PgYnNC7bJCI6meqA/OgnsQbZMtVW8Dt2D1PHgbHGtYmhSoEIgvt7xZ2ZA==", | |
| 1686 | 新增: "license": "BSD-3-Clause", | |
| 1687 | 新增: "dependencies": { | |
| 1688 | 新增: "es-define-property": "^1.0.1", | |
| 1689 | 新增: "side-channel": "^1.1.1" | |
| 1690 | 新增: }, | |
| 1691 | 新增: "engines": { | |
| 1692 | 新增: "node": ">=0.6" | |
| 1693 | 新增: }, | |
| 1694 | 新增: "funding": { | |
| 1695 | 新增: "url": "https://github.com/sponsors/ljharb" | |
| 1696 | 新增: } | |
| 1697 | 新增: }, | |
| 1698 | 新增: "node_modules/random-bytes": { | |
| 1699 | 新增: "version": "1.0.0", | |
| 1700 | 新增: "resolved": "https://registry.npmjs.org/random-bytes/-/random-bytes-1.0.0.tgz", | |
| 1701 | 新增: "integrity": "sha512-iv7LhNVO047HzYR3InF6pUcUsPQiHTM1Qal51DcGSuZFBil1aBBWG5eHPNek7bvILMaYJ/8RU1e8w1AMdHmLQQ==", | |
| 1702 | 新增: "license": "MIT", | |
| 1703 | 新增: "engines": { | |
| 1704 | 新增: "node": ">= 0.8" | |
| 1705 | 新增: } | |
| 1706 | 新增: }, | |
| 1707 | 新增: "node_modules/range-parser": { | |
| 1708 | 新增: "version": "1.2.1", | |
| 1709 | 新增: "resolved": "https://registry.npmjs.org/range-parser/-/range-parser-1.2.1.tgz", | |
| 1710 | 新增: "integrity": "sha512-Hrgsx+orqoygnmhFbKaHE6c296J+HTAQXoxEF6gNupROmmGJRoyzfG3ccAveqCBrwr/2yxQ5BVd/GTl5agOwSg==", | |
| 1711 | 新增: "license": "MIT", | |
| 1712 | 新增: "engines": { | |
| 1713 | 新增: "node": ">= 0.6" | |
| 1714 | 新增: } | |
| 1715 | 新增: }, | |
| 1716 | 新增: "node_modules/raw-body": { | |
| 1717 | 新增: "version": "2.5.3", | |
| 1718 | 新增: "resolved": "https://registry.npmjs.org/raw-body/-/raw-body-2.5.3.tgz", | |
| 1719 | 新增: "integrity": "sha512-s4VSOf6yN0rvbRZGxs8Om5CWj6seneMwK3oDb4lWDH0UPhWcxwOWw5+qk24bxq87szX1ydrwylIOp2uG1ojUpA==", | |
| 1720 | 新增: "license": "MIT", | |
| 1721 | 新增: "dependencies": { | |
| 1722 | 新增: "bytes": "~3.1.2", | |
| 1723 | 新增: "http-errors": "~2.0.1", | |
| 1724 | 新增: "iconv-lite": "~0.4.24", | |
| 1725 | 新增: "unpipe": "~1.0.0" | |
| 1726 | 新增: }, | |
| 1727 | 新增: "engines": { | |
| 1728 | 新增: "node": ">= 0.8" | |
| 1729 | 新增: } | |
| 1730 | 新增: }, | |
| 1731 | 新增: "node_modules/readable-stream": { | |
| 1732 | 新增: "version": "3.6.2", | |
| 1733 | 新增: "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.6.2.tgz", | |
| 1734 | 新增: "integrity": "sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA==", | |
| 1735 | 新增: "license": "MIT", | |
| 1736 | 新增: "dependencies": { | |
| 1737 | 新增: "inherits": "^2.0.3", | |
| 1738 | 新增: "string_decoder": "^1.1.1", | |
| 1739 | 新增: "util-deprecate": "^1.0.1" | |
| 1740 | 新增: }, | |
| 1741 | 新增: "engines": { | |
| 1742 | 新增: "node": ">= 6" | |
| 1743 | 新增: } | |
| 1744 | 新增: }, | |
| 1745 | 新增: "node_modules/readdirp": { | |
| 1746 | 新增: "version": "3.6.0", | |
| 1747 | 新增: "resolved": "https://registry.npmjs.org/readdirp/-/readdirp-3.6.0.tgz", | |
| 1748 | 新增: "integrity": "sha512-hOS089on8RduqdbhvQ5Z37A0ESjsqz6qnRcffsMU3495FuTdqSm+7bhJ29JvIOsBDEEnan5DPu9t3To9VRlMzA==", | |
| 1749 | 新增: "license": "MIT", | |
| 1750 | 新增: "dependencies": { | |
| 1751 | 新增: "picomatch": "^2.2.1" | |
| 1752 | 新增: }, | |
| 1753 | 新增: "engines": { | |
| 1754 | 新增: "node": ">=8.10.0" | |
| 1755 | 新增: } | |
| 1756 | 新增: }, | |
| 1757 | 新增: "node_modules/restore-cursor": { | |
| 1758 | 新增: "version": "3.1.0", | |
| 1759 | 新增: "resolved": "https://registry.npmjs.org/restore-cursor/-/restore-cursor-3.1.0.tgz", | |
| 1760 | 新增: "integrity": "sha512-l+sSefzHpj5qimhFSE5a8nufZYAM3sBSVMAPtYkmC+4EH2anSGaEMXSD0izRQbu9nfyQ9y5JrVmp7E8oZrUjvA==", | |
| 1761 | 新增: "license": "MIT", | |
| 1762 | 新增: "dependencies": { | |
| 1763 | 新增: "onetime": "^5.1.0", | |
| 1764 | 新增: "signal-exit": "^3.0.2" | |
| 1765 | 新增: }, | |
| 1766 | 新增: "engines": { | |
| 1767 | 新增: "node": ">=8" | |
| 1768 | 新增: } | |
| 1769 | 新增: }, | |
| 1770 | 新增: "node_modules/retry": { | |
| 1771 | 新增: "version": "0.12.0", | |
| 1772 | 新增: "resolved": "https://registry.npmjs.org/retry/-/retry-0.12.0.tgz", | |
| 1773 | 新增: "integrity": "sha512-9LkiTwjUh6rT555DtE9rTX+BKByPfrMzEAtnlEtdEwr3Nkffwiihqe2bWADg+OQRjt9gl6ICdmB/ZFDCGAtSow==", | |
| 1774 | 新增: "license": "MIT", | |
| 1775 | 新增: "engines": { | |
| 1776 | 新增: "node": ">= 4" | |
| 1777 | 新增: } | |
| 1778 | 新增: }, | |
| 1779 | 新增: "node_modules/rfdc": { | |
| 1780 | 新增: "version": "1.4.1", | |
| 1781 | 新增: "resolved": "https://registry.npmjs.org/rfdc/-/rfdc-1.4.1.tgz", | |
| 1782 | 新增: "integrity": "sha512-q1b3N5QkRUWUl7iyylaaj3kOpIT0N2i9MqIEQXP73GVsN9cw3fdx8X63cEmWhJGi2PPCF23Ijp7ktmd39rawIA==", | |
| 1783 | 新增: "license": "MIT" | |
| 1784 | 新增: }, | |
| 1785 | 新增: "node_modules/rxjs": { | |
| 1786 | 新增: "version": "7.8.2", | |
| 1787 | 新增: "resolved": "https://registry.npmjs.org/rxjs/-/rxjs-7.8.2.tgz", | |
| 1788 | 新增: "integrity": "sha512-dhKf903U/PQZY6boNNtAGdWbG85WAbjT/1xYoZIC7FAY0yWapOBQVsVrDl58W86//e1VpMNBtRV4MaXfdMySFA==", | |
| 1789 | 新增: "license": "Apache-2.0", | |
| 1790 | 新增: "dependencies": { | |
| 1791 | 新增: "tslib": "^2.1.0" | |
| 1792 | 新增: } | |
| 1793 | 新增: }, | |
| 1794 | 新增: "node_modules/safe-buffer": { | |
| 1795 | 新增: "version": "5.2.1", | |
| 1796 | 新增: "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz", | |
| 1797 | 新增: "integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==", | |
| 1798 | 新增: "funding": [ | |
| 1799 | 新增: { | |
| 1800 | 新增: "type": "github", | |
| 1801 | 新增: "url": "https://github.com/sponsors/feross" | |
| 1802 | 新增: }, | |
| 1803 | 新增: { | |
| 1804 | 新增: "type": "patreon", | |
| 1805 | 新增: "url": "https://www.patreon.com/feross" | |
| 1806 | 新增: }, | |
| 1807 | 新增: { | |
| 1808 | 新增: "type": "consulting", | |
| 1809 | 新增: "url": "https://feross.org/support" | |
| 1810 | 新增: } | |
| 1811 | 新增: ], | |
| 1812 | 新增: "license": "MIT" | |
| 1813 | 新增: }, | |
| 1814 | 新增: "node_modules/safer-buffer": { | |
| 1815 | 新增: "version": "2.1.2", | |
| 1816 | 新增: "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz", | |
| 1817 | 新增: "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==", | |
| 1818 | 新增: "license": "MIT" | |
| 1819 | 新增: }, | |
| 1820 | 新增: "node_modules/send": { | |
| 1821 | 新增: "version": "0.19.2", | |
| 1822 | 新增: "resolved": "https://registry.npmjs.org/send/-/send-0.19.2.tgz", | |
| 1823 | 新增: "integrity": "sha512-VMbMxbDeehAxpOtWJXlcUS5E8iXh6QmN+BkRX1GARS3wRaXEEgzCcB10gTQazO42tpNIya8xIyNx8fll1OFPrg==", | |
| 1824 | 新增: "license": "MIT", | |
| 1825 | 新增: "dependencies": { | |
| 1826 | 新增: "debug": "2.6.9", | |
| 1827 | 新增: "depd": "2.0.0", | |
| 1828 | 新增: "destroy": "1.2.0", | |
| 1829 | 新增: "encodeurl": "~2.0.0", | |
| 1830 | 新增: "escape-html": "~1.0.3", | |
| 1831 | 新增: "etag": "~1.8.1", | |
| 1832 | 新增: "fresh": "~0.5.2", | |
| 1833 | 新增: "http-errors": "~2.0.1", | |
| 1834 | 新增: "mime": "1.6.0", | |
| 1835 | 新增: "ms": "2.1.3", | |
| 1836 | 新增: "on-finished": "~2.4.1", | |
| 1837 | 新增: "range-parser": "~1.2.1", | |
| 1838 | 新增: "statuses": "~2.0.2" | |
| 1839 | 新增: }, | |
| 1840 | 新增: "engines": { | |
| 1841 | 新增: "node": ">= 0.8.0" | |
| 1842 | 新增: } | |
| 1843 | 新增: }, | |
| 1844 | 新增: "node_modules/send/node_modules/ms": { | |
| 1845 | 新增: "version": "2.1.3", | |
| 1846 | 新增: "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", | |
| 1847 | 新增: "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", | |
| 1848 | 新增: "license": "MIT" | |
| 1849 | 新增: }, | |
| 1850 | 新增: "node_modules/serve-static": { | |
| 1851 | 新增: "version": "1.16.3", | |
| 1852 | 新增: "resolved": "https://registry.npmjs.org/serve-static/-/serve-static-1.16.3.tgz", | |
| 1853 | 新增: "integrity": "sha512-x0RTqQel6g5SY7Lg6ZreMmsOzncHFU7nhnRWkKgWuMTu5NN0DR5oruckMqRvacAN9d5w6ARnRBXl9xhDCgfMeA==", | |
| 1854 | 新增: "license": "MIT", | |
| 1855 | 新增: "dependencies": { | |
| 1856 | 新增: "encodeurl": "~2.0.0", | |
| 1857 | 新增: "escape-html": "~1.0.3", | |
| 1858 | 新增: "parseurl": "~1.3.3", | |
| 1859 | 新增: "send": "~0.19.1" | |
| 1860 | 新增: }, | |
| 1861 | 新增: "engines": { | |
| 1862 | 新增: "node": ">= 0.8.0" | |
| 1863 | 新增: } | |
| 1864 | 新增: }, | |
| 1865 | 新增: "node_modules/setprototypeof": { | |
| 1866 | 新增: "version": "1.2.0", | |
| 1867 | 新增: "resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.2.0.tgz", | |
| 1868 | 新增: "integrity": "sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw==", | |
| 1869 | 新增: "license": "ISC" | |
| 1870 | 新增: }, | |
| 1871 | 新增: "node_modules/side-channel": { | |
| 1872 | 新增: "version": "1.1.1", | |
| 1873 | 新增: "resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.1.1.tgz", | |
| 1874 | 新增: "integrity": "sha512-6x6dK6zJdpTzF4sQeNYxwtvBzf6Eg4GtlesS94HOvTudUeyK2WXAaIfmDgsyslYrRBeFIlsi54AYsFGUuhmvrQ==", | |
| 1875 | 新增: "license": "MIT", | |
| 1876 | 新增: "dependencies": { | |
| 1877 | 新增: "es-errors": "^1.3.0", | |
| 1878 | 新增: "object-inspect": "^1.13.4", | |
| 1879 | 新增: "side-channel-list": "^1.0.1", | |
| 1880 | 新增: "side-channel-map": "^1.0.1", | |
| 1881 | 新增: "side-channel-weakmap": "^1.0.2" | |
| 1882 | 新增: }, | |
| 1883 | 新增: "engines": { | |
| 1884 | 新增: "node": ">= 0.4" | |
| 1885 | 新增: }, | |
| 1886 | 新增: "funding": { | |
| 1887 | 新增: "url": "https://github.com/sponsors/ljharb" | |
| 1888 | 新增: } | |
| 1889 | 新增: }, | |
| 1890 | 新增: "node_modules/side-channel-list": { | |
| 1891 | 新增: "version": "1.0.1", | |
| 1892 | 新增: "resolved": "https://registry.npmjs.org/side-channel-list/-/side-channel-list-1.0.1.tgz", | |
| 1893 | 新增: "integrity": "sha512-mjn/0bi/oUURjc5Xl7IaWi/OJJJumuoJFQJfDDyO46+hBWsfaVM65TBHq2eoZBhzl9EchxOijpkbRC8SVBQU0w==", | |
| 1894 | 新增: "license": "MIT", | |
| 1895 | 新增: "dependencies": { | |
| 1896 | 新增: "es-errors": "^1.3.0", | |
| 1897 | 新增: "object-inspect": "^1.13.4" | |
| 1898 | 新增: }, | |
| 1899 | 新增: "engines": { | |
| 1900 | 新增: "node": ">= 0.4" | |
| 1901 | 新增: }, | |
| 1902 | 新增: "funding": { | |
| 1903 | 新增: "url": "https://github.com/sponsors/ljharb" | |
| 1904 | 新增: } | |
| 1905 | 新增: }, | |
| 1906 | 新增: "node_modules/side-channel-map": { | |
| 1907 | 新增: "version": "1.0.1", | |
| 1908 | 新增: "resolved": "https://registry.npmjs.org/side-channel-map/-/side-channel-map-1.0.1.tgz", | |
| 1909 | 新增: "integrity": "sha512-VCjCNfgMsby3tTdo02nbjtM/ewra6jPHmpThenkTYh8pG9ucZ/1P8So4u4FGBek/BjpOVsDCMoLA/iuBKIFXRA==", | |
| 1910 | 新增: "license": "MIT", | |
| 1911 | 新增: "dependencies": { | |
| 1912 | 新增: "call-bound": "^1.0.2", | |
| 1913 | 新增: "es-errors": "^1.3.0", | |
| 1914 | 新增: "get-intrinsic": "^1.2.5", | |
| 1915 | 新增: "object-inspect": "^1.13.3" | |
| 1916 | 新增: }, | |
| 1917 | 新增: "engines": { | |
| 1918 | 新增: "node": ">= 0.4" | |
| 1919 | 新增: }, | |
| 1920 | 新增: "funding": { | |
| 1921 | 新增: "url": "https://github.com/sponsors/ljharb" | |
| 1922 | 新增: } | |
| 1923 | 新增: }, | |
| 1924 | 新增: "node_modules/side-channel-weakmap": { | |
| 1925 | 新增: "version": "1.0.2", | |
| 1926 | 新增: "resolved": "https://registry.npmjs.org/side-channel-weakmap/-/side-channel-weakmap-1.0.2.tgz", | |
| 1927 | 新增: "integrity": "sha512-WPS/HvHQTYnHisLo9McqBHOJk2FkHO/tlpvldyrnem4aeQp4hai3gythswg6p01oSoTl58rcpiFAjF2br2Ak2A==", | |
| 1928 | 新增: "license": "MIT", | |
| 1929 | 新增: "dependencies": { | |
| 1930 | 新增: "call-bound": "^1.0.2", | |
| 1931 | 新增: "es-errors": "^1.3.0", | |
| 1932 | 新增: "get-intrinsic": "^1.2.5", | |
| 1933 | 新增: "object-inspect": "^1.13.3", | |
| 1934 | 新增: "side-channel-map": "^1.0.1" | |
| 1935 | 新增: }, | |
| 1936 | 新增: "engines": { | |
| 1937 | 新增: "node": ">= 0.4" | |
| 1938 | 新增: }, | |
| 1939 | 新增: "funding": { | |
| 1940 | 新增: "url": "https://github.com/sponsors/ljharb" | |
| 1941 | 新增: } | |
| 1942 | 新增: }, | |
| 1943 | 新增: "node_modules/signal-exit": { | |
| 1944 | 新增: "version": "3.0.7", | |
| 1945 | 新增: "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-3.0.7.tgz", | |
| 1946 | 新增: "integrity": "sha512-wnD2ZE+l+SPC/uoS0vXeE9L1+0wuaMqKlfz9AMUo38JsyLSBWSFcHR1Rri62LZc12vLr1gb3jl7iwQhgwpAbGQ==", | |
| 1947 | 新增: "license": "ISC" | |
| 1948 | 新增: }, | |
| 1949 | 新增: "node_modules/slice-ansi": { | |
| 1950 | 新增: "version": "3.0.0", | |
| 1951 | 新增: "resolved": "https://registry.npmjs.org/slice-ansi/-/slice-ansi-3.0.0.tgz", | |
| 1952 | 新增: "integrity": "sha512-pSyv7bSTC7ig9Dcgbw9AuRNUb5k5V6oDudjZoMBSr13qpLBG7tB+zgCkARjq7xIUgdz5P1Qe8u+rSGdouOOIyQ==", | |
| 1953 | 新增: "license": "MIT", | |
| 1954 | 新增: "dependencies": { | |
| 1955 | 新增: "ansi-styles": "^4.0.0", | |
| 1956 | 新增: "astral-regex": "^2.0.0", | |
| 1957 | 新增: "is-fullwidth-code-point": "^3.0.0" | |
| 1958 | 新增: }, | |
| 1959 | 新增: "engines": { | |
| 1960 | 新增: "node": ">=8" | |
| 1961 | 新增: } | |
| 1962 | 新增: }, | |
| 1963 | 新增: "node_modules/smol-toml": { | |
| 1964 | 新增: "version": "1.9.1", | |
| 1965 | 新增: "resolved": "https://registry.npmjs.org/smol-toml/-/smol-toml-1.9.1.tgz", | |
| 1966 | 新增: "integrity": "sha512-j7WyPdf0CJoutMzMoPLF/bVXHtKZIT9Rb4eGeEbWw8X2t5oirjPgpL+OpaENZrILYaXqYwnVH+qgUwVbl+pUJQ==", | |
| 1967 | 新增: "license": "BSD-3-Clause", | |
| 1968 | 新增: "engines": { | |
| 1969 | 新增: "node": ">= 18" | |
| 1970 | 新增: }, | |
| 1971 | 新增: "funding": { | |
| 1972 | 新增: "url": "https://github.com/sponsors/cyyynthia" | |
| 1973 | 新增: } | |
| 1974 | 新增: }, | |
| 1975 | 新增: "node_modules/statuses": { | |
| 1976 | 新增: "version": "2.0.2", | |
| 1977 | 新增: "resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.2.tgz", | |
| 1978 | 新增: "integrity": "sha512-DvEy55V3DB7uknRo+4iOGT5fP1slR8wQohVdknigZPMpMstaKJQWhwiYBACJE3Ul2pTnATihhBYnRhZQHGBiRw==", | |
| 1979 | 新增: "license": "MIT", | |
| 1980 | 新增: "engines": { | |
| 1981 | 新增: "node": ">= 0.8" | |
| 1982 | 新增: } | |
| 1983 | 新增: }, | |
| 1984 | 新增: "node_modules/string_decoder": { | |
| 1985 | 新增: "version": "1.3.0", | |
| 1986 | 新增: "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.3.0.tgz", | |
| 1987 | 新增: "integrity": "sha512-hkRX8U1WjJFd8LsDJ2yQ/wWWxaopEsABU1XfkM8A+j0+85JAGppt16cr1Whg6KIbb4okU6Mql6BOj+uup/wKeA==", | |
| 1988 | 新增: "license": "MIT", | |
| 1989 | 新增: "dependencies": { | |
| 1990 | 新增: "safe-buffer": "~5.2.0" | |
| 1991 | 新增: } | |
| 1992 | 新增: }, | |
| 1993 | 新增: "node_modules/string-width": { | |
| 1994 | 新增: "version": "4.2.3", | |
| 1995 | 新增: "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz", | |
| 1996 | 新增: "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==", | |
| 1997 | 新增: "license": "MIT", | |
| 1998 | 新增: "dependencies": { | |
| 1999 | 新增: "emoji-regex": "^8.0.0", | |
| 2000 | 新增: "is-fullwidth-code-point": "^3.0.0", | |
| 2001 | 新增: "strip-ansi": "^6.0.1" | |
| 2002 | 新增: }, | |
| 2003 | 新增: "engines": { | |
| 2004 | 新增: "node": ">=8" | |
| 2005 | 新增: } | |
| 2006 | 新增: }, | |
| 2007 | 新增: "node_modules/strip-ansi": { | |
| 2008 | 新增: "version": "6.0.1", | |
| 2009 | 新增: "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", | |
| 2010 | 新增: "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", | |
| 2011 | 新增: "license": "MIT", | |
| 2012 | 新增: "dependencies": { | |
| 2013 | 新增: "ansi-regex": "^5.0.1" | |
| 2014 | 新增: }, | |
| 2015 | 新增: "engines": { | |
| 2016 | 新增: "node": ">=8" | |
| 2017 | 新增: } | |
| 2018 | 新增: }, | |
| 2019 | 新增: "node_modules/supports-color": { | |
| 2020 | 新增: "version": "7.2.0", | |
| 2021 | 新增: "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", | |
| 2022 | 新增: "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==", | |
| 2023 | 新增: "license": "MIT", | |
| 2024 | 新增: "dependencies": { | |
| 2025 | 新增: "has-flag": "^4.0.0" | |
| 2026 | 新增: }, | |
| 2027 | 新增: "engines": { | |
| 2028 | 新增: "node": ">=8" | |
| 2029 | 新增: } | |
| 2030 | 新增: }, | |
| 2031 | 新增: "node_modules/through": { | |
| 2032 | 新增: "version": "2.3.8", | |
| 2033 | 新增: "resolved": "https://registry.npmjs.org/through/-/through-2.3.8.tgz", | |
| 2034 | 新增: "integrity": "sha512-w89qg7PI8wAdvX60bMDP+bFoD5Dvhm9oLheFp5O4a2QF0cSBGsBX4qZmadPMvVqlLJBBci+WqGGOAPvcDeNSVg==", | |
| 2035 | 新增: "license": "MIT" | |
| 2036 | 新增: }, | |
| 2037 | 新增: "node_modules/tinycolor2": { | |
| 2038 | 新增: "version": "1.6.0", | |
| 2039 | 新增: "resolved": "https://registry.npmjs.org/tinycolor2/-/tinycolor2-1.6.0.tgz", | |
| 2040 | 新增: "integrity": "sha512-XPaBkWQJdsf3pLKJV9p4qN/S+fm2Oj8AIPo1BTUhg5oxkvm9+SVEGFdhyOz7tTdUTfvxMiAs4sp6/eZO2Ew+pw==", | |
| 2041 | 新增: "license": "MIT" | |
| 2042 | 新增: }, | |
| 2043 | 新增: "node_modules/tinygradient": { | |
| 2044 | 新增: "version": "1.1.5", | |
| 2045 | 新增: "resolved": "https://registry.npmjs.org/tinygradient/-/tinygradient-1.1.5.tgz", | |
| 2046 | 新增: "integrity": "sha512-8nIfc2vgQ4TeLnk2lFj4tRLvvJwEfQuabdsmvDdQPT0xlk9TaNtpGd6nNRxXoK6vQhN6RSzj+Cnp5tTQmpxmbw==", | |
| 2047 | 新增: "license": "MIT", | |
| 2048 | 新增: "dependencies": { | |
| 2049 | 新增: "@types/tinycolor2": "^1.4.0", | |
| 2050 | 新增: "tinycolor2": "^1.0.0" | |
| 2051 | 新增: } | |
| 2052 | 新增: }, | |
| 2053 | 新增: "node_modules/to-regex-range": { | |
| 2054 | 新增: "version": "5.0.1", | |
| 2055 | 新增: "resolved": "https://registry.npmjs.org/to-regex-range/-/to-regex-range-5.0.1.tgz", | |
| 2056 | 新增: "integrity": "sha512-65P7iz6X5yEr1cwcgvQxbbIw7Uk3gOy5dIdtZ4rDveLqhrdJP+Li/Hx6tyK0NEb+2GCyneCMJiGqrADCSNk8sQ==", | |
| 2057 | 新增: "license": "MIT", | |
| 2058 | 新增: "dependencies": { | |
| 2059 | 新增: "is-number": "^7.0.0" | |
| 2060 | 新增: }, | |
| 2061 | 新增: "engines": { | |
| 2062 | 新增: "node": ">=8.0" | |
| 2063 | 新增: } | |
| 2064 | 新增: }, | |
| 2065 | 新增: "node_modules/toidentifier": { | |
| 2066 | 新增: "version": "1.0.1", | |
| 2067 | 新增: "resolved": "https://registry.npmjs.org/toidentifier/-/toidentifier-1.0.1.tgz", | |
| 2068 | 新增: "integrity": "sha512-o5sSPKEkg/DIQNmH43V0/uerLrpzVedkUh8tGNvaeXpfpuwjKenlSox/2O/BTlZUtEe+JG7s5YhEz608PlAHRA==", | |
| 2069 | 新增: "license": "MIT", | |
| 2070 | 新增: "engines": { | |
| 2071 | 新增: "node": ">=0.6" | |
| 2072 | 新增: } | |
| 2073 | 新增: }, | |
| 2074 | 新增: "node_modules/tslib": { | |
| 2075 | 新增: "version": "2.9.1", | |
| 2076 | 新增: "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.9.1.tgz", | |
| 2077 | 新增: "integrity": "sha512-a4Ux9VKuIMHsOS7ENbEq6hK2ZGYIT27Rtl0E4eD9KqwxhKiQeMZE/9xb3IdYwWaSOyIBQLExhQgXDTYoiCxnWA==", | |
| 2078 | 新增: "license": "0BSD" | |
| 2079 | 新增: }, | |
| 2080 | 新增: "node_modules/type-fest": { | |
| 2081 | 新增: "version": "0.20.2", | |
| 2082 | 新增: "resolved": "https://registry.npmjs.org/type-fest/-/type-fest-0.20.2.tgz", | |
| 2083 | 新增: "integrity": "sha512-Ne+eE4r0/iWnpAxD852z3A+N0Bt5RN//NjJwRd2VFHEmrywxf5vsZlh4R6lixl6B+wz/8d+maTSAkN1FIkI3LQ==", | |
| 2084 | 新增: "license": "(MIT OR CC0-1.0)", | |
| 2085 | 新增: "engines": { | |
| 2086 | 新增: "node": ">=10" | |
| 2087 | 新增: }, | |
| 2088 | 新增: "funding": { | |
| 2089 | 新增: "url": "https://github.com/sponsors/sindresorhus" | |
| 2090 | 新增: } | |
| 2091 | 新增: }, | |
| 2092 | 新增: "node_modules/type-is": { | |
| 2093 | 新增: "version": "1.6.18", | |
| 2094 | 新增: "resolved": "https://registry.npmjs.org/type-is/-/type-is-1.6.18.tgz", | |
| 2095 | 新增: "integrity": "sha512-TkRKr9sUTxEH8MdfuCSP7VizJyzRNMjj2J2do2Jr3Kym598JVdEksuzPQCnlFPW4ky9Q+iA+ma9BGm06XQBy8g==", | |
| 2096 | 新增: "license": "MIT", | |
| 2097 | 新增: "dependencies": { | |
| 2098 | 新增: "media-typer": "0.3.0", | |
| 2099 | 新增: "mime-types": "~2.1.24" | |
| 2100 | 新增: }, | |
| 2101 | 新增: "engines": { | |
| 2102 | 新增: "node": ">= 0.6" | |
| 2103 | 新增: } | |
| 2104 | 新增: }, | |
| 2105 | 新增: "node_modules/uid-safe": { | |
| 2106 | 新增: "version": "2.1.5", | |
| 2107 | 新增: "resolved": "https://registry.npmjs.org/uid-safe/-/uid-safe-2.1.5.tgz", | |
| 2108 | 新增: "integrity": "sha512-KPHm4VL5dDXKz01UuEd88Df+KzynaohSL9fBh096KWAxSKZQDI2uBrVqtvRM4rwrIrRRKsdLNML/lnaaVSRioA==", | |
| 2109 | 新增: "license": "MIT", | |
| 2110 | 新增: "dependencies": { | |
| 2111 | 新增: "random-bytes": "~1.0.0" | |
| 2112 | 新增: }, | |
| 2113 | 新增: "engines": { | |
| 2114 | 新增: "node": ">= 0.8" | |
| 2115 | 新增: } | |
| 2116 | 新增: }, | |
| 2117 | 新增: "node_modules/undici": { | |
| 2118 | 新增: "version": "5.29.0", | |
| 2119 | 新增: "resolved": "https://registry.npmjs.org/undici/-/undici-5.29.0.tgz", | |
| 2120 | 新增: "integrity": "sha512-raqeBD6NQK4SkWhQzeYKd1KmIG6dllBOTt55Rmkt4HtI9mwdWtJljnrXjAFUBLTSN67HWrOIZ3EPF4kjUw80Bg==", | |
| 2121 | 新增: "license": "MIT", | |
| 2122 | 新增: "dependencies": { | |
| 2123 | 新增: "@fastify/busboy": "^2.0.0" | |
| 2124 | 新增: }, | |
| 2125 | 新增: "engines": { | |
| 2126 | 新增: "node": ">=14.0" | |
| 2127 | 新增: } | |
| 2128 | 新增: }, | |
| 2129 | 新增: "node_modules/unpipe": { | |
| 2130 | 新增: "version": "1.0.0", | |
| 2131 | 新增: "resolved": "https://registry.npmjs.org/unpipe/-/unpipe-1.0.0.tgz", | |
| 2132 | 新增: "integrity": "sha512-pjy2bYhSsufwWlKwPc+l3cN7+wuJlK6uz0YdJEOlQDbl6jo/YlPi4mb8agUkVC8BF7V8NuzeyPNqRksA3hztKQ==", | |
| 2133 | 新增: "license": "MIT", | |
| 2134 | 新增: "engines": { | |
| 2135 | 新增: "node": ">= 0.8" | |
| 2136 | 新增: } | |
| 2137 | 新增: }, | |
| 2138 | 新增: "node_modules/util-deprecate": { | |
| 2139 | 新增: "version": "1.0.2", | |
| 2140 | 新增: "resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz", | |
| 2141 | 新增: "integrity": "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==", | |
| 2142 | 新增: "license": "MIT" | |
| 2143 | 新增: }, | |
| 2144 | 新增: "node_modules/utils-merge": { | |
| 2145 | 新增: "version": "1.0.1", | |
| 2146 | 新增: "resolved": "https://registry.npmjs.org/utils-merge/-/utils-merge-1.0.1.tgz", | |
| 2147 | 新增: "integrity": "sha512-pMZTvIkT1d+TFGvDOqodOclx0QWkkgi6Tdoa8gC8ffGAAqz9pzPTZWAybbsHHoED/ztMtkv/VoYTYyShUn81hA==", | |
| 2148 | 新增: "license": "MIT", | |
| 2149 | 新增: "engines": { | |
| 2150 | 新增: "node": ">= 0.4.0" | |
| 2151 | 新增: } | |
| 2152 | 新增: }, | |
| 2153 | 新增: "node_modules/vary": { | |
| 2154 | 新增: "version": "1.1.2", | |
| 2155 | 新增: "resolved": "https://registry.npmjs.org/vary/-/vary-1.1.2.tgz", | |
| 2156 | 新增: "integrity": "sha512-BNGbWLfd0eUPabhkXUVm0j8uuvREyTh5ovRa/dyow/BqAbZJyC+5fU+IzQOzmAKzYqYRAISoRhdQr3eIZ/PXqg==", | |
| 2157 | 新增: "license": "MIT", | |
| 2158 | 新增: "engines": { | |
| 2159 | 新增: "node": ">= 0.8" | |
| 2160 | 新增: } | |
| 2161 | 新增: }, | |
| 2162 | 新增: "node_modules/wcwidth": { | |
| 2163 | 新增: "version": "1.0.1", | |
| 2164 | 新增: "resolved": "https://registry.npmjs.org/wcwidth/-/wcwidth-1.0.1.tgz", | |
| 2165 | 新增: "integrity": "sha512-XHPEwS0q6TaxcvG85+8EYkbiCux2XtWG2mkc47Ng2A77BQu9+DqIOJldST4HgPkuea7dvKSj5VgX3P1d4rW8Tg==", | |
| 2166 | 新增: "license": "MIT", | |
| 2167 | 新增: "dependencies": { | |
| 2168 | 新增: "defaults": "^1.0.3" | |
| 2169 | 新增: } | |
| 2170 | 新增: }, | |
| 2171 | 新增: "node_modules/widest-line": { | |
| 2172 | 新增: "version": "3.1.0", | |
| 2173 | 新增: "resolved": "https://registry.npmjs.org/widest-line/-/widest-line-3.1.0.tgz", | |
| 2174 | 新增: "integrity": "sha512-NsmoXalsWVDMGupxZ5R08ka9flZjjiLvHVAWYOKtiKM8ujtZWr9cRffak+uSE48+Ob8ObalXpwyeUiyDD6QFgg==", | |
| 2175 | 新增: "license": "MIT", | |
| 2176 | 新增: "dependencies": { | |
| 2177 | 新增: "string-width": "^4.0.0" | |
| 2178 | 新增: }, | |
| 2179 | 新增: "engines": { | |
| 2180 | 新增: "node": ">=8" | |
| 2181 | 新增: } | |
| 2182 | 新增: }, | |
| 2183 | 新增: "node_modules/wrap-ansi": { | |
| 2184 | 新增: "version": "7.0.0", | |
| 2185 | 新增: "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-7.0.0.tgz", | |
| 2186 | 新增: "integrity": "sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q==", | |
| 2187 | 新增: "license": "MIT", | |
| 2188 | 新增: "dependencies": { | |
| 2189 | 新增: "ansi-styles": "^4.0.0", | |
| 2190 | 新增: "string-width": "^4.1.0", | |
| 2191 | 新增: "strip-ansi": "^6.0.0" | |
| 2192 | 新增: }, | |
| 2193 | 新增: "engines": { | |
| 2194 | 新增: "node": ">=10" | |
| 2195 | 新增: }, | |
| 2196 | 新增: "funding": { | |
| 2197 | 新增: "url": "https://github.com/chalk/wrap-ansi?sponsor=1" | |
| 2198 | 新增: } | |
| 2199 | 新增: }, | |
| 2200 | 新增: "node_modules/ws": { | |
| 2201 | 新增: "version": "8.22.1", | |
| 2202 | 新增: "resolved": "https://registry.npmjs.org/ws/-/ws-8.22.1.tgz", | |
| 2203 | 新增: "integrity": "sha512-oyL6OPYme/CmiFvNuGzeoxCJ4nOrZE2O1FwM9MWM1AsGri6nLXB2pg+lNA8aLeXMSav0J6eIVS1j6vUPzUtK9g==", | |
| 2204 | 新增: "license": "MIT", | |
| 2205 | 新增: "engines": { | |
| 2206 | 新增: "node": ">=10.0.0" | |
| 2207 | 新增: }, | |
| 2208 | 新增: "peerDependencies": { | |
| 2209 | 新增: "bufferutil": "^4.0.1", | |
| 2210 | 新增: "utf-8-validate": ">=5.0.2" | |
| 2211 | 新增: }, | |
| 2212 | 新增: "peerDependenciesMeta": { | |
| 2213 | 新增: "bufferutil": { | |
| 2214 | 新增: "optional": true | |
| 2215 | 新增: }, | |
| 2216 | 新增: "utf-8-validate": { | |
| 2217 | 新增: "optional": true | |
| 2218 | 新增: } | |
| 2219 | 新增: } | |
| 2220 | 新增: } | |
| 2221 | 新增: } | |
| 2222 | 新增:} | |
| @@ -0,0 +1,8 @@ | ||
| 1 | 新增:{ | |
| 2 | 新增: "name": "cage-windows-ccs-runtime", | |
| 3 | 新增: "private": true, | |
| 4 | 新增: "version": "1.0.0", | |
| 5 | 新增: "dependencies": { | |
| 6 | 新增: "@kaitranntt/ccs": "8.11.0" | |
| 7 | 新增: } | |
| 8 | 新增:} | |
| 文件末尾没有换行 | ||
| @@ -0,0 +1,28 @@ | ||
| 1 | 新增:{ | |
| 2 | 新增: "uv": { | |
| 3 | 新增: "version": "0.13.7", | |
| 4 | 新增: "filename": "uv-x86_64-pc-windows-msvc.zip", | |
| 5 | 新增: "url": "https://github.com/astral-sh/uv/releases/download/0.13.7/uv-x86_64-pc-windows-msvc.zip", | |
| 6 | 新增: "sha256": "0cdc5b38fe5a8168ed6a25814f5ba43c21d313dd3187314fccb37b7cec46e021" | |
| 7 | 新增: }, | |
| 8 | 新增: "python": { | |
| 9 | 新增: "version": "3.13.18", | |
| 10 | 新增: "key": "cpython-3.13.18-windows-x86_64-none", | |
| 11 | 新增: "filename": "cpython-3.13.18+20261026-x86_64-pc-windows-msvc-install_only_stripped.tar.gz", | |
| 12 | 新增: "url": "https://github.com/astral-sh/python-build-standalone/releases/download/20261026/cpython-3.13.18%2B20261026-x86_64-pc-windows-msvc-install_only_stripped.tar.gz", | |
| 13 | 新增: "sha256": "7369f7a35f261222a6ac8b3a87c1c88eeebee8af945d85346202591a64038dd3" | |
| 14 | 新增: }, | |
| 15 | 新增: "claude": { | |
| 16 | 新增: "version": "2.1.311", | |
| 17 | 新增: "filename": "claude-2.1.311-win32-x64.exe", | |
| 18 | 新增: "url": "https://downloads.claude.ai/claude-code-releases/2.1.311/win32-x64/claude.exe", | |
| 19 | 新增: "manifest": "https://downloads.claude.ai/claude-code-releases/2.1.311/manifest.json", | |
| 20 | 新增: "sha256": "966f4b2ce962298f5dee6a942e8c47c8f97392e69e728e622319a98b259c0680" | |
| 21 | 新增: }, | |
| 22 | 新增: "git": { | |
| 23 | 新增: "version": "2.56.0.4", | |
| 24 | 新增: "filename": "PortableGit-2.56.0.4-64-bit.7z.exe", | |
| 25 | 新增: "url": "https://github.com/git-for-windows/git/releases/download/v2.56.0.windows.4/PortableGit-2.56.0.4-64-bit.7z.exe", | |
| 26 | 新增: "sha256": "b1f3e52216e2ed6882d1bebfd4d3fdf319bec40d2edbbf9fd26ec4fd3fce7ed1" | |
| 27 | 新增: } | |
| 28 | 新增:} | |
| @@ -0,0 +1,84 @@ | ||
| 1 | 新增:# Execute as the paired ordinary GUI user. Management copies only the validated | |
| 2 | 新增:# receipt into the readonly bridge; no ProgramFiles write permission is added. | |
| 3 | 新增:[CmdletBinding()] | |
| 4 | 新增:param( | |
| 5 | 新增: [Parameter(Mandatory)][string]$RuntimeArchive, | |
| 6 | 新增: [Parameter(Mandatory)][string]$NodeArchive, | |
| 7 | 新增: [Parameter(Mandatory)][string]$BridgeDirectory, | |
| 8 | 新增: [string]$ExistingNode = '', | |
| 9 | 新增: [string]$ReceiptDirectory = (Join-Path $env:USERPROFILE 'Cage\CLI\install-receipts') | |
| 10 | 新增:) | |
| 11 | 新增:$ErrorActionPreference='Stop' | |
| 12 | 新增:Set-StrictMode -Version Latest | |
| 13 | 新增:if (-not [Runtime.InteropServices.RuntimeInformation]::IsOSPlatform([Runtime.InteropServices.OSPlatform]::Windows)) { throw 'Native Windows is required.' } | |
| 14 | 新增:$user=[Security.Principal.WindowsIdentity]::GetCurrent() | |
| 15 | 新增:if ((New-Object Security.Principal.WindowsPrincipal($user)).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) { throw 'Use the paired ordinary GUI user.' } | |
| 16 | 新增:$bridge=[IO.Path]::GetFullPath($BridgeDirectory) | |
| 17 | 新增:if (-not (Test-Path (Join-Path $bridge 'Cage.GuestClipboard.exe') -PathType Leaf)) { throw 'Install the paired bridge first.' } | |
| 18 | 新增:function Assert-NoReparse([string]$Path) { | |
| 19 | 新增: $item=Get-Item -LiteralPath $Path -Force | |
| 20 | 新增: while ($null -ne $item) { if ($item.Attributes -band [IO.FileAttributes]::ReparsePoint) { throw 'A native CCS path is a reparse point.' }; if ($item -is [IO.FileInfo]) { $item=$item.Directory } else { $item=$item.Parent } } | |
| 21 | 新增:} | |
| 22 | 新增:function Protect-Path([string]$Path,[bool]$Directory) { | |
| 23 | 新增: if ($Directory) { $acl=New-Object Security.AccessControl.DirectorySecurity } else { $acl=New-Object Security.AccessControl.FileSecurity } | |
| 24 | 新增: $acl.SetOwner($user.User);$acl.SetAccessRuleProtection($true,$false) | |
| 25 | 新增: foreach ($sid in @($user.User,[Security.Principal.SecurityIdentifier]'S-1-5-18',[Security.Principal.SecurityIdentifier]'S-1-5-32-544')) { | |
| 26 | 新增: if ($Directory) { $rule=New-Object Security.AccessControl.FileSystemAccessRule($sid,'FullControl','ContainerInherit,ObjectInherit','None','Allow') } | |
| 27 | 新增: else { $rule=New-Object Security.AccessControl.FileSystemAccessRule($sid,'FullControl','Allow') } | |
| 28 | 新增: $acl.AddAccessRule($rule) | |
| 29 | 新增: } | |
| 30 | 新增: Set-Acl -LiteralPath $Path -AclObject $acl | |
| 31 | 新增:} | |
| 32 | 新增:function PrivateDirectory([string]$Path) { | |
| 33 | 新增: $parent=[IO.DirectoryInfo]$Path | |
| 34 | 新增: while (-not $parent.Exists) { $parent=$parent.Parent;if($null -eq $parent){throw 'Invalid native tool parent.'} } | |
| 35 | 新增: Assert-NoReparse $parent.FullName | |
| 36 | 新增: if(-not (Test-Path -LiteralPath $Path)){New-Item -ItemType Directory -Path $Path | Out-Null} | |
| 37 | 新增: Assert-NoReparse $Path;Protect-Path $Path $true | |
| 38 | 新增:} | |
| 39 | 新增:Assert-NoReparse $RuntimeArchive;Assert-NoReparse $NodeArchive;Assert-NoReparse $bridge | |
| 40 | 新增:if ((Get-FileHash $RuntimeArchive -Algorithm SHA256).Hash.ToLowerInvariant() -ne 'a0ab3bbac6b2c14ba53020474a4d6a6b307b9faf6f10998568b3200535c6b3e7') { throw 'CCS runtime archive checksum failed.' } | |
| 41 | 新增:if ((Get-FileHash $NodeArchive -Algorithm SHA256).Hash.ToLowerInvariant() -ne 'ca1bff5d8ead13c9f2ea404a176db46bd430704d5b5113734049fa365e7799e2') { throw 'Official Node archive checksum failed.' } | |
| 42 | 新增:$tools=Join-Path $env:USERPROFILE 'Cage\CLI\tools';PrivateDirectory $tools | |
| 43 | 新增:$runtime=Join-Path $tools 'ccs\8.11.0' | |
| 44 | 新增:if (-not (Test-Path -LiteralPath $runtime)) { | |
| 45 | 新增: $parent=Split-Path $runtime -Parent;PrivateDirectory $parent | |
| 46 | 新增: $stage=Join-Path $parent ('stage-'+[Guid]::NewGuid().ToString('N'));PrivateDirectory $stage | |
| 47 | 新增: & (Join-Path $env:SystemRoot 'System32\tar.exe') -xzf $RuntimeArchive -C $stage | |
| 48 | 新增: if($LASTEXITCODE -ne 0){throw 'CCS archive extraction failed; staged files were retained.'} | |
| 49 | 新增: [IO.Directory]::Move($stage,$runtime) | |
| 50 | 新增:} | |
| 51 | 新增:Assert-NoReparse $runtime | |
| 52 | 新增:$manifest=Join-Path $runtime 'runtime-files.json' | |
| 53 | 新增:$files=Get-Content -LiteralPath $manifest -Raw | ConvertFrom-Json | |
| 54 | 新增:foreach($entry in $files.PSObject.Properties) { | |
| 55 | 新增: $file=[IO.Path]::GetFullPath((Join-Path $runtime $entry.Name)) | |
| 56 | 新增: if(-not $file.StartsWith($runtime+'\',[StringComparison]::OrdinalIgnoreCase)){throw 'CCS runtime contains an invalid path.'} | |
| 57 | 新增: Assert-NoReparse $file | |
| 58 | 新增: if((Get-FileHash -LiteralPath $file -Algorithm SHA256).Hash.ToLowerInvariant() -ne $entry.Value){throw 'A CCS runtime file changed.'} | |
| 59 | 新增:} | |
| 60 | 新增:$nodeSha='1c331340fa6cac5e4294725959070a143fa0507195a78ad77eed7943f719aac9' | |
| 61 | 新增:if ($ExistingNode -ne '') { | |
| 62 | 新增: Assert-NoReparse $ExistingNode | |
| 63 | 新增: if((Get-FileHash $ExistingNode -Algorithm SHA256).Hash.ToLowerInvariant() -ne $nodeSha){throw 'Existing Node does not match the fixed official version.'} | |
| 64 | 新增: $node=[IO.Path]::GetFullPath($ExistingNode) | |
| 65 | 新增:} else { | |
| 66 | 新增: $nodeDir=Join-Path $tools 'node\24.22.2';PrivateDirectory $nodeDir | |
| 67 | 新增: $node=Join-Path $nodeDir 'node-v24.22.2-win-x64\node.exe' | |
| 68 | 新增: if(-not(Test-Path -LiteralPath $node)){Expand-Archive -LiteralPath $NodeArchive -DestinationPath $nodeDir} | |
| 69 | 新增: Assert-NoReparse $node | |
| 70 | 新增: if((Get-FileHash $node -Algorithm SHA256).Hash.ToLowerInvariant() -ne $nodeSha){throw 'Native Node changed.'} | |
| 71 | 新增:} | |
| 72 | 新增:$signature=Get-AuthenticodeSignature -FilePath $node | |
| 73 | 新增:if($signature.Status -ne 'Valid'){throw 'Native Node signature is invalid.'} | |
| 74 | 新增:$main=Join-Path $runtime 'node_modules\@kaitranntt\ccs\dist\ccs.js' | |
| 75 | 新增:$receiptDir=[IO.Path]::GetFullPath($ReceiptDirectory) | |
| 76 | 新增:$allowed=[IO.Path]::GetFullPath((Join-Path $env:USERPROFILE 'Cage\CLI')) | |
| 77 | 新增:if(-not $receiptDir.StartsWith($allowed+'\',[StringComparison]::OrdinalIgnoreCase)){throw 'Receipt staging must stay in the current user Cage CLI directory.'} | |
| 78 | 新增:PrivateDirectory $receiptDir | |
| 79 | 新增:$receipt=[ordered]@{version=1;node=$node;node_version='24.22.2';node_sha256=$nodeSha;main=$main;main_sha256=(Get-FileHash $main -Algorithm SHA256).Hash.ToLowerInvariant();manifest=$manifest;manifest_sha256=(Get-FileHash $manifest -Algorithm SHA256).Hash.ToLowerInvariant();ccs_version='8.11.0'} | |
| 80 | 新增:$temporary=Join-Path $receiptDir ('ccs-tools.'+[Guid]::NewGuid().ToString('N')+'.json') | |
| 81 | 新增:[IO.File]::WriteAllText($temporary,($receipt | ConvertTo-Json),(New-Object Text.UTF8Encoding($false))) | |
| 82 | 新增:Protect-Path $temporary $false | |
| 83 | 新增:Move-Item -LiteralPath $temporary -Destination (Join-Path $receiptDir 'ccs-tools.json') -Force | |
| 84 | 新增:Write-Output 'Native CCS runtime validated. Management must copy the staged ccs-tools.json into the readonly paired bridge. Existing CCS profiles and credentials were not imported or changed.' | |
| @@ -0,0 +1,122 @@ | ||
| 1 | 新增:# Run as the already paired ordinary GUI user. All packages are staged offline; | |
| 2 | 新增:# this installer changes only Cage-owned tool files and the bridge receipt. | |
| 3 | 新增:[CmdletBinding()] | |
| 4 | 新增:param( | |
| 5 | 新增: [Parameter(Mandatory)][string]$BundleDirectory, | |
| 6 | 新增: [Parameter(Mandatory)][string]$BridgeDirectory, | |
| 7 | 新增: [string]$ReceiptDirectory = (Join-Path $env:USERPROFILE 'Cage\CLI\install-receipts'), | |
| 8 | 新增: [switch]$WorkbenchSetup | |
| 9 | 新增:) | |
| 10 | 新增:$ErrorActionPreference = 'Stop' | |
| 11 | 新增:Set-StrictMode -Version Latest | |
| 12 | 新增:if (-not [System.Runtime.InteropServices.RuntimeInformation]::IsOSPlatform([System.Runtime.InteropServices.OSPlatform]::Windows)) { throw 'Native Windows is required.' } | |
| 13 | 新增:$user = [Security.Principal.WindowsIdentity]::GetCurrent() | |
| 14 | 新增:if ((New-Object Security.Principal.WindowsPrincipal($user)).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) { throw 'Use the paired ordinary GUI user.' } | |
| 15 | 新增:$manifest = Get-Content (Join-Path $PSScriptRoot 'cli-dependencies.json') -Raw | ConvertFrom-Json | |
| 16 | 新增:$bundle = [IO.Path]::GetFullPath($BundleDirectory) | |
| 17 | 新增:$bridge = [IO.Path]::GetFullPath($BridgeDirectory) | |
| 18 | 新增:if (-not (Test-Path (Join-Path $bridge 'Cage.GuestClipboard.exe') -PathType Leaf)) { throw 'The paired GUI bridge must be installed first.' } | |
| 19 | 新增:function Assert-NoReparse([string]$Path) { | |
| 20 | 新增: $item = Get-Item -LiteralPath $Path -Force | |
| 21 | 新增: while ($null -ne $item) { | |
| 22 | 新增: if ($item.Attributes -band [IO.FileAttributes]::ReparsePoint) { throw 'A Cage tool path is a reparse point.' } | |
| 23 | 新增: if ($item -is [IO.FileInfo]) { $item = $item.Directory } else { $item = $item.Parent } | |
| 24 | 新增: } | |
| 25 | 新增:} | |
| 26 | 新增:function Protect-Path([string]$Path, [bool]$Directory) { | |
| 27 | 新增: if ($Directory) { $acl = New-Object Security.AccessControl.DirectorySecurity } else { $acl = New-Object Security.AccessControl.FileSecurity } | |
| 28 | 新增: $acl.SetOwner($user.User); $acl.SetAccessRuleProtection($true, $false) | |
| 29 | 新增: foreach ($sid in @($user.User, [Security.Principal.SecurityIdentifier]'S-1-5-18', [Security.Principal.SecurityIdentifier]'S-1-5-32-544')) { | |
| 30 | 新增: if ($Directory) { $rule = New-Object Security.AccessControl.FileSystemAccessRule($sid,'FullControl','ContainerInherit,ObjectInherit','None','Allow') } | |
| 31 | 新增: else { $rule = New-Object Security.AccessControl.FileSystemAccessRule($sid,'FullControl','Allow') } | |
| 32 | 新增: $acl.AddAccessRule($rule) | |
| 33 | 新增: } | |
| 34 | 新增: Set-Acl -LiteralPath $Path -AclObject $acl | |
| 35 | 新增:} | |
| 36 | 新增:function New-PrivateDirectory([string]$Path) { | |
| 37 | 新增: $parent = [IO.DirectoryInfo]$Path | |
| 38 | 新增: while (-not $parent.Exists) { $parent = $parent.Parent; if ($null -eq $parent) { throw 'A Cage tool parent is invalid.' } } | |
| 39 | 新增: Assert-NoReparse $parent.FullName | |
| 40 | 新增: if (-not (Test-Path -LiteralPath $Path)) { New-Item -ItemType Directory -Path $Path | Out-Null } | |
| 41 | 新增: Assert-NoReparse $Path; Protect-Path $Path $true | |
| 42 | 新增:} | |
| 43 | 新增:function Check-Package($Entry) { | |
| 44 | 新增: $path = Join-Path $bundle $Entry.filename | |
| 45 | 新增: Assert-NoReparse $path | |
| 46 | 新增: if ((Get-FileHash -LiteralPath $path -Algorithm SHA256).Hash.ToLowerInvariant() -ne $Entry.sha256) { throw 'An offline native package failed its fixed checksum.' } | |
| 47 | 新增: return $path | |
| 48 | 新增:} | |
| 49 | 新增:$packages = @{} | |
| 50 | 新增:foreach ($name in @('uv','python','claude','git')) { $packages[$name] = Check-Package $manifest.$name } | |
| 51 | 新增:foreach ($name in @('claude','git')) { | |
| 52 | 新增: $signature = Get-AuthenticodeSignature -FilePath $packages[$name] | |
| 53 | 新增: if ($signature.Status -ne 'Valid') { throw 'An official Windows executable has an invalid Authenticode signature.' } | |
| 54 | 新增: if ($name -eq 'claude' -and $signature.SignerCertificate.Subject -notmatch 'Anthropic,? PBC') { throw 'The native Claude binary has the wrong signer.' } | |
| 55 | 新增:} | |
| 56 | 新增:$tools = Join-Path $env:USERPROFILE 'Cage\CLI\tools' | |
| 57 | 新增:New-PrivateDirectory $tools | |
| 58 | 新增:$uvDir = Join-Path $tools ('uv\' + $manifest.uv.version) | |
| 59 | 新增:New-PrivateDirectory $uvDir | |
| 60 | 新增:$uv = Join-Path $uvDir 'uv.exe' | |
| 61 | 新增:if (-not (Test-Path -LiteralPath $uv)) { Expand-Archive -LiteralPath $packages.uv -DestinationPath $uvDir } | |
| 62 | 新增:Assert-NoReparse $uv | |
| 63 | 新增:Add-Type -AssemblyName System.IO.Compression.FileSystem | |
| 64 | 新增:$zip = [IO.Compression.ZipFile]::OpenRead($packages.uv) | |
| 65 | 新增:try { | |
| 66 | 新增: $entry = $zip.Entries | Where-Object { $_.FullName -eq 'uv.exe' } | Select-Object -First 1 | |
| 67 | 新增: if ($null -eq $entry) { throw 'The fixed uv archive has no native executable.' } | |
| 68 | 新增: $reader = $entry.Open(); $hasher = [Security.Cryptography.SHA256]::Create() | |
| 69 | 新增: try { $expected = ([BitConverter]::ToString($hasher.ComputeHash($reader))).Replace('-','').ToLowerInvariant() } finally { $reader.Dispose(); $hasher.Dispose() } | |
| 70 | 新增: if ((Get-FileHash $uv -Algorithm SHA256).Hash.ToLowerInvariant() -ne $expected) { throw 'The Cage-owned uv executable changed.' } | |
| 71 | 新增:} finally { $zip.Dispose() } | |
| 72 | 新增:if ((& $uv --version) -notmatch ('^uv ' + [Regex]::Escape($manifest.uv.version) + '(?: |$)')) { throw 'The offline uv version does not match.' } | |
| 73 | 新增:$pythonDir = Join-Path $tools 'python' | |
| 74 | 新增:New-PrivateDirectory $pythonDir | |
| 75 | 新增:$pythonMeta = Join-Path $tools ('python-' + $manifest.python.version + '.json') | |
| 76 | 新增:$download = [ordered]@{name='cpython';arch=@{family='x86_64';variant=$null};os='windows';libc='none';major=3;minor=13;patch=18;prerelease='';url=([Uri]$packages.python).AbsoluteUri;sha256=$manifest.python.sha256;variant=$null;build='20261026'} | |
| 77 | 新增:$metadata = @{}; $metadata[$manifest.python.key] = $download | |
| 78 | 新增:[IO.File]::WriteAllText($pythonMeta, ($metadata | ConvertTo-Json -Depth 5), (New-Object Text.UTF8Encoding($false))) | |
| 79 | 新增:Protect-Path $pythonMeta $false | |
| 80 | 新增:$oldCache = [Environment]::GetEnvironmentVariable('UV_PYTHON_CACHE_DIR', 'Process') | |
| 81 | 新增:try { | |
| 82 | 新增: [Environment]::SetEnvironmentVariable('UV_PYTHON_CACHE_DIR', $null, 'Process') | |
| 83 | 新增: & $uv python install $manifest.python.key --install-dir $pythonDir --no-bin --no-registry --no-config --offline --python-downloads-json-url $pythonMeta | |
| 84 | 新增: if ($LASTEXITCODE -ne 0) { throw 'Offline uv Python installation failed.' } | |
| 85 | 新增:} finally { [Environment]::SetEnvironmentVariable('UV_PYTHON_CACHE_DIR', $oldCache, 'Process') } | |
| 86 | 新增:$python = Join-Path $pythonDir ($manifest.python.key + '\python.exe') | |
| 87 | 新增:Assert-NoReparse $python | |
| 88 | 新增:if ((& $python -X utf8 -I -c 'import platform; print(platform.python_version())') -ne $manifest.python.version) { throw 'The native Python version does not match.' } | |
| 89 | 新增:$gitDir = Join-Path $tools ('git\' + $manifest.git.version) | |
| 90 | 新增:if (-not (Test-Path (Join-Path $gitDir 'bin\bash.exe'))) { | |
| 91 | 新增: New-PrivateDirectory $gitDir | |
| 92 | 新增: $extract = Start-Process -FilePath $packages.git -ArgumentList @('-y', ('-o"' + $gitDir + '"')) -Wait -PassThru -NoNewWindow | |
| 93 | 新增: if ($extract.ExitCode -ne 0) { throw 'Portable Git extraction failed.' } | |
| 94 | 新增:} | |
| 95 | 新增:$bash = Join-Path $gitDir 'bin\bash.exe'; Assert-NoReparse $bash | |
| 96 | 新增:$claudeDir = Join-Path $tools ('claude\' + $manifest.claude.version) | |
| 97 | 新增:New-PrivateDirectory $claudeDir | |
| 98 | 新增:$claude = Join-Path $claudeDir 'claude.exe' | |
| 99 | 新增:if (-not (Test-Path -LiteralPath $claude)) { [IO.File]::Copy($packages.claude, $claude, $false) } | |
| 100 | 新增:if ((Get-FileHash -LiteralPath $claude -Algorithm SHA256).Hash.ToLowerInvariant() -ne $manifest.claude.sha256) { throw 'The Cage-owned native Claude binary changed.' } | |
| 101 | 新增:# The official native binary is used as a versioned custom launcher. No default | |
| 102 | 新增:# Claude account, existing installer, project, settings or history is replaced. | |
| 103 | 新增:$receipt = [ordered]@{version=1;python=$python;python_version=$manifest.python.version;python_sha256=(Get-FileHash $python -Algorithm SHA256).Hash.ToLowerInvariant();claude=$claude;claude_version=$manifest.claude.version;claude_sha256=$manifest.claude.sha256;git_bash=$bash;git_bash_sha256=(Get-FileHash $bash -Algorithm SHA256).Hash.ToLowerInvariant();uv_version=$manifest.uv.version} | |
| 104 | 新增:Assert-NoReparse $bridge | |
| 105 | 新增:if ($WorkbenchSetup) { | |
| 106 | 新增: # The provisioning process owns this file and its directory. The paired | |
| 107 | 新增: # user can write the receipt, but cannot replace the file or change its ACL. | |
| 108 | 新增: $staged = Join-Path $bridge 'setup-packages\cli-receipt.in' | |
| 109 | 新增: Assert-NoReparse $staged | |
| 110 | 新增: [IO.File]::WriteAllText($staged, ($receipt | ConvertTo-Json), (New-Object Text.UTF8Encoding($false))) | |
| 111 | 新增: return | |
| 112 | 新增:} | |
| 113 | 新增:$receiptDir = [IO.Path]::GetFullPath($ReceiptDirectory) | |
| 114 | 新增:$receiptRoot = [IO.Path]::GetFullPath((Join-Path $env:USERPROFILE 'Cage\CLI')) | |
| 115 | 新增:if (-not $receiptDir.StartsWith($receiptRoot + '\', [StringComparison]::OrdinalIgnoreCase)) { throw 'The receipt staging directory must be inside the current user Cage CLI directory.' } | |
| 116 | 新增:New-PrivateDirectory $receiptDir | |
| 117 | 新增:$target = Join-Path $receiptDir 'cli-tools.json' | |
| 118 | 新增:$temporary = Join-Path $receiptDir ('cli-tools.' + [Guid]::NewGuid().ToString('N') + '.json') | |
| 119 | 新增:[IO.File]::WriteAllText($temporary, ($receipt | ConvertTo-Json), (New-Object Text.UTF8Encoding($false))) | |
| 120 | 新增:Protect-Path $temporary $false | |
| 121 | 新增:Move-Item -LiteralPath $temporary -Destination $target -Force | |
| 122 | 新增:Write-Output 'Native Cage CLI tools installed. Management must copy the staged receipt into the readonly paired bridge, then restart only that bridge. Official account login remains user-controlled.' | |
| @@ -0,0 +1,76 @@ | ||
| 1 | 新增:#requires -Version 5.1 | |
| 2 | 新增:#requires -RunAsAdministrator | |
| 3 | 新增:[CmdletBinding(SupportsShouldProcess)] | |
| 4 | 新增:param( | |
| 5 | 新增: [Parameter(Mandatory)][string]$ProfilePath, | |
| 6 | 新增: [Parameter(Mandatory)][pscredential]$GuestAdministrator, | |
| 7 | 新增: [Parameter(Mandatory)][string]$AgentPath, | |
| 8 | 新增: [Parameter(Mandatory)][string]$WintunPath, | |
| 9 | 新增: [Parameter(Mandatory)][string]$WintunLicense, | |
| 10 | 新增: [object]$HostEnrollment | |
| 11 | 新增:) | |
| 12 | 新增:$ErrorActionPreference='Stop';$ProgressPreference='SilentlyContinue' | |
| 13 | 新增:$binding=Get-Content -LiteralPath $ProfilePath -Raw|ConvertFrom-Json | |
| 14 | 新增:if($HostEnrollment -and [guid]$HostEnrollment.VMID -ne [guid]$binding.vm_id){throw 'Original host enrollment does not match this packet bridge.'} | |
| 15 | 新增:$vm=Get-VM -Id ([guid]$binding.vm_id) | |
| 16 | 新增:if($binding.version -ne 1 -or $vm.State -ne 'Running' -or $binding.gui_user_sid -notmatch '^S-1-5-21-' -or | |
| 17 | 新增: @(Get-VMNetworkAdapter -VM $vm).Count -ne 0 -or $binding.network_pairing_file){throw 'Use the existing running zero-NIC guest binding without a prior packet pairing.'} | |
| 18 | 新增:if((Get-FileHash -LiteralPath $WintunPath -Algorithm SHA256).Hash -cne 'E5DA8447DC2C320EDC0FC52FA01885C103DE8C118481F683643CACC3220DAFCE'){throw 'Unexpected pinned Wintun payload.'} | |
| 19 | 新增:if((Get-AuthenticodeSignature -LiteralPath $WintunPath).Status -ne 'Valid'){throw 'Windows did not validate the official Wintun signature.'} | |
| 20 | 新增:if(!$PSCmdlet.ShouldProcess($vm.Id,'Install the separate SYSTEM packet bridge without adding a Hyper-V NIC')){return} | |
| 21 | 新增:$session=New-PSSession -VMId $vm.Id -Credential $GuestAdministrator | |
| 22 | 新增:try { | |
| 23 | 新增: $target=Invoke-Command -Session $session -ArgumentList $vm.Id,$binding.gui_user_sid -ScriptBlock { | |
| 24 | 新增: param($id,$sid) | |
| 25 | 新增: $ErrorActionPreference='Stop';$ProgressPreference='SilentlyContinue' | |
| 26 | 新增: if([guid](Get-ItemProperty -LiteralPath 'HKLM:\SOFTWARE\Microsoft\Virtual Machine\Guest\Parameters').VirtualMachineId -ne $id){throw 'guest_identity_mismatch'} | |
| 27 | 新增: $program=Join-Path $env:ProgramFiles ("Cage Guest Network\"+$id);$data=Join-Path $env:ProgramData ("Cage\PacketBridge\"+$id);$name="Cage-Packet-Bridge-$id" | |
| 28 | 新增: if((Test-Path -LiteralPath $program) -or (Test-Path -LiteralPath $data) -or (Get-ScheduledTask -TaskName $name -ErrorAction SilentlyContinue)){throw 'A packet deployment already exists; preserve its key and interface.'} | |
| 29 | 新增: foreach($directory in @($program,$data)){ | |
| 30 | 新增: $current=$directory;while($current){if(Test-Path -LiteralPath $current){if((Get-Item -LiteralPath $current -Force).Attributes -band [IO.FileAttributes]::ReparsePoint){throw 'Packet deployment paths must not traverse links.'}};$current=[IO.Path]::GetDirectoryName($current)} | |
| 31 | 新增: $null=New-Item -ItemType Directory -Path $directory -Force | |
| 32 | 新增: $acl=[Security.AccessControl.DirectorySecurity]::new();$acl.SetAccessRuleProtection($true,$false);$acl.SetOwner([Security.Principal.SecurityIdentifier]::new('S-1-5-32-544')) | |
| 33 | 新增: foreach($owner in @('S-1-5-18','S-1-5-32-544')){$acl.AddAccessRule([Security.AccessControl.FileSystemAccessRule]::new([Security.Principal.SecurityIdentifier]::new($owner),'FullControl','ContainerInherit,ObjectInherit','None','Allow'))} | |
| 34 | 新增: if($directory -eq $program){$acl.AddAccessRule([Security.AccessControl.FileSystemAccessRule]::new([Security.Principal.SecurityIdentifier]::new($sid),'ReadAndExecute','ContainerInherit,ObjectInherit','None','Allow'))} | |
| 35 | 新增: Set-Acl -LiteralPath $directory -AclObject $acl | |
| 36 | 新增: } | |
| 37 | 新增: [pscustomobject]@{Program=$program;Data=$data;Task=$name} | |
| 38 | 新增: } | |
| 39 | 新增: Copy-Item -LiteralPath $AgentPath -Destination (Join-Path $target.Program 'Cage.GuestNetwork.exe') -ToSession $session | |
| 40 | 新增: Copy-Item -LiteralPath $WintunPath -Destination (Join-Path $target.Program 'wintun.dll') -ToSession $session | |
| 41 | 新增: Copy-Item -LiteralPath $WintunLicense -Destination (Join-Path $target.Program 'WINTUN-LICENSE.txt') -ToSession $session | |
| 42 | 新增: $secret=New-Object byte[] 32;$random=[Security.Cryptography.RandomNumberGenerator]::Create();$random.GetBytes($secret);$random.Dispose() | |
| 43 | 新增: try { | |
| 44 | 新增: Invoke-Command -Session $session -ArgumentList $target.Program,$target.Data,$secret -ScriptBlock { | |
| 45 | 新增: param($program,$data,[byte[]]$secret) | |
| 46 | 新增: $ErrorActionPreference='Stop';$admin=[Security.Principal.SecurityIdentifier]::new('S-1-5-32-544') | |
| 47 | 新增: foreach($entry in (Get-ChildItem -LiteralPath $program -File)){$acl=Get-Acl -LiteralPath $entry.FullName;$acl.SetOwner($admin);Set-Acl -LiteralPath $entry.FullName -AclObject $acl} | |
| 48 | 新增: $acl=[Security.AccessControl.FileSecurity]::new();$acl.SetAccessRuleProtection($true,$false);$acl.SetOwner($admin) | |
| 49 | 新增: foreach($owner in @('S-1-5-18','S-1-5-32-544')){$acl.AddAccessRule([Security.AccessControl.FileSystemAccessRule]::new([Security.Principal.SecurityIdentifier]::new($owner),'FullControl','Allow'))} | |
| 50 | 新增: $stream=[IO.FileStream]::new((Join-Path $data 'packet.bin'),[IO.FileMode]::CreateNew,[Security.AccessControl.FileSystemRights]::Write,[IO.FileShare]::None,4096,[IO.FileOptions]::None,$acl) | |
| 51 | 新增: try{$stream.Write($secret,0,$secret.Length);$stream.Flush($true)}finally{$stream.Dispose()} | |
| 52 | 新增: if((Get-FileHash -LiteralPath (Join-Path $program 'wintun.dll') -Algorithm SHA256).Hash -cne 'E5DA8447DC2C320EDC0FC52FA01885C103DE8C118481F683643CACC3220DAFCE'){throw 'Guest Wintun transfer digest differs.'} | |
| 53 | 新增: } | |
| 54 | 新增: Add-Type -AssemblyName System.Security | |
| 55 | 新增: $entropy=[Security.Cryptography.SHA256]::Create().ComputeHash([Text.Encoding]::UTF8.GetBytes("Cage.HyperV.v1:$($vm.Id.ToString('D')):$($binding.gui_user_sid)")) | |
| 56 | 新增: $pair=Join-Path ([IO.Path]::GetDirectoryName($ProfilePath)) 'packet.dpapi';if(Test-Path -LiteralPath $pair){throw 'A host packet pairing already exists.'} | |
| 57 | 新增: if(!$HostEnrollment){[IO.File]::WriteAllBytes($pair,[Security.Cryptography.ProtectedData]::Protect($secret,$entropy,'CurrentUser'));Set-Acl -LiteralPath $pair -AclObject (Get-Acl -LiteralPath $binding.pairing_file)} | |
| 58 | 新增: $service='f4a4c1ce-3c9f-49f1-b7bf-82df6592c0fb';$key="HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Virtualization\GuestCommunicationServices\$service" | |
| 59 | 新增: if(Test-Path -LiteralPath $key){if((Get-ItemProperty -LiteralPath $key).ElementName -cne 'Cage Packet Guest Bridge v1'){throw 'The packet service GUID is owned by another application.'}} | |
| 60 | 新增: else{$null=New-Item -Path $key;New-ItemProperty -LiteralPath $key -Name ElementName -Value 'Cage Packet Guest Bridge v1' -PropertyType String|Out-Null} | |
| 61 | 新增: Invoke-Command -Session $session -ArgumentList $target.Program,$target.Data,$target.Task,$vm.Id,$binding.gui_user_sid -ScriptBlock { | |
| 62 | 新增: param($program,$data,$name,$vm,$sid) | |
| 63 | 新增: $exe=Join-Path $program 'Cage.GuestNetwork.exe';$key=Join-Path $data 'packet.bin' | |
| 64 | 新增: $action=New-ScheduledTaskAction -Execute $exe -Argument "serve-network --vm-id $vm --sid $sid --token-file `"$key`"" | |
| 65 | 新增: $principal=New-ScheduledTaskPrincipal -UserId 'S-1-5-18' -LogonType ServiceAccount -RunLevel Highest | |
| 66 | 新增: $settings=New-ScheduledTaskSettingsSet -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries -ExecutionTimeLimit ([TimeSpan]::Zero) -MultipleInstances IgnoreNew | |
| 67 | 新增: $null=Register-ScheduledTask -TaskName $name -Action $action -Principal $principal -Trigger (New-ScheduledTaskTrigger -AtStartup) -Settings $settings -Description "Cage protected packet bridge $vm $sid" | |
| 68 | 新增: } | |
| 69 | 新增: $binding|Add-Member -NotePropertyName network_pairing_file -NotePropertyValue $pair | |
| 70 | 新增: $stage=$ProfilePath+'.packet-stage';[IO.File]::WriteAllText($stage,($binding|ConvertTo-Json -Compress)+[Environment]::NewLine,[Text.UTF8Encoding]::new($false));Set-Acl -LiteralPath $stage -AclObject (Get-Acl -LiteralPath $ProfilePath);[IO.File]::Replace($stage,$ProfilePath,[Management.Automation.Language.NullString]::Value) | |
| 71 | 新增: Invoke-Command -Session $session -ArgumentList $target.Task -ScriptBlock {param($name);Start-ScheduledTask -TaskName $name} | |
| 72 | 新增: if($HostEnrollment){. (Join-Path $PSScriptRoot '../windows-host-enrollment.ps1');Send-CageHostEnrollmentKey $HostEnrollment 'packet' $binding.gui_user_sid $secret} | |
| 73 | 新增: if(@(Get-VMNetworkAdapter -VM (Get-VM -Id $vm.Id)).Count -ne 0){throw 'Hyper-V networking changed during packet setup.'} | |
| 74 | 新增: [pscustomobject]@{PacketTaskRegistered=$true;SystemKeyProtected=$true;IndependentHostPairing=$true;HyperVAdapters=0;NetworkConfigured=$false} | |
| 75 | 新增: }finally{[Array]::Clear($secret,0,$secret.Length)} | |
| 76 | 新增:}finally{Remove-PSSession $session} | |
| @@ -0,0 +1,124 @@ | ||
| 1 | 新增:#requires -Version 5.1 | |
| 2 | 新增:#requires -RunAsAdministrator | |
| 3 | 新增:<# | |
| 4 | 新增:.SYNOPSIS | |
| 5 | 新增:Bind one existing offline Hyper-V guest and its existing interactive user. | |
| 6 | 新增:.DESCRIPTION | |
| 7 | 新增:PowerShell Direct is only the authenticated management transport. The agent is | |
| 8 | 新增:registered as an InteractiveToken, Limited task for the supplied SID; it cannot | |
| 9 | 新增:use a management/Session0 clipboard. This script does not log a user in, create | |
| 10 | 新增:accounts, change VM networking, accept licenses or replace a running agent. | |
| 11 | 新增:Supply a new protected host profile directory. The returned binding contains | |
| 12 | 新增:only paths and identities; its separate pairing is DPAPI CurrentUser protected. | |
| 13 | 新增:#> | |
| 14 | 新增:[CmdletBinding(SupportsShouldProcess)] | |
| 15 | 新增:param( | |
| 16 | 新增: [Parameter(Mandatory)][guid]$VMId, | |
| 17 | 新增: [Parameter(Mandatory)][string]$InstanceDirectory, | |
| 18 | 新增: [Parameter(Mandatory)][ValidatePattern('^S-1-5-21-[0-9]+-[0-9]+-[0-9]+-[0-9]+$')][string]$GUIUserSID, | |
| 19 | 新增: [Parameter(Mandatory)][pscredential]$GuestAdministrator, | |
| 20 | 新增: [Parameter(Mandatory)][string]$PayloadDirectory, | |
| 21 | 新增: [Parameter(Mandatory)][string]$HostProfileDirectory, | |
| 22 | 新增: [string]$HostUserSID = ([Security.Principal.WindowsIdentity]::GetCurrent().User.Value), | |
| 23 | 新增: [object]$HostEnrollment | |
| 24 | 新增:) | |
| 25 | 新增:$ErrorActionPreference='Stop' | |
| 26 | 新增:$ProgressPreference='SilentlyContinue' | |
| 27 | 新增:if($HostUserSID -notmatch '^S-1-(5-21|12-1)-(\d+-){3}\d+$' -or | |
| 28 | 新增: ([Security.Principal.WindowsIdentity]::GetCurrent().User.Value -cne $HostUserSID -and !$HostEnrollment)){throw 'Another host user requires the original enrollment process.'} | |
| 29 | 新增:if($HostEnrollment -and ($HostEnrollment.HostSID -cne $HostUserSID -or [guid]$HostEnrollment.VMID -ne $VMId)){throw 'Original host enrollment does not match this bridge.'} | |
| 30 | 新增:$service='f4a4c1ce-3c9f-49f1-b7bf-82df6592c0fa' | |
| 31 | 新增:function Assert-LocalAncestors([string]$Path){ | |
| 32 | 新增: if(![IO.Path]::IsPathRooted($Path) -or $Path.StartsWith('\\') -or [IO.DriveInfo]::new([IO.Path]::GetPathRoot($Path)).DriveType -ne 'Fixed'){throw 'A local fixed-disk path is required.'} | |
| 33 | 新增: $current=$Path | |
| 34 | 新增: while($current){if(Test-Path -LiteralPath $current){if((Get-Item -LiteralPath $current -Force).Attributes -band [IO.FileAttributes]::ReparsePoint){throw 'Deployment paths must not traverse links.'}};$current=[IO.Path]::GetDirectoryName($current)} | |
| 35 | 新增:} | |
| 36 | 新增:$vm=Get-VM -Id $VMId | |
| 37 | 新增:$instance=Get-Item -LiteralPath $InstanceDirectory | |
| 38 | 新增:$payload=Get-Item -LiteralPath $PayloadDirectory | |
| 39 | 新增:if ($VMId -eq [guid]::Empty -or $vm.State -ne 'Running' -or $instance -isnot [IO.DirectoryInfo] -or | |
| 40 | 新增: $payload -isnot [IO.DirectoryInfo] -or $instance.Attributes -band [IO.FileAttributes]::ReparsePoint -or | |
| 41 | 新增: !($vm.ConfigurationLocation -eq $instance.FullName -or $vm.ConfigurationLocation.StartsWith($instance.FullName.TrimEnd('\')+'\',[StringComparison]::OrdinalIgnoreCase)) -or | |
| 42 | 新增: @(Get-VMNetworkAdapter -VM $vm).Count -ne 0) { throw 'Supply the exact running, retained zero-NIC guest and its private instance directory.' } | |
| 43 | 新增:$profile=$ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath($HostProfileDirectory) | |
| 44 | 新增:foreach($path in @($profile,$instance.FullName,$payload.FullName)){Assert-LocalAncestors $path} | |
| 45 | 新增:if (!(Test-Path -LiteralPath ([IO.Path]::GetDirectoryName($profile))) -or (Test-Path -LiteralPath $profile)) { throw 'Supply a new host profile directory under an existing local parent.' } | |
| 46 | 新增:foreach($file in @('Cage.GuestClipboard.exe','cage-guest-files.exe')) { | |
| 47 | 新增: $entry=Get-Item -LiteralPath (Join-Path $payload.FullName $file) | |
| 48 | 新增: if($entry -isnot [IO.FileInfo] -or $entry.Attributes -band [IO.FileAttributes]::ReparsePoint){throw 'The fixed GUI agent and file helper payloads are required.'} | |
| 49 | 新增:} | |
| 50 | 新增:if(!$PSCmdlet.ShouldProcess($VMId,'Install a protected GUI clipboard bridge and bind this host user')){return} | |
| 51 | 新增:$session=New-PSSession -VMId $VMId -Credential $GuestAdministrator | |
| 52 | 新增:try { | |
| 53 | 新增: $checked=Invoke-Command -Session $session -ArgumentList $VMId,$GUIUserSID -ScriptBlock { | |
| 54 | 新增: param($expected,$sid) | |
| 55 | 新增: $ErrorActionPreference='Stop';$ProgressPreference='SilentlyContinue' | |
| 56 | 新增: $kvp=Get-ItemProperty -LiteralPath 'HKLM:\SOFTWARE\Microsoft\Virtual Machine\Guest\Parameters' -Name VirtualMachineId | |
| 57 | 新增: if([guid]$kvp.VirtualMachineId -ne $expected){throw 'guest_identity_mismatch'} | |
| 58 | 新增: $users=@(Get-LocalUser | Where-Object {$_.SID.Value -eq $sid -and $_.Enabled}) | |
| 59 | 新增: if($users.Count -ne 1){throw 'The independently selected GUI SID is not an enabled existing local user.'} | |
| 60 | 新增: $name="Cage-GUI-Bridge-$expected-$sid" | |
| 61 | 新增: if(Get-ScheduledTask -TaskName $name -ErrorAction SilentlyContinue){throw 'A bridge task already exists; preserve the running user session and use its existing binding.'} | |
| 62 | 新增: $program=Join-Path $env:ProgramFiles ("Cage Guest Bridge\"+$expected) | |
| 63 | 新增: $data=Join-Path $env:ProgramData ("Cage\GuestBridge\"+$expected) | |
| 64 | 新增: foreach($directory in @($program,$data)){$current=$directory;while($current){if(Test-Path -LiteralPath $current){if((Get-Item -LiteralPath $current -Force).Attributes -band [IO.FileAttributes]::ReparsePoint){throw 'Guest deployment paths must not traverse links.'}};$current=[IO.Path]::GetDirectoryName($current)}} | |
| 65 | 新增: if((Test-Path -LiteralPath $program) -or (Test-Path -LiteralPath $data)){throw 'A guest bridge deployment already exists; preserve it.'} | |
| 66 | 新增: foreach($directory in @($program,$data)){ | |
| 67 | 新增: $null=New-Item -ItemType Directory -Path $directory -Force | |
| 68 | 新增: $acl=[Security.AccessControl.DirectorySecurity]::new();$acl.SetAccessRuleProtection($true,$false) | |
| 69 | 新增: foreach($owner in @('S-1-5-18','S-1-5-32-544')){$acl.AddAccessRule([Security.AccessControl.FileSystemAccessRule]::new([Security.Principal.SecurityIdentifier]::new($owner),'FullControl','ContainerInherit,ObjectInherit','None','Allow'))} | |
| 70 | 新增: $acl.AddAccessRule([Security.AccessControl.FileSystemAccessRule]::new([Security.Principal.SecurityIdentifier]::new($sid),'ReadAndExecute','ContainerInherit,ObjectInherit','None','Allow')) | |
| 71 | 新增: Set-Acl -LiteralPath $directory -AclObject $acl | |
| 72 | 新增: } | |
| 73 | 新增: [pscustomobject]@{Program=$program;Data=$data;Task=$name;User=$users[0].Name} | |
| 74 | 新增: } | |
| 75 | 新增: # Copy only the caller-selected payload directory. Optional Node/browser | |
| 76 | 新增: # dependencies remain local to this deployment and never need a guest NIC. | |
| 77 | 新增: Get-ChildItem -LiteralPath $payload.FullName -File|ForEach-Object { | |
| 78 | 新增: if($_.Attributes -band [IO.FileAttributes]::ReparsePoint){throw 'Payload links are not allowed.'} | |
| 79 | 新增: Copy-Item -LiteralPath $_.FullName -Destination (Join-Path $checked.Program $_.Name) -ToSession $session | |
| 80 | 新增: } | |
| 81 | 新增: $secret=New-Object byte[] 32;$random=[Security.Cryptography.RandomNumberGenerator]::Create();$random.GetBytes($secret);$random.Dispose() | |
| 82 | 新增: try { | |
| 83 | 新增: Invoke-Command -Session $session -ArgumentList $checked.Data,$secret,$GUIUserSID -ScriptBlock { | |
| 84 | 新增: param($data,[byte[]]$secret,$sid) | |
| 85 | 新增: $file=Join-Path $data 'pairing.bin';[IO.File]::WriteAllBytes($file,$secret) | |
| 86 | 新增: $acl=[Security.AccessControl.FileSecurity]::new();$acl.SetAccessRuleProtection($true,$false) | |
| 87 | 新增: foreach($owner in @('S-1-5-18','S-1-5-32-544')){$acl.AddAccessRule([Security.AccessControl.FileSystemAccessRule]::new([Security.Principal.SecurityIdentifier]::new($owner),'FullControl','Allow'))} | |
| 88 | 新增: $acl.AddAccessRule([Security.AccessControl.FileSystemAccessRule]::new([Security.Principal.SecurityIdentifier]::new($sid),'Read','Allow'));Set-Acl -LiteralPath $file -AclObject $acl | |
| 89 | 新增: } | |
| 90 | 新增: $hostSID=[Security.Principal.SecurityIdentifier]::new($HostUserSID) | |
| 91 | 新增: $hostOwner=if($HostEnrollment){[Security.Principal.SecurityIdentifier]::new('S-1-5-32-544')}else{$hostSID} | |
| 92 | 新增: $acl=[Security.AccessControl.DirectorySecurity]::new();$acl.SetAccessRuleProtection($true,$false);$acl.SetOwner($hostOwner) | |
| 93 | 新增: foreach($sid in @($hostSID,[Security.Principal.SecurityIdentifier]::new('S-1-5-18'),[Security.Principal.SecurityIdentifier]::new('S-1-5-32-544'))){$acl.AddAccessRule([Security.AccessControl.FileSystemAccessRule]::new($sid,'FullControl','ContainerInherit,ObjectInherit','None','Allow'))} | |
| 94 | 新增: $null=New-Item -ItemType Directory -Path $profile;Set-Acl -LiteralPath $profile -AclObject $acl | |
| 95 | 新增: foreach($entry in (Get-ChildItem -LiteralPath $payload.FullName -File)){Copy-Item -LiteralPath $entry.FullName -Destination (Join-Path $profile $entry.Name)} | |
| 96 | 新增: Add-Type -AssemblyName System.Security | |
| 97 | 新增: $entropy=[Security.Cryptography.SHA256]::Create().ComputeHash([Text.Encoding]::UTF8.GetBytes("Cage.HyperV.v1:$($VMId.ToString('D')):$GUIUserSID")) | |
| 98 | 新增: $pairing=Join-Path $profile 'pairing.dpapi' | |
| 99 | 新增: # The relay verifies protected file ACLs independently before decrypting. | |
| 100 | 新增: $fileACL=[Security.AccessControl.FileSecurity]::new();$fileACL.SetAccessRuleProtection($true,$false);$fileACL.SetOwner($hostOwner) | |
| 101 | 新增: foreach($sid in @($hostSID,[Security.Principal.SecurityIdentifier]::new('S-1-5-18'),[Security.Principal.SecurityIdentifier]::new('S-1-5-32-544'))){$fileACL.AddAccessRule([Security.AccessControl.FileSystemAccessRule]::new($sid,'FullControl','Allow'))} | |
| 102 | 新增: if(!$HostEnrollment){[IO.File]::WriteAllBytes($pairing,[Security.Cryptography.ProtectedData]::Protect($secret,$entropy,'CurrentUser'));Set-Acl -LiteralPath $pairing -AclObject $fileACL} | |
| 103 | 新增: $key="HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Virtualization\GuestCommunicationServices\$service" | |
| 104 | 新增: if(Test-Path -LiteralPath $key){if((Get-ItemProperty -LiteralPath $key).ElementName -cne 'Cage GUI Guest Bridge v1'){throw 'The fixed service GUID is owned by another application.'}} | |
| 105 | 新增: else{$null=New-Item -Path $key;New-ItemProperty -LiteralPath $key -Name ElementName -Value 'Cage GUI Guest Bridge v1' -PropertyType String|Out-Null} | |
| 106 | 新增: $task=Invoke-Command -Session $session -ArgumentList $checked.Program,$checked.Data,$checked.Task,$GUIUserSID,$VMId -ScriptBlock { | |
| 107 | 新增: param($program,$data,$name,$sid,$vm) | |
| 108 | 新增: $executable=Join-Path $program 'Cage.GuestClipboard.exe';$token=Join-Path $data 'pairing.bin' | |
| 109 | 新增: $action=New-ScheduledTaskAction -Execute $executable -Argument "serve --vm-id $vm --sid $sid --token-file `"$token`"" | |
| 110 | 新增: $trigger=New-ScheduledTaskTrigger -AtLogOn -User $sid | |
| 111 | 新增: $principal=New-ScheduledTaskPrincipal -UserId $sid -LogonType Interactive -RunLevel Limited | |
| 112 | 新增: $settings=New-ScheduledTaskSettingsSet -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries -ExecutionTimeLimit ([TimeSpan]::Zero) -MultipleInstances IgnoreNew | |
| 113 | 新增: $null=Register-ScheduledTask -TaskName $name -Action $action -Trigger $trigger -Principal $principal -Settings $settings -Description "Cage protected GUI bridge $vm $sid" | |
| 114 | 新增: $gui=@(Get-CimInstance Win32_Process -Filter "Name='explorer.exe'"|Where-Object {$_.SessionId -gt 0}|ForEach-Object {Invoke-CimMethod -InputObject $_ -MethodName GetOwnerSid}|Where-Object {$_.Sid -eq $sid}).Count -gt 0 | |
| 115 | 新增: if($gui){Start-ScheduledTask -TaskName $name} | |
| 116 | 新增: [pscustomobject]@{Registered=$true;GUIAlreadyLoggedIn=$gui} | |
| 117 | 新增: } | |
| 118 | 新增: $binding=[ordered]@{version=1;vm_id=$VMId.ToString('D');gui_user_sid=$GUIUserSID;gui_user=$checked.User;instance_directory=$instance.FullName;relay_executable=(Join-Path $profile 'Cage.GuestClipboard.exe');pairing_file=$pairing} | |
| 119 | 新增: $path=Join-Path $profile 'windows-guest.json';[IO.File]::WriteAllText($path,($binding|ConvertTo-Json -Compress)+[Environment]::NewLine,[Text.UTF8Encoding]::new($false));Set-Acl -LiteralPath $path -AclObject $fileACL | |
| 120 | 新增: if($HostEnrollment){. (Join-Path $PSScriptRoot '../windows-host-enrollment.ps1');Send-CageHostEnrollmentKey $HostEnrollment 'gui' $GUIUserSID $secret} | |
| 121 | 新增: if(@(Get-VMNetworkAdapter -VM (Get-VM -Id $VMId)).Count -ne 0){throw 'VM networking changed during deployment.'} | |
| 122 | 新增: [pscustomobject]@{Profile=$path;VMId=$VMId;GUIUserSID=$GUIUserSID;TaskRegistered=$task.Registered;RequiresGUILogin=(!$task.GUIAlreadyLoggedIn)} | |
| 123 | 新增: } finally { [Array]::Clear($secret,0,$secret.Length) } | |
| 124 | 新增:} finally { Remove-PSSession $session } | |
| @@ -0,0 +1,184 @@ | ||
| 1 | 新增:#requires -Version 5.1 | |
| 2 | 新增:param( | |
| 3 | 新增: [Parameter(Mandatory)][string]$ProfilePath, | |
| 4 | 新增: [Parameter(Mandatory)][string]$CredentialFile, | |
| 5 | 新增: [Parameter(Mandatory)][string]$FixturePath, | |
| 6 | 新增: [Parameter(Mandatory)][string]$EvidenceDirectory, | |
| 7 | 新增: [switch]$SplitOnly, | |
| 8 | 新增: [switch]$PerfOnly | |
| 9 | 新增:) | |
| 10 | 新增:$ErrorActionPreference='Stop';$ProgressPreference='SilentlyContinue' | |
| 11 | 新增:[Console]::OutputEncoding=[Text.UTF8Encoding]::new($false) | |
| 12 | 新增:$utf8=[Text.UTF8Encoding]::new($false) | |
| 13 | 新增:$copiedFixtureText=$utf8.GetString([Convert]::FromBase64String('Q2FnZSBuYXRpdmUgY29weSDkuK3mlofwn5mC')) | |
| 14 | 新增:$binding=Get-Content -LiteralPath $ProfilePath -Raw|ConvertFrom-Json | |
| 15 | 新增:$vm=Get-VM -Id ([guid]$binding.vm_id) | |
| 16 | 新增:if($binding.version -ne 1 -or $vm.State -ne 'Running' -or @(Get-VMNetworkAdapter -VM $vm).Count -ne 0){throw 'The independently bound offline guest is not ready.'} | |
| 17 | 新增:$credential=Import-Clixml -LiteralPath $CredentialFile | |
| 18 | 新增:if(($credential.UserName -split '\\')[-1] -cne 'CageLabSetup'){throw 'The retained QA administrator identity does not match.'} | |
| 19 | 新增:$credential=[pscredential]::new('CageLabSetup',$credential.Password) | |
| 20 | 新增:$session=New-PSSession -VMId $vm.Id -Credential $credential | |
| 21 | 新增:$owned=[Collections.Generic.List[Diagnostics.Process]]::new();$tabs=[Collections.Generic.List[string]]::new() | |
| 22 | 新增:$results=[ordered]@{};$script:phase='starting' | |
| 23 | 新增:function Bridge([string]$Operation){ | |
| 24 | 新增: $s=[Diagnostics.ProcessStartInfo]::new();$s.FileName=$binding.relay_executable | |
| 25 | 新增: $s.Arguments='--relay-profile "'+$ProfilePath+'" '+$Operation | |
| 26 | 新增: $s.UseShellExecute=$false;$s.CreateNoWindow=$true;$s.RedirectStandardInput=$true;$s.RedirectStandardOutput=$true;$s.RedirectStandardError=$true;$s.StandardOutputEncoding=$utf8 | |
| 27 | 新增: $p=[Diagnostics.Process]::Start($s);$owned.Add($p);$null=$p.StandardError.ReadToEndAsync();return $p | |
| 28 | 新增:} | |
| 29 | 新增:function Send($p,$value){$bytes=$utf8.GetBytes((ConvertTo-Json -InputObject $value -Compress -Depth 12)+"`n");$p.StandardInput.BaseStream.Write($bytes,0,$bytes.Length);$p.StandardInput.BaseStream.Flush()} | |
| 30 | 新增:function Read($p){$pending=$p.StandardOutput.ReadLineAsync();if(!$pending.Wait(45000) -or !$pending.Result){throw ('The owned browser response did not complete: '+$script:phase)};return $pending.Result|ConvertFrom-Json} | |
| 31 | 新增:function Call([string]$Path,$Payload=@{},[string]$Method='POST'){Send $browser @{method=$Method;path=$Path;input=$Payload};$value=Read $browser;if($value.error){throw ($script:phase+': '+$value.error)};return $value} | |
| 32 | 新增:function State {return Invoke-Command -Session $session -ArgumentList $guestDirectory -ScriptBlock {param($dir);$file=Join-Path $dir 'fixture-state.json';if(Test-Path -LiteralPath $file){foreach($report in (Get-Content -LiteralPath $file -Raw|ConvertFrom-Json)){$report}}}} | |
| 33 | 新增:function Frame([string]$Name){ | |
| 34 | 新增: $f=Call '/frame' @{} 'GET';if($f.width -lt 1 -or $f.height -lt 1 -or !$f.target){throw 'The native frame receipt is invalid.'} | |
| 35 | 新增: Add-Type -AssemblyName System.Drawing | |
| 36 | 新增: $image=[Drawing.Bitmap]::new($f.width,$f.height);$g=[Drawing.Graphics]::FromImage($image) | |
| 37 | 新增: try { | |
| 38 | 新增: $parts=@();if($f.jpeg -or $f.png){$parts+=@([pscustomobject]@{jpeg=$f.jpeg;png=$f.png;x=0;y=0;width=$f.width;height=$f.height})};$parts+=@($f.panes);$parts+=@($f.overlays) | |
| 39 | 新增: foreach($part in $parts){if(!$part){continue};$encoded=if($part.png){$part.png}else{$part.jpeg};$stream=[IO.MemoryStream]::new([Convert]::FromBase64String($encoded));$piece=[Drawing.Image]::FromStream($stream);try{$g.DrawImage($piece,[Drawing.Rectangle]::new($part.x,$part.y,$part.width,$part.height))}finally{$piece.Dispose();$stream.Dispose()}} | |
| 40 | 新增: $image.Save((Join-Path $EvidenceDirectory ($Name+'.png')),[Drawing.Imaging.ImageFormat]::Png) | |
| 41 | 新增: } finally {$g.Dispose();$image.Dispose()} | |
| 42 | 新增: return $f | |
| 43 | 新增:} | |
| 44 | 新增:function Pointer($Frame,[int]$X,[int]$Y,[int]$Mask){$null=Call '/input' @{kind='pointer';target=$Frame.target;x=$X;y=$Y;mask=$Mask}} | |
| 45 | 新增:function Click($Frame,[double]$X,[double]$Y,[int]$Mask=1){Pointer $Frame ([int]($X*$Frame.scale)) ([int]($Y*$Frame.scale)) $Mask;Pointer $Frame ([int]($X*$Frame.scale)) ([int]($Y*$Frame.scale)) 0} | |
| 46 | 新增:function Key($Frame,[uint32]$Symbol,[bool]$Down){$null=Call '/input' @{kind='key';target=$Frame.target;keysym=$Symbol;down=$Down}} | |
| 47 | 新增:function Text($Frame,[string]$Value){foreach($char in $Value.ToCharArray()){Key $Frame ([uint32][char]$char) $true;Key $Frame ([uint32][char]$char) $false}} | |
| 48 | 新增:function ReadAck([long]$Serial){while($true){$r=Read $clipboard;if($r.error){throw 'The GUI clipboard write failed.'};if($r.ack -eq $Serial){return}}} | |
| 49 | 新增:function NativeKeys { | |
| 50 | 新增: $probe=Bridge 'terminal';Send $probe @{action='open';workspace='home';shell='powershell';cols=160;rows=25};if(!(Read $probe).ready){throw 'The GUI native key probe is unavailable.'} | |
| 51 | 新增: $marker='__BN_'+[guid]::NewGuid().ToString('N').Substring(0,8)+'=' | |
| 52 | 新增: $code='Add-Type -TypeDefinition ''using System.Runtime.InteropServices; public static class BrowserKeyProbe { [DllImport("user32.dll")] public static extern short GetAsyncKeyState(int key); }'';$ctrl=if(([BrowserKeyProbe]::GetAsyncKeyState(17)-band 32768)-ne 0){"held"}else{"released"};$mouse=if(([BrowserKeyProbe]::GetAsyncKeyState(1)-band 32768)-ne 0){"held"}else{"released"};[Console]::WriteLine("'+$marker+'"+$ctrl+"_"+$mouse)' | |
| 53 | 新增: $command='powershell.exe -NoProfile -EncodedCommand '+[Convert]::ToBase64String([Text.Encoding]::Unicode.GetBytes($code))+"`r" | |
| 54 | 新增: Send $probe @{action='input';data=[Convert]::ToBase64String($utf8.GetBytes($command))};$output='' | |
| 55 | 新增: while($true){$r=Read $probe;if($r.error -or $null -ne $r.exit){throw 'The GUI native key probe exited.'};if($r.data){$output+=$utf8.GetString([Convert]::FromBase64String($r.data));$match=[regex]::Match($output,[regex]::Escape($marker)+'(held|released)_(held|released)');if($match.Success){return @{ctrl=$match.Groups[1].Value;mouse=$match.Groups[2].Value}}}} | |
| 56 | 新增:} | |
| 57 | 新增:function NativeGeometry { | |
| 58 | 新增: $probe=Bridge 'terminal';Send $probe @{action='open';workspace='home';shell='powershell';cols=160;rows=25};if(!(Read $probe).ready){throw 'The GUI geometry probe is unavailable.'} | |
| 59 | 新增: $source=@' | |
| 60 | 新增:using System;using System.Collections.Generic;using System.Runtime.InteropServices;using System.Text;using System.Diagnostics; | |
| 61 | 新增:public static class BrowserGeometryProbe { | |
| 62 | 新增: [StructLayout(LayoutKind.Sequential)]public struct Rect{public int Left,Top,Right,Bottom;} | |
| 63 | 新增: [StructLayout(LayoutKind.Sequential)]public struct Gui{public uint Size,Flags;public IntPtr Active,Focus,Capture,Menu,Move,Caret;public Rect CaretRect;} | |
| 64 | 新增: [DllImport("user32.dll")]static extern IntPtr GetForegroundWindow(); | |
| 65 | 新增: [DllImport("user32.dll")]static extern uint GetWindowThreadProcessId(IntPtr h,out int p); | |
| 66 | 新增: [DllImport("user32.dll")]static extern bool GetWindowRect(IntPtr h,out Rect r); | |
| 67 | 新增: [StructLayout(LayoutKind.Sequential)]public struct Point{public int X,Y;} | |
| 68 | 新增: [DllImport("user32.dll")]static extern bool GetClientRect(IntPtr h,out Rect r); | |
| 69 | 新增: [DllImport("user32.dll")]static extern bool ClientToScreen(IntPtr h,ref Point p); | |
| 70 | 新增: [DllImport("user32.dll")]static extern bool ScreenToClient(IntPtr h,ref Point p); | |
| 71 | 新增: [DllImport("user32.dll")]static extern IntPtr ChildWindowFromPointEx(IntPtr h,Point p,uint flags); | |
| 72 | 新增: [DllImport("user32.dll")]static extern uint GetDpiForWindow(IntPtr h); | |
| 73 | 新增: [DllImport("user32.dll")]static extern bool GetGUIThreadInfo(uint thread,ref Gui info); | |
| 74 | 新增: [DllImport("user32.dll")]static extern IntPtr SetThreadDpiAwarenessContext(IntPtr c); | |
| 75 | 新增: [DllImport("user32.dll",CharSet=CharSet.Unicode)]static extern int GetClassName(IntPtr h,StringBuilder s,int n); | |
| 76 | 新增: delegate bool EnumFn(IntPtr h,IntPtr p);[DllImport("user32.dll")]static extern bool EnumChildWindows(IntPtr h,EnumFn f,IntPtr p); | |
| 77 | 新增: public static string Read(){var old=SetThreadDpiAwarenessContext(new IntPtr(-4));try{var h=GetForegroundWindow();int p;var thread=GetWindowThreadProcessId(h,out p);using(var process=Process.GetProcessById(p)){var name=process.ProcessName;if(name!="msedge"&&name!="chrome")return "unowned_foreground";}Rect w;GetWindowRect(h,out w);var a=new List<string>();a.Add(GetDpiForWindow(h)+","+w.Left+","+w.Top+","+(w.Right-w.Left)+","+(w.Bottom-w.Top));var info=new Gui{Size=(uint)Marshal.SizeOf(typeof(Gui))};if(GetGUIThreadInfo(thread,ref info)){var cl=new StringBuilder(128);GetClassName(info.Focus,cl,128);Rect fr;GetWindowRect(info.Focus,out fr);a.Add("focus:"+cl+","+fr.Left+","+fr.Top+","+(fr.Right-fr.Left)+","+(fr.Bottom-fr.Top));}Rect cr;GetClientRect(h,out cr);var center=new Point{X=(cr.Right-cr.Left)/2,Y=(cr.Bottom-cr.Top)/2};ClientToScreen(h,ref center);foreach(uint flags in new uint[]{0,1,7}){var parent=h;for(int depth=0;depth<12;depth++){var pt=center;ScreenToClient(parent,ref pt);var child=ChildWindowFromPointEx(parent,pt,flags);if(child==IntPtr.Zero||child==parent){a.Add("hit"+flags+":none");break;}var cl=new StringBuilder(128);GetClassName(child,cl,128);Rect r;GetWindowRect(child,out r);a.Add("hit"+flags+":"+cl+","+r.Left+","+r.Top+","+(r.Right-r.Left)+","+(r.Bottom-r.Top));parent=child;}}EnumChildWindows(h,(c,_)=>{var s=new StringBuilder(128);GetClassName(c,s,128);Rect r;if(s.ToString()=="Chrome_RenderWidgetHostHWND"&&GetWindowRect(c,out r))a.Add(r.Left+","+r.Top+","+(r.Right-r.Left)+","+(r.Bottom-r.Top));return true;},IntPtr.Zero);return string.Join(";",a);}finally{SetThreadDpiAwarenessContext(old);}} | |
| 78 | 新增:} | |
| 79 | 新增:'@ | |
| 80 | 新增: $marker='__BG_'+[guid]::NewGuid().ToString('N').Substring(0,8)+'=' | |
| 81 | 新增: $geometryFile=Join-Path $guestDirectory ('geometry-'+[guid]::NewGuid().ToString('N')+'.txt') | |
| 82 | 新增: $code='Add-Type -TypeDefinition ([Text.Encoding]::UTF8.GetString([Convert]::FromBase64String("'+[Convert]::ToBase64String($utf8.GetBytes($source))+'")));[IO.File]::WriteAllText('''+$geometryFile+''',[BrowserGeometryProbe]::Read());[Console]::WriteLine("'+$marker+'done")' | |
| 83 | 新增: Send $probe @{action='input';data=[Convert]::ToBase64String($utf8.GetBytes('powershell.exe -NoProfile -EncodedCommand '+[Convert]::ToBase64String([Text.Encoding]::Unicode.GetBytes($code))+"`r"))};$output='' | |
| 84 | 新增: while($true){$r=Read $probe;if($r.error -or $null -ne $r.exit){throw 'The GUI geometry probe exited.'};if($r.data){$output+=$utf8.GetString([Convert]::FromBase64String($r.data));if($output.Contains($marker+'done')){return Invoke-Command -Session $session -ArgumentList $geometryFile -ScriptBlock {param($path);Get-Content -LiteralPath $path -Raw}}}} | |
| 85 | 新增:} | |
| 86 | 新增:try { | |
| 87 | 新增: $null=[IO.Directory]::CreateDirectory($EvidenceDirectory) | |
| 88 | 新增: $guestDirectory=Invoke-Command -Session $session -ArgumentList $vm.Id,$binding.gui_user_sid -ScriptBlock { | |
| 89 | 新增: param($expected,$sid) | |
| 90 | 新增: if([guid](Get-ItemProperty -LiteralPath 'HKLM:\SOFTWARE\Microsoft\Virtual Machine\Guest\Parameters').VirtualMachineId -ne $expected){throw 'guest_identity_mismatch'} | |
| 91 | 新增: $guiHome=(Get-ItemProperty -LiteralPath ('HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList\'+$sid)).ProfileImagePath | |
| 92 | 新增: $directory=Join-Path $guiHome ('AppData\Local\Temp\CageBrowserAcceptance-'+[guid]::NewGuid().ToString('N'));$null=[IO.Directory]::CreateDirectory($directory);return $directory | |
| 93 | 新增: } | |
| 94 | 新增: $copiedFixtureText+=' '+[IO.Path]::GetFileName($guestDirectory) | |
| 95 | 新增: $copiedFixtureBytes=[Convert]::ToBase64String($utf8.GetBytes($copiedFixtureText)) | |
| 96 | 新增: Copy-Item -LiteralPath $FixturePath -Destination (Join-Path $guestDirectory 'fixture.mjs') -ToSession $session | |
| 97 | 新增: $script:phase='gui_status';$statusProcess=Bridge 'status';$status=Read $statusProcess | |
| 98 | 新增: if(!$status.available -or !$status.browser.installed -or !$status.browser.network_configured){throw 'The actual GUI browser dependencies or trusted network receipt are unavailable.'} | |
| 99 | 新增: $script:phase='fixture_terminal';$terminal=Bridge 'terminal';Send $terminal @{action='open';workspace='home';shell='powershell';cols=160;rows=30};if(!(Read $terminal).ready){throw 'The GUI fixture terminal is unavailable.'} | |
| 100 | 新增: $guestNode='C:\Program Files\Cage Guest Bridge\'+$vm.Id.ToString('D')+'\node.exe' | |
| 101 | 新增: $launch='& '''+$guestNode+''' '''+(Join-Path $guestDirectory 'fixture.mjs')+''' '''+$guestDirectory+'''' | |
| 102 | 新增: $command='powershell.exe -NoProfile -EncodedCommand '+[Convert]::ToBase64String([Text.Encoding]::Unicode.GetBytes($launch))+"`r" | |
| 103 | 新增: Send $terminal @{action='input';data=[Convert]::ToBase64String($utf8.GetBytes($command))} | |
| 104 | 新增: $output='';while($output -notmatch 'CAGE_NATIVE_FIXTURE_READY'){ $r=Read $terminal;if($r.error -or $null -ne $r.exit){throw 'The GUI fixture server exited.'};if($r.data){$output+=$utf8.GetString([Convert]::FromBase64String($r.data))}} | |
| 105 | 新增: $port=Invoke-Command -Session $session -ArgumentList $guestDirectory -ScriptBlock {param($dir);[int](Get-Content -LiteralPath (Join-Path $dir 'fixture-port') -Raw)} | |
| 106 | 新增: $browser=Bridge 'browser';$clipboard=Bridge 'stream';$null=Read $clipboard | |
| 107 | 新增: # The production clipboard stream starts guest observation after the first | |
| 108 | 新增: # host write ACK. Exercise that lifecycle instead of waiting on an unseeded reader. | |
| 109 | 新增: Send $clipboard @{serial=1;text=('Cage fixture baseline '+[IO.Path]::GetFileName($guestDirectory))};ReadAck 1 | |
| 110 | 新增: if($PerfOnly){ | |
| 111 | 新增: $script:phase='native_capture_performance';$tab=Call '/new' @{url=('http://127.0.0.1:'+$port+'/perf')};$tabs.Add($tab.id);Start-Sleep -Milliseconds 300 | |
| 112 | 新增: $frame=Frame 'perf-01-page';Key $frame 65307 $true;Key $frame 65307 $false;$frame=Frame 'perf-02-native-ready' | |
| 113 | 新增: function Dimensions($f){if($f.unchanged){return};$encoded=if($f.jpeg){$f.jpeg}else{$f.png};$memory=[IO.MemoryStream]::new([Convert]::FromBase64String($encoded));$picture=[Drawing.Image]::FromStream($memory);try{if($picture.Width -ne $f.width -or $picture.Height -ne $f.height){throw 'The actual encoded frame does not match its native HiDPI dimensions.'}}finally{$picture.Dispose();$memory.Dispose()}} | |
| 114 | 新增: Dimensions $frame;$before=(Call '/health' @{} 'GET').capture;if(!$before){throw 'The actual capture counters are unavailable.'} | |
| 115 | 新增: $static=[Collections.Generic.List[double]]::new();$unchanged=0 | |
| 116 | 新增: for($i=0;$i -lt 16;$i++){$watch=[Diagnostics.Stopwatch]::StartNew();$next=Call '/frame' @{after=$frame.sequence} 'GET';$watch.Stop();$static.Add($watch.Elapsed.TotalMilliseconds);if($next.unchanged){$unchanged++}else{Dimensions $next;$frame=$next};Start-Sleep -Milliseconds 80} | |
| 117 | 新增: $still=(Call '/health' @{} 'GET').capture;$scroll=[Collections.Generic.List[double]]::new() | |
| 118 | 新增: for($i=0;$i -lt 20;$i++){Pointer $frame ([int](100*$frame.scale)) ([int](600*$frame.scale)) 16;Pointer $frame ([int](100*$frame.scale)) ([int](600*$frame.scale)) 0;$watch=[Diagnostics.Stopwatch]::StartNew();$next=Call '/frame' @{after=$frame.sequence} 'GET';$watch.Stop();$scroll.Add($watch.Elapsed.TotalMilliseconds);if(!$next.unchanged){Dimensions $next;$frame=$next};Start-Sleep -Milliseconds 80} | |
| 119 | 新增: $scrolled=(Call '/health' @{} 'GET').capture;if(!(@(State)|Where-Object {$_.type -eq 'scroll' -and $_.y -gt 0})){throw 'The actual native wheel did not scroll the fixture.'} | |
| 120 | 新增: $summary=[ordered]@{static_polls=16;static_unchanged=$unchanged;static_screenshots=$still.screenshots-$before.screenshots;static_damage_events=$still.damage_frames-$before.damage_frames;static_latency_ms=@($static);scroll_polls=20;scroll_screenshots=$scrolled.screenshots-$still.screenshots;scroll_damage_events=$scrolled.damage_frames-$still.damage_frames;scroll_latency_ms=@($scroll);actual_native_pixels=@($frame.width,$frame.height);completed=$true} | |
| 121 | 新增: [IO.File]::WriteAllText((Join-Path $EvidenceDirectory 'capture-performance.json'),($summary|ConvertTo-Json -Depth 8),$utf8);[IO.File]::WriteAllText((Join-Path $EvidenceDirectory 'perf-events.json'),(@(State)|ConvertTo-Json -Depth 8),$utf8) | |
| 122 | 新增: $summary|ConvertTo-Json -Compress;return | |
| 123 | 新增: } | |
| 124 | 新增: if(!$SplitOnly){ | |
| 125 | 新增: $script:phase='native_frame';$tab=Call '/new' @{url=('http://127.0.0.1:'+$port+'/one');incognito=$true};$tabs.Add($tab.id);Start-Sleep -Milliseconds 400 | |
| 126 | 新增: $frame=Frame '01-page';$results.native_frame=$true | |
| 127 | 新增: $script:phase='native_text';Click $frame 100 130;Text $frame 'native-text';Start-Sleep -Milliseconds 200 | |
| 128 | 新增: if(!(@(State)|Where-Object {$_.type -eq 'text' -and $_.value -eq 'native-text'})){throw 'Native key input did not reach the fixture textarea.'};$results.native_text=$true | |
| 129 | 新增: $frame=Frame '02-text';$script:phase='native_find';Key $frame 65507 $true;Key $frame 102 $true;Key $frame 102 $false;Key $frame 65507 $false;Start-Sleep -Milliseconds 200 | |
| 130 | 新增: $find=Frame '03-native-find';if(@($find.overlays).Count -eq 0){throw 'The native Find UI was not captured.'};Text $find 'cage-native-find-needle';Start-Sleep -Milliseconds 100 | |
| 131 | 新增: if(@(State|Where-Object {$_.type -eq 'text'})[-1].value -ne 'native-text'){throw 'Find input reached the webpage instead of native Chrome UI.'};$results.native_find=$true | |
| 132 | 新增: $find=Frame '04-find-query';Key $find 65307 $true;Key $find 65307 $false | |
| 133 | 新增: $frame=Frame '05-find-closed';$script:phase='native_context';Click $frame 100 130 4;Start-Sleep -Milliseconds 150 | |
| 134 | 新增: $menu=Frame '06-native-context';if(@($menu.overlays).Count -eq 0){throw 'The native context menu was not captured.'};$results.native_context_menu=$true;Key $menu 65307 $true;Key $menu 65307 $false | |
| 135 | 新增: $frame=Frame '07-context-closed';$script:phase='page_copy';Click $frame 100 215 | |
| 136 | 新增: do {$r=Read $clipboard}while($r.source -ne 'guest' -or $r.text -cne $copiedFixtureText) | |
| 137 | 新增: if([Convert]::ToBase64String($utf8.GetBytes($r.text)) -cne $copiedFixtureBytes){throw 'The actual clipboard text bytes differ from the fixture copy.'} | |
| 138 | 新增: if(!(@(State)|Where-Object type -eq copied)){throw 'The actual fixture copy button did not complete.'};$results.page_copy_reaches_os_clipboard=$true | |
| 139 | 新增: $script:phase='image_paste';$frame=Frame '08-before-png';Click $frame 100 295 | |
| 140 | 新增: $bitmap=[Drawing.Bitmap]::new(17,9);$graphics=[Drawing.Graphics]::FromImage($bitmap);$graphics.Clear([Drawing.Color]::Coral);$bytes=[IO.MemoryStream]::new();$bitmap.Save($bytes,[Drawing.Imaging.ImageFormat]::Png);$png=$bytes.ToArray();$bytes.Dispose();$graphics.Dispose();$bitmap.Dispose() | |
| 141 | 新增: $started=Call '/image-start' @{id=$tab.id;length=$png.Length};$null=Call '/image-chunk' @{transfer=$started.transfer;sequence=0;data=[Convert]::ToBase64String($png)};$null=Call '/image-finish' @{transfer=$started.transfer;sequence=1};Start-Sleep -Milliseconds 250 | |
| 142 | 新增: if(!(@(State)|Where-Object {$_.type -eq 'png' -and $_.width -eq 17 -and $_.height -eq 9})){throw 'The native OS PNG did not reach the fixture paste event.'};$results.native_png_paste=$true;$null=Frame '09-png-pasted' | |
| 143 | 新增: $script:phase='native_permission';$frame=Frame '10-before-permission';Click $frame 330 215;Start-Sleep -Milliseconds 250 | |
| 144 | 新增: $permission=Frame '11-native-permission';if(@($permission.overlays).Count -eq 0){throw 'The native permission prompt was not captured.'};$results.native_permission_prompt=$true;Key $permission 65307 $true;Key $permission 65307 $false | |
| 145 | 新增: $script:phase='native_private_tabs';$frame=Frame '11a-private-one';Click $frame ($frame.width/$frame.scale-120) 36 | |
| 146 | 新增: $privateSecond=$null;for($i=0;$i-lt 40;$i++){$snapshot=Call '/tabs' @{} 'GET';$privateSecond=@($snapshot.tabs|Where-Object {$_.incognito -and $_.url -like '*/private-two'})[0];if($privateSecond){break};Start-Sleep -Milliseconds 50} | |
| 147 | 新增: if(!$privateSecond){throw 'The native private popup was not registered.'};$tabs.Add($privateSecond.id) | |
| 148 | 新增: $privateFrame=Frame '11b-private-two';if($privateFrame.id -ne $privateSecond.id){throw 'The private popup did not become the actual active page.'} | |
| 149 | 新增: Key $privateFrame 65507 $true;Key $privateFrame 65289 $true;Key $privateFrame 65289 $false;Key $privateFrame 65507 $false;Start-Sleep -Milliseconds 200 | |
| 150 | 新增: $cycled=Frame '11c-native-ctrl-tab';if($cycled.id -ne $tab.id){throw 'Native Ctrl+Tab did not synchronize the known private document.'};$results.native_ctrl_tab=$true | |
| 151 | 新增: $null=Call '/close' @{id=$tab.id};$snapshot=Call '/tabs' @{} 'GET';if(!(@($snapshot.tabs)|Where-Object id -eq $privateSecond.id)){throw 'Closing a private tab also closed its sibling.'};$results.private_sibling_retained=$true | |
| 152 | 新增: } | |
| 153 | 新增: # Split follows the common browser contract: two ordinary tabs in one | |
| 154 | 新增: # context. Only these newly created fixture tabs are used and closed. | |
| 155 | 新增: $script:phase='split';$left=Call '/new' @{url=('http://127.0.0.1:'+$port+'/split-one')};$tabs.Add($left.id) | |
| 156 | 新增: $second=Call '/new' @{url=('http://127.0.0.1:'+$port+'/split-two')};$tabs.Add($second.id);$null=Call '/split' @{id=$left.id;left=$left.id;right=$second.id};Start-Sleep -Milliseconds 250 | |
| 157 | 新增: $split=Frame '12-split';if(@($split.panes).Count -ne 2){throw 'The real split frame does not contain both panes.'} | |
| 158 | 新增: Pointer $split ([int]($split.panes[1].x+100*$split.scale)) ([int](130*$split.scale)) 1;Pointer $split ([int]($split.panes[1].x+100*$split.scale)) ([int](130*$split.scale)) 0;Text $split 'split-right';Start-Sleep -Milliseconds 250 | |
| 159 | 新增: if(!(@(State)|Where-Object {$_.page -eq '/split-two' -and $_.type -eq 'text' -and $_.value -eq 'split-right'})){$null=Frame '13-split-failed';[IO.File]::WriteAllText((Join-Path $EvidenceDirectory 'split-events.json'),(@(State)|ConvertTo-Json -Depth 8),$utf8);[IO.File]::WriteAllText((Join-Path $EvidenceDirectory 'split-native-geometry.txt'),(NativeGeometry),$utf8);throw 'The native split input did not reach the right pane.'};$results.native_split_input=$true;$null=Frame '13-split-input' | |
| 160 | 新增: $null=Call '/split' @{} | |
| 161 | 新增: $script:phase='native_disconnect';$baseline=NativeKeys;if($baseline.ctrl -ne 'released' -or $baseline.mouse -ne 'released'){throw 'The GUI already contains held input before this isolated disconnect test.'} | |
| 162 | 新增: $primary=$browser;$viewerA=Bridge 'browser';$viewerB=Bridge 'browser' | |
| 163 | 新增: $browser=$viewerA;$leaseFrame=Frame '14-before-disconnect';Key $leaseFrame 65507 $true;Pointer $leaseFrame ([int](100*$leaseFrame.scale)) ([int](130*$leaseFrame.scale)) 1 | |
| 164 | 新增: $browser=$viewerB;Key $leaseFrame 65507 $true | |
| 165 | 新增: $viewerA.StandardInput.Close();if(!$viewerA.WaitForExit(3000)){$viewerA.Kill()};Start-Sleep -Milliseconds 250 | |
| 166 | 新增: $native=NativeKeys;if($native.ctrl -ne 'held' -or $native.mouse -ne 'released'){throw 'Disconnect did not release its own mouse while preserving the other viewer Ctrl.'};$results.disconnect_preserves_other_viewer=$true | |
| 167 | 新增: $viewerB.StandardInput.Close();if(!$viewerB.WaitForExit(3000)){$viewerB.Kill()};Start-Sleep -Milliseconds 250 | |
| 168 | 新增: $native=NativeKeys;if($native.ctrl -ne 'released' -or $native.mouse -ne 'released'){throw 'The last viewer disconnect left native input held.'};$results.disconnect_native_keys_released=$true | |
| 169 | 新增: $browser=$primary;$results.completed=$true | |
| 170 | 新增: [IO.File]::WriteAllText((Join-Path $EvidenceDirectory 'browser-result.json'),($results|ConvertTo-Json),$utf8) | |
| 171 | 新增: $results|ConvertTo-Json -Compress | |
| 172 | 新增:} catch { | |
| 173 | 新增: try{[IO.File]::WriteAllText((Join-Path $EvidenceDirectory 'failure-native-geometry.txt'),(NativeGeometry),$utf8)}catch{} | |
| 174 | 新增: $results.completed=$false;$results.failed_phase=$script:phase;$results.reason=$_.Exception.Message | |
| 175 | 新增: if(Test-Path -LiteralPath $EvidenceDirectory){[IO.File]::WriteAllText((Join-Path $EvidenceDirectory 'browser-result.json'),($results|ConvertTo-Json),$utf8)} | |
| 176 | 新增: $results|ConvertTo-Json -Compress | |
| 177 | 新增: throw | |
| 178 | 新增:} finally { | |
| 179 | 新增: if($primary){$browser=$primary} | |
| 180 | 新增: if($browser -and $frame){try{$cleanup=Call '/frame' @{} 'GET';foreach($symbol in @(65507,65505,65513)){Key $cleanup $symbol $false};Pointer $cleanup 1 1 0}catch{}} | |
| 181 | 新增: if($browser){foreach($id in $tabs){try{$null=Call '/close' @{id=$id}}catch{}}} | |
| 182 | 新增: foreach($p in $owned){try{$p.StandardInput.Close();if(!$p.WaitForExit(1000)){$p.Kill()};$p.Dispose()}catch{}} | |
| 183 | 新增: if($session){Remove-PSSession $session} | |
| 184 | 新增:} | |
| @@ -0,0 +1,25 @@ | ||
| 1 | 新增:#requires -Version 5.1 | |
| 2 | 新增:param([Parameter(Mandatory)][string]$ProfilePath,[Parameter(Mandatory)][string]$EvidenceDirectory) | |
| 3 | 新增:$ErrorActionPreference='Stop';$ProgressPreference='SilentlyContinue' | |
| 4 | 新增:$profile=Get-Content -LiteralPath $ProfilePath -Raw|ConvertFrom-Json;$utf8=[Text.UTF8Encoding]::new($false) | |
| 5 | 新增:$owned=[Collections.Generic.List[Diagnostics.Process]]::new() | |
| 6 | 新增:function Start-Transfer([string]$Operation,[bool]$Helper=$false){ | |
| 7 | 新增: $s=[Diagnostics.ProcessStartInfo]::new();$s.FileName=if($Helper){Join-Path ([IO.Path]::GetDirectoryName($profile.relay_executable)) 'cage-guest-files.exe'}else{$profile.relay_executable} | |
| 8 | 新增: $s.Arguments=if($Helper){$Operation}else{'--relay-profile "'+$ProfilePath+'" '+$Operation};if($Operation -eq 'export'){$s.Arguments+=' --paths-stdin'} | |
| 9 | 新增: $s.UseShellExecute=$false;$s.CreateNoWindow=$true;$s.RedirectStandardInput=$true;$s.RedirectStandardOutput=$true;$s.RedirectStandardError=$true;$s.StandardOutputEncoding=$utf8 | |
| 10 | 新增: $p=[Diagnostics.Process]::Start($s);$owned.Add($p);$null=$p.StandardError.ReadToEndAsync();$p | |
| 11 | 新增:} | |
| 12 | 新增:function Paths($P,$Selection){$bytes=$utf8.GetBytes((ConvertTo-Json -InputObject @($Selection) -Compress)+"`n");$P.StandardInput.BaseStream.Write($bytes,0,$bytes.Length);$P.StandardInput.Close()} | |
| 13 | 新增:function Result($P){$read=$P.StandardOutput.ReadLineAsync();if(!$read.Wait(120000) -or !$read.Result -or !$P.WaitForExit(120000) -or $P.ExitCode -ne 0){throw 'The bounded archive stream did not complete.'};$read.Result|ConvertFrom-Json} | |
| 14 | 新增:function Hash([string]$File){(Get-FileHash -LiteralPath $File -Algorithm SHA256).Hash} | |
| 15 | 新增:try { | |
| 16 | 新增: $directory=Join-Path $EvidenceDirectory ([guid]::NewGuid().ToString('N'));$null=[IO.Directory]::CreateDirectory($directory) | |
| 17 | 新增: $source=Join-Path $directory 'stream-64MiB.bin';$file=[IO.File]::Open($source,'CreateNew','Write','None');$buffer=New-Object byte[] (64KB);for($i=0;$i -lt $buffer.Length;$i++){$buffer[$i]=[byte]($i%251)} | |
| 18 | 新增: try{for($i=0;$i -lt 1024;$i++){$file.Write($buffer,0,$buffer.Length)}}finally{$file.Dispose()} | |
| 19 | 新增: $write=Start-Transfer 'export' $true;Paths $write @($source);$import=Start-Transfer 'import';$write.StandardOutput.BaseStream.CopyTo($import.StandardInput.BaseStream);$import.StandardInput.Close();$guest=Result $import | |
| 20 | 新增: if(!$write.WaitForExit(120000) -or $write.ExitCode -ne 0 -or @($guest.paths).Count -ne 1){throw 'The host archive source failed.'} | |
| 21 | 新增: $export=Start-Transfer 'export';Paths $export @($guest.paths);$read=Start-Transfer 'import' $true;$export.StandardOutput.BaseStream.CopyTo($read.StandardInput.BaseStream);$read.StandardInput.Close();$returnedHost=Result $read | |
| 22 | 新增: if(!$export.WaitForExit(120000) -or $export.ExitCode -ne 0 -or @($returnedHost.paths).Count -ne 1 -or (Get-Item -LiteralPath $returnedHost.paths[0]).Length -ne 64MB -or (Hash $source) -ne (Hash $returnedHost.paths[0])){throw 'The 64 MiB stream hash or completion status differs.'} | |
| 23 | 新增: $result=[ordered]@{bytes=64MB;host_to_guest_complete=$true;guest_to_host_complete=$true;sha256_equal=$true;clipboard_unchanged=$true} | |
| 24 | 新增: [IO.File]::WriteAllText((Join-Path $EvidenceDirectory 'large-file-result.json'),($result|ConvertTo-Json),$utf8);$result|ConvertTo-Json -Compress | |
| 25 | 新增:}finally{foreach($p in $owned){try{$p.StandardInput.Close();if(!$p.WaitForExit(1000)){$p.Kill()};$p.Dispose()}catch{}}} | |
| @@ -0,0 +1,100 @@ | ||
| 1 | 新增:#requires -Version 5.1 | |
| 2 | 新增:param( | |
| 3 | 新增: [Parameter(Mandatory)][string]$ProfilePath, | |
| 4 | 新增: [Parameter(Mandatory)][string]$CredentialFile, | |
| 5 | 新增: [Parameter(Mandatory)][string]$AssetDirectory, | |
| 6 | 新增: [Parameter(Mandatory)][string]$EvidenceDirectory, | |
| 7 | 新增: [switch]$EditorOnly | |
| 8 | 新增:) | |
| 9 | 新增:$ErrorActionPreference='Stop';$ProgressPreference='SilentlyContinue' | |
| 10 | 新增:$utf8=[Text.UTF8Encoding]::new($false);[Console]::OutputEncoding=$utf8 | |
| 11 | 新增:$binding=Get-Content -LiteralPath $ProfilePath -Raw|ConvertFrom-Json;$vm=Get-VM -Id ([guid]$binding.vm_id) | |
| 12 | 新增:if($vm.State -ne 'Running' -or @(Get-VMNetworkAdapter -VM $vm).Count -ne 0){throw 'The bound local-only guest must have zero normal NICs.'} | |
| 13 | 新增:$credential=Import-Clixml -LiteralPath $CredentialFile | |
| 14 | 新增:if(($credential.UserName -split '\\')[-1] -cne 'CageLabSetup'){throw 'The retained QA administrator identity does not match.'} | |
| 15 | 新增:$credential=[pscredential]::new('CageLabSetup',$credential.Password) | |
| 16 | 新增:$session=New-PSSession -VMId $vm.Id -Credential $credential | |
| 17 | 新增:$owned=[Collections.Generic.List[Diagnostics.Process]]::new();$changed=$false;$restored=$false | |
| 18 | 新增:function Bridge([string]$Operation){$s=[Diagnostics.ProcessStartInfo]::new();$s.FileName=$binding.relay_executable;$s.Arguments='--relay-profile "'+$ProfilePath+'" '+$Operation;$s.UseShellExecute=$false;$s.CreateNoWindow=$true;$s.RedirectStandardInput=$true;$s.RedirectStandardOutput=$true;$s.RedirectStandardError=$true;$s.StandardOutputEncoding=$utf8;$p=[Diagnostics.Process]::Start($s);$owned.Add($p);$null=$p.StandardError.ReadToEndAsync();return $p} | |
| 19 | 新增:function Send($p,$v){$bytes=$utf8.GetBytes((ConvertTo-Json -InputObject $v -Depth 12 -Compress)+"`n");$p.StandardInput.BaseStream.Write($bytes,0,$bytes.Length);$p.StandardInput.BaseStream.Flush()} | |
| 20 | 新增:function Read($p){$pending=$p.StandardOutput.ReadLineAsync();if(!$pending.Wait(45000) -or !$pending.Result){throw 'The owned local browser QA channel did not complete.'};return $pending.Result|ConvertFrom-Json} | |
| 21 | 新增:function Call([string]$Path,$Payload=@{},[string]$Method='POST'){Send $browser @{method=$Method;path=$Path;input=$Payload};$r=Read $browser;if($r.error){throw $r.error};return $r} | |
| 22 | 新增:try { | |
| 23 | 新增: $null=New-Item -ItemType Directory -Path $EvidenceDirectory | |
| 24 | 新增: $setup=Invoke-Command -Session $session -ArgumentList $vm.Id,$binding.gui_user_sid -ScriptBlock { | |
| 25 | 新增: param($expected,$sid) | |
| 26 | 新增: if([guid](Get-ItemProperty 'HKLM:\SOFTWARE\Microsoft\Virtual Machine\Guest\Parameters').VirtualMachineId -ne $expected){throw 'guest_identity_mismatch'} | |
| 27 | 新增: $guiProfile=(Get-ItemProperty ('HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList\'+$sid)).ProfileImagePath | |
| 28 | 新增: $directory=Join-Path $guiProfile ('AppData\Local\Temp\CageLocalBrowserQA-'+[guid]::NewGuid().ToString('N'));$null=New-Item -ItemType Directory -Path $directory | |
| 29 | 新增: $program=Join-Path $env:ProgramFiles ('Cage Guest Bridge\'+$expected);$config=Join-Path $program 'guest-config.json';$backup=Join-Path $program ('guest-config.browser-qa-'+[guid]::NewGuid().ToString('N')+'.backup') | |
| 30 | 新增: if((Get-Item $config).Attributes -band [IO.FileAttributes]::ReparsePoint){throw 'config_link_rejected'} | |
| 31 | 新增: Copy-Item -LiteralPath $config -Destination $backup | |
| 32 | 新增: [pscustomobject]@{Directory=$directory;Program=$program;Config=$config;Backup=$backup;Hash=(Get-FileHash $config -Algorithm SHA256).Hash} | |
| 33 | 新增: } | |
| 34 | 新增: Copy-Item -LiteralPath (Join-Path $AssetDirectory 'windows-browser-deny-proxy.mjs') -Destination (Join-Path $setup.Directory 'deny.mjs') -ToSession $session | |
| 35 | 新增: $terminal=Bridge 'terminal';Send $terminal @{action='open';workspace='home';shell='powershell';cols=160;rows=30};if(!(Read $terminal).ready){throw 'GUI ConPTY unavailable'} | |
| 36 | 新增: $privateHost=@(Get-NetIPAddress -AddressFamily IPv4|Where-Object {$_.IPAddress -notlike '127.*' -and $_.IPAddress -notlike '169.254.*' -and $_.AddressState -eq 'Preferred'})[0].IPAddress | |
| 37 | 新增: if(!$privateHost){throw 'An actual private host address is required for the denied request probe.'} | |
| 38 | 新增: $launch='& '''+(Join-Path $setup.Program 'node.exe')+''' '''+(Join-Path $setup.Directory 'deny.mjs')+''' '''+$setup.Directory+''' '''+$privateHost+'''' | |
| 39 | 新增: Send $terminal @{action='input';data=[Convert]::ToBase64String($utf8.GetBytes('powershell.exe -NoProfile -EncodedCommand '+[Convert]::ToBase64String([Text.Encoding]::Unicode.GetBytes($launch))+"`r"))} | |
| 40 | 新增: $output='';while(!$output.Contains('CAGE_QA_DENY_PROXY_READY')){$r=Read $terminal;if($null -ne $r.exit -or $r.error){throw 'The local deny proxy exited.'};if($r.data){$output+=$utf8.GetString([Convert]::FromBase64String($r.data))}} | |
| 41 | 新增: $port=Invoke-Command -Session $session -ArgumentList $setup.Directory -ScriptBlock {param($dir);[int](Get-Content (Join-Path $dir 'deny-proxy-port') -Raw)} | |
| 42 | 新增: $changed=$true;$windowStartUtc=[DateTime]::UtcNow.ToString('o') | |
| 43 | 新增: Invoke-Command -Session $session -ArgumentList $setup.Config,$port -ScriptBlock { | |
| 44 | 新增: param($file,$port);$config=Get-Content -LiteralPath $file -Raw|ConvertFrom-Json | |
| 45 | 新增: $config|Add-Member -NotePropertyName network_mode -NotePropertyValue 'proxy' -Force | |
| 46 | 新增: $config|Add-Member -NotePropertyName browser_proxy -NotePropertyValue ('http://127.0.0.1:'+$port) -Force | |
| 47 | 新增: [IO.File]::WriteAllText($file,($config|ConvertTo-Json -Depth 12),[Text.UTF8Encoding]::new($false)) | |
| 48 | 新增: } | |
| 49 | 新增: [Console]::WriteLine('LOCAL_ONLY_QA_CONFIG_STARTED '+$windowStartUtc) | |
| 50 | 新增: $browser=Bridge 'browser';$health=Call '/health' @{} 'GET';$version=Call '/info' | |
| 51 | 新增: $audited=Call '/audit' @{network=$true;timezone='UTC'} | |
| 52 | 新增: if($audited.network.status -ne 503){throw 'The actual browser request did not reach the rejecting local proxy.'} | |
| 53 | 新增: $known=@((Call '/tabs' @{} 'GET').tabs|ForEach-Object {$_.id}) | |
| 54 | 新增: $null=Call '/new' @{url='http://example.com/'};$null=Call '/new' @{url=('http://'+$privateHost+'/')} | |
| 55 | 新增: $connectDenied=$false;try{$null=Call '/new' @{url='https://example.com/'}}catch{$connectDenied=$true} | |
| 56 | 新增: $counts=Invoke-Command -Session $session -ArgumentList $setup.Directory -ScriptBlock {param($dir);Get-Content (Join-Path $dir 'deny-proxy-counts.json') -Raw|ConvertFrom-Json} | |
| 57 | 新增: if($counts.public_probe -lt 1 -or $counts.private_probe -lt 1 -or $counts.connect_probe -lt 1 -or !$connectDenied){throw 'The actual Chrome public/private host HTTP and HTTPS CONNECT probes were not all denied.'} | |
| 58 | 新增: foreach($tab in (Call '/tabs' @{} 'GET').tabs){if($tab.id -notin $known){$null=Call '/close' @{id=$tab.id}}} | |
| 59 | 新增: $tests=[ordered]@{local_only=$true;normal_nics=0;browser_version=$version.product;browser_audit_status=$audited.network.status;actual_public_http_denied=$true;actual_private_host_http_denied=$true;actual_https_connect_denied=$true;packet_network_verified=$false} | |
| 60 | 新增: [IO.File]::WriteAllText((Join-Path $EvidenceDirectory 'local-only-network.json'),($tests|ConvertTo-Json),$utf8) | |
| 61 | 新增: if(!$EditorOnly){$perf=Join-Path $EvidenceDirectory 'performance'; & (Join-Path $AssetDirectory 'qa-browser.ps1') -ProfilePath $ProfilePath -CredentialFile $CredentialFile -FixturePath (Join-Path $AssetDirectory 'windows-native-browser-fixture.mjs') -EvidenceDirectory $perf -PerfOnly} | |
| 62 | 新增: $env:CAGE_TEST_WINDOWS_WORKBENCH_PROFILE=Split-Path -Parent $ProfilePath;$env:CAGE_TEST_WINDOWS_BROWSER_ARTIFACTS=Join-Path $EvidenceDirectory 'editor';$env:CAGE_TEST_WINDOWS_BROWSER_NATIVE='1' | |
| 63 | 新增: & (Join-Path $AssetDirectory 'browser-editor-tests.exe') '-test.run=^TestWindowsBrowserEditorNativeE2E$' '-test.v' '-test.count=1' | |
| 64 | 新增: if($LASTEXITCODE -ne 0){throw 'The real local-only native editor test failed.'} | |
| 65 | 新增: if(!$EditorOnly){& (Join-Path $AssetDirectory 'qa-browser.ps1') -ProfilePath $ProfilePath -CredentialFile $CredentialFile -FixturePath (Join-Path $AssetDirectory 'windows-native-browser-fixture.mjs') -EvidenceDirectory (Join-Path $EvidenceDirectory 'native-core')} | |
| 66 | 新增:} finally { | |
| 67 | 新增: try { | |
| 68 | 新增: if($setup){ | |
| 69 | 新增: $restored=Invoke-Command -Session $session -ArgumentList $setup.Config,$setup.Backup,$setup.Hash,[bool]$changed,$vm.Id,$binding.gui_user_sid -ScriptBlock { | |
| 70 | 新增: param($file,$backup,$hash,$changed,$vm,$sid) | |
| 71 | 新增: if($changed){[IO.File]::WriteAllBytes($file,[IO.File]::ReadAllBytes($backup))} | |
| 72 | 新增: if((Get-FileHash $file -Algorithm SHA256).Hash -cne $hash){throw 'The original guest configuration was not restored.'} | |
| 73 | 新增: Remove-Item -LiteralPath $backup | |
| 74 | 新增: if($changed){ | |
| 75 | 新增: $name='Cage-GUI-Bridge-'+$vm+'-'+$sid;$task=Get-ScheduledTask -TaskName $name | |
| 76 | 新增: if($task.Description -cne ('Cage protected GUI bridge '+$vm+' '+$sid)){throw 'Owned GUI task mismatch'} | |
| 77 | 新增: Stop-ScheduledTask -InputObject $task | |
| 78 | 新增: $until=[DateTime]::UtcNow.AddSeconds(10) | |
| 79 | 新增: while((Get-ScheduledTask -TaskName $name).State -eq 'Running' -and [DateTime]::UtcNow -lt $until){Start-Sleep -Milliseconds 100} | |
| 80 | 新增: if((Get-ScheduledTask -TaskName $name).State -eq 'Running'){throw 'The owned GUI task did not stop.'} | |
| 81 | 新增: Start-ScheduledTask -InputObject $task | |
| 82 | 新增: $until=[DateTime]::UtcNow.AddSeconds(10) | |
| 83 | 新增: while((Get-ScheduledTask -TaskName $name).State -ne 'Running' -and [DateTime]::UtcNow -lt $until){Start-Sleep -Milliseconds 100} | |
| 84 | 新增: if((Get-ScheduledTask -TaskName $name).State -ne 'Running'){throw 'The owned GUI task did not restart.'} | |
| 85 | 新增: } | |
| 86 | 新增: return $true | |
| 87 | 新增: } | |
| 88 | 新增: } | |
| 89 | 新增: if($restored -and $changed){ | |
| 90 | 新增: $until=[DateTime]::UtcNow.AddSeconds(10);$confirmed=$false | |
| 91 | 新增: do{try{$status=Bridge 'status';$pending=$status.StandardOutput.ReadLineAsync();if($pending.Wait(2000) -and $pending.Result){$reply=$pending.Result|ConvertFrom-Json;$confirmed=$reply.available -eq $true -and $reply.vm_id -eq $binding.vm_id -and $reply.gui_user_sid -ceq $binding.gui_user_sid}}catch{};if(!$confirmed){Start-Sleep -Milliseconds 200}}while(!$confirmed -and [DateTime]::UtcNow -lt $until) | |
| 92 | 新增: if(!$confirmed){throw 'Configuration restored, but the actual paired GUI status ACK is unavailable.'} | |
| 93 | 新增: [Console]::WriteLine('LOCAL_ONLY_QA_GUI_ACK_CONFIRMED') | |
| 94 | 新增: } | |
| 95 | 新增: if($restored){$endUtc=[DateTime]::UtcNow.ToString('o');[IO.File]::WriteAllText((Join-Path $EvidenceDirectory 'configuration-window.json'),(@{start_utc=$windowStartUtc;end_utc=$endUtc;original_config_restored=$true;gui_ack_confirmed=$confirmed;network_mode='local-only-proxy';normal_nics=0}|ConvertTo-Json),$utf8);[Console]::WriteLine('LOCAL_ONLY_QA_CONFIG_RESTORED '+$endUtc)} | |
| 96 | 新增: } finally { | |
| 97 | 新增: foreach($p in $owned){try{$p.StandardInput.Close();if(!$p.WaitForExit(1000)){$p.Kill()};$p.Dispose()}catch{}} | |
| 98 | 新增: if($session){Remove-PSSession $session} | |
| 99 | 新增: } | |
| 100 | 新增:} | |
| @@ -0,0 +1,73 @@ | ||
| 1 | 新增:#requires -Version 5.1 | |
| 2 | 新增:param([Parameter(Mandatory)][string]$ProfilePath,[Parameter(Mandatory)][string]$EvidenceDirectory) | |
| 3 | 新增:$ErrorActionPreference='Stop';$ProgressPreference='SilentlyContinue' | |
| 4 | 新增:$profile=Get-Content -LiteralPath $ProfilePath -Raw|ConvertFrom-Json | |
| 5 | 新增:$executable=$profile.relay_executable;$helper=Join-Path ([IO.Path]::GetDirectoryName($executable)) 'cage-guest-files.exe' | |
| 6 | 新增:$utf8=[Text.UTF8Encoding]::new($false) | |
| 7 | 新增:$owned=[Collections.Generic.List[Diagnostics.Process]]::new() | |
| 8 | 新增:$script:phase='starting' | |
| 9 | 新增:function Start-Bridge([string]$Operation,[bool]$Files=$false){ | |
| 10 | 新增: $s=[Diagnostics.ProcessStartInfo]::new();$s.FileName=if($Files){$helper}else{$executable} | |
| 11 | 新增: $s.Arguments=if($Files){$Operation}else{'--relay-profile "'+$ProfilePath+'" '+$Operation} | |
| 12 | 新增: if($Operation -eq 'export'){$s.Arguments+=' --paths-stdin'} | |
| 13 | 新增: $s.UseShellExecute=$false;$s.CreateNoWindow=$true;$s.RedirectStandardInput=$true;$s.RedirectStandardOutput=$true;$s.RedirectStandardError=$true;$s.StandardOutputEncoding=$utf8 | |
| 14 | 新增: $p=[Diagnostics.Process]::Start($s);$owned.Add($p);$null=$p.StandardError.ReadToEndAsync();return $p | |
| 15 | 新增:} | |
| 16 | 新增:function Send-JSON($Process,$Object){$b=$utf8.GetBytes((ConvertTo-Json -InputObject $Object -Compress -Depth 8)+"`n");$Process.StandardInput.BaseStream.Write($b,0,$b.Length);$Process.StandardInput.BaseStream.Flush()} | |
| 17 | 新增:function Read-JSON($Process){$r=$Process.StandardOutput.ReadLineAsync();if(!$r.Wait(30000) -or !$r.Result){throw ('The GUI bridge response did not complete at '+$script:phase+'.')};return ($r.Result|ConvertFrom-Json)} | |
| 18 | 新增:function Check-Exit($Process){if(!$Process.WaitForExit(30000) -or $Process.ExitCode -ne 0){throw 'The GUI bridge child failed.'}} | |
| 19 | 新增:function SHA([byte[]]$Bytes){return [BitConverter]::ToString([Security.Cryptography.SHA256]::Create().ComputeHash($Bytes)).Replace('-','').ToLowerInvariant()} | |
| 20 | 新增:$echoes=0 | |
| 21 | 新增:function Read-Ack([long]$Serial){ | |
| 22 | 新增: while($true){$value=Read-JSON $clipboard;if($value.error){throw 'Clipboard write failed.'};if($value.ack -eq $Serial){return};if($value.source -eq 'guest' -and $value.text -eq $seed){$script:echoes++}} | |
| 23 | 新增:} | |
| 24 | 新增:function Read-Guest([string]$Format){while($true){$v=Read-JSON $clipboard;if($v.error){throw 'Clipboard selection failed.'};if($v.source -eq 'guest' -and $null -ne $v.$Format){return $v}}} | |
| 25 | 新增:function Invoke-Native([string]$Body){ | |
| 26 | 新增: $marker='__CQ_'+[guid]::NewGuid().ToString('N').Substring(0,8)+'=' | |
| 27 | 新增: $script='Add-Type -AssemblyName System.Windows.Forms;'+$Body+';[Console]::WriteLine("'+$marker+'"+$result)' | |
| 28 | 新增: $encoded=[Convert]::ToBase64String([Text.Encoding]::Unicode.GetBytes($script)) | |
| 29 | 新增: Send-JSON $terminal @{action='input';data=[Convert]::ToBase64String($utf8.GetBytes('powershell.exe -Sta -NoProfile -EncodedCommand '+$encoded+"`r"))} | |
| 30 | 新增: $output='' | |
| 31 | 新增: while($true){$m=Read-JSON $terminal;if($m.error -or $null -ne $m.exit){throw 'The ordinary GUI ConPTY failed.'};if($m.data){$output+=$utf8.GetString([Convert]::FromBase64String($m.data));$match=[regex]::Match($output,[regex]::Escape($marker)+'([a-zA-Z0-9_-]+)[\r\n]');if($match.Success){return $match.Groups[1].Value}}} | |
| 32 | 新增:} | |
| 33 | 新增:try { | |
| 34 | 新增: $script:phase='clipboard_public_hello';$clipboard=Start-Bridge 'stream';$hello=Read-JSON $clipboard | |
| 35 | 新增: if($hello.hello.os -ne 'windows' -or !$hello.hello.available -or $hello.version){throw 'The public clipboard hello shape is invalid.'} | |
| 36 | 新增: $script:phase='terminal_ready';$terminal=Start-Bridge 'terminal';Send-JSON $terminal @{action='open';cols=160;rows=35;workspace='home';shell='powershell'} | |
| 37 | 新增: if(!(Read-JSON $terminal).ready){throw 'The ordinary GUI ConPTY did not become ready.'} | |
| 38 | 新增: Send-JSON $terminal @{action='resize';cols=160;rows=40} | |
| 39 | 新增: $script:phase='host_text_ack';$seed="Windows host 中文 😀`nsecond line";Send-JSON $clipboard @{serial=1;text=$seed};Read-Ack 1 | |
| 40 | 新增: $expected=SHA $utf8.GetBytes($seed) | |
| 41 | 新增: $script:phase='host_text_native_read';$read=Invoke-Native '$b=[Text.Encoding]::UTF8.GetBytes([Windows.Forms.Clipboard]::GetText());$result=[BitConverter]::ToString([Security.Cryptography.SHA256]::Create().ComputeHash($b)).Replace("-","").ToLowerInvariant()' | |
| 42 | 新增: if($read -ne $expected){throw 'Native GUI clipboard text does not match the host write.'} | |
| 43 | 新增: $guest='Windows guest 中文 😀';$guest64=[Convert]::ToBase64String($utf8.GetBytes($guest)) | |
| 44 | 新增: $script:phase='guest_text_write';$null=Invoke-Native ('$text=[Text.Encoding]::UTF8.GetString([Convert]::FromBase64String("'+$guest64+'"));[Windows.Forms.Clipboard]::SetText($text);$result="written"') | |
| 45 | 新增: if((Read-Guest 'text').text -ne $guest){throw 'Native guest text did not reach the host.'} | |
| 46 | 新增: # A small valid PNG fixture has stable bytes, dimensions and transparency. | |
| 47 | 新增: Add-Type -AssemblyName System.Drawing | |
| 48 | 新增: $image=[Drawing.Bitmap]::new(13,7);$g=[Drawing.Graphics]::FromImage($image);$g.Clear([Drawing.Color]::FromArgb(177,21,80,140));$bytes=[IO.MemoryStream]::new();$image.Save($bytes,[Drawing.Imaging.ImageFormat]::Png);$g.Dispose();$image.Dispose();$png=$bytes.ToArray();$bytes.Dispose() | |
| 49 | 新增: $script:phase='host_png_ack';Send-JSON $clipboard @{serial=2;png=[Convert]::ToBase64String($png)};Read-Ack 2 | |
| 50 | 新增: $script:phase='host_png_native_read';$read=Invoke-Native '$b=([IO.MemoryStream][Windows.Forms.Clipboard]::GetData("PNG")).ToArray();$result=[BitConverter]::ToString([Security.Cryptography.SHA256]::Create().ComputeHash($b)).Replace("-","").ToLowerInvariant()' | |
| 51 | 新增: if($read -ne (SHA $png)){throw 'Native PNG bytes do not match the host write.'} | |
| 52 | 新增: $script:phase='guest_png_write';$null=Invoke-Native 'Add-Type -AssemblyName System.Drawing;$im=[Drawing.Bitmap]::new(9,5);$g=[Drawing.Graphics]::FromImage($im);$g.Clear([Drawing.Color]::Coral);$s=[IO.MemoryStream]::new();$im.Save($s,[Drawing.Imaging.ImageFormat]::Png);$d=[Windows.Forms.DataObject]::new();$d.SetData("PNG",$false,$s);$d.SetImage($im);[Windows.Forms.Clipboard]::SetDataObject($d,$true);$g.Dispose();$im.Dispose();$result="written"' | |
| 53 | 新增: $returned=[Convert]::FromBase64String((Read-Guest 'png').png);$pngImage=[Drawing.Image]::FromStream([IO.MemoryStream]::new($returned));if($pngImage.Width -ne 9 -or $pngImage.Height -ne 5){throw 'Native guest PNG did not reach the host.'};$pngImage.Dispose() | |
| 54 | 新增: $fixture=Join-Path $EvidenceDirectory ([guid]::NewGuid().ToString('N'));$null=[IO.Directory]::CreateDirectory($fixture) | |
| 55 | 新增: $file=Join-Path $fixture '中文😀.txt';$content=$utf8.GetBytes('Host to guest file 中文😀');[IO.File]::WriteAllBytes($file,$content) | |
| 56 | 新增: $script:phase='host_file_import';$writer=Start-Bridge 'export' $true;Send-JSON $writer @($file);$writer.StandardInput.Close() | |
| 57 | 新增: $importer=Start-Bridge 'import';$writer.StandardOutput.BaseStream.CopyTo($importer.StandardInput.BaseStream);$importer.StandardInput.Close();$imported=Read-JSON $importer;Check-Exit $writer;Check-Exit $importer | |
| 58 | 新增: if(@($imported.paths).Count -ne 1){throw 'The imported file selection is invalid.'} | |
| 59 | 新增: $script:phase='host_file_ack';Send-JSON $clipboard @{serial=3;files=@($imported.paths)};Read-Ack 3 | |
| 60 | 新增: $script:phase='host_file_native_read';$read=Invoke-Native '$files=[Windows.Forms.Clipboard]::GetFileDropList();if($files.Count -ne 1){throw "selection_invalid"};$b=[IO.File]::ReadAllBytes($files[0]);$result=[BitConverter]::ToString([Security.Cryptography.SHA256]::Create().ComputeHash($b)).Replace("-","").ToLowerInvariant()' | |
| 61 | 新增: if($read -ne (SHA $content)){throw 'The actual native GUI file-drop bytes do not match.'} | |
| 62 | 新增: $guestContent=$utf8.GetBytes('Guest to host file 中文😀');$guest64=[Convert]::ToBase64String($guestContent) | |
| 63 | 新增: $script:phase='guest_file_native_write';$null=Invoke-Native ('$dir=Join-Path ([IO.Path]::GetTempPath()) ("cage-clipboard-qa-"+[guid]::NewGuid().ToString("N"));$null=[IO.Directory]::CreateDirectory($dir);$f=Join-Path $dir "guest.txt";[IO.File]::WriteAllBytes($f,[Convert]::FromBase64String("'+$guest64+'"));$list=[Collections.Specialized.StringCollection]::new();$null=$list.Add($f);[Windows.Forms.Clipboard]::SetFileDropList($list);$result="written"') | |
| 64 | 新增: $selected=Read-Guest 'files';$exporter=Start-Bridge 'export';Send-JSON $exporter @($selected.files);$exporter.StandardInput.Close() | |
| 65 | 新增: $reader=Start-Bridge 'import' $true;$exporter.StandardOutput.BaseStream.CopyTo($reader.StandardInput.BaseStream);$reader.StandardInput.Close();$received=Read-JSON $reader;Check-Exit $exporter;Check-Exit $reader | |
| 66 | 新增: if(@($received.paths).Count -ne 1 -or (SHA ([IO.File]::ReadAllBytes($received.paths[0]))) -ne (SHA $guestContent)){throw 'The native guest selection did not export completely.'} | |
| 67 | 新增: # Host paths cannot bypass the GUI agent's recorded selection grants. | |
| 68 | 新增: $rejected=Start-Bridge 'export';Send-JSON $rejected @('C:\Windows\win.ini');$rejected.StandardInput.Close();$rejected.StandardOutput.BaseStream.CopyTo([IO.Stream]::Null);if(!$rejected.WaitForExit(30000) -or $rejected.ExitCode -eq 0){throw 'An unselected guest path was exported.'} | |
| 69 | 新增: if($echoes -ne 0){throw 'A host clipboard write was echoed as a guest selection.'} | |
| 70 | 新增: $result=[ordered]@{public_hello=$true;ordinary_gui_conpty=$true;terminal_resize=$true;text_host_to_guest=$true;text_guest_to_host=$true;png_host_to_guest_bytes=$true;png_guest_to_host_dimensions=$true;files_host_to_guest_bytes=$true;files_guest_to_host_bytes=$true;unselected_export_denied=$true;host_echoes=0} | |
| 71 | 新增: $null=[IO.Directory]::CreateDirectory($EvidenceDirectory);[IO.File]::WriteAllText((Join-Path $EvidenceDirectory 'clipboard-result.json'),($result|ConvertTo-Json -Depth 3),$utf8) | |
| 72 | 新增: $result|ConvertTo-Json -Compress | |
| 73 | 新增:} finally {foreach($p in $owned){try{$p.StandardInput.Close();if(!$p.WaitForExit(1000)){$p.Kill()};$p.Dispose()}catch{}}} | |
| @@ -0,0 +1,87 @@ | ||
| 1 | 新增:#requires -Version 5.1 | |
| 2 | 新增:#requires -RunAsAdministrator | |
| 3 | 新增:[CmdletBinding(SupportsShouldProcess)] | |
| 4 | 新增:param( | |
| 5 | 新增: [Parameter(Mandatory)][string]$ProfilePath, | |
| 6 | 新增: [Parameter(Mandatory)][string]$PayloadDirectory, | |
| 7 | 新增: [Parameter(Mandatory)][pscredential]$GuestAdministrator, | |
| 8 | 新增: [switch]$RestartActiveBridge, | |
| 9 | 新增: [switch]$GuestOnly | |
| 10 | 新增:) | |
| 11 | 新增:$ErrorActionPreference='Stop';$ProgressPreference='SilentlyContinue' | |
| 12 | 新增:$profile=Get-Item -LiteralPath $ProfilePath | |
| 13 | 新增:if($profile -isnot [IO.FileInfo] -or $profile.Length -gt 16384 -or $profile.Attributes -band [IO.FileAttributes]::ReparsePoint){throw 'Invalid protected guest binding.'} | |
| 14 | 新增:$binding=Get-Content -LiteralPath $profile.FullName -Raw|ConvertFrom-Json | |
| 15 | 新增:$vm=Get-VM -Id ([guid]$binding.vm_id) | |
| 16 | 新增:if($binding.version -ne 1 -or $vm.State -ne 'Running' -or @(Get-VMNetworkAdapter -VM $vm).Count -ne 0 -or | |
| 17 | 新增: $profile.Directory.FullName -ne [IO.Path]::GetDirectoryName($binding.relay_executable) -or | |
| 18 | 新增: !(Test-Path -LiteralPath $binding.pairing_file)){throw 'The existing VM/profile binding is not usable.'} | |
| 19 | 新增:$payload=Get-Item -LiteralPath $PayloadDirectory | |
| 20 | 新增:if($payload -isnot [IO.DirectoryInfo] -or $payload.Attributes -band [IO.FileAttributes]::ReparsePoint){throw 'Select a local payload directory.'} | |
| 21 | 新增:foreach($entry in (Get-ChildItem -LiteralPath $payload.FullName -Recurse -Force)){if($entry.Attributes -band [IO.FileAttributes]::ReparsePoint){throw 'Payload links are not allowed.'}} | |
| 22 | 新增:foreach($name in @('Cage.GuestClipboard.exe','cage-guest-files.exe')){if(!(Test-Path -LiteralPath (Join-Path $payload.FullName $name))){throw 'The fixed bridge payloads are required.'}} | |
| 23 | 新增:if(!$GuestOnly){ | |
| 24 | 新增: # A running packet or clipboard relay maps this host executable. Detect | |
| 25 | 新增: # that conflict before stopping the independent guest GUI agent. | |
| 26 | 新增: $image=[IO.Path]::GetFileNameWithoutExtension($binding.relay_executable) | |
| 27 | 新增: foreach($process in [Diagnostics.Process]::GetProcessesByName($image)){ | |
| 28 | 新增: try { if($process.MainModule.FileName -ieq $binding.relay_executable){throw 'The bound host relay is active. Close its associated workbench before a full update, or use GuestOnly with a compatible host relay.'} } | |
| 29 | 新增: finally { $process.Dispose() } | |
| 30 | 新增: } | |
| 31 | 新增:} | |
| 32 | 新增:if(!$PSCmdlet.ShouldProcess($vm.Id,'Update only the independently bound guest bridge application files')){return} | |
| 33 | 新增:$session=New-PSSession -VMId $vm.Id -Credential $GuestAdministrator | |
| 34 | 新增:$deployment=$null | |
| 35 | 新增:try { | |
| 36 | 新增: $deployment=Invoke-Command -Session $session -ArgumentList $vm.Id,$binding.gui_user_sid,[bool]$RestartActiveBridge -ScriptBlock { | |
| 37 | 新增: param($expected,$sid,$restart) | |
| 38 | 新增: $ErrorActionPreference='Stop';$ProgressPreference='SilentlyContinue' | |
| 39 | 新增: if([guid](Get-ItemProperty -LiteralPath 'HKLM:\SOFTWARE\Microsoft\Virtual Machine\Guest\Parameters').VirtualMachineId -ne $expected){throw 'guest_identity_mismatch'} | |
| 40 | 新增: $name="Cage-GUI-Bridge-$expected-$sid";$task=Get-ScheduledTask -TaskName $name | |
| 41 | 新增: $program=Join-Path $env:ProgramFiles ("Cage Guest Bridge\"+$expected) | |
| 42 | 新增: $actualSID=([Security.Principal.NTAccount]::new($task.Principal.UserId)).Translate([Security.Principal.SecurityIdentifier]).Value | |
| 43 | 新增: if($task.Description -cne "Cage protected GUI bridge $expected $sid" -or $actualSID -ne $sid -or | |
| 44 | 新增: $task.Principal.RunLevel -ne 'Limited' -or $task.Principal.LogonType -ne 'Interactive' -or | |
| 45 | 新增: $task.Actions.Count -ne 1 -or $task.Actions[0].Execute -ine (Join-Path $program 'Cage.GuestClipboard.exe')){throw 'The GUI task does not match the owned deployment.'} | |
| 46 | 新增: $active=$task.State -eq 'Running' | |
| 47 | 新增: if($active -and !$restart){throw 'The bridge is active. Close its workbench before updating, or explicitly request RestartActiveBridge.'} | |
| 48 | 新增: if($active){ | |
| 49 | 新增: Stop-ScheduledTask -InputObject $task | |
| 50 | 新增: $until=[DateTime]::UtcNow.AddSeconds(10) | |
| 51 | 新增: while((Get-ScheduledTask -TaskName $name).State -eq 'Running' -and [DateTime]::UtcNow -lt $until){Start-Sleep -Milliseconds 100} | |
| 52 | 新增: if((Get-ScheduledTask -TaskName $name).State -eq 'Running'){throw 'The owned bridge did not stop; preserved its application files.'} | |
| 53 | 新增: } | |
| 54 | 新增: [pscustomobject]@{Program=$program;Task=$name;WasActive=$active} | |
| 55 | 新增: } | |
| 56 | 新增: foreach($entry in (Get-ChildItem -LiteralPath $payload.FullName -Force)){Copy-Item -LiteralPath $entry.FullName -Destination $deployment.Program -Recurse -ToSession $session -Force} | |
| 57 | 新增: if(!$GuestOnly){foreach($entry in (Get-ChildItem -LiteralPath $payload.FullName -Force)){Copy-Item -LiteralPath $entry.FullName -Destination $profile.Directory.FullName -Recurse -Force}} | |
| 58 | 新增: $started=Invoke-Command -Session $session -ArgumentList $deployment.Task,$binding.gui_user_sid,$deployment.Program -ScriptBlock { | |
| 59 | 新增: param($name,$sid,$program) | |
| 60 | 新增: $administrators=[Security.Principal.SecurityIdentifier]::new('S-1-5-32-544') | |
| 61 | 新增: foreach($entry in @((Get-Item -LiteralPath $program)) + @(Get-ChildItem -LiteralPath $program -Recurse -Force)){ | |
| 62 | 新增: if($entry.Attributes -band [IO.FileAttributes]::ReparsePoint){throw 'Guest application files must not traverse links.'} | |
| 63 | 新增: $acl=Get-Acl -LiteralPath $entry.FullName;$acl.SetOwner($administrators);Set-Acl -LiteralPath $entry.FullName -AclObject $acl | |
| 64 | 新增: } | |
| 65 | 新增: $gui=@(Get-CimInstance Win32_Process -Filter "Name='explorer.exe'"|Where-Object {$_.SessionId -gt 0}|ForEach-Object{Invoke-CimMethod -InputObject $_ -MethodName GetOwnerSid}|Where-Object {$_.Sid -eq $sid}).Count -gt 0 | |
| 66 | 新增: if($gui){Start-ScheduledTask -TaskName $name};$gui | |
| 67 | 新增: } | |
| 68 | 新增: if(@(Get-VMNetworkAdapter -VM (Get-VM -Id $vm.Id)).Count -ne 0){throw 'VM networking changed during update.'} | |
| 69 | 新增: [pscustomobject]@{Updated=$true;HostRelayUpdated=(!$GuestOnly);RequiresGUILogin=(!$started);PairingPreserved=$true;PersonalDataPreserved=$true} | |
| 70 | 新增:} catch { | |
| 71 | 新增: $failure=$_ | |
| 72 | 新增: if($deployment -and $deployment.WasActive -and $session.State -eq 'Opened'){ | |
| 73 | 新增: try { | |
| 74 | 新增: Invoke-Command -Session $session -ArgumentList $deployment.Task,$deployment.Program -ScriptBlock { | |
| 75 | 新增: param($name,$program) | |
| 76 | 新增: $ErrorActionPreference='Stop';$ProgressPreference='SilentlyContinue' | |
| 77 | 新增: $exe=Join-Path $program 'Cage.GuestClipboard.exe' | |
| 78 | 新增: if((Get-Item -LiteralPath $exe).Attributes -band [IO.FileAttributes]::ReparsePoint){throw 'Bridge executable changed to a link.'} | |
| 79 | 新增: # Do not launch a truncated executable after a failed copy. | |
| 80 | 新增: & $exe self-test | Out-Null | |
| 81 | 新增: if($LASTEXITCODE -ne 0){throw 'The copied bridge failed its self-test.'} | |
| 82 | 新增: Start-ScheduledTask -TaskName $name | |
| 83 | 新增: } | Out-Null | |
| 84 | 新增: } catch { throw 'The bridge update failed and its GUI task could not be restored; preserve the binding and application files for recovery.' } | |
| 85 | 新增: } | |
| 86 | 新增: throw $failure | |
| 87 | 新增:} finally { Remove-PSSession $session } | |
| @@ -0,0 +1,120 @@ | ||
| 1 | 新增:#requires -Version 5.1 | |
| 2 | 新增:<# | |
| 3 | 新增:.SYNOPSIS | |
| 4 | 新增:Create isolated QA accounts after an authorized guest administrator completes Windows OOBE. | |
| 5 | 新增:.DESCRIPTION | |
| 6 | 新增:Supply a guest administrator credential with Get-Credential. Both new accounts | |
| 7 | 新增:get independent random passwords. On Windows, Export-Clixml protects the saved | |
| 8 | 新增:credentials with DPAPI for this host user. Use the returned AdminCredentialFile | |
| 9 | 新增:with Import-Clixml and New-PSSession -VMId for later PowerShell Direct sessions. | |
| 10 | 新增:The standard user is intended for the interactive Claude Desktop session. | |
| 11 | 新增:#> | |
| 12 | 新增:[CmdletBinding()] | |
| 13 | 新增:param( | |
| 14 | 新增: [Parameter(Mandatory)][guid]$VMId, | |
| 15 | 新增: [Parameter(Mandatory)][string]$InstanceDirectory, | |
| 16 | 新增: [Parameter(Mandatory)][pscredential]$GuestAdministrator | |
| 17 | 新增:) | |
| 18 | 新增:$ErrorActionPreference = 'Stop' | |
| 19 | 新增:if ([Environment]::OSVersion.Platform -ne 'Win32NT') { throw 'Run on the Hyper-V host in Windows PowerShell.' } | |
| 20 | 新增:$root = Get-Item -LiteralPath $InstanceDirectory | |
| 21 | 新增:$qa = Join-Path $root.FullName 'evaluation-setup' | |
| 22 | 新增:$qaDir = Get-Item -LiteralPath $qa | |
| 23 | 新增:if (($root.Attributes -band [IO.FileAttributes]::ReparsePoint) -or ($qaDir.Attributes -band [IO.FileAttributes]::ReparsePoint)) { | |
| 24 | 新增: throw 'The private QA directories cannot be redirected.' | |
| 25 | 新增:} | |
| 26 | 新增:$receipt = Get-Content -LiteralPath (Join-Path $qa 'receipt.json') -Raw | ConvertFrom-Json | |
| 27 | 新增:$vm = Get-VM -Id $VMId | |
| 28 | 新增:$disks = @(Get-VMHardDiskDrive -VM $vm) | |
| 29 | 新增:if ([guid]$receipt.VMId -ne $VMId -or $receipt.InstanceDirectory -ne $root.FullName -or $vm.State -ne 'Running' -or | |
| 30 | 新增: $disks.Count -ne 1 -or $disks[0].Path -ne $receipt.Disk -or @(Get-VMNetworkAdapter -VM $vm).Count) { | |
| 31 | 新增: throw 'Select the running offline evaluation VM that owns this setup receipt.' | |
| 32 | 新增:} | |
| 33 | 新增:$session = New-PSSession -VMId $VMId -Credential $GuestAdministrator | |
| 34 | 新增:try { | |
| 35 | 新增: $guestComputer = Invoke-Command -Session $session -ArgumentList $VMId -ScriptBlock { | |
| 36 | 新增: param($expected) | |
| 37 | 新增: $ErrorActionPreference = 'Stop' | |
| 38 | 新增: $identity = Get-ItemProperty 'HKLM:\SOFTWARE\Microsoft\Virtual Machine\Guest\Parameters' -Name VirtualMachineId | |
| 39 | 新增: $setup = Get-ItemProperty 'HKLM:\SYSTEM\Setup' | |
| 40 | 新增: $imageState = Get-ItemProperty 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Setup\State' -Name ImageState | |
| 41 | 新增: $os = Get-ItemProperty 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion' -Name EditionID | |
| 42 | 新增: $account = [Security.Principal.WindowsPrincipal]::new([Security.Principal.WindowsIdentity]::GetCurrent()) | |
| 43 | 新增: if ([guid]$identity.VirtualMachineId -ne $expected -or $os.EditionID -ne 'EnterpriseEval' -or | |
| 44 | 新增: $setup.SystemSetupInProgress -ne 0 -or $setup.OOBEInProgress -eq 1 -or $imageState.ImageState -ne 'IMAGE_STATE_COMPLETE' -or | |
| 45 | 新增: !$account.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) { | |
| 46 | 新增: throw 'PowerShell Direct must reach the matching Enterprise Evaluation guest after OOBE with guest administrator rights.' | |
| 47 | 新增: } | |
| 48 | 新增: $env:COMPUTERNAME | |
| 49 | 新增: } | |
| 50 | 新增: | |
| 51 | 新增: $credentials = @() | |
| 52 | 新增: $secrets = Join-Path $qa 'credentials' | |
| 53 | 新增: $owner = [Security.Principal.WindowsIdentity]::GetCurrent().User | |
| 54 | 新增: $permitted = @($owner.Value, 'S-1-5-18', 'S-1-5-32-544') | |
| 55 | 新增: if (!(Test-Path -LiteralPath $secrets)) { | |
| 56 | 新增: $acl = [Security.AccessControl.DirectorySecurity]::new() | |
| 57 | 新增: $acl.SetAccessRuleProtection($true, $false) | |
| 58 | 新增: $acl.SetOwner($owner) | |
| 59 | 新增: foreach ($value in $permitted) { | |
| 60 | 新增: $sid = [Security.Principal.SecurityIdentifier]::new($value) | |
| 61 | 新增: $acl.AddAccessRule([Security.AccessControl.FileSystemAccessRule]::new($sid, 'FullControl', 'ContainerInherit, ObjectInherit', 'None', 'Allow')) | |
| 62 | 新增: } | |
| 63 | 新增: if ($PSVersionTable.PSEdition -eq 'Desktop') { | |
| 64 | 新增: $null = [IO.Directory]::CreateDirectory($secrets, $acl) | |
| 65 | 新增: } else { [IO.FileSystemAclExtensions]::Create([IO.DirectoryInfo]::new($secrets), $acl) } | |
| 66 | 新增: } | |
| 67 | 新增: $secretsDir = Get-Item -LiteralPath $secrets | |
| 68 | 新增: $acl = Get-Acl -LiteralPath $secrets | |
| 69 | 新增: $unexpected = @($acl.GetAccessRules($true, $true, [Security.Principal.SecurityIdentifier]) | | |
| 70 | 新增: Where-Object { $_.AccessControlType -eq 'Allow' -and $_.IdentityReference.Value -notin $permitted }) | |
| 71 | 新增: if (($secretsDir.Attributes -band [IO.FileAttributes]::ReparsePoint) -or !$acl.AreAccessRulesProtected -or $unexpected.Count) { | |
| 72 | 新增: throw 'The test credential directory must have a private, protected Windows ACL.' | |
| 73 | 新增: } | |
| 74 | 新增: foreach ($name in @('CageQaAdmin', 'CageQaUser')) { | |
| 75 | 新增: $path = Join-Path $secrets "$name.credential.xml" | |
| 76 | 新增: $qualified = "$guestComputer\$name" | |
| 77 | 新增: if (Test-Path -LiteralPath $path) { | |
| 78 | 新增: $credential = Import-Clixml -LiteralPath $path | |
| 79 | 新增: if ($credential -isnot [pscredential] -or $credential.UserName -ne $qualified) { throw 'Unexpected saved QA credential identity.' } | |
| 80 | 新增: } else { | |
| 81 | 新增: $random = [byte[]]::new(32) | |
| 82 | 新增: $generator = [Security.Cryptography.RandomNumberGenerator]::Create() | |
| 83 | 新增: try { $generator.GetBytes($random) } finally { $generator.Dispose() } | |
| 84 | 新增: $password = ConvertTo-SecureString ('Qa9!' + [Convert]::ToBase64String($random)) -AsPlainText -Force | |
| 85 | 新增: $credential = [pscredential]::new($qualified, $password) | |
| 86 | 新增: $credential | Export-Clixml -LiteralPath $path -NoClobber | |
| 87 | 新增: } | |
| 88 | 新增: $credentials += $credential | |
| 89 | 新增: } | |
| 90 | 新增: $provision = Invoke-Command -Session $session -ArgumentList $VMId,$credentials[0],$credentials[1] -ScriptBlock { | |
| 91 | 新增: param($expected, [pscredential]$admin, [pscredential]$standard) | |
| 92 | 新增: $ErrorActionPreference = 'Stop' | |
| 93 | 新增: $tag = "Cage isolated test VM $expected" | |
| 94 | 新增: $admins = Get-LocalGroup -SID ([Security.Principal.SecurityIdentifier]::new('S-1-5-32-544')) | |
| 95 | 新增: $users = Get-LocalGroup -SID ([Security.Principal.SecurityIdentifier]::new('S-1-5-32-545')) | |
| 96 | 新增: foreach ($credential in @($admin,$standard)) { | |
| 97 | 新增: $name = $credential.UserName.Split('\')[-1] | |
| 98 | 新增: $u = Get-LocalUser -Name $name -ErrorAction SilentlyContinue | |
| 99 | 新增: if ($u -and $u.Description -ne $tag) { throw "An unrelated guest account already uses the name $name." } | |
| 100 | 新增: if (!$u) { $u = New-LocalUser -Name $name -Password $credential.Password -Description $tag } | |
| 101 | 新增: $group = if ($name -eq 'CageQaAdmin') { $admins } else { $users } | |
| 102 | 新增: if (!(Get-LocalGroupMember -Group $group | Where-Object { $_.SID -eq $u.SID })) { | |
| 103 | 新增: Add-LocalGroupMember -Group $group -Member $u | |
| 104 | 新增: } | |
| 105 | 新增: if ($name -eq 'CageQaUser' -and (Get-LocalGroupMember -Group $admins | Where-Object { $_.SID -eq $u.SID })) { | |
| 106 | 新增: throw 'The test desktop user is unexpectedly an administrator.' | |
| 107 | 新增: } | |
| 108 | 新增: } | |
| 109 | 新增: [pscustomobject]@{ Computer = $env:COMPUTERNAME; Admin = 'CageQaAdmin'; DesktopUser = 'CageQaUser' } | |
| 110 | 新增: } | |
| 111 | 新增: # Authenticate a fresh VMBus session using the new administrator. | |
| 112 | 新增: $verified = Invoke-Command -VMId $VMId -Credential $credentials[0] -ScriptBlock { [Security.Principal.WindowsIdentity]::GetCurrent().Name } | |
| 113 | 新增: if ($verified -ne $credentials[0].UserName) { throw 'The independent PowerShell Direct login did not match the QA administrator.' } | |
| 114 | 新增: [pscustomobject]@{ | |
| 115 | 新增: VMId = $VMId; Computer = $provision.Computer; Admin = $provision.Admin; StandardDesktopUser = $provision.DesktopUser | |
| 116 | 新增: PowerShellDirectVerified = $true | |
| 117 | 新增: AdminCredentialFile = Join-Path $secrets 'CageQaAdmin.credential.xml' | |
| 118 | 新增: DesktopCredentialFile = Join-Path $secrets 'CageQaUser.credential.xml' | |
| 119 | 新增: } | |
| 120 | 新增:} finally { Remove-PSSession -Session $session } | |
| @@ -0,0 +1,126 @@ | ||
| 1 | 新增:# Invoked by the first-run installer inside its own VM through PowerShell Direct. | |
| 2 | 新增:# No password is serialized, passed on a command line, or returned to the host. | |
| 3 | 新增:param([Parameter(Mandatory)][guid]$VMId) | |
| 4 | 新增:$ErrorActionPreference='Stop' | |
| 5 | 新增:$machine=Get-CimInstance Win32_ComputerSystem | |
| 6 | 新增:if ($VMId -eq [guid]::Empty -or $machine.Manufacturer -ne 'Microsoft Corporation' -or $machine.Model -ne 'Virtual Machine' -or | |
| 7 | 新增: [guid](Get-ItemProperty 'HKLM:\SOFTWARE\Microsoft\Virtual Machine\Guest\Parameters').VirtualMachineId -ne $VMId) { throw 'This operation requires the exact fresh Cage guest.' } | |
| 8 | 新增:$userName='Cage-'+$VMId.ToString('N').Substring(0,10) | |
| 9 | 新增:$description='Cage '+$VMId.ToString('D') | |
| 10 | 新增:$key='HKLM:\SOFTWARE\Cage\WorkbenchBoot\'+$VMId.ToString('D') | |
| 11 | 新增:$logon='HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon' | |
| 12 | 新增:$win=Get-Item -LiteralPath $logon | |
| 13 | 新增:$user=Get-LocalUser -Name $userName -ErrorAction SilentlyContinue | |
| 14 | 新增:$record=if(Test-Path -LiteralPath $key){Get-ItemProperty -LiteralPath $key} | |
| 15 | 新增:if ($record -and ($record.VM -ne $VMId.ToString('D') -or $record.User -ne $userName)) { throw 'An existing boot-account registration was preserved.' } | |
| 16 | 新增:if ($user -and (!$record -or $user.Description -cne $description -or ($record.SID -and $record.SID -ne $user.SID.Value))) { throw 'An existing Windows account cannot be used for automatic logon.' } | |
| 17 | 新增:if ($win.GetValueNames() -contains 'DefaultPassword' -or $win.GetValue('ForceAutoLogon','0') -ne '0' -or | |
| 18 | 新增: ($win.GetValue('AutoAdminLogon','0') -eq '1' -and (!$record -or $win.GetValue('DefaultUserName','') -ne $userName))) { | |
| 19 | 新增: throw 'An existing Windows logon policy was preserved.' | |
| 20 | 新增:} | |
| 21 | 新增:if (!$record -or $record.Stage -ne 'ready') { | |
| 22 | 新增: if (!$user -and $record -and $record.SID) { throw 'The dedicated account was removed. No replacement was created.' } | |
| 23 | 新增: # Microsoft's Winlogon LSA API. Only the fixed DefaultPassword object may | |
| 24 | 新增: # be tested for existence or created. Its contents cannot be read here. | |
| 25 | 新增: if (!('CageWorkbenchBootSecret' -as [type])) { | |
| 26 | 新增: Add-Type -TypeDefinition @' | |
| 27 | 新增:using System; | |
| 28 | 新增:using System.Runtime.InteropServices; | |
| 29 | 新增:using System.Security; | |
| 30 | 新增:using System.ComponentModel; | |
| 31 | 新增:public static class CageWorkbenchBootSecret { | |
| 32 | 新增: [StructLayout(LayoutKind.Sequential)] | |
| 33 | 新增: struct Attributes { public uint length; public IntPtr root, name; public uint flags; public IntPtr descriptor, quality; } | |
| 34 | 新增: [StructLayout(LayoutKind.Sequential)] | |
| 35 | 新增: struct Unicode { public ushort length, maximum; public IntPtr text; } | |
| 36 | 新增: [DllImport("advapi32.dll")] static extern int LsaOpenPolicy(IntPtr system,ref Attributes attr,uint access,out IntPtr policy); | |
| 37 | 新增: [DllImport("advapi32.dll")] static extern int LsaOpenSecret(IntPtr policy,ref Unicode name,uint access,out IntPtr secret); | |
| 38 | 新增: [DllImport("advapi32.dll")] static extern int LsaQuerySecret(IntPtr secret,out IntPtr current,IntPtr setTime,IntPtr previous,IntPtr previousSetTime); | |
| 39 | 新增: [DllImport("advapi32.dll")] static extern int LsaFreeMemory(IntPtr memory); | |
| 40 | 新增: [DllImport("advapi32.dll")] static extern int LsaStorePrivateData(IntPtr policy,ref Unicode name,ref Unicode data); | |
| 41 | 新增: [DllImport("advapi32.dll")] static extern int LsaNtStatusToWinError(int code); | |
| 42 | 新增: [DllImport("advapi32.dll")] static extern int LsaClose(IntPtr handle); | |
| 43 | 新增: static bool CheckOrStore(SecureString password) { | |
| 44 | 新增: var attr=new Attributes(); attr.length=(uint)Marshal.SizeOf(typeof(Attributes)); | |
| 45 | 新增: IntPtr policy; int code=LsaOpenPolicy(IntPtr.Zero,ref attr,0x24,out policy); | |
| 46 | 新增: if(code!=0)throw new Win32Exception(LsaNtStatusToWinError(code)); | |
| 47 | 新增: const string fixedName="DefaultPassword"; var name=new Unicode(); | |
| 48 | 新增: name.length=(ushort)(fixedName.Length*2);name.maximum=(ushort)(name.length+2);name.text=Marshal.StringToHGlobalUni(fixedName); | |
| 49 | 新增: try { | |
| 50 | 新增: IntPtr existing; code=LsaOpenSecret(policy,ref name,2,out existing); | |
| 51 | 新增: if(code==0){ | |
| 52 | 新增: // Fresh Windows can create the LSA object without assigning it | |
| 53 | 新增: // a password. Inspect only the length field, never its buffer. | |
| 54 | 新增: IntPtr valueHeader=IntPtr.Zero; | |
| 55 | 新增: try { | |
| 56 | 新增: code=LsaQuerySecret(existing,out valueHeader,IntPtr.Zero,IntPtr.Zero,IntPtr.Zero); | |
| 57 | 新增: if(code!=0 && unchecked((uint)code)!=0xc0000034U)throw new Win32Exception(LsaNtStatusToWinError(code)); | |
| 58 | 新增: if(valueHeader!=IntPtr.Zero && Marshal.ReadInt16(valueHeader)!=0){ | |
| 59 | 新增: if(password==null)return true; | |
| 60 | 新增: throw new InvalidOperationException("An existing Winlogon LSA secret was preserved."); | |
| 61 | 新增: } | |
| 62 | 新增: } finally {if(valueHeader!=IntPtr.Zero)LsaFreeMemory(valueHeader);LsaClose(existing);} | |
| 63 | 新增: } else if(unchecked((uint)code)!=0xc0000034U)throw new Win32Exception(LsaNtStatusToWinError(code)); | |
| 64 | 新增: if(password==null)return false; | |
| 65 | 新增: var value=new Unicode(); value.length=checked((ushort)(password.Length*2));value.maximum=(ushort)(value.length+2); | |
| 66 | 新增: value.text=Marshal.SecureStringToGlobalAllocUnicode(password); | |
| 67 | 新增: try {code=LsaStorePrivateData(policy,ref name,ref value);if(code!=0)throw new Win32Exception(LsaNtStatusToWinError(code));} | |
| 68 | 新增: finally {Marshal.ZeroFreeGlobalAllocUnicode(value.text);} | |
| 69 | 新增: return true; | |
| 70 | 新增: } finally {Marshal.FreeHGlobal(name.text);LsaClose(policy);} | |
| 71 | 新增: } | |
| 72 | 新增: public static bool Exists() { return CheckOrStore(null); } | |
| 73 | 新增: public static void StoreNew(SecureString password) { if(password==null)throw new ArgumentNullException();CheckOrStore(password); } | |
| 74 | 新增:} | |
| 75 | 新增:'@ | |
| 76 | 新增: } | |
| 77 | 新增: $hasSecret=[CageWorkbenchBootSecret]::Exists() | |
| 78 | 新增: if ($hasSecret -and (!$record -or $record.Stage -ne 'storing' -or !$user -or $record.SID -ne $user.SID.Value -or $user.LastLogon)) { | |
| 79 | 新增: throw 'An existing Winlogon secret was preserved.' | |
| 80 | 新增: } | |
| 81 | 新增: if (!$record) { | |
| 82 | 新增: $null=New-Item -Path $key -Force | |
| 83 | 新增: $null=New-ItemProperty -LiteralPath $key -Name VM -Value $VMId.ToString('D') -PropertyType String | |
| 84 | 新增: $null=New-ItemProperty -LiteralPath $key -Name User -Value $userName -PropertyType String | |
| 85 | 新增: } | |
| 86 | 新增: if (!$hasSecret) { | |
| 87 | 新增: if ($user -and ($user.Enabled -or $user.LastLogon)) {throw 'The partially prepared user has already been used. Its password was preserved.'} | |
| 88 | 新增: $random=[Security.Cryptography.RandomNumberGenerator]::Create() | |
| 89 | 新增: $bytes=New-Object byte[] 48 | |
| 90 | 新增: $password=[Security.SecureString]::new() | |
| 91 | 新增: try { | |
| 92 | 新增: $random.GetBytes($bytes) | |
| 93 | 新增: $alphabet='abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_' | |
| 94 | 新增: foreach ($b in $bytes) { $password.AppendChar($alphabet[[int]$b -band 63]) } | |
| 95 | 新增: foreach ($c in 'a9Q!'.ToCharArray()) { $password.AppendChar($c) } | |
| 96 | 新增: $password.MakeReadOnly() | |
| 97 | 新增: if (!$user) { | |
| 98 | 新增: $user=New-LocalUser -Name $userName -Password $password -Disabled -Description $description -PasswordNeverExpires -UserMayNotChangePassword | |
| 99 | 新增: } else { | |
| 100 | 新增: # Only our disabled, never-used account can reach this interrupted | |
| 101 | 新增: # initial transaction. An enabled account never has its password reset. | |
| 102 | 新增: Set-LocalUser -InputObject $user -Password $password | |
| 103 | 新增: } | |
| 104 | 新增: $null=New-ItemProperty -LiteralPath $key -Name SID -Value $user.SID.Value -PropertyType String -Force | |
| 105 | 新增: $null=New-ItemProperty -LiteralPath $key -Name Stage -Value 'storing' -PropertyType String -Force | |
| 106 | 新增: [CageWorkbenchBootSecret]::StoreNew($password) | |
| 107 | 新增: } finally { $password.Dispose();$random.Dispose();[Array]::Clear($bytes,0,$bytes.Length) } | |
| 108 | 新增: } | |
| 109 | 新增: if (!$user.Enabled) { Enable-LocalUser -InputObject $user } | |
| 110 | 新增: $user=Get-LocalUser -SID $user.SID | |
| 111 | 新增: $null=New-ItemProperty -LiteralPath $key -Name Stage -Value 'ready' -PropertyType String -Force | |
| 112 | 新增:} | |
| 113 | 新增:if (!$user) {throw 'The dedicated workbench account was removed. No replacement was created.'} | |
| 114 | 新增:if (!$user.Enabled -or $user.PrincipalSource -ne 'Local' -or $user.Description -cne $description) { throw 'The dedicated local account is unavailable.' } | |
| 115 | 新增:$sid=$user.SID.Value | |
| 116 | 新增:foreach ($group in Get-LocalGroup) { | |
| 117 | 新增: $member=@(Get-LocalGroupMember -Group $group -ErrorAction Stop | Where-Object { $_.SID.Value -eq $sid }) | |
| 118 | 新增: if ($member.Count -and $group.SID.Value -ne 'S-1-5-32-545') { throw 'The workbench account belongs to a privileged or unexpected group.' } | |
| 119 | 新增:} | |
| 120 | 新增:$users=Get-LocalGroup -SID 'S-1-5-32-545' | |
| 121 | 新增:if (!@(Get-LocalGroupMember -Group $users | Where-Object {$_.SID.Value -eq $sid}).Count) { Add-LocalGroupMember -Group $users -Member $user } | |
| 122 | 新增:$null=New-ItemProperty -LiteralPath $key -Name SID -Value $sid -PropertyType String -Force | |
| 123 | 新增: | |
| 124 | 新增:# First boot is armed by the separate boot service only during a real shutdown. | |
| 125 | 新增:# Windows logon UI is never sent a broad keyboard event or a cleartext value. | |
| 126 | 新增:[pscustomobject]@{ SID=$sid; Name=$userName; BootID=(Get-CimInstance Win32_OperatingSystem).LastBootUpTime.ToUniversalTime().ToString('o'); Program=(Join-Path $env:ProgramFiles ("Cage Guest Bridge\"+$VMId)); AlreadySignedIn=($machine.UserName -eq ($env:COMPUTERNAME+'\'+$userName)) } | |
| @@ -0,0 +1,45 @@ | ||
| 1 | 新增:@echo off | |
| 2 | 新增:setlocal EnableExtensions DisableDelayedExpansion | |
| 3 | 新增:rem Windows Setup runs this command from Cage's read-only answer DVD as SYSTEM. | |
| 4 | 新增:set "CAGE_PWSH_MEDIA=%~d0\" | |
| 5 | 新增:set "CAGE_PWSH_HASH=__CAGE_PWSH_SHA256__" | |
| 6 | 新增:set "CAGE_PWSH_VERSION=__CAGE_PWSH_VERSION__" | |
| 7 | 新增:"%SystemRoot%\System32\WindowsPowerShell\v1.0\powershell.exe" -NoLogo -NoProfile -NonInteractive -Command ^ | |
| 8 | 新增: "$ErrorActionPreference = 'Stop';" ^ | |
| 9 | 新增: "$medium = [IO.DriveInfo]::new($env:CAGE_PWSH_MEDIA);" ^ | |
| 10 | 新增: "if ($medium.DriveType -ne 'CDRom' -or $medium.VolumeLabel -ne 'CAGE_ANSWER' -or ![Environment]::Is64BitProcess -or ![Security.Principal.WindowsIdentity]::GetCurrent().IsSystem) { throw 'PowerShell guest installation requires Windows Setup and the Cage answer DVD.' }" ^ | |
| 11 | 新增: "$system = Get-CimInstance Win32_ComputerSystem;" ^ | |
| 12 | 新增: "if ($system.Manufacturer -ne 'Microsoft Corporation' -or $system.Model -ne 'Virtual Machine') { throw 'Expected the Hyper-V guest.' }" ^ | |
| 13 | 新增: "$zip = Join-Path $medium.RootDirectory.FullName 'PowerShell.zip';" ^ | |
| 14 | 新增: "$base = Join-Path ([Environment]::GetFolderPath('ProgramFiles')) 'PowerShell';" ^ | |
| 15 | 新增: "$target = Join-Path $base '7';" ^ | |
| 16 | 新增: "function Test-Runtime([string]$directory, [string]$expectedVersion) {" ^ | |
| 17 | 新增: " $exe = Join-Path $directory 'pwsh.exe';" ^ | |
| 18 | 新增: " $probe = @(& $exe -NoLogo -NoProfile -NonInteractive -Command '$PSVersionTable.PSVersion.ToString(); [Runtime.InteropServices.RuntimeInformation]::ProcessArchitecture.ToString()');" ^ | |
| 19 | 新增: " if ($LASTEXITCODE -ne 0 -or $probe.Count -ne 2 -or $probe[0] -notmatch '^7\.[0-9]+\.[0-9]+$' -or $probe[1] -ne 'X64' -or ($expectedVersion -and $probe[0] -ne $expectedVersion)) { throw 'The installed shell did not report the expected x64 PowerShell 7 version.' }" ^ | |
| 20 | 新增: "}" ^ | |
| 21 | 新增: "if ((Get-FileHash -LiteralPath $zip -Algorithm SHA256).Hash -ne $env:CAGE_PWSH_HASH) { throw 'The offline PowerShell package does not match its pinned SHA-256.' }" ^ | |
| 22 | 新增: "$null = [IO.Directory]::CreateDirectory($base);" ^ | |
| 23 | 新增: "if ((Get-Item -LiteralPath $base).Attributes -band [IO.FileAttributes]::ReparsePoint) { throw 'The PowerShell installation folder is redirected.' }" ^ | |
| 24 | 新增: "if (!(Test-Path -LiteralPath $target)) {" ^ | |
| 25 | 新增: " $stage = Join-Path $base ([guid]::NewGuid().ToString('N'));" ^ | |
| 26 | 新增: " try {" ^ | |
| 27 | 新增: " Add-Type -AssemblyName System.IO.Compression.FileSystem;" ^ | |
| 28 | 新增: " [IO.Compression.ZipFile]::ExtractToDirectory($zip, $stage);" ^ | |
| 29 | 新增: " Test-Runtime $stage $env:CAGE_PWSH_VERSION;" ^ | |
| 30 | 新增: " try { [IO.Directory]::Move($stage, $target) } catch [IO.IOException] { if (![IO.Directory]::Exists($target)) { throw } }" ^ | |
| 31 | 新增: " } finally { if ([IO.Directory]::Exists($stage)) { [IO.Directory]::Delete($stage, $true) } }" ^ | |
| 32 | 新增: "}" ^ | |
| 33 | 新增: "if ((Get-Item -LiteralPath $target).Attributes -band [IO.FileAttributes]::ReparsePoint) { throw 'The installed PowerShell directory is redirected.' }" ^ | |
| 34 | 新增: "Test-Runtime $target '';" ^ | |
| 35 | 新增: "$key = [Microsoft.Win32.Registry]::LocalMachine.OpenSubKey('SYSTEM\CurrentControlSet\Control\Session Manager\Environment', $true);" ^ | |
| 36 | 新增: "try {" ^ | |
| 37 | 新增: " $raw = [string]$key.GetValue('Path', '', [Microsoft.Win32.RegistryValueOptions]::DoNotExpandEnvironmentNames);" ^ | |
| 38 | 新增: " $entries = @($raw.Split(';') | ForEach-Object { [Environment]::ExpandEnvironmentVariables($_.Trim().Trim([char]34)).TrimEnd('\') });" ^ | |
| 39 | 新增: " if ($target -notin $entries) {" ^ | |
| 40 | 新增: " $newPath = if ($raw) { $target + ';' + $raw } else { $target };" ^ | |
| 41 | 新增: " $kind = if ('Path' -in $key.GetValueNames()) { $key.GetValueKind('Path') } else { [Microsoft.Win32.RegistryValueKind]::ExpandString };" ^ | |
| 42 | 新增: " $key.SetValue('Path', $newPath, $kind);" ^ | |
| 43 | 新增: " }" ^ | |
| 44 | 新增: "} finally { $key.Close() }" | |
| 45 | 新增:exit /b %errorlevel% | |
| @@ -0,0 +1,93 @@ | ||
| 1 | 新增:#requires -Version 5.1 | |
| 2 | 新增:# Exercise the actual Setup command with an isolated filesystem and registry stand-in. | |
| 3 | 新增:$ErrorActionPreference = 'Stop' | |
| 4 | 新增:$file = Join-Path $PSScriptRoot 'install-guest-powershell.cmd' | |
| 5 | 新增:$lines = @(Get-Content -LiteralPath $file | Where-Object { $_.StartsWith(' "') }) | |
| 6 | 新增:$parts = for ($i = 0; $i -lt $lines.Count; $i++) { | |
| 7 | 新增: $suffix = if ($i -lt $lines.Count - 1) { '" ^' } else { '"' } | |
| 8 | 新增: if (!$lines[$i].EndsWith($suffix)) { throw 'Broken CMD line continuation.' } | |
| 9 | 新增: $lines[$i].Substring(3, $lines[$i].Length - 3 - $suffix.Length) | |
| 10 | 新增:} | |
| 11 | 新增:$command = $parts -join ' ' | |
| 12 | 新增:if ($command.Length -gt 7700 -or $command.Contains('"') -or $command.Contains('%')) { | |
| 13 | 新增: throw 'The guest installer command may be truncated or expanded by cmd.exe.' | |
| 14 | 新增:} | |
| 15 | 新增:$errors = $null | |
| 16 | 新增:$ast = [Management.Automation.Language.Parser]::ParseInput($command, [ref]$null, [ref]$errors) | |
| 17 | 新增:if ($errors.Count) { throw $errors[0] } | |
| 18 | 新增:$steps = $ast.EndBlock.Statements | |
| 19 | 新增:$installStart = @($steps | Where-Object { $_.Extent.Text.StartsWith('if ((Get-FileHash ') })[0] | |
| 20 | 新增:$regStart = @($steps | Where-Object { $_.Extent.Text.StartsWith('$key = ') })[0] | |
| 21 | 新增:$install = [scriptblock]::Create($command.Substring($installStart.Extent.StartOffset, $regStart.Extent.StartOffset - $installStart.Extent.StartOffset)) | |
| 22 | 新增:$updatePath = [scriptblock]::Create($steps[-1].Extent.Text) | |
| 23 | 新增: | |
| 24 | 新增:function Assert-Failure([scriptblock]$run, [string]$message) { | |
| 25 | 新增: try { & $run } catch { | |
| 26 | 新增: if ($_.Exception.Message -like "*$message*") { return } | |
| 27 | 新增: throw | |
| 28 | 新增: } | |
| 29 | 新增: throw "Expected failure: $message" | |
| 30 | 新增:} | |
| 31 | 新增: | |
| 32 | 新增:# The archive, hash checks, staging, publication, cleanup and retry are real. | |
| 33 | 新增:# Simulate the version response of a Windows executable on non-Windows hosts. | |
| 34 | 新增:function Test-Runtime([string]$directory, [string]$expectedVersion) { | |
| 35 | 新增: $version = [IO.File]::ReadAllText((Join-Path $directory 'pwsh.exe')) | |
| 36 | 新增: if ($version -notmatch '^7\.[0-9]+\.[0-9]+$' -or ($expectedVersion -and $expectedVersion -ne $version)) { | |
| 37 | 新增: throw 'Simulated incompatible runtime' | |
| 38 | 新增: } | |
| 39 | 新增:} | |
| 40 | 新增: | |
| 41 | 新增:$oldHash = $env:CAGE_PWSH_HASH | |
| 42 | 新增:$oldVersion = $env:CAGE_PWSH_VERSION | |
| 43 | 新增:$temp = [IO.Directory]::CreateDirectory((Join-Path ([IO.Path]::GetTempPath()) ([guid]::NewGuid().ToString('N')))) | |
| 44 | 新增:try { | |
| 45 | 新增: $version = '7.6.0' | |
| 46 | 新增: $env:CAGE_PWSH_VERSION = $version | |
| 47 | 新增: $files = [IO.Directory]::CreateDirectory((Join-Path $temp 'source')) | |
| 48 | 新增: [IO.File]::WriteAllText((Join-Path $files.FullName 'pwsh.exe'), $version) | |
| 49 | 新增: $zip = Join-Path $temp.FullName 'PowerShell.zip' | |
| 50 | 新增: Add-Type -AssemblyName System.IO.Compression.FileSystem | |
| 51 | 新增: [IO.Compression.ZipFile]::CreateFromDirectory($files.FullName, $zip) | |
| 52 | 新增: $base = Join-Path $temp.FullName 'Program Files' | |
| 53 | 新增: $target = Join-Path $base '7' | |
| 54 | 新增: $env:CAGE_PWSH_HASH = '00' * 32 | |
| 55 | 新增: Assert-Failure { & $install } 'pinned SHA-256' | |
| 56 | 新增: if ([IO.Directory]::Exists($base)) { throw 'A hash mismatch changed the destination.' } | |
| 57 | 新增: | |
| 58 | 新增: $env:CAGE_PWSH_HASH = (Get-FileHash -LiteralPath $zip -Algorithm SHA256).Hash | |
| 59 | 新增: $env:CAGE_PWSH_VERSION = '7.5.0' | |
| 60 | 新增: Assert-Failure { & $install } 'incompatible runtime' | |
| 61 | 新增: if (@([IO.Directory]::EnumerateFileSystemEntries($base)).Count) { throw 'Failed runtime left partial files.' } | |
| 62 | 新增: $env:CAGE_PWSH_VERSION = $version | |
| 63 | 新增: & $install | |
| 64 | 新增: $exe = Join-Path $target 'pwsh.exe' | |
| 65 | 新增: if ([IO.File]::ReadAllText($exe) -ne $version) { throw 'Verified shell was not published.' } | |
| 66 | 新增: [IO.File]::WriteAllText($exe, '7.8.0') | |
| 67 | 新增: & $install | |
| 68 | 新增: if ([IO.File]::ReadAllText($exe) -ne '7.8.0') { throw 'A later installed release was overwritten.' } | |
| 69 | 新增: [IO.File]::WriteAllText($exe, 'unexpected') | |
| 70 | 新增: Assert-Failure { & $install } 'incompatible runtime' | |
| 71 | 新增: if ([IO.File]::ReadAllText($exe) -ne 'unexpected') { throw 'Existing installation was modified on failure.' } | |
| 72 | 新增: | |
| 73 | 新增: $key = [pscustomobject]@{ Raw = '%SystemRoot%\System32'; Writes = 0 } | |
| 74 | 新增: $key | Add-Member ScriptMethod GetValue { param($name,$fallback,$flags) $this.Raw } | |
| 75 | 新增: $key | Add-Member ScriptMethod GetValueNames { @('Path') } | |
| 76 | 新增: $key | Add-Member ScriptMethod GetValueKind { param($name) [Microsoft.Win32.RegistryValueKind]::ExpandString } | |
| 77 | 新增: $key | Add-Member ScriptMethod SetValue { | |
| 78 | 新增: param($name,$value,$kind) | |
| 79 | 新增: if ($kind -ne [Microsoft.Win32.RegistryValueKind]::ExpandString) { throw 'Changed registry value kind.' } | |
| 80 | 新增: $this.Raw = $value; $this.Writes++ | |
| 81 | 新增: } | |
| 82 | 新增: $key | Add-Member ScriptMethod Close {} | |
| 83 | 新增: & $updatePath | |
| 84 | 新增: & $updatePath | |
| 85 | 新增: if ($key.Writes -ne 1 -or $key.Raw -cne ($target + ';%SystemRoot%\System32')) { | |
| 86 | 新增: throw 'PATH retry duplicated the entry or rewrote existing variables.' | |
| 87 | 新增: } | |
| 88 | 新增:} finally { | |
| 89 | 新增: $env:CAGE_PWSH_HASH = $oldHash | |
| 90 | 新增: $env:CAGE_PWSH_VERSION = $oldVersion | |
| 91 | 新增: $temp.Delete($true) | |
| 92 | 新增:} | |
| 93 | 新增:Write-Output 'Passed offline ZIP verification, publication, retry, existing shell preservation and machine PATH checks (simulated guest).' | |
| @@ -0,0 +1,76 @@ | ||
| 1 | 新增:#!/bin/bash | |
| 2 | 新增:# Run as the administrator inside the prepared virtual Mac. All media are local. | |
| 3 | 新增:set -euo pipefail | |
| 4 | 新增:export PATH=/usr/bin:/bin:/usr/sbin:/sbin | |
| 5 | 新增:[[ ( $# == 1 || ( $# == 2 && $2 == --update-tools ) ) && $EUID == 0 && $(sysctl -n hw.model) =~ ^VirtualMac[0-9]+,[0-9]+$ ]] | |
| 6 | 新增:[[ -f /var/db/cage-guest-os && ! -L /var/db/cage-guest-os && $(stat -f %u /var/db/cage-guest-os) == 0 && $(cat /var/db/cage-guest-os) == macos ]] | |
| 7 | 新增:media=$(cd "$1" && pwd) | |
| 8 | 新增:base=/usr/local/libexec | |
| 9 | 新增:tools="$base/cage-workbench-browser-4.145.0-pw1.65.0" | |
| 10 | 新增:mkdir -p "$base" | |
| 11 | 新增:stage=$(mktemp -d "$base/.cage-browser.XXXXXXXX") | |
| 12 | 新增:volume="$stage/volume" | |
| 13 | 新增:trap 'if mount | grep -Fq " on $volume ("; then hdiutil detach "$volume" >/dev/null; fi; rm -rf "$stage"' EXIT | |
| 14 | 新增:umask 022 | |
| 15 | 新增:verify() { | |
| 16 | 新增: [[ $(shasum -a 256 "$1" | cut -d' ' -f1) == "$2" ]] || { echo "Unexpected package digest: $1" >&2; exit 1; } | |
| 17 | 新增:} | |
| 18 | 新增:if [[ ! -x $tools/editor/lib/node || ! -f $tools/playwright/package.json ]]; then | |
| 19 | 新增: mkdir -p "$stage/tools/editor" "$stage/tools/playwright" | |
| 20 | 新增: cp "$media/editor.tgz" "$media/playwright.tgz" "$stage/" | |
| 21 | 新增: verify "$stage/editor.tgz" a79774d8d34eed785c1f831bc0125f7534bc21a0039bef8e8a2aa32463f9421a | |
| 22 | 新增: verify "$stage/playwright.tgz" 315247c55a793ca760b2f05bdcee0e6a53fd65b1f22d1d3de8323c8c9395add3 | |
| 23 | 新增: tar -xzf "$stage/editor.tgz" -C "$stage/tools/editor" --no-same-owner --strip-components 1 | |
| 24 | 新增: tar -xzf "$stage/playwright.tgz" -C "$stage/tools/playwright" --no-same-owner --strip-components 1 | |
| 25 | 新增: "$stage/tools/editor/lib/node" --version | |
| 26 | 新增: mkdir -p "$tools" | |
| 27 | 新增: for component in editor playwright; do | |
| 28 | 新增: [[ ! -L $tools/$component ]] | |
| 29 | 新增: if [[ -e $tools/$component ]]; then mv "$tools/$component" "$stage/previous-$component"; fi | |
| 30 | 新增: if ! mv "$stage/tools/$component" "$tools/$component"; then | |
| 31 | 新增: if [[ -d $stage/previous-$component ]]; then mv "$stage/previous-$component" "$tools/$component"; fi | |
| 32 | 新增: exit 1 | |
| 33 | 新增: fi | |
| 34 | 新增: done | |
| 35 | 新增:fi | |
| 36 | 新增:app='/Applications/Google Chrome.app' | |
| 37 | 新增:requirement='anchor apple generic and identifier "com.google.Chrome" and certificate leaf[subject.OU] = "EQHXZ8M8AV"' | |
| 38 | 新增:if [[ ! -e $app || ${2:-} == --update-tools ]]; then | |
| 39 | 新增: cp "$media/chrome.dmg" "$stage/chrome.dmg" | |
| 40 | 新增: mkdir "$volume" | |
| 41 | 新增: hdiutil attach -readonly -nobrowse -noautoopen -mountpoint "$volume" "$stage/chrome.dmg" >/dev/null | |
| 42 | 新增: spctl --assess --type execute "$volume/Google Chrome.app" | |
| 43 | 新增: ditto --norsrc "$volume/Google Chrome.app" "$stage/Google Chrome.app" | |
| 44 | 新增: codesign --verify --strict --deep -R="$requirement" "$stage/Google Chrome.app" | |
| 45 | 新增: spctl --assess --type execute "$stage/Google Chrome.app" | |
| 46 | 新增: install_chrome=yes | |
| 47 | 新增: if [[ -e $app ]]; then | |
| 48 | 新增: [[ -d $app && ! -L $app ]] | |
| 49 | 新增: codesign --verify --strict -R="$requirement" "$app" | |
| 50 | 新增: current=$(/usr/libexec/PlistBuddy -c 'Print :CFBundleShortVersionString' "$app/Contents/Info.plist") | |
| 51 | 新增: incoming=$(/usr/libexec/PlistBuddy -c 'Print :CFBundleShortVersionString' "$stage/Google Chrome.app/Contents/Info.plist") | |
| 52 | 新增: [[ $current =~ ^[0-9]+(\.[0-9]+)*$ && $incoming =~ ^[0-9]+(\.[0-9]+)*$ ]] | |
| 53 | 新增: if ! /usr/bin/perl -e '@a=split(/\./,$ARGV[0]);@b=split(/\./,$ARGV[1]);for($i=0;$i<@a||$i<@b;$i++){exit(($a[$i]//0)>($b[$i]//0)?0:1) if ($a[$i]//0)!=($b[$i]//0)}exit 1' "$incoming" "$current"; then install_chrome=no; fi | |
| 54 | 新增: fi | |
| 55 | 新增: if [[ $install_chrome == yes ]]; then | |
| 56 | 新增: if [[ -e $app ]]; then mv "$app" "$stage/previous-chrome.app"; fi | |
| 57 | 新增: if ! mv "$stage/Google Chrome.app" "$app"; then | |
| 58 | 新增: if [[ -d $stage/previous-chrome.app ]]; then mv "$stage/previous-chrome.app" "$app"; fi | |
| 59 | 新增: exit 1 | |
| 60 | 新增: fi | |
| 61 | 新增: fi | |
| 62 | 新增:fi | |
| 63 | 新增:codesign --verify --strict -R="$requirement" "$app" | |
| 64 | 新增:sources=$(cd "$(dirname "$0")" && pwd) | |
| 65 | 新增:install -m 644 "$sources/macos-browser.mjs" "$base/cage-macos-browser.mjs" | |
| 66 | 新增:install -m 755 "$sources/cage-macos-editor" "$base/cage-macos-editor" | |
| 67 | 新增:if [[ -f "$media/native-browser/macos-native-browser.mjs" ]]; then | |
| 68 | 新增: cp -R "$media/native-browser" "$stage/controller" | |
| 69 | 新增:else | |
| 70 | 新增: "$sources/package-macos-browser.sh" "$stage/controller" | |
| 71 | 新增:fi | |
| 72 | 新增:install -d "$tools/controller" "$tools/controller/modules" "$tools/controller/split-extension" | |
| 73 | 新增:install -m 644 "$stage/controller/"*.mjs "$tools/controller/" | |
| 74 | 新增:install -m 755 "$stage/controller/cage-tailnet" "$tools/controller/cage-tailnet" | |
| 75 | 新增:install -m 644 "$stage/controller/modules/"*.mjs "$tools/controller/modules/" | |
| 76 | 新增:install -m 644 "$stage/controller/split-extension/"* "$tools/controller/split-extension/" | |
| @@ -0,0 +1,114 @@ | ||
| 1 | 新增:#!/bin/bash | |
| 2 | 新增:# Offline installation. Only Cage-owned guest tools are published. | |
| 3 | 新增:set -euo pipefail | |
| 4 | 新增:export PATH=/usr/bin:/bin:/usr/sbin:/sbin | |
| 5 | 新增:[[ ( $# == 1 || ( $# == 2 && $2 == --components ) ) && $1 == /* && $EUID == 0 && $(sysctl -n hw.model) =~ ^VirtualMac[0-9]+,[0-9]+$ ]] | |
| 6 | 新增:components=${2:-} | |
| 7 | 新增:marker=/var/db/cage-guest-os | |
| 8 | 新增:[[ ! -L $marker && -f $marker && $(stat -f %u "$marker") == 0 && $(cat "$marker") == macos ]] | |
| 9 | 新增:mode=$(stat -f %OLp "$marker") | |
| 10 | 新增:(( (8#$mode & 022) == 0 )) | |
| 11 | 新增:kit=$(cd -P "$1" && pwd) | |
| 12 | 新增:# Local helper sources are supplied by the trusted host, not by the GUI guest user. | |
| 13 | 新增:[[ -z $(find "$kit" \( -type l -o ! -user root -o -perm -0020 -o -perm -0002 \) -print -quit) ]] | |
| 14 | 新增:parent=$kit | |
| 15 | 新增:while [[ $parent != / ]]; do | |
| 16 | 新增: mode=$(stat -f %Op "$parent") | |
| 17 | 新增: [[ $(stat -f %u "$parent") == 0 ]] || exit 1 | |
| 18 | 新增: (( (8#$mode & 022) == 0 || (8#$mode & 01000) != 0 )) || exit 1 | |
| 19 | 新增: parent=$(dirname "$parent") | |
| 20 | 新增:done | |
| 21 | 新增:umask 022 | |
| 22 | 新增:base=/usr/local/libexec | |
| 23 | 新增:mkdir -p "$base" /usr/local/bin | |
| 24 | 新增:work=$(mktemp -d "$base/.cage-cli-install.XXXXXXXX") | |
| 25 | 新增:trap 'rm -rf "$work"' EXIT | |
| 26 | 新增:cd "$work" | |
| 27 | 新增:cp "$kit"/{macos-cli.py,cli_channel.py,cli_channel.resume.md,claude_account_resume.md,claude-account.py} . | |
| 28 | 新增:runtime="$base/cage-cli-runtime-2.1.311-py3.13.18-git2.56.0" | |
| 29 | 新增:if [[ $components == --components ]]; then | |
| 30 | 新增: [[ -x $runtime/bin/python3 && -x $runtime/bin/claude && -x $runtime/bin/git ]] || { echo '请先更新环境工具,再同步组件。' >&2; exit 1; } | |
| 31 | 新增:else | |
| 32 | 新增:cp "$kit"/{claude,uv.tar.gz,python.tar.gz,git.tar.gz} . | |
| 33 | 新增:check() { [[ $(shasum -a 256 "$2" | cut -d' ' -f1) == "$1" ]]; } | |
| 34 | 新增:check 85d8c08707fcfd1e78ffa0204eefbc6ec9e4fe22f375fb2767ef85d957ed3161 claude | |
| 35 | 新增:check 81b811b57e4624df7ed3aac148e0359100d9962f3d9dce00aec533dc2e086731 uv.tar.gz | |
| 36 | 新增:check 8392b6ea51d94391befb2c31ebe75463f045d0b69dfcf5e1bb3234e1f5fa3405 python.tar.gz | |
| 37 | 新增:check 1110de343de11cc6f469b782b60f36217b9199b5e06875dd65baa26dd60563c7 git.tar.gz | |
| 38 | 新增:chmod 755 claude | |
| 39 | 新增:codesign --verify --strict --architecture arm64 -R '=anchor apple generic and identifier "com.anthropic.claude-code" and certificate leaf[subject.OU] = "Q6L2SF6YDW"' claude | |
| 40 | 新增:fi | |
| 41 | 新增:# Use rename(2), which never nests the staged directory inside a | |
| 42 | 新增:# concurrently completed installation. | |
| 43 | 新增:publish_dir() { | |
| 44 | 新增: /usr/bin/perl -e 'rename($ARGV[0], $ARGV[1]) || -d $ARGV[1] || die "publish: $!"' "$1" "$2" | |
| 45 | 新增:} | |
| 46 | 新增:if [[ ! -d $runtime ]]; then | |
| 47 | 新增: tar -xzf uv.tar.gz --no-same-owner | |
| 48 | 新增: mkdir -p tools/bin | |
| 49 | 新增: # uv recognizes the distribution format from the archive filename. | |
| 50 | 新增: mv python.tar.gz cpython-3.13.18-aarch64-apple-darwin.tar.gz | |
| 51 | 新增: cat > python.json <<JSON | |
| 52 | 新增:{"cpython-3.13.18-darwin-aarch64-none":{"name":"cpython","arch":{"family":"aarch64","variant":null},"os":"darwin","libc":"none","major":3,"minor":13,"patch":18,"prerelease":"","url":"file://$work/cpython-3.13.18-aarch64-apple-darwin.tar.gz","sha256":"8392b6ea51d94391befb2c31ebe75463f045d0b69dfcf5e1bb3234e1f5fa3405","variant":null,"build":"20261026"}} | |
| 53 | 新增:JSON | |
| 54 | 新增: UV_CACHE_DIR="$work/cache" ./uv-aarch64-apple-darwin/uv python install 3.13.18 --install-dir "$work/tools/python" --no-bin --no-config --offline --python-downloads-json-url "$work/python.json" | |
| 55 | 新增: ln -s ../python/cpython-3.13.18-macos-aarch64-none/bin/python3.13 tools/bin/python3 | |
| 56 | 新增: tools/bin/python3 -I -c 'import sys, ssl; assert sys.version_info[:3] == (3,13,18)' | |
| 57 | 新增: mv claude tools/bin/ | |
| 58 | 新增: mkdir tools/git | |
| 59 | 新增: tar -xzf git.tar.gz -C tools/git --no-same-owner | |
| 60 | 新增: [[ $(tools/git/bin/git --version) == 'git version 2.56.0' ]] | |
| 61 | 新增: # This GitHub Desktop distribution is relocatable. Its remote helpers | |
| 62 | 新增: # and templates must be resolved from the same pinned distribution. | |
| 63 | 新增: cat > tools/bin/git <<GIT | |
| 64 | 新增:#!/bin/sh | |
| 65 | 新增:export GIT_EXEC_PATH="\${GIT_EXEC_PATH:-$runtime/git/libexec/git-core}" | |
| 66 | 新增:export GIT_TEMPLATE_DIR="\${GIT_TEMPLATE_DIR:-$runtime/git/share/git-core/templates}" | |
| 67 | 新增:export GIT_CONFIG_SYSTEM="\${GIT_CONFIG_SYSTEM:-$runtime/git/etc/gitconfig}" | |
| 68 | 新增:exec "$runtime/git/bin/git" "\$@" | |
| 69 | 新增:GIT | |
| 70 | 新增: chmod 755 tools/bin/git | |
| 71 | 新增: chmod -R a+rX,go-w tools | |
| 72 | 新增: publish_dir tools "$runtime" | |
| 73 | 新增:fi | |
| 74 | 新增:revision=$(shasum -a 256 macos-cli.py cli_channel.py cli_channel.resume.md claude_account_resume.md claude-account.py | shasum -a 256 | cut -c1-16) | |
| 75 | 新增:target="$base/cage-cli-2.1.311-git2.56.0-$revision" | |
| 76 | 新增:if [[ -d $target ]]; then | |
| 77 | 新增: intact=yes | |
| 78 | 新增: for name in macos-cli.py cli_channel.py cli_channel.resume.md; do | |
| 79 | 新增: if ! cmp -s "$name" "$target/$name"; then intact=no; fi | |
| 80 | 新增: done | |
| 81 | 新增: if ! cmp -s claude_account_resume.md "$target/cli_channel.account-resume.md" || | |
| 82 | 新增: ! cmp -s <(sed "1s@.*@#!$runtime/bin/python3 -I@" claude-account.py) "$target/bin/cage-claude-account"; then intact=no; fi | |
| 83 | 新增: for name in python3 claude git; do | |
| 84 | 新增: if [[ ! -L $target/bin/$name || $(readlink "$target/bin/$name") != "$runtime/bin/$name" ]]; then intact=no; fi | |
| 85 | 新增: done | |
| 86 | 新增: if [[ $intact == no ]]; then | |
| 87 | 新增: # Keep the damaged directory available for rollback while publishing a | |
| 88 | 新增: # fresh helper set for the same application revision. | |
| 89 | 新增: target="$target-repair-${work##*.}" | |
| 90 | 新增: fi | |
| 91 | 新增:fi | |
| 92 | 新增:if [[ ! -d $target ]]; then | |
| 93 | 新增: mkdir -p helpers/bin | |
| 94 | 新增: for name in python3 claude git; do ln -s "$runtime/bin/$name" "helpers/bin/$name"; done | |
| 95 | 新增: install -m 644 macos-cli.py cli_channel.py cli_channel.resume.md helpers/ | |
| 96 | 新增: install -m 644 claude_account_resume.md helpers/cli_channel.account-resume.md | |
| 97 | 新增: sed "1s@.*@#!$runtime/bin/python3 -I@" claude-account.py > helpers/bin/cage-claude-account | |
| 98 | 新增: chmod 755 helpers/bin/cage-claude-account | |
| 99 | 新增: ln -s cage-claude-account helpers/bin/cage-open | |
| 100 | 新增: publish_dir helpers "$target" | |
| 101 | 新增:fi | |
| 102 | 新增:current="$base/cage-cli" | |
| 103 | 新增:if [[ -e $current || -L $current ]]; then | |
| 104 | 新增: [[ -L $current && $(readlink "$current") == "$base"/cage-cli-2.* ]] | |
| 105 | 新增:fi | |
| 106 | 新增:ln -s "$target" "$work/current" | |
| 107 | 新增:mv -fh "$work/current" "$current" | |
| 108 | 新增:account=/usr/local/bin/cage-claude-account | |
| 109 | 新增:if [[ ! -e $account && ! -L $account ]]; then ln -s "$current/bin/cage-claude-account" "$account"; fi | |
| 110 | 新增:[[ -L $account && $(readlink "$account") == "$current/bin/cage-claude-account" ]] | |
| 111 | 新增:for name in claude git; do | |
| 112 | 新增: if [[ ! -e /usr/local/bin/$name && ! -L /usr/local/bin/$name ]]; then ln -s "$current/bin/$name" "/usr/local/bin/$name"; fi | |
| 113 | 新增:done | |
| 114 | 新增:"$current/bin/claude" --version | |
| @@ -0,0 +1,23 @@ | ||
| 1 | 新增:#!/bin/bash | |
| 2 | 新增:# The runtime used by ordinary terminal and debugger sessions in the macOS guest. | |
| 3 | 新增:set -euo pipefail | |
| 4 | 新增:export PATH=/usr/bin:/bin:/usr/sbin:/sbin | |
| 5 | 新增:[[ $# == 1 && $EUID == 0 && $(sysctl -n hw.model) =~ ^VirtualMac[0-9]+,[0-9]+$ ]] | |
| 6 | 新增:[[ -f /var/db/cage-guest-os && ! -L /var/db/cage-guest-os && $(stat -f %u /var/db/cage-guest-os) == 0 && $(cat /var/db/cage-guest-os) == macos ]] | |
| 7 | 新增:base=/usr/local/libexec | |
| 8 | 新增:target="$base/cage-node-v24.22.2" | |
| 9 | 新增:mkdir -p "$base" /usr/local/bin | |
| 10 | 新增:stage=$(mktemp -d "$base/.cage-node.XXXXXXXX") | |
| 11 | 新增:trap 'rm -rf "$stage"' EXIT | |
| 12 | 新增:if [[ ! -e $target ]]; then | |
| 13 | 新增: cp "$1" "$stage/node.tgz" | |
| 14 | 新增: [[ $(shasum -a 256 "$stage/node.tgz" | cut -d' ' -f1) == aa9549349e47dffaa42dcf95d6e06ade8c4bdafc980979883b88767670df385a ]] | |
| 15 | 新增: tar -xzf "$stage/node.tgz" -C "$stage" --no-same-owner | |
| 16 | 新增: [[ $("$stage/node-v24.22.2-darwin-arm64/bin/node" -p 'process.platform + "/" + process.arch + "/" + process.version') == darwin/arm64/v24.22.2 ]] | |
| 17 | 新增: mv "$stage/node-v24.22.2-darwin-arm64" "$target" | |
| 18 | 新增:fi | |
| 19 | 新增:for tool in node npm npx; do | |
| 20 | 新增: if [[ ! -e /usr/local/bin/$tool && ! -L /usr/local/bin/$tool ]]; then | |
| 21 | 新增: ln -s "$target/bin/$tool" "/usr/local/bin/$tool" | |
| 22 | 新增: fi | |
| 23 | 新增:done | |
| @@ -0,0 +1,94 @@ | ||
| 1 | 新增:#!/bin/bash | |
| 2 | 新增:# Run as root inside a Cage macOS guest. The supplied directory contains the | |
| 3 | 新增:# verified macFUSE 5.5.0 installer and the three project tools from this build. | |
| 4 | 新增:set -euo pipefail | |
| 5 | 新增:export PATH=/usr/bin:/bin:/usr/sbin:/sbin | |
| 6 | 新增:fail() { printf '%s\n' "$*" >&2; exit 1; } | |
| 7 | 新增:[[ $# == 1 && $1 == /* ]] || fail 'Usage: install-macos-project-tools.sh /path/to/root-owned-guest-project-kit' | |
| 8 | 新增:[[ $(uname -sm) == 'Darwin arm64' && $(sysctl -n hw.model) =~ ^VirtualMac[0-9]+,[0-9]+$ && $(id -u) == 0 ]] || | |
| 9 | 新增: fail 'Run this installer in the target arm64 Cage guest as administrator.' | |
| 10 | 新增:marker=/var/db/cage-guest-os | |
| 11 | 新增:[[ -f $marker && ! -L $marker && $(stat -f %u "$marker") == 0 && $(cat "$marker") == macos ]] || | |
| 12 | 新增: fail 'Missing the root-owned Cage guest marker.' | |
| 13 | 新增:mode=$(stat -f %OLp "$marker") | |
| 14 | 新增:(( (8#$mode & 022) == 0 )) || fail 'The guest marker is writable by another account.' | |
| 15 | 新增: | |
| 16 | 新增:# Copy before verification, so a source directory cannot change after checks. | |
| 17 | 新增:# Root-owned inputs are required because unsigned development builds can use a | |
| 18 | 新增:# local ad-hoc signature. No downloaded code is executed to verify identity. | |
| 19 | 新增:kit=$(cd -P "$1" && pwd) | |
| 20 | 新增:[[ $(stat -f %u "$kit") == 0 && -z $(find "$kit" \( -type l -o ! -user root -o -perm -0020 -o -perm -0002 \) -print -quit) ]] || | |
| 21 | 新增: fail 'Use a root-owned kit with no symlinks or group/other-writable members.' | |
| 22 | 新增:parent=$(dirname "$kit") | |
| 23 | 新增:while [[ $parent != / ]]; do | |
| 24 | 新增: mode=$(stat -f %Op "$parent") | |
| 25 | 新增: [[ $(stat -f %u "$parent") == 0 ]] && (( (8#$mode & 022) == 0 || (8#$mode & 01000) != 0 )) || | |
| 26 | 新增: fail 'The kit can be replaced through an untrusted parent directory.' | |
| 27 | 新增: parent=$(dirname "$parent") | |
| 28 | 新增:done | |
| 29 | 新增:for file in macfuse.pkg cage-sshfs cage-macos-terminal; do [[ -f $kit/$file ]] || fail "Missing $file"; done | |
| 30 | 新增:[[ -d $kit/CageProjectAccess.app ]] || fail 'Missing CageProjectAccess.app.' | |
| 31 | 新增:umask 077 | |
| 32 | 新增:work=$(mktemp -d /private/var/tmp/cage-project-kit.XXXXXXXX) | |
| 33 | 新增:trap 'rm -rf "$work"' EXIT | |
| 34 | 新增:for file in macfuse.pkg cage-sshfs cage-macos-terminal; do cp "$kit/$file" "$work/$file"; done | |
| 35 | 新增:ditto "$kit/CageProjectAccess.app" "$work/CageProjectAccess.app" | |
| 36 | 新增:pkg="$work/macfuse.pkg" | |
| 37 | 新增:[[ $(shasum -a 256 "$pkg" | cut -d' ' -f1) == 5acf9e30bab227707de8d15eb28472a0cc9ed45709846b3e067d283294dc7f9e ]] || | |
| 38 | 新增: fail 'The macFUSE installer SHA-256 does not match the pinned release.' | |
| 39 | 新增:pkgutil --check-signature "$pkg" | grep -F 'Developer ID Installer: Benjamin Fleischer (3T5GSNBU6W)' >/dev/null || | |
| 40 | 新增: fail 'Unexpected macFUSE installer signer.' | |
| 41 | 新增:for file in cage-sshfs cage-macos-terminal; do | |
| 42 | 新增: codesign --verify --strict --architecture arm64 "$work/$file" | |
| 43 | 新增:done | |
| 44 | 新增:access_id=dev.cage.guest.project-access | |
| 45 | 新增:codesign --verify --strict -R "=identifier \"$access_id\"" "$work/CageProjectAccess.app" | |
| 46 | 新增:macfuse_requirement='anchor apple generic and identifier "io.macfuse.app" and certificate leaf[subject.OU] = "3T5GSNBU6W"' | |
| 47 | 新增:driver=/Library/Filesystems/macfuse.fs | |
| 48 | 新增:vendor_app="$driver/Contents/Resources/macfuse.app" | |
| 49 | 新增:installed='' | |
| 50 | 新增:if [[ -e $driver ]]; then | |
| 51 | 新增: codesign --verify --strict -R "=$macfuse_requirement" "$vendor_app" | |
| 52 | 新增: installed=$(plutil -extract CFBundleShortVersionString raw -o - "$driver/Contents/Info.plist") | |
| 53 | 新增:fi | |
| 54 | 新增:up_to_date=no | |
| 55 | 新增:if [[ -n $installed ]]; then | |
| 56 | 新增: [[ $installed =~ ^([0-9]+)\.([0-9]+)(\.[0-9]+)?$ ]] || fail 'Unrecognized installed macFUSE version.' | |
| 57 | 新增: if (( 10#${BASH_REMATCH[1]} > 5 || (10#${BASH_REMATCH[1]} == 5 && 10#${BASH_REMATCH[2]} >= 5) )); then up_to_date=yes; fi | |
| 58 | 新增:fi | |
| 59 | 新增:if [[ $up_to_date == no ]]; then | |
| 60 | 新增: installer -pkg "$pkg" -target / | |
| 61 | 新增:fi | |
| 62 | 新增:codesign --verify --strict -R "=$macfuse_requirement" "$vendor_app" | |
| 63 | 新增: | |
| 64 | 新增:install_app() { | |
| 65 | 新增: local source=$1 target=$2 requirement=$3 stage | |
| 66 | 新增: if [[ -e $target || -L $target ]]; then | |
| 67 | 新增: [[ ! -L $target && -d $target ]] || fail "Unexpected application at $target" | |
| 68 | 新增: codesign --verify --strict -R "=$requirement" "$target" | |
| 69 | 新增: if diff -qr "$source" "$target" >/dev/null; then return; fi | |
| 70 | 新增: fail "A different verified build is already installed at $target. Stop and update that application before retrying." | |
| 71 | 新增: fi | |
| 72 | 新增: stage=$(mktemp -d /Applications/.cage-project-install.XXXXXXXX) | |
| 73 | 新增: if ditto "$source" "$stage/app" && chmod -R a+rX,go-w "$stage/app" && | |
| 74 | 新增: codesign --verify --strict -R "=$requirement" "$stage/app" && mv "$stage/app" "$target"; then | |
| 75 | 新增: rmdir "$stage" | |
| 76 | 新增: else | |
| 77 | 新增: rm -rf "$stage" | |
| 78 | 新增: fail "Could not install $target" | |
| 79 | 新增: fi | |
| 80 | 新增:} | |
| 81 | 新增:install_app "$vendor_app" /Applications/macFUSE.app "$macfuse_requirement" | |
| 82 | 新增:install_app "$work/CageProjectAccess.app" /Applications/CageProjectAccess.app "identifier \"$access_id\"" | |
| 83 | 新增:libexec=/usr/local/libexec | |
| 84 | 新增:mkdir -p "$libexec" | |
| 85 | 新增:for file in cage-sshfs cage-macos-terminal; do | |
| 86 | 新增: [[ ! -L $libexec/$file ]] || fail "Refusing to replace a linked executable: $file" | |
| 87 | 新增: if [[ -f $libexec/$file ]] && cmp -s "$work/$file" "$libexec/$file"; then continue; fi | |
| 88 | 新增: stage=$(mktemp "$libexec/.cage-tool.XXXXXXXX") | |
| 89 | 新增: if install -o root -g wheel -m 755 "$work/$file" "$stage" && mv -f "$stage" "$libexec/$file"; then :; else | |
| 90 | 新增: rm -f "$stage" | |
| 91 | 新增: fail "Could not install $file" | |
| 92 | 新增: fi | |
| 93 | 新增:done | |
| 94 | 新增:printf '%s\n' 'Project tools are ready. In the guest user session, open macFUSE.app once, then enable both macFUSE and macFUSE (local) under By Category > File System Extensions.' | |
| @@ -0,0 +1,99 @@ | ||
| 1 | 新增:#requires -Version 5.1 | |
| 2 | 新增:#requires -RunAsAdministrator | |
| 3 | 新增:[CmdletBinding(SupportsShouldProcess)] | |
| 4 | 新增:param( | |
| 5 | 新增: [Parameter(Mandatory)][guid]$VMId, | |
| 6 | 新增: [Parameter(Mandatory)][string]$HostSID, | |
| 7 | 新增: [Parameter(Mandatory)][string]$PayloadExecutable, | |
| 8 | 新增: [Parameter(Mandatory)][ValidatePattern('^[0-9a-fA-F]{64}$')][string]$PayloadSHA256 | |
| 9 | 新增:) | |
| 10 | 新增:$ErrorActionPreference='Stop';$ProgressPreference='SilentlyContinue' | |
| 11 | 新增:if($VMId -eq [guid]::Empty -or $HostSID -notmatch '^S-1-(5-21|12-1)-(\d+-){3}\d+$'){throw 'Select the exact VM and authorized host user.'} | |
| 12 | 新增:# HostSID is the ordinary Cage user's identity carried across its UAC boundary. | |
| 13 | 新增:# The administrator may be another account; its SID is never substituted here. | |
| 14 | 新增:function Assert-NoLink([string]$Path){ | |
| 15 | 新增: $item=Get-Item -LiteralPath $Path -Force | |
| 16 | 新增: while($item){if($item.Attributes -band [IO.FileAttributes]::ReparsePoint){throw 'Manager files cannot traverse links.'};if($item -is [IO.FileInfo]){$item=$item.Directory}else{$item=$item.Parent}} | |
| 17 | 新增:} | |
| 18 | 新增:function Protect-ManagerPath([string]$Path,[switch]$Shared){ | |
| 19 | 新增: $item=Get-Item -LiteralPath $Path -Force | |
| 20 | 新增: if($item.Attributes -band [IO.FileAttributes]::ReparsePoint){throw 'Manager paths cannot be links.'} | |
| 21 | 新增: if($item -is [IO.DirectoryInfo]){$acl=[Security.AccessControl.DirectorySecurity]::new()}else{$acl=[Security.AccessControl.FileSecurity]::new()} | |
| 22 | 新增: $acl.SetOwner([Security.Principal.SecurityIdentifier]::new('S-1-5-32-544'));$acl.SetAccessRuleProtection($true,$false) | |
| 23 | 新增: $reader=if($Shared){'S-1-5-32-545'}else{$HostSID} | |
| 24 | 新增: foreach($id in @('S-1-5-18','S-1-5-32-544',$reader)){ | |
| 25 | 新增: $rights=if($id -ceq $reader){'ReadAndExecute'}else{'FullControl'} | |
| 26 | 新增: if($item -is [IO.DirectoryInfo]){$rule=[Security.AccessControl.FileSystemAccessRule]::new([Security.Principal.SecurityIdentifier]::new($id),$rights,'ContainerInherit,ObjectInherit','None','Allow')}else{$rule=[Security.AccessControl.FileSystemAccessRule]::new([Security.Principal.SecurityIdentifier]::new($id),$rights,'Allow')} | |
| 27 | 新增: $acl.AddAccessRule($rule) | |
| 28 | 新增: } | |
| 29 | 新增: Set-Acl -LiteralPath $Path -AclObject $acl | |
| 30 | 新增:} | |
| 31 | 新增:$payload=Get-Item -LiteralPath $PayloadExecutable | |
| 32 | 新增:if($payload -isnot [IO.FileInfo]){throw 'Select the built manager executable.'};Assert-NoLink $payload.FullName | |
| 33 | 新增:if((Get-FileHash $payload.FullName -Algorithm SHA256).Hash.ToLowerInvariant() -cne $PayloadSHA256.ToLowerInvariant()){throw 'Manager payload checksum does not match.'} | |
| 34 | 新增:$programRoot=Join-Path ([Environment]::GetFolderPath('ProgramFiles')) 'Cage Host Manager' | |
| 35 | 新增:$program=Join-Path $programRoot $VMId.ToString('D');$exe=Join-Path $program 'Cage.HyperVManager.exe' | |
| 36 | 新增:$cageDataRoot=Join-Path ([Environment]::GetFolderPath('CommonApplicationData')) 'Cage' | |
| 37 | 新增:$dataRoot=Join-Path $cageDataRoot 'HyperVManager' | |
| 38 | 新增:$data=Join-Path $dataRoot $VMId.ToString('D');$bindingPath=Join-Path $data 'binding.json' | |
| 39 | 新增:$name='CageHV-'+$VMId.ToString('D');$binary='"'+$exe+'" service --binding "'+$bindingPath+'"' | |
| 40 | 新增:if(!$PSCmdlet.ShouldProcess($VMId,'Install the protected local fixed-VM manager; keep VM, disks, accounts and host networking')){return} | |
| 41 | 新增:foreach($path in @($programRoot,$program,$cageDataRoot,$dataRoot,$data)){ | |
| 42 | 新增: if(!(Test-Path -LiteralPath $path)){New-Item -ItemType Directory -Path $path|Out-Null};Assert-NoLink $path | |
| 43 | 新增: Protect-ManagerPath $path -Shared:($path -in @($programRoot,$cageDataRoot,$dataRoot)) | |
| 44 | 新增:} | |
| 45 | 新增:$prepare=Join-Path $program ('manager-prepare-'+[guid]::NewGuid().ToString('N')+'.exe') | |
| 46 | 新增:try{ | |
| 47 | 新增: # Hash and execute the same protected copy. The caller's original payload | |
| 48 | 新增: # may change while setup runs; it never becomes an execution authority. | |
| 49 | 新增: Copy-Item -LiteralPath $payload.FullName -Destination $prepare | |
| 50 | 新增: Protect-ManagerPath $prepare | |
| 51 | 新增: if((Get-FileHash $prepare -Algorithm SHA256).Hash.ToLowerInvariant() -cne $PayloadSHA256.ToLowerInvariant()){throw 'Protected manager preparation checksum does not match.'} | |
| 52 | 新增: $payload=Get-Item -LiteralPath $prepare | |
| 53 | 新增:$service=Get-Service -Name $name -ErrorAction SilentlyContinue | |
| 54 | 新增:if($service){ | |
| 55 | 新增: $existing=Get-CimInstance Win32_Service -Filter ("Name='"+$name+"'") | |
| 56 | 新增: if($existing.PathName -cne $binary -or $existing.StartName -notin @('LocalSystem','NT AUTHORITY\SYSTEM')){throw 'An unrelated service already uses this name.'} | |
| 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 | |
| 61 | 新增:if($LASTEXITCODE -ne 0){throw 'The exact VM/disk binding could not be verified.'} | |
| 62 | 新增:$binding=$raw|ConvertFrom-Json | |
| 63 | 新增: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.'} | |
| 64 | 新增:if(Test-Path -LiteralPath $bindingPath){ | |
| 65 | 新增: Assert-NoLink $bindingPath;$old=Get-Content -LiteralPath $bindingPath -Raw|ConvertFrom-Json | |
| 66 | 新增: foreach($key in @('version','vm_id','host_sid','disk_path','disk_volume','disk_file_id')){if([string]$old.$key -cne [string]$binding.$key){throw 'The existing protected VM/disk binding changed; preserved it.'}} | |
| 67 | 新增:} | |
| 68 | 新增:$rollback=$null;$cleanupRollback=$false;$wasRunning=$service -and $service.Status -eq 'Running' | |
| 69 | 新增:try{ | |
| 70 | 新增: if($service){ | |
| 71 | 新增: Assert-NoLink $exe | |
| 72 | 新增: $rollback=Join-Path $program ('manager-rollback-'+[guid]::NewGuid().ToString('N')+'.exe') | |
| 73 | 新增: Copy-Item -LiteralPath $exe -Destination $rollback;Protect-ManagerPath $rollback | |
| 74 | 新增: if($service.Status -ne 'Stopped'){Stop-Service -Name $name;$service.WaitForStatus('Stopped',[TimeSpan]::FromSeconds(30))} | |
| 75 | 新增: } | |
| 76 | 新增: Copy-Item -LiteralPath $payload.FullName -Destination $exe -Force;Protect-ManagerPath $exe | |
| 77 | 新增: if((Get-FileHash $exe -Algorithm SHA256).Hash.ToLowerInvariant() -cne $PayloadSHA256.ToLowerInvariant()){throw 'The copied manager checksum does not match.'} | |
| 78 | 新增: if(!(Test-Path -LiteralPath $bindingPath)){[IO.File]::WriteAllText($bindingPath,($binding|ConvertTo-Json -Depth 4),[Text.UTF8Encoding]::new($false))} | |
| 79 | 新增: Protect-ManagerPath $bindingPath | |
| 80 | 新增: if(!$service){New-Service -Name $name -BinaryPathName $binary -StartupType Automatic -DisplayName ('Cage fixed VM manager '+$VMId.ToString('D')) -Description ('Cage protected local VM manager '+$VMId.ToString('D'))|Out-Null} | |
| 81 | 新增: $sddl='O:SYG:SYD:(A;;GA;;;SY)(A;;GA;;;BA)(A;;CCLCRP;;;'+$HostSID+')' | |
| 82 | 新增: & ($env:windir+'\System32\sc.exe') sdset $name $sddl|Out-Null | |
| 83 | 新增: if($LASTEXITCODE -ne 0){throw 'The manager service permission could not be protected.'} | |
| 84 | 新增: & ($env:windir+'\System32\sc.exe') failure $name reset= 86400 actions= restart/5000/restart/15000/restart/60000|Out-Null | |
| 85 | 新增: if($LASTEXITCODE -ne 0){throw 'The manager recovery policy could not be configured.'} | |
| 86 | 新增: Start-Service -Name $name;(Get-Service -Name $name).WaitForStatus('Running',[TimeSpan]::FromSeconds(30)) | |
| 87 | 新增: $cleanupRollback=$true | |
| 88 | 新增:}catch{ | |
| 89 | 新增: if($rollback){ | |
| 90 | 新增: Stop-Service -Name $name -ErrorAction SilentlyContinue | |
| 91 | 新增: (Get-Service -Name $name).WaitForStatus('Stopped',[TimeSpan]::FromSeconds(30)) | |
| 92 | 新增: Copy-Item -LiteralPath $rollback -Destination $exe -Force;Protect-ManagerPath $exe | |
| 93 | 新增: if($wasRunning){Start-Service -Name $name} | |
| 94 | 新增: $cleanupRollback=$true | |
| 95 | 新增: } | |
| 96 | 新增: throw | |
| 97 | 新增:}finally{if($rollback -and $cleanupRollback -and (Test-Path -LiteralPath $rollback)){Remove-Item -LiteralPath $rollback}} | |
| 98 | 新增:[pscustomobject]@{Installed=$true;VMId=$VMId.ToString('D');HostSID=$HostSID;LocalPipeOnly=$true;VMDataPreserved=$true;HostGroupsUnchanged=$true;ServiceRunning=$true} | |
| 99 | 新增:}finally{if(Test-Path -LiteralPath $prepare){Remove-Item -LiteralPath $prepare}} | |
| @@ -0,0 +1,127 @@ | ||
| 1 | 新增:# Used by complete-windows-guest.ps1 through an authenticated VM-only | |
| 2 | 新增:# PowerShell Direct session, after the ordinary GUI SID has been pinned. | |
| 3 | 新增:param([guid]$VMId,[string]$GUIUserSID,[string]$Bridge,[string]$Stage,[string]$PackagesJSON,[string]$CLIJSON,[string]$ExtrasSHA,[ValidateSet('Prepare','UserTools')][string]$Phase,[switch]$RuntimeInstalled) | |
| 4 | 新增:$Packages=$PackagesJSON | ConvertFrom-Json | |
| 5 | 新增:$CLI=$CLIJSON | ConvertFrom-Json | |
| 6 | 新增:$ErrorActionPreference='Stop' | |
| 7 | 新增:if ([guid](Get-ItemProperty 'HKLM:\SOFTWARE\Microsoft\Virtual Machine\Guest\Parameters').VirtualMachineId -ne $VMId -or | |
| 8 | 新增: $Bridge -ne (Join-Path $env:ProgramFiles ("Cage Guest Bridge\"+$VMId)) -or $Stage -ne (Join-Path $Bridge 'setup-packages')) { | |
| 9 | 新增: throw 'Incorrect guest installation target.' | |
| 10 | 新增:} | |
| 11 | 新增:foreach ($file in @($Packages.desktop,$Packages.winfsp,$Packages.sshfs,$CLI.uv,$CLI.python,$CLI.claude,$CLI.git)) { | |
| 12 | 新增: if ((Get-FileHash -LiteralPath (Join-Path $Stage $file.filename)).Hash -ne $file.sha256) { throw ('Guest package digest mismatch: '+$file.filename) } | |
| 13 | 新增:} | |
| 14 | 新增:$extras=Join-Path $Stage 'extras.zip' | |
| 15 | 新增:if ((Get-FileHash -LiteralPath $extras).Hash -ne $ExtrasSHA) { throw 'Guest components digest mismatch.' } | |
| 16 | 新增:$taskName="Cage-GUI-Bridge-$VMId-$GUIUserSID" | |
| 17 | 新增:$bridgeTask=Get-ScheduledTask -TaskName $taskName | |
| 18 | 新增:if ($bridgeTask.Description -cne "Cage protected GUI bridge $VMId $GUIUserSID" -or $bridgeTask.Principal.RunLevel -ne 'Limited' -or | |
| 19 | 新增: $bridgeTask.Actions[0].Execute -ne (Join-Path $Bridge 'Cage.GuestClipboard.exe')) { throw 'The registered bridge does not match this guest.' } | |
| 20 | 新增: | |
| 21 | 新增:# All paths below are inside the administrator-owned bridge. Extraction and | |
| 22 | 新增:# package operations never take a filename supplied by an ordinary guest user. | |
| 23 | 新增:function Install-GuestComponents { | |
| 24 | 新增: # Windows PowerShell 5.1 ZIP APIs and Copy-Item truncate long editor | |
| 25 | 新增: # paths on a fresh Windows install. The OS-supplied archive tool supports | |
| 26 | 新增: # long paths. Only the verified, Cage-assembled application archive is | |
| 27 | 新增: # extracted into the administrator-owned guest bridge. | |
| 28 | 新增: if (!$RuntimeInstalled) { | |
| 29 | 新增: & (Join-Path $env:SystemRoot 'System32/tar.exe') -xf $extras -C $Bridge | |
| 30 | 新增: if ($LASTEXITCODE -ne 0) { throw 'Could not unpack the verified guest application components.' } | |
| 31 | 新增: } | |
| 32 | 新增: | |
| 33 | 新增: foreach ($package in @($Packages.winfsp,$Packages.sshfs)) { | |
| 34 | 新增: $file=Join-Path $Stage $package.filename | |
| 35 | 新增: $proc=Start-Process -FilePath (Join-Path $env:SystemRoot 'System32/msiexec.exe') -ArgumentList ('/i "'+$file+'" /qn /norestart') -Wait -PassThru | |
| 36 | 新增: if ($proc.ExitCode -notin @(0,3010)) { throw ('Windows file-system driver install failed: '+$package.filename+' ('+$proc.ExitCode+')') } | |
| 37 | 新增: } | |
| 38 | 新增: | |
| 39 | 新增: $msix=Join-Path $Stage $Packages.desktop.filename | |
| 40 | 新增: $signature=Get-AuthenticodeSignature -LiteralPath $msix | |
| 41 | 新增: if ($signature.Status -ne 'Valid' -or $signature.SignerCertificate.Subject -notmatch 'Anthropic,? PBC') { throw 'The official Claude Desktop package signature is invalid.' } | |
| 42 | 新增: $provisioned=@(Get-AppxProvisionedPackage -Online | Where-Object DisplayName -ceq 'Claude') | |
| 43 | 新增: if ($provisioned.Count -gt 1 -or ($provisioned.Count -eq 1 -and $provisioned[0].PackageName -notmatch '^Claude_[0-9.]+_x64__pzs8sxrjxfjjc$')) { throw 'An unexpected existing Claude registration was preserved.' } | |
| 44 | 新增: if (!$provisioned.Count) { | |
| 45 | 新增: $null=Add-AppxProvisionedPackage -Online -PackagePath $msix -SkipLicense -Regions 'all' | |
| 46 | 新增: } | |
| 47 | 新增: $name='Cage-Workbench-Boot-'+$VMId.ToString('D') | |
| 48 | 新增: $image='"'+(Join-Path $Bridge 'cage-guest-boot.exe')+'" '+$VMId.ToString('D') | |
| 49 | 新增: $service=Get-CimInstance Win32_Service -Filter "Name='$name'" | |
| 50 | 新增: if (!$service) { | |
| 51 | 新增: $service=New-Service -Name $name -BinaryPathName $image -StartupType Automatic -DisplayName 'Cage dedicated workbench boot sign-in' | |
| 52 | 新增: } elseif ($service.PathName -cne $image -or $service.StartName -ne 'LocalSystem') { throw 'An unrelated boot service was preserved.' } | |
| 53 | 新增: Start-Service -Name $name | |
| 54 | 新增:} | |
| 55 | 新增:if ($Phase -eq 'Prepare') { Install-GuestComponents; return } | |
| 56 | 新增: | |
| 57 | 新增:$receipt=Join-Path $Stage 'cli-receipt.in' | |
| 58 | 新增:if (!(Test-Path -LiteralPath $receipt)) { $f=[IO.File]::Open($receipt,'CreateNew','Write','None'); $f.Dispose() } | |
| 59 | 新增:$admin=[Security.Principal.SecurityIdentifier]::new('S-1-5-32-544') | |
| 60 | 新增:function Set-ReceiptAccess([string]$Path,[string]$UserRights) { | |
| 61 | 新增: $acl=[Security.AccessControl.FileSecurity]::new() | |
| 62 | 新增: $acl.SetAccessRuleProtection($true,$false) | |
| 63 | 新增: $acl.SetOwner($admin) | |
| 64 | 新增: foreach ($sid in @('S-1-5-18','S-1-5-32-544')) { | |
| 65 | 新增: $acl.AddAccessRule([Security.AccessControl.FileSystemAccessRule]::new([Security.Principal.SecurityIdentifier]::new($sid),'FullControl','Allow')) | |
| 66 | 新增: } | |
| 67 | 新增: $acl.AddAccessRule([Security.AccessControl.FileSystemAccessRule]::new([Security.Principal.SecurityIdentifier]::new($GUIUserSID),$UserRights,'Allow')) | |
| 68 | 新增: Set-Acl -LiteralPath $Path -AclObject $acl | |
| 69 | 新增:} | |
| 70 | 新增:Set-ReceiptAccess $receipt 'Read,Write' | |
| 71 | 新增:$cliTask="Cage-Workbench-CLI-Setup-$VMId" | |
| 72 | 新增:$description="Cage guest workbench tool install $VMId $GUIUserSID" | |
| 73 | 新增:if ($old=Get-ScheduledTask -TaskName $cliTask -ErrorAction SilentlyContinue) { | |
| 74 | 新增: if ($old.Description -cne $description -or $old.State -eq 'Running') { throw 'A workbench installation is already active.' } | |
| 75 | 新增: Unregister-ScheduledTask -TaskName $cliTask -Confirm:$false | |
| 76 | 新增:} | |
| 77 | 新增:$action=New-ScheduledTaskAction -Execute (Join-Path $env:SystemRoot 'System32/WindowsPowerShell/v1.0/powershell.exe') -Argument ('-NoProfile -NonInteractive -ExecutionPolicy RemoteSigned -File "'+(Join-Path $Bridge 'install-windows-workbench-user-tools.ps1')+'" -BundleDirectory "'+$Stage+'" -BridgeDirectory "'+$Bridge+'"') | |
| 78 | 新增:$principal=New-ScheduledTaskPrincipal -UserId $GUIUserSID -LogonType Interactive -RunLevel Limited | |
| 79 | 新增:$settings=New-ScheduledTaskSettingsSet -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries -ExecutionTimeLimit (New-TimeSpan -Minutes 15) | |
| 80 | 新增:$null=Register-ScheduledTask -TaskName $cliTask -Action $action -Principal $principal -Settings $settings -Description $description | |
| 81 | 新增:try { | |
| 82 | 新增: [IO.File]::WriteAllText($receipt,'') | |
| 83 | 新增: Start-ScheduledTask -TaskName $cliTask | |
| 84 | 新增: $deadline=[DateTime]::UtcNow.AddMinutes(15) | |
| 85 | 新增: do { | |
| 86 | 新增: Start-Sleep -Seconds 1 | |
| 87 | 新增: $task=Get-ScheduledTask -TaskName $cliTask | |
| 88 | 新增: $info=Get-ScheduledTaskInfo -TaskName $cliTask | |
| 89 | 新增: $ran=$info.LastRunTime.Year -gt 2000 -and $info.LastTaskResult -notin @(267008,267009,267011) | |
| 90 | 新增: } while ((!$ran -or $task.State -eq 'Running') -and [DateTime]::UtcNow -lt $deadline) | |
| 91 | 新增: if (!$ran -or $task.State -eq 'Running' -or $info.LastTaskResult -ne 0) { throw 'Claude Code tools did not finish for the signed-in standard guest user.' } | |
| 92 | 新增: # Copy only the bounded allowlisted JSON fields from the file opened | |
| 93 | 新增: # without write sharing. Never execute a user-supplied receipt path here. | |
| 94 | 新增: $handle=[IO.File]::Open($receipt,'Open','Read','Read') | |
| 95 | 新增: try { | |
| 96 | 新增: if ($handle.Length -lt 2 -or $handle.Length -gt 16384) { throw 'Invalid Claude Code tools receipt.' } | |
| 97 | 新增: $reader=[IO.StreamReader]::new($handle) | |
| 98 | 新增: $value=$reader.ReadToEnd() | ConvertFrom-Json | |
| 99 | 新增: } finally { $handle.Dispose() } | |
| 100 | 新增: if ($value.version -ne 1 -or $value.claude_sha256 -ne $CLI.claude.sha256) { throw 'Invalid Claude Code version or hash.' } | |
| 101 | 新增: $result=[ordered]@{version=1} | |
| 102 | 新增: foreach ($name in @('python','claude','git_bash')) { | |
| 103 | 新增: $hash=$name+'_sha256' | |
| 104 | 新增: if (![IO.Path]::IsPathRooted($value.$name) -or $value.$hash -notmatch '^[a-fA-F0-9]{64}$') { throw 'Invalid Claude tool record.' } | |
| 105 | 新增: $result[$name]=$value.$name | |
| 106 | 新增: $result[$hash]=$value.$hash.ToLowerInvariant() | |
| 107 | 新增: } | |
| 108 | 新增: $target=Join-Path $Bridge 'cli-tools.json' | |
| 109 | 新增: [IO.File]::WriteAllText($target,($result | ConvertTo-Json -Compress),[Text.UTF8Encoding]::new($false)) | |
| 110 | 新增: Set-ReceiptAccess $target 'Read' | |
| 111 | 新增:} finally { | |
| 112 | 新增: if ((Get-ScheduledTask -TaskName $cliTask).State -eq 'Running') { Stop-ScheduledTask -TaskName $cliTask } | |
| 113 | 新增: Unregister-ScheduledTask -TaskName $cliTask -Confirm:$false | |
| 114 | 新增:} | |
| 115 | 新增:if ($bridgeTask.State -eq 'Running') { | |
| 116 | 新增: Stop-ScheduledTask -TaskName $taskName | |
| 117 | 新增: $deadline=[DateTime]::UtcNow.AddSeconds(15) | |
| 118 | 新增: while ((Get-ScheduledTask -TaskName $taskName).State -eq 'Running' -and [DateTime]::UtcNow -lt $deadline) { Start-Sleep -Milliseconds 250 } | |
| 119 | 新增:} | |
| 120 | 新增:Start-ScheduledTask -TaskName $taskName | |
| 121 | 新增: | |
| 122 | 新增:# Packages have been verified and installed. The instance-scoped host cache | |
| 123 | 新增:# permits repairs; the guest does not need a second copy of the installers. | |
| 124 | 新增:foreach ($package in @($Packages.desktop,$Packages.winfsp,$Packages.sshfs,$CLI.uv,$CLI.python,$CLI.claude,$CLI.git)) { | |
| 125 | 新增: [IO.File]::Delete((Join-Path $Stage $package.filename)) | |
| 126 | 新增:} | |
| 127 | 新增:[IO.File]::Delete($extras) | |
| @@ -0,0 +1,10 @@ | ||
| 1 | 新增:# Runs once as the new, non-elevated Cage workbench user. The administrator | |
| 2 | 新增:# already provisioned the verified MSIX machine-wide; finishing registration | |
| 3 | 新增:# here makes Windows consider it usable in this particular user session. | |
| 4 | 新增:[CmdletBinding()] | |
| 5 | 新增:param([Parameter(Mandatory)][string]$BundleDirectory,[Parameter(Mandatory)][string]$BridgeDirectory) | |
| 6 | 新增:$ErrorActionPreference='Stop' | |
| 7 | 新增:$user=[Security.Principal.WindowsIdentity]::GetCurrent() | |
| 8 | 新增:if ([Security.Principal.WindowsPrincipal]::new($user).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) { throw 'Run as the dedicated standard guest user.' } | |
| 9 | 新增:Add-AppxPackage -RegisterByFamilyName -MainPackage 'Claude_pzs8sxrjxfjjc' -ErrorAction Stop | |
| 10 | 新增:& (Join-Path $PSScriptRoot 'install-cli.ps1') -BundleDirectory $BundleDirectory -BridgeDirectory $BridgeDirectory -WorkbenchSetup | |
| @@ -0,0 +1,241 @@ | ||
| 1 | 新增:// System-output audio for the already authorized per-user GUI window agent. | |
| 2 | 新增:import AppKit | |
| 3 | 新增:import AVFoundation | |
| 4 | 新增:import ScreenCaptureKit | |
| 5 | 新增: | |
| 6 | 新增:private let audioSampleRate = 48000 | |
| 7 | 新增:private let audioChannels = 2 | |
| 8 | 新增:private let audioFrameBytes = 4 | |
| 9 | 新增: | |
| 10 | 新增:private func audioGUIAvailable() -> Bool { | |
| 11 | 新增: var info = stat() | |
| 12 | 新增: return stat("/dev/console", &info) == 0 && info.st_uid == getuid() && info.st_uid >= 500 && | |
| 13 | 新增: (CGSessionCopyCurrentDictionary() as? [String: Any])?["CGSSessionScreenIsLocked"] as? Bool != true | |
| 14 | 新增:} | |
| 15 | 新增: | |
| 16 | 新增:private func writeAudioBytes(_ fd: Int32, _ data: Data) throws { | |
| 17 | 新增: try data.withUnsafeBytes { bytes in | |
| 18 | 新增: var offset = 0 | |
| 19 | 新增: while offset < bytes.count { | |
| 20 | 新增: let written = Darwin.write(fd, bytes.baseAddress!.advanced(by: offset), bytes.count - offset) | |
| 21 | 新增: if written < 0 && errno == EINTR { continue } | |
| 22 | 新增: guard written > 0 else { throw Failure(7, "audio_connection_closed") } | |
| 23 | 新增: offset += written | |
| 24 | 新增: } | |
| 25 | 新增: } | |
| 26 | 新增:} | |
| 27 | 新增: | |
| 28 | 新增:private final class AudioPCMConverter { | |
| 29 | 新增: private let outputFormat = AVAudioFormat(commonFormat: .pcmFormatInt16, sampleRate: Double(audioSampleRate), channels: AVAudioChannelCount(audioChannels), interleaved: true)! | |
| 30 | 新增: private var converter: AVAudioConverter? | |
| 31 | 新增: private var inputFormat: AVAudioFormat? | |
| 32 | 新增: | |
| 33 | 新增: func convert(_ input: AVAudioPCMBuffer) throws -> Data { | |
| 34 | 新增: guard input.format.sampleRate == Double(audioSampleRate), input.format.channelCount == audioChannels, | |
| 35 | 新增: input.frameLength > 0, input.frameLength <= 16384 else { throw Failure(7, "audio_format_invalid") } | |
| 36 | 新增: if inputFormat != input.format { | |
| 37 | 新增: converter = AVAudioConverter(from: input.format, to: outputFormat) | |
| 38 | 新增: inputFormat = input.format | |
| 39 | 新增: } | |
| 40 | 新增: guard let converter, let output = AVAudioPCMBuffer(pcmFormat: outputFormat, frameCapacity: input.frameLength) else { | |
| 41 | 新增: throw Failure(7, "audio_format_invalid") | |
| 42 | 新增: } | |
| 43 | 新增: try converter.convert(to: output, from: input) | |
| 44 | 新增: let buffer = output.audioBufferList.pointee.mBuffers | |
| 45 | 新增: let count = Int(output.frameLength) * audioFrameBytes | |
| 46 | 新增: guard count <= Int(buffer.mDataByteSize), let data = buffer.mData else { throw Failure(7, "audio_format_invalid") } | |
| 47 | 新增: return Data(bytes: data, count: count) | |
| 48 | 新增: } | |
| 49 | 新增: | |
| 50 | 新增: func convert(_ sample: CMSampleBuffer) throws -> Data { | |
| 51 | 新增: guard sample.isValid, let description = sample.formatDescription else { throw Failure(7, "audio_format_invalid") } | |
| 52 | 新增: guard let basic = CMAudioFormatDescriptionGetStreamBasicDescription(description), | |
| 53 | 新增: basic.pointee.mFormatID == kAudioFormatLinearPCM, basic.pointee.mBytesPerFrame > 0, | |
| 54 | 新增: basic.pointee.mSampleRate == Double(audioSampleRate), basic.pointee.mChannelsPerFrame == audioChannels else { | |
| 55 | 新增: throw Failure(7, "audio_format_invalid") | |
| 56 | 新增: } | |
| 57 | 新增: let format = AVAudioFormat(cmAudioFormatDescription: description) | |
| 58 | 新增: var required = 0 | |
| 59 | 新增: var block: CMBlockBuffer? | |
| 60 | 新增: let flags = UInt32(kCMSampleBufferFlag_AudioBufferList_Assure16ByteAlignment) | |
| 61 | 新增: _ = CMSampleBufferGetAudioBufferListWithRetainedBlockBuffer(sample, bufferListSizeNeededOut: &required, | |
| 62 | 新增: bufferListOut: nil, bufferListSize: 0, blockBufferAllocator: kCFAllocatorDefault, | |
| 63 | 新增: blockBufferMemoryAllocator: kCFAllocatorDefault, flags: flags, blockBufferOut: &block) | |
| 64 | 新增: guard required > 0, required <= 4096 else { throw Failure(7, "audio_format_invalid") } | |
| 65 | 新增: let memory = UnsafeMutableRawPointer.allocate(byteCount: required, alignment: 16) | |
| 66 | 新增: defer { memory.deallocate() } | |
| 67 | 新增: let list = memory.bindMemory(to: AudioBufferList.self, capacity: 1) | |
| 68 | 新增: let status = CMSampleBufferGetAudioBufferListWithRetainedBlockBuffer(sample, bufferListSizeNeededOut: nil, | |
| 69 | 新增: bufferListOut: list, bufferListSize: required, blockBufferAllocator: kCFAllocatorDefault, | |
| 70 | 新增: blockBufferMemoryAllocator: kCFAllocatorDefault, flags: flags, blockBufferOut: &block) | |
| 71 | 新增: guard status == noErr, let input = AVAudioPCMBuffer(pcmFormat: format, bufferListNoCopy: list, deallocator: nil) else { | |
| 72 | 新增: throw Failure(7, "audio_format_invalid") | |
| 73 | 新增: } | |
| 74 | 新增: return try withExtendedLifetime(block) { try convert(input) } | |
| 75 | 新增: } | |
| 76 | 新增:} | |
| 77 | 新增: | |
| 78 | 新增:private final class AudioSamples: NSObject, SCStreamOutput, SCStreamDelegate, @unchecked Sendable { | |
| 79 | 新增: private let lock = NSLock() | |
| 80 | 新增: private let converter = AudioPCMConverter() // Owned by the serial sample queue. | |
| 81 | 新增: private var pending = Data() | |
| 82 | 新增: private var failed = false | |
| 83 | 新增: private let limit = audioSampleRate * audioChannels * 2 / 5 // At most 200 ms. | |
| 84 | 新增: | |
| 85 | 新增: func stream(_ stream: SCStream, didOutputSampleBuffer sampleBuffer: CMSampleBuffer, of type: SCStreamOutputType) { | |
| 86 | 新增: guard type == .audio, sampleBuffer.isValid, CMSampleBufferDataIsReady(sampleBuffer), CMSampleBufferGetNumSamples(sampleBuffer) > 0 else { return } | |
| 87 | 新增: do { | |
| 88 | 新增: append(try converter.convert(sampleBuffer)) | |
| 89 | 新增: } catch { | |
| 90 | 新增: stop() | |
| 91 | 新增: } | |
| 92 | 新增: } | |
| 93 | 新增: | |
| 94 | 新增: func stream(_ stream: SCStream, didStopWithError error: Error) { | |
| 95 | 新增: stop() | |
| 96 | 新增: } | |
| 97 | 新增: | |
| 98 | 新增: func append(_ pcm: Data) { | |
| 99 | 新增: lock.lock(); defer { lock.unlock() } | |
| 100 | 新增: if !failed { | |
| 101 | 新增: pending.append(pcm) | |
| 102 | 新增: if pending.count > limit { pending.removeFirst(pending.count - limit) } | |
| 103 | 新增: } | |
| 104 | 新增: } | |
| 105 | 新增: | |
| 106 | 新增: func stop() { | |
| 107 | 新增: lock.lock(); failed = true; pending.removeAll(); lock.unlock() | |
| 108 | 新增: } | |
| 109 | 新增: | |
| 110 | 新增: func next() throws -> Data { | |
| 111 | 新增: lock.lock(); defer { lock.unlock() } | |
| 112 | 新增: guard !failed else { throw Failure(7, "audio_capture_failed") } | |
| 113 | 新增: let count = min(pending.count, 3840) // 20 ms, whole interleaved frames. | |
| 114 | 新增: let result = Data(pending.prefix(count)) | |
| 115 | 新增: pending.removeFirst(count) | |
| 116 | 新增: return result | |
| 117 | 新增: } | |
| 118 | 新增:} | |
| 119 | 新增: | |
| 120 | 新增:enum MacAudioCapture { | |
| 121 | 新增: static func status() -> [String: Any] { | |
| 122 | 新增: let gui = audioGUIAvailable() | |
| 123 | 新增: let permission = CGPreflightScreenCaptureAccess() | |
| 124 | 新增: return ["supported": true, "available": gui && permission, "format": "s16le", | |
| 125 | 新增: "sample_rate": audioSampleRate, "channels": audioChannels, | |
| 126 | 新增: "reason": !gui ? "requires_gui_login" : (!permission ? "screen_recording_permission" : "")] | |
| 127 | 新增: } | |
| 128 | 新增: | |
| 129 | 新增: static func respond(_ fd: Int32) async { | |
| 130 | 新增: var stream: SCStream? | |
| 131 | 新增: var ready = false | |
| 132 | 新增: do { | |
| 133 | 新增: try requireGuest() | |
| 134 | 新增: let epoch = try await MacGUISession.shared.validate() | |
| 135 | 新增: var timeout = timeval(tv_sec: 2, tv_usec: 0) | |
| 136 | 新增: setsockopt(fd, SOL_SOCKET, SO_SNDTIMEO, &timeout, socklen_t(MemoryLayout.size(ofValue: timeout))) | |
| 137 | 新增: guard audioGUIAvailable() else { throw Failure(4, "requires_gui_login") } | |
| 138 | 新增: // The existing setup-screen action opens the guest's system consent | |
| 139 | 新增: // UI. Audio status and playback never approve or request it silently. | |
| 140 | 新增: guard CGPreflightScreenCaptureAccess() else { throw Failure(6, "screen_recording_permission") } | |
| 141 | 新增: let content = try await SCShareableContent.excludingDesktopWindows(true, onScreenWindowsOnly: true) | |
| 142 | 新增: guard let display = content.displays.first else { throw Failure(7, "audio_display_unavailable") } | |
| 143 | 新增: let filter = SCContentFilter(display: display, excludingApplications: [], exceptingWindows: []) | |
| 144 | 新增: let configuration = SCStreamConfiguration() | |
| 145 | 新增: configuration.capturesAudio = true | |
| 146 | 新增: configuration.sampleRate = audioSampleRate | |
| 147 | 新增: configuration.channelCount = audioChannels | |
| 148 | 新增: configuration.width = 2 | |
| 149 | 新增: configuration.height = 2 | |
| 150 | 新增: configuration.minimumFrameInterval = CMTime(value: 1, timescale: 1) | |
| 151 | 新增: configuration.queueDepth = 3 | |
| 152 | 新增: let samples = AudioSamples() | |
| 153 | 新增: let capture = SCStream(filter: filter, configuration: configuration, delegate: samples) | |
| 154 | 新增: stream = capture | |
| 155 | 新增: try capture.addStreamOutput(samples, type: .audio, sampleHandlerQueue: DispatchQueue(label: "dev.cage.GuestAudio.samples")) | |
| 156 | 新增: try await capture.startCapture() | |
| 157 | 新增: guard audioGUIAvailable() else { throw Failure(4, "requires_gui_login") } | |
| 158 | 新增: let header: [String: Any] = ["ready": true, "format": "s16le", "sample_rate": audioSampleRate, "channels": audioChannels] | |
| 159 | 新增: try writeAudioBytes(fd, JSONSerialization.data(withJSONObject: header) + Data([10])) | |
| 160 | 新增: ready = true | |
| 161 | 新增: var checked = Date.distantPast | |
| 162 | 新增: while !Task.isCancelled { | |
| 163 | 新增: if Date().timeIntervalSince(checked) >= 0.5 { | |
| 164 | 新增: guard audioGUIAvailable(), CGPreflightScreenCaptureAccess() else { break } | |
| 165 | 新增: try await MacGUISession.shared.validate(epoch) | |
| 166 | 新增: checked = Date() | |
| 167 | 新增: } | |
| 168 | 新增: var byte: UInt8 = 0 | |
| 169 | 新增: let incoming = recv(fd, &byte, 1, MSG_PEEK | MSG_DONTWAIT) | |
| 170 | 新增: if incoming == 0 || incoming > 0 { break } | |
| 171 | 新增: if errno != EAGAIN && errno != EWOULDBLOCK && errno != EINTR { break } | |
| 172 | 新增: let packet = try samples.next() | |
| 173 | 新增: if packet.isEmpty { try await Task.sleep(nanoseconds: 20_000_000) } | |
| 174 | 新增: else { try writeAudioBytes(fd, packet) } | |
| 175 | 新增: } | |
| 176 | 新增: } catch { | |
| 177 | 新增: GuestDiagnostic.record("window", (error as? Failure)?.message ?? "audio_capture_failed") | |
| 178 | 新增: if !ready { | |
| 179 | 新增: let reason = (error as? Failure)?.message ?? "audio_capture_failed" | |
| 180 | 新增: if let data = try? JSONSerialization.data(withJSONObject: ["error": reason]) { | |
| 181 | 新增: try? writeAudioBytes(fd, data + Data([10])) | |
| 182 | 新增: } | |
| 183 | 新增: } | |
| 184 | 新增: } | |
| 185 | 新增: if let stream { try? await stream.stopCapture() } | |
| 186 | 新增: } | |
| 187 | 新增: | |
| 188 | 新增: static func selfTest() throws { | |
| 189 | 新增: let format = AVAudioFormat(commonFormat: .pcmFormatFloat32, sampleRate: 48000, channels: 2, interleaved: false)! | |
| 190 | 新增: let input = AVAudioPCMBuffer(pcmFormat: format, frameCapacity: 4)! | |
| 191 | 新增: input.frameLength = 4 | |
| 192 | 新增: let left: [Float] = [-0.75, 0, 0.5, 0.75] | |
| 193 | 新增: let right: [Float] = [0.75, 0.5, 0, -0.75] | |
| 194 | 新增: for index in 0..<4 { | |
| 195 | 新增: input.floatChannelData![0][index] = left[index] | |
| 196 | 新增: input.floatChannelData![1][index] = right[index] | |
| 197 | 新增: } | |
| 198 | 新增: let converter = AudioPCMConverter() | |
| 199 | 新增: let bytes = try converter.convert(input) | |
| 200 | 新增: guard bytes.count == 16 else { throw Failure(7, "audio_test_length") } | |
| 201 | 新增: for index in 0..<8 { | |
| 202 | 新增: let value = Int16(bitPattern: UInt16(bytes[index * 2]) | UInt16(bytes[index * 2 + 1]) << 8) | |
| 203 | 新增: let expected = index % 2 == 0 ? left[index / 2] : right[index / 2] | |
| 204 | 新增: guard abs(Double(value) / 32768 - Double(expected)) < 0.001 else { throw Failure(7, "audio_test_channels") } | |
| 205 | 新增: } | |
| 206 | 新增: let again = try converter.convert(input) | |
| 207 | 新增: guard again == bytes else { throw Failure(7, "audio_test_continuity") } | |
| 208 | 新增: var timing = CMSampleTimingInfo(duration: CMTime(value: 1, timescale: 48000), presentationTimeStamp: .zero, decodeTimeStamp: .invalid) | |
| 209 | 新增: var sample: CMSampleBuffer? | |
| 210 | 新增: let created = CMSampleBufferCreate(allocator: kCFAllocatorDefault, dataBuffer: nil, dataReady: false, | |
| 211 | 新增: makeDataReadyCallback: nil, refcon: nil, formatDescription: format.formatDescription, | |
| 212 | 新增: sampleCount: 4, sampleTimingEntryCount: 1, sampleTimingArray: &timing, | |
| 213 | 新增: sampleSizeEntryCount: 0, sampleSizeArray: nil, sampleBufferOut: &sample) | |
| 214 | 新增: guard created == noErr, let sample, | |
| 215 | 新增: CMSampleBufferSetDataBufferFromAudioBufferList(sample, blockBufferAllocator: kCFAllocatorDefault, | |
| 216 | 新增: blockBufferMemoryAllocator: kCFAllocatorDefault, flags: 0, bufferList: input.audioBufferList) == noErr else { | |
| 217 | 新增: throw Failure(7, "audio_test_sample_creation") | |
| 218 | 新增: } | |
| 219 | 新增: CMSampleBufferSetDataReady(sample) | |
| 220 | 新增: guard try converter.convert(sample) == bytes else { throw Failure(7, "audio_test_sample_conversion") } | |
| 221 | 新增: let queued = AudioSamples() | |
| 222 | 新增: queued.append(Data(repeating: 0, count: 10000)) | |
| 223 | 新增: queued.append(Data(repeating: 1, count: 40000)) | |
| 224 | 新增: var collected = Data() | |
| 225 | 新增: while true { | |
| 226 | 新增: let packet = try queued.next() | |
| 227 | 新增: if packet.isEmpty { break } | |
| 228 | 新增: guard packet.count <= 3840, packet.count % 4 == 0 else { throw Failure(7, "audio_test_packet_size") } | |
| 229 | 新增: collected.append(packet) | |
| 230 | 新增: } | |
| 231 | 新增: guard collected == Data(repeating: 1, count: 38400) else { throw Failure(7, "audio_test_queue_limit") } | |
| 232 | 新增: queued.stop() | |
| 233 | 新增: do { | |
| 234 | 新增: _ = try queued.next() | |
| 235 | 新增: throw Failure(7, "audio_test_stop") | |
| 236 | 新增: } catch let error as Failure { | |
| 237 | 新增: guard error.message == "audio_capture_failed" else { throw error } | |
| 238 | 新增: } | |
| 239 | 新增: print("macOS audio: CoreMedia samples, 48 kHz stereo s16le, consecutive buffers, bounded queue and stopped capture passed") | |
| 240 | 新增: } | |
| 241 | 新增:} | |
| @@ -0,0 +1,123 @@ | ||
| 1 | 新增:import net from "node:net"; | |
| 2 | 新增:import fs from "node:fs/promises"; | |
| 3 | 新增:import path from "node:path"; | |
| 4 | 新增:import { lines } from "./windows-browser.mjs"; | |
| 5 | 新增: | |
| 6 | 新增:async function privateDirectory(directory) { | |
| 7 | 新增: await fs.mkdir(directory, { recursive: true, mode: 0o700 }); | |
| 8 | 新增: const info = await fs.lstat(directory); | |
| 9 | 新增: if (!info.isDirectory() || info.uid !== process.getuid() || (info.mode & 0o077)) | |
| 10 | 新增: throw new Error("Browser service directory is unavailable"); | |
| 11 | 新增: return path.join(directory, "browser.sock"); | |
| 12 | 新增:} | |
| 13 | 新增: | |
| 14 | 新增:async function socketInfo(address) { | |
| 15 | 新增: const info = await fs.lstat(address); | |
| 16 | 新增: if (!info.isSocket() || info.uid !== process.getuid() || (info.mode & 0o077)) | |
| 17 | 新增: throw new Error("Browser service socket is unavailable"); | |
| 18 | 新增: return info; | |
| 19 | 新增:} | |
| 20 | 新增: | |
| 21 | 新增:function connect(address) { | |
| 22 | 新增: return new Promise((resolve, reject) => { | |
| 23 | 新增: const socket = net.createConnection({ path: address, allowHalfOpen: true }); | |
| 24 | 新增: socket.once("error", reject); | |
| 25 | 新增: socket.once("connect", () => { socket.off("error", reject); resolve(socket); }); | |
| 26 | 新增: }); | |
| 27 | 新增:} | |
| 28 | 新增: | |
| 29 | 新增:export async function relayMacOSBrowser(directory, input = process.stdin, output = process.stdout) { | |
| 30 | 新增: const address = await privateDirectory(directory); | |
| 31 | 新增: await socketInfo(address); | |
| 32 | 新增: const socket = await connect(address); | |
| 33 | 新增: socket.on("error", () => {}); | |
| 34 | 新增: try { | |
| 35 | 新增: const replies = lines(socket, 30 << 20)[Symbol.asyncIterator](); | |
| 36 | 新增: for await (const line of lines(input)) { | |
| 37 | 新增: await new Promise((resolve, reject) => socket.write(line + "\n", error => error ? reject(error) : resolve())); | |
| 38 | 新增: const reply = await replies.next(); | |
| 39 | 新增: if (reply.done) throw new Error("Browser service connection closed"); | |
| 40 | 新增: await new Promise((resolve, reject) => output.write(reply.value + "\n", error => error ? reject(error) : resolve())); | |
| 41 | 新增: } | |
| 42 | 新增: socket.end(); | |
| 43 | 新增: } finally { | |
| 44 | 新增: socket.destroy(); | |
| 45 | 新增: } | |
| 46 | 新增:} | |
| 47 | 新增: | |
| 48 | 新增:// The ordinary guest user owns one browser service. Each caller owns only its | |
| 49 | 新增:// connection and cancellation, while dispatch retains a single mutation order. | |
| 50 | 新增:export async function serveMacOSBrowser({ directory, dispatch, close, disconnect }) { | |
| 51 | 新增: const address = await privateDirectory(directory); | |
| 52 | 新增: const previous = await fs.lstat(address).catch(error => { if (error.code !== "ENOENT") throw error; }); | |
| 53 | 新增: if (previous) { | |
| 54 | 新增: await socketInfo(address); | |
| 55 | 新增: let live; | |
| 56 | 新增: try { live = await connect(address); } | |
| 57 | 新增: catch (error) { if (error.code !== "ECONNREFUSED" && error.code !== "ENOENT") throw error; } | |
| 58 | 新增: if (live) { live.destroy(); throw new Error("Browser service is already running"); } | |
| 59 | 新增: const current = await fs.lstat(address).catch(error => { if (error.code !== "ENOENT") throw error; }); | |
| 60 | 新增: if (current && current.ino !== previous.ino) throw new Error("Browser service owner changed"); | |
| 61 | 新增: if (current) await fs.unlink(address); | |
| 62 | 新增: } | |
| 63 | 新增: const clients = new Set(); | |
| 64 | 新增: let queue = Promise.resolve(), stopping; | |
| 65 | 新增: const request = (input, options = {}) => { | |
| 66 | 新增: const pending = queue.then(() => { | |
| 67 | 新增: if (stopping) throw new Error("Browser service is stopping"); | |
| 68 | 新增: options.signal?.throwIfAborted(); | |
| 69 | 新增: return dispatch(input, options); | |
| 70 | 新增: }); | |
| 71 | 新增: queue = pending.catch(() => {}); | |
| 72 | 新增: return pending; | |
| 73 | 新增: }; | |
| 74 | 新增: const server = net.createServer({ allowHalfOpen: true }, socket => { | |
| 75 | 新增: if (stopping || clients.size >= 16) { socket.destroy(); return; } | |
| 76 | 新增: clients.add(socket); | |
| 77 | 新增: const cancellation = new AbortController(); | |
| 78 | 新增: socket.on("error", () => {}); | |
| 79 | 新增: socket.once("end", () => { cancellation.abort(); socket.end(); }); | |
| 80 | 新增: socket.once("close", () => { | |
| 81 | 新增: cancellation.abort(); clients.delete(socket); | |
| 82 | 新增: if (disconnect) { | |
| 83 | 新增: const released = queue.then(() => disconnect(cancellation.signal)); | |
| 84 | 新增: queue = released.catch(() => {}); | |
| 85 | 新增: } | |
| 86 | 新增: }); | |
| 87 | 新增: let pendingReply = false; | |
| 88 | 新增: void (async () => { | |
| 89 | 新增: try { | |
| 90 | 新增: for await (const line of lines(socket)) { | |
| 91 | 新增: if (pendingReply) throw new Error("Browser service caller has an unfinished request"); | |
| 92 | 新增: pendingReply = true; | |
| 93 | 新增: const pending = request(JSON.parse(line), { signal: cancellation.signal }); | |
| 94 | 新增: void (async () => { | |
| 95 | 新增: let result; | |
| 96 | 新增: try { result = await pending; } | |
| 97 | 新增: catch (error) { result = { error: error.safe ? error.message : "客机浏览器操作失败", code: error.safe ? error.code : "browser_operation_failed" }; } | |
| 98 | 新增: if (socket.destroyed) return; | |
| 99 | 新增: const data = JSON.stringify({ ...result, service: { version: 1, persistent: true } }) + "\n"; | |
| 100 | 新增: if (Buffer.byteLength(data) > 30 << 20) throw new Error("Browser service response is too large"); | |
| 101 | 新增: await new Promise((resolve, reject) => socket.write(data, error => error ? reject(error) : resolve())); | |
| 102 | 新增: })().catch(() => socket.destroy()).finally(() => { pendingReply = false; }); | |
| 103 | 新增: } | |
| 104 | 新增: } catch { socket.destroy(); } | |
| 105 | 新增: })(); | |
| 106 | 新增: }); | |
| 107 | 新增: await new Promise((resolve, reject) => { server.once("error", reject); server.listen(address, resolve); }); | |
| 108 | 新增: await fs.chmod(address, 0o600); | |
| 109 | 新增: const owned = await socketInfo(address); | |
| 110 | 新增: const stop = async () => { | |
| 111 | 新增: if (!stopping) stopping = (async () => { | |
| 112 | 新增: const closed = new Promise(resolve => server.close(resolve)); | |
| 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); | |
| 119 | 新增: })(); | |
| 120 | 新增: return stopping; | |
| 121 | 新增: }; | |
| 122 | 新增: return { request, close: stop }; | |
| 123 | 新增:} | |
| @@ -0,0 +1,316 @@ | ||
| 1 | 新增:// This process runs over the standard user's pinned guest SSH session. Chrome's | |
| 2 | 新增:// DevTools connection uses inherited pipes, and host WebKit receives only pixels. | |
| 3 | 新增:import { chromium } from "/usr/local/libexec/cage-workbench-browser-4.145.0-pw1.65.0/playwright/index.mjs"; | |
| 4 | 新增:import { spawn } from "node:child_process"; | |
| 5 | 新增:import { randomBytes } from "node:crypto"; | |
| 6 | 新增:import { mkdir, rm, writeFile } from "node:fs/promises"; | |
| 7 | 新增:import { homedir } from "node:os"; | |
| 8 | 新增:import path from "node:path"; | |
| 9 | 新增:import { createInterface } from "node:readline"; | |
| 10 | 新增:import { once } from "node:events"; | |
| 11 | 新增: | |
| 12 | 新增:const editorSessions = path.join( | |
| 13 | 新增: homedir(), | |
| 14 | 新增: "Library", | |
| 15 | 新增: "Application Support", | |
| 16 | 新增: "Cage", | |
| 17 | 新增: "EditorSessions", | |
| 18 | 新增:); | |
| 19 | 新增:const profile = path.join( | |
| 20 | 新增: homedir(), | |
| 21 | 新增: "Library", | |
| 22 | 新增: "Application Support", | |
| 23 | 新增: "Cage", | |
| 24 | 新增: "Browser", | |
| 25 | 新增:); | |
| 26 | 新增:let editorConfig; | |
| 27 | 新增:let browser, page, editor, editorFolder, editorAddress, editorPassword, closing; | |
| 28 | 新增:function close() { | |
| 29 | 新增: return (closing ??= (async () => { | |
| 30 | 新增: if (editor) editor.kill(); | |
| 31 | 新增: await browser?.close().catch(() => {}); | |
| 32 | 新增: if (editorConfig) await rm(editorConfig, { force: true }); | |
| 33 | 新增: })()); | |
| 34 | 新增:} | |
| 35 | 新增:async function getPage() { | |
| 36 | 新增: if (!browser) { | |
| 37 | 新增: await mkdir(profile, { recursive: true, mode: 0o700 }); | |
| 38 | 新增: browser = await chromium.launchPersistentContext(profile, { | |
| 39 | 新增: executablePath: | |
| 40 | 新增: "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome", | |
| 41 | 新增: headless: true, | |
| 42 | 新增: chromiumSandbox: true, | |
| 43 | 新增: viewport: { width: 1140, height: 700 }, | |
| 44 | 新增: args: ["--disable-quic", "--no-default-browser-check"], | |
| 45 | 新增: acceptDownloads: false, | |
| 46 | 新增: timeout: 20000, | |
| 47 | 新增: }); | |
| 48 | 新增: browser.setDefaultTimeout(7000); | |
| 49 | 新增: page = browser.pages()[0] ?? (await browser.newPage()); | |
| 50 | 新增: browser.on("page", (p) => { | |
| 51 | 新增: page = p; | |
| 52 | 新增: }); | |
| 53 | 新增: browser.on("close", () => { | |
| 54 | 新增: browser = undefined; | |
| 55 | 新增: page = undefined; | |
| 56 | 新增: }); | |
| 57 | 新增: } | |
| 58 | 新增: if (!page || page.isClosed()) | |
| 59 | 新增: page = browser.pages().at(-1) ?? (await browser.newPage()); | |
| 60 | 新增: return page; | |
| 61 | 新增:} | |
| 62 | 新增:async function openEditor(folder) { | |
| 63 | 新增: const p = await getPage(); | |
| 64 | 新增: if ( | |
| 65 | 新增: editorFolder !== folder || | |
| 66 | 新增: !editor || | |
| 67 | 新增: editor.exitCode !== null || | |
| 68 | 新增: !editorAddress | |
| 69 | 新增: ) { | |
| 70 | 新增: if (editor) editor.kill(); | |
| 71 | 新增: editorPassword = randomBytes(32).toString("hex"); | |
| 72 | 新增: const project = path.basename(folder); | |
| 73 | 新增: if ( | |
| 74 | 新增: !/^[0-9a-f]{24}$/.test(project) || | |
| 75 | 新增: folder !== path.join(homedir(), "Cage", "Projects", project) | |
| 76 | 新增: ) | |
| 77 | 新增: throw new Error("请选择已授权的客机项目"); | |
| 78 | 新增: await mkdir(editorSessions, { recursive: true, mode: 0o700 }); | |
| 79 | 新增: if (editorConfig) await rm(editorConfig, { force: true }); | |
| 80 | 新增: editorConfig = path.join(editorSessions, project + ".yaml"); | |
| 81 | 新增: await writeFile( | |
| 82 | 新增: editorConfig, | |
| 83 | 新增: "bind-addr: 127.0.0.1:0\nauth: password\npassword: " + | |
| 84 | 新增: editorPassword + | |
| 85 | 新增: "\ncert: false\n", | |
| 86 | 新增: { mode: 0o600 }, | |
| 87 | 新增: ); | |
| 88 | 新增: const child = spawn( | |
| 89 | 新增: "/usr/local/libexec/cage-macos-terminal", | |
| 90 | 新增: ["--editor", folder], | |
| 91 | 新增: { | |
| 92 | 新增: stdio: ["pipe", "pipe", "pipe"], | |
| 93 | 新增: }, | |
| 94 | 新增: ); | |
| 95 | 新增: editor = child; | |
| 96 | 新增: child.stdin.on("error", () => {}); | |
| 97 | 新增: editorAddress = await new Promise((resolve, reject) => { | |
| 98 | 新增: let recent = ""; | |
| 99 | 新增: const timer = setTimeout( | |
| 100 | 新增: () => finish(new Error("客机编辑器未能启动,请检查项目授权")), | |
| 101 | 新增: 12000, | |
| 102 | 新增: ); | |
| 103 | 新增: const read = (data) => { | |
| 104 | 新增: recent = (recent + data.toString()).slice(-6000); | |
| 105 | 新增: const address = recent.match( | |
| 106 | 新增: /HTTP server listening on (http:\/\/127\.0\.0\.1:[1-9][0-9]*)/, | |
| 107 | 新增: ); | |
| 108 | 新增: if (address) finish(null, address[1]); | |
| 109 | 新增: }; | |
| 110 | 新增: const failed = () => | |
| 111 | 新增: finish(new Error("请先在 Cage 授权此项目,再打开编辑器")); | |
| 112 | 新增: function finish(error, address) { | |
| 113 | 新增: clearTimeout(timer); | |
| 114 | 新增: child.stdout.off("data", read); | |
| 115 | 新增: child.stderr.off("data", read); | |
| 116 | 新增: child.off("error", failed); | |
| 117 | 新增: child.off("exit", failed); | |
| 118 | 新增: if (error) { | |
| 119 | 新增: child.kill(); | |
| 120 | 新增: reject(error); | |
| 121 | 新增: } else { | |
| 122 | 新增: child.stdout.resume(); | |
| 123 | 新增: child.stderr.resume(); | |
| 124 | 新增: resolve(address); | |
| 125 | 新增: } | |
| 126 | 新增: } | |
| 127 | 新增: child.stdout.on("data", read); | |
| 128 | 新增: child.stderr.on("data", read); | |
| 129 | 新增: child.once("error", failed); | |
| 130 | 新增: child.once("exit", failed); | |
| 131 | 新增: }); | |
| 132 | 新增: editorFolder = folder; | |
| 133 | 新增: child.once("exit", () => { | |
| 134 | 新增: if (editor === child) { | |
| 135 | 新增: editor = undefined; | |
| 136 | 新增: editorAddress = undefined; | |
| 137 | 新增: } | |
| 138 | 新增: }); | |
| 139 | 新增: } | |
| 140 | 新增: const login = await p.request.post(editorAddress + "/login", { | |
| 141 | 新增: form: { password: editorPassword }, | |
| 142 | 新增: maxRedirects: 0, | |
| 143 | 新增: timeout: 7000, | |
| 144 | 新增: }); | |
| 145 | 新增: if (![302, 303].includes(login.status())) | |
| 146 | 新增: throw new Error("客机编辑器登录失败"); | |
| 147 | 新增: await login.dispose(); | |
| 148 | 新增: await p.goto(editorAddress + "/?folder=" + encodeURIComponent(folder), { | |
| 149 | 新增: waitUntil: "commit", | |
| 150 | 新增: }); | |
| 151 | 新增:} | |
| 152 | 新增:const keys = new Set([ | |
| 153 | 新增: "Tab", | |
| 154 | 新增: "Enter", | |
| 155 | 新增: "Backspace", | |
| 156 | 新增: "Delete", | |
| 157 | 新增: "Escape", | |
| 158 | 新增: "ArrowLeft", | |
| 159 | 新增: "ArrowRight", | |
| 160 | 新增: "ArrowUp", | |
| 161 | 新增: "ArrowDown", | |
| 162 | 新增: "Home", | |
| 163 | 新增: "End", | |
| 164 | 新增: "PageUp", | |
| 165 | 新增: "PageDown", | |
| 166 | 新增: "Space", | |
| 167 | 新增: "F5", | |
| 168 | 新增: "F8", | |
| 169 | 新增: "F9", | |
| 170 | 新增: "F10", | |
| 171 | 新增: "F11", | |
| 172 | 新增:]); | |
| 173 | 新增:// Observe a fresh document in the actual guest browser. The separate network | |
| 174 | 新增:// context carries no workbench session cookies and can reach only the fixed diagnostic service. | |
| 175 | 新增:async function audit(timezone, network) { | |
| 176 | 新增: await getPage(); | |
| 177 | 新增: const previous = page; | |
| 178 | 新增: const settingsPage = await browser.newPage(); | |
| 179 | 新增: let settings; | |
| 180 | 新增: try { | |
| 181 | 新增: settings = await settingsPage.evaluate( | |
| 182 | 新增: (zone) => ({ | |
| 183 | 新增: timezone: Intl.DateTimeFormat().resolvedOptions().timeZone, | |
| 184 | 新增: expected_timezone: new Intl.DateTimeFormat("en", { | |
| 185 | 新增: timeZone: zone, | |
| 186 | 新增: }).resolvedOptions().timeZone, | |
| 187 | 新增: language: navigator.language, | |
| 188 | 新增: platform: navigator.platform, | |
| 189 | 新增: }), | |
| 190 | 新增: timezone, | |
| 191 | 新增: ); | |
| 192 | 新增: } finally { | |
| 193 | 新增: await settingsPage.close(); | |
| 194 | 新增: page = previous; | |
| 195 | 新增: } | |
| 196 | 新增: if (!network) return settings; | |
| 197 | 新增: const owner = browser.browser(); | |
| 198 | 新增: if (!owner) throw new Error("无法创建独立的浏览器诊断会话"); | |
| 199 | 新增: const isolated = await owner.newContext({ serviceWorkers: "block" }); | |
| 200 | 新增: try { | |
| 201 | 新增: const test = await isolated.newPage(); | |
| 202 | 新增: await test.goto("http://198.18.0.254/", { | |
| 203 | 新增: waitUntil: "domcontentloaded", | |
| 204 | 新增: timeout: 12000, | |
| 205 | 新增: }); | |
| 206 | 新增: settings.network = await test.evaluate(async () => { | |
| 207 | 新增: if (location.origin !== "http://198.18.0.254") | |
| 208 | 新增: throw new Error("无效的诊断地址"); | |
| 209 | 新增: try { | |
| 210 | 新增: const r = await fetch("/egress", { | |
| 211 | 新增: cache: "no-store", | |
| 212 | 新增: credentials: "omit", | |
| 213 | 新增: signal: AbortSignal.timeout(14000), | |
| 214 | 新增: }); | |
| 215 | 新增: return { ...(await r.json()), status: r.status }; | |
| 216 | 新增: } catch { | |
| 217 | 新增: return { status: 0 }; | |
| 218 | 新增: } | |
| 219 | 新增: }); | |
| 220 | 新增: return settings; | |
| 221 | 新增: } finally { | |
| 222 | 新增: await isolated.close(); | |
| 223 | 新增: } | |
| 224 | 新增:} | |
| 225 | 新增: | |
| 226 | 新增:async function handle(a) { | |
| 227 | 新增: if (a.action === "audit") return audit(a.timezone, a.network); | |
| 228 | 新增: const p = await getPage(); | |
| 229 | 新增: switch (a.action) { | |
| 230 | 新增: case "frame": { | |
| 231 | 新增: const data = await p.screenshot({ | |
| 232 | 新增: type: "jpeg", | |
| 233 | 新增: quality: 70, | |
| 234 | 新增: timeout: 5000, | |
| 235 | 新增: }); | |
| 236 | 新增: return { | |
| 237 | 新增: image: data.toString("base64"), | |
| 238 | 新增: url: p.url(), | |
| 239 | 新增: title: await p.title(), | |
| 240 | 新增: width: p.viewportSize().width, | |
| 241 | 新增: height: p.viewportSize().height, | |
| 242 | 新增: }; | |
| 243 | 新增: } | |
| 244 | 新增: case "editor": | |
| 245 | 新增: await openEditor(a.folder); | |
| 246 | 新增: break; | |
| 247 | 新增: case "navigate": { | |
| 248 | 新增: const u = new URL(a.url); | |
| 249 | 新增: if (!["http:", "https:"].includes(u.protocol) || u.username || u.password) | |
| 250 | 新增: throw new Error("请输入 HTTP 或 HTTPS 地址"); | |
| 251 | 新增: await p.goto(u.href, { waitUntil: "commit", timeout: 8000 }); | |
| 252 | 新增: break; | |
| 253 | 新增: } | |
| 254 | 新增: case "click": | |
| 255 | 新增: await p.mouse.click(a.x, a.y, { clickCount: a.double ? 2 : 1 }); | |
| 256 | 新增: break; | |
| 257 | 新增: case "wheel": | |
| 258 | 新增: await p.mouse.move(a.x, a.y); | |
| 259 | 新增: await p.mouse.wheel(a.dx, a.dy); | |
| 260 | 新增: break; | |
| 261 | 新增: case "text": | |
| 262 | 新增: if (typeof a.text !== "string" || a.text.length > 4096) | |
| 263 | 新增: throw new Error("输入过长"); | |
| 264 | 新增: await p.keyboard.insertText(a.text); | |
| 265 | 新增: break; | |
| 266 | 新增: case "key": { | |
| 267 | 新增: if (!(keys.has(a.key) || /^[a-z0-9]$/i.test(a.key))) | |
| 268 | 新增: throw new Error("不支持此键"); | |
| 269 | 新增: await p.keyboard.press( | |
| 270 | 新增: [ | |
| 271 | 新增: a.meta && "Meta", | |
| 272 | 新增: a.ctrl && "Control", | |
| 273 | 新增: a.shift && "Shift", | |
| 274 | 新增: a.alt && "Alt", | |
| 275 | 新增: a.key, | |
| 276 | 新增: ] | |
| 277 | 新增: .filter(Boolean) | |
| 278 | 新增: .join("+"), | |
| 279 | 新增: ); | |
| 280 | 新增: break; | |
| 281 | 新增: } | |
| 282 | 新增: case "reload": | |
| 283 | 新增: await p.reload({ waitUntil: "commit" }); | |
| 284 | 新增: break; | |
| 285 | 新增: case "back": | |
| 286 | 新增: await p.goBack({ waitUntil: "commit" }); | |
| 287 | 新增: break; | |
| 288 | 新增: case "forward": | |
| 289 | 新增: await p.goForward({ waitUntil: "commit" }); | |
| 290 | 新增: break; | |
| 291 | 新增: default: | |
| 292 | 新增: throw new Error("未知的客机浏览器操作"); | |
| 293 | 新增: } | |
| 294 | 新增: return { ok: true }; | |
| 295 | 新增:} | |
| 296 | 新增:process.once("SIGHUP", () => { | |
| 297 | 新增: void close().finally(() => process.exit(0)); | |
| 298 | 新增:}); | |
| 299 | 新增:process.once("SIGTERM", () => { | |
| 300 | 新增: void close().finally(() => process.exit(0)); | |
| 301 | 新增:}); | |
| 302 | 新增:try { | |
| 303 | 新增: const lines = createInterface({ input: process.stdin, crlfDelay: Infinity }); | |
| 304 | 新增: for await (const line of lines) { | |
| 305 | 新增: let result; | |
| 306 | 新增: try { | |
| 307 | 新增: result = await handle(JSON.parse(line)); | |
| 308 | 新增: } catch (error) { | |
| 309 | 新增: result = { error: String(error.message).split("\n")[0].slice(0, 220) }; | |
| 310 | 新增: } | |
| 311 | 新增: if (!process.stdout.write(JSON.stringify(result) + "\n")) | |
| 312 | 新增: await once(process.stdout, "drain"); | |
| 313 | 新增: } | |
| 314 | 新增:} finally { | |
| 315 | 新增: await close(); | |
| 316 | 新增:} | |
| @@ -0,0 +1,169 @@ | ||
| 1 | 新增:// A geometry token describes only the signed Claude window actually captured. | |
| 2 | 新增:// All coordinates used for presentation and input are measured in guest points. | |
| 3 | 新增:import AppKit | |
| 4 | 新增:import ScreenCaptureKit | |
| 5 | 新增:import ImageIO | |
| 6 | 新增:import UniformTypeIdentifiers | |
| 7 | 新增: | |
| 8 | 新增:struct ClaudeCanvas { | |
| 9 | 新增: let id: CGWindowID | |
| 10 | 新增: let pid: pid_t | |
| 11 | 新增: let frame: CGRect | |
| 12 | 新增: let cropTop: CGFloat | |
| 13 | 新增: let scale: CGFloat | |
| 14 | 新增: let resizable: Bool | |
| 15 | 新增: var content: CGSize { CGSize(width: frame.width, height: frame.height - cropTop) } | |
| 16 | 新增: | |
| 17 | 新增: func matches(_ other: ClaudeCanvas) -> Bool { | |
| 18 | 新增: id == other.id && pid == other.pid && frame == other.frame && cropTop == other.cropTop && scale == other.scale | |
| 19 | 新增: } | |
| 20 | 新增:} | |
| 21 | 新增: | |
| 22 | 新增:private func axAttribute(_ element: AXUIElement, _ attribute: String) -> CFTypeRef? { | |
| 23 | 新增: var value: CFTypeRef? | |
| 24 | 新增: guard AXUIElementCopyAttributeValue(element, attribute as CFString, &value) == .success else { return nil } | |
| 25 | 新增: return value | |
| 26 | 新增:} | |
| 27 | 新增: | |
| 28 | 新增:private func axRect(_ element: AXUIElement) -> CGRect? { | |
| 29 | 新增: guard let p = axAttribute(element, kAXPositionAttribute), CFGetTypeID(p) == AXValueGetTypeID(), | |
| 30 | 新增: let s = axAttribute(element, kAXSizeAttribute), CFGetTypeID(s) == AXValueGetTypeID() else { return nil } | |
| 31 | 新增: var pos = CGPoint.zero, size = CGSize.zero | |
| 32 | 新增: guard AXValueGetValue(p as! AXValue, .cgPoint, &pos), AXValueGetValue(s as! AXValue, .cgSize, &size) else { return nil } | |
| 33 | 新增: return CGRect(origin: pos, size: size) | |
| 34 | 新增:} | |
| 35 | 新增: | |
| 36 | 新增:private func liveBounds(_ id: CGWindowID, _ pid: pid_t) throws -> CGRect { | |
| 37 | 新增: let windows = CGWindowListCopyWindowInfo(.optionIncludingWindow, id) as? [[String:Any]] | |
| 38 | 新增: guard let info = windows?.first, info[kCGWindowOwnerPID as String] as? Int32 == pid, | |
| 39 | 新增: info[kCGWindowIsOnscreen as String] as? Bool == true, | |
| 40 | 新增: let box = info[kCGWindowBounds as String] as? NSDictionary, | |
| 41 | 新增: let rect = CGRect(dictionaryRepresentation: box), !rect.isEmpty else { throw Failure(7, "window_changed") } | |
| 42 | 新增: return rect | |
| 43 | 新增:} | |
| 44 | 新增: | |
| 45 | 新增:private func owningAXWindow(_ pid: pid_t, _ frame: CGRect) -> AXUIElement? { | |
| 46 | 新增: guard AXIsProcessTrusted(), NSWorkspace.shared.frontmostApplication?.processIdentifier == pid, | |
| 47 | 新增: let raw = axAttribute(AXUIElementCreateApplication(pid), kAXFocusedWindowAttribute), | |
| 48 | 新增: CFGetTypeID(raw) == AXUIElementGetTypeID() else { return nil } | |
| 49 | 新增: let window = raw as! AXUIElement | |
| 50 | 新增: guard let actual = axRect(window), abs(actual.minX-frame.minX)<1, abs(actual.minY-frame.minY)<1, | |
| 51 | 新增: abs(actual.width-frame.width)<1, abs(actual.height-frame.height)<1 else { return nil } | |
| 52 | 新增: return window | |
| 53 | 新增:} | |
| 54 | 新增: | |
| 55 | 新增:private func canSet(_ window: AXUIElement, _ name: String) -> Bool { | |
| 56 | 新增: var result = DarwinBoolean(false) | |
| 57 | 新增: return AXUIElementIsAttributeSettable(window, name as CFString, &result) == .success && result.boolValue | |
| 58 | 新增:} | |
| 59 | 新增: | |
| 60 | 新增:private func titleBarHeight(_ window: AXUIElement, _ frame: CGRect) -> CGFloat { | |
| 61 | 新增: var bottom: CGFloat = 0 | |
| 62 | 新增: for name in [kAXCloseButtonAttribute, kAXMinimizeButtonAttribute, kAXZoomButtonAttribute] { | |
| 63 | 新增: guard let raw = axAttribute(window, name), CFGetTypeID(raw) == AXUIElementGetTypeID(), | |
| 64 | 新增: let button = axRect(raw as! AXUIElement), button.width > 2, button.height > 2, | |
| 65 | 新增: frame.contains(button), button.minX-frame.minX < 100, button.maxY-frame.minY < 70 else { continue } | |
| 66 | 新增: let margin = min(8, max(2, button.minY - frame.minY)) | |
| 67 | 新增: bottom = max(bottom, ceil(button.maxY - frame.minY + margin)) | |
| 68 | 新增: } | |
| 69 | 新增: return bottom < frame.height / 3 ? bottom : 0 | |
| 70 | 新增:} | |
| 71 | 新增: | |
| 72 | 新增:@MainActor | |
| 73 | 新增:final class ClaudeCanvasSession { | |
| 74 | 新增: static let shared = ClaudeCanvasSession() | |
| 75 | 新增: private var last: ClaudeCanvas? | |
| 76 | 新增: private var token = "" | |
| 77 | 新增: private var requested: (id: CGWindowID, pid: pid_t, size: CGSize, observed: CGSize, time: Date)? | |
| 78 | 新增: | |
| 79 | 新增: func layout(_ window: SCWindow, filter: SCContentFilter, width: Int, height: Int, scale: Double) async throws -> ClaudeCanvas { | |
| 80 | 新增: guard let pid = window.owningApplication?.processID, | |
| 81 | 新增: (320...2560).contains(width), (240...1600).contains(height), | |
| 82 | 新增: scale.isFinite, (1...2).contains(scale) else { throw Failure(8, "invalid_input") } | |
| 83 | 新增: var bounds = try liveBounds(window.windowID, pid) | |
| 84 | 新增: var crop: CGFloat = 0, resized = false | |
| 85 | 新增: if let ax = owningAXWindow(pid, bounds) { | |
| 86 | 新增: crop = titleBarHeight(ax, bounds) | |
| 87 | 新增: if canSet(ax, kAXSizeAttribute) { | |
| 88 | 新增: let display = CGDisplayBounds(CGMainDisplayID()) | |
| 89 | 新增: let wanted = CGSize(width: min(CGFloat(width), display.width), | |
| 90 | 新增: height: min(CGFloat(height) + crop, display.height)) | |
| 91 | 新增: let close = abs(bounds.width - wanted.width) < 2 && abs(bounds.height - wanted.height) < 2 | |
| 92 | 新增: let recent = requested.map { $0.id == window.windowID && $0.pid == pid && $0.size == wanted && | |
| 93 | 新增: $0.observed == bounds.size && Date().timeIntervalSince($0.time) < 3 } ?? false | |
| 94 | 新增: if !close && !recent { | |
| 95 | 新增: var size = wanted | |
| 96 | 新增: if let value = AXValueCreate(.cgSize, &size), | |
| 97 | 新增: AXUIElementSetAttributeValue(ax, kAXSizeAttribute as CFString, value) == .success { | |
| 98 | 新增: try await Task.sleep(nanoseconds: 70_000_000) | |
| 99 | 新增: bounds = try liveBounds(window.windowID, pid) | |
| 100 | 新增: // Position only an enlarged guest window that would extend off its display. | |
| 101 | 新增: var origin = CGPoint(x: max(display.minX, min(bounds.minX, display.maxX-bounds.width)), | |
| 102 | 新增: y: max(display.minY, min(bounds.minY, display.maxY-bounds.height))) | |
| 103 | 新增: if origin != bounds.origin, canSet(ax, kAXPositionAttribute), | |
| 104 | 新增: let point = AXValueCreate(.cgPoint, &origin) { | |
| 105 | 新增: _ = AXUIElementSetAttributeValue(ax, kAXPositionAttribute as CFString, point) | |
| 106 | 新增: bounds = try liveBounds(window.windowID, pid) | |
| 107 | 新增: } | |
| 108 | 新增: } | |
| 109 | 新增: requested = (window.windowID, pid, wanted, bounds.size, Date()) | |
| 110 | 新增: } | |
| 111 | 新增: resized = abs(bounds.width-wanted.width) < 2 && abs(bounds.height-wanted.height) < 2 | |
| 112 | 新增: crop = titleBarHeight(ax, bounds) | |
| 113 | 新增: } | |
| 114 | 新增: } | |
| 115 | 新增: return ClaudeCanvas(id: window.windowID, pid: pid, frame: bounds, cropTop: crop, | |
| 116 | 新增: scale: min(max(1,CGFloat(filter.pointPixelScale)), CGFloat(scale)), resizable: resized) | |
| 117 | 新增: } | |
| 118 | 新增: | |
| 119 | 新增: func record(_ value: ClaudeCanvas) -> String { | |
| 120 | 新增: if last?.matches(value) != true { token = UUID().uuidString; last = value } | |
| 121 | 新增: return token | |
| 122 | 新增: } | |
| 123 | 新增: | |
| 124 | 新增: func inputGeometry(_ requested: String, window: SCWindow) throws -> ClaudeCanvas { | |
| 125 | 新增: guard let last, token == requested, last.id == window.windowID, last.pid == window.owningApplication?.processID, | |
| 126 | 新增: try liveBounds(last.id, last.pid) == last.frame, | |
| 127 | 新增: let ax = owningAXWindow(last.pid, last.frame), titleBarHeight(ax,last.frame) == last.cropTop else { | |
| 128 | 新增: throw Failure(7, "window_changed") | |
| 129 | 新增: } | |
| 130 | 新增: return last | |
| 131 | 新增: } | |
| 132 | 新增: | |
| 133 | 新增: func capture(_ window: SCWindow, filter: SCContentFilter, layout: ClaudeCanvas, after: String? = nil, wait: Bool = false, binary: Bool = false, phoneJPEG: Bool = false) async throws -> [String:Any] { | |
| 134 | 新增: let config = SCStreamConfiguration() | |
| 135 | 新增: config.width = max(1, Int((layout.frame.width*layout.scale).rounded())) | |
| 136 | 新增: config.height = max(1, Int((layout.frame.height*layout.scale).rounded())) | |
| 137 | 新增: config.captureResolution = .best | |
| 138 | 新增: config.ignoreShadowsSingleWindow = true; config.showsCursor = false | |
| 139 | 新增: if #available(macOS 14.2, *) { config.includeChildWindows = false } | |
| 140 | 新增: let geometry = record(layout) | |
| 141 | 新增: let (updated, sequence) = try await MacWindowStream.shared.frame(filter: filter, configuration: config, identity: geometry, after: after, wait: wait) | |
| 142 | 新增: guard try liveBounds(layout.id, layout.pid) == layout.frame, | |
| 143 | 新增: try claudePIDs().contains(layout.pid) else { throw Failure(7, "window_changed") } | |
| 144 | 新增: guard let image = updated else { return ["unchanged": true, "sequence": sequence, "geometry": geometry] } | |
| 145 | 新增: let top = Int((layout.cropTop * CGFloat(image.height) / layout.frame.height).rounded()) | |
| 146 | 新增: guard top >= 0, top < image.height, | |
| 147 | 新增: let content = image.cropping(to: CGRect(x:0,y:top,width:image.width,height:image.height-top)), | |
| 148 | 新增: try liveBounds(layout.id, layout.pid) == layout.frame, | |
| 149 | 新增: try claudePIDs().contains(layout.pid) else { throw Failure(7, "window_changed") } | |
| 150 | 新增: var data = phoneJPEG ? try phoneDesktopJPEG(content) : try pngData(content) | |
| 151 | 新增: var mime = phoneJPEG ? "image/jpeg" : "image/png" | |
| 152 | 新增: if data.count >= 8<<20 { | |
| 153 | 新增: // Preserve native glyph density and geometry even on photo-heavy windows. | |
| 154 | 新增: mime = "image/jpeg" | |
| 155 | 新增: for quality in [0.93, 0.84] { | |
| 156 | 新增: data = try encodedImage(content, type:.jpeg, properties:[kCGImageDestinationLossyCompressionQuality: quality] as CFDictionary) | |
| 157 | 新增: if data.count < 8<<20 { break } | |
| 158 | 新增: } | |
| 159 | 新增: } | |
| 160 | 新增: guard data.count < 8<<20 else { throw Failure(8, "frame_limit") } | |
| 161 | 新增: var reply: [String:Any] = ["window":layout.id,"pid":layout.pid,"mime":mime,"sequence":sequence, | |
| 162 | 新增: "contentWidth":layout.content.width,"contentHeight":layout.content.height, | |
| 163 | 新增: "pixelWidth":content.width,"pixelHeight":content.height,"cropTop":layout.cropTop, | |
| 164 | 新增: "resizable":layout.resizable, "geometry":geometry] | |
| 165 | 新增: if binary { reply["imageBytes"] = data } | |
| 166 | 新增: else { reply["image"] = data.base64EncodedString() } | |
| 167 | 新增: return reply | |
| 168 | 新增: } | |
| 169 | 新增:} | |
| @@ -0,0 +1,486 @@ | ||
| 1 | 新增:// GUI LaunchAgent for the macOS guest. launchd owns one private per-user socket. | |
| 2 | 新增:import AppKit | |
| 3 | 新增:import ApplicationServices | |
| 4 | 新增:import ScreenCaptureKit | |
| 5 | 新增:import Security | |
| 6 | 新增: | |
| 7 | 新增:private let appURL = URL(fileURLWithPath: "/Applications/Claude.app") | |
| 8 | 新增:private let requirement = #"anchor apple generic and identifier "com.anthropic.claudefordesktop" and certificate leaf[subject.OU] = "Q6L2SF6YDW" and certificate 1[field.1.2.840.113635.100.6.2.6] exists and certificate leaf[field.1.2.840.113635.100.6.1.13] exists"# | |
| 9 | 新增: | |
| 10 | 新增:struct Request: Decodable { | |
| 11 | 新增: let action: String | |
| 12 | 新增: var window: UInt32? | |
| 13 | 新增: var pid: Int32? | |
| 14 | 新增: var x, y, delta: Double? | |
| 15 | 新增: var deltaX: Double? | |
| 16 | 新增: var key, text: String? | |
| 17 | 新增: var code, phase, mode, context, session: String? | |
| 18 | 新增: var down, control, alt: Bool? | |
| 19 | 新增: var button, buttons, clicks: Int? | |
| 20 | 新增: var shift, command: Bool? | |
| 21 | 新增: var project, nonce, geometry: String? | |
| 22 | 新增: var width, height: Int? | |
| 23 | 新增: var scale: Double? | |
| 24 | 新增: var after: String? | |
| 25 | 新增: var keepAlive: Bool? | |
| 26 | 新增: var refresh: Bool? | |
| 27 | 新增: var wait, binary: Bool? | |
| 28 | 新增: var id, kind: String? | |
| 29 | 新增: var transfer: String? | |
| 30 | 新增: var sequence: Int? | |
| 31 | 新增: var path: String? | |
| 32 | 新增: var error: String? | |
| 33 | 新增: var files: [String]? | |
| 34 | 新增: var length: Int? | |
| 35 | 新增: var phone: MacPhoneDesktopInput? | |
| 36 | 新增: var phone_token: String? | |
| 37 | 新增:} | |
| 38 | 新增: | |
| 39 | 新增:func consoleUser() throws { | |
| 40 | 新增: var info = stat() | |
| 41 | 新增: guard stat("/dev/console", &info) == 0, info.st_uid >= 500, info.st_uid == getuid(), | |
| 42 | 新增: (CGSessionCopyCurrentDictionary() as? [String:Any])?["CGSSessionScreenIsLocked"] as? Bool != true else { | |
| 43 | 新增: throw Failure(4, "requires_gui_login") | |
| 44 | 新增: } | |
| 45 | 新增:} | |
| 46 | 新增: | |
| 47 | 新增:private func verifiedInstall() throws { | |
| 48 | 新增: var rule: SecRequirement? | |
| 49 | 新增: var code: SecStaticCode? | |
| 50 | 新增: guard SecRequirementCreateWithString(requirement as CFString, [], &rule) == errSecSuccess, let rule, | |
| 51 | 新增: SecStaticCodeCreateWithPath(appURL as CFURL, [], &code) == errSecSuccess, let code, | |
| 52 | 新增: SecStaticCodeCheckValidity(code, [], rule) == errSecSuccess else { | |
| 53 | 新增: throw Failure(5, "identity_error") | |
| 54 | 新增: } | |
| 55 | 新增:} | |
| 56 | 新增: | |
| 57 | 新增:// The system picker can authorize a single window without persistent guest | |
| 58 | 新增:// screen-recording access. Never accept a display, another app, or a group. | |
| 59 | 新增:@available(macOS 15.2, *) | |
| 60 | 新增:@MainActor | |
| 61 | 新增:private final class ClaudePicker: NSObject, SCContentSharingPickerObserver { | |
| 62 | 新增: static let shared = ClaudePicker() | |
| 63 | 新增: private(set) var selection: SCContentFilter? | |
| 64 | 新增: func choose() { | |
| 65 | 新增: let picker = SCContentSharingPicker.shared | |
| 66 | 新增: picker.remove(self) | |
| 67 | 新增: picker.add(self) | |
| 68 | 新增: var config = SCContentSharingPickerConfiguration() | |
| 69 | 新增: config.allowedPickerModes = [.singleWindow] | |
| 70 | 新增: config.allowsChangingSelectedContent = false | |
| 71 | 新增: picker.defaultConfiguration = config | |
| 72 | 新增: picker.isActive = true | |
| 73 | 新增: picker.present(using: .window) | |
| 74 | 新增: } | |
| 75 | 新增: nonisolated func contentSharingPicker(_ picker: SCContentSharingPicker, didUpdateWith filter: SCContentFilter, for stream: SCStream?) { | |
| 76 | 新增: Task { @MainActor in | |
| 77 | 新增: let window = filter.includedWindows.first | |
| 78 | 新增: guard filter.style == .window, filter.includedWindows.count == 1, | |
| 79 | 新增: let owner = window?.owningApplication, | |
| 80 | 新增: owner.bundleIdentifier == "com.anthropic.claudefordesktop", | |
| 81 | 新增: (try? claudePIDs().contains(owner.processID)) == true else { self.selection = nil; return } | |
| 82 | 新增: self.selection = filter | |
| 83 | 新增: } | |
| 84 | 新增: } | |
| 85 | 新增: nonisolated func contentSharingPicker(_ picker: SCContentSharingPicker, didCancelFor stream: SCStream?) {} | |
| 86 | 新增: nonisolated func contentSharingPickerStartDidFailWithError(_ error: Error) {} | |
| 87 | 新增:} | |
| 88 | 新增: | |
| 89 | 新增:@MainActor | |
| 90 | 新增:func selectedWindow() async throws -> (SCWindow, SCContentFilter?) { | |
| 91 | 新增: if #available(macOS 15.2, *), let filter = ClaudePicker.shared.selection, let window = filter.includedWindows.first { | |
| 92 | 新增: let pids = try claudePIDs() | |
| 93 | 新增: guard let owner = window.owningApplication, pids.contains(owner.processID) else { throw Failure(7, "window_changed") } | |
| 94 | 新增: // Obtain current geometry by ID. This includes only window metadata. | |
| 95 | 新增: let list = CGWindowListCopyWindowInfo([.optionIncludingWindow], window.windowID) as? [[String:Any]] | |
| 96 | 新增: guard let exact = list?.first, exact[kCGWindowOwnerPID as String] as? Int32 == owner.processID, | |
| 97 | 新增: exact[kCGWindowIsOnscreen as String] as? Bool == true else { throw Failure(7, "window_changed") } | |
| 98 | 新增: return (window, filter) | |
| 99 | 新增: } | |
| 100 | 新增: return (try await claudeWindow(), nil) | |
| 101 | 新增:} | |
| 102 | 新增: | |
| 103 | 新增:@MainActor | |
| 104 | 新增:func sendInput(_ input: Request, window: SCWindow, canvas: ClaudeCanvas? = nil, maxTextBytes: Int = 8192, scrollX: Double = 0, maxScroll: Double = 1200, inputSession: MacWindowInputSession? = nil) throws { | |
| 105 | 新增: let target = try checkedMacInputWindow(input, window: window) | |
| 106 | 新增: try MacWindowInputSession.requirePointerOwner(inputSession) | |
| 107 | 新增: let focused = target.focused, pid = target.pid | |
| 108 | 新增: let origin = target.origin, extent = target.extent | |
| 109 | 新增: let source = CGEventSource(stateID: .privateState) | |
| 110 | 新增: func keyPair(_ key: CGKeyCode, flags: CGEventFlags = [], text: String? = nil) throws { | |
| 111 | 新增: for down in [true, false] { | |
| 112 | 新增: guard let event = CGEvent(keyboardEventSource: source, virtualKey: key, keyDown: down) else { throw Failure(8, "input_failed") } | |
| 113 | 新增: event.flags = flags | |
| 114 | 新增: if let text { | |
| 115 | 新增: let chars = Array(text.utf16) | |
| 116 | 新增: chars.withUnsafeBufferPointer { event.keyboardSetUnicodeString(stringLength: chars.count, unicodeString: $0.baseAddress) } | |
| 117 | 新增: } | |
| 118 | 新增: event.postToPid(pid) | |
| 119 | 新增: } | |
| 120 | 新增: } | |
| 121 | 新增: switch input.action { | |
| 122 | 新增: case "text": | |
| 123 | 新增: guard let text = input.text, !text.isEmpty, text.utf8.count <= maxTextBytes else { throw Failure(8, "invalid_input") } | |
| 124 | 新增: for character in text { try keyPair(0, text: String(character)) } | |
| 125 | 新增: case "key": | |
| 126 | 新增: if input.code != nil { | |
| 127 | 新增: guard let inputSession else { throw Failure(8, "input_connection_required") } | |
| 128 | 新增: try inputSession.key(input, target: target, window: window) | |
| 129 | 新增: return | |
| 130 | 新增: } | |
| 131 | 新增: let keys: [String: CGKeyCode] = ["Enter":36, "Tab":48, "Backspace":51, "Escape":53, "Delete":117, "ArrowLeft":123, "ArrowRight":124, "ArrowDown":125, "ArrowUp":126, "a":0, "z":6] | |
| 132 | 新增: guard let key = input.key, let code = keys[key], (input.command == true) == ["a", "z"].contains(key) else { throw Failure(8, "invalid_input") } | |
| 133 | 新增: var flags: CGEventFlags = [] | |
| 134 | 新增: if input.shift == true { flags.insert(.maskShift) } | |
| 135 | 新增: if input.command == true { flags.insert(.maskCommand) } | |
| 136 | 新增: try keyPair(code, flags: flags) | |
| 137 | 新增: case "pointer": | |
| 138 | 新增: guard let inputSession else { throw Failure(8, "input_connection_required") } | |
| 139 | 新增: try inputSession.pointer(input, target: target, window: window, canvas: canvas) | |
| 140 | 新增: case "click", "scroll", "project-click": | |
| 141 | 新增: guard let x = input.x, let y = input.y, (0..<1).contains(x), (0..<1).contains(y) else { throw Failure(8, "invalid_input") } | |
| 142 | 新增: let crop = canvas?.cropTop ?? 0 | |
| 143 | 新增: let point = CGPoint(x: origin.x + extent.width * x, y: origin.y + crop + (extent.height-crop) * y) | |
| 144 | 新增: if input.action == "project-click" { | |
| 145 | 新增: // NSOpenPanel's remote view returns the hosting AXWindow from | |
| 146 | 新增: // point queries. Hit-test only its actual approval button, using | |
| 147 | 新增: // its live accessibility bounds and the user's frame coordinates. | |
| 148 | 新增: var visited = 0 | |
| 149 | 新增: func attribute(_ node: AXUIElement, _ name: String) -> CFTypeRef? { | |
| 150 | 新增: var result: CFTypeRef? | |
| 151 | 新增: guard AXUIElementCopyAttributeValue(node, name as CFString, &result) == .success else { return nil } | |
| 152 | 新增: return result | |
| 153 | 新增: } | |
| 154 | 新增: func buttonAtPoint(_ node: AXUIElement, depth: Int) -> AXUIElement? { | |
| 155 | 新增: guard depth <= 14, visited < 2048 else { return nil } | |
| 156 | 新增: visited += 1 | |
| 157 | 新增: if attribute(node, kAXRoleAttribute) as? String == kAXButtonRole, | |
| 158 | 新增: attribute(node, kAXTitleAttribute) as? String == "Use Project", | |
| 159 | 新增: let pos = attribute(node, kAXPositionAttribute), CFGetTypeID(pos) == AXValueGetTypeID(), | |
| 160 | 新增: let dim = attribute(node, kAXSizeAttribute), CFGetTypeID(dim) == AXValueGetTypeID() { | |
| 161 | 新增: var p = CGPoint.zero, s = CGSize.zero | |
| 162 | 新增: if AXValueGetValue(pos as! AXValue, .cgPoint, &p), AXValueGetValue(dim as! AXValue, .cgSize, &s), | |
| 163 | 新增: CGRect(origin: p, size: s).contains(point) { return node } | |
| 164 | 新增: } | |
| 165 | 新增: for child in attribute(node, kAXChildrenAttribute) as? [AXUIElement] ?? [] { | |
| 166 | 新增: if let match = buttonAtPoint(child, depth: depth + 1) { return match } | |
| 167 | 新增: } | |
| 168 | 新增: return nil | |
| 169 | 新增: } | |
| 170 | 新增: guard let button = buttonAtPoint(focused, depth: 0), | |
| 171 | 新增: AXUIElementPerformAction(button, kAXPressAction as CFString) == .success else { | |
| 172 | 新增: throw Failure(8, "project_button_not_hit") | |
| 173 | 新增: } | |
| 174 | 新增: return | |
| 175 | 新增: } | |
| 176 | 新增: // An Electron NSView may ignore a CGEvent addressed to its process | |
| 177 | 新增: // while accepting the accessibility press on the hit control. Never | |
| 178 | 新增: // act on another window, a nearby control, or an arbitrary AX node. | |
| 179 | 新增: if input.action == "click", let button = macPressTarget(target, point: point) { | |
| 180 | 新增: guard AXUIElementPerformAction(button, kAXPressAction as CFString) == .success else { throw Failure(8, "input_failed") } | |
| 181 | 新增: return | |
| 182 | 新增: } | |
| 183 | 新增: let events: [CGEvent?] | |
| 184 | 新增: if input.action == "scroll" { | |
| 185 | 新增: let horizontal = input.deltaX ?? scrollX | |
| 186 | 新增: guard let delta = input.delta, delta.isFinite, horizontal.isFinite, | |
| 187 | 新增: (-maxScroll...maxScroll).contains(delta), (-maxScroll...maxScroll).contains(horizontal) else { throw Failure(8, "invalid_input") } | |
| 188 | 新增: events = [CGEvent(scrollWheelEvent2Source: source, units: .pixel, wheelCount: horizontal == 0 ? 1 : 2, wheel1: Int32(-delta), wheel2: Int32(-horizontal), wheel3: 0)] | |
| 189 | 新增: } else { | |
| 190 | 新增: // Address the NSEvent to this window using its unflipped local | |
| 191 | 新增: // coordinates. CGEvent's global position alone does not give an | |
| 192 | 新增: // Electron NSView a locationInWindow when posting to a process. | |
| 193 | 新增: let local = CGPoint(x: point.x-origin.x, y: extent.height-(point.y-origin.y)) | |
| 194 | 新增: let types: [NSEvent.EventType] = [.leftMouseDown, .leftMouseUp] | |
| 195 | 新增: events = types.map { type in | |
| 196 | 新增: NSEvent.mouseEvent(with: type, location: local, modifierFlags: [], | |
| 197 | 新增: timestamp: ProcessInfo.processInfo.systemUptime, windowNumber: Int(window.windowID), | |
| 198 | 新增: context: nil, eventNumber: 0, clickCount: 1, pressure: type == .leftMouseDown ? 1 : 0)?.cgEvent | |
| 199 | 新增: } | |
| 200 | 新增: } | |
| 201 | 新增: for item in events { | |
| 202 | 新增: guard let event = item else { throw Failure(8, "input_failed") } | |
| 203 | 新增: event.location = point | |
| 204 | 新增: event.setIntegerValueField(.mouseEventWindowUnderMousePointer, value: Int64(window.windowID)) | |
| 205 | 新增: event.setIntegerValueField(.mouseEventWindowUnderMousePointerThatCanHandleThisEvent, value: Int64(window.windowID)) | |
| 206 | 新增: event.setIntegerValueField(.mouseEventClickState, value: 1) | |
| 207 | 新增: event.postToPid(pid) | |
| 208 | 新增: } | |
| 209 | 新增: default: throw Failure(8, "invalid_input") | |
| 210 | 新增: } | |
| 211 | 新增:} | |
| 212 | 新增: | |
| 213 | 新增:@MainActor | |
| 214 | 新增:func launchClaudeWindow() async throws { | |
| 215 | 新增: try verifiedInstall() | |
| 216 | 新增: let configuration = NSWorkspace.OpenConfiguration() | |
| 217 | 新增: configuration.activates = true | |
| 218 | 新增: let application = try await NSWorkspace.shared.openApplication(at: appURL, configuration: configuration) | |
| 219 | 新增: if AXIsProcessTrusted(), try claudePIDs().contains(application.processIdentifier) { | |
| 220 | 新增: let element = AXUIElementCreateApplication(application.processIdentifier) | |
| 221 | 新增: _ = AXUIElementSetAttributeValue(element, "AXManualAccessibility" as CFString, kCFBooleanTrue) | |
| 222 | 新增: } | |
| 223 | 新增:} | |
| 224 | 新增: | |
| 225 | 新增:@MainActor | |
| 226 | 新增:private func handle(_ input: Request, inputSession: MacWindowInputSession) async throws -> [String: Any] { | |
| 227 | 新增: try requireGuest() | |
| 228 | 新增: if input.action.hasPrefix("phone-") { | |
| 229 | 新增: return try await MacPhoneDesktop.shared.handle(input) | |
| 230 | 新增: } | |
| 231 | 新增: try consoleUser() | |
| 232 | 新增: switch input.action { | |
| 233 | 新增: case "files-start": | |
| 234 | 新增: let (window, _) = try await selectedWindow() | |
| 235 | 新增: guard input.pid == window.owningApplication?.processID, input.window == window.windowID else { throw Failure(7, "window_changed") } | |
| 236 | 新增: return try MacDesktopFiles.shared.start(window: window, kind: input.kind ?? "") | |
| 237 | 新增: case "files-add": | |
| 238 | 新增: return try MacDesktopFiles.shared.add(input.id ?? "", files: input.files ?? []) | |
| 239 | 新增: case "files-validate": | |
| 240 | 新增: return try MacDesktopFiles.shared.validate(input.id ?? "") | |
| 241 | 新增: case "files-finish": | |
| 242 | 新增: return try await MacDesktopFiles.shared.finish(input.id ?? "") | |
| 243 | 新增: case "files-finish-image": | |
| 244 | 新增: return try await MacDesktopFiles.shared.finishImage(input.id ?? "") | |
| 245 | 新增: case "files-cancel": | |
| 246 | 新增: return await MacDesktopFiles.shared.cancel(input.id ?? "") | |
| 247 | 新增: case "files-poll": | |
| 248 | 新增: return try await MacDesktopFiles.shared.poll() | |
| 249 | 新增: case "files-download-open", "files-download-read", "files-download-close", "files-download-retry": | |
| 250 | 新增: return try MacDesktopDownloads.shared.read(input) | |
| 251 | 新增: case "files-open-claim", "files-open-complete": | |
| 252 | 新增: return try MacDesktopFiles.shared.openAction(input.id ?? "", complete: input.action == "files-open-complete") | |
| 253 | 新增: case "audio-status": | |
| 254 | 新增: return MacAudioCapture.status() | |
| 255 | 新增: case "setup-status": | |
| 256 | 新增: return ["screen": CGPreflightScreenCaptureAccess(), "input": AXIsProcessTrusted()] | |
| 257 | 新增: 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] | |
| 272 | 新增: case "setup-screen", "setup-input", "setup-projects": | |
| 273 | 新增: let pane: String | |
| 274 | 新增: if input.action == "setup-screen" { | |
| 275 | 新增: if !CGPreflightScreenCaptureAccess() { _ = CGRequestScreenCaptureAccess() } | |
| 276 | 新增: pane = "com.apple.preference.security?Privacy_ScreenCapture" | |
| 277 | 新增: } else if input.action == "setup-input" { | |
| 278 | 新增: let options = [kAXTrustedCheckOptionPrompt.takeUnretainedValue() as String: true] as CFDictionary | |
| 279 | 新增: _ = AXIsProcessTrustedWithOptions(options) | |
| 280 | 新增: pane = "com.apple.preference.security?Privacy_Accessibility" | |
| 281 | 新增: } else { | |
| 282 | 新增: let vendor = URL(fileURLWithPath: "/Applications/macFUSE.app") | |
| 283 | 新增: let configuration = NSWorkspace.OpenConfiguration() | |
| 284 | 新增: configuration.activates = false | |
| 285 | 新增: _ = try await NSWorkspace.shared.openApplication(at: vendor, configuration: configuration) | |
| 286 | 新增: pane = "com.apple.LoginItems-Settings.extension" | |
| 287 | 新增: } | |
| 288 | 新增: guard let url = URL(string: "x-apple.systempreferences:" + pane), NSWorkspace.shared.open(url) else { throw Failure(7, "settings_unavailable") } | |
| 289 | 新增: return ["ok":true] | |
| 290 | 新增: case "status": | |
| 291 | 新增: let installed = FileManager.default.fileExists(atPath: appURL.path) | |
| 292 | 新增: let running = ((try? claudePIDs())?.isEmpty == false) | |
| 293 | 新增: var screen = CGPreflightScreenCaptureAccess() | |
| 294 | 新增: if #available(macOS 15.2, *) { screen = screen || ClaudePicker.shared.selection != nil } | |
| 295 | 新增: return ["version": (Bundle(url: appURL)?.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String) ?? "", "installed": installed, "running": running, "screen": screen, "input": AXIsProcessTrusted(), "input_protocol": 1, "persistent": true, "push_frames": true] | |
| 296 | 新增: case "launch": | |
| 297 | 新增: try await launchClaudeWindow() | |
| 298 | 新增: return ["ok": true] | |
| 299 | 新增: case "stop": | |
| 300 | 新增: for pid in try claudePIDs() { | |
| 301 | 新增: guard let app = NSRunningApplication(processIdentifier: pid), app.terminate() else { throw Failure(7, "window_changed") } | |
| 302 | 新增: } | |
| 303 | 新增: return ["ok": true] | |
| 304 | 新增: case "request-screen": | |
| 305 | 新增: if #available(macOS 15.2, *) { ClaudePicker.shared.choose() } else { _ = CGRequestScreenCaptureAccess() } | |
| 306 | 新增: return ["screen": CGPreflightScreenCaptureAccess()] | |
| 307 | 新增: case "request-input": | |
| 308 | 新增: let options = [kAXTrustedCheckOptionPrompt.takeUnretainedValue() as String: true] as CFDictionary | |
| 309 | 新增: return ["input": AXIsProcessTrustedWithOptions(options)] | |
| 310 | 新增: case "frame": | |
| 311 | 新增: if input.wait != true && input.refresh != true && MacWindowStream.shared.unchanged(after: input.after) { | |
| 312 | 新增: return ["unchanged": true, "sequence": input.after!] | |
| 313 | 新增: } | |
| 314 | 新增: let (window, filter) = try await selectedWindow() | |
| 315 | 新增: if input.width != nil || input.height != nil || input.scale != nil { | |
| 316 | 新增: guard let width=input.width, let height=input.height, let scale=input.scale else { throw Failure(8,"invalid_input") } | |
| 317 | 新增: let capture = filter ?? SCContentFilter(desktopIndependentWindow: window) | |
| 318 | 新增: let canvas = ClaudeCanvasSession.shared | |
| 319 | 新增: let layout = try await canvas.layout(window, filter:capture, width:width, height:height, scale:scale) | |
| 320 | 新增: // A window object from before AX resizing still describes the old | |
| 321 | 新增: // surface. Reacquire that exact window before the first new frame. | |
| 322 | 新增: var target = window, source = capture | |
| 323 | 新增: if abs(window.frame.width - layout.frame.width) >= 1 || abs(window.frame.height - layout.frame.height) >= 1 { | |
| 324 | 新增: let (fresh, selection) = try await selectedWindow() | |
| 325 | 新增: guard fresh.windowID == layout.id, fresh.owningApplication?.processID == layout.pid else { | |
| 326 | 新增: throw Failure(7, "window_changed") | |
| 327 | 新增: } | |
| 328 | 新增: target = fresh | |
| 329 | 新增: source = selection ?? SCContentFilter(desktopIndependentWindow: fresh) | |
| 330 | 新增: } | |
| 331 | 新增: let reply = try await canvas.capture(target, filter:source, layout:layout, after:input.after, wait:input.wait == true, binary:input.binary == true) | |
| 332 | 新增: try consoleUser() | |
| 333 | 新增: return reply | |
| 334 | 新增: } | |
| 335 | 新增: let data = try await screenshot(window, filter: filter) | |
| 336 | 新增: guard data.count < 8 << 20, let owner = window.owningApplication, try claudePIDs().contains(owner.processID) else { | |
| 337 | 新增: throw Failure(7, "window_changed") | |
| 338 | 新增: } | |
| 339 | 新增: try consoleUser() | |
| 340 | 新增: return ["image": data.base64EncodedString(), "window": window.windowID, "pid": owner.processID] | |
| 341 | 新增: case "input-reset": | |
| 342 | 新增: inputSession.reset() | |
| 343 | 新增: return ["ok": true] | |
| 344 | 新增: case "ime": | |
| 345 | 新增: let (window, _) = try await selectedWindow() | |
| 346 | 新增: let canvas = try input.geometry.map { try ClaudeCanvasSession.shared.inputGeometry($0, window: window) } | |
| 347 | 新增: return try inputSession.ime(input, window: window, canvas: canvas) { value in | |
| 348 | 新增: if value.isEmpty { return } | |
| 349 | 新增: var text = Request(action: "text") | |
| 350 | 新增: text.pid = input.pid; text.window = input.window; text.geometry = input.geometry; text.text = value | |
| 351 | 新增: try sendInput(text, window: window, canvas: canvas, inputSession: inputSession) | |
| 352 | 新增: } | |
| 353 | 新增: case "text", "key", "click", "scroll", "pointer": | |
| 354 | 新增: let (window, _) = try await selectedWindow() | |
| 355 | 新增: let canvas = try input.geometry.map { try ClaudeCanvasSession.shared.inputGeometry($0, window:window) } | |
| 356 | 新增: try sendInput(input, window: window, canvas:canvas, inputSession: inputSession) | |
| 357 | 新增: return ["ok": true] | |
| 358 | 新增: case "project-frame", "project-click": | |
| 359 | 新增: guard let path = input.project else { throw Failure(7, "no_project_panel") } | |
| 360 | 新增: let panel = try pendingProjectPanel(path) | |
| 361 | 新增: let window = try await visibleProjectPanel(panel) | |
| 362 | 新增: if input.action == "project-click" { | |
| 363 | 新增: guard input.nonce == panel.nonce, try pendingProjectPanel(path) == panel else { throw Failure(7, "window_changed") } | |
| 364 | 新增: try sendInput(input, window: window) | |
| 365 | 新增: for _ in 0..<16 { | |
| 366 | 新增: try await Task.sleep(nanoseconds: 100_000_000) | |
| 367 | 新增: if (try? pendingProjectPanel(path)) != panel { return ["ok": true] } | |
| 368 | 新增: } | |
| 369 | 新增: throw Failure(8, "project_panel_still_open") | |
| 370 | 新增: } | |
| 371 | 新增: let data = try await screenshot(window) | |
| 372 | 新增: guard data.count < 8 << 20, try pendingProjectPanel(path) == panel else { throw Failure(7, "window_changed") } | |
| 373 | 新增: try consoleUser() | |
| 374 | 新增: return ["image": data.base64EncodedString(), "window": panel.windowNumber, "pid": panel.pid, "nonce": panel.nonce] | |
| 375 | 新增: default: throw Failure(8, "unknown_action") | |
| 376 | 新增: } | |
| 377 | 新增:} | |
| 378 | 新增: | |
| 379 | 新增:private func respond(_ fd: Int32) async { | |
| 380 | 新增: let inputSession = await MainActor.run { MacWindowInputSession() } | |
| 381 | 新增: await respondConnection(fd, inputSession: inputSession) | |
| 382 | 新增: await MainActor.run { inputSession.reset() } | |
| 383 | 新增:} | |
| 384 | 新增: | |
| 385 | 新增:private func respondConnection(_ fd: Int32, inputSession: MacWindowInputSession) async { | |
| 386 | 新增: let file = FileHandle(fileDescriptor: fd, closeOnDealloc: true) | |
| 387 | 新增: var timeout = timeval(tv_sec: 6, tv_usec: 0) | |
| 388 | 新增: setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, &timeout, socklen_t(MemoryLayout.size(ofValue: timeout))) | |
| 389 | 新增: setsockopt(fd, SOL_SOCKET, SO_SNDTIMEO, &timeout, socklen_t(MemoryLayout.size(ofValue: timeout))) | |
| 390 | 新增: var peer = uid_t(), group = gid_t() | |
| 391 | 新增: guard getpeereid(fd, &peer, &group) == 0, peer == getuid() else { return } | |
| 392 | 新增: var body = Data() | |
| 393 | 新增: do { | |
| 394 | 新增: repeat { | |
| 395 | 新增: while !body.contains(10) { | |
| 396 | 新增: var chunk = [UInt8](repeating: 0, count: (64 << 10) - body.count) | |
| 397 | 新增: let count = Darwin.read(fd, &chunk, chunk.count) | |
| 398 | 新增: if count < 0 && errno == EINTR { continue } | |
| 399 | 新增: guard count > 0 else { return } | |
| 400 | 新增: body.append(contentsOf: chunk.prefix(count)) | |
| 401 | 新增: guard body.count < (64 << 10) || body.contains(10) else { return } | |
| 402 | 新增: } | |
| 403 | 新增: let line = body.prefix(while: { $0 != 10 }) | |
| 404 | 新增: let request = try JSONDecoder().decode(Request.self, from: line) | |
| 405 | 新增: body.removeFirst(line.count + 1) | |
| 406 | 新增: if request.action == "audio-capture" { | |
| 407 | 新增: guard body.isEmpty else { return } | |
| 408 | 新增: await MacAudioCapture.respond(fd) | |
| 409 | 新增: return | |
| 410 | 新增: } | |
| 411 | 新增: var reply: [String:Any] | |
| 412 | 新增: do { | |
| 413 | 新增: if request.action == "paste-image" { | |
| 414 | 新增: guard let length = request.length, length > 0, length <= 20 * 1024 * 1024, body.count <= length else { throw Failure(8, "attachment_size_limit") } | |
| 415 | 新增: let (window, _) = try await selectedWindow() | |
| 416 | 新增: guard request.pid == window.owningApplication?.processID, request.window == window.windowID else { throw Failure(7, "window_changed") } | |
| 417 | 新增: var image = body | |
| 418 | 新增: body.removeAll() | |
| 419 | 新增: while image.count < length { | |
| 420 | 新增: guard let chunk = try file.read(upToCount: min(65536, length - image.count)), !chunk.isEmpty else { throw Failure(8, "attachment_incomplete") } | |
| 421 | 新增: image.append(chunk) | |
| 422 | 新增: } | |
| 423 | 新增: reply = try await MacDesktopFiles.shared.pasteImage(image, window: window) | |
| 424 | 新增: } else { reply = try await handle(request, inputSession: inputSession) } | |
| 425 | 新增: } | |
| 426 | 新增: catch { | |
| 427 | 新增: let reason = (error as? Failure)?.message.components(separatedBy: ":").first ?? "window_unavailable" | |
| 428 | 新增: GuestDiagnostic.record("window", reason) | |
| 429 | 新增: reply = ["error": reason] | |
| 430 | 新增: } | |
| 431 | 新增: if request.binary == true && request.action == "frame" { | |
| 432 | 新增: let pixels = reply.removeValue(forKey: "imageBytes") as? Data ?? Data() | |
| 433 | 新增: reply["imageLength"] = pixels.count | |
| 434 | 新增: let header = try JSONSerialization.data(withJSONObject: reply) | |
| 435 | 新增: var length = UInt32(header.count).bigEndian | |
| 436 | 新增: try file.write(contentsOf: withUnsafeBytes(of: &length) { Data($0) }) | |
| 437 | 新增: try file.write(contentsOf: header) | |
| 438 | 新增: try file.write(contentsOf: pixels) | |
| 439 | 新增: } else { | |
| 440 | 新增: var data = try JSONSerialization.data(withJSONObject: reply) | |
| 441 | 新增: data.append(10) | |
| 442 | 新增: try file.write(contentsOf: data) | |
| 443 | 新增: } | |
| 444 | 新增: if request.keepAlive != true { return } | |
| 445 | 新增: } while true | |
| 446 | 新增: } catch { | |
| 447 | 新增: let reason = (error as? Failure)?.message.components(separatedBy: ":").first ?? "window_unavailable" | |
| 448 | 新增: GuestDiagnostic.record("window", reason) | |
| 449 | 新增: if let data = try? JSONSerialization.data(withJSONObject: ["error": reason]) { try? file.write(contentsOf: data) } | |
| 450 | 新增: } | |
| 451 | 新增:} | |
| 452 | 新增: | |
| 453 | 新增:@main | |
| 454 | 新增:struct ClaudeWindowService { | |
| 455 | 新增: static func main() { | |
| 456 | 新增: if CommandLine.arguments.dropFirst() == ["--phone-self-test"] { | |
| 457 | 新增: do { try MacPhoneDesktop.selfTest(); return } | |
| 458 | 新增: catch { fputs("macOS phone desktop self-test failed\n", stderr); exit(1) } | |
| 459 | 新增: } | |
| 460 | 新增: if CommandLine.arguments.dropFirst() == ["--audio-self-test"] { | |
| 461 | 新增: do { try MacAudioCapture.selfTest(); return } | |
| 462 | 新增: catch { fputs("macOS audio self-test failed\n", stderr); exit(1) } | |
| 463 | 新增: } | |
| 464 | 新增: guard (try? requireGuest()) != nil, (try? consoleUser()) != nil else { exit(2) } | |
| 465 | 新增: _ = signal(SIGPIPE, SIG_IGN) | |
| 466 | 新增: let storage = UnsafeMutablePointer<UnsafeMutablePointer<Int32>>.allocate(capacity: 1) | |
| 467 | 新增: var count: Int = 0 | |
| 468 | 新增: guard launch_activate_socket("Window", storage, &count) == 0, count == 1 else { exit(3) } | |
| 469 | 新增: let sockets = storage.pointee | |
| 470 | 新增: storage.deallocate() | |
| 471 | 新增: let listener = sockets[0] | |
| 472 | 新增: free(sockets) | |
| 473 | 新增: GuestDiagnostic.record("window", "started") | |
| 474 | 新增: NSApplication.shared.setActivationPolicy(.accessory) | |
| 475 | 新增: DispatchQueue.global(qos: .userInitiated).async { | |
| 476 | 新增: let connections = DispatchSemaphore(value: 16) | |
| 477 | 新增: while true { | |
| 478 | 新增: connections.wait() | |
| 479 | 新增: let fd = accept(listener, nil, nil) | |
| 480 | 新增: if fd < 0 { connections.signal(); if errno == EINTR { continue }; exit(4) } | |
| 481 | 新增: Task { await respond(fd); connections.signal() } | |
| 482 | 新增: } | |
| 483 | 新增: } | |
| 484 | 新增: NSApplication.shared.run() | |
| 485 | 新增: } | |
| 486 | 新增:} | |
| @@ -0,0 +1,47 @@ | ||
| 1 | 新增:// Carries only Claude login links between processes owned by the ordinary guest user. | |
| 2 | 新增:import net from "node:net"; | |
| 3 | 新增:import fs from "node:fs/promises"; | |
| 4 | 新增:import path from "node:path"; | |
| 5 | 新增: | |
| 6 | 新增:export async function installMacOSCLIBrowser(data, dispatch) { | |
| 7 | 新增: const directory = path.join(data, "Login"); | |
| 8 | 新增: await fs.mkdir(directory, { mode: 0o700, recursive: true }); | |
| 9 | 新增: const dir = await fs.lstat(directory); | |
| 10 | 新增: if (!dir.isDirectory() || dir.uid !== process.getuid() || (dir.mode & 0o077)) throw new Error("Invalid login directory"); | |
| 11 | 新增: const address = path.join(directory, "open.sock"); | |
| 12 | 新增: const serve = net.createServer({ allowHalfOpen: true }, socket => { | |
| 13 | 新增: let input = "", size = 0; | |
| 14 | 新增: socket.setTimeout(15000, () => socket.destroy()); | |
| 15 | 新增: socket.on("error", () => {}); | |
| 16 | 新增: socket.setEncoding("utf8"); | |
| 17 | 新增: socket.on("data", chunk => { | |
| 18 | 新增: size += Buffer.byteLength(chunk); | |
| 19 | 新增: if (size > 12288) socket.destroy(); | |
| 20 | 新增: else input += chunk; | |
| 21 | 新增: }); | |
| 22 | 新增: socket.on("end", async () => { | |
| 23 | 新增: try { | |
| 24 | 新增: const { action, login, url } = JSON.parse(input); | |
| 25 | 新增: if (!["login-open", "login-finish"].includes(action) || !/^[0-9a-f]{24}$/.test(login)) throw new Error(); | |
| 26 | 新增: const result = await dispatch({ method: "POST", path: "/" + action, input: { login, url } }); | |
| 27 | 新增: socket.end(result?.error ? "ERR" : "OK"); | |
| 28 | 新增: } catch { socket.end("ERR"); } | |
| 29 | 新增: }); | |
| 30 | 新增: }); | |
| 31 | 新增: // Publish a fresh socket after its permissions are set. A replaced process | |
| 32 | 新增: // retains its own inode and cannot remove its successor's socket on exit. | |
| 33 | 新增: const temporary = path.join(directory, ".open-" + process.pid); | |
| 34 | 新增: await new Promise((resolve, reject) => { serve.once("error", reject); serve.listen(temporary, resolve); }); | |
| 35 | 新增: try { | |
| 36 | 新增: await fs.chmod(temporary, 0o600); | |
| 37 | 新增: const old = await fs.lstat(address).catch(e => { if (e.code !== "ENOENT") throw e; }); | |
| 38 | 新增: if (old && (!old.isSocket() || old.uid !== dir.uid)) throw new Error("Invalid login socket"); | |
| 39 | 新增: await fs.rename(temporary, address); | |
| 40 | 新增: } catch (error) { serve.close(); throw error; } | |
| 41 | 新增: const { ino } = await fs.lstat(address); | |
| 42 | 新增: return async () => { | |
| 43 | 新增: await new Promise(resolve => serve.close(resolve)); | |
| 44 | 新增: const current = await fs.lstat(address).catch(() => null); | |
| 45 | 新增: if (current?.ino === ino) await fs.unlink(address); | |
| 46 | 新增: }; | |
| 47 | 新增:} | |
| @@ -0,0 +1,55 @@ | ||
| 1 | 新增:"""Run the common Claude session protocol in the ordinary macOS guest account.""" | |
| 2 | 新增:import importlib.util | |
| 3 | 新增:import json | |
| 4 | 新增:import os | |
| 5 | 新增:from pathlib import Path | |
| 6 | 新增:import re | |
| 7 | 新增:import sys | |
| 8 | 新增: | |
| 9 | 新增: | |
| 10 | 新增:source = Path(__file__).resolve().with_name("cli_channel.py") | |
| 11 | 新增:spec = importlib.util.spec_from_file_location("cli_channel", source) | |
| 12 | 新增:cli_channel = importlib.util.module_from_spec(spec) | |
| 13 | 新增:spec.loader.exec_module(cli_channel) | |
| 14 | 新增:os.environ["PATH"] = "/usr/local/libexec/cage-cli/bin:/usr/local/bin:" + os.environ.get("PATH", os.defpath) | |
| 15 | 新增: | |
| 16 | 新增: | |
| 17 | 新增:def macos_launch(request): | |
| 18 | 新增: prefix = request["prefix"] | |
| 19 | 新增: managed = (len(prefix) == 5 and prefix[0] == "env" and re.fullmatch(r"CAGE_CLAUDE_SUBJECT=[a-f0-9]{64}", prefix[1]) | |
| 20 | 新增: and prefix[2:4] == ["/usr/local/bin/cage-claude-account", "run"] | |
| 21 | 新增: and (prefix[4] == "default" or re.fullmatch("[a-f0-9]{24}", prefix[4]))) | |
| 22 | 新增: ccs = len(prefix) == 2 and prefix[0] == "ccs" and re.fullmatch("[a-zA-Z0-9][a-zA-Z0-9_-]{0,63}", prefix[1]) | |
| 23 | 新增: if prefix != ["claude"] and not managed and not ccs: | |
| 24 | 新增: raise ValueError("不支持的客机 Claude 启动命令") | |
| 25 | 新增: # Adopt a nested transcript only inside the same approved mount, without | |
| 26 | 新增: # traversing symbolic links or interpreting a saved path in a shell. | |
| 27 | 新增: subdir = request.get("project_subdir") | |
| 28 | 新增: if subdir: | |
| 29 | 新增: directory = os.open(".", os.O_RDONLY | os.O_DIRECTORY) | |
| 30 | 新增: try: | |
| 31 | 新增: device = os.fstat(directory).st_dev | |
| 32 | 新增: for part in subdir.split("/"): | |
| 33 | 新增: if part in ("", ".", ".."): | |
| 34 | 新增: raise ValueError("会话目录无效") | |
| 35 | 新增: child = os.open(part, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW, dir_fd=directory) | |
| 36 | 新增: os.close(directory) | |
| 37 | 新增: directory = child | |
| 38 | 新增: if os.fstat(directory).st_dev != device: | |
| 39 | 新增: raise ValueError("会话目录不属于当前挂载") | |
| 40 | 新增: os.fchdir(directory) | |
| 41 | 新增: finally: | |
| 42 | 新增: os.close(directory) | |
| 43 | 新增: return cli_channel.launch(request) | |
| 44 | 新增: | |
| 45 | 新增: | |
| 46 | 新增:if __name__ == "__main__": | |
| 47 | 新增: if sys.argv[1] == "macos-launch": | |
| 48 | 新增: # An ordinary CLI exit leaves an interactive guest shell in this | |
| 49 | 新增: # project. Pass the launch JSON as a literal positional argument. | |
| 50 | 新增: script = '"$1" -I "$2" macos-exec "$3"; exec /bin/zsh -i' | |
| 51 | 新增: os.execv("/bin/zsh", ["zsh", "-c", script, "cage-claude", sys.executable, str(Path(__file__).resolve()), sys.argv[2]]) | |
| 52 | 新增: if sys.argv[1] == "macos-exec": | |
| 53 | 新增: os.umask(0o077) | |
| 54 | 新增: sys.exit(macos_launch(json.loads(sys.argv[2])) or 0) | |
| 55 | 新增: sys.exit(cli_channel.main() or 0) | |
| @@ -0,0 +1,256 @@ | ||
| 1 | 新增:import AppKit | |
| 2 | 新增:import CoreServices | |
| 3 | 新增: | |
| 4 | 新增:@_silgen_name("cage_file_has_writer") private func cageFileHasWriter(_ pid: Int32, _ path: UnsafePointer<CChar>) -> Int32 | |
| 5 | 新增: | |
| 6 | 新增:@MainActor | |
| 7 | 新增:final class MacDesktopDownloads { | |
| 8 | 新增: static let shared = MacDesktopDownloads(directory: FileManager.default.homeDirectoryForCurrentUser.appendingPathComponent("Library/Application Support/dev.cage.DesktopDownloads", isDirectory: true)) | |
| 9 | 新增: private struct Record: Codable { | |
| 10 | 新增: let id: String | |
| 11 | 新增: let name: String | |
| 12 | 新增: var state = "downloading" | |
| 13 | 新增: var error = "" | |
| 14 | 新增: var size: Int64 = 0 | |
| 15 | 新增: var modified: Int64 = 0 | |
| 16 | 新增: var started = Date() | |
| 17 | 新增: } | |
| 18 | 新增: private struct Transfer { | |
| 19 | 新增: let fd: Int32 | |
| 20 | 新增: let record: Record | |
| 21 | 新增: let epoch: UInt64 | |
| 22 | 新增: var sequence = 0 | |
| 23 | 新增: var offset: Int64 = 0 | |
| 24 | 新增: var used = Date() | |
| 25 | 新增: } | |
| 26 | 新增: private var records: [Record] = [] | |
| 27 | 新增: private var transfers: [String: Transfer] = [:] | |
| 28 | 新增: private var watches: [String: MacDownloadWatch] = [:] | |
| 29 | 新增: private var root: URL? | |
| 30 | 新增: private let baseDirectory: URL | |
| 31 | 新增: private var transferTimer: Timer? | |
| 32 | 新增: private let timestamp = ISO8601DateFormatter() | |
| 33 | 新增: | |
| 34 | 新增: init(directory: URL) { baseDirectory = directory } | |
| 35 | 新增: deinit { | |
| 36 | 新增: for watch in watches.values { watch.stop() } | |
| 37 | 新增: for transfer in transfers.values { close(transfer.fd) } | |
| 38 | 新增: transferTimer?.invalidate() | |
| 39 | 新增: } | |
| 40 | 新增: | |
| 41 | 新增: nonisolated static func validName(_ name: String) -> Bool { | |
| 42 | 新增: !name.isEmpty && name.utf8.count <= 255 && name != "." && name != ".." && | |
| 43 | 新增: name.rangeOfCharacter(from: CharacterSet(charactersIn: "/\\").union(.controlCharacters)) == nil | |
| 44 | 新增: } | |
| 45 | 新增: | |
| 46 | 新增: private func directory() throws -> URL { | |
| 47 | 新增: if let root { return root } | |
| 48 | 新增: try FileManager.default.createDirectory(at: baseDirectory, withIntermediateDirectories: true, attributes: [.posixPermissions: 0o700]) | |
| 49 | 新增: var info = stat() | |
| 50 | 新增: guard lstat(baseDirectory.path, &info) == 0, info.st_mode & S_IFMT == S_IFDIR, info.st_uid == getuid(), | |
| 51 | 新增: info.st_mode & 0o022 == 0, let canonical = realpath(baseDirectory.path, nil) else { throw Failure(8, "desktop_download_directory_invalid") } | |
| 52 | 新增: let root = URL(fileURLWithPath: String(cString: canonical), isDirectory: true) | |
| 53 | 新增: free(canonical) | |
| 54 | 新增: let manifest = root.appendingPathComponent("downloads.json") | |
| 55 | 新增: if FileManager.default.fileExists(atPath: manifest.path) { | |
| 56 | 新增: var stored = stat() | |
| 57 | 新增: guard lstat(manifest.path, &stored) == 0, stored.st_mode & S_IFMT == S_IFREG, stored.st_uid == getuid(), stored.st_size <= 1 << 20 else { | |
| 58 | 新增: throw Failure(8, "desktop_download_catalog_invalid") | |
| 59 | 新增: } | |
| 60 | 新增: let data = try Data(contentsOf: manifest, options: .mappedIfSafe) | |
| 61 | 新增: 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) } | |
| 63 | 新增: for index in records.indices where records[index].state == "downloading" { | |
| 64 | 新增: records[index].state = "failed" | |
| 65 | 新增: records[index].error = "保存过程被中断,请从 Claude Desktop 重新下载。" | |
| 66 | 新增: } | |
| 67 | 新增: } | |
| 68 | 新增: self.root = root | |
| 69 | 新增: return root | |
| 70 | 新增: } | |
| 71 | 新增: private func source(_ record: Record) throws -> URL { try directory().appendingPathComponent(record.id, isDirectory: true).appendingPathComponent(record.name) } | |
| 72 | 新增: private func persist() throws { | |
| 73 | 新增: let path = try directory().appendingPathComponent("downloads.json") | |
| 74 | 新增: try JSONEncoder().encode(Array(records.suffix(100))).write(to: path, options: .atomic) | |
| 75 | 新增: try FileManager.default.setAttributes([.posixPermissions: 0o600], ofItemAtPath: path.path) | |
| 76 | 新增: } | |
| 77 | 新增: private func openSource(_ record: Record) throws -> (Int32, stat) { | |
| 78 | 新增: let path = try source(record).path | |
| 79 | 新增: let fd = open(path, O_RDONLY | O_NOFOLLOW | O_NONBLOCK) | |
| 80 | 新增: guard fd >= 0 else { throw Failure(8, "desktop_download_unavailable") } | |
| 81 | 新增: var info = stat(), actual = [CChar](repeating: 0, count: Int(MAXPATHLEN)) | |
| 82 | 新增: guard fstat(fd, &info) == 0, info.st_mode & S_IFMT == S_IFREG, info.st_uid == getuid(), info.st_size <= 2 * 1024 * 1024 * 1024, | |
| 83 | 新增: fcntl(fd, F_GETPATH, &actual) == 0, String(cString: actual) == path else { | |
| 84 | 新增: close(fd); throw Failure(8, "desktop_download_file_invalid") | |
| 85 | 新增: } | |
| 86 | 新增: return (fd, info) | |
| 87 | 新增: } | |
| 88 | 新增: private func modified(_ info: stat) -> Int64 { Int64(info.st_mtimespec.tv_sec) * 1_000_000_000 + Int64(info.st_mtimespec.tv_nsec) } | |
| 89 | 新增: | |
| 90 | 新增: private func expireTransfers() { | |
| 91 | 新增: let epoch = try? MacGUISession.shared.validate() | |
| 92 | 新增: for (key, transfer) in transfers where epoch != transfer.epoch || Date().timeIntervalSince(transfer.used) > 120 { | |
| 93 | 新增: close(transfer.fd); transfers.removeValue(forKey: key) | |
| 94 | 新增: } | |
| 95 | 新增: if transfers.isEmpty { transferTimer?.invalidate(); transferTimer = nil } | |
| 96 | 新增: } | |
| 97 | 新增: | |
| 98 | 新增: func reserve(name: String, pid: Int32, submit: (String) async throws -> Void) async throws { | |
| 99 | 新增: _ = try directory() | |
| 100 | 新增: guard Self.validName(name), records.filter({ $0.state == "downloading" }).count < 12 else { throw Failure(8, "desktop_download_limit") } | |
| 101 | 新增: let record = Record(id: UUID().uuidString.lowercased(), name: name) | |
| 102 | 新增: let path = try source(record) | |
| 103 | 新增: try FileManager.default.createDirectory(at: path.deletingLastPathComponent(), withIntermediateDirectories: false, attributes: [.posixPermissions: 0o700]) | |
| 104 | 新增: let watcher = try MacDownloadWatch(directory: path.deletingLastPathComponent().path, file: path.path) { [weak self] valid in | |
| 105 | 新增: Task { @MainActor in | |
| 106 | 新增: if valid { await self?.complete(record.id, pid: pid) } | |
| 107 | 新增: else { self?.fail(record.id, message: "保存通知已中断,请从 Claude Desktop 重新下载。") } | |
| 108 | 新增: } | |
| 109 | 新增: } | |
| 110 | 新增: while records.count >= 100, let oldest = records.firstIndex(where: { $0.state != "downloading" }) { records.remove(at: oldest) } | |
| 111 | 新增: records.append(record); watches[record.id] = watcher | |
| 112 | 新增: do { try persist(); try await submit(path.path) } | |
| 113 | 新增: catch { fail(record.id, message: "客机保存窗口未接收文件位置,请重新下载。"); throw error } | |
| 114 | 新增: watcher.expiry = Task { @MainActor [weak self] in | |
| 115 | 新增: try? await Task.sleep(nanoseconds: 1800 * 1_000_000_000) | |
| 116 | 新增: if self?.records.first(where: { $0.id == record.id })?.state == "downloading" { | |
| 117 | 新增: self?.fail(record.id, message: "未能确认文件保存完成,请从 Claude Desktop 重新下载。") | |
| 118 | 新增: } | |
| 119 | 新增: } | |
| 120 | 新增: } | |
| 121 | 新增: private func fail(_ id: String, message: String) { | |
| 122 | 新增: watches.removeValue(forKey: id)?.stop() | |
| 123 | 新增: if let index = records.firstIndex(where: { $0.id == id }) { | |
| 124 | 新增: records[index].state = "failed"; records[index].error = message | |
| 125 | 新增: try? persist() | |
| 126 | 新增: } | |
| 127 | 新增: } | |
| 128 | 新增: private func complete(_ id: String, pid: Int32) async { | |
| 129 | 新增: guard let record = records.first(where: { $0.id == id && $0.state == "downloading" }), | |
| 130 | 新增: let watch = watches[id], !watch.completing else { return } | |
| 131 | 新增: watch.completing = true | |
| 132 | 新增: defer { watch.completing = false } | |
| 133 | 新增: while Date().timeIntervalSince(record.started) < 1800 { | |
| 134 | 新增: guard records.first(where: { $0.id == id })?.state == "downloading" else { return } | |
| 135 | 新增: do { | |
| 136 | 新增: let path = try source(record).path | |
| 137 | 新增: let writing = path.withCString { cageFileHasWriter(pid, $0) } | |
| 138 | 新增: if writing == 0 && !FileManager.default.fileExists(atPath: path + ".crdownload") { | |
| 139 | 新增: let (fd, info) = try openSource(record) | |
| 140 | 新增: defer { close(fd) } | |
| 141 | 新增: guard let index = records.firstIndex(where: { $0.id == id }) else { return } | |
| 142 | 新增: records[index].size = info.st_size; records[index].modified = modified(info); records[index].state = "saved" | |
| 143 | 新增: try persist(); watches.removeValue(forKey: id)?.stop(); return | |
| 144 | 新增: } | |
| 145 | 新增: } catch { } | |
| 146 | 新增: try? await Task.sleep(nanoseconds: 250_000_000) | |
| 147 | 新增: } | |
| 148 | 新增: fail(id, message: "未能确认文件保存完成,请从 Claude Desktop 重新下载。") | |
| 149 | 新增: } | |
| 150 | 新增: func snapshot() throws -> [[String: Any]] { | |
| 151 | 新增: _ = try directory() | |
| 152 | 新增: return records.suffix(100).reversed().map { record in | |
| 153 | 新增: ["id": record.id, "name": record.name, "target": "desktop", "state": record.state, | |
| 154 | 新增: "receivedBytes": record.size, "totalBytes": record.size, "retryable": false, | |
| 155 | 新增: "error": record.error, "startedAt": timestamp.string(from: record.started)] | |
| 156 | 新增: } | |
| 157 | 新增: } | |
| 158 | 新增: func find(path: String) throws -> (id: String, directory: Bool)? { | |
| 159 | 新增: _ = try directory() | |
| 160 | 新增: for record in records { | |
| 161 | 新增: let source = try source(record) | |
| 162 | 新增: if source.path == path { return (record.id, false) } | |
| 163 | 新增: if source.deletingLastPathComponent().path == path { return (record.id, true) } | |
| 164 | 新增: } | |
| 165 | 新增: return nil | |
| 166 | 新增: } | |
| 167 | 新增: func read(_ input: Request) throws -> [String: Any] { | |
| 168 | 新增: let epoch = try MacGUISession.shared.validate() | |
| 169 | 新增: _ = try directory() | |
| 170 | 新增: for (key, transfer) in transfers where transfer.epoch != epoch || Date().timeIntervalSince(transfer.used) > 120 { | |
| 171 | 新增: close(transfer.fd); transfers.removeValue(forKey: key) | |
| 172 | 新增: } | |
| 173 | 新增: if input.action == "files-download-retry" { | |
| 174 | 新增: guard let record = records.first(where: { $0.id == input.id }), record.state == "saved" else { throw Failure(8, "desktop_download_incomplete") } | |
| 175 | 新增: let (fd, info) = try openSource(record) | |
| 176 | 新增: defer { close(fd) } | |
| 177 | 新增: guard info.st_size == record.size, modified(info) == record.modified else { throw Failure(8, "desktop_download_changed") } | |
| 178 | 新增: return ["ok": true] | |
| 179 | 新增: } | |
| 180 | 新增: if input.action == "files-download-open" { | |
| 181 | 新增: guard let record = records.first(where: { $0.id == input.id && $0.state == "saved" }), transfers.count < 12 else { throw Failure(8, "desktop_download_unavailable") } | |
| 182 | 新增: let (fd, info) = try openSource(record) | |
| 183 | 新增: guard info.st_size == record.size, modified(info) == record.modified else { close(fd); throw Failure(8, "desktop_download_changed") } | |
| 184 | 新增: let key = UUID().uuidString.replacingOccurrences(of: "-", with: "").lowercased() | |
| 185 | 新增: transfers[key] = Transfer(fd: fd, record: record, epoch: epoch) | |
| 186 | 新增: if transferTimer == nil { | |
| 187 | 新增: transferTimer = Timer.scheduledTimer(withTimeInterval: 2, repeats: true) { [weak self] timer in | |
| 188 | 新增: Task { @MainActor in | |
| 189 | 新增: guard let self else { timer.invalidate(); return } | |
| 190 | 新增: self.expireTransfers() | |
| 191 | 新增: } | |
| 192 | 新增: } | |
| 193 | 新增: } | |
| 194 | 新增: return ["transfer": key, "size": record.size, "name": record.name] | |
| 195 | 新增: } | |
| 196 | 新增: let key = input.transfer ?? "" | |
| 197 | 新增: if input.action == "files-download-close" { | |
| 198 | 新增: if let transfer = transfers.removeValue(forKey: key) { close(transfer.fd) } | |
| 199 | 新增: return ["ok": true] | |
| 200 | 新增: } | |
| 201 | 新增: guard input.action == "files-download-read", var transfer = transfers[key], transfer.sequence == input.sequence else { throw Failure(8, "desktop_download_transfer_invalid") } | |
| 202 | 新增: var info = stat() | |
| 203 | 新增: guard fstat(transfer.fd, &info) == 0, info.st_size == transfer.record.size, modified(info) == transfer.record.modified else { | |
| 204 | 新增: close(transfer.fd); transfers.removeValue(forKey: key); throw Failure(8, "desktop_download_changed") | |
| 205 | 新增: } | |
| 206 | 新增: var data = Data(count: 64 << 10) | |
| 207 | 新增: let count = data.withUnsafeMutableBytes { Darwin.read(transfer.fd, $0.baseAddress, $0.count) } | |
| 208 | 新增: guard count >= 0 else { throw Failure(8, "desktop_download_read_failed") } | |
| 209 | 新增: guard fstat(transfer.fd, &info) == 0, info.st_size == transfer.record.size, modified(info) == transfer.record.modified else { | |
| 210 | 新增: close(transfer.fd); transfers.removeValue(forKey: key); throw Failure(8, "desktop_download_changed") | |
| 211 | 新增: } | |
| 212 | 新增: data.count = count; transfer.offset += Int64(count); transfer.sequence += 1; transfer.used = Date() | |
| 213 | 新增: let eof = transfer.offset == transfer.record.size | |
| 214 | 新增: if eof { close(transfer.fd); transfers.removeValue(forKey: key) } else { transfers[key] = transfer } | |
| 215 | 新增: return ["data": data.base64EncodedString(), "sequence": transfer.sequence, "eof": eof] | |
| 216 | 新增: } | |
| 217 | 新增:} | |
| 218 | 新增: | |
| 219 | 新增:private final class MacDownloadWatch { | |
| 220 | 新增: private var stream: FSEventStreamRef? | |
| 221 | 新增: private let file: String | |
| 222 | 新增: private let changed: (Bool) -> Void | |
| 223 | 新增: var completing = false | |
| 224 | 新增: var expiry: Task<Void, Never>? | |
| 225 | 新增: init(directory: String, file: String, changed: @escaping (Bool) -> Void) throws { | |
| 226 | 新增: self.file = file; self.changed = changed | |
| 227 | 新增: var context = FSEventStreamContext(version: 0, info: Unmanaged.passUnretained(self).toOpaque(), retain: { raw in | |
| 228 | 新增: guard let raw else { return nil } | |
| 229 | 新增: _ = Unmanaged<MacDownloadWatch>.fromOpaque(raw).retain() | |
| 230 | 新增: return raw | |
| 231 | 新增: }, release: { raw in | |
| 232 | 新增: if let raw { Unmanaged<MacDownloadWatch>.fromOpaque(raw).release() } | |
| 233 | 新增: }, copyDescription: nil) | |
| 234 | 新增: stream = FSEventStreamCreate(nil, { _, raw, count, paths, flags, _ in | |
| 235 | 新增: guard let raw else { return } | |
| 236 | 新增: let watcher = Unmanaged<MacDownloadWatch>.fromOpaque(raw).takeUnretainedValue() | |
| 237 | 新增: let names = Unmanaged<NSArray>.fromOpaque(paths).takeUnretainedValue() as? [String] ?? [] | |
| 238 | 新增: let failure = FSEventStreamEventFlags(kFSEventStreamEventFlagMustScanSubDirs | kFSEventStreamEventFlagUserDropped | kFSEventStreamEventFlagKernelDropped | kFSEventStreamEventFlagRootChanged) | |
| 239 | 新增: for index in 0..<count where flags[index] & failure != 0 { watcher.changed(false); return } | |
| 240 | 新增: for index in 0..<min(count, names.count) where names[index] == watcher.file { | |
| 241 | 新增: if flags[index] & FSEventStreamEventFlags(kFSEventStreamEventFlagItemModified | kFSEventStreamEventFlagItemRenamed) != 0 { watcher.changed(true) } | |
| 242 | 新增: } | |
| 243 | 新增: }, &context, [directory] as CFArray, FSEventStreamEventId(kFSEventStreamEventIdSinceNow), 0.1, | |
| 244 | 新增: FSEventStreamCreateFlags(kFSEventStreamCreateFlagUseCFTypes | kFSEventStreamCreateFlagFileEvents | kFSEventStreamCreateFlagNoDefer | kFSEventStreamCreateFlagWatchRoot)) | |
| 245 | 新增: guard let stream else { throw Failure(8, "desktop_download_watch_failed") } | |
| 246 | 新增: FSEventStreamSetDispatchQueue(stream, DispatchQueue.main) | |
| 247 | 新增: guard FSEventStreamStart(stream) else { stop(); throw Failure(8, "desktop_download_watch_failed") } | |
| 248 | 新增: } | |
| 249 | 新增: func stop() { | |
| 250 | 新增: expiry?.cancel(); expiry = nil | |
| 251 | 新增: guard let stream else { return } | |
| 252 | 新增: self.stream = nil | |
| 253 | 新增: FSEventStreamStop(stream); FSEventStreamInvalidate(stream); FSEventStreamRelease(stream) | |
| 254 | 新增: } | |
| 255 | 新增: deinit { stop() } | |
| 256 | 新增:} | |
| @@ -0,0 +1,557 @@ | ||
| 1 | 新增:// Attachments are bound to one verified Claude window and private guest caches. | |
| 2 | 新增:import AppKit | |
| 3 | 新增:import ScreenCaptureKit | |
| 4 | 新增: | |
| 5 | 新增:private func fileAttribute(_ element: AXUIElement, _ name: String) -> CFTypeRef? { | |
| 6 | 新增: var value: CFTypeRef? | |
| 7 | 新增: return AXUIElementCopyAttributeValue(element, name as CFString, &value) == .success ? value : nil | |
| 8 | 新增:} | |
| 9 | 新增: | |
| 10 | 新增:private func fileChildren(_ element: AXUIElement) -> [AXUIElement] { | |
| 11 | 新增: (fileAttribute(element, kAXChildrenAttribute) as? [AXUIElement] ?? []) + | |
| 12 | 新增: (fileAttribute(element, "AXSheets") as? [AXUIElement] ?? []) | |
| 13 | 新增:} | |
| 14 | 新增: | |
| 15 | 新增:private func filePanelButton(_ panel: AXUIElement, cancel: Bool = false) -> AXUIElement? { | |
| 16 | 新增: if let value = fileAttribute(panel, cancel ? kAXCancelButtonAttribute : kAXDefaultButtonAttribute), CFGetTypeID(value) == AXUIElementGetTypeID() { | |
| 17 | 新增: return (value as! AXUIElement) | |
| 18 | 新增: } | |
| 19 | 新增: var pending = fileChildren(panel), visited = 0 | |
| 20 | 新增: while visited < pending.count && visited < 1024 { | |
| 21 | 新增: let element = pending[visited]; visited += 1 | |
| 22 | 新增: if fileAttribute(element, kAXRoleAttribute) as? String == kAXButtonRole, | |
| 23 | 新增: fileAttribute(element, "AXIdentifier") as? String == (cancel ? "CancelButton" : "OKButton") { return element } | |
| 24 | 新增: pending.append(contentsOf: fileChildren(element)) | |
| 25 | 新增: } | |
| 26 | 新增: return nil | |
| 27 | 新增:} | |
| 28 | 新增: | |
| 29 | 新增:private func filePanelPresent(_ panel: AXUIElement, pid: pid_t) -> Bool { | |
| 30 | 新增: var pending = fileAttribute(AXUIElementCreateApplication(pid), kAXWindowsAttribute) as? [AXUIElement] ?? [], visited = 0 | |
| 31 | 新增: while visited < pending.count && visited < 1024 { | |
| 32 | 新增: let element = pending[visited]; visited += 1 | |
| 33 | 新增: if CFEqual(element, panel) { return true } | |
| 34 | 新增: pending.append(contentsOf: fileChildren(element)) | |
| 35 | 新增: } | |
| 36 | 新增: return false | |
| 37 | 新增:} | |
| 38 | 新增: | |
| 39 | 新增:private func filePanelFocused(_ panel: AXUIElement, pid: pid_t) -> Bool { | |
| 40 | 新增: var current = fileAttribute(AXUIElementCreateApplication(pid), kAXFocusedUIElementAttribute) | |
| 41 | 新增: for _ in 0..<32 { | |
| 42 | 新增: guard let value = current, CFGetTypeID(value) == AXUIElementGetTypeID() else { return false } | |
| 43 | 新增: let element = value as! AXUIElement | |
| 44 | 新增: if CFEqual(element, panel) { return true } | |
| 45 | 新增: current = fileAttribute(element, kAXParentAttribute) | |
| 46 | 新增: } | |
| 47 | 新增: return false | |
| 48 | 新增:} | |
| 49 | 新增: | |
| 50 | 新增:private func containsFileBrowser(_ element: AXUIElement) -> Bool { | |
| 51 | 新增: var pending = fileChildren(element) | |
| 52 | 新增: var visited = 0 | |
| 53 | 新增: while !pending.isEmpty && visited < 1024 { | |
| 54 | 新增: let child = pending.removeLast() | |
| 55 | 新增: visited += 1 | |
| 56 | 新增: if [kAXOutlineRole, kAXBrowserRole, kAXTableRole].contains(fileAttribute(child, kAXRoleAttribute) as? String ?? "") { return true } | |
| 57 | 新增: pending.append(contentsOf: fileChildren(child)) | |
| 58 | 新增: } | |
| 59 | 新增: return false | |
| 60 | 新增:} | |
| 61 | 新增: | |
| 62 | 新增:private func selectedFilePaths(_ panel: AXUIElement, expected: Set<String>) -> Set<String> { | |
| 63 | 新增: var pending = [panel], selected: [AXUIElement] = [] | |
| 64 | 新增: var visited = 0 | |
| 65 | 新增: while !pending.isEmpty && visited < 2048 { | |
| 66 | 新增: let element = pending.removeLast() | |
| 67 | 新增: visited += 1 | |
| 68 | 新增: selected.append(contentsOf: fileAttribute(element, kAXSelectedRowsAttribute) as? [AXUIElement] ?? []) | |
| 69 | 新增: selected.append(contentsOf: fileAttribute(element, kAXSelectedChildrenAttribute) as? [AXUIElement] ?? []) | |
| 70 | 新增: pending.append(contentsOf: fileChildren(element)) | |
| 71 | 新增: } | |
| 72 | 新增: var paths = Set<String>() | |
| 73 | 新增: func selectedPath(_ value: String) { | |
| 74 | 新增: let path: String | |
| 75 | 新增: if let canonical = realpath(value, nil) { | |
| 76 | 新增: path = String(cString: canonical); free(canonical) | |
| 77 | 新增: } else { path = URL(fileURLWithPath: value).standardizedFileURL.path } | |
| 78 | 新增: let prefix = path.hasSuffix("/") ? path : path + "/" | |
| 79 | 新增: // Column view also selects each ancestor directory. Every other | |
| 80 | 新增: // selected file must participate in the exact selection comparison. | |
| 81 | 新增: if expected.contains(where: { $0.hasPrefix(prefix) }) { return } | |
| 82 | 新增: paths.insert(path) | |
| 83 | 新增: } | |
| 84 | 新增: visited = 0 | |
| 85 | 新增: while !selected.isEmpty && visited < 4096 { | |
| 86 | 新增: let element = selected.removeLast() | |
| 87 | 新增: visited += 1 | |
| 88 | 新增: for attribute in [kAXURLAttribute, kAXValueAttribute] { | |
| 89 | 新增: let raw = fileAttribute(element, attribute) | |
| 90 | 新增: if let url = raw as? URL, url.isFileURL { selectedPath(url.path) } | |
| 91 | 新增: if let value = raw as? String { | |
| 92 | 新增: if value.hasPrefix("/") { selectedPath(value) } | |
| 93 | 新增: if let url = URL(string: value), url.isFileURL { selectedPath(url.path) } | |
| 94 | 新增: } | |
| 95 | 新增: } | |
| 96 | 新增: selected.append(contentsOf: fileChildren(element)) | |
| 97 | 新增: } | |
| 98 | 新增: return paths | |
| 99 | 新增:} | |
| 100 | 新增: | |
| 101 | 新增:private func openFilePanel(_ pid: pid_t) -> AXUIElement? { | |
| 102 | 新增: var pending = fileAttribute(AXUIElementCreateApplication(pid), kAXWindowsAttribute) as? [AXUIElement] ?? [] | |
| 103 | 新增: var visited = 0 | |
| 104 | 新增: while !pending.isEmpty && visited < 2048 { | |
| 105 | 新增: let element = pending.removeLast() | |
| 106 | 新增: visited += 1 | |
| 107 | 新增: let role = fileAttribute(element, kAXRoleAttribute) as? String | |
| 108 | 新增: let subrole = fileAttribute(element, kAXSubroleAttribute) as? String | |
| 109 | 新增: if role == kAXSheetRole || subrole == kAXDialogSubrole, | |
| 110 | 新增: let button = filePanelButton(element), filePanelButton(element, cancel: true) != nil, | |
| 111 | 新增: let title = fileAttribute(button, kAXTitleAttribute) as? String, | |
| 112 | 新增: ["Open", "Choose", "Select", "打开", "開啟", "选择", "選擇"].contains(title), containsFileBrowser(element) { | |
| 113 | 新增: return element | |
| 114 | 新增: } | |
| 115 | 新增: pending.append(contentsOf: fileChildren(element)) | |
| 116 | 新增: } | |
| 117 | 新增: return nil | |
| 118 | 新增:} | |
| 119 | 新增: | |
| 120 | 新增:private func saveFilePanel(_ pid: pid_t) -> (AXUIElement, AXUIElement)? { | |
| 121 | 新增: var pending = fileAttribute(AXUIElementCreateApplication(pid), kAXWindowsAttribute) as? [AXUIElement] ?? [] | |
| 122 | 新增: var visited = 0 | |
| 123 | 新增: while !pending.isEmpty && visited < 2048 { | |
| 124 | 新增: let panel = pending.removeLast() | |
| 125 | 新增: visited += 1 | |
| 126 | 新增: let role = fileAttribute(panel, kAXRoleAttribute) as? String | |
| 127 | 新增: let subrole = fileAttribute(panel, kAXSubroleAttribute) as? String | |
| 128 | 新增: if (role == kAXSheetRole || subrole == kAXDialogSubrole), | |
| 129 | 新增: let button = filePanelButton(panel), | |
| 130 | 新增: let title = fileAttribute(button, kAXTitleAttribute) as? String, | |
| 131 | 新增: ["Save", "保存", "儲存", "Enregistrer", "Sichern", "Guardar", "Сохранить", "저장"].contains(title), | |
| 132 | 新增: filePanelButton(panel, cancel: true) != nil { | |
| 133 | 新增: var children = fileChildren(panel), count = 0 | |
| 134 | 新增: while count < children.count && count < 1024 { | |
| 135 | 新增: let element = children[count] | |
| 136 | 新增: count += 1 | |
| 137 | 新增: if fileAttribute(element, kAXRoleAttribute) as? String == kAXTextFieldRole, | |
| 138 | 新增: fileAttribute(element, "AXIdentifier") as? String == "saveAsNameTextField", | |
| 139 | 新增: let name = fileAttribute(element, kAXValueAttribute) as? String, MacDesktopDownloads.validName(name) { | |
| 140 | 新增: return (panel, element) | |
| 141 | 新增: } | |
| 142 | 新增: children.append(contentsOf: fileChildren(element)) | |
| 143 | 新增: } | |
| 144 | 新增: } | |
| 145 | 新增: pending.append(contentsOf: fileChildren(panel)) | |
| 146 | 新增: } | |
| 147 | 新增: return nil | |
| 148 | 新增:} | |
| 149 | 新增: | |
| 150 | 新增:private func clipboardRequest(_ request: [String: Any]) async throws -> [String: Any] { | |
| 151 | 新增: let data = try JSONSerialization.data(withJSONObject: request) + Data([10]) | |
| 152 | 新增: guard data.count <= 30 * 1024 * 1024 else { throw Failure(8, "attachment_size_limit") } | |
| 153 | 新增: return try await withCheckedThrowingContinuation { continuation in | |
| 154 | 新增: DispatchQueue.global(qos: .userInitiated).async { | |
| 155 | 新增: let process = Process() | |
| 156 | 新增: process.executableURL = URL(fileURLWithPath: "/Applications/Cage Guest Clipboard.app/Contents/MacOS/CageGuestClipboard") | |
| 157 | 新增: process.arguments = ["--client", "request"] | |
| 158 | 新增: let input = Pipe(), output = Pipe() | |
| 159 | 新增: process.standardInput = input | |
| 160 | 新增: process.standardOutput = output | |
| 161 | 新增: process.standardError = FileHandle.nullDevice | |
| 162 | 新增: let timeout = DispatchWorkItem { if process.isRunning { process.terminate() } } | |
| 163 | 新增: defer { timeout.cancel(); try? input.fileHandleForWriting.close(); if process.isRunning { process.terminate() } } | |
| 164 | 新增: do { | |
| 165 | 新增: try process.run() | |
| 166 | 新增: DispatchQueue.global().asyncAfter(deadline: .now() + 15, execute: timeout) | |
| 167 | 新增: try input.fileHandleForWriting.write(contentsOf: data) | |
| 168 | 新增: try input.fileHandleForWriting.close() | |
| 169 | 新增: var reply = Data() | |
| 170 | 新增: while let chunk = try output.fileHandleForReading.read(upToCount: 4096), !chunk.isEmpty { | |
| 171 | 新增: reply.append(chunk) | |
| 172 | 新增: guard reply.count <= 65536 else { throw Failure(7, "clipboard_reply_invalid") } | |
| 173 | 新增: } | |
| 174 | 新增: process.waitUntilExit() | |
| 175 | 新增: guard process.terminationStatus == 0, | |
| 176 | 新增: let value = try JSONSerialization.jsonObject(with: reply) as? [String: Any], value["error"] == nil else { | |
| 177 | 新增: throw Failure(7, "clipboard_operation_failed") | |
| 178 | 新增: } | |
| 179 | 新增: continuation.resume(returning: value) | |
| 180 | 新增: } catch { continuation.resume(throwing: error) } | |
| 181 | 新增: } | |
| 182 | 新增: } | |
| 183 | 新增:} | |
| 184 | 新增: | |
| 185 | 新增:@MainActor | |
| 186 | 新增:final class MacDesktopFiles { | |
| 187 | 新增: static let shared = MacDesktopFiles() | |
| 188 | 新增: private final class Batch { | |
| 189 | 新增: let pid: pid_t | |
| 190 | 新增: let window: CGWindowID | |
| 191 | 新增: let kind: String | |
| 192 | 新增: let panel: AXUIElement? | |
| 193 | 新增: let focusedWindow: AXUIElement? | |
| 194 | 新增: let focusedElement: AXUIElement? | |
| 195 | 新增: let epoch: UInt64 | |
| 196 | 新增: let created = Date() | |
| 197 | 新增: var files: [String] = [] | |
| 198 | 新增: var busy = false | |
| 199 | 新增: init(pid: pid_t, window: CGWindowID, kind: String, epoch: UInt64, panel: AXUIElement? = nil) { | |
| 200 | 新增: self.pid = pid; self.window = window; self.kind = kind; self.panel = panel | |
| 201 | 新增: self.epoch = epoch | |
| 202 | 新增: if let value = fileAttribute(AXUIElementCreateApplication(pid), kAXFocusedWindowAttribute), CFGetTypeID(value) == AXUIElementGetTypeID() { | |
| 203 | 新增: focusedWindow = (value as! AXUIElement) | |
| 204 | 新增: } else { focusedWindow = nil } | |
| 205 | 新增: if let value = fileAttribute(AXUIElementCreateApplication(pid), kAXFocusedUIElementAttribute), CFGetTypeID(value) == AXUIElementGetTypeID() { | |
| 206 | 新增: focusedElement = (value as! AXUIElement) | |
| 207 | 新增: } else { focusedElement = nil } | |
| 208 | 新增: } | |
| 209 | 新增: } | |
| 210 | 新增: private var batches: [String: Batch] = [:] | |
| 211 | 新增: private var savingPanel: AXUIElement? | |
| 212 | 新增: private struct OpenRequest { | |
| 213 | 新增: let path: String | |
| 214 | 新增: let action: String | |
| 215 | 新增: let epoch: UInt64 | |
| 216 | 新增: let validate: () throws -> Void | |
| 217 | 新增: let created = Date() | |
| 218 | 新增: var claimed = false | |
| 219 | 新增: } | |
| 220 | 新增: private var opens: [String: OpenRequest] = [:] | |
| 221 | 新增: | |
| 222 | 新增: private func expireOpens() { | |
| 223 | 新增: let epoch = try? MacGUISession.shared.validate() | |
| 224 | 新增: opens = opens.filter { _, request in | |
| 225 | 新增: epoch == request.epoch && Date().timeIntervalSince(request.created) < (request.claimed ? 1800 : 60) | |
| 226 | 新增: } | |
| 227 | 新增: } | |
| 228 | 新增: | |
| 229 | 新增: func queueOpen(path: String, action: String, validate: @escaping () throws -> Void) throws { | |
| 230 | 新增: try queueOpen(paths: [path], action: action, validate: validate) | |
| 231 | 新增: } | |
| 232 | 新增: | |
| 233 | 新增: func queueOpen(paths: [String], action: String, validate: @escaping () throws -> Void) throws { | |
| 234 | 新增: guard !paths.isEmpty, paths.count <= 32, paths.allSatisfy({ ($0 as NSString).isAbsolutePath && $0.utf8.count <= 32768 && !$0.contains("\0") }), | |
| 235 | 新增: ["open", "reveal"].contains(action) else { throw Failure(8, "file_open_request_invalid") } | |
| 236 | 新增: let epoch = try MacGUISession.shared.validate() | |
| 237 | 新增: expireOpens(); try validate() | |
| 238 | 新增: guard opens.count + paths.count <= 32 else { throw Failure(8, "file_open_request_limit") } | |
| 239 | 新增: for path in paths { | |
| 240 | 新增: opens[UUID().uuidString.lowercased()] = OpenRequest(path: URL(fileURLWithPath: path).standardizedFileURL.path, action: action, epoch: epoch, validate: validate) | |
| 241 | 新增: } | |
| 242 | 新增: } | |
| 243 | 新增: | |
| 244 | 新增: func openSnapshot() -> [[String: String]] { | |
| 245 | 新增: expireOpens() | |
| 246 | 新增: return opens.filter { !$0.value.claimed }.map { ["id": $0.key] } | |
| 247 | 新增: } | |
| 248 | 新增: | |
| 249 | 新增: func openAction(_ id: String, complete: Bool) throws -> [String: Any] { | |
| 250 | 新增: expireOpens() | |
| 251 | 新增: guard var request = opens[id] else { return [complete ? "ok" : "handled": true] } | |
| 252 | 新增: if complete { | |
| 253 | 新增: opens.removeValue(forKey: id) | |
| 254 | 新增: try? request.validate() | |
| 255 | 新增: return ["ok": true] | |
| 256 | 新增: } | |
| 257 | 新增: if request.claimed { return ["handled": true] } | |
| 258 | 新增: do { try request.validate() } | |
| 259 | 新增: catch { opens.removeValue(forKey: id); throw Failure(7, "file_open_target_changed") } | |
| 260 | 新增: var result: [String: Any] = ["id": id, "action": request.action] | |
| 261 | 新增: if let download = try MacDesktopDownloads.shared.find(path: request.path) { | |
| 262 | 新增: result["download_id"] = download.id; result["directory"] = download.directory | |
| 263 | 新增: } else { result["path"] = request.path } | |
| 264 | 新增: request.claimed = true; opens[id] = request | |
| 265 | 新增: return result | |
| 266 | 新增: } | |
| 267 | 新增: | |
| 268 | 新增: private func valid(_ batch: Batch) throws { | |
| 269 | 新增: try consoleUser() | |
| 270 | 新增: try MacGUISession.shared.validate(batch.epoch) | |
| 271 | 新增: guard AXIsProcessTrusted() else { throw Failure(9, "accessibility_permission") } | |
| 272 | 新增: guard Date().timeIntervalSince(batch.created) < 1800, try claudePIDs().contains(batch.pid), | |
| 273 | 新增: NSWorkspace.shared.frontmostApplication?.processIdentifier == batch.pid else { throw Failure(7, "window_changed") } | |
| 274 | 新增: if let panel = batch.panel { | |
| 275 | 新增: guard filePanelPresent(panel, pid: batch.pid), filePanelFocused(panel, pid: batch.pid) else { throw Failure(7, "file_dialog_changed") } | |
| 276 | 新增: } else { | |
| 277 | 新增: let windows = CGWindowListCopyWindowInfo([.optionIncludingWindow], batch.window) as? [[String: Any]] | |
| 278 | 新增: guard let window = windows?.first, window[kCGWindowOwnerPID as String] as? Int32 == batch.pid, | |
| 279 | 新增: window[kCGWindowIsOnscreen as String] as? Bool == true else { throw Failure(7, "window_changed") } | |
| 280 | 新增: guard let focused = fileAttribute(AXUIElementCreateApplication(batch.pid), kAXFocusedWindowAttribute), | |
| 281 | 新增: let original = batch.focusedWindow, CFEqual(focused, original), | |
| 282 | 新增: let input = fileAttribute(AXUIElementCreateApplication(batch.pid), kAXFocusedUIElementAttribute), | |
| 283 | 新增: let originalInput = batch.focusedElement, CFEqual(input, originalInput), | |
| 284 | 新增: let position = fileAttribute(original, kAXPositionAttribute), CFGetTypeID(position) == AXValueGetTypeID(), | |
| 285 | 新增: let size = fileAttribute(original, kAXSizeAttribute), CFGetTypeID(size) == AXValueGetTypeID(), | |
| 286 | 新增: let bounds = window[kCGWindowBounds as String] as? [String: Any], | |
| 287 | 新增: let frame = CGRect(dictionaryRepresentation: bounds as CFDictionary) else { throw Failure(7, "window_changed") } | |
| 288 | 新增: var origin = CGPoint.zero, extent = CGSize.zero | |
| 289 | 新增: guard AXValueGetValue(position as! AXValue, .cgPoint, &origin), AXValueGetValue(size as! AXValue, .cgSize, &extent), | |
| 290 | 新增: abs(origin.x - frame.minX) < 2, abs(origin.y - frame.minY) < 2, | |
| 291 | 新增: abs(extent.width - frame.width) < 2, abs(extent.height - frame.height) < 2 else { throw Failure(7, "window_changed") } | |
| 292 | 新增: } | |
| 293 | 新增: } | |
| 294 | 新增: | |
| 295 | 新增: private func batch(_ id: String) throws -> Batch { | |
| 296 | 新增: guard UUID(uuidString: id) != nil, let value = batches[id] else { throw Failure(8, "attachment_request_invalid") } | |
| 297 | 新增: try valid(value) | |
| 298 | 新增: return value | |
| 299 | 新增: } | |
| 300 | 新增: | |
| 301 | 新增: private func key(_ pid: pid_t, _ code: CGKeyCode, flags: CGEventFlags = [], panel: AXUIElement? = nil, epoch: UInt64? = nil) throws { | |
| 302 | 新增: guard AXIsProcessTrusted(), try claudePIDs().contains(pid), NSWorkspace.shared.frontmostApplication?.processIdentifier == pid else { | |
| 303 | 新增: throw Failure(7, "window_changed") | |
| 304 | 新增: } | |
| 305 | 新增: let source = CGEventSource(stateID: .privateState) | |
| 306 | 新增: for down in [true, false] { | |
| 307 | 新增: try consoleUser() | |
| 308 | 新增: try MacGUISession.shared.validate(epoch) | |
| 309 | 新增: guard NSWorkspace.shared.frontmostApplication?.processIdentifier == pid, | |
| 310 | 新增: panel.map({ filePanelPresent($0, pid: pid) && filePanelFocused($0, pid: pid) }) ?? true else { throw Failure(7, "file_dialog_changed") } | |
| 311 | 新增: guard let event = CGEvent(keyboardEventSource: source, virtualKey: code, keyDown: down) else { throw Failure(8, "input_failed") } | |
| 312 | 新增: event.flags = flags | |
| 313 | 新增: if panel != nil { | |
| 314 | 新增: // AppKit's Open/Save panel runs in an XPC service. Events sent | |
| 315 | 新增: // only to the application PID do not reach its focused panel. | |
| 316 | 新增: guard CGPreflightPostEventAccess() else { throw Failure(9, "accessibility_permission") } | |
| 317 | 新增: event.post(tap: .cghidEventTap) | |
| 318 | 新增: } else { event.postToPid(pid) } | |
| 319 | 新增: } | |
| 320 | 新增: } | |
| 321 | 新增: | |
| 322 | 新增: func start(window: SCWindow, kind: String) throws -> [String: Any] { | |
| 323 | 新增: guard ["paste", "drop", "image"].contains(kind), let pid = window.owningApplication?.processID else { throw Failure(8, "attachment_request_invalid") } | |
| 324 | 新增: for (id, value) in batches where Date().timeIntervalSince(value.created) >= 1800 { | |
| 325 | 新增: batches.removeValue(forKey: id) | |
| 326 | 新增: if !value.files.isEmpty { Task { _ = try? await clipboardRequest(["operation": "discard", "files": value.files]) } } | |
| 327 | 新增: } | |
| 328 | 新增: guard batches.count < 12 else { throw Failure(8, "attachment_limit") } | |
| 329 | 新增: let value = Batch(pid: pid, window: window.windowID, kind: kind, epoch: try MacGUISession.shared.validate()) | |
| 330 | 新增: try valid(value) | |
| 331 | 新增: let id = UUID().uuidString.lowercased() | |
| 332 | 新增: batches[id] = value | |
| 333 | 新增: return ["ok": true, "id": id] | |
| 334 | 新增: } | |
| 335 | 新增: | |
| 336 | 新增: func add(_ id: String, files: [String]) throws -> [String: Any] { | |
| 337 | 新增: let value = try batch(id) | |
| 338 | 新增: guard !value.busy, !files.isEmpty, value.files.count + files.count <= 100 else { throw Failure(8, "attachment_limit") } | |
| 339 | 新增: for path in files { | |
| 340 | 新增: var info = stat() | |
| 341 | 新增: let url = URL(fileURLWithPath: path) | |
| 342 | 新增: guard url.standardizedFileURL.path == path, path.hasPrefix("/"), !path.contains("\0"), | |
| 343 | 新增: url.deletingLastPathComponent().lastPathComponent.hasPrefix("cage-clipboard-"), | |
| 344 | 新增: lstat(path, &info) == 0, info.st_mode & S_IFMT == S_IFREG, info.st_uid == getuid(), info.st_size <= 2 * 1024 * 1024 * 1024 else { | |
| 345 | 新增: throw Failure(8, "attachment_path_invalid") | |
| 346 | 新增: } | |
| 347 | 新增: } | |
| 348 | 新增: value.files.append(contentsOf: files) | |
| 349 | 新增: return ["ok": true, "id": id] | |
| 350 | 新增: } | |
| 351 | 新增: | |
| 352 | 新增: func validate(_ id: String) throws -> [String: Any] { | |
| 353 | 新增: let value = try batch(id) | |
| 354 | 新增: guard !value.busy else { throw Failure(8, "attachment_busy") } | |
| 355 | 新增: return ["ok": true] | |
| 356 | 新增: } | |
| 357 | 新增: | |
| 358 | 新增: func cancel(_ id: String) async -> [String: Any] { | |
| 359 | 新增: guard let value = batches.removeValue(forKey: id) else { return ["ok": true] } | |
| 360 | 新增: if let panel = value.panel, (try? valid(value)) != nil, | |
| 361 | 新增: let button = filePanelButton(panel, cancel: true) { | |
| 362 | 新增: _ = AXUIElementPerformAction(button, kAXPressAction as CFString) | |
| 363 | 新增: } | |
| 364 | 新增: if !value.files.isEmpty { _ = try? await clipboardRequest(["operation": "discard", "files": value.files]) } | |
| 365 | 新增: return ["ok": true] | |
| 366 | 新增: } | |
| 367 | 新增: | |
| 368 | 新增: func finish(_ id: String) async throws -> [String: Any] { | |
| 369 | 新增: let value = try batch(id) | |
| 370 | 新增: guard value.kind != "image", !value.busy, !value.files.isEmpty else { throw Failure(8, "attachment_incomplete") } | |
| 371 | 新增: value.busy = true | |
| 372 | 新增: defer { value.busy = false } | |
| 373 | 新增: if let panel = value.panel { | |
| 374 | 新增: // The native panel's Go To Folder action selects the uploaded file | |
| 375 | 新增: // without asking the guest to read a caller-selected arbitrary path. | |
| 376 | 新增: let copied = try await clipboardRequest(["operation": "prepare-files", "files": value.files]) | |
| 377 | 新增: guard let files = copied["paths"] as? [String], files.count == value.files.count, !files.isEmpty else { throw Failure(7, "clipboard_reply_invalid") } | |
| 378 | 新增: guard batches[id] === value else { | |
| 379 | 新增: _ = try? await clipboardRequest(["operation": "discard", "files": files]) | |
| 380 | 新增: throw Failure(8, "attachment_cancelled") | |
| 381 | 新增: } | |
| 382 | 新增: let previous = value.files | |
| 383 | 新增: value.files = files | |
| 384 | 新增: _ = try? await clipboardRequest(["operation": "discard", "files": previous]) | |
| 385 | 新增: guard batches[id] === value else { throw Failure(8, "attachment_cancelled") } | |
| 386 | 新增: try valid(value) | |
| 387 | 新增: try key(value.pid, 5, flags: [.maskCommand, .maskShift], panel: panel, epoch: value.epoch) | |
| 388 | 新增: let app = AXUIElementCreateApplication(value.pid) | |
| 389 | 新增: var field: AXUIElement? | |
| 390 | 新增: for _ in 0..<20 { | |
| 391 | 新增: try await Task.sleep(nanoseconds: 100_000_000) | |
| 392 | 新增: guard batches[id] === value else { throw Failure(8, "attachment_cancelled") } | |
| 393 | 新增: try valid(value) | |
| 394 | 新增: if let focus = fileAttribute(app, kAXFocusedUIElementAttribute), CFGetTypeID(focus) == AXUIElementGetTypeID(), | |
| 395 | 新增: [kAXTextFieldRole, kAXComboBoxRole].contains(fileAttribute(focus as! AXUIElement, kAXRoleAttribute) as? String ?? "") { | |
| 396 | 新增: field = (focus as! AXUIElement); break | |
| 397 | 新增: } | |
| 398 | 新增: } | |
| 399 | 新增: let destination = files.count == 1 ? files[0] : (files[0] as NSString).deletingLastPathComponent | |
| 400 | 新增: guard let field, AXUIElementSetAttributeValue(field, kAXValueAttribute as CFString, destination as CFString) == .success else { | |
| 401 | 新增: throw Failure(7, "file_dialog_navigation_failed") | |
| 402 | 新增: } | |
| 403 | 新增: try key(value.pid, 36, panel: panel, epoch: value.epoch) | |
| 404 | 新增: var resolved = false | |
| 405 | 新增: for _ in 0..<20 { | |
| 406 | 新增: try await Task.sleep(nanoseconds: 100_000_000) | |
| 407 | 新增: guard batches[id] === value else { throw Failure(8, "attachment_cancelled") } | |
| 408 | 新增: try valid(value) | |
| 409 | 新增: if let focus = fileAttribute(app, kAXFocusedUIElementAttribute), !CFEqual(focus, field) { resolved = true; break } | |
| 410 | 新增: } | |
| 411 | 新增: guard resolved else { throw Failure(7, "file_dialog_navigation_failed") } | |
| 412 | 新增: if files.count > 1 { | |
| 413 | 新增: try key(value.pid, 0, flags: .maskCommand, panel: panel, epoch: value.epoch) | |
| 414 | 新增: try await Task.sleep(nanoseconds: 150_000_000) | |
| 415 | 新增: guard batches[id] === value else { throw Failure(8, "attachment_cancelled") } | |
| 416 | 新增: try valid(value) | |
| 417 | 新增: } | |
| 418 | 新增: let expected = try Set(files.map { path -> String in | |
| 419 | 新增: guard let resolved = realpath(path, nil) else { throw Failure(7, "file_dialog_selection_mismatch") } | |
| 420 | 新增: defer { free(resolved) } | |
| 421 | 新增: return String(cString: resolved) | |
| 422 | 新增: }) | |
| 423 | 新增: guard selectedFilePaths(panel, expected: expected) == expected else { throw Failure(7, "file_dialog_selection_mismatch") } | |
| 424 | 新增: guard let button = filePanelButton(panel), | |
| 425 | 新增: fileAttribute(button, kAXEnabledAttribute) as? Bool == true, | |
| 426 | 新增: AXUIElementPerformAction(button, kAXPressAction as CFString) == .success else { | |
| 427 | 新增: throw Failure(7, "file_dialog_navigation_failed") | |
| 428 | 新增: } | |
| 429 | 新增: var accepted = false | |
| 430 | 新增: for _ in 0..<20 { | |
| 431 | 新增: try await Task.sleep(nanoseconds: 100_000_000) | |
| 432 | 新增: if let current = openFilePanel(value.pid), CFEqual(current, panel) { continue } | |
| 433 | 新增: accepted = true; break | |
| 434 | 新增: } | |
| 435 | 新增: guard accepted else { throw Failure(7, "file_dialog_still_open") } | |
| 436 | 新增: } else { | |
| 437 | 新增: let written = try await clipboardRequest(["operation": "write", "files": value.files]) | |
| 438 | 新增: guard batches[id] === value, let revision = written["revision"] as? Int, NSPasteboard.general.changeCount == revision else { | |
| 439 | 新增: throw Failure(8, "attachment_cancelled") | |
| 440 | 新增: } | |
| 441 | 新增: try valid(value) | |
| 442 | 新增: try key(value.pid, 9, flags: .maskCommand) | |
| 443 | 新增: } | |
| 444 | 新增: batches.removeValue(forKey: id) | |
| 445 | 新增: return ["ok": true] | |
| 446 | 新增: } | |
| 447 | 新增: | |
| 448 | 新增: private func save(_ panel: AXUIElement, field: AXUIElement, pid: pid_t, path: String, epoch: UInt64) async throws { | |
| 449 | 新增: func validate() throws { | |
| 450 | 新增: try MacGUISession.shared.validate(epoch) | |
| 451 | 新增: guard AXIsProcessTrusted(), try claudePIDs().contains(pid), NSWorkspace.shared.frontmostApplication?.processIdentifier == pid, | |
| 452 | 新增: filePanelPresent(panel, pid: pid), filePanelFocused(panel, pid: pid) else { throw Failure(7, "file_dialog_changed") } | |
| 453 | 新增: } | |
| 454 | 新增: try validate() | |
| 455 | 新增: try key(pid, 5, flags: [.maskCommand, .maskShift], panel: panel, epoch: epoch) | |
| 456 | 新增: let app = AXUIElementCreateApplication(pid) | |
| 457 | 新增: var location: AXUIElement? | |
| 458 | 新增: for _ in 0..<20 { | |
| 459 | 新增: try await Task.sleep(nanoseconds: 100_000_000) | |
| 460 | 新增: try validate() | |
| 461 | 新增: if let focus = fileAttribute(app, kAXFocusedUIElementAttribute), CFGetTypeID(focus) == AXUIElementGetTypeID(), | |
| 462 | 新增: !CFEqual(focus, field), [kAXTextFieldRole, kAXComboBoxRole].contains(fileAttribute(focus as! AXUIElement, kAXRoleAttribute) as? String ?? "") { | |
| 463 | 新增: location = (focus as! AXUIElement); break | |
| 464 | 新增: } | |
| 465 | 新增: } | |
| 466 | 新增: guard let location, AXUIElementSetAttributeValue(location, kAXValueAttribute as CFString, (path as NSString).deletingLastPathComponent as CFString) == .success else { | |
| 467 | 新增: throw Failure(7, "file_dialog_navigation_failed") | |
| 468 | 新增: } | |
| 469 | 新增: try key(pid, 36, panel: panel, epoch: epoch) | |
| 470 | 新增: var resolved = false | |
| 471 | 新增: for _ in 0..<20 { | |
| 472 | 新增: try await Task.sleep(nanoseconds: 100_000_000) | |
| 473 | 新增: try validate() | |
| 474 | 新增: if let focus = fileAttribute(app, kAXFocusedUIElementAttribute), !CFEqual(focus, location) { resolved = true; break } | |
| 475 | 新增: } | |
| 476 | 新增: guard resolved, AXUIElementSetAttributeValue(field, kAXValueAttribute as CFString, (path as NSString).lastPathComponent as CFString) == .success, | |
| 477 | 新增: let button = filePanelButton(panel), | |
| 478 | 新增: fileAttribute(button, kAXEnabledAttribute) as? Bool == true else { throw Failure(7, "file_dialog_navigation_failed") } | |
| 479 | 新增: try validate() | |
| 480 | 新增: guard AXUIElementPerformAction(button, kAXPressAction as CFString) == .success else { throw Failure(7, "file_dialog_navigation_failed") } | |
| 481 | 新增: for _ in 0..<20 { | |
| 482 | 新增: try await Task.sleep(nanoseconds: 100_000_000) | |
| 483 | 新增: if let current = saveFilePanel(pid), CFEqual(current.0, panel) { continue } | |
| 484 | 新增: return | |
| 485 | 新增: } | |
| 486 | 新增: throw Failure(7, "file_dialog_still_open") | |
| 487 | 新增: } | |
| 488 | 新增: | |
| 489 | 新增: func poll() async throws -> [String: Any] { | |
| 490 | 新增: let epoch = try MacGUISession.shared.validate() | |
| 491 | 新增: for (id, value) in batches where value.epoch != epoch || Date().timeIntervalSince(value.created) >= 1800 { | |
| 492 | 新增: batches.removeValue(forKey: id) | |
| 493 | 新增: if !value.files.isEmpty { Task { _ = try? await clipboardRequest(["operation": "discard", "files": value.files]) } } | |
| 494 | 新增: } | |
| 495 | 新增: guard AXIsProcessTrusted(), let pid = try? claudePIDs().first else { | |
| 496 | 新增: return ["available": false, "uploads": [], "downloads": try MacDesktopDownloads.shared.snapshot(), "opens": openSnapshot()] | |
| 497 | 新增: } | |
| 498 | 新增: if let (panel, field) = saveFilePanel(pid) { | |
| 499 | 新增: if savingPanel == nil || !CFEqual(savingPanel!, panel) { | |
| 500 | 新增: savingPanel = panel | |
| 501 | 新增: let name = fileAttribute(field, kAXValueAttribute) as? String ?? "" | |
| 502 | 新增: try await MacDesktopDownloads.shared.reserve(name: name, pid: pid) { path in | |
| 503 | 新增: try await self.save(panel, field: field, pid: pid, path: path, epoch: epoch) | |
| 504 | 新增: } | |
| 505 | 新增: } | |
| 506 | 新增: } else { savingPanel = nil } | |
| 507 | 新增: guard let panel = openFilePanel(pid) else { | |
| 508 | 新增: for (id, value) in batches where value.panel != nil && !value.busy { | |
| 509 | 新增: batches.removeValue(forKey: id) | |
| 510 | 新增: if !value.files.isEmpty { Task { _ = try? await clipboardRequest(["operation": "discard", "files": value.files]) } } | |
| 511 | 新增: } | |
| 512 | 新增: return ["available": true, "uploads": [], "downloads": try MacDesktopDownloads.shared.snapshot(), "opens": openSnapshot()] | |
| 513 | 新增: } | |
| 514 | 新增: let existing = batches.first { $0.value.pid == pid && $0.value.panel.map { CFEqual($0, panel) } == true } | |
| 515 | 新增: let id: String | |
| 516 | 新增: if let existing { id = existing.key } | |
| 517 | 新增: else { | |
| 518 | 新增: guard batches.count < 12 else { throw Failure(8, "attachment_limit") } | |
| 519 | 新增: id = UUID().uuidString.lowercased() | |
| 520 | 新增: batches[id] = Batch(pid: pid, window: 0, kind: "chooser", epoch: try MacGUISession.shared.validate(), panel: panel) | |
| 521 | 新增: } | |
| 522 | 新增: return ["available": true, "uploads": [["id": id, "kind": "chooser", "multiple": true, "directory": false, "target": "desktop"]], "downloads": try MacDesktopDownloads.shared.snapshot(), "opens": openSnapshot()] | |
| 523 | 新增: } | |
| 524 | 新增: | |
| 525 | 新增: func pasteImage(_ data: Data, window: SCWindow) async throws -> [String: Any] { | |
| 526 | 新增: guard data.count <= 20 * 1024 * 1024, let pid = window.owningApplication?.processID else { throw Failure(8, "attachment_size_limit") } | |
| 527 | 新增: let value = Batch(pid: pid, window: window.windowID, kind: "paste", epoch: try MacGUISession.shared.validate()) | |
| 528 | 新增: return try await deliverImage(data, batch: value) | |
| 529 | 新增: } | |
| 530 | 新增: | |
| 531 | 新增: func finishImage(_ id: String) async throws -> [String: Any] { | |
| 532 | 新增: let value = try batch(id) | |
| 533 | 新增: guard value.kind == "image", !value.busy, value.files.count == 1 else { throw Failure(8, "attachment_incomplete") } | |
| 534 | 新增: value.busy = true | |
| 535 | 新增: do { | |
| 536 | 新增: let file = try FileHandle(forReadingFrom: URL(fileURLWithPath: value.files[0])) | |
| 537 | 新增: defer { try? file.close() } | |
| 538 | 新增: let data = try file.read(upToCount: 20 * 1024 * 1024 + 1) ?? Data() | |
| 539 | 新增: guard !data.isEmpty, data.count <= 20 * 1024 * 1024 else { throw Failure(8, "attachment_size_limit") } | |
| 540 | 新增: let result = try await deliverImage(data, batch: value) | |
| 541 | 新增: _ = await cancel(id) | |
| 542 | 新增: return result | |
| 543 | 新增: } catch { | |
| 544 | 新增: _ = await cancel(id) | |
| 545 | 新增: throw error | |
| 546 | 新增: } | |
| 547 | 新增: } | |
| 548 | 新增: | |
| 549 | 新增: private func deliverImage(_ data: Data, batch value: Batch) async throws -> [String: Any] { | |
| 550 | 新增: try valid(value) | |
| 551 | 新增: let written = try await clipboardRequest(["operation": "write", "png": data.base64EncodedString()]) | |
| 552 | 新增: guard let revision = written["revision"] as? Int, NSPasteboard.general.changeCount == revision else { throw Failure(8, "attachment_cancelled") } | |
| 553 | 新增: try valid(value) | |
| 554 | 新增: try key(value.pid, 9, flags: .maskCommand, epoch: value.epoch) | |
| 555 | 新增: return ["ok": true] | |
| 556 | 新增: } | |
| 557 | 新增:} | |
| @@ -0,0 +1,61 @@ | ||
| 1 | 新增:import Foundation | |
| 2 | 新增:import Darwin | |
| 3 | 新增: | |
| 4 | 新增:enum GuestDiagnostic { | |
| 5 | 新增: private static let limit = 1 << 20 | |
| 6 | 新增: private static let sources = ["window", "clipboard"] | |
| 7 | 新增: | |
| 8 | 新增: static func record(_ source: String, _ reason: String) { | |
| 9 | 新增: guard sources.contains(source), reason.range(of: "^[a-zA-Z][a-zA-Z0-9_]{0,95}$", options: .regularExpression) != nil else { return } | |
| 10 | 新增: let directory = FileManager.default.homeDirectoryForCurrentUser.appendingPathComponent("Library/Logs/Cage") | |
| 11 | 新增: try? append(source, reason, directory: directory) | |
| 12 | 新增: } | |
| 13 | 新增: | |
| 14 | 新增: static func append(_ source: String, _ reason: String, directory: URL) throws { | |
| 15 | 新增: guard sources.contains(source), reason.range(of: "^[a-zA-Z][a-zA-Z0-9_]{0,95}$", options: .regularExpression) != nil else { return } | |
| 16 | 新增: try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true, attributes: [.posixPermissions: 0o700]) | |
| 17 | 新增: let root = open(directory.path, O_RDONLY | O_DIRECTORY | O_NOFOLLOW) | |
| 18 | 新增: guard root >= 0 else { throw CocoaError(.fileReadNoPermission) } | |
| 19 | 新增: defer { close(root) } | |
| 20 | 新增: var info = stat() | |
| 21 | 新增: guard fstat(root, &info) == 0, info.st_uid == getuid(), info.st_mode & 0o077 == 0 else { throw CocoaError(.fileReadNoPermission) } | |
| 22 | 新增: let lock = openat(root, source + ".lock", O_CREAT | O_RDWR | O_NOFOLLOW, 0o600) | |
| 23 | 新增: guard lock >= 0 else { throw CocoaError(.fileWriteNoPermission) } | |
| 24 | 新增: defer { close(lock) } | |
| 25 | 新增: guard fstat(lock, &info) == 0, info.st_mode & S_IFMT == S_IFREG, info.st_uid == getuid(), info.st_nlink == 1, | |
| 26 | 新增: flock(lock, LOCK_EX) == 0 else { throw CocoaError(.fileWriteNoPermission) } | |
| 27 | 新增: defer { flock(lock, LOCK_UN) } | |
| 28 | 新增: let now = Date() | |
| 29 | 新增: for index in 0...4 { | |
| 30 | 新增: let name = index == 0 ? source + ".jsonl" : source + "-\(index).jsonl" | |
| 31 | 新增: if fstatat(root, name, &info, AT_SYMLINK_NOFOLLOW) != 0 { continue } | |
| 32 | 新增: guard info.st_mode & S_IFMT == S_IFREG, info.st_uid == getuid(), info.st_nlink == 1 else { throw CocoaError(.fileReadNoPermission) } | |
| 33 | 新增: if Double(info.st_mtimespec.tv_sec) < now.addingTimeInterval(-14 * 86400).timeIntervalSince1970 { _ = unlinkat(root, name, 0) } | |
| 34 | 新增: } | |
| 35 | 新增: var data = try JSONSerialization.data(withJSONObject: ["time": ISO8601DateFormatter().string(from: now), "source": source, "reason": reason]) | |
| 36 | 新增: data.append(10) | |
| 37 | 新增: let current = source + ".jsonl" | |
| 38 | 新增: if fstatat(root, current, &info, AT_SYMLINK_NOFOLLOW) == 0, | |
| 39 | 新增: info.st_size + Int64(data.count) > limit || info.st_birthtimespec.tv_sec / 86400 != Int(now.timeIntervalSince1970) / 86400 { | |
| 40 | 新增: _ = unlinkat(root, source + "-4.jsonl", 0) | |
| 41 | 新增: for index in stride(from: 3, through: 0, by: -1) { | |
| 42 | 新增: let previous = index == 0 ? current : source + "-\(index).jsonl" | |
| 43 | 新增: let next = source + "-\(index + 1).jsonl" | |
| 44 | 新增: if renameat(root, previous, root, next) != 0, errno != ENOENT { throw CocoaError(.fileWriteUnknown) } | |
| 45 | 新增: } | |
| 46 | 新增: } | |
| 47 | 新增: let fd = openat(root, current, O_WRONLY | O_CREAT | O_APPEND | O_NOFOLLOW, 0o600) | |
| 48 | 新增: guard fd >= 0 else { throw CocoaError(.fileWriteNoPermission) } | |
| 49 | 新增: defer { close(fd) } | |
| 50 | 新增: guard fstat(fd, &info) == 0, info.st_mode & S_IFMT == S_IFREG, info.st_uid == getuid(), info.st_nlink == 1 else { throw CocoaError(.fileWriteNoPermission) } | |
| 51 | 新增: try data.withUnsafeBytes { bytes in | |
| 52 | 新增: var offset = 0 | |
| 53 | 新增: while offset < bytes.count { | |
| 54 | 新增: let count = Darwin.write(fd, bytes.baseAddress!.advanced(by: offset), bytes.count - offset) | |
| 55 | 新增: if count < 0 && errno == EINTR { continue } | |
| 56 | 新增: guard count > 0 else { throw CocoaError(.fileWriteUnknown) } | |
| 57 | 新增: offset += count | |
| 58 | 新增: } | |
| 59 | 新增: } | |
| 60 | 新增: } | |
| 61 | 新增:} | |
| @@ -0,0 +1,52 @@ | ||
| 1 | 新增:#include <errno.h> | |
| 2 | 新增:#include <libproc.h> | |
| 3 | 新增:#include <stdlib.h> | |
| 4 | 新增:#include <sys/file.h> | |
| 5 | 新增:#include <sys/proc_info.h> | |
| 6 | 新增:#include <sys/stat.h> | |
| 7 | 新增: | |
| 8 | 新增:// Return 1 while the verified application tree holds a writable descriptor, | |
| 9 | 新增:// 0 after those descriptors close, and -1 when the observation is incomplete. | |
| 10 | 新增:int cage_file_has_writer(int root, const char *path) { | |
| 11 | 新增: struct stat target; | |
| 12 | 新增: if (lstat(path, &target) != 0 || !S_ISREG(target.st_mode)) return -1; | |
| 13 | 新增: int pids[256] = {root}; | |
| 14 | 新增: int count = 1; | |
| 15 | 新增: for (int index = 0; index < count; index++) { | |
| 16 | 新增: int children[256]; | |
| 17 | 新增: int child_count = proc_listchildpids(pids[index], children, sizeof(children)); | |
| 18 | 新增: if (child_count < 0 || child_count >= 256) return -1; | |
| 19 | 新增: for (int child = 0; child < child_count; child++) { | |
| 20 | 新增: int seen = 0; | |
| 21 | 新增: for (int prior = 0; prior < count; prior++) seen |= pids[prior] == children[child]; | |
| 22 | 新增: if (!seen && children[child] > 0) { | |
| 23 | 新增: if (count == 256) return -1; | |
| 24 | 新增: pids[count++] = children[child]; | |
| 25 | 新增: } | |
| 26 | 新增: } | |
| 27 | 新增: int needed = proc_pidinfo(pids[index], PROC_PIDLISTFDS, 0, NULL, 0); | |
| 28 | 新增: if (needed <= 0) { | |
| 29 | 新增: if (errno == ESRCH) continue; | |
| 30 | 新增: return -1; | |
| 31 | 新增: } | |
| 32 | 新增: if (needed > 32768 * (int)sizeof(struct proc_fdinfo)) return -1; | |
| 33 | 新增: int capacity = needed + 128 * (int)sizeof(struct proc_fdinfo); | |
| 34 | 新增: struct proc_fdinfo *fds = malloc((size_t)capacity); | |
| 35 | 新增: if (!fds) return -1; | |
| 36 | 新增: int received = proc_pidinfo(pids[index], PROC_PIDLISTFDS, 0, fds, capacity); | |
| 37 | 新增: if (received <= 0 || received >= capacity) { free(fds); return -1; } | |
| 38 | 新增: for (int fd = 0; fd < received / (int)sizeof(*fds); fd++) { | |
| 39 | 新增: if (fds[fd].proc_fdtype != PROX_FDTYPE_VNODE) continue; | |
| 40 | 新增: struct vnode_fdinfo info; | |
| 41 | 新增: int size = proc_pidfdinfo(pids[index], fds[fd].proc_fd, PROC_PIDFDVNODEINFO, &info, sizeof(info)); | |
| 42 | 新增: if (size != sizeof(info)) { | |
| 43 | 新增: if (errno == EBADF || errno == ESRCH || errno == ENOENT) continue; | |
| 44 | 新增: free(fds); return -1; | |
| 45 | 新增: } | |
| 46 | 新增: if (info.pvi.vi_stat.vst_dev == (uint32_t)target.st_dev && info.pvi.vi_stat.vst_ino == target.st_ino && | |
| 47 | 新增: (info.pfi.fi_openflags & FWRITE) != 0) { free(fds); return 1; } | |
| 48 | 新增: } | |
| 49 | 新增: free(fds); | |
| 50 | 新增: } | |
| 51 | 新增: return 0; | |
| 52 | 新增:} | |
| @@ -0,0 +1,19 @@ | ||
| 1 | 新增:#!/bin/bash | |
| 2 | 新增:# Extract the pinned vendor installer on the host. Nothing is installed here. | |
| 3 | 新增:set -euo pipefail | |
| 4 | 新增:[[ $# == 2 && $1 == /* && $2 == /* && ! -e $2 ]] | |
| 5 | 新增:work=$(mktemp -d) | |
| 6 | 新增:volume="$work/volume" | |
| 7 | 新增:attached=0 | |
| 8 | 新增:cleanup() { | |
| 9 | 新增: if [[ $attached == 1 ]]; then hdiutil detach "$volume" >/dev/null || return; fi | |
| 10 | 新增: rm -rf "$work" | |
| 11 | 新增:} | |
| 12 | 新增:trap cleanup EXIT | |
| 13 | 新增:mkdir "$volume" | |
| 14 | 新增:[[ $(shasum -a 256 "$1" | cut -d' ' -f1) == 92c21ef2db4199bcf5bddc8e6efb57b23ecb9715f74ab38cba2c77ab226d3830 ]] | |
| 15 | 新增:hdiutil attach -readonly -nobrowse -noautoopen -mountpoint "$volume" "$1" >/dev/null | |
| 16 | 新增:attached=1 | |
| 17 | 新增:pkg="$volume/Install macFUSE.pkg" | |
| 18 | 新增:[[ -n $pkg && $(shasum -a 256 "$pkg" | cut -d' ' -f1) == 5acf9e30bab227707de8d15eb28472a0cc9ed45709846b3e067d283294dc7f9e ]] | |
| 19 | 新增:cp "$pkg" "$2" | |
| @@ -0,0 +1,39 @@ | ||
| 1 | 新增:// One GUI epoch is shared by delayed file delivery and remote window input. | |
| 2 | 新增:import AppKit | |
| 3 | 新增: | |
| 4 | 新增:@MainActor | |
| 5 | 新增:final class MacGUISession { | |
| 6 | 新增: static let shared = MacGUISession() | |
| 7 | 新增: private(set) var epoch: UInt64 = 1 | |
| 8 | 新增: private var available: Bool | |
| 9 | 新增: private var timer: Timer? | |
| 10 | 新增: private var observers: [NSObjectProtocol] = [] | |
| 11 | 新增: | |
| 12 | 新增: private init() { | |
| 13 | 新增: available = (try? consoleUser()) != nil | |
| 14 | 新增: timer = Timer.scheduledTimer(withTimeInterval: 0.25, repeats: true) { [weak self] _ in | |
| 15 | 新增: Task { @MainActor in self?.refresh() } | |
| 16 | 新增: } | |
| 17 | 新增: let center = NSWorkspace.shared.notificationCenter | |
| 18 | 新增: observers.append(center.addObserver(forName: NSWorkspace.sessionDidResignActiveNotification, object: nil, queue: .main) { [weak self] _ in | |
| 19 | 新增: Task { @MainActor in | |
| 20 | 新增: guard let self else { return } | |
| 21 | 新增: self.epoch &+= 1 | |
| 22 | 新增: self.refresh() | |
| 23 | 新增: } | |
| 24 | 新增: }) | |
| 25 | 新增: } | |
| 26 | 新增: | |
| 27 | 新增: private func refresh() { | |
| 28 | 新增: let current = (try? consoleUser()) != nil | |
| 29 | 新增: if current != available { available = current; epoch &+= 1 } | |
| 30 | 新增: } | |
| 31 | 新增: | |
| 32 | 新增: @discardableResult | |
| 33 | 新增: func validate(_ expected: UInt64? = nil) throws -> UInt64 { | |
| 34 | 新增: refresh() | |
| 35 | 新增: guard available else { throw Failure(4, "requires_gui_login") } | |
| 36 | 新增: guard expected == nil || expected == epoch else { throw Failure(7, "gui_session_changed") } | |
| 37 | 新增: return epoch | |
| 38 | 新增: } | |
| 39 | 新增:} | |
| @@ -0,0 +1,78 @@ | ||
| 1 | 新增:// Observe the guest kernel's IPv6 route selection for the fixed public probe. | |
| 2 | 新增:// An interface-scoped default on Darwin is selectable by a process that | |
| 3 | 新增:// requests IPV6_BOUND_IF, even when an ordinary route lookup returns no route. | |
| 4 | 新增:#include <arpa/inet.h> | |
| 5 | 新增:#include <errno.h> | |
| 6 | 新增:#include <fcntl.h> | |
| 7 | 新增:#include <ifaddrs.h> | |
| 8 | 新增:#include <net/if.h> | |
| 9 | 新增:#include <netinet/in.h> | |
| 10 | 新增:#include <poll.h> | |
| 11 | 新增:#include <stdio.h> | |
| 12 | 新增:#include <string.h> | |
| 13 | 新增:#include <sys/socket.h> | |
| 14 | 新增:#include <unistd.h> | |
| 15 | 新增: | |
| 16 | 新增:static int unicastSource(const struct in6_addr *address) { | |
| 17 | 新增: return !IN6_IS_ADDR_UNSPECIFIED(address) && !IN6_IS_ADDR_LOOPBACK(address) | |
| 18 | 新增: && !IN6_IS_ADDR_LINKLOCAL(address) && !IN6_IS_ADDR_MULTICAST(address); | |
| 19 | 新增:} | |
| 20 | 新增: | |
| 21 | 新增:// A link-local, one-hop datagram can leave the VM NIC even when the guest | |
| 22 | 新增:// deliberately has no ordinary IPv6 default route. It never targets the internet. | |
| 23 | 新增:static int sendProbe(const char *name, const char *run, const char *check) { | |
| 24 | 新增: if (strlen(run)!=32 || strlen(check)!=32 || strspn(run,"0123456789abcdef")!=32 || strspn(check,"0123456789abcdef")!=32) return 2; | |
| 25 | 新增: unsigned index=if_nametoindex(name); if(!index) return 1; | |
| 26 | 新增: int fd=socket(AF_INET6,SOCK_DGRAM,0), hops=1; | |
| 27 | 新增: if(fd<0 || setsockopt(fd,IPPROTO_IPV6,IPV6_BOUND_IF,&index,sizeof(index))!=0 || | |
| 28 | 新增: setsockopt(fd,IPPROTO_IPV6,IPV6_MULTICAST_IF,&index,sizeof(index))!=0 || | |
| 29 | 新增: setsockopt(fd,IPPROTO_IPV6,IPV6_MULTICAST_HOPS,&hops,sizeof(hops))!=0) return 1; | |
| 30 | 新增: struct sockaddr_in6 dst={.sin6_family=AF_INET6,.sin6_len=sizeof(dst),.sin6_scope_id=index,.sin6_port=htons(49417)}; | |
| 31 | 新增: if(inet_pton(AF_INET6,"ff02::2",&dst.sin6_addr)!=1) return 1; | |
| 32 | 新增: char payload[120];int len=snprintf(payload,sizeof(payload),"Cage IPv6 link probe v1 %s %s",run,check); | |
| 33 | 新增: ssize_t sent=sendto(fd,payload,(size_t)len,0,(struct sockaddr *)&dst,sizeof(dst)); | |
| 34 | 新增: close(fd); if(sent!=len) return 1; puts("sent");return 0; | |
| 35 | 新增:} | |
| 36 | 新增: | |
| 37 | 新增:int main(int argc, char **argv) { | |
| 38 | 新增: if (argc==5 && strcmp(argv[1],"link")==0) return sendProbe(argv[2],argv[3],argv[4]); | |
| 39 | 新增: if (argc != 2) return 2; | |
| 40 | 新增: int bound = strcmp(argv[1], "default") != 0; | |
| 41 | 新增: unsigned index = bound ? if_nametoindex(argv[1]) : 0; | |
| 42 | 新增: if (bound && !index) return 2; | |
| 43 | 新增: struct ifaddrs *interfaces; | |
| 44 | 新增: if (getifaddrs(&interfaces) != 0) return 1; | |
| 45 | 新增: int sources = 0, found = !bound; | |
| 46 | 新增: for (struct ifaddrs *item = interfaces; item; item = item->ifa_next) { | |
| 47 | 新增: if (bound && strcmp(item->ifa_name, argv[1])) continue; | |
| 48 | 新增: found = 1; | |
| 49 | 新增: if (item->ifa_addr && item->ifa_addr->sa_family == AF_INET6 && (item->ifa_flags & IFF_UP)) { | |
| 50 | 新增: struct sockaddr_in6 *a = (struct sockaddr_in6 *)item->ifa_addr; | |
| 51 | 新增: if (unicastSource(&a->sin6_addr)) sources++; | |
| 52 | 新增: } | |
| 53 | 新增: } | |
| 54 | 新增: freeifaddrs(interfaces); | |
| 55 | 新增: if (!found) return 1; | |
| 56 | 新增: int fd = socket(AF_INET6, SOCK_STREAM, 0); | |
| 57 | 新增: if (fd < 0 || fcntl(fd, F_SETFL, O_NONBLOCK) < 0) return 1; | |
| 58 | 新增: if (bound && setsockopt(fd, IPPROTO_IPV6, IPV6_BOUND_IF, &index, sizeof(index)) != 0) return 1; | |
| 59 | 新增: struct sockaddr_in6 dst = {.sin6_len = sizeof(dst), .sin6_family = AF_INET6, .sin6_port = htons(443)}; | |
| 60 | 新增: if (inet_pton(AF_INET6, "2606:4700:4700::1111", &dst.sin6_addr) != 1) return 1; | |
| 61 | 新增: int error = connect(fd, (struct sockaddr *)&dst, sizeof(dst)) == 0 ? 0 : errno; | |
| 62 | 新增: if (error == EINPROGRESS) { | |
| 63 | 新增: struct pollfd pfd = {fd, POLLOUT, 0}; | |
| 64 | 新增: int ready = poll(&pfd, 1, 1500); | |
| 65 | 新增: if (ready == 0) error = ETIMEDOUT; | |
| 66 | 新增: else if (ready < 0) return 1; | |
| 67 | 新增: else { | |
| 68 | 新增: socklen_t len = sizeof(error); | |
| 69 | 新增: if (getsockopt(fd, SOL_SOCKET, SO_ERROR, &error, &len) != 0) return 1; | |
| 70 | 新增: } | |
| 71 | 新增: } | |
| 72 | 新增: close(fd); | |
| 73 | 新增: const char *status = error == 0 ? "connected" | |
| 74 | 新增: : (error == ENETUNREACH || error == EHOSTUNREACH || error == EADDRNOTAVAIL) ? "no-route" | |
| 75 | 新增: : error == ETIMEDOUT ? "timeout" : "unknown"; | |
| 76 | 新增: printf("{\"globalSources\":%d,\"boundIndex\":%u,\"result\":\"%s\",\"errno\":%d}\n", sources, index, status, error); | |
| 77 | 新增: return 0; | |
| 78 | 新增:} | |
| @@ -0,0 +1,126 @@ | ||
| 1 | 新增:// Started by Cage through the bound ordinary user's SSH connection. | |
| 2 | 新增:import { installMacOSCLIBrowser } from "./macos-cli-browser.mjs"; | |
| 3 | 新增:import { spawn } from "node:child_process"; | |
| 4 | 新增:import { randomBytes } from "node:crypto"; | |
| 5 | 新增:import { mkdir, rm, writeFile } from "node:fs/promises"; | |
| 6 | 新增:import { homedir } from "node:os"; | |
| 7 | 新增:import path from "node:path"; | |
| 8 | 新增:import { chromium, request } from "/usr/local/libexec/cage-workbench-browser-4.145.0-pw1.65.0/playwright/index.mjs"; | |
| 9 | 新增:import { createNativeBrowserService } from "./windows-browser.mjs"; | |
| 10 | 新增:import { relayMacOSBrowser, serveMacOSBrowser } from "./macos-browser-service.mjs"; | |
| 11 | 新增:import { lstat, readFile } from "node:fs/promises"; | |
| 12 | 新增: | |
| 13 | 新增:const data = path.join(homedir(), "Library", "Application Support", "Cage"); | |
| 14 | 新增:const editors = new Map(); | |
| 15 | 新增: | |
| 16 | 新增:async function openEditor(id, restart) { | |
| 17 | 新增: if (!/^[a-f0-9]{24}$/.test(id)) throw new Error("项目标识无效"); | |
| 18 | 新增: const folder = path.join(homedir(), "Cage", "Projects", id); | |
| 19 | 新增: let editor = editors.get(id); | |
| 20 | 新增: if (restart && editor) { editor.child.kill(); editor = null; } | |
| 21 | 新增: if (!editor) { | |
| 22 | 新增: const password = randomBytes(32).toString("hex"); | |
| 23 | 新增: const directory = path.join(data, "EditorSessions"); | |
| 24 | 新增: const config = path.join(directory, id + ".yaml"); | |
| 25 | 新增: await mkdir(directory, { mode: 0o700, recursive: true }); | |
| 26 | 新增: await writeFile(config, "bind-addr: 127.0.0.1:0\nauth: password\npassword: " + password + "\ncert: false\n", { mode: 0o600 }); | |
| 27 | 新增: const child = spawn("/usr/local/libexec/cage-macos-terminal", ["--editor", folder], { stdio: "pipe" }); | |
| 28 | 新增: child.stdin.on("error", () => {}); | |
| 29 | 新增: editor = { child, password, config }; | |
| 30 | 新增: editors.set(id, editor); | |
| 31 | 新增: child.once("exit", () => { | |
| 32 | 新增: if (editors.get(id) === editor) { editors.delete(id); void rm(config, { force: true }).catch(() => {}); } | |
| 33 | 新增: }); | |
| 34 | 新增: editor.address = await new Promise((resolve, reject) => { | |
| 35 | 新增: let recent = ""; | |
| 36 | 新增: const failed = () => finish(); | |
| 37 | 新增: const read = chunk => { | |
| 38 | 新增: recent = (recent + chunk).slice(-6000); | |
| 39 | 新增: const address = recent.match(/HTTP server listening on (http:\/\/127\.0\.0\.1:[1-9][0-9]*)/); | |
| 40 | 新增: if (address) finish(address[1]); | |
| 41 | 新增: }; | |
| 42 | 新增: const timer = setTimeout(failed, 15000); | |
| 43 | 新增: function finish(address) { | |
| 44 | 新增: clearTimeout(timer); | |
| 45 | 新增: child.off("exit", failed); child.off("error", failed); | |
| 46 | 新增: for (const stream of [child.stdout, child.stderr]) { stream.off("data", read); stream.resume(); } | |
| 47 | 新增: if (address) resolve(address); | |
| 48 | 新增: else { child.kill(); reject(new Error("项目编辑器启动失败")); } | |
| 49 | 新增: } | |
| 50 | 新增: child.stdout.on("data", read); child.stderr.on("data", read); | |
| 51 | 新增: child.once("error", failed); child.once("exit", failed); | |
| 52 | 新增: }); | |
| 53 | 新增: } | |
| 54 | 新增: const client = await request.newContext(); | |
| 55 | 新增: try { | |
| 56 | 新增: const login = await client.post(editor.address + "/login", { form: { password: editor.password }, maxRedirects: 0, timeout: 7000 }); | |
| 57 | 新增: if (![302, 303].includes(login.status())) throw new Error("客机编辑器登录失败"); | |
| 58 | 新增: const hostname = id + ".cage-editor.localhost"; | |
| 59 | 新增: const url = new URL(editor.address); | |
| 60 | 新增: url.hostname = hostname; | |
| 61 | 新增: url.searchParams.set("folder", folder); | |
| 62 | 新增: const { cookies } = await client.storageState(); | |
| 63 | 新增: return { url: url.href, folder, cookies: cookies.map(cookie => ({ ...cookie, domain: hostname })) }; | |
| 64 | 新增: } finally { await client.dispose(); } | |
| 65 | 新增:} | |
| 66 | 新增: | |
| 67 | 新增:async function audit(context, { timezone, network }) { | |
| 68 | 新增: // Sample the real workbench tab in a fresh isolated world. Page scripts | |
| 69 | 新增: // cannot replace navigator or Intl in this execution context. | |
| 70 | 新增: const tab = context.pages().find(p => !p.url().startsWith("chrome-extension:")); | |
| 71 | 新增: const cdp = await context.newCDPSession(tab); | |
| 72 | 新增: let result; | |
| 73 | 新增: try { | |
| 74 | 新增: const {frameTree} = await cdp.send("Page.getFrameTree"); | |
| 75 | 新增: const {executionContextId} = await cdp.send("Page.createIsolatedWorld", {frameId: frameTree.frame.id, worldName: "cage-workbench-settings"}); | |
| 76 | 新增: const observed = await cdp.send("Runtime.evaluate", {contextId: executionContextId, returnByValue: true, | |
| 77 | 新增: expression: `({timezone:Intl.DateTimeFormat().resolvedOptions().timeZone, expected_timezone:new Intl.DateTimeFormat("en",{timeZone:${JSON.stringify(timezone)}}).resolvedOptions().timeZone,language:navigator.language,platform:navigator.platform})`}); | |
| 78 | 新增: result = observed.result.value; | |
| 79 | 新增: if (!result?.platform) throw new Error("无法读取客机浏览器设置"); | |
| 80 | 新增: } finally { await cdp.detach(); } | |
| 81 | 新增: if (!network) return result; | |
| 82 | 新增: const isolated = await context.browser().newContext({ serviceWorkers: "block" }); | |
| 83 | 新增: try { | |
| 84 | 新增: const page = await isolated.newPage(); | |
| 85 | 新增: await page.goto("http://198.18.0.254/", { waitUntil: "domcontentloaded", timeout: 12000 }); | |
| 86 | 新增: result.network = await page.evaluate(async () => { | |
| 87 | 新增: if (location.origin !== "http://198.18.0.254") throw new Error("无效的诊断地址"); | |
| 88 | 新增: try { | |
| 89 | 新增: const response = await fetch("/egress", { cache: "no-store", credentials: "omit", signal: AbortSignal.timeout(14000) }); | |
| 90 | 新增: return { ...(await response.json()), status: response.status }; | |
| 91 | 新增: } catch { return { status: 0 }; } | |
| 92 | 新增: }); | |
| 93 | 新增: return result; | |
| 94 | 新增: } finally { await isolated.close(); } | |
| 95 | 新增:} | |
| 96 | 新增: | |
| 97 | 新增:const marker = await lstat("/var/db/cage-guest-os"); | |
| 98 | 新增:if (process.platform !== "darwin" || process.getuid() < 500 || !marker.isFile() || marker.uid !== 0 || (marker.mode & 0o022) || | |
| 99 | 新增: (await readFile("/var/db/cage-guest-os", "utf8")).trim() !== "macos") throw new Error("Cage browser requires its bound guest user"); | |
| 100 | 新增:const directory = path.join(homedir(), "Library", "Caches", "dev.cage.GuestBrowser"); | |
| 101 | 新增:if (process.argv.length > 3 || process.argv[2] && process.argv[2] !== "--service" && process.argv[2] !== "--client") | |
| 102 | 新增: throw new Error("Unknown browser service operation"); | |
| 103 | 新增:if (process.argv[2] !== "--service") { | |
| 104 | 新增: // Older hosts invoke this file with no arguments. They attach to the same | |
| 105 | 新增: // service and receive ownership capability metadata with the first reply. | |
| 106 | 新增: await relayMacOSBrowser(directory); | |
| 107 | 新增:} else { | |
| 108 | 新增: const service = createNativeBrowserService({ | |
| 109 | 新增: platform: "darwin", chromium, editor: openEditor, audit, | |
| 110 | 新增: directory: path.join(data, "BrowserWorkbench"), | |
| 111 | 新增: profileDirectory: path.join(data, "Browser"), | |
| 112 | 新增: executablePath: "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome", | |
| 113 | 新增: }); | |
| 114 | 新增: await service.request({ operation: "configure", input: { networkMode: "packet", displayScale: 1 } }); | |
| 115 | 新增: const closeBrowser = async () => { | |
| 116 | 新增: for (const { child } of editors.values()) child.kill(); | |
| 117 | 新增: await service.close(); | |
| 118 | 新增: }; | |
| 119 | 新增: const server = await serveMacOSBrowser({ directory, dispatch: (request, options) => service.request(request, options), disconnect: signal => service.releaseInput(signal), close: closeBrowser }); | |
| 120 | 新增: let closeLogin; | |
| 121 | 新增: try { closeLogin = await installMacOSCLIBrowser(data, message => server.request(message)); } | |
| 122 | 新增: catch (error) { await server.close(); throw error; } | |
| 123 | 新增: const shutdown = async () => { await server.close(); await closeLogin(); }; | |
| 124 | 新增: process.once("SIGTERM", () => { void shutdown().catch(() => { process.exitCode = 1; }); }); | |
| 125 | 新增: process.once("SIGINT", () => { void shutdown().catch(() => { process.exitCode = 1; }); }); | |
| 126 | 新增:} | |
| @@ -0,0 +1,78 @@ | ||
| 1 | 新增:// The phone owns a separate browser profile and the shared public-web policy. | |
| 2 | 新增:import { homedir } from "node:os"; | |
| 3 | 新增:import path from "node:path"; | |
| 4 | 新增:import { pathToFileURL } from "node:url"; | |
| 5 | 新增:import { PhoneBrowser } from "./modules/browser-phone.mjs"; | |
| 6 | 新增:import { phoneError } from "./modules/browser-phone-network.mjs"; | |
| 7 | 新增:import { lines } from "./windows-browser.mjs"; | |
| 8 | 新增: | |
| 9 | 新增:export async function runMacOSPhoneBrowser(input = process.stdin, output = process.stdout, options = {}) { | |
| 10 | 新增: if (process.platform !== "darwin" && options.testing !== true) throw new Error("此浏览器需要 macOS 客机"); | |
| 11 | 新增: const phone = new PhoneBrowser({ | |
| 12 | 新增: binary: options.binary || "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome", | |
| 13 | 新增: directory: options.directory || path.join(homedir(), "Library", "Application Support", "Cage", "PhoneBrowser"), | |
| 14 | 新增: language: options.language || Intl.DateTimeFormat().resolvedOptions().locale, | |
| 15 | 新增: connect: options.connect, | |
| 16 | 新增: }); | |
| 17 | 新增: // This controller is private to one paired phone. Keep its cold launch | |
| 18 | 新增: // alive between frame polls, while close, SSH EOF and timeout can stop it. | |
| 19 | 新增: let opening; | |
| 20 | 新增: async function cancelOpen() { | |
| 21 | 新增: if (opening) { | |
| 22 | 新增: opening.abort.abort(); | |
| 23 | 新增: await opening.done; | |
| 24 | 新增: opening = undefined; | |
| 25 | 新增: } | |
| 26 | 新增: await phone.dispose(); | |
| 27 | 新增: } | |
| 28 | 新增: async function operate(operation, input) { | |
| 29 | 新增: if (opening && input?.id !== opening.id) throw phoneError(410, "手机浏览器会话已结束"); | |
| 30 | 新增: if (opening && operation === "close") { | |
| 31 | 新增: await cancelOpen(); | |
| 32 | 新增: return { id: input.id }; | |
| 33 | 新增: } | |
| 34 | 新增: if (!opening && operation === "open") { | |
| 35 | 新增: const entry = { id: input?.id, abort: new AbortController(), settled: false }; | |
| 36 | 新增: opening = entry; | |
| 37 | 新增: const deadline = setTimeout(() => entry.abort.abort(), 75000); | |
| 38 | 新增: entry.done = phone.run("open", input, entry.abort.signal).catch(error => { | |
| 39 | 新增: entry.error = entry.abort.signal.aborted ? phoneError(503, "客机浏览器启动超时") : error; | |
| 40 | 新增: }).finally(() => { | |
| 41 | 新增: entry.settled = true; | |
| 42 | 新增: clearTimeout(deadline); | |
| 43 | 新增: }); | |
| 44 | 新增: // Return quick URL/parameter rejections on the original open request. | |
| 45 | 新增: let timer; | |
| 46 | 新增: try { await Promise.race([entry.done, new Promise(resolve => { timer = setTimeout(resolve, 200); })]); } | |
| 47 | 新增: finally { clearTimeout(timer); } | |
| 48 | 新增: } | |
| 49 | 新增: if (opening) { | |
| 50 | 新增: if (opening.settled) { | |
| 51 | 新增: const { error } = opening; | |
| 52 | 新增: opening = undefined; | |
| 53 | 新增: if (error) throw error; | |
| 54 | 新增: } else if (operation !== "open") { | |
| 55 | 新增: throw phoneError(425, "正在启动虚拟 Mac 中的浏览器"); | |
| 56 | 新增: } | |
| 57 | 新增: if (operation === "open") return { id: input.id }; | |
| 58 | 新增: } | |
| 59 | 新增: return phone.run(operation, input); | |
| 60 | 新增: } | |
| 61 | 新增: try { | |
| 62 | 新增: for await (const line of lines(input)) { | |
| 63 | 新增: let result; | |
| 64 | 新增: try { | |
| 65 | 新增: const request = JSON.parse(line); | |
| 66 | 新增: if (request.method !== "POST" || !/^\/phone-browser\/(open|frame|action|close)$/.test(request.path || "")) throw new Error("手机浏览器请求无效"); | |
| 67 | 新增: result = await operate(request.path.split("/").at(-1), request.input); | |
| 68 | 新增: } catch (error) { | |
| 69 | 新增: result = { error: "手机浏览器操作未完成,请核对授权和最新画面", code: "phone_browser_error", status: [403, 409, 410, 425, 503].includes(error.status) ? error.status : 400 }; | |
| 70 | 新增: } | |
| 71 | 新增: await new Promise((resolve, reject) => output.write(JSON.stringify(result) + "\n", error => error ? reject(error) : resolve())); | |
| 72 | 新增: } | |
| 73 | 新增: } finally { await cancelOpen(); } | |
| 74 | 新增:} | |
| 75 | 新增: | |
| 76 | 新增:if (process.argv[1] && pathToFileURL(path.resolve(process.argv[1])).href === import.meta.url) { | |
| 77 | 新增: await runMacOSPhoneBrowser().catch(() => { process.exitCode = 1; }); | |
| 78 | 新增:} | |
| @@ -0,0 +1,253 @@ | ||
| 1 | 新增:// A phone sees the same signed Claude window as the computer. Its lease and | |
| 2 | 新增:// input focus belong to one GUI login, window and captured geometry. | |
| 3 | 新增:import AppKit | |
| 4 | 新增:import ScreenCaptureKit | |
| 5 | 新增:import ImageIO | |
| 6 | 新增: | |
| 7 | 新增:struct MacPhoneDesktopInput: Decodable { | |
| 8 | 新增: let id: String | |
| 9 | 新增: var width, height: Int? | |
| 10 | 新增: var pixel_ratio: Double? | |
| 11 | 新增: var type, document, focus, text, key: String? | |
| 12 | 新增: var x, y, dx, dy: Double? | |
| 13 | 新增:} | |
| 14 | 新增: | |
| 15 | 新增:func phoneDesktopJPEG(_ image: CGImage) throws -> Data { | |
| 16 | 新增: for quality in [0.9, 0.78, 0.62, 0.45] { | |
| 17 | 新增: let data = try encodedImage(image, type: .jpeg, | |
| 18 | 新增: properties: [kCGImageDestinationLossyCompressionQuality: quality] as CFDictionary) | |
| 19 | 新增: // Leave room for base64 expansion and the complete phone frame metadata. | |
| 20 | 新增: if data.count <= 2 << 20 { return data } | |
| 21 | 新增: } | |
| 22 | 新增: throw Failure(8, "frame_limit") | |
| 23 | 新增:} | |
| 24 | 新增: | |
| 25 | 新增:private func matchesPhoneFocus(_ requested: String?, token: String, previous: AXUIElement?, current: AXUIElement?, password: Bool) -> Bool { | |
| 26 | 新增: guard !token.isEmpty, requested == token, let previous, let current, !password else { return false } | |
| 27 | 新增: return CFEqual(previous, current) | |
| 28 | 新增:} | |
| 29 | 新增: | |
| 30 | 新增:@MainActor | |
| 31 | 新增:final class MacPhoneDesktop { | |
| 32 | 新增: static let shared = MacPhoneDesktop() | |
| 33 | 新增: | |
| 34 | 新增: @MainActor private final class Session { | |
| 35 | 新增: let id, secret: String | |
| 36 | 新增: let epoch: UInt64 | |
| 37 | 新增: let canvas = ClaudeCanvasSession() | |
| 38 | 新增: var width: Int | |
| 39 | 新增: var height: Int | |
| 40 | 新增: var ratio: Double | |
| 41 | 新增: var geometry = "" | |
| 42 | 新增: var document = "" | |
| 43 | 新增: var focus = "" | |
| 44 | 新增: var focusedElement: AXUIElement? | |
| 45 | 新增: var window: CGWindowID? | |
| 46 | 新增: var pid: pid_t? | |
| 47 | 新增: var touched = Date() | |
| 48 | 新增: | |
| 49 | 新增: init(_ input: MacPhoneDesktopInput, secret: String, epoch: UInt64) throws { | |
| 50 | 新增: let size = try MacPhoneDesktop.viewport(input) | |
| 51 | 新增: id = input.id | |
| 52 | 新增: self.secret = secret | |
| 53 | 新增: self.epoch = epoch | |
| 54 | 新增: width = size.0; height = size.1; ratio = size.2 | |
| 55 | 新增: } | |
| 56 | 新增: } | |
| 57 | 新增: | |
| 58 | 新增: private var current: Session? | |
| 59 | 新增: | |
| 60 | 新增: private static func viewport(_ input: MacPhoneDesktopInput) throws -> (Int, Int, Double) { | |
| 61 | 新增: guard let width = input.width, let height = input.height, | |
| 62 | 新增: (240...1440).contains(width), (160...1600).contains(height) else { | |
| 63 | 新增: throw Failure(8, "invalid_input") | |
| 64 | 新增: } | |
| 65 | 新增: let ratio = input.pixel_ratio ?? 1 | |
| 66 | 新增: guard ratio.isFinite, (1...8).contains(ratio) else { throw Failure(8, "invalid_input") } | |
| 67 | 新增: return (width, height, ratio) | |
| 68 | 新增: } | |
| 69 | 新增: | |
| 70 | 新增: private func validate(_ session: Session) throws { | |
| 71 | 新增: guard current === session, Date().timeIntervalSince(session.touched) < 120 else { | |
| 72 | 新增: throw Failure(7, "phone_session_ended") | |
| 73 | 新增: } | |
| 74 | 新增: do { try MacGUISession.shared.validate(session.epoch) } | |
| 75 | 新增: catch { current = nil; throw error } | |
| 76 | 新增: session.touched = Date() | |
| 77 | 新增: } | |
| 78 | 新增: | |
| 79 | 新增: func handle(_ request: Request) async throws -> [String: Any] { | |
| 80 | 新增: guard let input = request.phone, UUID(uuidString: input.id) != nil, | |
| 81 | 新增: let secret = request.phone_token, (32...128).contains(secret.utf8.count) else { | |
| 82 | 新增: throw Failure(8, "invalid_input") | |
| 83 | 新增: } | |
| 84 | 新增: if request.action == "phone-close" { | |
| 85 | 新增: if current?.id == input.id && current?.secret == secret { current = nil } | |
| 86 | 新增: return ["id": input.id] | |
| 87 | 新增: } | |
| 88 | 新增: if request.action == "phone-open" { | |
| 89 | 新增: let epoch = try MacGUISession.shared.validate() | |
| 90 | 新增: let session = try Session(input, secret: secret, epoch: epoch) | |
| 91 | 新增: current = session | |
| 92 | 新增: do { | |
| 93 | 新增: try await launchClaudeWindow() | |
| 94 | 新增: try validate(session) | |
| 95 | 新增: } catch { | |
| 96 | 新增: if current === session { current = nil } | |
| 97 | 新增: throw error | |
| 98 | 新增: } | |
| 99 | 新增: return ["id": session.id] | |
| 100 | 新增: } | |
| 101 | 新增: guard let session = current, session.id == input.id, session.secret == secret else { | |
| 102 | 新增: throw Failure(7, "phone_session_ended") | |
| 103 | 新增: } | |
| 104 | 新增: try validate(session) | |
| 105 | 新增: switch request.action { | |
| 106 | 新增: case "phone-frame": | |
| 107 | 新增: return try await frame(session) | |
| 108 | 新增: case "phone-action": | |
| 109 | 新增: if input.type == "resize" { | |
| 110 | 新增: let (width, height, ratio) = try Self.viewport(input) | |
| 111 | 新增: session.width = width; session.height = height; session.ratio = ratio | |
| 112 | 新增: session.document = ""; session.focus = ""; session.focusedElement = nil | |
| 113 | 新增: return ["id": session.id] | |
| 114 | 新增: } | |
| 115 | 新增: try await action(input, session: session) | |
| 116 | 新增: return ["id": session.id] | |
| 117 | 新增: default: | |
| 118 | 新增: throw Failure(8, "unknown_action") | |
| 119 | 新增: } | |
| 120 | 新增: } | |
| 121 | 新增: | |
| 122 | 新增: private func frame(_ session: Session) async throws -> [String: Any] { | |
| 123 | 新增: var (window, selection) = try await selectedWindow() | |
| 124 | 新增: try validate(session) | |
| 125 | 新增: let capture = selection ?? SCContentFilter(desktopIndependentWindow: window) | |
| 126 | 新增: let layout = try await session.canvas.layout(window, filter: capture, | |
| 127 | 新增: width: max(320, session.width), height: max(240, session.height), scale: min(2, session.ratio)) | |
| 128 | 新增: try validate(session) | |
| 129 | 新增: if window.frame != layout.frame { | |
| 130 | 新增: (window, selection) = try await selectedWindow() | |
| 131 | 新增: guard window.windowID == layout.id, window.owningApplication?.processID == layout.pid else { | |
| 132 | 新增: throw Failure(7, "window_changed") | |
| 133 | 新增: } | |
| 134 | 新增: } | |
| 135 | 新增: let raw = try await session.canvas.capture(window, | |
| 136 | 新增: filter: selection ?? SCContentFilter(desktopIndependentWindow: window), | |
| 137 | 新增: layout: layout, binary: true, phoneJPEG: true) | |
| 138 | 新增: try validate(session) | |
| 139 | 新增: guard let data = raw["imageBytes"] as? Data, let geometry = raw["geometry"] as? String else { | |
| 140 | 新增: throw Failure(8, "capture_failed") | |
| 141 | 新增: } | |
| 142 | 新增: if session.geometry != geometry || session.document.isEmpty { | |
| 143 | 新增: session.document = UUID().uuidString | |
| 144 | 新增: session.focus = ""; session.focusedElement = nil | |
| 145 | 新增: } | |
| 146 | 新增: session.geometry = geometry; session.window = layout.id; session.pid = layout.pid | |
| 147 | 新增: let focus = editableFocus(window, session: session) | |
| 148 | 新增: if let element = focus.element { | |
| 149 | 新增: if session.focusedElement.map({ CFEqual($0, element) }) != true { | |
| 150 | 新增: session.focus = UUID().uuidString | |
| 151 | 新增: } | |
| 152 | 新增: session.focusedElement = element | |
| 153 | 新增: } else { | |
| 154 | 新增: session.focusedElement = nil; session.focus = "" | |
| 155 | 新增: } | |
| 156 | 新增: let reply: [String: Any] = ["id": session.id, "document": session.document, | |
| 157 | 新增: "image": data.base64EncodedString(), "width": session.width, "height": session.height, | |
| 158 | 新增: "content_width": layout.content.width, "content_height": layout.content.height, | |
| 159 | 新增: "pixel_width": raw["pixelWidth"] ?? 0, "pixel_height": raw["pixelHeight"] ?? 0, | |
| 160 | 新增: "requested_pixel_ratio": session.ratio, "pixel_ratio_control": true, | |
| 161 | 新增: "focus": session.focus, "password": focus.password, "window": "desktop", "shared": true, | |
| 162 | 新增: "login_supported": false] | |
| 163 | 新增: guard try JSONSerialization.data(withJSONObject: reply).count <= 3 << 20 else { | |
| 164 | 新增: throw Failure(8, "frame_limit") | |
| 165 | 新增: } | |
| 166 | 新增: return reply | |
| 167 | 新增: } | |
| 168 | 新增: | |
| 169 | 新增: private func editableFocus(_ window: SCWindow, session: Session) -> (element: AXUIElement?, password: Bool) { | |
| 170 | 新增: guard (try? session.canvas.inputGeometry(session.geometry, window: window)) != nil, | |
| 171 | 新增: let pid = window.owningApplication?.processID else { return (nil, false) } | |
| 172 | 新增: func attribute(_ element: AXUIElement, _ name: String) -> CFTypeRef? { | |
| 173 | 新增: var value: CFTypeRef? | |
| 174 | 新增: return AXUIElementCopyAttributeValue(element, name as CFString, &value) == .success ? value : nil | |
| 175 | 新增: } | |
| 176 | 新增: let application = AXUIElementCreateApplication(pid) | |
| 177 | 新增: guard let raw = attribute(application, kAXFocusedUIElementAttribute), CFGetTypeID(raw) == AXUIElementGetTypeID(), | |
| 178 | 新增: let owner = attribute(application, kAXFocusedWindowAttribute) else { return (nil, false) } | |
| 179 | 新增: let element = raw as! AXUIElement | |
| 180 | 新增: guard let elementWindow = attribute(element, kAXWindowAttribute), CFEqual(owner, elementWindow), | |
| 181 | 新增: let role = attribute(element, kAXRoleAttribute) as? String, | |
| 182 | 新增: [kAXTextFieldRole, kAXTextAreaRole, kAXComboBoxRole].contains(role) else { return (nil, false) } | |
| 183 | 新增: let password = attribute(element, kAXSubroleAttribute) as? String == kAXSecureTextFieldSubrole | |
| 184 | 新增: return (element, password) | |
| 185 | 新增: } | |
| 186 | 新增: | |
| 187 | 新增: private func action(_ input: MacPhoneDesktopInput, session: Session) async throws { | |
| 188 | 新增: guard !session.document.isEmpty, input.document == session.document else { throw Failure(7, "phone_document_changed") } | |
| 189 | 新增: let (window, _) = try await selectedWindow() | |
| 190 | 新增: try validate(session) | |
| 191 | 新增: guard window.windowID == session.window, window.owningApplication?.processID == session.pid else { | |
| 192 | 新增: throw Failure(7, "window_changed") | |
| 193 | 新增: } | |
| 194 | 新增: let canvas = try session.canvas.inputGeometry(session.geometry, window: window) | |
| 195 | 新增: var native = Request(action: "") | |
| 196 | 新增: var scrollX: Double = 0 | |
| 197 | 新增: let typing = input.type == "text" || (input.type == "key" && !["Tab", "Escape", "ArrowUp", "ArrowDown", "ArrowLeft", "ArrowRight"].contains(input.key ?? "")) | |
| 198 | 新增: if typing { | |
| 199 | 新增: let fresh = editableFocus(window, session: session) | |
| 200 | 新增: guard matchesPhoneFocus(input.focus, token: session.focus, previous: session.focusedElement, | |
| 201 | 新增: current: fresh.element, password: fresh.password) else { throw Failure(7, "phone_focus_changed") } | |
| 202 | 新增: } | |
| 203 | 新增: switch input.type { | |
| 204 | 新增: case "text": | |
| 205 | 新增: native = Request(action: "text", text: input.text) | |
| 206 | 新增: case "key": | |
| 207 | 新增: if let key = input.key, key.utf8.count == 1, let scalar = key.unicodeScalars.first, (32...126).contains(scalar.value) { | |
| 208 | 新增: native = Request(action: "text", text: key) | |
| 209 | 新增: } else { native = Request(action: "key", key: input.key) } | |
| 210 | 新增: case "tap", "scroll": | |
| 211 | 新增: guard let x = input.x, let y = input.y, x.isFinite, y.isFinite, | |
| 212 | 新增: (0..<Double(canvas.content.width)).contains(x), (0..<Double(canvas.content.height)).contains(y) else { | |
| 213 | 新增: throw Failure(8, "invalid_input") | |
| 214 | 新增: } | |
| 215 | 新增: native = Request(action: input.type == "tap" ? "click" : "scroll", | |
| 216 | 新增: x: x / Double(canvas.content.width), y: y / Double(canvas.content.height), delta: input.dy) | |
| 217 | 新增: if input.type == "scroll" { | |
| 218 | 新增: guard let dx = input.dx, let dy = input.dy, dx.isFinite, dy.isFinite, | |
| 219 | 新增: (-3200...3200).contains(dx), (-3200...3200).contains(dy) else { throw Failure(8, "invalid_input") } | |
| 220 | 新增: scrollX = dx | |
| 221 | 新增: native.delta = dy | |
| 222 | 新增: } | |
| 223 | 新增: default: | |
| 224 | 新增: throw Failure(8, "invalid_input") | |
| 225 | 新增: } | |
| 226 | 新增: native.window = window.windowID; native.pid = window.owningApplication?.processID | |
| 227 | 新增: try sendInput(native, window: window, canvas: canvas, maxTextBytes: 8192, scrollX: scrollX, maxScroll: 32000) | |
| 228 | 新增: } | |
| 229 | 新增: | |
| 230 | 新增: static func selfTest() throws { | |
| 231 | 新增: let local = AXUIElementCreateApplication(getpid()) | |
| 232 | 新增: let other = AXUIElementCreateApplication(getpid() + 1) | |
| 233 | 新增: let accepts = matchesPhoneFocus("focus", token: "focus", previous: local, current: local, password: false) | |
| 234 | 新增: let rejects = [ | |
| 235 | 新增: matchesPhoneFocus("", token: "", previous: local, current: local, password: false), | |
| 236 | 新增: matchesPhoneFocus("old", token: "focus", previous: local, current: local, password: false), | |
| 237 | 新增: matchesPhoneFocus("focus", token: "focus", previous: local, current: other, password: false), | |
| 238 | 新增: matchesPhoneFocus("focus", token: "focus", previous: local, current: nil, password: false), | |
| 239 | 新增: matchesPhoneFocus("focus", token: "focus", previous: local, current: local, password: true) | |
| 240 | 新增: ] | |
| 241 | 新增: guard accepts, rejects.allSatisfy({ !$0 }) else { throw Failure(8, "focus_test_failed") } | |
| 242 | 新增: guard let context = CGContext(data: nil, width: 640, height: 480, bitsPerComponent: 8, | |
| 243 | 新增: bytesPerRow: 0, space: CGColorSpaceCreateDeviceRGB(), bitmapInfo: CGImageAlphaInfo.noneSkipLast.rawValue) else { throw Failure(8, "image_test_failed") } | |
| 244 | 新增: context.setFillColor(CGColor(red: 0.1, green: 0.2, blue: 0.3, alpha: 1)) | |
| 245 | 新增: context.fill(CGRect(x: 0, y: 0, width: 640, height: 480)) | |
| 246 | 新增: guard let image = context.makeImage() else { throw Failure(8, "image_test_failed") } | |
| 247 | 新增: let jpeg = try phoneDesktopJPEG(image) | |
| 248 | 新增: guard jpeg.starts(with: [0xff, 0xd8]), let source = CGImageSourceCreateWithData(jpeg as CFData, nil), | |
| 249 | 新增: let decoded = CGImageSourceCreateImageAtIndex(source, 0, nil), decoded.width == 640, decoded.height == 480, | |
| 250 | 新增: try JSONSerialization.data(withJSONObject: ["image": jpeg.base64EncodedString()]).count < 3 << 20 else { throw Failure(8, "jpeg_test_failed") } | |
| 251 | 新增: print("phone desktop focus token and real AX identity checks passed; JPEG 640x480 encoding and total JSON limit passed") | |
| 252 | 新增: } | |
| 253 | 新增:} | |
| @@ -0,0 +1,502 @@ | ||
| 1 | 新增:// Per-user guest application. macOS grants only the project selected in the | |
| 2 | 新增:// native Open panel. Terminal and editor children inherit that user selection. | |
| 3 | 新增:#import <AppKit/AppKit.h> | |
| 4 | 新增:#import <fcntl.h> | |
| 5 | 新增:#import <poll.h> | |
| 6 | 新增:#import <signal.h> | |
| 7 | 新增:#import <spawn.h> | |
| 8 | 新增:#import <sys/file.h> | |
| 9 | 新增:#import <sys/ioctl.h> | |
| 10 | 新增:#import <sys/mount.h> | |
| 11 | 新增:#import <sys/socket.h> | |
| 12 | 新增:#import <sys/stat.h> | |
| 13 | 新增:#import <sys/un.h> | |
| 14 | 新增:#import <sys/wait.h> | |
| 15 | 新增:#import <termios.h> | |
| 16 | 新增:#import <unistd.h> | |
| 17 | 新增: | |
| 18 | 新增:extern char **environ; | |
| 19 | 新增:static NSString *socketPath(void) { | |
| 20 | 新增: return [NSHomeDirectory() | |
| 21 | 新增: stringByAppendingPathComponent:@"Library/Application Support/Cage/project-terminal.sock"]; | |
| 22 | 新增:} | |
| 23 | 新增:static BOOL addressForSocket(struct sockaddr_un *address) { | |
| 24 | 新增: const char *p = socketPath().fileSystemRepresentation; | |
| 25 | 新增: memset(address, 0, sizeof(*address)); | |
| 26 | 新增: address->sun_family = AF_UNIX; | |
| 27 | 新增: return strlcpy(address->sun_path, p, sizeof(address->sun_path)) < sizeof(address->sun_path); | |
| 28 | 新增:} | |
| 29 | 新增:static BOOL writeAll(int fd, const void *data, size_t count) { | |
| 30 | 新增: const char *p = data; | |
| 31 | 新增: while (count) { | |
| 32 | 新增: ssize_t n = write(fd, p, count); | |
| 33 | 新增: if (n < 0 && errno == EINTR) | |
| 34 | 新增: continue; | |
| 35 | 新增: if (n <= 0) | |
| 36 | 新增: return NO; | |
| 37 | 新增: p += n; | |
| 38 | 新增: count -= n; | |
| 39 | 新增: } | |
| 40 | 新增: return YES; | |
| 41 | 新增:} | |
| 42 | 新增:static void reply(int fd, const char *message) { writeAll(fd, message, strlen(message)); } | |
| 43 | 新增:static NSString *mountID(NSString *project) { | |
| 44 | 新增: if (![project isKindOfClass:NSString.class] || ![project.stringByStandardizingPath isEqual:project]) | |
| 45 | 新增: return nil; | |
| 46 | 新增: NSString *base = [NSHomeDirectory() stringByAppendingPathComponent:@"Cage/Projects"]; | |
| 47 | 新增: NSString *leaf = project.lastPathComponent; | |
| 48 | 新增: if (![project.stringByDeletingLastPathComponent isEqual:base] || leaf.length != 24 || | |
| 49 | 新增: [leaf rangeOfCharacterFromSet:[NSCharacterSet characterSetWithCharactersInString:@"0123456789abcdef"] | |
| 50 | 新增: .invertedSet] | |
| 51 | 新增: .location != NSNotFound) | |
| 52 | 新增: return nil; | |
| 53 | 新增: struct statfs fs; | |
| 54 | 新增: if (statfs(project.fileSystemRepresentation, &fs) || | |
| 55 | 新增: strcmp(fs.f_mntonname, project.fileSystemRepresentation) || strcmp(fs.f_fstypename, "macfuse") || | |
| 56 | 新增: fs.f_owner != getuid() || (fs.f_flags & (MNT_NOSUID | MNT_NODEV)) != (MNT_NOSUID | MNT_NODEV)) | |
| 57 | 新增: return nil; | |
| 58 | 新增: return [NSString stringWithUTF8String:fs.f_mntfromname]; | |
| 59 | 新增:} | |
| 60 | 新增: | |
| 61 | 新增:@interface ProjectAccess : NSObject <NSApplicationDelegate, NSOpenSavePanelDelegate> | |
| 62 | 新增:@end | |
| 63 | 新增:@implementation ProjectAccess { | |
| 64 | 新增: NSMutableDictionary<NSString *, NSURL *> *_scopes; | |
| 65 | 新增: NSMutableDictionary<NSString *, NSString *> *_ready; | |
| 66 | 新增: NSString *_requesting; | |
| 67 | 新增: NSString *_nonce; | |
| 68 | 新增: NSOpenPanel *_panel; | |
| 69 | 新增: NSMutableDictionary<NSString *, NSDate *> *_declined; | |
| 70 | 新增:} | |
| 71 | 新增:- (void)applicationDidFinishLaunching:(NSNotification *)note { | |
| 72 | 新增: _scopes = [NSMutableDictionary dictionary]; | |
| 73 | 新增: _ready = [NSMutableDictionary dictionary]; | |
| 74 | 新增: _declined = [NSMutableDictionary dictionary]; | |
| 75 | 新增: dispatch_async(dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0), ^{ | |
| 76 | 新增: [self serve]; | |
| 77 | 新增: }); | |
| 78 | 新增:} | |
| 79 | 新增:// These state and UI methods run on the main thread. | |
| 80 | 新增:- (BOOL)restore:(NSString *)project { | |
| 81 | 新增: if (_scopes[project]) | |
| 82 | 新增: return YES; | |
| 83 | 新增: NSData *saved = [[NSUserDefaults standardUserDefaults] dataForKey:project]; | |
| 84 | 新增: if (!saved) | |
| 85 | 新增: return NO; | |
| 86 | 新增: BOOL stale = NO; | |
| 87 | 新增: NSURL *url = [NSURL | |
| 88 | 新增: URLByResolvingBookmarkData:saved | |
| 89 | 新增: options:NSURLBookmarkResolutionWithSecurityScope | | |
| 90 | 新增: NSURLBookmarkResolutionWithoutUI | NSURLBookmarkResolutionWithoutMounting | |
| 91 | 新增: relativeToURL:nil | |
| 92 | 新增: bookmarkDataIsStale:&stale | |
| 93 | 新增: error:nil]; | |
| 94 | 新增: if (![url.path isEqual:project] || ![url startAccessingSecurityScopedResource]) | |
| 95 | 新增: return NO; | |
| 96 | 新增: _scopes[project] = url; | |
| 97 | 新增: if (stale) | |
| 98 | 新增: [self remember:url]; | |
| 99 | 新增: return YES; | |
| 100 | 新增:} | |
| 101 | 新增:- (void)remember:(NSURL *)url { | |
| 102 | 新增: NSData *bookmark = [url bookmarkDataWithOptions:NSURLBookmarkCreationWithSecurityScope | |
| 103 | 新增: includingResourceValuesForKeys:nil | |
| 104 | 新增: relativeToURL:nil | |
| 105 | 新增: error:nil]; | |
| 106 | 新增: if (bookmark) | |
| 107 | 新增: [[NSUserDefaults standardUserDefaults] setObject:bookmark forKey:url.path]; | |
| 108 | 新增:} | |
| 109 | 新增:- (void)request:(NSString *)project { | |
| 110 | 新增: if (_requesting || (_declined[project] && [_declined[project] timeIntervalSinceNow] > 0)) | |
| 111 | 新增: return; | |
| 112 | 新增: _requesting = project; | |
| 113 | 新增: NSOpenPanel *panel = [NSOpenPanel openPanel]; | |
| 114 | 新增: panel.delegate = self; | |
| 115 | 新增: panel.canChooseDirectories = YES; | |
| 116 | 新增: panel.canChooseFiles = NO; | |
| 117 | 新增: panel.allowsMultipleSelection = NO; | |
| 118 | 新增: panel.directoryURL = [NSURL fileURLWithPath:project isDirectory:YES]; | |
| 119 | 新增: panel.message = @"Allow Cage to open this mounted project in the guest terminal and editor."; | |
| 120 | 新增: panel.prompt = @"Use Project"; | |
| 121 | 新增: _nonce = NSUUID.UUID.UUIDString; | |
| 122 | 新增: _panel = panel; | |
| 123 | 新增: __block NSTimer *timer; | |
| 124 | 新增: [NSApp activateIgnoringOtherApps:YES]; | |
| 125 | 新增: [panel beginWithCompletionHandler:^(NSModalResponse response) { | |
| 126 | 新增: [timer invalidate]; | |
| 127 | 新增: self->_panel = nil; | |
| 128 | 新增: self->_nonce = nil; | |
| 129 | 新增: NSURL *url = panel.URL; | |
| 130 | 新增: if (response == NSModalResponseOK && [url.path isEqual:project] && mountID(project) && | |
| 131 | 新增: [url startAccessingSecurityScopedResource]) { | |
| 132 | 新增: self->_scopes[project] = url; | |
| 133 | 新增: [self remember:url]; | |
| 134 | 新增: } else { | |
| 135 | 新增: self->_declined[project] = [NSDate dateWithTimeIntervalSinceNow:30]; | |
| 136 | 新增: } | |
| 137 | 新增: self->_requesting = nil; | |
| 138 | 新增: }]; | |
| 139 | 新增: // The request must disappear if the mount is revoked while the panel is open. | |
| 140 | 新增: timer = | |
| 141 | 新增: [NSTimer scheduledTimerWithTimeInterval:.25 | |
| 142 | 新增: repeats:YES | |
| 143 | 新增: block:^(NSTimer *t) { | |
| 144 | 新增: if (!mountID(project) || ![self->_requesting isEqual:project]) { | |
| 145 | 新增: [panel cancel:nil]; | |
| 146 | 新增: return; | |
| 147 | 新增: } | |
| 148 | 新增: }]; | |
| 149 | 新增:} | |
| 150 | 新增:- (NSString *)probe:(NSDictionary *)req { | |
| 151 | 新增: NSString *project = req[@"path"], *file = req[@"file"], *expected = req[@"expected"], | |
| 152 | 新增: *identity = mountID(project); | |
| 153 | 新增: if (!identity || ![file isKindOfClass:NSString.class] || ![file hasPrefix:@".cage-mount-probe-"] || | |
| 154 | 新增: ![file.lastPathComponent isEqual:file] || ![expected isKindOfClass:NSString.class] || | |
| 155 | 新增: expected.length < 1 || expected.length > 256) | |
| 156 | 新增: return @"ERR"; | |
| 157 | 新增: if (_ready[project] && ![_ready[project] isEqual:identity]) { | |
| 158 | 新增: [_ready removeObjectForKey:project]; | |
| 159 | 新增: [_scopes[project] stopAccessingSecurityScopedResource]; | |
| 160 | 新增: [_scopes removeObjectForKey:project]; | |
| 161 | 新增: } | |
| 162 | 新增: if (![self restore:project]) { | |
| 163 | 新增: [self request:project]; | |
| 164 | 新增: return @"PENDING"; | |
| 165 | 新增: } | |
| 166 | 新增: NSString *filePath = [project stringByAppendingPathComponent:file]; | |
| 167 | 新增: // Bounded read of the host challenge. A link cannot be used for the proof. | |
| 168 | 新增: char b[1024]; | |
| 169 | 新增: int fd = open(filePath.fileSystemRepresentation, O_RDONLY | O_NOFOLLOW | O_CLOEXEC | O_NONBLOCK); | |
| 170 | 新增: if (fd < 0) { | |
| 171 | 新增: if (errno == EPERM || errno == EACCES) { | |
| 172 | 新增: [_ready removeObjectForKey:project]; | |
| 173 | 新增: [_scopes[project] stopAccessingSecurityScopedResource]; | |
| 174 | 新增: [_scopes removeObjectForKey:project]; | |
| 175 | 新增: [self request:project]; | |
| 176 | 新增: return @"PENDING"; | |
| 177 | 新增: } | |
| 178 | 新增: return @"ERR"; | |
| 179 | 新增: } | |
| 180 | 新增: struct stat st; | |
| 181 | 新增: ssize_t n = | |
| 182 | 新增: !fstat(fd, &st) && S_ISREG(st.st_mode) && st.st_size < sizeof(b) ? read(fd, b, sizeof(b)) : -1; | |
| 183 | 新增: close(fd); | |
| 184 | 新增: NSData *answer = [expected dataUsingEncoding:NSUTF8StringEncoding]; | |
| 185 | 新增: if (n < 0 || n != (ssize_t)answer.length || memcmp(b, answer.bytes, n) || | |
| 186 | 新增: ![identity isEqual:mountID(project)]) | |
| 187 | 新增: return @"ERR"; | |
| 188 | 新增: _ready[project] = identity; | |
| 189 | 新增: return @"OK"; | |
| 190 | 新增:} | |
| 191 | 新增:- (void)serve { | |
| 192 | 新增: struct sockaddr_un address; | |
| 193 | 新增: if (!addressForSocket(&address)) | |
| 194 | 新增: return; | |
| 195 | 新增: NSString *dir = socketPath().stringByDeletingLastPathComponent; | |
| 196 | 新增: NSFileManager *fm = [NSFileManager defaultManager]; | |
| 197 | 新增: if (![fm createDirectoryAtPath:dir | |
| 198 | 新增: withIntermediateDirectories:YES | |
| 199 | 新增: attributes:@{NSFilePosixPermissions : @0700} | |
| 200 | 新增: error:nil]) | |
| 201 | 新增: return; | |
| 202 | 新增: struct stat st; | |
| 203 | 新增: if (lstat(dir.fileSystemRepresentation, &st) || !S_ISDIR(st.st_mode) || st.st_uid != getuid() || | |
| 204 | 新增: (st.st_mode & 0077)) | |
| 205 | 新增: return; | |
| 206 | 新增: // The advisory lock distinguishes a dead listener from another running copy. | |
| 207 | 新增: NSString *l = [dir stringByAppendingPathComponent:@"project-terminal.lock"]; | |
| 208 | 新增: int lock = open(l.fileSystemRepresentation, O_RDWR | O_CREAT | O_CLOEXEC | O_NOFOLLOW, 0600); | |
| 209 | 新增: if (lock < 0 || flock(lock, LOCK_EX | LOCK_NB)) { | |
| 210 | 新增: if (lock >= 0) | |
| 211 | 新增: close(lock); | |
| 212 | 新增: return; | |
| 213 | 新增: } | |
| 214 | 新增: if (!lstat(address.sun_path, &st) && !(S_ISSOCK(st.st_mode) && st.st_uid == getuid())) { | |
| 215 | 新增: close(lock); | |
| 216 | 新增: return; | |
| 217 | 新增: } | |
| 218 | 新增: unlink(address.sun_path); | |
| 219 | 新增: int listener = socket(AF_UNIX, SOCK_STREAM, 0); | |
| 220 | 新增: if (listener < 0 || bind(listener, (struct sockaddr *)&address, sizeof(address)) || | |
| 221 | 新增: chmod(address.sun_path, 0600) || listen(listener, 12)) { | |
| 222 | 新增: if (listener >= 0) | |
| 223 | 新增: close(listener); | |
| 224 | 新增: close(lock); | |
| 225 | 新增: return; | |
| 226 | 新增: } | |
| 227 | 新增: fcntl(listener, F_SETFD, FD_CLOEXEC); | |
| 228 | 新增: for (;;) { | |
| 229 | 新增: int fd = accept(listener, NULL, NULL); | |
| 230 | 新增: if (fd < 0) { | |
| 231 | 新增: if (errno == EINTR) | |
| 232 | 新增: continue; | |
| 233 | 新增: break; | |
| 234 | 新增: } | |
| 235 | 新增: fcntl(fd, F_SETFD, FD_CLOEXEC); | |
| 236 | 新增: dispatch_async(dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0), ^{ | |
| 237 | 新增: @autoreleasepool { | |
| 238 | 新增: [self handle:fd]; | |
| 239 | 新增: close(fd); | |
| 240 | 新增: } | |
| 241 | 新增: }); | |
| 242 | 新增: } | |
| 243 | 新增: close(listener); | |
| 244 | 新增: unlink(address.sun_path); | |
| 245 | 新增: close(lock); | |
| 246 | 新增:} | |
| 247 | 新增:- (void)handle:(int)fd { | |
| 248 | 新增: uid_t uid; | |
| 249 | 新增: gid_t gid; | |
| 250 | 新增: if (getpeereid(fd, &uid, &gid) || uid != getuid()) | |
| 251 | 新增: return; | |
| 252 | 新增: struct timeval timeout = {4, 0}; | |
| 253 | 新增: setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, &timeout, sizeof(timeout)); | |
| 254 | 新增: char bytes[8192], ancillary[CMSG_SPACE(8 * sizeof(int))]; | |
| 255 | 新增: int tty = -1; | |
| 256 | 新增: size_t len = 0; | |
| 257 | 新增: BOOL extra = NO; | |
| 258 | 新增: struct iovec iov = {bytes, sizeof(bytes)}; | |
| 259 | 新增: struct msghdr msg = {0}; | |
| 260 | 新增: msg.msg_iov = &iov; | |
| 261 | 新增: msg.msg_iovlen = 1; | |
| 262 | 新增: msg.msg_control = ancillary; | |
| 263 | 新增: msg.msg_controllen = sizeof(ancillary); | |
| 264 | 新增: ssize_t n = recvmsg(fd, &msg, 0); | |
| 265 | 新增: if (n <= 0) | |
| 266 | 新增: return; | |
| 267 | 新增: for (struct cmsghdr *c = CMSG_FIRSTHDR(&msg); c; c = CMSG_NXTHDR(&msg, c)) { | |
| 268 | 新增: if (c->cmsg_level != SOL_SOCKET || c->cmsg_type != SCM_RIGHTS) | |
| 269 | 新增: continue; | |
| 270 | 新增: size_t count = (c->cmsg_len - CMSG_LEN(0)) / sizeof(int); | |
| 271 | 新增: int *fds = (int *)CMSG_DATA(c); | |
| 272 | 新增: for (size_t i = 0; i < count; i++) { | |
| 273 | 新增: if (tty < 0) { | |
| 274 | 新增: tty = fds[i]; | |
| 275 | 新增: fcntl(tty, F_SETFD, FD_CLOEXEC); | |
| 276 | 新增: } else { | |
| 277 | 新增: close(fds[i]); | |
| 278 | 新增: extra = YES; | |
| 279 | 新增: } | |
| 280 | 新增: } | |
| 281 | 新增: } | |
| 282 | 新增: @try { | |
| 283 | 新增: if (extra || (msg.msg_flags & MSG_CTRUNC)) | |
| 284 | 新增: return; | |
| 285 | 新增: len = (size_t)n; | |
| 286 | 新增: while (!memchr(bytes, '\n', len) && len < sizeof(bytes)) { | |
| 287 | 新增: n = read(fd, bytes + len, sizeof(bytes) - len); | |
| 288 | 新增: if (n <= 0) | |
| 289 | 新增: return; | |
| 290 | 新增: len += n; | |
| 291 | 新增: } | |
| 292 | 新增: if (bytes[len - 1] != '\n') | |
| 293 | 新增: return; | |
| 294 | 新增: NSDictionary *req = [NSJSONSerialization JSONObjectWithData:[NSData dataWithBytes:bytes length:len] | |
| 295 | 新增: options:0 | |
| 296 | 新增: error:nil]; | |
| 297 | 新增: if (![req isKindOfClass:NSDictionary.class]) | |
| 298 | 新增: return; | |
| 299 | 新增: NSString *project = req[@"path"], *action = req[@"action"]; | |
| 300 | 新增: if (!mountID(project)) { | |
| 301 | 新增: reply(fd, "ERR\n"); | |
| 302 | 新增: return; | |
| 303 | 新增: } | |
| 304 | 新增: // The authenticated window forwarder obtains the live NSWindow from the | |
| 305 | 新增: // process that opened the panel. Closing it invalidates the nonce. | |
| 306 | 新增: if ([action isEqual:@"panel"] && tty < 0) { | |
| 307 | 新增: __block NSDictionary *state; | |
| 308 | 新增: dispatch_sync(dispatch_get_main_queue(), ^{ | |
| 309 | 新增: if ([self->_requesting isEqual:project] && self->_nonce && self->_panel.visible && | |
| 310 | 新增: self->_panel.windowNumber > 0 && | |
| 311 | 新增: [self->_panel.directoryURL.URLByStandardizingPath.path isEqual:project]) | |
| 312 | 新增: state = @{ | |
| 313 | 新增: @"path" : project, | |
| 314 | 新增: @"nonce" : self->_nonce, | |
| 315 | 新增: @"pid" : @(getpid()), | |
| 316 | 新增: @"windowNumber" : @(self->_panel.windowNumber) | |
| 317 | 新增: }; | |
| 318 | 新增: }); | |
| 319 | 新增: if (!state) { | |
| 320 | 新增: reply(fd, "ERR\n"); | |
| 321 | 新增: return; | |
| 322 | 新增: } | |
| 323 | 新增: NSData *json = [NSJSONSerialization dataWithJSONObject:state options:0 error:nil]; | |
| 324 | 新增: writeAll(fd, json.bytes, json.length); | |
| 325 | 新增: reply(fd, "\n"); | |
| 326 | 新增: return; | |
| 327 | 新增: } | |
| 328 | 新增: if ([action isEqual:@"probe"] && tty < 0) { | |
| 329 | 新增: __block NSString *status; | |
| 330 | 新增: dispatch_sync(dispatch_get_main_queue(), ^{ | |
| 331 | 新增: status = [self probe:req]; | |
| 332 | 新增: }); | |
| 333 | 新增: reply(fd, [status stringByAppendingString:@"\n"].UTF8String); | |
| 334 | 新增: return; | |
| 335 | 新增: } | |
| 336 | 新增: BOOL claude = [action isEqual:@"claude"]; | |
| 337 | 新增: NSString *launch = req[@"launch"]; | |
| 338 | 新增: if (tty < 0 || !([action isEqual:@"terminal"] || [action isEqual:@"editor"] || claude) || | |
| 339 | 新增: (claude && (![launch isKindOfClass:NSString.class] || !launch.length || | |
| 340 | 新增: [launch lengthOfBytesUsingEncoding:NSUTF8StringEncoding] > 4096))) { | |
| 341 | 新增: reply(fd, "ERR\n"); | |
| 342 | 新增: return; | |
| 343 | 新增: } | |
| 344 | 新增: struct stat st; | |
| 345 | 新增: char name[PATH_MAX]; | |
| 346 | 新增: if (fstat(tty, &st) || !S_ISCHR(st.st_mode) || st.st_uid != uid || | |
| 347 | 新增: ttyname_r(tty, name, sizeof(name)) || strncmp(name, "/dev/ttys", 9) || !isatty(tty)) { | |
| 348 | 新增: reply(fd, "ERR\n"); | |
| 349 | 新增: return; | |
| 350 | 新增: } | |
| 351 | 新增: __block NSString *identity; | |
| 352 | 新增: dispatch_sync(dispatch_get_main_queue(), ^{ | |
| 353 | 新增: identity = self->_ready[project]; | |
| 354 | 新增: }); | |
| 355 | 新增: if (!identity || ![identity isEqual:mountID(project)]) { | |
| 356 | 新增: reply(fd, "ERR\n"); | |
| 357 | 新增: return; | |
| 358 | 新增: } | |
| 359 | 新增: NSString *exe = NSBundle.mainBundle.executableURL.path; | |
| 360 | 新增: char *argv[] = {(char *)exe.fileSystemRepresentation, "--child", | |
| 361 | 新增: (char *)project.fileSystemRepresentation, (char *)action.UTF8String, | |
| 362 | 新增: claude ? (char *)launch.UTF8String : NULL, NULL}; | |
| 363 | 新增: posix_spawn_file_actions_t files; | |
| 364 | 新增: posix_spawn_file_actions_init(&files); | |
| 365 | 新增: posix_spawn_file_actions_adddup2(&files, tty, 3); | |
| 366 | 新增: posix_spawnattr_t attr; | |
| 367 | 新增: posix_spawnattr_init(&attr); | |
| 368 | 新增: posix_spawnattr_setflags(&attr, POSIX_SPAWN_CLOEXEC_DEFAULT); | |
| 369 | 新增: pid_t pid; | |
| 370 | 新增: int err = posix_spawn(&pid, argv[0], &files, &attr, argv, environ); | |
| 371 | 新增: posix_spawnattr_destroy(&attr); | |
| 372 | 新增: posix_spawn_file_actions_destroy(&files); | |
| 373 | 新增: if (err) { | |
| 374 | 新增: reply(fd, "ERR\n"); | |
| 375 | 新增: return; | |
| 376 | 新增: } | |
| 377 | 新增: reply(fd, "OK\n"); | |
| 378 | 新增: for (;;) { | |
| 379 | 新增: int childStatus; | |
| 380 | 新增: pid_t done = waitpid(pid, &childStatus, WNOHANG); | |
| 381 | 新增: if (done == pid || (done < 0 && errno != EINTR)) | |
| 382 | 新增: break; | |
| 383 | 新增: struct pollfd pollfd = {fd, POLLIN, 0}; | |
| 384 | 新增: if (poll(&pollfd, 1, 500) > 0 || ![identity isEqual:mountID(project)]) { | |
| 385 | 新增: kill(pid, SIGHUP); | |
| 386 | 新增: kill(-pid, SIGHUP); | |
| 387 | 新增: for (int i = 0; i < 15; i++) { | |
| 388 | 新增: if (waitpid(pid, &childStatus, WNOHANG) == pid) | |
| 389 | 新增: return; | |
| 390 | 新增: usleep(20000); | |
| 391 | 新增: } | |
| 392 | 新增: kill(pid, SIGKILL); | |
| 393 | 新增: kill(-pid, SIGKILL); | |
| 394 | 新增: waitpid(pid, &childStatus, 0); | |
| 395 | 新增: break; | |
| 396 | 新增: } | |
| 397 | 新增: } | |
| 398 | 新增: } @finally { | |
| 399 | 新增: if (tty >= 0) | |
| 400 | 新增: close(tty); | |
| 401 | 新增: } | |
| 402 | 新增:} | |
| 403 | 新增:- (void)panel:(id)sender didChangeToDirectoryURL:(NSURL *)url { | |
| 404 | 新增: // The host offered exactly one mounted project, and must never preview | |
| 405 | 新增: // guest directories reached through the dialog's sidebar. | |
| 406 | 新增: if (sender == _panel && _requesting && url && ![url.URLByStandardizingPath.path isEqual:_requesting]) | |
| 407 | 新增: [_panel cancel:nil]; | |
| 408 | 新增:} | |
| 409 | 新增:@end | |
| 410 | 新增: | |
| 411 | 新增:static int probeCLI(int argc, char **argv) { | |
| 412 | 新增: if (argc != 5) | |
| 413 | 新增: return 2; | |
| 414 | 新增: struct sockaddr_un address; | |
| 415 | 新增: if (!addressForSocket(&address)) | |
| 416 | 新增: return 1; | |
| 417 | 新增: int fd = socket(AF_UNIX, SOCK_STREAM, 0); | |
| 418 | 新增: if (fd < 0) | |
| 419 | 新增: return 1; | |
| 420 | 新增: struct timeval wait = {4, 0}; | |
| 421 | 新增: setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, &wait, sizeof(wait)); | |
| 422 | 新增: if (connect(fd, (struct sockaddr *)&address, sizeof(address))) { | |
| 423 | 新增: close(fd); | |
| 424 | 新增: return 1; | |
| 425 | 新增: } | |
| 426 | 新增: uid_t peer; | |
| 427 | 新增: gid_t group; | |
| 428 | 新增: if (getpeereid(fd, &peer, &group) || peer != getuid()) { | |
| 429 | 新增: close(fd); | |
| 430 | 新增: return 1; | |
| 431 | 新增: } | |
| 432 | 新增: NSData *j = [NSJSONSerialization dataWithJSONObject:@{ | |
| 433 | 新增: @"action" : @"probe", | |
| 434 | 新增: @"path" : @(argv[2]), | |
| 435 | 新增: @"file" : @(argv[3]), | |
| 436 | 新增: @"expected" : @(argv[4]) | |
| 437 | 新增: } | |
| 438 | 新增: options:0 | |
| 439 | 新增: error:nil]; | |
| 440 | 新增: BOOL ok = writeAll(fd, j.bytes, j.length) && writeAll(fd, "\n", 1); | |
| 441 | 新增: FILE *f = fdopen(fd, "r"); | |
| 442 | 新增: if (!f) { | |
| 443 | 新增: close(fd); | |
| 444 | 新增: return 1; | |
| 445 | 新增: } | |
| 446 | 新增: char line[32] = {0}; | |
| 447 | 新增: if (!ok || !fgets(line, sizeof(line), f)) { | |
| 448 | 新增: fclose(f); | |
| 449 | 新增: return 1; | |
| 450 | 新增: } | |
| 451 | 新增: fclose(f); | |
| 452 | 新增: if (!strcmp(line, "OK\n")) { | |
| 453 | 新增: puts("OK"); | |
| 454 | 新增: return 0; | |
| 455 | 新增: } | |
| 456 | 新增: if (!strcmp(line, "PENDING\n")) { | |
| 457 | 新增: puts("PENDING"); | |
| 458 | 新增: return 75; | |
| 459 | 新增: } | |
| 460 | 新增: return 1; | |
| 461 | 新增:} | |
| 462 | 新增: | |
| 463 | 新增:int main(int argc, char **argv) { | |
| 464 | 新增: @autoreleasepool { | |
| 465 | 新增: if (argc > 1 && !strcmp(argv[1], "probe")) | |
| 466 | 新增: return probeCLI(argc, argv); | |
| 467 | 新增: if ((argc == 4 || (argc == 5 && !strcmp(argv[3], "claude"))) && !strcmp(argv[1], "--child")) { | |
| 468 | 新增: if (!mountID(@(argv[2])) || setsid() < 0 || ioctl(3, TIOCSCTTY, 0) < 0) | |
| 469 | 新增: return 1; | |
| 470 | 新增: for (int i = 0; i < 3; i++) | |
| 471 | 新增: if (dup2(3, i) < 0) | |
| 472 | 新增: return 1; | |
| 473 | 新增: close(3); | |
| 474 | 新增: signal(SIGPIPE, SIG_DFL); | |
| 475 | 新增: if (chdir(argv[2])) | |
| 476 | 新增: return 1; | |
| 477 | 新增: setenv("TERM", "xterm-256color", 1); | |
| 478 | 新增: setenv("PWD", argv[2], 1); | |
| 479 | 新增: setenv("PATH", "/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin", 1); | |
| 480 | 新增: if (argc == 5) { | |
| 481 | 新增: execl("/usr/local/libexec/cage-cli/bin/python3", "python3", "-I", | |
| 482 | 新增: "/usr/local/libexec/cage-cli/macos-cli.py", "macos-launch", argv[4], (char *)NULL); | |
| 483 | 新增: return 1; | |
| 484 | 新增: } | |
| 485 | 新增: if (!strcmp(argv[3], "terminal")) | |
| 486 | 新增: execl("/bin/zsh", "-zsh", (char *)NULL); | |
| 487 | 新增: if (!strcmp(argv[3], "editor")) | |
| 488 | 新增: execl("/usr/local/libexec/cage-macos-editor", "cage-macos-editor", (char *)NULL); | |
| 489 | 新增: return 1; | |
| 490 | 新增: } | |
| 491 | 新增: if (argc != 1) | |
| 492 | 新增: return 2; | |
| 493 | 新增: signal(SIGPIPE, SIG_IGN); | |
| 494 | 新增: umask(0077); | |
| 495 | 新增: NSApplication *app = NSApplication.sharedApplication; | |
| 496 | 新增: ProjectAccess *delegate = [[ProjectAccess alloc] init]; | |
| 497 | 新增: app.delegate = delegate; | |
| 498 | 新增: [app setActivationPolicy:NSApplicationActivationPolicyAccessory]; | |
| 499 | 新增: [app run]; | |
| 500 | 新增: return 0; | |
| 501 | 新增: } | |
| 502 | 新增:} | |
| @@ -0,0 +1,80 @@ | ||
| 1 | 新增:// Only a currently pending panel, attested by the installed project access | |
| 2 | 新增:// agent and addressed by the host's active project grant, may be displayed. | |
| 3 | 新增:import AppKit | |
| 4 | 新增:import ScreenCaptureKit | |
| 5 | 新增:import Security | |
| 6 | 新增: | |
| 7 | 新增:struct ProjectPanel: Decodable, Equatable { | |
| 8 | 新增: let path, nonce: String | |
| 9 | 新增: let pid: pid_t | |
| 10 | 新增: let windowNumber: CGWindowID | |
| 11 | 新增:} | |
| 12 | 新增: | |
| 13 | 新增:private func matchesInstalledProjectApp(pid: pid_t) -> Bool { | |
| 14 | 新增: let path = "/Applications/CageProjectAccess.app" | |
| 15 | 新增: guard NSRunningApplication(processIdentifier: pid)?.bundleURL?.path == path else { return false } | |
| 16 | 新增: let url = URL(fileURLWithPath: path) | |
| 17 | 新增: var dynamic: SecCode?, installed: SecStaticCode?, running: SecStaticCode?, requirement: SecRequirement? | |
| 18 | 新增: let attributes = [kSecGuestAttributePid: pid] as CFDictionary | |
| 19 | 新增: var st = stat() | |
| 20 | 新增: guard lstat(path, &st) == 0, st.st_uid == 0, st.st_mode & 0o022 == 0, | |
| 21 | 新增: SecRequirementCreateWithString(#"identifier "dev.cage.guest.project-access""# as CFString, [], &requirement) == errSecSuccess, | |
| 22 | 新增: let requirement, | |
| 23 | 新增: SecCodeCopyGuestWithAttributes(nil, attributes, [], &dynamic) == errSecSuccess, let dynamic, | |
| 24 | 新增: SecCodeCheckValidity(dynamic, [], requirement) == errSecSuccess, | |
| 25 | 新增: SecCodeCopyStaticCode(dynamic, [], &running) == errSecSuccess, let running, | |
| 26 | 新增: SecStaticCodeCreateWithPath(url as CFURL, [], &installed) == errSecSuccess, let installed, | |
| 27 | 新增: SecStaticCodeCheckValidity(installed, [], requirement) == errSecSuccess else { return false } | |
| 28 | 新增: func hash(_ code: SecStaticCode) -> Data? { | |
| 29 | 新增: var info: CFDictionary? | |
| 30 | 新增: guard SecCodeCopySigningInformation(code, SecCSFlags(rawValue: kSecCSSigningInformation), &info) == errSecSuccess else { return nil } | |
| 31 | 新增: return (info as? [String: Any])?[kSecCodeInfoUnique as String] as? Data | |
| 32 | 新增: } | |
| 33 | 新增: guard let digest = hash(installed) else { return false } | |
| 34 | 新增: return digest == hash(running) | |
| 35 | 新增:} | |
| 36 | 新增: | |
| 37 | 新增:func pendingProjectPanel(_ path: String) throws -> ProjectPanel { | |
| 38 | 新增: let missing = Failure(7, "no_project_panel") | |
| 39 | 新增: let directory = URL(fileURLWithPath: NSHomeDirectory()).appendingPathComponent("Cage/Projects", isDirectory: true) | |
| 40 | 新增: let leaf = (path as NSString).lastPathComponent | |
| 41 | 新增: guard leaf.range(of: "^[a-f0-9]{24}$", options: .regularExpression) != nil, | |
| 42 | 新增: path == directory.appendingPathComponent(leaf).path else { throw missing } | |
| 43 | 新增: var addr = sockaddr_un() | |
| 44 | 新增: addr.sun_family = sa_family_t(AF_UNIX) | |
| 45 | 新增: let socketPath = NSHomeDirectory() + "/Library/Application Support/Cage/project-terminal.sock" | |
| 46 | 新增: let maxPath = MemoryLayout.size(ofValue: addr.sun_path) | |
| 47 | 新增: guard socketPath.utf8.count < maxPath else { throw missing } | |
| 48 | 新增: withUnsafeMutableBytes(of: &addr.sun_path) { dst in socketPath.utf8CString.withUnsafeBytes { dst.copyBytes(from: $0) } } | |
| 49 | 新增: let fd = socket(AF_UNIX, SOCK_STREAM, 0) | |
| 50 | 新增: guard fd >= 0 else { throw missing } | |
| 51 | 新增: let file = FileHandle(fileDescriptor: fd, closeOnDealloc: true) | |
| 52 | 新增: let connected = withUnsafePointer(to: &addr) { ptr in | |
| 53 | 新增: ptr.withMemoryRebound(to: sockaddr.self, capacity: 1) { connect(fd, $0, socklen_t(MemoryLayout<sockaddr_un>.size)) } | |
| 54 | 新增: } | |
| 55 | 新增: var user = uid_t(), group = gid_t(), peer = pid_t(), len = socklen_t(MemoryLayout<pid_t>.size) | |
| 56 | 新增: guard connected == 0, getpeereid(fd, &user, &group) == 0, user == geteuid(), | |
| 57 | 新增: getsockopt(fd, SOL_LOCAL, LOCAL_PEERPID, &peer, &len) == 0, matchesInstalledProjectApp(pid: peer) else { throw missing } | |
| 58 | 新增: var timeout = timeval(tv_sec: 2, tv_usec: 0) | |
| 59 | 新增: setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, &timeout, socklen_t(MemoryLayout.size(ofValue: timeout))) | |
| 60 | 新增: var request = try JSONSerialization.data(withJSONObject: ["action":"panel", "path":path]) | |
| 61 | 新增: request.append(10) | |
| 62 | 新增: try file.write(contentsOf: request) | |
| 63 | 新增: var body = Data() | |
| 64 | 新增: while !body.contains(10), body.count < 4096, let chunk = try file.read(upToCount: 4096 - body.count), !chunk.isEmpty { body.append(chunk) } | |
| 65 | 新增: guard let result = try? JSONDecoder().decode(ProjectPanel.self, from: body), result.path == path, result.pid == peer, | |
| 66 | 新增: result.windowNumber > 0, UUID(uuidString: result.nonce) != nil else { throw missing } | |
| 67 | 新增: return result | |
| 68 | 新增:} | |
| 69 | 新增: | |
| 70 | 新增:@MainActor | |
| 71 | 新增:func visibleProjectPanel(_ panel: ProjectPanel) async throws -> SCWindow { | |
| 72 | 新增: guard CGPreflightScreenCaptureAccess() else { throw Failure(6, "project_screen_permission") } | |
| 73 | 新增: let candidates = try await SCShareableContent.excludingDesktopWindows(true, onScreenWindowsOnly: true) | |
| 74 | 新增: guard let window = candidates.windows.first(where: { $0.windowID == panel.windowNumber && $0.isOnScreen }), | |
| 75 | 新增: let owner = window.owningApplication, NSWorkspace.shared.frontmostApplication?.processIdentifier == panel.pid, | |
| 76 | 新增: owner.processID == panel.pid, owner.bundleIdentifier == "dev.cage.guest.project-access" else { | |
| 77 | 新增: throw Failure(7, "no_project_panel") | |
| 78 | 新增: } | |
| 79 | 新增: return window | |
| 80 | 新增:} | |
| @@ -0,0 +1,168 @@ | ||
| 1 | 新增:// Guest-side terminal client. The signed-in helper owns the selected folder's | |
| 2 | 新增:// security scope. It gives a login shell our new slave PTY, while SSH owns | |
| 3 | 新增:// the outer terminal. The outer controlling terminal never changes owners. | |
| 4 | 新增:#import <Foundation/Foundation.h> | |
| 5 | 新增:#include <sys/ioctl.h> | |
| 6 | 新增:#include <sys/socket.h> | |
| 7 | 新增:#include <sys/stat.h> | |
| 8 | 新增:#include <sys/un.h> | |
| 9 | 新增:#include <util.h> | |
| 10 | 新增:#include <poll.h> | |
| 11 | 新增:#include <signal.h> | |
| 12 | 新增:#include <fcntl.h> | |
| 13 | 新增:#include <errno.h> | |
| 14 | 新增:#include <stdio.h> | |
| 15 | 新增:#include <string.h> | |
| 16 | 新增:#include <unistd.h> | |
| 17 | 新增: | |
| 18 | 新增:static volatile sig_atomic_t signalWrite = -1; | |
| 19 | 新增:static struct termios original; | |
| 20 | 新增:static int changedTerminal; | |
| 21 | 新增: | |
| 22 | 新增:static void restoreTerminal(void) { | |
| 23 | 新增: if (changedTerminal) tcsetattr(STDIN_FILENO, TCSANOW, &original); | |
| 24 | 新增:} | |
| 25 | 新增: | |
| 26 | 新增:static void signalHandler(int number) { | |
| 27 | 新增: int saved = errno; | |
| 28 | 新增: unsigned char value = number; | |
| 29 | 新增: if (signalWrite >= 0) (void)write(signalWrite, &value, 1); | |
| 30 | 新增: errno = saved; | |
| 31 | 新增:} | |
| 32 | 新增: | |
| 33 | 新增:static int writeAll(int fd, const void *data, size_t size) { | |
| 34 | 新增: const unsigned char *bytes = data; | |
| 35 | 新增: while (size) { | |
| 36 | 新增: ssize_t n = write(fd, bytes, size); | |
| 37 | 新增: if (n < 0 && errno == EINTR) continue; | |
| 38 | 新增: if (n <= 0) return -1; | |
| 39 | 新增: bytes += n; | |
| 40 | 新增: size -= (size_t)n; | |
| 41 | 新增: } | |
| 42 | 新增: return 0; | |
| 43 | 新增:} | |
| 44 | 新增: | |
| 45 | 新增:static int sendTerminal(int control, int slave, NSData *request) { | |
| 46 | 新增: struct iovec iov = {(void *)request.bytes, request.length}; | |
| 47 | 新增: union { struct cmsghdr align; char bytes[CMSG_SPACE(sizeof(int))]; } rights = {0}; | |
| 48 | 新增: struct msghdr msg = {0}; | |
| 49 | 新增: msg.msg_iov = &iov; | |
| 50 | 新增: msg.msg_iovlen = 1; | |
| 51 | 新增: msg.msg_control = rights.bytes; | |
| 52 | 新增: msg.msg_controllen = sizeof(rights.bytes); | |
| 53 | 新增: struct cmsghdr *header = CMSG_FIRSTHDR(&msg); | |
| 54 | 新增: header->cmsg_level = SOL_SOCKET; | |
| 55 | 新增: header->cmsg_type = SCM_RIGHTS; | |
| 56 | 新增: header->cmsg_len = CMSG_LEN(sizeof(int)); | |
| 57 | 新增: memcpy(CMSG_DATA(header), &slave, sizeof(slave)); | |
| 58 | 新增: ssize_t n; | |
| 59 | 新增: do { n = sendmsg(control, &msg, 0); } while (n < 0 && errno == EINTR); | |
| 60 | 新增: if (n <= 0) return -1; | |
| 61 | 新增: return writeAll(control, (const unsigned char *)request.bytes + n, request.length - (size_t)n); | |
| 62 | 新增:} | |
| 63 | 新增: | |
| 64 | 新增:static int relay(int control, int master, int signals) { | |
| 65 | 新增: struct pollfd fds[] = {{STDIN_FILENO, POLLIN, 0}, {master, POLLIN, 0}, | |
| 66 | 新增: {signals, POLLIN, 0}, {control, POLLIN, 0}}; | |
| 67 | 新增: char buffer[16384]; | |
| 68 | 新增: for (;;) { | |
| 69 | 新增: if (poll(fds, 4, -1) < 0) { | |
| 70 | 新增: if (errno == EINTR) continue; | |
| 71 | 新增: return 1; | |
| 72 | 新增: } | |
| 73 | 新增: if (fds[2].revents) { | |
| 74 | 新增: ssize_t n = read(signals, buffer, sizeof(buffer)); | |
| 75 | 新增: for (ssize_t j = 0; j < n; j++) { | |
| 76 | 新增: if (buffer[j] != SIGWINCH) return 0; | |
| 77 | 新增: } | |
| 78 | 新增: struct winsize size; | |
| 79 | 新增: if (ioctl(STDIN_FILENO, TIOCGWINSZ, &size) == 0) | |
| 80 | 新增: ioctl(master, TIOCSWINSZ, &size); | |
| 81 | 新增: } | |
| 82 | 新增: if (fds[1].revents) { | |
| 83 | 新增: ssize_t n = read(master, buffer, sizeof(buffer)); | |
| 84 | 新增: if (n < 0 && errno == EINTR) continue; | |
| 85 | 新增: if (n <= 0) return (n == 0 || errno == EIO) ? 0 : 1; | |
| 86 | 新增: if (writeAll(STDOUT_FILENO, buffer, (size_t)n) < 0) return 1; | |
| 87 | 新增: // The shell can exit just after printing. Drain the PTY before | |
| 88 | 新增: // treating an accompanying control-socket close as terminal EOF. | |
| 89 | 新增: if (fds[3].revents) continue; | |
| 90 | 新增: } | |
| 91 | 新增: if (fds[3].revents) return 0; | |
| 92 | 新增: if (fds[0].revents) { | |
| 93 | 新增: ssize_t n = read(STDIN_FILENO, buffer, sizeof(buffer)); | |
| 94 | 新增: if (n < 0 && errno == EINTR) continue; | |
| 95 | 新增: if (n <= 0) return 0; | |
| 96 | 新增: if (writeAll(master, buffer, (size_t)n) < 0) return 1; | |
| 97 | 新增: } | |
| 98 | 新增: } | |
| 99 | 新增:} | |
| 100 | 新增: | |
| 101 | 新增:int main(int argc, char **argv) { | |
| 102 | 新增: @autoreleasepool { | |
| 103 | 新增: BOOL editor = argc == 3 && strcmp(argv[1], "--editor") == 0; | |
| 104 | 新增: BOOL claude = argc == 4 && strcmp(argv[1], "--claude") == 0; | |
| 105 | 新增: BOOL interactive = isatty(STDIN_FILENO) && isatty(STDOUT_FILENO); | |
| 106 | 新增: if ((argc != 2 && !editor && !claude) || (!editor && !interactive)) { | |
| 107 | 新增: fprintf(stderr, "A project directory and an interactive guest terminal are required.\n"); | |
| 108 | 新增: return 2; | |
| 109 | 新增: } | |
| 110 | 新增: NSString *project = [NSString stringWithUTF8String:argv[editor || claude ? 2 : 1]]; | |
| 111 | 新增: if (!project || !project.isAbsolutePath) return 2; | |
| 112 | 新增: NSString *path = [NSHomeDirectory() stringByAppendingPathComponent:@"Library/Application Support/Cage/project-terminal.sock"]; | |
| 113 | 新增: struct sockaddr_un addr = {.sun_family = AF_UNIX}; | |
| 114 | 新增: if (strlcpy(addr.sun_path, path.fileSystemRepresentation, sizeof(addr.sun_path)) >= sizeof(addr.sun_path)) return 2; | |
| 115 | 新增: addr.sun_len = SUN_LEN(&addr); | |
| 116 | 新增: int control = socket(AF_UNIX, SOCK_STREAM, 0); | |
| 117 | 新增: if (control < 0 || connect(control, (struct sockaddr *)&addr, addr.sun_len) != 0) { | |
| 118 | 新增: fprintf(stderr, "The project helper is unavailable in this guest login session.\n"); | |
| 119 | 新增: return 1; | |
| 120 | 新增: } | |
| 121 | 新增: uid_t peer; gid_t group; | |
| 122 | 新增: if (getpeereid(control, &peer, &group) < 0 || peer != geteuid()) { | |
| 123 | 新增: fprintf(stderr, "The project helper belongs to a different guest user.\n"); | |
| 124 | 新增: return 1; | |
| 125 | 新增: } | |
| 126 | 新增: signal(SIGPIPE, SIG_IGN); | |
| 127 | 新增: int master, slave; | |
| 128 | 新增: struct winsize size = {.ws_row = 32, .ws_col = 100}; | |
| 129 | 新增: if (interactive && (tcgetattr(STDIN_FILENO, &original) < 0 || ioctl(STDIN_FILENO, TIOCGWINSZ, &size) < 0)) return 1; | |
| 130 | 新增: // The guest browser launches its fixed editor over pipes. Only the | |
| 131 | 新增: // helper's child needs a controlling terminal in that case. | |
| 132 | 新增: if (openpty(&master, &slave, NULL, interactive ? &original : NULL, &size) != 0 || fchmod(slave, 0600) < 0) return 1; | |
| 133 | 新增: NSMutableDictionary *operation = [@{@"action": editor ? @"editor" : claude ? @"claude" : @"terminal", @"path": project} mutableCopy]; | |
| 134 | 新增: if (claude) { | |
| 135 | 新增: NSString *launch = [NSString stringWithUTF8String:argv[3]]; | |
| 136 | 新增: if (!launch || [launch lengthOfBytesUsingEncoding:NSUTF8StringEncoding] > 4096) return 2; | |
| 137 | 新增: operation[@"launch"] = launch; | |
| 138 | 新增: } | |
| 139 | 新增: NSMutableData *request = [[NSJSONSerialization dataWithJSONObject:operation options:0 error:nil] mutableCopy]; | |
| 140 | 新增: [request appendBytes:"\n" length:1]; | |
| 141 | 新增: if (sendTerminal(control, slave, request) < 0) return 1; | |
| 142 | 新增: close(slave); | |
| 143 | 新增: char reply[3]; | |
| 144 | 新增: if (recv(control, reply, sizeof(reply), MSG_WAITALL) != sizeof(reply) || memcmp(reply, "OK\n", 3) != 0) { | |
| 145 | 新增: fprintf(stderr, "The guest user has not approved this mounted project.\n"); | |
| 146 | 新增: return 1; | |
| 147 | 新增: } | |
| 148 | 新增: int signals[2]; | |
| 149 | 新增: if (pipe(signals) < 0 || fcntl(signals[1], F_SETFL, O_NONBLOCK) < 0) return 1; | |
| 150 | 新增: signalWrite = signals[1]; | |
| 151 | 新增: const int events[] = {SIGWINCH, SIGHUP, SIGINT, SIGTERM, SIGQUIT}; | |
| 152 | 新增: struct sigaction action = {.sa_handler = signalHandler}; | |
| 153 | 新增: sigemptyset(&action.sa_mask); | |
| 154 | 新增: for (size_t i = 0; i < sizeof(events)/sizeof(events[0]); i++) sigaction(events[i], &action, NULL); | |
| 155 | 新增: if (interactive) { | |
| 156 | 新增: struct termios raw = original; | |
| 157 | 新增: cfmakeraw(&raw); | |
| 158 | 新增: atexit(restoreTerminal); | |
| 159 | 新增: if (tcsetattr(STDIN_FILENO, TCSANOW, &raw) < 0) return 1; | |
| 160 | 新增: changedTerminal = 1; | |
| 161 | 新增: } | |
| 162 | 新增: if (ioctl(STDIN_FILENO, TIOCGWINSZ, &size) == 0) ioctl(master, TIOCSWINSZ, &size); | |
| 163 | 新增: int code = relay(control, master, signals[0]); | |
| 164 | 新增: close(master); | |
| 165 | 新增: close(control); | |
| 166 | 新增: return code; | |
| 167 | 新增: } | |
| 168 | 新增:} | |
| @@ -0,0 +1,170 @@ | ||
| 1 | 新增:// The only administrator created by the native installer. The durable receipt | |
| 2 | 新增:// is root-only and binds both the directory service GUID and the numeric uid. | |
| 3 | 新增:#import <Foundation/Foundation.h> | |
| 4 | 新增:#import <OpenDirectory/OpenDirectory.h> | |
| 5 | 新增:#include <pwd.h> | |
| 6 | 新增:#include <sys/file.h> | |
| 7 | 新增:#include <sys/stat.h> | |
| 8 | 新增:#include <sys/sysctl.h> | |
| 9 | 新增:#include <unistd.h> | |
| 10 | 新增: | |
| 11 | 新增:static NSString *const directory = @"/var/db/cage-initial-setup"; | |
| 12 | 新增:static NSString *const setup = @"cagesetup"; | |
| 13 | 新增: | |
| 14 | 新增:static void require(BOOL ok, const char *reason) { | |
| 15 | 新增: if (!ok) { fprintf(stderr, "%s\n", reason); exit(1); } | |
| 16 | 新增:} | |
| 17 | 新增: | |
| 18 | 新增:static NSArray *users(ODNode *node, NSString *name) { | |
| 19 | 新增: ODQuery *q = [ODQuery queryWithNode:node forRecordTypes:kODRecordTypeUsers | |
| 20 | 新增: attribute:kODAttributeTypeRecordName matchType:kODMatchEqualTo queryValues:name | |
| 21 | 新增: returnAttributes:@[kODAttributeTypeGUID, kODAttributeTypeUniqueID] maximumResults:2 error:NULL]; | |
| 22 | 新增: NSArray *results = [q resultsAllowingPartial:NO error:NULL]; | |
| 23 | 新增: require(results != nil && results.count <= 1, "Cannot identify the local guest user."); | |
| 24 | 新增: return results; | |
| 25 | 新增:} | |
| 26 | 新增: | |
| 27 | 新增:static void save(NSDictionary *d, NSURL *file) { | |
| 28 | 新增: NSData *data = [NSJSONSerialization dataWithJSONObject:d options:0 error:NULL]; | |
| 29 | 新增: require(data && [data writeToURL:file options:NSDataWritingAtomic error:NULL], "Cannot persist the guest setup receipt."); | |
| 30 | 新增:} | |
| 31 | 新增: | |
| 32 | 新增:static BOOL member(ODRecord *group, ODRecord *user) { | |
| 33 | 新增: NSError *err = nil; | |
| 34 | 新增: BOOL result = [group isMemberRecord:user error:&err]; | |
| 35 | 新增: require(!err, "Cannot inspect guest administrator privileges."); | |
| 36 | 新增: return result; | |
| 37 | 新增:} | |
| 38 | 新增: | |
| 39 | 新增:static BOOL disabled(ODRecord *record) { | |
| 40 | 新增: NSError *error = nil; | |
| 41 | 新增: BOOL allowed = [record authenticationAllowedAndReturnError:&error]; | |
| 42 | 新增: return !allowed && [error.domain isEqual:ODFrameworkErrorDomain] && error.code == kODErrorCredentialsAccountDisabled; | |
| 43 | 新增:} | |
| 44 | 新增: | |
| 45 | 新增:static void retire(ODNode *node, ODRecord *admin, ODRecord *record) { | |
| 46 | 新增: if (member(admin, record)) require([admin removeMemberRecord:record error:NULL], "Cannot revoke setup administrator privileges."); | |
| 47 | 新增: require(!member(admin, record), "The setup user still has administrator privileges."); | |
| 48 | 新增: if (!disabled(record)) { | |
| 49 | 新增: // Invalidate the initial guest password before disabling the account. | |
| 50 | 新增: // This replacement is never persisted or exposed to a caller. | |
| 51 | 新增: NSString *replacement = [@"Z9!" stringByAppendingString:NSUUID.UUID.UUIDString]; | |
| 52 | 新增: require([record changePassword:nil toPassword:replacement error:NULL], "Cannot clear the temporary guest credential."); | |
| 53 | 新增: require([record setValue:@"/usr/bin/false" forAttribute:kODAttributeTypeUserShell error:NULL], "Cannot close the temporary login shell."); | |
| 54 | 新增: NSTask *task = [[NSTask alloc] init]; | |
| 55 | 新增: task.executableURL = [NSURL fileURLWithPath:@"/usr/bin/pwpolicy"]; | |
| 56 | 新增: task.arguments = @[@"-n", @"/Local/Default", @"-u", setup, @"-disableuser"]; | |
| 57 | 新增: require([task launchAndReturnError:NULL], "Cannot invoke the guest account policy tool."); | |
| 58 | 新增: [task waitUntilExit]; | |
| 59 | 新增: require(task.terminationStatus == 0, "Cannot disable the temporary guest user."); | |
| 60 | 新增: } | |
| 61 | 新增: ODRecord *current = users(node, setup).firstObject; | |
| 62 | 新增: require(current && disabled(current) && !member(admin, current) && | |
| 63 | 新增: [[current valuesForAttribute:kODAttributeTypeUserShell error:NULL].firstObject isEqual:@"/usr/bin/false"], | |
| 64 | 新增: "The temporary guest login remains available."); | |
| 65 | 新增:} | |
| 66 | 新增: | |
| 67 | 新增:int main(int argc, const char **argv) { | |
| 68 | 新增: @autoreleasepool { | |
| 69 | 新增: BOOL prepare = argc == 3 && strcmp(argv[1], "prepare") == 0; | |
| 70 | 新增: require(prepare || argc == 1, "Invalid first setup operation."); | |
| 71 | 新增: char model[128] = {0}; | |
| 72 | 新增: size_t size = sizeof(model); | |
| 73 | 新增: struct stat st; | |
| 74 | 新增: require(getuid() == 0 && sysctlbyname("hw.model", model, &size, NULL, 0) == 0 && | |
| 75 | 新增: strncmp(model, "VirtualMac", 10) == 0 && lstat("/var/db/cage-guest-os", &st) == 0 && | |
| 76 | 新增: S_ISREG(st.st_mode) && st.st_uid == 0 && !(st.st_mode & 022) && | |
| 77 | 新增: [[NSString stringWithContentsOfFile:@"/var/db/cage-guest-os" encoding:NSUTF8StringEncoding error:NULL] isEqual:@"macos\n"], | |
| 78 | 新增: "Run as root in the selected Cage virtual Mac."); | |
| 79 | 新增: umask(077); | |
| 80 | 新增: if (prepare && mkdir(directory.fileSystemRepresentation, 0700) != 0) require(errno == EEXIST, "Cannot create private receipt directory."); | |
| 81 | 新增: require(lstat(directory.fileSystemRepresentation, &st) == 0 && S_ISDIR(st.st_mode) && st.st_uid == 0 && !(st.st_mode & 077), | |
| 82 | 新增: "Invalid private setup directory."); | |
| 83 | 新增: NSString *lockPath = [directory stringByAppendingPathComponent:@"lock"]; | |
| 84 | 新增: int lock = open(lockPath.fileSystemRepresentation, O_NOFOLLOW|O_CREAT|O_RDWR, 0600); | |
| 85 | 新增: require(lock >= 0 && flock(lock, LOCK_EX|LOCK_NB) == 0, "Another first setup operation is running."); | |
| 86 | 新增: NSURL *file = [NSURL fileURLWithPath:[directory stringByAppendingPathComponent:@"account.json"]]; | |
| 87 | 新增: NSData *data = nil; | |
| 88 | 新增: if (lstat(file.fileSystemRepresentation, &st) == 0) { | |
| 89 | 新增: require(S_ISREG(st.st_mode) && st.st_uid == 0 && !(st.st_mode & 077) && st.st_size > 0 && st.st_size <= 2048, | |
| 90 | 新增: "Invalid guest setup receipt."); | |
| 91 | 新增: data = [NSData dataWithContentsOfURL:file]; require(data != nil,"Unreadable guest setup receipt."); | |
| 92 | 新增: } else require(errno == ENOENT && prepare, "Missing guest setup receipt."); | |
| 93 | 新增: ODNode *node = [ODNode nodeWithSession:[ODSession defaultSession] name:@"/Local/Default" error:NULL]; | |
| 94 | 新增: ODRecord *admin = [node recordWithRecordType:kODRecordTypeGroups name:@"admin" attributes:nil error:NULL]; | |
| 95 | 新增: NSString *ordinaryName = @"cage"; | |
| 96 | 新增: ODRecord *ordinary = users(node, ordinaryName).firstObject; | |
| 97 | 新增: require(node && admin && ordinary && !member(admin, ordinary), "The regular Cage user must not be a guest administrator."); | |
| 98 | 新增: ODRecord *record = users(node, setup).firstObject; | |
| 99 | 新增: NSString *install = prepare ? @(argv[2]) : nil; | |
| 100 | 新增: if (prepare) require([[NSUUID alloc] initWithUUIDString:install] != nil, "Invalid fresh guest installation ID."); | |
| 101 | 新增: NSMutableDictionary *receipt; | |
| 102 | 新增: if (data) { | |
| 103 | 新增: receipt = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:NULL]; | |
| 104 | 新增: require([receipt isKindOfClass:NSMutableDictionary.class] && | |
| 105 | 新增: [[NSUUID alloc] initWithUUIDString:receipt[@"guid"]] && [receipt[@"uid"] intValue] >= 502 && | |
| 106 | 新增: [[NSUUID alloc] initWithUUIDString:receipt[@"installation"]] && (!prepare || [receipt[@"installation"] isEqual:install]), | |
| 107 | 新增: "The setup account belongs to a different installation."); | |
| 108 | 新增: } else { | |
| 109 | 新增: require(!record && !getpwnam("cagesetup"), "A user already has the setup name; no account was modified."); | |
| 110 | 新增: int uid = 502; | |
| 111 | 新增: while (uid < 1000 && getpwuid(uid)) uid++; | |
| 112 | 新增: require(uid < 1000, "No free local setup UID."); | |
| 113 | 新增: receipt = [@{@"installation":install, @"guid":NSUUID.UUID.UUIDString, @"uid":@(uid), @"state":@"creating"} mutableCopy]; | |
| 114 | 新增: save(receipt, file); | |
| 115 | 新增: } | |
| 116 | 新增: NSString *uid = [receipt[@"uid"] stringValue]; | |
| 117 | 新增: if (record) { | |
| 118 | 新增: NSString *guid = [record valuesForAttribute:kODAttributeTypeGUID error:NULL].firstObject; | |
| 119 | 新增: NSString *actualUID = [record valuesForAttribute:kODAttributeTypeUniqueID error:NULL].firstObject; | |
| 120 | 新增: require(guid && [guid caseInsensitiveCompare:receipt[@"guid"]] == NSOrderedSame && [actualUID isEqual:uid], | |
| 121 | 新增: "Refusing to modify an unrelated guest user."); | |
| 122 | 新增: } | |
| 123 | 新增: NSString *phase = receipt[@"state"]; | |
| 124 | 新增: require([@[@"creating",@"ready",@"retiring",@"retired"] containsObject:phase], "Unknown guest setup state."); | |
| 125 | 新增: if (prepare) { | |
| 126 | 新增: require([phase isEqual:@"creating"] || [phase isEqual:@"ready"], "Initial setup has already closed."); | |
| 127 | 新增: char buf[258]; | |
| 128 | 新增: require(fgets(buf,sizeof(buf),stdin) != NULL, "Missing virtual Mac login password."); | |
| 129 | 新增: size_t len = strcspn(buf,"\r\n"); | |
| 130 | 新增: require(len >= 8 && len <= 256, "Invalid virtual Mac login password."); | |
| 131 | 新增: NSString *pw = [[NSString alloc] initWithBytes:buf length:len encoding:NSUTF8StringEncoding]; | |
| 132 | 新增: memset_s(buf,sizeof(buf),0,sizeof(buf)); | |
| 133 | 新增: require(pw != nil, "Invalid password encoding."); | |
| 134 | 新增: if (!record) { | |
| 135 | 新增: require([phase isEqual:@"creating"] && !getpwuid([receipt[@"uid"] intValue]), "Setup account disappeared or its UID is in use."); | |
| 136 | 新增: record = [node createRecordWithRecordType:kODRecordTypeUsers name:setup attributes:@{ | |
| 137 | 新增: kODAttributeTypeGUID:@[receipt[@"guid"]], kODAttributeTypeUniqueID:@[uid], | |
| 138 | 新增: kODAttributeTypePrimaryGroupID:@[@"20"], kODAttributeTypeFullName:@[@"Cage Setup"], | |
| 139 | 新增: kODAttributeTypeNFSHomeDirectory:@[@"/var/empty"], kODAttributeTypeUserShell:@[@"/bin/sh"], | |
| 140 | 新增: @"dsAttrTypeNative:IsHidden":@[@"1"] | |
| 141 | 新增: } error:NULL]; | |
| 142 | 新增: require(record != nil, "Cannot create the dedicated temporary guest account."); | |
| 143 | 新增: } | |
| 144 | 新增: if ([phase isEqual:@"creating"]) | |
| 145 | 新增: require([record changePassword:nil toPassword:pw error:NULL], "Cannot initialize the temporary password."); | |
| 146 | 新增: require([record verifyPassword:pw error:NULL], "The stored credential does not match this guest."); | |
| 147 | 新增: // macOS PAM checks /etc/shells even for System Settings authorization. | |
| 148 | 新增: // A hidden admin with /usr/bin/false passes OD password checks but | |
| 149 | 新增: // authorizationhost rejects it during account management. | |
| 150 | 新增: if ([[record valuesForAttribute:kODAttributeTypeUserShell error:NULL].firstObject isEqual:@"/usr/bin/false"]) | |
| 151 | 新增: require([record setValue:@"/bin/sh" forAttribute:kODAttributeTypeUserShell error:NULL], "Cannot repair the temporary account's login shell."); | |
| 152 | 新增: if (!member(admin, record)) require([admin addMemberRecord:record error:NULL], "Cannot grant temporary setup privileges."); | |
| 153 | 新增: require(member(admin, record), "Guest setup privileges were not applied."); | |
| 154 | 新增: receipt[@"state"] = @"ready"; | |
| 155 | 新增: } else { | |
| 156 | 新增: require(![phase isEqual:@"creating"], "The temporary account has not completed setup."); | |
| 157 | 新增: if (![phase isEqual:@"retired"]) { | |
| 158 | 新增: receipt[@"state"] = @"retiring"; save(receipt,file); | |
| 159 | 新增: } | |
| 160 | 新增: // Keep the disabled directory record. Its home is the shared system | |
| 161 | 新增: // directory /var/empty and must never be processed as a deletable home. | |
| 162 | 新增: if (record) retire(node, admin, record); | |
| 163 | 新增: require(!member(admin,ordinary), "The regular Cage user is a guest administrator."); | |
| 164 | 新增: receipt[@"state"] = @"retired"; | |
| 165 | 新增: } | |
| 166 | 新增: save(receipt,file); | |
| 167 | 新增: close(lock); | |
| 168 | 新增: return 0; | |
| 169 | 新增: } | |
| 170 | 新增:} | |
| @@ -0,0 +1,5 @@ | ||
| 1 | 新增:#include <stdbool.h> | |
| 2 | 新增: | |
| 3 | 新增:// Signature of Code-Hex/vz v3.7.1's startVirtualMachineWindow cgo entry. | |
| 4 | 新增:void CageRunSetupBridge(void *machine, void *queue, double width, double height, | |
| 5 | 新增: const char *title, bool controller); | |
| @@ -0,0 +1,47 @@ | ||
| 1 | 新增:#import "macos-setup-bridge.h" | |
| 2 | 新增:#import "macos-setup-view.h" | |
| 3 | 新增: | |
| 4 | 新增:// Build-only QA overlay. Demonstrate handing the actual VM to the main thread | |
| 5 | 新增:// and closing a session. It never publishes a framebuffer or accepts input. | |
| 6 | 新增:void CageRunSetupBridge(void *machine, void *queue, double width, double height, | |
| 7 | 新增: const char *title, bool controller) { | |
| 8 | 新增: (void)width; (void)height; (void)title; (void)controller; | |
| 9 | 新增: @autoreleasepool { | |
| 10 | 新增: if (!NSThread.isMainThread) { | |
| 11 | 新增: fprintf(stderr, "Cage setup probe requires the AppKit main thread\n"); | |
| 12 | 新增: return; | |
| 13 | 新增: } | |
| 14 | 新增: NSApplication *app = [NSApplication sharedApplication]; | |
| 15 | 新增: [app setActivationPolicy:NSApplicationActivationPolicyProhibited]; | |
| 16 | 新增: VZVirtualMachine *vm = (__bridge VZVirtualMachine *)machine; | |
| 17 | 新增: __block BOOL allowed = YES; | |
| 18 | 新增: CageGuestSetupView *setup = [[CageGuestSetupView alloc] initWithMachine:vm | |
| 19 | 新增: size:NSMakeSize(1024, 640) setupAuthorized:^BOOL { return allowed; }]; | |
| 20 | 新增: allowed = NO; | |
| 21 | 新增: BOOL revoked = setup && ![setup snapshotPNG] && ![setup clickAtX:1 y:1] && ![setup scrollAtX:1 y:1 deltaX:0 deltaY:10]; | |
| 22 | 新增: fprintf(stderr, "Cage setup probe: main-thread binding and revocation %s\n", revoked ? "passed" : "failed"); | |
| 23 | 新增: [setup close]; | |
| 24 | 新增: | |
| 25 | 新增: // Preserve Lima's normal shutdown path while AppKit owns its main loop. | |
| 26 | 新增: dispatch_queue_t vmQueue = (__bridge dispatch_queue_t)queue; | |
| 27 | 新增: __block BOOL seenRunning = NO; | |
| 28 | 新增: NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:0.25 repeats:YES block:^(NSTimer *tick) { | |
| 29 | 新增: (void)tick; | |
| 30 | 新增: dispatch_async(vmQueue, ^{ | |
| 31 | 新增: VZVirtualMachineState state = vm.state; | |
| 32 | 新增: if (state == VZVirtualMachineStateRunning) seenRunning = YES; | |
| 33 | 新增: if (seenRunning && (state == VZVirtualMachineStateStopped || state == VZVirtualMachineStateError)) { | |
| 34 | 新增: dispatch_async(dispatch_get_main_queue(), ^{ | |
| 35 | 新增: [app stop:nil]; | |
| 36 | 新增: NSEvent *wake = [NSEvent otherEventWithType:NSEventTypeApplicationDefined | |
| 37 | 新增: location:NSZeroPoint modifierFlags:0 timestamp:0 windowNumber:0 | |
| 38 | 新增: context:nil subtype:0 data1:0 data2:0]; | |
| 39 | 新增: [app postEvent:wake atStart:YES]; | |
| 40 | 新增: }); | |
| 41 | 新增: } | |
| 42 | 新增: }); | |
| 43 | 新增: }]; | |
| 44 | 新增: [app run]; | |
| 45 | 新增: [timer invalidate]; | |
| 46 | 新增: } | |
| 47 | 新增:} | |
| @@ -0,0 +1,22 @@ | ||
| 1 | 新增:#import <AppKit/AppKit.h> | |
| 2 | 新增:#import <Virtualization/Virtualization.h> | |
| 3 | 新增: | |
| 4 | 新增:NS_ASSUME_NONNULL_BEGIN | |
| 5 | 新增: | |
| 6 | 新增:// QA-only adapter for a VM the caller already owns. All calls, including the | |
| 7 | 新增:// authorization check, run on the AppKit main thread. A revoked session closes. | |
| 8 | 新增:@interface CageGuestSetupView : NSObject | |
| 9 | 新增:- (nullable instancetype)initWithMachine:(VZVirtualMachine *)machine | |
| 10 | 新增: size:(NSSize)size | |
| 11 | 新增: setupAuthorized:(BOOL (^)(void))setupAuthorized; | |
| 12 | 新增:- (instancetype)init NS_UNAVAILABLE; | |
| 13 | 新增:- (nullable NSData *)snapshotPNG; | |
| 14 | 新增:- (nullable NSData *)snapshotJPEG; | |
| 15 | 新增:- (BOOL)sendKey:(NSEvent *)event; | |
| 16 | 新增:// Click in the view's logical coordinates, with the origin at its top left. | |
| 17 | 新增:- (BOOL)clickAtX:(CGFloat)x y:(CGFloat)y; | |
| 18 | 新增:- (BOOL)scrollAtX:(CGFloat)x y:(CGFloat)y deltaX:(CGFloat)deltaX deltaY:(CGFloat)deltaY; | |
| 19 | 新增:- (void)close; | |
| 20 | 新增:@end | |
| 21 | 新增: | |
| 22 | 新增:NS_ASSUME_NONNULL_END | |
| @@ -0,0 +1,117 @@ | ||
| 1 | 新增:#import "macos-setup-view.h" | |
| 2 | 新增:#include <math.h> | |
| 3 | 新增: | |
| 4 | 新增:@implementation CageGuestSetupView { | |
| 5 | 新增: NSWindow *_window; | |
| 6 | 新增: VZVirtualMachineView *_view; | |
| 7 | 新增: BOOL (^_authorized)(void); | |
| 8 | 新增:} | |
| 9 | 新增: | |
| 10 | 新增:- (instancetype)initWithMachine:(VZVirtualMachine *)machine | |
| 11 | 新增: size:(NSSize)size | |
| 12 | 新增: setupAuthorized:(BOOL (^)(void))setupAuthorized { | |
| 13 | 新增: if (!NSThread.isMainThread || !machine || !setupAuthorized || !setupAuthorized() || | |
| 14 | 新增: !isfinite(size.width) || !isfinite(size.height) || size.width <= 0 || size.height <= 0) return nil; | |
| 15 | 新增: self = [super init]; | |
| 16 | 新增: if (self) { | |
| 17 | 新增: _authorized = [setupAuthorized copy]; | |
| 18 | 新增: NSRect rect = NSMakeRect(0, 0, size.width, size.height); | |
| 19 | 新增: _window = [[NSWindow alloc] initWithContentRect:rect styleMask:NSWindowStyleMaskBorderless | |
| 20 | 新增: backing:NSBackingStoreBuffered defer:NO]; | |
| 21 | 新增: _window.excludedFromWindowsMenu = YES; | |
| 22 | 新增: _view = [[VZVirtualMachineView alloc] initWithFrame:rect]; | |
| 23 | 新增: _view.virtualMachine = machine; | |
| 24 | 新增: _window.contentView = _view; | |
| 25 | 新增: [_window makeFirstResponder:_view]; | |
| 26 | 新增: } | |
| 27 | 新增: return self; | |
| 28 | 新增:} | |
| 29 | 新增: | |
| 30 | 新增:- (BOOL)canUseView { | |
| 31 | 新增: if (!NSThread.isMainThread) return NO; | |
| 32 | 新增: if (!_view || !_authorized || !_authorized()) { | |
| 33 | 新增: [self close]; | |
| 34 | 新增: return NO; | |
| 35 | 新增: } | |
| 36 | 新增: return YES; | |
| 37 | 新增:} | |
| 38 | 新增: | |
| 39 | 新增:- (NSData *)snapshotType:(NSBitmapImageFileType)type properties:(NSDictionary *)properties { | |
| 40 | 新增: if (![self canUseView]) return nil; | |
| 41 | 新增: NSBitmapImageRep *rep = [_view bitmapImageRepForCachingDisplayInRect:_view.bounds]; | |
| 42 | 新增: if (!rep) return nil; | |
| 43 | 新增: [_view cacheDisplayInRect:_view.bounds toBitmapImageRep:rep]; | |
| 44 | 新增: NSData *data = [rep representationUsingType:type properties:properties]; | |
| 45 | 新增: return [self canUseView] ? data : nil; | |
| 46 | 新增:} | |
| 47 | 新增: | |
| 48 | 新增:- (NSData *)snapshotPNG { return [self snapshotType:NSBitmapImageFileTypePNG properties:@{}]; } | |
| 49 | 新增:- (NSData *)snapshotJPEG { | |
| 50 | 新增: return [self snapshotType:NSBitmapImageFileTypeJPEG properties:@{NSImageCompressionFactor: @0.92}]; | |
| 51 | 新增:} | |
| 52 | 新增: | |
| 53 | 新增:- (BOOL)sendKey:(NSEvent *)event { | |
| 54 | 新增: if (![self canUseView]) return NO; | |
| 55 | 新增: NSEventType kind = event.type; | |
| 56 | 新增: if (kind != NSEventTypeKeyDown && kind != NSEventTypeKeyUp && kind != NSEventTypeFlagsChanged) return NO; | |
| 57 | 新增: BOOL flagsOnly = kind == NSEventTypeFlagsChanged; | |
| 58 | 新增: NSEvent *target = [NSEvent keyEventWithType:kind location:NSZeroPoint modifierFlags:event.modifierFlags | |
| 59 | 新增: timestamp:NSProcessInfo.processInfo.systemUptime windowNumber:_window.windowNumber | |
| 60 | 新增: context:nil characters:flagsOnly ? @"" : event.characters ?: @"" | |
| 61 | 新增: charactersIgnoringModifiers:flagsOnly ? @"" : event.charactersIgnoringModifiers ?: @"" | |
| 62 | 新增: isARepeat:!flagsOnly && event.isARepeat keyCode:event.keyCode]; | |
| 63 | 新增: if (kind == NSEventTypeKeyDown) [_view keyDown:target]; | |
| 64 | 新增: else if (kind == NSEventTypeKeyUp) [_view keyUp:target]; | |
| 65 | 新增: else [_view flagsChanged:target]; | |
| 66 | 新增: return YES; | |
| 67 | 新增:} | |
| 68 | 新增: | |
| 69 | 新增:- (BOOL)clickAtX:(CGFloat)x y:(CGFloat)y { | |
| 70 | 新增: if (![self canUseView]) return NO; | |
| 71 | 新增: NSRect rect = _view.bounds; | |
| 72 | 新增: if (!isfinite(x) || !isfinite(y) || x < 0 || y < 0 || x >= NSWidth(rect) || y >= NSHeight(rect)) return NO; | |
| 73 | 新增: NSPoint point = [_view convertPoint:NSMakePoint(x, NSHeight(rect) - y) toView:nil]; | |
| 74 | 新增: for (NSNumber *type in @[@(NSEventTypeLeftMouseDown), @(NSEventTypeLeftMouseUp)]) { | |
| 75 | 新增: if (![self canUseView]) return NO; | |
| 76 | 新增: NSEvent *event = [NSEvent mouseEventWithType:type.unsignedIntegerValue location:point modifierFlags:0 | |
| 77 | 新增: timestamp:NSProcessInfo.processInfo.systemUptime windowNumber:_window.windowNumber | |
| 78 | 新增: context:nil eventNumber:1 clickCount:1 pressure:1]; | |
| 79 | 新增: if (event.type == NSEventTypeLeftMouseDown) [_view mouseDown:event]; | |
| 80 | 新增: else [_view mouseUp:event]; | |
| 81 | 新增: } | |
| 82 | 新增: return YES; | |
| 83 | 新增:} | |
| 84 | 新增: | |
| 85 | 新增:- (BOOL)scrollAtX:(CGFloat)x y:(CGFloat)y deltaX:(CGFloat)deltaX deltaY:(CGFloat)deltaY { | |
| 86 | 新增: if (![self canUseView]) return NO; | |
| 87 | 新增: NSRect rect = _view.bounds; | |
| 88 | 新增: if (!isfinite(x) || !isfinite(y) || !isfinite(deltaX) || !isfinite(deltaY) || | |
| 89 | 新增: x < 0 || y < 0 || x >= NSWidth(rect) || y >= NSHeight(rect) || | |
| 90 | 新增: fabs(deltaX) > 4096 || fabs(deltaY) > 4096) return NO; | |
| 91 | 新增: NSPoint point = [_view convertPoint:NSMakePoint(x, NSHeight(rect) - y) toView:nil]; | |
| 92 | 新增: NSEvent *move = [NSEvent mouseEventWithType:NSEventTypeMouseMoved location:point modifierFlags:0 | |
| 93 | 新增: timestamp:NSProcessInfo.processInfo.systemUptime windowNumber:_window.windowNumber | |
| 94 | 新增: context:nil eventNumber:0 clickCount:0 pressure:0]; | |
| 95 | 新增: [_view mouseMoved:move]; | |
| 96 | 新增: CGEventRef wheel = CGEventCreateScrollWheelEvent(NULL, kCGScrollEventUnitPixel, 2, (int32_t)deltaY, (int32_t)deltaX); | |
| 97 | 新增: if (!wheel) return NO; | |
| 98 | 新增: // A new CG event inherits the host pointer location. Retarget the hidden | |
| 99 | 新增: // window at the screen origin before the VZ view maps it into the guest. | |
| 100 | 新增: NSPoint screen = [_window convertPointToScreen:point]; | |
| 101 | 新增: CGEventSetLocation(wheel, CGPointMake(screen.x, NSMaxY(NSScreen.screens.firstObject.frame) - screen.y)); | |
| 102 | 新增: NSEvent *event = [NSEvent eventWithCGEvent:wheel]; | |
| 103 | 新增: CFRelease(wheel); | |
| 104 | 新增: if (!event || ![self canUseView]) return NO; | |
| 105 | 新增: [_view scrollWheel:event]; | |
| 106 | 新增: return YES; | |
| 107 | 新增:} | |
| 108 | 新增: | |
| 109 | 新增:- (void)close { | |
| 110 | 新增: NSAssert(NSThread.isMainThread, @"Close the setup view on the AppKit main thread."); | |
| 111 | 新增: _authorized = nil; | |
| 112 | 新增: _view.virtualMachine = nil; | |
| 113 | 新增: _window.contentView = nil; | |
| 114 | 新增: _view = nil; | |
| 115 | 新增: _window = nil; | |
| 116 | 新增:} | |
| 117 | 新增:@end | |
| @@ -0,0 +1,262 @@ | ||
| 1 | 新增:import AppKit | |
| 2 | 新增:import ApplicationServices | |
| 3 | 新增:import ScreenCaptureKit | |
| 4 | 新增: | |
| 5 | 新增:struct MacInputWindow { | |
| 6 | 新增: let app: AXUIElement | |
| 7 | 新增: let focused: AXUIElement | |
| 8 | 新增: let pid: pid_t | |
| 9 | 新增: let origin: CGPoint | |
| 10 | 新增: let extent: CGSize | |
| 11 | 新增:} | |
| 12 | 新增: | |
| 13 | 新增:@MainActor | |
| 14 | 新增:func checkedMacInputWindow(_ input: Request, window: SCWindow) throws -> MacInputWindow { | |
| 15 | 新增: guard AXIsProcessTrusted() else { throw Failure(9, "accessibility_permission") } | |
| 16 | 新增: guard let pid = window.owningApplication?.processID, input.pid == pid, input.window == window.windowID, | |
| 17 | 新增: NSWorkspace.shared.frontmostApplication?.processIdentifier == pid else { throw Failure(7, "window_changed") } | |
| 18 | 新增: let app = AXUIElementCreateApplication(pid) | |
| 19 | 新增: AXUIElementSetMessagingTimeout(app, 1) | |
| 20 | 新增: var value: CFTypeRef? | |
| 21 | 新增: guard AXUIElementCopyAttributeValue(app, kAXFocusedWindowAttribute as CFString, &value) == .success, | |
| 22 | 新增: let value, CFGetTypeID(value) == AXUIElementGetTypeID() else { throw Failure(7, "window_changed") } | |
| 23 | 新增: let focused = value as! AXUIElement | |
| 24 | 新增: var position: CFTypeRef?, size: CFTypeRef? | |
| 25 | 新增: var origin = CGPoint.zero, extent = CGSize.zero | |
| 26 | 新增: guard AXUIElementCopyAttributeValue(focused, kAXPositionAttribute as CFString, &position) == .success, | |
| 27 | 新增: AXUIElementCopyAttributeValue(focused, kAXSizeAttribute as CFString, &size) == .success, | |
| 28 | 新增: let position, let size, CFGetTypeID(position) == AXValueGetTypeID(), CFGetTypeID(size) == AXValueGetTypeID(), | |
| 29 | 新增: AXValueGetValue(position as! AXValue, .cgPoint, &origin), AXValueGetValue(size as! AXValue, .cgSize, &extent) else { | |
| 30 | 新增: throw Failure(7, "window_changed") | |
| 31 | 新增: } | |
| 32 | 新增: let tolerance: CGFloat = input.action == "project-click" ? 24 : 1 | |
| 33 | 新增: guard abs(origin.x - window.frame.minX) < tolerance, abs(origin.y - window.frame.minY) < tolerance, | |
| 34 | 新增: abs(extent.width - window.frame.width) < tolerance, abs(extent.height - window.frame.height) < tolerance else { | |
| 35 | 新增: throw Failure(7, "window_changed") | |
| 36 | 新增: } | |
| 37 | 新增: return MacInputWindow(app: app, focused: focused, pid: pid, origin: origin, extent: extent) | |
| 38 | 新增:} | |
| 39 | 新增: | |
| 40 | 新增:@MainActor | |
| 41 | 新增:func macPressTarget(_ target: MacInputWindow, point: CGPoint) -> AXUIElement? { | |
| 42 | 新增: var hit: AXUIElement? | |
| 43 | 新增: guard AXUIElementCopyElementAtPosition(target.app, Float(point.x), Float(point.y), &hit) == .success else { return nil } | |
| 44 | 新增: var node = hit | |
| 45 | 新增: for _ in 0..<8 { | |
| 46 | 新增: guard let current = node, !CFEqual(current, target.focused) else { break } | |
| 47 | 新增: func attribute(_ name: String) -> CFTypeRef? { | |
| 48 | 新增: var value: CFTypeRef? | |
| 49 | 新增: return AXUIElementCopyAttributeValue(current, name as CFString, &value) == .success ? value : nil | |
| 50 | 新增: } | |
| 51 | 新增: var pid: pid_t = 0 | |
| 52 | 新增: guard AXUIElementGetPid(current, &pid) == .success, pid == target.pid, | |
| 53 | 新增: let owner = attribute(kAXWindowAttribute), CFEqual(owner, target.focused) else { break } | |
| 54 | 新增: if let role = attribute(kAXRoleAttribute) as? String, [kAXButtonRole, "AXLink"].contains(role) { | |
| 55 | 新增: var actions: CFArray? | |
| 56 | 新增: if AXUIElementCopyActionNames(current, &actions) == .success, | |
| 57 | 新增: (actions as? [String])?.contains(kAXPressAction) == true { return current } | |
| 58 | 新增: } | |
| 59 | 新增: guard let parent = attribute(kAXParentAttribute), CFGetTypeID(parent) == AXUIElementGetTypeID() else { break } | |
| 60 | 新增: node = (parent as! AXUIElement) | |
| 61 | 新增: } | |
| 62 | 新增: return nil | |
| 63 | 新增:} | |
| 64 | 新增: | |
| 65 | 新增:// Each socket owns its held input and composition. Disconnect releases only that socket. | |
| 66 | 新增:@MainActor | |
| 67 | 新增:final class MacWindowInputSession { | |
| 68 | 新增: private static var pointerOwner: UUID? | |
| 69 | 新增: private static var keyOwners: [UInt16: UUID] = [:] | |
| 70 | 新增: private let id = UUID() | |
| 71 | 新增: private let source = CGEventSource(stateID: .privateState) | |
| 72 | 新增: private var keys: [UInt16: (pid_t, CGWindowID)] = [:] | |
| 73 | 新增: private var pressedCodes: [String: UInt16] = [:] | |
| 74 | 新增: private var buttons: [Int: (pid_t, CGWindowID, CGPoint, Int)] = [:] | |
| 75 | 新增: private var press: (element: AXUIElement, down: CGEvent, point: CGPoint, pid: pid_t, window: CGWindowID)? | |
| 76 | 新增: private var focusedElement: AXUIElement? | |
| 77 | 新增: private var focusedTarget = "" | |
| 78 | 新增: private var focusContext = "" | |
| 79 | 新增: private var composition: (id: String, context: String, sequence: Int, updated: Date)? | |
| 80 | 新增: | |
| 81 | 新增: static func requirePointerOwner(_ session: MacWindowInputSession?) throws { | |
| 82 | 新增: if let owner = pointerOwner, owner != session?.id { throw Failure(8, "input_owned_by_another_view") } | |
| 83 | 新增: } | |
| 84 | 新增: | |
| 85 | 新增: private func flags(_ input: Request) -> CGEventFlags { | |
| 86 | 新增: var value: CGEventFlags = [] | |
| 87 | 新增: if input.shift == true { value.insert(.maskShift) } | |
| 88 | 新增: if input.control == true { value.insert(.maskControl) } | |
| 89 | 新增: if input.alt == true { value.insert(.maskAlternate) } | |
| 90 | 新增: if input.command == true { value.insert(.maskCommand) } | |
| 91 | 新增: return value | |
| 92 | 新增: } | |
| 93 | 新增: | |
| 94 | 新增: func key(_ input: Request, target: MacInputWindow, window: SCWindow) throws { | |
| 95 | 新增: try Self.requirePointerOwner(self) | |
| 96 | 新增: if let pending = press { | |
| 97 | 新增: guard pending.pid == target.pid, pending.window == window.windowID else { throw Failure(7, "window_changed") } | |
| 98 | 新增: pending.down.postToPid(target.pid) | |
| 99 | 新增: press = nil | |
| 100 | 新增: } | |
| 101 | 新增: guard let down = input.down, let name = input.code, let key = input.key else { throw Failure(8, "invalid_input") } | |
| 102 | 新增: let mapped = MacKeyboard.virtualKey(code: name, key: key, shortcut: input.command == true || input.control == true || input.alt == true) | |
| 103 | 新增: guard let code = pressedCodes[name] ?? (down ? mapped : nil) else { | |
| 104 | 新增: if down { throw Failure(8, "invalid_input") } | |
| 105 | 新增: return | |
| 106 | 新增: } | |
| 107 | 新增: guard let event = CGEvent(keyboardEventSource: source, virtualKey: code, keyDown: down) else { throw Failure(8, "input_failed") } | |
| 108 | 新增: if let owner = Self.keyOwners[code], owner != id { throw Failure(8, "input_owned_by_another_view") } | |
| 109 | 新增: if !down && keys[code] == nil { return } | |
| 110 | 新增: event.flags = flags(input) | |
| 111 | 新增: event.setIntegerValueField(.keyboardEventAutorepeat, value: down && keys[code] != nil ? 1 : 0) | |
| 112 | 新增: if down && input.command != true && input.control != true && key.count == 1 { | |
| 113 | 新增: let text = Array(key.utf16) | |
| 114 | 新增: text.withUnsafeBufferPointer { event.keyboardSetUnicodeString(stringLength: text.count, unicodeString: $0.baseAddress) } | |
| 115 | 新增: } | |
| 116 | 新增: if down { keys[code] = (target.pid, window.windowID); pressedCodes[name] = code; Self.keyOwners[code] = id } | |
| 117 | 新增: else { keys.removeValue(forKey: code); pressedCodes.removeValue(forKey: name); Self.keyOwners.removeValue(forKey: code) } | |
| 118 | 新增: event.postToPid(target.pid) | |
| 119 | 新增: } | |
| 120 | 新增: | |
| 121 | 新增: func pointer(_ input: Request, target: MacInputWindow, window: SCWindow, canvas: ClaudeCanvas?) throws { | |
| 122 | 新增: try Self.requirePointerOwner(self) | |
| 123 | 新增: guard let phase = input.phase, ["down", "move", "up"].contains(phase), | |
| 124 | 新增: let x = input.x, let y = input.y, x.isFinite, y.isFinite, (0..<1).contains(x), (0..<1).contains(y) else { throw Failure(8, "invalid_input") } | |
| 125 | 新增: let crop = canvas?.cropTop ?? 0 | |
| 126 | 新增: let point = CGPoint(x: target.origin.x + target.extent.width * x, y: target.origin.y + crop + (target.extent.height - crop) * y) | |
| 127 | 新增: let button = phase == "move" ? buttons.keys.sorted().first : input.button | |
| 128 | 新增: let types: [NSEvent.EventType] | |
| 129 | 新增: if phase == "move" { types = [.leftMouseDragged, .otherMouseDragged, .rightMouseDragged] } | |
| 130 | 新增: else if phase == "down" { types = [.leftMouseDown, .otherMouseDown, .rightMouseDown] } | |
| 131 | 新增: else { types = [.leftMouseUp, .otherMouseUp, .rightMouseUp] } | |
| 132 | 新增: if phase != "move" && (button == nil || !(0...2).contains(button!) || !(1...3).contains(input.clicks ?? 0)) { throw Failure(8, "invalid_input") } | |
| 133 | 新增: if phase == "up", let button, buttons[button] == nil { return } | |
| 134 | 新增: if let pending = press { | |
| 135 | 新增: guard pending.pid == target.pid, pending.window == window.windowID else { throw Failure(7, "window_changed") } | |
| 136 | 新增: if phase == "move" && abs(point.x - pending.point.x) < 4 && abs(point.y - pending.point.y) < 4 { return } | |
| 137 | 新增: press = nil | |
| 138 | 新增: if phase == "up", button == 0, flags(input).isEmpty, | |
| 139 | 新增: let hit = macPressTarget(target, point: point), CFEqual(hit, pending.element) { | |
| 140 | 新增: buttons.removeValue(forKey: 0) | |
| 141 | 新增: if buttons.isEmpty { Self.pointerOwner = nil } | |
| 142 | 新增: guard AXUIElementPerformAction(hit, kAXPressAction as CFString) == .success else { throw Failure(8, "input_failed") } | |
| 143 | 新增: return | |
| 144 | 新增: } | |
| 145 | 新增: pending.down.postToPid(target.pid) | |
| 146 | 新增: } | |
| 147 | 新增: let type = button.map { types[$0] } ?? .mouseMoved | |
| 148 | 新增: let count = input.clicks ?? button.flatMap { buttons[$0]?.3 } ?? 0 | |
| 149 | 新增: let local = CGPoint(x: point.x - target.origin.x, y: target.extent.height - (point.y - target.origin.y)) | |
| 150 | 新增: guard let event = NSEvent.mouseEvent(with: type, location: local, modifierFlags: NSEvent.ModifierFlags(rawValue: UInt(flags(input).rawValue)), | |
| 151 | 新增: timestamp: ProcessInfo.processInfo.systemUptime, windowNumber: Int(window.windowID), context: nil, | |
| 152 | 新增: eventNumber: 0, clickCount: count, pressure: phase == "up" ? 0 : 1)?.cgEvent else { throw Failure(8, "input_failed") } | |
| 153 | 新增: event.location = point | |
| 154 | 新增: event.setIntegerValueField(.mouseEventWindowUnderMousePointer, value: Int64(window.windowID)) | |
| 155 | 新增: event.setIntegerValueField(.mouseEventWindowUnderMousePointerThatCanHandleThisEvent, value: Int64(window.windowID)) | |
| 156 | 新增: if phase == "down", let button { buttons[button] = (target.pid, window.windowID, point, count); Self.pointerOwner = id } | |
| 157 | 新增: if phase == "up", let button { buttons.removeValue(forKey: button); if buttons.isEmpty { Self.pointerOwner = nil } } | |
| 158 | 新增: if phase == "move" { for button in Array(buttons.keys) { buttons[button] = (target.pid, window.windowID, point, count) } } | |
| 159 | 新增: // Preserve the existing AX activation for Electron buttons. A real | |
| 160 | 新增: // drag flushes the deferred down before its first dragged event. | |
| 161 | 新增: if phase == "down", button == 0, count == 1, buttons.count == 1, flags(input).isEmpty, | |
| 162 | 新增: let element = macPressTarget(target, point: point) { | |
| 163 | 新增: press = (element, event, point, target.pid, window.windowID) | |
| 164 | 新增: return | |
| 165 | 新增: } | |
| 166 | 新增: event.postToPid(target.pid) | |
| 167 | 新增: } | |
| 168 | 新增: | |
| 169 | 新增: private func stillOwnsWindow(_ pid: pid_t, _ window: CGWindowID) -> Bool { | |
| 170 | 新增: guard (try? consoleUser()) != nil else { return false } | |
| 171 | 新增: let values = CGWindowListCopyWindowInfo(.optionIncludingWindow, window) as? [[String: Any]] | |
| 172 | 新增: return values?.first?[kCGWindowOwnerPID as String] as? Int32 == pid | |
| 173 | 新增: } | |
| 174 | 新增: | |
| 175 | 新增: func reset() { | |
| 176 | 新增: for (code, target) in keys { | |
| 177 | 新增: if stillOwnsWindow(target.0, target.1) { CGEvent(keyboardEventSource: source, virtualKey: code, keyDown: false)?.postToPid(target.0) } | |
| 178 | 新增: if Self.keyOwners[code] == id { Self.keyOwners.removeValue(forKey: code) } | |
| 179 | 新增: } | |
| 180 | 新增: for (button, target) in buttons where !(button == 0 && press != nil) && stillOwnsWindow(target.0, target.1) { | |
| 181 | 新增: let type: CGEventType = button == 0 ? .leftMouseUp : button == 2 ? .rightMouseUp : .otherMouseUp | |
| 182 | 新增: let mouse: CGMouseButton = button == 0 ? .left : button == 2 ? .right : .center | |
| 183 | 新增: if let event = CGEvent(mouseEventSource: source, mouseType: type, mouseCursorPosition: target.2, mouseButton: mouse) { | |
| 184 | 新增: event.setIntegerValueField(.mouseEventWindowUnderMousePointer, value: Int64(target.1)) | |
| 185 | 新增: event.setIntegerValueField(.mouseEventWindowUnderMousePointerThatCanHandleThisEvent, value: Int64(target.1)) | |
| 186 | 新增: event.postToPid(target.0) | |
| 187 | 新增: } | |
| 188 | 新增: } | |
| 189 | 新增: keys.removeAll(); pressedCodes.removeAll(); buttons.removeAll(); press = nil; composition = nil | |
| 190 | 新增: if Self.pointerOwner == id { Self.pointerOwner = nil } | |
| 191 | 新增: } | |
| 192 | 新增: | |
| 193 | 新增: func ime(_ input: Request, window: SCWindow, canvas: ClaudeCanvas?, commit: (String) throws -> Void) throws -> [String: Any] { | |
| 194 | 新增: let mode = input.mode ?? "" | |
| 195 | 新增: guard ["status", "begin", "update", "commit", "cancel"].contains(mode) else { throw Failure(8, "input_mode_invalid") } | |
| 196 | 新增: let token = input.session ?? "", sequence = input.sequence ?? 0 | |
| 197 | 新增: if mode != "status" && (token.count != 32 || token.range(of: "^[a-f0-9]{32}$", options: .regularExpression) == nil || sequence < 0) { throw Failure(8, "input_session_invalid") } | |
| 198 | 新增: if mode == "cancel" { | |
| 199 | 新增: if composition?.id == token && sequence > composition!.sequence { composition = nil } | |
| 200 | 新增: return ["available": false] | |
| 201 | 新增: } | |
| 202 | 新增: let target = try checkedMacInputWindow(input, window: window) | |
| 203 | 新增: func attribute(_ element: AXUIElement, _ name: String) -> CFTypeRef? { | |
| 204 | 新增: var value: CFTypeRef? | |
| 205 | 新增: return AXUIElementCopyAttributeValue(element, name as CFString, &value) == .success ? value : nil | |
| 206 | 新增: } | |
| 207 | 新增: guard let raw = attribute(target.app, kAXFocusedUIElementAttribute), CFGetTypeID(raw) == AXUIElementGetTypeID() else { | |
| 208 | 新增: composition = nil; focusedElement = nil; return ["available": false] | |
| 209 | 新增: } | |
| 210 | 新增: let element = raw as! AXUIElement | |
| 211 | 新增: var pid: pid_t = 0 | |
| 212 | 新增: var valueWritable = DarwinBoolean(false), selectionWritable = DarwinBoolean(false) | |
| 213 | 新增: _ = AXUIElementIsAttributeSettable(element, kAXValueAttribute as CFString, &valueWritable) | |
| 214 | 新增: _ = AXUIElementIsAttributeSettable(element, kAXSelectedTextAttribute as CFString, &selectionWritable) | |
| 215 | 新增: guard AXUIElementGetPid(element, &pid) == .success, pid == target.pid, | |
| 216 | 新增: [kAXTextFieldRole, kAXTextAreaRole, kAXComboBoxRole].contains(attribute(element, kAXRoleAttribute) as? String ?? ""), | |
| 217 | 新增: valueWritable.boolValue || selectionWritable.boolValue, | |
| 218 | 新增: let owner = attribute(element, kAXWindowAttribute), CFEqual(owner, target.focused), | |
| 219 | 新增: (attribute(element, kAXEnabledAttribute) as? Bool) != false else { composition = nil; return ["available": false] } | |
| 220 | 新增: let identity = "\(window.windowID):\(target.pid):\(input.geometry ?? "")" | |
| 221 | 新增: if focusedElement == nil || !CFEqual(focusedElement!, element) || focusedTarget != identity { | |
| 222 | 新增: focusedElement = element; focusedTarget = identity; focusContext = UUID().uuidString.replacingOccurrences(of: "-", with: "").lowercased(); composition = nil | |
| 223 | 新增: } | |
| 224 | 新增: var rect = CGRect.zero | |
| 225 | 新增: var exact = false | |
| 226 | 新增: if let range = attribute(element, kAXSelectedTextRangeAttribute), CFGetTypeID(range) == AXValueGetTypeID() { | |
| 227 | 新增: var selected = CFRange() | |
| 228 | 新增: if AXValueGetValue(range as! AXValue, .cfRange, &selected) { | |
| 229 | 新增: selected.location += selected.length; selected.length = 0 | |
| 230 | 新增: var bounds: CFTypeRef? | |
| 231 | 新增: if let parameter = AXValueCreate(.cfRange, &selected), | |
| 232 | 新增: AXUIElementCopyParameterizedAttributeValue(element, kAXBoundsForRangeParameterizedAttribute as CFString, parameter, &bounds) == .success, | |
| 233 | 新增: let bounds, CFGetTypeID(bounds) == AXValueGetTypeID() { exact = AXValueGetValue(bounds as! AXValue, .cgRect, &rect) } | |
| 234 | 新增: } | |
| 235 | 新增: } | |
| 236 | 新增: if !exact || rect.height <= 0 { | |
| 237 | 新增: var point = CGPoint.zero, size = CGSize.zero | |
| 238 | 新增: guard let position = attribute(element, kAXPositionAttribute), let extent = attribute(element, kAXSizeAttribute), | |
| 239 | 新增: CFGetTypeID(position) == AXValueGetTypeID(), CFGetTypeID(extent) == AXValueGetTypeID(), | |
| 240 | 新增: AXValueGetValue(position as! AXValue, .cgPoint, &point), AXValueGetValue(extent as! AXValue, .cgSize, &size) else { return ["available": false] } | |
| 241 | 新增: rect = CGRect(origin: point, size: CGSize(width: 1, height: min(24, size.height))) | |
| 242 | 新增: } | |
| 243 | 新增: if let current = composition, current.context != focusContext || Date().timeIntervalSince(current.updated) > 30 { composition = nil } | |
| 244 | 新增: let result: [String: Any] = ["available": true, "context": focusContext, "preedit_supported": false, | |
| 245 | 新增: "password": attribute(element, kAXSubroleAttribute) as? String == kAXSecureTextFieldSubrole, | |
| 246 | 新增: "rect": [rect.minX - target.origin.x, rect.minY - target.origin.y - (canvas?.cropTop ?? 0), max(1, rect.width), max(1, rect.height)], | |
| 247 | 新增: "width": target.extent.width, "height": target.extent.height - (canvas?.cropTop ?? 0), "caret_exact": exact] | |
| 248 | 新增: if mode == "status" { | |
| 249 | 新增: if composition?.id == token { composition?.updated = Date() } | |
| 250 | 新增: return result | |
| 251 | 新增: } | |
| 252 | 新增: if mode == "begin" { | |
| 253 | 新增: guard input.context == focusContext else { return ["available": false] } | |
| 254 | 新增: composition = (token, focusContext, sequence, Date()); return result | |
| 255 | 新增: } | |
| 256 | 新增: guard let current = composition, current.id == token, sequence > current.sequence else { return ["available": false] } | |
| 257 | 新增: guard (input.text ?? "").utf8.count <= 8192 else { throw Failure(8, "input_text_limit") } | |
| 258 | 新增: if mode == "commit" { try commit(input.text ?? ""); composition = nil } | |
| 259 | 新增: else { composition = (token, focusContext, sequence, Date()) } | |
| 260 | 新增: return result | |
| 261 | 新增: } | |
| 262 | 新增:} | |
| @@ -0,0 +1,131 @@ | ||
| 1 | 新增:import AppKit | |
| 2 | 新增:import CoreImage | |
| 3 | 新增:import ScreenCaptureKit | |
| 4 | 新增: | |
| 5 | 新增:@MainActor | |
| 6 | 新增:final class MacWindowStream: NSObject, SCStreamOutput, SCStreamDelegate { | |
| 7 | 新增: static let shared = MacWindowStream() | |
| 8 | 新增: private var stream: SCStream? | |
| 9 | 新增: private var key = "" | |
| 10 | 新增: private var generation = UUID().uuidString | |
| 11 | 新增: private var number: UInt64 = 0 | |
| 12 | 新增: private var sequence: String { generation + "-" + String(number) } | |
| 13 | 新增: private var buffer: CVPixelBuffer? | |
| 14 | 新增: private var expiry: Task<Void, Never>? | |
| 15 | 新增: private var waiters: [UUID: CheckedContinuation<Void, Never>] = [:] | |
| 16 | 新增: private let images = CIContext() | |
| 17 | 新增: | |
| 18 | 新增: nonisolated func stream(_ stream: SCStream, didOutputSampleBuffer sample: CMSampleBuffer, of type: SCStreamOutputType) { | |
| 19 | 新增: guard type == .screen, | |
| 20 | 新增: let attachments = CMSampleBufferGetSampleAttachmentsArray(sample, createIfNecessary: false) as? [[SCStreamFrameInfo: Any]], | |
| 21 | 新增: let status = attachments.first?[.status] as? Int else { return } | |
| 22 | 新增: let pixels = sample.isValid ? sample.imageBuffer : nil | |
| 23 | 新增: let changed = (attachments.first?[.dirtyRects] as? [Any])?.isEmpty != true | |
| 24 | 新增: Task { @MainActor [weak self] in | |
| 25 | 新增: guard let self, self.stream === stream else { return } | |
| 26 | 新增: if status == SCFrameStatus.complete.rawValue, let pixels { | |
| 27 | 新增: if self.buffer != nil && !changed { return } | |
| 28 | 新增: self.buffer = pixels | |
| 29 | 新增: self.number += 1 | |
| 30 | 新增: } else if status != SCFrameStatus.idle.rawValue { | |
| 31 | 新增: self.buffer = nil | |
| 32 | 新增: self.number += 1 | |
| 33 | 新增: } | |
| 34 | 新增: self.wake() | |
| 35 | 新增: } | |
| 36 | 新增: } | |
| 37 | 新增: | |
| 38 | 新增: nonisolated func stream(_ stream: SCStream, didStopWithError error: Error) { | |
| 39 | 新增: Task { @MainActor [weak self] in | |
| 40 | 新增: guard let self, self.stream === stream else { return } | |
| 41 | 新增: self.stream = nil | |
| 42 | 新增: self.buffer = nil | |
| 43 | 新增: self.wake() | |
| 44 | 新增: } | |
| 45 | 新增: } | |
| 46 | 新增: | |
| 47 | 新增: private func stop() async { | |
| 48 | 新增: let previous = stream | |
| 49 | 新增: stream = nil | |
| 50 | 新增: buffer = nil | |
| 51 | 新增: key = "" | |
| 52 | 新增: wake() | |
| 53 | 新增: try? await previous?.stopCapture() | |
| 54 | 新增: } | |
| 55 | 新增: | |
| 56 | 新增: private func wake() { | |
| 57 | 新增: let pending = waiters.values | |
| 58 | 新增: waiters.removeAll() | |
| 59 | 新增: for continuation in pending { continuation.resume() } | |
| 60 | 新增: } | |
| 61 | 新增: | |
| 62 | 新增: private func waitForFrame(after expected: String, seconds: Double) async throws { | |
| 63 | 新增: let id = UUID() | |
| 64 | 新增: let timeout = Task { @MainActor [weak self] in | |
| 65 | 新增: do { try await Task.sleep(nanoseconds: UInt64(seconds * 1_000_000_000)) } | |
| 66 | 新增: catch { return } | |
| 67 | 新增: self?.waiters.removeValue(forKey: id)?.resume() | |
| 68 | 新增: } | |
| 69 | 新增: defer { timeout.cancel() } | |
| 70 | 新增: await withTaskCancellationHandler { | |
| 71 | 新增: await withCheckedContinuation { continuation in | |
| 72 | 新增: if Task.isCancelled || stream == nil || expected != sequence { continuation.resume() } | |
| 73 | 新增: else { waiters[id] = continuation } | |
| 74 | 新增: } | |
| 75 | 新增: } onCancel: { | |
| 76 | 新增: Task { @MainActor [weak self] in self?.waiters.removeValue(forKey: id)?.resume() } | |
| 77 | 新增: } | |
| 78 | 新增: try Task.checkCancellation() | |
| 79 | 新增: } | |
| 80 | 新增: | |
| 81 | 新增: private func renew() { | |
| 82 | 新增: expiry?.cancel() | |
| 83 | 新增: expiry = Task { [weak self] in | |
| 84 | 新增: do { try await Task.sleep(nanoseconds: 1_500_000_000) } | |
| 85 | 新增: catch { return } | |
| 86 | 新增: await self?.stop() | |
| 87 | 新增: } | |
| 88 | 新增: } | |
| 89 | 新增: | |
| 90 | 新增: func unchanged(after: String?) -> Bool { | |
| 91 | 新增: guard stream != nil, buffer != nil, after == sequence else { return false } | |
| 92 | 新增: renew() | |
| 93 | 新增: return true | |
| 94 | 新增: } | |
| 95 | 新增: | |
| 96 | 新增: func frame(filter: SCContentFilter, configuration: SCStreamConfiguration, identity: String, after: String?, wait: Bool = false) async throws -> (CGImage?, String) { | |
| 97 | 新增: expiry?.cancel() | |
| 98 | 新增: defer { renew() } | |
| 99 | 新增: if stream == nil || key != identity { | |
| 100 | 新增: await stop() | |
| 101 | 新增: generation = UUID().uuidString | |
| 102 | 新增: number = 0 | |
| 103 | 新增: key = identity | |
| 104 | 新增: configuration.minimumFrameInterval = CMTime(value: 1, timescale: 30) | |
| 105 | 新增: configuration.queueDepth = 3 | |
| 106 | 新增: configuration.pixelFormat = kCVPixelFormatType_32BGRA | |
| 107 | 新增: let next = SCStream(filter: filter, configuration: configuration, delegate: self) | |
| 108 | 新增: try next.addStreamOutput(self, type: .screen, sampleHandlerQueue: DispatchQueue(label: "cage.window.frames")) | |
| 109 | 新增: stream = next | |
| 110 | 新增: do { try await next.startCapture() } | |
| 111 | 新增: catch { await stop(); throw error } | |
| 112 | 新增: } | |
| 113 | 新增: // Only the first frame of a newly configured stream needs to wait. | |
| 114 | 新增: let deadline = Date().addingTimeInterval(5) | |
| 115 | 新增: while buffer == nil && stream != nil && Date() < deadline { | |
| 116 | 新增: try await waitForFrame(after: sequence, seconds: max(0, deadline.timeIntervalSinceNow)) | |
| 117 | 新增: } | |
| 118 | 新增: if wait, buffer != nil, after == sequence { | |
| 119 | 新增: // Revalidate window ownership and the console session at least every | |
| 120 | 新增: // two seconds even when ScreenCaptureKit reports no changed pixels. | |
| 121 | 新增: try await waitForFrame(after: sequence, seconds: 2) | |
| 122 | 新增: } | |
| 123 | 新增: guard key == identity else { throw Failure(7, "window_changed") } | |
| 124 | 新增: guard let buffer else { await stop(); throw Failure(8, "capture_no_frame") } | |
| 125 | 新增: let sequence = self.sequence | |
| 126 | 新增: if sequence == after { return (nil, sequence) } | |
| 127 | 新增: let image = CIImage(cvPixelBuffer: buffer) | |
| 128 | 新增: guard let output = images.createCGImage(image, from: image.extent) else { throw Failure(8, "capture_conversion_failed") } | |
| 129 | 新增: return (output, sequence) | |
| 130 | 新增: } | |
| 131 | 新增:} | |
| @@ -0,0 +1,186 @@ | ||
| 1 | 新增:#!/bin/bash | |
| 2 | 新增:# Runs through the verified provisioning identity of an already bound Mac. | |
| 3 | 新增:# The ordinary account and its home directory are never initialized here. | |
| 4 | 新增:set -euo pipefail | |
| 5 | 新增:export PATH=/usr/bin:/bin:/usr/sbin:/sbin | |
| 6 | 新增:[[ $# == 3 && $1 == /* && $2 =~ ^[a-z][a-z0-9_]{0,30}$ && ( $3 == components || $3 == tools ) ]] | |
| 7 | 新增:[[ $EUID == 0 && $(uname -sm) == 'Darwin arm64' && $(sysctl -n hw.model) =~ ^VirtualMac[0-9]+,[0-9]+$ ]] | |
| 8 | 新增:[[ -f /var/db/cage-guest-os && ! -L /var/db/cage-guest-os && $(stat -f %u /var/db/cage-guest-os) == 0 && $(cat /var/db/cage-guest-os) == macos ]] | |
| 9 | 新增:lock=/var/run/cage-component-update.lock | |
| 10 | 新增:[[ ! -L $lock && ( ! -e $lock || ( -f $lock && $(stat -f %u "$lock") == 0 ) ) ]] | |
| 11 | 新增:exec 9>"$lock" | |
| 12 | 新增:/usr/bin/lockf -s -t 0 9 || { echo '另一项组件更新仍在运行,请稍后重试。' >&2; exit 1; } | |
| 13 | 新增:umask 022 | |
| 14 | 新增:kit=$(cd -P "$1" && pwd) | |
| 15 | 新增:# Helpers run as the ordinary guest user and need a traversable working directory. | |
| 16 | 新增:cd / | |
| 17 | 新增:user=$2 | |
| 18 | 新增:mode=$3 | |
| 19 | 新增:uid=$(id -u "$user") | |
| 20 | 新增:[[ $uid -ge 500 && " $(id -Gn "$user") " != *' admin '* ]] | |
| 21 | 新增:[[ $(stat -f %u "$kit") == 0 && -z $(find "$kit" \( -type l -o ! -user root -o -perm -0020 -o -perm -0002 \) -print -quit) ]] | |
| 22 | 新增:manifest="$kit/native-components.json" | |
| 23 | 新增:/usr/bin/perl "$kit/native-component-manifest.pl" source "$manifest" "$kit" | |
| 24 | 新增:backup=$(mktemp -d /private/var/tmp/cage-components-backup.XXXXXXXX) | |
| 25 | 新增:chmod 700 "$backup" | |
| 26 | 新增:changed=() | |
| 27 | 新增:existed=() | |
| 28 | 新增:loaded=() | |
| 29 | 新增:previous_loaded=() | |
| 30 | 新增:apps=() | |
| 31 | 新增:app_existed=() | |
| 32 | 新增:app_applied=0 | |
| 33 | 新增:cli_previous='' | |
| 34 | 新增:if [[ -L /usr/local/libexec/cage-cli ]]; then cli_previous=$(readlink /usr/local/libexec/cage-cli); fi | |
| 35 | 新增: | |
| 36 | 新增:finish() { | |
| 37 | 新增: local status=$? index target label | |
| 38 | 新增: trap - EXIT | |
| 39 | 新增: if (( status != 0 )); then | |
| 40 | 新增: for ((index=0; index<${#loaded[@]}; index++)); do | |
| 41 | 新增: label=${loaded[$index]} | |
| 42 | 新增: sudo -Hu "$user" /bin/launchctl bootout "gui/$uid/$label" >/dev/null 2>&1 || true | |
| 43 | 新增: done | |
| 44 | 新增: for ((index=${#changed[@]}-1; index>=0; index--)); do | |
| 45 | 新增: target=${changed[$index]} | |
| 46 | 新增: if [[ ${existed[$index]} == yes ]]; then | |
| 47 | 新增: mv -f "$backup/$index" "$target" || status=1 | |
| 48 | 新增: elif [[ -f $target && ! -L $target ]]; then | |
| 49 | 新增: rm "$target" || status=1 | |
| 50 | 新增: fi | |
| 51 | 新增: done | |
| 52 | 新增: for ((index=app_applied-1; index>=0; index--)); do | |
| 53 | 新增: target=${apps[$index]} | |
| 54 | 新增: if [[ -d $target && ! -L $target ]]; then rm -rf "$target"; fi | |
| 55 | 新增: if [[ ${app_existed[$index]} == yes ]]; then mv "$backup/old-app-$index" "$target" || status=1; fi | |
| 56 | 新增: done | |
| 57 | 新增: if [[ -n $cli_previous ]]; then | |
| 58 | 新增: ln -s "$cli_previous" "$backup/cli-previous" | |
| 59 | 新增: mv -fh "$backup/cli-previous" /usr/local/libexec/cage-cli || status=1 | |
| 60 | 新增: fi | |
| 61 | 新增: for ((index=0; index<${#previous_loaded[@]}; index++)); do | |
| 62 | 新增: label=${previous_loaded[$index]} | |
| 63 | 新增: if ! sudo -Hu "$user" /bin/launchctl bootstrap "gui/$uid" "/Users/$user/Library/LaunchAgents/$label.plist" >/dev/null 2>&1; then status=1; fi | |
| 64 | 新增: done | |
| 65 | 新增: fi | |
| 66 | 新增: if (( status == 0 )); then | |
| 67 | 新增: rm -rf "$backup" | |
| 68 | 新增: else | |
| 69 | 新增: printf '组件更新未完成。已恢复可恢复的原文件,备份位于 %s。可以在 Cage 重试。\n' "$backup" >&2 | |
| 70 | 新增: fi | |
| 71 | 新增: exit "$status" | |
| 72 | 新增:} | |
| 73 | 新增:trap finish EXIT | |
| 74 | 新增:trap 'exit 1' HUP INT TERM | |
| 75 | 新增: | |
| 76 | 新增:# Verify app ownership before stopping the corresponding GUI helpers. | |
| 77 | 新增:for app in "$kit"/*.app "$kit"/project/*.app; do | |
| 78 | 新增: [[ -d $app ]] || continue | |
| 79 | 新增: identifier=$(/usr/libexec/PlistBuddy -c 'Print :CFBundleIdentifier' "$app/Contents/Info.plist") | |
| 80 | 新增: [[ $identifier == dev.cage.* ]] | |
| 81 | 新增: codesign --verify --deep --strict -R "=identifier \"$identifier\"" "$app" | |
| 82 | 新增: target="/Applications/$(basename "$app")" | |
| 83 | 新增: if [[ -e $target ]]; then | |
| 84 | 新增: [[ -d $target && ! -L $target ]] | |
| 85 | 新增: # Missing or damaged installed files are repairable. The incoming app | |
| 86 | 新增: # is fully verified, and an existing signing team remains a constraint. | |
| 87 | 新增: previous_team=$(codesign -dv "$target" 2>&1 | sed -n 's/^TeamIdentifier=//p' || true) | |
| 88 | 新增: next_team=$(codesign -dv "$app" 2>&1 | sed -n 's/^TeamIdentifier=//p') | |
| 89 | 新增: [[ -z $previous_team || $previous_team == not\ set || $previous_team == "$next_team" ]] | |
| 90 | 新增: fi | |
| 91 | 新增: index=${#apps[@]} | |
| 92 | 新增: ditto "$app" "$backup/new-app-$index" | |
| 93 | 新增: chmod -R a+rX,go-w "$backup/new-app-$index" | |
| 94 | 新增: codesign --verify --deep --strict "$backup/new-app-$index" | |
| 95 | 新增: apps+=("$target") | |
| 96 | 新增: if [[ -d $target ]]; then app_existed+=(yes); else app_existed+=(no); fi | |
| 97 | 新增:done | |
| 98 | 新增:for label in dev.cage.GuestClaudeWindow dev.cage.GuestClipboard dev.cage.GuestBrowser; do | |
| 99 | 新增: if sudo -Hu "$user" /bin/launchctl print "gui/$uid/$label" >/dev/null 2>&1; then | |
| 100 | 新增: loaded+=("$label") | |
| 101 | 新增: previous_loaded+=("$label") | |
| 102 | 新增: sudo -Hu "$user" /bin/launchctl bootout "gui/$uid/$label" | |
| 103 | 新增: fi | |
| 104 | 新增:done | |
| 105 | 新增:# Project shares and workbench terminals have already been closed by the host. | |
| 106 | 新增:while read -r pid owner executable; do | |
| 107 | 新增: if [[ $owner == "$uid" && $executable == /Applications/CageProjectAccess.app/Contents/MacOS/CageProjectAccess ]]; then kill -TERM "$pid" 2>/dev/null || true; fi | |
| 108 | 新增:done < <(ps -axo pid=,uid=,comm=) | |
| 109 | 新增: | |
| 110 | 新增:for ((index=0; index<${#apps[@]}; index++)); do | |
| 111 | 新增: target=${apps[$index]} | |
| 112 | 新增: if [[ ${app_existed[$index]} == yes ]]; then mv "$target" "$backup/old-app-$index"; fi | |
| 113 | 新增: app_applied=$((index+1)) | |
| 114 | 新增: mv "$backup/new-app-$index" "$target" | |
| 115 | 新增:done | |
| 116 | 新增: | |
| 117 | 新增:while IFS= read -r -d '' source && IFS= read -r -d '' target; do | |
| 118 | 新增: # The CLI installer publishes a new immutable helper directory and moves | |
| 119 | 新增: # its owned symlink. It also generates the verified Python entry shebang. | |
| 120 | 新增: [[ $target != /usr/local/libexec/cage-cli/* && $target != /Applications/* ]] || continue | |
| 121 | 新增: parent=$(dirname "$target") | |
| 122 | 新增: check=$parent | |
| 123 | 新增: while [[ $check != / ]]; do | |
| 124 | 新增: [[ ! -L $check ]] | |
| 125 | 新增: check=$(dirname "$check") | |
| 126 | 新增: done | |
| 127 | 新增: mkdir -p "$parent" | |
| 128 | 新增: [[ ! -L $target && ( ! -e $target || -f $target ) ]] | |
| 129 | 新增: if [[ -f $target ]] && cmp -s "$kit/$source" "$target"; then continue; fi | |
| 130 | 新增: index=${#changed[@]} | |
| 131 | 新增: if [[ -f $target ]]; then | |
| 132 | 新增: cp -p "$target" "$backup/$index" | |
| 133 | 新增: existed+=(yes) | |
| 134 | 新增: else | |
| 135 | 新增: existed+=(no) | |
| 136 | 新增: fi | |
| 137 | 新增: changed+=("$target") | |
| 138 | 新增: stage=$(mktemp "$parent/.cage-component.XXXXXXXX") | |
| 139 | 新增: cp -p "$kit/$source" "$stage" | |
| 140 | 新增: case "$target" in | |
| 141 | 新增: */controller/cage-tailnet|/usr/local/libexec/cage-register-*|/usr/local/libexec/cage-macos-editor|/usr/local/libexec/cage-sshfs|/usr/local/libexec/cage-macos-terminal|/usr/local/libexec/cage-finish-initial-setup|/usr/local/libexec/cage-macos-ipv6-check) chmod 755 "$stage" ;; | |
| 142 | 新增: *) chmod a+r,go-w "$stage" ;; | |
| 143 | 新增: esac | |
| 144 | 新增: mv -f "$stage" "$target" | |
| 145 | 新增:done < <(/usr/bin/perl "$kit/native-component-manifest.pl" targets "$manifest" "$kit") | |
| 146 | 新增: | |
| 147 | 新增:if [[ $mode == tools ]]; then | |
| 148 | 新增: bash "$kit/install-macos-node.sh" "$kit/node.tgz" | |
| 149 | 新增: bash "$kit/install-macos-browser.sh" "$kit" --update-tools | |
| 150 | 新增: bash "$kit/cli/install-macos-cli.sh" "$kit/cli" | |
| 151 | 新增:else | |
| 152 | 新增: bash "$kit/install-macos-cli.sh" "$kit" --components | |
| 153 | 新增:fi | |
| 154 | 新增:for app in "$kit"/*.app "$kit"/project/*.app; do | |
| 155 | 新增: [[ -d $app ]] || continue | |
| 156 | 新增: codesign --verify --deep --strict "/Applications/$(basename "$app")" | |
| 157 | 新增:done | |
| 158 | 新增:# Registration can migrate an existing agent's lifecycle settings. Restore | |
| 159 | 新增:# those files with the matching binaries if activation or publication fails. | |
| 160 | 新增:for label in dev.cage.GuestClaudeWindow dev.cage.GuestClipboard dev.cage.GuestBrowser; do | |
| 161 | 新增: target="/Users/$user/Library/LaunchAgents/$label.plist" | |
| 162 | 新增: [[ ! -L $target && ( ! -e $target || ( -f $target && $(stat -f %u "$target") == "$uid" ) ) ]] | |
| 163 | 新增: index=${#changed[@]} | |
| 164 | 新增: if [[ -f $target ]]; then | |
| 165 | 新增: cp -p "$target" "$backup/$index" | |
| 166 | 新增: existed+=(yes) | |
| 167 | 新增: else | |
| 168 | 新增: existed+=(no) | |
| 169 | 新增: fi | |
| 170 | 新增: changed+=("$target") | |
| 171 | 新增:done | |
| 172 | 新增:sudo -Hu "$user" /usr/local/libexec/cage-register-claude-window --prepare | |
| 173 | 新增:sudo -Hu "$user" /usr/local/libexec/cage-register-clipboard --prepare | |
| 174 | 新增:sudo -Hu "$user" /usr/local/libexec/cage-register-browser --prepare | |
| 175 | 新增:# New helpers are activated for an already logged-in GUI user as well. | |
| 176 | 新增:if [[ $(stat -f %u /dev/console) == "$uid" ]]; then | |
| 177 | 新增: for label in dev.cage.GuestClaudeWindow dev.cage.GuestClipboard dev.cage.GuestBrowser; do | |
| 178 | 新增: if [[ " ${loaded[*]-} " != *" $label "* ]]; then loaded+=("$label"); fi | |
| 179 | 新增: done | |
| 180 | 新增:fi | |
| 181 | 新增:for ((index=0; index<${#loaded[@]}; index++)); do | |
| 182 | 新增: label=${loaded[$index]} | |
| 183 | 新增: sudo -Hu "$user" /bin/launchctl bootstrap "gui/$uid" "/Users/$user/Library/LaunchAgents/$label.plist" | |
| 184 | 新增:done | |
| 185 | 新增:/usr/bin/perl "$kit/native-component-manifest.pl" publish "$manifest" "$kit" | |
| 186 | 新增:printf '%s\n' '原生客机组件已更新并通过文件核验。' | |
改动太大,不在线显示。
改动太大,不在线显示。
改动太大,不在线显示。
改动太大,不在线显示。
改动太大,不在线显示。
改动太大,不在线显示。
改动太大,不在线显示。
改动太大,不在线显示。
改动太大,不在线显示。
改动太大,不在线显示。
改动太大,不在线显示。
改动太大,不在线显示。
改动太大,不在线显示。
改动太大,不在线显示。
改动太大,不在线显示。
改动太大,不在线显示。
改动太大,不在线显示。
改动太大,不在线显示。
改动太大,不在线显示。
改动太大,不在线显示。
改动太大,不在线显示。
改动太大,不在线显示。
改动太大,不在线显示。
改动太大,不在线显示。
改动太大,不在线显示。
改动太大,不在线显示。
改动太大,不在线显示。
改动太大,不在线显示。
改动太大,不在线显示。
改动太大,不在线显示。
改动太大,不在线显示。
改动太大,不在线显示。
改动太大,不在线显示。
改动太大,不在线显示。
改动太大,不在线显示。
改动太大,不在线显示。
改动太大,不在线显示。
改动太大,不在线显示。
改动太大,不在线显示。
改动太大,不在线显示。
改动太大,不在线显示。
改动太大,不在线显示。
改动太大,不在线显示。
改动太大,不在线显示。
改动太大,不在线显示。
改动太大,不在线显示。
改动太大,不在线显示。
改动太大,不在线显示。
改动太大,不在线显示。
改动太大,不在线显示。
改动太大,不在线显示。
改动太大,不在线显示。
改动太大,不在线显示。

